text:
import sys

from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy import exc
from sqlalchemy import func
from sqlalchemy import INT
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy import VARCHAR
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import ne_
from sqlalchemy.testing.engines import testing_engine
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table

users, metadata = None, None

class TransactionTest(fixtures.TestBase):
    __backend__ = True

    @classmethod
    def setup_class(cls):
        global users, metadata
        metadata = MetaData()
        users = Table(
            "query_users",
            metadata,
            Column("user_id", INT, primary_key=True),
            Column("user_name", VARCHAR(20)),
            test_needs_acid=True,
        )
        users.create(testing.db)

    def teardown(self):
        testing.db.execute(users.delete()).close()

    @classmethod
    def teardown_class(cls):
        users.drop(testing.db)

    def test_commits(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction.commit()

        transaction = connection.begin()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.commit()

        transaction = connection.begin()
        result = connection.execute("select * from query_users")
        assert len(result.fetchall()) == 3
        transaction.commit()
        connection.close()

    def test_rollback(self):
        """test a basic rollback"""

        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.rollback()
        result = connection.execute("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    def test_raise(self):
        connection = testing.db.connect()

        transaction = connection.begin()
        try:
            connection.execute(users.insert(), user_id=1, user_name="user1")
            connection.execute(users.insert(), user_id=2, user_name="user2")
            connection.execute(users.insert(), user_id=1, user_name="user3")
            transaction.commit()
            assert False
        except Exception as e:
            print("Exception: ", e)
            transaction.rollback()

        result = connection.execute("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    def test_nested_rollback(self):
        connection = testing.db.connect()
        try:
            transaction = connection.begin()
            try:
                connection.execute(
                    users.insert(), user_id=1, user_name="user1"
                )
                connection.execute(
                    users.insert(), user_id=2, user_name="user2"
                )
                connection.execute(
                    users.insert(), user_id=3, user_name="user3"
                )
                trans2 = connection.begin()
                try:
                    connection.execute(
                        users.insert(), user_id=4, user_name="user4"
                    )
                    connection.execute(
                        users.insert(), user_id=5, user_name="user5"
                    )
                    raise Exception("uh oh")
                    trans2.commit()
                except Exception:
                    trans2.rollback()
                    raise
                transaction.rollback()
            except Exception:
                transaction.rollback()
                raise
        except Exception as e:
            try:
                # and not "This transaction is inactive"
                # comment moved here to fix pep8
                assert str(e) == "uh oh"
            finally:
                connection.close()

    def test_branch_nested_rollback(self):
        connection = testing.db.connect()
        try:
            connection.begin()
            branched = connection.connect()
            assert branched.in_transaction()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            assert not connection.in_transaction()

            assert_raises_message(
                exc.InvalidRequestError,
                "This connection is on an inactive transaction.  Please",
                connection.execute,
                "select 1",
            )

        finally:
            connection.close()

    def test_inactive_due_to_subtransaction_no_commit(self):
        connection = testing.db.connect()
        trans = connection.begin()
        trans2 = connection.begin()
        trans2.rollback()
        assert_raises_message(
            exc.InvalidRequestError,
            "This transaction is inactive",
            trans.commit,
        )

    def test_branch_autorollback(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            try:
                branched.execute(users.insert(), user_id=1, user_name="user1")
            except exc.DBAPIError:
                pass
        finally:
            connection.close()

    def test_branch_orig_rollback(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin()
            assert branched.in_transaction()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            eq_(connection.scalar("select count(*) from query_users"), 1)

        finally:
            connection.close()

    def test_branch_autocommit(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            branched.execute(users.insert(), user_id=1, user_name="user1")
        finally:
            connection.close()
        eq_(testing.db.scalar("select count(*) from query_users"), 1)

    @testing.requires.savepoints
    def test_branch_savepoint_rollback(self):
        connection = testing.db.connect()
        try:
            trans = connection.begin()
            branched = connection.connect()
            assert branched.in_transaction()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin_nested()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            assert connection.in_transaction()
            trans.commit()
            eq_(connection.scalar("select count(*) from query_users"), 1)

        finally:
            connection.close()

    @testing.requires.two_phase_transactions
    def test_branch_twophase_rollback(self):
        connection = testing.db.connect()
        try:
            branched = connection.connect()
            assert not branched.in_transaction()
            branched.execute(users.insert(), user_id=1, user_name="user1")
            nested = branched.begin_twophase()
            branched.execute(users.insert(), user_id=2, user_name="user2")
            nested.rollback()
            assert not connection.in_transaction()
            eq_(connection.scalar("select count(*) from query_users"), 1)

        finally:
            connection.close()

    @testing.requires.python2
    @testing.requires.savepoints_w_release
    def test_savepoint_release_fails_warning(self):
        with testing.db.connect() as connection:
            connection.begin()

            with expect_warnings(
                "An exception has occurred during handling of a previous "
                "exception.  The previous exception "
                r"is:.*..SQL\:.*RELEASE SAVEPOINT"
            ):

                def go():
                    with connection.begin_nested() as savepoint:
                        connection.dialect.do_release_savepoint(
                            connection, savepoint._savepoint
                        )

                assert_raises_message(
                    exc.DBAPIError, r".*SQL\:.*ROLLBACK TO SAVEPOINT", go
                )

    def test_retains_through_options(self):
        connection = testing.db.connect()
        try:
            transaction = connection.begin()
            connection.execute(users.insert(), user_id=1, user_name="user1")
            conn2 = connection.execution_options(dummy=True)
            conn2.execute(users.insert(), user_id=2, user_name="user2")
            transaction.rollback()
            eq_(connection.scalar("select count(*) from query_users"), 0)
        finally:
            connection.close()

    def test_nesting(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans2 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        connection.execute(users.insert(), user_id=5, user_name="user5")
        trans2.commit()
        transaction.rollback()
        self.assert_(
            connection.scalar("select count(*) from " "query_users") == 0
        )
        result = connection.execute("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    def test_with_interface(self):
        connection = testing.db.connect()
        trans = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        try:
            connection.execute(users.insert(), user_id=2, user_name="user2.5")
        except Exception:
            trans.__exit__(*sys.exc_info())

        assert not trans.is_active
        self.assert_(
            connection.scalar("select count(*) from " "query_users") == 0
        )

        trans = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans.__exit__(None, None, None)
        assert not trans.is_active
        self.assert_(
            connection.scalar("select count(*) from " "query_users") == 1
        )
        connection.close()

    def test_close(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans2 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        connection.execute(users.insert(), user_id=5, user_name="user5")
        assert connection.in_transaction()
        trans2.close()
        assert connection.in_transaction()
        transaction.commit()
        assert not connection.in_transaction()
        self.assert_(
            connection.scalar("select count(*) from " "query_users") == 5
        )
        result = connection.execute("select * from query_users")
        assert len(result.fetchall()) == 5
        connection.close()

    def test_close2(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        connection.execute(users.insert(), user_id=2, user_name="user2")
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans2 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        connection.execute(users.insert(), user_id=5, user_name="user5")
        assert connection.in_transaction()
        trans2.close()
        assert connection.in_transaction()
        transaction.close()
        assert not connection.in_transaction()
        self.assert_(
            connection.scalar("select count(*) from " "query_users") == 0
        )
        result = connection.execute("select * from query_users")
        assert len(result.fetchall()) == 0
        connection.close()

    @testing.requires.savepoints
    def test_nested_subtransaction_rollback(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans2 = connection.begin_nested()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        trans2.rollback()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (3,)],
        )
        connection.close()

    @testing.requires.savepoints
    @testing.crashes(
        "oracle+zxjdbc",
        "Errors out and causes subsequent tests to " "deadlock",
    )
    def test_nested_subtransaction_commit(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans2 = connection.begin_nested()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        trans2.commit()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (2,), (3,)],
        )
        connection.close()

    @testing.requires.savepoints
    def test_rollback_to_subtransaction(self):
        connection = testing.db.connect()
        transaction = connection.begin()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        trans2 = connection.begin_nested()
        connection.execute(users.insert(), user_id=2, user_name="user2")

        trans3 = connection.begin()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        trans3.rollback()

        assert_raises_message(
            exc.InvalidRequestError,
            "This connection is on an inactive savepoint transaction.",
            connection.execute,
            "select 1",
        )
        trans2.rollback()

        connection.execute(users.insert(), user_id=4, user_name="user4")
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (4,)],
        )
        connection.close()

    @testing.requires.two_phase_transactions
    def test_two_phase_transaction(self):
        connection = testing.db.connect()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction.prepare()
        transaction.commit()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        transaction.commit()
        transaction.close()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction.rollback()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        transaction.prepare()
        transaction.rollback()
        transaction.close()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (2,)],
        )
        connection.close()

    # PG emergency shutdown:
    # select * from pg_prepared_xacts
    # ROLLBACK PREPARED '<xid>'
    # MySQL emergency shutdown:
    # for arg in `mysql -u root -e "xa recover" | cut -c 8-100 |
    #     grep sa`; do mysql -u root -e "xa rollback '$arg'"; done
    @testing.crashes("mysql", "Crashing on 5.5, not worth it")
    @testing.requires.skip_mysql_on_windows
    @testing.requires.two_phase_transactions
    @testing.requires.savepoints
    def test_mixed_two_phase_transaction(self):
        connection = testing.db.connect()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction2 = connection.begin()
        connection.execute(users.insert(), user_id=2, user_name="user2")
        transaction3 = connection.begin_nested()
        connection.execute(users.insert(), user_id=3, user_name="user3")
        transaction4 = connection.begin()
        connection.execute(users.insert(), user_id=4, user_name="user4")
        transaction4.commit()
        transaction3.rollback()
        connection.execute(users.insert(), user_id=5, user_name="user5")
        transaction2.commit()
        transaction.prepare()
        transaction.commit()
        eq_(
            connection.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,), (2,), (5,)],
        )
        connection.close()

    @testing.requires.two_phase_transactions
    @testing.requires.two_phase_recovery
    def test_two_phase_recover(self):

        # MySQL recovery doesn't currently seem to work correctly
        # Prepared transactions disappear when connections are closed
        # and even when they aren't it doesn't seem possible to use the
        # recovery id.

        connection = testing.db.connect()
        transaction = connection.begin_twophase()
        connection.execute(users.insert(), user_id=1, user_name="user1")
        transaction.prepare()
        connection.invalidate()

        connection2 = testing.db.connect()
        eq_(
            connection2.execution_options(autocommit=True)
            .execute(select([users.c.user_id]).order_by(users.c.user_id))
            .fetchall(),
            [],
        )
        recoverables = connection2.recover_twophase()
        assert transaction.xid in recoverables
        connection2.commit_prepared(transaction.xid, recover=True)
        eq_(
            connection2.execute(
                select([users.c.user_id]).order_by(users.c.user_id)
            ).fetchall(),
            [(1,)],
        )
        connection2.close()

    @testing.requires.two_phase_transactions
    def test_multiple_two_phase(self):
        conn = testing.db.connect()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=1, user_name="user1")
        xa.prepare()
        xa.commit()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=2, user_name="user2")
        xa.prepare()
        xa.rollback()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=3, user_name="user3")
        xa.rollback()
        xa = conn.begin_twophase()
        conn.execute(users.insert(), user_id=4, user_name="user4")
        xa.prepare()
        xa.commit()
        result = conn.execute(
            select([users.c.user_name]).order_by(users.c.user_id)
        )
        eq_(result.fetchall(), [("user1",), ("user4",)])
        conn.close()

    @testing.requires.two_phase_transactions
    def test_reset_rollback_two_phase_no_rollback(self):
        # test [ticket:2907], essentially that the
        # TwoPhaseTransaction is given the job of "reset on return"
        # so that picky backends like MySQL correctly clear out
        # their state when a connection is closed without handling
        # the transaction explicitly.

        eng = testing_engine()

        # MySQL raises if you call straight rollback() on
        # a connection with an XID present
        @event.listens_for(eng, "invalidate")
        def conn_invalidated(dbapi_con, con_record, exception):
            dbapi_con.close()
            raise exception

        with eng.connect() as conn:
            rec = conn.connection._connection_record
            raw_dbapi_con = rec.connection
            conn.begin_twophase()
            conn.execute(users.insert(), user_id=1, user_name="user1")

        assert rec.connection is raw_dbapi_con

        with eng.connect() as conn:
            result = conn.execute(
                select([users.c.user_name]).order_by(users.c.user_id)
            )
            eq_(result.fetchall(), [])

