text:
"""Tests for Requests."""

from __future__ import division
import json
import os
import pickle
import unittest
import collections

import io
import requests
import pytest
from requests.adapters import HTTPAdapter
from requests.auth import HTTPDigestAuth
from requests.compat import (
    Morsel, cookielib, getproxies, str, urljoin, urlparse)
from requests.cookies import cookiejar_from_dict, morsel_to_cookie
from requests.exceptions import InvalidURL, MissingSchema
from requests.models import PreparedRequest, Response
from requests.structures import CaseInsensitiveDict
from requests.sessions import SessionRedirectMixin
from requests.models import PreparedRequest, urlencode
from requests.hooks import default_hooks

try:
    import StringIO
except ImportError:
    import io as StringIO

HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')
# Issue #1483: Make sure the URL always has a trailing slash
HTTPBIN = HTTPBIN.rstrip('/') + '/'

def httpbin(*suffix):
    """Returns url for HTTPBIN resource."""
    return urljoin(HTTPBIN, '/'.join(suffix))

class RequestsTestCase(unittest.TestCase):

    _multiprocess_can_split_ = True

    def setUp(self):
        """Create simple data set with headers."""
        pass

    def tearDown(self):
        """Teardown."""
        pass

    def test_entry_points(self):

        requests.session
        requests.session().get
        requests.session().head
        requests.get
        requests.head
        requests.put
        requests.patch
        requests.post

    def test_invalid_url(self):
        with pytest.raises(MissingSchema):
            requests.get('hiwpefhipowhefopw')
        with pytest.raises(InvalidURL):
            requests.get('http://')

    def test_basic_building(self):
        req = requests.Request()
        req.url = 'http://kennethreitz.org/'
        req.data = {'life': '42'}

        pr = req.prepare()
        assert pr.url == req.url
        assert pr.body == 'life=42'

    def test_no_content_length(self):
        get_req = requests.Request('GET', httpbin('get')).prepare()
        assert 'Content-Length' not in get_req.headers
        head_req = requests.Request('HEAD', httpbin('head')).prepare()
        assert 'Content-Length' not in head_req.headers

    def test_path_is_not_double_encoded(self):
        request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()

        assert request.path_url == '/get/test%20case'

    def test_params_are_added_before_fragment(self):
        request = requests.Request('GET',
            "http://example.com/path#fragment", params={"a": "b"}).prepare()
        assert request.url == "http://example.com/path?a=b#fragment"
        request = requests.Request('GET',
            "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()
        assert request.url == "http://example.com/path?key=value&a=b#fragment"

    def test_mixed_case_scheme_acceptable(self):
        s = requests.Session()
        s.proxies = getproxies()
        parts = urlparse(httpbin('get'))
        schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',
                   'https://', 'HTTPS://', 'hTTps://', 'HttPs://']
        for scheme in schemes:
            url = scheme + parts.netloc + parts.path
            r = requests.Request('GET', url)
            r = s.send(r.prepare())
            assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)

    def test_HTTP_200_OK_GET_ALTERNATIVE(self):
        r = requests.Request('GET', httpbin('get'))
        s = requests.Session()
        s.proxies = getproxies()

        r = s.send(r.prepare())

        assert r.status_code == 200

    def test_HTTP_302_ALLOW_REDIRECT_GET(self):
        r = requests.get(httpbin('redirect', '1'))
        assert r.status_code == 200
        assert r.history[0].status_code == 302
        assert r.history[0].is_redirect

    # def test_HTTP_302_ALLOW_REDIRECT_POST(self):
    #     r = requests.post(httpbin('status', '302'), data={'some': 'data'})
    #     self.assertEqual(r.status_code, 200)

    def test_HTTP_200_OK_GET_WITH_PARAMS(self):
        heads = {'User-agent': 'Mozilla/5.0'}

        r = requests.get(httpbin('user-agent'), headers=heads)

        assert heads['User-agent'] in r.text
        assert r.status_code == 200

    def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):
        heads = {'User-agent': 'Mozilla/5.0'}

        r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)
        assert r.status_code == 200

    def test_set_cookie_on_301(self):
        s = requests.session()
        url = httpbin('cookies/set?foo=bar')
        r = s.get(url)
        assert s.cookies['foo'] == 'bar'

    def test_cookie_sent_on_redirect(self):
        s = requests.session()
        s.get(httpbin('cookies/set?foo=bar'))
        r = s.get(httpbin('redirect/1'))  # redirects to httpbin('get')
        assert 'Cookie' in r.json()['headers']

    def test_cookie_removed_on_expire(self):
        s = requests.session()
        s.get(httpbin('cookies/set?foo=bar'))
        assert s.cookies['foo'] == 'bar'
        s.get(
            httpbin('response-headers'),
            params={
                'Set-Cookie':
                    'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'
            }
        )
        assert 'foo' not in s.cookies

    def test_cookie_quote_wrapped(self):
        s = requests.session()
        s.get(httpbin('cookies/set?foo="bar:baz"'))
        assert s.cookies['foo'] == '"bar:baz"'

    def test_cookie_persists_via_api(self):
        s = requests.session()
        r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})
        assert 'foo' in r.request.headers['Cookie']
        assert 'foo' in r.history[0].request.headers['Cookie']

    def test_request_cookie_overrides_session_cookie(self):
        s = requests.session()
        s.cookies['foo'] = 'bar'
        r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})
        assert r.json()['cookies']['foo'] == 'baz'
        # Session cookie should not be modified
        assert s.cookies['foo'] == 'bar'

    def test_request_cookies_not_persisted(self):
        s = requests.session()
        s.get(httpbin('cookies'), cookies={'foo': 'baz'})
        # Sending a request with cookies should not add cookies to the session
        assert not s.cookies

    def test_generic_cookiejar_works(self):
        cj = cookielib.CookieJar()
        cookiejar_from_dict({'foo': 'bar'}, cj)
        s = requests.session()
        s.cookies = cj
        r = s.get(httpbin('cookies'))
        # Make sure the cookie was sent
        assert r.json()['cookies']['foo'] == 'bar'
        # Make sure the session cj is still the custom one
        assert s.cookies is cj

    def test_param_cookiejar_works(self):
        cj = cookielib.CookieJar()
        cookiejar_from_dict({'foo' : 'bar'}, cj)
        s = requests.session()
        r = s.get(httpbin('cookies'), cookies=cj)
        # Make sure the cookie was sent
        assert r.json()['cookies']['foo'] == 'bar'

    def test_requests_in_history_are_not_overridden(self):
        resp = requests.get(httpbin('redirect/3'))
        urls = [r.url for r in resp.history]
        req_urls = [r.request.url for r in resp.history]
        assert urls == req_urls

    def test_history_is_always_a_list(self):
        """
        Show that even with redirects, Response.history is always a list.
        """
        resp = requests.get(httpbin('get'))
        assert isinstance(resp.history, list)
        resp = requests.get(httpbin('redirect/1'))
        assert isinstance(resp.history, list)
        assert not isinstance(resp.history, tuple)

    def test_headers_on_session_with_None_are_not_sent(self):
        """Do not send headers in Session.headers with None values."""
        ses = requests.Session()
        ses.headers['Accept-Encoding'] = None
        req = requests.Request('GET', 'http://httpbin.org/get')
        prep = ses.prepare_request(req)
        assert 'Accept-Encoding' not in prep.headers

    def test_user_agent_transfers(self):

        heads = {
            'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'
        }

        r = requests.get(httpbin('user-agent'), headers=heads)
        assert heads['User-agent'] in r.text

        heads = {
            'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'
        }

        r = requests.get(httpbin('user-agent'), headers=heads)
        assert heads['user-agent'] in r.text

    def test_HTTP_200_OK_HEAD(self):
        r = requests.head(httpbin('get'))
        assert r.status_code == 200

    def test_HTTP_200_OK_PUT(self):
        r = requests.put(httpbin('put'))
        assert r.status_code == 200

    def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):
        auth = ('user', 'pass')
        url = httpbin('basic-auth', 'user', 'pass')

        r = requests.get(url, auth=auth)
        assert r.status_code == 200

        r = requests.get(url)
        assert r.status_code == 401

        s = requests.session()
        s.auth = auth
        r = s.get(url)
        assert r.status_code == 200

    def test_basicauth_with_netrc(self):
        auth = ('user', 'pass')
        wrong_auth = ('wronguser', 'wrongpass')
        url = httpbin('basic-auth', 'user', 'pass')

        def get_netrc_auth_mock(url):
            return auth
        requests.sessions.get_netrc_auth = get_netrc_auth_mock

        # Should use netrc and work.
        r = requests.get(url)
        assert r.status_code == 200

        # Given auth should override and fail.
        r = requests.get(url, auth=wrong_auth)
        assert r.status_code == 401

        s = requests.session()

        # Should use netrc and work.
        r = s.get(url)
        assert r.status_code == 200

        # Given auth should override and fail.
        s.auth = wrong_auth
        r = s.get(url)
        assert r.status_code == 401

    def test_DIGEST_HTTP_200_OK_GET(self):

        auth = HTTPDigestAuth('user', 'pass')
        url = httpbin('digest-auth', 'auth', 'user', 'pass')

        r = requests.get(url, auth=auth)
        assert r.status_code == 200

        r = requests.get(url)
        assert r.status_code == 401

        s = requests.session()
        s.auth = HTTPDigestAuth('user', 'pass')
        r = s.get(url)
        assert r.status_code == 200

    def test_DIGEST_AUTH_RETURNS_COOKIE(self):
        url = httpbin('digest-auth', 'auth', 'user', 'pass')
        auth = HTTPDigestAuth('user', 'pass')
        r = requests.get(url)
        assert r.cookies['fake'] == 'fake_value'

        r = requests.get(url, auth=auth)
        assert r.status_code == 200

    def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):
        url = httpbin('digest-auth', 'auth', 'user', 'pass')
        auth = HTTPDigestAuth('user', 'pass')
        s = requests.Session()
        s.get(url, auth=auth)
        assert s.cookies['fake'] == 'fake_value'

    def test_DIGEST_STREAM(self):

        auth = HTTPDigestAuth('user', 'pass')
        url = httpbin('digest-auth', 'auth', 'user', 'pass')

        r = requests.get(url, auth=auth, stream=True)
        assert r.raw.read() != b''

        r = requests.get(url, auth=auth, stream=False)
        assert r.raw.read() == b''

    def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):

        auth = HTTPDigestAuth('user', 'wrongpass')
        url = httpbin('digest-auth', 'auth', 'user', 'pass')

        r = requests.get(url, auth=auth)
        assert r.status_code == 401

        r = requests.get(url)
        assert r.status_code == 401

        s = requests.session()
        s.auth = auth
        r = s.get(url)
        assert r.status_code == 401

    def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):

        auth = HTTPDigestAuth('user', 'pass')
        url = httpbin('digest-auth', 'auth', 'user', 'pass')

        r = requests.get(url, auth=auth)
        assert '"auth"' in r.request.headers['Authorization']

    def test_POSTBIN_GET_POST_FILES(self):

        url = httpbin('post')
        post1 = requests.post(url).raise_for_status()

        post1 = requests.post(url, data={'some': 'data'})
        assert post1.status_code == 200

        with open('requirements.txt') as f:
            post2 = requests.post(url, files={'some': f})
        assert post2.status_code == 200

        post4 = requests.post(url, data='[{"some": "json"}]')
        assert post4.status_code == 200

        with pytest.raises(ValueError):
            requests.post(url, files = ['bad file data'])

    def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):

        url = httpbin('post')
        post1 = requests.post(url).raise_for_status()

        post1 = requests.post(url, data={'some': 'data'})
        assert post1.status_code == 200

        with open('requirements.txt') as f:
            post2 = requests.post(url, data={'some': 'data'}, files={'some': f})
        assert post2.status_code == 200

        post4 = requests.post(url, data='[{"some": "json"}]')
        assert post4.status_code == 200

        with pytest.raises(ValueError):
            requests.post(url, files = ['bad file data'])

    def test_conflicting_post_params(self):
        url = httpbin('post')
        with open('requirements.txt') as f:
            pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")
            pytest.raises(ValueError, "requests.post(url, data=u'[{\"some\": \"data\"}]', files={'some': f})")

    def test_request_ok_set(self):
        r = requests.get(httpbin('status', '404'))
        assert not r.ok

    def test_status_raising(self):
        r = requests.get(httpbin('status', '404'))
        with pytest.raises(requests.exceptions.HTTPError):
            r.raise_for_status()

        r = requests.get(httpbin('status', '500'))
        assert not r.ok

    def test_decompress_gzip(self):
        r = requests.get(httpbin('gzip'))
        r.content.decode('ascii')

    def test_unicode_get(self):
        url = httpbin('/get')
        requests.get(url, params={'foo': 'føø'})
        requests.get(url, params={'føø': 'føø'})
        requests.get(url, params={'føø': 'føø'})
        requests.get(url, params={'foo': 'foo'})
        requests.get(httpbin('ø'), params={'foo': 'foo'})

    def test_unicode_header_name(self):
        requests.put(httpbin('put'), headers={str('Content-Type'): 'application/octet-stream'}, data='\xff') # compat.str is unicode.

    def test_pyopenssl_redirect(self):
        requests.get('https://httpbin.org/status/301')

    def test_urlencoded_get_query_multivalued_param(self):

        r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))
        assert r.status_code == 200
        assert r.url == httpbin('get?test=foo&test=baz')

    def test_different_encodings_dont_break_post(self):
        r = requests.post(httpbin('post'),
                          data={'stuff': json.dumps({'a': 123})},
                          params={'blah': 'asdf1234'},
                          files={'file': ('test_requests.py', open(__file__, 'rb'))})
        assert r.status_code == 200

    def test_unicode_multipart_post(self):
        r = requests.post(httpbin('post'),
                          data={'stuff': u'ëlïxr'},
                          files={'file': ('test_requests.py', open(__file__, 'rb'))})
        assert r.status_code == 200

        r = requests.post(httpbin('post'),
                          data={'stuff': u'ëlïxr'.encode('utf-8')},
                          files={'file': ('test_requests.py', open(__file__, 'rb'))})
        assert r.status_code == 200

        r = requests.post(httpbin('post'),
                          data={'stuff': 'elixr'},
                          files={'file': ('test_requests.py', open(__file__, 'rb'))})
        assert r.status_code == 200

        r = requests.post(httpbin('post'),
                          data={'stuff': 'elixr'.encode('utf-8')},
                          files={'file': ('test_requests.py', open(__file__, 'rb'))})
        assert r.status_code == 200

    def test_unicode_multipart_post_fieldnames(self):
        filename = os.path.splitext(__file__)[0] + '.py'
        r = requests.Request(method='POST',
                             url=httpbin('post'),
                             data={'stuff'.encode('utf-8'): 'elixr'},
                             files={'file': ('test_requests.py',
                                             open(filename, 'rb'))})
        prep = r.prepare()
        assert b'name="stuff"' in prep.body
        assert b'name="b\'stuff\'"' not in prep.body

    def test_unicode_method_name(self):
        files = {'file': open('test_requests.py', 'rb')}
        r = requests.request(method=u'POST', url=httpbin('post'), files=files)
        assert r.status_code == 200

    def test_custom_content_type(self):
        r = requests.post(httpbin('post'),
                          data={'stuff': json.dumps({'a': 123})},
                          files={'file1': ('test_requests.py', open(__file__, 'rb')),
                                 'file2': ('test_requests', open(__file__, 'rb'),
                                           'text/py-content-type')})
        assert r.status_code == 200
        assert b"text/py-content-type" in r.request.body

    def test_hook_receives_request_arguments(self):
        def hook(resp, **kwargs):
            assert resp is not None
            assert kwargs != {}

        requests.Request('GET', HTTPBIN, hooks={'response': hook})

    def test_session_hooks_are_used_with_no_request_hooks(self):
        hook = lambda x, *args, **kwargs: x
        s = requests.Session()
        s.hooks['response'].append(hook)
        r = requests.Request('GET', HTTPBIN)
        prep = s.prepare_request(r)
        assert prep.hooks['response'] != []
        assert prep.hooks['response'] == [hook]

    def test_session_hooks_are_overriden_by_request_hooks(self):
        hook1 = lambda x, *args, **kwargs: x
        hook2 = lambda x, *args, **kwargs: x
        assert hook1 is not hook2
        s = requests.Session()
        s.hooks['response'].append(hook2)
        r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})
        prep = s.prepare_request(r)
        assert prep.hooks['response'] == [hook1]

    def test_prepared_request_hook(self):
        def hook(resp, **kwargs):
            resp.hook_working = True
            return resp

        req = requests.Request('GET', HTTPBIN, hooks={'response': hook})
        prep = req.prepare()

        s = requests.Session()
        s.proxies = getproxies()
        resp = s.send(prep)

        assert hasattr(resp, 'hook_working')

    def test_prepared_from_session(self):
        class DummyAuth(requests.auth.AuthBase):
            def __call__(self, r):
                r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'
                return r

        req = requests.Request('GET', httpbin('headers'))
        assert not req.auth

        s = requests.Session()
        s.auth = DummyAuth()

        prep = s.prepare_request(req)
        resp = s.send(prep)

        assert resp.json()['headers']['Dummy-Auth-Test'] == 'dummy-auth-test-ok'

    def test_links(self):
        r = requests.Response()
        r.headers = {
            'cache-control': 'public, max-age=60, s-maxage=60',
            'connection': 'keep-alive',
            'content-encoding': 'gzip',
            'content-type': 'application/json; charset=utf-8',
            'date': 'Sat, 26 Jan 2013 16:47:56 GMT',
            'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',
            'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',
            'link': ('<https://api.github.com/users/kennethreitz/repos?'
                     'page=2&per_page=10>; rel="next", <https://api.github.'
                     'com/users/kennethreitz/repos?page=7&per_page=10>; '
                     ' rel="last"'),
            'server': 'GitHub.com',
            'status': '200 OK',
            'vary': 'Accept',
            'x-content-type-options': 'nosniff',
            'x-github-media-type': 'github.beta',
            'x-ratelimit-limit': '60',
            'x-ratelimit-remaining': '57'
        }
        assert r.links['next']['rel'] == 'next'

    def test_cookie_parameters(self):
        key = 'some_cookie'
        value = 'some_value'
        secure = True
        domain = 'test.com'
        rest = {'HttpOnly': True}

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value, secure=secure, domain=domain, rest=rest)

        assert len(jar) == 1
        assert 'some_cookie' in jar

        cookie = list(jar)[0]
        assert cookie.secure == secure
        assert cookie.domain == domain
        assert cookie._rest['HttpOnly'] == rest['HttpOnly']

    def test_cookie_as_dict_keeps_len(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert len(jar) == 2
        assert len(d1) == 2
        assert len(d2) == 2
        assert len(d3) == 2

    def test_cookie_as_dict_keeps_items(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        d1 = dict(jar)
        d2 = dict(jar.iteritems())
        d3 = dict(jar.items())

        assert d1['some_cookie'] == 'some_value'
        assert d2['some_cookie'] == 'some_value'
        assert d3['some_cookie1'] == 'some_value1'

    def test_cookie_as_dict_keys(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        keys = jar.keys()
        assert keys == list(keys)
        # make sure one can use keys multiple times
        assert list(keys) == list(keys)

    def test_cookie_as_dict_values(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        values = jar.values()
        assert values == list(values)
        # make sure one can use values multiple times
        assert list(values) == list(values)

    def test_cookie_as_dict_items(self):
        key = 'some_cookie'
        value = 'some_value'

        key1 = 'some_cookie1'
        value1 = 'some_value1'

        jar = requests.cookies.RequestsCookieJar()
        jar.set(key, value)
        jar.set(key1, value1)

        items = jar.items()
        assert items == list(items)
        # make sure one can use items multiple times
        assert list(items) == list(items)

    def test_time_elapsed_blank(self):
        r = requests.get(httpbin('get'))
        td = r.elapsed
        total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)
                         * 10**6) / 10**6)
        assert total_seconds > 0.0

    def test_response_is_iterable(self):
        r = requests.Response()
        io = StringIO.StringIO('abc')
        read_ = io.read

        def read_mock(amt, decode_content=None):
            return read_(amt)
        setattr(io, 'read', read_mock)
        r.raw = io
        assert next(iter(r))
        io.close()

    def test_response_decode_unicode(self):
        """
        When called with decode_unicode, Response.iter_content should always
        return unicode.
        """
        r = requests.Response()
        r._content_consumed = True
        r._content = b'the content'
        r.encoding = 'ascii'

        chunks = r.iter_content(decode_unicode=True)
        assert all(isinstance(chunk, str) for chunk in chunks)

        # also for streaming
        r = requests.Response()
        r.raw = io.BytesIO(b'the content')
        r.encoding = 'ascii'
        chunks = r.iter_content(decode_unicode=True)
        assert all(isinstance(chunk, str) for chunk in chunks)

    def test_request_and_response_are_pickleable(self):
        r = requests.get(httpbin('get'))

        # verify we can pickle the original request
        assert pickle.loads(pickle.dumps(r.request))

        # verify we can pickle the response and that we have access to
        # the original request.
        pr = pickle.loads(pickle.dumps(r))
        assert r.request.url == pr.request.url
        assert r.request.headers == pr.request.headers

    def test_get_auth_from_url(self):
        url = 'http://user:pass@complex.url.com/path?query=yes'
        assert ('user', 'pass') == requests.utils.get_auth_from_url(url)

    def test_get_auth_from_url_encoded_spaces(self):
        url = 'http://user:pass%20pass@complex.url.com/path?query=yes'
        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)

    def test_get_auth_from_url_not_encoded_spaces(self):
        url = 'http://user:pass pass@complex.url.com/path?query=yes'
        assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)

    def test_get_auth_from_url_percent_chars(self):
        url = 'http://user%25user:pass@complex.url.com/path?query=yes'
        assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)

    def test_get_auth_from_url_encoded_hashes(self):
        url = 'http://user:pass%23pass@complex.url.com/path?query=yes'
        assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)

    def test_cannot_send_unprepared_requests(self):
        r = requests.Request(url=HTTPBIN)
        with pytest.raises(ValueError):
            requests.Session().send(r)

    def test_http_error(self):
        error = requests.exceptions.HTTPError()
        assert not error.response
        response = requests.Response()
        error = requests.exceptions.HTTPError(response=response)
        assert error.response == response
        error = requests.exceptions.HTTPError('message', response=response)
        assert str(error) == 'message'
        assert error.response == response

    def test_session_pickling(self):
        r = requests.Request('GET', httpbin('get'))
        s = requests.Session()

        s = pickle.loads(pickle.dumps(s))
        s.proxies = getproxies()

        r = s.send(r.prepare())
        assert r.status_code == 200

    def test_fixes_1329(self):
        """
        Ensure that header updates are done case-insensitively.
        """
        s = requests.Session()
        s.headers.update({'ACCEPT': 'BOGUS'})
        s.headers.update({'accept': 'application/json'})
        r = s.get(httpbin('get'))
        headers = r.request.headers
        assert headers['accept'] == 'application/json'
        assert headers['Accept'] == 'application/json'
        assert headers['ACCEPT'] == 'application/json'

    def test_uppercase_scheme_redirect(self):
        parts = urlparse(httpbin('html'))
        url = "HTTP://" + parts.netloc + parts.path
        r = requests.get(httpbin('redirect-to'), params={'url': url})
        assert r.status_code == 200
        assert r.url.lower() == url.lower()

    def test_transport_adapter_ordering(self):
        s = requests.Session()
        order = ['https://', 'http://']
        assert order == list(s.adapters)
        s.mount('http://git', HTTPAdapter())
        s.mount('http://github', HTTPAdapter())
        s.mount('http://github.com', HTTPAdapter())
        s.mount('http://github.com/about/', HTTPAdapter())
        order = [
            'http://github.com/about/',
            'http://github.com',
            'http://github',
            'http://git',
            'https://',
            'http://',
        ]
        assert order == list(s.adapters)
        s.mount('http://gittip', HTTPAdapter())
        s.mount('http://gittip.com', HTTPAdapter())
        s.mount('http://gittip.com/about/', HTTPAdapter())
        order = [
            'http://github.com/about/',
            'http://gittip.com/about/',
            'http://github.com',
            'http://gittip.com',
            'http://github',
            'http://gittip',
            'http://git',
            'https://',
            'http://',
        ]
        assert order == list(s.adapters)
        s2 = requests.Session()
        s2.adapters = {'http://': HTTPAdapter()}
        s2.mount('https://', HTTPAdapter())
        assert 'http://' in s2.adapters
        assert 'https://' in s2.adapters

    def test_header_remove_is_case_insensitive(self):
        # From issue #1321
        s = requests.Session()
        s.headers['foo'] = 'bar'
        r = s.get(httpbin('get'), headers={'FOO': None})
        assert 'foo' not in r.request.headers

    def test_params_are_merged_case_sensitive(self):
        s = requests.Session()
        s.params['foo'] = 'bar'
        r = s.get(httpbin('get'), params={'FOO': 'bar'})
        assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}

    def test_long_authinfo_in_url(self):
        url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(
            'E8A3BE87-9E3F-4620-8858-95478E385B5B',
            'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',
            'exactly-------------sixty-----------three------------characters',
        )
        r = requests.Request('GET', url).prepare()
        assert r.url == url

    def test_header_keys_are_native(self):
        headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}
        r = requests.Request('GET', httpbin('get'), headers=headers)
        p = r.prepare()

        # This is testing that they are builtin strings. A bit weird, but there
        # we go.
        assert 'unicode' in p.headers.keys()
        assert 'byte' in p.headers.keys()

    def test_can_send_nonstring_objects_with_files(self):
        data = {'a': 0.0}
        files = {'b': 'foo'}
        r = requests.Request('POST', httpbin('post'), data=data, files=files)
        p = r.prepare()

        assert 'multipart/form-data' in p.headers['Content-Type']

    def test_autoset_header_values_are_native(self):
        data = 'this is a string'
        length = '16'
        req = requests.Request('POST', httpbin('post'), data=data)
        p = req.prepare()

        assert p.headers['Content-Length'] == length

    def test_oddball_schemes_dont_check_URLs(self):
        test_urls = (
            'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',
            'file:///etc/passwd',
            'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',
        )
        for test_url in test_urls:
            req = requests.Request('GET', test_url)
            preq = req.prepare()
            assert test_url == preq.url

    def test_auth_is_stripped_on_redirect_off_host(self):
        r = requests.get(
            httpbin('redirect-to'),
            params={'url': 'http://www.google.co.uk'},
            auth=('user', 'pass'),
        )
        assert r.history[0].request.headers['Authorization']
        assert not r.request.headers.get('Authorization', '')

    def test_auth_is_retained_for_redirect_on_host(self):
        r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))
        h1 = r.history[0].request.headers['Authorization']
        h2 = r.request.headers['Authorization']

        assert h1 == h2

    def test_manual_redirect_with_partial_body_read(self):
        s = requests.Session()
        r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)
        assert r1.is_redirect
        rg = s.resolve_redirects(r1, r1.request, stream=True)

        # read only the first eight bytes of the response body,
        # then follow the redirect
        r1.iter_content(8)
        r2 = next(rg)
        assert r2.is_redirect

        # read all of the response via iter_content,
        # then follow the redirect
        for _ in r2.iter_content():
            pass
        r3 = next(rg)
        assert not r3.is_redirect

    def _patch_adapter_gzipped_redirect(self, session, url):
        adapter = session.get_adapter(url=url)
        org_build_response = adapter.build_response
        self._patched_response = False

        def build_response(*args, **kwargs):
            resp = org_build_response(*args, **kwargs)
            if not self._patched_response:
                resp.raw.headers['content-encoding'] = 'gzip'
                self._patched_response = True
            return resp

        adapter.build_response = build_response

    def test_redirect_with_wrong_gzipped_header(self):
        s = requests.Session()
        url = httpbin('redirect/1')
        self._patch_adapter_gzipped_redirect(s, url)
        s.get(url)

