text:
package at.ameise.moodtracker.backend.apis;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HttpServlet for handling maintenance tasks.
 */
public class MaintenanceTasksServlet extends HttpServlet {

    @Override
    public final void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
        resp.setContentType("text/plain");
        if (!false){//buildSearchIndexForPlaces()) {
            resp.getWriter().println(
                    "MaintenanceTasks failed. Try again by refreshing.");
            return;
        }
        resp.getWriter().println("MaintenanceTasks completed");
    }
}


text:
import threading
import time
from sqlalchemy import pool, select, event
import sqlalchemy as tsa
from sqlalchemy import testing
from sqlalchemy.testing.util import gc_collect, lazy_gc
from sqlalchemy.testing import eq_, assert_raises, is_not_
from sqlalchemy.testing.engines import testing_engine
from sqlalchemy.testing import fixtures
import random
from sqlalchemy.testing.mock import Mock, call

join_timeout = 10

def MockDBAPI():
    def cursor():
        while True:
            yield Mock()

    def connect():
        while True:
            yield Mock(cursor=Mock(side_effect=cursor()))

    def shutdown(value):
        if value:
            db.connect = Mock(side_effect=Exception("connect failed"))
        else:
            db.connect = Mock(side_effect=connect())

    db = Mock(connect=Mock(side_effect=connect()),
                    shutdown=shutdown, _shutdown=False)
    return db

class PoolTestBase(fixtures.TestBase):
    def setup(self):
        pool.clear_managers()

    @classmethod
    def teardown_class(cls):
        pool.clear_managers()

    def _queuepool_fixture(self, **kw):
        dbapi, pool = self._queuepool_dbapi_fixture(**kw)
        return pool

    def _queuepool_dbapi_fixture(self, **kw):
        dbapi = MockDBAPI()
        return dbapi, pool.QueuePool(creator=lambda: dbapi.connect('foo.db'),
                        **kw)

class PoolTest(PoolTestBase):
    def test_manager(self):
        manager = pool.manage(MockDBAPI(), use_threadlocal=True)

        c1 = manager.connect('foo.db')
        c2 = manager.connect('foo.db')
        c3 = manager.connect('bar.db')
        c4 = manager.connect("foo.db", bar="bat")
        c5 = manager.connect("foo.db", bar="hoho")
        c6 = manager.connect("foo.db", bar="bat")

        assert c1.cursor() is not None
        assert c1 is c2
        assert c1 is not c3
        assert c4 is c6
        assert c4 is not c5

    def test_manager_with_key(self):

        dbapi = MockDBAPI()
        manager = pool.manage(dbapi, use_threadlocal=True)

        c1 = manager.connect('foo.db', sa_pool_key="a")
        c2 = manager.connect('foo.db', sa_pool_key="b")
        c3 = manager.connect('bar.db', sa_pool_key="a")

        assert c1.cursor() is not None
        assert c1 is not c2
        assert c1 is c3

        eq_(dbapi.connect.mock_calls,
            [
                call("foo.db"),
                call("foo.db"),
            ]
        )

    def test_bad_args(self):
        manager = pool.manage(MockDBAPI())
        manager.connect(None)

    def test_non_thread_local_manager(self):
        manager = pool.manage(MockDBAPI(), use_threadlocal=False)

        connection = manager.connect('foo.db')
        connection2 = manager.connect('foo.db')

        self.assert_(connection.cursor() is not None)
        self.assert_(connection is not connection2)

    @testing.fails_on('+pyodbc',
                      "pyodbc cursor doesn't implement tuple __eq__")
    def test_cursor_iterable(self):
        conn = testing.db.raw_connection()
        cursor = conn.cursor()
        cursor.execute(str(select([1], bind=testing.db)))
        expected = [(1, )]
        for row in cursor:
            eq_(row, expected.pop(0))

    def test_no_connect_on_recreate(self):
        def creator():
            raise Exception("no creates allowed")

        for cls in (pool.SingletonThreadPool, pool.StaticPool,
                    pool.QueuePool, pool.NullPool, pool.AssertionPool):
            p = cls(creator=creator)
            p.dispose()
            p2 = p.recreate()
            assert p2.__class__ is cls

            mock_dbapi = MockDBAPI()
            p = cls(creator=mock_dbapi.connect)
            conn = p.connect()
            conn.close()
            mock_dbapi.connect.side_effect = Exception("error!")
            p.dispose()
            p.recreate()

    def testthreadlocal_del(self):
        self._do_testthreadlocal(useclose=False)

    def testthreadlocal_close(self):
        self._do_testthreadlocal(useclose=True)

    def _do_testthreadlocal(self, useclose=False):
        dbapi = MockDBAPI()
        for p in pool.QueuePool(creator=dbapi.connect,
                                pool_size=3, max_overflow=-1,
                                use_threadlocal=True), \
            pool.SingletonThreadPool(creator=dbapi.connect,
                use_threadlocal=True):
            c1 = p.connect()
            c2 = p.connect()
            self.assert_(c1 is c2)
            c3 = p.unique_connection()
            self.assert_(c3 is not c1)
            if useclose:
                c2.close()
            else:
                c2 = None
            c2 = p.connect()
            self.assert_(c1 is c2)
            self.assert_(c3 is not c1)
            if useclose:
                c2.close()
            else:
                c2 = None
                lazy_gc()
            if useclose:
                c1 = p.connect()
                c2 = p.connect()
                c3 = p.connect()
                c3.close()
                c2.close()
                self.assert_(c1.connection is not None)
                c1.close()
            c1 = c2 = c3 = None

            # extra tests with QueuePool to ensure connections get
            # __del__()ed when dereferenced

            if isinstance(p, pool.QueuePool):
                lazy_gc()
                self.assert_(p.checkedout() == 0)
                c1 = p.connect()
                c2 = p.connect()
                if useclose:
                    c2.close()
                    c1.close()
                else:
                    c2 = None
                    c1 = None
                    lazy_gc()
                self.assert_(p.checkedout() == 0)

    def test_info(self):
        p = self._queuepool_fixture(pool_size=1, max_overflow=0)

        c = p.connect()
        self.assert_(not c.info)
        self.assert_(c.info is c._connection_record.info)

        c.info['foo'] = 'bar'
        c.close()
        del c

        c = p.connect()
        self.assert_('foo' in c.info)

        c.invalidate()
        c = p.connect()
        self.assert_('foo' not in c.info)

        c.info['foo2'] = 'bar2'
        c.detach()
        self.assert_('foo2' in c.info)

        c2 = p.connect()
        is_not_(c.connection, c2.connection)
        assert not c2.info
        assert 'foo2' in c.info

class PoolDialectTest(PoolTestBase):
    def _dialect(self):
        canary = []
        class PoolDialect(object):
            def do_rollback(self, dbapi_connection):
                canary.append('R')
                dbapi_connection.rollback()

            def do_commit(self, dbapi_connection):
                canary.append('C')
                dbapi_connection.commit()

            def do_close(self, dbapi_connection):
                canary.append('CL')
                dbapi_connection.close()
        return PoolDialect(), canary

    def _do_test(self, pool_cls, assertion):
        mock_dbapi = MockDBAPI()
        dialect, canary = self._dialect()

        p = pool_cls(creator=mock_dbapi.connect)
        p._dialect = dialect
        conn = p.connect()
        conn.close()
        p.dispose()
        p.recreate()
        conn = p.connect()
        conn.close()
        eq_(canary, assertion)

    def test_queue_pool(self):
        self._do_test(pool.QueuePool, ['R', 'CL', 'R'])

    def test_assertion_pool(self):
        self._do_test(pool.AssertionPool, ['R', 'CL', 'R'])

    def test_singleton_pool(self):
        self._do_test(pool.SingletonThreadPool, ['R', 'CL', 'R'])

    def test_null_pool(self):
        self._do_test(pool.NullPool, ['R', 'CL', 'R', 'CL'])

    def test_static_pool(self):
        self._do_test(pool.StaticPool, ['R', 'R'])