class ResetAgentTest(fixtures.TestBase):
    __backend__ = True

    def test_begin_close(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            assert connection.connection._reset_agent is trans
        assert not trans.is_active

    def test_begin_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            assert connection.connection._reset_agent is trans
            trans.rollback()
            assert connection.connection._reset_agent is None

    def test_begin_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.savepoints
    def test_begin_nested_close(self):
        with testing.db.connect() as connection:
            trans = connection.begin_nested()
            assert connection.connection._reset_agent is trans
        assert not trans.is_active

    @testing.requires.savepoints
    def test_begin_begin_nested_close(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin_nested()
            assert connection.connection._reset_agent is trans
        assert trans2.is_active  # was never closed
        assert not trans.is_active

    @testing.requires.savepoints
    def test_begin_begin_nested_rollback_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin_nested()
            assert connection.connection._reset_agent is trans
            trans2.rollback()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.savepoints
    def test_begin_begin_nested_rollback_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin_nested()
            assert connection.connection._reset_agent is trans
            trans2.rollback()
            assert connection.connection._reset_agent is trans
            trans.rollback()
            assert connection.connection._reset_agent is None

    def test_begin_begin_rollback_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin()
            assert connection.connection._reset_agent is trans
            trans2.rollback()
            assert connection.connection._reset_agent is None
            trans.rollback()
            assert connection.connection._reset_agent is None

    def test_begin_begin_commit_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin()
            trans2 = connection.begin()
            assert connection.connection._reset_agent is trans
            trans2.commit()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.two_phase_transactions
    def test_reset_via_agent_begin_twophase(self):
        with testing.db.connect() as connection:
            trans = connection.begin_twophase()
            assert connection.connection._reset_agent is trans

    @testing.requires.two_phase_transactions
    def test_reset_via_agent_begin_twophase_commit(self):
        with testing.db.connect() as connection:
            trans = connection.begin_twophase()
            assert connection.connection._reset_agent is trans
            trans.commit()
            assert connection.connection._reset_agent is None

    @testing.requires.two_phase_transactions
    def test_reset_via_agent_begin_twophase_rollback(self):
        with testing.db.connect() as connection:
            trans = connection.begin_twophase()
            assert connection.connection._reset_agent is trans
            trans.rollback()
            assert connection.connection._reset_agent is None

class AutoRollbackTest(fixtures.TestBase):
    __backend__ = True

    @classmethod
    def setup_class(cls):
        global metadata
        metadata = MetaData()

    @classmethod
    def teardown_class(cls):
        metadata.drop_all(testing.db)

    def test_rollback_deadlock(self):
        """test that returning connections to the pool clears any object
        locks."""

        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        users = Table(
            "deadlock_users",
            metadata,
            Column("user_id", INT, primary_key=True),
            Column("user_name", VARCHAR(20)),
            test_needs_acid=True,
        )
        users.create(conn1)
        conn1.execute("select * from deadlock_users")
        conn1.close()

        # without auto-rollback in the connection pool's return() logic,
        # this deadlocks in PostgreSQL, because conn1 is returned to the
        # pool but still has a lock on "deadlock_users". comment out the
        # rollback in pool/ConnectionFairy._close() to see !

        users.drop(conn2)
        conn2.close()

class ExplicitAutoCommitTest(fixtures.TestBase):

    """test the 'autocommit' flag on select() and text() objects.

    Requires PostgreSQL so that we may define a custom function which
    modifies the database. """

    __only_on__ = "postgresql"

    @classmethod
    def setup_class(cls):
        global metadata, foo
        metadata = MetaData(testing.db)
        foo = Table(
            "foo",
            metadata,
            Column("id", Integer, primary_key=True),
            Column("data", String(100)),
        )
        metadata.create_all()
        testing.db.execute(
            "create function insert_foo(varchar) "
            "returns integer as 'insert into foo(data) "
            "values ($1);select 1;' language sql"
        )

    def teardown(self):
        foo.delete().execute().close()

    @classmethod
    def teardown_class(cls):
        testing.db.execute("drop function insert_foo(varchar)")
        metadata.drop_all()

    def test_control(self):

        # test that not using autocommit does not commit

        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(select([func.insert_foo("data1")]))
        assert conn2.execute(select([foo.c.data])).fetchall() == []
        conn1.execute(text("select insert_foo('moredata')"))
        assert conn2.execute(select([foo.c.data])).fetchall() == []
        trans = conn1.begin()
        trans.commit()
        assert conn2.execute(select([foo.c.data])).fetchall() == [
            ("data1",),
            ("moredata",),
        ]
        conn1.close()
        conn2.close()

    def test_explicit_compiled(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(
            select([func.insert_foo("data1")]).execution_options(
                autocommit=True
            )
        )
        assert conn2.execute(select([foo.c.data])).fetchall() == [("data1",)]
        conn1.close()
        conn2.close()

    def test_explicit_connection(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execution_options(autocommit=True).execute(
            select([func.insert_foo("data1")])
        )
        eq_(conn2.execute(select([foo.c.data])).fetchall(), [("data1",)])

        # connection supersedes statement

        conn1.execution_options(autocommit=False).execute(
            select([func.insert_foo("data2")]).execution_options(
                autocommit=True
            )
        )
        eq_(conn2.execute(select([foo.c.data])).fetchall(), [("data1",)])

        # ditto

        conn1.execution_options(autocommit=True).execute(
            select([func.insert_foo("data3")]).execution_options(
                autocommit=False
            )
        )
        eq_(
            conn2.execute(select([foo.c.data])).fetchall(),
            [("data1",), ("data2",), ("data3",)],
        )
        conn1.close()
        conn2.close()

    def test_explicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(
            text("select insert_foo('moredata')").execution_options(
                autocommit=True
            )
        )
        assert conn2.execute(select([foo.c.data])).fetchall() == [
            ("moredata",)
        ]
        conn1.close()
        conn2.close()

    def test_implicit_text(self):
        conn1 = testing.db.connect()
        conn2 = testing.db.connect()
        conn1.execute(text("insert into foo (data) values ('implicitdata')"))
        assert conn2.execute(select([foo.c.data])).fetchall() == [
            ("implicitdata",)
        ]
        conn1.close()
        conn2.close()

class IsolationLevelTest(fixtures.TestBase):
    __requires__ = ("isolation_level", "ad_hoc_engines")
    __backend__ = True

    def _default_isolation_level(self):
        if testing.against("sqlite"):
            return "SERIALIZABLE"
        elif testing.against("postgresql"):
            return "READ COMMITTED"
        elif testing.against("mysql"):
            return "REPEATABLE READ"
        elif testing.against("mssql"):
            return "READ COMMITTED"
        else:
            assert False, "default isolation level not known"

    def _non_default_isolation_level(self):
        if testing.against("sqlite"):
            return "READ UNCOMMITTED"
        elif testing.against("postgresql"):
            return "SERIALIZABLE"
        elif testing.against("mysql"):
            return "SERIALIZABLE"
        elif testing.against("mssql"):
            return "SERIALIZABLE"
        else:
            assert False, "non default isolation level not known"

    def test_engine_param_stays(self):

        eng = testing_engine()
        isolation_level = eng.dialect.get_isolation_level(
            eng.connect().connection
        )
        level = self._non_default_isolation_level()

        ne_(isolation_level, level)

        eng = testing_engine(options=dict(isolation_level=level))
        eq_(eng.dialect.get_isolation_level(eng.connect().connection), level)

        # check that it stays
        conn = eng.connect()
        eq_(eng.dialect.get_isolation_level(conn.connection), level)
        conn.close()

        conn = eng.connect()
        eq_(eng.dialect.get_isolation_level(conn.connection), level)
        conn.close()

    def test_default_level(self):
        eng = testing_engine(options=dict())
        isolation_level = eng.dialect.get_isolation_level(
            eng.connect().connection
        )
        eq_(isolation_level, self._default_isolation_level())

    def test_reset_level(self):
        eng = testing_engine(options=dict())
        conn = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._default_isolation_level(),
        )

        eng.dialect.set_isolation_level(
            conn.connection, self._non_default_isolation_level()
        )
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )

        eng.dialect.reset_isolation_level(conn.connection)
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._default_isolation_level(),
        )

        conn.close()

    def test_reset_level_with_setting(self):
        eng = testing_engine(
            options=dict(isolation_level=self._non_default_isolation_level())
        )
        conn = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )
        eng.dialect.set_isolation_level(
            conn.connection, self._default_isolation_level()
        )
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._default_isolation_level(),
        )
        eng.dialect.reset_isolation_level(conn.connection)
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )
        conn.close()

    def test_invalid_level(self):
        eng = testing_engine(options=dict(isolation_level="FOO"))
        assert_raises_message(
            exc.ArgumentError,
            "Invalid value '%s' for isolation_level. "
            "Valid isolation levels for %s are %s"
            % (
                "FOO",
                eng.dialect.name,
                ", ".join(eng.dialect._isolation_lookup),
            ),
            eng.connect,
        )

    def test_connection_invalidated(self):
        eng = testing_engine()
        conn = eng.connect()
        c2 = conn.execution_options(
            isolation_level=self._non_default_isolation_level()
        )
        c2.invalidate()
        c2.connection

        # TODO: do we want to rebuild the previous isolation?
        # for now, this is current behavior so we will leave it.
        eq_(c2.get_isolation_level(), self._default_isolation_level())

    def test_per_connection(self):
        from sqlalchemy.pool import QueuePool

        eng = testing_engine(
            options=dict(poolclass=QueuePool, pool_size=2, max_overflow=0)
        )

        c1 = eng.connect()
        c1 = c1.execution_options(
            isolation_level=self._non_default_isolation_level()
        )
        c2 = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(c1.connection),
            self._non_default_isolation_level(),
        )
        eq_(
            eng.dialect.get_isolation_level(c2.connection),
            self._default_isolation_level(),
        )
        c1.close()
        c2.close()
        c3 = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(c3.connection),
            self._default_isolation_level(),
        )
        c4 = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(c4.connection),
            self._default_isolation_level(),
        )

        c3.close()
        c4.close()

    def test_warning_in_transaction(self):
        eng = testing_engine()
        c1 = eng.connect()
        with expect_warnings(
            "Connection is already established with a Transaction; "
            "setting isolation_level may implicitly rollback or commit "
            "the existing transaction, or have no effect until next "
            "transaction"
        ):
            with c1.begin():
                c1 = c1.execution_options(
                    isolation_level=self._non_default_isolation_level()
                )

                eq_(
                    eng.dialect.get_isolation_level(c1.connection),
                    self._non_default_isolation_level(),
                )
        # stays outside of transaction
        eq_(
            eng.dialect.get_isolation_level(c1.connection),
            self._non_default_isolation_level(),
        )

    def test_per_statement_bzzt(self):
        assert_raises_message(
            exc.ArgumentError,
            r"'isolation_level' execution option may only be specified "
            r"on Connection.execution_options\(\), or "
            r"per-engine using the isolation_level "
            r"argument to create_engine\(\).",
            select([1]).execution_options,
            isolation_level=self._non_default_isolation_level(),
        )

    def test_per_engine(self):
        # new in 0.9
        eng = create_engine(
            testing.db.url,
            execution_options={
                "isolation_level": self._non_default_isolation_level()
            },
        )
        conn = eng.connect()
        eq_(
            eng.dialect.get_isolation_level(conn.connection),
            self._non_default_isolation_level(),
        )

    def test_isolation_level_accessors_connection_default(self):
        eng = create_engine(testing.db.url)
        with eng.connect() as conn:
            eq_(conn.default_isolation_level, self._default_isolation_level())
        with eng.connect() as conn:
            eq_(conn.get_isolation_level(), self._default_isolation_level())

    def test_isolation_level_accessors_connection_option_modified(self):
        eng = create_engine(testing.db.url)
        with eng.connect() as conn:
            c2 = conn.execution_options(
                isolation_level=self._non_default_isolation_level()
            )
            eq_(conn.default_isolation_level, self._default_isolation_level())
            eq_(
                conn.get_isolation_level(), self._non_default_isolation_level()
            )
            eq_(c2.get_isolation_level(), self._non_default_isolation_level())


