text:
import imp
import os
import sys
import unittest

from iptest import IronPythonTestCase, is_cli, is_posix, path_modifier, run_test, skipUnlessIronPython
import collections

def get_builtins_dict():
    if type(__builtins__) is type(sys):
        return __builtins__.__dict__
    return __builtins__

class meta_loader(object):
    def __init__(self, value):
        self.value = value
    def load_module(self, fullname):
        if type(self.value) is Exception: raise self.value

        return self.value

class meta_importer(object):
    def __init__(self, s):
        self.s = s
    def find_module(self, fullname, path=None):
        self.s.assertIsNone(path)
        if fullname == 'does_not_exist_throw': raise Exception('hello')
        elif fullname == 'does_not_exist_abc': return meta_loader('abc')
        elif fullname == 'does_not_exist_loader_throw': return meta_loader(Exception('loader'))
        elif fullname == 'does_not_exist_None': return meta_loader(None)
        elif fullname == 'does_not_exist_X':
            class X(object):
                abc = 3
            return meta_loader(X)

class ImpTest(IronPythonTestCase):
    def setUp(self):
        super(ImpTest, self).setUp()

        self._testdir = "ImpTest"
        self._imptestdir = os.path.join(self.test_dir, self._testdir)
        self._f_init = os.path.join(self._imptestdir, "__init__.py")
        self._f_module  = os.path.join(self._imptestdir, "imptestmod.py")

        self.temp_name = ["os",
                    "os.P_WAIT",
                    "os.chmod",
                    "sys.path",
                    "xxxx"
                    ]

        # backup path values
        self.__path = sys.path[:]
        self.__path_hooks = sys.path_hooks[:]
        self.__meta_path = sys.meta_path[:]

    def tearDown(self):
        super(ImpTest, self).tearDown()
        self.clean_directory(self._imptestdir)

        # restore path values
        sys.path_importer_cache = {}
        sys.path = self.__path
        sys.path_hooks = self.__path_hooks
        sys.meta_path = self.__meta_path

    def test_imp_new_module(self):
        x = imp.new_module('abcd')
        sys.modules['abcd'] = x
        try:
            x.foo = 'bar'
            import abcd
            self.assertEqual(abcd.foo, 'bar')
        finally:
            del sys.modules['abcd']

        y = imp.new_module('\r\n')
        sys.modules['xyz'] = y
        try:
            y.foo = 'foo'
            import xyz
            self.assertEqual(xyz.foo, 'foo')
        finally:
            del sys.modules['xyz']

    def test_imp_in_exec(self):
        _imfp = 'impmodfrmpkg'
        _f_imfp_init = os.path.join(self.test_dir, _imfp, "__init__.py")
        _f_imfp_mod  = os.path.join(self.test_dir, _imfp, "mod.py")
        _f_imfp_start = os.path.join(self.test_dir, "imfpstart.tpy")

        self.write_to_file(_f_imfp_init, "")
        self.write_to_file(_f_imfp_mod, "value = 10")
        self.write_to_file(_f_imfp_start, """
try:
    from impmodfrmpkg.mod import mod
except ImportError as e:
    pass
else:
    raise AssertionError("Import of mod from pkg.mod unexpectedly succeeded")
        """)

        try:
            # import a package
            import impmodfrmpkg

            # create a dictionary like that package
            glb = {'__name__' : impmodfrmpkg.__name__, '__path__' : impmodfrmpkg.__path__}
            loc = {}

            exec('from . import mod', glb, loc)
            self.assertIn('mod', loc)

            glb = {'__name__' : impmodfrmpkg.__name__, '__path__' : impmodfrmpkg.__path__}
            loc = {}
            exec('from .mod import *', glb, loc)
            self.assertIn('value', loc)

            if is_cli:
                loc = {}
                exec('from System import *', globals(), loc)

                self.assertIn('Int32', loc)
                self.assertNotIn('Int32', globals())

                exec('from System import *')
                self.assertIn('Int32', dir())

        finally:
            self.delete_files(_f_imfp_start)
            self.clean_directory(os.path.join(self.test_dir, _imfp))

    def test_imp_basic(self):
        magic = imp.get_magic()
        suffixes = imp.get_suffixes()
        self.assertTrue(isinstance(suffixes, list))
        for suffix in suffixes:
            self.assertTrue(isinstance(suffix, tuple))
            self.assertEqual(len(suffix), 3)
        self.assertTrue((".py", "r", 1) in suffixes)

    def test_imp_package(self):
        self.write_to_file(self._f_init, "my_name = 'imp package test'")
        pf, pp, (px, pm, pt) = imp.find_module(self._testdir, [self.test_dir])
        self.assertEqual(pt, imp.PKG_DIRECTORY)
        self.assertEqual(pf, None)
        self.assertEqual(px, "")
        self.assertEqual(pm, "")
        module = imp.load_module(self._testdir, pf, pp, (px, pm, pt))
        self.assertTrue(self._testdir in sys.modules)
        self.assertEqual(module.my_name, 'imp package test')

        with path_modifier(self.test_dir):
            fm = imp.find_module(self._testdir)
        # unpack the result obtained above
        pf, pp, (px, pm, pt) = fm
        self.assertEqual(pt, imp.PKG_DIRECTORY)
        self.assertEqual(pf, None)
        self.assertEqual(px, "")
        self.assertEqual(pm, "")
        module = imp.load_module(self._testdir, pf, pp, (px, pm, pt))
        self.assertEqual(module.my_name, 'imp package test')

    def test_imp_module(self):
        self.write_to_file(self._f_module, "value = 'imp test module'")
        pf, pp, (px, pm, pt) = imp.find_module("imptestmod", [self._imptestdir])
        self.assertEqual(pt, imp.PY_SOURCE)
        self.assertTrue(pf is not None)
        module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
        self.assertEqual(module.value, 'imp test module')
        pf.close()

        with path_modifier(self._imptestdir) as p:
            fm = imp.find_module("imptestmod")
        # unpack the result obtained above
        pf, pp, (px, pm, pt) = fm
        self.assertEqual(pt, imp.PY_SOURCE)
        self.assertTrue(pf != None)
        self.assertEqual(px, ".py")
        self.assertEqual(pm, "r")
        module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
        self.assertEqual(module.value, 'imp test module')
        pf.close()

    def test_direct_module_creation(self):
        import math

        for baseMod in math, sys:
            module = type(baseMod)

            x = module.__new__(module)
            self.assertEqual(repr(x), "<module '?' (built-in)>" if is_cli else "<module '?'>")
            #self.assertEqual(x.__dict__, None)

            x.__init__('abc', 'def')
            self.assertEqual(repr(x), "<module 'abc' (built-in)>" if is_cli else "<module 'abc'>")
            self.assertEqual(x.__doc__, 'def')

            x.__init__('aaa', 'zzz')
            self.assertEqual(repr(x), "<module 'aaa' (built-in)>" if is_cli else "<module 'aaa'>")
            self.assertEqual(x.__doc__, 'zzz')

            # can't assign to module __dict__
            with self.assertRaises(AttributeError):
                x.__dict__ = {}

            # can't delete __dict__
            with self.assertRaises(AttributeError):
                del(x.__dict__)

            # init doesn't clobber dict, it just re-initializes values

            x.__dict__['foo'] = 'xyz'
            x.__init__('xyz', 'nnn')

            self.assertEqual(x.foo, 'xyz')

            # dict is lazily created on set
            x = module.__new__(module)
            x.foo = 23
            self.assertEqual(x.__dict__, {'foo':23})

            self.assertEqual(repr(x), "<module '?' (built-in)>" if is_cli else "<module '?'>")

            # can't pass wrong sub-type to new
            with self.assertRaises(TypeError):
                module.__new__(str)

            # dir on non-initialized module raises TypeError
            x = module.__new__(module)

            x.__name__ = 'module_does_not_exist_in_sys_dot_modules'
            self.assertRaises(ImportError, imp.reload, x)

    def test_redefine_import(self):
        # redefining global __import__ shouldn't change import semantics
        global __import__
        global called
        called = False
        def __import__(*args):
            global called
            called = True

        self.assertEqual(called, False)
        del __import__
        called = False

        self.assertEqual(called, False)

    def test_module_dict(self):
        currentModule = sys.modules[__name__]
        self.assertEqual(isinstance(currentModule.__dict__, collections.Mapping), True)
        self.assertEqual(type({}), type(currentModule.__dict__))
        self.assertEqual(isinstance(currentModule.__dict__, dict), True)

    def test_lock(self):
        i=0
        while i<5:
            i+=1
            if not imp.lock_held():
                self.assertRaises(RuntimeError,imp.release_lock)
                imp.acquire_lock()
            else:
                imp.release_lock()

    def test_is_frozen(self):
        for name in self.temp_name:
            f = imp.is_frozen(name)
            self.assertFalse(f)

    def test_init_frozen(self):
        for name in self.temp_name:
            f = imp.init_frozen(name)
            self.assertIsNone(f)

    def test_is_builtin(self):

        self.assertEqual(imp.is_builtin("xxx"),0)
        self.assertEqual(imp.is_builtin("12324"),0)
        self.assertEqual(imp.is_builtin("&*^^"),0)

        self.assertEqual(imp.is_builtin("dir"),0)
        self.assertEqual(imp.is_builtin("__doc__"),0)
        self.assertEqual(imp.is_builtin("__name__"),0)

        self.assertEqual(imp.is_builtin("_locle"),0)

        if is_cli:
            self.assertEqual(imp.is_builtin("_pickle"),0)
        else:
            self.assertEqual(imp.is_builtin("_pickle"),1)
        self.assertEqual(imp.is_builtin("_random"),1)

        # nt module disabled in Silverlight
        if is_posix:
            self.assertEqual(imp.is_builtin("posix"),1)
        else:
            self.assertEqual(imp.is_builtin("nt"),1)

        self.assertEqual(imp.is_builtin("_thread"),1)

        # used to be a builtin but no longer is
        self.assertEqual(imp.is_builtin("copyreg"),0)

        # supposedly you can't re-init these
        self.assertEqual(imp.is_builtin("sys"), -1)
        self.assertEqual(imp.is_builtin("builtins"), -1)

        imp.init_builtin("sys")
        imp.init_builtin("builtins")

    def test_sys_path_none_builtins(self):
        prevPath = sys.path

        #import some builtin modules not previously imported
        try:
            sys.path = [None] + prevPath
            self.assertNotIn('array', sorted(sys.modules.keys()))
            import array
            self.assertIn('array', sys.modules)

            sys.path = prevPath + [None]
            self.assertNotIn('cmath', sys.modules)
            import array
            import cmath
            self.assertIn('array', sys.modules)
            self.assertIn('cmath', sys.modules)

            sys.path = [None]
            self.assertNotIn('_bisect', sys.modules)
            import array
            import cmath
            import _bisect
            self.assertIn('array', sys.modules)
            self.assertIn('cmath', sys.modules)
            self.assertIn('_bisect', sys.modules)

        finally:
            sys.path = prevPath

    def test_sys_path_none_userpy(self):
        prevPath = sys.path

        #import a *.py file
        temp_syspath_none = os.path.join(self.test_dir, "temp_syspath_none.py")
        self.write_to_file(temp_syspath_none, "stuff = 3.14")

        try:
            sys.path = [None] + prevPath
            import temp_syspath_none
            self.assertEqual(temp_syspath_none.stuff, 3.14)

        finally:
            sys.path = prevPath
            self.delete_files(os.path.join(self.test_dir, "temp_syspath_none.py"))

    def test_sys_path_none_negative(self):
        prevPath = sys.path
        test_paths = [  [None] + prevPath,
                        prevPath + [None],
                        [None],
                    ]

        try:
            for temp_path in test_paths:

                sys.path = temp_path
                with self.assertRaises(ImportError):
                    import does_not_exist
        finally:
            sys.path = prevPath

    def test_init_builtin(self):
        r  = imp.init_builtin("c_Pickle")
        self.assertEqual(r,None)

        r  = imp.init_builtin("2345")
        self.assertEqual(r,None)
        r  = imp.init_builtin("xxxx")
        self.assertEqual(r,None)
        r  = imp.init_builtin("^$%$#@")
        self.assertEqual(r,None)

        r  = imp.init_builtin("_locale")
        self.assertTrue(r!=None)

    def test_flags(self):
        self.assertEqual(imp.SEARCH_ERROR,0)
        self.assertEqual(imp.PY_SOURCE,1)
        self.assertEqual(imp.PY_COMPILED,2)
        self.assertEqual(imp.C_EXTENSION,3)
        self.assertEqual(imp.PY_RESOURCE,4)
        self.assertEqual(imp.PKG_DIRECTORY,5)
        self.assertEqual(imp.C_BUILTIN,6)
        self.assertEqual(imp.PY_FROZEN,7)
        self.assertEqual(imp.PY_CODERESOURCE,8)

    def test_user_defined_modules(self):
        """test the importer using user-defined module types"""
        class MockModule(object):
            def __init__(self, name): self.__name__ = name
            def __repr__(self): return 'MockModule("' + self.__name__ + '")'

        TopModule = MockModule("TopModule")
        sys.modules["TopModule"] = TopModule

        SubModule = MockModule("SubModule")
        theObj = object()
        SubModule.Object = theObj
        TopModule.SubModule = SubModule
        sys.modules["TopModule.SubModule"] = SubModule

        # clear the existing names from our namespace...
        x, y = TopModule, SubModule
        del TopModule, SubModule

        # verify we can import TopModule w/ TopModule.SubModule name
        import TopModule.SubModule
        self.assertEqual(TopModule, x)
        self.assertTrue('SubModule' not in dir())

        # verify we can import Object from TopModule.SubModule
        from TopModule.SubModule import Object
        self.assertEqual(Object, theObj)

        # verify we short-circuit the lookup in TopModule if
        # we have a sys.modules entry...
        SubModule2 = MockModule("SubModule2")
        SubModule2.Object2 = theObj
        sys.modules["TopModule.SubModule"] = SubModule2
        from TopModule.SubModule import Object2
        self.assertEqual(Object2, theObj)

        del sys.modules['TopModule']
        del sys.modules['TopModule.SubModule']

    def test_constructed_module(self):
        """verify that we don't load arbitrary modules from modules, only truly nested modules"""
        ModuleType = type(sys)

        TopModule = ModuleType("TopModule")
        sys.modules["TopModule"] = TopModule

        SubModule = ModuleType("SubModule")
        SubModule.Object = object()
        TopModule.SubModule = SubModule

        with self.assertRaises(ImportError):
            import TopModule.SubModule

        del sys.modules['TopModule']

    #TODO: @skip("multiple_execute")
    def test_import_from_custom(self):
        import builtins
        try:
            class foo(object):
                b = 'abc'
            def __import__(name, globals, locals, fromlist, level):
                global received
                received = name, fromlist
                return foo()

            saved = builtins.__import__
            builtins.__import__ = __import__

            from a import b
            self.assertEqual(received, ('a', ('b', )))
        finally:
            builtins.__import__ = saved

    def test_module_name(self):
        import imp
        m = imp.new_module('foo')
        self.assertEqual(m.__str__(), "<module 'foo' (built-in)>" if is_cli else "<module 'foo'>")
        m.__name__ = 'bar'
        self.assertEqual(m.__str__(), "<module 'bar' (built-in)>" if is_cli else "<module 'bar'>")
        m.__name__ = None
        self.assertEqual(m.__str__(), "<module '?' (built-in)>" if is_cli else "<module None>")
        m.__name__ = []
        self.assertEqual(m.__str__(), "<module '?' (built-in)>" if is_cli else "<module []>")
        m.__file__ = None
        self.assertEqual(m.__str__(), "<module '?' (built-in)>" if is_cli else "<module [] from None>")
        m.__file__ = []
        self.assertEqual(m.__str__(), "<module '?' (built-in)>" if is_cli else "<module [] from []>")
        m.__file__ = 'foo.py'
        self.assertEqual(m.__str__(), "<module '?' from 'foo.py'>" if is_cli else "<module [] from 'foo.py'>")

    def test_cp7007(self):
        file_contents = '''
called = 3.14
    '''

        strange_module_names = [    "+",
                                    "+a",
                                    "a+",
                                    "++",
                                    "+++",
                                    "-",
                                    "=",
                                    "$",
                                    "^",
                                ]

        strange_file_names = [ os.path.join(self.test_dir, "cp7007", x + ".py") for x in strange_module_names ]

        for x in strange_file_names: self.write_to_file(x, file_contents)

        try:
            with path_modifier(os.path.join(self.test_dir, 'cp7007')) as p:
                for x in strange_module_names:
                    temp_mod = __import__(x)
                    self.assertEqual(temp_mod.called, 3.14)
        finally:
            self.clean_directory(os.path.join(self.test_dir, "cp7007"))

    def test_relative_control(self):
        """test various flavors of relative/absolute import and ensure the right
        arguments are delivered to __import__"""
        def myimport(*args):
            global importArgs
            importArgs = list(args)
            importArgs[1] = None    # globals, we don't care about this
            importArgs[2] = None    # locals, we don't care about this either

            # we'll pull values out of this class on success, but that's not
            # the important part
            class X:
                abc = 3
                absolute_import = 2
                bar = 5
            return X
        old_import = get_builtins_dict()['__import__']
        try:
            get_builtins_dict()['__import__'] = myimport

            import abc
            self.assertEqual(importArgs, ['abc', None, None, None, 0])

            from . import abc
            self.assertEqual(importArgs, ['', None, None, ('abc',), 1])

            from .. import abc
            self.assertEqual(importArgs, ['', None, None, ('abc',), 2])

            from ... import abc
            self.assertEqual(importArgs, ['', None, None, ('abc',), 3])

            from ...d import abc
            self.assertEqual(importArgs, ['d', None, None, ('abc',), 3])

            from ...d import (abc, bar)
            self.assertEqual(importArgs, ['d', None, None, ('abc', 'bar'), 3])

            from d import (abc, bar)
            self.assertEqual(importArgs, ['d', None, None, ('abc', 'bar'), 0])

            code = """from __future__ import absolute_import\nimport abc"""
            exec(code, globals(), locals())
            self.assertEqual(importArgs, ['abc', None, None, None, 0])

            def f():exec("from import abc")
            self.assertRaises(SyntaxError, f)

        finally:
            get_builtins_dict()['__import__'] = old_import

    #TODO:@skip("multiple_execute") #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=26829
    def test_import_relative_error(self):
        with self.assertRaises(SystemError):
            exec('from . import *')

    @unittest.skip('No access to CPython stdlib')
    def test_import_hooks_import_precence(self):
        """__import__ takes precedence over import hooks"""
        global myimpCalled
        myimpCalled = None
        class myimp(object):
            def find_module(self, fullname, path=None):
                global myimpCalled
                myimpCalled = fullname, path

        def myimport(*args):
            return 'myimport'

        import distutils
        import distutils.command
        mi = myimp()
        sys.meta_path.append(mi)
        builtinimp = get_builtins_dict()['__import__']
        try:
            get_builtins_dict()['__import__'] = myimport

            import abc
            self.assertEqual(abc, 'myimport')
            self.assertEqual(myimpCalled, None)

            # reload on a built-in hits the loader protocol
            imp.reload(distutils)
            self.assertEqual(myimpCalled, ('distutils', None))

            imp.reload(distutils.command)
            self.assertEqual(myimpCalled[0], 'distutils.command')
            self.assertEqual(myimpCalled[1][0][-7:], 'distutils')
        finally:
            get_builtins_dict()['__import__'] = builtinimp
            sys.meta_path.remove(mi)

    def test_import_hooks_bad_importer(self):
        class bad_importer(object): pass

        mi = bad_importer()
        sys.path.append(mi)
        try:
            def f(): import does_not_exist

            self.assertRaises(ImportError, f)
        finally:
            sys.path.remove(mi)

        sys.path.append(None)
        try:
            def f(): import does_not_exist

            self.assertRaises(ImportError, f)
        finally:
            sys.path.remove(None)

        class inst_importer(object): pass

        mi = inst_importer()
        def f(*args): raise Exception()
        mi.find_module = f
        sys.path.append(mi)
        try:
            def f(): import does_not_exist

            self.assertRaises(ImportError, f)
        finally:
            sys.path.remove(mi)

    def test_import_hooks_importer(self):
        """importer tests - verify the importer gets passed correct values, handles
        errors coming back out correctly"""
        global myimpCalled
        myimpCalled = None

        class myimp(object):
            def find_module(self, fullname, path=None):
                global myimpCalled
                myimpCalled = fullname, path
                if fullname == 'does_not_exist_throw':
                    raise Exception('hello')

        mi = myimp()
        sys.meta_path.append(mi)
        try:
            with self.assertRaises(ImportError):
                import does_not_exist

            self.assertEqual(myimpCalled, ('does_not_exist', None))

            with self.assertRaises(ImportError):
                from testpkg1 import blah

            self.assertEqual(type(myimpCalled[1]), list)
            self.assertEqual(myimpCalled[0], 'testpkg1.blah')
            self.assertEqual(myimpCalled[1][0][-8:], 'testpkg1')

            def f(): import does_not_exist_throw

            self.assertRaisesMessage(Exception, 'hello', f)
        finally:
            sys.meta_path.remove(mi)

    #TODO: @skip("multiple_execute")
    def test_import_hooks_loader(self):
        """loader tests - verify the loader gets the right values, handles errors correctly"""
        global myimpCalled
        myimpCalled = None

        moduleType = type(sys)

        class myloader(object):
            loadcount = 0
            def __init__(self, fullname, path):
                self.fullname = fullname
                self.path = path
            def load_module(self, fullname):
                if fullname == 'does_not_exist_throw':
                    raise Exception('hello again')
                elif fullname == 'does_not_exist_return_none':
                    return None
                else:
                    myloader.loadcount += 1
                    module = sys.modules.setdefault(fullname, moduleType(fullname))
                    module.__file__ = '<myloader file ' + str(myloader.loadcount) + '>'
                    module.fullname = self.fullname
                    module.path = self.path
                    module.__loader__ = self
                    if fullname[-3:] == 'pkg':
                        # create a package
                        module.__path__ = [fullname]

                    return module

        class myimp(object):
            def find_module(self, fullname, path=None):
                return myloader(fullname, path)

        mi = myimp()
        sys.meta_path.append(mi)
        try:
            def f(): import does_not_exist_throw

            self.assertRaisesMessage(Exception, 'hello again', f)

            if is_cli:
                def f(): import does_not_exist_return_none
                self.assertRaises(ImportError, f)

            import does_not_exist_create
            self.assertEqual(does_not_exist_create.__file__, '<myloader file 1>')
            self.assertEqual(does_not_exist_create.fullname, 'does_not_exist_create')
            self.assertEqual(does_not_exist_create.path, None)

            imp.reload(does_not_exist_create)
            self.assertEqual(does_not_exist_create.__file__, '<myloader file 2>')
            self.assertEqual(does_not_exist_create.fullname, 'does_not_exist_create')
            self.assertEqual(does_not_exist_create.path, None)

            import testpkg1.does_not_exist_create_sub
            self.assertEqual(testpkg1.does_not_exist_create_sub.__file__, '<myloader file 3>')
            self.assertEqual(testpkg1.does_not_exist_create_sub.fullname, 'testpkg1.does_not_exist_create_sub')
            self.assertEqual(testpkg1.does_not_exist_create_sub.path[0][-8:], 'testpkg1')

            imp.reload(testpkg1.does_not_exist_create_sub)
            self.assertEqual(testpkg1.does_not_exist_create_sub.__file__, '<myloader file 4>')
            self.assertEqual(testpkg1.does_not_exist_create_sub.fullname, 'testpkg1.does_not_exist_create_sub')
            self.assertEqual(testpkg1.does_not_exist_create_sub.path[0][-8:], 'testpkg1')

            import does_not_exist_create_pkg.does_not_exist_create_subpkg
            self.assertEqual(does_not_exist_create_pkg.__file__, '<myloader file 5>')
            self.assertEqual(does_not_exist_create_pkg.fullname, 'does_not_exist_create_pkg')
        finally:
            sys.meta_path.remove(mi)

    def test_path_hooks(self):
        import toimport
        def prepare(f):
            sys.path_importer_cache = {}
            sys.path_hooks = [f] + old_path_hooks
            if 'toimport' in sys.modules: del sys.modules['toimport']

        old_path_hooks = sys.path_hooks[:]
        try:
            def hook(*args):  raise Exception('hello')
            prepare(hook)
            def f(): import toimport
            self.assertRaisesMessage(Exception, 'hello', f)

            # ImportError shouldn't propagate out
            def hook(*args):  raise ImportError('foo')
            prepare(hook)
            f()

            # returning None
            def hook(*args): pass
            prepare(hook)
            if is_cli:
                f()
            else:
                self.assertRaises(ImportError, f)
        finally:
            sys.path_hooks = old_path_hooks

    def common_meta_import_tests(self):
        def f(): import does_not_exist_throw
        self.assertRaisesMessage(Exception, 'hello', f)

        if is_cli:
            import does_not_exist_abc
            self.assertEqual(does_not_exist_abc, 'abc')

        def f(): import does_not_exist_loader_throw
        self.assertRaisesMessage(Exception, 'loader', f)

        def f(): import does_not_exist_loader_None
        self.assertRaisesMessage(ImportError, "No module named 'does_not_exist_loader_None'", f)

        if is_cli:
            from does_not_exist_X import abc
            self.assertEqual(abc, 3)

    def test_path_hooks_importer_and_loader(self):
        path = list(sys.path)
        hooks = list(sys.path_hooks)
        try:
            sys.path.append('<myname>')
            def hook(name):
                if name == "<myname>":
                    return meta_importer(self)
            sys.path_hooks.append(hook)

            self.common_meta_import_tests()
        finally:
            sys.path = path
            sys.path_hooks = hooks

    def test_meta_path(self):
        mi = meta_importer(self)
        sys.meta_path.append(mi)
        try:
            self.common_meta_import_tests()
        finally:
            sys.meta_path.remove(mi)

    def test_custom_meta_path(self):
        """most special methods invoked by the runtime from Python only invoke on the type, not the instance.
        the import methods will invoke on instances including using __getattribute__ for resolution or on
        old-style classes.   This test verifies we do a full member lookup to find these methods"""
        finder = None
        loader = None
        class K(object):
            def __init__(self):
                self.calls = []
            def __getattribute__(self, name):
                if name != 'calls': self.calls.append(name)
                if name == 'find_module': return finder
                if name == 'load_module': return loader
                return object.__getattribute__(self, name)

        loaderInst = K()
        sys.meta_path.insert(0, loaderInst)

        def ok_finder(name, path=None):
            loaderInst.calls.append( (name, path) )
            return loaderInst

        def ok_loader(name):
            loaderInst.calls.append(name)
            return sys.modules.setdefault('xyz', 'abc')

        try:
            # dynamically resolve find_module to None
            with self.assertRaises(TypeError):
                import xyz
            self.assertEqual(loaderInst.calls, ['find_module'] if is_cli else ['find_spec', 'find_module'])
            loaderInst.calls = []

            # dynamically resolve find_module to a function,
            # and load_module to None.
            finder = ok_finder
            with self.assertRaises(TypeError):
                import xyz
            self.assertEqual(loaderInst.calls, ['find_module', ('xyz', None), 'load_module'] if is_cli else ['find_spec', 'find_module', ('xyz', None), 'get_filename', 'is_package', 'exec_module', 'load_module'])
            loaderInst.calls = []

            loader = ok_loader
            import xyz

            self.assertEqual(xyz, 'abc')
            self.assertEqual(loaderInst.calls, ['find_module', ('xyz', None), 'load_module', 'xyz'] if is_cli else ['find_spec', 'find_module', ('xyz', None), 'get_filename', 'is_package', 'exec_module', 'load_module', 'xyz'])
        finally:
            sys.meta_path.remove(loaderInst)

    def test_import_kw_args(self):
        self.assertEqual(__import__(name = 'sys', globals = globals(), locals = locals(), fromlist = [], level = 0), sys)

    def test_import_list_empty_string(self):
        """importing w/ an empty string in the from list should be ignored"""
        x = __import__('testpkg1', {}, {}, [''])
        self.assertTrue(not '' in dir(x))

    def test_cp7050(self):
        '''
        This test case complements CPython's test_import.py
        '''
        with self.assertRaises(ImportError):
            import Nt

        self.assertRaises(ImportError, __import__, "Nt")
        if is_cli:
            self.assertRaises(ImportError, __import__, "Lib")
        self.assertRaises(ImportError, __import__, "iptest.Assert_Util")

    def test_meta_path_before_builtins(self):
        """the meta path should be consulted before builtins are loaded"""
        class MyException(Exception): pass

        class K:
            def find_module(self, name, path=None):
                if name == "time": return self
                return None
            def load_module(self, name):
                raise MyException

        if 'time' in sys.modules:
            del sys.modules["time"]

        loader = K()
        sys.meta_path.insert(0, loader)
        try:
            with self.assertRaises(MyException):
                import time
        finally:
            sys.meta_path.remove(loader)

        import time

    def test_file_coding(self):
        try:
            import os
            with open('test_coding_mod.py', 'wb+') as f:
                f.write(b"# coding: utf-8\nx = '\xc3\xa6ble'\n")
            with path_modifier('.'):
                import test_coding_mod
                self.assertEqual(test_coding_mod.x[0], '\xe6')
        finally:
            os.unlink('test_coding_mod.py')

        try:
            with open('test_coding_2.py', 'wb+') as f:
                f.write(b"\xef\xbb\xbf# -*- coding: utf-8 -*-\n")
                f.write(b"x = u'ABCDE'\n")
            with path_modifier('.'):
                import test_coding_2
                self.assertEqual(test_coding_2.x, 'ABCDE')
        finally:
            os.unlink('test_coding_2.py')

        try:
            with open('test_coding_3.py', 'wb+') as f:
                f.write(b"# -*- coding: utf-8 -*-\n")
                f.write(b"raise Exception()")
            f.close()
            try:
                with path_modifier('.'):
                    import test_coding_3
            except Exception as e:
                tb = sys.exc_info()[2].tb_next
                if is_cli:
                    while tb.tb_next is not None: tb = tb.tb_next # importlib has a longer traceback
                self.assertEqual(tb.tb_lineno, 2)
        finally:
            os.unlink('test_coding_3.py')

    def test_module_subtype(self):
        class x(type(sys)):
            def __init__(self): self.baz = 100
            def __getattr__(self, name):
                if name == 'qux': raise AttributeError
                return 42
            def __getattribute__(self, name):
                if name == 'foo' or name == 'qux': raise AttributeError
                if name == 'baz': return type(sys).__getattribute__(self, name)
                return 23

        a = x()
        self.assertEqual(a.foo, 42)
        self.assertEqual(a.bar, 23)
        self.assertEqual(a.baz, 100)
        self.assertRaises(AttributeError, lambda : a.qux)

        #Real *.py file
        import testpkg1.mod1
        class x(type(testpkg1.mod1)):
            def __init__(self): self.baz = 100
            def __getattr__(self, name):
                if name == 'qux': raise AttributeError
                return 42
            def __getattribute__(self, name):
                if name == 'foo' or name == 'qux': raise AttributeError
                if name == 'baz': return type(sys).__getattribute__(self, name)
                return 23

        a = x()
        self.assertEqual(a.foo, 42)
        self.assertEqual(a.bar, 23)
        self.assertEqual(a.baz, 100)
        self.assertRaises(AttributeError, lambda : a.qux)

        #Package
        import testpkg1
        class x(type(testpkg1)):
            def __init__(self): self.baz = 100
            def __getattr__(self, name):
                if name == 'qux': raise AttributeError
                return 42
            def __getattribute__(self, name):
                if name == 'foo' or name == 'qux': raise AttributeError
                if name == 'baz': return type(sys).__getattribute__(self, name)
                return 23

        a = x()
        self.assertEqual(a.foo, 42)
        self.assertEqual(a.bar, 23)
        self.assertEqual(a.baz, 100)
        self.assertRaises(AttributeError, lambda : a.qux)

    #TODO:@runonly("stdlib")
    def test_cp13736(self):
        import os
        _f_imp_cp13736 = os.path.join(self.test_dir, "impcp13736.py")
        shortName = _f_imp_cp13736.rsplit(os.sep, 1)[1].split(".")[0]

        self.write_to_file(_f_imp_cp13736, """
class Test(object):
    def a(self):
        return 34
""")

        try:
            import sys
            import imp

            moduleInfo = imp.find_module(shortName)
            module = imp.load_module(shortName, moduleInfo[0], moduleInfo[1], moduleInfo[2])
            t = type('Test1', (getattr(module, 'Test'),), {})
            i = t()
            self.assertEqual(i.a(), 34)

            moduleInfo[0].close()
        finally:
            self.delete_files(_f_imp_cp13736)

    def test_import_path_seperator(self):
        """verify using the path seperator in a direct call will result in an ImportError"""
        self.assertRaises(ImportError, __import__, 'iptest\\type_util')
        __import__('iptest.type_util')

    def test_load_package(self):
        import testpkg1
        pkg = imp.load_package('libcopy', testpkg1.__path__[0])
        self.assertEqual(sys.modules['libcopy'], pkg)

        with self.assertRaises(AttributeError): # AttributeError: 'NoneType' object has no attribute 'name'
            imp.load_package('some_new_pkg', 'some_path_that_does_not_and_never_will_exist')

    def test_NullImporter(self):
        self.assertEqual(imp.NullImporter.__module__, 'imp')

        sys.path.append('directory_that_does_not_exist')
        try:
            with self.assertRaises(ImportError):
                import SomeFileThatDoesNotExist

            # Changed in version 3.3: None is inserted into sys.path_importer_cache instead of an instance of NullImporter.
            self.assertTrue(sys.path_importer_cache['directory_that_does_not_exist'] is None)
        finally:
            sys.path.remove('directory_that_does_not_exist')

    def test_get_frozen_object(self):
        # frozen objects not supported, this always fails
        self.assertRaises(ImportError, imp.get_frozen_object, 'foo')

    def test_cp17459(self):
        self.assertEqual(imp.IMP_HOOK, 9)

    def test_module_getattribute(self):
        mymod = type(sys)('foo', 'bar')
        attrs = ['__delattr__', '__doc__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__str__']
        for attr in attrs:
            d = mymod.__dict__
            d[attr] = 42
            self.assertEqual(getattr(mymod, attr), 42)
            self.assertEqual(mymod.__getattribute__(attr), 42)
            self.assertEqual(mymod.__getattribute__(attr), getattr(mymod, attr))
            del d[attr]

        for x in dir(type(sys)):
            self.assertEqual(mymod.__getattribute__(x), getattr(mymod, x))

    @skipUnlessIronPython()
    def test_import_lookup_after(self):
        import os
        try:
            _x_mod = os.path.join(self.test_dir, "x.py")
            _y_mod = os.path.join(self.test_dir, "y.py")

            self.write_to_file(_x_mod, """
import sys
oldmod = sys.modules['y']
newmod = object()
sys.modules['y'] = newmod
""")
            self.write_to_file(_y_mod, "import x")
            import y
            self.assertEqual(type(y), object)
        finally:
            os.unlink(_x_mod)
            os.unlink(_y_mod)

    @skipUnlessIronPython()
    def test_imp_load_source(self):
        import os
        try:
            _x_mod = os.path.join(self.test_dir, "x.py")
            self.write_to_file(_x_mod, """
'''some pydoc'''
X = 3.14
    """)
            with open(_x_mod, "r") as f:
                x = imp.load_source("test_imp_load_source_x",
                                    _x_mod,
                                    f)
            self.assertEqual(x.__name__, "test_imp_load_source_x")
            self.assertEqual(x.X, 3.14)
            self.assertEqual(x.__doc__, '''some pydoc''')
        finally:
            os.unlink(_x_mod)

    @skipUnlessIronPython()
    def test_imp_load_compiled(self):
        #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459
        with self.assertRaises(FileNotFoundError):
            imp.load_compiled("", "")

    @skipUnlessIronPython()
    def test_imp_load_dynamic(self):
        #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459
        self.assertEqual(imp.load_dynamic, None)

    def test_override_dict(self):
        class M(type(sys)):
            @property
            def __dict__(self):
                return 'not a dict'
            @__dict__.setter
            def __dict__(self, value):
                global setCalled
                setCalled = True

        a = M('foo')
        self.assertEqual(a.__dict__, 'not a dict')
        a.__dict__ = 42
        self.assertEqual(setCalled, True)

        class MyDesc(object):
            def __get__(self, instance, context):
                return 'abc'

        class M(type(sys)):
            __dict__ = MyDesc()

        a = M('foo')
        self.assertEqual(a.__dict__, 'abc')

        # instance members won't be found
        class M(type(sys)): pass

        a = M('foo')
        a.__dict__['__dict__'] = 42
        self.assertEqual(type(a.__dict__), dict)

        self.assertEqual(a.__getattribute__('__dict__'), a.__dict__)

        class M(type(sys)):
            def baz(self):
                return 'hello'
            @property
            def foo(self):
                return 'hello'
            @foo.setter
            def foo(self, value):
                self.bar = value
            @foo.deleter
            def foo(self):
                del self.bar

        a = M('hello')
        self.assertEqual(a.__getattribute__('baz'), a.baz)
        self.assertEqual(a.baz(), 'hello')

        a.__setattr__('foo', 42)
        self.assertEqual(a.__dict__['bar'], 42)

        a.__delattr__('foo')
        self.assertTrue('bar' not in a.__dict__)

        # mix-in an old-style class
        class old_class:
            def old_method(self):
                return 42
            @property
            def old_prop(self):
                return 'abc'
            @old_prop.setter
            def old_prop(self, value):
                self.op = value
            @old_prop.deleter
            def old_prop(self):
                del self.op

        M.__bases__ += (old_class, )
        self.assertEqual(a.old_method(), 42)

        a.__setattr__('old_prop', 42)
        self.assertEqual(a.__dict__['op'], 42)

        a.__delattr__('old_prop')
        self.assertTrue('op' not in a.__dict__)

        # change the class
        class M2(type(sys)): pass
        a.__setattr__('__class__', M2)
        self.assertEqual(type(a), M2)
        self.assertRaisesMessage(AttributeError, "readonly attribute", a.__setattr__, '__dict__', int)
        self.assertRaisesMessage(AttributeError, "readonly attribute", a.__delattr__, '__dict__')

        # __setattr__/__delattr__ no non-derived type
        m = type(sys)('foo')
        self.assertRaisesMessage(TypeError, "__class__ assignment: only for heap types", m.__setattr__, '__class__', int)
        self.assertRaisesMessage(AttributeError, "readonly attribute", m.__setattr__, '__dict__', int)
        self.assertRaisesMessage(TypeError, "can't delete __class__ attribute", m.__delattr__, '__class__')
        self.assertRaisesMessage(AttributeError, "readonly attribute", m.__delattr__, '__dict__')

    def test_ximp_load_module(self):
        mod = imp.new_module('my_module_test')
        mod.__file__ = 'does_not_exist.py'
        sys.modules['my_module_test'] = mod

        with open('test.py', 'w+') as f:
            f.write('x = 42')

        try:
            with open('test.py') as inp_file:
                imp.load_module('my_module_test', inp_file, 'does_not_exist.py', ('', 'U', 1))
        finally:
            os.unlink('test.py')

        self.assertEqual(mod.x, 42)

    def test_import_string_from_list_cp26098(self):
        self.assertEqual(__import__('email.mime.application', globals(), locals(), 'MIMEApplication').__name__, 'email.mime.application')

    @skipUnlessIronPython()
    def test_new_builtin_modules(self):
        import clr
        clr.AddReference('IronPythonTest')
        import test_new_module
        dir(test_new_module)

        # static members should still be accessible
        self.assertEqual(test_new_module.StaticMethod(), 42)
        self.assertEqual(test_new_module.StaticField, 42)
        self.assertEqual(test_new_module.StaticProperty, 42)

        # built-in functions shouldn't appear to be bound
        self.assertEqual(test_new_module.test_method.__doc__, 'test_method() -> object%s' % os.linesep)
        self.assertEqual(test_new_module.test_method.__self__, None)

        # unassigned attributes should throw as if the callee failed to look them up
        self.assertRaises(NameError, lambda : test_new_module.get_test_attr())

        # unassigned builtins should return the built-in as if the caller looked them up
        self.assertEqual(test_new_module.get_min(), min)

        # we should be able to assign to values
        test_new_module.test_attr = 42

        # and the built-in module should see them
        self.assertEqual(test_new_module.get_test_attr(), 42)
        self.assertEqual(test_new_module.test_attr, 42)

        # static members take precedence over things in globals
        self.assertEqual(test_new_module.test_overlap_method(), 42)
        self.assertEqual(type(test_new_module.test_overlap_type), type)

        test_new_module.inc_value()
        self.assertEqual(test_new_module.get_value(), 1)
        test_new_module.inc_value()
        self.assertEqual(test_new_module.get_value(), 2)

        # can't access private fields
        self.assertRaises(AttributeError, lambda : test_new_module._value)