class PoolEventsTest(PoolTestBase):
    def _first_connect_event_fixture(self):
        p = self._queuepool_fixture()
        canary = []
        def first_connect(*arg, **kw):
            canary.append('first_connect')

        event.listen(p, 'first_connect', first_connect)

        return p, canary

    def _connect_event_fixture(self):
        p = self._queuepool_fixture()
        canary = []
        def connect(*arg, **kw):
            canary.append('connect')
        event.listen(p, 'connect', connect)

        return p, canary

    def _checkout_event_fixture(self):
        p = self._queuepool_fixture()
        canary = []
        def checkout(*arg, **kw):
            canary.append('checkout')
        event.listen(p, 'checkout', checkout)

        return p, canary

    def _checkin_event_fixture(self):
        p = self._queuepool_fixture()
        canary = []
        def checkin(*arg, **kw):
            canary.append('checkin')
        event.listen(p, 'checkin', checkin)

        return p, canary

    def _reset_event_fixture(self):
        p = self._queuepool_fixture()
        canary = []
        def reset(*arg, **kw):
            canary.append('reset')
        event.listen(p, 'reset', reset)

        return p, canary

    def _invalidate_event_fixture(self):
        p = self._queuepool_fixture()
        canary = Mock()
        event.listen(p, 'invalidate', canary)

        return p, canary

    def test_first_connect_event(self):
        p, canary = self._first_connect_event_fixture()

        c1 = p.connect()
        eq_(canary, ['first_connect'])

    def test_first_connect_event_fires_once(self):
        p, canary = self._first_connect_event_fixture()

        c1 = p.connect()
        c2 = p.connect()

        eq_(canary, ['first_connect'])

    def test_first_connect_on_previously_recreated(self):
        p, canary = self._first_connect_event_fixture()

        p2 = p.recreate()
        c1 = p.connect()
        c2 = p2.connect()

        eq_(canary, ['first_connect', 'first_connect'])

    def test_first_connect_on_subsequently_recreated(self):
        p, canary = self._first_connect_event_fixture()

        c1 = p.connect()
        p2 = p.recreate()
        c2 = p2.connect()

        eq_(canary, ['first_connect', 'first_connect'])

    def test_connect_event(self):
        p, canary = self._connect_event_fixture()

        c1 = p.connect()
        eq_(canary, ['connect'])

    def test_connect_event_fires_subsequent(self):
        p, canary = self._connect_event_fixture()

        c1 = p.connect()
        c2 = p.connect()

        eq_(canary, ['connect', 'connect'])

    def test_connect_on_previously_recreated(self):
        p, canary = self._connect_event_fixture()

        p2 = p.recreate()

        c1 = p.connect()
        c2 = p2.connect()

        eq_(canary, ['connect', 'connect'])

    def test_connect_on_subsequently_recreated(self):
        p, canary = self._connect_event_fixture()

        c1 = p.connect()
        p2 = p.recreate()
        c2 = p2.connect()

        eq_(canary, ['connect', 'connect'])

    def test_checkout_event(self):
        p, canary = self._checkout_event_fixture()

        c1 = p.connect()
        eq_(canary, ['checkout'])

    def test_checkout_event_fires_subsequent(self):
        p, canary = self._checkout_event_fixture()

        c1 = p.connect()
        c2 = p.connect()
        eq_(canary, ['checkout', 'checkout'])

    def test_checkout_event_on_subsequently_recreated(self):
        p, canary = self._checkout_event_fixture()

        c1 = p.connect()
        p2 = p.recreate()
        c2 = p2.connect()

        eq_(canary, ['checkout', 'checkout'])

    def test_checkin_event(self):
        p, canary = self._checkin_event_fixture()

        c1 = p.connect()
        eq_(canary, [])
        c1.close()
        eq_(canary, ['checkin'])

    def test_reset_event(self):
        p, canary = self._reset_event_fixture()

        c1 = p.connect()
        eq_(canary, [])
        c1.close()
        eq_(canary, ['reset'])

    def test_invalidate_event_no_exception(self):
        p, canary = self._invalidate_event_fixture()

        c1 = p.connect()
        c1.close()
        assert not canary.called
        c1 = p.connect()
        dbapi_con = c1.connection
        c1.invalidate()
        assert canary.call_args_list[0][0][0] is dbapi_con
        assert canary.call_args_list[0][0][2] is None

    def test_invalidate_event_exception(self):
        p, canary = self._invalidate_event_fixture()

        c1 = p.connect()
        c1.close()
        assert not canary.called
        c1 = p.connect()
        dbapi_con = c1.connection
        exc = Exception("hi")
        c1.invalidate(exc)
        assert canary.call_args_list[0][0][0] is dbapi_con
        assert canary.call_args_list[0][0][2] is exc

    def test_checkin_event_gc(self):
        p, canary = self._checkin_event_fixture()

        c1 = p.connect()
        eq_(canary, [])
        del c1
        lazy_gc()
        eq_(canary, ['checkin'])

    def test_checkin_event_on_subsequently_recreated(self):
        p, canary = self._checkin_event_fixture()

        c1 = p.connect()
        p2 = p.recreate()
        c2 = p2.connect()

        eq_(canary, [])

        c1.close()
        eq_(canary, ['checkin'])

        c2.close()
        eq_(canary, ['checkin', 'checkin'])

    def test_listen_targets_scope(self):
        canary = []
        def listen_one(*args):
            canary.append("listen_one")
        def listen_two(*args):
            canary.append("listen_two")
        def listen_three(*args):
            canary.append("listen_three")
        def listen_four(*args):
            canary.append("listen_four")

        engine = testing_engine(testing.db.url)
        event.listen(pool.Pool, 'connect', listen_one)
        event.listen(engine.pool, 'connect', listen_two)
        event.listen(engine, 'connect', listen_three)
        event.listen(engine.__class__, 'connect', listen_four)

        engine.execute(select([1])).close()
        eq_(
            canary,
            ["listen_one", "listen_four", "listen_two", "listen_three"]
        )

    def test_listen_targets_per_subclass(self):
        """test that listen() called on a subclass remains specific to that subclass."""

        canary = []
        def listen_one(*args):
            canary.append("listen_one")
        def listen_two(*args):
            canary.append("listen_two")
        def listen_three(*args):
            canary.append("listen_three")

        event.listen(pool.Pool, 'connect', listen_one)
        event.listen(pool.QueuePool, 'connect', listen_two)
        event.listen(pool.SingletonThreadPool, 'connect', listen_three)

        p1 = pool.QueuePool(creator=MockDBAPI().connect)
        p2 = pool.SingletonThreadPool(creator=MockDBAPI().connect)

        assert listen_one in p1.dispatch.connect
        assert listen_two in p1.dispatch.connect
        assert listen_three not in p1.dispatch.connect
        assert listen_one in p2.dispatch.connect
        assert listen_two not in p2.dispatch.connect
        assert listen_three in p2.dispatch.connect

        p1.connect()
        eq_(canary, ["listen_one", "listen_two"])
        p2.connect()
        eq_(canary, ["listen_one", "listen_two", "listen_one", "listen_three"])

    def teardown(self):
        # TODO: need to get remove() functionality
        # going
        pool.Pool.dispatch._clear()

class PoolFirstConnectSyncTest(PoolTestBase):
    # test [ticket:2964]

    def test_sync(self):
        pool = self._queuepool_fixture(pool_size=3, max_overflow=0)

        evt = Mock()

        @event.listens_for(pool, 'first_connect')
        def slow_first_connect(dbapi_con, rec):
            time.sleep(1)
            evt.first_connect()

        @event.listens_for(pool, 'connect')
        def on_connect(dbapi_con, rec):
            evt.connect()

        def checkout():
            for j in range(2):
                c1 = pool.connect()
                time.sleep(.02)
                c1.close()
                time.sleep(.02)

        threads = []
        for i in range(5):
            th = threading.Thread(target=checkout)
            th.start()
            threads.append(th)
        for th in threads:
            th.join(join_timeout)

        eq_(evt.mock_calls,
                [call.first_connect(), call.connect(), call.connect(), call.connect()]
            )

class DeprecatedPoolListenerTest(PoolTestBase):
    @testing.requires.predictable_gc
    @testing.uses_deprecated(r".*Use event.listen")
    def test_listeners(self):
        class InstrumentingListener(object):
            def __init__(self):
                if hasattr(self, 'connect'):
                    self.connect = self.inst_connect
                if hasattr(self, 'first_connect'):
                    self.first_connect = self.inst_first_connect
                if hasattr(self, 'checkout'):
                    self.checkout = self.inst_checkout
                if hasattr(self, 'checkin'):
                    self.checkin = self.inst_checkin
                self.clear()
            def clear(self):
                self.connected = []
                self.first_connected = []
                self.checked_out = []
                self.checked_in = []
            def assert_total(innerself, conn, fconn, cout, cin):
                eq_(len(innerself.connected), conn)
                eq_(len(innerself.first_connected), fconn)
                eq_(len(innerself.checked_out), cout)
                eq_(len(innerself.checked_in), cin)
            def assert_in(innerself, item, in_conn, in_fconn,
                                                in_cout, in_cin):
                self.assert_((item in innerself.connected) == in_conn)
                self.assert_((item in innerself.first_connected) == in_fconn)
                self.assert_((item in innerself.checked_out) == in_cout)
                self.assert_((item in innerself.checked_in) == in_cin)
            def inst_connect(self, con, record):
                print("connect(%s, %s)" % (con, record))
                assert con is not None
                assert record is not None
                self.connected.append(con)
            def inst_first_connect(self, con, record):
                print("first_connect(%s, %s)" % (con, record))
                assert con is not None
                assert record is not None
                self.first_connected.append(con)
            def inst_checkout(self, con, record, proxy):
                print("checkout(%s, %s, %s)" % (con, record, proxy))
                assert con is not None
                assert record is not None
                assert proxy is not None
                self.checked_out.append(con)
            def inst_checkin(self, con, record):
                print("checkin(%s, %s)" % (con, record))
                # con can be None if invalidated
                assert record is not None
                self.checked_in.append(con)

        class ListenAll(tsa.interfaces.PoolListener, InstrumentingListener):
            pass
        class ListenConnect(InstrumentingListener):
            def connect(self, con, record):
                pass
        class ListenFirstConnect(InstrumentingListener):
            def first_connect(self, con, record):
                pass
        class ListenCheckOut(InstrumentingListener):
            def checkout(self, con, record, proxy, num):
                pass
        class ListenCheckIn(InstrumentingListener):
            def checkin(self, con, record):
                pass

        def assert_listeners(p, total, conn, fconn, cout, cin):
            for instance in (p, p.recreate()):
                self.assert_(len(instance.dispatch.connect) == conn)
                self.assert_(len(instance.dispatch.first_connect) == fconn)
                self.assert_(len(instance.dispatch.checkout) == cout)
                self.assert_(len(instance.dispatch.checkin) == cin)

        p = self._queuepool_fixture()
        assert_listeners(p, 0, 0, 0, 0, 0)

        p.add_listener(ListenAll())
        assert_listeners(p, 1, 1, 1, 1, 1)

        p.add_listener(ListenConnect())
        assert_listeners(p, 2, 2, 1, 1, 1)

        p.add_listener(ListenFirstConnect())
        assert_listeners(p, 3, 2, 2, 1, 1)

        p.add_listener(ListenCheckOut())
        assert_listeners(p, 4, 2, 2, 2, 1)

        p.add_listener(ListenCheckIn())
        assert_listeners(p, 5, 2, 2, 2, 2)
        del p

        snoop = ListenAll()
        p = self._queuepool_fixture(listeners=[snoop])
        assert_listeners(p, 1, 1, 1, 1, 1)

        c = p.connect()
        snoop.assert_total(1, 1, 1, 0)
        cc = c.connection
        snoop.assert_in(cc, True, True, True, False)
        c.close()
        snoop.assert_in(cc, True, True, True, True)
        del c, cc

        snoop.clear()

        # this one depends on immediate gc
        c = p.connect()
        cc = c.connection
        snoop.assert_in(cc, False, False, True, False)
        snoop.assert_total(0, 0, 1, 0)
        del c, cc
        lazy_gc()
        snoop.assert_total(0, 0, 1, 1)

        p.dispose()
        snoop.clear()

        c = p.connect()
        c.close()
        c = p.connect()
        snoop.assert_total(1, 0, 2, 1)
        c.close()
        snoop.assert_total(1, 0, 2, 2)

        # invalidation
        p.dispose()
        snoop.clear()

        c = p.connect()
        snoop.assert_total(1, 0, 1, 0)
        c.invalidate()
        snoop.assert_total(1, 0, 1, 1)
        c.close()
        snoop.assert_total(1, 0, 1, 1)
        del c
        lazy_gc()
        snoop.assert_total(1, 0, 1, 1)
        c = p.connect()
        snoop.assert_total(2, 0, 2, 1)
        c.close()
        del c
        lazy_gc()
        snoop.assert_total(2, 0, 2, 2)

        # detached
        p.dispose()
        snoop.clear()

        c = p.connect()
        snoop.assert_total(1, 0, 1, 0)
        c.detach()
        snoop.assert_total(1, 0, 1, 0)
        c.close()
        del c
        snoop.assert_total(1, 0, 1, 0)
        c = p.connect()
        snoop.assert_total(2, 0, 2, 0)
        c.close()
        del c
        snoop.assert_total(2, 0, 2, 1)

        # recreated
        p = p.recreate()
        snoop.clear()

        c = p.connect()
        snoop.assert_total(1, 1, 1, 0)
        c.close()
        snoop.assert_total(1, 1, 1, 1)
        c = p.connect()
        snoop.assert_total(1, 1, 2, 1)
        c.close()
        snoop.assert_total(1, 1, 2, 2)

    @testing.uses_deprecated(r".*Use event.listen")
    def test_listeners_callables(self):
        def connect(dbapi_con, con_record):
            counts[0] += 1
        def checkout(dbapi_con, con_record, con_proxy):
            counts[1] += 1
        def checkin(dbapi_con, con_record):
            counts[2] += 1

        i_all = dict(connect=connect, checkout=checkout, checkin=checkin)
        i_connect = dict(connect=connect)
        i_checkout = dict(checkout=checkout)
        i_checkin = dict(checkin=checkin)

        for cls in (pool.QueuePool, pool.StaticPool):
            counts = [0, 0, 0]

            def assert_listeners(p, total, conn, cout, cin):
                for instance in (p, p.recreate()):
                    eq_(len(instance.dispatch.connect), conn)
                    eq_(len(instance.dispatch.checkout), cout)
                    eq_(len(instance.dispatch.checkin), cin)

            p = self._queuepool_fixture()
            assert_listeners(p, 0, 0, 0, 0)

            p.add_listener(i_all)
            assert_listeners(p, 1, 1, 1, 1)

            p.add_listener(i_connect)
            assert_listeners(p, 2, 1, 1, 1)

            p.add_listener(i_checkout)
            assert_listeners(p, 3, 1, 1, 1)

            p.add_listener(i_checkin)
            assert_listeners(p, 4, 1, 1, 1)
            del p

            p = self._queuepool_fixture(listeners=[i_all])
            assert_listeners(p, 1, 1, 1, 1)

            c = p.connect()
            assert counts == [1, 1, 0]
            c.close()
            assert counts == [1, 1, 1]

            c = p.connect()
            assert counts == [1, 2, 1]
            p.add_listener(i_checkin)
            c.close()
            assert counts == [1, 2, 2]