class TestContentEncodingDetection(unittest.TestCase):

    def test_none(self):
        encodings = requests.utils.get_encodings_from_content('')
        assert not len(encodings)

    def test_html_charset(self):
        """HTML5 meta charset attribute"""
        content = '<meta charset="UTF-8">'
        encodings = requests.utils.get_encodings_from_content(content)
        assert len(encodings) == 1
        assert encodings[0] == 'UTF-8'

    def test_html4_pragma(self):
        """HTML4 pragma directive"""
        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'
        encodings = requests.utils.get_encodings_from_content(content)
        assert len(encodings) == 1
        assert encodings[0] == 'UTF-8'

    def test_xhtml_pragma(self):
        """XHTML 1.x served with text/html MIME type"""
        content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'
        encodings = requests.utils.get_encodings_from_content(content)
        assert len(encodings) == 1
        assert encodings[0] == 'UTF-8'

    def test_xml(self):
        """XHTML 1.x served as XML"""
        content = '<?xml version="1.0" encoding="UTF-8"?>'
        encodings = requests.utils.get_encodings_from_content(content)
        assert len(encodings) == 1
        assert encodings[0] == 'UTF-8'

    def test_precedence(self):
        content = '''
        <?xml version="1.0" encoding="XML"?>
        <meta charset="HTML5">
        <meta http-equiv="Content-type" content="text/html;charset=HTML4" />
        '''.strip()
        encodings = requests.utils.get_encodings_from_content(content)
        assert encodings == ['HTML5', 'HTML4', 'XML']

