Monkey-patches the standard library in Py2.6/7 to provide
    aliases for better Py3 compatibility.
970337
def install_aliases():
    
    if PY3:
        return
    # if hasattr(install_aliases, 'run_already'):
    #     return
    for (newmodname, newobjname, oldmodname, oldobjname) in MOVES:
        __import__(newmodname)
        # We look up the module in sys.modules because __import__ just returns the
        # top-level package:
        newmod = sys.modules[newmodname]
        # newmod.__future_module__ = True

        __import__(oldmodname)
        oldmod = sys.modules[oldmodname]

        obj = getattr(oldmod, oldobjname)
        setattr(newmod, newobjname, obj)

    # Hack for urllib so it appears to have the same structure on Py2 as on Py3
    import urllib
    from future.backports.urllib import request
    from future.backports.urllib import response
    from future.backports.urllib import parse
    from future.backports.urllib import error
    from future.backports.urllib import robotparser
    urllib.request = request
    urllib.response = response
    urllib.parse = parse
    urllib.error = error
    urllib.robotparser = robotparser
    sys.modules['urllib.request'] = request
    sys.modules['urllib.response'] = response
    sys.modules['urllib.parse'] = parse
    sys.modules['urllib.error'] = error
    sys.modules['urllib.robotparser'] = robotparser

    # Patch the test module so it appears to have the same structure on Py2 as on Py3
    try:
        import test
    except ImportError:
        pass
    try:
        from future.moves.test import support
    except ImportError:
        pass
    else:
        test.support = support
        sys.modules['test.support'] = support

    # Patch the dbm module so it appears to have the same structure on Py2 as on Py3
    try:
        import dbm
    except ImportError:
        pass
    else:
        from future.moves.dbm import dumb
        dbm.dumb = dumb
        sys.modules['dbm.dumb'] = dumb
        try:
            from future.moves.dbm import gnu
        except ImportError:
            pass
        else:
            dbm.gnu = gnu
            sys.modules['dbm.gnu'] = gnu
        try:
            from future.moves.dbm import ndbm
        except ImportError:
            pass
        else:
            dbm.ndbm = ndbm
            sys.modules['dbm.ndbm'] = ndbm
1333774
def default_user_agent(name="python-requests"):
    """"""
    _implementation = platform.python_implementation()

    if _implementation == 'CPython':
        _implementation_version = platform.python_version()
    elif _implementation == 'PyPy':
        _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
                                                sys.pypy_version_info.minor,
                                                sys.pypy_version_info.micro)
        if sys.pypy_version_info.releaselevel != 'final':
            _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])
    elif _implementation == 'Jython':
        _implementation_version = platform.python_version()  # Complete Guess
    elif _implementation == 'IronPython':
        _implementation_version = platform.python_version()  # Complete Guess
    else:
        _implementation_version = 'Unknown'

    try:
        p_system = platform.system()
        p_release = platform.release()
    except IOError:
        p_system = 'Unknown'
        p_release = 'Unknown'

    return " ".join(['%s/%s' % (name, __version__),
                     '%s/%s' % (_implementation, _implementation_version),
                     '%s/%s' % (p_system, p_release)])
133200
def _patch_for_tf1_12(tf):
  """"""
  tf.io.gfile = tf.gfile
  tf.io.gfile.copy = tf.gfile.Copy
  tf.io.gfile.exists = tf.gfile.Exists
  tf.io.gfile.glob = tf.gfile.Glob
  tf.io.gfile.isdir = tf.gfile.IsDirectory
  tf.io.gfile.listdir = tf.gfile.ListDirectory
  tf.io.gfile.makedirs = tf.gfile.MakeDirs
  tf.io.gfile.mkdir = tf.gfile.MkDir
  tf.io.gfile.remove = tf.gfile.Remove
  tf.io.gfile.rename = tf.gfile.Rename
  tf.io.gfile.rmtree = tf.gfile.DeleteRecursively
  tf.io.gfile.stat = tf.gfile.Stat
  tf.io.gfile.walk = tf.gfile.Walk
  tf.io.gfile.GFile = tf.gfile.GFile
  tf.data.experimental = tf.contrib.data
  tf.compat.v1 = types.ModuleType("tf.compat.v1")
  tf.compat.v1.assert_greater = tf.assert_greater
  tf.compat.v1.placeholder = tf.placeholder
  tf.compat.v1.ConfigProto = tf.ConfigProto
  tf.compat.v1.Session = tf.Session
  tf.compat.v1.enable_eager_execution = tf.enable_eager_execution
  tf.compat.v1.io = tf.io
  tf.compat.v1.data = tf.data
  tf.compat.v1.data.Dataset = tf.data.Dataset
  tf.compat.v1.data.make_one_shot_iterator = (
      lambda ds: ds.make_one_shot_iterator())
  tf.compat.v1.train = tf.train
  tf.compat.v1.global_variables_initializer = tf.global_variables_initializer
  tf.compat.v1.test = tf.test
  tf.compat.v1.test.get_temp_dir = tf.test.get_temp_dir
  tf.nest = tf.contrib.framework.nest
