text:
from pyquery import PyQuery
from Cookie import SimpleCookie

from django.core.urlresolvers import reverse as urlreverse

import debug                            # pyflakes:ignore

from ietf.utils.test_data import make_test_data
from ietf.utils.test_utils import TestCase

class CookieTests(TestCase):
    def test_settings_defaults(self):
        make_test_data()
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])

    def test_settings_defaults_from_cookies(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '7', 'expires_soon' : 7, 'left_menu': 'on', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/7"]').contents(),    ['7 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/7"]').contents(),  ['7 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])

    def test_settings_values_from_cookies_garbage(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'foo', 'new_enough' : 'foo', 'expires_soon' : 'foo', 'left_menu': 'foo', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])

    def test_settings_values_from_cookies_random(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'zappa', 'new_enough' : '365', 'expires_soon' : '5', 'left_menu': 'zappa', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href^="/accounts/settings/new_enough/"]').contents(),    [])
        self.assertEqual(q('div a.active[href^="/accounts/settings/expires_soon/"]').contents(),  [])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])

#
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertNotRegexpMatches(r.content, r'ietf-highlight-y.*new_enough')
#         self.assertNotRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon')

    def test_settings_values_from_cookies_1(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'new_enough' : '90', 'expires_soon' : 7, 'left_menu': 'off', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/90"]').contents(),   ['90 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/7"]').contents(), ['7 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/off"]').contents(),    ['Off'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*90 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*7 days')

    def test_settings_values_from_cookies_2(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '60', 'expires_soon' : 14, 'left_menu': 'on', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/60"]').contents(),   ['60 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*60 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*14 days')

    def test_settings_values_from_cookies_3(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'new_enough' : '30', 'expires_soon' : 21, 'left_menu': 'off'})
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/30"]').contents(),   ['30 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/21"]').contents(), ['21 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/off"]').contents(),    ['Off'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*30 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*21 days')

    def test_settings_values_from_cookies_4(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '21', 'expires_soon' : 30, 'left_menu': 'on', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/21"]').contents(),   ['21 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/30"]').contents(), ['30 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*21 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*30 days')

    def test_settings_values_from_cookies_5(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'new_enough' : '14', 'expires_soon' : 60, 'left_menu': 'off', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/60"]').contents(), ['60 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/off"]').contents(),    ['Off'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*14 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*60 days')

    def test_settings_values_from_cookies_6(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '7', 'expires_soon' : 90, 'left_menu': 'on', })
        r = self.client.get(urlreverse("ietf.cookies.views.preferences"))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/7"]').contents(),   ['7 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/90"]').contents(), ['90 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*7 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*90 days')

    def test_full_draft(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.full_draft")) # no value: reset
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['full_draft'].value, '')
        self.assertListEqual(['full_draft'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*14 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*14 days')

    def test_full_draft_on(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.full_draft", kwargs=dict(enabled="on")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['full_draft'].value, 'on')
        self.assertListEqual(['full_draft'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')

    def test_full_draft_off(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.full_draft", kwargs=dict(enabled="off")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['full_draft'].value, 'off')
        self.assertListEqual(['full_draft'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
#        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
#        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
#        self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')

    def test_full_draft_foo(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.full_draft", kwargs=dict(enabled="foo")))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
#        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
#        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
#        self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')

    def test_left_menu(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14, 'left_menu': 'off', })
        r = self.client.get(urlreverse("ietf.cookies.views.left_menu")) # no value: reset
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['left_menu'].value, '')
        self.assertListEqual(['left_menu'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),    ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])

    def test_left_menu_on(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14, 'left_menu': 'off', })
        r = self.client.get(urlreverse("ietf.cookies.views.left_menu", kwargs=dict(enabled="on")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['left_menu'].value, 'on')
        self.assertListEqual(['left_menu'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/on"]').contents(),  ['On'])

    def test_left_menu_off(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14, 'left_menu': 'off', })
        r = self.client.get(urlreverse("ietf.cookies.views.left_menu", kwargs=dict(enabled="off")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['left_menu'].value, 'off')
        self.assertListEqual(['left_menu'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/off"]').contents(),  ['Off'])

    def test_left_menu_foo(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14, 'left_menu': 'off', })
        r = self.client.get(urlreverse("ietf.cookies.views.left_menu", kwargs=dict(enabled="foo")))
        self.assertEqual(r.status_code, 200)
        self.assertListEqual([], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/left_menu/off"]').contents(),  ['Off'])

    def test_new_enough(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.new_enough")) # no value: reset
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['new_enough'].value, '')
        self.assertListEqual(['new_enough'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*14 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*14 days')

    def test_new_enough_7(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'new_enough' : '14', 'expires_soon' : 21})
        r = self.client.get(urlreverse("ietf.cookies.views.new_enough", kwargs=dict(days="7")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['new_enough'].value, '7')
        self.assertListEqual(['new_enough'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/7"]').contents(),   ['7 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/21"]').contents(), ['21 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*7 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*21 days')

    def test_new_enough_14(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'new_enough' : '7', 'expires_soon' : 99})
        r = self.client.get(urlreverse("ietf.cookies.views.new_enough", kwargs=dict(days="14")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['new_enough'].value, '14')
        self.assertListEqual(['new_enough'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href^="/accounts/settings/expires_soon/14"]').contents(), [])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*14 days')
#         self.assertNotRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon')

    def test_new_enough_21(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'new_enough' : '14', 'expires_soon' : 90})
        r = self.client.get(urlreverse("ietf.cookies.views.new_enough", kwargs=dict(days="21")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['new_enough'].value, '21')
        self.assertListEqual(['new_enough'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/21"]').contents(),   ['21 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/90"]').contents(), ['90 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*21 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*90 days')

    def test_new_enough_30(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 7})
        r = self.client.get(urlreverse("ietf.cookies.views.new_enough", kwargs=dict(days="30")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['new_enough'].value, '30')
        self.assertListEqual(['new_enough'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/30"]').contents(),   ['30 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/7"]').contents(),  ['7 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*30 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*7 days')

    def test_new_enough_60(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '14', 'expires_soon' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.new_enough", kwargs=dict(days="60")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['new_enough'].value, '60')
        self.assertListEqual(['new_enough'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/60"]').contents(),   ['60 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*60 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*14 days')

    def test_new_enough_90(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'new_enough' : '22', 'expires_soon' : 60})
        r = self.client.get(urlreverse("ietf.cookies.views.new_enough", kwargs=dict(days="90")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['new_enough'].value, '90')
        self.assertListEqual(['new_enough'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/90"]').contents(),   ['90 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/60"]').contents(), ['60 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*90 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*60 days')

    def test_expires_soon(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'expires_soon' : '14', 'new_enough' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.expires_soon")) # no value: reset
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['expires_soon'].value, '')
        self.assertListEqual(['expires_soon'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(), ['14 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*14 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*14 days')

    def test_expires_soon_7(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'expires_soon' : '14', 'new_enough' : 21})
        r = self.client.get(urlreverse("ietf.cookies.views.expires_soon", kwargs=dict(days="7")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['expires_soon'].value, '7')
        self.assertListEqual(['expires_soon'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/21"]').contents(),   ['21 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/7"]').contents(), ['7 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*7 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*21 days')

    def test_expires_soon_14(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'expires_soon' : '7', 'new_enough' : 99})
        r = self.client.get(urlreverse("ietf.cookies.views.expires_soon", kwargs=dict(days="14")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['expires_soon'].value, '14')
        self.assertListEqual(['expires_soon'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href^="/accounts/settings/new_enough/"]').contents(),   [])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/14"]').contents(),['14 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*14 days')
#         self.assertNotRegexpMatches(r.content, r'ietf-highlight-y.*new_enough')

    def test_expires_soon_21(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'on', 'expires_soon' : '14', 'new_enough' : 90})
        r = self.client.get(urlreverse("ietf.cookies.views.expires_soon", kwargs=dict(days="21")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['expires_soon'].value, '21')
        self.assertListEqual(['expires_soon'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/on"]').contents(),  ['On'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/90"]').contents(),   ['90 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/21"]').contents(), ['21 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*on')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*21 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*90 days')

    def test_expires_soon_30(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'expires_soon' : '14', 'new_enough' : 7})
        r = self.client.get(urlreverse("ietf.cookies.views.expires_soon", kwargs=dict(days="30")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['expires_soon'].value, '30')
        self.assertListEqual(['expires_soon'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/7"]').contents(),   ['7 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/30"]').contents(), ['30 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*30 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*7 days')

    def test_expires_soon_60(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'expires_soon' : '14', 'new_enough' : 14})
        r = self.client.get(urlreverse("ietf.cookies.views.expires_soon", kwargs=dict(days="60")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['expires_soon'].value, '60')
        self.assertListEqual(['expires_soon'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/14"]').contents(),   ['14 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/60"]').contents(), ['60 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*60 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*14 days')

    def test_expires_soon_90(self):
        make_test_data()
        self.client.cookies = SimpleCookie({'full_draft': 'off', 'expires_soon' : '22', 'new_enough' : 60})
        r = self.client.get(urlreverse("ietf.cookies.views.expires_soon", kwargs=dict(days="90")))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.cookies['expires_soon'].value, '90')
        self.assertListEqual(['expires_soon'], r.cookies.keys())
        q = PyQuery(r.content)
        self.assertEqual(q('div a.active[href="/accounts/settings/full_draft/off"]').contents(),  ['Off'])
        self.assertEqual(q('div a.active[href="/accounts/settings/new_enough/60"]').contents(),   ['60 days'])
        self.assertEqual(q('div a.active[href="/accounts/settings/expires_soon/90"]').contents(), ['90 days'])
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*full_draft.*off')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*expires_soon.*90 days')
#         self.assertRegexpMatches(r.content, r'ietf-highlight-y.*new_enough.*60 days')


text:
package com.codamasters.client;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.codamasters.LittleNibolas;
import com.codamasters.LNHelpers.ActionResolverDesktop;

public class HtmlLauncher extends GwtApplication {

        @Override
        public GwtApplicationConfiguration getConfig () {
                return new GwtApplicationConfiguration(480, 320);
        }

        @Override
        public ApplicationListener getApplicationListener () {
                return new LittleNibolas(new ActionResolverDesktop());
        }
}

redpajama_set_name: RedPajamaGithub


text:
import esgfpid.rabbit.rabbit
import logging
import time
import datetime

TESTVALUES_REAL = dict(
    url_messaging_service='handle-esgf.dkrz.de',
    messaging_exchange='rabbitsender_integration_tests',
    exchange_no_queue='rabbitsender_integration_tests_no_queue',
    exchange_name='rabbitsender_integration_tests', # TODO JUST ONE NAME!
    rabbit_username='sendertests',
    rabbit_password='testmebaby',
    routing_key='test_routing_key',
)

#logging.basicConfig(level=logging.DEBUG)
logdate = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
FORMAT = "%(asctime)-15s %(levelname)s:%(name)s:%(message)s"
logging.basicConfig(level=logging.DEBUG, filename='test_log_'+logdate+'.log', filemode='w', format=FORMAT)
logging.getLogger('esgfpid.rabbit.asynchronous.thread_builder').setLevel(logging.DEBUG)
logging.getLogger('pika').setLevel(logging.DEBUG)

# Test variables:
routing_key = TESTVALUES_REAL['routing_key']
num_messages = 15

# Make connection:
#testrabbit = self.make_rabbit_with_access()
testrabbit = esgfpid.rabbit.rabbit.RabbitMessageSender(
      exchange_name=TESTVALUES_REAL['exchange_name'],
      urls_fallback=TESTVALUES_REAL['url_messaging_service'],
      url_preferred=None,
      username=TESTVALUES_REAL['rabbit_username'],
      password=TESTVALUES_REAL['rabbit_password'],
)
testrabbit.start()

# Run code to be tested:
for i in range(num_messages):
      print("Publishing message %i..." % i)
      testrabbit.send_message_to_queue({"stuffee":"foo"+str(i+1),"ROUTING_KEY":routing_key})
      print("Publishing message %i... done." % i)
      if i==2:
        print('Please reboot server now.')
      time.sleep(3)

# Close connection after some time:
#print('Wait to close... 1')
#time.sleep(5)
print('Try to close... 1')
testrabbit.finish()

# Check result:
leftovers = testrabbit.get_leftovers()
if not len(leftovers)==0:
      print('There is leftovers: '+str(len(leftovers)))
if not testrabbit.is_finished():
      print('Thread is still alive.')

# Close connection after some time:
print('Wait to close... 2')
time.sleep(5)
print('Try to close... 2')
testrabbit.finish()

# Check result:
leftovers = testrabbit.get_leftovers()
if not len(leftovers)==0:
      print('There is leftovers: '+str(len(leftovers)))
if not testrabbit.is_finished():
      print('Thread is still alive.')

# Close connection after some time:
print('Wait to close... 2')
time.sleep(5)
print('Try to force-close... 2')
testrabbit.force_finish()
print('Force-close done')

# Check result:
leftovers = testrabbit.get_leftovers()
if not len(leftovers)==0:
      print('There is leftovers: '+str(len(leftovers)))
if not testrabbit.is_finished():
      print('Thread is still alive.')


text:
package org.postgresql.xa;

import org.postgresql.PGConnection;
import org.postgresql.ds.PGPooledConnection;
import org.postgresql.core.BaseConnection;
import org.postgresql.core.ProtocolConnection;
import org.postgresql.core.Logger;
import org.postgresql.util.GT;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;

import javax.sql.*;
import java.sql.*;
import java.util.*;
import java.lang.reflect.*;
import javax.transaction.xa.Xid;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.XAException;

/**
 * The PostgreSQL implementation of {@link XAResource}.
 *
 * This implementation doesn't support transaction interleaving
 * (see JTA specification, section 3.4.4) and suspend/resume.
 *
 * Two-phase commit requires PostgreSQL server version 8.1
 * or higher.
 *
 * @author Heikki Linnakangas (heikki.linnakangas@iki.fi)
 */
public class PGXAConnection extends PGPooledConnection implements XAConnection, XAResource
{
    /**
     * Underlying physical database connection. It's used for issuing PREPARE TRANSACTION/
     * COMMIT PREPARED/ROLLBACK PREPARED commands.
     */
    private final BaseConnection conn;
    private final Logger logger;

    /*
     * PGXAConnection-object can be in one of three states:
     *
     * IDLE
     * Not associated with a XA-transaction. You can still call
     * getConnection and use the connection outside XA. currentXid is null.
     * autoCommit is true on a connection by getConnection, per normal JDBC
     * rules, though the caller can change it to false and manage transactions
     * itself using Connection.commit and rollback.
     *
     * ACTIVE
     * start has been called, and we're associated with an XA transaction.
     * currentXid is valid. autoCommit is false on a connection returned by
     * getConnection, and should not be messed with by the caller or the XA
     * transaction will be broken.
     *
     * ENDED
     * end has been called, but the transaction has not yet been prepared.
     * currentXid is still valid. You shouldn't use the connection for anything
     * else than issuing a XAResource.commit or rollback.
     */
    private Xid currentXid;

    private int state;

    private static final int STATE_IDLE = 0;
    private static final int STATE_ACTIVE = 1;
    private static final int STATE_ENDED = 2;

    /*
     * When an XA transaction is started, we put the underlying connection
     * into non-autocommit mode. The old setting is saved in
     * localAutoCommitMode, so that we can restore it when the XA transaction
     * ends and the connection returns into local transaction mode.
     */
    private boolean localAutoCommitMode = true;

    private void debug(String s) {
        logger.debug("XAResource " + Integer.toHexString(this.hashCode()) + ": " + s);
    }

    public PGXAConnection(BaseConnection conn) throws SQLException
    {
        super(conn, true, true);
        this.conn = conn;
        this.state = STATE_IDLE;
	this.logger = conn.getLogger();
    }

    /**** XAConnection interface ****/

    public Connection getConnection() throws SQLException
    {
        if (logger.logDebug())
            debug("PGXAConnection.getConnection called");

        Connection conn = super.getConnection();

        // When we're outside an XA transaction, autocommit
        // is supposed to be true, per usual JDBC convention.
        // When an XA transaction is in progress, it should be
        // false.
        if(state == STATE_IDLE)
            conn.setAutoCommit(true);

        /*
         * Wrap the connection in a proxy to forbid application from
         * fiddling with transaction state directly during an XA transaction
         */
        ConnectionHandler handler = new ConnectionHandler(conn);
        return (Connection)Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Connection.class, PGConnection.class}, handler);
    }

    public XAResource getXAResource() {
        return this;
    }

    /*
     * A java.sql.Connection proxy class to forbid calls to transaction
     * control methods while the connection is used for an XA transaction.
     */
    private class ConnectionHandler implements InvocationHandler
    {
	private Connection con;

	public ConnectionHandler(Connection con)
	{
            this.con = con;
        }

        public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable
        {
	    if (state != STATE_IDLE)
            {
                String methodName = method.getName();
                if (methodName.equals("commit") ||
                    methodName.equals("rollback") ||
                    methodName.equals("setSavePoint") ||
                    (methodName.equals("setAutoCommit") && ((Boolean) args[0]).booleanValue()))
                {
		    throw new PSQLException(GT.tr("Transaction control methods setAutoCommit(true), commit, rollback and setSavePoint not allowed while an XA transaction is active."),
					    PSQLState.OBJECT_NOT_IN_STATE);
                }
            }
            try {
                return method.invoke(con, args);
            } catch (InvocationTargetException ex) {
                throw ex.getTargetException();
            }
        }
    }

    /**** XAResource interface ****/

    /**
     * Preconditions:
     * 1. flags must be one of TMNOFLAGS, TMRESUME or TMJOIN
     * 2. xid != null
     * 3. connection must not be associated with a transaction
     * 4. the TM hasn't seen the xid before
     *
     * Implementation deficiency preconditions:
     * 1. TMRESUME not supported.
     * 2. if flags is TMJOIN, we must be in ended state,
     *    and xid must be the current transaction
     * 3. unless flags is TMJOIN, previous transaction using the
     *    connection must be committed or prepared or rolled back
     *
     * Postconditions:
     * 1. Connection is associated with the transaction
     */
    public void start(Xid xid, int flags) throws XAException {
        if (logger.logDebug())
            debug("starting transaction xid = " + xid);

        // Check preconditions
        if (flags != XAResource.TMNOFLAGS && flags != XAResource.TMRESUME && flags != XAResource.TMJOIN)
            throw new PGXAException(GT.tr("Invalid flags"), XAException.XAER_INVAL);

        if (xid == null)
            throw new PGXAException(GT.tr("xid must not be null"), XAException.XAER_INVAL);

        if (state == STATE_ACTIVE)
            throw new PGXAException(GT.tr("Connection is busy with another transaction"), XAException.XAER_PROTO);

        // We can't check precondition 4 easily, so we don't. Duplicate xid will be catched in prepare phase.

        // Check implementation deficiency preconditions
        if (flags == TMRESUME)
            throw new PGXAException(GT.tr("suspend/resume not implemented"), XAException.XAER_RMERR);

        // It's ok to join an ended transaction. WebLogic does that.
        if (flags == TMJOIN)
        {
            if (state != STATE_ENDED)
                throw new PGXAException(GT.tr("Transaction interleaving not implemented"), XAException.XAER_RMERR);

            if (!xid.equals(currentXid))
                throw new PGXAException(GT.tr("Transaction interleaving not implemented"), XAException.XAER_RMERR);
        } else if(state == STATE_ENDED)
            throw new PGXAException(GT.tr("Transaction interleaving not implemented"), XAException.XAER_RMERR);

        try
        {
            localAutoCommitMode = conn.getAutoCommit();
            conn.setAutoCommit(false);
        }
        catch (SQLException ex)
        {
            throw new PGXAException(GT.tr("Error disabling autocommit"), ex, XAException.XAER_RMERR);
        }

        // Preconditions are met, Associate connection with the transaction
        state = STATE_ACTIVE;
        currentXid = xid;
    }

    /**
     * Preconditions:
     * 1. Flags is one of TMSUCCESS, TMFAIL, TMSUSPEND
     * 2. xid != null
     * 3. Connection is associated with transaction xid
     *
     * Implementation deficiency preconditions:
     * 1. Flags is not TMSUSPEND
     *
     * Postconditions:
     * 1. connection is disassociated from the transaction.
     */
    public void end(Xid xid, int flags) throws XAException {
        if (logger.logDebug())
            debug("ending transaction xid = " + xid);

        // Check preconditions

        if (flags != XAResource.TMSUSPEND && flags != XAResource.TMFAIL && flags != XAResource.TMSUCCESS)
            throw new PGXAException(GT.tr("Invalid flags"), XAException.XAER_INVAL);

        if (xid == null)
            throw new PGXAException(GT.tr("xid must not be null"), XAException.XAER_INVAL);

        if (state != STATE_ACTIVE || !currentXid.equals(xid))
            throw new PGXAException(GT.tr("tried to call end without corresponding start call"), XAException.XAER_PROTO);

        // Check implementation deficiency preconditions
        if (flags == XAResource.TMSUSPEND)
            throw new PGXAException(GT.tr("suspend/resume not implemented"), XAException.XAER_RMERR);

        // We ignore TMFAIL. It's just a hint to the RM. We could roll back immediately
        // if TMFAIL was given.

        // All clear. We don't have any real work to do.
        state = STATE_ENDED;
    }

    /**
     * Preconditions:
     * 1. xid != null
     * 2. xid is in ended state
     *
     * Implementation deficiency preconditions:
     * 1. xid was associated with this connection
     *
     * Postconditions:
     * 1. Transaction is prepared
     */
    public int prepare(Xid xid) throws XAException {
        if (logger.logDebug())
            debug("preparing transaction xid = " + xid);

        // Check preconditions
        if (!currentXid.equals(xid))
        {
            throw new PGXAException(GT.tr("Not implemented: Prepare must be issued using the same connection that started the transaction"),
                                    XAException.XAER_RMERR);
        }
        if (state != STATE_ENDED)
            throw new PGXAException(GT.tr("Prepare called before end"), XAException.XAER_INVAL);

        state = STATE_IDLE;
        currentXid = null;

        if (!conn.haveMinimumServerVersion("8.1"))
            throw new PGXAException(GT.tr("Server versions prior to 8.1 do not support two-phase commit."), XAException.XAER_RMERR);

        try
        {
            String s = RecoveredXid.xidToString(xid);

            Statement stmt = conn.createStatement();
            try
            {
                stmt.executeUpdate("PREPARE TRANSACTION '" + s + "'");
            }
            finally
            {
                stmt.close();
            }
            conn.setAutoCommit(localAutoCommitMode);

            return XA_OK;
        }
        catch (SQLException ex)
        {
            throw new PGXAException(GT.tr("Error preparing transaction"), ex, XAException.XAER_RMERR);
        }
    }

    /**
     * Preconditions:
     * 1. flag must be one of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS or TMSTARTTRSCAN | TMENDRSCAN
     * 2. if flag isn't TMSTARTRSCAN or TMSTARTRSCAN | TMENDRSCAN, a recovery scan must be in progress
     *
     * Postconditions:
     * 1. list of prepared xids is returned
     */
    public Xid[] recover(int flag) throws XAException {
        // Check preconditions
        if (flag != TMSTARTRSCAN && flag != TMENDRSCAN && flag != TMNOFLAGS && flag != (TMSTARTRSCAN | TMENDRSCAN))
            throw new PGXAException(GT.tr("Invalid flag"), XAException.XAER_INVAL);

        // We don't check for precondition 2, because we would have to add some additional state in
        // this object to keep track of recovery scans.

        // All clear. We return all the xids in the first TMSTARTRSCAN call, and always return
        // an empty array otherwise.
        if ((flag & TMSTARTRSCAN) == 0)
            return new Xid[0];
        else
        {
            try
            {
                Statement stmt = conn.createStatement();
                try
                {
                    // If this connection is simultaneously used for a transaction,
                    // this query gets executed inside that transaction. It's OK,
                    // except if the transaction is in abort-only state and the
                    // backed refuses to process new queries. Hopefully not a problem
                    // in practise.
                    ResultSet rs = stmt.executeQuery("SELECT gid FROM pg_prepared_xacts");
                    LinkedList l = new LinkedList();
                    while (rs.next())
                    {
                        Xid recoveredXid = RecoveredXid.stringToXid(rs.getString(1));
                        if (recoveredXid != null)
                            l.add(recoveredXid);
                    }
                    rs.close();

                    return (Xid[]) l.toArray(new Xid[l.size()]);
                }
                finally
                {
                    stmt.close();
                }
            }
            catch (SQLException ex)
            {
                throw new PGXAException(GT.tr("Error during recover"), ex, XAException.XAER_RMERR);
            }
        }
    }

    /**
     * Preconditions:
     * 1. xid is known to the RM or it's in prepared state
     *
     * Implementation deficiency preconditions:
     * 1. xid must be associated with this connection if it's not in prepared state.
     *
     * Postconditions:
     * 1. Transaction is rolled back and disassociated from connection
     */
    public void rollback(Xid xid) throws XAException {
        if (logger.logDebug())
            debug("rolling back xid = " + xid);

        // We don't explicitly check precondition 1.

        try
        {
            if (currentXid != null && xid.equals(currentXid))
            {
                state = STATE_IDLE;
                currentXid = null;
                conn.rollback();
                conn.setAutoCommit(localAutoCommitMode);
            }
            else
            {
                String s = RecoveredXid.xidToString(xid);

                conn.setAutoCommit(true);
                Statement stmt = conn.createStatement();
                try
                {
                    stmt.executeUpdate("ROLLBACK PREPARED '" + s + "'");
                }
                finally
                {
                    stmt.close();
                }
            }
        }
        catch (SQLException ex)
        {
            throw new PGXAException(GT.tr("Error rolling back prepared transaction"), ex, XAException.XAER_RMERR);
        }
    }

    public void commit(Xid xid, boolean onePhase) throws XAException {
        if (logger.logDebug())
            debug("committing xid = " + xid + (onePhase ? " (one phase) " : " (two phase)"));

        if (xid == null)
            throw new PGXAException(GT.tr("xid must not be null"), XAException.XAER_INVAL);

        if (onePhase)
            commitOnePhase(xid);
        else
            commitPrepared(xid);
    }

    /**
     * Preconditions:
     * 1. xid must in ended state.
     *
     * Implementation deficiency preconditions:
     * 1. this connection must have been used to run the transaction
     *
     * Postconditions:
     * 1. Transaction is committed
     */
    private void commitOnePhase(Xid xid) throws XAException {
        try
        {
            // Check preconditions
            if (currentXid == null || !currentXid.equals(xid))
            {
                // In fact, we don't know if xid is bogus, or if it just wasn't associated with this connection.
                // Assume it's our fault.
                throw new PGXAException(GT.tr("Not implemented: one-phase commit must be issued using the same connection that was used to start it"),
                                        XAException.XAER_RMERR);
            }
            if (state != STATE_ENDED)
                throw new PGXAException(GT.tr("commit called before end"), XAException.XAER_PROTO);

            // Preconditions are met. Commit
            state = STATE_IDLE;
            currentXid = null;

            conn.commit();
            conn.setAutoCommit(localAutoCommitMode);
        }
        catch (SQLException ex)
        {
            throw new PGXAException(GT.tr("Error during one-phase commit"), ex, XAException.XAER_RMERR);
        }
    }

    /**
     * Preconditions:
     * 1. xid must be in prepared state in the server
     *
     * Implementation deficiency preconditions:
     * 1. Connection must be in idle state
     *
     * Postconditions:
     * 1. Transaction is committed
     */
    private void commitPrepared(Xid xid) throws XAException {
        try
        {
            // Check preconditions. The connection mustn't be used for another
            // other XA or local transaction, or the COMMIT PREPARED command
            // would mess it up.
            if (state != STATE_IDLE || conn.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
                throw new PGXAException(GT.tr("Not implemented: 2nd phase commit must be issued using an idle connection"),
                                        XAException.XAER_RMERR);

            String s = RecoveredXid.xidToString(xid);

            localAutoCommitMode = conn.getAutoCommit();
            conn.setAutoCommit(true);
            Statement stmt = conn.createStatement();
            try
            {
                stmt.executeUpdate("COMMIT PREPARED '" + s + "'");
            }
            finally
            {
                stmt.close();
                conn.setAutoCommit(localAutoCommitMode);
            }
        }
        catch (SQLException ex)
        {
            throw new PGXAException(GT.tr("Error committing prepared transaction"), ex, XAException.XAER_RMERR);
        }
    }

    public boolean isSameRM(XAResource xares) throws XAException {
        // This trivial implementation makes sure that the
        // application server doesn't try to use another connection
        // for prepare, commit and rollback commands.
        return xares == this;
    }

    /**
     * Does nothing, since we don't do heuristics,
     */
    public void forget(Xid xid) throws XAException {
        throw new PGXAException(GT.tr("Heuristic commit/rollback not supported"), XAException.XAER_NOTA);
    }

    /**
     * We don't do transaction timeouts. Just returns 0.
     */
    public int getTransactionTimeout() {
        return 0;
    }

    /**
     * We don't do transaction timeouts. Returns false.
     */
    public boolean setTransactionTimeout(int seconds) {
        return false;
    }
}


text:
<?php

use yii\helpers\Url as Url;
use app\tests\fixtures\PostFixture;

class ContactCest
{
    public function _fixtures()
    {
        return ['posts' => PostFixture::className()];
    }

    public function _before(AcceptanceTester $I)
    {
        $I->amOnPage(Url::toRoute('/site/contact'));
    }

    public function contactPageWorks(AcceptanceTester $I)
    {
        $I->wantTo('ensure that contact page works');
        $I->see('Contact Company Name', 'h1');
    }

    public function contactFormCanBeSubmitted(AcceptanceTester $I)
    {
        $I->amGoingTo('submit contact form with correct data');
        $I->fillField('#contactform-name', 'tester');
        $I->fillField('#contactform-email', 'tester@example.com');
        $I->fillField('#contactform-subject', 'test subject');
        $I->fillField('#contactform-body', 'test content');
        $I->fillField('#contactform-verifycode', 'testme');

        $I->click('contact-button');

        $I->wait(2); // wait for button to be clicked

        $I->dontSeeElement('#contact-form');
        $I->see('Thank you for contacting us. We will respond to you as soon as possible.');
    }
}


text:
class PWSWeather: public WeatherSink
{
public:
   PWSWeather( Config cfg, WeatherData *wd );
   ~PWSWeather();

   void newData();
   void main();

   static size_t curl_write( void *buffer, size_t size, size_t nmemb, void* userp );

private:
   bool appendData( const char * format, WeatherData::PROPERTY, float divider = 1 );
   void generatePacket( void );
   void uploadPacket( void );

private:
   pthread_mutex_t notify;
   CURL *curl;
   CURLcode res;
   int failureCount;
   float updateFrequency;
   Now uploadTime;

   char curlErrorBuf[CURL_ERROR_SIZE];
   char uploadString[PWSWEATHER_STRING_SIZE];
};

#endif //__PWSWeather_H__
#ifndef __PWSWeather_H__
#define __PWSWeather_H__
#include "WeatherSink.h"
#include <curl/curl.h>

#define PWSWEATHER_STRING_SIZE (512)
#define PWSWEATHER_RT_URL "http://www.pwsweather.com/pwsupdate/pwsupdate.php"

class PWSWeather: public WeatherSink
{
public:
   PWSWeather( Config cfg, WeatherData *wd );
   ~PWSWeather();

   void newData();
   void main();

   static size_t curl_write( void *buffer, size_t size, size_t nmemb, void* userp );

private:
   bool appendData( const char * format, WeatherData::PROPERTY, float divider = 1 );
   void generatePacket( void );
   void uploadPacket( void );

private:
   pthread_mutex_t notify;
   CURL *curl;
   CURLcode res;
   int failureCount;
   float updateFrequency;
   Now uploadTime;

   char curlErrorBuf[CURL_ERROR_SIZE];
   char uploadString[PWSWEATHER_STRING_SIZE];
};

#endif //__PWSWeather_H__


text:
(function() {
  // Reference your test modules here
  var testModules = [
    'components/home-page'
  ];

  // After the 'jasmine-boot' module creates the Jasmine environment, load all test modules then run them
  require(['jasmine-boot'], function () {
  	var modulesCorrectedPaths = testModules.map(function(m) { return '../test/' + m; });
    require(modulesCorrectedPaths, window.onload);
  });
})();


text:
package model;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author christophermortensen
 */
@Entity
@Table(name = "CATEGORY")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c")
    , @NamedQuery(name = "Category.findByCategoryId", query = "SELECT c FROM Category c WHERE c.categoryId = :categoryId")
    , @NamedQuery(name = "Category.findByCategoryName", query = "SELECT c FROM Category c WHERE c.categoryName = :categoryName")
    , @NamedQuery(name = "Category.findByDescription", query = "SELECT c FROM Category c WHERE c.description = :description")
    , @NamedQuery(name = "Category.findByPicture", query = "SELECT c FROM Category c WHERE c.picture = :picture")})
public class Category implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "CATEGORY_ID")
    private Integer categoryId;
    @Basic(optional = false)
    @Column(name = "CATEGORY_NAME")
    private String categoryName;
    @Column(name = "DESCRIPTION")
    private String description;
    @Column(name = "PICTURE")
    private String picture;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "categoryId")
    private Collection<Product> productCollection;

    public Category() {
    }

    public Category(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public Category(Integer categoryId, String categoryName) {
        this.categoryId = categoryId;
        this.categoryName = categoryName;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }

    @XmlTransient
    public Collection<Product> getProductCollection() {
        return productCollection;
    }

    public void setProductCollection(Collection<Product> productCollection) {
        this.productCollection = productCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (categoryId != null ? categoryId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Category)) {
            return false;
        }
        Category other = (Category) object;
        if ((this.categoryId == null && other.categoryId != null) || (this.categoryId != null && !this.categoryId.equals(other.categoryId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "model.Category[ categoryId=" + categoryId + " ]";
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.yasoon.jira;

import com.atlassian.applinks.api.ApplicationId;
import com.atlassian.applinks.api.ApplicationLink;
import com.atlassian.applinks.api.ApplicationType;
import com.atlassian.applinks.api.application.generic.GenericApplicationType;
import com.atlassian.applinks.spi.link.ApplicationLinkDetails;
import com.atlassian.applinks.spi.link.MutatingApplicationLinkService;
import com.atlassian.applinks.spi.manifest.ManifestNotFoundException;
import com.atlassian.applinks.spi.util.TypeAccessor;
import com.atlassian.oauth.Consumer;
import com.atlassian.oauth.serviceprovider.ServiceProviderConsumerStore;
import com.atlassian.oauth.util.RSAKeys;
import com.atlassian.sal.api.auth.LoginUriProvider;
import com.atlassian.sal.api.user.UserManager;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.cert.CertificateException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.util.StreamReaderDelegate;

/**
 *
 * @author Tobias
 */
public class ApplicationLinkServlet extends HttpServlet {

    private final UserManager userManager;
    private final LoginUriProvider loginUriProvider;
    private MutatingApplicationLinkService appLinkService;
    private TypeAccessor accessor;
    private ServiceProviderConsumerStore storeService;

    public ApplicationLinkServlet(UserManager userManager, LoginUriProvider loginUriProvider,
            MutatingApplicationLinkService appLinks, TypeAccessor typeAccessor, ServiceProviderConsumerStore storeService)
    {
        this.userManager = userManager;
        this.loginUriProvider = loginUriProvider;
        this.appLinkService = appLinks;
        this.accessor = typeAccessor;
        this.storeService = storeService;
    }

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = userManager.getRemoteUsername(request);
        if (username == null || !userManager.isSystemAdmin(username)) {
            redirectToLogin(request, response);
            return;
        }

        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");

        PrintWriter out = response.getWriter();
        try {
            if(request.getMethod().equalsIgnoreCase("get")) {
                out.println("{ \"exists\": " + checkAppLink() + " }");
            }
            else if(request.getMethod().equalsIgnoreCase("post")){
                Gson g = new Gson();
                PostRequest post = g.fromJson(new InputStreamReader(request.getInputStream()), PostRequest.class);
                try {
                    createAppLink(post.getCert());
                    out.println("{}");
                } catch (ManifestNotFoundException ex) {
                    Logger.getLogger(ApplicationLinkServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(ApplicationLinkServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvalidKeySpecException ex) {
                    Logger.getLogger(ApplicationLinkServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (CertificateException ex) {
                    Logger.getLogger(ApplicationLinkServlet.class.getName()).log(Level.SEVERE, null, ex);
                } catch (java.security.cert.CertificateException ex) {
                    Logger.getLogger(ApplicationLinkServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } finally {
            out.close();
        }
    }

    private boolean checkAppLink() {
        Iterable<ApplicationLink> links = this.appLinkService.getApplicationLinks();
        for(ApplicationLink link : links) {
            try {
                String conKey = (String) link.getProperty("oauth.incoming.consumerkey");
                if(conKey != null) {
                    Consumer con = this.storeService.get(conKey);
                    if(con != null && con.getKey().equals("yasoonjira"))
                        return true;
                }
            }
            catch(Exception ex) {
            }
        }

        return false;
    }

    private ApplicationLink TryGetApplicationLink() {
        try {
            Iterable<ApplicationLink> links = this.appLinkService.getApplicationLinks();
            for(ApplicationLink link : links) {
                if (link.getDisplayUrl().getHost().equals("jira.yasoon.com"))
                    return link;
            }
        }
        catch(Exception ex) {
        }

        return null;
    }

    private void createAppLink(String cert) throws ManifestNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException, java.security.cert.CertificateException {
        //Handle broken links
        ApplicationLink existingLink = TryGetApplicationLink();
        PublicKey key = RSAKeys.fromEncodedCertificateToPublicKey(cert);
        Consumer con = Consumer.key("yasoonjira").name("Jira for Outlook").publicKey(key).callback(URI.create("http://oauth.yasoon/v1/com.yasoon.jira/auth")).build();

        if(existingLink == null) {
            ApplicationLinkDetails.Builder builder = ApplicationLinkDetails.builder();
            ApplicationLinkDetails details = builder.name("Jira for Outlook").displayUrl(URI.create("http://jira.yasoon.com")).build();
            ApplicationType generic = this.accessor.getApplicationType(GenericApplicationType.class);
            existingLink = this.appLinkService.createApplicationLink(generic, details);
        }
        else {
            String conKey = (String) existingLink.getProperty("oauth.incoming.consumerkey");
            if(conKey != null) {
                Consumer conOld = this.storeService.get(conKey);
                if(conOld != null && conOld.getKey().equals("yasoonjira"))
                    this.storeService.remove(conKey);
            }
        }

        this.storeService.put(con);
        existingLink.putProperty("oauth.incoming.consumerkey", con.getKey());
    }

    private void redirectToLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect(loginUriProvider.getLoginUri(getUri(request)).toASCIIString());
    }

    private URI getUri(HttpServletRequest request) {
        StringBuffer builder = request.getRequestURL();
        if (request.getQueryString() != null) {
            builder.append("?");
            builder.append(request.getQueryString());
        }
        return URI.create(builder.toString());
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

class PostRequest {
    private String cert;

    public String getCert() {
        return cert;
    }

    public void setCert(String cert) {
        this.cert = cert;
    }
}


text:
from sklearn_json import classification as clf
from sklearn_json import regression as reg
from sklearn import svm, discriminant_analysis, dummy
from sklearn.linear_model import LogisticRegression, Perceptron
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, RandomForestRegressor, GradientBoostingRegressor, _gb_losses
from sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB, ComplementNB
from sklearn.linear_model import LinearRegression, Lasso, Ridge
from sklearn.neural_network import MLPClassifier, MLPRegressor
from sklearn.svm import SVR
import json

__version__ = '0.1.0'

def serialize_model(model):
    if isinstance(model, LogisticRegression):
        return clf.serialize_logistic_regression(model)
    elif isinstance(model, BernoulliNB):
        return clf.serialize_bernoulli_nb(model)
    elif isinstance(model, GaussianNB):
        return clf.serialize_gaussian_nb(model)
    elif isinstance(model, MultinomialNB):
        return clf.serialize_multinomial_nb(model)
    elif isinstance(model, ComplementNB):
        return clf.serialize_complement_nb(model)
    elif isinstance(model, discriminant_analysis.LinearDiscriminantAnalysis):
        return clf.serialize_lda(model)
    elif isinstance(model, discriminant_analysis.QuadraticDiscriminantAnalysis):
        return clf.serialize_qda(model)
    elif isinstance(model, svm.SVC):
        return clf.serialize_svm(model)
    elif isinstance(model, Perceptron):
        return clf.serialize_perceptron(model)
    elif isinstance(model, DecisionTreeClassifier):
        return clf.serialize_decision_tree(model)
    elif isinstance(model, GradientBoostingClassifier):
        return clf.serialize_gradient_boosting(model)
    elif isinstance(model, RandomForestClassifier):
        return clf.serialize_random_forest(model)
    elif isinstance(model, MLPClassifier):
        return clf.serialize_mlp(model)

    elif isinstance(model, LinearRegression):
        return reg.serialize_linear_regressor(model)
    elif isinstance(model, Lasso):
        return reg.serialize_lasso_regressor(model)
    elif isinstance(model, Ridge):
        return reg.serialize_ridge_regressor(model)
    elif isinstance(model, SVR):
        return reg.serialize_svr(model)
    elif isinstance(model, DecisionTreeRegressor):
        return reg.serialize_decision_tree_regressor(model)
    elif isinstance(model, GradientBoostingRegressor):
        return reg.serialize_gradient_boosting_regressor(model)
    elif isinstance(model, RandomForestRegressor):
        return reg.serialize_random_forest_regressor(model)
    elif isinstance(model, MLPRegressor):
        return reg.serialize_mlp_regressor(model)
    else:
        raise ModellNotSupported('This model type is not currently supported. Email support@mlrequest.com to request a feature or report a bug.')

def deserialize_model(model_dict):
    if model_dict['meta'] == 'lr':
        return clf.deserialize_logistic_regression(model_dict)
    elif model_dict['meta'] == 'bernoulli-nb':
        return clf.deserialize_bernoulli_nb(model_dict)
    elif model_dict['meta'] == 'gaussian-nb':
        return clf.deserialize_gaussian_nb(model_dict)
    elif model_dict['meta'] == 'multinomial-nb':
        return clf.deserialize_multinomial_nb(model_dict)
    elif model_dict['meta'] == 'complement-nb':
        return clf.deserialize_complement_nb(model_dict)
    elif model_dict['meta'] == 'lda':
        return clf.deserialize_lda(model_dict)
    elif model_dict['meta'] == 'qda':
        return clf.deserialize_qda(model_dict)
    elif model_dict['meta'] == 'svm':
        return clf.deserialize_svm(model_dict)
    elif model_dict['meta'] == 'perceptron':
        return clf.deserialize_perceptron(model_dict)
    elif model_dict['meta'] == 'decision-tree':
        return clf.deserialize_decision_tree(model_dict)
    elif model_dict['meta'] == 'gb':
        return clf.deserialize_gradient_boosting(model_dict)
    elif model_dict['meta'] == 'rf':
        return clf.deserialize_random_forest(model_dict)
    elif model_dict['meta'] == 'mlp':
        return clf.deserialize_mlp(model_dict)

    elif model_dict['meta'] == 'linear-regression':
        return reg.deserialize_linear_regressor(model_dict)
    elif model_dict['meta'] == 'lasso-regression':
        return reg.deserialize_lasso_regressor(model_dict)
    elif model_dict['meta'] == 'ridge-regression':
        return reg.deserialize_ridge_regressor(model_dict)
    elif model_dict['meta'] == 'svr':
        return reg.deserialize_svr(model_dict)
    elif model_dict['meta'] == 'decision-tree-regression':
        return reg.deserialize_decision_tree_regressor(model_dict)
    elif model_dict['meta'] == 'gb-regression':
        return reg.deserialize_gradient_boosting_regressor(model_dict)
    elif model_dict['meta'] == 'rf-regression':
        return reg.deserialize_random_forest_regressor(model_dict)
    elif model_dict['meta'] == 'mlp-regression':
        return reg.deserialize_mlp_regressor(model_dict)
    else:
        raise ModellNotSupported('Model type not supported or corrupt JSON file. Email support@mlrequest.com to request a feature or report a bug.')

def to_dict(model):
    return serialize_model(model)

def from_dict(model_dict):
    return deserialize_model(model_dict)

def to_json(model, model_name):
    with open(model_name, 'w') as model_json:
        json.dump(serialize_model(model), model_json)

def from_json(model_name):
    with open(model_name, 'r') as model_json:
        model_dict = json.load(model_json)
        return deserialize_model(model_dict)

class ModellNotSupported(Exception):
    pass


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { update_books, get_user_info } from '../actions';
import { Button } from 'react-bootstrap';
import { browserHistory } from 'react-router';
require('../../styles/index.scss');

class SignInScreen extends Component {

componentDidMount() {
    const { dispatch } = this.props
    const urlUsername = this.props.params.urlUsername
    if (urlUsername !== undefined) {
    // get user info
    dispatch(get_user_info(urlUsername));
    }
}

render() {
    const { username } = this.props

    var isProduction = process.env.NODE_ENV === 'production';
    if (isProduction) var url = 'https://the-book-thing.herokuapp.com/';
    else var url = 'http://127.0.0.1:3000/';
    return (

            { username === undefined ?

The Book Thing
:

{'Welcome '+ username + '!'}

            }

            <Button bsStyle="primary" bsSize="lg">Sign in with Twitter

            </Button>

            {username !== undefined ?
            (

            <Button style={{'marginTop':'20px'}} bsStyle="success" bsSize="lg" onClick={()=>browserHistory.push('/mybooks')}>
            View My Books
            </Button>

            ):(

)}

Trade books with people from all over

        )
    }
}

function mapStateToProps(state){
    return {
        username: state.user.user_info.username
    }
}

SignInScreen = connect(
mapStateToProps
)(SignInScreen)
export default SignInScreen


text:
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * MediaWiki exception
 *
 * @ingroup Exception
 */
class MWException extends Exception {
	/**
	 * Should the exception use $wgOut to output the error?
	 *
	 * @return bool
	 */
	public function useOutputPage() {
		return $this->useMessageCache() &&
		!empty( $GLOBALS['wgFullyInitialised'] ) &&
		!empty( $GLOBALS['wgOut'] ) &&
		!defined( 'MEDIAWIKI_INSTALL' );
	}

	/**
	 * Whether to log this exception in the exception debug log.
	 *
	 * @since 1.23
	 * @return bool
	 */
	public function isLoggable() {
		return true;
	}

	/**
	 * Can the extension use the Message class/wfMessage to get i18n-ed messages?
	 *
	 * @return bool
	 */
	public function useMessageCache() {
		global $wgLang;

		foreach ( $this->getTrace() as $frame ) {
			if ( isset( $frame['class'] ) && $frame['class'] === 'LocalisationCache' ) {
				return false;
			}
		}

		return $wgLang instanceof Language;
	}

	/**
	 * Run hook to allow extensions to modify the text of the exception
	 *
	 * @param string $name Class name of the exception
	 * @param array $args Arguments to pass to the callback functions
	 * @return string|null String to output or null if any hook has been called
	 */
	public function runHooks( $name, $args = [] ) {
		global $wgExceptionHooks;

		if ( !isset( $wgExceptionHooks ) || !is_array( $wgExceptionHooks ) ) {
			return null; // Just silently ignore
		}

		if ( !array_key_exists( $name, $wgExceptionHooks ) ||
			!is_array( $wgExceptionHooks[$name] )
		) {
			return null;
		}

		$hooks = $wgExceptionHooks[$name];
		$callargs = array_merge( [ $this ], $args );

		foreach ( $hooks as $hook ) {
			if (
				is_string( $hook ) ||
				( is_array( $hook ) && count( $hook ) >= 2 && is_string( $hook[0] ) )
			) {
				// 'function' or array( 'class', hook' )
				$result = call_user_func_array( $hook, $callargs );
			} else {
				$result = null;
			}

			if ( is_string( $result ) ) {
				return $result;
			}
		}
		return null;
	}

	/**
	 * Get a message from i18n
	 *
	 * @param string $key Message name
	 * @param string $fallback Default message if the message cache can't be
	 *                  called by the exception
	 * The function also has other parameters that are arguments for the message
	 * @return string Message with arguments replaced
	 */
	public function msg( $key, $fallback /*[, params...] */ ) {
		$args = array_slice( func_get_args(), 2 );

		if ( $this->useMessageCache() ) {
			try {
				return wfMessage( $key, $args )->text();
			} catch ( Exception $e ) {
			}
		}
		return wfMsgReplaceArgs( $fallback, $args );
	}

	/**
	 * If $wgShowExceptionDetails is true, return a HTML message with a
	 * backtrace to the error, otherwise show a message to ask to set it to true
	 * to show that information.
	 *
	 * @return string Html to output
	 */
	public function getHTML() {
		global $wgShowExceptionDetails;

		if ( $wgShowExceptionDetails ) {
			return '
' . nl2br( htmlspecialchars( MWExceptionHandler::getLogMessage( $this ) ) ) .
			'

Backtrace:

' .
			nl2br( htmlspecialchars( MWExceptionHandler::getRedactedTraceAsString( $this ) ) ) .
			"
\n";
		} else {
			$logId = WebRequest::getRequestId();
			$type = get_class( $this );
			return "
" .
			'[' . $logId . '] ' .
			gmdate( 'Y-m-d H:i:s' ) . ": " .
			$this->msg( "internalerror-fatal-exception",
				"Fatal exception of type $1",
				$type,
				$logId,
				MWExceptionHandler::getURL( $this )
			) . "
\n" .
			"";
		}
	}

	/**
	 * Get the text to display when reporting the error on the command line.
	 * If $wgShowExceptionDetails is true, return a text message with a
	 * backtrace to the error.
	 *
	 * @return string
	 */
	public function getText() {
		global $wgShowExceptionDetails;

		if ( $wgShowExceptionDetails ) {
			return MWExceptionHandler::getLogMessage( $this ) .
			"\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString( $this ) . "\n";
		} else {
			return "Set \$wgShowExceptionDetails = true; " .
			"in LocalSettings.php to show detailed debugging information.\n";
		}
	}

	/**
	 * Return the title of the page when reporting this error in a HTTP response.
	 *
	 * @return string
	 */
	public function getPageTitle() {
		return $this->msg( 'internalerror', 'Internal error' );
	}

	/**
	 * Output the exception report using HTML.
	 */
	public function reportHTML() {
		global $wgOut, $wgSitename;
		if ( $this->useOutputPage() ) {
			$wgOut->prepareErrorPage( $this->getPageTitle() );

			$hookResult = $this->runHooks( get_class( $this ) );
			if ( $hookResult ) {
				$wgOut->addHTML( $hookResult );
			} else {
				$wgOut->addHTML( $this->getHTML() );
			}

			$wgOut->output();
		} else {
			self::header( 'Content-Type: text/html; charset=utf-8' );
			echo "<!DOCTYPE html>\n" .
				'' .
				// Mimick OutputPage::setPageTitle behaviour
				'<title>' .
				htmlspecialchars( $this->msg( 'pagetitle', "$1 - $wgSitename", $this->getPageTitle() ) ) .
				'</title>' .
				'' .
				"\n";

			$hookResult = $this->runHooks( get_class( $this ) . 'Raw' );
			if ( $hookResult ) {
				echo $hookResult;
			} else {
				echo $this->getHTML();
			}

			echo "\n";
		}
	}

	/**
	 * Output a report about the exception and takes care of formatting.
	 * It will be either HTML or plain text based on isCommandLine().
	 */
	public function report() {
		global $wgMimeType;

		if ( defined( 'MW_API' ) ) {
			// Unhandled API exception, we can't be sure that format printer is alive
			self::header( 'MediaWiki-API-Error: internal_api_error_' . get_class( $this ) );
			wfHttpError( 500, 'Internal Server Error', $this->getText() );
		} elseif ( self::isCommandLine() ) {
			MWExceptionHandler::printError( $this->getText() );
		} else {
			self::statusHeader( 500 );
			self::header( "Content-Type: $wgMimeType; charset=utf-8" );

			$this->reportHTML();
		}
	}

	/**
	 * Check whether we are in command line mode or not to report the exception
	 * in the correct format.
	 *
	 * @return bool
	 */
	public static function isCommandLine() {
		return !empty( $GLOBALS['wgCommandLineMode'] );
	}

	/**
	 * Send a header, if we haven't already sent them. We shouldn't,
	 * but sometimes we might in a weird case like Export
	 * @param string $header
	 */
	private static function header( $header ) {
		if ( !headers_sent() ) {
			header( $header );
		}
	}
	private static function statusHeader( $code ) {
		if ( !headers_sent() ) {
			HttpStatus::header( $code );
		}
	}
}


text:
<ivy-module version="1.0">
    <info organisation="jayasoft" module="namespace" revision="2.0" />

    <dependencies>
 		   <dependency org="systemorg" name="systemmod2" rev="1.0" />
    </dependencies>
</ivy-module>