class TestCaseInsensitiveDict(unittest.TestCase):

    def test_mapping_init(self):
        cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})
        assert len(cid) == 2
        assert 'foo' in cid
        assert 'bar' in cid

    def test_iterable_init(self):
        cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])
        assert len(cid) == 2
        assert 'foo' in cid
        assert 'bar' in cid

    def test_kwargs_init(self):
        cid = CaseInsensitiveDict(FOO='foo', BAr='bar')
        assert len(cid) == 2
        assert 'foo' in cid
        assert 'bar' in cid

    def test_docstring_example(self):
        cid = CaseInsensitiveDict()
        cid['Accept'] = 'application/json'
        assert cid['aCCEPT'] == 'application/json'
        assert list(cid) == ['Accept']

    def test_len(self):
        cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})
        cid['A'] = 'a'
        assert len(cid) == 2

    def test_getitem(self):
        cid = CaseInsensitiveDict({'Spam': 'blueval'})
        assert cid['spam'] == 'blueval'
        assert cid['SPAM'] == 'blueval'

    def test_fixes_649(self):
        """__setitem__ should behave case-insensitively."""
        cid = CaseInsensitiveDict()
        cid['spam'] = 'oneval'
        cid['Spam'] = 'twoval'
        cid['sPAM'] = 'redval'
        cid['SPAM'] = 'blueval'
        assert cid['spam'] == 'blueval'
        assert cid['SPAM'] == 'blueval'
        assert list(cid.keys()) == ['SPAM']

    def test_delitem(self):
        cid = CaseInsensitiveDict()
        cid['Spam'] = 'someval'
        del cid['sPam']
        assert 'spam' not in cid
        assert len(cid) == 0

    def test_contains(self):
        cid = CaseInsensitiveDict()
        cid['Spam'] = 'someval'
        assert 'Spam' in cid
        assert 'spam' in cid
        assert 'SPAM' in cid
        assert 'sPam' in cid
        assert 'notspam' not in cid

    def test_get(self):
        cid = CaseInsensitiveDict()
        cid['spam'] = 'oneval'
        cid['SPAM'] = 'blueval'
        assert cid.get('spam') == 'blueval'
        assert cid.get('SPAM') == 'blueval'
        assert cid.get('sPam') == 'blueval'
        assert cid.get('notspam', 'default') == 'default'

    def test_update(self):
        cid = CaseInsensitiveDict()
        cid['spam'] = 'blueval'
        cid.update({'sPam': 'notblueval'})
        assert cid['spam'] == 'notblueval'
        cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})
        cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})
        assert len(cid) == 2
        assert cid['foo'] == 'anotherfoo'
        assert cid['bar'] == 'anotherbar'

    def test_update_retains_unchanged(self):
        cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})
        cid.update({'foo': 'newfoo'})
        assert cid['bar'] == 'bar'

    def test_iter(self):
        cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})
        keys = frozenset(['Spam', 'Eggs'])
        assert frozenset(iter(cid)) == keys

    def test_equality(self):
        cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})
        othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})
        assert cid == othercid
        del othercid['spam']
        assert cid != othercid
        assert cid == {'spam': 'blueval', 'eggs': 'redval'}

    def test_setdefault(self):
        cid = CaseInsensitiveDict({'Spam': 'blueval'})
        assert cid.setdefault('spam', 'notblueval') == 'blueval'
        assert cid.setdefault('notspam', 'notblueval') == 'notblueval'

    def test_lower_items(self):
        cid = CaseInsensitiveDict({
            'Accept': 'application/json',
            'user-Agent': 'requests',
        })
        keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())
        lowerkeyset = frozenset(['accept', 'user-agent'])
        assert keyset == lowerkeyset

    def test_preserve_key_case(self):
        cid = CaseInsensitiveDict({
            'Accept': 'application/json',
            'user-Agent': 'requests',
        })
        keyset = frozenset(['Accept', 'user-Agent'])
        assert frozenset(i[0] for i in cid.items()) == keyset
        assert frozenset(cid.keys()) == keyset
        assert frozenset(cid) == keyset

    def test_preserve_last_key_case(self):
        cid = CaseInsensitiveDict({
            'Accept': 'application/json',
            'user-Agent': 'requests',
        })
        cid.update({'ACCEPT': 'application/json'})
        cid['USER-AGENT'] = 'requests'
        keyset = frozenset(['ACCEPT', 'USER-AGENT'])
        assert frozenset(i[0] for i in cid.items()) == keyset
        assert frozenset(cid.keys()) == keyset
        assert frozenset(cid) == keyset