class QueuePoolTest(PoolTestBase):

    def testqueuepool_del(self):
        self._do_testqueuepool(useclose=False)

    def testqueuepool_close(self):
        self._do_testqueuepool(useclose=True)

    def _do_testqueuepool(self, useclose=False):
        p = self._queuepool_fixture(pool_size=3,
                           max_overflow=-1)

        def status(pool):
            tup = pool.size(), pool.checkedin(), pool.overflow(), \
                pool.checkedout()
            print('Pool size: %d  Connections in pool: %d Current '\
                'Overflow: %d Current Checked out connections: %d' % tup)
            return tup

        c1 = p.connect()
        self.assert_(status(p) == (3, 0, -2, 1))
        c2 = p.connect()
        self.assert_(status(p) == (3, 0, -1, 2))
        c3 = p.connect()
        self.assert_(status(p) == (3, 0, 0, 3))
        c4 = p.connect()
        self.assert_(status(p) == (3, 0, 1, 4))
        c5 = p.connect()
        self.assert_(status(p) == (3, 0, 2, 5))
        c6 = p.connect()
        self.assert_(status(p) == (3, 0, 3, 6))
        if useclose:
            c4.close()
            c3.close()
            c2.close()
        else:
            c4 = c3 = c2 = None
            lazy_gc()
        self.assert_(status(p) == (3, 3, 3, 3))
        if useclose:
            c1.close()
            c5.close()
            c6.close()
        else:
            c1 = c5 = c6 = None
            lazy_gc()
        self.assert_(status(p) == (3, 3, 0, 0))
        c1 = p.connect()
        c2 = p.connect()
        self.assert_(status(p) == (3, 1, 0, 2), status(p))
        if useclose:
            c2.close()
        else:
            c2 = None
            lazy_gc()
        self.assert_(status(p) == (3, 2, 0, 1))
        c1.close()
        lazy_gc()
        assert not pool._refs

    def test_timeout(self):
        p = self._queuepool_fixture(pool_size=3,
                           max_overflow=0,
                           timeout=2)
        c1 = p.connect()
        c2 = p.connect()
        c3 = p.connect()
        now = time.time()
        try:
            c4 = p.connect()
            assert False
        except tsa.exc.TimeoutError:
            assert int(time.time() - now) == 2

    @testing.requires.threading_with_mock
    def test_timeout_race(self):
        # test a race condition where the initial connecting threads all race
        # to queue.Empty, then block on the mutex.  each thread consumes a
        # connection as they go in.  when the limit is reached, the remaining
        # threads go in, and get TimeoutError; even though they never got to
        # wait for the timeout on queue.get().  the fix involves checking the
        # timeout again within the mutex, and if so, unlocking and throwing
        # them back to the start of do_get()
        dbapi = MockDBAPI()
        p = pool.QueuePool(
                creator=lambda: dbapi.connect(delay=.05),
                pool_size=2,
                max_overflow=1, use_threadlocal=False, timeout=3)
        timeouts = []
        def checkout():
            for x in range(1):
                now = time.time()
                try:
                    c1 = p.connect()
                except tsa.exc.TimeoutError:
                    timeouts.append(time.time() - now)
                    continue
                time.sleep(4)
                c1.close()

        threads = []
        for i in range(10):
            th = threading.Thread(target=checkout)
            th.start()
            threads.append(th)
        for th in threads:
            th.join(join_timeout)

        assert len(timeouts) > 0
        for t in timeouts:
            assert t >= 3, "Not all timeouts were >= 3 seconds %r" % timeouts
            # normally, the timeout should under 4 seconds,
            # but on a loaded down buildbot it can go up.
            assert t < 14, "Not all timeouts were < 14 seconds %r" % timeouts

    def _test_overflow(self, thread_count, max_overflow):
        gc_collect()

        dbapi = MockDBAPI()
        mutex = threading.Lock()
        def creator():
            time.sleep(.05)
            with mutex:
                return dbapi.connect()

        p = pool.QueuePool(creator=creator,
                           pool_size=3, timeout=2,
                           max_overflow=max_overflow)
        peaks = []
        def whammy():
            for i in range(10):
                try:
                    con = p.connect()
                    time.sleep(.005)
                    peaks.append(p.overflow())
                    con.close()
                    del con
                except tsa.exc.TimeoutError:
                    pass
        threads = []
        for i in range(thread_count):
            th = threading.Thread(target=whammy)
            th.start()
            threads.append(th)
        for th in threads:
            th.join(join_timeout)

        self.assert_(max(peaks) <= max_overflow)

        lazy_gc()
        assert not pool._refs

    def test_overflow_reset_on_failed_connect(self):
        dbapi = Mock()

        def failing_dbapi():
            time.sleep(2)
            raise Exception("connection failed")

        creator = dbapi.connect
        def create():
            return creator()

        p = pool.QueuePool(creator=create, pool_size=2, max_overflow=3)
        c1 = p.connect()
        c2 = p.connect()
        c3 = p.connect()
        eq_(p._overflow, 1)
        creator = failing_dbapi
        assert_raises(Exception, p.connect)
        eq_(p._overflow, 1)

    @testing.requires.threading_with_mock
    def test_hanging_connect_within_overflow(self):
        """test that a single connect() call which is hanging
        does not block other connections from proceeding."""

        dbapi = Mock()
        mutex = threading.Lock()

        def hanging_dbapi():
            time.sleep(2)
            with mutex:
                return dbapi.connect()

        def fast_dbapi():
            with mutex:
                return dbapi.connect()

        creator = threading.local()

        def create():
            return creator.mock_connector()

        def run_test(name, pool, should_hang):
            if should_hang:
                creator.mock_connector = hanging_dbapi
            else:
                creator.mock_connector = fast_dbapi

            conn = pool.connect()
            conn.operation(name)
            time.sleep(1)
            conn.close()

        p = pool.QueuePool(creator=create, pool_size=2, max_overflow=3)

        threads = [
            threading.Thread(
                        target=run_test, args=("success_one", p, False)),
            threading.Thread(
                        target=run_test, args=("success_two", p, False)),
            threading.Thread(
                        target=run_test, args=("overflow_one", p, True)),
            threading.Thread(
                        target=run_test, args=("overflow_two", p, False)),
            threading.Thread(
                        target=run_test, args=("overflow_three", p, False))
        ]
        for t in threads:
            t.start()
            time.sleep(.2)

        for t in threads:
            t.join(timeout=join_timeout)
        eq_(
            dbapi.connect().operation.mock_calls,
            [call("success_one"), call("success_two"),
                call("overflow_two"), call("overflow_three"),
                call("overflow_one")]
        )

    @testing.requires.threading_with_mock
    def test_waiters_handled(self):
        """test that threads waiting for connections are
        handled when the pool is replaced.

        """
        mutex = threading.Lock()
        dbapi = MockDBAPI()
        def creator():
            mutex.acquire()
            try:
                return dbapi.connect()
            finally:
                mutex.release()

        success = []
        for timeout in (None, 30):
            for max_overflow in (0, -1, 3):
                p = pool.QueuePool(creator=creator,
                                   pool_size=2, timeout=timeout,
                                   max_overflow=max_overflow)
                def waiter(p, timeout, max_overflow):
                    success_key = (timeout, max_overflow)
                    conn = p.connect()
                    success.append(success_key)
                    time.sleep(.1)
                    conn.close()

                c1 = p.connect()
                c2 = p.connect()

                threads = []
                for i in range(2):
                    t = threading.Thread(target=waiter,
                                    args=(p, timeout, max_overflow))
                    t.daemon = True
                    t.start()
                    threads.append(t)

                # this sleep makes sure that the
                # two waiter threads hit upon wait()
                # inside the queue, before we invalidate the other
                # two conns
                time.sleep(.2)
                p._invalidate(c2)

                for t in threads:
                    t.join(join_timeout)

        eq_(len(success), 12, "successes: %s" % success)

    @testing.requires.threading_with_mock
    def test_notify_waiters(self):
        dbapi = MockDBAPI()

        canary = []
        def creator():
            canary.append(1)
            return dbapi.connect()
        p1 = pool.QueuePool(creator=creator,
                           pool_size=1, timeout=None,
                           max_overflow=0)
        def waiter(p):
            conn = p.connect()
            canary.append(2)
            time.sleep(.5)
            conn.close()

        c1 = p1.connect()

        threads = []
        for i in range(5):
            t = threading.Thread(target=waiter, args=(p1, ))
            t.start()
            threads.append(t)
        time.sleep(.5)
        eq_(canary, [1])

        # this also calls invalidate()
        # on c1
        p1._invalidate(c1)

        for t in threads:
            t.join(join_timeout)

        eq_(canary, [1, 1, 2, 2, 2, 2, 2])

    def test_dispose_closes_pooled(self):
        dbapi = MockDBAPI()

        p = pool.QueuePool(creator=dbapi.connect,
                           pool_size=2, timeout=None,
                           max_overflow=0)
        c1 = p.connect()
        c2 = p.connect()
        c1_con = c1.connection
        c2_con = c2.connection

        c1.close()

        eq_(c1_con.close.call_count, 0)
        eq_(c2_con.close.call_count, 0)

        p.dispose()

        eq_(c1_con.close.call_count, 1)
        eq_(c2_con.close.call_count, 0)

        # currently, if a ConnectionFairy is closed
        # after the pool has been disposed, there's no
        # flag that states it should be invalidated
        # immediately - it just gets returned to the
        # pool normally...
        c2.close()
        eq_(c1_con.close.call_count, 1)
        eq_(c2_con.close.call_count, 0)

        # ...and that's the one we'll get back next.
        c3 = p.connect()
        assert c3.connection is c2_con

    @testing.requires.threading_with_mock
    def test_no_overflow(self):
        self._test_overflow(40, 0)

    @testing.requires.threading_with_mock
    def test_max_overflow(self):
        self._test_overflow(40, 5)

    def test_mixed_close(self):
        pool._refs.clear()
        p = self._queuepool_fixture(pool_size=3, max_overflow=-1, use_threadlocal=True)
        c1 = p.connect()
        c2 = p.connect()
        assert c1 is c2
        c1.close()
        c2 = None
        assert p.checkedout() == 1
        c1 = None
        lazy_gc()
        assert p.checkedout() == 0
        lazy_gc()
        assert not pool._refs

    def test_overflow_no_gc_tlocal(self):
        self._test_overflow_no_gc(True)

    def test_overflow_no_gc(self):
        self._test_overflow_no_gc(False)

    def _test_overflow_no_gc(self, threadlocal):
        p = self._queuepool_fixture(pool_size=2,
                           max_overflow=2)

        # disable weakref collection of the
        # underlying connections
        strong_refs = set()
        def _conn():
            c = p.connect()
            strong_refs.add(c.connection)
            return c

        for j in range(5):
            # open 4 conns at a time.  each time this
            # will yield two pooled connections + two
            # overflow connections.
            conns = [_conn() for i in range(4)]
            for c in conns:
                c.close()

        # doing that for a total of 5 times yields
        # ten overflow connections closed plus the
        # two pooled connections unclosed.

        eq_(
            set([c.close.call_count for c in strong_refs]),
            set([1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0])
        )

    @testing.requires.predictable_gc
    def test_weakref_kaboom(self):
        p = self._queuepool_fixture(pool_size=3,
                           max_overflow=-1, use_threadlocal=True)
        c1 = p.connect()
        c2 = p.connect()
        c1.close()
        c2 = None
        del c1
        del c2
        gc_collect()
        assert p.checkedout() == 0
        c3 = p.connect()
        assert c3 is not None

    def test_trick_the_counter(self):
        """this is a "flaw" in the connection pool; since threadlocal
        uses a single ConnectionFairy per thread with an open/close
        counter, you can fool the counter into giving you a
        ConnectionFairy with an ambiguous counter.  i.e. its not true
        reference counting."""

        p = self._queuepool_fixture(pool_size=3,
                           max_overflow=-1, use_threadlocal=True)
        c1 = p.connect()
        c2 = p.connect()
        assert c1 is c2
        c1.close()
        c2 = p.connect()
        c2.close()
        self.assert_(p.checkedout() != 0)
        c2.close()
        self.assert_(p.checkedout() == 0)

    def test_recycle(self):
        p = self._queuepool_fixture(pool_size=1,
                           max_overflow=0,
                           recycle=3)
        c1 = p.connect()
        c_id = id(c1.connection)
        c1.close()
        c2 = p.connect()
        assert id(c2.connection) == c_id
        c2.close()
        time.sleep(4)
        c3 = p.connect()
        assert id(c3.connection) != c_id

    def test_recycle_on_invalidate(self):
        p = self._queuepool_fixture(pool_size=1,
                           max_overflow=0)
        c1 = p.connect()
        c_id = id(c1.connection)
        c1.close()
        c2 = p.connect()
        assert id(c2.connection) == c_id

        p._invalidate(c2)
        c2.close()
        time.sleep(.5)
        c3 = p.connect()
        assert id(c3.connection) != c_id

    def _assert_cleanup_on_pooled_reconnect(self, dbapi, p):
        # p is QueuePool with size=1, max_overflow=2,
        # and one connection in the pool that will need to
        # reconnect when next used (either due to recycle or invalidate)
        eq_(p.checkedout(), 0)
        eq_(p._overflow, 0)
        dbapi.shutdown(True)
        assert_raises(
            Exception,
            p.connect
        )
        eq_(p._overflow, 0)
        eq_(p.checkedout(), 0)  # and not 1

        dbapi.shutdown(False)

        c1 = p.connect()
        assert p._pool.empty()  # poolsize is one, so we're empty OK
        c2 = p.connect()
        eq_(p._overflow, 1)  # and not 2

        # this hangs if p._overflow is 2
        c3 = p.connect()

    def test_error_on_pooled_reconnect_cleanup_invalidate(self):
        dbapi, p = self._queuepool_dbapi_fixture(pool_size=1, max_overflow=2)
        c1 = p.connect()
        c1.invalidate()
        c1.close()
        self._assert_cleanup_on_pooled_reconnect(dbapi, p)

    def test_error_on_pooled_reconnect_cleanup_recycle(self):
        dbapi, p = self._queuepool_dbapi_fixture(pool_size=1,
                                        max_overflow=2, recycle=1)
        c1 = p.connect()
        c1.close()
        time.sleep(1)
        self._assert_cleanup_on_pooled_reconnect(dbapi, p)

    def test_recycle_pool_no_race(self):
        def slow_close():
            slow_closing_connection._slow_close()
            time.sleep(.5)

        slow_closing_connection = Mock()
        slow_closing_connection.connect.return_value.close = slow_close

        class Error(Exception):
            pass

        dialect = Mock()
        dialect.is_disconnect = lambda *arg, **kw: True
        dialect.dbapi.Error = Error

        pools = []
        class TrackQueuePool(pool.QueuePool):
            def __init__(self, *arg, **kw):
                pools.append(self)
                super(TrackQueuePool, self).__init__(*arg, **kw)

        def creator():
            return slow_closing_connection.connect()
        p1 = TrackQueuePool(creator=creator, pool_size=20)

        from sqlalchemy import create_engine
        eng = create_engine(testing.db.url, pool=p1, _initialize=False)
        eng.dialect = dialect

        # 15 total connections
        conns = [eng.connect() for i in range(15)]

        # return 8 back to the pool
        for conn in conns[3:10]:
            conn.close()

        def attempt(conn):
            time.sleep(random.random())
            try:
                conn._handle_dbapi_exception(Error(), "statement", {}, Mock(), Mock())
            except tsa.exc.DBAPIError:
                pass

        # run an error + invalidate operation on the remaining 7 open connections
        threads = []
        for conn in conns:
            t = threading.Thread(target=attempt, args=(conn, ))
            t.start()
            threads.append(t)

        for t in threads:
            t.join()

        # return all 15 connections to the pool
        for conn in conns:
            conn.close()

        # re-open 15 total connections
        conns = [eng.connect() for i in range(15)]

        # 15 connections have been fully closed due to invalidate
        assert slow_closing_connection._slow_close.call_count == 15

        # 15 initial connections + 15 reconnections
        assert slow_closing_connection.connect.call_count == 30
        assert len(pools) <= 2, len(pools)

    def test_invalidate(self):
        p = self._queuepool_fixture(pool_size=1, max_overflow=0)
        c1 = p.connect()
        c_id = c1.connection.id
        c1.close()
        c1 = None
        c1 = p.connect()
        assert c1.connection.id == c_id
        c1.invalidate()
        c1 = None
        c1 = p.connect()
        assert c1.connection.id != c_id

    def test_recreate(self):
        p = self._queuepool_fixture(reset_on_return=None, pool_size=1, max_overflow=0)
        p2 = p.recreate()
        assert p2.size() == 1
        assert p2._reset_on_return is pool.reset_none
        assert p2._use_threadlocal is False
        assert p2._max_overflow == 0

    def test_reconnect(self):
        """tests reconnect operations at the pool level.  SA's
        engine/dialect includes another layer of reconnect support for
        'database was lost' errors."""

        dbapi, p = self._queuepool_dbapi_fixture(pool_size=1, max_overflow=0)
        c1 = p.connect()
        c_id = c1.connection.id
        c1.close()
        c1 = None
        c1 = p.connect()
        assert c1.connection.id == c_id
        dbapi.raise_error = True
        c1.invalidate()
        c1 = None
        c1 = p.connect()
        assert c1.connection.id != c_id

    def test_detach(self):
        dbapi, p = self._queuepool_dbapi_fixture(pool_size=1, max_overflow=0)
        c1 = p.connect()
        c1.detach()
        c2 = p.connect()
        eq_(dbapi.connect.mock_calls, [call("foo.db"), call("foo.db")])

        c1_con = c1.connection
        assert c1_con is not None
        eq_(c1_con.close.call_count, 0)
        c1.close()
        eq_(c1_con.close.call_count, 1)

    def test_detach_via_invalidate(self):
        dbapi, p = self._queuepool_dbapi_fixture(pool_size=1, max_overflow=0)

        c1 = p.connect()
        c1_con = c1.connection
        c1.invalidate()
        assert c1.connection is None
        eq_(c1_con.close.call_count, 1)

        c2 = p.connect()
        assert c2.connection is not c1_con
        c2_con = c2.connection

        c2.close()
        eq_(c2_con.close.call_count, 0)

    def test_threadfairy(self):
        p = self._queuepool_fixture(pool_size=3, max_overflow=-1, use_threadlocal=True)
        c1 = p.connect()
        c1.close()
        c2 = p.connect()
        assert c2.connection is not None