text:
import LightDetailsController from './LightDetailsController'

export default {
  name : 'lightDetails',
  config : {
    bindings         : {  selected: '<' },
    templateUrl      : 'src/materialhue/components/details/LightDetails.html',
    controller       : LightDetailsController
  }
};

redpajama_set_name: RedPajamaGithub


text:
from colorlog import ColoredFormatter
import logging
global logger
logger = logging.getLogger('M3ARPG')
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler('M3ARPG.log')
streamHandler = logging.StreamHandler()
fileHandler.setLevel(logging.DEBUG)
streamHandler.setLevel(logging.DEBUG)

#formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
formatter = ColoredFormatter(
               '%(log_color)s%(asctime)s %(levelname)s %(white)s%(message)s',
               reset=True,
               log_colors={
                  'DEBUG':   'green',
                  'INFO':    'yellow',
                  'WARNING': 'cyan',
                  'ERROR':   'red',
                  'CRITICAL':'red',
               })

fileHandler.setFormatter(formatter)
streamHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
logger.addHandler(streamHandler)


text:
var jsmin = require('jsmin').jsmin,
	path = require('path'),
	_ = require('lodash'),
	fs = require('fs');

var BackboneAdapter = function BackboneAdapter(options) {
	this.urlRoot = options.urlRoot;
};

BackboneAdapter.prototype = {
	generate: function generate(modelName, requiredModel) {
		var urlRoot = this.urlRoot + modelName;

		var clientDefaults = {},
			modelAttributes = requiredModel.attributes;

		for(var attr in modelAttributes) {
			if(typeof modelAttributes[attr].default !== 'undefined') {
				clientDefaults[attr] = modelAttributes[attr].default;
			}
		}

		//Possible fields of a Backbone.Model
		var clientModel = {
		  idAttribute: 'id',
		  urlRoot: urlRoot,
		  defaults: clientDefaults
		};

		//Stringify all the model data, but not the methods, and remove the closing '}' that
		//will be included after the methods be concatenated
		//We do it because JSON.stringify ignores the functions
		var modelData = JSON.stringify(clientModel);
		modelData = modelData.substring(0, modelData.length - 1) + ', ';

		//Merge shared methods first, so it can be overwriten by specific client methods
		var modelMethods = requiredModel.sharedMethods;
		modelMethods = _.merge(modelMethods, requiredModel.clientMethods);

		_.forIn(modelMethods, function(method, methodName) {
		  modelData += '\"' + methodName + '\": ' + method.toString() + ',\n';
		});

		//Remove the last comma and '\n' then closes the '}'
		modelData = modelData.substring(0, modelData.length - 2) + '}';

		//Lodash template for Backbone.Model
		var backboneModelTemplate = _.template(fs.readFileSync(path.join(__dirname, 'template.js')));

		//Create the Backbone.Model file content
		var backboneModelString = backboneModelTemplate({
		  name: modelName,
		  modelData: modelData
		});

		//Minifies the file content
		backboneModelString = jsmin(backboneModelString);

		return backboneModelString;

	}
};

module.exports = BackboneAdapter;


text:
require 'rails_helper'