class UtilsTestCase(unittest.TestCase):

    def test_super_len_io_streams(self):
        """ Ensures that we properly deal with different kinds of IO streams. """
        # uses StringIO or io.StringIO (see import above)
        from io import BytesIO
        from requests.utils import super_len

        assert super_len(StringIO.StringIO()) == 0
        assert super_len(StringIO.StringIO('with so much drama in the LBC')) == 29

        assert super_len(BytesIO()) == 0
        assert super_len(BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 40

        try:
            import cStringIO
        except ImportError:
            pass
        else:
            assert super_len(cStringIO.StringIO('but some how, some way...')) == 25

    def test_get_environ_proxies_ip_ranges(self):
        """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """
        from requests.utils import get_environ_proxies
        os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"
        assert get_environ_proxies('http://192.168.0.1:5000/') == {}
        assert get_environ_proxies('http://192.168.0.1/') == {}
        assert get_environ_proxies('http://172.16.1.1/') == {}
        assert get_environ_proxies('http://172.16.1.1:5000/') == {}
        assert get_environ_proxies('http://192.168.1.1:5000/') != {}
        assert get_environ_proxies('http://192.168.1.1/') != {}

    def test_get_environ_proxies(self):
        """ Ensures that IP addresses are correctly matches with ranges in no_proxy variable """
        from requests.utils import get_environ_proxies
        os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"
        assert get_environ_proxies('http://localhost.localdomain:5000/v1.0/') == {}
        assert get_environ_proxies('http://www.requests.com/') != {}

    def test_is_ipv4_address(self):
        from requests.utils import is_ipv4_address
        assert is_ipv4_address('8.8.8.8')
        assert not is_ipv4_address('8.8.8.8.8')
        assert not is_ipv4_address('localhost.localdomain')

    def test_is_valid_cidr(self):
        from requests.utils import is_valid_cidr
        assert not is_valid_cidr('8.8.8.8')
        assert is_valid_cidr('192.168.1.0/24')

    def test_dotted_netmask(self):
        from requests.utils import dotted_netmask
        assert dotted_netmask(8) == '255.0.0.0'
        assert dotted_netmask(24) == '255.255.255.0'
        assert dotted_netmask(25) == '255.255.255.128'

    def test_address_in_network(self):
        from requests.utils import address_in_network
        assert address_in_network('192.168.1.1', '192.168.1.0/24')
        assert not address_in_network('172.16.0.1', '192.168.1.0/24')

    def test_get_auth_from_url(self):
        """ Ensures that username and password in well-encoded URI as per RFC 3986 are correclty extracted """
        from requests.utils import get_auth_from_url
        from requests.compat import quote
        percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "
        url_address = "request.com/url.html#test"
        url = "http://" + quote(percent_encoding_test_chars, '') + ':' + quote(percent_encoding_test_chars, '') + '@' + url_address
        (username, password) = get_auth_from_url(url)
        assert username == percent_encoding_test_chars
        assert password == percent_encoding_test_chars

class TestMorselToCookieExpires(unittest.TestCase):

    """Tests for morsel_to_cookie when morsel contains expires."""

    def test_expires_valid_str(self):
        """Test case where we convert expires from string time."""

        morsel = Morsel()
        morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'
        cookie = morsel_to_cookie(morsel)
        assert cookie.expires == 1

    def test_expires_invalid_int(self):
        """Test case where an invalid type is passed for expires."""

        morsel = Morsel()
        morsel['expires'] = 100
        with pytest.raises(TypeError):
            morsel_to_cookie(morsel)

    def test_expires_invalid_str(self):
        """Test case where an invalid string is input."""

        morsel = Morsel()
        morsel['expires'] = 'woops'
        with pytest.raises(ValueError):
            morsel_to_cookie(morsel)

    def test_expires_none(self):
        """Test case where expires is None."""

        morsel = Morsel()
        morsel['expires'] = None
        cookie = morsel_to_cookie(morsel)
        assert cookie.expires is None

class TestMorselToCookieMaxAge(unittest.TestCase):

    """Tests for morsel_to_cookie when morsel contains max-age."""

    def test_max_age_valid_int(self):
        """Test case where a valid max age in seconds is passed."""

        morsel = Morsel()
        morsel['max-age'] = 60
        cookie = morsel_to_cookie(morsel)
        assert isinstance(cookie.expires, int)

    def test_max_age_invalid_str(self):
        """Test case where a invalid max age is passed."""

        morsel = Morsel()
        morsel['max-age'] = 'woops'
        with pytest.raises(TypeError):
            morsel_to_cookie(morsel)

class TestTimeout:
    def test_stream_timeout(self):
        try:
            r = requests.get('https://httpbin.org/delay/10', timeout=5.0)
        except requests.exceptions.Timeout as e:
            assert 'Read timed out' in e.args[0].args[0]

SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))

class RedirectSession(SessionRedirectMixin):
    def __init__(self, order_of_redirects):
        self.redirects = order_of_redirects
        self.calls = []
        self.max_redirects = 30
        self.cookies = {}
        self.trust_env = False

    def send(self, *args, **kwargs):
        self.calls.append(SendCall(args, kwargs))
        return self.build_response()

    def build_response(self):
        request = self.calls[-1].args[0]
        r = requests.Response()

        try:
            r.status_code = int(self.redirects.pop(0))
        except IndexError:
            r.status_code = 200

        r.headers = CaseInsensitiveDict({'Location': '/'})
        r.raw = self._build_raw()
        r.request = request
        return r

    def _build_raw(self):
        string = StringIO.StringIO('')
        setattr(string, 'release_conn', lambda *args: args)
        return string

class TestRedirects:
    default_keyword_args = {
        'stream': False,
        'verify': True,
        'cert': None,
        'timeout': None,
        'allow_redirects': False,
        'proxies': {},
    }

    def test_requests_are_updated_each_time(self):
        session = RedirectSession([303, 307])
        prep = requests.Request('POST', 'http://httpbin.org/post').prepare()
        r0 = session.send(prep)
        assert r0.request.method == 'POST'
        assert session.calls[-1] == SendCall((r0.request,), {})
        redirect_generator = session.resolve_redirects(r0, prep)
        for response in redirect_generator:
            assert response.request.method == 'GET'
            send_call = SendCall((response.request,),
                                 TestRedirects.default_keyword_args)
            assert session.calls[-1] == send_call

@pytest.fixture
def list_of_tuples():
    return [
            (('a', 'b'), ('c', 'd')),
            (('c', 'd'), ('a', 'b')),
            (('a', 'b'), ('c', 'd'), ('e', 'f')),
            ]

def test_data_argument_accepts_tuples(list_of_tuples):
    """
    Ensure that the data argument will accept tuples of strings
    and properly encode them.
    """
    for data in list_of_tuples:
        p = PreparedRequest()
        p.prepare(
            method='GET',
            url='http://www.example.com',
            data=data,
            hooks=default_hooks()
        )
        assert p.body == urlencode(data)

if __name__ == '__main__':
    unittest.main()


text:
"""
Set performance test
"""

import timeit

SETUP = '''
import array
selected = array.array('d')
with open('selected.arr', 'rb') as fp:
    selected.fromfile(fp, {size})
haystack = {type}(selected)
# print('haystack: %10d' % len(haystack), end='  ')
needles = array.array('d')
with open('not_selected.arr', 'rb') as fp:
    needles.fromfile(fp, 500)
needles.extend(selected[:500])
needles = set(needles)
# print(' needles: %10d' % len(needles), end='  ')
'''

tests = [
('FOR_LOOP_TEST', '''
found = 0
for n in needles:
    if n in haystack:
        found += 1
assert found == 500
'''),
('SET_&_TEST', '''
found = len(needles & haystack)
assert found == 500
'''
)]

MAX_EXPONENT = 7
for collection_type in 'dict.fromkeys set list'.split():
    if collection_type == 'set':
        available_tests = tests
    else:
        available_tests = tests[:1]
    for test_name, test in available_tests:
        print('*' * 25, collection_type, test_name)
        for n in range(3, MAX_EXPONENT + 1):
            size = 10**n
            setup = SETUP.format(type=collection_type, size=size)
            tt = timeit.repeat(stmt=test, setup=setup, repeat=5, number=1)
            print('|{:{}d}|{:9.6f}'.format(size, MAX_EXPONENT + 1, min(tt)))

redpajama_set_name: RedPajamaGithub


text:
To install, run: sudo python setup.py install

This program has been written to run from the command line.

To run type: good_boids [-h]
                    	[--file FILE]
                    	[--size SIZE]
                    	[--dist DIST]
                    	[--strength STRENGTH]
                    	[--avoid_dist AVOID_DIST]
                    	[--mid_strength MID_STRENGTH]

Optional arguments:
  -h, --help
                        Shows a help message and exits.

  --file "filename.yml"
                        YAML file to load data from.

  --size [int]
                        Number of boids in flock.

  --dist [num]
                        Distance over which boids try to match speed.

  --strength [num]
                        How strongly boids try and match speed.

  --avoid_dist [num]
                        Distance in which boids avoid colliding with one another.

  --d_strength [num]
                        The degree to which boids try and flock together.