class ResetOnReturnTest(PoolTestBase):
    def _fixture(self, **kw):
        dbapi = Mock()
        return dbapi, pool.QueuePool(creator=lambda: dbapi.connect('foo.db'), **kw)

    def test_plain_rollback(self):
        dbapi, p = self._fixture(reset_on_return='rollback')

        c1 = p.connect()
        c1.close()
        assert dbapi.connect().rollback.called
        assert not dbapi.connect().commit.called

    def test_plain_commit(self):
        dbapi, p = self._fixture(reset_on_return='commit')

        c1 = p.connect()
        c1.close()
        assert not dbapi.connect().rollback.called
        assert dbapi.connect().commit.called

    def test_plain_none(self):
        dbapi, p = self._fixture(reset_on_return=None)

        c1 = p.connect()
        c1.close()
        assert not dbapi.connect().rollback.called
        assert not dbapi.connect().commit.called

    def test_agent_rollback(self):
        dbapi, p = self._fixture(reset_on_return='rollback')

        class Agent(object):
            def __init__(self, conn):
                self.conn = conn

            def rollback(self):
                self.conn.special_rollback()

            def commit(self):
                self.conn.special_commit()

        c1 = p.connect()
        c1._reset_agent = Agent(c1)
        c1.close()

        assert dbapi.connect().special_rollback.called
        assert not dbapi.connect().special_commit.called

        assert not dbapi.connect().rollback.called
        assert not dbapi.connect().commit.called

        c1 = p.connect()
        c1.close()
        eq_(dbapi.connect().special_rollback.call_count, 1)
        eq_(dbapi.connect().special_commit.call_count, 0)

        assert dbapi.connect().rollback.called
        assert not dbapi.connect().commit.called

    def test_agent_commit(self):
        dbapi, p = self._fixture(reset_on_return='commit')

        class Agent(object):
            def __init__(self, conn):
                self.conn = conn

            def rollback(self):
                self.conn.special_rollback()

            def commit(self):
                self.conn.special_commit()

        c1 = p.connect()
        c1._reset_agent = Agent(c1)
        c1.close()
        assert not dbapi.connect().special_rollback.called
        assert dbapi.connect().special_commit.called

        assert not dbapi.connect().rollback.called
        assert not dbapi.connect().commit.called

        c1 = p.connect()
        c1.close()

        eq_(dbapi.connect().special_rollback.call_count, 0)
        eq_(dbapi.connect().special_commit.call_count, 1)
        assert not dbapi.connect().rollback.called
        assert dbapi.connect().commit.called