RSpec.describe 'Course: Videos: Viewing' do
  let!(:instance) { create(:instance, :with_video_component_enabled) }

  with_tenant(:instance) do
    let!(:course) { create(:course, :with_video_component_enabled) }
    let(:unpublished_video) { create(:video, course: course) }
    let(:published_video) { create(:video, :published, course: course) }
    let(:published_not_started_video) { create(:video, :published, :not_started, course: course) }
    let(:videos) { [unpublished_video, published_video, published_not_started_video] }
    before { login_as(user, scope: :user) }

    context 'As a Course Student' do
      let(:user) { create(:course_student, course: course).user }

      scenario 'I can view published videos and attempt these videos from the videos page' do
        videos
        visit course_videos_path(course)

        expect(page).to have_no_content_tag_for(unpublished_video)
        expect(page).to have_content_tag_for(published_video)
        expect(page).to have_content_tag_for(published_not_started_video)

        within find(content_tag_selector(published_not_started_video)) do
          expect(page).to have_css('a.btn.btn-info.disabled')
        end

        within find(content_tag_selector(published_video)) do
          find('.btn.btn-info').click

          submission =
            Course::Video::Submission.where(video: published_video, creator: user).first
          expect(current_path).
            to eq(edit_course_video_submission_path(course, published_video, submission))

          expect(page).to have_tag('div', with: { 'id': 'video-component' })
        end

        # Button is updated when submission exists
        visit course_videos_path(course)
        within find(content_tag_selector(published_video)) do
          expect(page).to have_text(I18n.t('course.video.videos.video_attempt_button.rewatch'))
          find('.btn.btn-info').click
        end

        expect(page).to have_tag('div', with: { 'id': 'video-component' })
        data = JSON.parse(page.find('#video-component')['data'])

        expect(data['video']['videoUrl']).to eq(published_video.url)
      end
    end
  end
end


text:
@extends('dashboard')

@section('content')

Role Admin: Edit

            <form method="POST" action="/admin/roles/{{ $role->id }}">
                <input name="_method" type="hidden" value="PATCH">
                {!! csrf_field() !!}

                    @input_maker_label('Name')
                    @input_maker_create('name', ['type' => 'string'], $role)

                    @input_maker_label('Label')
                    @input_maker_create('label', ['type' => 'string'], $role)

Permissions

                    @foreach(Config::get('permissions', []) as $permission => $name)

                                @if (stristr($role->permissions, $permission))
                                    <input type="checkbox" name="permissions[{{ $permission }}]" id="{{ $name }}" checked>
                                @else
                                    <input type="checkbox" name="permissions[{{ $permission }}]" id="{{ $name }}">
                                @endif
                                {{ $name }}

                    @endforeach

                    Cancel
                    <button class="btn btn-primary pull-right" type="submit">Save</button>

            </form>

@stop


text:
require_relative 'item'
require_relative 'client'
require_relative 'filesystem_common'

module Bitcasa
	# File class is aimed to provide native File object like interface
	#		to bitcasa cloudfs files
	#
	# @author Mrinal Dhillon
	# @example
	#		file = session.filesystem.root.upload("/tmp/testfile")
	#		file.seek(4, IO::SEEK_SET) #=> 4
	#		file.tell #=> 4
	#		file.read #=> " is some buffer till end of file"
	#		file.rewind
	#		file.read {|chunk| puts chunk} #=> "this is some buffer till end of file"
	# 	file.download("/tmp", filename: "new_testfile")
	class File < Item

		# @see Item#initialize
		def initialize(client, parent: nil, in_trash: false,
				in_share: false, **properties)
			@offset = 0
			super
		end

		# Download this file to local directory
		#
		# @param local_path [String] path of local folder
		# @param filename [String] name of downloaded file, default is name of this file
		#
		# @raise [Client::Errors::ServiceError, Client::Errors::ArgumentError,
		#		Client::Errors::InvalidItemError, Client::Errors::OperationNotAllowedError]
		def download(local_path, filename: nil)
			fail Client::Errors::ArgumentError,
				"local path is not a valid directory" unless ::File.directory?(local_path)
			FileSystemCommon.validate_item_state(self)

			filename ||= @name
			if local_path[-1] == '/'
				local_filepath = "#{local_path}#{filename}"
			else
				local_filepath = "#{local_path}/#{filename}"
			end

			::File.open(local_filepath, 'wb') do |file|
				@client.download(url) { |buffer| file.write(buffer) }
			end
		end

		# Read from file to buffer
		#
		#	@param bytecount [Fixnum] number of bytes to read from current access position
		# @return [String] buffer
		# @raise [Client::Errors::ServiceError]
		def read_to_buffer(bytecount)
			buffer = @client.download(url, startbyte: @offset, bytecount: bytecount)
			@offset += buffer.nil? ? 0 : buffer.size
			buffer
		end

		# Read from file to proc
		#
		#	@param bytecount [Fixnum] number of bytes to read from current access position
		# @yield [String] chunk of data as soon as available,
		#		chunksize size may vary each time
		# @raise [Client::Errors::ServiceError]
		def read_to_proc(bytecount, &block)
			@client.download(url, startbyte: @offset, bytecount: bytecount) do |chunk|
				@offset += chunk.nil? ? 0 : chunk.size
				yield chunk
			end
		end

		# Read from file
		#
	 	#	@param bytecount [Fixnum] number of bytes to read from
		#		current access position, default reads upto end of file
		#
		# @yield [String] chunk data as soon as available,
		#		chunksize size may vary each time
		# @return [String] buffer, unless block is given
		# @raise [Client::Errors::ServiceError, Client::Errors::ArgumentError,
		#		Client::Errors::InvalidItemError, Client::Errors::OperationNotAllowedError]
		def read(bytecount: nil, &block)
			fail Client::Errors::ArgumentError,
				"Negative length given - #{bytecount}" if bytecount && bytecount < 0
			FileSystemCommon.validate_item_state(self)

			if bytecount == 0 || @offset >= @size
				return yield "" if block_given?
				return ""
			end

			# read till end of file if no bytecount is given
			# 	or offset + bytecount  > size of file
			bytecount = @size - @offset if bytecount.nil? || (@offset + bytecount > @size)

			if block_given?
				read_to_proc(bytecount, &block)
			else
				read_to_buffer(bytecount)
			end
		end

		#	Reset position indicator
		def rewind
			@offset = 0
		end

		# Return current access position in this file
		# @return [Fixnum] current position in file
		def tell
			@offset
		end

		# Seek to a particular byte in this file
		# @param offset [Fixnum] offset in this file to seek to
		# @param whence [Fixnum] defaults 0,
		#		If whence is 0 file offset shall be set to offset bytes
		#		If whence is 1, the file offset shall be set to its
		#			current location plus offset
		#		If whence is 2, the file offset shall be set to the size of
		#			the file plus offset
		# @return [Fixnum] resulting offset
		# @raise [Client::Errors::ArgumentError]
		def seek(offset, whence: 0)

			case whence
			when 0
				@offset = offset if whence == 0
			when 1
				@offset += offset if whence == 1
			when 2
				@offset = @size + offset if whence == 2
			else
				raise Client::Errors::ArgumentError,
					"Invalid value of whence, should be 0 or IO::SEEK_SET, 1 or IO::SEEK_CUR, 2 or IO::SEEK_END,"
			end

			@offset
		end

		private :read_to_buffer, :read_to_proc
	end
end


text:
using System.Collections.Generic;

namespace Gallio.UI.ProgressMonitoring
{
    /// <summary>
    /// Manages multiple queues of tasks.
    /// </summary>
    /// <remarks>
    /// Queue id is an arbitrary string, used as a key.
    /// </remarks>
    public class TaskQueue : ITaskQueue
    {
        private readonly IDictionary<string, Queue<ICommand>> allTasks;

        ///<summary>
        /// Ctor.
        ///</summary>
        public TaskQueue()
        {
            allTasks = new Dictionary<string, Queue<ICommand>>();
        }

        /// <summary>
        /// Adds a task to the specified queue.
        /// </summary>
        /// <param name="queueId">The id of the queue to use.</param>
        /// <param name="command">An <see cref="ICommand"/> to queue.</param>
        public void AddTask(string queueId, ICommand command)
        {
            var tasks = GetTasks(queueId);
            tasks.Enqueue(command);
        }

        private Queue<ICommand> GetTasks(string queueId)
        {
            Queue<ICommand> tasks;
            allTasks.TryGetValue(queueId, out tasks);
            if (tasks == null)
            {
                tasks = new Queue<ICommand>();
                allTasks.Add(queueId, tasks);
            }
            return tasks;
        }

        /// <summary>
        /// Get the next task for the specified queue.
        /// </summary>
        /// <param name="queueId">The id of the queue to use.</param>
        /// <returns>An <see cref="ICommand"/>, or null if the queue is empty.</returns>
        public ICommand GetNextTask(string queueId)
        {
            var tasks = GetTasks(queueId);
            return tasks.Count > 0 ? tasks.Dequeue() : null;
        }

        /// <summary>
        /// Removes all tasks from the specified queue.
        /// </summary>
        /// <param name="queueId">The id of the queue to use.</param>
        public void RemoveAllTasks(string queueId)
        {
            var tasks = GetTasks(queueId);
            tasks.Clear();
        }
    }
}


