text:
from iptest.assert_util import *
from iptest.warning_util import warning_trapper
import sys

AreEqual(sys.exc_info(), (None, None, None))

def test_exception_line_no_with_finally():
    def f():
        try:
            raise Exception()   # this line should correspond w/ the number below
        finally:
            pass

    try:
        f()
    except Exception, e:
        tb = sys.exc_info()[2]
        expected = [25, 30]
        while tb:
            AreEqual(tb.tb_lineno, expected.pop()) # adding lines will require an update here
            tb = tb.tb_next

if is_cli or is_silverlight:
    def test_system_exception():
        import System

        def RaiseSystemException():
            raise System.SystemException()

        AssertError(SystemError, RaiseSystemException)

    AreEqual(sys.exc_info(), (None, None, None))

if is_cli or is_silverlight:
    def test_raise():
        try:
             Fail("Message")
        except AssertionError, e:
             AreEqual(e.__str__(), e.args[0])
        else:
            Fail("Expected exception")

def test_finally_continue_fails():
    t = '''
try:
    pass
finally:
    continue
'''
    try:
        compile(t, '<test>', 'exec')
        Fail("Should raise SyntaxError")
    except SyntaxError:
        pass

def test_finally_continue_in_loop_allowed():
    t = '''
try:
    pass
finally:
    for i in range(1):
        continue
'''
    try:
        compile(t, '<test>', 'exec')
    except SyntaxError:
        Fail("Should not raise SyntaxError")

def test_finally_continue_nested_finally_fails():
    t = '''
try:
    pass
finally:
    for i in range(1):
        try:
            pass
        finally:
            continue
'''
    try:
        compile(t, '<test>', 'exec')
        Fail("Should raise SyntaxError")
    except SyntaxError:
        pass

def test_bigint_division():
    def divide(a, b):
        try:
            c = a / b
            Fail("Expected ZeroDivisionError for %r / %r == %r" % (a, b, c))
        except ZeroDivisionError:
            pass

        try:
            c = a % b
            Fail("Expected ZeroDivisionError for %r %% %r == %r" % (a, b, c))
        except ZeroDivisionError:
            pass

        try:
            c = a // b
            Fail("Expected ZeroDivisionError for %r // %r == %r" % (a, b, c))
        except ZeroDivisionError:
            pass

    big0 = 9999999999999999999999999999999999999999999999999999999999999999999999
    big0 = big0-big0

    pats = [0L, 0, 0.0, big0, (0+0j)]
    nums = [42, 987654321, 7698736985726395723649587263984756239847562983745692837465928374569283746592837465923, 2352345324523532523, 5223523.3453, (10+25j)]

    for divisor in pats:
        for number in nums:
            divide(number, divisor)

# sys.exit() test

def test_handlers():
    handlers = []

    def a():
        try:
            b()
        finally:
            handlers.append("finally a")

    def b():
        try:
            c()
        finally:
            handlers.append("finally b")

    def c():
        try:
            d()
        finally:
            handlers.append("finally c")

    def d():
        sys.exit("abnormal termination")

    try:
        a()
    except SystemExit, e:
        handlers.append(e.args[0])

    Assert(handlers == ["finally c", "finally b", "finally a", "abnormal termination"])

def test_sys_exit1():
    try:
        sys.exit()
        Assert(False)
    except SystemExit, e:
        AreEqual(len(e.args), 0)

def test_sys_exit2():
    try:
        sys.exit(None)
        Assert(False)
    except SystemExit, e:
        AreEqual(e.args, ())

    AreEqual(SystemExit(None).args, (None,))

def test_sys_exit3():
    try:
        sys.exit(-10)
    except SystemExit, e:
        AreEqual(e.code, -10)
        AreEqual(e.args, (-10,))
    else:
        Assert(False)

################################
# exception interop tests
if is_cli or is_silverlight:
    def test_interop():
        load_iron_python_test()

        from IronPythonTest import ExceptionsTest
        import System
        import sys

        a = ExceptionsTest()

        try:
            a.ThrowException()  # throws index out of range
        except IndexError, e:
            Assert(e.__class__ == IndexError)

        class MyTest(ExceptionsTest):
            def VirtualFunc(self):
                raise ex, "hello world"

        ex = ValueError

        a = MyTest()

        # raise in python, translate into .NET, catch in Python
        try:
            a.CallVirtual()
        except ex, e:
            Assert(e.__class__ == ValueError)
            Assert(e.args[0] == "hello world")

        # raise in python, catch in .NET, verify .NET got an ArgumentException

        try:
            x = a.CallVirtCatch()
        except ex, e:
            Assert(False)

        Assert(isinstance(x, System.ArgumentException))

        # call through the slow paths...

        try:
            a.CallVirtualOverloaded('abc')
        except ex,e:
            Assert(e.__class__ == ex)
            Assert(e.args[0] == "hello world")
        # Note that sys.exc_info() is still set

        try:
            a.CallVirtualOverloaded(5)
        except ex,e:
            Assert(e.__class__ == ex)
            Assert(e.args[0] == "hello world")

        try:
            a.CallVirtualOverloaded(a)
        except ex,e:
            Assert(e.__class__ == ex)
            Assert(e.args[0] == "hello world")

        # catch and re-throw (both throw again and rethrow)

        try:
            a.CatchAndRethrow()
        except ex,e:
            Assert(e.__class__ == ex)
            Assert(e.args[0] == "hello world")

        try:
            a.CatchAndRethrow2()
        except ex,e:
            Assert(e.__class__ == ex)
            Assert(e.args[0] == "hello world")

        class MyTest(ExceptionsTest):
            def VirtualFunc(self):
                self.ThrowException()

        a = MyTest()

        # start in python, call CLS which calls Python which calls CLS which raises the exception
        try:
            a.CallVirtual()  # throws index out of range
        except IndexError, e:
            Assert(e.__class__ == IndexError)

        # verify we can throw arbitrary classes
        class MyClass: pass

        try:
            raise MyClass
            Assert(False)
        except MyClass, mc:
            Assert(mc.__class__ == MyClass)

        # BUG 430 intern(None) should throw TypeError
        try:
            intern(None)
            Assert(False)
        except TypeError:
            pass
        # /BUG

        # BUG 393 exceptions throw when bad value passed to except
        try:
            try:
                raise SyntaxError("foo")
            except 12:
                Assert(False)
                pass
        except SyntaxError:
            pass
        # /BUG

        # BUG 319 IOError not raised.
        if is_silverlight==False:
            try:
                fp = file('thisfiledoesnotexistatall.txt')
            except IOError:
                pass
        # /BUG

        # verify we can raise & catch CLR exceptions
        try:
            raise System.Exception('Hello World')
        except System.Exception, e:
            Assert(type(e) == System.Exception)

        # BUG 481 Trying to pass raise in Traceback should cause an error until it is implemented
        try:
            raise StopIteration("BadTraceback"), "somedata", "a string is not a traceback"
            Assert (False, "fell through raise for some reason")
        except StopIteration:
            Assert(False)
        except TypeError:
            pass

        try:
            raise TypeError
        except:
            import sys
            if (sys.exc_traceback != None):
                x = dir(sys.exc_traceback)
                for name in ['tb_frame', 'tb_lasti', 'tb_lineno', 'tb_next']:
                    Assert(name in x, name)
                try:
                    raise Exception("foo"), "Msg", sys.exc_traceback
                except Exception, X:
                    pass

        try:
            raise Exception(3,4,5)
        except Exception, X:
            AreEqual(X[0], 3)
            AreEqual(X[1], 4)
            AreEqual(X[2], 5)

        try:
            raise Exception
        except:
            import exceptions
            AreEqual(sys.exc_info()[0], exceptions.Exception)
            AreEqual(sys.exc_info()[1].__class__, exceptions.Exception)

        try:
            Fail("message")
        except AssertionError, e:
            import exceptions

            AreEqual(e.__class__, exceptions.AssertionError)
            AreEqual(len(e.args), 1)
            AreEqual(e.args[0], "message")
        else:
            Fail("Expected exception")

#####################################################################################
# __str__ behaves differently for exceptions because of implementation (ExceptionConverter.ExceptionToString)

# TODO: doesn't work in IronPython
#def test_str1():
#    AssertErrorWithMessage(TypeError, "descriptor '__str__' of 'exceptions.BaseException' object needs an argument", Exception.__str__)
#    AssertErrorWithMessage(TypeError, "descriptor '__str__' requires a 'exceptions.BaseException' object but received a 'list'", Exception.__str__, list())
#    AssertErrorWithMessage(TypeError, "descriptor '__str__' requires a 'exceptions.BaseException' object but received a 'list'", Exception.__str__, list(), 1)
#    AssertErrorWithMessage(TypeError, "expected 0 arguments, got 1", Exception.__str__, Exception(), 1)

def test_str2():
    # verify we can assign to sys.exc_*
    sys.exc_traceback = None
    sys.exc_value = None
    sys.exc_type = None

    AreEqual(str(Exception()), '')

#####################################################################

if is_cli or is_silverlight:
    def test_array():
        import System
        try:
            a = System.Array()
        except Exception, e:
            AreEqual(e.__class__, TypeError)
        else:
            Assert(False, "FAILED!")

def test_assert_error():
    AssertError(ValueError, chr, -1)
    AssertError(TypeError, None)

def test_dir():
    testingdir = 10
    Assert('testingdir' in dir())
    del testingdir
    Assert(not 'testingdir' in dir())

def test_assert():
    try:
        Assert(False, "Failed message")
    except AssertionError, e:
        Assert(e.args[0] == "Failed message")
    else:
        Fail("should have thrown")

    try:
        Assert(False, "Failed message 2")
    except AssertionError, e:
        Assert(e.args[0] == "Failed message 2")
    else:
        Fail("should have thrown")

def test_syntax_error_exception():
    try:
        compile('a = """\n\n', 'foo', 'single', 0x200)
    except SyntaxError, se:
        AreEqual(se.offset, 9)

    try:
        compile('a = """\n\nxxxx\nxxx\n', 'foo', 'single', 0x200)
    except SyntaxError, se:
        AreEqual(se.offset, 18)

    try:
        compile('abc\na = """\n\n', 'foo', 'exec', 0x200)
    except SyntaxError, se:
        AreEqual(se.offset, 9)

    try:
        compile("if 2==2: x=2\nelse:y=", "Error", "exec")
    except SyntaxError, se:
        l1 = dir(se)
        Assert('lineno' in l1)
        Assert('offset' in l1)
        Assert('filename' in l1)
        Assert('text' in l1)
        if is_cli or is_silverlight:
            import clr
            l2 = dir(se.clsException)
            Assert('Line' in l2)
            Assert('Column' in l2)
            Assert('GetSymbolDocumentName' in l2)
            Assert('GetCodeLine' in l2)
        AreEqual(se.lineno, 2)
        # Bug 1132
        #AreEqual(se.offset, 7)
        AreEqual(se.filename, "Error")
        if is_ironpython: #http://ironpython.codeplex.com/workitem/27989
            AreEqual(se.text, "else:y=")
        else:
            AreEqual(se.text, "else:y=\n")
        if is_cli or is_silverlight:
            AreEqual(se.clsException.Line, 2)
            # Bug 1132
            #AreEqual(se.clsException.Column, 7)
            AreEqual(se.clsException.GetSymbolDocumentName(), "Error")
            AreEqual(se.clsException.GetCodeLine(), "else:y=")
        AreEqual(se.__dict__, {})
        AreEqual(type(se.__dict__), dict)