class SingletonThreadPoolTest(PoolTestBase):

    @testing.requires.threading_with_mock
    def test_cleanup(self):
        self._test_cleanup(False)

    @testing.requires.threading_with_mock
    def test_cleanup_no_gc(self):
        self._test_cleanup(True)

    def _test_cleanup(self, strong_refs):
        """test that the pool's connections are OK after cleanup() has
        been called."""

        dbapi = MockDBAPI()

        lock = threading.Lock()
        def creator():
            # the mock iterator isn't threadsafe...
            with lock:
                return dbapi.connect()
        p = pool.SingletonThreadPool(creator=creator, pool_size=3)

        if strong_refs:
            sr = set()
            def _conn():
                c = p.connect()
                sr.add(c.connection)
                return c
        else:
            def _conn():
                return p.connect()

        def checkout():
            for x in range(10):
                c = _conn()
                assert c
                c.cursor()
                c.close()
                time.sleep(.1)

        threads = []
        for i in range(10):
            th = threading.Thread(target=checkout)
            th.start()
            threads.append(th)
        for th in threads:
            th.join(join_timeout)
        assert len(p._all_conns) == 3

        if strong_refs:
            still_opened = len([c for c in sr if not c.close.call_count])
            eq_(still_opened, 3)

class AssertionPoolTest(PoolTestBase):
    def test_connect_error(self):
        dbapi = MockDBAPI()
        p = pool.AssertionPool(creator=lambda: dbapi.connect('foo.db'))
        c1 = p.connect()
        assert_raises(AssertionError, p.connect)

    def test_connect_multiple(self):
        dbapi = MockDBAPI()
        p = pool.AssertionPool(creator=lambda: dbapi.connect('foo.db'))
        c1 = p.connect()
        c1.close()
        c2 = p.connect()
        c2.close()

        c3 = p.connect()
        assert_raises(AssertionError, p.connect)

class NullPoolTest(PoolTestBase):
    def test_reconnect(self):
        dbapi = MockDBAPI()
        p = pool.NullPool(creator=lambda: dbapi.connect('foo.db'))
        c1 = p.connect()

        c1.close()
        c1 = None

        c1 = p.connect()
        c1.invalidate()
        c1 = None

        c1 = p.connect()
        dbapi.connect.assert_has_calls([
                            call('foo.db'),
                            call('foo.db')],
                            any_order=True)

class StaticPoolTest(PoolTestBase):
    def test_recreate(self):
        dbapi = MockDBAPI()
        creator = lambda: dbapi.connect('foo.db')
        p = pool.StaticPool(creator)
        p2 = p.recreate()
        assert p._creator is p2._creator

redpajama_set_name: RedPajamaGithub


text:
require_dependency "renalware/hd"
require "collection_presenter"

module Renalware
  module HD
    class TransmissionLogsController < BaseController
      include PresenterHelper
      include Pagy::Backend

      # NB be sure not to select the payload as this will slow things down.
      # The payload is loaded by clicking on a link in the table
      def index
        pagy, logs = pagy(
          TransmissionLog
            .order(created_at: :desc)
            .select(TransmissionLog.attribute_names - [:payload])
        )
        authorize logs
        render locals: { logs: logs, pagy: pagy }
      end

      def show
        log = TransmissionLog.find(params[:id])
        authorize log
        respond_to do |format|
          format.xml { render xml: log.payload, template: nil }
        end
      end
    end
  end
end


text:
package send.components;

/**
 * @deprecated
 * We should use {{@link ButtonPostback}}
 * Created by vinaymavi on 17/02/17.
 */
public class ButtonPayload {
    /**
     * Button JSON format.
     * {
     * "type":"postback",
     * "title":"Start Chatting",
     * "payload":"USER_DEFINED_PAYLOAD"
     * }
     */
    String type = new String("postback");
    String title;
    String payload;

    public ButtonPayload(String title, String payload) {
        this.title = title;
        this.payload = payload;
    }
}


text:
'use strict';

var ltx = require('ltx'),
    XmppClient = require('node-xmpp-client'),
    debug = require('debug')('gitxmpp:muc');

var XmppMuc = function (options) {
    this.options = options;
    this.nickname = options.nickname || 'bot';

    this.client = new XmppClient({
        reconnect: true,
        jid: options.jid,
        password: options.password,
        host: options.host,
        port: options.port
    });

    var self = this;
    this.client.on('online', function () {
        debug('online');

        // announce the bot
        // join room
        this.send(self.joinPresence());
        // send message
        this.send(self.roomMessage('I wait for git events and will send them to this room'));
        // leave room
        this.send(self.leavePresence());
    });

    this.client.on('error', function (err) {
        console.error(err);
    });

};

XmppMuc.prototype.generateMessage = function (eventdata) {
    var message = '';
    message += '[' + eventdata.repo.name + '] ';

    if (eventdata.type === 'push') {
        message += eventdata.user.name + ' ';

        if (eventdata.before.match(/000000/)) {
            message += 'pushed new branch #{ref} \n';
        } else if (eventdata.after.match(/000000/)) {
            message += 'removed branch #{ref} \n';
        } else {
            message += 'pushed ' + eventdata.commits.length + ' commits to ' + eventdata.ref + '. ';
            message += eventdata.compare;
        }
    } else if (eventdata.type === 'pull_request') {

        if (eventdata.user.name) {
            message += eventdata.user.name + ' ';
        } else {
            message += eventdata.user.username + ' ';
        }

        message += 'created a new pull request with ' + eventdata.commits + ' commits. ';
        message += eventdata.html_url;
    }

    return message;
};

XmppMuc.prototype.handleEvent = function (eventdata) {

    // generate text message
    var msg = this.generateMessage(eventdata);

    // join room
    this.send(this.joinPresence());
    // send message
    this.send(this.roomMessage(msg));
    // leave room
    this.send(this.leavePresence());
};

XmppMuc.prototype.clientJid = function () {
    return this.client.jid;
};

XmppMuc.prototype.roomJid = function () {
    return this.options.room;
};

XmppMuc.prototype.send = function (msg) {
    if (this.client) {
        this.client.send(msg);
    }
};

XmppMuc.prototype.joinPresence = function () {

    var presence = new ltx.Element('presence', {
        to: this.roomJid() + '/' + this.nickname,
        from: this.clientJid()
    });

    debug(presence.root().toString());

    return presence;
};

XmppMuc.prototype.leavePresence = function () {

    var presence = new ltx.Element('presence', {
        to: this.roomJid() + '/' + this.nickname,
        from: this.clientJid(),
        type: 'unavailable'
    });

    debug(presence.root().toString());

    return presence;
};

XmppMuc.prototype.roomMessage = function (msg) {
    var message = new ltx.Element('message', {
        to: this.roomJid(),
        from: this.clientJid(),
        type: 'groupchat'
    });
    message.c('body')
        .t(msg);

    debug(message.root().toString());

    return message;
};

XmppMuc.prototype.privateMessage = function (eventdata) {

    var message = new ltx.Element('message', {
        to: this.roomJid(),
        from: this.clientJid(),
        type: 'chat'
    });
    message.c('body')
        .t(this.generateMessage(eventdata));

    debug(message.root().toString());

    return message;
};

module.exports = XmppMuc;


text:
layout: post
title: She gives him a blowjob in the bath
titleinfo: pornvd
desc: Watch She gives him a blowjob in the bath. Pornhub is the ultimate xxx porn and sex site.
---

She gives him a blowjob in the bath

Watch She gives him a blowjob in the bath. Pornhub is the ultimate xxx porn and sex site.


text:
<?php

namespace Liuggio\StatsDClientBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files.
 *
 * To learn more see {@link https://symfony.com/doc/current/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    private $debug;

    public function __construct($debug)
    {
        $this->debug = $debug;
    }

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('liuggio_stats_d_client');
        $rootNode = method_exists(TreeBuilder::class, 'getRootNode') ? $treeBuilder->getRootNode() : $treeBuilder->root('liuggio_stats_d_client');

        $rootNode
          ->children()
            ->booleanNode('enable_collector')->defaultFalse()->end()
            ->arrayNode('connection')
                ->children()
                    ->scalarNode('class')->defaultValue('Liuggio\StatsdClient\Sender\SocketSender')->end()
                    ->scalarNode('debug_class')->defaultValue('Liuggio\StatsdClient\Sender\SysLogSender')->end()
                    ->scalarNode('debug')->defaultValue($this->debug)->end()
                    ->scalarNode('port')->defaultValue(8125)->end()
                    ->scalarNode('host')->defaultValue('localhost')->end()
                    ->scalarNode('reduce_packet')->defaultValue(true)->end()
                    ->scalarNode('protocol')->defaultValue('udp')->end()
                    ->scalarNode('fail_silently')->defaultValue(true)->end()
                ->end()
            ->end()
            ->arrayNode('collectors')->canBeUnset()
                ->prototype('scalar')->end()
                ->useAttributeAsKey('name')
            ->end()
            ->arrayNode('monolog')->canBeUnset()
                ->children()
                    ->scalarNode('enable')->defaultValue(false)->end()
                    ->scalarNode('prefix')->defaultValue('log')->end()
                    ->scalarNode('level')->defaultValue('warning')->end()
                    ->arrayNode('formatter')
                        ->children()
                            ->scalarNode('class')->defaultValue('Liuggio\StatsdClient\Monolog\Formatter\StatsDFormatter')->end()
                            ->scalarNode('format')->defaultValue(null)->end()
                            ->booleanNode('context_logging')->defaultValue(false)->end()
                            ->booleanNode('extra_logging')->defaultValue(false)->end()
                            ->scalarNode('words')->defaultValue(2)->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
          ->end();

        return $treeBuilder;
    }
}


