text:
"""Unittests for the various HTTPServer modules.

Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>,
Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
"""

from http.server import BaseHTTPRequestHandler, HTTPServer, \
     SimpleHTTPRequestHandler, CGIHTTPRequestHandler
from http import server, HTTPStatus

import os
import sys
import re
import base64
import ntpath
import shutil
import urllib.parse
import html
import http.client
import tempfile
import time
from io import BytesIO

import unittest
from test import support
threading = support.import_module('threading')

class NoLogRequestHandler:
    def log_message(self, *args):
        # don't write log messages to stderr
        pass

    def read(self, n=None):
        return ''

class TestServerThread(threading.Thread):
    def __init__(self, test_object, request_handler):
        threading.Thread.__init__(self)
        self.request_handler = request_handler
        self.test_object = test_object

    def run(self):
        self.server = HTTPServer(('localhost', 0), self.request_handler)
        self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
        self.test_object.server_started.set()
        self.test_object = None
        try:
            self.server.serve_forever(0.05)
        finally:
            self.server.server_close()

    def stop(self):
        self.server.shutdown()

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        self._threads = support.threading_setup()
        os.environ = support.EnvironmentVarGuard()
        self.server_started = threading.Event()
        self.thread = TestServerThread(self, self.request_handler)
        self.thread.start()
        self.server_started.wait()

    def tearDown(self):
        self.thread.stop()
        self.thread = None
        os.environ.__exit__()
        support.threading_cleanup(*self._threads)

    def request(self, uri, method='GET', body=None, headers={}):
        self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
        self.connection.request(method, uri, body, headers)
        return self.connection.getresponse()

class BaseHTTPServerTestCase(BaseTestCase):
    class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
        protocol_version = 'HTTP/1.1'
        default_request_version = 'HTTP/1.1'

        def do_TEST(self):
            self.send_response(HTTPStatus.NO_CONTENT)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Connection', 'close')
            self.end_headers()

        def do_KEEP(self):
            self.send_response(HTTPStatus.NO_CONTENT)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Connection', 'keep-alive')
            self.end_headers()

        def do_KEYERROR(self):
            self.send_error(999)

        def do_NOTFOUND(self):
            self.send_error(HTTPStatus.NOT_FOUND)

        def do_EXPLAINERROR(self):
            self.send_error(999, "Short Message",
                            "This is a long \n explanation")

        def do_CUSTOM(self):
            self.send_response(999)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Connection', 'close')
            self.end_headers()

        def do_LATINONEHEADER(self):
            self.send_response(999)
            self.send_header('X-Special', 'Dängerous Mind')
            self.send_header('Connection', 'close')
            self.end_headers()
            body = self.headers['x-special-incoming'].encode('utf-8')
            self.wfile.write(body)

        def do_SEND_ERROR(self):
            self.send_error(int(self.path[1:]))

        def do_HEAD(self):
            self.send_error(int(self.path[1:]))

    def setUp(self):
        BaseTestCase.setUp(self)
        self.con = http.client.HTTPConnection(self.HOST, self.PORT)
        self.con.connect()

    def test_command(self):
        self.con.request('GET', '/')
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)

    def test_request_line_trimming(self):
        self.con._http_vsn_str = 'HTTP/1.1\n'
        self.con.putrequest('XYZBOGUS', '/')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)

    def test_version_bogus(self):
        self.con._http_vsn_str = 'FUBAR'
        self.con.putrequest('GET', '/')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)

    def test_version_digits(self):
        self.con._http_vsn_str = 'HTTP/9.9.9'
        self.con.putrequest('GET', '/')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)

    def test_version_none_get(self):
        self.con._http_vsn_str = ''
        self.con.putrequest('GET', '/')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)

    def test_version_none(self):
        # Test that a valid method is rejected when not HTTP/1.x
        self.con._http_vsn_str = ''
        self.con.putrequest('CUSTOM', '/')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)

    def test_version_invalid(self):
        self.con._http_vsn = 99
        self.con._http_vsn_str = 'HTTP/9.9'
        self.con.putrequest('GET', '/')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)

    def test_send_blank(self):
        self.con._http_vsn_str = ''
        self.con.putrequest('', '')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)

    def test_header_close(self):
        self.con.putrequest('GET', '/')
        self.con.putheader('Connection', 'close')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)

    def test_header_keep_alive(self):
        self.con._http_vsn_str = 'HTTP/1.1'
        self.con.putrequest('GET', '/')
        self.con.putheader('Connection', 'keep-alive')
        self.con.endheaders()
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)

    def test_handler(self):
        self.con.request('TEST', '/')
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.NO_CONTENT)

    def test_return_header_keep_alive(self):
        self.con.request('KEEP', '/')
        res = self.con.getresponse()
        self.assertEqual(res.getheader('Connection'), 'keep-alive')
        self.con.request('TEST', '/')
        self.addCleanup(self.con.close)

    def test_internal_key_error(self):
        self.con.request('KEYERROR', '/')
        res = self.con.getresponse()
        self.assertEqual(res.status, 999)

    def test_return_custom_status(self):
        self.con.request('CUSTOM', '/')
        res = self.con.getresponse()
        self.assertEqual(res.status, 999)

    def test_return_explain_error(self):
        self.con.request('EXPLAINERROR', '/')
        res = self.con.getresponse()
        self.assertEqual(res.status, 999)
        self.assertTrue(int(res.getheader('Content-Length')))

    def test_latin1_header(self):
        self.con.request('LATINONEHEADER', '/', headers={
            'X-Special-Incoming':       'Ärger mit Unicode'
        })
        res = self.con.getresponse()
        self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
        self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))

    def test_error_content_length(self):
        # Issue #16088: standard error responses should have a content-length
        self.con.request('NOTFOUND', '/')
        res = self.con.getresponse()
        self.assertEqual(res.status, HTTPStatus.NOT_FOUND)

        data = res.read()
        self.assertEqual(int(res.getheader('Content-Length')), len(data))

    def test_send_error(self):
        allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
                                         HTTPStatus.RESET_CONTENT)
        for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
                     HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
                     HTTPStatus.SWITCHING_PROTOCOLS):
            self.con.request('SEND_ERROR', '/{}'.format(code))
            res = self.con.getresponse()
            self.assertEqual(code, res.status)
            self.assertEqual(None, res.getheader('Content-Length'))
            self.assertEqual(None, res.getheader('Content-Type'))
            if code not in allow_transfer_encoding_codes:
                self.assertEqual(None, res.getheader('Transfer-Encoding'))

            data = res.read()
            self.assertEqual(b'', data)

    def test_head_via_send_error(self):
        allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
                                         HTTPStatus.RESET_CONTENT)
        for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
                     HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
                     HTTPStatus.SWITCHING_PROTOCOLS):
            self.con.request('HEAD', '/{}'.format(code))
            res = self.con.getresponse()
            self.assertEqual(code, res.status)
            if code == HTTPStatus.OK:
                self.assertTrue(int(res.getheader('Content-Length')) > 0)
                self.assertIn('text/html', res.getheader('Content-Type'))
            else:
                self.assertEqual(None, res.getheader('Content-Length'))
                self.assertEqual(None, res.getheader('Content-Type'))
            if code not in allow_transfer_encoding_codes:
                self.assertEqual(None, res.getheader('Transfer-Encoding'))

            data = res.read()
            self.assertEqual(b'', data)

class RequestHandlerLoggingTestCase(BaseTestCase):
    class request_handler(BaseHTTPRequestHandler):
        protocol_version = 'HTTP/1.1'
        default_request_version = 'HTTP/1.1'

        def do_GET(self):
            self.send_response(HTTPStatus.OK)
            self.end_headers()

        def do_ERROR(self):
            self.send_error(HTTPStatus.NOT_FOUND, 'File not found')

    def test_get(self):
        self.con = http.client.HTTPConnection(self.HOST, self.PORT)
        self.con.connect()

        with support.captured_stderr() as err:
            self.con.request('GET', '/')
            with self.con.getresponse():
                pass

        self.assertTrue(
            err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))

    def test_err(self):
        self.con = http.client.HTTPConnection(self.HOST, self.PORT)
        self.con.connect()

        with support.captured_stderr() as err:
            self.con.request('ERROR', '/')
            with self.con.getresponse():
                pass

        lines = err.getvalue().split('\n')
        self.assertTrue(lines[0].endswith('code 404, message File not found'))
        self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))