def test_syntax_error_exception_exec():
    try:
        compile("if 2==2: x=", "Error", "exec")
    except SyntaxError, se:
        AreEqual(se.lineno, 1)
        # Bug 1132
        #AreEqual(se.offset, 11)
        AreEqual(se.filename, "Error")
        if is_ironpython: #http://ironpython.codeplex.com/workitem/27989
            AreEqual(se.text, "if 2==2: x=")
        else:
            AreEqual(se.text, "if 2==2: x=\n")
        AreEqual(se.__dict__, {})
        AreEqual(type(se.__dict__), dict)

def test_syntax_error_exception_eval():
    try:
        compile("if 2==2: x=", "Error", "eval")
    except SyntaxError, se:
        AreEqual(se.lineno, 1)
        # Bug 1132
        #AreEqual(se.offset, 2)
        AreEqual(se.filename, "Error")
        AreEqual(se.text, "if 2==2: x=")
        AreEqual(se.__dict__, {})
        AreEqual(type(se.__dict__), dict)

def test_user_syntax_error_exception():
    x = SyntaxError()
    AreEqual(x.lineno, None)
    AreEqual(x.filename, None)
    AreEqual(x.msg, None)
    AreEqual(x.message, '')
    AreEqual(x.offset, None)
    AreEqual(x.print_file_and_line, None)
    AreEqual(x.text, None)
    #Run a few minimal tests to ensure the __dict__ member works OK
    AreEqual(x.__dict__, {})
    AreEqual(type(x.__dict__), dict)
    x.arbitrary = 3.14
    AreEqual(x.__dict__["arbitrary"], 3.14)
    del x.__dict__["arbitrary"]
    AreEqual(x.__dict__, {})

    x = SyntaxError('hello')
    AreEqual(x.lineno, None)
    AreEqual(x.filename, None)
    AreEqual(x.msg, 'hello')
    AreEqual(x.message, 'hello')
    AreEqual(x.offset, None)
    AreEqual(x.print_file_and_line, None)
    AreEqual(x.text, None)

    x = SyntaxError('hello', (1,2,3,4))
    AreEqual(x.lineno, 2)
    AreEqual(x.filename, 1)
    AreEqual(x.msg, 'hello')
    AreEqual(x.message, '')
    AreEqual(x.offset, 3)
    AreEqual(x.print_file_and_line, None)
    AreEqual(x.text, 4)

    AssertError(IndexError, SyntaxError, 'abc', ())
    AssertError(IndexError, SyntaxError, 'abc', (1,))
    AssertError(IndexError, SyntaxError, 'abc', (1,2))
    AssertError(IndexError, SyntaxError, 'abc', (1,2,3))

def test_return():
    def test_func():
        try: pass
        finally:
            try: raise 'foo'
            except:
                return 42

    AreEqual(test_func(), 42)

    def test_func():
        try: pass
        finally:
            try: raise 'foo'
            except:
                try: raise 'foo'
                except:
                    return 42

    AreEqual(test_func(), 42)

    def test_func():
        try: pass
        finally:
            try: pass
            finally:
                try: raise 'foo'
                except:
                    try: raise 'foo'
                    except:
                        return 42

    AreEqual(test_func(), 42)

    def test_func():
        try: raise 'foo'
        except:
            try: pass
            finally:
                try: raise 'foo'
                except:
                    try: raise 'foo'
                    except:
                        return 42

    AreEqual(test_func(), 42)

def test_break_and_continue():
    class stateobj(object):
        __slots__ = ['loops', 'finallyCalled']
        def __init__(self):
            self.loops = 0
            self.finallyCalled = False

    def test_break(state):
        try:
            try:
                raise Exception()
            except:
                for n in range(10):
                    state.loops += 1
                    break
            return 42
        except: pass

    def test_continue(state):
        try:
            try:
                raise Exception()
            except:
                for n in range(10):
                    state.loops += 1
                    continue
            return 42
        except: pass

    def test_multi_break(state):
        try:
            try:
                raise Exception()
            except:
                for n in range(10):
                    state.loops += 1
                    if False: break

                    break

            return 42
        except: pass

    def test_multi_continue(state):
        try:
            try:
                raise Exception()
            except:
                for n in range(10):
                    state.loops += 1
                    if False: continue

                    continue

            return 42
        except: pass

    state = stateobj()
    AreEqual(test_break(state), 42)
    AreEqual(state.loops, 1)

    state = stateobj()
    AreEqual(test_continue(state), 42)
    AreEqual(state.loops, 10)

    state = stateobj()
    AreEqual(test_multi_break(state), 42)
    AreEqual(state.loops, 1)

    state = stateobj()
    AreEqual(test_multi_continue(state), 42)
    AreEqual(state.loops, 10)

    def test_break_in_finally_raise(state):
        for x in range(10):
            try:
                raise 'foo'
            finally:
                state.finallyCalled = True
                break
        return 42

    def test_break_in_finally(state):
        for x in range(10):
            try: pass
            finally:
                state.finallyCalled = True
                break
        return 42

    state = stateobj()
    AreEqual(test_break_in_finally_raise(state), 42)
    AreEqual(state.finallyCalled, True)

    state = stateobj()
    AreEqual(test_break_in_finally(state), 42)
    AreEqual(state.finallyCalled, True)

    def test_outer_for_with_finally(state, shouldRaise):
        for x in range(10):
            try:
                try:
                    if shouldRaise:
                        raise 'hello world'
                finally:
                    state.finallyCalled = True
                    break
            except:
                pass
            raise 'bad!!!'
        return 42

    state = stateobj()
    AreEqual(test_outer_for_with_finally(state, False), 42)
    AreEqual(state.finallyCalled, True)

    state = stateobj()
    AreEqual(test_outer_for_with_finally(state, True), 42)
    AreEqual(state.finallyCalled, True)

    def test_outer_for_with_finally(state, shouldRaise):
        for x in range(10):
            try:
                try:
                    if shouldRaise:
                        raise 'hello world'
                finally:
                    state.finallyCalled = True
                    break
            except:
                pass
            raise 'bad!!!'
        return 42

    state = stateobj()
    AreEqual(test_outer_for_with_finally(state, False), 42)
    AreEqual(state.finallyCalled, True)

    state = stateobj()
    AreEqual(test_outer_for_with_finally(state, True), 42)
    AreEqual(state.finallyCalled, True)

def test_serializable_clionly():
    import clr
    import System
    from IronPythonTest import ExceptionsTest
    path = clr.GetClrType(ExceptionsTest).Assembly.Location
    mbro = System.AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap(path, "IronPythonTest.EngineTest")
    AssertError(AssertionError, mbro.Run, 'raise AssertionError')
    import exceptions

    for eh in dir(exceptions):
        eh = getattr(exceptions, eh)
        if isinstance(eh, type) and issubclass(eh, BaseException):
            # unicode exceptions require more args...
            if (eh.__name__ != 'UnicodeDecodeError' and
                eh.__name__ != 'UnicodeEncodeError' and
                eh.__name__ != 'UnicodeTranslateError'):
                AssertError(eh, mbro.Run, 'raise ' + eh.__name__)

def test_sanity():
    '''
    Sanity checks to ensure all exceptions implemented can be created/thrown/etc
    in the standard ways.
    '''
    #build up a list of all valid exceptions
    import exceptions
    #special cases - do not test these like everything else
    special_types = [ "UnicodeTranslateError", "UnicodeEncodeError", "UnicodeDecodeError"]
    exception_types = [ x for x in exceptions.__dict__.keys() if x.startswith("__")==False and special_types.count(x)==0]
    exception_types = [ eval("exceptions." + x) for x in exception_types]

    #run a few sanity checks
    for exception_type in exception_types:
        except_list = [exception_type(), exception_type("a single param")]

        for t_except in except_list:
            try:
                raise t_except
            except exception_type, e:
                pass

            str_except = str(t_except)

            #there is no __getstate__ method of exceptions...
            Assert(not hasattr(t_except, '__getstate__'))

    if not is_silverlight:
        #special cases
        encode_except = exceptions.UnicodeEncodeError("1", u"2", 3, 4, "5")
        AreEqual(encode_except.encoding, "1")
        AreEqual(encode_except.object, u"2")
        AreEqual(encode_except.start, 3)
        AreEqual(encode_except.end, 4)
        AreEqual(encode_except.reason, "5")
        AreEqual(encode_except.message, "")

        #CodePlex Work Item 356
        #AssertError(TypeError, exceptions.UnicodeDecodeError, "1", u"2", 3, 4, "e")
        exceptions.UnicodeDecodeError("1", "2", 3, 4, "e")

        decode_except = exceptions.UnicodeDecodeError("1", "2", 3, 4, "5")
        AreEqual(decode_except.encoding, "1")
        AreEqual(decode_except.object, "2")
        AreEqual(decode_except.start, 3)
        AreEqual(decode_except.end, 4)
        AreEqual(decode_except.reason, "5")
        AreEqual(decode_except.message, "")

        translate_except = exceptions.UnicodeTranslateError(u"1", 2, 3, "4")
        AreEqual(translate_except.object, u"1")
        AreEqual(translate_except.start, 2)
        AreEqual(translate_except.end, 3)
        AreEqual(translate_except.reason, "4")
        AreEqual(translate_except.message, "")
        AreEqual(translate_except.encoding, None)

def test_nested_exceptions():
    try:
        raise Exception()
    except Exception, e:
        # PushException
        try:
            raise TypeError
        except TypeError, te:
            # PushException
            ei = sys.exc_info()
            # PopException
        ei2 = sys.exc_info()
        AreEqual(ei, ei2)
    ei3 = sys.exc_info()
    AreEqual(ei, ei3)

def test_swallow_from_else():
    def f():
        try:
            pass
        except:
            pass
        else:
            raise AttributeError
        finally:
            return 4

    AreEqual(f(), 4)

def test_newstyle_raise():
    # raise a new style exception via raise type, value that returns an arbitrary object
    class MyException(Exception):
        def __new__(cls, *args): return 42

    try:
        raise MyException, 'abc'
        AssertUnreachable()
    except Exception, e:
        AreEqual(e, 42)

def test_enverror_init():
    x = EnvironmentError()
    AreEqual(x.message, '')
    AreEqual(x.errno, None)
    AreEqual(x.filename, None)
    AreEqual(x.strerror, None)
    AreEqual(x.args, ())

    x.__init__('abc')
    AreEqual(x.message, 'abc')
    AreEqual(x.args, ('abc', ))

    x.__init__('123', '456')
    AreEqual(x.message, 'abc')
    AreEqual(x.errno, '123')
    AreEqual(x.strerror, '456')
    AreEqual(x.args, ('123', '456'))

    x.__init__('def', 'qrt', 'foo')
    AreEqual(x.message, 'abc')
    AreEqual(x.errno, 'def')
    AreEqual(x.strerror, 'qrt')
    AreEqual(x.filename, 'foo')
    AreEqual(x.args, ('def', 'qrt')) # filename not included in args

    x.__init__()
    AreEqual(x.message, 'abc')
    AreEqual(x.errno, 'def')
    AreEqual(x.strerror, 'qrt')
    AreEqual(x.filename, 'foo')
    AreEqual(x.args, ())

    x.__init__('1', '2', '3', '4')
    AreEqual(x.message, 'abc')
    AreEqual(x.errno, 'def')
    AreEqual(x.strerror, 'qrt')
    AreEqual(x.filename, 'foo')
    AreEqual(x.args, ('1', '2', '3', '4'))

    x = EnvironmentError('a', 'b', 'c', 'd')
    AreEqual(x.message, '')
    AreEqual(x.errno, None)
    AreEqual(x.filename, None)
    AreEqual(x.strerror, None)
    AreEqual(x.args, ('a', 'b', 'c', 'd'))

def test_raise_None():
    lineno1, lineno2 = 0, 0
    try:
        raise None
    except:
        lineno1 = sys.exc_info()[2].tb_lineno

    try:
        # dummy line
        raise None
    except:
        lineno2 = sys.exc_info()[2].tb_lineno

    Assert(lineno1 != lineno2, "FAILED! Should not have reused exception")