574898
def patch_tree(actions, tree):
    """"""
    patcher = patch.Patcher()
    return patcher.patch(actions, tree)
613741
def upgrade(yes, dry_run, patches):
    
    patcher = _get_mongopatcher()
    if dry_run:
        patcher.discover_and_apply(directory=patches, dry_run=dry_run)
    else:
        if (yes or prompt_bool("Are you sure you want to alter %s" %
                               green(patcher.db))):
            patcher.discover_and_apply(patches)
        else:
            raise SystemExit('You changed your mind, exiting...')
1053537
def _patch_distribution_metadata():
    """"""
    for attr in ('write_pkg_file', 'read_pkg_file', 'get_metadata_version'):
        new_val = getattr(setuptools.dist, attr)
        setattr(distutils.dist.DistributionMetadata, attr, new_val)
330614
def update_environment(lib_directory):
        """"""
        # Use this if you want to include modules from a subfolder
        # lib_path = os.path.realpath(
        #     os.path.abspath(
        #         os.path.join(
        #             os.path.split(inspect.getfile(inspect.currentframe()))[0], lib_directory)))
        lib_path = os.path.join(os.getcwd(), lib_directory)
        if 'PYTHONPATH' in os.environ:
            os.environ['PYTHONPATH'] = '{}{}{}'.format(
                lib_path, os.pathsep, os.environ['PYTHONPATH']
            )
        else:
            os.environ['PYTHONPATH'] = '{}'.format(lib_path)
494307
def patch(self):
        
        from django.db.models.sql import compiler

        self._read_compilers = (
            compiler.SQLCompiler,
            compiler.SQLAggregateCompiler,
            compiler.SQLDateCompiler,
        )
        self._write_compilers = (
            compiler.SQLInsertCompiler,
            compiler.SQLDeleteCompiler,
            compiler.SQLUpdateCompiler,
        )
        if not self._patched:
            self._original = {}
            for reader in self._read_compilers:
                self._original[reader] = reader.execute_sql
                reader.execute_sql = self._monkey_select(reader.execute_sql)
            for updater in self._write_compilers:
                self._original[updater] = updater.execute_sql
                updater.execute_sql = self._monkey_write(updater.execute_sql)
            self._patched = True
            self.cache_backend.patch()
            self._handle_signals()
155121
def monkey_patch(enabled=True):
    

    if enabled:
        Image.open = imdirect_open
    else:
        Image.open = pil_open
388155
def _updater_wrapper(updater):
    """"""
    def updater_handle(key, lhs_handle, rhs_handle, _):
        """ ctypes function """
        lhs = _ndarray_cls(NDArrayHandle(lhs_handle))
        rhs = _ndarray_cls(NDArrayHandle(rhs_handle))
        updater(key, lhs, rhs)
    return updater_handle
630579
def _apply_cn_keys_patch():
    
    import sys
    if sys.version_info[:2] == (3, 5):
        import http.client as hc
        old_parse = hc.parse_headers

        def parse_header(*args, **kwargs):
            fp = args[0]
            old_readline = fp.readline

            def new_readline(*args, **kwargs):
                ret = old_readline(*args, **kwargs)
                if ret.lower().startswith(b'x-log-query-info'):
                    return b'x-log-query-info: \r\n'
                return ret

            fp.readline = new_readline

            ret = old_parse(*args, **kwargs)
            return ret

        hc.parse_headers = parse_header