class SimpleHTTPServerTestCase(BaseTestCase):
    class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
        pass

    def setUp(self):
        BaseTestCase.setUp(self)
        self.cwd = os.getcwd()
        basetempdir = tempfile.gettempdir()
        os.chdir(basetempdir)
        self.data = b'We are the knights who say Ni!'
        self.tempdir = tempfile.mkdtemp(dir=basetempdir)
        self.tempdir_name = os.path.basename(self.tempdir)
        self.base_url = '/' + self.tempdir_name
        with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
            temp.write(self.data)

    def tearDown(self):
        try:
            os.chdir(self.cwd)
            try:
                shutil.rmtree(self.tempdir)
            except:
                pass
        finally:
            BaseTestCase.tearDown(self)

    def check_status_and_reason(self, response, status, data=None):
        def close_conn():
            """Don't close reader yet so we can check if there was leftover
            buffered input"""
            nonlocal reader
            reader = response.fp
            response.fp = None
        reader = None
        response._close_conn = close_conn

        body = response.read()
        self.assertTrue(response)
        self.assertEqual(response.status, status)
        self.assertIsNotNone(response.reason)
        if data:
            self.assertEqual(data, body)
        # Ensure the server has not set up a persistent connection, and has
        # not sent any extra data
        self.assertEqual(response.version, 10)
        self.assertEqual(response.msg.get("Connection", "close"), "close")
        self.assertEqual(reader.read(30), b'', 'Connection should be closed')

        reader.close()
        return body

    @support.requires_mac_ver(10, 5)
    @unittest.skipIf(sys.platform == 'win32',
                     'undecodable name cannot be decoded on win32')
    @unittest.skipUnless(support.TESTFN_UNDECODABLE,
                         'need support.TESTFN_UNDECODABLE')
    def test_undecodable_filename(self):
        enc = sys.getfilesystemencoding()
        filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
        with open(os.path.join(self.tempdir, filename), 'wb') as f:
            f.write(support.TESTFN_UNDECODABLE)
        response = self.request(self.base_url + '/')
        if sys.platform == 'darwin':
            # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
            # UTF-8 into a percent-encoded value.
            for name in os.listdir(self.tempdir):
                if name != 'test': # Ignore a filename created in setUp().
                    filename = name
                    break
        body = self.check_status_and_reason(response, HTTPStatus.OK)
        quotedname = urllib.parse.quote(filename, errors='surrogatepass')
        self.assertIn(('href="%s"' % quotedname)
                      .encode(enc, 'surrogateescape'), body)
        self.assertIn(('>%s<' % html.escape(filename, quote=False))
                      .encode(enc, 'surrogateescape'), body)
        response = self.request(self.base_url + '/' + quotedname)
        self.check_status_and_reason(response, HTTPStatus.OK,
                                     data=support.TESTFN_UNDECODABLE)

    def test_get(self):
        #constructs the path relative to the root directory of the HTTPServer
        response = self.request(self.base_url + '/test')
        self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
        # check for trailing "/" which should return 404. See Issue17324
        response = self.request(self.base_url + '/test/')
        self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
        response = self.request(self.base_url + '/')
        self.check_status_and_reason(response, HTTPStatus.OK)
        response = self.request(self.base_url)
        self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
        response = self.request(self.base_url + '/?hi=2')
        self.check_status_and_reason(response, HTTPStatus.OK)
        response = self.request(self.base_url + '?hi=1')
        self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
        self.assertEqual(response.getheader("Location"),
                         self.base_url + "/?hi=1")
        response = self.request('/ThisDoesNotExist')
        self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
        response = self.request('/' + 'ThisDoesNotExist' + '/')
        self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)

        data = b"Dummy index file\r\n"
        with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
            f.write(data)
        response = self.request(self.base_url + '/')
        self.check_status_and_reason(response, HTTPStatus.OK, data)

        # chmod() doesn't work as expected on Windows, and filesystem
        # permissions are ignored by root on Unix.
        if os.name == 'posix' and os.geteuid() != 0:
            os.chmod(self.tempdir, 0)
            try:
                response = self.request(self.base_url + '/')
                self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
            finally:
                os.chmod(self.tempdir, 0o755)

    def test_head(self):
        response = self.request(
            self.base_url + '/test', method='HEAD')
        self.check_status_and_reason(response, HTTPStatus.OK)
        self.assertEqual(response.getheader('content-length'),
                         str(len(self.data)))
        self.assertEqual(response.getheader('content-type'),
                         'application/octet-stream')

    def test_invalid_requests(self):
        response = self.request('/', method='FOO')
        self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
        # requests must be case sensitive,so this should fail too
        response = self.request('/', method='custom')
        self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
        response = self.request('/', method='GETs')
        self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)

    def test_path_without_leading_slash(self):
        response = self.request(self.tempdir_name + '/test')
        self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
        response = self.request(self.tempdir_name + '/test/')
        self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
        response = self.request(self.tempdir_name + '/')
        self.check_status_and_reason(response, HTTPStatus.OK)
        response = self.request(self.tempdir_name)
        self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
        response = self.request(self.tempdir_name + '/?hi=2')
        self.check_status_and_reason(response, HTTPStatus.OK)
        response = self.request(self.tempdir_name + '?hi=1')
        self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
        self.assertEqual(response.getheader("Location"),
                         self.tempdir_name + "/?hi=1")

    def test_html_escape_filename(self):
        filename = '<test&>.txt'
        fullpath = os.path.join(self.tempdir, filename)

        try:
            open(fullpath, 'w').close()
        except OSError:
            raise unittest.SkipTest('Can not create file %s on current file '
                                    'system' % filename)

        try:
            response = self.request(self.base_url + '/')
            body = self.check_status_and_reason(response, HTTPStatus.OK)
            enc = response.headers.get_content_charset()
        finally:
            os.unlink(fullpath)  # avoid affecting test_undecodable_filename

        self.assertIsNotNone(enc)
        html_text = '>%s<' % html.escape(filename, quote=False)
        self.assertIn(html_text.encode(enc), body)

cgi_file1 = """\
#!%s

print("Content-type: text/html")
print()
print("Hello World")
"""

cgi_file2 = """\
#!%s
import cgi

print("Content-type: text/html")
print()

form = cgi.FieldStorage()
print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
                          form.getfirst("bacon")))
"""

cgi_file4 = """\
#!%s
import os

print("Content-type: text/html")
print()

print(os.environ["%s"])
"""

@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
        "This test can't be run reliably as root (issue #13308).")