text:
namespace gfx {
class Size;
}

namespace window_manager {

class CaptureController;
class FocusController;
class FocusRules;
class ViewEventDispatcher;
class WindowManagerDelegate;
class WindowManagerImpl;

// Implements core window manager functionality that could conceivably be shared
// across multiple window managers implementing superficially different user
// experiences. Establishes communication with the view manager.
// A window manager wishing to use this core should create and own an instance
// of this object. They may implement the associated ViewManager/WindowManager
// delegate interfaces exposed by the view manager, this object provides the
// canonical implementation of said interfaces but will call out to the wrapped
// instances.
class WindowManagerApp
    : public mojo::ApplicationDelegate,
      public mojo::ViewManagerDelegate,
      public mojo::ViewObserver,
      public ui::EventHandler,
      public FocusControllerObserver,
      public CaptureControllerObserver,
      public mojo::InterfaceFactory<mojo::WindowManager>,
      public mojo::InterfaceFactory<mojo::WindowManagerInternal>,
      public mojo::InterfaceFactory<mojo::NativeViewportEventDispatcher>,
      public mojo::WindowManagerInternal {
 public:
  WindowManagerApp(ViewManagerDelegate* view_manager_delegate,
                   WindowManagerDelegate* window_manager_delegate);
  ~WindowManagerApp() override;

  ViewEventDispatcher* event_dispatcher() {
    return view_event_dispatcher_.get();
  }

  // Register/deregister new connections to the window manager service.
  void AddConnection(WindowManagerImpl* connection);
  void RemoveConnection(WindowManagerImpl* connection);

  // These are canonical implementations of the window manager API methods.
  bool SetCapture(mojo::Id view);
  bool FocusWindow(mojo::Id view);
  bool ActivateWindow(mojo::Id view);

  void DispatchInputEventToView(mojo::View* view, mojo::EventPtr event);
  void SetViewportSize(const gfx::Size& size);

  bool IsReady() const;

  FocusController* focus_controller() { return focus_controller_.get(); }
  CaptureController* capture_controller() { return capture_controller_.get(); }

  void InitFocus(scoped_ptr<FocusRules> rules);

  ui::AcceleratorManager* accelerator_manager() {
    return &accelerator_manager_;
  }

  // WindowManagerImpl::Embed() forwards to this. If connected to ViewManager
  // then forwards to delegate, otherwise waits for connection to establish then
  // forwards.
  void Embed(const mojo::String& url,
             mojo::InterfaceRequest<mojo::ServiceProvider> services,
             mojo::ServiceProviderPtr exposed_services);

  // Overridden from ApplicationDelegate:
  void Initialize(mojo::ApplicationImpl* impl) override;
  bool ConfigureIncomingConnection(
      mojo::ApplicationConnection* connection) override;

 private:
  // TODO(sky): rename this. Connections is ambiguous.
  typedef std::set<WindowManagerImpl*> Connections;
  typedef std::set<mojo::Id> RegisteredViewIdSet;

  struct PendingEmbed;
  class WindowManagerInternalImpl;

  mojo::ViewManager* view_manager() {
    return root_ ? root_->view_manager() : nullptr;
  }

  bool SetCaptureImpl(mojo::View* view);
  bool FocusWindowImpl(mojo::View* view);
  bool ActivateWindowImpl(mojo::View* view);

  ui::Accelerator ConvertEventToAccelerator(const ui::KeyEvent* event);

  // Creates an ViewTarget for every view in the hierarchy beneath |view|,
  // and adds to the registry so that it can be retrieved later via
  // GetViewTargetForViewId().
  // TODO(beng): perhaps View should have a property bag.
  void RegisterSubtree(mojo::View* view);

  // Recursively invokes Unregister() for |view| and all its descendants.
  void UnregisterSubtree(mojo::View* view);

  // Deletes the ViewTarget associated with the hierarchy beneath |id|,
  // and removes from the registry.
  void Unregister(mojo::View* view);

  // Overridden from ViewManagerDelegate:
  void OnEmbed(mojo::View* root,
               mojo::InterfaceRequest<mojo::ServiceProvider> services,
               mojo::ServiceProviderPtr exposed_services) override;
  void OnViewManagerDisconnected(mojo::ViewManager* view_manager) override;
  bool OnPerformAction(mojo::View* view, const std::string& action) override;

  // Overridden from ViewObserver:
  void OnTreeChanged(const ViewObserver::TreeChangeParams& params) override;
  void OnViewDestroying(mojo::View* view) override;

  // Overridden from ui::EventHandler:
  void OnEvent(ui::Event* event) override;

  // Overridden from mojo::FocusControllerObserver:
  void OnFocused(mojo::View* gained_focus) override;
  void OnActivated(mojo::View* gained_active) override;

  // Overridden from mojo::CaptureControllerObserver:
  void OnCaptureChanged(mojo::View* gained_capture) override;

  // Creates the connection to the ViewManager.
  void LaunchViewManager(mojo::ApplicationImpl* app);

  // InterfaceFactory<WindowManagerInternal>:
  void Create(
      mojo::ApplicationConnection* connection,
      mojo::InterfaceRequest<mojo::WindowManagerInternal> request) override;

  // InterfaceFactory<WindowManager>:
  void Create(mojo::ApplicationConnection* connection,
              mojo::InterfaceRequest<mojo::WindowManager> request) override;

  // InterfaceFactory<NativeViewportEventDispatcher>:
  void Create(mojo::ApplicationConnection* connection,
              mojo::InterfaceRequest<mojo::NativeViewportEventDispatcher>
                  request) override;

  // WindowManagerInternal:
  void CreateWindowManagerForViewManagerClient(
      uint16_t connection_id,
      mojo::ScopedMessagePipeHandle window_manager_pipe) override;
  void SetViewManagerClient(
      mojo::ScopedMessagePipeHandle view_manager_client_request) override;

  mojo::Shell* shell_;

  ViewManagerDelegate* wrapped_view_manager_delegate_;
  WindowManagerDelegate* window_manager_delegate_;

  mojo::ViewManagerServicePtr view_manager_service_;
  scoped_ptr<mojo::ViewManagerClientFactory> view_manager_client_factory_;
  mojo::View* root_;

  scoped_ptr<FocusController> focus_controller_;
  scoped_ptr<CaptureController> capture_controller_;

  ui::AcceleratorManager accelerator_manager_;

  Connections connections_;
  RegisteredViewIdSet registered_view_id_set_;

  mojo::WindowManagerInternalClientPtr window_manager_client_;

  ScopedVector<PendingEmbed> pending_embeds_;

  scoped_ptr<mojo::ViewManagerClient> view_manager_client_;

  scoped_ptr<ViewEventDispatcher> view_event_dispatcher_;

  scoped_ptr<mojo::Binding<WindowManagerInternal>> wm_internal_binding_;

  DISALLOW_COPY_AND_ASSIGN(WindowManagerApp);
};

}  // namespace window_manager

#endif  // SERVICES_WINDOW_MANAGER_WINDOW_MANAGER_APP_H_


text:
package com.goka.rssts.helper;

import android.app.Activity;
import android.widget.Toast;

/**
 * Created by katsuyagoto on 2015/04/26.
 */
public class ToastHelper {

    public static void showShort(Activity activity, CharSequence text) {
        Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
    }

    public static void showShort(Activity activity, int resId) {
        Toast.makeText(activity, resId, Toast.LENGTH_SHORT).show();
    }

    public static void showLong(Activity activity, CharSequence text) {
        Toast.makeText(activity, text, Toast.LENGTH_LONG).show();
    }

    public static void showLong(Activity activity, int resId) {
        Toast.makeText(activity, resId, Toast.LENGTH_LONG).show();
    }
}


text:
package org.apache.camel.processor;

import javax.naming.Context;

import org.apache.camel.CamelExecutionException;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.JndiRegistry;
import org.junit.Test;

public class BeanCachedProcessorTest extends ContextTestSupport {

    private Context context;

    private JndiRegistry registry;

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:noCache").to("bean:something?cache=false");
                from("direct:cached").to("bean:something?cache=true");

            }
        };
    }

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry registry = super.createRegistry();
        registry.bind("something", new MyBean());
        this.context = registry.getContext();
        this.registry = registry;
        return registry;
    }

    @Test
    public void testFreshBeanInContext() throws Exception {
        // Just make sure the bean processor doesn't work if the cached is false
        MyBean originalInstance = registry.lookupByNameAndType("something", MyBean.class);
        template.sendBody("direct:noCache", null);
        context.unbind("something");
        context.bind("something", new MyBean());
        // Make sure we can get the object from the registry
        assertNotSame(registry.lookupByName("something"), originalInstance);
        template.sendBody("direct:noCache", null);
    }

    @Test
    public void testBeanWithCached() throws Exception {
        // Just make sure the bean processor doesn't work if the cached is false
        MyBean originalInstance = registry.lookupByNameAndType("something", MyBean.class);
        template.sendBody("direct:cached", null);
        context.unbind("something");
        context.bind("something", new MyBean());
        // Make sure we can get the object from the registry
        assertNotSame(registry.lookupByName("something"), originalInstance);
        try {
            template.sendBody("direct:cached", null);
            fail("The IllegalStateException is expected");
        } catch (CamelExecutionException ex) {
            assertTrue("IllegalStateException is expected!", ex.getCause() instanceof IllegalStateException);
            assertEquals("This bean is not supported to be invoked again!", ex.getCause().getMessage());
        }
    }

    public static class MyBean implements Processor {
        private boolean invoked;

        @Override
        public void process(Exchange exchange) throws Exception {
            if (invoked) {
                throw new IllegalStateException("This bean is not supported to be invoked again!");
            } else {
                invoked = true;
            }
        }
    }

}