def test_exception_setstate():
    x = BaseException()
    AreEqual(x.__dict__, {})
    x.__setstate__({'a' : 1, 'b' : 2})
    AreEqual(x.__dict__, {'a' : 1, 'b' : 2})
    x.__setstate__({'a' : 3, 'c' : 4})
    AreEqual(x.__dict__, {'a' : 3, 'b' : 2, 'c' : 4})

def test_deprecated_string_exception():
    w = warning_trapper()
    try:
        raise 'Error'
    except:
        pass
    m = w.finish()
    try:
        raise 'foo'
    except TypeError, e:
        print e.message

def test_nested_try():
    global l
    l = []
    def foo():
        try:
            try:
                l.append(1)
            except:
                pass
        except:
            l.append(2)
        else:
            l.append(3)

    foo()
    AreEqual(l, [1, 3])
    l = []

    def bar():
        try:
            l.append(1)
        except:
            l.append(2)
        else:
            l.append(3)

    bar()
    AreEqual(l, [1, 3])

def test_module_exceptions():
    """verify exceptions in modules are like user defined exception objects, not built-in types."""

    # these modules have normal types...
    normal_types = ['sys', 'clr', 'exceptions', '__builtin__', '_winreg', 'mmap', 'nt']
    builtins = [x for x in sys.builtin_module_names if x not in normal_types ]
    for module in builtins:
        mod = __import__(module)

        for attrName in dir(mod):
            val = getattr(mod, attrName)
            if isinstance(val, type) and issubclass(val, Exception):
                if "BlockingIOError" not in repr(val):
                    Assert(repr(val).startswith("<class "))
                    val.x = 2
                    AreEqual(val.x, 2)
                elif is_cpython:
                    Assert(repr(val).startswith("<type "))
                else: #http://ironpython.codeplex.com/workitem/28383
                    Assert(repr(val).startswith("<class "))

def test_raise_inside_str():
    #raising an error inside the __str__ used to cause an unhandled exception.
    class error(Exception):
	    def __str__(self):
		    raise TypeError, "inside __str__"

    def f():
	    raise error
    AssertError(error, f)

def test_exception_doc():
    # should be accessible, CPython and IronPython have different strings though.
    Exception().__doc__
    Exception("abc").__doc__

def test_repr_not_called():
    """__repr__ shouldn't be called when message is a tuple w/ multiple args"""
    class x(object):
        def __repr__(self):
            raise StopIteration('repr should not be called')

    try:
        sys.exit((x(), x()))
    except SystemExit:
        pass

def test_windows_error():
    # int is required for 2/3 params
    AssertError(TypeError, WindowsError, 'foo', 'bar')
    AssertError(TypeError, WindowsError, 'foo', 'bar', 'baz')

    err = WindowsError('foo', 'bar', 'baz', 'quox')
    AreEqual(err.errno, None)
    AreEqual(err.winerror, None)
    AreEqual(err.filename, None)
    AreEqual(err.strerror, None)
    AreEqual(err.args, ('foo', 'bar', 'baz', 'quox'))

    err = WindowsError(42, 'bar', 'baz')
    AreEqual(err.filename, 'baz')
    AreEqual(err.winerror, 42)
    AreEqual(err.strerror, 'bar')
    AreEqual(err.args, (42, 'bar'))

    # winerror code is passed through unmodified
    for i in xrange(256):
        x = WindowsError(i, 'foo')
        AreEqual(x.winerror, i)

    # winerror code is mapped to Python error code
    AreEqual(WindowsError(10, 'foo').errno, 7)

def test_derived_keyword_args():
    class ED(Exception):
        def __init__(self, args=''):
            pass

    AreEqual(type(ED(args='')), ED)

run_test(__name__)


text:
static const int ddLogLevel = LOG_LEVEL_VERBOSE;

@implementation WindowManager

static NSMutableArray *chatControllers;
static NSMutableArray *mucControllers;

+ (void)initialize
{
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{

		chatControllers = [[NSMutableArray alloc] init];
		mucControllers  = [[NSMutableArray alloc] init];
	});
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark ChatController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

+ (ChatController *)chatControllerForJID:(XMPPJID *)jid matchResource:(BOOL)matchResource
{
	// Loop through all the open chat windows, and see if any of them are the one we want...

	XMPPJIDCompareOptions options = matchResource ? XMPPJIDCompareFull : XMPPJIDCompareBare;

	for (ChatController *chatController in chatControllers)
	{
		XMPPJID *currentJID = [chatController jid];

		if ([currentJID isEqualToJID:jid options:options])
		{
			return chatController;
		}
	}

	return nil;
}

+ (void)openChatWindowWithStream:(XMPPStream *)xmppStream forUser:(id <XMPPUser>)user
{
	ChatController *chatController = [self chatControllerForJID:[user jid] matchResource:NO];

	if (chatController)
	{
		[[chatController window] makeKeyAndOrderFront:self];
	}
	else
	{
		// Create chat controller
		XMPPJID *jid;

		id <XMPPResource> primaryResource = [user primaryResource];
		if (primaryResource)
			jid = [primaryResource jid];
		else
			jid = [user jid];

		chatController = [[ChatController alloc] initWithStream:xmppStream jid:jid];
		[chatController showWindow:self];

		[chatControllers addObject:chatController];
	}
}