1137013
def fix_lib64(lib_dir, symlink=True):
    
    # PyPy's library path scheme is not affected by this.
    # Return early or we will die on the following assert.
    if is_pypy:
        logger.debug('PyPy detected, skipping lib64 symlinking')
        return
    # Check we have a lib64 library path
    if not [p for p in distutils.sysconfig.get_config_vars().values()
            if isinstance(p, basestring) and 'lib64' in p]:
        return

    logger.debug('This system uses lib64; symlinking lib64 to lib')

    assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], (
        "Unexpected python lib dir: %r" % lib_dir)
    lib_parent = os.path.dirname(lib_dir)
    top_level = os.path.dirname(lib_parent)
    lib_dir = os.path.join(top_level, 'lib')
    lib64_link = os.path.join(top_level, 'lib64')
    assert os.path.basename(lib_parent) == 'lib', (
        "Unexpected parent dir: %r" % lib_parent)
    if os.path.lexists(lib64_link):
        return
    if symlink:
        os.symlink('lib', lib64_link)
    else:
        copyfile('lib', lib64_link)
396981
def replace(self, target):
        
        if sys.version_info < (3, 3):
            raise NotImplementedError("replace() is only available "
                                      "with Python 3.3 and later")
        if self._closed:
            self._raise_closed()
        self._accessor.replace(self, target)
1304529
def patch_init_py(base_dir, name, version):
    """"""
    # Ensure main package dir is there (may be absent in script-only packages)
    package_dir = os.path.join(base_dir, name)
    if not os.path.isdir(package_dir):
        os.makedirs(package_dir)
    # Open top-level __init__.py and read whole file
    init_py = os.path.join(package_dir, '__init__.py')
    log.info("patching %s to bake in version '%s'" % (init_py, version))
    with open(init_py, 'r+') as init_file:
        lines = init_file.readlines()
        # Search for sentinels indicating version checking block
        try:
            begin = lines.index("# BEGIN VERSION CHECK\n")
            end = lines.index("# END VERSION CHECK\n")
        except ValueError:
            begin = end = len(lines)
        # Delete existing repo version checking block in file
        init_file.seek(0)
        init_file.writelines(lines[:begin] + lines[end+1:])
        # Append new version attribute to ensure it is authoritative, but only
        # if it is not already there (this happens in pip sdist installs)
        version_cmd = "__version__ = '{0}'\n".format(version)
        if not lines or lines[-1] != version_cmd:
            init_file.write("\n# Automatically added by katversion\n")
            init_file.write(version_cmd)
        init_file.truncate()
313528
function _monkeyPatchConfigure(compiler, complete, options) {
  var configurePath = path.join(compiler.dir, 'configure.py');
  var snapshotPath = options.startupSnapshot;

  if (snapshotPath != null) {
    _log('monkey patching configure file');
    snapshotPath = path.join(process.cwd(), snapshotPath);
    return _monkeypatch(
      configurePath,
      function(content) {
        return ~content.indexOf('v8_embed_script');
      },
      function(content, next) {
        next(
          null,
          content.replace(
            'def configure_v8(o):',
            `def configure_v8(o):
  o['variables']['v8_embed_script'] = r'${snapshotPath}'
  o['variables']['v8_warmup_script'] = r'${snapshotPath}'`,
          ),
        );
      },
      complete,
    );
  } else {
    _log('not  patching configure file');
  }

  return complete();
}
1157090
def pydoc_cli_monkey_patched(port):
    

    # Monkey-patch input so that input does not raise EOFError when
    # called by pydoc.cli
    def input(_):  # pylint: disable=W0622
        """Monkey-patched version of builtins.input"""
        while 1:
            time.sleep(1.0)

    import builtins
    builtins.input = input
    sys.argv += ["-p", port]
    pydoc.cli()
453277
function _monkeypatch(filePath, monkeyPatched, processor, complete) {
  async.waterfall(
    [
      function read(next) {
        fs.readFile(filePath, 'utf8', next);
      },

      // TODO - need to parse gyp file - this is a bit hacker
      function monkeypatch(content, next) {
        if (monkeyPatched(content)) return complete();

        _log('monkey patch %s', filePath);
        processor(content, next);
      },

      function write(content, next) {
        fs.writeFile(filePath, content, 'utf8', function(err) {
          return next(err);
        });
      },
    ],
    complete,
  );
}