text:
using System;

namespace UB.LastFM.Services
{
	/// <summary>
	/// Objects that implement this can be shared with others.
	/// </summary>
	public interface IShareable
	{
		void Share(Recipients recipients, string message);
		void Share(Recipients recipients);
	}
}


text:
"""Presubmit script for changes affecting //ui/views.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools.
"""

USE_PYTHON3 = True

INCLUDE_CPP_FILES_ONLY = (
  r'.*\.(cc|h)$',
)

def CheckChangeLintsClean(input_api, output_api):
  """Makes sure that the change is cpplint clean."""
  sources = lambda x: input_api.FilterSourceFile(
    x, files_to_check=INCLUDE_CPP_FILES_ONLY,
    files_to_skip=input_api.DEFAULT_FILES_TO_SKIP)
  return input_api.canned_checks.CheckChangeLintsClean(
      input_api, output_api, sources, lint_filters=[], verbose_level=1)

def CheckChange(input_api, output_api):
  results = []
  results += CheckChangeLintsClean(input_api, output_api)
  return results

def CheckChangeOnUpload(input_api, output_api):
  return CheckChange(input_api, output_api)

def CheckChangeOnCommit(input_api, output_api):
  return CheckChange(input_api, output_api)


text:
import  os
import configparser
from pyrdp.rdp import Settings

PATH = os.path.expanduser(os.environ['HOME'])
PATH = os.path.join(PATH, '.pyrdp')

if not os.path.exists(PATH):
    os.mkdir(PATH)

class ConnectionFile(object):

    def __init__(self, conn_name):
        self._file_name = os.path.join(PATH, conn_name)

    def file_exists(self):
        return os.path.exists(self._file_name)

    def write(self, cfg):
        file = open(self._file_name, 'w')
        print("[settings]", file=file)
        for key, value in cfg.itens():
            print(("%s=%s" % (key, value)), file=file)

        print("[plugins]", file=file)
        for key, value in cfg.plugins():
            print(("%s=%s" % (key, value)), file=file)

        file.close()

    def read(self):
        conf = configparser.ConfigParser()
        conf.read(self._file_name, 'UTF-8')
        vars = dict(conf.items('settings'))
        return Settings(args=vars)


text:
require 'spec_helper'

describe User, type: :model do
  describe "with an admin user existing" do
    before(:each) do
      @admin = FactoryBot.create(:admin_user)
    end
    it "should have a to: address in new_applicant_email" do
      ActionMailer::Base.deliveries.clear

      user = FactoryBot.create(:user)
      # doesn't send the devise e-mail, because it's already confirmed

      deliveries = ActionMailer::Base.deliveries
      num_deliveries = ActionMailer::Base.deliveries.size

      expect(num_deliveries).to eq(1)

      new_applicant_email = deliveries.last

      expect(new_applicant_email.bcc.count).to eq(1) # sent by after_create hook
      expect(new_applicant_email.bcc).to eq([@admin.email]) # sent by after_create hook
    end
  end

  it "should return it's name as the string" do
    user = FactoryBot.create(:user)

    expect(user.to_s).to eq(user.name)
  end

  it "should be able to get a list of accessible committees" do
    committee = FactoryBot.create(:committee)
    user = FactoryBot.create(:admin_user)
    expect(user.accessible_committees).to eq([committee])
  end

  it "should be able to see its committees" do
    cm = FactoryBot.create(:committee_member)

    expect(cm.user.committees).to eq([cm.committee])
  end

  it "should describe it's voting status via method" do
    user = FactoryBot.create(:user)
    cm = FactoryBot.create(:committee_member, user: user)

    expect(user.voting_text(cm.committee)).to eq("Voting Member")
  end

  it "should describe it's voting status via method when non-voting member" do
    user = FactoryBot.create(:user)
    cm = FactoryBot.create(:committee_member, user: user, voting: false)

    expect(user.voting_text(cm.committee)).to eq("Non-Voting Member")
  end

  it "should be able to list its votes" do
    user = FactoryBot.create(:user)
    vote = FactoryBot.create(:vote, user: user)

    expect(user.votes).to eq([vote])
  end

  it "doesn't need a name initially" do
    u = FactoryBot.build(:user, name: nil, confirmed_at: nil)
    expect(u).to be_valid
  end

  describe "when a user is created without a name" do
    let(:user) { FactoryBot.create(:user, name: nil, confirmed_at: nil, email: "robin@test.com") }

    it "uses the beginning of the e-mail as the to_s" do
      expect(user.to_s).to eq("robin@...")
    end
  end

  it "does require a name after being created" do
    u = FactoryBot.build(:user, name: nil)
    expect(u).to be_invalid
    u.name = "Robin"
    expect(u).to be_valid
  end

  context "with discussion comments" do
    let(:user) { FactoryBot.create(:user) }
    let!(:discussion_comment) { FactoryBot.create(:comment, user: user) }

    it "returns the discussion comments" do
      expect(user.discussion_comments).to match_array([discussion_comment])
    end
  end

  it "should be able to be created with comments" do
    user = User.new({name: "Robin",
                     email: "email@robin.com",
                     password: "password",
                     password_confirmation: "password",
                     comments: "Something"})
    expect(user.comments).to eq("Something")
    expect(user.valid?).to eq(true)
  end

  it "should have no_emails false by default" do
    user = User.new
    expect(user.no_emails).to eq(false)
  end

  it "should be able to be created with no_emails" do
    user = User.new({name: "Robin",
                     email: "email@robin.com",
                     password: "password",
                     password_confirmation: "password",
                     no_emails: true})
    expect(user.no_emails).to eq(true)
    expect(user.valid?).to eq(true)
  end
end


text:
package org.jf.dexlib2.iface.instruction.formats;

import org.jf.dexlib2.iface.instruction.OneFixedFourParameterRegisterInstruction;

public interface Instruction25x extends OneFixedFourParameterRegisterInstruction {
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright (C) 2021 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/buttons_glance_widget_description"
    android:initialLayout="@layout/widget_buttons"
    android:minWidth="180dp"
    android:minHeight="180dp"
    android:minResizeWidth="130dp"
    android:minResizeHeight="96dp"
    android:previewImage="@drawable/buttons_widget_preview"
    android:previewLayout="@layout/widget_buttons_preview"
    android:resizeMode="horizontal|vertical"
    android:targetCellWidth="3"
    android:targetCellHeight="3"
    android:widgetCategory="home_screen" />


text:
package joshie.harvest.shops.requirement;

import joshie.harvest.core.helpers.InventoryHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

import static joshie.harvest.core.helpers.InventoryHelper.ORE_DICTIONARY;

public class Stone extends AbstractRequirement {
    private static final ItemStack stoneItem = new ItemStack(Blocks.STONE);

    private Stone(ItemStack icon, int cost) {
        super(icon, cost);
    }

    public static Stone of(int amount) {
        return new Stone(stoneItem, amount);
    }

    @Override
    public boolean isFulfilled(World world, EntityPlayer player, int amount) {
        return InventoryHelper.hasInInventory(player, ORE_DICTIONARY, "stone", (cost * amount));
    }

    @Override
    public void onPurchased(EntityPlayer player) {
        InventoryHelper.takeItemsInInventory(player, ORE_DICTIONARY, "stone", cost);
    }
}


text:
{{define "settings"}}

Projected Monthly Income

$

                            <input type="number" min="0.01" step="0.01" class="form-control" id="amount" placeholder="0.00">

                    <button type="button" class="btn btn-warning btn-lg" ontouchstart="setProjectedIncome()">Save</button>

            <button type="button" class="btn btn-danger btn-lg" ontouchstart="logout()">Logout</button>

{{end}}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Caralluma commutata A.Berger

### Remarks
null


text:
package org.springside.modules.metrics;

import static org.assertj.core.api.Assertions.*;

import java.util.Map;

import org.junit.Test;
import org.springside.modules.metrics.metric.Counter;
import org.springside.modules.metrics.metric.Histogram;
import org.springside.modules.metrics.metric.HistogramMetric;
import org.springside.modules.metrics.metric.Timer;

public class MetricRegistryTest {

	@Test
	public void counter() {
		MetricRegistry metricRegistry = new MetricRegistry();
		Counter counter = metricRegistry.counter(MetricRegistry.name("UserService", "getUser.counter"));
		assertThat(counter).isNotNull();

		Map<String, Counter> counters = metricRegistry.getCounters();

		Counter counter2 = counters.get("UserService.getUser.counter");
		assertThat(counter2).isNotNull().isSameAs(counter);

		Counter counter3 = metricRegistry.counter(MetricRegistry.name("UserService", "getUser.counter"));
		assertThat(counter3).isNotNull().isSameAs(counter);
	}