run_test(__name__)
if __name__ == '__main__':
    from iptest.file_util import delete_all_f
    delete_all_f(__name__, remove_folders=True)


text:
package com.google.api.codegen.viewmodel;

import com.google.auto.value.AutoValue;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;

@AutoValue
public abstract class RequestObjectParamView implements Comparable<RequestObjectParamView> {
  public abstract String name();

  public abstract String keyName();

  @Nullable
  public abstract String nameAsMethodName();

  public abstract String elementTypeName();

  public abstract String typeName();

  public abstract String setCallName();

  public abstract String addCallName();

  public abstract String getCallName();

  @Nullable
  public abstract String transformParamFunctionName();

  public abstract boolean isMap();

  public abstract boolean isArray();

  public boolean isCollection() {
    return isMap() || isArray();
  }

  public abstract boolean isPrimitive();

  public abstract boolean isOptional();

  @Nullable // Used in C#
  public abstract String defaultValue();

  public boolean hasDefaultValue() {
    return defaultValue() != null;
  }

  @Nullable // Used in C#
  public abstract String optionalDefault();

  public boolean hasOptionalDefault() {
    return optionalDefault() != null;
  }

  public boolean hasTransformParamFunction() {
    return transformParamFunctionName() != null;
  }

  // Methods for getting/setting the fields of the generated class.
  public abstract List<FieldCopyView> fieldCopyMethods();