text:
from bs4 import BeautifulSoup
import urllib
import re

# function to get the url input from the user
def get_user_url():
  target_url = input("Enter the URL to scrape: ")
  if target_url == "":
    raise ValueError("Input cannot be an empty string.")
  return target_url.strip()

# function to get HTML from a url and parse into sentences
def grab_and_parse_results(target_url):
  http_response = urllib.request.urlopen(target_url)
  html_soup = BeautifulSoup(http_response) # Grab the HTML from the given url address
  # Pull out only the lines that match the pattern given by the regualar expression below
  pattern = u'[\u3030-\u9FAF][\u3030-\u9FAF0-9A-Za-z\u3001\u2026 ]+[\u300D|\u3002|\uFF01|\uFF1F|\u2026]+'
  # Return a list based on a set of unique sentences only (removes duplicates)
  return list(re.findall(pattern, html_soup.decode('utf-8-sig')))

# function to run scrapper and output results
def run_scraper():
  sentences = grab_and_parse_results(get_user_url()) # Get target url, grab and parse HTML into sentences
  # print out each of the sentences to a file
  with open('ja_output.txt','w') as f:
    for sentence in sentences:
      print(sentence + '\n', f)

if __name__ == '__main__':
  run_scraper()


text:
package drt.server.feeds.lhr

import akka.NotUsed
import akka.actor.Cancellable
import akka.stream.scaladsl.Source
import com.typesafe.config.ConfigFactory
import drt.server.feeds.lhr.LHRFlightFeed.{emptyStringToOption, parseDateTime}
import org.apache.commons.csv.{CSVFormat, CSVParser, CSVRecord}
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
import org.slf4j.LoggerFactory
import drt.shared.ApiFlight

import scala.concurrent.duration._
import scala.sys.process._
import scala.util.{Failure, Success, Try}
import scala.collection.JavaConverters._

case class LHRLiveFlight(
                          term: String,
                          flightCode: String,
                          operator: String,
                          from: String,
                          airportName: String,
                          scheduled: DateTime,
                          estimated: Option[DateTime],
                          touchdown: Option[DateTime],
                          estChox: Option[DateTime],
                          actChox: Option[DateTime],
                          stand: Option[String],
                          maxPax: Option[Int],
                          actPax: Option[Int],
                          connPax: Option[Int]
                        ) {
  def flightId(): Int = {
    // flightcode,scheduled datetime and from port make the flight sufficiently unique for later parts of the pipeline
    // but we do not want to override the hashCode here because that would be surprising.
    val s = flightCode.toString + scheduled.toString + from
    s.hashCode()
  }
}

case class LHRCsvException(originalLine: String, idx: Int, innerException: Throwable) extends Exception {
  override def toString = s"$originalLine : $idx $innerException"
}

case class LHRFlightFeed(csvRecords: Iterator[(Int) => String]) {

  def opt(s: String) = emptyStringToOption(s, x => x)

  def optDate(s: String) = emptyStringToOption(s, parseDateTime(_))

  def optInt(s: String) = emptyStringToOption(s, _.toInt)

  lazy val lhrFlights: Iterator[Try[LHRLiveFlight]] = {
    csvRecords.zipWithIndex.map { case (splitRow, lineNo) =>
      val t = Try {
        val sq: (String) => String = (x) => x
        LHRLiveFlight(
          term = s"T${sq(splitRow(0))}",
          flightCode = sq(splitRow(1)),
          operator = sq(splitRow(2)),
          from = sq(splitRow(3)),
          airportName = sq(splitRow(4)),
          scheduled = parseDateTime(splitRow(5)),
          estimated = optDate(splitRow(6)),
          touchdown = optDate(splitRow(7)),
          estChox = optDate(splitRow(8)),
          actChox = optDate(sq(splitRow(9))),
          stand = opt(splitRow(10)),
          maxPax = optInt(splitRow(11)),
          actPax = optInt(splitRow(12)),
          connPax = optInt(splitRow(13)))
      }

      t match {
        case Success(s) => Success(s)
        case Failure(t) =>
          Failure(LHRCsvException("", lineNo, t))
      }
    }
  }

  val walkTimeMinutes = 4

  lazy val successfulFlights = lhrFlights.collect {
    case Success(s) => s
  }

  def dateOptToStringOrEmptyString = (dto: Option[DateTime]) => dto.map(_.toDateTimeISO.toString()).getOrElse("")

  lazy val copiedToApiFlights: Source[List[ApiFlight], NotUsed] = Source(
    List(
      successfulFlights.map(flight => {
        val pcpTime: Long = flight.scheduled.plusMinutes(walkTimeMinutes).getMillis
        val schDtIso = flight.scheduled.toDateTimeISO().toString()
        val defaultPaxPerFlight = 200
        ApiFlight(
          Operator = flight.operator,
          Status = "UNK",
          EstDT = dateOptToStringOrEmptyString(flight.estimated),
          ActDT = dateOptToStringOrEmptyString(flight.touchdown),
          EstChoxDT = dateOptToStringOrEmptyString(flight.estChox),
          ActChoxDT = dateOptToStringOrEmptyString(flight.actChox),
          Gate = "",
          Stand = flight.stand.getOrElse(""),
          MaxPax = flight.maxPax.getOrElse(-1),
          ActPax = flight.actPax.getOrElse(defaultPaxPerFlight),
          TranPax = flight.connPax.getOrElse(-1),
          RunwayID = "",
          BaggageReclaimId = "",
          FlightID = flight.flightId(),
          AirportID = "LHR",
          Terminal = flight.term,
          ICAO = flight.flightCode,
          IATA = flight.flightCode,
          Origin = flight.from,
          SchDT = schDtIso,
          PcpTime = pcpTime)
      }).toList))
}

object LHRFlightFeed {

  def csvParserAsIteratorOfColumnGetter(csvString: String) = {
    val csv: CSVParser = CSVParser.parse(csvString, CSVFormat.DEFAULT)
    val csvGetters: Iterator[(Int) => String] = csv.iterator().asScala.map((l: CSVRecord) => (i: Int) => l.get(i))
    csvGetters
  }

  def emptyStringToOption[T](s: String, t: (String) => T) = {
    if (s.isEmpty) None else Option(t(s))
  }

  def csvContentsProviderProd(): String = {
    Seq(
      "/usr/local/bin/lhr-live-fetch-latest-feed.sh",
      "-u", ConfigFactory.load.getString("lhr_live_username"),
      "-p", ConfigFactory.load.getString("lhr_live_password")).!!
  }

  val pattern: DateTimeFormatter = DateTimeFormat.forPattern("HH:mm dd/MM/YYYY")
  val log = LoggerFactory.getLogger(classOf[LHRFlightFeed])

  def parseDateTime(dateString: String) = pattern.parseDateTime(dateString)

  def apply(csvContentsProvider: () => String = csvContentsProviderProd _): Source[List[ApiFlight], Cancellable] = {
    log.info(s"preparing lhrfeed")

    val pollFrequency = 1 minute
    val initialDelayImmediately: FiniteDuration = 1 milliseconds
    val tickingSource: Source[Source[List[ApiFlight], NotUsed], Cancellable] = Source.tick(initialDelayImmediately, pollFrequency, NotUsed)
      .map((t) => {
        log.info(s"about to request csv")
        val csvContents: String = csvContentsProvider()
        log.info(s"got csv content")
        val f = LHRFlightFeed(csvParserAsIteratorOfColumnGetter(csvContents)).copiedToApiFlights
        log.info(s"copied to api flights")
        f
      })

    val recoverableTicking: Source[List[ApiFlight], Cancellable] = tickingSource.flatMapConcat(s => s.map(x => x))

    recoverableTicking
  }
}


text:
using NUnit.Framework;

namespace Ghpr.NUnitExamples.Cat1
{
    [TestFixtureSource("SomeData")]
    public class TestFixtureSourceTests3
    {
        private readonly TestDataObject2 _data;

        public TestFixtureSourceTests3(TestDataObject2 data)
        {
            _data = data;
        }

        [Test]
        public void Test()
        {
            Assert.IsTrue(_data.Field1.Equals(1));
            Assert.IsTrue(_data.Field2.Equals("1"));
        }

        public static TestDataObject2[] SomeData =
        {
            new TestDataObject2 { Field1 = 1, Field2 = "1", Field3 = new[]{0.1, 0.2}},
            new TestDataObject2 { Field1 = 2, Field2 = "2", Field3 = new[]{0.2, 0.4}},
            new TestDataObject2 { Field1 = 3, Field2 = "3", Field3 = new[]{0.3, 0.6}}
        };
    }

    //this object will give the wrong test list!
    public class TestDataObject2
    {
        public int Field1;
        public string Field2;
        public double[] Field3;
    }
}


text:
typedef void **omp_allocator_handle_t;
extern const omp_allocator_handle_t omp_default_mem_alloc;
extern const omp_allocator_handle_t omp_large_cap_mem_alloc;
extern const omp_allocator_handle_t omp_const_mem_alloc;
extern const omp_allocator_handle_t omp_high_bw_mem_alloc;
extern const omp_allocator_handle_t omp_low_lat_mem_alloc;
extern const omp_allocator_handle_t omp_cgroup_mem_alloc;
extern const omp_allocator_handle_t omp_pteam_mem_alloc;
extern const omp_allocator_handle_t omp_thread_mem_alloc;

void foo() {
}

bool foobool(int argc) {
  return argc;
}

struct S1; // expected-note {{declared here}} expected-note {{forward declaration of 'S1'}}
extern S1 a;
class S2 {
  mutable int a;
public:
  S2():a(0) { }
  static float S2s; // expected-note {{predetermined as shared}}
};
const S2 b;
const S2 ba[5];
class S3 {
  int a;
public:
  S3():a(0) { }
};
const S3 c; // expected-note {{'c' defined here}}
const S3 ca[5]; // expected-note {{'ca' defined here}}
extern const int f;  // expected-note {{'f' declared here}}
class S4 {
  int a;
  S4(); // expected-note {{implicitly declared private here}}
public:
  S4(int v):a(v) { }
};
class S5 {
  int a;
  S5():a(0) {} // expected-note {{implicitly declared private here}}
public:
  S5(int v):a(v) { }
};