	@Test
	public void histogram() {
		MetricRegistry metricRegistry = new MetricRegistry();
		Histogram histogram = metricRegistry.histogram(MetricRegistry.name("UserService", "getUser.latency"));
		assertThat(histogram).isNotNull();

		Map<String, Histogram> histograms = metricRegistry.getHistograms();

		Histogram histogram2 = histograms.get("UserService.getUser.latency");
		assertThat(histogram2).isNotNull().isSameAs(histogram);

		Histogram histogram3 = metricRegistry.histogram(MetricRegistry.name("UserService", "getUser.latency"));
		assertThat(histogram3).isNotNull().isSameAs(histogram);

	}

	@Test
	public void execution() {
		MetricRegistry metricRegistry = new MetricRegistry();

		Timer execution = metricRegistry.timer(MetricRegistry.name("UserService", "getUser.execution"));
		assertThat(execution).isNotNull();

		Map<String, Timer> executions = metricRegistry.getTimers();

		Timer execution2 = executions.get("UserService.getUser.execution");
		assertThat(execution2).isNotNull().isSameAs(execution);

		Timer execution3 = metricRegistry.timer(MetricRegistry.name("UserService", "getUser.execution"));
		assertThat(execution3).isNotNull().isSameAs(execution);
	}

	@Test
	public void defaultPcts() {
		MetricRegistry metricRegistry = new MetricRegistry();

		// set pcts 60,70
		Histogram histogram = metricRegistry.histogram(MetricRegistry.name("UserService", "getUser.histogram.setPcts"),
				60d, 70d);

		for (int i = 1; i <= 100; i++) {
			histogram.update(i);
		}

		HistogramMetric metric = histogram.calculateMetric();

		assertThat(metric.pcts.get(60d)).isEqualTo(60);
		assertThat(metric.pcts.get(70d)).isEqualTo(70);

		// new default 50
		metricRegistry.setDefaultPcts(new Double[] { 50d });
		Histogram histogramWithNewDefaultPcts = metricRegistry.histogram(MetricRegistry.name("UserService",
				"getUser.histogram.newDefault"));

		for (int i = 1; i <= 100; i++) {
			histogramWithNewDefaultPcts.update(i);
		}

		metric = histogramWithNewDefaultPcts.calculateMetric();

		assertThat(metric.pcts.get(50d)).isEqualTo(50);
		assertThat(metric.pcts.get(90d)).isNull();
	}
}


text:
package net.sourceforge.plantuml.tim.expression;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;

import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.tim.EaterException;
import net.sourceforge.plantuml.tim.EaterExceptionLocated;
import net.sourceforge.plantuml.tim.TContext;
import net.sourceforge.plantuml.tim.TFunction;
import net.sourceforge.plantuml.tim.TFunctionSignature;
import net.sourceforge.plantuml.tim.TMemory;

public class ReversePolishInterpretor {

	private final TValue result;
	private boolean trace = false;

	public ReversePolishInterpretor(TokenStack queue, Knowledge knowledge, TMemory memory, TContext context)
			throws EaterException, EaterExceptionLocated {
		this(null, queue, knowledge, memory, context);
	}

	public ReversePolishInterpretor(LineLocation location, TokenStack queue, Knowledge knowledge, TMemory memory,
			TContext context) throws EaterException, EaterExceptionLocated {

		final Deque<TValue> stack = new ArrayDeque<>();
		if (trace)
			System.err.println("ReversePolishInterpretor::queue=" + queue);
		for (TokenIterator it = queue.tokenIterator(); it.hasMoreTokens();) {
			final Token token = it.nextToken();
			if (trace)
				System.err.println("rpn " + token);
			if (token.getTokenType() == TokenType.NUMBER) {
				stack.addFirst(TValue.fromNumber(token));
			} else if (token.getTokenType() == TokenType.QUOTED_STRING) {
				stack.addFirst(TValue.fromString(token));
			} else if (token.getTokenType() == TokenType.JSON_DATA) {
				stack.addFirst(TValue.fromJson(token.getJson()));
			} else if (token.getTokenType() == TokenType.OPERATOR) {
				final TValue v2 = stack.removeFirst();
				final TValue v1 = stack.removeFirst();
				final TokenOperator op = token.getTokenOperator();
				if (op == null) {
					throw EaterException.unlocated("bad op");
				}
				final TValue tmp = op.operate(v1, v2);
				stack.addFirst(tmp);
			} else if (token.getTokenType() == TokenType.OPEN_PAREN_FUNC) {
				final int nb = Integer.parseInt(token.getSurface());
				final Token token2 = it.nextToken();
				if (token2.getTokenType() != TokenType.FUNCTION_NAME) {
					throw EaterException.unlocated("rpn43");
				}
				if (trace)
					System.err.println("token2=" + token2);
				final TFunction function = knowledge.getFunction(new TFunctionSignature(token2.getSurface(), nb));
				if (trace)
					System.err.println("function=" + function);
				if (function == null) {
					throw EaterException.unlocated("Unknown built-in function " + token2.getSurface());
				}
				if (function.canCover(nb, Collections.<String>emptySet()) == false) {
					throw EaterException
							.unlocated("Bad number of arguments for " + function.getSignature().getFunctionName());
				}
				final List<TValue> args = new ArrayList<>();
				for (int i = 0; i < nb; i++) {
					args.add(0, stack.removeFirst());
				}
				if (trace)
					System.err.println("args=" + args);
				if (location == null) {
					throw EaterException.unlocated("rpn44");
				}
				final TValue r = function.executeReturnFunction(context, memory, location, args,
						Collections.<String, TValue>emptyMap());
				if (trace)
					System.err.println("r=" + r);
				stack.addFirst(r);
			} else {
				throw EaterException.unlocated("rpn41");
			}
		}
		result = stack.removeFirst();
	}

	public final TValue getResult() {
		return result;
	}
}


text:
A bukkit/spigot plugin that manages your worlds!

**Notice**: This project is not completed and is terminated temporarily.


text:
script_time_0=$(date +%s.%N)

# We'll split the work amongst multiple cores; choose how many to use.
# 2014.02.14: Runic has 24 cores, so... let's use half of 'em.
#CORE_COUNT=12
# Let's use more...
#  anecdotally, [lb] sees about 5.2 or 5.5 lps (loops per second) when
#  processing node_stack_ids for --populate-nodes, regardless of if its
#  one core or 8... but I haven't tested, ya know, like 32.
CORE_COUNT=17

#CCP_DATABASE=ccpv3_live
#CCP_DATABASE=ccpv3_lite
#CCP_DATABASE=ccpv3_demo
if [[ -z "$CCP_DATABASE" ]]; then
  echo "ERROR: Please set CCP_DATABASE to the database to 'fix'"
  exit 1
fi

CCP_BRANCHES=("Mpls-St. Paul" "Metc Bikeways 2012")

# NOTE: You need to set search_path in ~/.psqlrc with the same, and public.
#INSTANCE="minnesota"
if [[ -z "$INSTANCE" ]]; then
  echo "ERROR: Please set INSTANCE to db namespace (SET search_path TO ...)"
  exit 1
fi

cd /ccp/dev/cp_cron/scripts/setupcp/

todays_date=`date +%Y.%m.%d`

# *** STEP 1: Drop existing node_* tables and recreate 'em.

./node_cache_maker.py \
  --database ${CCP_DATABASE} \
  --create-tables

# *** STEP 2: Populate node_endpoint table.

if false; then

   # For Devs to cxpx for testing...
  ./node_cache_maker.py --instance-master
  ./node_cache_maker.py --populate-nodes --branch 0 \
    --instance-worker --items-limit 500 --items-offset     0
  ./node_cache_maker.py --populate-nodes --branch 0 \
    --instance-worker --items-limit 500 --items-offset   500
  ./node_cache_maker.py --populate-nodes --branch 0 \
    --instance-worker --items-limit 500 --items-offset  1000
  ./node_cache_maker.py --populate-nodes --branch 0 \
    --instance-worker --items-limit 500 --items-offset  1500
  ./node_cache_maker.py --populate-nodes --branch 0 \
    --instance-worker --items-limit 500 --items-offset  2000
  ./node_cache_maker.py --populate-nodes --branch 0 \
    --instance-worker --items-limit 500 --items-offset  2500
  # etc...

  # You can also use nohup...
  nohup ./node_cache_maker.py --populate-nodes --branch "$branch_name" \
    --instance-worker --items-limit 25000 --items-offset 350000 \
    | tee /ccp/var/log/daily/2014.02.14.node_cache_make-worker-350.log 2>&1 &

else