  public static Builder newBuilder() {
    return new AutoValue_RequestObjectParamView.Builder()
        .fieldCopyMethods(new ArrayList<FieldCopyView>());
  }

  @AutoValue.Builder
  public abstract static class Builder {
    public abstract Builder name(String val);

    public abstract Builder keyName(String val);

    public abstract Builder nameAsMethodName(String val);

    public abstract Builder elementTypeName(String val);

    public abstract Builder typeName(String val);

    public abstract Builder setCallName(String val);

    public abstract Builder addCallName(String val);

    public abstract Builder getCallName(String val);

    public abstract Builder transformParamFunctionName(String val);

    public abstract Builder isMap(boolean val);

    public abstract Builder isArray(boolean val);

    public abstract Builder isPrimitive(boolean val);

    public abstract Builder isOptional(boolean val);

    public abstract Builder defaultValue(String val);

    public abstract Builder optionalDefault(String val);

    public abstract Builder fieldCopyMethods(List<FieldCopyView> val);

    public abstract RequestObjectParamView build();
  }

  @Override
  public int compareTo(RequestObjectParamView o) {
    return this.name().compareTo(o.name());
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Unknown Station</location>
	<station_id>46075</station_id>
	<observation_time>Last Updated on Jan 4 2016, 9:50 pm AST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 21:50:00 -0400</observation_time_rfc822>
	<temperature_string>41.2 F (5.1 C)</temperature_string>
	<temp_f>41.2</temp_f>
	<temp_c>5.1</temp_c>
	<water_temp_f>41.9</water_temp_f>
	<water_temp_c>5.5</water_temp_c>
	<wind_string>Northeast at 2.2 MPH (1.94 KT)</wind_string>
	<wind_dir>Northeast</wind_dir>
	<wind_degrees>30</wind_degrees>
	<wind_mph>2.2</wind_mph>
	<wind_gust_mph>0.0</wind_gust_mph>
	<wind_kt>1.94</wind_kt>
	<pressure_string>970.6 mb</pressure_string>
	<pressure_mb>970.6</pressure_mb>
	<pressure_tendency_mb>0.0</pressure_tendency_mb>
	<dewpoint_string>39.7 F (4.3 C)</dewpoint_string>
	<dewpoint_f>39.7</dewpoint_f>
	<dewpoint_c>4.3</dewpoint_c>
	<wave_height_m>3.5</wave_height_m>
	<wave_height_ft>11.48</wave_height_ft>
	<dominant_period_sec>11</dominant_period_sec>
	<average_period_sec>7.8</average_period_sec>
	<mean_wave_dir>Northeast</mean_wave_dir>
	<mean_wave_degrees></mean_wave_degrees>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;

namespace Microsoft.WindowsAzure.MobileServices
{
    /// <summary>
    /// Help to do registrationManagement and convert the exceptions
    /// </summary>
    internal class RegistrationManager : IRegistrationManager
    {
        internal readonly PushHttpClient PushHttpClient;

        public RegistrationManager(PushHttpClient pushHttpClient, ILocalStorageManager storageManager)
        {
            this.PushHttpClient = pushHttpClient;

            this.LocalStorageManager = storageManager;
        }

        public ILocalStorageManager LocalStorageManager { get; private set; }

        /// <summary>
        /// If local storage does not have this registrationName, we will create a new one.
        /// If local storage has this name, we will call update.
        /// If update failed with 404(not found), we will create a new one.
        /// </summary>
        /// <param name="registration"></param>
        /// <returns></returns>
        public async Task RegisterAsync(Registration registration)
        {
            // if localStorage is empty or has different storage version, we need retrieve registrations and refresh local storage
            if (this.LocalStorageManager.IsRefreshNeeded)
            {
                string refreshDeviceId = string.IsNullOrEmpty(this.LocalStorageManager.PushHandle) ? registration.PushHandle : this.LocalStorageManager.PushHandle;
                await this.RefreshRegistrationsForChannelAsync(refreshDeviceId);
                this.LocalStorageManager.RefreshFinished(refreshDeviceId);
            }

            var cached = this.LocalStorageManager.GetRegistration(registration.Name);
            if (cached != null)
            {
                registration.RegistrationId = cached.RegistrationId;
            }
            else
            {
                await this.CreateRegistrationIdAsync(registration);
            }

            try
            {
                await this.UpsertRegistration(registration);
                return;
            }
            catch (MobileServiceInvalidOperationException e)
            {
                // if we get an RegistrationGoneException (410) from service, we will recreate registration id and will try to do upsert one more time.
                // The likely cause of this is an expired registration in local storage due to a long unused app.
                if (e.Response.StatusCode != HttpStatusCode.Gone)
                {
                    throw;
                }
            }

            // recreate registration id if we encountered a previously expired registrationId
            await this.CreateRegistrationIdAsync(registration);
            await this.UpsertRegistration(registration);
        }

        public async Task UnregisterAsync(string registrationName)
        {
            if (string.IsNullOrWhiteSpace(registrationName))
            {
                throw new ArgumentNullException("registrationName");
            }

            var cached = this.LocalStorageManager.GetRegistration(registrationName);
            if (cached == null)
            {
                return;
            }

            await this.PushHttpClient.UnregisterAsync(cached.RegistrationId);
            this.LocalStorageManager.DeleteRegistrationByName(registrationName);
        }

        public async Task DeleteRegistrationsForChannelAsync(string deviceId)
        {
            var registrations = await this.ListRegistrationsAsync(deviceId);
            foreach (var registration in registrations)
            {
                await this.PushHttpClient.UnregisterAsync(registration.RegistrationId);
                this.LocalStorageManager.DeleteRegistrationByRegistrationId(registration.RegistrationId);
            }

            // clear local storage
            this.LocalStorageManager.ClearRegistrations();
        }

        public async Task<List<Registration>> ListRegistrationsAsync(string deviceId)
        {
            return new List<Registration>(await this.PushHttpClient.ListRegistrationsAsync(deviceId));
        }

        private async Task<Registration> CreateRegistrationIdAsync(Registration registration)
        {
            registration.RegistrationId = await this.PushHttpClient.CreateRegistrationIdAsync();
            this.LocalStorageManager.UpdateRegistrationByName(registration.Name, registration.RegistrationId, registration.PushHandle);
            return registration;
        }

        private async Task UpsertRegistration(Registration registration)
        {
            await this.PushHttpClient.CreateOrUpdateRegistrationAsync(registration);
            this.LocalStorageManager.UpdateRegistrationByName(registration.Name, registration.RegistrationId, registration.PushHandle);
        }

        private async Task RefreshRegistrationsForChannelAsync(string deviceId)
        {
            var registrations = new List<Registration>(await this.PushHttpClient.ListRegistrationsAsync(deviceId));
            var count = registrations.Count;
            if (count == 0)
            {
                this.LocalStorageManager.ClearRegistrations();
            }

            for (int i = 0; i < count; i++)
            {
                this.LocalStorageManager.UpdateRegistrationByRegistrationId(registrations[i].RegistrationId, registrations[i].Name, registrations[i].PushHandle);
            }
        }
    }
}


text:
package fetchers

import (
	"fmt"
	"io/ioutil"
	"net/url"
	"strings"

	"github.com/asaskevich/govalidator"
	"github.com/flexiant/kdeploy/utils"
	"github.com/flexiant/kdeploy/webservice"
)

// GithubFetcher downloads and extracts a kubeware from a github repo
type GithubFetcher struct{}

// CanHandle tells if the URL can be handled by this resolver
func (gh *GithubFetcher) CanHandle(kubeware string) bool {
	if !govalidator.IsURL(kubeware) {
		return false
	}
	kubewareURL, err := url.Parse(kubeware)
	if err != nil {
		return false
	}
	return gh.canHandleURL(kubewareURL)
}

func (gh *GithubFetcher) canHandleURL(uri *url.URL) bool {
	if uri.Host == "github.com" {
		path := strings.Split(uri.Path, "/")
		if len(path) != 3 {
			return false
		}
		return true
	}
	return false
}

// Fetch downloads and extract archive/master zip from github repo into
// a temporal local directory, and returns its path
func (gh *GithubFetcher) Fetch(kware string) (string, error) {
	if !gh.CanHandle(kware) {
		return "", fmt.Errorf("URL can't be handled by GithubFetcher: '%s'", kware)
	}
	kubewareURL, err := url.Parse(kware)
	if err != nil {
		return "", err
	}
	return gh.fetchURL(kubewareURL)
}

func (gh *GithubFetcher) fetchURL(uri *url.URL) (string, error) {

	path := strings.Split(uri.Path, "/")
	kubewareName := path[2]
	newPath := append([]string{""}, path[1], path[2], "archive", "master.zip")

	kubewareURL := *uri
	kubewareURL.Path = strings.Join(newPath, "/")
	client, err := webservice.NewSimpleWebClient(kubewareURL.String())
	if err != nil {
		return "", err
	}

	tmpDir, err := ioutil.TempDir("", "kdeploy")
	if err != nil {
		return "", err
	}

	zipFileLocation, err := client.GetFile(kubewareURL.Path, tmpDir)
	if err != nil {
		return "", err
	}

	err = utils.Unzip(zipFileLocation, tmpDir)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("%s/%s-master/", tmpDir, kubewareName), nil
}


text:
package tdd.cap8;

public class NFDao {
	public void persiste(NotaFiscal nf) {
		// persiste NF
	}

}


text:
const {
  Pictures, User
} = require('../models')
// const _ = require('lodash')
const cloudinary = require('cloudinary')

module.exports = {

  async addProfilePic (req, res) {
    try {
      const userId = req.body.userId
      // const profileId = req.body.profileId
      // const offerId = req.body.offerId
      var claudynainfo = await cloudinary.v2.uploader.upload(req.files.image.path,
        {
          folder: 'hp2/',
          tags: userId
          // public_id: 'teztestowy',
          // transformation: [
          //   // {aspect_ratio: '4:3', crop: 'fill', gravity: 'faces'},
          //   {width: 'auto', dpr: 'auto', crop: 'scale'},
          //   // {overlay: 'glasses', gravity: 'faces', width: '1.0', flags: 'region_relative'}
          //   {effect: 'blur_faces:1000'}
          // ]
        },
        function (error, result) {
          res.json(result)
          // console.log('v' + result.version + '/' + result.public_id + '.' + result.format)
          console.log(error)
          return result
          // claudynainfo = result
        })
      // console.log(claudynainfo)
      const url = 'v' + claudynainfo.version + '/' + claudynainfo.public_id + '.' + claudynainfo.format

      await User.update({ photo: url }, {
        where: { id: userId }
      })
    } catch (err) {
      console.log(err)
      res.status(500).send({
        error: 'an error has occured trying to upload image'
      })
    }
  },
  // This function is not used as currently I keep photos in user/profile/offer tables
  async getuserpictures (req, res) {
    try {
      const userId = req.params.userId
      const pictures = await Pictures.findOne({
        // limit: 1,
        where: {
          UserId: userId
        },
        order: [['id', 'DESC']]
      })
      res.send(pictures)
    } catch (err) {
      res.status(500).send({
        error: 'an error has occured trying get pictures'
      })
    }
  },
  async addOfferPic (req, res) {
    try {
      const userId = req.body.userId
      // const profileId = req.body.profileId
      // const offerId = req.body.offerId
      await cloudinary.v2.uploader.upload(req.files.image.path,
        {
          folder: 'hp2/',
          tags: userId
          // public_id: 'teztestowy',
          // transformation: [
          //   // {aspect_ratio: '4:3', crop: 'fill', gravity: 'faces'},
          //   {width: 'auto', dpr: 'auto', crop: 'scale'},
          //   // {overlay: 'glasses', gravity: 'faces', width: '1.0', flags: 'region_relative'}
          //   {effect: 'blur_faces:1000'}
          // ]
        },
        function (error, result) {
          res.json(result)
          // console.log('v' + result.version + '/' + result.public_id + '.' + result.format)
          console.log(error)
          return result
          // claudynainfo = result
        })
      // console.log(claudynainfo)
      // const url = 'v' + claudynainfo.version + '/' + claudynainfo.public_id + '.' + claudynainfo.format

      // await Offer.update({ offerPhoto: url }, {
      //   where: { id: offerId }
      // })
    } catch (err) {
      console.log(err)
      res.status(500).send({
        error: 'an error has occured trying to upload image'
      })
    }
  }
}


text:
package io.confluent.kafkarest;

import java.util.Collection;

import io.confluent.kafkarest.entities.ProduceRecord;
import io.confluent.kafkarest.entities.SpoolMode;

/**
 * Wrapper for KafkaProducer that handles schemas.
 */
public interface RestProducer<K, V> {

  /**
   * Produces messages to the topic, handling any conversion, schema lookups or other operations
   * that need to be performed before sending the messages. If schemas are looked up or registered,
   * the SchemaHolder is updated with the resulting IDs.
   */
  public void produce(ProduceTask task, String topic, Integer partition, SpoolMode spoolMode,
                      Collection<? extends ProduceRecord<K, V>> records);

  public void close();
}


text:
var path = require('path'),
    env = require('./env.json'),
    config;

config = {
    // ### Production
    // When running Ghost in the wild, use the production environment
    // Configure your URL and mail settings here
    production: {
        url: 'http://www.donniel.com',
        mail: {
            transport: 'SMTP',
            options: {
                service: 'Mailgun',
                auth: {
                    user: env["production"].GHOST_SMTP_USERNAME,
                    pass: env["production"].GHOST_SMTP_PASSWORD
                }
            }
        },

        database: {
            client: 'mysql',
            connection: {
                host: 'localhost',
                user: env["production"].GHOST_DB_USER,
                password: env["production"].GHOST_DB_PASSWORD,
                database: 'ghost',
                charset: 'utf8'
            }
        },

        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '127.0.0.1',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        }
    },

    // ### Development **(default)**
    development: {
        // The url to use when providing links to the site, E.g. in RSS and email.
        // Change this to your Ghost blogs published URL.
        url: 'http://localhost:2368',

        mail: {
            transport: 'SMTP',
            options: {
                service: 'Mailgun',
                auth: {
                    user: env["development"].GHOST_SMTP_USERNAME,
                    pass: env["development"].GHOST_SMTP_PASSWORD
                }
            }
        },

        database: {
            client: 'mysql',
            connection: {
                host: 'localhost',
                user: 'ghost',
                password: 'password',
                database: 'ghost',
                charset: 'utf8'
            },
            debug: true
        },

        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '127.0.0.1',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        },
        paths: {
            contentPath: path.join(__dirname, '/content/')
        }
    },