This code implements an algorithm which simulates how birds fly and avoid each other
(http://dl.acm.org/citation.cfm?doid=37401.37406) . This code was written as part of
an assignment for UCL's MPHYG001 course (http://development.rc.ucl.ac.uk/training/engineering)

The parameters of this code can be modified by specifying a YAML file using --file "filename.yml".
If one provides a config file in this way, all parameters will be modified by the values held
in the config file.

The initial_position and initial_velocity ranges axis_limits, can be specified in a YAML config also.


text:
<?php defined('BLUDIT') or die('Bludit CMS.');

class Category {

	protected $vars;

	function __construct($key)
	{
		global $categories;
		if (isset($categories->db[$key])) {
			$this->vars['name'] 		= $categories->db[$key]['name'];
			$this->vars['template'] 	= $categories->db[$key]['template'];
			$this->vars['description'] 	= $categories->db[$key]['description'];
			$this->vars['key'] 		= $key;
			$this->vars['permalink'] 	= DOMAIN_CATEGORIES . $key;
			$this->vars['list'] 		= $categories->db[$key]['list'];
		} else {
			$errorMessage = 'Category not found in database by key ['.$key.']';
			Log::set(__METHOD__.LOG_SEP.$errorMessage);
			throw new Exception($errorMessage);
		}
	}

	public function getValue($field)
	{
		if (isset($this->vars[$field])) {
			return $this->vars[$field];
		}
		return false;
	}

	public function key()
	{
		return $this->getValue('key');
	}

	public function name()
	{
		return $this->getValue('name');
	}

	public function permalink()
	{
		return $this->getValue('permalink');
	}

	public function template()
	{
		return $this->getValue('template');
	}

	public function description()
	{
		return $this->getValue('description');
	}

	// Returns an array with the keys of pages linked to the category
	public function pages()
	{
		return $this->getValue('list');
	}

	// Returns an array in json format with all the data of the tag
	public function json($returnsArray=false)
	{
		$tmp['key'] 		= $this->key();
		$tmp['name'] 		= $this->name();
		$tmp['description'] 	= $this->description();
		$tmp['permalink'] 	= $this->permalink();
		$tmp['pages'] 		= $this->pages();

		if ($returnsArray) {
			return $tmp;
		}

		return json_encode($tmp);
	}
}


text:
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

namespace LifeSimulation.Core.GUI
{
	public class StartScreen : Form
	{

		#region Private Variables

		private TableLayoutPanel _layout;
		private CheckedListBox _checkedListRaces;
		private Button _buttonSimulate;
		private Label _labelInitialLifelets;
		private TrackBar _trackbarInitialLifelets;

		#endregion

		#region Public Method

		public StartScreen () : base()
		{
			// Init

			// Window
			//this.ClientSize = new Size(300, 500);
			this.Text = "Life Simulation";
			this.FormBorderStyle = FormBorderStyle.FixedDialog;
    		this.StartPosition = FormStartPosition.CenterScreen;

			// Layout
			_layout = new TableLayoutPanel();
			_layout.Dock = DockStyle.Fill;
			this.Controls.Add(_layout);

			// Suspend layouting
			_layout.SuspendLayout();
			this.SuspendLayout();

			// Races list
			_checkedListRaces = new CheckedListBox();
			_checkedListRaces.Dock = DockStyle.Fill;
			_layout.Controls.Add(createLabel("Races to Simulate:"));
			_layout.Controls.Add(_checkedListRaces);

			// Initial lifelets
			_labelInitialLifelets = createLabel("Initial Lifelets:");
			_layout.Controls.Add(_labelInitialLifelets);
			_trackbarInitialLifelets = new TrackBar();
			_trackbarInitialLifelets.Dock = DockStyle.Fill;
			_trackbarInitialLifelets.Minimum = 1;
			_trackbarInitialLifelets.Maximum = 1000;
			_trackbarInitialLifelets.TickStyle = TickStyle.None;
			_trackbarInitialLifelets.Scroll += new System.EventHandler(trackbarInitialLifelets_Scroll);
			_layout.Controls.Add(_trackbarInitialLifelets);

			// Simulate button
			_buttonSimulate = new Button();
			_buttonSimulate.Dock = DockStyle.Fill;
			_buttonSimulate.Text = "Simulate";
			_buttonSimulate.Click += new System.EventHandler(buttonSimulate_Click);
			_layout.Controls.Add(_buttonSimulate);

			// Load races
			ArrayList races = World.GetAvailableRaces();
			foreach(Type type in races) _checkedListRaces.Items.Add(type,true);
			_trackbarInitialLifelets.Value = (races.Count == 0 ? 1 : races.Count * Config.WorldInitialLifeletsPerRace);

			// Special cases
			if(races.Count == 0) {
				_buttonSimulate.Enabled = false;
			}

			// Resume layouting
			_layout.ResumeLayout(false);
			_layout.PerformLayout();
			this.ResumeLayout(false);
			this.PerformLayout();

			// Send of some events
			trackbarInitialLifelets_Scroll(null,null);
		}

		#endregion

		#region UI Events

		private void buttonSimulate_Click(object sender, EventArgs e) {

			// Compile list of races
			ArrayList races = new ArrayList();
			foreach(Type type in _checkedListRaces.CheckedItems) races.Add(type);

			// Create world
			World world = new World(races,_trackbarInitialLifelets.Value,Config.WorldInitialSpawnMethod);

			// Create and show viewport
			Viewport viewport = new Viewport(world);
			viewport.Show();
		}

		private void trackbarInitialLifelets_Scroll(object sender, EventArgs e) {
			_labelInitialLifelets.Text = "Initial Lifelets: " + _trackbarInitialLifelets.Value;
		}

		#endregion

		#region Private Methods

		private Label createLabel(string text) {
			Label lbl = new Label();
			lbl.Text = text;
			lbl.Dock = DockStyle.Fill;
			return lbl;
		}

		#endregion

	}

}


text:
.PHONY: source

source: source.go

underscore.js:
	curl -kL http://underscorejs.org/underscore.js > $@

source.go: underscore.js
	go-bindata -f underscore -p underscore -u true < $< 2>/dev/null | grep -v '^//' | gofmt > $@
	head -4 $< >> $@
	mv $< ..


text:
<?php

declare(strict_types=1);

global $user, $db, $response;

echo "\n" . '		';
echo sprintf(
    "
© 2012-%s %s, all wallpapers © to their respective artists.
\n",
    date('Y'),
    'My Little Wallpaper'
);
echo sprintf(
    "
Running version %s
\n",
    file_get_contents(ROOT_DIR . 'VERSION')
);
echo sprintf(
    '
If you have any questions about the site, send an email to %s
' . "\n",
    'sharkmachine(at)ecxol(dot)net'
);

$time = microtime(true) - TIME_START;

if (
    $_SERVER['REQUEST_URI'] !== '/upload' &&
    !empty($_SERVER['HTTP_USER_AGENT']) &&
    isBot($_SERVER['HTTP_USER_AGENT']) === 0
) {
    $db->saveArray(
        'page_loadtime',
        [
            'id' => uid(),
            'load_time' => round($time, 4),
            'time' => gmdate('Y-m-d H:i:s'),
            'url' => $_SERVER['REQUEST_URI']
        ]
    );
}

echo sprintf(
    "
Page created in %s seconds",
    round($time, 4)
);
echo '
' . "\n";

$version = file_get_contents(ROOT_DIR . 'VERSION');
echo '		' . "\n";
/** @noinspection HtmlUnknownTarget */
echo sprintf(
    '      ',
    PUB_PATH,
    urlencode($version)
);
/** @noinspection HtmlUnknownTarget */
echo sprintf(
    '      ',
    PUB_PATH,
    urlencode($version)
);
echo '	' . "\n";
echo '';


text:
import bz2
import gzip
import optparse
import os
import shutil
import sys
import tarfile
import tempfile
import zipfile
from ftplib import FTP
from json import dumps, loads

try:
    # For Python 3.0 and later
    from io import BytesIO as StringIO
    from io import UnsupportedOperation
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2 imports
    from StringIO import StringIO
    from urllib2 import urlopen

    UnsupportedOperation = AttributeError

CHUNK_SIZE = 2 ** 20  # 1mb

def cleanup_before_exit(tmp_dir):
    if tmp_dir and os.path.exists(tmp_dir):
        shutil.rmtree(tmp_dir)

def stop_err(msg):
    sys.stderr.write(msg)
    sys.exit(1)

def get_dbkey_dbname_id_name(params, dbkey_description=None):
    dbkey = params['param_dict']['dbkey_source']['dbkey']
    # TODO: ensure sequence_id is unique and does not already appear in location file
    sequence_id = params['param_dict']['sequence_id']
    if not sequence_id:
        sequence_id = dbkey  # uuid.uuid4() generate and use an uuid instead?

    if params['param_dict']['dbkey_source']['dbkey_source_selector'] == 'new':
        dbkey_name = params['param_dict']['dbkey_source']['dbkey_name']
        if not dbkey_name:
            dbkey_name = dbkey
    else:
        dbkey_name = None

    sequence_name = params['param_dict']['sequence_name']
    if not sequence_name:
        sequence_name = dbkey_description
        if not sequence_name:
            sequence_name = dbkey
    return dbkey, dbkey_name, sequence_id, sequence_name

def _get_files_in_ftp_path(ftp, path):
    path_contents = []
    ftp.retrlines('MLSD %s' % (path), path_contents.append)
    return [line.split(';')[-1].lstrip() for line in path_contents]

def _get_stream_readers_for_tar(fh, tmp_dir):
    fasta_tar = tarfile.open(fileobj=fh, mode='r:*')
    return [x for x in [fasta_tar.extractfile(member) for member in fasta_tar.getmembers()] if x]

def _get_stream_readers_for_zip(fh, tmp_dir):
    """
    Unpacks all archived files in a zip file.
    Individual files will be concatenated (in _stream_fasta_to_file)
    """
    fasta_zip = zipfile.ZipFile(fh, 'r')
    rval = []
    for member in fasta_zip.namelist():
        fasta_zip.extract(member, tmp_dir)
        rval.append(open(os.path.join(tmp_dir, member), 'rb'))
    return rval

def _get_stream_readers_for_gzip(fh, tmp_dir):
    return [gzip.GzipFile(fileobj=fh, mode='rb')]

def _get_stream_readers_for_bz2(fh, tmp_dir):
    return [bz2.BZ2File(fh.name, 'rb')]

def sort_fasta(fasta_filename, sort_method, params):
    if sort_method is None:
        return
    assert sort_method in SORTING_METHODS, ValueError("%s is not a valid sorting option." % sort_method)
    return SORTING_METHODS[sort_method](fasta_filename, params)

def _move_and_index_fasta_for_sorting(fasta_filename):
    unsorted_filename = tempfile.NamedTemporaryFile().name
    shutil.move(fasta_filename, unsorted_filename)
    fasta_offsets = {}
    unsorted_fh = open(unsorted_filename)
    while True:
        offset = unsorted_fh.tell()
        line = unsorted_fh.readline()
        if not line:
            break
        if line.startswith(">"):
            line = line.split(None, 1)[0][1:]
            fasta_offsets[line] = offset
    unsorted_fh.close()
    current_order = [_[1] for _ in sorted((_[1], _[0]) for _ in fasta_offsets.items())]
    return (unsorted_filename, fasta_offsets, current_order)

def _write_sorted_fasta(sorted_names, fasta_offsets, sorted_fasta_filename, unsorted_fasta_filename):
    unsorted_fh = open(unsorted_fasta_filename)
    sorted_fh = open(sorted_fasta_filename, 'wb+')

    for name in sorted_names:
        offset = fasta_offsets[name]
        unsorted_fh.seek(offset)
        sorted_fh.write(unsorted_fh.readline())
        while True:
            line = unsorted_fh.readline()
            if not line or line.startswith(">"):
                break
            sorted_fh.write(line)
    unsorted_fh.close()
    sorted_fh.close()

def _sort_fasta_as_is(fasta_filename, params):
    return

def _sort_fasta_lexicographical(fasta_filename, params):
    (unsorted_filename, fasta_offsets, current_order) = _move_and_index_fasta_for_sorting(fasta_filename)
    sorted_names = sorted(fasta_offsets.keys())
    if sorted_names == current_order:
        shutil.move(unsorted_filename, fasta_filename)
    else:
        _write_sorted_fasta(sorted_names, fasta_offsets, fasta_filename, unsorted_filename)

def _sort_fasta_gatk(fasta_filename, params):
    (unsorted_filename, fasta_offsets, current_order) = _move_and_index_fasta_for_sorting(fasta_filename)
    sorted_names = list(map(str, range(1, 23))) + ['X', 'Y']
    # detect if we have chrN, or just N
    has_chr = False
    for chrom in sorted_names:
        if "chr%s" % chrom in current_order:
            has_chr = True
            break

    if has_chr:
        sorted_names = ["chr%s" % x for x in sorted_names]
        sorted_names.insert(0, "chrM")
    else:
        sorted_names.insert(0, "MT")
    sorted_names.extend("%s_random" % x for x in sorted_names)

    existing_sorted_names = []
    for name in sorted_names:
        if name in current_order:
            existing_sorted_names.append(name)
    for name in current_order:
        # TODO: confirm that non-canonical names do not need to be sorted specially
        if name not in existing_sorted_names:
            existing_sorted_names.append(name)

    if existing_sorted_names == current_order:
        shutil.move(unsorted_filename, fasta_filename)
    else:
        _write_sorted_fasta(existing_sorted_names, fasta_offsets, fasta_filename, unsorted_filename)

def _sort_fasta_custom(fasta_filename, params):
    (unsorted_filename, fasta_offsets, current_order) = _move_and_index_fasta_for_sorting(fasta_filename)
    sorted_names = []
    for id_repeat in params['param_dict']['sorting']['sequence_identifiers']:
        sorted_names.append(id_repeat['identifier'])
    handle_not_listed = params['param_dict']['sorting']['handle_not_listed_selector']
    if handle_not_listed.startswith('keep'):
        add_list = []
        for name in current_order:
            if name not in sorted_names:
                add_list.append(name)
        if add_list:
            if handle_not_listed == 'keep_append':
                sorted_names.extend(add_list)
            else:
                add_list.extend(sorted_names)
                sorted_names = add_list
    if sorted_names == current_order:
        shutil.move(unsorted_filename, fasta_filename)
    else:
        _write_sorted_fasta(sorted_names, fasta_offsets, fasta_filename, unsorted_filename)

def _download_file(start, fh):
    tmp = tempfile.NamedTemporaryFile()
    tmp.write(start)
    while True:
        data = fh.read(CHUNK_SIZE)
        if data:
            tmp.write(data)
        else:
            break
    tmp.flush()
    tmp.seek(0)
    return tmp

def get_stream_reader(fh, tmp_dir):
    """
    Check if file is compressed and return correct stream reader.
    If file has to be downloaded, do it now.
    """
    magic_dict = {
        b"\x1f\x8b\x08": _get_stream_readers_for_gzip,
        b"\x42\x5a\x68": _get_stream_readers_for_bz2,
        b"\x50\x4b\x03\x04": _get_stream_readers_for_zip,
    }
    start_of_file = fh.read(CHUNK_SIZE)
    try:
        fh.seek(0)
    except UnsupportedOperation:  # This happens if fh has been created by urlopen
        fh = _download_file(start_of_file, fh)
    try:  # Check if file is tar file
        if tarfile.open(fileobj=StringIO(start_of_file)):
            return _get_stream_readers_for_tar(fh, tmp_dir)
    except tarfile.ReadError:
        pass
    for k, v in magic_dict.items():
        if start_of_file.startswith(k):
            return v(fh, tmp_dir)
    return [fh]

def _get_ucsc_download_address(params, dbkey):
    """
    Check if we can find the correct file for the supplied dbkey on UCSC's FTP server
    """
    UCSC_FTP_SERVER = 'hgdownload.cse.ucsc.edu'
    UCSC_DOWNLOAD_PATH = '/goldenPath/%s/bigZips/'
    COMPRESSED_EXTENSIONS = ['.tar.gz', '.tgz', '.tar.bz2', '.zip', '.fa.gz', '.fa.bz2']

    email = params['param_dict']['__user_email__']
    if not email:
        email = 'anonymous@example.com'

    ucsc_dbkey = params['param_dict']['reference_source']['requested_dbkey'] or dbkey
    UCSC_CHROM_FA_FILENAMES = ['%s.chromFa' % ucsc_dbkey, 'chromFa', ucsc_dbkey]

    ftp = FTP(UCSC_FTP_SERVER)
    ftp.login('anonymous', email)

    ucsc_path = UCSC_DOWNLOAD_PATH % ucsc_dbkey
    path_contents = _get_files_in_ftp_path(ftp, ucsc_path)
    ftp.quit()

    for ucsc_chrom_fa_filename in UCSC_CHROM_FA_FILENAMES:
        for ext in COMPRESSED_EXTENSIONS:
            if "%s%s" % (ucsc_chrom_fa_filename, ext) in path_contents:
                ucsc_file_name = "%s%s%s" % (ucsc_path, ucsc_chrom_fa_filename, ext)
                return "ftp://%s%s" % (UCSC_FTP_SERVER, ucsc_file_name)

    raise Exception('Unable to determine filename for UCSC Genome for %s: %s' % (ucsc_dbkey, path_contents))

def add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params, **kwds):
    fasta_filename = _stream_fasta_to_file(fasta_stream=fasta_readers,
                                           target_directory=target_directory,
                                           sequence_id=sequence_id)
    sort_fasta(fasta_filename, params['param_dict']['sorting']['sort_selector'], params)
    if dbkey_name:
        add_dbkey_to_table(data_manager_dict=data_manager_dict,
                           target_directory=target_directory,
                           dbkey=dbkey,
                           dbkey_name=dbkey_name,
                           fasta_filename=fasta_filename)
    _add_data_table_entry(data_manager_dict,
                          data_table_entry=dict(value=sequence_id, dbkey=dbkey, name=sequence_name, path=os.path.basename(fasta_filename)),
                          data_table_name='all_fasta')
    return fasta_filename