  # Iterate over every branch...
  for arr_index in $(seq 0 $((${#CCP_BRANCHES[@]} - 1))); do

    # For cxpx testing:
    if false; then
      arr_index=0
      branch_name="Mpls-St. Paul"
      arr_index=1
      branch_name="Metc Bikeways 2012"
    fi
    #
    # But this is really what we want:
    branch_name=${CCP_BRANCHES[$arr_index]}
    echo "Processing branch: populate-nodes: $branch_name"

    # NOTE: Not using ${branch_name} because too lazy to convert spaces to
    #       underscores.
    log_file_base="/ccp/var/log/daily/${todays_date}.fix_nodes.${arr_index}"

    WAITPIDS=()
    time_0=$(date +%s.%N)

    # Start the so-called master instance that gets and sits on the rev. lock.
    # NOTE: Use --has-revision-lock because, if you've been a good dev. and
    #       have run litemaint.sh, then pyserver won't let you try to lock
    #       the revision table unless you're a local script deliberately
    #       trying to lock it.
    ./node_cache_maker.py \
        --database ${CCP_DATABASE} \
        --branch "$branch_name" \
        --instance-master \
        --has-revision-lock \
        -m "Reset node cache: --populate-nodes" \
        > ${log_file_base}-master.log 2>&1 &
    # Get the process ID of the last command (last/lastest pid)
    MASTER_PID="${!}"

    # 2014.02.14: Total nodes: 376688 distinct, non-null in geofeature
    if false; then
      # Explicitly set limit and offset.
      limit_size=25000
      last_offset=375000
    else
      # Otherwise, programmatically figure it out.
      sql_node_count="
        SELECT COUNT(*) FROM (
           SELECT DISTINCT (node_id) FROM (
              SELECT beg_node_id FROM ${INSTANCE}.geofeature
              UNION
                 SELECT fin_node_id FROM ${INSTANCE}.geofeature
              ) AS node_id
              WHERE node_id IS NOT NULL
           ) AS foo
           ;
        "
        number_nodes=$(psql -U postgres --no-psqlrc -d ${CCP_DATABASE} \
                            --tuples-only -c "$sql_node_count")
        echo "Node count: $number_nodes"
        # Find the page size limit according to the number of cores sacrificed.
        # Add one to adjust for possible floating point truncation.
        limit_size=$((($number_nodes / $CORE_COUNT) + 1))
        echo "Limit size: $limit_size"
        # Get the floor of the node count w.r.t. the limit value.
        last_offset=$((($number_nodes) / $limit_size * $limit_size))
        echo "Last offset: $last_offset"
    fi

    # 2014.02.14: Running 6 processes asynchronously on 25,000 nodes each
    #             takes about 1.25 hours.
    init_offset=0
    for seq_offset in $(seq $init_offset $limit_size $last_offset); do
      echo "On offset: $seq_offset"
      ./node_cache_maker.py \
        --database ${CCP_DATABASE} \
        --branch "$branch_name" \
        --populate-nodes \
        --instance-worker \
        --has-revision-lock \
        --items-limit $limit_size \
        --items-offset $seq_offset \
        > ${log_file_base}-worker-$seq_offset.log 2>&1 &
      WAITPIDS+=("${!}")
    done # loop over each limit/offset

    # 2014.02.21: Processing branch: populate-nodes: Mpls-St. Paul
    #             Node count:  376688
    #             Background tasks complete after 89.00 mins.
    #             Processing branch: populate-nodes: Metc Bikeways 2012
    #             Background tasks complete after 67.00 mins.

    # Wait for all children to finish, and then finalize the revision.
    printf "Waiting for background tasks to complete...\n"
    echo "WAITPIDS: ${WAITPIDS[*]}"
    #
    wait ${WAITPIDS[*]}
    #
    sleep 1
    #
    time_1=$(date +%s.%N)
    $DEBUG_TRACE && printf "Background tasks complete after %.2F mins.\n" \
      $(echo "(${time_1} - ${time_0}) / 60.0" | bc -l)

    # Ctrl-C the master thread
    if true; then
      # Get the process details, e.g.,
      # $USER $PID 0.1 0.0 158172 27408 pts/2 S 14:08 0:06 /usr/bin/python \
      #  ./node_cache_maker.py --instance-master
      proc_details=`ps aux \
                    | grep node_cache_maker \
                    | grep -- "--instance-master"`
      set -- junk $proc_details
      shift
      master_proc_pid=$2
      if [[ $MASTER_PID -ne $master_proc_pid ]]; then
        echo "WARNING: Unexpected Master PID: $MASTER_PID not $master_proc_pid"
      fi
      echo "Killing master process: PID $master_proc_pid"
      kill -s 2 $master_proc_pid
      # We probably don't need to sleep, but maybe commit takes a sec.
      sleep 1
    fi

  done # loop over each branch

fi # done with --populate-nodes

# *** STEP 3: Perform final two activities.

for arr_index in $(seq 0 $((${#CCP_BRANCHES[@]} - 1))); do

  # For cxpx testing:
  if false; then
    branch_name="Mpls-St. Paul"
    branch_name="Metc Bikeways 2012"
  fi
  #
  # But this is really what we want:
  branch_name=${CCP_BRANCHES[$arr_index]}
  echo "Processing branch: internals and routes: $branch_name"

  # NOTE: Not using ${branch_name} because too lazy to convert spaces to
  #       underscores.
  log_file_base="/ccp/var/log/daily/${todays_date}.fix_nodes.${arr_index}"

  # 2013.02.21: For Greater MN,         12.18 mins.
  # 2013.02.21: For Metc Bikeways 2012,  4.08 mins.
  ./node_cache_maker.py \
    --add-internals \
    --branch "$branch_name" \
    --has-revision-lock \
    -m "Reset node cache: --add-internals" \
    > ${log_file_base}-internals.log 2>&1 &

  # 2013.02.21: For Greater MN,          2.10 mins.
  # 2013.02.21: For Metc Bikeways 2012, 54.47 secs.
  ./node_cache_maker.py \
    --update-route \
    --branch "$branch_name" \
    --has-revision-lock \
    -m "Reset node cache: --update-route" \
    > ${log_file_base}-routes.log 2>&1 &

done

# *** STEP 4: Recreate the VIEWs that we dropped.

cd /ccp/dev/cp_cron/scripts/dev

# This won't work: --no-psqlrc... so ~/.psqlrc should specify the schemas.
psql -U cycling -d ${CCP_DATABASE} \
   < /ccp/dev/cp_cron/scripts/dev/convenience_views.sql

# *** STEP 5: Vacuum me maybe.

# MAYBE: vacuum...
if false; then
   psql -U postgres -d ${CCP_DATABASE} -c "VACUUM ANALYZE;"
fi

# *** Print elapsed time.

time_1=$(date +%s.%N)
printf "All done: Elapsed: %.2F mins.\n" \
  $(echo "($time_1 - $script_time_0) / 60.0" | bc -l)

# *** All done.

exit 0


text:
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Azure.Analytics.Synapse.Artifacts;
using Azure.Analytics.Synapse.Artifacts.Models;
using Azure.Analytics.Synapse.Tests;
using Azure.Core.TestFramework;
using NUnit.Framework;

namespace Azure.Analytics.Synapse.Artifacts.Tests
{
    /// <summary>
    /// The suite of tests for the <see cref="PipelineClient"/> class.
    /// </summary>
    /// <remarks>
    /// These tests have a dependency on live Azure services and may incur costs for the associated
    /// Azure subscription.
    /// </remarks>
    public class PipelineClientLiveTests : RecordedTestBase<SynapseTestEnvironment>
    {
        public PipelineClientLiveTests(bool isAsync) : base(isAsync)
        {
        }

        private PipelineClient CreateClient()
        {
            return InstrumentClient(new PipelineClient(
                new Uri(TestEnvironment.EndpointUrl),
                TestEnvironment.Credential,
                InstrumentClientOptions(new ArtifactsClientOptions())
            ));
        }

        [RecordedTest]
        public async Task TestGetPipeline()
        {
            PipelineClient client = CreateClient ();
            await using DisposablePipeline pipeline = await DisposablePipeline.Create (client, this.Recording);

            IList<PipelineResource> pipelines = await client.GetPipelinesByWorkspaceAsync().ToListAsync();
            Assert.GreaterOrEqual(pipelines.Count, 1);

            foreach (var expectedPipeline in pipelines)
            {
                PipelineResource actualPipeline = await client.GetPipelineAsync(expectedPipeline.Name);
                Assert.AreEqual(expectedPipeline.Name, actualPipeline.Name);
                Assert.AreEqual(expectedPipeline.Id, actualPipeline.Id);
            }
        }

        [RecordedTest]
        public async Task TestDeleteNotebook()
        {
            PipelineClient client = CreateClient();

            PipelineResource resource = await DisposablePipeline.CreateResource (client, this.Recording);

            PipelineDeletePipelineOperation operation = await client.StartDeletePipelineAsync (resource.Name);
            await operation.WaitAndAssertSuccessfulCompletion();
        }

        [RecordedTest]
        public async Task TestRenameLinkedService()
        {
            PipelineClient client = CreateClient();

            PipelineResource resource = await DisposablePipeline.CreateResource (client, Recording);

            string newPipelineName = Recording.GenerateId("Pipeline2", 16);

            PipelineRenamePipelineOperation renameOperation = await client.StartRenamePipelineAsync (resource.Name, new ArtifactRenameRequest () { NewName = newPipelineName } );
            await renameOperation.WaitForCompletionAsync();

            PipelineResource pipeline = await client.GetPipelineAsync (newPipelineName);
            Assert.AreEqual (newPipelineName, pipeline.Name);

            PipelineDeletePipelineOperation operation = await client.StartDeletePipelineAsync (newPipelineName);
            await operation.WaitForCompletionAsync();
        }

        [RecordedTest]
        public async Task TestPipelineRun()
        {
            PipelineClient client = CreateClient();

            await using DisposablePipeline pipeline = await DisposablePipeline.Create (client, this.Recording);

            CreateRunResponse runResponse = await client.CreatePipelineRunAsync (pipeline.Name);
            Assert.NotNull(runResponse.RunId);
        }
    }
}