S3 h;
#pragma omp threadprivate(h) // expected-note {{defined as threadprivate or thread local}}

int main(int argc, char **argv) {
  const int d = 5;  // expected-note {{'d' defined here}}
  const int da[5] = { 0 }; // expected-note {{'da' defined here}}
  S4 e(4);
  S5 g(5);
  int i;
  int &j = i;

#pragma omp target teams distribute simd private // expected-error {{expected '(' after 'private'}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private () // expected-error {{expected expression}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private (argc // expected-error {{expected ')'}} expected-note {{to match this '('}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private (argc) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private (S1) // expected-error {{'S1' does not refer to a value}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private (a, b, c, d, f) // expected-error {{private variable with incomplete type 'S1'}} expected-error 1 {{const-qualified variable without mutable fields cannot be private}} expected-error 2 {{const-qualified variable cannot be private}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private (argv[1]) // expected-error {{expected variable name}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private(ba) allocate(omp_thread_mem_alloc: ba) // expected-warning {{allocator with the 'thread' trait access has unspecified behavior on 'target teams distribute simd' directive}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private(ca) // expected-error {{const-qualified variable without mutable fields cannot be private}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private(da) // expected-error {{const-qualified variable cannot be private}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private(S2::S2s) // expected-error {{shared variable cannot be private}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private(h) // expected-error {{threadprivate or thread local variable cannot be private}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd shared(i)
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd firstprivate(i), private(i) // expected-error {{firstprivate variable cannot be private}} expected-note {{defined as firstprivate}}
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd private(j)
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp target teams distribute simd reduction(+:i)
  for (int k = 0; k < argc; ++k) ++k;

#pragma omp distribute private(i)
  for (int k = 0; k < 10; ++k) {
    #pragma omp target teams distribute simd private(i)
    for (int x = 0; x < 10; ++x) foo();
  }

#pragma omp target teams distribute simd firstprivate(i)
  for (int k = 0; k < 10; ++k) {
  }

#pragma omp target teams distribute simd private(j) map(j) // expected-error {{private variable cannot be in a map clause in '#pragma omp target teams distribute simd' directive}} expected-note {{defined as private}}
  for (int k = 0; k < argc; ++k) ++k;

  return 0;
}


text:
function clonepull {
    git clone $1 $2 || (cd $2 ; git pull) || exit 1
}

# The root dir is a level above SKA-RC root.
export MS7_DIR="`pwd`/../.."
export ROOT="`pwd`/../../../.."

# The directory to have all builds in. Easier to clean.
export BUILDDIR="$ROOT/build"
mkdir -p $BUILDDIR

# Clean the environment.
./clean-env.sh

# Going to the root.
cd $BUILDDIR

# -- GASnet --------------------------------------------------------------------
# Right now GASnet does not seem to be available in any modules on cluster.

# getting GASnet.
# TODO: make git clone/pull choice a proc.
clonepull https://github.com/thesz/GASnet.git GASnet

# Conduit selection. This variable also used in Legion build.
# TODO: move to clean-env.sh???
export CONDUIT=udp

# Build it for cluster architecture.
cd GASnet/GASNet-1.26.0

# Set configure switches based on conduit selected above.
set GASNET_CONFIGURE_OPTS=""
case $CONDUIT in
    udp) GASNET_CONFIGURE_OPTS="" ;;
    *) echo "invalid conduit $CONDUIT selected" ; exit 1 ;;
esac
./configure || exit 1
make || exit 1
cd ../..

export GASNET_BIN=$ROOT/GASnet/GASNet-1.26.0/bin

export GASNET=$ROOT/GASnet/GASNet-1.26.0

# -- LLVM ----------------------------------------------------------------------
# LLVM will be our compiler of choice for everything.

export LLVM_VER=3.5

# TODO: add a test for working LLVM in environment - cluster can have one sometimes.
wget -c http://llvm.org/releases/$LLVM_VER/llvm-$LLVM_VER.src.tar.xz || exit 1
tar xf llvm-$LLVM_VER.src.tar.xz || exit 1

# Prevent CMake compplaints.
rm -rf llvm-$LLVM_VER.src/CMakeFiles
rm -f CMakeCache.txt

wget -c http://llvm.org/releases/3.7.1/cfe-$LLVM_VER.src.tar.xz || exit 1
wget -c http://llvm.org/releases/3.7.1/compiler-rt-$LLVM_VER.src.tar.xz || exit 1
cd llvm-$LLVM_VER.src/tools
tar xf ../../cfe-$LLVM_VER.src.tar.xz
tar xf ../../compiler-rt-$LLVM_VER.src.tar.xz
cd ../..

# Perform generation of Makefiles and then make and install the LLVM.
mkdir -p llvm-build
cd llvm-build
cmake -v -G "Unix Makefiles" -DCMAKE_BUILD_TYPE="Release" -DCMAKE_INSTALL_PREFIX="$BUILDDIR/llvm" -DLLVM_BUILD_LLVM_DYLIB="1" $BUILDDIR/llvm-$LLVM_VER.src

make -j8 || exit 1
make install || exit 1

export LLVMBIN=$BUILDDIR/llvm/bin

export PATH=$LLVMBIN:$PATH

echo "LLVMBIN: $LLVMBIN"
echo "PATH: $PATH"

cd ..

# -- Terra ---------------------------------------------------------------------
# Terra also unavailable on cluster.

clonepull https://github.com/zdevito/terra.git terra

cd terra

echo "LLVM_CONFIG = $LLVMBIN/llvm-config" >Makefile.inc

make all || exit 1
cd ..

export TERRA_DIR=$BUILDDIR/terra

export TERRA_BIN=$BUILDDIR/terra/release/bin

export TERRA=$TERRA_BIN/terra

# -- Legion --------------------------------------------------------------------
# We will build Legion by compiling one of the applications.

clonepull https://github.com/thesz/legion.git Legion

# Go to Regent place.
cd Legion/language

# Running the installation, enabling the GASnet..
./install.py --with-terra=$TERRA_DIR/release --gasnet

# Run the tests.
echo "=========================================================="
echo "Running Regent tests."

./test.py -v

# Up from Regent.
cd $BUILDDIR


text:
export EDITOR=vim

export LANGUAGE=zh_TW.UTF-8
export LC_ALL=en_US.UTF-8

export PHP_ENV=DEV

export PATH=${PATH}:${HOME}/bin:${HOME}/.local/bin


text:
class AddJrcTerrestrialAreaToCountryStatistics < ActiveRecord::Migration[5.0]
  def change
    add_column :country_statistics, :jrc_terr_area, :float
  end
end


text:
  <link rel="stylesheet" href="/examples/astrojs.css" type="text/css" charset="utf-8">

Single WebFITS Instance (WebGL)


text: Implementing a few CLRS algorithms in Java from the Foundations chapter.


text:
import { Subscriber } from './subscriber.model';
export class CreateSessionModel {
    idAvailability:number;
    startDateTime:Date;
    numberOfPlayers:number;
    level:number;
    subscribers:Subscriber[];
    discounts:any[]
}


text:
package org.sakaiproject.site.tool.helper.participant.rsf;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.authz.api.Role;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.site.tool.helper.participant.impl.SiteAddParticipantHandler;
import org.sakaiproject.site.tool.helper.participant.impl.UserRoleEntry;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;

import uk.ac.cam.caret.sakai.rsf.producers.FrameAdjustingProducer;
import uk.ac.cam.caret.sakai.rsf.util.SakaiURLUtil;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.messageutil.TargettedMessage;
import uk.org.ponder.messageutil.TargettedMessageList;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.flow.ARIResult;
import uk.org.ponder.rsf.flow.ActionResultInterceptor;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.RawViewParameters;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.stringutil.StringList;

/**
 * Assign different roles while adding participant
 * @author
 *
 */
public class DifferentRoleProducer implements ViewComponentProducer, NavigationCaseReporter, ActionResultInterceptor{

	/** Our log (commons). */
	private static Log M_log = LogFactory.getLog(DifferentRoleProducer.class);

    public SiteAddParticipantHandler handler;
    public static final String VIEW_ID = "DifferentRole";
    public MessageLocator messageLocator;
    public FrameAdjustingProducer frameAdjustingProducer;
    public SessionManager sessionManager;

    private String[] roleIds;

    public SiteService siteService = null;
    public void setSiteService(SiteService siteService)
	{
		this.siteService = siteService;
	}

    public String getViewID() {
        return VIEW_ID;
    }

    private TargettedMessageList targettedMessageList;
	public void setTargettedMessageList(TargettedMessageList targettedMessageList) {
		this.targettedMessageList = targettedMessageList;
	}

	public UserDirectoryService userDirectoryService;
	public void setUserDirectoryService(UserDirectoryService userDirectoryService)
	{
		this.userDirectoryService = userDirectoryService;
	}