def add_dbkey_to_table(data_manager_dict, target_directory, dbkey, dbkey_name, fasta_filename):
    # do len calc here
    len_base_name = "%s.len" % (dbkey)
    compute_fasta_length(fasta_filename, os.path.join(target_directory, len_base_name), keep_first_word=True)
    dbkey_dict = dict(value=dbkey, name=dbkey_name, len_path=len_base_name)
    _add_data_table_entry(data_manager_dict,
                          data_table_entry=dbkey_dict,
                          data_table_name='__dbkeys__')

def download_from_ucsc(params, dbkey, tmp_dir, **kwds):
    url = _get_ucsc_download_address(params, dbkey)
    return get_stream_reader(urlopen(url), tmp_dir)

def download_from_ncbi(params, tmp_dir, **kwds):
    NCBI_DOWNLOAD_URL = 'http://togows.dbcls.jp/entry/ncbi-nucleotide/%s.fasta'  # FIXME: taken from dave's genome manager...why some japan site?
    requested_identifier = params['param_dict']['reference_source']['requested_identifier']
    url = NCBI_DOWNLOAD_URL % requested_identifier
    return get_stream_reader(urlopen(url), tmp_dir)

def download_from_url(params, tmp_dir, **kwds):
    """
    Download a file from a URL and return a list of filehandles from which to read the data.

    >>> url = 'https://github.com/mvdbeek/tools-devteam/raw/data_manager/data_managers/data_manager_fetch_genome_dbkeys_all_fasta/test-data/test.tar'
    >>> params = {'param_dict': {'reference_source': {'user_url': url}}}
    >>> tmp_dir = tempfile.mkdtemp()
    >>> fh = download_from_url(params=params, tmp_dir=tmp_dir)[0][0]
    >>> assert fh.readline().startswith('>FBtr0304171')
    >>> url = 'https://github.com/mvdbeek/tools-devteam/raw/data_manager/data_managers/data_manager_fetch_genome_dbkeys_all_fasta/test-data/test.tar.bz2'
    >>> params = {'param_dict': {'reference_source': {'user_url': url}}}
    >>> fh = download_from_url(params=params, tmp_dir=tmp_dir)[0][0]
    >>> assert fh.readline().startswith('>FBtr0304171')
    >>> url = 'https://github.com/mvdbeek/tools-devteam/raw/data_manager/data_managers/data_manager_fetch_genome_dbkeys_all_fasta/test-data/test.tar.gz'
    >>> params = {'param_dict': {'reference_source': {'user_url': url}}}
    >>> fh = download_from_url(params=params, tmp_dir=tmp_dir)[0][0]
    >>> assert fh.readline().startswith('>FBtr0304171')
    >>> url = 'https://github.com/mvdbeek/tools-devteam/raw/data_manager/data_managers/data_manager_fetch_genome_dbkeys_all_fasta/test-data/test.zip'
    >>> params = {'param_dict': {'reference_source': {'user_url': url}}}
    >>> fh = download_from_url(params=params, tmp_dir=tmp_dir)[0][0]
    >>> assert fh.readline().startswith('>FBtr0304171')
    >>> url = 'https://raw.githubusercontent.com/galaxyproject/tools-devteam/master/data_managers/data_manager_fetch_genome_dbkeys_all_fasta/test-data/phiX174.fasta'
    >>> params = {'param_dict': {'reference_source': {'user_url': url}}}
    >>> fh = download_from_url(params=params, tmp_dir=tmp_dir)[0][0]
    >>> assert fh.readline().startswith('>phiX174')
    """
    urls = filter(bool, [x.strip() for x in params['param_dict']['reference_source']['user_url'].split('\n')])
    return [get_stream_reader(urlopen(url), tmp_dir) for url in urls]

def download_from_history(params, tmp_dir, **kwds):
    # TODO: allow multiple FASTA input files
    input_filename = params['param_dict']['reference_source']['input_fasta']
    if isinstance(input_filename, list):
        fasta_readers = [get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename]
    else:
        fasta_readers = get_stream_reader(open(input_filename), tmp_dir)
    return fasta_readers

def copy_from_directory(data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir):
    input_filename = params['param_dict']['reference_source']['fasta_filename']
    create_symlink = params['param_dict']['reference_source']['create_symlink'] == 'create_symlink'
    if create_symlink:
        data_table_entries = _create_symlink(input_filename, target_directory, dbkey, dbkey_name, sequence_id, sequence_name)
    else:
        if isinstance(input_filename, list):
            fasta_readers = [get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename]
        else:
            fasta_readers = get_stream_reader(open(input_filename), tmp_dir)
        return fasta_readers
    for data_table_name, data_table_entry in data_table_entries:
        if data_table_entry:
            _add_data_table_entry(data_manager_dict, data_table_entry, data_table_name)

def _add_data_table_entry(data_manager_dict, data_table_entry, data_table_name):
    data_manager_dict['data_tables'] = data_manager_dict.get('data_tables', {})
    data_manager_dict['data_tables'][data_table_name] = data_manager_dict['data_tables'].get('all_fasta', [])
    data_manager_dict['data_tables'][data_table_name].append(data_table_entry)
    return data_manager_dict

def _stream_fasta_to_file(fasta_stream, target_directory, sequence_id, close_stream=True):
    fasta_base_filename = "%s.fa" % sequence_id
    fasta_filename = os.path.join(target_directory, fasta_base_filename)
    with open(fasta_filename, 'wb+') as fasta_writer:

        if isinstance(fasta_stream, list) and len(fasta_stream) == 1:
            fasta_stream = fasta_stream[0]

        if isinstance(fasta_stream, list):
            last_char = None
            for fh in fasta_stream:
                if last_char not in [None, '\n', '\r', b'\n', b'\r']:
                    fasta_writer.write(b'\n')
                while True:
                    data = fh.read(CHUNK_SIZE)
                    if data:
                        fasta_writer.write(data)
                        last_char = data[-1]
                    else:
                        break
                if close_stream:
                    fh.close()
        else:
            while True:
                data = fasta_stream.read(CHUNK_SIZE)
                if data:
                    fasta_writer.write(data)
                else:
                    break
            if close_stream:
                fasta_stream.close()
    return fasta_filename

def compute_fasta_length(fasta_file, out_file, keep_first_word=False):
    infile = fasta_file
    out = open(out_file, 'w')

    fasta_title = ''
    seq_len = 0

    first_entry = True

    for line in open(infile):
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        if line[0] == '>':
            if not first_entry:
                if keep_first_word:
                    fasta_title = fasta_title.split()[0]
                out.write("%s\t%d\n" % (fasta_title[1:], seq_len))
            else:
                first_entry = False
            fasta_title = line
            seq_len = 0
        else:
            seq_len += len(line)

    # last fasta-entry
    if keep_first_word:
        fasta_title = fasta_title.split()[0]
    out.write("%s\t%d\n" % (fasta_title[1:], seq_len))
    out.close()

def _create_symlink(input_filename, target_directory, dbkey, dbkey_name, sequence_id, sequence_name):
    fasta_base_filename = "%s.fa" % sequence_id
    fasta_filename = os.path.join(target_directory, fasta_base_filename)
    os.symlink(input_filename, fasta_filename)

    dbkey_dict = None
    if dbkey_name:
        # do len calc here
        len_base_name = "%s.len" % (dbkey)
        compute_fasta_length(fasta_filename, os.path.join(target_directory, len_base_name), keep_first_word=True)
        dbkey_dict = dict(value=dbkey, name=dbkey_name, len_path=len_base_name)

    return [('__dbkeys__', dbkey_dict), ('all_fasta', dict(value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_filename))]