class CGIHTTPServerTestCase(BaseTestCase):
    class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
        pass

    linesep = os.linesep.encode('ascii')

    def setUp(self):
        BaseTestCase.setUp(self)
        self.cwd = os.getcwd()
        self.parent_dir = tempfile.mkdtemp()
        self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
        self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
        os.mkdir(self.cgi_dir)
        os.mkdir(self.cgi_child_dir)
        self.nocgi_path = None
        self.file1_path = None
        self.file2_path = None
        self.file3_path = None
        self.file4_path = None

        # The shebang line should be pure ASCII: use symlink if possible.
        # See issue #7668.
        if support.can_symlink():
            self.pythonexe = os.path.join(self.parent_dir, 'python')
            os.symlink(sys.executable, self.pythonexe)
        else:
            self.pythonexe = sys.executable

        try:
            # The python executable path is written as the first line of the
            # CGI Python script. The encoding cookie cannot be used, and so the
            # path should be encodable to the default script encoding (utf-8)
            self.pythonexe.encode('utf-8')
        except UnicodeEncodeError:
            self.tearDown()
            self.skipTest("Python executable path is not encodable to utf-8")

        self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
        with open(self.nocgi_path, 'w') as fp:
            fp.write(cgi_file1 % self.pythonexe)
        os.chmod(self.nocgi_path, 0o777)

        self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
        with open(self.file1_path, 'w', encoding='utf-8') as file1:
            file1.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file1_path, 0o777)

        self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
        with open(self.file2_path, 'w', encoding='utf-8') as file2:
            file2.write(cgi_file2 % self.pythonexe)
        os.chmod(self.file2_path, 0o777)

        self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
        with open(self.file3_path, 'w', encoding='utf-8') as file3:
            file3.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file3_path, 0o777)

        self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
        with open(self.file4_path, 'w', encoding='utf-8') as file4:
            file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
        os.chmod(self.file4_path, 0o777)

        os.chdir(self.parent_dir)

    def tearDown(self):
        try:
            os.chdir(self.cwd)
            if self.pythonexe != sys.executable:
                os.remove(self.pythonexe)
            if self.nocgi_path:
                os.remove(self.nocgi_path)
            if self.file1_path:
                os.remove(self.file1_path)
            if self.file2_path:
                os.remove(self.file2_path)
            if self.file3_path:
                os.remove(self.file3_path)
            if self.file4_path:
                os.remove(self.file4_path)
            os.rmdir(self.cgi_child_dir)
            os.rmdir(self.cgi_dir)
            os.rmdir(self.parent_dir)
        finally:
            BaseTestCase.tearDown(self)

    def test_url_collapse_path(self):
        # verify tail is the last portion and head is the rest on proper urls
        test_vectors = {
            '': '//',
            '..': IndexError,
            '/.//..': IndexError,
            '/': '//',
            '//': '//',
            '/\\': '//\\',
            '/.//': '//',
            'cgi-bin/file1.py': '/cgi-bin/file1.py',
            '/cgi-bin/file1.py': '/cgi-bin/file1.py',
            'a': '//a',
            '/a': '//a',
            '//a': '//a',
            './a': '//a',
            './C:/': '/C:/',
            '/a/b': '/a/b',
            '/a/b/': '/a/b/',
            '/a/b/.': '/a/b/',
            '/a/b/c/..': '/a/b/',
            '/a/b/c/../d': '/a/b/d',
            '/a/b/c/../d/e/../f': '/a/b/d/f',
            '/a/b/c/../d/e/../../f': '/a/b/f',
            '/a/b/c/../d/e/.././././..//f': '/a/b/f',
            '../a/b/c/../d/e/.././././..//f': IndexError,
            '/a/b/c/../d/e/../../../f': '/a/f',
            '/a/b/c/../d/e/../../../../f': '//f',
            '/a/b/c/../d/e/../../../../../f': IndexError,
            '/a/b/c/../d/e/../../../../f/..': '//',
            '/a/b/c/../d/e/../../../../f/../.': '//',
        }
        for path, expected in test_vectors.items():
            if isinstance(expected, type) and issubclass(expected, Exception):
                self.assertRaises(expected,
                                  server._url_collapse_path, path)
            else:
                actual = server._url_collapse_path(path)
                self.assertEqual(expected, actual,
                                 msg='path = %r\nGot:    %r\nWanted: %r' %
                                 (path, actual, expected))

    def test_headers_and_content(self):
        res = self.request('/cgi-bin/file1.py')
        self.assertEqual(
            (res.read(), res.getheader('Content-type'), res.status),
            (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))

    def test_issue19435(self):
        res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
        self.assertEqual(res.status, HTTPStatus.NOT_FOUND)

    def test_post(self):
        params = urllib.parse.urlencode(
            {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
        headers = {'Content-type' : 'application/x-www-form-urlencoded'}
        res = self.request('/cgi-bin/file2.py', 'POST', params, headers)

        self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)

    def test_invaliduri(self):
        res = self.request('/cgi-bin/invalid')
        res.read()
        self.assertEqual(res.status, HTTPStatus.NOT_FOUND)

    def test_authorization(self):
        headers = {b'Authorization' : b'Basic ' +
                   base64.b64encode(b'username:pass')}
        res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
        self.assertEqual(
            (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
            (res.read(), res.getheader('Content-type'), res.status))

    def test_no_leading_slash(self):
        # http://bugs.python.org/issue2254
        res = self.request('cgi-bin/file1.py')
        self.assertEqual(
            (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
            (res.read(), res.getheader('Content-type'), res.status))

    def test_os_environ_is_not_altered(self):
        signature = "Test CGI Server"
        os.environ['SERVER_SOFTWARE'] = signature
        res = self.request('/cgi-bin/file1.py')
        self.assertEqual(
            (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
            (res.read(), res.getheader('Content-type'), res.status))
        self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)

    def test_urlquote_decoding_in_cgi_check(self):
        res = self.request('/cgi-bin%2ffile1.py')
        self.assertEqual(
            (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
            (res.read(), res.getheader('Content-type'), res.status))

    def test_nested_cgi_path_issue21323(self):
        res = self.request('/cgi-bin/child-dir/file3.py')
        self.assertEqual(
            (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
            (res.read(), res.getheader('Content-type'), res.status))

    def test_query_with_multiple_question_mark(self):
        res = self.request('/cgi-bin/file4.py?a=b?c=d')
        self.assertEqual(
            (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
            (res.read(), res.getheader('Content-type'), res.status))

    def test_query_with_continuous_slashes(self):
        res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
        self.assertEqual(
            (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
             'text/html', HTTPStatus.OK),
            (res.read(), res.getheader('Content-type'), res.status))

class SocketlessRequestHandler(SimpleHTTPRequestHandler):
    def __init__(self):
        self.get_called = False
        self.protocol_version = "HTTP/1.1"

    def do_GET(self):
        self.get_called = True
        self.send_response(HTTPStatus.OK)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()
        self.wfile.write(b'<html><body>Data</body></html>\r\n')

    def log_message(self, format, *args):
        pass

class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
    def handle_expect_100(self):
        self.send_error(HTTPStatus.EXPECTATION_FAILED)
        return False

class AuditableBytesIO:

    def __init__(self):
        self.datas = []

    def write(self, data):
        self.datas.append(data)

    def getData(self):
        return b''.join(self.datas)

    @property
    def numWrites(self):
        return len(self.datas)

class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
    """Test the functionality of the BaseHTTPServer.

       Test the support for the Expect 100-continue header.
       """

    HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')

    def setUp (self):
        self.handler = SocketlessRequestHandler()

    def send_typical_request(self, message):
        input = BytesIO(message)
        output = BytesIO()
        self.handler.rfile = input
        self.handler.wfile = output
        self.handler.handle_one_request()
        output.seek(0)
        return output.readlines()

    def verify_get_called(self):
        self.assertTrue(self.handler.get_called)

    def verify_expected_headers(self, headers):
        for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
            self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)

    def verify_http_server_response(self, response):
        match = self.HTTPResponseMatch.search(response)
        self.assertIsNotNone(match)

    def test_http_1_1(self):
        result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
        self.verify_http_server_response(result[0])
        self.verify_expected_headers(result[1:-1])
        self.verify_get_called()
        self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
        self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
        self.assertEqual(self.handler.command, 'GET')
        self.assertEqual(self.handler.path, '/')
        self.assertEqual(self.handler.request_version, 'HTTP/1.1')
        self.assertSequenceEqual(self.handler.headers.items(), ())

    def test_http_1_0(self):
        result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
        self.verify_http_server_response(result[0])
        self.verify_expected_headers(result[1:-1])
        self.verify_get_called()
        self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
        self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
        self.assertEqual(self.handler.command, 'GET')
        self.assertEqual(self.handler.path, '/')
        self.assertEqual(self.handler.request_version, 'HTTP/1.0')
        self.assertSequenceEqual(self.handler.headers.items(), ())

    def test_http_0_9(self):
        result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
        self.verify_get_called()

    def test_with_continue_1_0(self):
        result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
        self.verify_http_server_response(result[0])
        self.verify_expected_headers(result[1:-1])
        self.verify_get_called()
        self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
        self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
        self.assertEqual(self.handler.command, 'GET')
        self.assertEqual(self.handler.path, '/')
        self.assertEqual(self.handler.request_version, 'HTTP/1.0')
        headers = (("Expect", "100-continue"),)
        self.assertSequenceEqual(self.handler.headers.items(), headers)

    def test_with_continue_1_1(self):
        result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
        self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
        self.assertEqual(result[1], b'\r\n')
        self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
        self.verify_expected_headers(result[2:-1])
        self.verify_get_called()
        self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
        self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
        self.assertEqual(self.handler.command, 'GET')
        self.assertEqual(self.handler.path, '/')
        self.assertEqual(self.handler.request_version, 'HTTP/1.1')
        headers = (("Expect", "100-continue"),)
        self.assertSequenceEqual(self.handler.headers.items(), headers)

    def test_header_buffering_of_send_error(self):

        input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
        output = AuditableBytesIO()
        handler = SocketlessRequestHandler()
        handler.rfile = input
        handler.wfile = output
        handler.request_version = 'HTTP/1.1'
        handler.requestline = ''
        handler.command = None

        handler.send_error(418)
        self.assertEqual(output.numWrites, 2)

    def test_header_buffering_of_send_response_only(self):

        input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
        output = AuditableBytesIO()
        handler = SocketlessRequestHandler()
        handler.rfile = input
        handler.wfile = output
        handler.request_version = 'HTTP/1.1'

        handler.send_response_only(418)
        self.assertEqual(output.numWrites, 0)
        handler.end_headers()
        self.assertEqual(output.numWrites, 1)

    def test_header_buffering_of_send_header(self):

        input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
        output = AuditableBytesIO()
        handler = SocketlessRequestHandler()
        handler.rfile = input
        handler.wfile = output
        handler.request_version = 'HTTP/1.1'

        handler.send_header('Foo', 'foo')
        handler.send_header('bar', 'bar')
        self.assertEqual(output.numWrites, 0)
        handler.end_headers()
        self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
        self.assertEqual(output.numWrites, 1)

    def test_header_unbuffered_when_continue(self):

        def _readAndReseek(f):
            pos = f.tell()
            f.seek(0)
            data = f.read()
            f.seek(pos)
            return data

        input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
        output = BytesIO()
        self.handler.rfile = input
        self.handler.wfile = output
        self.handler.request_version = 'HTTP/1.1'

        self.handler.handle_one_request()
        self.assertNotEqual(_readAndReseek(output), b'')
        result = _readAndReseek(output).split(b'\r\n')
        self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
        self.assertEqual(result[1], b'')
        self.assertEqual(result[2], b'HTTP/1.1 200 OK')

    def test_with_continue_rejected(self):
        usual_handler = self.handler        # Save to avoid breaking any subsequent tests.
        self.handler = RejectingSocketlessRequestHandler()
        result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
        self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
        self.verify_expected_headers(result[1:-1])
        # The expect handler should short circuit the usual get method by
        # returning false here, so get_called should be false
        self.assertFalse(self.handler.get_called)
        self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
        self.handler = usual_handler        # Restore to avoid breaking any subsequent tests.

    def test_request_length(self):
        # Issue #10714: huge request lines are discarded, to avoid Denial
        # of Service attacks.
        result = self.send_typical_request(b'GET ' + b'x' * 65537)
        self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
        self.assertFalse(self.handler.get_called)
        self.assertIsInstance(self.handler.requestline, str)

    def test_header_length(self):
        # Issue #6791: same for headers
        result = self.send_typical_request(
            b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
        self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
        self.assertFalse(self.handler.get_called)
        self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')

    def test_too_many_headers(self):
        result = self.send_typical_request(
            b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
        self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
        self.assertFalse(self.handler.get_called)
        self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')

    def test_html_escape_on_error(self):
        result = self.send_typical_request(
            b'<script>alert("hello")</script> / HTTP/1.1')
        result = b''.join(result)
        text = '<script>alert("hello")</script>'
        self.assertIn(html.escape(text, quote=False).encode('ascii'), result)

    def test_close_connection(self):
        # handle_one_request() should be repeatedly called until
        # it sets close_connection
        def handle_one_request():
            self.handler.close_connection = next(close_values)
        self.handler.handle_one_request = handle_one_request

        close_values = iter((True,))
        self.handler.handle()
        self.assertRaises(StopIteration, next, close_values)

        close_values = iter((False, False, True))
        self.handler.handle()
        self.assertRaises(StopIteration, next, close_values)

    def test_date_time_string(self):
        now = time.time()
        # this is the old code that formats the timestamp
        year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
        expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
            self.handler.weekdayname[wd],
            day,
            self.handler.monthname[month],
            year, hh, mm, ss
        )
        self.assertEqual(self.handler.date_time_string(timestamp=now), expected)

class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
    """ Test url parsing """
    def setUp(self):
        self.translated = os.getcwd()
        self.translated = os.path.join(self.translated, 'filename')
        self.handler = SocketlessRequestHandler()

    def test_query_arguments(self):
        path = self.handler.translate_path('/filename')
        self.assertEqual(path, self.translated)
        path = self.handler.translate_path('/filename?foo=bar')
        self.assertEqual(path, self.translated)
        path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
        self.assertEqual(path, self.translated)

    def test_start_with_double_slash(self):
        path = self.handler.translate_path('//filename')
        self.assertEqual(path, self.translated)
        path = self.handler.translate_path('//filename?foo=bar')
        self.assertEqual(path, self.translated)

    def test_windows_colon(self):
        with support.swap_attr(server.os, 'path', ntpath):
            path = self.handler.translate_path('c:c:c:foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('\\c:../filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:\\c:..\\foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

class MiscTestCase(unittest.TestCase):
    def test_all(self):
        expected = []
        blacklist = {'executable', 'nobody_uid', 'test'}
        for name in dir(server):
            if name.startswith('_') or name in blacklist:
                continue
            module_object = getattr(server, name)
            if getattr(module_object, '__module__', None) == 'http.server':
                expected.append(name)
        self.assertCountEqual(server.__all__, expected)

def test_main(verbose=None):
    cwd = os.getcwd()
    try:
        support.run_unittest(
            RequestHandlerLoggingTestCase,
            BaseHTTPRequestHandlerTestCase,
            BaseHTTPServerTestCase,
            SimpleHTTPServerTestCase,
            CGIHTTPServerTestCase,
            SimpleHTTPRequestHandlerTestCase,
            MiscTestCase,
        )
    finally:
        os.chdir(cwd)

if __name__ == '__main__':
    test_main()


text:
package ru.job4j.orderbook;

import java.util.Map;
import java.util.TreeMap;

/**
 * The class distributes orders for order books.
 *
 * @author Ruzhev Alexander
 * @since 19.02.2018
 */
public class MyOrderBook {
    /**
     * Contains oder books.
     */
    private Map<String, MyBook> bookMap = new TreeMap<>();

    /**
     * Add new order.
     *
     * @param order - order
     * @return true if add ok
     */
    public boolean add(Order order) {
        boolean result = false;
        if (this.bookMap.get(order.getBook()) != null) {
            this.bookMap.get(order.getBook()).add(order);
        } else {
            MyBook newBook = new MyBook();
            newBook.add(order);
            bookMap.put(order.getBook(), newBook);
        }
        return result;
    }

    /**
     * Print to screen.
     */
    public void print() {
        for (Map.Entry<String, MyBook> map : this.bookMap.entrySet()) {
            System.out.println(map.getKey());
            map.getValue().print();
            System.out.println("++++++++++++++++++++++");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

if (!process.env.GCLOUD_PROJECT_NUM) {
  console.log('The GCLOUD_PROJECT_NUM environment variable must be set.');
  process.exit(1);
}

var agent = require('..').start().private_();
var TraceLabels = require('../lib/trace-labels.js');
var assert = require('assert');
var cls = require('../lib/cls.js');

describe('SpanData', function() {

  it('has correct default values', function() {
    cls.getNamespace().run(function() {
      var data = agent.createRootSpanData('name', 1, 2);
      assert.ok(data.trace);
      assert.equal(data.trace.traceId, 1);
      assert.ok(data.span.spanId);
      assert.equal(data.span.name, 'name');
    });
  });

  it('creates children', function() {
    cls.getNamespace().run(function() {
      var data = agent.createRootSpanData('name', 1, 2);
      var child = data.createChildSpanData('name2');
      assert.equal(child.span.name, 'name2');
      assert.equal(child.span.parentSpanId, data.span.spanId);
      assert.ok(child.trace);
      assert.equal(child.trace.traceId, 1);
    });
  });

  it('closes', function() {
    cls.getNamespace().run(function() {
      var data = agent.createRootSpanData('name', 1, 2);
      assert.ok(!data.span.isClosed());
      data.close();
      assert.ok(data.span.isClosed());
    });
  });

  it('captures stack traces', function() {
    agent.config().stackTraceLimit = 25;
    cls.getNamespace().run(function() {
      var data = agent.createRootSpanData('name', 1, 2);
      assert.ok(!data.span.isClosed());
      data.close();
      var stack = data.span.labels[TraceLabels.STACK_TRACE_DETAILS_KEY];
      assert.ok(stack);
      assert.ok(typeof stack === 'string');
      var frames = JSON.parse(stack);
      assert.ok(frames && frames.stack_frame);
      assert.ok(Array.isArray(frames.stack_frame));
      assert.ok(frames.stack_frame.some(function(frame) {
        return frame.method_name &&
               frame.method_name.indexOf('createRootSpanData') !== -1;
      }));
    });
  });

  it('should close all spans', function() {
    cls.getNamespace().run(function() {
      var span = agent.createRootSpanData('hi');
      span.createChildSpanData('sub');
      span.close();
      var traces = agent.traceWriter.buffer_.map(JSON.parse);
      for (var i = 0; i < traces.length; i++) {
        for (var j = 0; j < traces[i].spans.length; j++) {
          assert.notEqual(traces[i].spans[j].endTime, '');
        }
      }
    });
  });
});


text:
package com.topie.core.http;

import java.io.IOException;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class HttpFuture implements Callable<String> {
    private String url;

    public HttpFuture(String url) {
        this.url = url;
    }

    public String call() throws Exception {
        return new HttpHandlerImpl().readText(url);
    }

    public String readText(ExecutorService executorService, long timeout)
            throws IOException, InterruptedException, ExecutionException,
            TimeoutException {
        FutureTask<String> futureTask = new FutureTask(this);
        executorService.execute(futureTask);

        String text = futureTask.get(timeout, TimeUnit.MILLISECONDS);

        return text;
    }
}


text:
#include "slate.hpp"

void socket_module_init(struct object_heap* oh) {
  oh->socketTicketCount = SLATE_NETTICKET_MAXIMUM;
  oh->socketTickets = (struct slate_addrinfo_request*)calloc(oh->socketTicketCount * sizeof(struct slate_addrinfo_request), 1);
#if 0
  oh->socketTicketMutex = PTHREAD_MUTEX_INITIALIZER;
#endif
}

/* remap platform specific errors to slate errors */
word_t socket_return(word_t ret) {

  if (ret >= 0) return ret;

  switch (-ret) {
#ifdef WIN32
	  // TODO WIN32 port
#else
  case EACCES: return -2;
  case EAFNOSUPPORT: return -3;
  case EINVAL: return -4;
  case EMFILE: return -5;
  case ENFILE: return -5;
  case ENOMEM: return -6;
  case EPROTONOSUPPORT: return -3;
  case EADDRINUSE: return -7;
  case EBADF: return -8;
  case ENOTSOCK: return -8;
  case EFAULT: return -4;
  case EOPNOTSUPP: return -3;
  case EAGAIN: return -9;
    /*  case EWOULDBLOCK: return -10;*/
  case ECONNABORTED: return -11;
  case EINTR: return -12;
  case EPERM: return -2;
  case EALREADY: return -13;
  case ECONNREFUSED: return -14;
  case EINPROGRESS: return -15;
  case EISCONN: return -16;
  case ENETUNREACH: return -17;
  case ETIMEDOUT: return -18;
#endif

  default: return -1;
  }

}

int socket_select_setup(struct OopArray* selectOn, fd_set* fdList, int* maxFD) {
  word_t fdCount, i;

  FD_ZERO(fdList);
  fdCount = array_size(selectOn);

  for (i = 0; i < fdCount; i++) {
    struct Object* fdo = object_array_get_element((struct Object*)selectOn, i);
    word_t fd = object_to_smallint(fdo);
    if (!object_is_smallint(fdo) || fd >= FD_SETSIZE) {
      return -1;
    }
    *maxFD = max(*maxFD, fd);
    FD_SET(fd, fdList);
    assert(FD_ISSET(fd, fdList));
  }

  return fdCount;
}

void socket_select_find_available(struct OopArray* selectOn, fd_set* fdList, struct OopArray* readyPipes, word_t readyCount) {
  word_t fdCount, i, readyIndex;
  fdCount = array_size(selectOn);

  for (i = 0, readyIndex = 0; i < fdCount && readyIndex < readyCount; i++) {
    if (FD_ISSET(object_to_smallint(object_array_get_element((struct Object*)selectOn, i)), fdList)) {
      readyPipes->elements[readyIndex++] = object_array_get_element((struct Object*)selectOn, i);
    }
  }
}

void prim_selectOnReadPipesFor(struct object_heap* oh, struct Object* args[], word_t arity, struct Object* opts[], word_t optCount, word_t resultStackPointer) {
  struct OopArray* selectOn = (struct OopArray*) args[0];
  struct OopArray* readyPipes;
  word_t waitTime = object_to_smallint(args[1]);
  int retval, fdCount, maxFD;
  struct timeval tv;
  fd_set fdList;
  maxFD = 0;

ASSURE_SMALLINT_ARG(1);

  if ((fdCount = socket_select_setup(selectOn, &fdList, &maxFD)) < 0) {
    oh->cached.interpreter->stack->elements[resultStackPointer] = oh->cached.nil;
    return;
  }

  tv.tv_sec = waitTime / 1000000;
  tv.tv_usec = waitTime % 1000000;
  retval = select(maxFD+1, &fdList, NULL, NULL, &tv);

  if (retval < 0) {
    oh->cached.interpreter->stack->elements[resultStackPointer] = oh->cached.nil;
    return;
  }

  readyPipes = heap_clone_oop_array_sized(oh, get_special(oh, SPECIAL_OOP_ARRAY_PROTO), retval);
  socket_select_find_available(selectOn, &fdList, readyPipes, retval);

  oh->cached.interpreter->stack->elements[resultStackPointer] = (struct Object*)readyPipes;

}

int socket_lookup_domain(word_t domain) {
  switch (domain) {
  case SLATE_DOMAIN_LOCAL: return AF_UNIX;
  case SLATE_DOMAIN_IPV4: return AF_INET;
  case SLATE_DOMAIN_IPV6: return AF_INET6;
  default: return AF_INET;
  }
}

int socket_reverse_lookup_domain(word_t domain) {
  switch (domain) {
  case AF_UNIX: return SLATE_DOMAIN_LOCAL;
  case AF_INET: return SLATE_DOMAIN_IPV4;
  case AF_INET6: return SLATE_DOMAIN_IPV6;
  default: return SLATE_DOMAIN_IPV4;
  }
}

int socket_lookup_type(word_t type) {
  switch (type) {
  case SLATE_TYPE_STREAM: return SOCK_STREAM;
  default: return SOCK_STREAM;
  }
}

int socket_reverse_lookup_type(word_t type) {
  switch (type) {
  case SOCK_STREAM: return SLATE_TYPE_STREAM;
  default: return SLATE_TYPE_STREAM;
  }
}

int socket_lookup_protocol(word_t protocol) {
  switch (protocol) {
  default: return 0;
  }
}

int socket_reverse_lookup_protocol(word_t protocol) {
  switch (protocol) {
  default: return 0;
  }
}

int socket_set_nonblocking(int fd) {
    int flags;

#ifdef WIN32
#pragma message("TODO WIN32 port set-nonblocking on socket")
	return 0;
#else
	if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
        flags = 0;
    return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
#endif
}

#ifdef WIN32
DWORD WINAPI socket_getaddrinfo_callback(LPVOID ptr) {
#else
void *socket_getaddrinfo_callback(void *ptr) {
#endif
  struct slate_addrinfo_request* req = (struct slate_addrinfo_request*)ptr;
  /*  struct object_heap* oh = req->oh;*/
  struct addrinfo ai;
  memset(&ai, 0, sizeof(ai));
  ai.ai_flags = req->flags;
  ai.ai_family = socket_lookup_domain(req->family);
  ai.ai_socktype = socket_lookup_type(req->type);
  ai.ai_protocol = socket_lookup_protocol(req->protocol);

  req->result = getaddrinfo(req->hostname, req->service, &ai, &req->addrResult);
  req->finished = 1;
#ifdef WIN32
  return 0;
#else
  return NULL;
#endif
}

int socket_getaddrinfo(struct object_heap* oh, struct ByteArray* hostname, word_t hostnameSize, struct ByteArray* service, word_t serviceSize, word_t family, word_t type, word_t protocol, word_t flags) {
  int i;
#ifdef WIN32
  HANDLE thread;
  DWORD pret;
  oh->socketThreadMutex = CreateMutex(NULL, FALSE, TEXT("SocketThreadMutex"));
#else
  pthread_t thread;
  int pret;
#if 0
  pthread_mutex_lock(&oh->socketTicketMutex);
#endif
#endif
  for (i = 0; i < oh->socketTicketCount; i++) {
    if (oh->socketTickets[i].inUse == 0) {
      /*use this one*/
      oh->socketTickets[i].inUse = 1;
      oh->socketTickets[i].result = 0;
      oh->socketTickets[i].finished = 0;
      oh->socketTickets[i].addrResult = 0;
      oh->socketTickets[i].family = family;
      oh->socketTickets[i].type = type;
      oh->socketTickets[i].protocol = protocol;
      oh->socketTickets[i].flags = flags;
      oh->socketTickets[i].oh = oh;
      oh->socketTickets[i].ticketNumber = i;
      if (hostnameSize == 0) {
        oh->socketTickets[i].hostname = NULL;
      } else {
        oh->socketTickets[i].hostname = (char*)calloc(hostnameSize, 1);
        extractCString(hostname, (byte_t*)oh->socketTickets[i].hostname, hostnameSize);
      }
      if (serviceSize == 0) {
        oh->socketTickets[i].service = NULL;
      } else {
        oh->socketTickets[i].service = (char*)calloc(hostnameSize, 1);
        extractCString(service, (byte_t*)oh->socketTickets[i].service, serviceSize);
      }

#ifdef WIN32
	  ReleaseMutex(oh->socketThreadMutex);
	  thread = CreateThread(NULL, 0, socket_getaddrinfo_callback, (void*) &oh->socketTickets[i], 0, &pret);
#else
#if 0
      pthread_mutex_unlock(&oh->socketTicketMutex);
#endif
      pret = pthread_create(&thread, NULL, socket_getaddrinfo_callback, (void*) &oh->socketTickets[i]);
#endif
	  if (pret != 0) {
        free(oh->socketTickets[i].hostname);
        free(oh->socketTickets[i].service);
        oh->socketTickets[i].hostname = NULL;
        oh->socketTickets[i].service = NULL;
        return -1;
      }
      return i;
    }
  }
#ifdef WIN32
  ReleaseMutex(oh->socketThreadMutex);
#else
#if 0
  pthread_mutex_unlock(&oh->socketTicketMutex);
#endif
#endif

  return -1;

}


text: require "middleman-java-properties"


text:
<!DOCTYPE HTML>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Kanrisha - A Premium HTML5 Responsive Admin Template</title>

	<link href="http://fonts.googleapis.com/css?family=Oswald|Droid+Sans:400,700" rel="stylesheet">

	<link rel="stylesheet" href="../CSS/style.css">

				John Alex

								<form class="top_search_form">
									<input type="text" class="top_search_input">
									<input type="submit" class="top_search_submit" value="">
								</form>

							Settings

							Upload

									New File

									Files Left
									2

									Browse Files

							Inbox
							3

							Pages

									403 Forbidden

									404 Not Found

		Go Back To Home Page

				COPYRIGHT © 2012 Mahieddine Abd-kader


text:
namespace base {
class FilePath;
class ScopedClosureRunner;
class SequencedTaskRunner;
}  // namespace base

namespace drive {
namespace internal {
class FileCache;
class FileWriteWatcher;
class ResourceMetadata;
}  // namespace internal

class EventLogger;
class JobScheduler;
class ResourceEntry;

namespace file_system {

class CreateFileOperation;
class DownloadOperation;
class OperationDelegate;

// Implements GetFileForSaving() operation that prepares a local cache for
// a Drive file whose next modification is monitored and notified to the
// OperationDelegate.
// TODO(kinaba): crbug.com/269424: we might want to monitor all the changes
// to the cache directory, not just the one immediately after the save dialog.
class GetFileForSavingOperation {
 public:
  GetFileForSavingOperation(EventLogger* logger,
                            base::SequencedTaskRunner* blocking_task_runner,
                            base::SingleThreadTaskRunner* file_task_runner,
                            OperationDelegate* delegate,
                            JobScheduler* scheduler,
                            internal::ResourceMetadata* metadata,
                            internal::FileCache* cache,
                            const base::FilePath& temporary_file_directory);
  ~GetFileForSavingOperation();

  // Makes sure that |file_path| in the file system is available in the local
  // cache, and marks it as dirty. The next modification to the cache file is
  // watched and is automatically notified to the delegate. If the entry is not
  // present in the file system, it is created.
  void GetFileForSaving(const base::FilePath& file_path,
                        const GetFileCallback& callback);

  internal::FileWriteWatcher* file_write_watcher_for_testing() {
    return file_write_watcher_.get();
  }

 private:
  void GetFileForSavingAfterCreate(const base::FilePath& file_path,
                                   const GetFileCallback& callback,
                                   FileError error);
  void GetFileForSavingAfterDownload(const GetFileCallback& callback,
                                     FileError error,
                                     const base::FilePath& cache_path,
                                     scoped_ptr<ResourceEntry> entry);
  void GetFileForSavingAfterOpenForWrite(
      const GetFileCallback& callback,
      const base::FilePath& cache_path,
      scoped_ptr<ResourceEntry> entry,
      scoped_ptr<base::ScopedClosureRunner>* file_closer,
      FileError error);
  void GetFileForSavingAfterWatch(const GetFileCallback& callback,
                                  const base::FilePath& cache_path,
                                  scoped_ptr<ResourceEntry> entry,
                                  bool success);
  // Called when the cache file for |local_id| is written.
  void OnWriteEvent(const std::string& local_id,
                    scoped_ptr<base::ScopedClosureRunner> file_closer);

  EventLogger* logger_;
  scoped_ptr<CreateFileOperation> create_file_operation_;
  scoped_ptr<DownloadOperation> download_operation_;
  scoped_ptr<internal::FileWriteWatcher> file_write_watcher_;
  scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_;
  OperationDelegate* delegate_;
  internal::ResourceMetadata* metadata_;
  internal::FileCache* cache_;

  base::ThreadChecker thread_checker_;

  // Note: This should remain the last member so it'll be destroyed and
  // invalidate the weak pointers before any other members are destroyed.
  base::WeakPtrFactory<GetFileForSavingOperation> weak_ptr_factory_;
  DISALLOW_COPY_AND_ASSIGN(GetFileForSavingOperation);
};

}  // namespace file_system
}  // namespace drive

#endif  // COMPONENTS_DRIVE_FILE_SYSTEM_GET_FILE_FOR_SAVING_OPERATION_H_


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>GlobalPlatformAPI: GP_GetData.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

GlobalPlatformAPI

C++ API for Global Platform commands

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

GP_GetData.h

00001 #pragma once
00002
00003 #include "GP_Command.h"
00004
00005 namespace GPAPI
00006 {
00007
00011         class GP_GetData : public GP_Command
00012         {
00013         private:
00014
00015         public:
00016                 GP_GetData();
00017                 ~GP_GetData();
00018
00028                 void SetObjectTag(unsigned char nTag1, unsigned char nTag2);
00029         };
00030
00031 }

 All Classes Functions Variables

<address class="footer">Generated on Mon Sep 3 2012 08:53:48 for GlobalPlatformAPI by

 1.7.3 </address>


text:
'use strict';

import React, { Component } from 'react';
import {
  ActivityIndicator,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View
} from 'react-native';

import styles from '../style/FormStyles';

export default class AddFriend extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uname: '',
      isLoading: false,
      message: ''
    };

    this.socket = this.props.socket;
    this.socket.on('add_friend_resp', this.addResp.bind(this));
  }

  onUsernameChanged(ev) {
    this.setState({ uname: ev.nativeEvent.text });
  }

  clearForm() { this.setState({ uname: '' }); }

  addResp(resp) {
    switch (resp) {
      case 300:
        this.clearForm();
        this.setState({message: 'User had become friend', isLoading: false});
        break;
      case 400:
        this.clearForm();
        this.setState({message: 'Username not found', isLoading: false});
        break;
      case 500:
        this.clearForm();
        this.setState({message: 'Service error\nPlease try again', isLoading: false});
        break;
      case 200:
        this.setState({message: 'Request has been sent', isLoading: false});
        setTimeout(() => {
          this.setState({message: ''});
        }, 500);
        this.props.onAdd();
        break;
    }
  }

  onFind() {
    this.socket.emit('add_friend', { uname: this.props.uname, fname: this.state.uname });
    this.setState({ isLoading: true });
  }

  render() {
    var loading = this.state.isLoading ?
      <ActivityIndicator
          style={styles.loading}
          size='large'/> :
      <View/>
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.textInput}
          value={this.state.uname}
          onChange={this.onUsernameChanged.bind(this)}
          underlineColorAndroid={'transparent'}
          placeholder='Username'/>
        <TouchableHighlight style={styles.button}
            onPress={this.onFind.bind(this)}
            underlayColor='#1219FF'>
          <Text style={styles.buttonText}>Find</Text>
        </TouchableHighlight>
        {loading}
        <Text style={styles.description}>{this.state.message}</Text>
      </View>
    );
  }
};


text:
package org.springframework.boot.actuate.endpoint.cache;

import java.lang.reflect.Method;
import java.util.function.Function;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import org.springframework.boot.actuate.endpoint.OperationInvoker;
import org.springframework.boot.actuate.endpoint.OperationType;
import org.springframework.boot.actuate.endpoint.reflect.OperationMethodInfo;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ReflectionUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link CachingOperationInvokerAdvisor}.
 *
 * @author Phillip Webb
 */
public class CachingOperationInvokerAdvisorTests {

	@Mock
	private OperationInvoker invoker;

	@Mock
	private Function<String, Long> timeToLive;

	private CachingOperationInvokerAdvisor advisor;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
		this.advisor = new CachingOperationInvokerAdvisor(this.timeToLive);
	}

	@Test
	public void applyWhenOperationIsNotReadShouldNotAddAdvise() {
		OperationMethodInfo info = mockInfo(OperationType.WRITE, "get");
		OperationInvoker advised = this.advisor.apply("foo", info, this.invoker);
		assertThat(advised).isSameAs(this.invoker);
	}

	@Test
	public void applyWhenHasParametersShouldNotAddAdvise() {
		OperationMethodInfo info = mockInfo(OperationType.READ, "getWithParameter",
				String.class);
		OperationInvoker advised = this.advisor.apply("foo", info, this.invoker);
		assertThat(advised).isSameAs(this.invoker);
	}

	@Test
	public void applyWhenTimeToLiveReturnsNullShouldNotAddAdvise() {
		OperationMethodInfo info = mockInfo(OperationType.READ, "get");
		given(this.timeToLive.apply(any())).willReturn(null);
		OperationInvoker advised = this.advisor.apply("foo", info, this.invoker);
		assertThat(advised).isSameAs(this.invoker);
		verify(this.timeToLive).apply("foo");
	}

	@Test
	public void applyWhenTimeToLiveIsZeroShouldNotAddAdvise() {
		OperationMethodInfo info = mockInfo(OperationType.READ, "get");
		given(this.timeToLive.apply(any())).willReturn(0L);
		OperationInvoker advised = this.advisor.apply("foo", info, this.invoker);
		assertThat(advised).isSameAs(this.invoker);
		verify(this.timeToLive).apply("foo");
	}

	@Test
	public void applyShouldAddCacheAdvise() {
		OperationMethodInfo info = mockInfo(OperationType.READ, "get");
		given(this.timeToLive.apply(any())).willReturn(100L);
		OperationInvoker advised = this.advisor.apply("foo", info, this.invoker);
		assertThat(advised).isInstanceOf(CachingOperationInvoker.class);
		assertThat(ReflectionTestUtils.getField(advised, "target"))
				.isEqualTo(this.invoker);
		assertThat(ReflectionTestUtils.getField(advised, "timeToLive")).isEqualTo(100L);
	}

	private OperationMethodInfo mockInfo(OperationType operationType, String methodName,
			Class<?>... parameterTypes) {
		Method method = ReflectionUtils.findMethod(TestOperations.class, methodName,
				parameterTypes);
		return new OperationMethodInfo(method, operationType, new AnnotationAttributes());
	}

	public static class TestOperations {

		public String get() {
			return "";
		}

		public String getWithParameter(String foo) {
			return "";
		}

	}

}


text:
package org.virtue.network.event.context.impl.in;

import org.virtue.game.content.chat.OnlineStatus;
import org.virtue.network.event.context.GameEventContext;

/**
 * @author Im Frizzy <skype:kfriz1998>
 * @author Frosty Teh Snowman <skype:travis.mccorkle>
 * @author Arthur <skype:arthur.behesnilian>
 * @author Sundays211
 * @since 2/11/2014
 */
public class ChatFilterEventContext implements GameEventContext {

	private OnlineStatus onlineStatus;

	public ChatFilterEventContext (OnlineStatus onlineStatus) {
		this.onlineStatus = onlineStatus;
	}

	public OnlineStatus getOnlineStatus () {
		return onlineStatus;
	}
}


text:
package gBacktracking;

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

public class DiceRollAndSum {

	/*
	 * Prints all possible outcomes of rolling the given number of six-sided dice in [#, #, #] format.
	 */

	public static void diceRolls(int dice){
		List<Integer> chosen = new ArrayList<Integer>();
		diceRolls(dice, chosen);
	}

	private static void diceRolls(int dice, List<Integer> chosen) {
		if(dice == 0)
			System.out.println(chosen);
		else{
			for(int i = 1; i<=6; i++){
				chosen.add(i);				//choose
				diceRolls(dice - 1 , chosen); //explore
				chosen.remove(chosen.size() - 1); //unchoose
			}
		}
	}

	/**
	 * Write a method diceSum similar to diceRoll, but it also accepts a desired sum and prints only
	 * combinations that adds up to exactly that sum.
	 */

	public static void diceSum(int dice, int sum){
		List<Integer> chosen = new ArrayList<Integer>();
		diceSum(dice, sum, chosen);
	}

	private static void diceSum(int dice, int sum, List<Integer> chosen) {

		if(dice == 0 && sums(chosen) == sum){
			System.out.println(chosen);
		}
		else{
			for(int i=1; i <= 6; i++){
				chosen.add(i);
				diceSum(dice -1 , sum, chosen);
				chosen.remove(chosen.size() -1);
			}
		}
	}

	private static int sums(List<Integer> chosen) {
		int sum = 0;
		for(Integer i : chosen){
			sum += i;
		}
		return sum;
	}

}


text:
module GoogleVisualr
  module Interactive

    # https://developers.google.com/chart/interactive/docs/gallery/calendar
    class Calendar < BaseChart

      def initialize(data_table, options={})
        super
        @packages    = ['calendar']
        send(:options=, options)
      end

      # For Configuration Options, please refer to:
      # https://developers.google.com/chart/interactive/docs/gallery/calendar#configuration-options
    end

  end
end


text:
/*global jQuery psc window resigTemplate */
psc.namespace("subject");

(function ($) {
  psc.subject.ScheduleList = (function () {
    function zeropad(i) {
      if (i < 10) {
        return "0" + i;
      } else {
        return "" + i;
      }
    }

    function dateKey(date) {
      return date.getUTCFullYear() + "-" +
        zeropad(date.getUTCMonth() + 1) + "-" +
        zeropad(date.getUTCDate());
    }

    function scheduleReady() {
      var schedule = psc.subject.ScheduleData.current();

      if (null !== schedule) {
        var container = $('#scheduled-activities').empty();
        jQuery.each(schedule.allDays(), function (i, day) {
          var key = dateKey(day);
          var hiddenActivities =(schedule.days && schedule.days[key] && schedule.days[key].hidden_activities);
          var activities =
            (schedule.days && schedule.days[key] && schedule.days[key].activities);
          if (psc.subject.isToday(day) && !activities) {
            container.append("

");
          }
          if (activities) {
            var items = $.map(activities, function (sa) {
              return resigTemplate('list_day_sa_entry', sa);
            }).join('\n');
            container.append(
              resigTemplate('list_day_entry', {
                dateClass: activities[0].dateClasses(),
                isToday: activities[0].isToday(),
                scheduledActivities: activities,
                hasHiddenActivities: hiddenActivities,
                displayDate: key,
                scheduledActivityListItems: items
              })
            );
            $(container.find("div.day:last-child")[0]).data("date", day);
          }
        });
        buildPopulationControls(schedule);
        buildAmendmentControls(schedule);
        if (buildNotificationControls(schedule)) {
          if ($(".accordion-content:visible").length == 0) {
            jQuery("#schedule-controls").accordion('activate', "#notification-header");
          }
        } else {
          if ($(".accordion-content:visible").length == 0) {
            jQuery("#schedule-controls").accordion('activate', "#display-header");
          }
        }
        psc.subject.ScheduleList.FocusHandler.init();
      }

      psc.subject.ScheduleList.buildDayPixelRanges();
      $('#schedule-error').hide();
      $('.loading').fadeOut().hide();
    }

    function buildPopulationControls(schedule){
      var container = $('#assignment-populations').empty();
      if (schedule['assignments'] != null) {
        jQuery.each(schedule['assignments'], function (i, assignment) {
          var items = $.map(assignment['populations'], function(population){
             return resigTemplate('population_entry', population);
          }).join('\n');
          container.append(
            resigTemplate('populations_entry', {
              name: assignment.name,
              id: assignment.id,
              counterClass: assignment.counterClass(),
              canUpdateSchedule: assignment.canUpdateSchedule(),
              hasPopulations: assignment.hasPopulations(),
              populationsListItems: items
            })
          );
        });
      }
    }

    function buildAmendmentControls(schedule){
      var container = $('#assignment-amendments').empty();
      if (schedule['assignments'] != null) {
        jQuery.each(schedule['assignments'], function (i, assignment) {
          var currentAmendment = assignment['current_amendment']['display_name'];
          container.append(
            resigTemplate('amendments_entry', {
              name: assignment.name,
              id: assignment.id,
              currentAmendment: currentAmendment,
              counterClass: assignment.counterClass(),
              canUpdateSchedule: assignment.canUpdateSchedule(),
              hasUnappliedAmendment: assignment.hasUnappliedAmendment()
            })
          );
        });
      }
    }

    function buildNotificationControls(schedule) {
      var container = $('#pending-notifications').empty();
      if (schedule['assignments'] != null) {
        var hasAnyNotification = false;
        jQuery.each(schedule['assignments'], function (i, assignment) {
          var items = $.map(assignment['notifications'], function(notification){
            return resigTemplate('list_notification_entry', notification);
          }).join('\n');
          hasAnyNotification = assignment.hasNotifications();
          container.append(
            resigTemplate('notifications_entry', {
              name: assignment.name,
              hasNotifications: assignment.hasNotifications(),
              notificationListItems: items
            })
          );
        });

        if (!hasAnyNotification) {
           container.text("No current notifications available.")
        }
        return hasAnyNotification;
      } else {
        return false;
      }
    }

    function scheduleError(evt, message) {
      $('#schedule-error').empty().
        append("Problem loading schedule data: " + message).show();

      $('.loading').fadeOut();
    }

    function changeActivityVisibility(evt, data) {
      var originalVisibilityCriteria = { }
      originalVisibilityCriteria.range = psc.subject.ScheduleList.visibleDayRange();
      originalVisibilityCriteria.date = originalVisibilityCriteria.range.start;
      originalVisibilityCriteria.additionalOffset =
        $('#scheduled-activities div.date-' + psc.tools.Dates.utcToApiDate(originalVisibilityCriteria.date)).
          position().top

      var affected = $("#scheduled-activities div.day li.scheduled-activity." + data.state);

      data.show ? affected.show() : affected.hide();
      $('#scheduled-activities div.day').each(function (index, day) {
        if (data.show && $(day).find('li.scheduled-activity.' + data.state).is('*')) {
          $(day).show();
        } else if (!data.show && !$(day).find('li.scheduled-activity').is(':visible')) {
          $(day).hide();
        }
      });

      psc.subject.ScheduleList.buildDayPixelRanges();
      psc.subject.ScheduleList.FocusHandler.realign(originalVisibilityCriteria);
    }

    return {
      init: function () {
        $('#schedule').bind('schedule-load-start', function () {
          $('.loading').fadeIn();
        });
        $('#schedule').bind('schedule-ready', scheduleReady);
        $('#schedule').bind('schedule-error', scheduleError);
        $('#schedule').bind('change-activity-visibility', changeActivityVisibility)
      },

      /* Creates an index of the positions of each day block to make it easier to search for what's visible */
      buildDayPixelRanges: function() {
        var currentOffset = $('#schedule').scrollTop();
        this.dayPixelRanges = $('#scheduled-activities > div.day:visible').collect(function () {
          var header = $(this).find("h3");
          var blockTop = $(this).position().top;
          return {
            date: $(this).data('date'),
            absolutePixelRange: {
              // count as "visible" if any part of the date header is visible
              start: blockTop + header.position().top + header.height() + currentOffset,
              stop: blockTop + $(this).height() + currentOffset
            }
          };
        });
      },

      visibleDayRange: function() {
        var min, max;
        var scheduleBlockHeight = $('#schedule').height();
        var scheduleScroll = $('#schedule').scrollTop();
        $(this.dayPixelRanges).each(function (i, dayInfo) {
          if (!min && (dayInfo.absolutePixelRange.start - scheduleScroll > 0)) {
            min = dayInfo.date;
          } else if ((dayInfo.absolutePixelRange.stop - scheduleScroll) > scheduleBlockHeight) {
            max = dayInfo.date;
          }

          if (min && max) {
            return false;
          }
        });

        if (!max) {
          max = $('#scheduled-activities > .day:last-child').data('date');
        }

        if (min && max) {
          return new psc.tools.Range(min, max);
        } else {
          return new psc.tools.Range(max);
        }
      },

      FocusHandler: (function () {
        var SOURCE_NAME = "list";
        var hoverUpdating = false, manualScrolling = false;
        var programaticallyScrolling = false;

        var hoverAnimator = new psc.tools.AsyncUpdater(function (dateStr) {
          $('#scheduled-activities div.day.hover-date').removeClass('hover-date');
          if (dateStr) {
            $('#scheduled-activities div.date-' + dateStr).addClass('hover-date');
          }
        });

        var focusAnimator = new psc.tools.AsyncUpdater(function (data) {
          if (SOURCE_NAME == data.source) return;
          var scrollTo = determineOffsetToDate(data.date, data.range);
          if (data.additionalOffset) scrollTo -= data.additionalOffset;
          if (scrollTo) {
            programaticallyScrolling = true;
            $('#schedule').scrollTop(scrollTo);
            // allow scroll handlers to fire
            setTimeout(function () {
              programaticallyScrolling = false;
            }, 1);
          }
        }, function (v) {
          if (v === null) {
            return null;
          } else {
            return v.date.getTime() + " " + v.additionalOffset;
          }
        });

        function extractDate(classes) {
          var bits = classes.match(/date-(\d{4})-(\d{1,2})-(\d{1,2})/);
          return new Date(Date.UTC(bits[1], bits[2] - 1, bits[3], 12, 0, 0, 0));
        }

        function hoverOverDay(evt) {
          psc.subject.ScheduleData.hoverDate(
            extractDate(this.className), SOURCE_NAME);
        }

        function hoverOutDay() {
          psc.subject.ScheduleData.hoverDate(null, SOURCE_NAME);
        }

        function hoverEvent(evt, triggerData) {
          if (triggerData.date) {
            hoverAnimator.update(dateKey(triggerData.date));
          } else {
            hoverAnimator.update(null);
          }
        }

        function determineOffsetToDate(date, range) {
          var offset;
          if (psc.subject.isToday(date)) {
            var todayElts = $('#schedule-today-marker, #scheduled-activities .today');
            if (todayElts.length > 0) {
              offset = todayElts.position().top;
            }
          } else {
            var nextVisibleBlock;
            $('#scheduled-activities > div.day:visible').each(function (i, dayBlock) {
              if (date <= $(dayBlock).data('date')) {
                nextVisibleBlock = $(dayBlock);
                return false;
              }
            });
            // only shift the list if the next visible activity in the list
            // is actually visible on the timeline (avoids nasty feedback)
            if (nextVisibleBlock && range.includes(nextVisibleBlock.data('date'))) {
              offset = nextVisibleBlock.position().top;
            } else {
              offset = 0;
            }
          }

          if (offset !== undefined) {
            return offset + $('#schedule').scrollTop();
          } else {
            return $('#scheduled-activities').height();
          }
        }

        function fireFocusChanged(evt) {
          if (!programaticallyScrolling) {
            var span = psc.subject.ScheduleList.visibleDayRange();
            psc.subject.ScheduleData.focusDate(span.start, SOURCE_NAME, span);
          }
        }

        function scrollToFocusDate(evt, triggerData) {
          focusAnimator.update(triggerData);
        }

        return {
          init: function () {
            $('#scheduled-activities > .day').mouseover(hoverOverDay).mouseout(hoverOutDay);
            $('#schedule').scroll(fireFocusChanged);

            $('#schedule').bind('hover-date-changed', hoverEvent);
            $('#schedule').bind('focus-date-changed', scrollToFocusDate);
          },

          /* When the content changes, this function can shift the scroll so that the previously
             focussed date is still focussed. */
          realign: function (ref) {
            scrollToFocusDate(null, ref);
          }
        };
      }())
    };
  }());
}(jQuery));


text:
from pylab import *
def get_buffer(particle,cluster,ic):
    cluster.neighbor_buffer = int(ceil((cluster.nsigma_buffer-cluster.nsigma_box)/2/\
                          cluster.nsigma_box))
    cluster.buffer_length = cluster.nsigma_buffer*particle.sigma/2+1e-5

# loop through all i clusters
    ista = cluster.ista[ic]
    iend = cluster.iend[ic]
    if ista <= iend:
        xc = cluster.xc[ic]
        yc = cluster.yc[ic]
        ix = cluster.ix[ic]
        iy = cluster.iy[ic]
        jx_min = max(0,ix-cluster.neighbor_buffer)
        jx_max = min(cluster.nx-1,ix+cluster.neighbor_buffer)
        jy_min = max(0,iy-cluster.neighbor_buffer)
        jy_max = min(cluster.ny-1,iy+cluster.neighbor_buffer)

# put all particles in the center box into the corresponding cell structure
        clusterx = []
        clustery = []
        clusterg = []
        clustere = []
        clusterw = []
        clusterx.extend(particle.xi[ista:iend+1])
        clustery.extend(particle.yi[ista:iend+1])
        clusterg.extend(particle.gj[ista:iend+1])
        clustere.extend(particle.ei[ista:iend+1])
        clusterw.extend(particle.wi[ista:iend+1])

# loop through all neighbor
        for jx in range(jx_min,jx_max+1):
            for jy in range(jy_min,jy_max+1):
                if ix != jx or iy != jy:
                    jc = jx*cluster.ny+jy
                    jsta = cluster.ista[jc]
                    jend = cluster.iend[jc]

# select from the particles in the neighbor boxes, the ones that belong in the buffer zone
                    xi = particle.xi[jsta:jend+1]
                    yi = particle.yi[jsta:jend+1]
                    gi = particle.gj[jsta:jend+1]
                    ei = particle.ei[jsta:jend+1]
                    wi = particle.wi[jsta:jend+1]
                    buffer = abs(xi-xc)<cluster.buffer_length
                    xi = extract(buffer,xi)
                    yi = extract(buffer,yi)
                    gi = extract(buffer,gi)
                    ei = extract(buffer,ei)
                    wi = extract(buffer,wi)
                    buffer = abs(yi-yc)<cluster.buffer_length
                    xi = extract(buffer,xi)
                    yi = extract(buffer,yi)
                    gi = extract(buffer,gi)
                    ei = extract(buffer,ei)
                    wi = extract(buffer,wi)

# add all particles in the neighbor boxes into the corresponding cell structure
                    clusterx.extend(xi)
                    clustery.extend(yi)
                    clusterg.extend(gi)
                    clustere.extend(ei)
                    clusterw.extend(wi)
            cluster.xib=clusterx
            cluster.yib=clustery
            cluster.gib=clusterg
            cluster.eib=clustere
            cluster.wib=clusterw
            cluster.npbufferi = len(clusterx)
    else:
        cluster.xib=[]
        cluster.yib=[]
        cluster.gib=[]
        cluster.eib=[]
        cluster.wib=[]
        cluster.npbufferi = 0

    return particle,cluster


text:
title: <%= hoc_s(:title_press_kit) %>
layout: wide
nav: promote_nav

---

## Cómo atraer los medios a tú evento "Hora de Código"

*Para todas las consultas de la prensa y los medios de comunicación, póngase en contacto con <press@code.org>*

### Consejos clave

  * Llegar a los medios de comunicación dos semanas antes de su evento por correo electrónico. Reitere por email y teléfono si no recibe una respuesta inicial.
  * Pide a un miembro del personal escolar o voluntario que tome fotos para compartirla en línea o enviar a la prensa.
  * Escribe sobre la Hora de Código en la página principal de tu sitio web y en el periódico de la escuela. Pública los detalles de tu evento y fotos de las actividades de tus estudiantes.
  * On Facebook and Twitter, share updates on your plans, announce your events and post pictures during Dec. 7-13. Use the hashtag **#HourOfCode** so Code.org can see and promote your events.

### Guía paso a paso:

**1. Planifica tu evento**

  * Haz una reunión para iniciar la Hora de Código.
  * Send [a letter](<%= resolve_url('/promote/resources#sample-emails') %>) to parents. Ask them to spread the word.
  * Send [a letter](<%= resolve_url('/promote/resources#sample-emails') %>) to invite your local mayor, congressman, governor, or influential businessperson to attend and speak to your students.
  * Organiza actividades grupales (como una demostración de una actividad de programación 'fuera de línea'), o muestra lo que han hecho los estudiantes y guía las actividades.
  * Show Code.org's [Hour of Code video](<%= resolve_url('/') %>) or one of [these](<%= resolve_url('/promote/resources#videos') %>) to inspire.

**2. Identifica a los reporteros locales que cubren notas escolares o eventos locales.**

Piensa en un periódico local, estación de TV, estación de radio o blog.

Busca en línea la información de contacto de un reportero. Si no puedes encontrarlo, habla al medio de comunicación para preguntar, o manda un correo electrónico a tips@nombredelmedio.com y pide que tu correo sea dirigido al reportero adecuado.

**3. Contacta a medios locales**

La mejor forma es por correo electrónico. Debe ser corto y debe responder a la siguiente pregunta: ¿por qué les debe importar a las personas este evento? Incluye información de contacto (sobre todo un número de teléfono móvil) para quien esté en el sitio del evento. **See a [sample pitch to media](<%= resolve_url('/promote/resources#sample-emails') %>):**

**4. Prepárate para las preguntas que te hagan acerca de tu evento escolar. Aquí hay unos ejemplos:**

*¿Por que tu escuela hace una Hora de Programación?*

Todos sabemos que es importante que los estudiantes aprendan a navegar en este mundo saturado de tecnología, muchos profesores no tienen experiencia con las ciencias computacionales y no saben como empezar. Este evento es una oportunidad para que todos nosotros veamos qué son las Ciencias de la computación.

Esperamos que despierte inquietud en nuestros estudiantes para seguir aprendiendo. La investigación también muestra que los niños aprenden conceptos de programación antes de que sepan leer y escribir. De hecho, el cerebros es más receptivo a los lenguajes de programación en edades más tempranas, tal como en los idiomas.

*¿Por qué es importante?*

En China, todos los estudiantes toman clases de computación para graduarse de la preparatoria. En Estados Unidos, el 90% de la escuelas ni siquiera enseña computación. Es tiempo de avanzar al siglo XXI. Sabemos que sin importar la carrera que sigan nuestros estudiantes al crecer, ya sea medicina, negocios, política o las artes, saber como construir tecnología les dará confianza y conocimientos para triunfar.

**Otros detalles y una cita que puedes usar para tus materiales promocionales**

"La Hora de Programación ha sido diseñada para desmitificar la programación y mostrar que la informática no es ciencia espacial, cualquiera puede aprender las bases," dijo Hadi Partovi, fundador y CEO de Code.org. "Over 100 million students worldwide have tried an Hour of Code. The demand for relevant 21st century computer science education crosses all borders and knows no boundaries."

**Acerca de Code.org**

Code.org is a 501c3 public non-profit dedicated to expanding participation in computer science and increasing participation by women and underrepresented students of color. Su visión es que todos los estudiantes en todas las escuelas tengan la oportunidad de aprender programación informática. After launching in 2013, Code.org organized the Hour of Code campaign – which has introduced over 100 million students to computer science to date – and partnered with 70 public school districts nationwide to expand computer science programs. Code.org is supported by philanthropic donations from corporations, foundations and generous individuals, including Microsoft, Infosys Foundation, USA, The Ballmer Family Giving, Omidyar Network and others. Para obtener más información por favor visite: [<%= resolve_url('code.org') %>](<%= resolve_url('https://code.org') %>).

Find more resources and sample emails [here](<%= resolve_url('/promote') %>).


text:
import React from 'react';
import DatePicker from 'react-bootstrap-date-picker';
import t from 'tcomb-form';
const Form = t.form.Form;

  const dateTransformer = {
    format: (value) => t.Date.is(value) ? value.toISOString() : value,
    parse: (str) => str ? new Date(str) : null
  };

  const renderDate = (locals) => {
    return (
      <DatePicker value={locals.value} onChange={locals.onChange}/>
    );
  }

  const datePickerTemplate = Form.templates.date.clone({ renderDate });

  class DatePickerFactory extends t.form.Component {
    getTemplate() {
      return datePickerTemplate;
    }
  }

  t.Date.getTcombFormFactory = () => DatePickerFactory;

module.exports = renderDate;


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Dart - Polymer</title>

		<meta name="description" content="Une toute petite présentation sur Dart">
		<meta name="author" content="Vincent FERRIES">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/default.css" id="theme">
		<link rel="stylesheet" href="css/fullscreen-img.css">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Scalable Web App Engineering

						By Vincent FERRIES / @VincentFERRIES

First thing first...

What we will see today

A new language for web development

Construct both server and client parts

Have a glimpse at the future of the web

Don't we allready have what we need?

JavaScript!

Even GWT / Vaadin to code in Java

Applets !

And finally...

We've got JavaScript!

Let's talk about JavaScript!

							<video controls src="images/wat.mov">Destroy all software</video>

Let's talk about GWT!

public class Hello implements EntryPoint {

  public void onModuleLoad() {
    Button b = new Button("Click me", new ClickHandler() {
      public void onClick(ClickEvent event) {
        Window.alert("Hello, AJAX");
      }
    });

    RootPanel.get().add(b);
  }
}

Let's talk about Applets!

Le contrat de confiance

A Language

Web Components (Polymer and Angular)

An editor (many actually)

A virtual machine

Pub

The Killer Feature

dart2js

Base concepts

Everything is an object

Optional Types

Production mode / Checked mode

No private keyword but _

Some examples

var bigInt = 1234567890234568972349642987923445778389768989647678576;

String interpolated = "Amount: $bigInt";

var complexInterpolation = "VAT: ${bigInt * 0.196}";

double onePointOne = double.parse('1.1');

Complex Types

List<int> list = [1,2,3];

var gifts = {
	'first': 'Dart Vader',
	'second': 'Dartagnan',
	'fifth': 'The Dart Knight'
};

Map nobleGases = {2: 'helium', 10: 'neon', 18: 'argon'};

var gifts = new Map();
gifts['first'] = 'Alone in the Dart 2';
gifts['second'] = 'The Dartist';
assert(gifts.length == 2);

Methods

setOptions({String url, int port , bool useProxy}) {
	// Do something with these params
}

setOptions(useProxy: true, port: 8080);

String doSomething(String param, [List flags]) {
	// Do something here
}

Classes

class Point {
	num x, y;
	Point(this.x, this.y);
	Point.zero() : x = 0, y = 0;
	String toString() => '($x, $y)';
}

Point pos = new Point(2, 3.4);
String pStr = new Point.zero().toString();

Functional programming

list.forEach((x) => print(x));

map.forEach((k, v) {
	i++;
	print('$i - $k = $v');
});

square(x) => x*x;
list.map(square);

list = ['Cap Gemini', 'Genigraph', 'Atos'];
list.filter((name) => name.startsWith('G'));

Builders are over...

var myObject = new MyObject();
myObject.setName("EclipseCon");
myObject.setSize(42);
myObject.callMethod(3);
return myObject;

return new MyObject()
	..setName("EclipseCon")
	..setSize(42)
	..callMethod(3);

DOM Manipulation

querySelector("#myId").classes.add("success");

querySelectorAll("#myId li").forEach((el){
	el.on.mouseOver.add("selected");
	el.on.mouseOut.remove("selected");
});

Alone in the Dart

Good old time!

Once upon a time...

<select multiple>
	<option>Dart</option>
	<option>JavaScript</option>
	<option>Polymer</option>
	<p>What if we write something else here?</p>
</select>

					<select multiple>
						<option>Dart</option>
						<option>JavaScript</option>
						<option>Polymer</option>

What if we write something else here?

					</select>

Since at least 1993

<select>
	<optgroup label="Front-End">
		<option selected>Dart</option>
		<option disabled>JavaScript</option>
		<option>Polymer</option>
	</optgroup>
	<optgroup label="Back-End">
		<option>Dart</option>
		<option>JavaScript</option>
		<option disabled>Polymer</option>
	</optgroup>
	<p>What if we write something else here?</p>
</select>

					<select>
						<optgroup label="Front-End">
							<option selected>Dart</option>
							<option disabled>JavaScript</option>
							<option>Polymer</option>
						</optgroup>
						<optgroup label="Back-End">
							<option>Dart</option>
							<option>JavaScript</option>
							<option disabled>Polymer</option>
						</optgroup>
					</select>

<e-mails>
  <e-mail>
    <subject>Valar Morghulis</subject>
    <sent>2014-10-03</sent>
    <summary>Dracarys!</summary>
  </e-mail>
  <e-mail>
    <subject>Reminder: Beware!</subject>
    <sent>2012-10-04</sent>
    <summary>The night is dark and full of terrors. </summary>
  </e-mail>
</e-mails>
<hangouts>
  <hangout with="arya.stark@gmail.com">
    <you>What do we say to the God of death?</you>
    <her>Not today.</her>
  </hangout>
  <hangout with="ned.stark@gmail.com">
    <him>War was easier than daughters.</him>
  </hangout>
</hangouts>

Polymer

A quick demo

Polymer Designer (JS)

Defining a Custom Element

<polymer-element name="hello-you" noscript>
  <template>

Hello EclipseCon France!

  </template>
</polymer-element>

Using Custom Element

In the head section

  <link rel="import" href="hello_world.html">
  <script type="application/dart">
  	export 'package:polymer/init.dart';
  </script>
  <script src="packages/browser/dart.js"></script>

Simply use it

<hello-you></hello-you>

Data binding

In the template

<polymer-element name="click-counter">
  <template>
    <button on-click="{{increment}}">Click Me</button>
    <p>You clicked the button {{count}} times.</p>
  </template>
  <script type="application/dart" src="click_counter.dart"></script>
</polymer-element>

Data binding

In the script

import 'package:polymer/polymer.dart';
import 'dart:html';

@CustomTag('click-counter')
class ClickCounterElement extends PolymerElement {
  @observable int count = 0;

  ClickCounterElement.created() : super.created();

  void increment(Event e, var detail, Node target) {
    count += 1;
  }
}

Shadow DOM

					In the settings of Chrome Dev Tools.

<content select=".email"></content>

</thank-you>


text:
case $1 in
  development)
    rsync -r --delete-after --exclude-from 'scripts/exclude.txt' --quiet $TRAVIS_BUILD_DIR/ git@jyps.fi:/usr/share/nginx/betarekkari.jyps.fi
    ssh git@jyps.fi "php /usr/share/nginx/betarekkari.jyps.fi/app/console cache:clear --env=dev"
    ;;
  production)
    rsync -r --delete-after --exclude-from 'scripts/exclude.txt' --quiet $TRAVIS_BUILD_DIR/ git@jyps.fi:/usr/share/nginx/jasenrekisteri.jyps.fi
    ssh git@jyps.fi "php /usr/share/nginx/jasenrekisteri.jyps.fi/app/console cache:clear --env=prod"
    ;;
esac


text:
package com.example.tests;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

//import static com.example.tests.GroupDataGenerator.ganerateRandomGroups;
import static com.example.tests.GroupDataGenerator.loadGroupsFromCsvFile;
import static com.example.tests.GroupDataGenerator.loadGroupsFromXmlFile;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.*;

import com.example.utils.SortedListOf;

public class GroupCreationTests extends TestBase {

	@DataProvider
	public Iterator<Object[]> groupsFromFile() throws IOException {
	//	return wrapGroupsDataForProvider(loadGroupsFromCsvFile(new File("groups.txt"))).iterator();
		return wrapGroupsDataForProvider(loadGroupsFromXmlFile(new File("groups.xml"))).iterator();
	}

@Test(dataProvider = "groupsFromFile")
  public void testGroupCreationWithValidData(GroupData group) throws Exception {
	//app.navigateTo().mainPage();
    //app.navigateTo().groupsPage();

    //save old state
    SortedListOf<GroupData> oldList=app.getGroupHelper().getGroups();

    //actions
    app.getGroupHelper().createGroup(group);

    //save new state
    SortedListOf<GroupData> newList=app.getGroupHelper().getGroups();

    //compare states
    assertThat(newList, equalTo(oldList.withAdded(group)));
    }

}


text:
/// <reference path="../../../typings/typescriptapp.d.ts" />

module App.UI {

    "use strict";

    var $q: ng.IQService = <ng.IQService>angular.injector(['ng']).get("$q");

    export var translateXYAsync = (options: any) => {

        var deferred = $q.defer();

        options.element.addEventListener('transitionend', () => {
            deferred.resolve();
        }, false);

        angular.element(options.element).css({
            "-moz-transform": "translate(" + options.x + "px, " + options.y + "px)",
            "-webkit-transform": "translate(" + options.x + "px, " + options.y + "px)",
            "-ms-transform": "translate(" + options.x + "px, " + options.y + "px)",
            "-transform": "translate(" + options.x + "px, " + options.y + "px)"
        });

        return deferred.promise;

    };

    angular.module("app.ui").value("translateXYAsync", translateXYAsync);
}


text:
package security;

import model.user.User;

import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import repository.UserRepository;
import repository.events.ApplicationContextProvider;

@Service
public class LoginUserService implements UserDetailsService {

  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username)
      throws UsernameNotFoundException {

    // http://stackoverflow.com/questions/16455348/autowired-dependency-injection-with-spring-security
    if (userRepository == null) {
      ApplicationContext context = ApplicationContextProvider.getApplicationContext();
      userRepository = context.getBean(UserRepository.class);
    }

    User user = userRepository.findUser(username);
    if (user != null)
      return new V2VUserDetails(user);
    else
      return null;
  }

}


text:
using namespace cv;
using namespace cvproc;
using namespace cvproc::imagematch;

cMatchResult::cMatchResult()
{
	Clear();
}

cMatchResult::~cMatchResult()
{
}

void cMatchResult::Init(cMatchScript2 *p, const cv::Mat &input, const string &inputName,
	const int inputImageId, sParseTree *labelTree, const bool isRegisterInput, const bool isBlockMode)
{
	Clear();

	m_script = p;
	m_isRun = true;
	m_isTerminate = false;
	m_input = input.clone();
	m_srcImage = input.clone();
	m_inputName = inputName;
	m_inputImageId = inputImageId;
	m_registerInput = isRegisterInput;
	m_removeInput = isRegisterInput;
	m_blockMode = isBlockMode;
	m_nodeLabel = labelTree;
	m_beginTime = timeGetTime();
}

void cMatchResult::Clear()
{
	m_traverseType = 0;
	m_script = NULL;
	m_input = Mat();
 	m_srcImage = Mat();
 	m_inputName.clear();
	m_inputImageId = -1;
	m_registerInput = true;
	m_blockMode = false;
	m_removeInput = false;
	m_nodeLabel = NULL;
	m_resultStr.clear();
	m_isRun = false;
	m_isTerminate = false;
	m_isEnd = false;
	m_result = 0;
	m_matchCount = 0;
	m_beginTime = 0;

	ZeroMemory(m_data, sizeof(m_data));
}

void cMatchResult::TerminateMatch()
{
	m_isTerminate = true;
}

void cMatchResult::MatchComplete()
{
	m_isRun = false;
	m_isEnd = false;
	m_isTerminate = false;
}