    // **Developers only need to edit below here**

    // ### Testing
    // Used when developing Ghost to run tests and check the health of Ghost
    // Uses a different port number
    testing: {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-test.db')
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing MySQL
    // Used by Travis - Automated testing run through GitHub
    'testing-mysql': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'mysql',
            connection: {
                host     : '127.0.0.1',
                user     : 'root',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing pg
    // Used by Travis - Automated testing run through GitHub
    'testing-pg': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'pg',
            connection: {
                host     : '127.0.0.1',
                user     : 'postgres',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    }
};

// Export config
module.exports = config;


text:
package pl.info.rkluszczynski.mockito;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.MockitoAnnotations;

/**
 *
 * @author Rafal
 */
public class MockitoExampleTest {

    @Mock
    private MockitoExample mockitoExampleUnderTest;

    @Before
    public void setUp() throws Exception {
	MockitoAnnotations.initMocks(this);
    }

    @Test
    public void helloMockitoStringTest() {
	final String hiMockitoString = "Hi, Mockito!";
	when(mockitoExampleUnderTest.helloMockito()).thenReturn(hiMockitoString);

	String returnedString = mockitoExampleUnderTest.helloMockito();

	Assert.assertTrue( hiMockitoString.equals(returnedString) );
    }

}


text:
var BaseModel = require('../base/BaseModel.js');
var util = require('util');
var debug = require('debug')('connector:builder');
var spaces = "    ";//4 spaces
var OrderBuilder = function(orderList){
	var currentOrderList = orderList;
	this.getOrderList = function(){
		return currentOrderList;
	};
};
util.inherits(OrderBuilder, BaseModel);

/**
	The main entrance method interpreting and building the clauses
*/
OrderBuilder.prototype.buildClause = function(){
	var self = this;
	var orderList = this.getOrderList();
	var finalClause = "ORDER BY";

	if(typeof orderList == "string"){
		finalClause = finalClause + " " + escapeOneOrderBy(orderList,self);
	}else{
		var i = 0;
		for(i=0;i<orderList.length;i++){
			if(i===0){
				finalClause = finalClause + " ";
			}
			finalClause = finalClause + escapeOneOrderBy(orderList[i],self);
			if(i<(orderList.length-1)){
				finalClause = finalClause + ",";
			}
		}
	}
	return finalClause;
};

/*
	Escape the field name with back-tick in a order-by condition.
	An order-by condition is something like : "id DESC"  or  just "id"  (means "id ASC")
	There should be only one condition, should NOT be like: "id DESC name ASC"

	The expected result would be like:  `id` DESC
*/
var escapeOneOrderBy = function(orderCondition,self){
	var elementArr = orderCondition.split(" ");
	if(elementArr.length==1){
		return self.escapeFieldWithBackTick(orderCondition) + " ASC";
	}else if (elementArr.length==2){
		return self.escapeFieldWithBackTick(elementArr[0]) + " " + elementArr[1].toUpperCase();
	}
	throw "The ORDER BY clause '" + orderCondition + "' has illegal syntax";
};

module.exports = OrderBuilder;


text:
using System;

namespace Apache.Ignite.Core.Impl.Unmanaged.Jni
{
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Threading;
    using Apache.Ignite.Core.Impl.Handle;
    using Apache.Ignite.Core.Log;

    /// <summary>
    /// Java -> .NET callback dispatcher.
    /// Instance of this class should only exist once per process, in the default AppDomain.
    /// </summary>
    internal sealed class Callbacks : MarshalByRefObject
    {
        /** Holds delegates so that GC does not collect them. */
        // ReSharper disable once CollectionNeverQueried.Local
        private readonly List<Delegate> _delegates = new List<Delegate>();

        /** Holds Ignite instance-specific callbacks. */
        private readonly HandleRegistry _callbackRegistry = new HandleRegistry(100);

        /** Console writers. */
        private readonly ConcurrentDictionary<long, ConsoleWriter> _consoleWriters
            = new ConcurrentDictionary<long, ConsoleWriter>();

        /** Gets the JVM. */
        private readonly Jvm _jvm;

        /** Console writer id generator. */
        private long _consoleWriterId;

        /// <summary>
        /// Initializes a new instance of the <see cref="Callbacks"/> class.
        /// </summary>
        public Callbacks(Env env, Jvm jvm)
        {
            Debug.Assert(env != null);
            Debug.Assert(jvm != null);

            _jvm = jvm;
            RegisterNatives(env);
        }

        /** <inheritdoc /> */
        public override object InitializeLifetimeService()
        {
            // Ensure that cross-AppDomain reference lives forever.
            return null;
        }

        /// <summary>
        /// Registers callback handlers.
        /// </summary>
        public long RegisterHandlers(UnmanagedCallbacks cbs)
        {
            Debug.Assert(cbs != null);

            return _callbackRegistry.AllocateCritical(cbs);
        }

        /// <summary>
        /// Releases callback handlers.
        /// </summary>
        public void ReleaseHandlers(long igniteId)
        {
            _callbackRegistry.Release(igniteId);
        }

        /// <summary>
        /// Registers the console writer.
        /// </summary>
        public long RegisterConsoleWriter(ConsoleWriter writer)
        {
            Debug.Assert(writer != null);

            var id = Interlocked.Increment(ref _consoleWriterId);

            var res = _consoleWriters.TryAdd(id, writer);
            Debug.Assert(res);

            return id;
        }

        /// <summary>
        /// Registers the console writer.
        /// </summary>
        public void ReleaseConsoleWriter(long id)
        {
            ConsoleWriter writer;
            var res = _consoleWriters.TryRemove(id, out writer);
            Debug.Assert(res);
        }

        /// <summary>
        /// Registers native callbacks.
        /// </summary>
        private void RegisterNatives(Env env)
        {
            // Native callbacks are per-jvm.
            // Every callback (except ConsoleWrite) includes envPtr (third arg) to identify Ignite instance.

            using (var callbackUtils = env.FindClass(
                "org/apache/ignite/internal/processors/platform/callback/PlatformCallbackUtils"))
            {
                // Any signature works, but wrong one will cause segfault eventually.
                var methods = new[]
                {
                    GetNativeMethod("loggerLog", "(JILjava/lang/String;Ljava/lang/String;Ljava/lang/String;J)V",
                        (CallbackDelegates.LoggerLog) LoggerLog),

                    GetNativeMethod("loggerIsLevelEnabled", "(JI)Z",
                        (CallbackDelegates.LoggerIsLevelEnabled) LoggerIsLevelEnabled),

                    GetNativeMethod("consoleWrite", "(Ljava/lang/String;Z)V",
                        (CallbackDelegates.ConsoleWrite) ConsoleWrite),

                    GetNativeMethod("inLongOutLong", "(JIJ)J", (CallbackDelegates.InLongOutLong) InLongOutLong),

                    GetNativeMethod("inLongLongLongObjectOutLong", "(JIJJJLjava/lang/Object;)J",
                        (CallbackDelegates.InLongLongLongObjectOutLong) InLongLongLongObjectOutLong)
                };

                try
                {
                    env.RegisterNatives(callbackUtils, methods);
                }
                finally
                {
                    foreach (var nativeMethod in methods)
                    {
                        Marshal.FreeHGlobal(nativeMethod.Name);
                        Marshal.FreeHGlobal(nativeMethod.Signature);
                    }
                }
            }
        }

        /// <summary>
        /// Gets the native method.
        /// </summary>
        private unsafe NativeMethod GetNativeMethod(string name, string sig, Delegate d)
        {
            _delegates.Add(d);

            return new NativeMethod
            {
                Name = (IntPtr)IgniteUtils.StringToUtf8Unmanaged(name),
                Signature = (IntPtr)IgniteUtils.StringToUtf8Unmanaged(sig),
                FuncPtr = Marshal.GetFunctionPointerForDelegate(d)
            };
        }

        /// <summary>
        /// <see cref="ILogger.Log"/> callback.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void LoggerLog(IntPtr envPtr, IntPtr clazz, long igniteId, int level, IntPtr message, IntPtr category,
            IntPtr errorInfo, long memPtr)
        {
            try
            {
                var cbs = _callbackRegistry.Get<UnmanagedCallbacks>(igniteId, true);
                var env = _jvm.AttachCurrentThread();

                var message0 = env.JStringToString(message);
                var category0 = env.JStringToString(category);
                var errorInfo0 = env.JStringToString(errorInfo);

                cbs.LoggerLog(level, message0, category0, errorInfo0, memPtr);
            }
            catch (Exception e)
            {
                _jvm.AttachCurrentThread().ThrowToJava(e);
            }
        }

        /// <summary>
        /// <see cref="ILogger.IsEnabled"/> callback.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private bool LoggerIsLevelEnabled(IntPtr env, IntPtr clazz, long igniteId, int level)
        {
            try
            {
                var cbs = _callbackRegistry.Get<UnmanagedCallbacks>(igniteId, true);

                return cbs.LoggerIsLevelEnabled(level);
            }
            catch (Exception e)
            {
                _jvm.AttachCurrentThread().ThrowToJava(e);
                return false;
            }
        }

        /// <summary>
        /// 3 longs + object -> long.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private long InLongLongLongObjectOutLong(IntPtr env, IntPtr clazz, long igniteId,
            int op, long arg1, long arg2, long arg3, IntPtr arg)
        {
            try
            {
                var cbs = _callbackRegistry.Get<UnmanagedCallbacks>(igniteId, true);

                return cbs.InLongLongLongObjectOutLong(op, arg1, arg2, arg3, arg);
            }
            catch (Exception e)
            {
                _jvm.AttachCurrentThread().ThrowToJava(e);
                return 0;
            }
        }

        /// <summary>
        /// long -> long.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private long InLongOutLong(IntPtr env, IntPtr clazz, long igniteId,
            int op, long arg)
        {
            try
            {
                var cbs = _callbackRegistry.Get<UnmanagedCallbacks>(igniteId, true);

                return cbs.InLongOutLong(op, arg);
            }
            catch (Exception e)
            {
                _jvm.AttachCurrentThread().ThrowToJava(e);

                return 0;
            }
        }