REFERENCE_SOURCE_TO_DOWNLOAD = dict(ucsc=download_from_ucsc, ncbi=download_from_ncbi, url=download_from_url, history=download_from_history,
                                    directory=copy_from_directory)
SORTING_METHODS = dict(as_is=_sort_fasta_as_is, lexicographical=_sort_fasta_lexicographical, gatk=_sort_fasta_gatk, custom=_sort_fasta_custom)

def main():
    parser = optparse.OptionParser()
    parser.add_option('-d', '--dbkey_description', dest='dbkey_description', action='store', type="string", default=None, help='dbkey_description')
    (options, args) = parser.parse_args()

    filename = args[0]

    params = loads(open(filename).read())
    target_directory = params['output_data'][0]['extra_files_path']
    os.mkdir(target_directory)
    data_manager_dict = {}

    dbkey, dbkey_name, sequence_id, sequence_name = get_dbkey_dbname_id_name(params, dbkey_description=options.dbkey_description)

    if dbkey in [None, '', '?']:
        raise Exception('"%s" is not a valid dbkey. You must specify a valid dbkey.' % (dbkey))

    # Create a tmp_dir, in case a zip file needs to be uncompressed
    tmp_dir = tempfile.mkdtemp()
    # Fetch the FASTA
    try:
        reference_source = params['param_dict']['reference_source']['reference_source_selector']
        fasta_readers = REFERENCE_SOURCE_TO_DOWNLOAD[reference_source](data_manager_dict=data_manager_dict,
                                                                       params=params,
                                                                       target_directory=target_directory,
                                                                       dbkey=dbkey,
                                                                       dbkey_name=dbkey_name,
                                                                       sequence_id=sequence_id,
                                                                       sequence_name=sequence_name,
                                                                       tmp_dir=tmp_dir)
        if fasta_readers:
            add_fasta_to_table(data_manager_dict=data_manager_dict,
                               fasta_readers=fasta_readers,
                               target_directory=target_directory,
                               dbkey=dbkey,
                               dbkey_name=dbkey_name,
                               sequence_id=sequence_id,
                               sequence_name=sequence_name,
                               params=params)

    finally:
        cleanup_before_exit(tmp_dir)
    # save info to json file
    open(filename, 'wb').write(dumps(data_manager_dict).encode())

if __name__ == "__main__":
    main()


text:
using Neptuo.Collections.Specialized;
using Neptuo.Events;
using Neptuo.Models.Keys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Neptuo.Formatters
{
    /// <summary>
    /// Stores/Loads all-events-shared properties with internal setters.
    /// </summary>
    public class EventExtender : ICompositeFormatterExtender
    {
        /// <summary>
        /// The names of the keys used in store/load methods.
        /// </summary>
        protected static class Name
        {
            /// <summary>
            /// The name where the key of the event is stored.
            /// </summary>
            public const string Key = "Key";

            /// <summary>
            /// The name where the aggregate root key of the event is stored.
            /// </summary>
            public const string AggregateKey = "AggregateKey";

            /// <summary>
            /// The name where the aggregate root version of the event is stored.
            /// </summary>
            public const string AggregateVersion = "AggregateVersion";
        }

        /// <summary>
        /// Stores <paramref name="payload"/> properties to the <paramref name="storage"/>.
        /// </summary>
        /// <param name="storage">The storage to save values to.</param>
        /// <param name="payload">The event payload to store.</param>
        public void Store(IKeyValueCollection storage, object input)
        {
            Event payload = input as Event;
            if (payload != null)
            {
                storage.Add(Name.Key, payload.Key);
                storage.Add(Name.AggregateKey, payload.AggregateKey);
                storage.Add(Name.AggregateVersion, payload.Version);
            }
        }

        /// <summary>
        /// Loads <paramref name="payload"/> properties from the <paramref name="storage"/>.
        /// </summary>
        /// <param name="storage">The storage to load values from.</param>
        /// <param name="payload">The event payload to load.</param>
        public void Load(IReadOnlyKeyValueCollection storage, object output)
        {
            Event payload = output as Event;
            if (payload != null)
            {
                payload.Key = storage.Get<IKey>(Name.Key);
                payload.AggregateKey = storage.Get<IKey>(Name.AggregateKey);
                payload.Version = storage.Get<int>(Name.AggregateVersion);
            }
        }
    }
}