+ (void)closeChatWindow:(ChatController *)chatController
{
	[chatControllers removeObject:chatController];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark MucController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

+ (MucController *)mucControllerForJID:(XMPPJID *)jid
{
	// Loop through all the open controllers, and see if any of them are the one we want...

	for (MucController *mucController in mucControllers)
	{
		XMPPJID *currentJID = [mucController jid];

		if ([currentJID isEqualToJID:jid])
		{
			return mucController;
		}
	}

	return nil;
}

+ (void)openMucWindowWithStream:(XMPPStream *)xmppStream forRoom:(XMPPJID *)roomJid
{
	MucController *mucController = [self mucControllerForJID:roomJid];

	if (mucController)
	{
		[[mucController window] makeKeyAndOrderFront:self];
	}
	else
	{
		// Create muc controller
		mucController = [[MucController alloc] initWithStream:xmppStream roomJID:roomJid];
		[mucController showWindow:self];

		[mucControllers addObject:mucController];
	}
}

+ (void)closeMucWindow:(MucController *)mucController
{
	[mucControllers removeObject:mucController];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark HandleMessage
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

+ (void)handleMessage:(XMPPMessage *)message withStream:(XMPPStream *)xmppStream
{
	ChatController *chatController = [self chatControllerForJID:[message from] matchResource:YES];

	if (chatController == nil)
	{
		// Create new chat window
		XMPPJID *jid = [message from];

		chatController = [[ChatController alloc] initWithStream:xmppStream jid:jid message:message];
		[chatController showWindow:self];

		[chatControllers addObject:chatController];
	}
}

@end

redpajama_set_name: RedPajamaGithub


text:
require "kramdown"
set :markdown_engine, ::Tilt::KramdownTemplate
set :markdown_engine, :kramdown

# Per-page layout changes:
#
# With no layout
page '/*.xml', layout: false
page '/*.json', layout: false
page '/*.txt', layout: false

set :partials_dir, 'partials'
set :fonts_dir, 'fonts'
set :css_dir, 'stylesheets'

set :strip_index_file, false

set :build_dir, 'docs' # for github pages master (not for projects)

# With alternative layout
# page "/path/to/file.html", layout: :otherlayout

# Proxy pages (http://middlemanapp.com/basics/dynamic-pages/)
# proxy "/this-page-has-no-template.html", "/template-file.html", locals: {
#  which_fake_page: "Rendering a fake page with a local variable" }

###
# Helpers
###

# activate :asset_hash # github cache buster

activate :deploy do |deploy|
  deploy.deploy_method = :git
  # Optional Settings
  deploy.remote   = 'https://github.com/janzheng/janzheng.github.io.git' # remote name or git url, default: origin
  deploy.branch   = 'master' # default: gh-pages
  # deploy.strategy = :submodule      # commit strategy: can be :force_push or :submodule, default: :force_push
  # deploy.commit_message = 'custom-message'      # commit message (can be empty), default: Automated commit at `timestamp` by middleman-deploy `version`
end

activate :relative_assets

activate :aria_current

activate :blog do |blog|
  # This will add a prefix to all links, template references and source paths
  # blog.prefix = "blog"

  # blog.permalink = "{year}/{month}/{day}/{title}.html"
  # Matcher for blog source files
  # blog.sources = "posts/{year}-{month}-{day}-{title}.html"
  blog.sources = "posts/{title}, styleguide"
  # blog.taglink = "tags/{tag}.html"
  # blog.layout = "layout"
  # blog.summary_separator = /(READMORE)/
  # blog.summary_length = 250
  # blog.year_link = "{year}.html"
  # blog.month_link = "{year}/{month}.html"
  # blog.day_link = "{year}/{month}/{day}.html"
  # blog.default_extension = ".markdown"

  blog.tag_template = "tag.html"
  blog.calendar_template = "calendar.html"

  # Enable pagination
  # blog.paginate = true
  # blog.per_page = 10
  # blog.page_link = "page/{num}"
end

# https://github.com/manastech/middleman-search
activate :search do |search|
  search.resources = ['styleguide/', 'index.html', 'landing.html']
  # search.index_path = 'search/lunr-index.json' # defaults to `search.json`
  # search.lunr_dirs = ['source/vendor/lunr-custom/'] # optional alternate paths where to look for lunr js files
  # search.language = 'es' # defaults to 'en'
  search.fields = {
    title:   {boost: 100, store: true, required: true},
    content: {boost: 50},
    # url:     {index: false, store: true},
    # author:  {boost: 30}
  }
end

page "/feed.xml", layout: false
# Reload the browser automatically whenever files change
# configure :development do
#   activate :livereload
# end

# Methods defined in the helpers block are available in templates
# helpers do
#   def some_helper
#     "Helping"
#   end
# end

# Build-specific configuration
configure :build do
  # Minify CSS on build
  # activate :minify_css

  # Minify Javascript on build
  # activate :minify_javascript
end


text:
from oslo_config import cfg

console_group = cfg.OptGroup('console',
    title='Console Options',
    help="""
Options under this group allow to tune the configuration of the console proxy
service.

Note: in configuration of every compute is a ``console_host`` option,
which allows to select the console proxy service to connect to.
""")

default_opts = [
    cfg.StrOpt('console_driver',
        default='nova.console.xvp.XVPConsoleProxy',
        deprecated_for_removal=True,
        deprecated_since='15.0.0',
        deprecated_reason="""
This option no longer does anything. Previously this option had only two valid,
in-tree values: nova.console.xvp.XVPConsoleProxy and
nova.console.fake.FakeConsoleProxy. The latter of these was only used in tests
and has since been replaced.
""",
        help="""
nova-console-proxy is used to set up multi-tenant VM console access.
This option allows pluggable driver program for the console session
and represents driver to use for the console proxy.

Possible values:

* A string representing fully classified class name of console driver.
"""),
    cfg.StrOpt('console_topic',
        default='console',
        deprecated_for_removal=True,
        deprecated_since='15.0.0',
        deprecated_reason="""
There is no need to let users choose the RPC topic for all services - there
is little gain from this. Furthermore, it makes it really easy to break Nova
by using this option.
""",
        help="""
Represents the message queue topic name used by nova-console
service when communicating via the AMQP server. The Nova API uses a message
queue to communicate with nova-console to retrieve a console URL for that
host.

Possible values:

* A string representing topic exchange name
""")
]

console_opts = [
    cfg.ListOpt('allowed_origins',
        default=[],
        deprecated_group='DEFAULT',
        deprecated_name='console_allowed_origins',
        help="""
Adds list of allowed origins to the console websocket proxy to allow
connections from other origin hostnames.
Websocket proxy matches the host header with the origin header to
prevent cross-site requests. This list specifies if any there are
values other than host are allowed in the origin header.

Possible values:

* A list where each element is an allowed origin hostnames, else an empty list
"""),
]

def register_opts(conf):
    conf.register_group(console_group)
    conf.register_opts(console_opts, group=console_group)
    conf.register_opts(default_opts)

def list_opts():
    return {
        console_group: console_opts,
        'DEFAULT': default_opts,
    }


text:
import {Component, OnInit} from 'angular2/core';
import {FORM_DIRECTIVES} from 'angular2/common';

@Component({
    selector: 'home',
    directives: [...FORM_DIRECTIVES],
    pipes: [],
    styles: [require('./home.scss')],
    template: require('./home.html')
})
export class Home implements OnInit {

    constructor() {
        // Do stuff
    }

    ngOnInit() {
        console.log('Hello Home');
    }

}


text:
local input

repeat
  io.write("wax> ")
  input = io.read()
  local success, e = wax.eval(input)

  if not success then print("Error: " .. e) end
until not input


text:
Contributing to elasticsearch
=============================

Elasticsearch is an open source project and we love to receive contributions from our community — you! There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, submitting bug reports and feature requests or writing code which can be incorporated into Elasticsearch itself.

Bug reports
-----------

If you think you have found a bug in Elasticsearch, first make sure that you are testing against the [latest version of Elasticsearch](https://www.elastic.co/downloads/elasticsearch) - your issue may already have been fixed. If not, search our [issues list](https://github.com/elastic/elasticsearch/issues) on GitHub in case a similar issue has already been opened.

It is very helpful if you can prepare a reproduction of the bug. In other words, provide a small test case which we can run to confirm your bug. It makes it easier to find the problem and to fix it. Test cases should be provided as `curl` commands which we can copy and paste into a terminal to run it locally, for example:

```sh
# delete the index
curl -XDELETE localhost:9200/test

# insert a document
curl -XPUT localhost:9200/test/test/1 -d '{
 "title": "test document"
}'

# this should return XXXX but instead returns YYY
curl ....
```

Provide as much information as you can. You may think that the problem lies with your query, when actually it depends on how your data is indexed. The easier it is for us to recreate your problem, the faster it is likely to be fixed.

Feature requests
----------------

If you find yourself wishing for a feature that doesn't exist in Elasticsearch, you are probably not alone. There are bound to be others out there with similar needs. Many of the features that Elasticsearch has today have been added because our users saw the need.
Open an issue on our [issues list](https://github.com/elastic/elasticsearch/issues) on GitHub which describes the feature you would like to see, why you need it, and how it should work.

Contributing code and documentation changes
-------------------------------------------

If you have a bugfix or new feature that you would like to contribute to Elasticsearch, please find or open an issue about it first. Talk about what you would like to do. It may be that somebody is already working on it, or that there are particular issues that you should know about before implementing the change.

We enjoy working with contributors to get their code accepted. There are many approaches to fixing a problem and it is important to find the best approach before writing too much code.

The process for contributing to any of the [Elastic repositories](https://github.com/elastic/) is similar. Details for individual projects can be found below.

### Fork and clone the repository

You will need to fork the main Elasticsearch code or documentation repository and clone it to your local machine. See
[github help page](https://help.github.com/articles/fork-a-repo) for help.

Further instructions for specific projects are given below.

### Submitting your changes

Once your changes and tests are ready to submit for review:

1. Test your changes

    Run the test suite to make sure that nothing is broken. See the
[TESTING](TESTING.asciidoc) file for help running tests.

2. Sign the Contributor License Agreement

    Please make sure you have signed our [Contributor License Agreement](https://www.elastic.co/contributor-agreement/). We are not asking you to assign copyright to us, but to give us the right to distribute your code without restriction. We ask this of all contributors in order to assure our users of the origin and continuing existence of the code. You only need to sign the CLA once.

3. Rebase your changes

    Update your local repository with the most recent code from the main Elasticsearch repository, and rebase your branch on top of the latest master branch. We prefer your initial changes to be squashed into a single commit. Later, if we ask you to make changes, add them as separate commits.  This makes them easier to review.  As a final step before merging we will either ask you to squash all commits yourself or we'll do it for you.

4. Submit a pull request

    Push your local changes to your forked copy of the repository and [submit a pull request](https://help.github.com/articles/using-pull-requests). In the pull request, choose a title which sums up the changes that you have made, and in the body provide more details about what your changes do. Also mention the number of the issue where discussion has taken place, eg "Closes #123".

Then sit back and wait. There will probably be discussion about the pull request and, if any changes are needed, we would love to work with you to get your pull request merged into Elasticsearch.

Please adhere to the general guideline that you should never force push
to a publicly shared branch. Once you have opened your pull request, you
should consider your branch publicly shared. Instead of force pushing
you can just add incremental commits; this is generally easier on your
reviewers. If you need to pick up changes from master, you can merge
master into your branch. A reviewer might ask you to rebase a
long-running pull request in which case force pushing is okay for that
request. Note that squashing at the end of the review process should
also not be done, that can be done when the pull request is [integrated
via GitHub](https://github.com/blog/2141-squash-your-commits).

Contributing to the Elasticsearch codebase
------------------------------------------

**Repository:** [https://github.com/elastic/elasticsearch](https://github.com/elastic/elasticsearch)

Make sure you have [Gradle](http://gradle.org) installed, as
Elasticsearch uses it as its build system.

Eclipse users can automatically configure their IDE: `gradle eclipse`
then `File: Import: Existing Projects into Workspace`. Select the
option `Search for nested projects`. Additionally you will want to
ensure that Eclipse is using 2048m of heap by modifying `eclipse.ini`
accordingly to avoid GC overhead errors.

IntelliJ users can automatically configure their IDE: `gradle idea`
then `File->New Project From Existing Sources`. Point to the root of
the source directory, select
`Import project from external model->Gradle`, enable
`Use auto-import`.

The Elasticsearch codebase makes heavy use of Java `assert`s and the
test runner requires that assertions be enabled within the JVM. This
can be accomplished by passing the flag `-ea` to the JVM on startup.

For IntelliJ, go to
`Run->Edit Configurations...->Defaults->JUnit->VM options` and input
`-ea`.

For Eclipse, go to `Preferences->Java->Installed JREs` and add `-ea` to
`VM Arguments`.

Please follow these formatting guidelines:

* Java indent is 4 spaces
* Line width is 140 characters
* The rest is left to Java coding standards
* Disable "auto-format on save" to prevent unnecessary format changes. This makes reviews much harder as it generates unnecessary formatting changes. If your IDE supports formatting only modified chunks that is fine to do.
* Wildcard imports (`import foo.bar.baz.*`) are forbidden and will cause the build to fail. Please attempt to tame your IDE so it doesn't make them and please send a PR against this document with instructions for your IDE if it doesn't contain them.
 * Eclipse: `Preferences->Java->Code Style->Organize Imports`. There are two boxes labeled "`Number of (static )? imports needed for .*`". Set their values to 99999 or some other absurdly high value.
 * IntelliJ: `Preferences->Editor->Code Style->Java->Imports`. There are two configuration options: `Class count to use import with '*'` and `Names count to use static import with '*'`. Set their values to 99999 or some other absurdly high value.
* Don't worry too much about import order. Try not to change it but don't worry about fighting your IDE to stop it from doing so.

To create a distribution from the source, simply run:

```sh
cd elasticsearch/
gradle assemble
```

You will find the newly built packages under: `./distribution/(deb|rpm|tar|zip)/build/distributions/`.

Before submitting your changes, run the test suite to make sure that nothing is broken, with:

```sh
gradle check
```


text:
const colorMap = require('@spinnaker/styleguide/src/colorMap');
const { nodeResolve } = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
const json = require('@rollup/plugin-json');
const postCss = require('rollup-plugin-postcss');
const replace = require('@rollup/plugin-replace');
const url = require('@rollup/plugin-url');
const svgr = require('@svgr/rollup');
const autoPrefixer = require('autoprefixer');
const postCssColorFix = require('postcss-colorfix');
const postCssUrl = require('postcss-url');
const esbuild = require('rollup-plugin-esbuild').default;
const { terser } = require('rollup-plugin-terser');
const { visualizer } = require('rollup-plugin-visualizer');

const ROLLUP_STATS = !!process.env.ROLLUP_STATS;
const ROLLUP_WATCH = !!process.env.ROLLUP_WATCH;
const NODE_ENV = process.env.NODE_ENV || 'development';
const ENV_MINIFY = process.env.ROLLUP_MINIFY;
const ROLLUP_MINIFY = ENV_MINIFY === 'true' || (NODE_ENV === 'production' && ENV_MINIFY !== 'false');

// eslint-disable-next-line no-console
console.log({ ROLLUP_STATS, ROLLUP_WATCH, ROLLUP_MINIFY, NODE_ENV });

const plugins = [
  nodeResolve(),
  commonjs(),
  json(),
  url({
    include: ['**/*.html', '**/*.svg', '**/*.png', '**/*.jp(e)?g', '**/*.gif', '**/*.webp'],
    fileName: '[name][hash][extname]',
    limit: 24000,
  }),
  // Replace literal string 'process.env.NODE_ENV' with the current NODE_ENV
  replace({
    preventAssignment: true,
    values: { 'process.env.NODE_ENV': `"${NODE_ENV}"` },
  }),
  esbuild({
    sourcemap: true,
    target: 'es2018',
  }),
  svgr(),
  // import from .css, .less, and inject into the document <head></head>
  postCss({
    plugins: [
      autoPrefixer(),
      postCssColorFix({
        colors: colorMap,
      }),
      postCssUrl({
        url: 'inline',
      }),
    ],
  }),
];

if (ROLLUP_MINIFY) {
  plugins.push(
    terser({
      format: {
        comments: function (node, comment) {
          if (comment.type == 'comment2') {
            // Preserve multiline comments containing any of these strings
            return /@preserve|@license|@cc_on|webpackChunkName|webpackIgnore/i.test(comment.value);
          }
        },
      },
    }),
  );
}

if (ROLLUP_STATS) {
  plugins.push(visualizer({ sourcemap: true }));
}

module.exports = {
  plugins,
};


text:
<?php

namespace IdeasBucket\Common\Swiftmailer\Transport;

use IdeasBucket\Common\Swiftmailer\Message\TrackedMessage;

class MailgunTest extends \PHPUnit_Framework_TestCase
{
    public function testSend()
    {
        $message = new TrackedMessage('Foo subject', 'Bar body');
        $message->setCampaignId('test');
        $message->setDescription('test');
        $message->setSender('myself@example.com');
        $message->setTo('me@example.com');
        $message->setCc('me@example.com');

        $message->setBcc('me@example.com');

        $client = $this->getMockBuilder('GuzzleHttp\ClientInterface')
                       ->setMethods(['send', 'sendAsync', 'request', 'requestAsync', 'getConfig', 'post'])
                       ->disableOriginalConstructor()
                       ->getMock();

        $transport = new Mailgun($client, 'test', 'test');

        $client->expects($this->once())
               ->method('post')
               ->with('https://api.mailgun.net/v3/test/messages.mime', $this->arrayHasKey('auth'));

        $transport->send($message);
    }

    public function testGetterSetter()
    {
        $message = new TrackedMessage('Foo subject', 'Bar body');
        $message->setSender('myself@example.com');
        $message->setTo('me@example.com');

        $client = $this->getMockBuilder('GuzzleHttp\ClientInterface')
                       ->setMethods(['send', 'sendAsync', 'request', 'requestAsync', 'getConfig', 'post'])
                       ->disableOriginalConstructor()
                       ->getMock();

        $transport = new Mailgun($client, 'test', 'test');
        $transport->setKey('another');
        $this->assertEquals('another', $transport->getKey());
    }
}


text:
class Swingfish < Cask
  url 'http://cloakedcode.com/apps/swingfish/swingfish_latest.zip'
  appcast 'http://cloakedcode.com/apps/swingfish/profileInfo.php'
  homepage 'http://cloakedcode.com/swingfish.html'
  version 'latest'
  sha256 :no_check
  link 'SwingFish.app'
end


text:
import {combineReducers} from 'redux'
import {routerReducer} from 'react-router-redux'
import loginReducer from './login'
import registerReducer from './register'
import resetPasswordRequestReducer from './resetPasswordRequest'
import resetPasswordReducer from './resetPassword'
import profileReducer from './profile'
import buttonsReducer from './buttons'
import callsReducer from './calls'

export default combineReducers({
	route: routerReducer,
	login: loginReducer,
	register: registerReducer,
	resetPasswordRequest: resetPasswordRequestReducer,
	resetPassword: resetPasswordReducer,
	profile: profileReducer,
	buttons: buttonsReducer,
	calls: callsReducer
});


text:
import DEFAULT_EXPORT from './lib/dev-server';
export default DEFAULT_EXPORT;


text:
function showStarContent() {
    //send starBoard to front
    $("#scoreName").css("z-index", "-1");
    $("#starBoard").css("z-index", "1");
    getScoreList();
}

function prompNameScore(){
    //send starBoard to front
    $("#scoreName").css("z-index", "1");
}

$("#back").click(function(){
  //send starBoard to front
    $("#starBoard").css("z-index", "-1");
});

$("#ok").click(function(){
    var playerName = $("#playerName").prop("value");
    if(playerName != ''){
        registerScore(currentScore, playerName);
        //send starBoard to front
        showStarContent();
    }
});

var soportaLS = false;

//Check if Browser supports LocalStorage
    function checkLSSupport(){
		try {
			soportaLS = 'localStorage' in window && window['localStorage'] !== null;
		} catch (e) {
			soportaLS =  false;
		}
	}

	function checkAndMockScore(){
		//Check if there are scores registered, if nothing is found, mock it!
		var anyscore = JSON.parse(localStorage.getItem("score-n1"));
		if (anyscore == null)
		{
			// mock the full list
			for(var i=1;i<6;i++){
				var mockedScore = {"name": "Empty", "amount": 0};
				localStorage.setItem("score-n" + i, JSON.stringify(mockedScore));
			}

		}
	}

	function getScoreList(){
		checkAndMockScore();
		var scoreList = "";

		for(var i=1;i<=5;i++){
				var theScore = JSON.parse(localStorage.getItem("score-n" + i))
				scoreList = scoreList + "
" + theScore.name + " - " + theScore.amount + "
";
		}
		scoreList = "
" + scoreList + "
";

		$('#scoredboard').empty().append(scoreList);

	}

	function gameOverCheckScore(currentScore){

        checkLSSupport()

		if (soportaLS){

            checkAndMockScore();

            var lowestHighScore = JSON.parse(localStorage.getItem("score-n5"));

            //check if new high score, comparing lowest in the board

            if (currentScore > lowestHighScore.amount){

                //Congrats, new highscore
                prompNameScore();

            }
        }
    }

    function registerScore(currentScore, name){
        //but first we need to check the position in the score board
        var newScorePos = checkScorePosition(currentScore);
        addHighScore(currentScore, newScorePos, name);
        //showStarContent();
    }

	function checkScorePosition(scoreAmount){
		for(var i=4;i>0;i--){
			var storedScore = JSON.parse(localStorage.getItem("score-n"+i));
			if (storedScore.amount > scoreAmount){
				return i+1;
			}if (i==1){
				return i;
			}
		}
	}

	function addHighScore(score, position, name){
		for (var i=5;i>position;i--){
			var storedScore = localStorage.getItem("score-n"+(i-1));
			localStorage.setItem("score-n"+i, storedScore);
		}
		//arreglar esto
		var newHighScore = {"name": name, "amount": score};
		localStorage.setItem("score-n" + position, JSON.stringify(newHighScore));
   }


text:
matlab_funcs_src_folder=$'../../../utilities/'

matlab_funcs=$'diffnc\nplot_sphere\ncomputeNMSE\ngenerateLinespecCodes'

for matlab_func in $matlab_funcs
do
	ln -f -s "$matlab_funcs_src_folder$matlab_func.m" "$matlab_func.m"
done


text:
namespace Nene::Windows::Direct3D11
{
	VertexShader::VertexShader(const Microsoft::WRL::ComPtr<ID3D11Device>& device, ByteArrayView compiledBinary)
		: shader_()
		, layout_()
	{
		assert(device);

		// Create shader object.
		throwIfFailed(
			device->CreateVertexShader(
				compiledBinary.data(),
				compiledBinary.size(),
				nullptr,
				shader_.GetAddressOf()),
			u8"Failed to create Direct3D11 vertex shader.");

		// Create shader reflection.
		Microsoft::WRL::ComPtr<ID3D11ShaderReflection> reflection;

		throwIfFailed(
			::D3DReflect(
				compiledBinary.data(),
				compiledBinary.size(),
				IID_ID3D11ShaderReflection,
				reinterpret_cast<void**>(reflection.GetAddressOf())),
			u8"Failed to create Direct3D11 shader reflection");

		// Get shader reflection.
		D3D11_SHADER_DESC shaderDesc;

		throwIfFailed(
			reflection->GetDesc(&shaderDesc),
			u8"Failed to get Direct3D11 shader reflection description");

		// Get input layout elements.
		std::vector<D3D11_INPUT_ELEMENT_DESC> inputElements(shaderDesc.InputParameters);

		for (UINT i = 0; i < shaderDesc.InputParameters; i++)
		{
			// Get input parameter description.
			D3D11_SIGNATURE_PARAMETER_DESC paramDesc;

			throwIfFailed(
				reflection->GetInputParameterDesc(i, &paramDesc),
				u8"Failed to get Direct3D11 shader input parameter description.");

			// Get DXGI format.
			DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;

			if (paramDesc.Mask <= 0b0001)
			{
				// 4byte.
				switch (paramDesc.ComponentType)
				{
					case D3D_REGISTER_COMPONENT_UINT32:
						format = DXGI_FORMAT_R32_UINT;
						break;

					case D3D_REGISTER_COMPONENT_SINT32:
						format = DXGI_FORMAT_R32_SINT;
						break;

					case D3D_REGISTER_COMPONENT_FLOAT32:
						format = DXGI_FORMAT_R32_FLOAT;
						break;
				}
			}
			else if (paramDesc.Mask <= 0b0011)
			{
				// 8byte.
				switch (paramDesc.ComponentType)
				{
					case D3D_REGISTER_COMPONENT_UINT32:
						format = DXGI_FORMAT_R32G32_UINT;
						break;

					case D3D_REGISTER_COMPONENT_SINT32:
						format = DXGI_FORMAT_R32G32_SINT;
						break;

					case D3D_REGISTER_COMPONENT_FLOAT32:
						format = DXGI_FORMAT_R32G32_FLOAT;
						break;
				}
			}
			else if (paramDesc.Mask <= 0b0111)
			{
				// 12byte.
				switch (paramDesc.ComponentType)
				{
					case D3D_REGISTER_COMPONENT_UINT32:
						format = DXGI_FORMAT_R32G32B32_UINT;
						break;

					case D3D_REGISTER_COMPONENT_SINT32:
						format = DXGI_FORMAT_R32G32B32_SINT;
						break;

					case D3D_REGISTER_COMPONENT_FLOAT32:
						format = DXGI_FORMAT_R32G32B32_FLOAT;
						break;
				}
			}
			else if (paramDesc.Mask <= 0b1111)
			{
				// 12byte.
				switch (paramDesc.ComponentType)
				{
					case D3D_REGISTER_COMPONENT_UINT32:
						format = DXGI_FORMAT_R32G32B32A32_UINT;
						break;

					case D3D_REGISTER_COMPONENT_SINT32:
						format = DXGI_FORMAT_R32G32B32A32_SINT;
						break;

					case D3D_REGISTER_COMPONENT_FLOAT32:
						format = DXGI_FORMAT_R32G32B32A32_FLOAT;
						break;
				}
			}

			// Construct input element description.
			inputElements[i].SemanticName         = paramDesc.SemanticName;
			inputElements[i].SemanticIndex        = paramDesc.SemanticIndex;
			inputElements[i].Format               = format;
			inputElements[i].InputSlot            = 0;
			inputElements[i].AlignedByteOffset    = D3D11_APPEND_ALIGNED_ELEMENT;
			inputElements[i].InputSlotClass       = D3D11_INPUT_PER_VERTEX_DATA;
			inputElements[i].InstanceDataStepRate = 0;
		}

		// Create input layout.
		throwIfFailed(
			device->CreateInputLayout(
				inputElements.data(),
				shaderDesc.InputParameters,
				compiledBinary.data(),
				compiledBinary.size(),
				layout_.GetAddressOf()),
			u8"Failed to create Direct3D11 shader input layout.");
	}
}

#endif


text:
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.1.1/material.indigo-pink.min.css">

Stale While Revalidate

This strategy transforms the headers of the following images so
          that they get a <tt>cache-control</tt> header of <tt>max-age=10,
          stale-while-revalidate=50</tt>.

This has the behavior:

image was retrieved less than 10 seconds ago -
              cached image is returned

image was retrieved between 10 and 60 seconds
              ago - cached image is returned immediately, but service
              worker retrieves a fresh copy of the image in the background and
              uses it to refresh the cache

image was retrieved more than 60 seconds ago, or not
              in cache - image is retrieved from network


text:
@implementation LYSPerson

@end


text:
/* global assert:true */
export default function (options) {
  describe('Adapter#beforeUpdate', function () {
    it('should exist', function () {
      assert.equal(typeof this.$$adapter.beforeUpdate, 'function', 'adapter should have a "beforeUpdate" method')
    })
    it('should call beforeUpdate', async function () {
      const adapter = this.$$adapter
      const User = this.$$User
      const props = { name: 'John' }

      sinon.stub(adapter, 'beforeUpdate').callsFake(function (mapper, id, props, opts) {
        assert.isDefined(opts, 'beforeUpdate should have received options')
        assert.equal(opts.op, 'beforeUpdate', 'opts.op')
      })

      assert.debug('create', User.name, props)
      const user = await adapter.create(User, props)
      const userId = user[User.idAttribute]
      assert.debug('created', User.name, user)

      assert.equal(user.name, props.name, `name of user should be "${props.name}"`)
      assert.isDefined(user[User.idAttribute], 'new user should have an id')

      assert.debug('update', User.name, userId, { name: 'Johnny' })
      let updatedUser = await adapter.update(User, userId, { name: 'Johnny' })
      assert.debug('updated', User.name, updatedUser)
      assert.equal(updatedUser.name, 'Johnny')
      assert.equal(updatedUser[User.idAttribute], userId)

      assert.isTrue(adapter.beforeUpdate.calledOnce, 'beforeUpdate should have been called once')

      const args = adapter.beforeUpdate.firstCall.args
      assert.equal(args.length, 4, 'beforeUpdate should have received 4 arguments')
      assert.isTrue(args[0] === User, 'beforeUpdate should have received User mapper')
      assert.isTrue(args[1] === userId, 'beforeUpdate should have received user id')
      assert.objectsEqual(args[2], { name: 'Johnny' }, 'beforeUpdate should have received update props')
      assert.isObject(args[3], 'beforeUpdate should have received options')
      adapter.beforeUpdate.restore()
    })
    it('should allow re-assignment', async function () {
      const adapter = this.$$adapter
      const User = this.$$User
      const props = { name: 'John' }

      sinon.stub(adapter, 'beforeUpdate').callsFake(function (mapper, id, props, opts) {
        assert.isDefined(opts, 'beforeUpdate should have received options')
        assert.equal(opts.op, 'beforeUpdate', 'opts.op')
        return { name: 'Sally' }
      })

      assert.debug('create', User.name, props)
      const user = await adapter.create(User, props)
      const userId = user[User.idAttribute]
      assert.debug('created', User.name, user)

      assert.equal(user.name, props.name, `name of user should be "${props.name}"`)
      assert.isDefined(user[User.idAttribute], 'new user should have an id')

      assert.debug('update', User.name, userId, { name: 'Johnny' })
      let updatedUser = await adapter.update(User, userId, { name: 'Johnny' })
      assert.debug('updated', User.name, updatedUser)
      assert.equal(updatedUser.name, 'Sally')
      assert.equal(updatedUser[User.idAttribute], userId)

      assert.isTrue(adapter.beforeUpdate.calledOnce, 'beforeUpdate should have been called once')

      const args = adapter.beforeUpdate.firstCall.args
      assert.equal(args.length, 4, 'beforeUpdate should have received 4 arguments')
      assert.isTrue(args[0] === User, 'beforeUpdate should have received User mapper')
      assert.isTrue(args[1] === userId, 'beforeUpdate should have received user id')
      assert.objectsEqual(args[2], { name: 'Johnny' }, 'beforeUpdate should have received update props')
      assert.isObject(args[3], 'beforeUpdate should have received options')
      adapter.beforeUpdate.restore()
    })
    it('should allow returning a promise', async function () {
      const adapter = this.$$adapter
      const User = this.$$User
      const props = { name: 'John' }

      sinon.stub(adapter, 'beforeUpdate').callsFake(function (mapper, id, props, opts) {
        assert.isDefined(opts, 'beforeUpdate should have received options')
        assert.equal(opts.op, 'beforeUpdate', 'opts.op')
        return Promise.resolve()
      })

      assert.debug('create', User.name, props)
      const user = await adapter.create(User, props)
      const userId = user[User.idAttribute]
      assert.debug('created', User.name, user)

      assert.equal(user.name, props.name, `name of user should be "${props.name}"`)
      assert.isDefined(user[User.idAttribute], 'new user should have an id')

      assert.debug('update', User.name, userId, { name: 'Johnny' })
      let updatedUser = await adapter.update(User, userId, { name: 'Johnny' })
      assert.debug('updated', User.name, updatedUser)
      assert.equal(updatedUser.name, 'Johnny')
      assert.equal(updatedUser[User.idAttribute], userId)

      assert.isTrue(adapter.beforeUpdate.calledOnce, 'beforeUpdate should have been called once')

      const args = adapter.beforeUpdate.firstCall.args
      assert.equal(args.length, 4, 'beforeUpdate should have received 4 arguments')
      assert.isTrue(args[0] === User, 'beforeUpdate should have received User mapper')
      assert.isTrue(args[1] === userId, 'beforeUpdate should have received user id')
      assert.objectsEqual(args[2], { name: 'Johnny' }, 'beforeUpdate should have received update props')
      assert.isObject(args[3], 'beforeUpdate should have received options')
      adapter.beforeUpdate.restore()
    })
    it('should allow returning a promise and re-assignment', async function () {
      const adapter = this.$$adapter
      const User = this.$$User
      const props = { name: 'John' }

      sinon.stub(adapter, 'beforeUpdate').callsFake(function (mapper, id, props, opts) {
        assert.isDefined(opts, 'beforeUpdate should have received options')
        assert.equal(opts.op, 'beforeUpdate', 'opts.op')
        return Promise.resolve({ name: 'Sally' })
      })

      assert.debug('create', User.name, props)
      const user = await adapter.create(User, props)
      const userId = user[User.idAttribute]
      assert.debug('created', User.name, user)

      assert.equal(user.name, props.name, `name of user should be "${props.name}"`)
      assert.isDefined(user[User.idAttribute], 'new user should have an id')

      assert.debug('update', User.name, userId, { name: 'Johnny' })
      let updatedUser = await adapter.update(User, userId, { name: 'Johnny' })
      assert.debug('updated', User.name, updatedUser)
      assert.equal(updatedUser.name, 'Sally')
      assert.equal(updatedUser[User.idAttribute], userId)

      assert.isTrue(adapter.beforeUpdate.calledOnce, 'beforeUpdate should have been called once')

      const args = adapter.beforeUpdate.firstCall.args
      assert.equal(args.length, 4, 'beforeUpdate should have received 4 arguments')
      assert.isTrue(args[0] === User, 'beforeUpdate should have received User mapper')
      assert.isTrue(args[1] === userId, 'beforeUpdate should have received user id')
      assert.objectsEqual(args[2], { name: 'Johnny' }, 'beforeUpdate should have received update props')
      assert.isObject(args[3], 'beforeUpdate should have received options')
      adapter.beforeUpdate.restore()
    })
  })
}


text:
package org.softeg.slartus.forpdaapi.users;

import android.text.Html;
import android.text.TextUtils;

import org.softeg.slartus.forpdaapi.Comment;
import org.softeg.slartus.forpdaapi.Comments;
import org.softeg.slartus.forpdaapi.IHttpClient;
import org.softeg.slartus.forpdaapi.OldUser;
import org.softeg.slartus.forpdaapi.devdb.DevModel;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: slinkin
 * Date: 25.09.12
 * Time: 8:45
 */
public class UserProfile {
    public String info;
    public String sign;
    public String avatar;
    public String Group;
    public String personalPhoto;
    public String reputation;
    public String rating;
    public Users UserViews = new Users();
    public Comments UserComments = new Comments();
    public Users Friends = new Users();
    //О Себе
    public String about;

    public String getAbout() {
        if (TextUtils.isEmpty(about))
            return login + " не указал(а) ничего о себе.";
        return about;
    }

    public String site;

    // личная информация
    public String login;
    public String status;
    public String age;
    public String gender;
    public String location;
    public String born;
    // интересы
    public String interests;
    //Другая информация
    public String devices;
    public String city;
    public DevModel device;
    // Статистика
    public String registration;
    public String profileViewsCount;
    public String lastActivity;
    public String timeZone;
    public String messagesCount;
    // Контактная информация
    public String aim;
    public String yahoo;
    public String icq;
    public String msn;

    public String[] getMain() {
        return new String[]{Group, sign == null ? "" : sign.toString()};
    }

    public String getValue(int groupPosition, int childPosition) {
        String[] group = null;
        switch (groupPosition) {
            case 0:
                group = getMain();
                break;
            case 1:
                group = getAboutGroup();
                break;
            case 2:
                group = getPrivateInfo();
                break;
            case 3:
                group = getInterests();
                break;
            case 4:
                group = getOtherInfo();
                break;
            case 5:
                group = getStatistic();
                break;
            case 6:
                group = getContactInfo();
                break;
        }
        for (String str : group) {
            if (str == null) continue;
            if (TextUtils.isEmpty(str.trim())) continue;
            if (childPosition == 0)
                return str;
            childPosition--;
        }
        return "";
    }

    public static String[] getGroupSimpleData(String[] fullGroupData) {
        ArrayList<String> res = new ArrayList<String>();
        for (String str : fullGroupData) {
            if (str == null) continue;
            if (TextUtils.isEmpty(str.trim())) continue;
            res.add(Html.fromHtml(str).toString().trim());
        }
        String[] resArray = new String[res.size()];
        return res.toArray(resArray);
    }

    public String[] getAboutGroup() {
        return new String[]{getAbout() + (site == null ? "" : ("\n" + site)), info};
    }

    public String[] getPrivateInfo() {
        return new String[]{status, age, gender, location, born};
    }

    public String[] getInterests() {
        return new String[]{interests};
    }

    public String[] getOtherInfo() {
        return new String[]{devices, city, device == null ? "" : ("Устройство: " + device.name)};
    }

    public String[] getStatistic() {
        return new String[]{registration, profileViewsCount, lastActivity == null ? "" : lastActivity.toString(), timeZone, messagesCount};
    }

    public String[] getContactInfo() {
        return new String[]{aim, yahoo, icq, msn};
    }

    public void parsePage(String page) {
//        Matcher tablesMatcher = Pattern.compile("([\\s\\S]*?)[\\s\\S]*?([\\s\\S]*?)[\\s\\S]*?([\\s\\S]*?)").matcher(page);
//        if (!tablesMatcher.find()) return;
        parseLeftTable(this, getValue("([\\s\\S]*?)", page));
        parseMainTable(this, getValue("([\\s\\S]*?)", page));
        parseRightTable(this, getValue("([\\s\\S]*?)", page));
    }

    private static void parseLeftTable(UserProfile res, String table) {
        Matcher groupMatcher = Pattern.compile("([\\s\\S]*?)").matcher(table);
        Matcher m;
        while (groupMatcher.find()) {
            String group = groupMatcher.group(1).trim();
            String groupBody = groupMatcher.group(2).trim();
            if (group.equals("Personal Photo")) {
                res.personalPhoto = getValue("src='(.*?)'", groupBody);
            } else if (group.equals("Quick contact")) {
                res.reputation = getValue("title='Просмотреть репутацию'>(.*?)", groupBody);
            } else if (group.equals("Rating")) {
                // пропускаем - не знаю, что это
            } else if (group.equals("Options")) {
                // пропускаем
            } else if (group.equals("Personal Statement")) {
                res.about = getValue("id='pp-personal_statement'>([\\s\\S]*?)</?div", groupBody).toString();
                res.site = getValue("href='(.*?)'", groupBody);
            } else if (group.equals("Personal Info")) {
                m = Pattern.compile("
(.*?)
").matcher(groupBody);
                if (m.find()) {
                    res.login = m.group(1);
                    if (m.find())
                        res.status = m.group(1);
                }
                res.age = getValue("(\\d+) лет", groupBody);
                if (res.age.equals(""))
                    res.age = "Возраст не указан";
                else
                    res.age += " лет";
                res.gender = getValue("(.*?)", groupBody);
                res.location = getValue("(.*?)", groupBody);
                res.born = getValue("Дата рождения: (.*?)", groupBody, "Дата рождения: ");
                if (res.born.equals(""))
                    res.born = "День рождения не указан";

            } else if (group.equals("Interests")) {
                res.interests = getValue("id='pp-personal_statement'>([\\s\\S]*?)
", groupBody).trim();
            } else if (group.equals("Custom Fields")) {
                res.devices = getValue("Описание ваших девайсов:(.*?)
", groupBody, "Описание ваших девайсов: ");
                res.city = getValue("Город где вы живёте:(.*?)
", groupBody, "Город где вы живёте: ");
                parseDevice(res, groupBody);
            } else if (group.equals("Statistics")) {
                m = Pattern.compile("
([\\s\\S]*?)
").matcher(groupBody);
                int ind = 0;
                while (m.find()) {
                    switch (ind) {
                        case 0:
                            res.registration = m.group(1);
                            break;
                        case 1:
                            res.profileViewsCount = m.group(1);
                            break;
                        case 2:
                            res.lastActivity = m.group(1);
                            break;
                        case 3:
                            res.timeZone = m.group(1);
                            break;
                        case 4:
                            res.messagesCount = m.group(1);
                            break;
                    }
                    ind++;
                }
            } else if (group.equals("Contact Information")) {
                m = Pattern.compile("(.*?)").matcher(groupBody);
                while (m.find()) {
                    String contactGroup = m.group(1);
                    if (contactGroup.equals("aim"))
                        res.aim = "Вконтакте: " + m.group(2);
                    else if (contactGroup.equals("yahoo"))
                        res.yahoo = "Twitter: " + m.group(2);
                    else if (contactGroup.equals("icq"))
                        res.icq = "ICQ: " + m.group(2);
                    else if (contactGroup.equals("msn"))
                        res.msn = "Jabber: " + m.group(2);
                }
            }
        }
    }

    private static void parseDevice(UserProfile profile, String text) {
        Matcher m = Pattern.compile("Устройство:[\\s\\n]*]*href=\"([^\"]*)\"[^>]*>(.*?)",
                Pattern.CASE_INSENSITIVE|Pattern.MULTILINE).matcher(text);
        if (m.find()) {
            profile.device = new DevModel(m.group(1), Html.fromHtml(m.group(2)).toString());
            return;
        }
        profile.device = null;
    }

    private static void parseMainTable(UserProfile res, String table) {
        res.avatar = getValue("'(http://s.4pda.to/*?forum/*?uploads/*?av-.*?)'", table);
        if (TextUtils.isEmpty(res.avatar))
            res.avatar = getValue("'(http://s.4pda.ru/*?forum/*?uploads/*?av-.*?)'", table);
        if (TextUtils.isEmpty(res.avatar))
            res.avatar = getValue("'(http://s.4pda.ru/*?forum/*?style_avatars/*?.*?)'", table);
        res.info = getValue("
([\\s\\S]*?)
", table);
        res.sign = getValue("
([\\s\\S]*?)
", table);
        if ("".equals(res.sign))
            res.sign = "Нет подписи";
        res.Group = getValue("(.*?)", table);
    }

    private static void parseRightTable(UserProfile res, String table) {
        Matcher groupMatcher = Pattern.compile("([\\s\\S]*?)").matcher(table);
        Matcher m;
        while (groupMatcher.find()) {
            String group = groupMatcher.group(1).trim();
            String groupBody = groupMatcher.group(2).trim();
            if (group.equals("Recent Visitors")) {
                m = Pattern.compile("href='http://4pda.ru/forum/index.php\\?.*?showuser=(\\d+)'.*?>(.*?)[\\s\\S]*?(.*?)\\s*(.*?)
").matcher(groupBody);
                while (m.find()) {
                    OldUser user = new OldUser();
                    user.setMid(m.group(1));
                    user.setNick(m.group(2));
                    user.State = m.group(3);
                    user.LastVisit = m.group(4);
                    res.UserViews.add(user);
                }

            } else if (group.equals("Comments")) {
                m = Pattern.compile("
[\\s\\S]*?(.*?)\\s*
\\s*([\\s\\S]*?)
[\\s\\S]*?([\\s\\S]*?)").matcher(groupBody);
                while (m.find()) {
                    Comment item = new Comment();
                    item.Id = m.group(1);
                    item.UserId = m.group(2);
                    item.User = m.group(3);
                    item.Text = Html.fromHtml(m.group(4).trim()).toString().trim();
                    item.DateTime = m.group(5);
                    res.UserComments.add(item);
                }

            } else if (group.equals("Friends")) {
                m = Pattern.compile("(.*?)[\\s\\S]*?(\\d+) сообщений\\s*
\\s*(.*?)([\\s\\S]*?)
").matcher(groupBody);
                while (m.find()) {
                    OldUser item = new OldUser();
                    item.setMid(m.group(1));
                    item.setNick(m.group(2));
                    item.MessagesCount = m.group(3);
                    item.State = m.group(4);
                    item.LastVisit = Html.fromHtml(m.group(5)).toString().trim();
                    res.Friends.add(item);
                }

            }
        }
    }

    private void parseFriendsPage(String page) {
        Matcher m = Pattern.compile("href='http://4pda.ru/forum/index.php\\?.*?showuser=(\\d+)'.*?>(.*?)\\s*
\\s*(.*?)\\s*
(\\d+) сообщений\\s*
Последнее действие: (.*?)\\s*
")
                .matcher(page);

        while (m.find()) {
            OldUser item = new OldUser();
            item.setMid(m.group(1));
            item.setNick(m.group(2));
            item.Group = m.group(3);
            item.MessagesCount = m.group(4);
            item.LastVisit = Html.fromHtml(m.group(5)).toString();
            Friends.add(item);

        }

        // на одну страницу помещается 10 друзей. поэтому, только если больше 9 есть смысл искать страницы
        if (Friends.size() > 9) {
            m = Pattern.compile("st=(\\d+)").matcher(page);
            int max = 0;
            while (m.find()) {

                max = Math.max(Integer.parseInt(m.group(1)), max);

            }
            Friends.setFullLength(max);
        }
    }

    private void parseCommentsPage(String page) {
        Matcher m = Pattern.compile("(.*?)\\s*
\\s*([\\s\\S]*?)\\s*
\\s*(.*?)")
                .matcher(page);

        while (m.find()) {
            Comment item = new Comment();
            item.UserId = m.group(1);
            item.User = m.group(2);
            item.Text = Html.fromHtml(m.group(3)).toString().trim();
            item.DateTime = m.group(4);

            UserComments.add(item);
        }

        // на одну страницу помещается 10 комментов. поэтому, только если больше 9 есть смысл искать страницы
        if (UserComments.size() > 9) {
            m = Pattern.compile("st=(\\d+)").matcher(page);
            int max = 0;
            while (m.find()) {

                max = Math.max(Integer.parseInt(m.group(1)), max);

            }
            UserComments.setFullLength(max);
        }

    }

    private static String getValue(String pattern, String input) {

        return getValue(pattern, input, "");
    }

    private static String getValue(String pattern, String input, String prefix) {
        Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(input);
        if (m.find()) {
            String res = m.group(1);
            if (res == null)
                res = "";
            return prefix + res.trim();
        }
        return "";
    }

    public static UserProfile loadProfile(IHttpClient client, UserProfile userProfile, String userId) throws Throwable {
        if (userProfile == null)
            userProfile = new UserProfile();
        if (TextUtils.isEmpty(userProfile.registration)) {
            String page = client.performGet("http://4pda.ru/forum/index.php?showuser=" + userId);
            userProfile.parsePage(page);
        }

        return userProfile;
    }

    public static UserProfile loadProfileFriends(IHttpClient client, UserProfile userProfile, String userId, String md5)
            throws Throwable {
        if (userProfile == null)
            userProfile = new UserProfile();
        if (userProfile.Friends.size() < 10)
            userProfile.Friends.clear();
        String page = client.performGet("http://4pda.ru/forum/index.php?s=&act=profile&CODE=personal_iframe_friends&member_id="
                + userId + "&md5check=" + md5 + "&st=" + userProfile.Friends.size());
        userProfile.parseFriendsPage(page);

        return userProfile;
    }

    public static UserProfile loadUserProfileComments(IHttpClient client, UserProfile userProfile, String userId, String md5)
            throws Throwable {
        if (userProfile == null)
            userProfile = new UserProfile();
        if (userProfile.UserComments.size() < 10)
            userProfile.UserComments.clear();
        String page = client.performGet("http://4pda.ru/forum/index.php?s=&act=profile&CODE=personal_iframe_comments&member_id="
                + userId + "&md5check=" + md5 + "&st=" + userProfile.UserComments.size());
        userProfile.parseCommentsPage(page);

        return userProfile;
    }

}


text:
.PHONY:

dockeret: .PHONY
	docker build \
		--build-arg http_proxy=${http_proxy} \
		--build-arg https_proxy=${https_proxy} \
		--build-arg no_proxy=${no_proxy} \
		-t sourcesimian/mailsort:1 -f ./dockeret/Dockerfile ./


text:
using DevExpress.Mvvm.UI.Native;
using DevExpress.Mvvm.UI.Interactivity;
using System.Windows;
using System.Windows.Controls;
using DevExpress.Mvvm.Native;
using System.Windows.Input;
using System.ComponentModel;
using DevExpress.Mvvm.UI;
using DevExpress.Mvvm;
using System.Collections.Generic;
using System.Linq;

namespace DevExpress.Mvvm.UI {
    [TargetTypeAttribute(typeof(UserControl))]
    [TargetTypeAttribute(typeof(Window))]
    public class CurrentWindowService : WindowAwareServiceBase, ICurrentWindowService {
        public ICommand ClosingCommand {
            get { return (ICommand)GetValue(ClosingCommandProperty); }
            set { SetValue(ClosingCommandProperty, value); }
        }

        public static readonly DependencyProperty ClosingCommandProperty =
            DependencyProperty.Register("ClosingCommand", typeof(ICommand), typeof(CurrentWindowService), new PropertyMetadata(null));

        protected Window GetActualWindow() {
            if (ActualWindow == null)
                UpdateActualWindow();
            return ActualWindow;
        }

        DXWindowState ICurrentWindowService.WindowState {
            get { return DXWindowStateConverter.ToDXWindowState(GetActualWindow()?.WindowState ?? WindowState.Normal); }
            set {
                var w = GetActualWindow();
                if(w != null)
                    w.WindowState = DXWindowStateConverter.ToWindowState(value);
            }
        }
        void ICurrentWindowService.Close() {
            GetActualWindow().Do(x => x.Close());
        }
        void ICurrentWindowService.Activate() {
            GetActualWindow().Do(x => x.Activate());
        }
        void ICurrentWindowService.Hide() {
            GetActualWindow().Do(x => x.Hide());
        }
        void ICurrentWindowService.Show() {
            GetActualWindow().Do(x => x.Show());
        }

        protected override void OnActualWindowChanged(Window oldWindow) {
            oldWindow.Do(x => x.Closing -= OnClosing);
            ActualWindow.Do(x => x.Closing += OnClosing);
        }
        void OnClosing(object sender, CancelEventArgs e) {
            ClosingCommand.Do(x => x.Execute(e));
        }
    }
}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.util.logging.ErrorManager
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_UTIL_LOGGING_ERRORMANAGER_HPP_DECL
#define J2CPP_JAVA_UTIL_LOGGING_ERRORMANAGER_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Exception; } } }

#include <java/lang/Exception.hpp>
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>

namespace j2cpp {

namespace java { namespace util { namespace logging {

	class ErrorManager;
	class ErrorManager
		: public object<ErrorManager>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_FIELD(0)
		J2CPP_DECLARE_FIELD(1)
		J2CPP_DECLARE_FIELD(2)
		J2CPP_DECLARE_FIELD(3)
		J2CPP_DECLARE_FIELD(4)
		J2CPP_DECLARE_FIELD(5)

		explicit ErrorManager(jobject jobj)
		: object<ErrorManager>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;

		ErrorManager();
		void error(local_ref< java::lang::String >  const&, local_ref< java::lang::Exception >  const&, jint);

		static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > GENERIC_FAILURE;
		static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > WRITE_FAILURE;
		static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > FLUSH_FAILURE;
		static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jint > CLOSE_FAILURE;
		static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), jint > OPEN_FAILURE;
		static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), jint > FORMAT_FAILURE;
	}; //class ErrorManager

} //namespace logging
} //namespace util
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_UTIL_LOGGING_ERRORMANAGER_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_UTIL_LOGGING_ERRORMANAGER_HPP_IMPL
#define J2CPP_JAVA_UTIL_LOGGING_ERRORMANAGER_HPP_IMPL

namespace j2cpp {

java::util::logging::ErrorManager::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

java::util::logging::ErrorManager::ErrorManager()
: object<java::util::logging::ErrorManager>(
	call_new_object<
		java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
		java::util::logging::ErrorManager::J2CPP_METHOD_NAME(0),
		java::util::logging::ErrorManager::J2CPP_METHOD_SIGNATURE(0)
	>()
)
{
}

void java::util::logging::ErrorManager::error(local_ref< java::lang::String > const &a0, local_ref< java::lang::Exception > const &a1, jint a2)
{
	return call_method<
		java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
		java::util::logging::ErrorManager::J2CPP_METHOD_NAME(1),
		java::util::logging::ErrorManager::J2CPP_METHOD_SIGNATURE(1),
		void
	>(get_jobject(), a0, a1, a2);
}

static_field<
	java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
	java::util::logging::ErrorManager::J2CPP_FIELD_NAME(0),
	java::util::logging::ErrorManager::J2CPP_FIELD_SIGNATURE(0),
	jint
> java::util::logging::ErrorManager::GENERIC_FAILURE;

static_field<
	java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
	java::util::logging::ErrorManager::J2CPP_FIELD_NAME(1),
	java::util::logging::ErrorManager::J2CPP_FIELD_SIGNATURE(1),
	jint
> java::util::logging::ErrorManager::WRITE_FAILURE;

static_field<
	java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
	java::util::logging::ErrorManager::J2CPP_FIELD_NAME(2),
	java::util::logging::ErrorManager::J2CPP_FIELD_SIGNATURE(2),
	jint
> java::util::logging::ErrorManager::FLUSH_FAILURE;

static_field<
	java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
	java::util::logging::ErrorManager::J2CPP_FIELD_NAME(3),
	java::util::logging::ErrorManager::J2CPP_FIELD_SIGNATURE(3),
	jint
> java::util::logging::ErrorManager::CLOSE_FAILURE;

static_field<
	java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
	java::util::logging::ErrorManager::J2CPP_FIELD_NAME(4),
	java::util::logging::ErrorManager::J2CPP_FIELD_SIGNATURE(4),
	jint
> java::util::logging::ErrorManager::OPEN_FAILURE;

static_field<
	java::util::logging::ErrorManager::J2CPP_CLASS_NAME,
	java::util::logging::ErrorManager::J2CPP_FIELD_NAME(5),
	java::util::logging::ErrorManager::J2CPP_FIELD_SIGNATURE(5),
	jint
> java::util::logging::ErrorManager::FORMAT_FAILURE;

J2CPP_DEFINE_CLASS(java::util::logging::ErrorManager,"java/util/logging/ErrorManager")
J2CPP_DEFINE_METHOD(java::util::logging::ErrorManager,0,"<init>","()V")
J2CPP_DEFINE_METHOD(java::util::logging::ErrorManager,1,"error","(Ljava/lang/String;Ljava/lang/Exception;I)V")
J2CPP_DEFINE_FIELD(java::util::logging::ErrorManager,0,"GENERIC_FAILURE","I")
J2CPP_DEFINE_FIELD(java::util::logging::ErrorManager,1,"WRITE_FAILURE","I")
J2CPP_DEFINE_FIELD(java::util::logging::ErrorManager,2,"FLUSH_FAILURE","I")
J2CPP_DEFINE_FIELD(java::util::logging::ErrorManager,3,"CLOSE_FAILURE","I")
J2CPP_DEFINE_FIELD(java::util::logging::ErrorManager,4,"OPEN_FAILURE","I")
J2CPP_DEFINE_FIELD(java::util::logging::ErrorManager,5,"FORMAT_FAILURE","I")

} //namespace j2cpp

#endif //J2CPP_JAVA_UTIL_LOGGING_ERRORMANAGER_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
package org.apache.hadoop.mapreduce.lib.fieldsel;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.MapReduceTestUtil;

import junit.framework.TestCase;
import java.text.NumberFormat;

public class TestMRFieldSelection extends TestCase {

private static NumberFormat idFormat = NumberFormat.getInstance();
  static {
    idFormat.setMinimumIntegerDigits(4);
    idFormat.setGroupingUsed(false);
  }

  public void testFieldSelection() throws Exception {
    launch();
  }
  private static Path testDir = new Path(
    System.getProperty("test.build.data", "/tmp"), "field");

  public static void launch() throws Exception {
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    int numOfInputLines = 10;

    Path outDir = new Path(testDir, "output_for_field_selection_test");
    Path inDir = new Path(testDir, "input_for_field_selection_test");

    StringBuffer inputData = new StringBuffer();
    StringBuffer expectedOutput = new StringBuffer();
    constructInputOutputData(inputData, expectedOutput, numOfInputLines);

    conf.set(FieldSelectionHelper.DATA_FIELD_SEPERATOR, "-");
    conf.set(FieldSelectionHelper.MAP_OUTPUT_KEY_VALUE_SPEC, "6,5,1-3:0-");
    conf.set(
      FieldSelectionHelper.REDUCE_OUTPUT_KEY_VALUE_SPEC, ":4,3,2,1,0,0-");
    Job job = MapReduceTestUtil.createJob(conf, inDir, outDir,
      1, 1, inputData.toString());
    job.setMapperClass(FieldSelectionMapper.class);
    job.setReducerClass(FieldSelectionReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);
    job.setNumReduceTasks(1);

    job.waitForCompletion(true);
    assertTrue("Job Failed!", job.isSuccessful());

    //
    // Finally, we compare the reconstructed answer key with the
    // original one.  Remember, we need to ignore zero-count items
    // in the original key.
    //
    String outdata = MapReduceTestUtil.readOutput(outDir, conf);
    assertEquals("Outputs doesnt match.",expectedOutput.toString(), outdata);
    fs.delete(outDir, true);
  }

  public static void constructInputOutputData(StringBuffer inputData,
      StringBuffer expectedOutput, int numOfInputLines) {
    for (int i = 0; i < numOfInputLines; i++) {
      inputData.append(idFormat.format(i));
      inputData.append("-").append(idFormat.format(i+1));
      inputData.append("-").append(idFormat.format(i+2));
      inputData.append("-").append(idFormat.format(i+3));
      inputData.append("-").append(idFormat.format(i+4));
      inputData.append("-").append(idFormat.format(i+5));
      inputData.append("-").append(idFormat.format(i+6));
      inputData.append("\n");

      expectedOutput.append(idFormat.format(i+3));
      expectedOutput.append("-" ).append (idFormat.format(i+2));
      expectedOutput.append("-" ).append (idFormat.format(i+1));
      expectedOutput.append("-" ).append (idFormat.format(i+5));
      expectedOutput.append("-" ).append (idFormat.format(i+6));

      expectedOutput.append("-" ).append (idFormat.format(i+6));
      expectedOutput.append("-" ).append (idFormat.format(i+5));
      expectedOutput.append("-" ).append (idFormat.format(i+1));
      expectedOutput.append("-" ).append (idFormat.format(i+2));
      expectedOutput.append("-" ).append (idFormat.format(i+3));
      expectedOutput.append("-" ).append (idFormat.format(i+0));
      expectedOutput.append("-" ).append (idFormat.format(i+1));
      expectedOutput.append("-" ).append (idFormat.format(i+2));
      expectedOutput.append("-" ).append (idFormat.format(i+3));
      expectedOutput.append("-" ).append (idFormat.format(i+4));
      expectedOutput.append("-" ).append (idFormat.format(i+5));
      expectedOutput.append("-" ).append (idFormat.format(i+6));
      expectedOutput.append("\n");
    }
    System.out.println("inputData:");
    System.out.println(inputData.toString());
    System.out.println("ExpectedData:");
    System.out.println(expectedOutput.toString());
  }

  /**
   * Launches all the tasks in order.
   */
  public static void main(String[] argv) throws Exception {
    launch();
  }
}


text:
//
// Created by foxfire on 7/12/17.
//

#ifndef FOX_GFX_TEXTURE_CONFIG_HPP
#define FOX_GFX_TEXTURE_CONFIG_HPP

#include <string>
#include <unordered_set>

namespace fox
{
namespace gfx
{

/**
 * @brief Information loaded from a config file for a texture
 */
class texture_config
{
public:
	/**
	 * @brief Leave the constructor empty
	 */
	texture_config() = default;
	/**
	 * @brief Leave the destructor empty
	 */
	virtual ~texture_config() = default;
	/**
	 * @brief The file name without the path
	 */
	std::string file_name;
	/**
	 * @brief Internal application names for the texture
	 */
	std::unordered_set<std::string> names;
};

}
}

#endif //FOX_GFX_TEXTURE_CONFIG_HPP


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
using osu.Game.Localisation;

namespace osu.Game.Overlays.Settings.Sections.UserInterface
{
    public class SongSelectSettings : SettingsSubsection
    {
        private Bindable<double> minStars;
        private Bindable<double> maxStars;

        protected override LocalisableString Header => UserInterfaceStrings.SongSelectHeader;

        [BackgroundDependencyLoader]
        private void load(OsuConfigManager config)
        {
            minStars = config.GetBindable<double>(OsuSetting.DisplayStarsMinimum);
            maxStars = config.GetBindable<double>(OsuSetting.DisplayStarsMaximum);

            minStars.ValueChanged += min => maxStars.Value = Math.Max(min.NewValue, maxStars.Value);
            maxStars.ValueChanged += max => minStars.Value = Math.Min(max.NewValue, minStars.Value);

            Children = new Drawable[]
            {
                new SettingsCheckbox
                {
                    ClassicDefault = true,
                    LabelText = UserInterfaceStrings.RightMouseScroll,
                    Current = config.GetBindable<bool>(OsuSetting.SongSelectRightMouseScroll),
                },
                new SettingsCheckbox
                {
                    LabelText = UserInterfaceStrings.ShowConvertedBeatmaps,
                    Current = config.GetBindable<bool>(OsuSetting.ShowConvertedBeatmaps),
                },
                new SettingsSlider<double, StarsSlider>
                {
                    LabelText = UserInterfaceStrings.StarsMinimum,
                    Current = config.GetBindable<double>(OsuSetting.DisplayStarsMinimum),
                    KeyboardStep = 0.1f,
                    Keywords = new[] { "minimum", "maximum", "star", "difficulty" }
                },
                new SettingsSlider<double, MaximumStarsSlider>
                {
                    LabelText = UserInterfaceStrings.StarsMaximum,
                    Current = config.GetBindable<double>(OsuSetting.DisplayStarsMaximum),
                    KeyboardStep = 0.1f,
                    Keywords = new[] { "minimum", "maximum", "star", "difficulty" }
                },
                new SettingsEnumDropdown<RandomSelectAlgorithm>
                {
                    LabelText = UserInterfaceStrings.RandomSelectionAlgorithm,
                    Current = config.GetBindable<RandomSelectAlgorithm>(OsuSetting.RandomSelectAlgorithm),
                }
            };
        }

        private class MaximumStarsSlider : StarsSlider
        {
            public override LocalisableString TooltipText => Current.IsDefault ? UserInterfaceStrings.NoLimit : base.TooltipText;
        }

        private class StarsSlider : OsuSliderBar<double>
        {
            public override LocalisableString TooltipText => Current.Value.ToString(@"0.## stars");
        }
    }
}


text:
/** @jsx React.DOM */

var src = '../src/title-list.js';

jest.dontMock( src );

describe( 'TitleList', function() {
  it( 'renders a list of titles', function() {
    var titleData = ['A Title', 'Another Title'];

    var React = require( 'react/addons' );
    var TitleList = require( src );
    var TestUtils = React.addons.TestUtils;

    var titleList = TestUtils.renderIntoDocument(
      <TitleList titles={titleData} />
    );

    var titleLists = TestUtils.scryRenderedComponentsWithType( titleList, TitleList );
    var ul = TestUtils.findRenderedDOMComponentWithTag( titleList, 'ul' );
    var childNodes = ul.getDOMNode().childNodes;

    expect( ul.getDOMNode().childNodes.length ).toEqual( titleData.length );

    for(var i = 0; i < childNodes.length; i++) {
      expect( childNodes[i].tagName.toLowerCase() ).toEqual( 'li' );
    };
  });
});


text:
'use strict';

let angular = require('angular');

module.exports = angular.module('sanya.broadcast.service', ['ngResource'])
    .service('BroadcastService', ['$resource', BroadcastService]);

function BroadcastService($resource) {
    var url = '/apis/messages/:messageId';
    return $resource(url, null, { });
}