    public void fillComponents(UIContainer tofill, ViewParameters arg1, ComponentChecker arg2) {

    	UIBranchContainer content = UIBranchContainer.make(tofill, "content:");

		List<Role> roles = handler.getRoles();
	    StringList roleIds = new StringList();
	    int i = 0;
	    for (Role role: roles) {
	    	if (!role.isProviderOnly())
	    	{
	    		roleIds.add(role.getId());
	    		UIBranchContainer roleRow = UIBranchContainer.make(content, "role-row:", role.getId());
	            UIOutput.make(roleRow, "role-id", role.getId());
	            UIOutput.make(roleRow, "role-description", StringUtils.trimToEmpty(role.getDescription()));
	    	}
	    }

    	UIForm differentRoleForm = UIForm.make(content, "differentRole-form");
    	// csrf token
    	UIInput.make(differentRoleForm, "csrfToken", "#{siteAddParticipantHandler.csrfToken}", handler.csrfToken);

        // list of users
        String curItemNum = null;
        i = 0;
        for (Iterator<UserRoleEntry> it=handler.userRoleEntries.iterator(); it.hasNext(); i++) {
        	curItemNum = Integer.toString(i);
        	UserRoleEntry userRoleEntry = it.next();
        	String userEId = userRoleEntry.userEId;
        	// default to userEid
        	String userName = userEId;
        	String displayId = userEId;
        	// if there is last name or first name specified, use it
        	if (userRoleEntry.lastName != null && userRoleEntry.lastName.length() > 0
        			|| userRoleEntry.firstName != null && userRoleEntry.firstName.length() > 0)
        		userName = userRoleEntry.lastName + "," + userRoleEntry.firstName;
        	// get user from directory
        	try
        	{
        		User u = userDirectoryService.getUserByEid(userEId);
        		userName = u.getSortName();
        		displayId = u.getDisplayId();
        	}
        	catch (Exception e)
        	{
        		M_log.debug(this + ":fillComponents: cannot find user with eid=" + userEId);
        	}
            // SECOND LINE
            UIBranchContainer userRow = UIBranchContainer.make(differentRoleForm, "user-row:", curItemNum);
            UIOutput.make(userRow, "user-name", displayId + "(" + userName + ")");
            UISelect.make(userRow, "role-select", roleIds.toStringArray(), "siteAddParticipantHandler.userRoleEntries." + i + ".role", handler.getUserRole(userEId));

  		}

    	UICommand.make(differentRoleForm, "continue", messageLocator.getMessage("gen.continue"), "#{siteAddParticipantHandler.processDifferentRoleContinue}");
    	UICommand.make(differentRoleForm, "back", messageLocator.getMessage("gen.back"), "#{siteAddParticipantHandler.processDifferentRoleBack}");
    	UICommand.make(differentRoleForm, "cancel", messageLocator.getMessage("gen.cancel"), "#{siteAddParticipantHandler.processCancel}");

    	//process any messages
    	targettedMessageList = handler.targettedMessageList;
        if (targettedMessageList != null && targettedMessageList.size() > 0) {
			for (int ii = 0; ii < targettedMessageList.size(); ii++ ) {
				TargettedMessage msg = targettedMessageList.messageAt(i);
				if (msg.severity == TargettedMessage.SEVERITY_ERROR)
				{
					UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", Integer.valueOf(ii).toString());

			    	if (msg.args != null )
			    	{
			    		UIMessage.make(errorRow,"error", msg.acquireMessageCode(), (Object[]) msg.args);
			    	}
			    	else
			    	{
			    		UIMessage.make(errorRow,"error", msg.acquireMessageCode());
			    	}
				}
				else if (msg.severity == TargettedMessage.SEVERITY_INFO)
				{
					UIBranchContainer errorRow = UIBranchContainer.make(tofill,"info-row:", Integer.valueOf(ii).toString());

			    	if (msg.args != null )
			    	{
			    		UIMessage.make(errorRow,"info", msg.acquireMessageCode(), (Object[]) msg.args);
			    	}
			    	else
			    	{
			    		UIMessage.make(errorRow,"info", msg.acquireMessageCode());
			    	}
				}

			}
        }

    }

    public ViewParameters getViewParameters() {
    	AddViewParameters params = new AddViewParameters();

        params.id = null;
        return params;
    }

    public List<NavigationCase> reportNavigationCases() {
        List<NavigationCase> togo = new ArrayList<NavigationCase>();
        togo.add(new NavigationCase("continue", new SimpleViewParameters(EmailNotiProducer.VIEW_ID)));
        togo.add(new NavigationCase("back", new SimpleViewParameters(AddProducer.VIEW_ID)));
        return togo;
    }

    public void interceptActionResult(ARIResult result, ViewParameters incoming,
            Object actionReturn)
    {
        if ("done".equals(actionReturn)) {
          Tool tool = handler.getCurrentTool();
           result.resultingView = new RawViewParameters(SakaiURLUtil.getHelperDoneURL(tool, sessionManager));
        }
    }

}


text:
package pnb.orp.handlers;

import com.google.inject.Inject;
import com.google.inject.Injector;

import net.minecraftforge.event.ServerChatEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import pnb.orp.cache.ORPCache;

public class ChatHandler {

	private final Injector injector;
	private final ORPCache cache;

	@Inject
	private ChatHandler(Injector injector, ORPCache cache) {
		this.injector = injector;
		this.cache = cache;
	}

	@SubscribeEvent
	public void onServerChatEvent(ServerChatEvent event) {

	}

}


text:
"""
Tests For Scheduler
"""

import mock
from mox3 import mox
from oslo.config import cfg

from nova.compute import api as compute_api
from nova import context
from nova import db
from nova import exception
from nova.image import glance
from nova import rpc
from nova.scheduler import driver
from nova.scheduler import manager
from nova import servicegroup
from nova import test
from nova.tests.unit import fake_server_actions
from nova.tests.unit.image import fake as fake_image
from nova.tests.unit.objects import test_instance_fault
from nova.tests.unit.scheduler import fakes

CONF = cfg.CONF

class SchedulerManagerTestCase(test.NoDBTestCase):
    """Test case for scheduler manager."""

    manager_cls = manager.SchedulerManager
    driver_cls = driver.Scheduler
    driver_cls_name = 'nova.scheduler.driver.Scheduler'

    def setUp(self):
        super(SchedulerManagerTestCase, self).setUp()
        self.flags(scheduler_driver=self.driver_cls_name)
        self.stubs.Set(compute_api, 'API', fakes.FakeComputeAPI)
        self.manager = self.manager_cls()
        self.context = context.RequestContext('fake_user', 'fake_project')
        self.topic = 'fake_topic'
        self.fake_args = (1, 2, 3)
        self.fake_kwargs = {'cat': 'meow', 'dog': 'woof'}
        fake_server_actions.stub_out_action_events(self.stubs)

    def test_1_correct_init(self):
        # Correct scheduler driver
        manager = self.manager
        self.assertIsInstance(manager.driver, self.driver_cls)

    def _mox_schedule_method_helper(self, method_name):
        # Make sure the method exists that we're going to test call
        def stub_method(*args, **kwargs):
            pass

        setattr(self.manager.driver, method_name, stub_method)

        self.mox.StubOutWithMock(self.manager.driver,
                method_name)

    def test_select_destination(self):
        with mock.patch.object(self.manager, 'select_destinations'
                ) as select_destinations:
            self.manager.select_destinations(None, None, {})
            select_destinations.assert_called_once_with(None, None, {})

class SchedulerV3PassthroughTestCase(test.TestCase):
    def setUp(self):
        super(SchedulerV3PassthroughTestCase, self).setUp()
        self.manager = manager.SchedulerManager()
        self.proxy = manager._SchedulerManagerV3Proxy(self.manager)

    def test_select_destination(self):
        with mock.patch.object(self.manager, 'select_destinations'
                ) as select_destinations:
            self.proxy.select_destinations(None, None, {})
            select_destinations.assert_called_once_with(None, None, {})

class SchedulerTestCase(test.NoDBTestCase):
    """Test case for base scheduler driver class."""

    # So we can subclass this test and re-use tests if we need.
    driver_cls = driver.Scheduler

    def setUp(self):
        super(SchedulerTestCase, self).setUp()
        self.stubs.Set(compute_api, 'API', fakes.FakeComputeAPI)

        def fake_show(meh, context, id, **kwargs):
            if id:
                return {'id': id, 'min_disk': None, 'min_ram': None,
                        'name': 'fake_name',
                        'status': 'active',
                        'properties': {'kernel_id': 'fake_kernel_id',
                                       'ramdisk_id': 'fake_ramdisk_id',
                                       'something_else': 'meow'}}
            else:
                raise exception.ImageNotFound(image_id=id)

        fake_image.stub_out_image_service(self.stubs)
        self.stubs.Set(fake_image._FakeImageService, 'show', fake_show)
        self.image_service = glance.get_default_image_service()

        self.driver = self.driver_cls()
        self.context = context.RequestContext('fake_user', 'fake_project')
        self.topic = 'fake_topic'
        self.servicegroup_api = servicegroup.API()

    def test_hosts_up(self):
        service1 = {'host': 'host1'}
        service2 = {'host': 'host2'}
        services = [service1, service2]

        self.mox.StubOutWithMock(db, 'service_get_all_by_topic')
        self.mox.StubOutWithMock(servicegroup.API, 'service_is_up')

        db.service_get_all_by_topic(self.context,
                self.topic).AndReturn(services)
        self.servicegroup_api.service_is_up(service1).AndReturn(False)
        self.servicegroup_api.service_is_up(service2).AndReturn(True)

        self.mox.ReplayAll()
        result = self.driver.hosts_up(self.context, self.topic)
        self.assertEqual(result, ['host2'])

    def test_handle_schedule_error_adds_instance_fault(self):
        instance = {'uuid': 'fake-uuid'}
        self.mox.StubOutWithMock(db, 'instance_update_and_get_original')
        self.mox.StubOutWithMock(db, 'instance_fault_create')
        db.instance_update_and_get_original(self.context, instance['uuid'],
                                            mox.IgnoreArg()).AndReturn(
                                                (None, instance))
        db.instance_fault_create(self.context, mox.IgnoreArg()).AndReturn(
            test_instance_fault.fake_faults['fake-uuid'][0])
        self.mox.StubOutWithMock(rpc, 'get_notifier')
        notifier = self.mox.CreateMockAnything()
        rpc.get_notifier('scheduler').AndReturn(notifier)
        notifier.error(self.context, 'scheduler.run_instance', mox.IgnoreArg())
        self.mox.ReplayAll()

        driver.handle_schedule_error(self.context,
                                     exception.NoValidHost('test'),
                                     instance['uuid'], {})

class SchedulerDriverBaseTestCase(SchedulerTestCase):
    """Test cases for base scheduler driver class methods
       that will fail if the driver is changed.
    """

    def test_unimplemented_select_destinations(self):
        self.assertRaises(NotImplementedError,
                self.driver.select_destinations, self.context, {}, {})

class SchedulerInstanceGroupData(test.TestCase):

    driver_cls = driver.Scheduler

    def setUp(self):
        super(SchedulerInstanceGroupData, self).setUp()
        self.user_id = 'fake_user'
        self.project_id = 'fake_project'
        self.context = context.RequestContext(self.user_id, self.project_id)
        self.driver = self.driver_cls()

    def _get_default_values(self):
        return {'name': 'fake_name',
                'user_id': self.user_id,
                'project_id': self.project_id}

    def _create_instance_group(self, context, values, policies=None,
                               metadata=None, members=None):
        return db.instance_group_create(context, values, policies=policies,
                                        metadata=metadata, members=members)


text:
apetools.commons.centraltendency.CentralTendency.percentile
===========================================================

.. currentmodule:: apetools.commons.centraltendency

.. automethod:: CentralTendency.percentile


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>A Client-Server</title>

Chat

<form method="Get" id="chatForm">
  Message: <input type="text" name="message" id="message" value="Hello World">
  <input type="submit" value="Submit">
</form>

More Info


text:
'use strict';

var Counter = function() {
	var o = Object.create(Methods);
	o.count = 0;

	return o;
};

var Methods = {};
Methods.inc = function() {
	this.count++;
};
Methods.print = function() {
	console.log(this.count);
};

var c = Counter();
c.print();
// OUTPUT: 0
c.inc();
c.inc();
c.print();
// OUTPUT: 2