text:
"""basic tests of lazy loaded attributes"""

from sqlalchemy.testing import assert_raises
import datetime
from sqlalchemy.orm import attributes, exc as orm_exc, configure_mappers
import sqlalchemy as sa
from sqlalchemy import testing, and_, bindparam
from sqlalchemy import Integer, String, ForeignKey, SmallInteger, Boolean
from sqlalchemy import ForeignKeyConstraint
from sqlalchemy.types import TypeDecorator
from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.schema import Column
from sqlalchemy import orm
from sqlalchemy.orm import mapper, relationship, create_session, Session
from sqlalchemy.testing import eq_, is_true, is_false
from sqlalchemy.testing import fixtures
from test.orm import _fixtures
from sqlalchemy.testing.assertsql import CompiledSQL

class LazyTest(_fixtures.FixtureTest):
    run_inserts = 'once'
    run_deletes = None

    def test_basic(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(User, users, properties={
            'addresses': relationship(
                mapper(Address, addresses), lazy='select')
        })
        sess = create_session()
        q = sess.query(User)
        eq_(
            [User(id=7,
                  addresses=[Address(id=1, email_address='jack@bean.com')])],
            q.filter(users.c.id == 7).all()
        )

    def test_needs_parent(self):
        """test the error raised when parent object is not bound."""

        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(User, users, properties={
            'addresses': relationship(
                mapper(Address, addresses), lazy='select')
        })
        sess = create_session()
        q = sess.query(User)
        u = q.filter(users.c.id == 7).first()
        sess.expunge(u)
        assert_raises(orm_exc.DetachedInstanceError, getattr, u, 'addresses')

    def test_orderby(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(User, users, properties={
            'addresses': relationship(
                mapper(Address, addresses),
                lazy='select', order_by=addresses.c.email_address),
        })
        q = create_session().query(User)
        assert [
            User(id=7, addresses=[
                Address(id=1)
            ]),
            User(id=8, addresses=[
                Address(id=3, email_address='ed@bettyboop.com'),
                Address(id=4, email_address='ed@lala.com'),
                Address(id=2, email_address='ed@wood.com')
            ]),
            User(id=9, addresses=[
                Address(id=5)
            ]),
            User(id=10, addresses=[])
        ] == q.all()

    def test_orderby_secondary(self):
        """tests that a regular mapper select on a single table can
        order by a relationship to a second table"""

        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User)

        mapper(Address, addresses)

        mapper(User, users, properties=dict(
            addresses=relationship(Address, lazy='select'),
        ))
        q = create_session().query(User)
        l = q.filter(users.c.id == addresses.c.user_id).\
            order_by(addresses.c.email_address).all()
        assert [
            User(id=8, addresses=[
                Address(id=2, email_address='ed@wood.com'),
                Address(id=3, email_address='ed@bettyboop.com'),
                Address(id=4, email_address='ed@lala.com'),
            ]),
            User(id=9, addresses=[
                Address(id=5)
            ]),
            User(id=7, addresses=[
                Address(id=1)
            ]),
        ] == l

    def test_orderby_desc(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User)

        mapper(Address, addresses)

        mapper(User, users, properties=dict(
            addresses=relationship(
                Address, lazy='select',
                order_by=[sa.desc(addresses.c.email_address)]),
        ))
        sess = create_session()
        assert [
            User(id=7, addresses=[
                Address(id=1)
            ]),
            User(id=8, addresses=[
                Address(id=2, email_address='ed@wood.com'),
                Address(id=4, email_address='ed@lala.com'),
                Address(id=3, email_address='ed@bettyboop.com'),
            ]),
            User(id=9, addresses=[
                Address(id=5)
            ]),
            User(id=10, addresses=[])
        ] == sess.query(User).all()

    def test_no_orphan(self):
        """test that a lazily loaded child object is not marked as an orphan"""

        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(User, users, properties={
            'addresses': relationship(
                Address, cascade="all,delete-orphan", lazy='select')
        })
        mapper(Address, addresses)

        sess = create_session()
        user = sess.query(User).get(7)
        assert getattr(User, 'addresses').hasparent(
            attributes.instance_state(user.addresses[0]), optimistic=True)
        assert not sa.orm.class_mapper(Address)._is_orphan(
            attributes.instance_state(user.addresses[0]))

    def test_limit(self):
        """test limit operations combined with lazy-load relationships."""

        users, items, order_items, orders, Item, \
            User, Address, Order, addresses = (
                self.tables.users,
                self.tables.items,
                self.tables.order_items,
                self.tables.orders,
                self.classes.Item,
                self.classes.User,
                self.classes.Address,
                self.classes.Order,
                self.tables.addresses)

        mapper(Item, items)
        mapper(Order, orders, properties={
            'items': relationship(Item, secondary=order_items, lazy='select')
        })
        mapper(User, users, properties={
            'addresses': relationship(
                mapper(Address, addresses), lazy='select'),
            'orders': relationship(Order, lazy='select')
        })

        sess = create_session()
        q = sess.query(User)

        if testing.against('mssql'):
            l = q.limit(2).all()
            assert self.static.user_all_result[:2] == l
        else:
            l = q.limit(2).offset(1).all()
            assert self.static.user_all_result[1:3] == l

    def test_distinct(self):
        users, items, order_items, orders, \
            Item, User, Address, Order, addresses = (
                self.tables.users,
                self.tables.items,
                self.tables.order_items,
                self.tables.orders,
                self.classes.Item,
                self.classes.User,
                self.classes.Address,
                self.classes.Order,
                self.tables.addresses)

        mapper(Item, items)
        mapper(Order, orders, properties={
            'items': relationship(Item, secondary=order_items, lazy='select')
        })
        mapper(User, users, properties={
            'addresses': relationship(
                mapper(Address, addresses), lazy='select'),
            'orders': relationship(Order, lazy='select')
        })

        sess = create_session()
        q = sess.query(User)

        # use a union all to get a lot of rows to join against
        u2 = users.alias('u2')
        s = sa.union_all(
            u2.select(use_labels=True),
            u2.select(use_labels=True), u2.select(use_labels=True)).alias('u')
        l = q.filter(s.c.u2_id == User.id).order_by(User.id).distinct().all()
        eq_(self.static.user_all_result, l)

    def test_uselist_false_warning(self):
        """test that multiple rows received by a
        uselist=False raises a warning."""

        User, users, orders, Order = (
            self.classes.User,
            self.tables.users,
            self.tables.orders,
            self.classes.Order)

        mapper(User, users, properties={
            'order': relationship(Order, uselist=False)
        })
        mapper(Order, orders)
        s = create_session()
        u1 = s.query(User).filter(User.id == 7).one()
        assert_raises(sa.exc.SAWarning, getattr, u1, 'order')

    def test_callable_bind(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User)

        mapper(User, users, properties=dict(
            addresses=relationship(
                mapper(Address, addresses),
                lazy='select',
                primaryjoin=and_(
                    users.c.id == addresses.c.user_id,
                    users.c.name == bindparam("name", callable_=lambda: "ed")
                )
            )
        ))

        s = Session()
        ed = s.query(User).filter_by(name='ed').one()
        eq_(ed.addresses, [
            Address(id=2, user_id=8),
            Address(id=3, user_id=8),
            Address(id=4, user_id=8)
        ])

        fred = s.query(User).filter_by(name='fred').one()
        eq_(fred.addresses, [])  # fred is missing

    def test_one_to_many_scalar(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User)

        mapper(User, users, properties=dict(
            address=relationship(
                mapper(Address, addresses), lazy='select', uselist=False)
        ))
        q = create_session().query(User)
        l = q.filter(users.c.id == 7).all()
        assert [User(id=7, address=Address(id=1))] == l

    def test_many_to_one_binds(self):
        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User)

        mapper(Address, addresses,
               primary_key=[addresses.c.user_id, addresses.c.email_address])

        mapper(User, users, properties=dict(
            address=relationship(
                Address, uselist=False,
                primaryjoin=sa.and_(
                    users.c.id == addresses.c.user_id,
                    addresses.c.email_address == 'ed@bettyboop.com'))
        ))
        q = create_session().query(User)
        eq_(
            [
                User(id=7, address=None),
                User(id=8, address=Address(id=3)),
                User(id=9, address=None),
                User(id=10, address=None),
            ],
            list(q)
        )

    def test_double(self):
        """tests lazy loading with two relationships simultaneously,
        from the same table, using aliases.  """

        users, orders, User, Address, Order, addresses = (
            self.tables.users,
            self.tables.orders,
            self.classes.User,
            self.classes.Address,
            self.classes.Order,
            self.tables.addresses)

        openorders = sa.alias(orders, 'openorders')
        closedorders = sa.alias(orders, 'closedorders')

        mapper(Address, addresses)

        mapper(Order, orders)

        open_mapper = mapper(Order, openorders, non_primary=True)
        closed_mapper = mapper(Order, closedorders, non_primary=True)
        mapper(User, users, properties=dict(
            addresses=relationship(Address, lazy=True),
            open_orders=relationship(
                open_mapper,
                primaryjoin=sa.and_(
                    openorders.c.isopen == 1,
                    users.c.id == openorders.c.user_id), lazy='select'),
            closed_orders=relationship(
                closed_mapper,
                primaryjoin=sa.and_(
                    closedorders.c.isopen == 0,
                    users.c.id == closedorders.c.user_id), lazy='select')
        ))
        q = create_session().query(User)

        assert [
            User(
                id=7,
                addresses=[Address(id=1)],
                open_orders=[Order(id=3)],
                closed_orders=[Order(id=1), Order(id=5)]
            ),
            User(
                id=8,
                addresses=[Address(id=2), Address(id=3), Address(id=4)],
                open_orders=[],
                closed_orders=[]
            ),
            User(
                id=9,
                addresses=[Address(id=5)],
                open_orders=[Order(id=4)],
                closed_orders=[Order(id=2)]
            ),
            User(id=10)

        ] == q.all()

        sess = create_session()
        user = sess.query(User).get(7)
        eq_(
            [Order(id=1), Order(id=5)],
            create_session().query(closed_mapper).with_parent(
                user, property='closed_orders').all()
        )
        eq_(
            [Order(id=3)],
            create_session().query(open_mapper).
            with_parent(user, property='open_orders').all()
        )

    def test_many_to_many(self):
        keywords, items, item_keywords, Keyword, Item = (
            self.tables.keywords,
            self.tables.items,
            self.tables.item_keywords,
            self.classes.Keyword,
            self.classes.Item)

        mapper(Keyword, keywords)
        mapper(Item, items, properties=dict(
            keywords=relationship(
                Keyword, secondary=item_keywords, lazy='select'),
        ))

        q = create_session().query(Item)
        assert self.static.item_keyword_result == q.all()

        eq_(
            self.static.item_keyword_result[0:2],
            q.join('keywords').filter(keywords.c.name == 'red').all()
        )

    def test_uses_get(self):
        """test that a simple many-to-one lazyload optimizes
        to use query.get()."""

        Address, addresses, users, User = (
            self.classes.Address,
            self.tables.addresses,
            self.tables.users,
            self.classes.User)

        for pj in (
            None,
            users.c.id == addresses.c.user_id,
            addresses.c.user_id == users.c.id
        ):
            mapper(Address, addresses, properties=dict(
                user=relationship(
                    mapper(User, users), lazy='select', primaryjoin=pj)
            ))

            sess = create_session()

            # load address
            a1 = sess.query(Address).\
                filter_by(email_address="ed@wood.com").one()

            # load user that is attached to the address
            u1 = sess.query(User).get(8)

            def go():
                # lazy load of a1.user should get it from the session
                assert a1.user is u1
            self.assert_sql_count(testing.db, go, 0)
            sa.orm.clear_mappers()

    def test_uses_get_compatible_types(self):
        """test the use_get optimization with compatible
        but non-identical types"""

        User, Address = self.classes.User, self.classes.Address

        class IntDecorator(TypeDecorator):
            impl = Integer

        class SmallintDecorator(TypeDecorator):
            impl = SmallInteger

        class SomeDBInteger(sa.Integer):
            pass

        for tt in [
            Integer,
            SmallInteger,
            IntDecorator,
            SmallintDecorator,
            SomeDBInteger,
        ]:
            m = sa.MetaData()
            users = Table(
                'users', m,
                Column(
                    'id', Integer, primary_key=True,
                    test_needs_autoincrement=True),
                Column('name', String(30), nullable=False),
            )
            addresses = Table(
                'addresses', m,
                Column(
                    'id', Integer, primary_key=True,
                    test_needs_autoincrement=True),
                Column('user_id', tt, ForeignKey('users.id')),
                Column('email_address', String(50), nullable=False),
            )

            mapper(Address, addresses, properties=dict(
                user=relationship(mapper(User, users))
            ))

            sess = create_session(bind=testing.db)

            # load address
            a1 = sess.query(Address).\
                filter_by(email_address="ed@wood.com").one()

            # load user that is attached to the address
            u1 = sess.query(User).get(8)

            def go():
                # lazy load of a1.user should get it from the session
                assert a1.user is u1
            self.assert_sql_count(testing.db, go, 0)
            sa.orm.clear_mappers()

    def test_many_to_one(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(Address, addresses, properties=dict(
            user=relationship(mapper(User, users), lazy='select')
        ))
        sess = create_session()
        q = sess.query(Address)
        a = q.filter(addresses.c.id == 1).one()

        assert a.user is not None

        u1 = sess.query(User).get(7)

        assert a.user is u1

    def test_backrefs_dont_lazyload(self):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(User, users, properties={
            'addresses': relationship(Address, backref='user')
        })
        mapper(Address, addresses)
        sess = create_session()
        ad = sess.query(Address).filter_by(id=1).one()
        assert ad.user.id == 7

        def go():
            ad.user = None
            assert ad.user is None
        self.assert_sql_count(testing.db, go, 0)

        u1 = sess.query(User).filter_by(id=7).one()

        def go():
            assert ad not in u1.addresses
        self.assert_sql_count(testing.db, go, 1)

        sess.expire(u1, ['addresses'])

        def go():
            assert ad in u1.addresses
        self.assert_sql_count(testing.db, go, 1)

        sess.expire(u1, ['addresses'])
        ad2 = Address()

        def go():
            ad2.user = u1
            assert ad2.user is u1
        self.assert_sql_count(testing.db, go, 0)

        def go():
            assert ad2 in u1.addresses
        self.assert_sql_count(testing.db, go, 1)

class GetterStateTest(_fixtures.FixtureTest):

    """test lazyloader on non-existent attribute returns
    expected attribute symbols, maintain expected state"""

    run_inserts = None

    def _unhashable_fixture(self, metadata, load_on_pending=False):
        class MyHashType(sa.TypeDecorator):
            impl = sa.String(100)

            def process_bind_param(self, value, dialect):
                return ";".join(
                    "%s=%s" % (k, v)
                       for k, v in
                       sorted(value.items(), key=lambda key: key[0]))

            def process_result_value(self, value, dialect):
                return dict(elem.split("=", 1) for elem in value.split(";"))

        category = Table(
            'category', metadata,
            Column('id', Integer, primary_key=True),
            Column('data', MyHashType())
        )
        article = Table(
            'article', metadata,
            Column('id', Integer, primary_key=True),
            Column('data', MyHashType())
        )

        class Category(fixtures.ComparableEntity):
            pass

        class Article(fixtures.ComparableEntity):
            pass

        mapper(Category, category)
        mapper(Article, article, properties={
            "category": relationship(
                Category,
                primaryjoin=orm.foreign(article.c.data) == category.c.data,
                load_on_pending=load_on_pending
            )
        })

        metadata.create_all()
        sess = Session(autoflush=False)
        data = {"im": "unhashable"}
        a1 = Article(id=1, data=data)
        c1 = Category(id=1, data=data)
        if load_on_pending:
            sess.add(c1)
        else:
            sess.add_all([c1, a1])
        sess.flush()
        if load_on_pending:
            sess.add(a1)
        return Category, Article, sess, a1, c1

    def _u_ad_fixture(self, populate_user, dont_use_get=False):
        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(User, users, properties={
            'addresses': relationship(Address, back_populates='user')
        })
        mapper(Address, addresses, properties={
            'user': relationship(
                User,
                primaryjoin=and_(
                    users.c.id == addresses.c.user_id, users.c.id != 27)
                if dont_use_get else None,
                back_populates='addresses'
            )
        })

        sess = create_session()
        a1 = Address(email_address='a1')
        sess.add(a1)
        if populate_user:
            a1.user = User(name='ed')
        sess.flush()
        if populate_user:
            sess.expire_all()
        return User, Address, sess, a1

    def test_no_use_get_params_missing(self):
        User, Address, sess, a1 = self._u_ad_fixture(False, True)

        def go():
            eq_(a1.user, None)

        # doesn't emit SQL
        self.assert_sql_count(
            testing.db,
            go,
            0
        )

    @testing.provide_metadata
    def test_no_use_get_params_not_hashable(self):
        Category, Article, sess, a1, c1 = \
            self._unhashable_fixture(self.metadata)

        def go():
            eq_(a1.category, c1)

        self.assert_sql_count(
            testing.db,
            go,
            1
        )

    @testing.provide_metadata
    def test_no_use_get_params_not_hashable_on_pending(self):
        Category, Article, sess, a1, c1 = \
            self._unhashable_fixture(self.metadata, load_on_pending=True)

        def go():
            eq_(a1.category, c1)

        self.assert_sql_count(
            testing.db,
            go,
            1
        )

    def test_get_empty_passive_return_never_set(self):
        User, Address, sess, a1 = self._u_ad_fixture(False)
        eq_(
            Address.user.impl.get(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_RETURN_NEVER_SET),
            attributes.NEVER_SET
        )
        assert 'user_id' not in a1.__dict__
        assert 'user' not in a1.__dict__

    def test_history_empty_passive_return_never_set(self):
        User, Address, sess, a1 = self._u_ad_fixture(False)
        eq_(
            Address.user.impl.get_history(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_RETURN_NEVER_SET),
            ((), (), ())
        )
        assert 'user_id' not in a1.__dict__
        assert 'user' not in a1.__dict__

    def test_get_empty_passive_no_initialize(self):
        User, Address, sess, a1 = self._u_ad_fixture(False)
        eq_(
            Address.user.impl.get(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_NO_INITIALIZE),
            attributes.PASSIVE_NO_RESULT
        )
        assert 'user_id' not in a1.__dict__
        assert 'user' not in a1.__dict__

    def test_history_empty_passive_no_initialize(self):
        User, Address, sess, a1 = self._u_ad_fixture(False)
        eq_(
            Address.user.impl.get_history(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_NO_INITIALIZE),
            attributes.HISTORY_BLANK
        )
        assert 'user_id' not in a1.__dict__
        assert 'user' not in a1.__dict__

    def test_get_populated_passive_no_initialize(self):
        User, Address, sess, a1 = self._u_ad_fixture(True)
        eq_(
            Address.user.impl.get(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_NO_INITIALIZE),
            attributes.PASSIVE_NO_RESULT
        )
        assert 'user_id' not in a1.__dict__
        assert 'user' not in a1.__dict__

    def test_history_populated_passive_no_initialize(self):
        User, Address, sess, a1 = self._u_ad_fixture(True)
        eq_(
            Address.user.impl.get_history(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_NO_INITIALIZE),
            attributes.HISTORY_BLANK
        )
        assert 'user_id' not in a1.__dict__
        assert 'user' not in a1.__dict__

    def test_get_populated_passive_return_never_set(self):
        User, Address, sess, a1 = self._u_ad_fixture(True)
        eq_(
            Address.user.impl.get(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_RETURN_NEVER_SET),
            User(name='ed')
        )

    def test_history_populated_passive_return_never_set(self):
        User, Address, sess, a1 = self._u_ad_fixture(True)
        eq_(
            Address.user.impl.get_history(
                attributes.instance_state(a1),
                attributes.instance_dict(a1),
                passive=attributes.PASSIVE_RETURN_NEVER_SET),
            ((), [User(name='ed'), ], ())
        )

class M2OGetTest(_fixtures.FixtureTest):
    run_inserts = 'once'
    run_deletes = None

    def test_m2o_noload(self):
        """test that a NULL foreign key doesn't trigger a lazy load"""

        users, Address, addresses, User = (
            self.tables.users,
            self.classes.Address,
            self.tables.addresses,
            self.classes.User)

        mapper(User, users)

        mapper(Address, addresses, properties={
            'user': relationship(User)
        })

        sess = create_session()
        ad1 = Address(email_address='somenewaddress', id=12)
        sess.add(ad1)
        sess.flush()
        sess.expunge_all()

        ad2 = sess.query(Address).get(1)
        ad3 = sess.query(Address).get(ad1.id)

        def go():
            # one lazy load
            assert ad2.user.name == 'jack'
            # no lazy load
            assert ad3.user is None
        self.assert_sql_count(testing.db, go, 1)

class CorrelatedTest(fixtures.MappedTest):

    @classmethod
    def define_tables(self, meta):
        Table('user_t', meta,
              Column('id', Integer, primary_key=True),
              Column('name', String(50)))

        Table('stuff', meta,
              Column('id', Integer, primary_key=True),
              Column('date', sa.Date),
              Column('user_id', Integer, ForeignKey('user_t.id')))

    @classmethod
    def insert_data(cls):
        stuff, user_t = cls.tables.stuff, cls.tables.user_t

        user_t.insert().execute(
            {'id': 1, 'name': 'user1'},
            {'id': 2, 'name': 'user2'},
            {'id': 3, 'name': 'user3'})

        stuff.insert().execute(
            {'id': 1, 'user_id': 1, 'date': datetime.date(2007, 10, 15)},
            {'id': 2, 'user_id': 1, 'date': datetime.date(2007, 12, 15)},
            {'id': 3, 'user_id': 1, 'date': datetime.date(2007, 11, 15)},
            {'id': 4, 'user_id': 2, 'date': datetime.date(2008, 1, 15)},
            {'id': 5, 'user_id': 3, 'date': datetime.date(2007, 6, 15)})

    def test_correlated_lazyload(self):
        stuff, user_t = self.tables.stuff, self.tables.user_t

        class User(fixtures.ComparableEntity):
            pass

        class Stuff(fixtures.ComparableEntity):
            pass

        mapper(Stuff, stuff)

        stuff_view = sa.select([stuff.c.id]).\
            where(stuff.c.user_id == user_t.c.id).correlate(user_t).\
            order_by(sa.desc(stuff.c.date)).limit(1)

        mapper(User, user_t, properties={
            'stuff': relationship(
                Stuff,
                primaryjoin=sa.and_(
                    user_t.c.id == stuff.c.user_id,
                    stuff.c.id == (stuff_view.as_scalar())))
        })

        sess = create_session()

        eq_(
            sess.query(User).all(),
            [
                User(
                    name='user1',
                    stuff=[Stuff(date=datetime.date(2007, 12, 15), id=2)]),
                User(
                    name='user2',
                    stuff=[Stuff(id=4, date=datetime.date(2008, 1, 15))]),
                User(
                    name='user3',
                    stuff=[Stuff(id=5, date=datetime.date(2007, 6, 15))])
            ]
        )

class O2MWOSideFixedTest(fixtures.MappedTest):
    # test #2948 - o2m backref with a "m2o does/does not count"
    # criteria doesn't scan the "o" table

    @classmethod
    def define_tables(self, meta):
        Table('city', meta,
              Column('id', Integer, primary_key=True),
              Column('deleted', Boolean),
              )
        Table('person', meta,
              Column('id', Integer, primary_key=True),
              Column('city_id', ForeignKey('city.id'))
              )

    @classmethod
    def setup_classes(cls):
        class Person(cls.Basic):
            pass

        class City(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        Person, City = cls.classes.Person, cls.classes.City
        city, person = cls.tables.city, cls.tables.person

        mapper(Person, person, properties={
            'city': relationship(City,
                                 primaryjoin=and_(
                                     person.c.city_id == city.c.id,
                                     city.c.deleted == False),
                                 backref='people'
                                 )
        })
        mapper(City, city)

    def _fixture(self, include_other):
        city, person = self.tables.city, self.tables.person

        if include_other:
            city.insert().execute(
                {"id": 1, "deleted": False},
            )

            person.insert().execute(
                {"id": 1, "city_id": 1},
                {"id": 2, "city_id": 1},
            )

        city.insert().execute(
            {"id": 2, "deleted": True},
        )

        person.insert().execute(
            {"id": 3, "city_id": 2},
            {"id": 4, "city_id": 2},
        )

    def test_lazyload_assert_expected_sql(self):
        self._fixture(True)
        City = self.classes.City
        sess = Session(testing.db)
        c1, c2 = sess.query(City).order_by(City.id).all()

        def go():
            eq_(
                [p.id for p in c2.people],
                []
            )

        self.assert_sql_execution(
            testing.db,
            go,
            CompiledSQL(
                "SELECT person.id AS person_id, person.city_id AS "
                "person_city_id FROM person "
                "WHERE person.city_id = :param_1 AND :param_2 = 0",
                {"param_1": 2, "param_2": 1}
            )
        )

    def test_lazyload_people_other_exists(self):
        self._fixture(True)
        City = self.classes.City
        sess = Session(testing.db)
        c1, c2 = sess.query(City).order_by(City.id).all()
        eq_(
            [p.id for p in c1.people],
            [1, 2]
        )

        eq_(
            [p.id for p in c2.people],
            []
        )

    def test_lazyload_people_no_other_exists(self):
        # note that if we revert #2948, *this still passes!*
        # e.g. due to the scan of the "o" table, whether or not *another*
        # row exists determines if this works.

        self._fixture(False)
        City = self.classes.City
        sess = Session(testing.db)
        c2, = sess.query(City).order_by(City.id).all()

        eq_(
            [p.id for p in c2.people],
            []
        )

class RefersToSelfLazyLoadInterferenceTest(fixtures.MappedTest):
    """Test [issue:3145].

    This involves an object that refers to itself, which isn't
    entirely a supported use case.   Here, we're able to fix it,
    but long term it's not clear if future needs will affect this.
    The use case is not super-critical.

    """

    @classmethod
    def define_tables(cls, metadata):
        Table(
            'a', metadata,
            Column('a_id', Integer, primary_key=True),
            Column('b_id', ForeignKey('b.b_id')),
        )

        Table(
            'b', metadata,
            Column('b_id', Integer, primary_key=True),
            Column('parent_id', ForeignKey('b.b_id')),
        )

        Table(
            'c', metadata,
            Column('c_id', Integer, primary_key=True),
            Column('b_id', ForeignKey('b.b_id')),
        )

    @classmethod
    def setup_classes(cls):
        class A(cls.Basic):
            pass

        class B(cls.Basic):
            pass

        class C(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        mapper(cls.classes.A, cls.tables.a, properties={
            "b": relationship(cls.classes.B)
        })
        bm = mapper(cls.classes.B, cls.tables.b, properties={
            "parent": relationship(
                cls.classes.B, remote_side=cls.tables.b.c.b_id),
            "zc": relationship(cls.classes.C)
        })
        mapper(cls.classes.C, cls.tables.c)

        bmp = bm._props
        configure_mappers()
        # Bug is order-dependent, must sort the "zc" property to the end
        bmp.sort()

    def test_lazy_doesnt_interfere(self):
        A, B, C = self.classes("A", "B", "C")

        session = Session()
        b = B()
        session.add(b)
        session.flush()

        b.parent_id = b.b_id

        b.zc.append(C())
        b.zc.append(C())
        session.commit()

        # If the bug is here, the next line throws an exception
        session.query(B).options(
            sa.orm.joinedload('parent').joinedload('zc')).all()

class TypeCoerceTest(fixtures.MappedTest, testing.AssertsExecutionResults,):
    """ORM-level test for [ticket:3531]"""

    # mysql is having a recursion issue in the bind_expression
    __only_on__ = ('sqlite', 'postgresql')

    class StringAsInt(TypeDecorator):
        impl = String(50)

        def column_expression(self, col):
            return sa.cast(col, Integer)

        def bind_expression(self, col):
            return sa.cast(col, String)

    @classmethod
    def define_tables(cls, metadata):
        Table(
            'person', metadata,
            Column("id", cls.StringAsInt, primary_key=True),
        )
        Table(
            "pets", metadata,
            Column("id", Integer, primary_key=True),
            Column("person_id", Integer),
        )

    @classmethod
    def setup_classes(cls):
        class Person(cls.Basic):
            pass

        class Pet(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        mapper(cls.classes.Person, cls.tables.person, properties=dict(
            pets=relationship(
                cls.classes.Pet, primaryjoin=(
                    orm.foreign(cls.tables.pets.c.person_id) ==
                    sa.cast(
                        sa.type_coerce(cls.tables.person.c.id, Integer),
                        Integer
                    )
                )
            )
        ))

        mapper(cls.classes.Pet, cls.tables.pets)

    def test_lazyload_singlecast(self):
        Person = self.classes.Person
        Pet = self.classes.Pet

        s = Session()
        s.add_all([
            Person(id=5), Pet(id=1, person_id=5)
        ])
        s.commit()

        p1 = s.query(Person).first()

        with self.sql_execution_asserter() as asserter:
            p1.pets

        asserter.assert_(
            CompiledSQL(
                "SELECT pets.id AS pets_id, pets.person_id "
                "AS pets_person_id FROM pets "
                "WHERE pets.person_id = CAST(:param_1 AS INTEGER)",
                [{'param_1': 5}]
            )
        )

class CompositeSimpleM2OTest(fixtures.MappedTest):
    """ORM-level test for [ticket:3788]"""

    @classmethod
    def define_tables(cls, metadata):
        Table(
            'a', metadata,
            Column("id1", Integer, primary_key=True),
            Column("id2", Integer, primary_key=True),
        )

        Table(
            "b_sameorder", metadata,
            Column("id", Integer, primary_key=True),
            Column('a_id1', Integer),
            Column('a_id2', Integer),
            ForeignKeyConstraint(['a_id1', 'a_id2'], ['a.id1', 'a.id2'])
        )

        Table(
            "b_differentorder", metadata,
            Column("id", Integer, primary_key=True),
            Column('a_id1', Integer),
            Column('a_id2', Integer),
            ForeignKeyConstraint(['a_id1', 'a_id2'], ['a.id1', 'a.id2'])
        )

    @classmethod
    def setup_classes(cls):
        class A(cls.Basic):
            pass

        class B(cls.Basic):
            pass

    def test_use_get_sameorder(self):
        mapper(self.classes.A, self.tables.a)
        m_b = mapper(self.classes.B, self.tables.b_sameorder, properties={
            'a': relationship(self.classes.A)
        })

        configure_mappers()
        is_true(m_b.relationships.a.strategy.use_get)

    def test_use_get_reverseorder(self):
        mapper(self.classes.A, self.tables.a)
        m_b = mapper(self.classes.B, self.tables.b_differentorder, properties={
            'a': relationship(self.classes.A)
        })

        configure_mappers()
        is_true(m_b.relationships.a.strategy.use_get)

    def test_dont_use_get_pj_is_different(self):
        mapper(self.classes.A, self.tables.a)
        m_b = mapper(self.classes.B, self.tables.b_sameorder, properties={
            'a': relationship(self.classes.A, primaryjoin=and_(
                self.tables.a.c.id1 == self.tables.b_sameorder.c.a_id1,
                self.tables.a.c.id2 == 12
            ))
        })

        configure_mappers()
        is_false(m_b.relationships.a.strategy.use_get)


text:
/**
 * Options that can be used with ng add @ngx-i18nsupport.
 */
import {CommonOptions} from '../common';

export interface NgAddOptions extends CommonOptions {
    localePath?: string;
    i18nFormat?: string; // the used format
    i18nLocale?: string; // the default language
    languages?: string; // comma separared list of languages
    useCommandlineForLanguages?: boolean; // if set, all languages are given as command line argument to xliffmerge
                                        // if not, they are configured in xliffmerge.json (preferred variant)
    skipInstall?: boolean; // When true, does not install dependency packages.
    useXliffmergeBuilder?: boolean; // use builder if true
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

  <title>Test for Cross domain access to properties</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />


text:
## What's it ???

This repo contains source code for [my personal website][website]. All the stuff is processed and deployed on [this site][website]. So yeah, this site is now hosted on Firebase

## How to run the site locally ???

Before you get started make sure you have an up-to-date version of Go and Node. I use [Homebrew][brew] for all this thingies :

```bash
$ brew install node
$ brew install go
```

So then, clone this repo by running :

```bash
$ git clone https://github.com/nurlansu/su-site.git
```

If you haven't [Wellington][wt], you should install it on your computer by running :

```bash
$ go get -u github.com/wellington/wellington/wt
```

Also we need [Hugo][hugo], to generate `.html` files. You cand do it by running

```bash
$ go get -u github.com/spf13/hugo
```

or using `brew` :

```bash
$ brew install hugo
```

Now we can install all necessary `node` modules :

```bash
$ npm install
```

So now we should be able to generate all `.html` files and process all `.scss` files. We can do it by running :

```bash
$ hugo && npm run build
```

Normally, that's all. All necessary files for running this site locally are now in `public` folder

## How the sausage is made ???

Actually, I'm using [Travis CI][travis] for building and deploying all static files on [Firebase][firebase]. You can check out [.travis.yml](./.travis.yml) file for understand how all of this is working.

## What's gopher doying here ???

Well...

## Thanks 👏
The site use many tools and services to stay alive 🤘
- [GitHub][gh], all the data is generously hosted on :octocat:;
- [Git][git], 📦 blogs, codes, files version control system;
- [Markdown][md], a 🌺 beautiful and ❄ lightweight markup language;
- [Google][google], :squirrel: the one who tell me how to make it
- And many other cool stuff

## License

  MIT

[brew]: https://brew.sh
[firebase]: https://firebase.google.com
[gh]: https://github.com
[git]: https://git-scm.com
[google]: https://google.com
[md]: https://daringfireball.net/projects/markdown/
[travis]: https://travis-ci.org
[website]: https://nurlan.co
[wt]: https://github.com/wellington/wellington


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FetchPollsService } from '../../services/fetch-polls.service';
import { AuthService } from '../../services/auth.service';
import { FlashMessagesService } from 'angular2-flash-messages';

@Component({
  selector: 'app-display-user-poll',
  templateUrl: './display-user-poll.component.html',
  styleUrls: ['./display-user-poll.component.css']
})
export class DisplayUserPollComponent implements OnInit {
  // Setup a shitload of member variables.
  private obs;
  private id: string;
  private title: string;
  private opts: string[];
  private loggedInUser: string;
  private pollCreator: string;
  private userAuthenticated: boolean;
  private userCanDeletePoll: boolean;
  private url: string;
  private smShareUrl: string;
  private selectedValue: string;
  private doughnutChartData: number[] = [];
  private doughnutChartLables: string[] = [];
  private doughnutChartType = 'doughnut';
  private votesObj: Object;
  private dataAvailable: boolean;
  private ip: string;
  private ips: any;
  private hasVoted: boolean;

  constructor(private route: ActivatedRoute,
              private fetchPollService: FetchPollsService,
              private authService: AuthService,
              private router: Router,
              private fm: FlashMessagesService) { }

  // Do some setup work. Chart wont be drawn until this.dataAvailable is true.
  ngOnInit() {
    this.dataAvailable = false;
    this.obs = this.route.params;
    this.id = this.obs._value.id;

    // Try to get username, if it throws error, set user to null.
    try {
      this.loggedInUser = this.authService.getUsername();
    } catch (err) {
      this.loggedInUser = null;
    }

    // Get user IP address.
    this.authService.getIpAddress().subscribe(
      // Success
      (res) => this.ip = res.ip,
    );

    // Verify that current IP address hasn't already voted on this poll.
    this.authService.verifyIPHasntVoted(this.id).subscribe(
      // Success
      (res) => {
        this.ips = res['data']['poll']['ips'];
        this.hasVoted = this.ips.indexOf(this.ip) >= 0;
      }
    );

    // Get poll by id, get info from poll object. Initialize some data when
    // Observable completes.
    this.fetchPollService.fetchPollById(this.id).subscribe(
        // Success
        (res) => {
          this.title = res.data['poll']['title'].toUpperCase();
          this.opts = res.data['poll']['opts'];
          this.votesObj = res.data['poll']['votes'];

        },

        // Error
        (err) => {
          throw new Error(err);
        },

        // Complete
        () => {
          this.initalizeChart();

          // Get the current URL.
          this.url = `http://localhost:4200${this.router.url}`;

          // Set the twitter intent content.
          this.smShareUrl =
          `http://twitter.com/intent/tweet?text=Check%20Out%20My%20Poll:%20${this.title}&url=${this.url}`;
          this.dataAvailable = true;
          console.log('opts: ', this.opts);
          console.log('votes: ', this.votesObj);
        }
    );

    // Verify user is logged in.
    this.userAuthenticated = this.authService.loggedIn();

    // Verify that current user has access to be able to delete current poll.
    this.authService.verifyCanDeletePoll(this.id, this.loggedInUser)
      .subscribe(
        (success) => {
          this.pollCreator = success['data']['username'];
        },
        (err) => {
          throw new Error(err);
        },
        () => {
          this.userCanDeletePoll = this.pollCreator === this.loggedInUser;
        }
      );
  }

  /**
   *
   *
   * @private
   * Delete current poll.
   * @memberOf DisplayUserPollComponent
   */
  private deletePoll(): void {
    // Activate deletion of current poll by subscribing to method in service.
    this.fetchPollService.deletePollById(this.id).subscribe(
      (res) => {
        if (res.success) {
          this.fm.show('Deleted poll: ' + this.title, {
            cssClass: 'warning-success',
            timeout: 2000,
          });
        } else {
          this.fm.show('Unable to delete poll: ' + this.title, {
            cssClass: 'warning-error',
            timeout: 2000,
          });
        }
      },
      (err) => {
        console.log(err);
      }
    );

    // Navigate to dashboard after deleting poll.
    this.router.navigate(['/dashboard']);
  }

  /**
   *
   *
   * @private
   * @returns {void}
   * Handle the submission of a new vote.
   * @memberOf DisplayUserPollComponent
   */
  private handleVote(): void {
    const id = this.id;

    // Set the value to change in.
    const valueToChange = this.opts.indexOf(this.selectedValue);

    // If current IP isn't found in the ips array, run the code.
    if (this.ips.indexOf(this.ip) < 0) {

      // Return a new array of chartData values, modifying the one that was voted on.
      this.doughnutChartData = this.doughnutChartData
        .map((item, index) => {
          console.log('item: ', item);
          console.log('index: ', index);
          console.log('selectedValue: ', this.selectedValue);
          if (index === this.opts.indexOf(this.selectedValue)) {
            const newValue = this.doughnutChartData[valueToChange] + 1;
            console.log('newValue: ', newValue);
            this.fetchPollService.updateVotesForPollById(
              id, this.selectedValue, newValue, this.ip).subscribe();

            // Update this.ips, update this.hasVoted.
            this.authService.verifyIPHasntVoted(this.id).subscribe(
              // Success
              (res) => this.ips = res.data.poll.ips,

              // Error.
              (err) => console.log('Error: ', new Error(err)),

              // Completed.
              () => {
                this.ips.push(this.ip);
                this.hasVoted = this.ips.indexOf(this.ip) >= 0;
              }
            );
            return item + 1;
          }
          return item;
        });

    // Current IP has already voted, display message and exit.
    } else {
        this.hasVoted = this.ips.indexOf(this.ip) >= 0;
        return;
    }
  }

  // Initalize the labels array equal to the opts array.
  /**
   *
   *
   * @private
   * Initalize chart.js chart labels to use for current poll.
   * @memberOf DisplayUserPollComponent
   */
  private initalizeChart(): void {
    this.opts.forEach((item, index) => {
      this.doughnutChartLables.push(item);
  });

    this.opts.forEach(option => {
      this.doughnutChartData.push(this.votesObj[option]);
    });
  }

  /**
   *
   *
   * @private
   * @returns {void}
   * If selected dropdown is create new option, navigate to new-poll-option
   * component.
   * @memberOf DisplayUserPollComponent
   */
  private newOptionSelected(): void {
    if (this.selectedValue === 'create') {
      this.router.navigate(['/add_option', this.id]);
    }
  }
}


text:
  Les Hôpitaux-Vieux est
       un village
       géographiquement positionné dans le département des Doubs en Franche-Comté. Elle totalisait 332 habitants en 2008.

Si vous envisagez de venir habiter à Les Hôpitaux-Vieux, vous pourrez facilement trouver une maison à acheter.

À proximité de Les Hôpitaux-Vieux sont situées les villes de
Jougne à 3 km, 1 338 habitants,
Fourcatier-et-Maison-Neuve localisée à 4 km, 76 habitants,
Malbuisson à 5 km, 498 habitants,
Longevilles-Mont-d'Or localisée à 5 km, 400 habitants,
Montperreux localisée à 4 km, 747 habitants,
Saint-Antoine localisée à 2 km, 278 habitants,
 entre autres. De plus, Les Hôpitaux-Vieux est située à seulement douze km de Pontarlier.

La ville compte quelques  équipements, elle dispose, entre autres, de deux domaines skiables.

Le parc d'habitations, à Les Hôpitaux-Vieux, se décomposait en 2011 en 78 appartements et 124 maisons soit
 un marché plutôt équilibré.


text:
"Cutout" templating system concept.

This project represents the first take on yet another logicless templating system named "Cutout".
Main idea behind Cutout system, is to enable a programmer to program template logic in his favorite programming language.

Firstly, we takes template prototype, say, simple .html file.

```html
<!DOCTYPE html>
<html>
	<head>

		<meta charset="UTF-8"/>

		<title></title>

	</head>

	<body>

		<header>

			<h1></h1>
			<nav>
				<ul>
					<li>
						<a href=""></a>
					</li>
				</ul>
			</nav>

			<span class="warning">session timeout</span>
			<span class="warning">we don't support your client, sorry</span>
			<span class="error">oops...</span>
		</header>

		<main>

		</main>

		<footer>

			<small></small>
		</footer>
	</body>
</html>
```

Next, we "cut" it to parts and "mark" injection points.

```html
<!DOCTYPE html>
<html>
	<head>
	{?head}

		<meta charset="UTF-8"/>

		<title>{title}</title>

	{/head}

	</head>

	<body>
	{?body}

		<header>

			<h1>{heading}</h1>
			<nav>
			{?navigation}
				<ul>
					{?links}
					<li>
						<a href="{href}">{text}</a>
					</li>
					{/links}
				</ul>
			{/navigation}
			</nav>

			{?status}
				{?timeout}<span class="warning">session timeout</span>{/timeout}
				{?client_unsupported}<span class="warning">we don't support your client, sorry</span>{/client_unsupported}
				{?error}<span class="error">oops...</span>{/error}
			{/status}
		</header>

		<main>
			{?content}{/content}
		</main>

		<footer>
		{?footer}

			<small>{copyright}</small>
		{/footer}
		</footer>
	{/body}
	</body>
</html>
```

"Cut" syntax contains open and close tags, like {?head} and {/head} in example above. The "head" string in these tags defines a name of the "cut". Everything between "cut" tags is treated as nested template.

"Mark" syntax contains one tag, like {title} in example above. The "title" string in this tag defines a name of the "mark".
Additionally, "mark" name may be followed by equal sign (=) and default string value.

After that we generate code for target programming language.

In general we get a template function for each template. We must provide arguments for each unique mark name and cut name to to get rendering function. Then we may use renderig function to render resulting text.

Actual implementation for concrete programming language or platform may has additional features and/or constraints.


text:
var rushEditor = {
    addword : function(){
        var wordList = document.getElementById("word-list");
        var wordTag = document.createElement("li");
        wordTag.className = "list-group-item";
        var input = document.createElement("input");
        input.type = "text";
        input.value = "";
        wordTag.appendChild(input);
        wordList.appendChild(wordTag);
    },

    generategrid: function(wordlist){
        $('#addword-modal').modal('toggle');
        wait.start("Génération de la grille");
        var wordlist = [];

        var ul = document.getElementById("word-list");
        var items = ul.getElementsByTagName("input");
        for (var i = 0; i < items.length; ++i) {
            var word = items[i].value;
            if (word.length != 0) {
                wordlist.push(word);
            }
        }

        var time = 1000;
        var generator = Generator();
        var best = new generator(4, wordlist, time).run();

        var x = 0;
        for (var i = best.grid.length - 1; i >= 0; i--) {
            for (var j = best.grid[i].length - 1; j >= 0; j--) {
                $("#square-"+x).val(best.grid[i][j]);
                x++;
            };
        };

        wait.stop();
    },

    savegrid: function(){
        if(editor.isFormValid("grid")){
            wait.start("Sauvegarde de la grille");
            var data = $("#grid").serializeArray();
            var url = Routing.generate('rush_save_grid', {id: $('#rushId').val()});
            $.ajax({
                  type: 'POST',
                  url: url,
                  data: data,
             })
             .done(function(data) {
                 wait.stop();
                 $("#foundables").html(data.foundables);
             });
         }
    },
};


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office;
import com.wilutions.com.*;

/**
 * Signature.
 *
 */
@CoInterface(guid="{000C0411-0000-0000-C000-000000000046}")
public interface Signature extends IDispatch {
  static boolean __typelib__loaded = __TypeLib.load();
  @DeclDISPID(1610743808)  public IDispatch getApplication() throws ComException;
  @DeclDISPID(1610743809)  public Integer getCreator() throws ComException;
  @DeclDISPID(1610809350)  public void Delete() throws ComException;
  @DeclDISPID(1610809351)  public IDispatch getParent() throws ComException;
  @DeclDISPID(1610809355)  public Boolean getIsSigned() throws ComException;
  @DeclDISPID(1610809356)  public void Sign(final Object varSigImg, final Object varDelSuggSigner, final Object varDelSuggSignerLine2, final Object varDelSuggSignerEmail) throws ComException;
  @DeclDISPID(1610809357)  public SignatureInfo getDetails() throws ComException;
  @DeclDISPID(1610809358)  public void ShowDetails() throws ComException;
  @DeclDISPID(1610809359)  public Boolean getCanSetup() throws ComException;
  @DeclDISPID(1610809360)  public SignatureSetup getSetup() throws ComException;
  @DeclDISPID(1610809361)  public Boolean getIsSignatureLine() throws ComException;
  @DeclDISPID(1610809362)  public IDispatch getSignatureLineShape() throws ComException;
  @DeclDISPID(1610809363)  public Integer getSortHint() throws ComException;
}


text:
namespace blink {

class CORE_EXPORT NGTextFragment final : public NGFragmentBase {
 public:
  NGTextFragment(NGWritingMode writing_mode,
                 NGDirection direction,
                 NGPhysicalTextFragment* physical_text_fragment)
      : NGFragmentBase(writing_mode, direction, physical_text_fragment) {}

  String Text() const {
    return toNGPhysicalTextFragment(physical_fragment_)->Text();
  }
};

}  // namespace blink

#endif  // NGTextFragment_h


text:
"""
Test for softmax_regression.ipynb
"""

import os

from pylearn2.testing.skip import skip_if_no_data
from pylearn2.config import yaml_parse

def test():
    skip_if_no_data()

    dirname = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')

    with open(os.path.join(dirname, 'sr_dataset.yaml'), 'r') as f:
        dataset = f.read()

    hyper_params = {'train_stop': 50}
    dataset = dataset % (hyper_params)

    with open(os.path.join(dirname, 'sr_model.yaml'), 'r') as f:
        model = f.read()

    with open(os.path.join(dirname, 'sr_algorithm.yaml'), 'r') as f:
        algorithm = f.read()

    hyper_params = {'batch_size': 10,
                    'valid_stop': 50050}
    algorithm = algorithm % (hyper_params)

    with open(os.path.join(dirname, 'sr_train.yaml'), 'r') as f:
        train = f.read()

    save_path = os.path.dirname(os.path.realpath(__file__))
    train = train % locals()

    train = yaml_parse.load(train)
    train.main_loop()

    try:
        os.remove("{}/softmax_regression.pkl".format(save_path))
        os.remove("{}/softmax_regression_best.pkl".format(save_path))
    except:
        pass

if __name__ == '__main__':
    test()


text:
#ifndef H_BLE_LL_SCHED_
#define H_BLE_LL_SCHED_

#include "os/os_list.h"

/* Time per BLE scheduler slot */
#define BLE_LL_SCHED_USECS_PER_SLOT (1250)

/*
 * This is the number of slots needed to transmit and receive a maximum
 * size PDU, including an IFS time before each. The actual time is
 * 2120 usecs for tx/rx and 150 for IFS = 4540 usecs.
 */
#define BLE_LL_SCHED_MAX_TXRX_SLOT  (4 * BLE_LL_SCHED_USECS_PER_SLOT)

/* BLE scheduler errors */
#define BLE_LL_SCHED_ERR_OVERLAP    (1)

/* Types of scheduler events */
#define BLE_LL_SCHED_TYPE_ADV       (1)
#define BLE_LL_SCHED_TYPE_SCAN      (2)
#define BLE_LL_SCHED_TYPE_CONN      (3)

/* Return values for schedule callback. */
#define BLE_LL_SCHED_STATE_ERROR    (-1)
#define BLE_LL_SCHED_STATE_RUNNING  (0)
#define BLE_LL_SCHED_STATE_DONE     (1)

/* Callback function */
struct ble_ll_sched_item;
typedef int (*sched_cb_func)(struct ble_ll_sched_item *sch);

struct ble_ll_sched_item
{
    uint8_t         sched_type;
    uint8_t         enqueued;
    uint32_t        start_time;
    uint32_t        end_time;
    void            *cb_arg;
    sched_cb_func   sched_cb;
    struct list_head link;
};

/* Initialize the scheduler */
int ble_ll_sched_init(void);

/* Remove item(s) from schedule */
void ble_ll_sched_rmv_elem(struct ble_ll_sched_item *sch);

/* Get a schedule item */
struct ble_ll_sched_item *ble_ll_sched_get_item(void);

/* Free a schedule item */
void ble_ll_sched_free_item(struct ble_ll_sched_item *sch);

/* Schedule a new master connection */
struct ble_ll_conn_sm;
int ble_ll_sched_master_new(struct ble_ll_conn_sm *connsm, uint32_t adv_rxend,
                            uint8_t req_slots);

/* Schedule a new slave connection */
int ble_ll_sched_slave_new(struct ble_ll_conn_sm *connsm);

/* Schedule a new advertising event */
int ble_ll_sched_adv_new(struct ble_ll_sched_item *sch);

/* Reschedule an advertising event */
int ble_ll_sched_adv_reschedule(struct ble_ll_sched_item *sch);

/* Reschedule a connection that had previously been scheduled or that is over */
int ble_ll_sched_conn_reschedule(struct ble_ll_conn_sm * connsm);

/**
 * Called to determine when the next scheduled event will occur.
 *
 * If there are not scheduled events this function returns 0; otherwise it
 * returns 1 and *next_event_time is set to the start time of the next event.
 *
 * @param next_event_time cputime at which next scheduled event will occur
 *
 * @return int 0: No events are scheduled 1: there is an upcoming event
 */
int ble_ll_sched_next_time(uint32_t *next_event_time);

/* Stop the scheduler */
void ble_ll_sched_stop(void);

#endif /* H_LL_SCHED_ */


text:
from __future__ import unicode_literals

from six.moves.urllib.parse import urlencode

from django.conf import settings
from django.core import urlresolvers

def reverse(viewname, site_id=None, add_domain=False, urlconf=None, args=None, kwargs=None, current_app=None,
            qs_kwargs=None):
    from .domain import get_domain

    urlconf = (get_domain(site_id).urlconf
               if site_id is not None and urlconf is None and settings.SITE_ID != site_id
               else urlconf)
    site_id = settings.SITE_ID if site_id is None else site_id
    domain = get_domain(site_id).url if add_domain else ''
    qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else ''
    return ''.join((domain, urlresolvers.reverse(viewname, urlconf, args, kwargs, current_app), qs))


text:
var U = {};
var R = {};
var C = {};

var Officer = {

};

var Criminal = {

};

//some helper functions from racer
var Game = {

    paused : false,
    trains : [],
    activeTrains : [],
    allTrains : [],
    ticks : 0.0, //in seconds start at 00:00:00
    step : 1/60, //60 fps
    timeMultiplier : 10, //10x real time

    init : function( trains ) {

        for ( t in trains ) {

            var train = trains[t];
            trains[t].nextStop = 1;
            trains[t].lastStop = 0;
            trains[t].lat = trains[t].s[trains[t].lastStop].lat;
            trains[t].lng = trains[t].s[trains[t].lastStop].lng;

            if ( trains[t].s[trains[t].nextStop].t >= Game.ticks &&
                 trains[t].s[trains[t].lastStop].t <= Game.ticks) {
                trains[t].uuid = t;
                Game.activeTrains.push(trains[t]);
            }

            Game.allTrains.push( trains[t] );
        }
    },

    run : function( Util, Render, Constants, options ) {

        U = Util;
        R = Render;
        C = Constants;

        var map    = options.map,
            update = options.update,
            render = options.render,
            step   = options.step,
            now    = null,
            last   = U.timestamp(),
            dt     = 0,
            gdt    = 0;

        var frame = function() {
                        now = U.timestamp();
                        dt = Math.min( 1, ( now - last ) / 1000 );
                        gdt += dt;
                        while ( gdt > step ) {
                            gdt -= step;
                            update( step );
                        }

                        last = now;

                        //render();

                        requestAnimationFrame( frame, map );
                    }

        frame();
    },

    update: function( dt ) {

        if ( !Game.paused ) {

            //update time
            Game.ticks += dt * Game.timeMultiplier;
            Game.ticks = Game.ticks % C.SECONDS_IN_DAY; //rollover

            //update subway locations
            for ( t in Game.activeTrains ) {
                Game.updateTrain( t );
            }

            //update criminal location

            //update criminal logic

            //update player location
        }
    },

    togglePause: function() {
        Game.paused = !Game.paused;
    },

    updateTrain: function( t ) {

        if ( Game.ticks >= Game.activeTrains[t].s[Game.activeTrains[t].nextStop].t  && Game.activeTrains[t].s.length > Game.activeTrains[t].nextStop ) {
            Game.activeTrains[t].nextStop++;
            Game.activeTrains[t].lastStop++;
        }

        //remove unused trains
        if ( Game.activeTrains[t].s[ Game.activeTrains[t].nextStop ].t < Game.ticks ) {
            Game.recycleTrain( Game.activeTrains[t].uuid );
            Game.activeTrains.splice( t, 1 ); //remove me from list of active trains
            return;
        }

        //interpolate train positions

        var p = U.percentRemaining(Game.ticks - Game.activeTrains[t].s[Game.activeTrains[t].lastStop].t,
                                   Game.activeTrains[t].s[Game.activeTrains[t].nextStop].t - Game.activeTrains[t].s[Game.activeTrains[t].lastStop].t);

        //hopefully this is not buggy...
        Game.activeTrains[t].lat = Math.round( U.interpolate( Game.activeTrains[t].s[Game.activeTrains[t].lastStop].lat,
                                                              Game.activeTrains[t].s[Game.activeTrains[t].nextStop].lat,
                                                              p ) );
        Game.activeTrains[t].lng = Math.round( U.interpolate( Game.activeTrains[t].s[Game.activeTrains[t].lastStop].lng,
                                                              Game.activeTrains[t].s[Game.activeTrains[t].nextStop].lng,
                                                              p ) );

        //debug
        if ( t == 0 ) {
            //console.log( p + " to stop " + Game.activeTrains[t].nextStop );
            console.log( Game.activeTrains[t].lat + "," + Game.activeTrains[t].lng);
        }
    },

    //use the train later
    recycleTrain : function( t ) {
        for ( st in Game.allTrains[t].s ) {
            Game.allTrains[t].s[st].t += Constants.RECYCLE_INTERVAL;
        }
    },

    setKeyListener: function( keys ) {
        var onkey = function( keyCode, mode ) {
            var n, k;

            for( n = 0 ; n < keys.length ; n++ ) {
                k = keys[n];
                k.mode = k.mode || 'up';
                if ( ( k.key == keyCode ) || ( k.keys && ( k.keys.indexOf( keyCode ) >= 0 ) ) ) {
                    if ( k.mode == mode ) {
                        k.action.call();
                    }
                }
            }
        };

        Dom.on( document, 'keydown', function( ev ) { onkey( ev.keyCode, 'down' ); } );
        Dom.on( document, 'keyup',   function( ev ) { onkey( ev.keyCode, 'up' );   } );
    }
}


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

 Bio::EnsEMBL::Compara::PipeConfig::EPO_pt3_conf

=head1 DESCRIPTION

    The PipeConfig file for the last part (3rd part) of the EPO pipeline.
    This will genereate the multiple sequence alignments (MSA) from a database containing a
    set of anchor sequences mapped to a set of target genomes. The pipeline runs Enredo
    (which generates a graph of the syntenic regions of the target genomes)
    and then runs Ortheus (which runs Pecan for generating the MSA) and infers
    ancestral genome sequences. Finally Gerp may be run to generate constrained elements and
    conservation scores from the MSA

=head1 SYNOPSIS

    #1. update ensembl-hive, ensembl and ensembl-compara GIT repositories before each new release

    #2. you may need to update 'schema_version' in meta table to the current release number in ensembl-hive/sql/tables.sql

    #3. make sure that all default_options are set correctly

    #4. Run init_pipeline.pl script:
        init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::ProteinTrees_conf -password <your_password> -mlss_id <your_current_PT_mlss_id>

    #5. Sync and loop the beekeeper.pl as shown in init_pipeline.pl's output

=head1 AUTHORSHIP

Ensembl Team. Individual contributions can be found in the GIT log.

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with an underscore (_)

=cut

package Bio::EnsEMBL::Compara::PipeConfig::EPO_pt3_conf;

use strict;
use warnings;
use base ('Bio::EnsEMBL::Compara::PipeConfig::ComparaGeneric_conf');

sub default_options {
 my ($self) = @_;

 return {
  %{$self->SUPER::default_options},

  'pipeline_name' => '4reptiles_EPOpt3pt2',
  'core_db_version' => 74,
  'rel_with_suffix' => 74,
  'mapping_mlssid' => 11000, # method_link_species_set_id of the final (2bp) mapped anchors
  'epo_mlss_id' => 647, # method_link_species_set_id of the ortheus alignments which will be generated
#  'gerp_ce_mlss_id' => 648,
#  'gerp_cs_mlss_id' => 50295,
  'bl2seq' => '/software/ensembl/compara/bl2seq', # location of ncbi bl2seq executable on farm3
  'bl2seq_dump_dir' => $self->o('dump_dir')."BL2SEQ".$self->o('db_suffix').$self->o('rel_with_suffix'), # location for dumping sequences to determine strand (for bl2seq)
  'bl2seq_file_stem' => $self->o('bl2seq_dump_dir')."/bl2seq",
  'enredo_bin_dir' => '/software/ensembl/compara/', # location of enredo executable
  'enredo_params' => ' --min-score 0 --max-gap-length 200000 --max-path-dissimilarity 4 --min-length 10000 '.
	'--min-regions 2 --min-anchors 3 --max-ratio 3 --simplify-graph 7 --bridges -o ',
  'enredo_output_file_name' => 'enredo_'.$self->o('epo_mlss_id').'.out',
  'enredo_output_file' => $self->o('dump_dir').$self->o('enredo_output_file_name'),
  'db_suffix' => '_epo_4sauropsids_',
  'ancestral_sequences_name' => 'ancestral_sequences',
  'dump_dir' => $self->o('ENV', 'EPO_DUMP_PATH').'epo_'.$self->o('rel_with_suffix')."/dumps".$self->o('db_suffix').$self->o('rel_with_suffix')."/",
  'bed_dir' => $self->o('dump_dir').'bed_dir',
  'feature_dumps' => $self->o('dump_dir').'feature_dumps',
  'enredo_mapping_file_name' => 'enredo_friendly.mlssid_'.$self->o('epo_mlss_id')."_".$self->o('rel_with_suffix'),
  'enredo_mapping_file' => $self->o('dump_dir').$self->o('enredo_mapping_file_name'),
  'cvs_dir' => $self->o('ENV', 'ENSEMBL_CVS_ROOT_DIR'),
  'ancestral_db_cmd' => "mysql -u".$self->o('ancestral_db', '-user')." -P".$self->o('ancestral_db', '-port').
	" -h".$self->o('ancestral_db', '-host')." -p".$self->o('ancestral_db', '-pass'),
  'species_tree_file' => $self->o('cvs_dir').'/ensembl-compara/scripts/pipeline/species_tree_blength.nh',
  # add MT dnafrags separately (1) or not (0) to the dnafrag_region table
  'addMT' => 1,
  'jar_file' => '/software/ensembl/compara/pecan/pecan_v0.8.jar',
  'gerp_version' => '2.1', #gerp program version
  'gerp_window_sizes'    => '[1,10,100,500]', #gerp window sizes
  'gerp_exe_dir'    => '/software/ensembl/compara/gerp/GERPv2.1', #gerp program
  # Use 'quick' method for finding max alignment length (ie max(genomic_align_block.length)) rather than the more
  # accurate (and slow) method of max(genomic_align.dnafrag_end-genomic_align.dnafrag_start+1)
  'quick' => 1,
  'skip_multiplealigner_stats' => 0, #skip this module if set to 1
  'dump_features_exe' => $self->o('ensembl_cvs_root_dir')."/ensembl-compara/scripts/dumps/dump_features.pl",
  'compare_beds_exe' => $self->o('ensembl_cvs_root_dir')."/ensembl-compara/scripts/pipeline/compare_beds.pl",

  # connection parameters to various databases:
	'pipeline_db' => { # the production database itself (will be created)
		-driver => 'mysql',
		-host   => 'compara4',
		-port   => 3306,
                -user   => 'ensadmin',
		-pass   => $self->o('password'),
		-dbname => $self->o('ENV', 'USER').$self->o('db_suffix').$self->o('rel_with_suffix'),
   	},
	'ancestral_db' => { # core ancestral db
		-driver => 'mysql',
		-host   => 'compara4',
		-port   => 3306,
		-species => "ancestral_sequences",
		-user   => 'ensadmin',
		-pass   => $self->o('password'),
		-dbname => $self->o('ENV', 'USER').$self->o('db_suffix').'ancestral_core_'.$self->o('rel_with_suffix'),
	},
	# master db
	'compara_master' => {
		-driver => 'mysql',
		-user => 'ensro',
		-port => 3306,
		-pass => '',
		-host => 'compara1',
		-dbname => 'sf5_ensembl_compara_master',
	#	-dbname => 'sf5_test_74_mammal_master',
#		-dbname => 'kb3_ensembl_compara_71',
	},
	# location of most of the core dbs
	'main_core_dbs' => [
		{
			-driver => 'mysql',
			-user => 'ensro',
			-port => 3306,
			-host => 'ens-staging1',
			-dbname => '',
			-db_version => $self->o('core_db_version'),
		},
		{
			-driver => 'mysql',
			-user => 'ensro',
			-port => 3306,
			-host => 'ens-staging2',
			-dbname => '',
			-db_version => $self->o('core_db_version'),
		},

	],
	# any additional core dbs
	'additional_core_db_urls' => {
#		'ovis_aries' => 'mysql://ensro@compara1:3306/ovis_aries_core_73_1',
	},
	# anchor mappings
	'compara_mapped_anchor_db' => {
		-driver => 'mysql',
		-user => 'ensro',
		-port => 3306,
		-pass => '',
		-host => 'compara2',
	#	-dbname => 'sf5_bird_lizard_epo_anchor_mappings74',
		-dbname => 'sf5_bird_lizard_epo_anchor_mappings74',
#		-dbname => 'sf5_13_mammal_anchor_mappings69',
	},

     };
}

sub pipeline_create_commands {
    my ($self) = @_;
    return [
        @{$self->SUPER::pipeline_create_commands},
	'mkdir -p '.$self->o('dump_dir'),
	'mkdir -p '.$self->o('bl2seq_dump_dir'),
        'mkdir -p '.$self->o('bed_dir'),
        'mkdir -p '.$self->o('feature_dumps'),
           ];
}

sub resource_classes {
    my ($self) = @_;
    return {
	%{$self->SUPER::resource_classes},  # inherit 'default' from the parent class
	'default' => {'LSF' => '-C0 -M2500 -R"select[mem>2500] rusage[mem=2500]"' }, # reset the default   farm3 lsf syntax
	'mem3500' => {'LSF' => '-C0 -M3500 -R"select[mem>3500] rusage[mem=3500]"' }, # farm3 lsf syntax
	'mem7500' => {'LSF' => '-C0 -M7500 -R"select[mem>7500] rusage[mem=7500]"' }, # farm3 lsf syntax
	'hugemem' => {'LSF' => '-q hugemem -C0 -M30000 -R"select[mem>30000] rusage[mem=30000]"' }, # farm3 lsf syntax
    };
}

sub pipeline_wide_parameters {
	my $self = shift @_;
	return {
		%{$self->SUPER::pipeline_wide_parameters},
		'enredo_mapping_file' => $self->o('enredo_mapping_file'),
		'compara_master' => $self->o('compara_master'),
		'main_core_dbs' => $self->o('main_core_dbs'),
		'compara_mapped_anchor_db' => $self->o('compara_mapped_anchor_db'),
 		'mapping_mlssid' => $self->o('mapping_mlssid'),
		'ancestral_db' => $self->o('ancestral_db'),
		'additional_core_db_urls' => $self->o('additional_core_db_urls'),
		'epo_mlss_id' => $self->o('epo_mlss_id'),
#		'gerp_ce_mlss_id' => $self->o('gerp_ce_mlss_id'),
#		'gerp_cs_mlss_id' => $self->o('gerp_cs_mlss_id'),
		'enredo_output_file' => $self->o('enredo_output_file'),
	};
}

sub pipeline_analyses {
	my ($self) = @_;
	print "pipeline_analyses\n";

return
[
# ------------------------------------- create the ancestral db
{
 -logic_name => 'create_ancestral_db',
 -input_ids  => [{}],
 -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
 -parameters => {
  'cmd' => $self->o('ancestral_db_cmd')." -e\"CREATE DATABASE ".$self->o('ancestral_db', '-dbname')."\";".
  $self->o('ancestral_db_cmd')." -D".$self->o('ancestral_db', '-dbname')." <".$self->o('cvs_dir')."/ensembl/sql/table.sql",
  },
  -flow_into => { 1 => 'dump_mappings_to_file' },
},
# ------------------------------------- dump mapping info from mapping db to file
{
 -logic_name => 'dump_mappings_to_file',
 -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
 -parameters => {
  'db_conn' => $self->dbconn_2_mysql('compara_mapped_anchor_db', 1),
  'enredo_mapping_file' => $self->o('enredo_mapping_file'),
  'cmd' => "mysql #db_conn# -NB -e \'SELECT aa.anchor_id, gdb.name, df.name, aa.dnafrag_start, aa.dnafrag_end, CASE ".
  "aa.dnafrag_strand WHEN 1 THEN \"+\" ELSE \"-\" END, aa.num_of_organisms, aa.score FROM anchor_align aa INNER JOIN ".
  "dnafrag df ON aa.dnafrag_id = df.dnafrag_id INNER JOIN genome_db gdb ON gdb.genome_db_id = df.genome_db_id WHERE ".
  "aa.method_link_species_set_id = \'" . $self->o('mapping_mlssid') .
  "\' ORDER BY gdb.name, df.name, aa.dnafrag_start\' >"."#enredo_mapping_file#",
  },
   -flow_into => {
	'1->A' => [ 'copy_table_factory', 'run_enredo' ],
#       'A->1' => [ 'dump_before_ldr' ],
        'A->1' => [ 'load_dnafrag_region' ],
	},
},
# ------ set up the necessary databas tables for loading the enredo output and runnig ortheus and gerp
{
 -logic_name => 'copy_table_factory',
 -module     => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory',
 -parameters => {
  'db_conn' => $self->o('compara_master'),
  'inputlist'    => [ 'genome_db', 'dnafrag', 'method_link', 'method_link_species_set', 'species_set', 'ncbi_taxa_name', 'ncbi_taxa_node' ],
  'column_names' => [ 'table' ],
 },
 -flow_into => {
  '2->A' => [ 'copy_tables' ],
  'A->1' => [ 'delete_from_copied_tables' ],
 },
 -meadow_type    => 'LOCAL',
},
{
  -logic_name    => 'copy_tables',
  -module        => 'Bio::EnsEMBL::Hive::RunnableDB::MySQLTransfer',
  -parameters    => {
	'src_db_conn'   => $self->o('compara_master'),
	'dest_db_conn'  => $self->o('pipeline_db'),
	'mode'          => 'overwrite',
	'filter_cmd'    => 'sed "s/ENGINE=MyISAM/ENGINE=InnoDB/"',
  },
},
{
  -logic_name => 'delete_from_copied_tables',
  -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SqlCmd',
  -parameters => {
   'sql' => [
#    'DELETE FROM method_link_species_set WHERE method_link_species_set_id NOT IN ('.$self->o('epo_mlss_id').','.$self->o('gerp_ce_mlss_id').','.$self->o('gerp_cs_mlss_id').')',
    'DELETE FROM method_link_species_set WHERE method_link_species_set_id NOT IN ('.$self->o('epo_mlss_id').')',
    'DELETE ss.* FROM species_set ss LEFT OUTER JOIN method_link_species_set mlss ON ss.species_set_id = mlss.species_set_id WHERE mlss.species_set_id IS NULL',
    'DELETE df.*, gdb.* FROM dnafrag df INNER JOIN genome_db gdb ON gdb.genome_db_id = df.genome_db_id LEFT OUTER JOIN species_set ss ON gdb.genome_db_id = ss.genome_db_id WHERE ss.genome_db_id IS NULL AND gdb.name <> "'.$self->o('ancestral_sequences_name').'"',
   'DELETE FROM genome_db WHERE ! assembly_default',
   'DELETE df.* FROM dnafrag df INNER JOIN genome_db gdb ON gdb.genome_db_id = df.genome_db_id WHERE gdb.name = "'.$self->o('ancestral_sequences_name').'"',
   ],
  },
 -flow_into => { 1 => [ 'set_genome_db_locator_factory', 'set_internal_ids' ], },
},
{
	-logic_name => 'set_genome_db_locator_factory',
	-module     => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory',
	-parameters => {
		'inputquery' => 'SELECT name AS species_loc_name FROM genome_db WHERE assembly_default',
	},
	-flow_into => { 2 => 'update_genome_db_locator', 1 => 'make_species_tree', },
},
{
	-logic_name => 'update_genome_db_locator',
	-module     => 'Bio::EnsEMBL::Compara::Production::EPOanchors::UpdateGenomeDBLocator',
	-meadow_type    => 'LOCAL',

},
{
	-logic_name => 'set_internal_ids',
	-module => 'Bio::EnsEMBL::Hive::RunnableDB::SqlCmd',
	-parameters => {
	'epo_mlssid' => $self->o('epo_mlss_id'),
		'sql'   => [
		  'ALTER TABLE genomic_align_block AUTO_INCREMENT=#expr(($epo_mlss_id * 10**10) + 1)expr#',
		  'ALTER TABLE genomic_align AUTO_INCREMENT=#expr(($epo_mlss_id * 10**10) + 1)expr#',
		  'ALTER TABLE genomic_align_tree AUTO_INCREMENT=#expr(($epo_mlss_id * 10**10) + 1)expr#',
		  'ALTER TABLE dnafrag AUTO_INCREMENT=#expr(($epo_mlss_id * 10**10) + 1)expr#',
		],
        },
},
{
	-logic_name    => 'make_species_tree',
	-module        => 'Bio::EnsEMBL::Compara::RunnableDB::MakeSpeciesTree',
	-parameters    => {
			'mlss_id' => $self->o('epo_mlss_id'),
			'newick_format' => 'simple',
			'blength_tree_file' => $self->o('species_tree_file'),
	},
#	-flow_into => {
#		4 => { 'mysql:////' => { 'method_link_species_set_id' => '#mlss_id#', 'tag' => 'species_tree', 'value' => '#species_tree_string#' } },
#	},
},
# ------------------------------------- run enredo
{
	-logic_name => 'run_enredo',
	-module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
	-parameters => {
		'cmd' => $self->o('enredo_bin_dir').'enredo '.$self->o('enredo_params')." ".$self->o('enredo_output_file')." ".$self->o('enredo_mapping_file'),
	},
},

#{   -logic_name => 'dump_before_ldr',
#    -module     => 'Bio::EnsEMBL::Hive::RunnableDB::DatabaseDumper',
#    -parameters => {
#        'output_file'   => '/lustre/scratch109/ensembl/sf5/EPO_DUMPS/epo_rel80/sf5_epo_multi_way_leo_taxa_test_80.mysql',
#    },
#    -flow_into  => {
#	1 => [ 'load_dnafrag_region' ],
#    },
#},

# ------------------------------------- load the synteny blocks from the enredo output into the dnafrag_region and synteny_region tables
{
	-logic_name => 'load_dnafrag_region',
	-module    => 'Bio::EnsEMBL::Compara::Production::EPOanchors::LoadDnaFragRegion',
	-parameters => {
		'addMT'	=> $self->o('addMT'),
	},
        -flow_into => {
                '2->A' => [ 'find_dnafrag_region_strand' ],
                '3->A' => [ 'ortheus' ],
		'A->1' => [ 'update_max_alignment_length' ],
	},
},
# find the most likely strand orientation for genomic regions which enredo was unable to determine the
# orientation (when the strand is set to '0' in the enredo output file)
{
	-logic_name => 'find_dnafrag_region_strand',
	-module    => 'Bio::EnsEMBL::Compara::Production::EPOanchors::FindDfrStrand',
	-parameters => {
		bl2seq => $self->o('bl2seq'),
		bl2seq_file => $self->o('bl2seq_file_stem'),
	},
	-hive_capacity => 10,
	-flow_into => {
		2 => 'ortheus',
		-1 => 'find_dnafrag_region_strand_more_mem',
	},
},

{
	-logic_name => 'find_dnafrag_region_strand_more_mem',
	-module    => 'Bio::EnsEMBL::Compara::Production::EPOanchors::FindDfrStrand',
	-parameters => {
		bl2seq => $self->o('bl2seq'),
		bl2seq_file => $self->o('bl2seq_file_stem'),
	},
	-can_be_empty => 1,
	-rc_name => 'mem3500',
	-flow_into => {
		2 => 'ortheus',
	},
},
# ------------------------------------- run ortheus - this will populate the genomic_align* tables and the seq_region and dna tables in the ancestral db
{
	-logic_name => 'ortheus',
	-parameters => {
		max_block_size => 1000000,
		java_options => '-server -Xmx1000M',
		jar_file => $self->o('jar_file'),
		ortheus_mlssid => $self->o('epo_mlss_id'),
	},
	-module => 'Bio::EnsEMBL::Compara::RunnableDB::Ortheus',
	-failed_job_tolerance => 1,
	-hive_capacity => 50,
	-max_retry_count => 3,
	-flow_into => {
#		1 => [ 'gerp' ],
		-1 => [ 'ortheus_high_mem' ],
	},
},
# increase compute memory and java memory if default settings fail
{
	-logic_name => 'ortheus_high_mem',
	-parameters => {
		max_block_size=>1000000,
		java_options=>'-server -Xmx2500M -Xms2000m',
		jar_file => $self->o('jar_file'),
		ortheus_mlssid => $self->o('epo_mlss_id'),
	},
	-can_be_empty => 1,
	-module => 'Bio::EnsEMBL::Compara::RunnableDB::Ortheus',
	-rc_name => 'mem7500',
	-max_retry_count => 2,
	-failed_job_tolerance => 1,
	-flow_into => {
#		1 => [ 'gerp' ],
		-1 => [ 'ortheus_huge_mem' ],
	},
},
{
        -logic_name => 'ortheus_huge_mem',
        -parameters => {
                max_block_size=>1000000,
                java_options=>'-server -Xmx6500M -Xms6000m',
		jar_file => $self->o('jar_file'),
                ortheus_mlssid => $self->o('epo_mlss_id'),
        },
        -module => 'Bio::EnsEMBL::Compara::RunnableDB::Ortheus',
        -rc_name => 'hugemem',
	-max_retry_count => 1,
	-failed_job_tolerance => 1,
#        -flow_into => {
#		1 => [ 'gerp' ],
#        },
},
# ------------------------------------- run gerp - this will populate the constrained_element and conservation_scores tables
#{
#	-logic_name => 'gerp',
#        -module     => 'Bio::EnsEMBL::Compara::RunnableDB::GenomicAlignBlock::Gerp',
#        -parameters => {
#            'mlss_id' => $self->o('epo_mlss_id'),
#            'program_version' => $self->o('gerp_version'),
#            'window_sizes' => $self->o('gerp_window_sizes'),
#            'gerp_exe_dir' => $self->o('gerp_exe_dir'),
#	    'do_transactions' => 0,
#        },
#	-max_retry_count => 3,
#        -hive_capacity   => 50,
#	-failed_job_tolerance => 1,
#        -flow_into => {
#                -1 => [ 'gerp_high_mem' ],
#        },
#},
#{
#	-logic_name => 'gerp_high_mem',
#        -module     => 'Bio::EnsEMBL::Compara::RunnableDB::GenomicAlignBlock::Gerp',
#        -parameters => {
#            'mlss_id' => $self->o('epo_mlss_id'),
#            'program_version' => $self->o('gerp_version'),
#            'window_sizes' => $self->o('gerp_window_sizes'),
#            'gerp_exe_dir' => $self->o('gerp_exe_dir'),
#        },
#        -hive_capacity   => 10,
#	-rc_name => 'mem7500',
#	-failed_job_tolerance => 100,
#},
# ---------------------------------------------------[Update the max_align data in meta]--------------------------------------------------
            {  -logic_name => 'update_max_alignment_length',
               -module     => 'Bio::EnsEMBL::Compara::RunnableDB::GenomicAlignBlock::UpdateMaxAlignmentLength',
                -parameters => {
                               'quick' => $self->o('quick'),
                               'method_link_species_set_id' => $self->o('epo_mlss_id'),
                              },
               -flow_into => {
                              1 => [ 'create_neighbour_nodes_jobs_alignment' ],
                             },
            },

# --------------------------------------[Populate the left and right node_id of the genomic_align_tree table]-----------------------------
            {   -logic_name => 'create_neighbour_nodes_jobs_alignment',
                -module     => 'Bio::EnsEMBL::Hive::RunnableDB::JobFactory',
                -parameters => {
                                'inputquery' => 'SELECT root_id FROM genomic_align_tree WHERE parent_id = 0',
                                'fan_branch_code' => 2,
                               },
                -flow_into => {
                               '2->A' => [ 'set_neighbour_nodes' ],
                               'A->1' => [ 'healthcheck_factory' ],
                              },
            },
            {   -logic_name => 'set_neighbour_nodes',
                -module     => 'Bio::EnsEMBL::Compara::RunnableDB::EpoLowCoverage::SetNeighbourNodes',
                -parameters => {
                                'method_link_species_set_id' => $self->o('epo_mlss_id')
                               },
                -batch_size    => 10,
                -hive_capacity => 20,
            },
# -----------------------------------------------------------[Run healthcheck]------------------------------------------------------------
            {   -logic_name => 'healthcheck_factory',
                -module     => 'Bio::EnsEMBL::Hive::RunnableDB::Dummy',
                -meadow_type=> 'LOCAL',
                -flow_into => {
                     1 => [ 'stats_factory' ],
                },
#                               '2->A' => {
#                                     'conservation_score_healthcheck'  => [
#                                                                           {'test' => 'conservation_jobs', 'logic_name'=>'gerp','method_link_type'=>'EPO_LOW_COVERAGE'},
#                                                                           {'test' => 'conservation_scores','method_link_species_set_id'=>$self->o('gerp_cs_mlss_id')},
#                                                                ],
#                                    },
#                               'A->1' => ['stats_factory'],
#                              },
            },

#            {   -logic_name => 'conservation_score_healthcheck',
#                -module     => 'Bio::EnsEMBL::Compara::RunnableDB::HealthCheck',
#            },

            {   -logic_name => 'stats_factory',
                -module     => 'Bio::EnsEMBL::Compara::RunnableDB::ObjectFactory',
                -parameters => {
                                'call_list'             => [ 'compara_dba', 'get_GenomeDBAdaptor', 'fetch_all'],
                                'column_names2getters'  => { 'genome_db_id' => 'dbID' },

                                'fan_branch_code'       => 2,
                               },
                -flow_into  => {
                                2 => [ 'multiplealigner_stats' ],
                               },
            },

            { -logic_name => 'multiplealigner_stats',
              -module => 'Bio::EnsEMBL::Compara::RunnableDB::GenomicAlignBlock::MultipleAlignerStats',
              -parameters => {
                              'skip' => $self->o('skip_multiplealigner_stats'),
                              'dump_features' => $self->o('dump_features_exe'),
                              'compare_beds' => $self->o('compare_beds_exe'),
                              'bed_dir' => $self->o('bed_dir'),
                              'ensembl_release' => $self->o('rel_with_suffix'),
                              'output_dir' => $self->o('feature_dumps'),
                              'mlss_id'   => $self->o('epo_mlss_id'),
                             },
              -rc_name => 'mem3500',
              -hive_capacity => 100,
            },

];
}

1;


text:
package com.netflix.astyanax.connectionpool.impl;

import com.netflix.astyanax.connectionpool.*;
import com.netflix.astyanax.connectionpool.exceptions.*;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Connection pool implementation using simple round robin.
 *
 * @author elandau
 *
 * @param <CL>
 */
public class RoundRobinConnectionPoolImpl<CL> extends AbstractHostPartitionConnectionPool<CL> {

    private final AtomicInteger roundRobinCounter = new AtomicInteger(new Random().nextInt(997));
    private static final int MAX_RR_COUNTER = Integer.MAX_VALUE/2;

    public RoundRobinConnectionPoolImpl(ConnectionPoolConfiguration config, ConnectionFactory<CL> factory,
            ConnectionPoolMonitor monitor) {
        super(config, factory, monitor);
    }

    @SuppressWarnings("unchecked")
    public <R> ExecuteWithFailover<CL, R> newExecuteWithFailover(Operation<CL, R> operation) throws ConnectionException {
        try {
            if (operation.getPinnedHost() != null) {
                HostConnectionPool<CL> pool = hosts.get(operation.getPinnedHost());
                if (pool == null) {
                    throw new NoAvailableHostsException("Host " + operation.getPinnedHost() + " not active");
                }
                return new RoundRobinExecuteWithFailover<CL, R>(config, monitor,
                        Arrays.<HostConnectionPool<CL>> asList(pool), 0);
            }

            int index = roundRobinCounter.incrementAndGet();
            if (index > MAX_RR_COUNTER) {
                roundRobinCounter.set(0);
            }

            return new RoundRobinExecuteWithFailover<CL, R>(config, monitor, topology.getAllPools().getPools(), index);
        }
        catch (ConnectionException e) {
            monitor.incOperationFailure(e.getHost(), e);
            throw e;
        }
    }
}


text:
try:
    from jupyter_client import kernelspec as kernelspec
    import ipykernel.kernelspec as ipy_kernelspec
    from notebook.notebookapp import NotebookApp
    have_notebook = True
except ImportError as e:
    have_notebook = False

import pwnypack.main

__all__ = []

if have_notebook:
    class KSM(kernelspec.KernelSpecManager):
        """
        A custom jupyter KernelSpecManager which adds a pwnypack KernelSpec
        that is the same as the native kernel (python 2 / 3) but with the
        pwnypack ipython extension preloaded.
        """

        def _get_kernel_spec_by_name(self, kernel_name, resource_dir):
            if kernel_name == 'pwnypack':
                d = ipy_kernelspec.get_kernel_dict()
                d['display_name'] = 'pwnypack (%s)' % d['display_name']
                d['argv'].append('--ext=pwnypack.ipython_ext')
                return kernelspec.KernelSpec(resource_dir=resource_dir, **d)
            else:
                return super(KSM, self)._get_kernel_spec_by_name(kernel_name, resource_dir)

        def find_kernel_specs(self):
            specs = super(KSM, self).find_kernel_specs()
            if not 'pwnypack' in specs:
                specs['pwnypack'] = ipy_kernelspec.RESOURCES
            return specs

    @pwnypack.main.register()
    def pwnbook(_parser, cmd, args):  # pragma: no cover
        """
        Start a jupyter notebook with the pwnypack enhanced kernel pre-loaded.
        """

        notebook = NotebookApp(kernel_spec_manager_class=KSM)
        notebook.initialize(args)
        notebook.start()


text:
<title>
The must-see movie that you can't
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Hollywood silences The Quiet American

The must-see movie that you can't

Review by Bill Kimmel | January 17, 2003 | Page 13

MOVIES: The Quiet American, directed by Phillip Noyce, screenplay by Christopher Hampton and Robert Schenkkan, based on the novel by Graham Greene, starring Michael Caine, Brendan Fraser and Do Thi Hai Yen.

THE QUIET American is a must-see movie--too bad U.S. audiences will have an impossible time finding a theater that's showing it. The movie is based on a 1955 Graham Greene novel about the early years of U.S. involvement in Vietnam. The film was completed shortly before September 11, when Miramax co-chair Harvey Weinstein pulled the plug on the film, calling it "unpatriotic."

The Quiet American only saw the light of day after Michael Caine, who plays the lead in the movie, objected and persuaded Miramax to do a limited run in order to qualify for the Academy Awards. So The Quiet American appeared for two weeks in December in a few cities.

The result is that people in the U.S. are denied an opportunity to see a great movie. It's set in Vietnam in 1952. French power is waning as Communist forces are winning efforts to liberate Vietnam.

Caine plays Thomas Fowler, an English reporter who meets "the quiet American"--Alden Pyle, played by Brendan Fraser. Pyle has a job working with medical teams in Vietnam, but this is cover for his real work--as a CIA agent who is attempting to throw U.S. support behind a new force in Vietnamese politics, led by a notorious Vietnamese general, General Thé.

Even though Thé is guilty of butchering civilians, the U.S. is arming him and his forces in order to make sure that the Communists do not gain control. As the movie progresses, Pyle's true role slowly emerges, culminating in Thé's forces using American explosives in a terrorist attack in a public square, killing dozens of civilians. The bombing was done to place blame on the Communists, with Pyle taking pictures of dying civilians instead of helping them.

The backdrop to this story is Pyle and Fowler's relationship with a young Vietnamese woman named Phuong, played by Do Thi Hai Yen. Trapped economically, she has attached herself to Fowler in the hopes of some stable future.

When Pyle becomes infatuated with Phuong and attempts to steal her away from Fowler, Pyle's wholesome intentions appear clearly at odds with his willingness to participate in a civilian massacre to ensure U.S. hegemony.

The Quiet American has some great acting by Caine and is visually stunning. Much of it was shot on location in Vietnam, and the backdrops of city life and scenes in the country are beautiful. The movie exposes the U.S. role in Vietnam, showing how the CIA has supported despots there for years.

It is no surprise that movie executives are unhappy with the politics of the movie--how dare anyone imply that the U.S. kills civilians as part of its foreign policy when it's launching a "war on terrorism" across the globe.

The book is available at bookstores, so grab a copy and keep your eyes open for showings. Perhaps the U.S. studios' greed will outweigh their patriotism as the Oscar race heats up.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
<?php

namespace Mammoth\Modules\Search\Models;

use Illuminate\Database\Eloquent\Model;

class Search extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = '';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
}