        /// <summary>
        /// System.out.println -> Console.Write.
        /// <para />
        /// Java uses system output which can not be accessed with native .NET APIs.
        /// For example, unit test runners won't show Java console output, and so on.
        /// To fix this we delegate console output from Java to .NET APIs.
        /// </summary>
        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void ConsoleWrite(IntPtr envPtr, IntPtr clazz, IntPtr message, bool isError)
        {
            try
            {
                if (message != IntPtr.Zero)
                {
                    // Each domain registers it's own writer.
                    var writer = _consoleWriters.Select(x => x.Value).FirstOrDefault();

                    if (writer != null)
                    {
                        var env = _jvm.AttachCurrentThread();
                        var msg = env.JStringToString(message);

                        writer.Write(msg, isError);
                    }
                }
            }
            catch (Exception e)
            {
                _jvm.AttachCurrentThread().ThrowToJava(e);
            }
        }
    }
}


text:
<!-- TOC depthFrom:2 -->

- [AppHarbor](#appharbor)
- [AWS EC2](#aws-ec2)
- [Azure App Service](#azure-app-service)
- [Fly](#fly)
- [GearHost](#gearhost)
- [Glitch](#glitch)
- [Google App Engine](#google-app-engine)
- [Google Compute Engine](#google-compute-engine)
- [IBM Cloud](#ibm-cloud)
- [Koyeb](#koyeb)
- [Netlify](#netlify)
- [OpenShift](#openshift)
- [Oracle](#oracle)
- [Qoddi](#qoddi)
- [Railway](#railway)
- [Vercel](#vercel)

<!-- /TOC -->

## AppHarbor

[Pricing page](https://appharbor.com/pricing)

* *Free tier*: 1 worker unit, apphb.com hostname
* *Pros*: Auto scaling, Deploy with git, One of few PaaS for .NET apps
* *Limitations*: No custom domain on free tier

## AWS EC2

[Product page](https://aws.amazon.com/free/)

* *Free tier*: 750 hours/month of t2.micro instances
* *Limitations*: Expires 12 months after sign-up

## Azure App Service

[Pricing page](https://azure.microsoft.com/en-us/pricing/details/app-service/)

* *Free tier*: 10 applications, 1 shared core, 1GB RAM and 1GB storage per application
* *Pros*: Supports .NET, easy publishing directly from Git/GitHub/Bitbucket
* *Limitations*: Cumulative limit for CPU (60 minutes allowed every 24 hours), No uptime SLA, No custom domain, No SSL

## Fly

[Pricing page](https://fly.io/docs/about/pricing/)

* *Free tier*: 2340 shared CPU hours per month, 160GB outbound bandwidth per month (unlimited inbound), Unlimited IPv6 and 1 IPv4 Anycast IPs per active app, 10 active certificates per app
* *Limitations*: No uptime SLA, No web app (access through CLI only)

## GearHost

[Pricing page](https://www.gearhost.com/pricing)

* *Free tier*: 1 shared node and 1 worker at max, 100MB storage, 1GB bandwidth/month, Custom domains
* *Pros*: Supports .NET (4.6), PHP (5.3-5.5) and Node.js apps, MSSQL and MySQL databases, Easy publishing over FTP, WebDeploy or directly from Git/GitHub/Bitbucket
* *Limitations*: Cumulative limits for CPU (60 minutes allowed every 24 hours) and RAM (256MB allocated every hour), 1GB bandwidth allowd every 24 hours, [250 concurrent connections](https://www.gearhost.com/documentation/difference-free-standard-reserved-plans), No SSL support, only 32bits processes
* *Exceeding the free tier*: If CPU usage, RAM usage or bandwidth consumed reaches the limit within its timefame, the application goes offline until the counter resets

## Glitch

[Pricing page](https://glitch.com/pricing)

* *Free tier*: Instantly deployed Node.js app with collaboration tool, 1000 project hours, 4000 requests/hour, 512MB ram, 200MB disk excluding node_modules, Custom domain
* *Pros*: Based on Node.js, Online editor with real time collaboration, Live redeploy, Great for prototyping and collaboration
* *Limitations*: Free tier instances will sleep after 5 mins of inactivity but will turn on when someone accesses the website

## Google App Engine

[Product page](https://cloud.google.com/appengine)

* *Free tier*: 28 instance hours/day, 1GB outbound bandwidth/day, 1GB inbound bandwidth/day, 5GB Cloud storage, Shared memcache, 1000 search operations per day, 10MB search indexing, 100 emails per day
* *Pros*: Managed, Autoscaling, Works well with other Google Cloud features (load balancing, datastores, etc.), Multiple languages supported
* *Limitations*: Free tier only applies to a standard environment which supports Python, Java, PHP and Go

## Google Compute Engine

[Product page](https://cloud.google.com/compute/)

* *Free tier*: 1 f1-micro instance per month (US regions only), 30GB-months HDD, 5GB-months snapshot, 1GB network egress from North America to all region destinations per month (excluding China and Australia)
* *Pros*: Works well with other Google Cloud features (load balancing, datastores, etc.)
* *Limitations*: Limited to US region only for now

## IBM Cloud

[Pricing page](https://cloud.ibm.com/pricing/)

* *Free tier*: 512MB/month
* *Pros*: Can deploy multiple smaller instance for free for a total of 512MB (4x128MB, 2x256MB...), Supports multiple languages (Java, JS, Go, PHP, Python Ruby), Supports containers

## Koyeb

[Pricing page](https://www.koyeb.com/pricing)

* *Free tier*: 2 nano services, 1vCPU per service, 256MB of RAM per service, 2.5GB SSD per service, 100GB outbound bandwidth (unlimited inbound)
* *Pros*:  Native autoscaling, Intuitive web interface and CLI, Deploy with Git, Edge CDN, Cron background tasks, Good observability, Supports containers
* *Limitations*: Custom domains not supported yet, Websockets not supported yet, No uptime SLA on free tier.

## Netlify

[Pricing page](https://www.netlify.com/pricing/)

* *Free tier*: 100GB bandwidth per month, 1 concurrent build, 300 build minutes/month, 125000 serverless function invocations per month, 100 form submissions per month, 1000 active Identity users per month, 2500 large media transformations per month
* *Pros*: Deploy with Git, Edge CDN
* *Limitations*: No site analytics on free tier

## OpenShift

[Pricing page](https://www.openshift.com/pricing/index.html)

* *Free tier*: 1 project, 2GB memory, 2GB storage, no custom domain
* *Pros*: Gears can be used to deploy apps in a lot of languages and/or databases, Many deployment templates are provided
* *Limitations*: Deployment requires installation of OpenShift app, Idle apps take longer to load (>30s)

## Oracle

[Pricing page](https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier.htm)

* *Free tier*: 2 Compute(AMD) Micro instances (1/8th OCPU, 1GB memory each), Ampere A1 Compute(Arm) instances (4 OCPUs and 24GB of memory that you can allocate flexibly), 20TB outbound bandwidth (unlimited inbound) [Read more](https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier_topic-Always_Free_Resources.htm)
* *Pros*: Free forever virtual machines
* *Limitations*: OS selection restricted to Oracle Enterprise Linux, CentOS and Ubuntu

## Qoddi

[Pricing page](https://qoddi.com/#pricing)

* *Free tier*: 512MB RAM, 1 vCPU
* *Pros*: Always online, Unlimited build minutes
* *Limitations*: No uptime SLA on free tier

## Railway

[Pricing page](https://railway.app/pricing)

* *Free tier*: 1GB memory per container, Shared CPU, 1GB disk usage (10GB hard limit), 100GB outbound bandwidth (unlimited inbound). [Read more](https://railway.app/legal/fair-use)
* *Pros*: You can have your app and database on the same platform and run both of them for free, [see](database-hosting.md#railway) for database hosting
* *Limitations*: Only 99% uptime SLA, 3 projects, 2 plugins per project, 2 environments per project, 3 live deploys per environment

## Vercel

[Pricing page](https://vercel.com/pricing)

* *Free tier*: 100GB bandwidth per month, 100GB-Hours serverless function execution, 1000 image optimizations, Unlimited serverless function invocations, 100000 edge function invocations, 6000 build minutes/month, 1 concurrent build, 50 domains per project, 3 projects per git repository, 100 deployments per day, 12 serverless functions written in Node.js, Go, Python and Ruby
* *Pros*:  Deploy with git, Edge CDN, Preview deployments, Next.js API endpoints are converted to serverless functions automatically. [Also see](static-app-hosting.md#vercel) for static hosting
* *Limitations*: No uptime SLA on free tier, Free tier does not allow commercial usage, observability is limited, Free tier has limited analytics


text:
package com.microsoft.azure.management.network.v2019_09_01.implementation;

import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.network.v2019_09_01.ServiceTags;
import rx.functions.Func1;
import rx.Observable;
import com.microsoft.azure.management.network.v2019_09_01.ServiceTagsListResult;

class ServiceTagsImpl extends WrapperImpl<ServiceTagsInner> implements ServiceTags {
    private final NetworkManager manager;

    ServiceTagsImpl(NetworkManager manager) {
        super(manager.inner().serviceTags());
        this.manager = manager;
    }

    public NetworkManager manager() {
        return this.manager;
    }

    @Override
    public Observable<ServiceTagsListResult> listAsync(String location) {
        ServiceTagsInner client = this.inner();
        return client.listAsync(location)
        .map(new Func1<ServiceTagsListResultInner, ServiceTagsListResult>() {
            @Override
            public ServiceTagsListResult call(ServiceTagsListResultInner inner) {
                return new ServiceTagsListResultImpl(inner, manager());
            }
        });
    }

}


text:
package com.vmware.vim25;

/**
 * @author Steve Jin (http://www.doublecloud.org)
 * @version 5.1
 */

public enum ProfileNumericComparator {
    lessThan("lessThan"),
    lessThanEqual("lessThanEqual"),
    equal("equal"),
    notEqual("notEqual"),
    greaterThanEqual("greaterThanEqual"),
    greaterThan("greaterThan");

    @SuppressWarnings("unused")
    private final String val;

    private ProfileNumericComparator(String val) {
        this.val = val;
    }
}


text:
cat > /tmp/gitblit.defaults << EOF
GITBLIT_PATH=/opt/gitblit
GITBLIT_BASE_FOLDER=/opt/gitblit/data
GITBLIT_HTTP_PORT=0
GITBLIT_HTTPS_PORT=8443
GITBLIT_LOG=/var/log/gitblit.log
EOF
# Create a systemd service file
cat > /tmp/gitblit.service << EOF
[Unit]
Description=Gitblit managing, viewing, and serving Git repositories.
After=network.target

[Service]
User=gitblit
Group=gitblit
Environment="ARGS=-server -Xmx1024M -Djava.awt.headless=true -jar"
EnvironmentFile=-/etc/sysconfig/gitblit
WorkingDirectory=/opt/gitblit
ExecStart=/usr/bin/java \$ARGS gitblit.jar --httpsPort \$GITBLIT_HTTPS_PORT --httpPort \$GITBLIT_HTTP_PORT --baseFolder \$GITBLIT_BASE_FOLDER --dailyLogFile
ExecStop=/usr/bin/java \$ARGS gitblit.jar --baseFolder \$GITBLIT_BASE_FOLDER --stop

[Install]
WantedBy=multi-user.target
EOF

# Finally copy the files to the destination and register the systemd unit.
sudo su -c "cp /tmp/gitblit.defaults /etc/sysconfig/gitblit && cp /tmp/gitblit.service /usr/lib/systemd/system/"
sudo su -c "systemctl daemon-reload && systemctl enable gitblit.service && systemctl start gitblit.service"
# Prepare the logfile
sudo su -c "touch /var/log/gitblit.log && chown gitblit:gitblit /var/log/gitblit.log"


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = reduce;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/builtin/extends"));

var _ActionTypes = require("../constants/ActionTypes");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var initialState = {
  upvotes: [],
  downvotes: [],
  favorites: []
};

function reduce(state, action) {
  if (state === void 0) {
    state = initialState;
  }

  if (action === void 0) {
    action = {};
  }

  var _action = action,
      type = _action.type,
      payload = _action.payload;

  switch (type) {
    case _ActionTypes.ADVANCE:
      if (payload && payload.stats) {
        return (0, _extends2.default)({}, state, {
          upvotes: payload.stats.upvotes,
          downvotes: payload.stats.downvotes,
          favorites: payload.stats.favorites
        });
      }

      return initialState;

    case _ActionTypes.LOAD_VOTES:
      return (0, _extends2.default)({}, state, {
        upvotes: payload.upvotes,
        downvotes: payload.downvotes,
        favorites: payload.favorites
      });

    case _ActionTypes.UPVOTE:
      return (0, _extends2.default)({}, state, {
        upvotes: state.upvotes.concat([payload.userID]),
        downvotes: state.downvotes.filter(function (vote) {
          return vote !== payload.userID;
        })
      });

    case _ActionTypes.DOWNVOTE:
      return (0, _extends2.default)({}, state, {
        upvotes: state.upvotes.filter(function (vote) {
          return vote !== payload.userID;
        }),
        downvotes: state.downvotes.concat([payload.userID])
      });

    case _ActionTypes.FAVORITE:
      if (state.favorites.indexOf(payload.userID) === -1) {
        return (0, _extends2.default)({}, state, {
          favorites: state.favorites.concat([payload.userID])
        });
      }

      return state;

    case _ActionTypes.DO_FAVORITE_START:
      return state;

    case _ActionTypes.DO_FAVORITE_COMPLETE:
      return state;

    default:
      return state;
  }
}
//# sourceMappingURL=votes.js.map


text:
<?php

namespace Stash\Driver\Sub;

/**
 * Class SqlitePDO
 *
 * This SQLite subdriver uses PDO and the latest version of SQLite.
 *
 * @internal
 * @package Stash
 * @author  Robert Hafner <tedivm@tedivm.com>
 */
class SqlitePdo
{
    /**
     * Directory where the SQLite databases are stored.
     *
     * @var string
     */
    protected $path;

    /**
     * Output of buildDriver, used to interact with the relevant SQLite extension.
     *
     * @var \PDO
     */
    protected $driver;

    /**
     * PDO driver string, used to distinguish between SQLite versions.
     *
     * @var string
     */
    protected static $pdoDriver = 'sqlite';

    /**
     * The SQLite query used to generate the database.
     *
     * @var string
     */
    protected $creationSql = 'CREATE TABLE cacheStore (
                              key TEXT UNIQUE ON CONFLICT REPLACE,
                              expiration INTEGER,
                              encoding TEXT,
                              data BLOB
                              );
                              CREATE INDEX keyIndex ON cacheStore (key);';

    /**
     * File permissions of new SQLite databases.
     *
     * @var string
     */
    protected $filePermissions;

    /**
     * File permissions of new directories leading to SQLite databases.
     *
     * @var string
     */
    protected $dirPermissions;

    /**
     * Amounts of time to wait for the SQLite engine before timing out.
     *
     * @var int milliseconds
     */
    protected $busyTimeout;

    /**
     * The appropriate response code to use when retrieving data.
     *
     * @var int
     */
    protected $responseCode;

    /**
     * @param string $path
     * @param string $directoryPermission
     * @param string $filePermission
     * @param int    $busyTimeout
     */
    public function __construct($path, $directoryPermission, $filePermission, $busyTimeout)
    {
        $this->path = $path;
        $this->filePermissions = $filePermission;
        $this->dirPermissions = $directoryPermission;
        $this->busyTimeout = $busyTimeout;
        $this->responseCode = \PDO::FETCH_ASSOC;
    }

    /**
     * Clear out driver, closing file sockets.
     */
    public function __destruct()
    {
        $this->driver = null;
    }

    /**
     * Retrieves data from cache store.
     *
     * @param  string     $key
     * @return bool|mixed
     */
    public function get($key)
    {
        $driver = $this->getDriver();
        $query = $driver->query("SELECT * FROM cacheStore WHERE key LIKE '{$key}'");
        if ($query === false) {
            return false;
        }

        if ($resultArray = $query->fetch($this->responseCode)) {
            return unserialize(base64_decode($resultArray['data']));
        }

        return false;
    }

    /**
     * Stores data in sqlite database.
     *
     * @param  string $key
     * @param  mixed  $value
     * @param  int    $expiration
     * @return bool
     */
    public function set($key, $value, $expiration)
    {
        $driver = $this->getDriver();
        $data = base64_encode(serialize($value));

        $contentLength = strlen($data);
        if ($contentLength > 100000) {
            $this->setTimeout($this->busyTimeout * (ceil($contentLength / 100000))); // .5s per 100k
        }

        $driver->query("INSERT INTO cacheStore (key, expiration, data)
                                  VALUES ('{$key}', '{$expiration}', '{$data}')");

        return true;
    }

    /**
     * Clears data from database. If a key is defined only it and it's children are removed. If everything is set to be
     * cleared then the database itself is deleted off disk.
     *
     * @param  null|string $key
     * @return bool
     */
    public function clear($key = null)
    {
        // return true if the cache is already empty
        try {
            $driver = $this->getDriver();
        } catch (RuntimeException $e) {
            return true;
        }

        if (!isset($key)) {
            unset($driver);
            $this->driver = null;
            $this->driver = false;
            \Stash\Utilities::deleteRecursive($this->path);
        } else {
            $driver->query("DELETE FROM cacheStore WHERE key LIKE '{$key}%'");
        }

        return true;
    }

    /**
     * Old data is removed and the "vacuum" operation is run.
     *
     * @return bool
     */
    public function purge()
    {
        $driver = $this->getDriver();
        $driver->query('DELETE FROM cacheStore WHERE expiration < ' . time());
        $driver->query('VACUUM');

        return true;
    }

    /**
     * Checks that PDO extension is present and has the appropriate SQLite driver.
     *
     */
    public static function isAvailable()
    {
        if (!class_exists('\PDO', false)) {
            return false;
        }

        $drivers = \PDO::getAvailableDrivers();

        return in_array(static::$pdoDriver, $drivers);
    }

    /**
     * Tells the SQLite driver how long to wait for data to be written.
     *
     * @param  int  $milliseconds
     * @return bool
     */
    protected function setTimeout($milliseconds)
    {
        $driver = $this->getDriver();
        $timeout = ceil($milliseconds / 1000);
        $driver->setAttribute(\PDO::ATTR_TIMEOUT, $timeout);
    }

    /**
     * Retrieves the relevant SQLite driver, creating the database file if necessary.
     *
     * @return \SQLiteDatabase
     * @throws \Stash\Exception\RuntimeException
     */
    protected function getDriver()
    {
        if (isset($this->driver) && $this->driver !== false) {
            return $this->driver;
        }

        if (!file_exists($this->path)) {
            $dir = $this->path;

            // Since PHP will understand paths with mixed slashes- both the windows \ and unix / variants- we have
            // to test for both and see which one is the last in the string.
            $pos1 = strrpos($this->path, '/');
            $pos2 = strrpos($this->path, '\\');

            if ($pos1 || $pos2) {
                $pos = $pos1 >= $pos2 ? $pos1 : $pos2;
                $dir = substr($this->path, 0, $pos);
            }

            if (!is_dir($dir)) {
                mkdir($dir, $this->dirPermissions, true);
            }
            $runInstall = true;
        } else {
            $runInstall = false;
        }

        $db = $this->buildDriver();

        if ($runInstall && !$db->query($this->creationSql)) {
            unlink($this->path);
            throw new RuntimeException('Unable to set SQLite: structure');
        }

        if (!$db) {
            throw new RuntimeException('SQLite driver failed to load');
        }

        $this->driver = $db;

        // prevent the cache from getting hungup waiting on a return
        $this->setTimeout($this->busyTimeout);

        return $db;
    }

    /**
     * Creates the actual database driver itself.
     *
     * @return \SQLiteDatabase
     * @throws \Stash\Exception\RuntimeException
     */
    protected function buildDriver()
    {
        $db = new \PDO(static::$pdoDriver . ':' . $this->path);

        return $db;
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Tripgo.Content.themes.MasterTemplate
{

    public partial class Site1
    {

        /// <summary>
        /// form1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlForm form1;

        /// <summary>
        /// ContentPlaceHolder1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1;
    }
}