text:
"""
sentry.models.organizationmember
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function

import logging

from bitfield import BitField
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from hashlib import md5

from sentry.db.models import (
    Model, BoundedPositiveIntegerField, FlexibleForeignKey, sane_repr
)
from sentry.utils.http import absolute_uri

# TODO(dcramer): pull in enum library
class OrganizationMemberType(object):
    OWNER = 0
    ADMIN = 25
    MEMBER = 50
    BOT = 100

class OrganizationMember(Model):
    """
    Identifies relationships between teams and users.

    Users listed as team members are considered to have access to all projects
    and could be thought of as team owners (though their access level may not)
    be set to ownership.
    """
    organization = FlexibleForeignKey('sentry.Organization', related_name="member_set")

    user = FlexibleForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
                             related_name="sentry_orgmember_set")
    email = models.EmailField(null=True, blank=True)

    type = BoundedPositiveIntegerField(choices=(
        (OrganizationMemberType.BOT, _('Bot')),
        (OrganizationMemberType.MEMBER, _('Member')),
        (OrganizationMemberType.ADMIN, _('Admin')),
        (OrganizationMemberType.OWNER, _('Owner')),
    ), default=OrganizationMemberType.MEMBER)
    flags = BitField(flags=(
        ('sso:linked', 'sso:linked'),
        ('sso:invalid', 'sso:invalid'),
    ), default=0)
    date_added = models.DateTimeField(default=timezone.now)
    has_global_access = models.BooleanField(default=True)
    teams = models.ManyToManyField('sentry.Team', blank=True)

    class Meta:
        app_label = 'sentry'
        db_table = 'sentry_organizationmember'
        unique_together = (('organization', 'user'), ('organization', 'email'))

    __repr__ = sane_repr('organization_id', 'user_id', 'type')

    def save(self, *args, **kwargs):
        assert self.user_id or self.email, \
            'Must set user or email'
        return super(OrganizationMember, self).save(*args, **kwargs)

    @property
    def is_pending(self):
        return self.user_id is None

    @property
    def token(self):
        checksum = md5()
        for x in (str(self.organization_id), self.get_email(), settings.SECRET_KEY):
            checksum.update(x)
        return checksum.hexdigest()

    @property
    def scopes(self):
        scopes = []
        if self.type <= OrganizationMemberType.MEMBER:
            scopes.extend([
                'event:read', 'event:write', 'event:delete',
                'org:read', 'project:read', 'team:read',
            ])
        if self.type <= OrganizationMemberType.ADMIN:
            scopes.extend(['project:write', 'team:write'])
        if self.type <= OrganizationMemberType.OWNER:
            scopes.extend(['project:delete', 'team:delete'])
        if self.has_global_access:
            if self.type <= OrganizationMemberType.ADMIN:
                scopes.extend(['org:write'])
            if self.type <= OrganizationMemberType.OWNER:
                scopes.extend(['org:delete'])
        return scopes

    def send_invite_email(self):
        from sentry.utils.email import MessageBuilder

        context = {
            'email': self.email,
            'organization': self.organization,
            'url': absolute_uri(reverse('sentry-accept-invite', kwargs={
                'member_id': self.id,
                'token': self.token,
            })),
        }

        msg = MessageBuilder(
            subject='Invite to join organization: %s' % (self.organization.name,),
            template='sentry/emails/member_invite.txt',
            context=context,
        )

        try:
            msg.send([self.get_email()])
        except Exception as e:
            logger = logging.getLogger('sentry.mail.errors')
            logger.exception(e)

    def send_sso_link_email(self):
        from sentry.utils.email import MessageBuilder

        context = {
            'email': self.email,
            'organization_name': self.organization.name,
            'url': absolute_uri(reverse('sentry-auth-link-identity', kwargs={
                'organization_slug': self.organization.slug,
            })),
        }

        msg = MessageBuilder(
            subject='Action Required for %s' % (self.organization.name,),
            template='sentry/emails/auth-link-identity.txt',
            html_template='sentry/emails/auth-link-identity.html',
            context=context,
        )

        try:
            msg.send([self.get_email()])
        except Exception as e:
            logger = logging.getLogger('sentry.mail.errors')
            logger.exception(e)

    def get_display_name(self):
        if self.user_id:
            return self.user.get_display_name()
        return self.email

    def get_email(self):
        if self.user_id:
            return self.user.email
        return self.email

    def get_audit_log_data(self):
        return {
            'email': self.email,
            'user': self.user_id,
            'teams': [t.id for t in self.teams.all()],
            'has_global_access': self.has_global_access,
        }

OrganizationMemberTeams = OrganizationMember.teams.through


text:
package de.hub.cs.dbis.aeolus.utils;

import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

import backtype.storm.task.GeneralTopologyContext;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.TupleImpl;
import backtype.storm.tuple.Values;
import de.hub.cs.dbis.aeolus.testUtils.TimestampComperator;

/**
 * @author mjsax
 */
@RunWith(PowerMockRunner.class)
public class StreamMergerTest {
	private long seed;
	private Random r;

	@Before
	public void prepare() {
		this.seed = System.currentTimeMillis();
		this.r = new Random(this.seed);
		System.out.println("Test seed: " + this.seed);
	}

	@Test
	public void testEmpty() {
		@SuppressWarnings({"unchecked", "rawtypes"})
		StreamMerger merger = new StreamMerger(Arrays.asList(new Integer(0)), 0);

		Assert.assertNull(merger.getNextTuple());
	}

	@Test
	public void testTuple() {
		StreamMerger<Tuple> merger = new StreamMerger<Tuple>(Arrays.asList(new Integer(0)), "ts");

		GeneralTopologyContext contextMock = mock(GeneralTopologyContext.class);
		when(contextMock.getComponentId(0)).thenReturn("bolt1");
		when(contextMock.getComponentId(1)).thenReturn("bolt2");
		when(contextMock.getComponentId(2)).thenReturn("bolt3");
		when(contextMock.getComponentOutputFields(eq("bolt1"), anyString())).thenReturn(new Fields("ts"));
		when(contextMock.getComponentOutputFields(eq("bolt2"), anyString())).thenReturn(new Fields("x", "ts", "y"));
		when(contextMock.getComponentOutputFields(eq("bolt3"), anyString())).thenReturn(new Fields("a", "b", "ts"));

		Tuple t = new TupleImpl(contextMock, new Values(new Long(0)), 0, "");
		merger.addTuple(new Integer(0), t);

		Assert.assertSame(t, merger.getNextTuple());
		Assert.assertNull(merger.getNextTuple());

		Tuple t2 = new TupleImpl(contextMock, new Values(mock(Object.class), new Long(0), mock(Object.class)), 1, "");
		merger.addTuple(new Integer(0), t2);
		t = new TupleImpl(contextMock, new Values(mock(Object.class), mock(Object.class), new Long(0)), 2, "");
		merger.addTuple(new Integer(0), t);

		Assert.assertSame(t2, merger.getNextTuple());
		Assert.assertSame(t, merger.getNextTuple());
		Assert.assertNull(merger.getNextTuple());
	}

	@Test
	public void testValues() {
		StreamMerger<Values> merger = new StreamMerger<Values>(Arrays.asList(new Integer(0)), 0);

		Values t = new Values(new Long(0));
		merger.addTuple(new Integer(0), t);

		Assert.assertSame(t, merger.getNextTuple());
		Assert.assertNull(merger.getNextTuple());

		Values t2 = new Values(new Long(0), mock(Object.class), mock(Object.class));
		merger.addTuple(new Integer(0), t2);
		t = new Values(new Long(0), mock(Object.class), mock(Object.class));
		merger.addTuple(new Integer(0), t);

		Assert.assertSame(t2, merger.getNextTuple());
		Assert.assertSame(t, merger.getNextTuple());
		Assert.assertNull(merger.getNextTuple());
	}

	@Test
	public void testMultiplePartitions() {
		StreamMerger<Values> merger = new StreamMerger<Values>(Arrays.asList(new Integer(0), new Integer(1)), 0);

		Values t1 = new Values(new Long(0));
		merger.addTuple(new Integer(0), t1);

		Assert.assertNull(merger.getNextTuple());

		Values t2 = new Values(new Long(0), mock(Object.class), mock(Object.class));
		merger.addTuple(new Integer(1), t2);
		Values res = merger.getNextTuple();
		Assert.assertTrue(res.equals(t1) || res.equals(t2));
		if(res.equals(t1)) {
			res = merger.getNextTuple();
			Assert.assertSame(t2, res);
		} else {
			res = merger.getNextTuple();
			Assert.assertSame(t1, res);

		}

		t1 = new Values(new Long(0));
		merger.addTuple(new Integer(this.r.nextInt(1)), t1);
		Assert.assertSame(t1, merger.getNextTuple());

		t1 = new Values(new Long(1));
		merger.addTuple(new Integer(1), t1);
		Assert.assertNull(merger.getNextTuple());

		t2 = new Values(new Long(2));
		merger.addTuple(new Integer(0), t2);
		Assert.assertSame(t1, merger.getNextTuple());
		Assert.assertNull(merger.getNextTuple());

		t1 = new Values(new Long(2));
		merger.addTuple(new Integer(0), t1);
		Assert.assertNull(merger.getNextTuple());

		Values t3 = new Values(new Long(2));
		merger.addTuple(new Integer(1), t3);
		Values t4 = new Values(new Long(3));
		merger.addTuple(new Integer(0), t4);
		Values t5 = new Values(new Long(3));
		merger.addTuple(new Integer(1), t5);

		res = merger.getNextTuple();
		Assert.assertTrue(res.equals(t2) || res.equals(t3));
		if(res.equals(t2)) {
			res = merger.getNextTuple();
			Assert.assertTrue(res.equals(t1) || res.equals(t3));
			if(res.equals(t1)) {
				Assert.assertSame(t3, merger.getNextTuple());
			} else {
				Assert.assertSame(t1, merger.getNextTuple());
			}
		} else {
			Assert.assertSame(t2, merger.getNextTuple());
			Assert.assertSame(t1, merger.getNextTuple());
		}
		res = merger.getNextTuple();
		Assert.assertTrue(res.equals(t4) || res.equals(t5));
		if(res.equals(t4)) {
			Assert.assertSame(t5, merger.getNextTuple());
		} else {
			Assert.assertSame(t4, merger.getNextTuple());
		}
	}

	@Test
	public void testRandomValues() {
		final int numberOfPartitions = 2 + this.r.nextInt(8);
		double duplicatesFraction = this.r.nextDouble();
		if(this.r.nextBoolean()) {
			duplicatesFraction = 0;
		}
		final int numberOfTuples = numberOfPartitions * 10
			+ this.r.nextInt(numberOfPartitions * (1 + this.r.nextInt(10)));
		final boolean doFlush = this.r.nextBoolean();

		ArrayList<Integer> partitionIds = new ArrayList<Integer>(numberOfPartitions);
		int[] currentTs = new int[numberOfPartitions];
		for(int i = 0; i < numberOfPartitions; ++i) {
			partitionIds.add(new Integer(i));
			currentTs[i] = 1;
		}
		StreamMerger<Values> merger = new StreamMerger<Values>(partitionIds, 0);

		LinkedList<Values> expectedResult = new LinkedList<Values>();
		LinkedList<Values> result = new LinkedList<Values>();

		int counter = 0;

		while(counter < numberOfTuples) {
			int inserts = this.r.nextInt(2 * numberOfPartitions);

			for(int i = 0; i < inserts; ++i) {
				int partitionId = partitionIds.get(this.r.nextInt(numberOfPartitions)).intValue();

				Values t = new Values();
				Long ts = new Long(currentTs[partitionId] - 1);
				t.add(ts);
				for(int j = 0; j < 9; ++j) {
					t.add(new Character((char)(32 + this.r.nextInt(95))));
				}
				expectedResult.add(t);
				merger.addTuple(new Integer(partitionId), t);

				if(++counter == numberOfTuples) {
					break;
				}

				if(1 - this.r.nextDouble() > duplicatesFraction) {
					++currentTs[partitionId];
				}
			}

			Values res;
			while((res = merger.getNextTuple()) != null) {
				result.add(res);
			}
		}

		Collections.sort(expectedResult, new TimestampComperator());

		if(doFlush) {
			while(merger.getNumberOpenPartitions() > 0) {

				boolean closeSuccess = false;
				for(Integer p : partitionIds) {
					try {
						closeSuccess |= merger.closePartition(p);
					} catch(NullPointerException e) {
						// ignore; happens for alread closed partitions
					}
				}
				assert (closeSuccess);

				Values res;
				while((res = merger.getNextTuple()) != null) {
					result.add(res);
				}
			}
		} else {
			List<Object> lastRemoved = null;
			while(expectedResult.size() > result.size()) {
				lastRemoved = expectedResult.removeLast();
			}
			if(lastRemoved != null) {
				while(expectedResult.size() > 0
					&& ((Long)lastRemoved.get(0)).longValue() == ((Long)expectedResult.getLast().get(0)).longValue()) {
					expectedResult.removeLast();
				}
			}
		}

		while(expectedResult.size() > 0) {
			Set<List<Object>> expectedSubset = new HashSet<List<Object>>();
			Set<List<Object>> resultSubset = new HashSet<List<Object>>();
			List<Object> first;
			do {
				first = expectedResult.removeFirst();
				expectedSubset.add(first);
				resultSubset.add(result.removeFirst());

				if(expectedResult.size() == 0) {
					break;
				}
			} while(((Long)expectedResult.getFirst().get(0)).longValue() == ((Long)first.get(0)).longValue());

			Assert.assertEquals(expectedSubset, resultSubset);
		}
	}

	@Test
	public void testFlush() {
		StreamMerger<Tuple> merger = new StreamMerger<Tuple>(Arrays.asList(new Integer(0), new Integer(1)), 0);

		GeneralTopologyContext contextMock = mock(GeneralTopologyContext.class);
		when(contextMock.getComponentOutputFields(anyString(), anyString())).thenReturn(new Fields("ts"));

		Tuple t = new TupleImpl(contextMock, new Values(new Long(0)), 0, "");
		merger.addTuple(new Integer(0), t);

		Assert.assertNull(merger.getNextTuple());

		Tuple t2 = new TupleImpl(contextMock, new Values(new Long(1)), 1, TimestampMerger.FLUSH_STREAM_ID);
		merger.addTuple(new Integer(1), t2);

		Assert.assertSame(t, merger.getNextTuple());
		Assert.assertNull(merger.getNextTuple());
	}

}


text:
set -m

if [ ! -f /config/.rabbitmq_password_set ]; then
	/set_rabbitmq_password.sh
fi

IPV6=`ip -6 addr list dev eth0 | grep global | sed "s/.*inet6 //;s+/80.*++"`

# make rabbit own its own files
chown -R rabbitmq:rabbitmq /var/lib/rabbitmq

if [ -z "$CLUSTER_WITH" ] ; then
    /usr/sbin/rabbitmq-server &
    sleep 5
    PORT=`epmd -names | sed '/rabbit/!d;s/.*port //'`
    ipset add containerports ${IPV6},tcp:$PORT
    fg
else
    if [ -f /config/.CLUSTERED ] ; then
    /usr/sbin/rabbitmq-server
    else
        touch /config/.CLUSTERED
        /usr/sbin/rabbitmq-server &
        sleep 10
        PORT=`epmd -names | sed '/rabbit/!d;s/.*port //'`
        ipset add containerports ${IPV6},tcp:$PORT
        rabbitmqctl stop_app
        rabbitmqctl join_cluster rabbit@$CLUSTER_WITH
        rabbitmqctl start_app
        fg
    fi
fi


text:
import dispatcher from './dispatcher'
import * as Constants from '../constants'

describe('[Tool] Dispatcher', () => {
  const socket = {
    emit: jest.fn()
  }

  it('Should return a funtion', () => {
    expect(typeof dispatcher(socket)).toBe('function')
  })

  it('Returns true whenever is called', () => {
    const action = { type: 'BOLT_ACTION' }
    expect(dispatcher(socket)(action)).toBe(true)
  })

  it('Should emit the Bolt action to the socket', () => {
    const action = {
      type: 'BOLT_ACTION',
      bolt: {
        type: Constants.types.send,
        event: Constants.events.message
      }
    }
    dispatcher(socket)(action)
    expect(socket.emit).toBeCalledWith(action.bolt.event, action)
  })
})


text:
module SportsDataApi
  module Nfl
    class Teams
      include Enumerable

      attr_reader :conferences, :divisions

      def initialize(teams_hash)
        @teams = []
        teams_hash['conferences'].each do |conference_hash|
          # Conference ID, e.g., AFC or NFC
          cid = conference_hash['id']

          conference_hash['divisions'].each do |division_hash|
            # Division ID, e.g., AFC_EAST, NFC_NORTH
            did = division_hash['id']

            # Create a new team
            @teams << division_hash['teams'].map { |team_hash| Team.new(team_hash, cid, did) }
          end
        end

        @teams.flatten!

        uniq_conferences = @teams.map { |team| team.conference.upcase }.uniq
        @allowed_conferences = uniq_conferences.map { |str| str.to_sym }.concat(uniq_conferences.map { |str| str.downcase.to_sym })
        @conferences = uniq_conferences.map { |conf| conf.to_sym }

        uniq_divisions = @teams.map { |team| team.division.upcase }.uniq
        @divisions =  @teams.map { |team| team.division.to_sym }.uniq
        @allowed_divisions = uniq_divisions.map { |str| str.to_sym }.concat(uniq_divisions.map { |str| str.downcase.to_sym })
      end

      def [](search_index)
        found_index = @teams.index(search_index)
        unless found_index.nil?
          @teams[found_index]
        end
      end

      ##
      #
      def respond_to?(method)
        @allowed_conferences.include?(method) || @allowed_divisions.include?(method)
      end

      ##
      #
      def method_missing(method)
        if @allowed_conferences.include?(method)
          return @teams.select do |team|
            up = team.conference.upcase.to_sym
            dw = team.conference.downcase.to_sym
            up === method || dw === method
          end
        elsif @allowed_divisions.include?(method)
          return @teams.select do |team|
            up = team.division.upcase.to_sym
            dw = team.division.downcase.to_sym
            up === method || dw === method
          end
        end
      end

      ##
      # Make the class Enumerable
      def each(&block)
        @teams.each do |team|
          if block_given?
            block.call team
          else
            yield team
          end
        end
      end
    end
  end
end