�ɲɾ�����ӯ�����һ��ˣ��������С���˴��ͣ�������P���ҹ��ñ˽��ά�Բ��������˸߸ԣ�������ơ��ҹ��ñ�����ά�Բ���ˡ���˳^�ӣ������ӡ� ���ͯj�ӣ��ƺ���ӣ� ? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!wheel.py000064400000077037152527136320006246 0ustar00""" Support for installing and building the "wheel" binary package format. """ from __future__ import absolute_import import compileall import csv import errno import functools import hashlib import logging import os import os.path import re import shutil import stat import sys import tempfile import warnings from base64 import urlsafe_b64encode from email.parser import Parser from pip._vendor.six import StringIO import pip from pip.compat import expanduser from pip.download import path_to_url, unpack_url from pip.exceptions import ( InstallationError, InvalidWheelFilename, UnsupportedWheel) from pip.locations import distutils_scheme, PIP_DELETE_MARKER_FILENAME from pip import pep425tags from pip.utils import ( call_subprocess, ensure_dir, captured_stdout, rmtree, read_chunks, ) from pip.utils.ui import open_spinner from pip.utils.logging import indent_log from pip.utils.setuptools_build import SETUPTOOLS_SHIM from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.six.moves import configparser wheel_ext = '.whl' VERSION_COMPATIBLE = (1, 0) logger = logging.getLogger(__name__) class WheelCache(object): """A cache of wheels for future installs.""" def __init__(self, cache_dir, format_control): """Create a wheel cache. :param cache_dir: The root of the cache. :param format_control: A pip.index.FormatControl object to limit binaries being read from the cache. """ self._cache_dir = expanduser(cache_dir) if cache_dir else None self._format_control = format_control def cached_wheel(self, link, package_name): return cached_wheel( self._cache_dir, link, self._format_control, package_name) def _cache_for_link(cache_dir, link): """ Return a directory to store cached wheels in for link. Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param cache_dir: The cache_dir being used by pip. :param link: The link of the sdist for which this will cache wheels. """ # We want to generate an url to use as our cache key, we don't want to just # re-use the URL because it might have other items in the fragment and we # don't care about those. key_parts = [link.url_without_fragment] if link.hash_name is not None and link.hash is not None: key_parts.append("=".join([link.hash_name, link.hash])) key_url = "#".join(key_parts) # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and thus # less secure). However the differences don't make a lot of difference for # our use case here. hashed = hashlib.sha224(key_url.encode()).hexdigest() # We want to nest the directories some to prevent having a ton of top level # directories where we might run out of sub directories on some FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] # Inside of the base location for cached wheels, expand our parts and join # them all together. return os.path.join(cache_dir, "wheels", *parts) def cached_wheel(cache_dir, link, format_control, package_name): if not cache_dir: return link if not link: return link if link.is_wheel: return link if not link.is_artifact: return link if not package_name: return link canonical_name = canonicalize_name(package_name) formats = pip.index.fmt_ctl_formats(format_control, canonical_name) if "binary" not in formats: return link root = _cache_for_link(cache_dir, link) try: wheel_names = os.listdir(root) except OSError as e: if e.errno in (errno.ENOENT, errno.ENOTDIR): return link raise candidates = [] for wheel_name in wheel_names: try: wheel = Wheel(wheel_name) except InvalidWheelFilename: continue if not wheel.supported(): # Built for a different python/arch/etc continue candidates.append((wheel.support_index_min(), wheel_name)) if not candidates: return link candidates.sort() path = os.path.join(root, candidates[0][1]) return pip.index.Link(path_to_url(path)) def rehash(path, algo='sha256', blocksize=1 << 20): """Return (hash, length) for path using hashlib.new(algo)""" h = hashlib.new(algo) length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') return (digest, length) def open_for_csv(name, mode): if sys.version_info[0] < 3: nl = {} bin = 'b' else: nl = {'newline': ''} bin = '' return open(name, mode + bin, **nl) def fix_script(path): """Replace #!python with #!/path/to/python Return True if file was changed.""" # XXX RECORD hashes will need to be updated if os.path.isfile(path): with open(path, 'rb') as script: firstline = script.readline() if not firstline.startswith(b'#!python'): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b'#!' + exename + os.linesep.encode("ascii") rest = script.read() with open(path, 'wb') as script: script.write(firstline) script.write(rest) return True dist_info_re = re.compile(r"""^(?P(?P.+?)(-(?P\d.+?))?) \.dist-info$""", re.VERBOSE) def root_is_purelib(name, wheeldir): """ Return True if the extracted wheel in wheeldir should go into purelib. """ name_folded = name.replace("-", "_") for item in os.listdir(wheeldir): match = dist_info_re.match(item) if match and match.group('name') == name_folded: with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel: for line in wheel: line = line.lower().rstrip() if line == "root-is-purelib: true": return True return False def get_entrypoints(filename): if not os.path.exists(filename): return {}, {} # This is done because you can pass a string to entry_points wrappers which # means that they may or may not be valid INI files. The attempt here is to # strip leading and trailing whitespace in order to make them valid INI # files. with open(filename) as fp: data = StringIO() for line in fp: data.write(line.strip()) data.write("\n") data.seek(0) cp = configparser.RawConfigParser() cp.optionxform = lambda option: option cp.readfp(data) console = {} gui = {} if cp.has_section('console_scripts'): console = dict(cp.items('console_scripts')) if cp.has_section('gui_scripts'): gui = dict(cp.items('gui_scripts')) return console, gui def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None, pycompile=True, scheme=None, isolated=False, prefix=None, strip_file_prefix=None): """Install a wheel""" if not scheme: scheme = distutils_scheme( name, user=user, home=home, root=root, isolated=isolated, prefix=prefix, ) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_dir = scheme['platlib'] info_dir = [] data_dirs = [] source = wheeldir.rstrip(os.path.sep) + os.path.sep # Record details of the files moved # installed = files copied from the wheel to the destination # changed = files changed while installing (scripts #! line typically) # generated = files newly generated during the install (script wrappers) installed = {} changed = set() generated = [] # Compile all of the pyc files that we're going to be installing if pycompile: with captured_stdout() as stdout: with warnings.catch_warnings(): warnings.filterwarnings('ignore') compileall.compile_dir(source, force=True, quiet=True) logger.debug(stdout.getvalue()) def normpath(src, p): return os.path.relpath(src, p).replace(os.path.sep, '/') def record_installed(srcfile, destfile, modified=False): """Map archive RECORD paths to installation RECORD paths.""" oldpath = normpath(srcfile, wheeldir) newpath = normpath(destfile, lib_dir) installed[oldpath] = newpath if modified: changed.add(destfile) def clobber(source, dest, is_base, fixer=None, filter=None): ensure_dir(dest) # common for the 'include' path for dir, subdirs, files in os.walk(source): basedir = dir[len(source):].lstrip(os.path.sep) destdir = os.path.join(dest, basedir) if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'): continue for s in subdirs: destsubdir = os.path.join(dest, basedir, s) if is_base and basedir == '' and destsubdir.endswith('.data'): data_dirs.append(s) continue elif (is_base and s.endswith('.dist-info') and canonicalize_name(s).startswith( canonicalize_name(req.name))): assert not info_dir, ('Multiple .dist-info directories: ' + destsubdir + ', ' + ', '.join(info_dir)) info_dir.append(destsubdir) for f in files: # Skip unwanted files if filter and filter(f): continue srcfile = os.path.join(dir, f) destfile = os.path.join(dest, basedir, f) # directory creation is lazy and after the file filtering above # to ensure we don't install empty dirs; empty dirs can't be # uninstalled. ensure_dir(destdir) # We use copyfile (not move, copy, or copy2) to be extra sure # that we are not moving directories over (copyfile fails for # directories) as well as to ensure that we are not copying # over any metadata because we want more control over what # metadata we actually copy over. shutil.copyfile(srcfile, destfile) # Copy over the metadata for the file, currently this only # includes the atime and mtime. st = os.stat(srcfile) if hasattr(os, "utime"): os.utime(destfile, (st.st_atime, st.st_mtime)) # If our file is executable, then make our destination file # executable. if os.access(srcfile, os.X_OK): st = os.stat(srcfile) permissions = ( st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH ) os.chmod(destfile, permissions) changed = False if fixer: changed = fixer(destfile) record_installed(srcfile, destfile, changed) clobber(source, lib_dir, True) assert info_dir, "%s .dist-info directory not found" % req # Get the defined entry points ep_file = os.path.join(info_dir[0], 'entry_points.txt') console, gui = get_entrypoints(ep_file) def is_entrypoint_wrapper(name): # EP, EP.exe and EP-script.py are scripts generated for # entry point EP by setuptools if name.lower().endswith('.exe'): matchname = name[:-4] elif name.lower().endswith('-script.py'): matchname = name[:-10] elif name.lower().endswith(".pya"): matchname = name[:-4] else: matchname = name # Ignore setuptools-generated scripts return (matchname in console or matchname in gui) for datadir in data_dirs: fixer = None filter = None for subdir in os.listdir(os.path.join(wheeldir, datadir)): fixer = None if subdir == 'scripts': fixer = fix_script filter = is_entrypoint_wrapper source = os.path.join(wheeldir, datadir, subdir) dest = scheme[subdir] clobber(source, dest, False, fixer=fixer, filter=filter) maker = ScriptMaker(None, scheme['scripts']) # Ensure old scripts are overwritten. # See https://github.com/pypa/pip/issues/1800 maker.clobber = True # Ensure we don't generate any variants for scripts because this is almost # never what somebody wants. # See https://bitbucket.org/pypa/distlib/issue/35/ maker.variants = set(('', )) # This is required because otherwise distlib creates scripts that are not # executable. # See https://bitbucket.org/pypa/distlib/issue/32/ maker.set_mode = True # Simplify the script and fix the fact that the default script swallows # every single stack trace. # See https://bitbucket.org/pypa/distlib/issue/34/ # See https://bitbucket.org/pypa/distlib/issue/33/ def _get_script_text(entry): if entry.suffix is None: raise InstallationError( "Invalid script entry point: %s for req: %s - A callable " "suffix is required. Cf https://packaging.python.org/en/" "latest/distributing.html#console-scripts for more " "information." % (entry, req) ) return maker.script_template % { "module": entry.prefix, "import_name": entry.suffix.split(".")[0], "func": entry.suffix, } maker._get_script_text = _get_script_text maker.script_template = """# -*- coding: utf-8 -*- import re import sys from %(module)s import %(import_name)s if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(%(func)s()) """ # Special case pip and setuptools to generate versioned wrappers # # The issue is that some projects (specifically, pip and setuptools) use # code in setup.py to create "versioned" entry points - pip2.7 on Python # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into # the wheel metadata at build time, and so if the wheel is installed with # a *different* version of Python the entry points will be wrong. The # correct fix for this is to enhance the metadata to be able to describe # such versioned entry points, but that won't happen till Metadata 2.0 is # available. # In the meantime, projects using versioned entry points will either have # incorrect versioned entry points, or they will not be able to distribute # "universal" wheels (i.e., they will need a wheel per Python version). # # Because setuptools and pip are bundled with _ensurepip and virtualenv, # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we # override the versioned entry points in the wheel and generate the # correct ones. This code is purely a short-term measure until Metadata 2.0 # is available. # # To add the level of hack in this section of code, in order to support # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment # variable which will control which version scripts get installed. # # ENSUREPIP_OPTIONS=altinstall # - Only pipX.Y and easy_install-X.Y will be generated and installed # ENSUREPIP_OPTIONS=install # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note # that this option is technically if ENSUREPIP_OPTIONS is set and is # not altinstall # DEFAULT # - The default behavior is to install pip, pipX, pipX.Y, easy_install # and easy_install-X.Y. pip_script = console.pop('pip', None) if pip_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'pip = ' + pip_script generated.extend(maker.make(spec)) if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": spec = 'pip%s = %s' % (sys.version[:1], pip_script) generated.extend(maker.make(spec)) spec = 'pip%s = %s' % (sys.version[:3], pip_script) generated.extend(maker.make(spec)) # Delete any other versioned pip entry points pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)] for k in pip_ep: del console[k] easy_install_script = console.pop('easy_install', None) if easy_install_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'easy_install = ' + easy_install_script generated.extend(maker.make(spec)) spec = 'easy_install-%s = %s' % (sys.version[:3], easy_install_script) generated.extend(maker.make(spec)) # Delete any other versioned easy_install entry points easy_install_ep = [ k for k in console if re.match(r'easy_install(-\d\.\d)?$', k) ] for k in easy_install_ep: del console[k] # Generate the console and GUI entry points specified in the wheel if len(console) > 0: generated.extend( maker.make_multiple(['%s = %s' % kv for kv in console.items()]) ) if len(gui) > 0: generated.extend( maker.make_multiple( ['%s = %s' % kv for kv in gui.items()], {'gui': True} ) ) # Record pip as the installer installer = os.path.join(info_dir[0], 'INSTALLER') temp_installer = os.path.join(info_dir[0], 'INSTALLER.pip') with open(temp_installer, 'wb') as installer_file: installer_file.write(b'pip\n') shutil.move(temp_installer, installer) generated.append(installer) # Record details of all files installed record = os.path.join(info_dir[0], 'RECORD') temp_record = os.path.join(info_dir[0], 'RECORD.pip') with open_for_csv(record, 'r') as record_in: with open_for_csv(temp_record, 'w+') as record_out: reader = csv.reader(record_in) writer = csv.writer(record_out) for row in reader: row[0] = installed.pop(row[0], row[0]) if row[0] in changed: row[1], row[2] = rehash(row[0]) writer.writerow(row) for f in generated: h, l = rehash(f) final_path = normpath(f, lib_dir) if strip_file_prefix and final_path.startswith(strip_file_prefix): final_path = os.path.join(os.sep, os.path.relpath(final_path, strip_file_prefix)) writer.writerow((final_path, h, l)) for f in installed: writer.writerow((installed[f], '', '')) shutil.move(temp_record, record) def _unique(fn): @functools.wraps(fn) def unique(*args, **kw): seen = set() for item in fn(*args, **kw): if item not in seen: seen.add(item) yield item return unique # TODO: this goes somewhere besides the wheel module @_unique def uninstallation_paths(dist): """ Yield all the uninstallation paths for dist based on RECORD-without-.pyc Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc in the same directory. UninstallPathSet.add() takes care of the __pycache__ .pyc. """ from pip.utils import FakeFile # circular import r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r: path = os.path.join(dist.location, row[0]) yield path if path.endswith('.py'): dn, fn = os.path.split(path) base = fn[:-3] path = os.path.join(dn, base + '.pyc') yield path def wheel_version(source_dir): """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return False if we couldn't parse / extract it. """ try: dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0] wheel_data = dist.get_metadata('WHEEL') wheel_data = Parser().parsestr(wheel_data) version = wheel_data['Wheel-Version'].strip() version = tuple(map(int, version.split('.'))) return version except: return False def check_compatibility(version, name): """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name ) if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "%s's Wheel-Version (%s) is not compatible with this version " "of pip" % (name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), ) class Wheel(object): """A wheel file""" # TODO: maybe move the install code into this class wheel_file_re = re.compile( r"""^(?P(?P.+?)-(?P\d.*?)) ((-(?P\d.*?))?-(?P.+?)-(?P.+?)-(?P.+?) \.whl|\.dist-info)$""", re.VERBOSE ) def __init__(self, filename): """ :raises InvalidWheelFilename: when the filename is invalid for a wheel """ wheel_info = self.wheel_file_re.match(filename) if not wheel_info: raise InvalidWheelFilename( "%s is not a valid wheel filename." % filename ) self.filename = filename self.name = wheel_info.group('name').replace('_', '-') # we'll assume "_" means "-" due to wheel naming scheme # (https://github.com/pypa/pip/issues/1150) self.version = wheel_info.group('ver').replace('_', '-') self.pyversions = wheel_info.group('pyver').split('.') self.abis = wheel_info.group('abi').split('.') self.plats = wheel_info.group('plat').split('.') # All the tag combinations from this file self.file_tags = set( (x, y, z) for x in self.pyversions for y in self.abis for z in self.plats ) def support_index_min(self, tags=None): """ Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported. """ if tags is None: # for mock tags = pep425tags.supported_tags indexes = [tags.index(c) for c in self.file_tags if c in tags] return min(indexes) if indexes else None def supported(self, tags=None): """Is this wheel supported on this system?""" if tags is None: # for mock tags = pep425tags.supported_tags return bool(set(tags).intersection(self.file_tags)) class WheelBuilder(object): """Build wheels from a RequirementSet.""" def __init__(self, requirement_set, finder, build_options=None, global_options=None): self.requirement_set = requirement_set self.finder = finder self._cache_root = requirement_set._wheel_cache._cache_dir self._wheel_dir = requirement_set.wheel_download_dir self.build_options = build_options or [] self.global_options = global_options or [] def _build_one(self, req, output_dir, python_tag=None): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ tempd = tempfile.mkdtemp('pip-wheel-') try: if self.__build_one(req, tempd, python_tag=python_tag): try: wheel_name = os.listdir(tempd)[0] wheel_path = os.path.join(output_dir, wheel_name) shutil.move(os.path.join(tempd, wheel_name), wheel_path) logger.info('Stored in directory: %s', output_dir) return wheel_path except: pass # Ignore return, we can't do anything else useful. self._clean_one(req) return None finally: rmtree(tempd) def _base_setup_args(self, req): return [ sys.executable, "-u", '-c', SETUPTOOLS_SHIM % req.setup_py ] + list(self.global_options) def __build_one(self, req, tempd, python_tag=None): base_args = self._base_setup_args(req) spin_message = 'Running setup.py bdist_wheel for %s' % (req.name,) with open_spinner(spin_message) as spinner: logger.debug('Destination directory: %s', tempd) wheel_args = base_args + ['bdist_wheel', '-d', tempd] \ + self.build_options if python_tag is not None: wheel_args += ["--python-tag", python_tag] try: call_subprocess(wheel_args, cwd=req.setup_py_dir, show_stdout=False, spinner=spinner) return True except: spinner.finish("error") logger.error('Failed building wheel for %s', req.name) return False def _clean_one(self, req): base_args = self._base_setup_args(req) logger.info('Running setup.py clean for %s', req.name) clean_args = base_args + ['clean', '--all'] try: call_subprocess(clean_args, cwd=req.source_dir, show_stdout=False) return True except: logger.error('Failed cleaning build dir for %s', req.name) return False def build(self, autobuilding=False): """Build wheels. :param unpack: If True, replace the sdist we built from with the newly built wheel, in preparation for installation. :return: True if all the wheels built correctly. """ assert self._wheel_dir or (autobuilding and self._cache_root) # unpack sdists and constructs req set self.requirement_set.prepare_files(self.finder) reqset = self.requirement_set.requirements.values() buildset = [] for req in reqset: if req.constraint: continue if req.is_wheel: if not autobuilding: logger.info( 'Skipping %s, due to already being wheel.', req.name) elif autobuilding and req.editable: pass elif autobuilding and req.link and not req.link.is_artifact: pass elif autobuilding and not req.source_dir: pass else: if autobuilding: link = req.link base, ext = link.splitext() if pip.index.egg_info_matches(base, None, link) is None: # Doesn't look like a package - don't autobuild a wheel # because we'll have no way to lookup the result sanely continue if "binary" not in pip.index.fmt_ctl_formats( self.finder.format_control, canonicalize_name(req.name)): logger.info( "Skipping bdist_wheel for %s, due to binaries " "being disabled for it.", req.name) continue buildset.append(req) if not buildset: return True # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join([req.name for req in buildset]), ) with indent_log(): build_success, build_failure = [], [] for req in buildset: python_tag = None if autobuilding: python_tag = pep425tags.implementation_tag output_dir = _cache_for_link(self._cache_root, req.link) try: ensure_dir(output_dir) except OSError as e: logger.warning("Building wheel for %s failed: %s", req.name, e) build_failure.append(req) continue else: output_dir = self._wheel_dir wheel_file = self._build_one( req, output_dir, python_tag=python_tag, ) if wheel_file: build_success.append(req) if autobuilding: # XXX: This is mildly duplicative with prepare_files, # but not close enough to pull out to a single common # method. # The code below assumes temporary source dirs - # prevent it doing bad things. if req.source_dir and not os.path.exists(os.path.join( req.source_dir, PIP_DELETE_MARKER_FILENAME)): raise AssertionError( "bad source dir - missing marker") # Delete the source we built the wheel from req.remove_temporary_source() # set the build directory again - name is known from # the work prepare_files did. req.source_dir = req.build_location( self.requirement_set.build_dir) # Update the link for this. req.link = pip.index.Link( path_to_url(wheel_file)) assert req.link.is_wheel # extract the wheel into the dir unpack_url( req.link, req.source_dir, None, False, session=self.requirement_set.session) else: build_failure.append(req) # notify success/failure if build_success: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_success]), ) if build_failure: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failure]), ) # Return True if all builds were successful return len(build_failure) == 0 basecommand.pyc000064400000021347152527136320007547 0ustar00 abc@@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZmZmZmZmZdd lmZdd lmZmZdd lmZmZdd lmZm Z m!Z!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'ddl(m)Z)ddl*m+Z+dgZ,ej-e.Z/de0fdYZ1de1fdYZ2dS(s(Base Command class, and related routinesi(tabsolute_importN(t cmdoptions(t PackageFinder(trunning_under_virtualenv(t PipSession(t BadCommandtInstallationErrortUninstallationErrort CommandErrortPreviousBuildDirError(tlogging_dictConfig(tConfigOptionParsertUpdatingDefaultsHelpFormatter(tInstallRequirementtparse_requirements(tSUCCESStERRORt UNKNOWN_ERRORtVIRTUALENV_NOT_FOUNDtPREVIOUS_BUILD_DIR_ERROR(t deprecationtget_progtnormalize_path(tIndentingFormatter(tpip_version_checktCommandcB@sMeZdZdZeZdZedZdddZ dZ dZ RS(sext://sys.stdoutsext://sys.stderrcC@si|jd6dt|jfd6td6td6|jd6|jd6|d6}t||_d |jj}t j |j||_ t j t j|j}|jj|dS( Ntusages%s %stprogt formattertadd_help_optiontnamet descriptiontisolateds %s Options(RRRR tFalset__doc__R tparsert capitalizetoptparset OptionGrouptcmd_optsRtmake_option_groupt general_grouptadd_option_group(tselfR t parser_kwt optgroup_nametgen_opts((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyt__init__)s      cC@std|jr-ttjj|jdndd|dk rE|n|jd|j}|j rr|j |_ n|j r|j |_ n|j s|r|dk r|n|j |_ n|j ri|j d6|j d6|_n|j |j_|S(Ntcachethttptretriestinsecure_hoststhttps(Rt cache_dirRtostpathtjointNoneR2t trusted_hoststcerttverifyt client_certttimeouttproxytproxiestno_inputtautht prompting(R+toptionsR2R>tsession((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyt_build_sessionAs -   !  cC@s|jj|S(N(R#t parse_args(R+targs((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyRGesc @s|j|\}}|jrW|jdkr6dn|jdkrNdqodn|jridnd}|jrd}ntidd6td 6iid d 6tjd 6d 6d6iitd 6dd6d6d6iid 6dd6|j dd6d gd6dd6d6idd 6dd6|j dd6dd6d6idd 6dd6|jpTdd6t d6dd6d6d6i|d 6t t ddd|jrdndgd6d 6tfd!d"d#d$d%gDd&6tjd d7krtjd(tjn|jrd)tjd*d+j|jtjd,s s pip._vendortdistlibtrequeststurllib3tloggersisPython 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6t1t PIP_NO_INPUTt tPIP_EXISTS_ACTIONs2Could not find an activated virtualenv (required).sException information:texc_infos ERROR: %ssOperation cancelled by users Exception:tno_indexR2R>i(ii(5RGtquiettverbosetlogR R!tloggingRIRt log_streamstTruetlisttfilterR9tdicttsyst version_infotwarningstwarnRtPython26DeprecationWarningRAR6tenviront exists_actionR8t require_venvRtloggertcriticaltexitRtrunt isinstancetintR tstrtdebugRRRRRRtKeyboardInterruptRtdisable_pip_version_checktgetattrRFtminR>RR(R+RHRDt root_leveltstatustexcRE((ROs3/usr/lib/python2.7/site-packages/pip/basecommand.pytmainis            #          N(sext://sys.stdoutsext://sys.stderr( t__name__t __module__R9RRR!thiddenRmR/RFRGR(((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyR#s $ tRequirementCommandcB@s,eZedZdddddZRS(c C@sxS|jD]H}x?t|dtd|d|d|d|D]}|j|q;Wq Wx6|D].}|jtj|d d|jd|q]Wx?|jD]4}|jtj |d|j d|jd|qWt } xS|j D]H}x?t|d|d|d|d|D]}t} |j|q WqW|j |_ |pK|jpK| si|d6} |jrd t| d d j|j} n d | } tj| nd S(s? Marshal cmd line args into a requirement set. t constrainttfinderRDREt wheel_cacheR t default_vcsRs^You must give at least one requirement to %(name)s (maybe you meant "pip %(name)s %(links)s"?)tlinksResLYou must give at least one requirement to %(name)s (see "pip help %(name)s")N(t constraintsRRntadd_requirementR t from_lineR9t isolated_modet editablest from_editableRR!t requirementstrequire_hashest find_linksRqR8Rztwarning( trequirement_setRHRDRRERRRYtreqtfound_req_in_filetoptstmsg((s3/usr/lib/python2.7/site-packages/pip/basecommand.pytpopulate_requirement_setsF       "cC@s|jg|j}|jr>tjddj|g}ntd|jd|jd|d|j d|j d|j d |d |d |d |d | S(sR Create a package finder appropriate to this requirement command. sIgnoring indexes: %st,Rtformat_controlt index_urlsR:tallow_all_prereleasestprocess_dependency_linksREtplatformtversionstabitimplementation( t index_urltextra_index_urlsRhRzRR8RRRR:tpreR(R+RDRERtpython_versionsRRR((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyt_build_package_finder:s        N(RRt staticmethodRR9R(((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyRs8(3R"t __future__RRlR6RrR%RttpipRt pip.indexRt pip.locationsRt pip.downloadRtpip.exceptionsRRRRR t pip.compatR tpip.baseparserR R tpip.reqR Rtpip.status_codesRRRRRt pip.utilsRRRtpip.utils.loggingRtpip.utils.outdatedRt__all__t getLoggerRRztobjectRR(((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyts,     (( exceptions.pyo000064400000030240152527136320007463 0ustar00 abc@@sdZddlmZddlmZmZmZddlmZde fdYZ de fdYZ d e fd YZ d e fd YZ d e fdYZde fdYZde fdYZde fdYZde fdYZde fdYZde fdYZde fdYZde fdYZdefd YZd!efd"YZd#efd$YZd%efd&YZd'efd(YZd)e fd*YZd+S(,s"Exceptions used throughout packagei(tabsolute_import(tchaintgroupbytrepeat(t iteritemstPipErrorcB@seZdZRS(sBase pip exception(t__name__t __module__t__doc__(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR stInstallationErrorcB@seZdZRS(s%General exception during installation(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR stUninstallationErrorcB@seZdZRS(s'General exception during uninstallation(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR stDistributionNotFoundcB@seZdZRS(sCRaised when a distribution cannot be found to satisfy a requirement(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR stRequirementsFileParseErrorcB@seZdZRS(sDRaised when a general error occurs parsing a requirements file line.(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR stBestVersionAlreadyInstalledcB@seZdZRS(sNRaised when the most up-to-date version of a package is already installed.(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR st BadCommandcB@seZdZRS(s0Raised when virtualenv or a command is not found(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR"st CommandErrorcB@seZdZRS(s7Raised when there is an error in command-line arguments(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR&stPreviousBuildDirErrorcB@seZdZRS(s:Raised when there's a previous conflicting build directory(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR*stInvalidWheelFilenamecB@seZdZRS(sInvalid wheel filename.(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR.stUnsupportedWheelcB@seZdZRS(sUnsupported wheel.(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR2st HashErrorscB@s;eZdZdZdZdZdZdZRS(s:Multiple HashError instances rolled into one for reportingcC@s g|_dS(N(terrors(tself((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyt__init__9scC@s|jj|dS(N(Rtappend(Rterror((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR<scC@sg}|jjddxJt|jdD]3\}}|j|j|jd|Dq2W|r|dj|SdS(NtkeycS@s|jS(N(torder(te((s2/usr/lib/python2.7/site-packages/pip/exceptions.pytAtcS@s|jS(N(t __class__(R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyRBRcs@s|]}|jVqdS(N(tbody(t.0R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pys Dss (RtsortRRtheadtextendtjoin(Rtlinestclst errors_of_cls((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyt__str__?s"cC@s t|jS(N(tboolR(R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyt __nonzero__HscC@s |jS(N(R*(R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyt__bool__Ks(RRRRRR(R*R+(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR6s    t HashErrorcB@s5eZdZdZdZdZdZdZRS(s A failure to verify a package against known-good hashes :cvar order: An int sorting hash exception classes by difficulty of recovery (lower being harder), so the user doesn't bother fretting about unpinned packages when he has deeper issues, like VCS dependencies, to deal with. Also keeps error reports in a deterministic order. :cvar head: A section heading for display above potentially many exceptions of this kind :ivar req: The InstallRequirement that triggered this error. This is pasted on after the exception is instantiated, because it's not typically available earlier. RcC@sd|jS(s)Return a summary of me for display under the heading. This default implementation simply prints a description of the triggering requirement. :param req: The InstallRequirement that provoked this error, with populate_link() having already been called s %s(t_requirement_name(R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyRbs cC@sd|j|jfS(Ns%s %s(R"R(R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR(nscC@s|jrt|jSdS(sReturn a description of the requirement that triggered me. This default implementation returns long description of the req, with line numbers sunknown package(treqtstr(R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR-qsN( RRRtNoneR.R"RR(R-(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR,Os  tVcsHashUnsupportedcB@seZdZdZdZRS(suA hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.islCan't verify hashes for these requirements because we don't have a way to hash version control repositories:(RRRRR"(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR1{stDirectoryUrlHashUnsupportedcB@seZdZdZdZRS(suA hash was provided for a version-control-system-based requirement, but we don't have a method for hashing those.isUCan't verify hashes for these file:// requirements because they point to directories:(RRRRR"(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR2st HashMissingcB@s,eZdZdZdZdZdZRS(s2A hash was needed for a requirement but is absent.iswHashes are required in --require-hashes mode, but they are missing from some requirements. Here is a list of those requirements along with the hashes their downloaded archives actually had. Add lines like these to your requirements files to prevent tampering. (If you did not enable --require-hashes manually, note that it turns on automatically when any package has a hash.)cC@s ||_dS(sq :param gotten_hash: The hash of the (possibly malicious) archive we just downloaded N(t gotten_hash(RR4((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyRscC@siddlm}d}|jrO|jjr7|jjnt|jdd}nd|p[d||jfS(Ni(t FAVORITE_HASHR.s %s --hash=%s:%ssunknown package(tpip.utils.hashesR5R0R.t original_linktgetattrR4(RR5tpackage((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyRs  (RRRRR"RR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR3s  t HashUnpinnedcB@seZdZdZdZRS(sPA requirement had a hash specified but was not pinned to a specific version.isaIn --require-hashes mode, all requirements must have their versions pinned with ==. These do not:(RRRRR"(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR:st HashMismatchcB@s5eZdZdZdZdZdZdZRS(s Distribution file hash values don't match. :ivar package_name: The name of the package that triggered the hash mismatch. Feel free to write to this after the exception is raise to improve its error message. isTHESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.cC@s||_||_dS(s :param allowed: A dict of algorithm names pointing to lists of allowed hex digests :param gots: A dict of algorithm names pointing to hashes we actually got from the files under suspicion N(tallowedtgots(RR<R=((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyRs cC@sd|j|jfS(Ns %s: %s(R-t_hash_comparison(R((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyRs c@sd}g}xjt|jD]Y\}}|||jfd|D|jd|j|jdqWdj|S(sE Return a comparison of actual and expected hash values. Example:: Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde or 123451234512345123451234512345123451234512345 Got bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef cS@st|gtdS(Ns or(RR(t hash_name((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyt hash_then_orsc3@s%|]}dt|fVqdS(s Expected %s %sN(tnext(R R(tprefix(s2/usr/lib/python2.7/site-packages/pip/exceptions.pys ss Got %s s ors (RR<R#RR=t hexdigestR$(RR@R%R?t expecteds((RBs2/usr/lib/python2.7/site-packages/pip/exceptions.pyR>s     (RRRRR"RRR>(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyR;s  tUnsupportedPythonVersioncB@seZdZRS(sMUnsupported python version according to Requires-Python package metadata.(RRR(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyREsN(Rt __future__Rt itertoolsRRRtpip._vendor.sixRt ExceptionRR R R R R RRRRRRR,R1R2R3R:R;RE(((s2/usr/lib/python2.7/site-packages/pip/exceptions.pyts,,  $ 8compat/dictconfig.py000064400000055070152527136320010527 0ustar00# This is a copy of the Python logging.config.dictconfig module, # reproduced with permission. It is provided here for backwards # compatibility for Python versions prior to 2.7. # # Copyright 2009-2010 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. from __future__ import absolute_import import logging.handlers import re import sys import types from pip._vendor import six # flake8: noqa IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) def valid_ident(s): m = IDENTIFIER.match(s) if not m: raise ValueError('Not a valid Python identifier: %r' % s) return True # # This function is defined in logging only in recent versions of Python # try: from logging import _checkLevel except ImportError: def _checkLevel(level): if isinstance(level, int): rv = level elif str(level) == level: if level not in logging._levelNames: raise ValueError('Unknown level: %r' % level) rv = logging._levelNames[level] else: raise TypeError('Level not an integer or a ' 'valid string: %r' % level) return rv # The ConvertingXXX classes are wrappers around standard Python containers, # and they serve to convert any suitable values in the container. The # conversion converts base dicts, lists and tuples to their wrapped # equivalents, whereas strings which match a conversion format are converted # appropriately. # # Each wrapper should have a configurator attribute holding the actual # configurator to use for conversion. class ConvertingDict(dict): """A converting dictionary wrapper.""" def __getitem__(self, key): value = dict.__getitem__(self, key) result = self.configurator.convert(value) # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def get(self, key, default=None): value = dict.get(self, key, default) result = self.configurator.convert(value) # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, key, default=None): value = dict.pop(self, key, default) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class ConvertingList(list): """A converting list wrapper.""" def __getitem__(self, key): value = list.__getitem__(self, key) result = self.configurator.convert(value) # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, idx=-1): value = list.pop(self, idx) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self return result class ConvertingTuple(tuple): """A converting tuple wrapper.""" def __getitem__(self, key): value = tuple.__getitem__(self, key) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class BaseConfigurator(object): """ The configurator base class which defines some useful defaults. """ CONVERT_PATTERN = re.compile(r'^(?P[a-z]+)://(?P.*)$') WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') DIGIT_PATTERN = re.compile(r'^\d+$') value_converters = { 'ext' : 'ext_convert', 'cfg' : 'cfg_convert', } # We might want to use a different one, e.g. importlib importer = __import__ def __init__(self, config): self.config = ConvertingDict(config) self.config.configurator = self def resolve(self, s): """ Resolve strings to objects using standard import and attribute syntax. """ name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) except AttributeError: self.importer(used) found = getattr(found, frag) return found except ImportError: e, tb = sys.exc_info()[1:] v = ValueError('Cannot resolve %r: %s' % (s, e)) v.__cause__, v.__traceback__ = e, tb raise v def ext_convert(self, value): """Default converter for the ext:// protocol.""" return self.resolve(value) def cfg_convert(self, value): """Default converter for the cfg:// protocol.""" rest = value m = self.WORD_PATTERN.match(rest) if m is None: raise ValueError("Unable to convert %r" % value) else: rest = rest[m.end():] d = self.config[m.groups()[0]] # print d, rest while rest: m = self.DOT_PATTERN.match(rest) if m: d = d[m.groups()[0]] else: m = self.INDEX_PATTERN.match(rest) if m: idx = m.groups()[0] if not self.DIGIT_PATTERN.match(idx): d = d[idx] else: try: n = int(idx) # try as number first (most likely) d = d[n] except TypeError: d = d[idx] if m: rest = rest[m.end():] else: raise ValueError('Unable to convert ' '%r at %r' % (value, rest)) # rest should be empty return d def convert(self, value): """ Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ if not isinstance(value, ConvertingDict) and isinstance(value, dict): value = ConvertingDict(value) value.configurator = self elif not isinstance(value, ConvertingList) and isinstance(value, list): value = ConvertingList(value) value.configurator = self elif not isinstance(value, ConvertingTuple) and\ isinstance(value, tuple): value = ConvertingTuple(value) value.configurator = self elif isinstance(value, six.string_types): # str for py3k m = self.CONVERT_PATTERN.match(value) if m: d = m.groupdict() prefix = d['prefix'] converter = self.value_converters.get(prefix, None) if converter: suffix = d['suffix'] converter = getattr(self, converter) value = converter(suffix) return value def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers kwargs = dict((k, config[k]) for k in config if valid_ident(k)) result = c(**kwargs) if props: for name, value in props.items(): setattr(result, name, value) return result def as_tuple(self, value): """Utility function which converts lists to tuples.""" if isinstance(value, list): value = tuple(value) return value class DictConfigurator(BaseConfigurator): """ Configure logging using a dictionary-like object to describe the configuration. """ def configure(self): """Do the configuration.""" config = self.config if 'version' not in config: raise ValueError("dictionary doesn't specify a version") if config['version'] != 1: raise ValueError("Unsupported version: %s" % config['version']) incremental = config.pop('incremental', False) EMPTY_DICT = {} logging._acquireLock() try: if incremental: handlers = config.get('handlers', EMPTY_DICT) # incremental handler config only if handler name # ties in to logging._handlers (Python 2.7) if sys.version_info[:2] == (2, 7): for name in handlers: if name not in logging._handlers: raise ValueError('No handler found with ' 'name %r' % name) else: try: handler = logging._handlers[name] handler_config = handlers[name] level = handler_config.get('level', None) if level: handler.setLevel(_checkLevel(level)) except StandardError as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) loggers = config.get('loggers', EMPTY_DICT) for name in loggers: try: self.configure_logger(name, loggers[name], True) except StandardError as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) root = config.get('root', None) if root: try: self.configure_root(root, True) except StandardError as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) else: disable_existing = config.pop('disable_existing_loggers', True) logging._handlers.clear() del logging._handlerList[:] # Do formatters first - they don't refer to anything else formatters = config.get('formatters', EMPTY_DICT) for name in formatters: try: formatters[name] = self.configure_formatter( formatters[name]) except StandardError as e: raise ValueError('Unable to configure ' 'formatter %r: %s' % (name, e)) # Next, do filters - they don't refer to anything else, either filters = config.get('filters', EMPTY_DICT) for name in filters: try: filters[name] = self.configure_filter(filters[name]) except StandardError as e: raise ValueError('Unable to configure ' 'filter %r: %s' % (name, e)) # Next, do handlers - they refer to formatters and filters # As handlers can refer to other handlers, sort the keys # to allow a deterministic order of configuration handlers = config.get('handlers', EMPTY_DICT) for name in sorted(handlers): try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except StandardError as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Next, do loggers - they refer to handlers and filters # we don't want to lose the existing loggers, # since other threads may have pointers to them. # existing is set to contain all existing loggers, # and as we go through the new configuration we # remove any which are configured. At the end, # what's left in existing is the set of loggers # which were in the previous configuration but # which are not in the new configuration. root = logging.root existing = list(root.manager.loggerDict) # The list needs to be sorted so that we can # avoid disabling child loggers of explicitly # named loggers. With a sorted list it is easier # to find the child loggers. existing.sort() # We'll keep the list of existing loggers # which are children of named loggers here... child_loggers = [] # now set up the new ones... loggers = config.get('loggers', EMPTY_DICT) for name in loggers: if name in existing: i = existing.index(name) prefixed = name + "." pflen = len(prefixed) num_existing = len(existing) i = i + 1 # look at the entry after name while (i < num_existing) and\ (existing[i][:pflen] == prefixed): child_loggers.append(existing[i]) i = i + 1 existing.remove(name) try: self.configure_logger(name, loggers[name]) except StandardError as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) # Disable any old loggers. There's no point deleting # them as other threads may continue to hold references # and by disabling them, you stop them doing any logging. # However, don't disable children of named loggers, as that's # probably not what was intended by the user. for log in existing: logger = root.manager.loggerDict[log] if log in child_loggers: logger.level = logging.NOTSET logger.handlers = [] logger.propagate = True elif disable_existing: logger.disabled = True # And finally, do the root logger root = config.get('root', None) if root: try: self.configure_root(root) except StandardError as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) finally: logging._releaseLock() def configure_formatter(self, config): """Configure a formatter from a dictionary.""" if '()' in config: factory = config['()'] # for use in exception handler try: result = self.configure_custom(config) except TypeError as te: if "'format'" not in str(te): raise # Name of parameter changed from fmt to format. # Retry with old name. # This is so that code can be used with older Python versions #(e.g. by Django) config['fmt'] = config.pop('format') config['()'] = factory result = self.configure_custom(config) else: fmt = config.get('format', None) dfmt = config.get('datefmt', None) result = logging.Formatter(fmt, dfmt) return result def configure_filter(self, config): """Configure a filter from a dictionary.""" if '()' in config: result = self.configure_custom(config) else: name = config.get('name', '') result = logging.Filter(name) return result def add_filters(self, filterer, filters): """Add filters to a filterer from a list of names.""" for f in filters: try: filterer.addFilter(self.config['filters'][f]) except StandardError as e: raise ValueError('Unable to add filter %r: %s' % (f, e)) def configure_handler(self, config): """Configure a handler from a dictionary.""" formatter = config.pop('formatter', None) if formatter: try: formatter = self.config['formatters'][formatter] except StandardError as e: raise ValueError('Unable to set formatter ' '%r: %s' % (formatter, e)) level = config.pop('level', None) filters = config.pop('filters', None) if '()' in config: c = config.pop('()') if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: c = self.resolve(c) factory = c else: klass = self.resolve(config.pop('class')) # Special case for handler which refers to another handler if issubclass(klass, logging.handlers.MemoryHandler) and\ 'target' in config: try: config['target'] = self.config['handlers'][config['target']] except StandardError as e: raise ValueError('Unable to set target handler ' '%r: %s' % (config['target'], e)) elif issubclass(klass, logging.handlers.SMTPHandler) and\ 'mailhost' in config: config['mailhost'] = self.as_tuple(config['mailhost']) elif issubclass(klass, logging.handlers.SysLogHandler) and\ 'address' in config: config['address'] = self.as_tuple(config['address']) factory = klass kwargs = dict((k, config[k]) for k in config if valid_ident(k)) try: result = factory(**kwargs) except TypeError as te: if "'stream'" not in str(te): raise # The argument name changed from strm to stream # Retry with old name. # This is so that code can be used with older Python versions #(e.g. by Django) kwargs['strm'] = kwargs.pop('stream') result = factory(**kwargs) if formatter: result.setFormatter(formatter) if level is not None: result.setLevel(_checkLevel(level)) if filters: self.add_filters(result, filters) return result def add_handlers(self, logger, handlers): """Add handlers to a logger from a list of names.""" for h in handlers: try: logger.addHandler(self.config['handlers'][h]) except StandardError as e: raise ValueError('Unable to add handler %r: %s' % (h, e)) def common_logger_config(self, logger, config, incremental=False): """ Perform configuration which is common to root and non-root loggers. """ level = config.get('level', None) if level is not None: logger.setLevel(_checkLevel(level)) if not incremental: # Remove any existing handlers for h in logger.handlers[:]: logger.removeHandler(h) handlers = config.get('handlers', None) if handlers: self.add_handlers(logger, handlers) filters = config.get('filters', None) if filters: self.add_filters(logger, filters) def configure_logger(self, name, config, incremental=False): """Configure a non-root logger from a dictionary.""" logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logger.propagate = propagate def configure_root(self, config, incremental=False): """Configure a root logger from a dictionary.""" root = logging.getLogger() self.common_logger_config(root, config, incremental) dictConfigClass = DictConfigurator def dictConfig(config): """Configure logging using a dictionary.""" dictConfigClass(config).configure() compat/__init__.pyc000064400000012127152527136320010314 0ustar00 abc @`sdZddlmZmZddlZddlZddlmZyddlm Z Wn!e k r{ddl m Z nXyddl mZWn!e k rddlmZnXyddlZWn]e k r#yddlmZWq$e k rddlZeje_eje_q$XnXyddlZdZWn*e k ridd lmZd ZnXd d d dddddddg Zejd)kreZddlmZn3ddl Z e!e dZere jZndZejd*krdZ#e$dZ%ndZ#e$dZ%dZ&dZ'dZ(d+Z)ejd,krbe)d-7Z)nej*j+d%pej*d&koej,d'kZ-d(Z.dS(.sKStuff that differs in different Python versions and platform distributions.i(tabsolute_importtdivisionN(t text_type(t dictConfig(t OrderedDict(t ipaddresscC`s1tjdtjdg}ttt|S(Ntstdlibt platstdlib(t sysconfigtget_pathtsettfiltertbool(tpaths((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyt get_stdlib"s (RcC`s=tjdttjdtdtg}ttt|S(Nt standard_libt plat_specific(Rtget_python_libtTrueR R R (R ((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyR+stlogging_dictConfigRt uses_pycachetconsole_to_strt native_strt get_path_uidt stdlib_pkgstWINDOWStsamefileRii(tcache_from_sourceRcC`s9y|jtjjSWntk r4|jdSXdS(Ntutf_8(tdecodetsyst __stdout__tencodingtUnicodeDecodeError(ts((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRGs cC`s/t|tr+|jd|r$dndS|S(Nsutf-8treplacetstrict(t isinstancetbytesR(R"R#((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRMscC`s|S(N((R"((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRSscC`s t|tr|jdS|S(Nsutf-8(R%Rtencode(R"R#((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRVs cC`sHt|dr|jS|j|j|jddd}|dSdS(Nt total_secondsiii ii@Bi@B(thasattrR(t microsecondstsecondstdays(ttdtval((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyR(]s #cC`sttdrMtj|tjtjB}tj|j}tj|n7tjj |sttj |j}nt d||S(s) Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. t O_NOFOLLOWs1%s is a symlink; Will not return uid for symlinks( R)tostopentO_RDONLYR/tfstattst_uidtclosetpathtislinktstattOSError(R6tfdtfile_uid((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRes  cC`sAtjj|}|jdr=|jdr=|d}n|S(sl Expand ~ and ~user constructions. Includes a workaround for http://bugs.python.org/issue14768 s~/s//i(R0R6t expandusert startswith(R6texpanded((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyR<s tpythontwsgirefiitargparsetwintclitntcC`sottjdr%tjj||Stjjtjj|}tjjtjj|}||kSdS(s>Provide an alternative for os.path.samefile on Windows/Python2RN(R)R0R6Rtnormcasetabspath(tfile1tfile2tpath1tpath2((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRs (ii(i(R?R@(ii(RA(/t__doc__t __future__RRR0Rtpip._vendor.sixRtlogging.configRRt ImportErrortpip.compat.dictconfigt collectionsRtpip._vendor.ordereddictRt pip._vendortipaddrt IPAddresst ip_addresst IPNetworkt ip_networkRRt distutilst__all__t version_infoRRtimportlib.utilRtimpR)tNoneRtFalseRR(RR<RtplatformR=tnameRR(((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pytsh                      compat/dictconfig.pyo000064400000040437152527136320010707 0ustar00 abc@@s ddlmZddlZddlZddlZddlZddlmZej dej Z dZ yddlm Z Wnek rdZ nXdefd YZd efd YZd efd YZdefdYZdefdYZeZdZdS(i(tabsolute_importN(tsixs^[a-z_][a-z0-9_]*$cC@s,tj|}|s(td|ntS(Ns!Not a valid Python identifier: %r(t IDENTIFIERtmatcht ValueErrortTrue(tstm((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt valid_ident"s(t _checkLevelcC@spt|tr|}nTt||kr\|tjkrLtd|ntj|}ntd||S(NsUnknown level: %rs*Level not an integer or a valid string: %r(t isinstancetinttstrtloggingt _levelNamesRt TypeError(tleveltrv((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR .s  tConvertingDictcB@s/eZdZdZddZddZRS(s A converting dictionary wrapper.cC@sqtj||}|jj|}||k rm|||[a-z]+)://(?P.*)$s ^\s*(\w+)\s*s^\.\s*(\w+)\s*s^\[\s*(\w+)\s*\]\s*s^\d+$t ext_converttextt cfg_converttcfgcC@st||_||j_dS(N(RtconfigR(RR.((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt__init__sc C@s|jd}|jd}yy|j|}x_|D]W}|d|7}yt||}Wq7tk r|j|t||}q7Xq7W|SWnVtk rtjd\}}td||f}|||_ |_ |nXdS(s` Resolve strings to objects using standard import and attribute syntax. t.iisCannot resolve %r: %sN( tsplitR!timportertgetattrtAttributeErrort ImportErrortsystexc_infoRt __cause__t __traceback__( RRtnametusedtfoundtfragtettbtv((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytresolves"    cC@s |j|S(s*Default converter for the ext:// protocol.(RA(RR((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR*scC@sO|}|jj|}|dkr7td|n||j}|j|jd}x|rJ|jj|}|r||jd}n|jj|}|r|jd}|j j|s||}qyt |}||}Wqt k r||}qXn|r1||j}qatd||fqaW|S(s*Default converter for the cfg:// protocol.sUnable to convert %risUnable to convert %r at %rN( t WORD_PATTERNRR%RtendR.tgroupst DOT_PATTERNt INDEX_PATTERNt DIGIT_PATTERNR R(RRtrestRtdR'tn((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR,s2     cC@s2t|t r7t|tr7t|}||_nt|t rnt|trnt|}||_nt|t rt|trt|}||_nt|tj r.|j j |}|r.|j }|d}|j j|d}|r+|d}t||}||}q+q.n|S(s Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. tprefixtsuffixN(R RRRRR&RR(Rt string_typestCONVERT_PATTERNRt groupdicttvalue_convertersRR%R3(RRRRIRKt converterRL((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRs*         c@sjd}t|d rUttdrUt|tjkrU|j|}njdd}tfdD}||}|rx-|jD]\}}t |||qWn|S(s1Configure an object with a user-supplied factory.s()t__call__t ClassTypeR0c3@s+|]!}t|r||fVqdS(N(R(t.0tk(R.(s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pys sN( R!thasattrttypesRRSRAR%Rtitemstsetattr(RR.tctpropstkwargsRR:R((R.s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytconfigure_customs4 cC@s"t|trt|}n|S(s0Utility function which converts lists to tuples.(R R&R((RR((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytas_tuples(R"R#R$tretcompileRNRBRERFRGRPt __import__R2R/RAR*R,RR]R^(((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR)s"     "  tDictConfiguratorcB@sheZdZdZdZdZdZdZdZe dZ e dZ e d Z RS( s] Configure logging using a dictionary-like object to describe the configuration. cC@sq|j}d|kr$tdn|ddkrKtd|dn|jdt}i}tjz|r|jd|}tjd dkrFx|D]}|tj krtd |qyItj |}||}|jd d}|r|j t |nWqt k r>} td || fqXqWn|jd |} xU| D]M}y|j|| |tWq_t k r} td || fq_Xq_W|jdd} | r^y|j| tWqt k r} td| qXq^nV|jdt} tj jtj2|jd|} xU| D]M}y|j| || |RfRgtdisable_existingRiRjtexistingt child_loggerstitprefixedtpflent num_existingtlogtlogger((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt configures                         cC@sd|kr|d}y|j|}Wqtk r}dt|krSn|jd|d<||d<|j|}qXn6|jdd}|jdd}tj||}|S(s(Configure a formatter from a dictionary.s()s'format'tformattfmttdatefmtN(R]RR R!RR%R t Formatter(RR.tfactoryRtteRtdfmt((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRus   cC@sCd|kr|j|}n!|jdd}tj|}|S(s%Configure a filter from a dictionary.s()R:t(R]RR tFilter(RR.RR:((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRvs  cC@s]xV|D]N}y|j|jd|Wqtk rT}td||fqXqWdS(s/Add filters to a filterer from a list of names.RjsUnable to add filter %r: %sN(t addFilterR.RpR(RtfiltererRjtfR>((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt add_filterss  c @sjdd}|r\y|jd|}Wq\tk rX}td||fq\Xnjdd}jdd}dkrjd}t|d rttdrt|tjkr|j |}n|}n|j jd }t |t j j rsd krsy|jd d d ss'stream'tstreamtstrmN(R!R%R.RpRRVRWRRSRAt issubclassR Ret MemoryHandlert SMTPHandlerR^t SysLogHandlerRRR t setFormatterRoR R( RR.RR>RRjRZRtklassR\RR((R.s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRxsX 4     cC@s]xV|D]N}y|j|jd|Wqtk rT}td||fqXqWdS(s.Add handlers to a logger from a list of names.ResUnable to add handler %r: %sN(t addHandlerR.RpR(RRRethR>((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt add_handlers s  cC@s|jdd}|dk r4|jt|n|sx|jD]}|j|qEW|jdd}|r|j||n|jdd}|r|j||qndS(sU Perform configuration which is common to root and non-root loggers. RReRjN(RR%RoR Ret removeHandlerRR(RRR.RdRRReRj((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytcommon_logger_configs cC@sPtj|}|j||||jdd}|dk rL||_ndS(s.Configure a non-root logger from a dictionary.RN(R t getLoggerRRR%R(RR:R.RdRR((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRq#s  cC@s#tj}|j|||dS(s*Configure a root logger from a dictionary.N(R RR(RR.RdRg((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRr+s ( R"R#R$RRuRvRRxRRkRRqRr(((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRbs   5   cC@st|jdS(s%Configure logging using a dictionary.N(tdictConfigClassR(R.((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt dictConfig3s(t __future__Rtlogging.handlersR R_R6RWt pip._vendorRR`tIRRR R5RRR&RR(RtobjectR)RbRR(((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyts&       & compat/__init__.pyo000064400000012127152527136320010330 0ustar00 abc @`sdZddlmZmZddlZddlZddlmZyddlm Z Wn!e k r{ddl m Z nXyddl mZWn!e k rddlmZnXyddlZWn]e k r#yddlmZWq$e k rddlZeje_eje_q$XnXyddlZdZWn*e k ridd lmZd ZnXd d d dddddddg Zejd)kreZddlmZn3ddl Z e!e dZere jZndZejd*krdZ#e$dZ%ndZ#e$dZ%dZ&dZ'dZ(d+Z)ejd,krbe)d-7Z)nej*j+d%pej*d&koej,d'kZ-d(Z.dS(.sKStuff that differs in different Python versions and platform distributions.i(tabsolute_importtdivisionN(t text_type(t dictConfig(t OrderedDict(t ipaddresscC`s1tjdtjdg}ttt|S(Ntstdlibt platstdlib(t sysconfigtget_pathtsettfiltertbool(tpaths((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyt get_stdlib"s (RcC`s=tjdttjdtdtg}ttt|S(Nt standard_libt plat_specific(Rtget_python_libtTrueR R R (R ((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyR+stlogging_dictConfigRt uses_pycachetconsole_to_strt native_strt get_path_uidt stdlib_pkgstWINDOWStsamefileRii(tcache_from_sourceRcC`s9y|jtjjSWntk r4|jdSXdS(Ntutf_8(tdecodetsyst __stdout__tencodingtUnicodeDecodeError(ts((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRGs cC`s/t|tr+|jd|r$dndS|S(Nsutf-8treplacetstrict(t isinstancetbytesR(R"R#((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRMscC`s|S(N((R"((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRSscC`s t|tr|jdS|S(Nsutf-8(R%Rtencode(R"R#((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRVs cC`sHt|dr|jS|j|j|jddd}|dSdS(Nt total_secondsiii ii@Bi@B(thasattrR(t microsecondstsecondstdays(ttdtval((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyR(]s #cC`sttdrMtj|tjtjB}tj|j}tj|n7tjj |sttj |j}nt d||S(s) Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. t O_NOFOLLOWs1%s is a symlink; Will not return uid for symlinks( R)tostopentO_RDONLYR/tfstattst_uidtclosetpathtislinktstattOSError(R6tfdtfile_uid((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRes  cC`sAtjj|}|jdr=|jdr=|d}n|S(sl Expand ~ and ~user constructions. Includes a workaround for http://bugs.python.org/issue14768 s~/s//i(R0R6t expandusert startswith(R6texpanded((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyR<s tpythontwsgirefiitargparsetwintclitntcC`sottjdr%tjj||Stjjtjj|}tjjtjj|}||kSdS(s>Provide an alternative for os.path.samefile on Windows/Python2RN(R)R0R6Rtnormcasetabspath(tfile1tfile2tpath1tpath2((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pyRs (ii(i(R?R@(ii(RA(/t__doc__t __future__RRR0Rtpip._vendor.sixRtlogging.configRRt ImportErrortpip.compat.dictconfigt collectionsRtpip._vendor.ordereddictRt pip._vendortipaddrt IPAddresst ip_addresst IPNetworkt ip_networkRRt distutilst__all__t version_infoRRtimportlib.utilRtimpR)tNoneRtFalseRR(RR<RtplatformR=tnameRR(((s7/usr/lib/python2.7/site-packages/pip/compat/__init__.pytsh                      compat/dictconfig.pyc000064400000040437152527136320010673 0ustar00 abc@@s ddlmZddlZddlZddlZddlZddlmZej dej Z dZ yddlm Z Wnek rdZ nXdefd YZd efd YZd efd YZdefdYZdefdYZeZdZdS(i(tabsolute_importN(tsixs^[a-z_][a-z0-9_]*$cC@s,tj|}|s(td|ntS(Ns!Not a valid Python identifier: %r(t IDENTIFIERtmatcht ValueErrortTrue(tstm((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt valid_ident"s(t _checkLevelcC@spt|tr|}nTt||kr\|tjkrLtd|ntj|}ntd||S(NsUnknown level: %rs*Level not an integer or a valid string: %r(t isinstancetinttstrtloggingt _levelNamesRt TypeError(tleveltrv((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR .s  tConvertingDictcB@s/eZdZdZddZddZRS(s A converting dictionary wrapper.cC@sqtj||}|jj|}||k rm|||[a-z]+)://(?P.*)$s ^\s*(\w+)\s*s^\.\s*(\w+)\s*s^\[\s*(\w+)\s*\]\s*s^\d+$t ext_converttextt cfg_converttcfgcC@st||_||j_dS(N(RtconfigR(RR.((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt__init__sc C@s|jd}|jd}yy|j|}x_|D]W}|d|7}yt||}Wq7tk r|j|t||}q7Xq7W|SWnVtk rtjd\}}td||f}|||_ |_ |nXdS(s` Resolve strings to objects using standard import and attribute syntax. t.iisCannot resolve %r: %sN( tsplitR!timportertgetattrtAttributeErrort ImportErrortsystexc_infoRt __cause__t __traceback__( RRtnametusedtfoundtfragtettbtv((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytresolves"    cC@s |j|S(s*Default converter for the ext:// protocol.(RA(RR((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR*scC@sO|}|jj|}|dkr7td|n||j}|j|jd}x|rJ|jj|}|r||jd}n|jj|}|r|jd}|j j|s||}qyt |}||}Wqt k r||}qXn|r1||j}qatd||fqaW|S(s*Default converter for the cfg:// protocol.sUnable to convert %risUnable to convert %r at %rN( t WORD_PATTERNRR%RtendR.tgroupst DOT_PATTERNt INDEX_PATTERNt DIGIT_PATTERNR R(RRtrestRtdR'tn((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR,s2     cC@s2t|t r7t|tr7t|}||_nt|t rnt|trnt|}||_nt|t rt|trt|}||_nt|tj r.|j j |}|r.|j }|d}|j j|d}|r+|d}t||}||}q+q.n|S(s Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. tprefixtsuffixN(R RRRRR&RR(Rt string_typestCONVERT_PATTERNRt groupdicttvalue_convertersRR%R3(RRRRIRKt converterRL((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRs*         c@sjd}t|d rUttdrUt|tjkrU|j|}njdd}tfdD}||}|rx-|jD]\}}t |||qWn|S(s1Configure an object with a user-supplied factory.s()t__call__t ClassTypeR0c3@s+|]!}t|r||fVqdS(N(R(t.0tk(R.(s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pys sN( R!thasattrttypesRRSRAR%Rtitemstsetattr(RR.tctpropstkwargsRR:R((R.s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytconfigure_customs4 cC@s"t|trt|}n|S(s0Utility function which converts lists to tuples.(R R&R((RR((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytas_tuples(R"R#R$tretcompileRNRBRERFRGRPt __import__R2R/RAR*R,RR]R^(((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyR)s"     "  tDictConfiguratorcB@sheZdZdZdZdZdZdZdZe dZ e dZ e d Z RS( s] Configure logging using a dictionary-like object to describe the configuration. cC@sq|j}d|kr$tdn|ddkrKtd|dn|jdt}i}tjz|r|jd|}tjd dkrFx|D]}|tj krtd |qyItj |}||}|jd d}|r|j t |nWqt k r>} td || fqXqWn|jd |} xU| D]M}y|j|| |tWq_t k r} td || fq_Xq_W|jdd} | r^y|j| tWqt k r} td| qXq^nV|jdt} tj jtj2|jd|} xU| D]M}y|j| || |RfRgtdisable_existingRiRjtexistingt child_loggerstitprefixedtpflent num_existingtlogtlogger((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt configures                         cC@sd|kr|d}y|j|}Wqtk r}dt|krSn|jd|d<||d<|j|}qXn6|jdd}|jdd}tj||}|S(s(Configure a formatter from a dictionary.s()s'format'tformattfmttdatefmtN(R]RR R!RR%R t Formatter(RR.tfactoryRtteRtdfmt((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRus   cC@sCd|kr|j|}n!|jdd}tj|}|S(s%Configure a filter from a dictionary.s()R:t(R]RR tFilter(RR.RR:((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRvs  cC@s]xV|D]N}y|j|jd|Wqtk rT}td||fqXqWdS(s/Add filters to a filterer from a list of names.RjsUnable to add filter %r: %sN(t addFilterR.RpR(RtfiltererRjtfR>((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt add_filterss  c @sjdd}|r\y|jd|}Wq\tk rX}td||fq\Xnjdd}jdd}dkrjd}t|d rttdrt|tjkr|j |}n|}n|j jd }t |t j j rsd krsy|jd d d ss'stream'tstreamtstrmN(R!R%R.RpRRVRWRRSRAt issubclassR Ret MemoryHandlert SMTPHandlerR^t SysLogHandlerRRR t setFormatterRoR R( RR.RR>RRjRZRtklassR\RR((R.s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRxsX 4     cC@s]xV|D]N}y|j|jd|Wqtk rT}td||fqXqWdS(s.Add handlers to a logger from a list of names.ResUnable to add handler %r: %sN(t addHandlerR.RpR(RRRethR>((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt add_handlers s  cC@s|jdd}|dk r4|jt|n|sx|jD]}|j|qEW|jdd}|r|j||n|jdd}|r|j||qndS(sU Perform configuration which is common to root and non-root loggers. RReRjN(RR%RoR Ret removeHandlerRR(RRR.RdRRReRj((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pytcommon_logger_configs cC@sPtj|}|j||||jdd}|dk rL||_ndS(s.Configure a non-root logger from a dictionary.RN(R t getLoggerRRR%R(RR:R.RdRR((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRq#s  cC@s#tj}|j|||dS(s*Configure a root logger from a dictionary.N(R RR(RR.RdRg((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRr+s ( R"R#R$RRuRvRRxRRkRRqRr(((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyRbs   5   cC@st|jdS(s%Configure logging using a dictionary.N(tdictConfigClassR(R.((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyt dictConfig3s(t __future__Rtlogging.handlersR R_R6RWt pip._vendorRR`tIRRR R5RRR&RR(RtobjectR)RbRR(((s9/usr/lib/python2.7/site-packages/pip/compat/dictconfig.pyts&       & compat/__init__.py000064400000011100152527136320010137 0ustar00"""Stuff that differs in different Python versions and platform distributions.""" from __future__ import absolute_import, division import os import sys from pip._vendor.six import text_type try: from logging.config import dictConfig as logging_dictConfig except ImportError: from pip.compat.dictconfig import dictConfig as logging_dictConfig try: from collections import OrderedDict except ImportError: from pip._vendor.ordereddict import OrderedDict try: import ipaddress except ImportError: try: from pip._vendor import ipaddress except ImportError: import ipaddr as ipaddress ipaddress.ip_address = ipaddress.IPAddress ipaddress.ip_network = ipaddress.IPNetwork try: import sysconfig def get_stdlib(): paths = [ sysconfig.get_path("stdlib"), sysconfig.get_path("platstdlib"), ] return set(filter(bool, paths)) except ImportError: from distutils import sysconfig def get_stdlib(): paths = [ sysconfig.get_python_lib(standard_lib=True), sysconfig.get_python_lib(standard_lib=True, plat_specific=True), ] return set(filter(bool, paths)) __all__ = [ "logging_dictConfig", "ipaddress", "uses_pycache", "console_to_str", "native_str", "get_path_uid", "stdlib_pkgs", "WINDOWS", "samefile", "OrderedDict", ] if sys.version_info >= (3, 4): uses_pycache = True from importlib.util import cache_from_source else: import imp uses_pycache = hasattr(imp, 'cache_from_source') if uses_pycache: cache_from_source = imp.cache_from_source else: cache_from_source = None if sys.version_info >= (3,): def console_to_str(s): try: return s.decode(sys.__stdout__.encoding) except UnicodeDecodeError: return s.decode('utf_8') def native_str(s, replace=False): if isinstance(s, bytes): return s.decode('utf-8', 'replace' if replace else 'strict') return s else: def console_to_str(s): return s def native_str(s, replace=False): # Replace is ignored -- unicode to UTF-8 can't fail if isinstance(s, text_type): return s.encode('utf-8') return s def total_seconds(td): if hasattr(td, "total_seconds"): return td.total_seconds() else: val = td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6 return val / 10 ** 6 def get_path_uid(path): """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. """ if hasattr(os, 'O_NOFOLLOW'): fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) file_uid = os.fstat(fd).st_uid os.close(fd) else: # AIX and Jython # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW if not os.path.islink(path): # older versions of Jython don't have `os.fstat` file_uid = os.stat(path).st_uid else: # raise OSError for parity with os.O_NOFOLLOW above raise OSError( "%s is a symlink; Will not return uid for symlinks" % path ) return file_uid def expanduser(path): """ Expand ~ and ~user constructions. Includes a workaround for http://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path.startswith('~/') and expanded.startswith('//'): expanded = expanded[1:] return expanded # packages in the stdlib that may have installation metadata, but should not be # considered 'installed'. this theoretically could be determined based on # dist.location (py27:`sysconfig.get_paths()['stdlib']`, # py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may # make this ineffective, so hard-coding stdlib_pkgs = ('python', 'wsgiref') if sys.version_info >= (2, 7): stdlib_pkgs += ('argparse',) # windows detection, covers cpython and ironpython WINDOWS = (sys.platform.startswith("win") or (sys.platform == 'cli' and os.name == 'nt')) def samefile(file1, file2): """Provide an alternative for os.path.samefile on Windows/Python2""" if hasattr(os.path, 'samefile'): return os.path.samefile(file1, file2) else: path1 = os.path.normcase(os.path.abspath(file1)) path2 = os.path.normcase(os.path.abspath(file2)) return path1 == path2 pep425tags.py000064400000025344152527136320007032 0ustar00"""Generate and work with PEP 425 Compatibility Tags.""" from __future__ import absolute_import import re import sys import warnings import platform import logging try: import sysconfig except ImportError: # pragma nocover # Python < 2.7 import distutils.sysconfig as sysconfig import distutils.util from pip.compat import OrderedDict import pip.utils.glibc logger = logging.getLogger(__name__) _osx_arch_pat = re.compile(r'(.+)_(\d+)_(\d+)_(.+)') def get_config_var(var): try: return sysconfig.get_config_var(var) except IOError as e: # Issue #1074 warnings.warn("{0}".format(e), RuntimeWarning) return None def get_abbr_impl(): """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return pyimpl def get_impl_ver(): """Return implementation version.""" impl_ver = get_config_var("py_version_nodot") if not impl_ver or get_abbr_impl() == 'pp': impl_ver = ''.join(map(str, get_impl_version_info())) return impl_ver def get_impl_version_info(): """Return sys.version_info-like tuple for use in decrementing the minor version.""" if get_abbr_impl() == 'pp': # as per https://github.com/pypa/pip/issues/2882 return (sys.version_info[0], sys.pypy_version_info.major, sys.pypy_version_info.minor) else: return sys.version_info[0], sys.version_info[1] def get_impl_tag(): """ Returns the Tag for this specific implementation. """ return "{0}{1}".format(get_abbr_impl(), get_impl_ver()) def get_flag(var, fallback, expected=True, warn=True): """Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.""" val = get_config_var(var) if val is None: if warn: logger.debug("Config variable '%s' is unset, Python ABI tag may " "be incorrect", var) return fallback() return val == expected def get_abi_tag(): """Return the ABI tag based on SOABI (if available) or emulate SOABI (CPython 2, PyPy).""" soabi = get_config_var('SOABI') impl = get_abbr_impl() if not soabi and impl in ('cp', 'pp') and hasattr(sys, 'maxunicode'): d = '' m = '' u = '' if get_flag('Py_DEBUG', lambda: hasattr(sys, 'gettotalrefcount'), warn=(impl == 'cp')): d = 'd' if get_flag('WITH_PYMALLOC', lambda: impl == 'cp', warn=(impl == 'cp')): m = 'm' if get_flag('Py_UNICODE_SIZE', lambda: sys.maxunicode == 0x10ffff, expected=4, warn=(impl == 'cp' and sys.version_info < (3, 3))) \ and sys.version_info < (3, 3): u = 'u' abi = '%s%s%s%s%s' % (impl, get_impl_ver(), d, m, u) elif soabi and soabi.startswith('cpython-'): abi = 'cp' + soabi.split('-')[1] elif soabi: abi = soabi.replace('.', '_').replace('-', '_') else: abi = None return abi def _is_running_32bit(): return sys.maxsize == 2147483647 def get_platform(): """Return our platform name 'win32', 'linux_x86_64'""" if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be significantly older than the user's current machine. release, _, machine = platform.mac_ver() split_ver = release.split('.') if machine == "x86_64" and _is_running_32bit(): machine = "i386" elif machine == "ppc64" and _is_running_32bit(): machine = "ppc" return 'macosx_{0}_{1}_{2}'.format(split_ver[0], split_ver[1], machine) # XXX remove distutils dependency result = distutils.util.get_platform().replace('.', '_').replace('-', '_') if result == "linux_x86_64" and _is_running_32bit(): # 32 bit Python program (running on a 64 bit Linux): pip should only # install and run 32 bit compiled extensions in that case. result = "linux_i686" return result def is_manylinux1_compatible(): # Only Linux, and only x86-64 / i686 if get_platform() not in ("linux_x86_64", "linux_i686"): return False # Check for presence of _manylinux module try: import _manylinux return bool(_manylinux.manylinux1_compatible) except (ImportError, AttributeError): # Fall through to heuristic check below pass # Check glibc version. CentOS 5 uses glibc 2.5. return pip.utils.glibc.have_compatible_glibc(2, 5) def get_darwin_arches(major, minor, machine): """Return a list of supported arches (including group arches) for the given major, minor and machine architecture of an macOS machine. """ arches = [] def _supports_arch(major, minor, arch): # Looking at the application support for macOS versions in the chart # provided by https://en.wikipedia.org/wiki/OS_X#Versions it appears # our timeline looks roughly like: # # 10.0 - Introduces ppc support. # 10.4 - Introduces ppc64, i386, and x86_64 support, however the ppc64 # and x86_64 support is CLI only, and cannot be used for GUI # applications. # 10.5 - Extends ppc64 and x86_64 support to cover GUI applications. # 10.6 - Drops support for ppc64 # 10.7 - Drops support for ppc # # Given that we do not know if we're installing a CLI or a GUI # application, we must be conservative and assume it might be a GUI # application and behave as if ppc64 and x86_64 support did not occur # until 10.5. # # Note: The above information is taken from the "Application support" # column in the chart not the "Processor support" since I believe # that we care about what instruction sets an application can use # not which processors the OS supports. if arch == 'ppc': return (major, minor) <= (10, 5) if arch == 'ppc64': return (major, minor) == (10, 5) if arch == 'i386': return (major, minor) >= (10, 4) if arch == 'x86_64': return (major, minor) >= (10, 5) if arch in groups: for garch in groups[arch]: if _supports_arch(major, minor, garch): return True return False groups = OrderedDict([ ("fat", ("i386", "ppc")), ("intel", ("x86_64", "i386")), ("fat64", ("x86_64", "ppc64")), ("fat32", ("x86_64", "i386", "ppc")), ]) if _supports_arch(major, minor, machine): arches.append(machine) for garch in groups: if machine in groups[garch] and _supports_arch(major, minor, garch): arches.append(garch) arches.append('universal') return arches def get_supported(versions=None, noarch=False, platform=None, impl=None, abi=None): """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. :param platform: specify the exact platform you want valid tags for, or None. If None, use the local system platform. :param impl: specify the exact implementation you want valid tags for, or None. If None, use the local interpreter impl. :param abi: specify the exact abi you want valid tags for, or None. If None, use the local interpreter abi. """ supported = [] # Versions must be given with respect to the preference if versions is None: versions = [] version_info = get_impl_version_info() major = version_info[:-1] # Support all previous minor Python versions. for minor in range(version_info[-1], -1, -1): versions.append(''.join(map(str, major + (minor,)))) impl = impl or get_abbr_impl() abis = [] abi = abi or get_abi_tag() if abi: abis[0:0] = [abi] abi3s = set() import imp for suffix in imp.get_suffixes(): if suffix[0].startswith('.abi'): abi3s.add(suffix[0].split('.', 2)[1]) abis.extend(sorted(list(abi3s))) abis.append('none') if not noarch: arch = platform or get_platform() if arch.startswith('macosx'): # support macosx-10.6-intel on macosx-10.9-x86_64 match = _osx_arch_pat.match(arch) if match: name, major, minor, actual_arch = match.groups() tpl = '{0}_{1}_%i_%s'.format(name, major) arches = [] for m in reversed(range(int(minor) + 1)): for a in get_darwin_arches(int(major), m, actual_arch): arches.append(tpl % (m, a)) else: # arch pattern didn't match (?!) arches = [arch] elif platform is None and is_manylinux1_compatible(): arches = [arch.replace('linux', 'manylinux1'), arch] else: arches = [arch] # Current version, current API (built specifically for our Python): for abi in abis: for arch in arches: supported.append(('%s%s' % (impl, versions[0]), abi, arch)) # abi3 modules compatible with older version of Python for version in versions[1:]: # abi3 was introduced in Python 3.2 if version in ('31', '30'): break for abi in abi3s: # empty set if not Python 3 for arch in arches: supported.append(("%s%s" % (impl, version), abi, arch)) # Has binaries, does not use the Python API: for arch in arches: supported.append(('py%s' % (versions[0][0]), 'none', arch)) # No abi / arch, but requires our implementation: supported.append(('%s%s' % (impl, versions[0]), 'none', 'any')) # Tagged specifically as being cross-version compatible # (with just the major version specified) supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any')) # No abi / arch, generic Python for i, version in enumerate(versions): supported.append(('py%s' % (version,), 'none', 'any')) if i == 0: supported.append(('py%s' % (version[0]), 'none', 'any')) return supported supported_tags = get_supported() supported_tags_noarch = get_supported(noarch=True) implementation_tag = get_impl_tag() vcs/bazaar.pyo000064400000011236152527136320007341 0ustar00 abc@@sddlmZddlZddlZddlZyddlmZWnek rgddl ZnXddl m Z m Z ddl mZmZddlmZejeZdefdYZejedS( i(tabsolute_importN(tparse(trmtreet display_path(tvcstVersionControl(t path_to_urltBazaarcB@s}eZdZdZdZdZdd Zd Zd Z d Z d Z dZ dZ dZdZdZRS(tbzrs.bzrtbranchsbzr+https bzr+httpssbzr+sshsbzr+sftpsbzr+ftpsbzr+lpcO@s[tt|j|||ttddrWtjjdgtjjdgndS(Nt uses_fragmenttlp( tsuperRt__init__tgetattrt urllib_parsetNoneR textendtnon_hierarchical(tselfturltargstkwargs((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR scC@sstjdd}|j|tjj|r>t|nz#|jd|gd|dtWdt|XdS(sU Export the Bazaar repository at the url to the destination location s-exportspip-texporttcwdt show_stdoutN( ttempfiletmkdtemptunpacktostpathtexistsRt run_commandtFalse(Rtlocationttemp_dir((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR&s   cC@s|jd|gd|dS(NtswitchR(R (RtdestRt rev_options((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR$5scC@s!|jddg|d|dS(Ntpulls-qR(R (RR%R&((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytupdate8scC@s|j\}}|r1d|g}d|}n g}d}|j||||rtjd||t||jddg|||gndS(Ns-rs (to revision %s)tsChecking out %s%s to %sR s-q(t get_url_revtcheck_destinationtloggertinfoRR (RR%RtrevR&t rev_display((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytobtain;s   cC@sAtt|j\}}|jdr7d|}n||fS(Nsssh://sbzr+(R RR*t startswith(RRR.((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR*Ls cC@s|jdgdtd|}xp|jD]b}|j}xMdD]E}|j|rD|j|d}|j|rt|S|SqDWq+WdS(NR-RRscheckout of branch: sparent branch: i(scheckout of branch: sparent branch: ( R R!t splitlineststripR1tsplitt_is_local_repositoryRR(RR"turlstlinetxtrepo((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytget_urlSs    cC@s,|jdgdtd|}|jdS(NtrevnoRRi(R R!R2(RR"trevision((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyt get_revision`scC@sw|j|}|sdS|jjds;d|}n|jjddd}|j|}d|||fS(Nsbzr:sbzr+t-iis %s@%s#egg=%s(R:RtlowerR1tegg_nameR4R=(RtdistR"R9tegg_project_namet current_rev((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytget_src_requirementes cC@stS(s&Always assume the versions don't match(R!(RR%R&((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyt check_versionos(Rsbzr+https bzr+httpssbzr+sshsbzr+sftpsbzr+ftpsbzr+lpN(t__name__t __module__tnametdirnamet repo_nametschemesRR RR$R(R0R*R:R=RDRE(((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyRs        (t __future__RtloggingRRturllibRRt ImportErrorturlparset pip.utilsRRtpip.vcsRRt pip.downloadRt getLoggerRFR,Rtregister(((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyts    _vcs/bazaar.py000064400000007333152527136320007165 0ustar00from __future__ import absolute_import import logging import os import tempfile # TODO: Get this into six.moves.urllib.parse try: from urllib import parse as urllib_parse except ImportError: import urlparse as urllib_parse from pip.utils import rmtree, display_path from pip.vcs import vcs, VersionControl from pip.download import path_to_url logger = logging.getLogger(__name__) class Bazaar(VersionControl): name = 'bzr' dirname = '.bzr' repo_name = 'branch' schemes = ( 'bzr', 'bzr+http', 'bzr+https', 'bzr+ssh', 'bzr+sftp', 'bzr+ftp', 'bzr+lp', ) def __init__(self, url=None, *args, **kwargs): super(Bazaar, self).__init__(url, *args, **kwargs) # Python >= 2.7.4, 3.3 doesn't have uses_fragment or non_hierarchical # Register lp but do not expose as a scheme to support bzr+lp. if getattr(urllib_parse, 'uses_fragment', None): urllib_parse.uses_fragment.extend(['lp']) urllib_parse.non_hierarchical.extend(['lp']) def export(self, location): """ Export the Bazaar repository at the url to the destination location """ temp_dir = tempfile.mkdtemp('-export', 'pip-') self.unpack(temp_dir) if os.path.exists(location): # Remove the location to make sure Bazaar can export it correctly rmtree(location) try: self.run_command(['export', location], cwd=temp_dir, show_stdout=False) finally: rmtree(temp_dir) def switch(self, dest, url, rev_options): self.run_command(['switch', url], cwd=dest) def update(self, dest, rev_options): self.run_command(['pull', '-q'] + rev_options, cwd=dest) def obtain(self, dest): url, rev = self.get_url_rev() if rev: rev_options = ['-r', rev] rev_display = ' (to revision %s)' % rev else: rev_options = [] rev_display = '' if self.check_destination(dest, url, rev_options, rev_display): logger.info( 'Checking out %s%s to %s', url, rev_display, display_path(dest), ) self.run_command(['branch', '-q'] + rev_options + [url, dest]) def get_url_rev(self): # hotfix the URL scheme after removing bzr+ from bzr+ssh:// readd it url, rev = super(Bazaar, self).get_url_rev() if url.startswith('ssh://'): url = 'bzr+' + url return url, rev def get_url(self, location): urls = self.run_command(['info'], show_stdout=False, cwd=location) for line in urls.splitlines(): line = line.strip() for x in ('checkout of branch: ', 'parent branch: '): if line.startswith(x): repo = line.split(x)[1] if self._is_local_repository(repo): return path_to_url(repo) return repo return None def get_revision(self, location): revision = self.run_command( ['revno'], show_stdout=False, cwd=location) return revision.splitlines()[-1] def get_src_requirement(self, dist, location): repo = self.get_url(location) if not repo: return None if not repo.lower().startswith('bzr:'): repo = 'bzr+' + repo egg_project_name = dist.egg_name().split('-', 1)[0] current_rev = self.get_revision(location) return '%s@%s#egg=%s' % (repo, current_rev, egg_project_name) def check_version(self, dest, rev_options): """Always assume the versions don't match""" return False vcs.register(Bazaar) vcs/mercurial.pyc000064400000010776152527136320010060 0ustar00 abc@@sddlmZddlZddlZddlZddlmZmZddlm Z m Z ddl m Z ddl mZejeZde fdYZe jedS( i(tabsolute_importN(t display_pathtrmtree(tvcstVersionControl(t path_to_url(t configparsert MercurialcB@sqeZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZRS(thgs.hgtcloneshg+httpshg+httpsshg+sshshg+static-httpcC@sTtjdd}|j|z#|jd|gdtd|Wdt|XdS(s?Export the Hg repository at the url to the destination locations-exportspip-tarchivet show_stdouttcwdN(ttempfiletmkdtemptunpackt run_commandtFalseR(tselftlocationttemp_dir((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytexports  cC@stjj||jd}tj}yI|j||jdd|t|d}|j |WdQXWn/t tj fk r}t j d||nX|jddg|d|dS( Nthgrctpathstdefaulttws/Could not switch Mercurial repository to %s: %stupdates-qR (tostpathtjointdirnameRtSafeConfigParsertreadtsettopentwritetOSErrortNoSectionErrortloggertwarningR(Rtdestturlt rev_optionst repo_configtconfigt config_filetexc((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytswitch s  cC@s:|jddgd||jddg|d|dS(Ntpulls-qR R(R(RR(R*((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyR/scC@s|j\}}|r.|g}d|}n g}d}|j||||rtjd||t||jddd||g|jddg|d|ndS( Ns (to revision %s)tsCloning hg %s%s to %sR s --noupdates-qRR (t get_url_revtcheck_destinationR&tinfoRR(RR(R)trevR*t rev_display((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytobtain3s   cC@sO|jddgdtd|j}|j|rEt|}n|jS(Nt showconfigs paths.defaultR R (RRtstript_is_local_repositoryR(RRR)((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytget_urlEs  cC@s+|jddgdtd|j}|S(Ntparentss--template={rev}R R (RRR9(RRtcurrent_revision((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyt get_revisionMs cC@s+|jddgdtd|j}|S(NR<s--template={node}R R (RRR9(RRtcurrent_rev_hash((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytget_revision_hashSs cC@sw|j|}|jjds1d|}n|jjddd}|sWdS|j|}d|||fS(Nshg:shg+t-iis %s@%s#egg=%s(R;tlowert startswithtegg_nametsplittNoneR@(RtdistRtrepotegg_project_nameR?((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytget_src_requirementYs cC@stS(s&Always assume the versions don't match(R(RR(R*((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyt check_versioncs(Rshg+httpshg+httpsshg+sshshg+static-http(t__name__t __module__tnameRt repo_nametschemesRR/RR7R;R>R@RJRK(((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyRs       (t __future__RtloggingRR t pip.utilsRRtpip.vcsRRt pip.downloadRtpip._vendor.six.movesRt getLoggerRLR&Rtregister(((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyts   Wvcs/mercurial.py000064400000006620152527136320007706 0ustar00from __future__ import absolute_import import logging import os import tempfile from pip.utils import display_path, rmtree from pip.vcs import vcs, VersionControl from pip.download import path_to_url from pip._vendor.six.moves import configparser logger = logging.getLogger(__name__) class Mercurial(VersionControl): name = 'hg' dirname = '.hg' repo_name = 'clone' schemes = ('hg', 'hg+http', 'hg+https', 'hg+ssh', 'hg+static-http') def export(self, location): """Export the Hg repository at the url to the destination location""" temp_dir = tempfile.mkdtemp('-export', 'pip-') self.unpack(temp_dir) try: self.run_command( ['archive', location], show_stdout=False, cwd=temp_dir) finally: rmtree(temp_dir) def switch(self, dest, url, rev_options): repo_config = os.path.join(dest, self.dirname, 'hgrc') config = configparser.SafeConfigParser() try: config.read(repo_config) config.set('paths', 'default', url) with open(repo_config, 'w') as config_file: config.write(config_file) except (OSError, configparser.NoSectionError) as exc: logger.warning( 'Could not switch Mercurial repository to %s: %s', url, exc, ) else: self.run_command(['update', '-q'] + rev_options, cwd=dest) def update(self, dest, rev_options): self.run_command(['pull', '-q'], cwd=dest) self.run_command(['update', '-q'] + rev_options, cwd=dest) def obtain(self, dest): url, rev = self.get_url_rev() if rev: rev_options = [rev] rev_display = ' (to revision %s)' % rev else: rev_options = [] rev_display = '' if self.check_destination(dest, url, rev_options, rev_display): logger.info( 'Cloning hg %s%s to %s', url, rev_display, display_path(dest), ) self.run_command(['clone', '--noupdate', '-q', url, dest]) self.run_command(['update', '-q'] + rev_options, cwd=dest) def get_url(self, location): url = self.run_command( ['showconfig', 'paths.default'], show_stdout=False, cwd=location).strip() if self._is_local_repository(url): url = path_to_url(url) return url.strip() def get_revision(self, location): current_revision = self.run_command( ['parents', '--template={rev}'], show_stdout=False, cwd=location).strip() return current_revision def get_revision_hash(self, location): current_rev_hash = self.run_command( ['parents', '--template={node}'], show_stdout=False, cwd=location).strip() return current_rev_hash def get_src_requirement(self, dist, location): repo = self.get_url(location) if not repo.lower().startswith('hg:'): repo = 'hg+' + repo egg_project_name = dist.egg_name().split('-', 1)[0] if not repo: return None current_rev_hash = self.get_revision_hash(location) return '%s@%s#egg=%s' % (repo, current_rev_hash, egg_project_name) def check_version(self, dest, rev_options): """Always assume the versions don't match""" return False vcs.register(Mercurial) vcs/__init__.pyc000064400000031653152527136320007631 0ustar00 abc@@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl mZmZmZmZmZddgZejeZd efd YZeZd efd YZd ZdS(s)Handles all VCS (version control) supporti(tabsolute_importN(tparse(t BadCommand(t display_patht backup_dirtcall_subprocesstrmtreetask_path_existstvcstget_src_requirementt VcsSupportcB@seZiZddddddgZdZdZedZed Zed Z d Z ddd Z d Z dZdZRS(tsshtgitthgtbzrtsftptsvncC@sRtjj|jttddr;tjj|jntt|j dS(Nt uses_fragment( t urllib_parset uses_netloctextendtschemestgetattrtNoneRtsuperR t__init__(tself((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyRscC@s |jjS(N(t _registryt__iter__(R((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR$scC@st|jjS(N(tlistRtvalues(R((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytbackends'scC@sg|jD]}|j^q S(N(Rtdirname(Rtbackend((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytdirnames+scC@s.g}x!|jD]}|j|jqW|S(N(RRR(RRR!((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt all_schemes/scC@sbt|ds&tjd|jdS|j|jkr^||j|js  cC@sJxC|jjD]2}|j|rtjd||j|jSqWdS(s Return the name of the version control backend if found at given location, e.g. vcs.get_backend_name('/path/to/vcs/checkout') sDetermine that %s uses VCS: %sN(RRtcontrols_locationR&R)R$R(Rtlocationtvc_type((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytget_backend_nameFs    cC@s*|j}||jkr&|j|SdS(N(tlowerR(RR$((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt get_backendRs cC@s&|j|}|r"|j|SdS(N(R0R2R(RR.R/((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytget_backend_from_locationWs N(R(t __module__RRRRtpropertyRR"R#R+RR,R0R2R3(((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR s   tVersionControlcB@seZdZdZdZddZdZdZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZdZdZdZdZeddddddZedZRS(tcO@s&||_tt|j||dS(N(turlRR6R(RR8targstkwargs((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyRgs cC@s1tjj|\}}|jtjjp0|S(sy posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\folder) (tostpatht splitdrivet startswithtsep(Rtrepotdrivettail((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt_is_local_repositorykscC@s|jddS(Nt/t_(treplace(Rtsurname((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyttranslate_egg_surnameuscC@s tdS(s Export the repository at the url to the destination location i.e. only download the files, without vcs informations N(tNotImplementedError(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytexportysc C@sd}d|jks(t||j|jjddd}tj|\}}}}}d}d|kr|jdd\}}ntj||||df}||fS(sm Returns the correct repository URL and revision by parsing the given repository URL svSorry, '%s' is a malformed VCS url. The format is +://, e.g. svn+http://myrepo/svn/MyApp#egg=MyAppt+it@R7N(R8tAssertionErrortsplitRturlsplitRtrsplitt urlunsplit( Rt error_messageR8tschemetnetlocR<tquerytfragtrev((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt get_url_revs" cC@sH|jdj|j s,td||j||j|fS(sA Returns (url, revision), where both are strings RDsBad directory: %s(trstriptendswithR RMtget_urlt get_revision(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytget_infos cC@stj|jdS(si Normalize a URL for comparison by unquoting it and removing any trailing slash. RD(RtunquoteRY(RR8((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt normalize_urlscC@s|j||j|kS(sV Compare two repo URLs for identity, ignoring incidental differences. (R_(Rturl1turl2((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt compare_urlsscC@s tdS(sx Called when installing or updating an editable package, takes the source path of the checkout. N(RI(Rtdest((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytobtainscC@s tdS(sB Switch the repo at ``dest`` to point to ``URL``. N(RI(RRcR8t rev_options((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytswitchscC@s tdS(sO Update an already-existing repo to the given ``rev_options``. N(RI(RRcRe((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytupdatescC@s tdS(sp Return True if the version is identical to what exists and doesn't need to be updated. N(RI(RRcRe((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt check_versionsc C@smt}t}tjj|rAt}tjjtjj||jr|j|}|j||rt j d|j j t |||j||st jdt ||j ||j||qt jdq>t jd|j|j t ||ddf}qAt jd ||j|j d df}n|rit jd |j|td |d|d}|dkrt jd|j t ||||j|||qi|dkrqi|dkrt jdt |t|t}qi|d krJt|} t jdt || tj|| t}qi|dkritjdqin|S(s Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise. s)%s in %s exists, and has correct URL (%s)sUpdating %s %s%ss$Skipping because already up-to-date.s%s %s in %s exists with URL %ss%(s)witch, (i)gnore, (w)ipe, (b)ackup tstitwtbs0Directory %s already exists, and is not a %s %s.s(i)gnore, (w)ipe, (b)ackup s+The plan is to install the %s repository %ssWhat to do? %siisSwitching %s %s to %s%ss Deleting %ssBacking up %s to %stai(RiRjRkRl(RjRkRl(tTruetFalseR;R<texiststjoinR R[RbR&R)t repo_namettitleRRhtinfoRgR'R$RRfRRtshutiltmovetsystexit( RRcR8Ret rev_displaytcheckouttpromptt existing_urltresponsetdest_dir((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytcheck_destinations$                  cC@s0tjj|rt|n|j|dS(sq Clean up current location and download the url repository (and vcs infos) into location N(R;R<RpRRd(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytunpacks cC@s tdS(s Return a string representing the requirement needed to redownload the files currently present in location, something like: {repository_url}@{revision}#egg={project_name}-{version_identifier} N(RI(RtdistR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR scC@s tdS(s_ Return the url used at location Used in get_info or check_destination N(RI(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR[)scC@s tdS(s_ Return the current revision of the files at location Used in get_info N(RI(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR\0straisec C@su|jg|}y t|||||||SWn>tk rp}|jtjkrjtd|jqqnXdS(s Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available sCannot find command %rN(R$RtOSErrorterrnotENOENTR( Rtcmdt show_stdouttcwdt on_returncodet command_desct extra_environtspinnerte((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt run_command7s   cC@sDtjd||j|jtjj||j}tjj|S(s Check if a location is controlled by the vcs. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. sChecking in %s for %s (%s)...(R&R)R R$R;R<RqRp(R*R.R<((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR-Ns (N(R(R4R$R RRRRCRHRJRXR]R_RbRdRfRgRhRRR R[R\RnRt classmethodR-(((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR6as2            U  cC@sztj|}|r`y|j||SWq`tk r\tjd||j|jSXntjd||jS(NsPcannot determine version of editable source in %s (%s command not found in path)stcannot determine version of editable source in %s (is not SVN checkout, Git clone, Mercurial clone or Bazaar branch)(RR3R RR&R'R$tas_requirement(RR.tversion_control((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR [s    (t__doc__t __future__RRtloggingR;RuRwtpip._vendor.six.moves.urllibRRtpip.exceptionsRt pip.utilsRRRRRt__all__t getLoggerR(R&tobjectR RR6R (((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyts     ( G vcs/git.py000064400000025675152527136320006521 0ustar00from __future__ import absolute_import import logging import tempfile import os.path from pip.compat import samefile from pip.exceptions import BadCommand from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._vendor.packaging.version import parse as parse_version from pip.utils import display_path, rmtree from pip.vcs import vcs, VersionControl urlsplit = urllib_parse.urlsplit urlunsplit = urllib_parse.urlunsplit logger = logging.getLogger(__name__) class Git(VersionControl): name = 'git' dirname = '.git' repo_name = 'clone' schemes = ( 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file', ) def __init__(self, url=None, *args, **kwargs): # Works around an apparent Git bug # (see http://article.gmane.org/gmane.comp.version-control.git/146500) if url: scheme, netloc, path, query, fragment = urlsplit(url) if scheme.endswith('file'): initial_slashes = path[:-len(path.lstrip('/'))] newpath = ( initial_slashes + urllib_request.url2pathname(path) .replace('\\', '/').lstrip('/') ) url = urlunsplit((scheme, netloc, newpath, query, fragment)) after_plus = scheme.find('+') + 1 url = scheme[:after_plus] + urlunsplit( (scheme[after_plus:], netloc, newpath, query, fragment), ) super(Git, self).__init__(url, *args, **kwargs) def get_git_version(self): VERSION_PFX = 'git version ' version = self.run_command(['version'], show_stdout=False) if version.startswith(VERSION_PFX): version = version[len(VERSION_PFX):] else: version = '' # get first 3 positions of the git version becasue # on windows it is x.y.z.windows.t, and this parses as # LegacyVersion which always smaller than a Version. version = '.'.join(version.split('.')[:3]) return parse_version(version) def export(self, location): """Export the Git repository at the url to the destination location""" temp_dir = tempfile.mkdtemp('-export', 'pip-') self.unpack(temp_dir) try: if not location.endswith('/'): location = location + '/' self.run_command( ['checkout-index', '-a', '-f', '--prefix', location], show_stdout=False, cwd=temp_dir) finally: rmtree(temp_dir) def check_rev_options(self, rev, dest, rev_options): """Check the revision options before checkout to compensate that tags and branches may need origin/ as a prefix. Returns the SHA1 of the branch or tag if found. """ revisions = self.get_short_refs(dest) origin_rev = 'origin/%s' % rev if origin_rev in revisions: # remote branch return [revisions[origin_rev]] elif rev in revisions: # a local tag or branch name return [revisions[rev]] else: logger.warning( "Could not find a tag or branch '%s', assuming commit.", rev, ) return rev_options def check_version(self, dest, rev_options): """ Compare the current sha to the ref. ref may be a branch or tag name, but current rev will always point to a sha. This means that a branch or tag will never compare as True. So this ultimately only matches against exact shas. """ return self.get_revision(dest).startswith(rev_options[0]) def switch(self, dest, url, rev_options): self.run_command(['config', 'remote.origin.url', url], cwd=dest) self.run_command(['checkout', '-q'] + rev_options, cwd=dest) self.update_submodules(dest) def update(self, dest, rev_options): # First fetch changes from the default remote if self.get_git_version() >= parse_version('1.9.0'): # fetch tags in addition to everything else self.run_command(['fetch', '-q', '--tags'], cwd=dest) else: self.run_command(['fetch', '-q'], cwd=dest) # Then reset to wanted revision (maybe even origin/master) if rev_options: rev_options = self.check_rev_options( rev_options[0], dest, rev_options, ) self.run_command(['reset', '--hard', '-q'] + rev_options, cwd=dest) #: update submodules self.update_submodules(dest) def obtain(self, dest): url, rev = self.get_url_rev() if rev: rev_options = [rev] rev_display = ' (to %s)' % rev else: rev_options = ['origin/master'] rev_display = '' if self.check_destination(dest, url, rev_options, rev_display): logger.info( 'Cloning %s%s to %s', url, rev_display, display_path(dest), ) self.run_command(['clone', '-q', url, dest]) if rev: rev_options = self.check_rev_options(rev, dest, rev_options) # Only do a checkout if rev_options differs from HEAD if not self.check_version(dest, rev_options): self.run_command( ['checkout', '-q'] + rev_options, cwd=dest, ) #: repo may contain submodules self.update_submodules(dest) def get_url(self, location): """Return URL of the first remote encountered.""" remotes = self.run_command( ['config', '--get-regexp', 'remote\..*\.url'], show_stdout=False, cwd=location) remotes = remotes.splitlines() found_remote = remotes[0] for remote in remotes: if remote.startswith('remote.origin.url '): found_remote = remote break url = found_remote.split(' ')[1] return url.strip() def get_revision(self, location): current_rev = self.run_command( ['rev-parse', 'HEAD'], show_stdout=False, cwd=location) return current_rev.strip() def get_full_refs(self, location): """Yields tuples of (commit, ref) for branches and tags""" output = self.run_command(['show-ref'], show_stdout=False, cwd=location) for line in output.strip().splitlines(): commit, ref = line.split(' ', 1) yield commit.strip(), ref.strip() def is_ref_remote(self, ref): return ref.startswith('refs/remotes/') def is_ref_branch(self, ref): return ref.startswith('refs/heads/') def is_ref_tag(self, ref): return ref.startswith('refs/tags/') def is_ref_commit(self, ref): """A ref is a commit sha if it is not anything else""" return not any(( self.is_ref_remote(ref), self.is_ref_branch(ref), self.is_ref_tag(ref), )) # Should deprecate `get_refs` since it's ambiguous def get_refs(self, location): return self.get_short_refs(location) def get_short_refs(self, location): """Return map of named refs (branches or tags) to commit hashes.""" rv = {} for commit, ref in self.get_full_refs(location): ref_name = None if self.is_ref_remote(ref): ref_name = ref[len('refs/remotes/'):] elif self.is_ref_branch(ref): ref_name = ref[len('refs/heads/'):] elif self.is_ref_tag(ref): ref_name = ref[len('refs/tags/'):] if ref_name is not None: rv[ref_name] = commit return rv def _get_subdirectory(self, location): """Return the relative path of setup.py to the git repo root.""" # find the repo root git_dir = self.run_command(['rev-parse', '--git-dir'], show_stdout=False, cwd=location).strip() if not os.path.isabs(git_dir): git_dir = os.path.join(location, git_dir) root_dir = os.path.join(git_dir, '..') # find setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None # relative path of setup.py to repo root if samefile(root_dir, location): return None return os.path.relpath(location, root_dir) def get_src_requirement(self, dist, location): repo = self.get_url(location) if not repo.lower().startswith('git:'): repo = 'git+' + repo egg_project_name = dist.egg_name().split('-', 1)[0] if not repo: return None current_rev = self.get_revision(location) req = '%s@%s#egg=%s' % (repo, current_rev, egg_project_name) subdirectory = self._get_subdirectory(location) if subdirectory: req += '&subdirectory=' + subdirectory return req def get_url_rev(self): """ Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes doesn't work with a ssh:// scheme (e.g. Github). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. """ if '://' not in self.url: assert 'file:' not in self.url self.url = self.url.replace('git+', 'git+ssh://') url, rev = super(Git, self).get_url_rev() url = url.replace('ssh://', '') else: url, rev = super(Git, self).get_url_rev() return url, rev def update_submodules(self, location): if not os.path.exists(os.path.join(location, '.gitmodules')): return self.run_command( ['submodule', 'update', '--init', '--recursive', '-q'], cwd=location, ) @classmethod def controls_location(cls, location): if super(Git, cls).controls_location(location): return True try: r = cls().run_command(['rev-parse'], cwd=location, show_stdout=False, on_returncode='ignore') return not r except BadCommand: logger.debug("could not determine if %s is under git control " "because git is not available", location) return False vcs.register(Git) vcs/subversion.pyc000064400000020725152527136320010267 0ustar00 abc@@s)ddlmZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZddlmZmZejdZejd Zejd Zejd Zejd Zejd ZejeZdefdYZdZejedS(i(tabsolute_importN(tparse(tLink(trmtreet display_path(t indent_log(tvcstVersionControls url="([^"]+)"scommitted-rev="(\d+)"s URL: (.+)sRevision: (.+)s\s*revision="(\d+)"s(.*)t SubversioncB@seZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZdZdZdZedZRS(tsvns.svntcheckoutssvn+sshssvn+https svn+httpsssvn+svncC@s|jdj|j s,td||jd|gdtdidd6}tj|}|stj dt |tj d |d S|j d j}tj|}|stj d t |tj d ||d fS||j d fS(s/Returns (url, revision), where both are stringst/sBad directory: %stinfot show_stdoutt extra_environtCtLANGs'Cannot determine URL of svn checkout %ss!Output that cannot be parsed: %sis,Cannot determine revision of svn checkout %sN(NN(trstriptendswithtdirnametAssertionErrort run_commandtFalset _svn_url_retsearchtloggertwarningRtdebugtNonetgrouptstript_svn_revision_re(tselftlocationtoutputtmatchturl((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytget_infos,     cC@s|j\}}t||}|j|}tjd||tHtjj|rlt |n|j dg|||gdt WdQXdS(s@Export the svn repository at the url to the destination locations!Exporting svn repository %s to %stexportR N( t get_url_revtget_rev_optionstremove_auth_from_urlRR RtostpathtexistsRRR(R R!R$trevt rev_options((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR&;s  cC@s"|jdg|||gdS(Ntswitch(R(R tdestR$R.((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR/JscC@s|jdg||gdS(Ntupdate(R(R R0R.((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR1MscC@s|j\}}t||}|j|}|rCd|}nd}|j||||rtjd||t||jddg|||gndS(Ns (to revision %s)tsChecking out %s%s to %sR s-q(R'R(R)tcheck_destinationRR RR(R R0R$R-R.t rev_display((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytobtainPs  cC@sx|D]{}t|j}|s(qnd|krYdj|jdd j}n|}||jkr|jdddSqWdS(Nt-it#ii(Rt egg_fragmenttjointsplittlowertkeyR(R tdisttdependency_linksR$R8R<((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyt get_locationas  %c C@sd}xtj|D]\}}}|j|krAg|(qn|j|jtjj||jd}tjj|sqn|j|\}}||kr|d} n$| s|j|  rg|(qnt ||}qW|S(sR Return the maximum revision for all files under a given location itentriesR ( R*twalkRtremoveR+R9R,t_get_svn_url_revt startswithtmax( R R!trevisiontbasetdirstfilest entries_fntdirurltlocalrevtbase_url((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyt get_revisionos"  cC@sAtt|j\}}|jdr7d|}n||fS(Nsssh://ssvn+(tsuperRR'RD(R R$R-((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR's cC@sw|}x]tjjtjj|dse|}tjj|}||kr tjd|dSq W|j|dS(Nssetup.pysGCould not find setup.py for directory %s (tried all parent directories)i( R*R+R,R9RRRRRC(R R!t orig_locationt last_location((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytget_urls$ c C@sIddlm}tjj||jd}tjj|rat|}|j}WdQXnd}|j ds|j ds|j drt t t j |jd}|dd=|dd }g|D]2}t|d kr|d rt|d ^qdg}n |j d rtj|} | sNtd |n| jd }gtj|D]} t| jd ^qmdg}nyk|jdd|gdt} tj| jd }gtj| D]} t| jd ^q}Wn|k r#dg}}nX|r9t|} nd} || fS(Ni(tInstallationErrorR@R2t8t9t10s ii s! I; 5 cC@s[|j|}|dkrdS|jjddd}|j|}d|||fS(NR6iissvn+%s@%s#egg=%s(RRRtegg_nameR:RN(R R=R!trepotegg_project_nameR-((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytget_src_requirements  cC@stS(s&Always assume the versions don't match(R(R R0R.((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyt check_versionscC@sYtj|}|jjdd}|j||j|j|jf}tj|}|S(Nt@i( t urllib_parseturlsplittnetlocR:tschemeR+tquerytfragmentt urlunsplit(R$tpurltstripped_netloct url_piecestsurl((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR)s !(R ssvn+sshssvn+https svn+httpsssvn+svn(t__name__t __module__tnameRt repo_nametschemesR%R&R/R1R5R?RNR'RRRCRpRqt staticmethodR)(((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyRs"          , cC@s|rd|g}ng}tj|}t|drO|j|j}}nl|d}d|kr|jdd}d|kr|jdd\}}q|d}}n d \}}|r|d|g7}n|r|d|g7}n|S( Ns-rtusernameiRrit:s --usernames --password(NN(RsRtthasattrRtpasswordR:R(R$R-R.trRRRutauth((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR(s$    (t __future__RtloggingR*tretpip._vendor.six.moves.urllibRRst pip.indexRt pip.utilsRRtpip.utils.loggingRtpip.vcsRRtcompileR`RbRRReRdt getLoggerR~RRR(tregister(((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyts$    vcs/subversion.py000064400000022206152527136320010120 0ustar00from __future__ import absolute_import import logging import os import re from pip._vendor.six.moves.urllib import parse as urllib_parse from pip.index import Link from pip.utils import rmtree, display_path from pip.utils.logging import indent_log from pip.vcs import vcs, VersionControl _svn_xml_url_re = re.compile('url="([^"]+)"') _svn_rev_re = re.compile('committed-rev="(\d+)"') _svn_url_re = re.compile(r'URL: (.+)') _svn_revision_re = re.compile(r'Revision: (.+)') _svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"') _svn_info_xml_url_re = re.compile(r'(.*)') logger = logging.getLogger(__name__) class Subversion(VersionControl): name = 'svn' dirname = '.svn' repo_name = 'checkout' schemes = ('svn', 'svn+ssh', 'svn+http', 'svn+https', 'svn+svn') def get_info(self, location): """Returns (url, revision), where both are strings""" assert not location.rstrip('/').endswith(self.dirname), \ 'Bad directory: %s' % location output = self.run_command( ['info', location], show_stdout=False, extra_environ={'LANG': 'C'}, ) match = _svn_url_re.search(output) if not match: logger.warning( 'Cannot determine URL of svn checkout %s', display_path(location), ) logger.debug('Output that cannot be parsed: \n%s', output) return None, None url = match.group(1).strip() match = _svn_revision_re.search(output) if not match: logger.warning( 'Cannot determine revision of svn checkout %s', display_path(location), ) logger.debug('Output that cannot be parsed: \n%s', output) return url, None return url, match.group(1) def export(self, location): """Export the svn repository at the url to the destination location""" url, rev = self.get_url_rev() rev_options = get_rev_options(url, rev) url = self.remove_auth_from_url(url) logger.info('Exporting svn repository %s to %s', url, location) with indent_log(): if os.path.exists(location): # Subversion doesn't like to check out over an existing # directory --force fixes this, but was only added in svn 1.5 rmtree(location) self.run_command( ['export'] + rev_options + [url, location], show_stdout=False) def switch(self, dest, url, rev_options): self.run_command(['switch'] + rev_options + [url, dest]) def update(self, dest, rev_options): self.run_command(['update'] + rev_options + [dest]) def obtain(self, dest): url, rev = self.get_url_rev() rev_options = get_rev_options(url, rev) url = self.remove_auth_from_url(url) if rev: rev_display = ' (to revision %s)' % rev else: rev_display = '' if self.check_destination(dest, url, rev_options, rev_display): logger.info( 'Checking out %s%s to %s', url, rev_display, display_path(dest), ) self.run_command(['checkout', '-q'] + rev_options + [url, dest]) def get_location(self, dist, dependency_links): for url in dependency_links: egg_fragment = Link(url).egg_fragment if not egg_fragment: continue if '-' in egg_fragment: # FIXME: will this work when a package has - in the name? key = '-'.join(egg_fragment.split('-')[:-1]).lower() else: key = egg_fragment if key == dist.key: return url.split('#', 1)[0] return None def get_revision(self, location): """ Return the maximum revision for all files under a given location """ # Note: taken from setuptools.command.egg_info revision = 0 for base, dirs, files in os.walk(location): if self.dirname not in dirs: dirs[:] = [] continue # no sense walking uncontrolled subdirs dirs.remove(self.dirname) entries_fn = os.path.join(base, self.dirname, 'entries') if not os.path.exists(entries_fn): # FIXME: should we warn? continue dirurl, localrev = self._get_svn_url_rev(base) if base == location: base_url = dirurl + '/' # save the root url elif not dirurl or not dirurl.startswith(base_url): dirs[:] = [] continue # not part of the same svn tree, skip it revision = max(revision, localrev) return revision def get_url_rev(self): # hotfix the URL scheme after removing svn+ from svn+ssh:// readd it url, rev = super(Subversion, self).get_url_rev() if url.startswith('ssh://'): url = 'svn+' + url return url, rev def get_url(self, location): # In cases where the source is in a subdirectory, not alongside # setup.py we have to look up in the location until we find a real # setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None return self._get_svn_url_rev(location)[0] def _get_svn_url_rev(self, location): from pip.exceptions import InstallationError entries_path = os.path.join(location, self.dirname, 'entries') if os.path.exists(entries_path): with open(entries_path) as f: data = f.read() else: # subversion >= 1.7 does not have the 'entries' file data = '' if (data.startswith('8') or data.startswith('9') or data.startswith('10')): data = list(map(str.splitlines, data.split('\n\x0c\n'))) del data[0][0] # get rid of the '8' url = data[0][3] revs = [int(d[9]) for d in data if len(d) > 9 and d[9]] + [0] elif data.startswith('= 1.7 xml = self.run_command( ['info', '--xml', location], show_stdout=False, ) url = _svn_info_xml_url_re.search(xml).group(1) revs = [ int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml) ] except InstallationError: url, revs = None, [] if revs: rev = max(revs) else: rev = 0 return url, rev def get_src_requirement(self, dist, location): repo = self.get_url(location) if repo is None: return None # FIXME: why not project name? egg_project_name = dist.egg_name().split('-', 1)[0] rev = self.get_revision(location) return 'svn+%s@%s#egg=%s' % (repo, rev, egg_project_name) def check_version(self, dest, rev_options): """Always assume the versions don't match""" return False @staticmethod def remove_auth_from_url(url): # Return a copy of url with 'username:password@' removed. # username/pass params are passed to subversion through flags # and are not recognized in the url. # parsed url purl = urllib_parse.urlsplit(url) stripped_netloc = \ purl.netloc.split('@')[-1] # stripped url url_pieces = ( purl.scheme, stripped_netloc, purl.path, purl.query, purl.fragment ) surl = urllib_parse.urlunsplit(url_pieces) return surl def get_rev_options(url, rev): if rev: rev_options = ['-r', rev] else: rev_options = [] r = urllib_parse.urlsplit(url) if hasattr(r, 'username'): # >= Python-2.5 username, password = r.username, r.password else: netloc = r[1] if '@' in netloc: auth = netloc.split('@')[0] if ':' in auth: username, password = auth.split(':', 1) else: username, password = auth, None else: username, password = None, None if username: rev_options += ['--username', username] if password: rev_options += ['--password', password] return rev_options vcs.register(Subversion) vcs/__init__.pyo000064400000031415152527136320007641 0ustar00 abc@@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl mZmZmZmZmZddgZejeZd efd YZeZd efd YZd ZdS(s)Handles all VCS (version control) supporti(tabsolute_importN(tparse(t BadCommand(t display_patht backup_dirtcall_subprocesstrmtreetask_path_existstvcstget_src_requirementt VcsSupportcB@seZiZddddddgZdZdZedZed Zed Z d Z ddd Z d Z dZdZRS(tsshtgitthgtbzrtsftptsvncC@sRtjj|jttddr;tjj|jntt|j dS(Nt uses_fragment( t urllib_parset uses_netloctextendtschemestgetattrtNoneRtsuperR t__init__(tself((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyRscC@s |jjS(N(t _registryt__iter__(R((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR$scC@st|jjS(N(tlistRtvalues(R((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytbackends'scC@sg|jD]}|j^q S(N(Rtdirname(Rtbackend((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytdirnames+scC@s.g}x!|jD]}|j|jqW|S(N(RRR(RRR!((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt all_schemes/scC@sbt|ds&tjd|jdS|j|jkr^||j|js  cC@sJxC|jjD]2}|j|rtjd||j|jSqWdS(s Return the name of the version control backend if found at given location, e.g. vcs.get_backend_name('/path/to/vcs/checkout') sDetermine that %s uses VCS: %sN(RRtcontrols_locationR&R)R$R(Rtlocationtvc_type((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytget_backend_nameFs    cC@s*|j}||jkr&|j|SdS(N(tlowerR(RR$((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt get_backendRs cC@s&|j|}|r"|j|SdS(N(R0R2R(RR.R/((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytget_backend_from_locationWs N(R(t __module__RRRRtpropertyRR"R#R+RR,R0R2R3(((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR s   tVersionControlcB@seZdZdZdZddZdZdZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZdZdZdZdZeddddddZedZRS(tcO@s&||_tt|j||dS(N(turlRR6R(RR8targstkwargs((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyRgs cC@s1tjj|\}}|jtjjp0|S(sy posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\folder) (tostpatht splitdrivet startswithtsep(Rtrepotdrivettail((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt_is_local_repositorykscC@s|jddS(Nt/t_(treplace(Rtsurname((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyttranslate_egg_surnameuscC@s tdS(s Export the repository at the url to the destination location i.e. only download the files, without vcs informations N(tNotImplementedError(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytexportysc C@sd}|jjddd}tj|\}}}}}d}d|krj|jdd\}}ntj||||df}||fS(sm Returns the correct repository URL and revision by parsing the given repository URL svSorry, '%s' is a malformed VCS url. The format is +://, e.g. svn+http://myrepo/svn/MyApp#egg=MyAppt+it@R7N(R8tsplitRturlsplitRtrsplitt urlunsplit( Rt error_messageR8tschemetnetlocR<tquerytfragtrev((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt get_url_revs cC@s|j||j|fS(sA Returns (url, revision), where both are strings (tget_urlt get_revision(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytget_infoscC@stj|jdS(si Normalize a URL for comparison by unquoting it and removing any trailing slash. RD(Rtunquotetrstrip(RR8((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt normalize_urlscC@s|j||j|kS(sV Compare two repo URLs for identity, ignoring incidental differences. (R](Rturl1turl2((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt compare_urlsscC@s tdS(sx Called when installing or updating an editable package, takes the source path of the checkout. N(RI(Rtdest((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytobtainscC@s tdS(sB Switch the repo at ``dest`` to point to ``URL``. N(RI(RRaR8t rev_options((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytswitchscC@s tdS(sO Update an already-existing repo to the given ``rev_options``. N(RI(RRaRc((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytupdatescC@s tdS(sp Return True if the version is identical to what exists and doesn't need to be updated. N(RI(RRaRc((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt check_versionsc C@smt}t}tjj|rAt}tjjtjj||jr|j|}|j||rt j d|j j t |||j||st jdt ||j ||j||qt jdq>t jd|j|j t ||ddf}qAt jd ||j|j d df}n|rit jd |j|td |d|d}|dkrt jd|j t ||||j|||qi|dkrqi|dkrt jdt |t|t}qi|d krJt|} t jdt || tj|| t}qi|dkritjdqin|S(s Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise. s)%s in %s exists, and has correct URL (%s)sUpdating %s %s%ss$Skipping because already up-to-date.s%s %s in %s exists with URL %ss%(s)witch, (i)gnore, (w)ipe, (b)ackup tstitwtbs0Directory %s already exists, and is not a %s %s.s(i)gnore, (w)ipe, (b)ackup s+The plan is to install the %s repository %ssWhat to do? %siisSwitching %s %s to %s%ss Deleting %ssBacking up %s to %stai(RgRhRiRj(RhRiRj(tTruetFalseR;R<texiststjoinR RXR`R&R)t repo_namettitleRRftinfoReR'R$RRdRRtshutiltmovetsystexit( RRaR8Rct rev_displaytcheckouttpromptt existing_urltresponsetdest_dir((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytcheck_destinations$                  cC@s0tjj|rt|n|j|dS(sq Clean up current location and download the url repository (and vcs infos) into location N(R;R<RnRRb(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pytunpacks cC@s tdS(s Return a string representing the requirement needed to redownload the files currently present in location, something like: {repository_url}@{revision}#egg={project_name}-{version_identifier} N(RI(RtdistR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR scC@s tdS(s_ Return the url used at location Used in get_info or check_destination N(RI(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyRX)scC@s tdS(s_ Return the current revision of the files at location Used in get_info N(RI(RR.((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyRY0straisec C@su|jg|}y t|||||||SWn>tk rp}|jtjkrjtd|jqqnXdS(s Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available sCannot find command %rN(R$RtOSErrorterrnotENOENTR( Rtcmdt show_stdouttcwdt on_returncodet command_desct extra_environtspinnerte((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyt run_command7s   cC@sDtjd||j|jtjj||j}tjj|S(s Check if a location is controlled by the vcs. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. sChecking in %s for %s (%s)...(R&R)R R$R;R<RoRn(R*R.R<((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR-Ns (N(R(R4R$R RRRRCRHRJRWRZR]R`RbRdReRfR}R~R RXRYRlRt classmethodR-(((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR6as2            U  cC@sztj|}|r`y|j||SWq`tk r\tjd||j|jSXntjd||jS(NsPcannot determine version of editable source in %s (%s command not found in path)stcannot determine version of editable source in %s (is not SVN checkout, Git clone, Mercurial clone or Bazaar branch)(RR3R RR&R'R$tas_requirement(RR.tversion_control((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyR [s    (t__doc__t __future__RRtloggingR;RsRutpip._vendor.six.moves.urllibRRtpip.exceptionsRt pip.utilsRRRRRt__all__t getLoggerR(R&tobjectR RR6R (((s4/usr/lib/python2.7/site-packages/pip/vcs/__init__.pyts     ( G vcs/git.pyc000064400000025427152527136320006657 0ustar00 abc@@sddlmZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Zddlm ZddlmZmZddlmZmZe jZe jZejeZd efd YZejedS( i(tabsolute_importN(tsamefile(t BadCommand(tparse(trequest(t display_pathtrmtree(tvcstVersionControltGitcB@seZdZdZdZdZddZd Zd Z d Z d Z d Z dZ dZdZdZdZdZdZdZdZdZdZdZdZdZdZedZRS( tgits.gittclonesgit+https git+httpssgit+sshsgit+gitsgit+filec O@s|rt|\}}}}}|jdr|t|jd } | tj|jddjd} t||| ||f}|jdd} || t|| || ||f}qnt t |j |||dS(Ntfilet/s\t+i( turlsplittendswithtlentlstripturllib_requestt url2pathnametreplacet urlunsplittfindtsuperR t__init__( tselfturltargstkwargstschemetnetloctpathtquerytfragmenttinitial_slashestnewpatht after_plus((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyR s #cC@sld}|jdgdt}|j|r@|t|}nd}dj|jdd }t|S(Ns git version tversiont show_stdouttt.i(t run_commandtFalset startswithRtjointsplitt parse_version(Rt VERSION_PFXR&((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytget_git_version5scC@sytjdd}|j|zH|jds>|d}n|jdddd|gdtd |Wd t|Xd S( s@Export the Git repository at the url to the destination locations-exportspip-R scheckout-indexs-as-fs--prefixR'tcwdN(ttempfiletmkdtemptunpackRR*R+R(Rtlocationttemp_dir((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytexportBs  cC@s_|j|}d|}||kr0||gS||krG||gStjd||SdS(sCheck the revision options before checkout to compensate that tags and branches may need origin/ as a prefix. Returns the SHA1 of the branch or tag if found. s origin/%ss5Could not find a tag or branch '%s', assuming commit.N(tget_short_refstloggertwarning(Rtrevtdestt rev_optionst revisionst origin_rev((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytcheck_rev_optionsOs      cC@s|j|j|dS(s  Compare the current sha to the ref. ref may be a branch or tag name, but current rev will always point to a sha. This means that a branch or tag will never compare as True. So this ultimately only matches against exact shas. i(t get_revisionR,(RR=R>((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt check_versioncscC@sJ|jdd|gd||jddg|d||j|dS(Ntconfigsremote.origin.urlR2tcheckouts-q(R*tupdate_submodules(RR=RR>((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytswitchlscC@s|jtdkr7|jdddgd|n|jddgd||rr|j|d||}n|jdddg|d||j|dS( Ns1.9.0tfetchs-qs--tagsR2itresets--hard(R1R/R*RARF(RR=R>((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytupdaters cC@s|j\}}|r.|g}d|}ndg}d}|j||||rtjd||t||jdd||g|r|j|||}|j||s|jddg|d|qn|j|ndS( Ns (to %s)s origin/masterR(sCloning %s%s to %sR s-qRER2( t get_url_revtcheck_destinationR:tinfoRR*RARCRF(RR=RR<R>t rev_display((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytobtains"    cC@s|jdddgdtd|}|j}|d}x'|D]}|jdrA|}PqAqAW|jdd }|jS( s+Return URL of the first remote encountered.RDs --get-regexpsremote\..*\.urlR'R2isremote.origin.url t i(R*R+t splitlinesR,R.tstrip(RR6tremotest found_remotetremoteR((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytget_urls   cC@s+|jddgdtd|}|jS(Ns rev-parsetHEADR'R2(R*R+RR(RR6t current_rev((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyRBscc@sn|jdgdtd|}xI|jjD]5}|jdd\}}|j|jfVq1WdS(s4Yields tuples of (commit, ref) for branches and tagssshow-refR'R2RPiN(R*R+RRRQR.(RR6toutputtlinetcommittref((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt get_full_refss cC@s |jdS(Ns refs/remotes/(R,(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_remotescC@s |jdS(Ns refs/heads/(R,(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_branchscC@s |jdS(Ns refs/tags/(R,(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_tagscC@s/t|j||j||j|f S(s0A ref is a commit sha if it is not anything else(tanyR^R_R`(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_commits  cC@s |j|S(N(R9(RR6((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytget_refsscC@si}x|j|D]\}}d}|j|rJ|td}nD|j|rl|td}n"|j|r|td}n|dk r|||s      vcs/mercurial.pyo000064400000010776152527136320010074 0ustar00 abc@@sddlmZddlZddlZddlZddlmZmZddlm Z m Z ddl m Z ddl mZejeZde fdYZe jedS( i(tabsolute_importN(t display_pathtrmtree(tvcstVersionControl(t path_to_url(t configparsert MercurialcB@sqeZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZRS(thgs.hgtcloneshg+httpshg+httpsshg+sshshg+static-httpcC@sTtjdd}|j|z#|jd|gdtd|Wdt|XdS(s?Export the Hg repository at the url to the destination locations-exportspip-tarchivet show_stdouttcwdN(ttempfiletmkdtemptunpackt run_commandtFalseR(tselftlocationttemp_dir((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytexports  cC@stjj||jd}tj}yI|j||jdd|t|d}|j |WdQXWn/t tj fk r}t j d||nX|jddg|d|dS( Nthgrctpathstdefaulttws/Could not switch Mercurial repository to %s: %stupdates-qR (tostpathtjointdirnameRtSafeConfigParsertreadtsettopentwritetOSErrortNoSectionErrortloggertwarningR(Rtdestturlt rev_optionst repo_configtconfigt config_filetexc((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytswitch s  cC@s:|jddgd||jddg|d|dS(Ntpulls-qR R(R(RR(R*((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyR/scC@s|j\}}|r.|g}d|}n g}d}|j||||rtjd||t||jddd||g|jddg|d|ndS( Ns (to revision %s)tsCloning hg %s%s to %sR s --noupdates-qRR (t get_url_revtcheck_destinationR&tinfoRR(RR(R)trevR*t rev_display((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytobtain3s   cC@sO|jddgdtd|j}|j|rEt|}n|jS(Nt showconfigs paths.defaultR R (RRtstript_is_local_repositoryR(RRR)((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytget_urlEs  cC@s+|jddgdtd|j}|S(Ntparentss--template={rev}R R (RRR9(RRtcurrent_revision((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyt get_revisionMs cC@s+|jddgdtd|j}|S(NR<s--template={node}R R (RRR9(RRtcurrent_rev_hash((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytget_revision_hashSs cC@sw|j|}|jjds1d|}n|jjddd}|sWdS|j|}d|||fS(Nshg:shg+t-iis %s@%s#egg=%s(R;tlowert startswithtegg_nametsplittNoneR@(RtdistRtrepotegg_project_nameR?((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pytget_src_requirementYs cC@stS(s&Always assume the versions don't match(R(RR(R*((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyt check_versioncs(Rshg+httpshg+httpsshg+sshshg+static-http(t__name__t __module__tnameRt repo_nametschemesRR/RR7R;R>R@RJRK(((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyRs       (t __future__RtloggingRR t pip.utilsRRtpip.vcsRRt pip.downloadRtpip._vendor.six.movesRt getLoggerRLR&Rtregister(((s5/usr/lib/python2.7/site-packages/pip/vcs/mercurial.pyts   Wvcs/bazaar.pyc000064400000011236152527136320007325 0ustar00 abc@@sddlmZddlZddlZddlZyddlmZWnek rgddl ZnXddl m Z m Z ddl mZmZddlmZejeZdefdYZejedS( i(tabsolute_importN(tparse(trmtreet display_path(tvcstVersionControl(t path_to_urltBazaarcB@s}eZdZdZdZdZdd Zd Zd Z d Z d Z dZ dZ dZdZdZRS(tbzrs.bzrtbranchsbzr+https bzr+httpssbzr+sshsbzr+sftpsbzr+ftpsbzr+lpcO@s[tt|j|||ttddrWtjjdgtjjdgndS(Nt uses_fragmenttlp( tsuperRt__init__tgetattrt urllib_parsetNoneR textendtnon_hierarchical(tselfturltargstkwargs((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR scC@sstjdd}|j|tjj|r>t|nz#|jd|gd|dtWdt|XdS(sU Export the Bazaar repository at the url to the destination location s-exportspip-texporttcwdt show_stdoutN( ttempfiletmkdtemptunpacktostpathtexistsRt run_commandtFalse(Rtlocationttemp_dir((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR&s   cC@s|jd|gd|dS(NtswitchR(R (RtdestRt rev_options((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR$5scC@s!|jddg|d|dS(Ntpulls-qR(R (RR%R&((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytupdate8scC@s|j\}}|r1d|g}d|}n g}d}|j||||rtjd||t||jddg|||gndS(Ns-rs (to revision %s)tsChecking out %s%s to %sR s-q(t get_url_revtcheck_destinationtloggertinfoRR (RR%RtrevR&t rev_display((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytobtain;s   cC@sAtt|j\}}|jdr7d|}n||fS(Nsssh://sbzr+(R RR*t startswith(RRR.((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyR*Ls cC@s|jdgdtd|}xp|jD]b}|j}xMdD]E}|j|rD|j|d}|j|rt|S|SqDWq+WdS(NR-RRscheckout of branch: sparent branch: i(scheckout of branch: sparent branch: ( R R!t splitlineststripR1tsplitt_is_local_repositoryRR(RR"turlstlinetxtrepo((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytget_urlSs    cC@s,|jdgdtd|}|jdS(NtrevnoRRi(R R!R2(RR"trevision((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyt get_revision`scC@sw|j|}|sdS|jjds;d|}n|jjddd}|j|}d|||fS(Nsbzr:sbzr+t-iis %s@%s#egg=%s(R:RtlowerR1tegg_nameR4R=(RtdistR"R9tegg_project_namet current_rev((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pytget_src_requirementes cC@stS(s&Always assume the versions don't match(R!(RR%R&((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyt check_versionos(Rsbzr+https bzr+httpssbzr+sshsbzr+sftpsbzr+ftpsbzr+lpN(t__name__t __module__tnametdirnamet repo_nametschemesRR RR$R(R0R*R:R=RDRE(((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyRs        (t __future__RtloggingRRturllibRRt ImportErrorturlparset pip.utilsRRtpip.vcsRRt pip.downloadRt getLoggerRFR,Rtregister(((s2/usr/lib/python2.7/site-packages/pip/vcs/bazaar.pyts    _vcs/git.pyo000064400000025343152527136320006670 0ustar00 abc@@sddlmZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Zddlm ZddlmZmZddlmZmZe jZe jZejeZd efd YZejedS( i(tabsolute_importN(tsamefile(t BadCommand(tparse(trequest(t display_pathtrmtree(tvcstVersionControltGitcB@seZdZdZdZdZddZd Zd Z d Z d Z d Z dZ dZdZdZdZdZdZdZdZdZdZdZdZdZdZedZRS( tgits.gittclonesgit+https git+httpssgit+sshsgit+gitsgit+filec O@s|rt|\}}}}}|jdr|t|jd } | tj|jddjd} t||| ||f}|jdd} || t|| || ||f}qnt t |j |||dS(Ntfilet/s\t+i( turlsplittendswithtlentlstripturllib_requestt url2pathnametreplacet urlunsplittfindtsuperR t__init__( tselfturltargstkwargstschemetnetloctpathtquerytfragmenttinitial_slashestnewpatht after_plus((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyR s #cC@sld}|jdgdt}|j|r@|t|}nd}dj|jdd }t|S(Ns git version tversiont show_stdouttt.i(t run_commandtFalset startswithRtjointsplitt parse_version(Rt VERSION_PFXR&((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytget_git_version5scC@sytjdd}|j|zH|jds>|d}n|jdddd|gdtd |Wd t|Xd S( s@Export the Git repository at the url to the destination locations-exportspip-R scheckout-indexs-as-fs--prefixR'tcwdN(ttempfiletmkdtemptunpackRR*R+R(Rtlocationttemp_dir((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytexportBs  cC@s_|j|}d|}||kr0||gS||krG||gStjd||SdS(sCheck the revision options before checkout to compensate that tags and branches may need origin/ as a prefix. Returns the SHA1 of the branch or tag if found. s origin/%ss5Could not find a tag or branch '%s', assuming commit.N(tget_short_refstloggertwarning(Rtrevtdestt rev_optionst revisionst origin_rev((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytcheck_rev_optionsOs      cC@s|j|j|dS(s  Compare the current sha to the ref. ref may be a branch or tag name, but current rev will always point to a sha. This means that a branch or tag will never compare as True. So this ultimately only matches against exact shas. i(t get_revisionR,(RR=R>((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt check_versioncscC@sJ|jdd|gd||jddg|d||j|dS(Ntconfigsremote.origin.urlR2tcheckouts-q(R*tupdate_submodules(RR=RR>((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytswitchlscC@s|jtdkr7|jdddgd|n|jddgd||rr|j|d||}n|jdddg|d||j|dS( Ns1.9.0tfetchs-qs--tagsR2itresets--hard(R1R/R*RARF(RR=R>((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytupdaters cC@s|j\}}|r.|g}d|}ndg}d}|j||||rtjd||t||jdd||g|r|j|||}|j||s|jddg|d|qn|j|ndS( Ns (to %s)s origin/masterR(sCloning %s%s to %sR s-qRER2( t get_url_revtcheck_destinationR:tinfoRR*RARCRF(RR=RR<R>t rev_display((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytobtains"    cC@s|jdddgdtd|}|j}|d}x'|D]}|jdrA|}PqAqAW|jdd }|jS( s+Return URL of the first remote encountered.RDs --get-regexpsremote\..*\.urlR'R2isremote.origin.url t i(R*R+t splitlinesR,R.tstrip(RR6tremotest found_remotetremoteR((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytget_urls   cC@s+|jddgdtd|}|jS(Ns rev-parsetHEADR'R2(R*R+RR(RR6t current_rev((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyRBscc@sn|jdgdtd|}xI|jjD]5}|jdd\}}|j|jfVq1WdS(s4Yields tuples of (commit, ref) for branches and tagssshow-refR'R2RPiN(R*R+RRRQR.(RR6toutputtlinetcommittref((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt get_full_refss cC@s |jdS(Ns refs/remotes/(R,(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_remotescC@s |jdS(Ns refs/heads/(R,(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_branchscC@s |jdS(Ns refs/tags/(R,(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_tagscC@s/t|j||j||j|f S(s0A ref is a commit sha if it is not anything else(tanyR^R_R`(RR\((s//usr/lib/python2.7/site-packages/pip/vcs/git.pyt is_ref_commits  cC@s |j|S(N(R9(RR6((s//usr/lib/python2.7/site-packages/pip/vcs/git.pytget_refsscC@si}x|j|D]\}}d}|j|rJ|td}nD|j|rl|td}n"|j|r|td}n|dk r|||s      vcs/__init__.py000064400000030126152527136320007460 0ustar00"""Handles all VCS (version control) support""" from __future__ import absolute_import import errno import logging import os import shutil import sys from pip._vendor.six.moves.urllib import parse as urllib_parse from pip.exceptions import BadCommand from pip.utils import (display_path, backup_dir, call_subprocess, rmtree, ask_path_exists) __all__ = ['vcs', 'get_src_requirement'] logger = logging.getLogger(__name__) class VcsSupport(object): _registry = {} schemes = ['ssh', 'git', 'hg', 'bzr', 'sftp', 'svn'] def __init__(self): # Register more schemes with urlparse for various version control # systems urllib_parse.uses_netloc.extend(self.schemes) # Python >= 2.7.4, 3.3 doesn't have uses_fragment if getattr(urllib_parse, 'uses_fragment', None): urllib_parse.uses_fragment.extend(self.schemes) super(VcsSupport, self).__init__() def __iter__(self): return self._registry.__iter__() @property def backends(self): return list(self._registry.values()) @property def dirnames(self): return [backend.dirname for backend in self.backends] @property def all_schemes(self): schemes = [] for backend in self.backends: schemes.extend(backend.schemes) return schemes def register(self, cls): if not hasattr(cls, 'name'): logger.warning('Cannot register VCS %s', cls.__name__) return if cls.name not in self._registry: self._registry[cls.name] = cls logger.debug('Registered VCS backend: %s', cls.name) def unregister(self, cls=None, name=None): if name in self._registry: del self._registry[name] elif cls in self._registry.values(): del self._registry[cls.name] else: logger.warning('Cannot unregister because no class or name given') def get_backend_name(self, location): """ Return the name of the version control backend if found at given location, e.g. vcs.get_backend_name('/path/to/vcs/checkout') """ for vc_type in self._registry.values(): if vc_type.controls_location(location): logger.debug('Determine that %s uses VCS: %s', location, vc_type.name) return vc_type.name return None def get_backend(self, name): name = name.lower() if name in self._registry: return self._registry[name] def get_backend_from_location(self, location): vc_type = self.get_backend_name(location) if vc_type: return self.get_backend(vc_type) return None vcs = VcsSupport() class VersionControl(object): name = '' dirname = '' # List of supported schemes for this Version Control schemes = () def __init__(self, url=None, *args, **kwargs): self.url = url super(VersionControl, self).__init__(*args, **kwargs) def _is_local_repository(self, repo): """ posix absolute paths start with os.path.sep, win32 ones start with drive (like c:\\folder) """ drive, tail = os.path.splitdrive(repo) return repo.startswith(os.path.sep) or drive # See issue #1083 for why this method was introduced: # https://github.com/pypa/pip/issues/1083 def translate_egg_surname(self, surname): # For example, Django has branches of the form "stable/1.7.x". return surname.replace('/', '_') def export(self, location): """ Export the repository at the url to the destination location i.e. only download the files, without vcs informations """ raise NotImplementedError def get_url_rev(self): """ Returns the correct repository URL and revision by parsing the given repository URL """ error_message = ( "Sorry, '%s' is a malformed VCS url. " "The format is +://, " "e.g. svn+http://myrepo/svn/MyApp#egg=MyApp" ) assert '+' in self.url, error_message % self.url url = self.url.split('+', 1)[1] scheme, netloc, path, query, frag = urllib_parse.urlsplit(url) rev = None if '@' in path: path, rev = path.rsplit('@', 1) url = urllib_parse.urlunsplit((scheme, netloc, path, query, '')) return url, rev def get_info(self, location): """ Returns (url, revision), where both are strings """ assert not location.rstrip('/').endswith(self.dirname), \ 'Bad directory: %s' % location return self.get_url(location), self.get_revision(location) def normalize_url(self, url): """ Normalize a URL for comparison by unquoting it and removing any trailing slash. """ return urllib_parse.unquote(url).rstrip('/') def compare_urls(self, url1, url2): """ Compare two repo URLs for identity, ignoring incidental differences. """ return (self.normalize_url(url1) == self.normalize_url(url2)) def obtain(self, dest): """ Called when installing or updating an editable package, takes the source path of the checkout. """ raise NotImplementedError def switch(self, dest, url, rev_options): """ Switch the repo at ``dest`` to point to ``URL``. """ raise NotImplementedError def update(self, dest, rev_options): """ Update an already-existing repo to the given ``rev_options``. """ raise NotImplementedError def check_version(self, dest, rev_options): """ Return True if the version is identical to what exists and doesn't need to be updated. """ raise NotImplementedError def check_destination(self, dest, url, rev_options, rev_display): """ Prepare a location to receive a checkout/clone. Return True if the location is ready for (and requires) a checkout/clone, False otherwise. """ checkout = True prompt = False if os.path.exists(dest): checkout = False if os.path.exists(os.path.join(dest, self.dirname)): existing_url = self.get_url(dest) if self.compare_urls(existing_url, url): logger.debug( '%s in %s exists, and has correct URL (%s)', self.repo_name.title(), display_path(dest), url, ) if not self.check_version(dest, rev_options): logger.info( 'Updating %s %s%s', display_path(dest), self.repo_name, rev_display, ) self.update(dest, rev_options) else: logger.info( 'Skipping because already up-to-date.') else: logger.warning( '%s %s in %s exists with URL %s', self.name, self.repo_name, display_path(dest), existing_url, ) prompt = ('(s)witch, (i)gnore, (w)ipe, (b)ackup ', ('s', 'i', 'w', 'b')) else: logger.warning( 'Directory %s already exists, and is not a %s %s.', dest, self.name, self.repo_name, ) prompt = ('(i)gnore, (w)ipe, (b)ackup ', ('i', 'w', 'b')) if prompt: logger.warning( 'The plan is to install the %s repository %s', self.name, url, ) response = ask_path_exists('What to do? %s' % prompt[0], prompt[1]) if response == 's': logger.info( 'Switching %s %s to %s%s', self.repo_name, display_path(dest), url, rev_display, ) self.switch(dest, url, rev_options) elif response == 'i': # do nothing pass elif response == 'w': logger.warning('Deleting %s', display_path(dest)) rmtree(dest) checkout = True elif response == 'b': dest_dir = backup_dir(dest) logger.warning( 'Backing up %s to %s', display_path(dest), dest_dir, ) shutil.move(dest, dest_dir) checkout = True elif response == 'a': sys.exit(-1) return checkout def unpack(self, location): """ Clean up current location and download the url repository (and vcs infos) into location """ if os.path.exists(location): rmtree(location) self.obtain(location) def get_src_requirement(self, dist, location): """ Return a string representing the requirement needed to redownload the files currently present in location, something like: {repository_url}@{revision}#egg={project_name}-{version_identifier} """ raise NotImplementedError def get_url(self, location): """ Return the url used at location Used in get_info or check_destination """ raise NotImplementedError def get_revision(self, location): """ Return the current revision of the files at location Used in get_info """ raise NotImplementedError def run_command(self, cmd, show_stdout=True, cwd=None, on_returncode='raise', command_desc=None, extra_environ=None, spinner=None): """ Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name, and checks that the VCS is available """ cmd = [self.name] + cmd try: return call_subprocess(cmd, show_stdout, cwd, on_returncode, command_desc, extra_environ, spinner) except OSError as e: # errno.ENOENT = no such file or directory # In other words, the VCS executable isn't available if e.errno == errno.ENOENT: raise BadCommand('Cannot find command %r' % self.name) else: raise # re-raise exception if a different error occurred @classmethod def controls_location(cls, location): """ Check if a location is controlled by the vcs. It is meant to be overridden to implement smarter detection mechanisms for specific vcs. """ logger.debug('Checking in %s for %s (%s)...', location, cls.dirname, cls.name) path = os.path.join(location, cls.dirname) return os.path.exists(path) def get_src_requirement(dist, location): version_control = vcs.get_backend_from_location(location) if version_control: try: return version_control().get_src_requirement(dist, location) except BadCommand: logger.warning( 'cannot determine version of editable source in %s ' '(%s command not found in path)', location, version_control.name, ) return dist.as_requirement() logger.warning( 'cannot determine version of editable source in %s (is not SVN ' 'checkout, Git clone, Mercurial clone or Bazaar branch)', location, ) return dist.as_requirement() vcs/subversion.pyo000064400000020532152527136320010277 0ustar00 abc@@s)ddlmZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZddlmZmZejdZejd Zejd Zejd Zejd Zejd ZejeZdefdYZdZejedS(i(tabsolute_importN(tparse(tLink(trmtreet display_path(t indent_log(tvcstVersionControls url="([^"]+)"scommitted-rev="(\d+)"s URL: (.+)sRevision: (.+)s\s*revision="(\d+)"s(.*)t SubversioncB@seZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZdZdZdZedZRS(tsvns.svntcheckoutssvn+sshssvn+https svn+httpsssvn+svncC@s|jd|gdtdidd6}tj|}|sgtjdt|tjd|d S|j dj }t j|}|stjd t|tjd||d fS||j dfS( s/Returns (url, revision), where both are stringstinfot show_stdoutt extra_environtCtLANGs'Cannot determine URL of svn checkout %ss!Output that cannot be parsed: %sis,Cannot determine revision of svn checkout %sN(NN( t run_commandtFalset _svn_url_retsearchtloggertwarningRtdebugtNonetgrouptstript_svn_revision_re(tselftlocationtoutputtmatchturl((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytget_infos(    cC@s|j\}}t||}|j|}tjd||tHtjj|rlt |n|j dg|||gdt WdQXdS(s@Export the svn repository at the url to the destination locations!Exporting svn repository %s to %stexportR N( t get_url_revtget_rev_optionstremove_auth_from_urlRR RtostpathtexistsRRR(RRRtrevt rev_options((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR!;s  cC@s"|jdg|||gdS(Ntswitch(R(RtdestRR)((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR*JscC@s|jdg||gdS(Ntupdate(R(RR+R)((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR,MscC@s|j\}}t||}|j|}|rCd|}nd}|j||||rtjd||t||jddg|||gndS(Ns (to revision %s)tsChecking out %s%s to %sR s-q(R"R#R$tcheck_destinationRR RR(RR+RR(R)t rev_display((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytobtainPs  cC@sx|D]{}t|j}|s(qnd|krYdj|jdd j}n|}||jkr|jdddSqWdS(Nt-it#ii(Rt egg_fragmenttjointsplittlowertkeyR(Rtdisttdependency_linksRR3R7((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyt get_locationas  %c C@sd}xtj|D]\}}}|j|krAg|(qn|j|jtjj||jd}tjj|sqn|j|\}}||kr|d} n$| s|j|  rg|(qnt ||}qW|S(sR Return the maximum revision for all files under a given location itentriest/( R%twalktdirnametremoveR&R4R't_get_svn_url_revt startswithtmax( RRtrevisiontbasetdirstfilest entries_fntdirurltlocalrevtbase_url((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyt get_revisionos"  cC@sAtt|j\}}|jdr7d|}n||fS(Nsssh://ssvn+(tsuperRR"RA(RRR(((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR"s cC@sw|}x]tjjtjj|dse|}tjj|}||kr tjd|dSq W|j|dS(Nssetup.pysGCould not find setup.py for directory %s (tried all parent directories)i( R%R&R'R4R>RRRR@(RRt orig_locationt last_location((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytget_urls$ c C@sIddlm}tjj||jd}tjj|rat|}|j}WdQXnd}|j ds|j ds|j drt t t j |jd}|dd=|dd }g|D]2}t|d kr|d rt|d ^qdg}n |j d rtj|} | sNtd |n| jd }gtj|D]} t| jd ^qmdg}nyk|jdd|gdt} tj| jd }gtj| D]} t| jd ^q}Wn|k r#dg}}nX|r9t|} nd} || fS(Ni(tInstallationErrorR;R-t8t9t10s ii sR'topentreadRAtlisttmaptstrt splitlinesR5tlentintt_svn_xml_url_reRt ValueErrorRt _svn_rev_retfinditerRRt_svn_info_xml_url_ret_svn_info_xml_rev_reRRB( RRRPt entries_pathtftdataRtdtrevsRtmtxmlR(((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR@s>! I; 5 cC@s[|j|}|dkrdS|jjddd}|j|}d|||fS(NR1iissvn+%s@%s#egg=%s(RORtegg_nameR5RK(RR8Rtrepotegg_project_nameR(((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pytget_src_requirements  cC@stS(s&Always assume the versions don't match(R(RR+R)((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyt check_versionscC@sYtj|}|jjdd}|j||j|j|jf}tj|}|S(Nt@i( t urllib_parseturlsplittnetlocR5tschemeR&tquerytfragmentt urlunsplit(Rtpurltstripped_netloct url_piecestsurl((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR$s !(R ssvn+sshssvn+https svn+httpsssvn+svn(t__name__t __module__tnameR>t repo_nametschemesR R!R*R,R0R:RKR"ROR@RmRnt staticmethodR$(((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyRs"          , cC@s|rd|g}ng}tj|}t|drO|j|j}}nl|d}d|kr|jdd}d|kr|jdd\}}q|d}}n d \}}|r|d|g7}n|r|d|g7}n|S( Ns-rtusernameiRoit:s --usernames --password(NN(RpRqthasattrRtpasswordR5R(RR(R)trRRRrtauth((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyR#s$    (t __future__RtloggingR%tretpip._vendor.six.moves.urllibRRpt pip.indexRt pip.utilsRRtpip.utils.loggingRtpip.vcsRRtcompileR]R_RRRbRat getLoggerR{RRR#tregister(((s6/usr/lib/python2.7/site-packages/pip/vcs/subversion.pyts$    __main__.pyc000064400000000744152527136320007014 0ustar00 abc@@sddlmZddlZddlZedkrhejjejjeZejjdenddl Z e dkrej e j ndS(i(tabsolute_importNtt__main__( t __future__Rtostsyst __package__tpathtdirnamet__file__tinserttpipt__name__texittmain(((s0/usr/lib/python2.7/site-packages/pip/__main__.pyts     basecommand.py000064400000027206152527136320007404 0ustar00"""Base Command class, and related routines""" from __future__ import absolute_import import logging import os import sys import optparse import warnings from pip import cmdoptions from pip.index import PackageFinder from pip.locations import running_under_virtualenv from pip.download import PipSession from pip.exceptions import (BadCommand, InstallationError, UninstallationError, CommandError, PreviousBuildDirError) from pip.compat import logging_dictConfig from pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter from pip.req import InstallRequirement, parse_requirements from pip.status_codes import ( SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND, PREVIOUS_BUILD_DIR_ERROR, ) from pip.utils import deprecation, get_prog, normalize_path from pip.utils.logging import IndentingFormatter from pip.utils.outdated import pip_version_check __all__ = ['Command'] logger = logging.getLogger(__name__) class Command(object): name = None usage = None hidden = False log_streams = ("ext://sys.stdout", "ext://sys.stderr") def __init__(self, isolated=False): parser_kw = { 'usage': self.usage, 'prog': '%s %s' % (get_prog(), self.name), 'formatter': UpdatingDefaultsHelpFormatter(), 'add_help_option': False, 'name': self.name, 'description': self.__doc__, 'isolated': isolated, } self.parser = ConfigOptionParser(**parser_kw) # Commands should add options to this option group optgroup_name = '%s Options' % self.name.capitalize() self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name) # Add the general options gen_opts = cmdoptions.make_option_group( cmdoptions.general_group, self.parser, ) self.parser.add_option_group(gen_opts) def _build_session(self, options, retries=None, timeout=None): session = PipSession( cache=( normalize_path(os.path.join(options.cache_dir, "http")) if options.cache_dir else None ), retries=retries if retries is not None else options.retries, insecure_hosts=options.trusted_hosts, ) # Handle custom ca-bundles from the user if options.cert: session.verify = options.cert # Handle SSL client certificate if options.client_cert: session.cert = options.client_cert # Handle timeouts if options.timeout or timeout: session.timeout = ( timeout if timeout is not None else options.timeout ) # Handle configured proxies if options.proxy: session.proxies = { "http": options.proxy, "https": options.proxy, } # Determine if we can prompt the user for authentication or not session.auth.prompting = not options.no_input return session def parse_args(self, args): # factored out for testability return self.parser.parse_args(args) def main(self, args): options, args = self.parse_args(args) if options.quiet: if options.quiet == 1: level = "WARNING" if options.quiet == 2: level = "ERROR" else: level = "CRITICAL" elif options.verbose: level = "DEBUG" else: level = "INFO" # The root logger should match the "console" level *unless* we # specified "--log" to send debug logs to a file. root_level = level if options.log: root_level = "DEBUG" logging_dictConfig({ "version": 1, "disable_existing_loggers": False, "filters": { "exclude_warnings": { "()": "pip.utils.logging.MaxLevelFilter", "level": logging.WARNING, }, }, "formatters": { "indent": { "()": IndentingFormatter, "format": "%(message)s", }, }, "handlers": { "console": { "level": level, "class": "pip.utils.logging.ColorizedStreamHandler", "stream": self.log_streams[0], "filters": ["exclude_warnings"], "formatter": "indent", }, "console_errors": { "level": "WARNING", "class": "pip.utils.logging.ColorizedStreamHandler", "stream": self.log_streams[1], "formatter": "indent", }, "user_log": { "level": "DEBUG", "class": "pip.utils.logging.BetterRotatingFileHandler", "filename": options.log or "/dev/null", "delay": True, "formatter": "indent", }, }, "root": { "level": root_level, "handlers": list(filter(None, [ "console", "console_errors", "user_log" if options.log else None, ])), }, # Disable any logging besides WARNING unless we have DEBUG level # logging enabled. These use both pip._vendor and the bare names # for the case where someone unbundles our libraries. "loggers": dict( ( name, { "level": ( "WARNING" if level in ["INFO", "ERROR"] else "DEBUG" ), }, ) for name in ["pip._vendor", "distlib", "requests", "urllib3"] ), }) if sys.version_info[:2] == (2, 6): warnings.warn( "Python 2.6 is no longer supported by the Python core team, " "please upgrade your Python. A future version of pip will " "drop support for Python 2.6", deprecation.Python26DeprecationWarning ) # TODO: try to get these passing down from the command? # without resorting to os.environ to hold these. if options.no_input: os.environ['PIP_NO_INPUT'] = '1' if options.exists_action: os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action) if options.require_venv: # If a venv is required check if it can really be found if not running_under_virtualenv(): logger.critical( 'Could not find an activated virtualenv (required).' ) sys.exit(VIRTUALENV_NOT_FOUND) try: status = self.run(options, args) # FIXME: all commands should return an exit status # and when it is done, isinstance is not needed anymore if isinstance(status, int): return status except PreviousBuildDirError as exc: logger.critical(str(exc)) logger.debug('Exception information:', exc_info=True) return PREVIOUS_BUILD_DIR_ERROR except (InstallationError, UninstallationError, BadCommand) as exc: logger.critical(str(exc)) logger.debug('Exception information:', exc_info=True) return ERROR except CommandError as exc: logger.critical('ERROR: %s', exc) logger.debug('Exception information:', exc_info=True) return ERROR except KeyboardInterrupt: logger.critical('Operation cancelled by user') logger.debug('Exception information:', exc_info=True) return ERROR except: logger.critical('Exception:', exc_info=True) return UNKNOWN_ERROR finally: # Check if we're using the latest version of pip available if (not options.disable_pip_version_check and not getattr(options, "no_index", False)): with self._build_session( options, retries=0, timeout=min(5, options.timeout)) as session: pip_version_check(session) return SUCCESS class RequirementCommand(Command): @staticmethod def populate_requirement_set(requirement_set, args, options, finder, session, name, wheel_cache): """ Marshal cmd line args into a requirement set. """ for filename in options.constraints: for req in parse_requirements( filename, constraint=True, finder=finder, options=options, session=session, wheel_cache=wheel_cache): requirement_set.add_requirement(req) for req in args: requirement_set.add_requirement( InstallRequirement.from_line( req, None, isolated=options.isolated_mode, wheel_cache=wheel_cache ) ) for req in options.editables: requirement_set.add_requirement( InstallRequirement.from_editable( req, default_vcs=options.default_vcs, isolated=options.isolated_mode, wheel_cache=wheel_cache ) ) found_req_in_file = False for filename in options.requirements: for req in parse_requirements( filename, finder=finder, options=options, session=session, wheel_cache=wheel_cache): found_req_in_file = True requirement_set.add_requirement(req) # If --require-hashes was a line in a requirements file, tell # RequirementSet about it: requirement_set.require_hashes = options.require_hashes if not (args or options.editables or found_req_in_file): opts = {'name': name} if options.find_links: msg = ('You must give at least one requirement to ' '%(name)s (maybe you meant "pip %(name)s ' '%(links)s"?)' % dict(opts, links=' '.join(options.find_links))) else: msg = ('You must give at least one requirement ' 'to %(name)s (see "pip help %(name)s")' % opts) logger.warning(msg) def _build_package_finder(self, options, session, platform=None, python_versions=None, abi=None, implementation=None): """ Create a package finder appropriate to this requirement command. """ index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.debug('Ignoring indexes: %s', ','.join(index_urls)) index_urls = [] return PackageFinder( find_links=options.find_links, format_control=options.format_control, index_urls=index_urls, trusted_hosts=options.trusted_hosts, allow_all_prereleases=options.pre, process_dependency_links=options.process_dependency_links, session=session, platform=platform, versions=python_versions, abi=abi, implementation=implementation, ) basecommand.pyo000064400000021347152527136320007563 0ustar00 abc@@sdZddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZddlmZmZmZmZmZdd lmZdd lmZmZdd lmZmZdd lmZm Z m!Z!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'ddl(m)Z)ddl*m+Z+dgZ,ej-e.Z/de0fdYZ1de1fdYZ2dS(s(Base Command class, and related routinesi(tabsolute_importN(t cmdoptions(t PackageFinder(trunning_under_virtualenv(t PipSession(t BadCommandtInstallationErrortUninstallationErrort CommandErrortPreviousBuildDirError(tlogging_dictConfig(tConfigOptionParsertUpdatingDefaultsHelpFormatter(tInstallRequirementtparse_requirements(tSUCCESStERRORt UNKNOWN_ERRORtVIRTUALENV_NOT_FOUNDtPREVIOUS_BUILD_DIR_ERROR(t deprecationtget_progtnormalize_path(tIndentingFormatter(tpip_version_checktCommandcB@sMeZdZdZeZdZedZdddZ dZ dZ RS(sext://sys.stdoutsext://sys.stderrcC@si|jd6dt|jfd6td6td6|jd6|jd6|d6}t||_d |jj}t j |j||_ t j t j|j}|jj|dS( Ntusages%s %stprogt formattertadd_help_optiontnamet descriptiontisolateds %s Options(RRRR tFalset__doc__R tparsert capitalizetoptparset OptionGrouptcmd_optsRtmake_option_groupt general_grouptadd_option_group(tselfR t parser_kwt optgroup_nametgen_opts((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyt__init__)s      cC@std|jr-ttjj|jdndd|dk rE|n|jd|j}|j rr|j |_ n|j r|j |_ n|j s|r|dk r|n|j |_ n|j ri|j d6|j d6|_n|j |j_|S(Ntcachethttptretriestinsecure_hoststhttps(Rt cache_dirRtostpathtjointNoneR2t trusted_hoststcerttverifyt client_certttimeouttproxytproxiestno_inputtautht prompting(R+toptionsR2R>tsession((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyt_build_sessionAs -   !  cC@s|jj|S(N(R#t parse_args(R+targs((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyRGesc @s|j|\}}|jrW|jdkr6dn|jdkrNdqodn|jridnd}|jrd}ntidd6td 6iid d 6tjd 6d 6d6iitd 6dd6d6d6iid 6dd6|j dd6d gd6dd6d6idd 6dd6|j dd6dd6d6idd 6dd6|jpTdd6t d6dd6d6d6i|d 6t t ddd|jrdndgd6d 6tfd!d"d#d$d%gDd&6tjd d7krtjd(tjn|jrd)tjd*d+j|jtjd,s s pip._vendortdistlibtrequeststurllib3tloggersisPython 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6t1t PIP_NO_INPUTt tPIP_EXISTS_ACTIONs2Could not find an activated virtualenv (required).sException information:texc_infos ERROR: %ssOperation cancelled by users Exception:tno_indexR2R>i(ii(5RGtquiettverbosetlogR R!tloggingRIRt log_streamstTruetlisttfilterR9tdicttsyst version_infotwarningstwarnRtPython26DeprecationWarningRAR6tenviront exists_actionR8t require_venvRtloggertcriticaltexitRtrunt isinstancetintR tstrtdebugRRRRRRtKeyboardInterruptRtdisable_pip_version_checktgetattrRFtminR>RR(R+RHRDt root_leveltstatustexcRE((ROs3/usr/lib/python2.7/site-packages/pip/basecommand.pytmainis            #          N(sext://sys.stdoutsext://sys.stderr( t__name__t __module__R9RRR!thiddenRmR/RFRGR(((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyR#s $ tRequirementCommandcB@s,eZedZdddddZRS(c C@sxS|jD]H}x?t|dtd|d|d|d|D]}|j|q;Wq Wx6|D].}|jtj|d d|jd|q]Wx?|jD]4}|jtj |d|j d|jd|qWt } xS|j D]H}x?t|d|d|d|d|D]}t} |j|q WqW|j |_ |pK|jpK| si|d6} |jrd t| d d j|j} n d | } tj| nd S(s? Marshal cmd line args into a requirement set. t constrainttfinderRDREt wheel_cacheR t default_vcsRs^You must give at least one requirement to %(name)s (maybe you meant "pip %(name)s %(links)s"?)tlinksResLYou must give at least one requirement to %(name)s (see "pip help %(name)s")N(t constraintsRRntadd_requirementR t from_lineR9t isolated_modet editablest from_editableRR!t requirementstrequire_hashest find_linksRqR8Rztwarning( trequirement_setRHRDRRERRRYtreqtfound_req_in_filetoptstmsg((s3/usr/lib/python2.7/site-packages/pip/basecommand.pytpopulate_requirement_setsF       "cC@s|jg|j}|jr>tjddj|g}ntd|jd|jd|d|j d|j d|j d |d |d |d |d | S(sR Create a package finder appropriate to this requirement command. sIgnoring indexes: %st,Rtformat_controlt index_urlsR:tallow_all_prereleasestprocess_dependency_linksREtplatformtversionstabitimplementation( t index_urltextra_index_urlsRhRzRR8RRRR:tpreR(R+RDRERtpython_versionsRRR((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyt_build_package_finder:s        N(RRt staticmethodRR9R(((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyRs8(3R"t __future__RRlR6RrR%RttpipRt pip.indexRt pip.locationsRt pip.downloadRtpip.exceptionsRRRRR t pip.compatR tpip.baseparserR R tpip.reqR Rtpip.status_codesRRRRRt pip.utilsRRRtpip.utils.loggingRtpip.utils.outdatedRt__all__t getLoggerRRztobjectRR(((s3/usr/lib/python2.7/site-packages/pip/basecommand.pyts,     (( locations.pyc000064400000011241152527136320007261 0ustar00 abc@@sdZddlmZddlZddlZddlZddlZddlmZddl m Z m Z ddl m Z mZddlmZejdZd Zd Zd Zd Zd ZerejjejdZn@yejjejdZWnek r+ejdnXejjeZej Z!ej"Z#edZ$e rejjejdZ%ejje#dZ&ejj'e%sejjejdZ%ejje#dZ&ndZ(ejje$dZ)ejje)e(Z*nejjejdZ%ejje#dZ&dZ(ejje$dZ)ejje)e(Z*ej+d dkrejd dkrdZ%ngej,dD]Zejjee(^qZ-e.dde.ddZ0dS(s7Locations where we look for configs, install stuff, etci(tabsolute_importN(t sysconfig(tinstallt SCHEME_KEYS(tWINDOWSt expanduser(tappdirstpipsThis file is placed here by pip to indicate the source was put here by pip. Once this package is successfully installed this source code will be deleted (unless you remove this file). spip-delete-this-directory.txtcC@s>tjj|t}t|d}|jtWdQXdS(s? Write the pip delete marker file into this directory. twN(tostpathtjointPIP_DELETE_MARKER_FILENAMEtopentwritetDELETE_MARKER_MESSAGE(t directorytfilepatht marker_fp((s1/usr/lib/python2.7/site-packages/pip/locations.pytwrite_delete_marker_filescC@s9ttdrtStjttdtjkr5tStS(sM Return True if we're running inside a virtualenv, False otherwise. t real_prefixt base_prefix(thasattrtsystTruetprefixtgetattrtFalse(((s1/usr/lib/python2.7/site-packages/pip/locations.pytrunning_under_virtualenv's cC@sYtjjtjjtj}tjj|d}trUtjj|rUt SdS(s? Return True if in a venv and no system site packages. sno-global-site-packages.txtN( R R tdirnametabspathtsitet__file__R RtisfileR(t site_mod_dirtno_global_file((s1/usr/lib/python2.7/site-packages/pip/locations.pytvirtualenv_no_global4s!tsrcs=The folder you are executing pip from can no longer be found.t~tScriptstbinspip.inispip.confs.pipitdarwinis/System/Library/s/usr/local/bincC@sddlm}i}|r/idgd6}ni}i|d6} | j||| } | j| jddt} |o| stdj|||p| j| _|rd | _ n|p| j | _ |p| j | _ |p| j | _ | j x%t D]} t| d | || tisolatedRR*tschemetextra_dist_argst dist_argstdtitkeyt path_no_drive((s1/usr/lib/python2.7/site-packages/pip/locations.pytdistutils_scheme|sH    %   %      (1t__doc__t __future__RR tos.pathRRt distutilsRtdistutils.command.installRRt pip.compatRRt pip.utilsRtuser_cache_dirtUSER_CACHE_DIRRR RRR$R R Rt src_prefixtgetcwdtOSErrortexitRtget_python_libt site_packagest USER_SITEt user_sitetuser_dirtbin_pytbin_usertexiststconfig_basenametlegacy_storage_dirtlegacy_config_filetplatformtsite_config_dirstsite_config_filesRRCRN(((s1/usr/lib/python2.7/site-packages/pip/locations.pytsd               & . _vendor/appdirs.pyo000064400000050246152527136320010410 0ustar00 abc@s@dZd,ZdjeeeZddlZddlZejddkZ e r^eZ nej j drddl Z e j ddZej d rd Zqej d rd Zqd Zn ej ZdddedZdddedZdddedZdddedZdddedZdddedZdefdYZdZdZdZdZed kr!yddlZ eZ!Wq!e"k ryddl#m$Z$eZ!Wqe"k ryddl%Z&eZ!Wqe"k reZ!qXqXq!Xne'dkr<dZ(dZ)d-Z*d$GHee(e)d%d&Z+x&e*D]Z,d'e,e-e+e,fGHq`Wd(GHee(e)Z+x&e*D]Z,d'e,e-e+e,fGHqWd)GHee(Z+x&e*D]Z,d'e,e-e+e,fGHqWd*GHee(d+eZ+x)e*D]Z,d'e,e-e+e,fGHqWndS(.syUtilities for determining application-specific dirs. See for details and usage. iiit.iNitjavatWindowstwin32tMactdarwintlinux2cCs6tdkr|dkr!|}n|r-dp0d}tjjt|}|r|tk rxtjj|||}qtjj||}qn{tdkrtjjd}|rtjj||}qn<tj dtjjd}|rtjj||}n|r2|r2tjj||}n|S( sJReturn full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: ~/Library/Application Support/ Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\\Application Data\\ Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ Win 7 (not roaming): C:\Users\\AppData\Local\\ Win 7 (roaming): C:\Users\\AppData\Roaming\\ For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/". Rt CSIDL_APPDATAtCSIDL_LOCAL_APPDATARs~/Library/Application Support/t XDG_DATA_HOMEs~/.local/shareN( tsystemtNonetostpathtnormpatht_get_win_foldertFalsetjoint expandusertgetenv(tappnamet appauthortversiontroamingtconstR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt user_data_dir-s&      cCstdkr|d kr!|}ntjjtd}|r|tk rftjj|||}q~tjj||}qntdkrtjjd}|rtjj||}qntj dtj jddg}g|j tj D]$}tjj|j tj ^q}|rs|rEtjj||}ng|D]}tj j||g^qL}n|rtj j|}n |d}|S|r|rtjj||}n|S( siReturn full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/', if XDG_DATA_DIRS is not set Typical user data directories are: macOS: /Library/Application Support/ Unix: /usr/local/share/ or /usr/share/ Win XP: C:\Documents and Settings\All Users\Application Data\\ Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. RtCSIDL_COMMON_APPDATARs/Library/Application Supportt XDG_DATA_DIRSs/usr/local/shares /usr/shareiN(R R R R RRRRRRtpathseptsplittrstriptsep(RRRt multipathR txtpathlist((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt site_data_dirds4      =.  cCstdkr$t||d|}n<tjdtjjd}|r`tjj||}n|r|rtjj||}n|S(sReturn full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: same as user_data_dir Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by deafult "~/.config/". RRtXDG_CONFIG_HOMEs ~/.config(RRN(R RR R RR RR(RRRRR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pytuser_config_dirs  cCs tdkrBt||}|r|rtjj||}qntjdd}g|jtjD]$}tjj|j tj ^qg}|r|rtjj||}ng|D]}tj j||g^q}n|rtjj|}n |d}|S(sReturn full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of config dirs should be returned. By default, the first item from XDG_CONFIG_DIRS is returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set Typical user data directories are: macOS: same as site_data_dir Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in $XDG_CONFIG_DIRS Win *: same as site_data_dir Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False WARNING: Do not use this on Windows. See the Vista-Fail note above for why. RRtXDG_CONFIG_DIRSs/etc/xdgi(RR( R R#R R RRRRRRR(RRRR R R!R"((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pytsite_config_dirs  =. cCsBtdkr|dkr!|}ntjjtd}|r|tk rftjj|||}ntjj||}|rtjj|d}qqn{tdkrtjjd}|rtjj||}qn<tj dtjjd}|rtjj||}n|r>|r>tjj||}n|S( sReturn full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: macOS: ~/Library/Caches/ Unix: ~/.cache/ (XDG default) Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache Vista: C:\Users\\AppData\Local\\\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. RRtCacheRs~/Library/CachestXDG_CACHE_HOMEs~/.cacheN( R R R R RRRRRR(RRRtopinionR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pytuser_cache_dirs(!      cCstdkr0tjjtjjd|}n{tdkrut|||}t}|rtjj|d}qn6t|||}t}|rtjj|d}n|r|rtjj||}n|S(sReturn full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user cache directories are: macOS: ~/Library/Logs/ Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs Vista: C:\Users\\AppData\Local\\\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. Rs~/Library/LogsRtLogstlog(R R R RRRRR+(RRRR*R ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt user_log_dir:s     tAppDirscBs}eZdZddeedZedZedZedZ edZ edZ edZ RS( s1Convenience wrapper for getting application dirs.cCs1||_||_||_||_||_dS(N(RRRRR (tselfRRRRR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt__init__os     cCs%t|j|jd|jd|jS(NRR(RRRRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyRwscCs%t|j|jd|jd|jS(NRR (R#RRRR (R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR#|scCs%t|j|jd|jd|jS(NRR(R%RRRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR%scCs%t|j|jd|jd|jS(NRR (R'RRRR (R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR'scCst|j|jd|jS(NR(R+RRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR+scCst|j|jd|jS(NR(R.RRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR.sN( t__name__t __module__t__doc__R RR1tpropertyRR#R%R'R+R.(((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR/ms  cCs\ddl}idd6dd6dd6|}|j|jd }|j||\}}|S( sThis is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. iNtAppDataRsCommon AppDataRs Local AppDataRs@Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders(t_winregtOpenKeytHKEY_CURRENT_USERt QueryValueEx(t csidl_nameR7tshell_folder_nametkeytdirttype((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_from_registrys  cCsddlm}m}|jdt||dd}yt|}t}x*|D]"}t|dkrSt}PqSqSW|ryddl }|j |}Wqt k rqXnWnt k rnX|S(Ni(tshellcontshellii( twin32com.shellRARBtSHGetFolderPathtgetattrtunicodeRtordtTruetwin32apitGetShortPathNamet ImportErrort UnicodeError(R;RARBR>t has_high_chartcRI((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_with_pywin32s$!      cCsddl}idd6dd6dd6|}|jd}|jjjd|dd |t}x*|D]"}t|d krft}PqfqfW|r|jd}|jj j |j |dr|}qn|j S( NiiRi#RiRiii( tctypestcreate_unicode_buffertwindlltshell32tSHGetFolderPathWR RRGRHtkernel32tGetShortPathNameWtvalue(R;RPt csidl_consttbufRMRNtbuf2((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_with_ctypess$   c Cs=ddl}ddlm}ddlm}|jjd}|jd|}|jj }|j dt |j |d|j j||jj|jjd}t}x*|D]"} t| dkrt}PqqW|r9|jd|}|jj } tj|||r9|jj|jjd}q9n|S(Ni(tjna(RiRNsi(tarraytcom.sunR\tcom.sun.jna.platformRtWinDeftMAX_PATHtzerostShell32tINSTANCERDR REtShlObjtSHGFP_TYPE_CURRENTtNativettoStringttostringRRRGRHtKernel32tkernalRJ( R;R]R\Rtbuf_sizeRYRBR>RMRNtkernel((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_with_jnas&  +!  '(RRt__main__tMyAppt MyCompanyRR#R%R'R+R.s%-- app dirs (with optional 'version')Rs1.0s%s: %ss) -- app dirs (without optional 'version')s+ -- app dirs (without optional 'appauthor')s( -- app dirs (with disabled 'appauthor')R(iii(RR#R%R'R+R.(.R4t__version_info__Rtmaptstrt __version__tsysR t version_infotPY3RFtplatformt startswithtjava_vertos_nameR R RRR#R%R'RHR+R.tobjectR/R@ROR[RnRCtwin32comRRKRPRRt com.sun.jnatcomR2RRtpropstdirstpropRE(((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt s~        7B(393+                   _vendor/retrying.pyc000064400000023735152527136320010600 0ustar00 abc@sddlZddlmZddlZddlZddlZdZdZdefdYZ defdYZ d e fd YZ dS( iN(tsixi?csStdkr9tdr9d}|dSfd}|SdS(s Decorator function that instantiates the Retrying object @param *dargs: positional arguments passed to Retrying object @param **dkw: keyword arguments passed to the Retrying object iics"tjfd}|S(Ncstj||S(N(tRetryingtcall(targstkw(tf(s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyt wrapped_f$s(Rtwraps(RR((Rs8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyt wrap_simple"scs(tjfd}|S(Ncstj||S(N(RR(RR(tdargstdkwR(s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR/s(RR(RR(R R (Rs8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pytwrap-s$N(tlentcallable(R R RR ((R R s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pytretrys " RcBseZd d d d d d d d d d d d d ed d d dZdZdZdZdZdZ dZ dZ dZ d Z d Zd ZRS( cs|dkrdn||_|dkr-dn||_|dkrHdn||_|dkrcdn||_|dkr~dn||_|dkrdn||_| dkrdn| |_| dkrdn| |_| dkrt n| |_ |dkrdn||_ g|dk r3j |j n|dk rRj |jn|dk rj||_n3|dkrfd|_nt|||_dg|dk rj |jn|dk s|dk rj |jn|dk s | dk rj |jn| dk s6| dk rIj |jn|dk ra||_n3|dkrfd|_nt|||_| dkr|j|_n | |_| dkr|j|_n | |_||_dS( NiidiiicstfdDS(Nc3s|]}|VqdS(N((t.0R(tattemptstdelay(s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pys as(tany(RR(t stop_funcs(RRs8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pytatc_sdS(Ni((Rtkwargs((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRhRcstfdDS(Nc3s|]}|VqdS(N((RR(RR(s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pys ys(tmax(RR(t wait_funcs(RRs8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRyR(tNonet_stop_max_attempt_numbert_stop_max_delayt _wait_fixedt_wait_random_mint_wait_random_maxt_wait_incrementing_startt_wait_incrementing_incrementt_wait_exponential_multipliertMAX_WAITt_wait_exponential_maxt_wait_jitter_maxtappendtstop_after_attempttstop_after_delaytstoptgetattrt fixed_sleept random_sleeptincrementing_sleeptexponential_sleeptwaitt always_rejectt_retry_on_exceptiont never_rejectt_retry_on_resultt_wrap_exception(tselfR(R.tstop_max_attempt_numbertstop_max_delayt wait_fixedtwait_random_mintwait_random_maxtwait_incrementing_starttwait_incrementing_incrementtwait_exponential_multipliertwait_exponential_maxtretry_on_exceptiontretry_on_resulttwrap_exceptiont stop_funct wait_functwait_jitter_max((RRs8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyt__init__:sR              cCs ||jkS(s;Stop after the previous attempt >= stop_max_attempt_number.(R(R4tprevious_attempt_numbertdelay_since_first_attempt_ms((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR&scCs ||jkS(s=Stop after the time from the first attempt >= stop_max_delay.(R(R4RERF((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR'scCsdS(s#Don't sleep at all before retrying.i((R4RERF((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pytno_sleepscCs|jS(s0Sleep a fixed amount of time between each retry.(R(R4RERF((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR*scCstj|j|jS(sISleep a random amount of time between wait_random_min and wait_random_max(trandomtrandintRR(R4RERF((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR+scCs1|j|j|d}|dkr-d}n|S(s Sleep an incremental amount of time after each attempt, starting at wait_incrementing_start and incrementing by wait_incrementing_increment ii(RR (R4RERFtresult((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR,s  cCsKd|}|j|}||jkr2|j}n|dkrGd}n|S(Nii(R!R#(R4RERFtexpRJ((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR-s     cCstS(N(tFalse(R4RJ((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR1scCstS(N(tTrue(R4RJ((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR/scCsFt}|jr,||j|jdO}n||j|jO}|S(Ni(RLt has_exceptionR0tvalueR2(R4tattempttreject((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyt should_rejects  c Os[tttjd}d}x2trVyt||||t}Wn%tj}t||t}nX|j|s|j |j Stttjd|}|j ||r|j r|j r|j qIt |nU|j||} |jr8tj|j} | td| } ntj| d|d7}q%WdS(Niiig@@(tinttroundttimeRMtAttemptRLtsystexc_infoRRtgetR3R(RNt RetryErrorR.R$RHRtsleep( R4tfnRRt start_timetattempt_numberRPttbRFR[tjitter((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRs*    N(t__name__t __module__RRLRDR&R'RGR*R+R,R-R1R/RRR(((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyR8s0 F        RVcBs,eZdZdZedZdZRS(s An Attempt encapsulates a call to a target function that may end as a normal return value from the function or an Exception depending on what occurred during the execution. cCs||_||_||_dS(N(ROR^RN(R4ROR^RN((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRDs  cCsT|jrI|rt|qPtj|jd|jd|jdn|jSdS(s Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised. iiiN(RNRZRtreraiseRO(R4R@((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRYs  +cCsO|jr5dj|jdjtj|jdSdj|j|jSdS(NsAttempts: {0}, Error: {1}RisAttempts: {0}, Value: {1}(RNtformatR^tjoint tracebackt format_tbRO(R4((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyt__repr__s ,(RaRbt__doc__RDRLRYRh(((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRVs  RZcBs eZdZdZdZRS(sU A RetryError encapsulates the last Attempt instance right before giving up. cCs ||_dS(N(t last_attempt(R4Rj((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRDscCsdj|jS(NsRetryError[{0}](RdRj(R4((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyt__str__ s(RaRbRiRDRk(((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyRZs ( RHt pip._vendorRRWRURfR"RtobjectRRVt ExceptionRZ(((s8/usr/lib/python2.7/site-packages/pip/_vendor/retrying.pyts     !_vendor/appdirs.pyc000064400000050246152527136320010374 0ustar00 abc@s@dZd,ZdjeeeZddlZddlZejddkZ e r^eZ nej j drddl Z e j ddZej d rd Zqej d rd Zqd Zn ej ZdddedZdddedZdddedZdddedZdddedZdddedZdefdYZdZdZdZdZed kr!yddlZ eZ!Wq!e"k ryddl#m$Z$eZ!Wqe"k ryddl%Z&eZ!Wqe"k reZ!qXqXq!Xne'dkr<dZ(dZ)d-Z*d$GHee(e)d%d&Z+x&e*D]Z,d'e,e-e+e,fGHq`Wd(GHee(e)Z+x&e*D]Z,d'e,e-e+e,fGHqWd)GHee(Z+x&e*D]Z,d'e,e-e+e,fGHqWd*GHee(d+eZ+x)e*D]Z,d'e,e-e+e,fGHqWndS(.syUtilities for determining application-specific dirs. See for details and usage. iiit.iNitjavatWindowstwin32tMactdarwintlinux2cCs6tdkr|dkr!|}n|r-dp0d}tjjt|}|r|tk rxtjj|||}qtjj||}qn{tdkrtjjd}|rtjj||}qn<tj dtjjd}|rtjj||}n|r2|r2tjj||}n|S( sJReturn full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: ~/Library/Application Support/ Unix: ~/.local/share/ # or in $XDG_DATA_HOME, if defined Win XP (not roaming): C:\Documents and Settings\\Application Data\\ Win XP (roaming): C:\Documents and Settings\\Local Settings\Application Data\\ Win 7 (not roaming): C:\Users\\AppData\Local\\ Win 7 (roaming): C:\Users\\AppData\Roaming\\ For Unix, we follow the XDG spec and support $XDG_DATA_HOME. That means, by default "~/.local/share/". Rt CSIDL_APPDATAtCSIDL_LOCAL_APPDATARs~/Library/Application Support/t XDG_DATA_HOMEs~/.local/shareN( tsystemtNonetostpathtnormpatht_get_win_foldertFalsetjoint expandusertgetenv(tappnamet appauthortversiontroamingtconstR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt user_data_dir-s&      cCstdkr|d kr!|}ntjjtd}|r|tk rftjj|||}q~tjj||}qntdkrtjjd}|rtjj||}qntj dtj jddg}g|j tj D]$}tjj|j tj ^q}|rs|rEtjj||}ng|D]}tj j||g^qL}n|rtj j|}n |d}|S|r|rtjj||}n|S( siReturn full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of data dirs should be returned. By default, the first item from XDG_DATA_DIRS is returned, or '/usr/local/share/', if XDG_DATA_DIRS is not set Typical user data directories are: macOS: /Library/Application Support/ Unix: /usr/local/share/ or /usr/share/ Win XP: C:\Documents and Settings\All Users\Application Data\\ Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) Win 7: C:\ProgramData\\ # Hidden, but writeable on Win 7. For Unix, this is using the $XDG_DATA_DIRS[0] default. WARNING: Do not use this on Windows. See the Vista-Fail note above for why. RtCSIDL_COMMON_APPDATARs/Library/Application Supportt XDG_DATA_DIRSs/usr/local/shares /usr/shareiN(R R R R RRRRRRtpathseptsplittrstriptsep(RRRt multipathR txtpathlist((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt site_data_dirds4      =.  cCstdkr$t||d|}n<tjdtjjd}|r`tjj||}n|r|rtjj||}n|S(sReturn full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "roaming" (boolean, default False) can be set True to use the Windows roaming appdata directory. That means that for users on a Windows network setup for roaming profiles, this user data will be sync'd on login. See for a discussion of issues. Typical user data directories are: macOS: same as user_data_dir Unix: ~/.config/ # or in $XDG_CONFIG_HOME, if defined Win *: same as user_data_dir For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME. That means, by deafult "~/.config/". RRtXDG_CONFIG_HOMEs ~/.config(RRN(R RR R RR RR(RRRRR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pytuser_config_dirs  cCs tdkrBt||}|r|rtjj||}qntjdd}g|jtjD]$}tjj|j tj ^qg}|r|rtjj||}ng|D]}tj j||g^q}n|rtjj|}n |d}|S(sReturn full path to the user-shared data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "multipath" is an optional parameter only applicable to *nix which indicates that the entire list of config dirs should be returned. By default, the first item from XDG_CONFIG_DIRS is returned, or '/etc/xdg/', if XDG_CONFIG_DIRS is not set Typical user data directories are: macOS: same as site_data_dir Unix: /etc/xdg/ or $XDG_CONFIG_DIRS[i]/ for each value in $XDG_CONFIG_DIRS Win *: same as site_data_dir Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.) For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False WARNING: Do not use this on Windows. See the Vista-Fail note above for why. RRtXDG_CONFIG_DIRSs/etc/xdgi(RR( R R#R R RRRRRRR(RRRR R R!R"((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pytsite_config_dirs  =. cCsBtdkr|dkr!|}ntjjtd}|r|tk rftjj|||}ntjj||}|rtjj|d}qqn{tdkrtjjd}|rtjj||}qn<tj dtjjd}|rtjj||}n|r>|r>tjj||}n|S( sReturn full path to the user-specific cache dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Cache" to the base app data dir for Windows. See discussion below. Typical user cache directories are: macOS: ~/Library/Caches/ Unix: ~/.cache/ (XDG default) Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Cache Vista: C:\Users\\AppData\Local\\\Cache On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming app data dir (the default returned by `user_data_dir` above). Apps typically put cache data somewhere *under* the given dir here. Some examples: ...\Mozilla\Firefox\Profiles\\Cache ...\Acme\SuperApp\Cache\1.0 OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value. This can be disabled with the `opinion=False` option. RRtCacheRs~/Library/CachestXDG_CACHE_HOMEs~/.cacheN( R R R R RRRRRR(RRRtopinionR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pytuser_cache_dirs(!      cCstdkr0tjjtjjd|}n{tdkrut|||}t}|rtjj|d}qn6t|||}t}|rtjj|d}n|r|rtjj||}n|S(sReturn full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. "appauthor" (only used on Windows) is the name of the appauthor or distributing body for this application. Typically it is the owning company name. This falls back to appname. You may pass False to disable it. "version" is an optional version path element to append to the path. You might want to use this if you want multiple versions of your app to be able to run independently. If used, this would typically be ".". Only applied when appname is present. "opinion" (boolean) can be False to disable the appending of "Logs" to the base app data dir for Windows, and "log" to the base cache dir for Unix. See discussion below. Typical user cache directories are: macOS: ~/Library/Logs/ Unix: ~/.cache//log # or under $XDG_CACHE_HOME if defined Win XP: C:\Documents and Settings\\Local Settings\Application Data\\\Logs Vista: C:\Users\\AppData\Local\\\Logs On Windows the only suggestion in the MSDN docs is that local settings go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in examples of what some windows apps use for a logs dir.) OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA` value for Windows and appends "log" to the user cache dir for Unix. This can be disabled with the `opinion=False` option. Rs~/Library/LogsRtLogstlog(R R R RRRRR+(RRRR*R ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt user_log_dir:s     tAppDirscBs}eZdZddeedZedZedZedZ edZ edZ edZ RS( s1Convenience wrapper for getting application dirs.cCs1||_||_||_||_||_dS(N(RRRRR (tselfRRRRR ((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt__init__os     cCs%t|j|jd|jd|jS(NRR(RRRRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyRwscCs%t|j|jd|jd|jS(NRR (R#RRRR (R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR#|scCs%t|j|jd|jd|jS(NRR(R%RRRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR%scCs%t|j|jd|jd|jS(NRR (R'RRRR (R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR'scCst|j|jd|jS(NR(R+RRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR+scCst|j|jd|jS(NR(R.RRR(R0((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR.sN( t__name__t __module__t__doc__R RR1tpropertyRR#R%R'R+R.(((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyR/ms  cCs\ddl}idd6dd6dd6|}|j|jd }|j||\}}|S( sThis is a fallback technique at best. I'm not sure if using the registry for this guarantees us the correct answer for all CSIDL_* names. iNtAppDataRsCommon AppDataRs Local AppDataRs@Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders(t_winregtOpenKeytHKEY_CURRENT_USERt QueryValueEx(t csidl_nameR7tshell_folder_nametkeytdirttype((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_from_registrys  cCsddlm}m}|jdt||dd}yt|}t}x*|D]"}t|dkrSt}PqSqSW|ryddl }|j |}Wqt k rqXnWnt k rnX|S(Ni(tshellcontshellii( twin32com.shellRARBtSHGetFolderPathtgetattrtunicodeRtordtTruetwin32apitGetShortPathNamet ImportErrort UnicodeError(R;RARBR>t has_high_chartcRI((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_with_pywin32s$!      cCsddl}idd6dd6dd6|}|jd}|jjjd|dd |t}x*|D]"}t|d krft}PqfqfW|r|jd}|jj j |j |dr|}qn|j S( NiiRi#RiRiii( tctypestcreate_unicode_buffertwindlltshell32tSHGetFolderPathWR RRGRHtkernel32tGetShortPathNameWtvalue(R;RPt csidl_consttbufRMRNtbuf2((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_with_ctypess$   c Cs=ddl}ddlm}ddlm}|jjd}|jd|}|jj }|j dt |j |d|j j||jj|jjd}t}x*|D]"} t| dkrt}PqqW|r9|jd|}|jj } tj|||r9|jj|jjd}q9n|S(Ni(tjna(RiRNsi(tarraytcom.sunR\tcom.sun.jna.platformRtWinDeftMAX_PATHtzerostShell32tINSTANCERDR REtShlObjtSHGFP_TYPE_CURRENTtNativettoStringttostringRRRGRHtKernel32tkernalRJ( R;R]R\Rtbuf_sizeRYRBR>RMRNtkernel((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt_get_win_folder_with_jnas&  +!  '(RRt__main__tMyAppt MyCompanyRR#R%R'R+R.s%-- app dirs (with optional 'version')Rs1.0s%s: %ss) -- app dirs (without optional 'version')s+ -- app dirs (without optional 'appauthor')s( -- app dirs (with disabled 'appauthor')R(iii(RR#R%R'R+R.(.R4t__version_info__Rtmaptstrt __version__tsysR t version_infotPY3RFtplatformt startswithtjava_vertos_nameR R RRR#R%R'RHR+R.tobjectR/R@ROR[RnRCtwin32comRRKRPRRt com.sun.jnatcomR2RRtpropstdirstpropRE(((s7/usr/lib/python2.7/site-packages/pip/_vendor/appdirs.pyt s~        7B(393+                   _vendor/pyparsing.pyo000064400000701330152527136320010757 0ustar00 abci@sdZdZdZdZddlZddlmZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlmZyddlmZWn!ek rddlmZnXydd l mZWn?ek r=ydd lmZWnek r9eZnXnXd d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrgiZee jds ZedtdskZere jZ e!Z"e#Z$e!Z%e&e'e(e)e*ee+e,e-e.e/g Z0nre j1Z e2Z3duZ%gZ0ddl4Z4xEdvj5D]7Z6ye0j7e8e4e6Wne9k rZq$nXq$We:dwe3dxDZ;dyZ<dze=fd{YZ>ej?ej@ZAd|ZBeBd}ZCeAeBZDe#d~ZEdjFdejGDZHd!eIfdYZJd#eJfdYZKd%eJfdYZLd'eLfdYZMd*eIfdYZNde=fdYZOd&e=fdYZPe jQjRePdZSdZTdZUdZVdZWdZXdZYddZZd(e=fdYZ[d0e[fdYZ\de\fdYZ]de\fdYZ^de\fdYZ_e_Z`e_e[_ade\fdYZbd e_fdYZcd ebfdYZddpe\fdYZed3e\fdYZfd+e\fdYZgd)e\fdYZhd e\fdYZid2e\fdYZjde\fdYZkdekfdYZldekfdYZmdekfdYZnd.ekfdYZod-ekfdYZpd5ekfdYZqd4ekfdYZrd$e[fdYZsd esfdYZtd esfdYZudesfdYZvdesfdYZwd"e[fdYZxdexfdYZydexfdYZzdexfdYZ{de{fdYZ|d6e{fdYZ}de=fdYZ~e~ZdexfdYZd,exfdYZdexfdYZdefdYZd1exfdYZdefdYZdefdYZdefdYZd/efdYZde=fdYZdZdedZedZdZdZdZdZeedZdZedZdZdZe]jdGZemjdMZenjdLZeojdeZepjddZefeEdddjdZegdjdZegdjdZeeBeBefeHddddxBegde jBZeeedeZe_dedjdee|eeBjddZdZdZdZdZdZedZedZdZdZdZdZe=e_ddZe>Ze=e_e=e_ededdZeZeegddjdZeegddjdZeegddegddBjdZee`dejjdZddeejdZedZedZedZeefeAeDdjd\ZZeedj5dZegddjFejdjdZdZeegddjdZegdjdZegd jjd Zegd jd ZeegddeBjd ZeZegdjdZee|efeHddeefde_denjjdZeeejeBddjd>ZdrfdYZedkrecdZecdZefeAeDdZeeddejeZeeejdZdeBZeeddejeZeeejdZededeedZejdejjdejjdejjd ddlZejjeejejjd!ndS("sS pyparsing module - Classes and methods to define and execute parsing grammars The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python. Here is a program to parse "Hello, World!" (or any greeting of the form C{", !"}), built up using L{Word}, L{Literal}, and L{And} elements (L{'+'} operator gives L{And} expressions, strings are auto-converted to L{Literal} expressions):: from pyparsing import Word, alphas # define grammar of a greeting greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) The program outputs the following:: Hello, World! -> ['Hello', ',', 'World', '!'] The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of '+', '|' and '^' operators. The L{ParseResults} object returned from L{ParserElement.parseString} can be accessed as a nested list, a dictionary, or an object with named attributes. The pyparsing module handles some of the problems that are typically vexing when writing text parsers: - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.) - quoted strings - embedded comments s2.1.10s07 Oct 2016 01:31 UTCs*Paul McGuire iN(tref(tdatetime(tRLock(t OrderedDicttAndtCaselessKeywordtCaselessLiteralt CharsNotIntCombinetDicttEachtEmptyt FollowedBytForwardt GoToColumntGrouptKeywordtLineEndt LineStarttLiteralt MatchFirsttNoMatchtNotAnyt OneOrMoretOnlyOncetOptionaltOrtParseBaseExceptiontParseElementEnhancetParseExceptiontParseExpressiontParseFatalExceptiont ParseResultstParseSyntaxExceptiont ParserElementt QuotedStringtRecursiveGrammarExceptiontRegextSkipTot StringEndt StringStarttSuppresstTokentTokenConvertertWhitetWordtWordEndt WordStartt ZeroOrMoret alphanumstalphast alphas8bitt anyCloseTagt anyOpenTagt cStyleCommenttcoltcommaSeparatedListtcommonHTMLEntityt countedArraytcppStyleCommenttdblQuotedStringtdblSlashCommentt delimitedListtdictOftdowncaseTokenstemptythexnumst htmlCommenttjavaStyleCommenttlinetlineEndt lineStarttlinenot makeHTMLTagst makeXMLTagstmatchOnlyAtColtmatchPreviousExprtmatchPreviousLiteralt nestedExprtnullDebugActiontnumstoneOftopAssoctoperatorPrecedencet printablestpunc8bittpythonStyleCommentt quotedStringt removeQuotestreplaceHTMLEntityt replaceWitht restOfLinetsglQuotedStringtsranget stringEndt stringStartttraceParseActiont unicodeStringt upcaseTokenst withAttributet indentedBlocktoriginalTextFortungroupt infixNotationt locatedExprt withClasst CloseMatchttokenMaptpyparsing_commoniicCs}t|tr|Syt|SWnUtk rxt|jtjd}td}|jd|j |SXdS(sDrop-in replacement for str(obj) that tries to be Unicode friendly. It first tries str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It then < returns the unicode object | encodes it with the default encoding | ... >. txmlcharrefreplaces&#\d+;cSs#dtt|ddd!dS(Ns\uiii(thextint(tt((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyttN( t isinstancetunicodetstrtUnicodeEncodeErrortencodetsystgetdefaultencodingR%tsetParseActionttransformString(tobjtrett xmlcharref((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt_ustrs  s6sum len sorted reversed list tuple set any all min maxccs|] }|VqdS(N((t.0ty((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys sicCsRd}ddjD}x/t||D]\}}|j||}q,W|S(s/Escape &, <, >, ", ', etc. in a string of data.s&><"'css|]}d|dVqdS(t&t;N((Rts((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys ssamp gt lt quot apos(tsplittziptreplace(tdatat from_symbolst to_symbolstfrom_tto_((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt _xml_escapes t _ConstantscBseZRS((t__name__t __module__(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRst 0123456789t ABCDEFabcdefi\Rrccs$|]}|tjkr|VqdS(N(tstringt whitespace(Rtc((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys scBs_eZdZdd d dZedZdZdZdZ ddZ d Z RS( s7base exception class for all parsing runtime exceptionsicCs[||_|dkr*||_d|_n||_||_||_|||f|_dS(NRr(tloctNonetmsgtpstrt parserElementtargs(tselfRRRtelem((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__init__s       cCs||j|j|j|jS(s internal factory method to simplify creating one type of ParseException from another - avoids having __init__ signature conflicts among subclasses (RRRR(tclstpe((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt_from_exceptionscCsm|dkrt|j|jS|dkr>t|j|jS|dkr]t|j|jSt|dS(ssupported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text RHR7tcolumnREN(R7R(RHRRR7REtAttributeError(Rtaname((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt __getattr__s   cCs d|j|j|j|jfS(Ns"%s (at char %d), (line:%d, col:%d)(RRRHR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__str__scCs t|S(N(R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__repr__ss>!} ('-' operator) indicates that parsing is to stop immediately because an unbacktrackable syntax error has been found(RRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR!scBs eZdZdZdZRS(sZexception thrown by L{ParserElement.validate} if the grammar could be improperly recursivecCs ||_dS(N(tparseElementTrace(RtparseElementList((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCs d|jS(NsRecursiveGrammarException: %s(R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s(RRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR$s t_ParseResultsWithOffsetcBs,eZdZdZdZdZRS(cCs||f|_dS(N(ttup(Rtp1tp2((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR$scCs |j|S(N(R(Rti((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt __getitem__&scCst|jdS(Ni(treprR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR(scCs|jd|f|_dS(Ni(R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt setOffset*s(RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR#s   cBseZdZd-d-eedZd-d-eeedZdZedZ dZ dZ dZ dZ e Zd Zd Zd Zd Zd ZereZeZeZn-eZeZeZdZdZdZdZdZd-dZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'ddZ(d Z)d!Z*d"Z+d-e,ded#Z-d$Z.d%Z/dd&ed'Z0d(Z1d)Z2d*Z3d+Z4d,Z5RS(.sI Structured parse results, to provide multiple means of access to the parsed data: - as a list (C{len(results)}) - by list index (C{results[0], results[1]}, etc.) - by attribute (C{results.} - see L{ParserElement.setResultsName}) Example:: integer = Word(nums) date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: # date_str = integer("year") + '/' + integer("month") + '/' + integer("day") # parseString returns a ParseResults object result = date_str.parseString("1999/12/31") def test(s, fn=repr): print("%s -> %s" % (s, fn(eval(s)))) test("list(result)") test("result[0]") test("result['month']") test("result.day") test("'month' in result") test("'minutes' in result") test("result.dump()", str) prints:: list(result) -> ['1999', '/', '12', '/', '31'] result[0] -> '1999' result['month'] -> '12' result.day -> '31' 'month' in result -> True 'minutes' in result -> False result.dump() -> ['1999', '/', '12', '/', '31'] - day: 31 - month: 12 - year: 1999 cCs/t||r|Stj|}t|_|S(N(Rstobjectt__new__tTruet_ParseResults__doinit(RttoklisttnametasListtmodaltretobj((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRTs  cCs|jrt|_d|_d|_i|_||_||_|dkrTg}n||trp||_ n-||t rt||_ n |g|_ t |_ n|dk r|r|sd|j|s(R(R((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt _itervaluesscsfdjDS(Nc3s|]}||fVqdS(N((RR(R(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s(R(R((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt _iteritemsscCst|jS(sVReturns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).(RR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytkeysscCst|jS(sXReturns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).(Rt itervalues(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytvaluesscCst|jS(sfReturns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).(Rt iteritems(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCs t|jS(sSince keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.(tboolR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pythaskeysscOs|sdg}nxI|jD];\}}|dkrJ|d|f}qtd|qWt|dtst|dks|d|kr|d}||}||=|S|d}|SdS(s Removes and returns item at specified index (default=C{last}). Supports both C{list} and C{dict} semantics for C{pop()}. If passed no argument or an integer argument, it will use C{list} semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use C{dict} semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in C{dict.pop()}. Example:: def remove_first(tokens): tokens.pop(0) print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + OneOrMore(Word(nums)) print(patt.parseString("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.addParseAction(remove_LABEL) print(patt.parseString("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: AAB ['AAB', '123', '321'] itdefaultis-pop() got an unexpected keyword argument '%s'iN(RRRsRoR(RRtkwargsRRtindexR}t defaultvalue((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytpops"     cCs||kr||S|SdS(si Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified. Similar to C{dict.get()}. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None N((Rtkeyt defaultValue((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs cCsw|jj||x]|jjD]L\}}x=t|D]/\}\}}t||||k|| ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed results def insert_locn(locn, tokens): tokens.insert(0, locn) print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321'] N(RtinsertRRRR(RRtinsStrRRRRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR2scCs|jj|dS(s Add single element to end of ParseResults list of elements. Example:: print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] N(Rtappend(Rtitem((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRFs cCs0t|tr||7}n|jj|dS(s Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' N(RsR Rtextend(Rtitemseq((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRTs  cCs|j2|jjdS(s7 Clear all elements and results names. N(RRtclear(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRfscCsy ||SWntk r dSX||jkr}||jkrR|j|ddStg|j|D]}|d^qcSndSdS(NRrii(RRRR (RRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRms  +cCs|j}||7}|S(N(R(RtotherR}((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__add__{s  c s|jrt|jfd}|jj}g|D]<\}}|D])}|t|d||df^qMq=}xJ|D]?\}}|||st](RR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRsRrcCsog}xb|jD]W}|r2|r2|j|nt|trT||j7}q|jt|qW|S(N(RRRsR t _asStringListR(RtseptoutR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs cCs5g|jD]'}t|tr+|jn|^q S(s Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> ['sldkj', 'lsdkj', 'sldkj'] # Use asList() to create an actual list result_list = result.asList() print(type(result_list), result_list) # -> ['sldkj', 'lsdkj', 'sldkj'] (RRsR R(Rtres((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscsGtr|j}n |j}fdtfd|DS(s Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(result), repr(result)) # -> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.asDict() print(type(result_dict), repr(result_dict)) # -> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} csMt|trE|jr%|jSg|D]}|^q,Sn|SdS(N(RsR RtasDict(R|R(ttoItem(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs    c3s'|]\}}||fVqdS(N((RRR(R(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s(tPY_3RRR(Rtitem_fn((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs    cCsPt|j}|jj|_|j|_|jj|j|j|_|S(sA Returns a new copy of a C{ParseResults} object. (R RRRRRR R(RR}((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs   c Csd}g}td|jjD}|d}|sPd}d}d}nd } |d k rk|} n|jr|j} n| s|rdSd} n|||d| dg7}x t|jD]\} } t| trI| |kr|| j || |o|d k||g7}q|| j d |o6|d k||g7}qd } | |krh|| } n| s|rzqqd} nt t | } |||d| d| d| dg 7}qW|||d| dg7}dj |S( s (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. s css2|](\}}|D]}|d|fVqqdS(iN((RRRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s s RrtITEMtsgss %s%s- %s: s icss|]}t|tVqdS(N(RsR (Rtvv((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys sss %s%s[%d]: %s%s%sRr( RRRRtsortedRRsR tdumpRtanyRR( RR$tdepthtfullRtNLRRRRR1((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR3Ps,  B?cOstj|j||dS(s Pretty-printer for parsed results as a list, using the C{pprint} module. Accepts additional positional or keyword args as defined for the C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint}) Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(delimitedList(term))) result = func.parseString("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] N(tpprintR(RRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR8}scCsC|j|jj|jdk r-|jp0d|j|jffS(N(RRRRRRR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt __getstate__s  cCsm|d|_|d\|_}}|_i|_|jj||dk r`t||_n d|_dS(Nii(RRRRR RRR(RtstateR/t inAccumNames((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt __setstate__s   cCs|j|j|j|jfS(N(RRRR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__getnewargs__scCs tt|t|jS(N(RRRR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRsN(6RRRRRRRsRRRRRRRt __nonzero__RRRRRRRRRRRRRRRRRRRRR RRRRRRRRRR!R-R0R3R8R9R<R=R(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR -sh& '              4             # =  %-   cCsW|}d|ko#t|knr@||ddkr@dS||jdd|S(sReturns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}} for more information on parsing strings containing C{}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. iis (Rtrfind(RtstrgR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR7s cCs|jdd|dS(sReturns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}} for more information on parsing strings containing C{}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. s ii(tcount(RR@((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRHs cCsR|jdd|}|jd|}|dkrB||d|!S||dSdS(sfReturns the line of text containing loc within a string, counting newlines as line separators. s iiN(R?tfind(RR@tlastCRtnextCR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyREs  cCsAdt|dt|dt||t||fGHdS(NsMatch s at loc s(%d,%d)(RRHR7(tinstringRtexpr((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt_defaultStartDebugActionscCs'dt|dt|jGHdS(NsMatched s -> (RRuR(REtstartloctendlocRFttoks((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt_defaultSuccessDebugActionscCsdt|GHdS(NsException raised:(R(RERRFtexc((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt_defaultExceptionDebugActionscGsdS(sG'Do-nothing' debug action, to suppress debugging output during parsing.N((R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyROsics tkrfdSdgtgtd dkrVdd}ddntj}tjd}|d dd }|d|d |ffd }d }y"tdtdj}Wntk rt }nX||_|S(Ncs |S(N((RtlRp(tfunc(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRriiiicSsJtdkrdnd}tjd| |d|}|j|jfgS( Niiiiitlimiti(iii(tsystem_versiont tracebackt extract_stacktfilenameRH(RPR t frame_summary((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRSscSs2tj|d|}|d}|j|jfgS(NRPi(RRt extract_tbRTRH(ttbRPtframesRU((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRVs iRPiicsxy&|d}td<|SWqtk rdrInAz:tjd}|dddd ksnWd~Xdkrdcd7Rt __class__(ii( tsingleArgBuiltinsRRQRRRSRVtgetattrRt ExceptionRu(ROR[RSt LINE_DIFFt this_lineR]t func_name((RVRZRORPR[R\s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt _trim_aritys*          cBseZdZdZeZedZedZedZ dZ dZ edZ e dZd Zd Zd Zd Zd ZdZe dZdZe e dZdZdZdefdYZedFk rdefdYZndefdYZiZe Z!ddgZ"e e dZ#eZ$edZ%eZ&eddZ'edZ(e)edZ*d Z+e)d!Z,e)ed"Z-d#Z.d$Z/d%Z0d&Z1d'Z2d(Z3d)Z4d*Z5d+Z6d,Z7d-Z8d.Z9d/Z:dFd0Z;d1Z<d2Z=d3Z>d4Z?d5Z@d6ZAe d7ZBd8ZCd9ZDd:ZEd;ZFgd<ZGed=ZHd>ZId?ZJd@ZKdAZLdBZMe dCZNe dDe e edEZORS(Gs)Abstract base level parser element class.s cCs |t_dS(s Overrides the default whitespace chars Example:: # default whitespace chars are space, and newline OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] # change to just treat newline as significant ParserElement.setDefaultWhitespaceChars(" \t") OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] N(R"tDEFAULT_WHITE_CHARS(tchars((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetDefaultWhitespaceChars=s cCs |t_dS(s Set class to be used for inclusion of string literals into a parser. Example:: # default literal class used is Literal integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # change to Suppress ParserElement.inlineLiteralsUsing(Suppress) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") date_str.parseString("1999/12/31") # -> ['1999', '12', '31'] N(R"t_literalStringClass(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytinlineLiteralsUsingLscCst|_d|_d|_d|_||_t|_t j |_ t|_ t |_t |_t|_t |_t |_t|_d|_t|_d|_d|_t|_t |_dS(NRr(NNN(Rt parseActionRt failActiontstrReprt resultsNamet saveAsListRtskipWhitespaceR"Rft whiteCharstcopyDefaultWhiteCharsRtmayReturnEmptytkeepTabst ignoreExprstdebugt streamlinedt mayIndexErrorterrmsgt modalResultst debugActionstret callPreparset callDuringTry(Rtsavelist((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRas(                   cCsEtj|}|j|_|j|_|jrAtj|_n|S(s$ Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K") integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) prints:: [5120, 100, 655360, 268435456] Equivalent form of C{expr.copy()} is just C{expr()}:: integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") (RRkRuRrR"RfRq(Rtcpy((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRxs    cCs>||_d|j|_t|dr:|j|j_n|S(sf Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) s Expected t exception(RRyRRR(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetNames  cCsE|j}|jdr.|d }t}n||_| |_|S(sP Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") t*i(RtendswithRRnRz(RRtlistAllMatchestnewself((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetResultsNames     csa|r9|jttfd}|_||_n$t|jdr]|jj|_n|S(sMethod to invoke the Python pdb debugger when this element is about to be parsed. Set C{breakFlag} to True to enable, False to disable. cs)ddl}|j||||S(Ni(tpdbt set_trace(RERt doActionst callPreParseR(t _parseMethod(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytbreakers  t_originalParseMethod(t_parseRRR(Rt breakFlagR((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetBreaks   cOs7tttt||_|jdt|_|S(s  Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}} for more information on parsing strings containing C{}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] R~(RtmapReRkRRR~(RtfnsR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRzs"cOsF|jtttt|7_|jp<|jdt|_|S(s Add parse action to expression's list of parse actions. See L{I{setParseAction}}. See examples in L{I{copy}}. R~(RkRRReR~RR(RRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytaddParseActions$cs|jdd|jdtr*tntx3|D]+fd}|jj|q7W|jp~|jdt|_|S(sAdd a boolean predicate function to expression's list of parse actions. See L{I{setParseAction}} for function call signatures. Unlike C{setParseAction}, functions passed to C{addCondition} need to return boolean success/fail of the condition. Optional keyword arguments: - message = define a custom message to be used in the raised exception - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) year_int = integer.copy() year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") date_str = year_int + '/' + integer + '/' + integer result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) tmessagesfailed user-defined conditiontfatalcs7tt|||s3||ndS(N(RRe(RRNRp(texc_typetfnR(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytpasR~(RRRRRkRR~(RRRR((RRRs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt addConditions cCs ||_|S(s Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments C{fn(s,loc,expr,err)} where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw C{L{ParseFatalException}} if it is desired to stop parsing immediately.(Rl(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt setFailActions cCsnt}xa|rit}xN|jD]C}y)x"|j||\}}t}q+WWqtk raqXqWq W|S(N(RRRuRR(RRERt exprsFoundtetdummy((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt_skipIgnorables#s   cCsp|jr|j||}n|jrl|j}t|}x-||krh|||krh|d7}q?Wn|S(Ni(RuRRpRqR(RRERtwttinstrlen((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytpreParse0s    cCs |gfS(N((RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt parseImpl<scCs|S(N((RRERt tokenlist((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt postParse?sc Cs|j}|s|jr,|jdr?|jd|||n|rc|jrc|j||}n|}|}yUy|j|||\}}Wn/tk rt|t||j |nXWqt k r(} |jdr|jd|||| n|jr"|j|||| nqXn|rP|jrP|j||}n|}|}|j sw|t|kry|j|||\}}Wqtk rt|t||j |qXn|j|||\}}|j |||}t ||jd|jd|j} |jrf|s7|jrf|ryrxk|jD]`} | ||| }|dk rJt ||jd|jot|t tfd|j} qJqJWWqct k r} |jdr|jd|||| nqcXqfxn|jD]`} | ||| }|dk rt ||jd|joMt|t tfd|j} qqWn|r|jdr|jd||||| qn|| fS(NiiRRi(RvRlR{R}RRRRRRyRRxRR RnRoRzRkR~RRsR( RRERRRt debuggingtpreloct tokensStartttokensterrt retTokensR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt _parseNoCacheCsp   &    %$       #cCsNy|j||dtdSWn)tk rIt|||j|nXdS(NRi(RRRRRy(RRER((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyttryParses cCs7y|j||Wnttfk r.tSXtSdS(N(RRRRR(RRER((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt canParseNexts t_UnboundedCachecBseZdZRS(csit|_fd}fd}fd}tj|||_tj|||_tj|||_dS(Ncsj|S(N(R(RR(tcachet not_in_cache(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscs||}) - define your parse action using the full C{(s,loc,toks)} signature, and reference the input string using the parse action's C{s} argument - explictly expand the tabs in your input string before calling C{parseString} Example:: Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text iN( R"RRwt streamlineRuRtt expandtabsRRR R'Rtverbose_stacktrace(RREtparseAllRRRtseRL((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt parseString#s$      ccs|js|jnx|jD]}|jq W|jsRt|j}nt|}d}|j}|j}t j d} yx||kra| |kray.|||} ||| dt \} } Wnt k r| d}qX| |krT| d7} | | | fV|rK|||} | |kr>| }qQ|d7}q^| }q| d}qWWn(t k r}t jrq|nXdS(s Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after 'n' matches are found. If C{overlap} is specified, then overlapping matches will be reported. Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}} for more information on parsing strings with embedded tabs. Example:: source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" print(source) for tokens,start,end in Word(alphas).scanString(source): print(' '*start + '^'*(end-start)) print(' '*start + tokens[0]) prints:: sldjf123lsdjjkf345sldkjf879lkjsfd987 ^^^^^ sldjf ^^^^^^^ lsdjjkf ^^^^^^ sldkjf ^^^^^^ lkjsfd iRiN(RwRRuRtRRRRRR"RRRRR(RREt maxMatchestoverlapRRRt preparseFntparseFntmatchesRtnextLocRtnextlocRL((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt scanStringUsB               c Cs%g}d}t|_yx|j|D]}\}}}|j|||!|rt|trs||j7}qt|tr||7}q|j|n|}q(W|j||g|D]}|r|^q}djt t t |SWn(t k r }t jrq!|nXdS(sf Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. Invoking C{transformString()} on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. C{transformString()} returns the resulting transformed string. Example:: wd = Word(alphas) wd.setParseAction(lambda toks: toks[0].title()) print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) Prints:: Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. iRrN(RRtRRRsR RRRRRt_flattenRR"R( RRERtlastERpRRtoRL((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR{s(     cCsey6tg|j||D]\}}}|^qSWn(tk r`}tjrWqa|nXdS(s~ Another extension to C{L{scanString}}, simplifying the access to the tokens found to match the given parse expression. May be called with optional C{maxMatches} argument, to clip searching after 'n' matches are found. Example:: # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters cap_word = Word(alphas.upper(), alphas.lower()) print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) prints:: ['More', 'Iron', 'Lead', 'Gold', 'I'] N(R RRR"R(RRERRpRRRL((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt searchStrings 6 c csfd}d}xJ|j|d|D]3\}}}|||!V|rO|dVn|}q"W||VdS(s[ Generator method to split a string using the given expression as a separator. May be called with optional C{maxsplit} argument, to limit the number of splits; and the optional C{includeSeparators} argument (default=C{False}), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] iRN(R( RREtmaxsplittincludeSeparatorstsplitstlastRpRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs %   cCsdt|tr!tj|}nt|tsTtjdt|tdddSt ||gS(s Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!'] s4Cannot combine element of type %s with ParserElementt stackleveliN( RsRR"RitwarningstwarnRt SyntaxWarningRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  cCs\t|tr!tj|}nt|tsTtjdt|tdddS||S(s] Implementation of + operator when left operand is not a C{L{ParserElement}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs cCsmt|tr!tj|}nt|tsTtjdt|tdddSt |t j |gS(sQ Implementation of - operator, returns C{L{And}} with error stop s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRRRt _ErrorStop(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__sub__s cCs\t|tr!tj|}nt|tsTtjdt|tdddS||S(s] Implementation of - operator when left operand is not a C{L{ParserElement}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__rsub__ s csEt|tr|d}}n-t|tr7|d d }|dd kr_d|df}nt|dtr|dd kr|ddkrtS|ddkrtS|dtSqLt|dtrt|dtr|\}}||8}qLtdt|dt|dntdt||dkrgtdn|dkrtdn||kodknrtdn|rfd |r |dkr|}qt g||}qA|}n(|dkr.}nt g|}|S( s Implementation of * operator, allows use of C{expr * 3} in place of C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples may also include C{None} as in: - C{expr*(n,None)} or C{expr*(n,)} is equivalent to C{expr*n + L{ZeroOrMore}(expr)} (read as "at least n instances of C{expr}") - C{expr*(None,n)} is equivalent to C{expr*(0,n)} (read as "0 to n instances of C{expr}") - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} Note that C{expr*(None,n)} does not raise an exception if more than n exprs exist in the input stream; that is, C{expr*(None,n)} does not enforce a maximum number of expr occurrences. If this behavior is desired, then write C{expr*(None,n) + ~expr} iiis7cannot multiply 'ParserElement' and ('%s','%s') objectss0cannot multiply 'ParserElement' and '%s' objectss/cannot multiply ParserElement by negative values@second tuple value must be greater or equal to first tuple values+cannot multiply ParserElement by 0 or (0,0)cs2|dkr$t|dStSdS(Ni(R(tn(tmakeOptionalListR(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR]s N(NN( RsRottupleRR0RRRt ValueErrorR(RR t minElementst optElementsR}((RRs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__mul__,sD#  &  )      cCs |j|S(N(R(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__rmul__pscCsdt|tr!tj|}nt|tsTtjdt|tdddSt ||gS(sI Implementation of | operator - returns C{L{MatchFirst}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__or__ss cCs\t|tr!tj|}nt|tsTtjdt|tdddS||BS(s] Implementation of | operator when left operand is not a C{L{ParserElement}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__ror__s cCsdt|tr!tj|}nt|tsTtjdt|tdddSt ||gS(sA Implementation of ^ operator - returns C{L{Or}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__xor__s cCs\t|tr!tj|}nt|tsTtjdt|tdddS||AS(s] Implementation of ^ operator when left operand is not a C{L{ParserElement}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__rxor__s cCsdt|tr!tj|}nt|tsTtjdt|tdddSt ||gS(sC Implementation of & operator - returns C{L{Each}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRRR (RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__and__s cCs\t|tr!tj|}nt|tsTtjdt|tdddS||@S(s] Implementation of & operator when left operand is not a C{L{ParserElement}} s4Cannot combine element of type %s with ParserElementRiN( RsRR"RiRRRRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__rand__s cCs t|S(sE Implementation of ~ operator - returns C{L{NotAny}} (R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt __invert__scCs'|dk r|j|S|jSdS(s  Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be passed as C{True}. If C{name} is omitted, same as calling C{L{copy}}. Example:: # these are equivalent userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") N(RRR(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__call__s  cCs t|S(s Suppresses the output of this C{ParserElement}; useful to keep punctuation from cluttering up returned output. (R)(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsuppressscCs t|_|S(s Disables the skipping of whitespace before matching the characters in the C{ParserElement}'s defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. (RRp(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytleaveWhitespaces cCst|_||_t|_|S(s8 Overrides the default whitespace chars (RRpRqRRr(RRg((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetWhitespaceCharss   cCs t|_|S(s Overrides default behavior to expand C{}s to spaces before parsing the input string. Must be called before C{parseString} when the input grammar contains elements that match C{} characters. (RRt(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt parseWithTabss cCsrt|trt|}nt|trR||jkrn|jj|qnn|jjt|j|S(s Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] patt.ignore(cStyleComment) patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] (RsRR)RuRR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytignores cCs1|p t|pt|ptf|_t|_|S(sT Enable display of debugging messages while doing pattern matching. (RGRKRMR{RRv(Rt startActiont successActiontexceptionAction((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetDebugActions s    cCs)|r|jtttn t|_|S(s Enable display of debugging messages while doing pattern matching. Set C{flag} to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = wd | integer # turn on debugging for wd wd.setDebug() OneOrMore(term).parseString("abc 123 xyz 890") prints:: Match alphaword at loc 0(1,1) Matched alphaword -> ['abc'] Match alphaword at loc 3(1,4) Exception raised:Expected alphaword (at char 4), (line:1, col:5) Match alphaword at loc 7(1,8) Matched alphaword -> ['xyz'] Match alphaword at loc 11(1,12) Exception raised:Expected alphaword (at char 12), (line:1, col:13) Match alphaword at loc 15(1,16) Exception raised:Expected alphaword (at char 15), (line:1, col:16) The output shown is that produced by the default debug actions - custom debug actions can be specified using L{setDebugActions}. Prior to attempting to match the C{wd} expression, the debugging message C{"Match at loc (,)"} is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, which makes debugging and exception messages easier to understand - for instance, the default name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. (RRGRKRMRRv(Rtflag((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetDebugs# cCs|jS(N(R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR@scCs t|S(N(R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRCscCst|_d|_|S(N(RRwRRm(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRFs  cCsdS(N((RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytcheckRecursionKscCs|jgdS(sj Check defined expressions for valid structure, check for infinite recursive definitions. N(R(Rt validateTrace((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytvalidateNscCsy|j}Wn5tk rGt|d}|j}WdQXnXy|j||SWn(tk r}tjr}q|nXdS(s Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. trN(treadRtopenRRR"R(Rtfile_or_filenameRt file_contentstfRL((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt parseFileTs  cCsdt|tr1||kp0t|t|kSt|trM|j|Stt||kSdS(N(RsR"tvarsRRtsuper(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__eq__hs " cCs ||k S(N((RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__ne__pscCstt|S(N(thashtid(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__hash__sscCs ||kS(N((RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__req__vscCs ||k S(N((RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__rne__yscCs:y!|jt|d|tSWntk r5tSXdS(s Method for quick testing of a parser against a test string. Good for simple inline microtests of sub expressions while building up larger parser. Parameters: - testString - to test against this expression for a match - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests Example:: expr = Word(nums) assert expr.matches("100") RN(RRRRR(Rt testStringR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR|s  t#cCsyt|tr6tttj|jj}nt|trTt|}ng}g}t } x|D]} |d k r|j | t s|r| r|j | qmn| sqmndj|| g} g}yQ| jdd} |j| d|} | j | jd|| o%| } Wntk r} t| trPdnd}d| kr| j t| j| | j dt| j| dd |n| j d| jd || j d t| | o|} | } n<tk r*}| j d t|| o|} |} nX|rX|rG| j dndj| GHn|j | | fqmW| |fS( s3 Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\n of strings that spans \n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.) s s\nRR6s(FATAL)Rrt it^sFAIL: sFAIL-EXCEPTION: N(RsRRRRuRtrstript splitlinesRRRRRRRRRR3RRRERR7Ra(RttestsRtcommenttfullDumpt printResultst failureTestst allResultstcommentstsuccessRpRtresultRRRL((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytrunTestssNW' +  ,    N(PRRRRfRRt staticmethodRhRjRRRRRRRzRRRRRRRRRRRRRRRRRRRRRRRRRt_MAX_INTRR{RRR RRRRRRRRRRRRRRRRRRRRRRRRRR R R RRRRR"(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR"8s      &   H     " 2G +   D      )            cBseZdZdZRS(sT Abstract C{ParserElement} subclass, for defining atomic matching patterns. cCstt|jdtdS(NR(R R*RR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s(RRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR* scBseZdZdZRS(s, An empty token, will always match. cCs2tt|jd|_t|_t|_dS(NR (R R RRRRsRRx(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  (RRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR  scBs#eZdZdZedZRS(s( A token that will never match. cCs;tt|jd|_t|_t|_d|_dS(NRsUnmatchable token( R RRRRRsRRxRy(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR* s    cCst|||j|dS(N(RRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR1 s(RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR& s cBs#eZdZdZedZRS(s Token to exactly match a specified string. Example:: Literal('blah').parseString('blah') # -> ['blah'] Literal('blah').parseString('blahfooblah') # -> ['blah'] Literal('blah').parseString('bla') # -> Exception: Expected "blah" For case-insensitive matching, use L{CaselessLiteral}. For keyword matching (force word break before and after the matched string), use L{Keyword} or L{CaselessKeyword}. cCstt|j||_t||_y|d|_Wn0tk rntj dt ddt |_ nXdt |j|_d|j|_t|_t|_dS(Nis2null string passed to Literal; use Empty() insteadRis"%s"s Expected (R RRtmatchRtmatchLentfirstMatchCharRRRRR R^RRRyRRsRx(Rt matchString((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRC s      cCsg|||jkrK|jdks7|j|j|rK||j|jfSt|||j|dS(Ni(R'R&t startswithR%RRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRV s$(RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR5 s  cBsKeZdZedZdedZedZ dZ e dZ RS(s\ Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with C{L{Literal}}: - C{Literal("if")} will match the leading C{'if'} in C{'ifAndOnlyIf'}. - C{Keyword("if")} will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'} Accepts two optional constructor arguments in addition to the keyword string: - C{identChars} is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + "_" and "$" - C{caseless} allows case-insensitive matching, default is C{False}. Example:: Keyword("start").parseString("start") # -> ['start'] Keyword("start").parseString("starting") # -> Exception For case-insensitive matching, use L{CaselessKeyword}. s_$cCstt|j|dkr+tj}n||_t||_y|d|_Wn't k r}t j dt ddnXd|j|_ d|j |_t|_t|_||_|r|j|_|j}nt||_dS(Nis2null string passed to Keyword; use Empty() insteadRis"%s"s Expected (R RRRtDEFAULT_KEYWORD_CHARSR%RR&R'RRRRRRyRRsRxtcaselesstuppert caselessmatchRt identChars(RR(R.R+((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRq s&        cCsb|jr||||j!j|jkrF|t||jkse|||jj|jkrF|dks||dj|jkrF||j|jfSn|||jkrF|jdks|j|j|rF|t||jks|||j|jkrF|dks2||d|jkrF||j|jfSt |||j |dS(Nii( R+R&R,R-RR.R%R'R)RRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s #9)$3#cCs%tt|j}tj|_|S(N(R RRR*R.(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s cCs |t_dS(s,Overrides the default Keyword chars N(RR*(Rg((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytsetDefaultKeywordChars sN( RRRR1R*RRRRRRR#R/(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR^ s    cBs#eZdZdZedZRS(sl Token to match a specified string, ignoring case of letters. Note: the matched results will always be in the case of the given match string, NOT the case of the input text. Example:: OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] (Contrast with example for L{CaselessKeyword}.) cCsItt|j|j||_d|j|_d|j|_dS(Ns'%s's Expected (R RRR,t returnStringRRy(RR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s cCsS||||j!j|jkr7||j|jfSt|||j|dS(N(R&R,R%R0RRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s#(RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  cBs&eZdZddZedZRS(s Caseless version of L{Keyword}. Example:: OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD'] (Contrast with example for L{CaselessLiteral}.) cCs#tt|j||dtdS(NR+(R RRR(RR(R.((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR scCs||||j!j|jkrp|t||jks\|||jj|jkrp||j|jfSt|||j|dS(N(R&R,R-RR.R%RRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s#9N(RRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s cBs&eZdZddZedZRS(sx A variation on L{Literal} which matches "close" matches, that is, strings with at most 'n' mismatching characters. C{CloseMatch} takes parameters: - C{match_string} - string to be matched - C{maxMismatches} - (C{default=1}) maximum number of mismatches allowed to count as a match The results from a successful parse will contain the matched text from the input string and the following named results: - C{mismatches} - a list of the positions within the match_string where mismatches were found - C{original} - the original match_string used to compare against the input string If C{mismatches} is an empty list, then the match was an exact match. Example:: patt = CloseMatch("ATCATCGAATGGA") patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) # exact match patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) # close match allowing up to 2 mismatches patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2) patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) icCs]tt|j||_||_||_d|j|jf|_t|_t|_ dS(Ns&Expected %r (with up to %d mismatches)( R RjRRt match_stringt maxMismatchesRyRRxRs(RR1R2((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s    cCs|}t|}|t|j}||kr|j}d}g} |j} xtt|||!|jD]J\}} | \} } | | kro| j|t| | krPqqoqoW|d}t|||!g}|j|d<| |d<||fSnt|||j|dS(Niitoriginalt mismatches( RR1R2RRRR RRy(RRERRtstartRtmaxlocR1tmatch_stringlocR4R2ts_mtsrctmattresults((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s(    ,        (RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRj s cBs>eZdZddddeddZedZdZRS(s Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction. An optional C{excludeChars} parameter can list characters that might be found in the input C{bodyChars} string; useful to define a word of all printables except for one or two characters, for instance. L{srange} is useful for defining custom character set strings for defining C{Word} expressions, using range notation from regular expression character sets. A common mistake is to use C{Word} to match a specific literal string, as in C{Word("Address")}. Remember that C{Word} uses the string argument to define I{sets} of matchable characters. This expression would match "Add", "AAA", "dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an exact literal string, use L{Literal} or L{Keyword}. pyparsing includes helper strings for building Words: - L{alphas} - L{nums} - L{alphanums} - L{hexnums} - L{alphas8bit} (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.) - L{punc8bit} (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.) - L{printables} (any non-whitespace character) Example:: # a word composed of digits integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9")) # a word with a leading capital, and zero or more lowercase capital_word = Word(alphas.upper(), alphas.lower()) # hostnames are alphanumeric, with leading alpha, and '-' hostname = Word(alphas, alphanums+'-') # roman numeral (not a strict parser, accepts invalid mix of characters) roman = Word("IVXLCDM") # any string of non-whitespace characters, except for ',' csv_value = Word(printables, excludeChars=",") iicstt|jrcdjfd|D}|rcdjfd|D}qcn||_t||_|r||_t||_n||_t||_|dk|_ |dkrt dn||_ |dkr||_ n t |_ |dkr)||_ ||_ nt||_d|j|_t|_||_d|j|jkr}|dkr}|dkr}|dkr}|j|jkrd t|j|_net|jdkrd tj|jt|jf|_n%d t|jt|jf|_|jrDd |jd |_nytj|j|_Wq}tk ryd|_q}XndS( NRrc3s!|]}|kr|VqdS(N((RR(t excludeChars(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys 7 sc3s!|]}|kr|VqdS(N((RR(R<(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys 9 siisZcannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitteds Expected Rs[%s]+s%s[%s]*s [%s][%s]*s\b(R R-RRt initCharsOrigRt initCharst bodyCharsOrigt bodyCharst maxSpecifiedRtminLentmaxLenR$RRRyRRxt asKeywordt_escapeRegexRangeCharstreStringRR|tescapetcompileRaR(RR>R@tmintmaxtexactRDR<((R<s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR4 sT%             :   c Cs|jr[|jj||}|s?t|||j|n|j}||jfS|||jkrt|||j|n|}|d7}t|}|j}||j }t ||}x*||kr|||kr|d7}qWt } |||j krt } n|jrG||krG|||krGt } n|jr|dkrp||d|ks||kr|||krt } qn| rt|||j|n||||!fS(Nii(R|R%RRytendtgroupR>RR@RCRIRRBRRARD( RRERRR!R5Rt bodycharsR6tthrowException((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRj s6       %  < cCsytt|jSWntk r*nX|jdkrd}|j|jkr}d||j||jf|_qd||j|_n|jS(NcSs&t|dkr|d dS|SdS(Nis...(R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt charsAsStr s s W:(%s,%s)sW:(%s)(R R-RRaRmRR=R?(RRP((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  (N( RRRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR- s.6 #cBsDeZdZeejdZddZedZ dZ RS(s Token for matching strings that match a given regular expression. Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module. If the given regex contains named groups (defined using C{(?P...)}), these will be preserved as named parse results. Example:: realnum = Regex(r"[+-]?\d+\.\d*") date = Regex(r'(?P\d{4})-(?P\d\d?)-(?P\d\d?)') # ref: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression roman = Regex(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") s[A-Z]icCs3tt|jt|tr|sAtjdtddn||_||_ y+t j |j|j |_ |j|_ Wqt jk rtjd|tddqXnIt|tjr||_ t||_|_ ||_ n tdt||_d|j|_t|_t|_dS(sThe parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.s0null string passed to Regex; use Empty() insteadRis$invalid pattern (%s) passed to RegexsCRegex may only be constructed with a string or a compiled RE objects Expected N(R R%RRsRRRRtpatterntflagsR|RHRFt sre_constantsterrortcompiledREtypeRuRRRRyRRxRRs(RRQRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s.          cCs|jj||}|s6t|||j|n|j}|j}t|j}|rx|D]}||||eZdZddeededZedZdZRS(s Token for matching strings that are delimited by quoting characters. Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default=C{None}) - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=C{None}) - multiline - boolean indicating whether quotes can span multiple lines (default=C{False}) - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True}) - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar) - convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True}) Example:: qs = QuotedString('"') print(qs.searchString('lsjdf "This is the quote" sldjf')) complex_qs = QuotedString('{{', endQuoteChar='}}') print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf')) sql_qs = QuotedString('"', escQuote='""') print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf')) prints:: [['This is the quote']] [['This is the "quote"']] [['This is the quote with "embedded" quotes']] c sttj|j}|sGtjdtddtn|dkr\|}n4|j}|stjdtddtn|_ t |_ |d_ |_ t |_|_|_|_|_|rTtjtjB_dtjj tj d|dk rDt|pGdf_nPd_dtjj tj d|dk rt|pdf_t j d krjd d jfd tt j d dd Dd7_n|r*jdtj|7_n|rhjdtj|7_tjjd_njdtjj 7_y+tjjj_j_Wn4tj k rtjdjtddnXt!_"dj"_#t$_%t&_'dS(Ns$quoteChar cannot be the empty stringRis'endQuoteChar cannot be the empty stringis %s(?:[^%s%s]Rrs%s(?:[^%s\n\r%s]is|(?:s)|(?:c3s<|]2}dtjj| tj|fVqdS(s%s[^%s]N(R|RGt endQuoteCharRE(RR(R(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys / sit)s|(?:%s)s|(?:%s.)s(.)s)*%ss$invalid pattern (%s) passed to Regexs Expected ((R R#RRRRRt SyntaxErrorRt quoteCharRt quoteCharLentfirstQuoteCharRXtendQuoteCharLentescChartescQuotetunquoteResultstconvertWhitespaceEscapesR|t MULTILINEtDOTALLRRRGRERQRRtescCharReplacePatternRHRFRSRTRRRyRRxRRs(RR[R_R`t multilineRaRXRb((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR sf             ( %E  c CsT|||jkr(|jj||p+d}|sOt|||j|n|j}|j}|jrJ||j |j !}t |t rJd|kr|j ridd6dd6dd6dd 6}x/|jD]\}}|j||}qWn|jr tj|jd |}n|jrG|j|j|j}qGqJn||fS( Ns\s s\ts s\ns s\fs s\rs\g<1>(R]R|R%RRRyRLRMRaR\R^RsRRbRRR_RReR`RX( RRERRR!R}tws_maptwslittwschar((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRG s*.      !cCs]ytt|jSWntk r*nX|jdkrVd|j|jf|_n|jS(Ns.quoted string, starting with %s ending with %s(R R#RRaRmRR[RX(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRj s N( RRRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR# sA #cBs5eZdZddddZedZdZRS(s Token for matching words composed of characters I{not} in a given set (will include whitespace in matched characters if not listed in the provided exclusion set - see example). Defined with string containing all disallowed characters, and an optional minimum, maximum, and/or exact length. The default value for C{min} is 1 (a minimum value < 1 is not valid); the default values for C{max} and C{exact} are 0, meaning no maximum or exact length restriction. Example:: # define a comma-separated-value as anything that is not a ',' csv_value = CharsNotIn(',') print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213")) prints:: ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] iicCstt|jt|_||_|dkr@tdn||_|dkra||_n t |_|dkr||_||_nt ||_ d|j |_ |jdk|_ t|_dS(Nisfcannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permittedis Expected (R RRRRptnotCharsRRBRCR$RRRyRsRx(RRjRIRJRK((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s           cCs|||jkr.t|||j|n|}|d7}|j}t||jt|}x*||kr|||kr|d7}qfW|||jkrt|||j|n||||!fS(Ni(RjRRyRIRCRRB(RRERRR5tnotcharstmaxlen((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  cCsytt|jSWntk r*nX|jdkryt|jdkrfd|jd |_qyd|j|_n|jS(Nis !W:(%s...)s!W:(%s)(R RRRaRmRRRj(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s (RRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRv s cBsXeZdZidd6dd6dd6dd6d d 6Zd d d d dZedZRS(s Special matching class for matching whitespace. Normally, whitespace is ignored by pyparsing grammars. This class is included when some whitespace structures are significant. Define with a string containing the whitespace characters to be matched; default is C{" \t\r\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments, as defined for the C{L{Word}} class. sRss ss ss ss s iicsttj|_jdjfdjDdjdjD_t_ dj_ |_ |dkr|_ n t _ |dkr|_ |_ ndS(NRrc3s$|]}|jkr|VqdS(N(t matchWhite(RR(R(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys scss|]}tj|VqdS(N(R,t whiteStrs(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys ss Expected i(R R,RRmRRRqRRRsRyRBRCR$(RtwsRIRJRK((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s )       cCs|||jkr.t|||j|n|}|d7}||j}t|t|}x-||kr|||jkr|d7}qcW|||jkrt|||j|n||||!fS(Ni(RmRRyRCRIRRB(RRERRR5R6((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  "(RRRRnRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR, s t_PositionTokencBseZdZRS(cCs8tt|j|jj|_t|_t|_ dS(N( R RpRR^RRRRsRRx(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s (RRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRp scBs,eZdZdZdZedZRS(sb Token to advance to a specific column of input text; useful for tabular report scraping. cCs tt|j||_dS(N(R RRR7(Rtcolno((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR scCst|||jkrt|}|jrB|j||}nxE||kr||jrt|||jkr|d7}qEWn|S(Ni(R7RRuRtisspace(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  7cCs^t||}||jkr6t||d|n||j|}|||!}||fS(NsText not in expected column(R7R(RRERRtthiscoltnewlocR}((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  (RRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  cBs#eZdZdZedZRS(s Matches if current position is at the beginning of a line within the parse string Example:: test = ''' AAA this line AAA and this line AAA but not this one B AAA and definitely not this one ''' for t in (LineStart() + 'AAA' + restOfLine).searchString(test): print(t) Prints:: ['AAA', ' this line'] ['AAA', ' and this line'] cCs tt|jd|_dS(NsExpected start of line(R RRRy(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR& scCs;t||dkr|gfSt|||j|dS(Ni(R7RRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR* s (RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s cBs#eZdZdZedZRS(sU Matches if current position is at the end of a line within the parse string cCs<tt|j|jtjjddd|_dS(Ns RrsExpected end of line(R RRRR"RfRRy(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR3 scCs|t|krK||dkr0|ddfSt|||j|n8|t|krk|dgfSt|||j|dS(Ns i(RRRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR8 s(RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR/ s cBs#eZdZdZedZRS(sM Matches if current position is at the beginning of the parse string cCs tt|jd|_dS(NsExpected start of text(R R(RRy(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRG scCsL|dkrB||j|dkrBt|||j|qBn|gfS(Ni(RRRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRK s (RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR(C s cBs#eZdZdZedZRS(sG Matches if current position is at the end of the parse string cCs tt|jd|_dS(NsExpected end of text(R R'RRy(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRV scCs|t|kr-t|||j|nT|t|krM|dgfS|t|kri|gfSt|||j|dS(Ni(RRRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRZ s (RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR'R s cBs&eZdZedZedZRS(sp Matches if the current position is at the beginning of a Word, and is not preceded by any character in a given set of C{wordChars} (default=C{printables}). To emulate the C{} behavior of regular expressions, use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of the string being parsed, or at the beginning of a line. cCs/tt|jt||_d|_dS(NsNot at the start of a word(R R/RRt wordCharsRy(RRu((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRl scCs^|dkrT||d|jks6|||jkrTt|||j|qTn|gfS(Nii(RuRRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRq s  (RRRRTRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR/d s cBs&eZdZedZedZRS(sZ Matches if the current position is at the end of a Word, and is not followed by any character in a given set of C{wordChars} (default=C{printables}). To emulate the C{} behavior of regular expressions, use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of the string being parsed, or at the end of a line. cCs8tt|jt||_t|_d|_dS(NsNot at the end of a word(R R.RRRuRRpRy(RRu((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s cCsvt|}|dkrl||krl|||jksN||d|jkrlt|||j|qln|gfS(Nii(RRuRRy(RRERRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  (RRRRTRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR.x s cBsqeZdZedZdZdZdZdZdZ dZ edZ gd Z d Z RS( s^ Abstract subclass of ParserElement, for combining and post-processing parsed tokens. cCstt|j|t|tr4t|}nt|tr[tj|g|_ nt|t j rt|}t d|Drt tj|}nt||_ n3yt||_ Wntk r|g|_ nXt|_dS(Ncss|]}t|tVqdS(N(RsR(RRF((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s(R RRRsRRRR"RitexprsRtIterabletallRRRR}(RRvR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  cCs |j|S(N(Rv(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR scCs|jj|d|_|S(N(RvRRRm(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s cCsPt|_g|jD]}|j^q|_x|jD]}|jq8W|S(s~Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on all contained expressions.(RRpRvRR(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s  %cCst|trb||jkrtt|j|x(|jD]}|j|jdq>Wqn>tt|j|x%|jD]}|j|jdqW|S(Ni(RsR)RuR RRRv(RR R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR scCsfytt|jSWntk r*nX|jdkr_d|jjt|j f|_n|jS(Ns%s:(%s)( R RRRaRmRR^RRRv(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s %cCswtt|jx|jD]}|jqWt|jdkr`|jd}t||jr|j r|jdkr|j r|j|jdg|_d|_ |j |j O_ |j |j O_ n|jd}t||jr`|j r`|jdkr`|j r`|jd |j|_d|_ |j |j O_ |j |j O_ q`ndt||_|S(Niiiis Expected (R RRRvRRsR^RkRnRRvRmRsRxRRy(RRR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s0        cCstt|j||}|S(N(R RR(RRRR}((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR scCs@||g}x|jD]}|j|qW|jgdS(N(RvRR(RRttmpR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR scCs>tt|j}g|jD]}|j^q|_|S(N(R RRRv(RR}R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s%(RRRRRRRRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s    "  cBsWeZdZdefdYZedZedZdZdZ dZ RS(s  Requires all given C{ParseExpression}s to be found in the given order. Expressions may be separated by whitespace. May be constructed using the C{'+'} operator. May also be constructed using the C{'-'} operator, which will suppress backtracking. Example:: integer = Word(nums) name_expr = OneOrMore(Word(alphas)) expr = And([integer("id"),name_expr("name"),integer("age")]) # more easily written as: expr = integer("id") + name_expr("name") + integer("age") RcBseZdZRS(cOs3ttj|j||d|_|jdS(Nt-(R RRRRR(RRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s (RRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR scCsltt|j||td|jD|_|j|jdj|jdj|_t |_ dS(Ncss|]}|jVqdS(N(Rs(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys  si( R RRRxRvRsRRqRpRR}(RRvR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s c Cs?|jdj|||dt\}}t}x|jdD]}t|tjr`t}q<n|ry|j|||\}}Wqtk rqtk r}d|_ tj |qt k rt|t ||j|qXn|j|||\}}|s$|jr<||7}q<q<W||fS(NiRi(RvRRRsRRRR!RRt __traceback__RRRRyR( RRERRt resultlistt errorStopRt exprtokensR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s((   %cCs.t|tr!tj|}n|j|S(N(RsRR"RiR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR5 scCs@||g}x+|jD] }|j||jsPqqWdS(N(RvRRs(RRtsubRecCheckListR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR: s   cCsVt|dr|jS|jdkrOddjd|jDd|_n|jS(NRt{Rcss|]}t|VqdS(N(R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys F st}(RRRmRRRv(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRA s *( RRRR RRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s    cBsAeZdZedZedZdZdZdZ RS(s Requires that at least one C{ParseExpression} is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the C{'^'} operator. Example:: # construct Or using '^' operator number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) print(number.searchString("123 3.1416 789")) prints:: [['123'], ['3.1416'], ['789']] cCsNtt|j|||jrAtd|jD|_n t|_dS(Ncss|]}|jVqdS(N(Rs(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys \ s(R RRRvR4RsR(RRvR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRY s c Csd}d}g}x|jD]}y|j||}Wntk rw} d| _| j|kr| }| j}qqtk rt||krt|t||j|}t|}qqX|j ||fqW|rh|j ddxn|D]c\} }y|j |||SWqtk r`} d| _| j|kra| }| j}qaqXqWn|dk r|j|_ |nt||d|dS(NiRcSs |d S(Ni((tx((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqu Rrs no defined alternatives to match( RRvRRR{RRRRyRtsortRR( RRERRt maxExcLoct maxExceptionRRtloc2Rt_((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR` s<      cCs.t|tr!tj|}n|j|S(N(RsRR"RiR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__ixor__ scCsVt|dr|jS|jdkrOddjd|jDd|_n|jS(NRRs ^ css|]}t|VqdS(N(R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys sR(RRRmRRRv(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s *cCs3||g}x|jD]}|j|qWdS(N(RvR(RRRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s( RRRRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRK s    &  cBsAeZdZedZedZdZdZdZ RS(s Requires that at least one C{ParseExpression} is found. If two expressions match, the first one listed is the one that will match. May be constructed using the C{'|'} operator. Example:: # construct MatchFirst using '|' operator # watch the order of expressions to match number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] # put more selective expression first number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] cCsNtt|j|||jrAtd|jD|_n t|_dS(Ncss|]}|jVqdS(N(Rs(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s(R RRRvR4RsR(RRvR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s c Csd}d}x|jD]}y|j|||}|SWqtk ro}|j|kr|}|j}qqtk rt||krt|t||j|}t|}qqXqW|dk r|j|_|nt||d|dS(Nis no defined alternatives to match( RRvRRRRRRyR( RRERRRRRR}R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s$    cCs.t|tr!tj|}n|j|S(N(RsRR"RiR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt__ior__ scCsVt|dr|jS|jdkrOddjd|jDd|_n|jS(NRRs | css|]}t|VqdS(N(R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys sR(RRRmRRRv(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s *cCs3||g}x|jD]}|j|qWdS(N(RvR(RRRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s( RRRRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s     cBs8eZdZedZedZdZdZRS(sm Requires all given C{ParseExpression}s to be found, but in any order. Expressions may be separated by whitespace. May be constructed using the C{'&'} operator. Example:: color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") integer = Word(nums) shape_attr = "shape:" + shape_type("shape") posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") color_attr = "color:" + color("color") size_attr = "size:" + integer("size") # use Each (using operator '&') to accept attributes in any order # (shape and posn are required, color and size are optional) shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr) shape_spec.runTests(''' shape: SQUARE color: BLACK posn: 100, 120 shape: CIRCLE size: 50 color: BLUE posn: 50,80 color:GREEN size:20 shape:TRIANGLE posn:20,40 ''' ) prints:: shape: SQUARE color: BLACK posn: 100, 120 ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] - color: BLACK - posn: ['100', ',', '120'] - x: 100 - y: 120 - shape: SQUARE shape: CIRCLE size: 50 color: BLUE posn: 50,80 ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']] - color: BLUE - posn: ['50', ',', '80'] - x: 50 - y: 80 - shape: CIRCLE - size: 50 color: GREEN size: 20 shape: TRIANGLE posn: 20,40 ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']] - color: GREEN - posn: ['20', ',', '40'] - x: 20 - y: 40 - shape: TRIANGLE - size: 20 cCsKtt|j||td|jD|_t|_t|_dS(Ncss|]}|jVqdS(N(Rs(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s( R R RRxRvRsRRptinitExprGroups(RRvR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs cCs4|jrLtd|jD|_g|jD]}t|tr/|j^q/}g|jD]%}|jr]t|t r]|^q]}|||_g|jD]}t|t r|j^q|_ g|jD]}t|t r|j^q|_ g|jD]$}t|tt t fs|^q|_ |j |j 7_ t|_n|}|j }|j} g} t} x| r_|| |j |j } g} x| D]}y|j||}Wntk r| j|qX| j|jjt||||kr|j|q|| kr| j|qqWt| t| krut} ququW|rdjd|D}t||d|n| g|jD]*}t|tr|j| kr|^q7} g}x6| D].}|j|||\}}|j|qWt|tg}||fS(Ncss3|])}t|trt|j|fVqdS(N(RsRRRF(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys ss, css|]}t|VqdS(N(R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys =ss*Missing one or more required elements (%s)(RRRvtopt1mapRsRRFRst optionalsR0tmultioptionalsRt multirequiredtrequiredRRRRRRRtremoveRRRtsumR (RRERRRtopt1topt2ttmpLocttmpReqdttmpOptt matchOrdert keepMatchingttmpExprstfailedtmissingR|R;t finalResults((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRsP .5 117      "   > cCsVt|dr|jS|jdkrOddjd|jDd|_n|jS(NRRs & css|]}t|VqdS(N(R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys PsR(RRRmRRRv(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRKs *cCs3||g}x|jD]}|j|qWdS(N(RvR(RRRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRTs(RRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s 5  1 cBs_eZdZedZedZdZdZdZ dZ gdZ dZ RS( sa Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens. cCstt|j|t|trattjtrItj|}qatjt |}n||_ d|_ |dk r|j |_ |j|_|j|j|j|_|j|_|j|_|jj|jndS(N(R RRRsRt issubclassR"RiR*RRFRRmRxRsRRqRpRoR}RuR(RRFR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR^s        cCsG|jdk r+|jj|||dtStd||j|dS(NRRr(RFRRRRRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRpscCs>t|_|jj|_|jdk r:|jjn|S(N(RRpRFRRR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRvs  cCst|trc||jkrtt|j||jdk r`|jj|jdq`qn?tt|j||jdk r|jj|jdn|S(Ni(RsR)RuR RRRFR(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR}s cCs6tt|j|jdk r2|jjn|S(N(R RRRFR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCsV||kr"t||gn||g}|jdk rR|jj|ndS(N(R$RFRR(RRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs  cCsA||g}|jdk r0|jj|n|jgdS(N(RFRRR(RRRy((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCsuytt|jSWntk r*nX|jdkrn|jdk rnd|jjt |jf|_n|jS(Ns%s:(%s)( R RRRaRmRRFR^RR(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs %( RRRRRRRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRZs      cBs#eZdZdZedZRS(s Lookahead matching of the given parse expression. C{FollowedBy} does I{not} advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current position. C{FollowedBy} always returns a null token list. Example:: # use FollowedBy to match a label only if it is followed by a ':' data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint() prints:: [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] cCs#tt|j|t|_dS(N(R R RRRs(RRF((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCs|jj|||gfS(N(RFR(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs(RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR s cBs,eZdZdZedZdZRS(s Lookahead to disallow matching with the given parse expression. C{NotAny} does I{not} advance the parsing position within the input string, it only verifies that the specified parse expression does I{not} match at the current position. Also, C{NotAny} does I{not} skip over leading whitespace. C{NotAny} always returns a null token list. May be constructed using the '~' operator. Example:: cCsBtt|j|t|_t|_dt|j|_ dS(NsFound unwanted token, ( R RRRRpRRsRRFRy(RRF((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs  cCs:|jj||r0t|||j|n|gfS(N(RFRRRy(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCsIt|dr|jS|jdkrBdt|jd|_n|jS(NRs~{R(RRRmRRRF(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs (RRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs   t_MultipleMatchcBs eZddZedZRS(cCsftt|j|t|_|}t|trFtj|}n|dk rY|nd|_ dS(N( R RRRRoRsRR"RiRt not_ender(RRFtstopOntender((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs  c Cs|jj}|j}|jdk }|r9|jj}n|rO|||n||||dt\}}y|j } xo|r|||n| r|||} n|} ||| |\}} | s| jr~|| 7}q~q~WWnt t fk rnX||fS(NR( RFRRRRRRRuRRR( RRERRtself_expr_parsetself_skip_ignorablest check_endert try_not_enderRthasIgnoreExprsRt tmptokens((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs,   N(RRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs cBseZdZdZRS(s Repetition of one or more of the given expression. Parameters: - expr - expression that must match one or more times - stopOn - (default=C{None}) - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) text = "shape: SQUARE posn: upper left color: BLACK" OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] # use stopOn attribute for OneOrMore to avoid reading label string as part of the data attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] # could also be written as (attr_expr * (1,)).parseString(text).pprint() cCsIt|dr|jS|jdkrBdt|jd|_n|jS(NRRs}...(RRRmRRRF(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR!s (RRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscBs/eZdZddZedZdZRS(sw Optional repetition of zero or more of the given expression. Parameters: - expr - expression that must match zero or more times - stopOn - (default=C{None}) - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) Example: similar to L{OneOrMore} cCs)tt|j|d|t|_dS(NR(R R0RRRs(RRFR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR6scCsEy tt|j|||SWnttfk r@|gfSXdS(N(R R0RRR(RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR:s cCsIt|dr|jS|jdkrBdt|jd|_n|jS(NRRs]...(RRRmRRRF(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR@s N(RRRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR0*s   t _NullTokencBs eZdZeZdZRS(cCstS(N(R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRJscCsdS(NRr((R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRMs(RRRR>R(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRIs cBs/eZdZedZedZdZRS(sa Optional matching of the given expression. Parameters: - expr - expression that must match zero or more times - default (optional) - value to be returned if the optional expression is not found. Example:: # US postal code can be a 5-digit zip, plus optional 4-digit qualifier zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4))) zip.runTests(''' # traditional ZIP code 12345 # ZIP+4 form 12101-0001 # invalid ZIP 98765- ''') prints:: # traditional ZIP code 12345 ['12345'] # ZIP+4 form 12101-0001 ['12101-0001'] # invalid ZIP 98765- ^ FAIL: Expected end of text (at char 5), (line:1, col:6) cCsAtt|j|dt|jj|_||_t|_dS(NR( R RRRRFRoRRRs(RRFR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRts cCsy(|jj|||dt\}}Wnottfk r|jtk r|jjrt|jg}|j||jj ['3', '.', '1416'] # will also erroneously match the following print(real.parseString('3. 1416')) # -> ['3', '.', '1416'] real = Combine(Word(nums) + '.' + Word(nums)) print(real.parseString('3.1416')) # -> ['3.1416'] # no match when there are internal spaces print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...) RrcCsQtt|j||r)|jn||_t|_||_t|_dS(N( R RRRtadjacentRRpt joinStringR}(RRFRR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRrs    cCs6|jrtj||ntt|j||S(N(RR"RR R(RR ((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR|s cCse|j}|2|tdj|j|jgd|j7}|jr]|jr]|gS|SdS(NRrR(RR RRRRzRnR(RRERRtretToks((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs  1(RRRRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRas cBs eZdZdZdZRS(s Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions. Example:: ident = Word(alphas) num = Word(nums) term = ident | num func = ident + Optional(delimitedList(term)) print(func.parseString("fn a,b,100")) # -> ['fn', 'a', 'b', '100'] func = ident + Group(Optional(delimitedList(term))) print(func.parseString("fn a,b,100")) # -> ['fn', ['a', 'b', '100']] cCs#tt|j|t|_dS(N(R RRRRo(RRF((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCs|gS(N((RRERR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs(RRRRR(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRs  cBs eZdZdZdZRS(sW Converter to return a repetitive expression as a list, but also as a dictionary. Each element can also be referenced using the first token in the expression as its key. Useful for tabular report scraping when the first column can be used as a item key. Example:: data_word = Word(alphas) label = data_word + FollowedBy(':') attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) # print attributes as plain groups print(OneOrMore(attr_expr).parseString(text).dump()) # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names result = Dict(OneOrMore(Group(attr_expr))).parseString(text) print(result.dump()) # access named fields as dict entries, or output as dict print(result['shape']) print(result.asDict()) prints:: ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'} See more examples at L{ParseResults} of accessing fields by results name. cCs#tt|j|t|_dS(N(R R RRRo(RRF((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRscCsTx9t|D]+\}}t|dkr1q n|d}t|trct|dj}nt|dkrtd|||nX|S(ss Decorator for debugging parse actions. When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".} When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised. Example:: wd = Word(alphas) @traceParseAction def remove_duplicate_chars(tokens): return ''.join(sorted(set(''.join(tokens))) wds = OneOrMore(wd).setParseAction(remove_duplicate_chars) print(wds.parseString("slkdjs sld sldd sdlf sdljf")) prints:: >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) <>entering %s(line: '%s', %d, %r) s< ['aa', 'bb', 'cc'] delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] s [Rs]...N(RRR0RR)(RFtdelimtcombinetdlName((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR>9s ,!cstfd}|dkrBttjd}n |j}|jd|j|dt|jdt dS(s: Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value. Example:: countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] # in this parser, the leading integer value is given in binary, # '10' indicating that 2 values are in the array binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd'] cs;|d}|r,ttg|p5tt>gS(Ni(RRRA(RRNRpR(t arrayExprRF(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytcountFieldParseAction_s -cSst|dS(Ni(Ro(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqdRrtarrayLenR~s(len) s...N( R RR-RPRzRRRRR(RFtintExprR((RRFs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR:Ls    cCsMg}x@|D]8}t|tr8|jt|q |j|q W|S(N(RsRRRR(tLR}R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRks  csFtfd}|j|dtjdt|S(s* Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousLiteral(first) matchExpr = first + ":" + second will match C{"1:1"}, but not C{"1:2"}. Because this matches a previous literal, will also match the leading C{"1:1"} in C{"1:10"}. If this is not desired, use C{matchPreviousExpr}. Do I{not} use with packrat parsing enabled. csc|rTt|dkr'|d>q_t|j}td|D>n t>dS(Niicss|]}t|VqdS(N(R(Rttt((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s(RRRRR (RRNRpttflat(trep(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytcopyTokenToRepeaters R~s(prev) (R RRRR(RFR((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRMts  cs\t|j}|Kfd}|j|dtjdt|S(sS Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousExpr(first) matchExpr = first + ":" + second will match C{"1:1"}, but not C{"1:2"}. Because this matches by expressions, will I{not} match the leading C{"1:1"} in C{"1:10"}; the expressions are evaluated first, and then compared, so C{"1"} is compared with C{"10"}. Do I{not} use with packrat parsing enabled. cs8t|jfd}j|dtdS(Ncs7t|j}|kr3tdddndS(NRri(RRR(RRNRpt theseTokens(t matchTokens(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytmustMatchTheseTokenss R~(RRRzR(RRNRpR(R(Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRsR~s(prev) (R RRRRR(RFte2R((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRLs   cCsUx$dD]}|j|t|}qW|jdd}|jdd}t|S(Ns\^-]s s\ns s\t(Rt_bslashR(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyREs  c sD|r!d}d}tnd}d}tg}t|tr]|j}n7t|tjr~t|}ntj dt dd|st Sd}x|t |d krV||}xt ||d D]f\}} || |r |||d =Pq||| r|||d =|j|| | }PqqW|d 7}qW| r|ryt |t d j|krtd d jd |Djd j|Stdjd|Djd j|SWqtk rtj dt ddqXntfd|Djd j|S(s Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a C{L{MatchFirst}} for best performance. Parameters: - strs - a string of space-delimited literals, or a collection of string literals - caseless - (default=C{False}) - treat all literals as caseless - useRegex - (default=C{True}) - as an optimization, will generate a Regex object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or if creating a C{Regex} raises an exception) Example:: comp_oper = oneOf("< = > <= >= !=") var = Word(alphas) number = Word(nums) term = var | number comparison_expr = term + comp_oper + term print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12")) prints:: [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] cSs|j|jkS(N(R,(R tb((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrcSs|jj|jS(N(R,R)(R R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrcSs ||kS(N((R R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrcSs |j|S(N(R)(R R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrs6Invalid argument to oneOf, expected string or iterableRiiiRrs[%s]css|]}t|VqdS(N(RE(Rtsym((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys ss | t|css|]}tj|VqdS(N(R|RG(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys ss7Exception creating Regex for oneOf, building MatchFirstc3s|]}|VqdS(N((RR(tparseElementClass(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys s(RRRsRRRRwRRRRRRRRRR%RRaR( tstrsR+tuseRegextisequaltmaskstsymbolsRtcurRR ((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRQsL        ! !33  cCsttt||S(s Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} (R R0R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR?s!cCs|tjd}|j}t|_|d||d}|rVd}n d}|j||j|_|S(s Helper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. By default, returns astring containing the original parsed text. If the optional C{asString} argument is passed as C{False}, then the return value is a C{L{ParseResults}} containing any results names that were originally matched, and a single token containing the original matched text from the input string. So if the expression passed to C{L{originalTextFor}} contains expressions with defined results names, you must set C{asString} to C{False} if you want to preserve those results name values. Example:: src = "this is test bold text normal text " for tag in ("b","i"): opener,closer = makeHTMLTags(tag) patt = originalTextFor(opener + SkipTo(closer) + closer) print(patt.searchString(src)[0]) prints:: [' bold text '] ['text'] cSs|S(N((RRRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRq8Rrt_original_startt _original_endcSs||j|j!S(N(RR(RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRq=RrcSs'||jd|jd!g|(dS(NRR(R(RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt extractText?s(R RzRRR}Ru(RFtasStringt locMarkert endlocMarkert matchExprR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRe s      cCst|jdS(sp Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. cSs|dS(Ni((Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqJRr(R+Rz(RF((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRfEscCsEtjd}t|d|d|jjdS(s Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - locn_start = location where matched expression begins - locn_end = location where matched expression ends - value = the actual parsed results Be careful if the input text contains C{} characters, you may want to call C{L{ParserElement.parseWithTabs}} Example:: wd = Word(alphas) for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): print(match) prints:: [[0, 'ljsdf', 5]] [[8, 'lksdjjf', 15]] [[18, 'lkkjj', 23]] cSs|S(N((RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRq`Rrt locn_startRtlocn_end(R RzRRR(RFtlocator((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRhLss\[]-*.$+^?()~ RKcCs |ddS(Nii((RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqkRrs\\0?[xX][0-9a-fA-F]+cCs tt|djddS(Nis\0xi(tunichrRotlstrip(RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqlRrs \\0[0-7]+cCstt|dddS(Niii(RRo(RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqmRrR<s\]s\wRzRRtnegatetbodyRcsOdy-djfdtj|jDSWntk rJdSXdS(s Helper to easily define string ranges for use in Word construction. Borrows syntax from regexp '[]' string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" The input string must be enclosed in []'s, and the returned string is the expanded character set joined into a single string. The values enclosed in the []'s may be: - a single character - an escaped character with a leading backslash (such as C{\-} or C{\]}) - an escaped hex character with a leading C{'\x'} (C{\x21}, which is a C{'!'} character) (C{\0x##} is also supported for backwards compatibility) - an escaped octal character with a leading C{'\0'} (C{\041}, which is a C{'!'} character) - a range of any of the above, separated by a dash (C{'a-z'}, etc.) - any combination of the above (C{'aeiouy'}, C{'a-zA-Z0-9_$'}, etc.) cSsKt|ts|Sdjdtt|dt|ddDS(NRrcss|]}t|VqdS(N(R(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys sii(RsR RRtord(tp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrRrc3s|]}|VqdS(N((Rtpart(t _expanded(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys sN(Rt_reBracketExprRRRa(R((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyR]rs  - csfd}|S(st Helper method for defining parse actions that require matching at a specific column in the input text. cs2t||kr.t||dndS(Nsmatched token not at column %d(R7R(R@tlocnRJ(R(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt verifyCols((RR((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRKscs fdS(s Helper method for common parse actions that simply return a literal value. Especially useful when used with C{L{transformString}()}. Example:: num = Word(nums).setParseAction(lambda toks: int(toks[0])) na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) term = na | num OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] csgS(N((RRNRp(treplStr(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRr((R((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRZs cCs|ddd!S(s Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] iii((RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRXs csafd}y"tdtdj}Wntk rSt}nX||_|S(sG Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the parsed data to an integer using base 16. Example (compare the last to example in L{ParserElement.transformString}:: hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) hex_ints.runTests(''' 00 11 22 aa FF 0a 0d 1a ''') upperword = Word(alphas).setParseAction(tokenMap(str.upper)) OneOrMore(upperword).runTests(''' my kingdom for a horse ''') wd = Word(alphas).setParseAction(tokenMap(str.title)) OneOrMore(wd).setParseAction(' '.join).runTests(''' now is the winter of our discontent made glorious summer by this sun of york ''') prints:: 00 11 22 aa FF 0a 0d 1a [0, 17, 34, 170, 255, 10, 13, 26] my kingdom for a horse ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] now is the winter of our discontent made glorious summer by this sun of york ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] cs g|D]}|^qS(N((RRNRpttokn(RRO(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRsRR^(R`RRaRu(RORRRd((RROs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRks    cCst|jS(N(RR,(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrcCst|jS(N(Rtlower(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrcCs<t|tr+|}t|d| }n |j}tttd}|rtjj t }t d|dt t t|t d|tddtgjdj d t d }nd jd tD}tjj t t|B}t d|dt t t|j ttt d|tddtgjdj d t d }ttd|d }|jdd j|jddjjjd|}|jdd j|jddjjjd|}||_||_||fS(sRInternal helper to construct opening and closing tag expressions, given a tag nameR+s_-:Rttagt=t/RRAcSs|ddkS(NiR((RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrR Rrcss!|]}|dkr|VqdS(R N((RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys scSs|ddkS(NiR((RRNRp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrsRLs(RsRRRR-R2R1R<RRzRXR)R R0RRRRRRTRWR@Rt_LRttitleRRR(ttagStrtxmltresnamet tagAttrNamet tagAttrValuetopenTagtprintablesLessRAbracktcloseTag((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt _makeTagss" o{AA  cCs t|tS(s  Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. Example:: text = 'More info at the pyparsing wiki page' # makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple a,a_end = makeHTMLTags("A") link_expr = a + SkipTo(a_end)("link_text") + a_end for link in link_expr.searchString(text): # attributes in the tag (like "href" shown here) are also accessible as named results print(link.link_text, '->', link.href) prints:: pyparsing -> http://pyparsing.wikispaces.com (R R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRIscCs t|tS(s Helper to construct opening and closing tag expressions for XML, given a tag name. Matches tags only in the given upper/lower case. Example: similar to L{makeHTMLTags} (R R(R((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRJscsT|r|n |jgD]\}}||f^q#fd}|S(s< Helper to create a validating parse action to be used with start tags created with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as C{} or C{
}. Call C{withAttribute} with a series of attribute names and values. Specify the list of filter attributes names and values as: - keyword arguments, as in C{(align="right")}, or - as an explicit dict with C{**} operator, when an attribute name is also a Python reserved word, as in C{**{"class":"Customer", "align":"right"}} - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) For attribute names with a namespace prefix, you must use the second form. Attribute names are matched insensitive to upper/lower case. If just testing for C{class} (with or without a namespace), use C{L{withClass}}. To verify that the attribute exists, but without specifying a value, pass C{withAttribute.ANY_VALUE} as the value. Example:: html = '''
Some text
1 4 0 1 0
1,3 2,3 1,1
this has no type
''' div,div_end = makeHTMLTags("div") # only match div tag having a type attribute with value "grid" div_grid = div().setParseAction(withAttribute(type="grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.searchString(html): print(grid_header.body) # construct a match with any div tag having a type attribute, regardless of the value div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.searchString(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 csx~D]v\}}||kr8t||d|n|tjkr|||krt||d||||fqqWdS(Nsno matching attribute s+attribute '%s' has value '%s', must be '%s'(RRct ANY_VALUE(RRNRtattrNamet attrValue(tattrs(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRRs   (R(RtattrDictRRR((Rs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRcs 2  %cCs'|rd|nd}ti||6S(s Simplified version of C{L{withAttribute}} when matching on a div class - made difficult because C{class} is a reserved word in Python. Example:: html = '''
Some text
1 4 0 1 0
1,3 2,3 1,1
this <div> has no class
''' div,div_end = makeHTMLTags("div") div_grid = div().setParseAction(withClass("grid")) grid_expr = div_grid + SkipTo(div | div_end)("body") for grid_header in grid_expr.searchString(html): print(grid_header.body) div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE)) div_expr = div_any_type + SkipTo(div | div_end)("body") for div_header in div_expr.searchString(html): print(div_header.body) prints:: 1 4 0 1 0 1 4 0 1 0 1,3 2,3 1,1 s%s:classtclass(Rc(t classnamet namespacet classattr((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRi\s t(RYcCs<t}||||B}xt|D]\}}|d d \}} } } | dkrdd|nd|} | dkr|d kst|dkrtdn|\} }ntj| }| tjkr| dkr t||t |t |}q| dkrx|d k rQt|||t |t ||}qt||t |t |}q| dkrt|| |||t || |||}qtdn+| tj kr| dkr)t |t st |}nt|j|t ||}q| dkr|d k rpt|||t |t ||}qt||t |t |}q| dkrt|| |||t || |||}qtdn td | r |j| n||j| |BK}|}q(W||K}|S( s Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. The generated parser will also recognize the use of parentheses to override operator precedences (see example below). Note: if you define a deep operator list, you may see performance issues when using infixNotation. See L{ParserElement.enablePackrat} for a mechanism to potentially improve your parser performance. Parameters: - baseExpr - expression representing the most basic element for the nested - opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form (opExpr, numTerms, rightLeftAssoc, parseAction), where: - opExpr is the pyparsing expression for the operator; may also be a string, which will be converted to a Literal; if numTerms is 3, opExpr is a tuple of two expressions, for the two operators separating the 3 terms - numTerms is the number of terms for this operator (must be 1, 2, or 3) - rightLeftAssoc is the indicator whether the operator is right or left associative, using the pyparsing-defined constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}. - parseAction is the parse action to be associated with expressions matching this operator expression (the parse action tuple member may be omitted) - lpar - expression for matching left-parentheses (default=C{Suppress('(')}) - rpar - expression for matching right-parentheses (default=C{Suppress(')')}) Example:: # simple example of four-function arithmetic with ints and variable names integer = pyparsing_common.signed_integer varname = pyparsing_common.identifier arith_expr = infixNotation(integer | varname, [ ('-', 1, opAssoc.RIGHT), (oneOf('* /'), 2, opAssoc.LEFT), (oneOf('+ -'), 2, opAssoc.LEFT), ]) arith_expr.runTests(''' 5+3*6 (5+3)*6 -2--11 ''', fullDump=False) prints:: 5+3*6 [[5, '+', [3, '*', 6]]] (5+3)*6 [[[5, '+', 3], '*', 6]] -2--11 [[['-', 2], '-', ['-', 11]]] iis%s terms %s%s termis@if numterms=3, opExpr must be a tuple or list of two expressionsis6operator must be unary (1), binary (2), or ternary (3)s2operator must indicate right or left associativityN(N(R RRRRRRRtLEFTR RRtRIGHTRsRRFRz(tbaseExprtopListtlpartrparR}tlastExprRtoperDeftopExprtaritytrightLeftAssocRttermNametopExpr1topExpr2tthisExprR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRgsR;    '  /'   $  /'     s4"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*t"s string enclosed in double quotess4'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*t's string enclosed in single quotess*quotedString using single or double quotestusunicode string literalcCs!||krtdn|d krt|trt|trt|dkrt|dkr|d k rtt|t||tj ddj d}q|t j t||tj j d}q|d k r9tt|t |t |ttj ddj d}qttt |t |ttj ddj d}qtdnt}|d k r|tt|t||B|Bt|K}n.|tt|t||Bt|K}|jd ||f|S( s~ Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression - content - expression for items within the nested lists (default=C{None}) - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString}) If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the C{ignoreExpr} argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. The default is L{quotedString}, but if no expressions are to be ignored, then pass C{None} for this argument. Example:: data_type = oneOf("void int short long char float double") decl_data_type = Combine(data_type + Optional(Word('*'))) ident = Word(alphas+'_', alphanums+'_') number = pyparsing_common.number arg = Group(decl_data_type + ident) LPAR,RPAR = map(Suppress, "()") code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) c_function = (decl_data_type("type") + ident("name") + LPAR + Optional(delimitedList(arg), [])("args") + RPAR + code_body("body")) c_function.ignore(cStyleComment) source_code = ''' int is_odd(int x) { return (x%2); } int dec_to_hex(char hchar) { if (hchar >= '0' && hchar <= '9') { return (ord(hchar)-ord('0')); } else { return (10+ord(hchar)-ord('A')); } } ''' for func in c_function.searchString(source_code): print("%(name)s (%(type)s) args: %(args)s" % func) prints:: is_odd (int) args: [['int', 'x']] dec_to_hex (int) args: [['char', 'hchar']] s.opening and closing strings cannot be the sameiRKcSs|djS(Ni(R(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRq9RrcSs|djS(Ni(R(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRq<RrcSs|djS(Ni(R(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqBRrcSs|djS(Ni(R(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqFRrsOopening and closing arguments must be strings if no content expression is givensnested %s%s expressionN(RRRsRRRRRR"RfRzRARRR RR)R0R(topenertclosertcontentRR}((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRNs4:  $  $    5.c s5fd}fd}fd}ttjdj}ttj|jd}tj|jd}tj|jd} |rtt||t|t|t|| } n0tt|t|t|t|} |j t t| jdS( s Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements (default=C{True}) A valid block must contain at least one C{blockStatement}. Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group( funcDecl + func_body ) rvalue = Forward() funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << ( funcDef | assignment | identifier ) module_body = OneOrMore(stmt) parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] css|t|krdSt||}|dkro|dkrZt||dnt||dndS(Nisillegal nestingsnot a peer entry(RR7RR(RRNRptcurCol(t indentStack(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytcheckPeerIndentscsEt||}|dkr/j|nt||ddS(Nisnot a subentry(R7RR(RRNRpR+(R,(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytcheckSubIndentscsn|t|krdSt||}oH|dkoH|dks`t||dnjdS(Niisnot an unindent(RR7RR(RRNRpR+(R,(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt checkUnindents &s tINDENTRrtUNINDENTsindented block( RRRRR RzRRRRR( tblockStatementExprR,R$R-R.R/R7R0tPEERtUNDENTtsmExpr((R,s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRdQsN"8 $s#[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]s[\0xa1-\0xbf\0xd7\0xf7]s_:sany tagsgt lt amp nbsp quot aposs><& "'s &(?PRs);scommon HTML entitycCstj|jS(sRHelper parser action to replace common HTML entities with their special characters(t_htmlEntityMapRtentity(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRYss/\*(?:[^*]|\*(?!/))*s*/sC style commentss HTML comments.*s rest of lines//(?:\\\n|[^\n])*s // commentsC++ style comments#.*sPython style comments t commaItemRcBseZdZeeZeeZee j dj eZ ee j dj eedZedj dj eZej edej ej dZejdeeeed jeBj d Zejeed j d j eZed j dj eZeeBeBjZedj dj eZeededj dZedj dZedj dZ e de dj dZ!ee de d8dee de d9j dZ"e"j#ddej d Z$e%e!e$Be"Bj d!j d!Z&ed"j d#Z'e(d$d%Z)e(d&d'Z*ed(j d)Z+ed*j d+Z,ed,j d-Z-e.je/jBZ0e(d.Z1e%e2e3d/e4ee5d0d/ee6d1jj d2Z7e8ee9j:e7Bd3d4j d5Z;e(ed6Z<e(ed7Z=RS(:s Here are some common low-level expressions that may be useful in jump-starting parser development: - numeric forms (L{integers}, L{reals}, L{scientific notation}) - common L{programming identifiers} - network addresses (L{MAC}, L{IPv4}, L{IPv6}) - ISO8601 L{dates} and L{datetime} - L{UUID} - L{comma-separated list} Parse actions: - C{L{convertToInteger}} - C{L{convertToFloat}} - C{L{convertToDate}} - C{L{convertToDatetime}} - C{L{stripHTMLTags}} - C{L{upcaseTokens}} - C{L{downcaseTokens}} Example:: pyparsing_common.number.runTests(''' # any int or real number, returned as the appropriate type 100 -100 +100 3.14159 6.02e23 1e-12 ''') pyparsing_common.fnumber.runTests(''' # any int or real number, returned as float 100 -100 +100 3.14159 6.02e23 1e-12 ''') pyparsing_common.hex_integer.runTests(''' # hex numbers 100 FF ''') pyparsing_common.fraction.runTests(''' # fractions 1/2 -3/4 ''') pyparsing_common.mixed_integer.runTests(''' # mixed fractions 1 1/2 -3/4 1-3/4 ''') import uuid pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) pyparsing_common.uuid.runTests(''' # uuid 12345678-1234-5678-1234-567812345678 ''') prints:: # any int or real number, returned as the appropriate type 100 [100] -100 [-100] +100 [100] 3.14159 [3.14159] 6.02e23 [6.02e+23] 1e-12 [1e-12] # any int or real number, returned as float 100 [100.0] -100 [-100.0] +100 [100.0] 3.14159 [3.14159] 6.02e23 [6.02e+23] 1e-12 [1e-12] # hex numbers 100 [256] FF [255] # fractions 1/2 [0.5] -3/4 [-0.75] # mixed fractions 1 [1] 1/2 [0.5] -3/4 [-0.75] 1-3/4 [1.75] # uuid 12345678-1234-5678-1234-567812345678 [UUID('12345678-1234-5678-1234-567812345678')] tintegers hex integeris[+-]?\d+ssigned integerRtfractioncCs|d|dS(Nii((Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrRzs"fraction or mixed integer-fractions [+-]?\d+\.\d*s real numbers+[+-]?\d+([eE][+-]?\d+|\.\d*([eE][+-]?\d+)?)s$real number with scientific notations[+-]?\d+\.?\d*([eE][+-]?\d+)?tfnumberRt identifiersK(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}s IPv4 addresss[0-9a-fA-F]{1,4}t hex_integerRisfull IPv6 addressiis::sshort IPv6 addresscCstd|DdkS(Ncss'|]}tjj|rdVqdS(iN(Rlt _ipv6_partR(RR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pys si(R(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrs::ffff:smixed IPv6 addresss IPv6 addresss:[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}s MAC addresss%Y-%m-%dcsfd}|S(s Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"}) Example:: date_expr = pyparsing_common.iso8601_date.copy() date_expr.setParseAction(pyparsing_common.convertToDate()) print(date_expr.parseString("1999-12-31")) prints:: [datetime.date(1999, 12, 31)] csPytj|djSWn+tk rK}t||t|nXdS(Ni(RtstrptimetdateRRRu(RRNRptve(tfmt(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytcvt_fns((RBRC((RBs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt convertToDatess%Y-%m-%dT%H:%M:%S.%fcsfd}|S(s Helper to create a parse action for converting parsed datetime string to Python datetime.datetime Params - - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"}) Example:: dt_expr = pyparsing_common.iso8601_datetime.copy() dt_expr.setParseAction(pyparsing_common.convertToDatetime()) print(dt_expr.parseString("1999-12-31T23:59:59.999")) prints:: [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] csJytj|dSWn+tk rE}t||t|nXdS(Ni(RR?RRRu(RRNRpRA(RB(s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRCs((RBRC((RBs9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pytconvertToDatetimess7(?P\d{4})(?:-(?P\d\d)(?:-(?P\d\d))?)?s ISO8601 dates(?P\d{4})-(?P\d\d)-(?P\d\d)[T ](?P\d\d):(?P\d\d)(:(?P\d\d(\.\d*)?)?)?(?PZ|[+-]\d\d:?\d\d)?sISO8601 datetimes2[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}tUUIDcCstjj|dS(s Parse action to remove HTML tags from web page HTML source Example:: # strip HTML links from normal text text = 'More info at the
pyparsing wiki page' td,td_end = makeHTMLTags("TD") table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' i(Rlt_html_stripperR{(RRNR((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt stripHTMLTagss RR<s R8RRrscomma separated listcCst|jS(N(RR,(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRrcCst|jS(N(RR(Rp((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRqRr(ii(ii(>RRRRkRotconvertToIntegertfloattconvertToFloatR-RPRRzR9RBR=R%tsigned_integerR:RRRt mixed_integerRtrealtsci_realRtnumberR;R2R1R<t ipv4_addressR>t_full_ipv6_addresst_short_ipv6_addressRt_mixed_ipv6_addressRt ipv6_addresst mac_addressR#RDREt iso8601_datetiso8601_datetimetuuidR5R4RGRHRRRRTR,t _commasepitemR>RWRtcomma_separated_listRbR@(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyRlsL  '/-  ;&J+t__main__tselecttfroms_$RRtcolumnsRttablestcommandsK # '*' as column list and dotted table name select * from SYS.XYZZY # caseless match on "SELECT", and casts back to "select" SELECT * from XYZZY, ABC # list of column names, and mixed case SELECT keyword Select AA,BB,CC from Sys.dual # multiple tables Select A, B, C from Sys.dual, Table2 # invalid SELECT keyword - should fail Xelect A, B, C from Sys.dual # incomplete command - should fail Select # invalid column name - should fail Select ^^^ frox Sys.dual s] 100 -100 +100 3.14159 6.02e23 1e-12 s 100 FF s6 12345678-1234-5678-1234-567812345678 (Rt __version__t__versionTime__t __author__RtweakrefRRRRxRR|RSRR8RRRRt_threadRt ImportErrort threadingRRt ordereddictRt__all__Rt version_infoRQRtmaxsizeR$RuRtchrRRRRR2treversedRRR4RxRIRJR_tmaxinttxrangeRt __builtin__RtfnameRR`RRRRRRtascii_uppercasetascii_lowercaseR2RPRBR1RRt printableRTRaRRRR!R$RR tMutableMappingtregisterR7RHRERGRKRMROReR"R*R RRRRiRRRRjR-R%R#RR,RpRRRR(R'R/R.RRRRR RR RRRR0RRRR&R RR+RRR R)RR`RR>R:RRMRLRERRQR?ReRfRhRRARGRFR_R^Rzt _escapedPunct_escapedHexChart_escapedOctChartUNICODEt _singleChart _charRangeRRR]RKRZRXRkRbR@R RIRJRcR RiRRRRRgRSR<R\RWRaRNRdR3RUR5R4RRR6RR9RYR6RCRR[R=R;RDRVRRZR8RlRt selectTokent fromTokentidentt columnNametcolumnNameListt columnSpect tableNamet tableNameListt simpleSQLR"RPR;R=RYRF(((s9/usr/lib/python2.7/site-packages/pip/_vendor/pyparsing.pyt=s              *         8      @ & A=IG3pLOD|M &# @sQ,A ,    I # %  !4@    ,   ?  #   k%Z r  (, #8+    $     _vendor/re-vendor.pyc000064400000002650152527136320010627 0ustar00 abc@sddlZddlZddlZddlZddlZejjejjeZ dZ dZ dZ e dkreejdkre nejddkre qejdd kre qe ndS( iNcCsdGHtjddS(Ns"Usage: re-vendor.py [clean|vendor]i(tsystexit(((s9/usr/lib/python2.7/site-packages/pip/_vendor/re-vendor.pytusage scCsqxNtjtD]=}tjjt|}tjj|rtj|qqWtjtjjtddS(Nssix.py( tostlistdirtheretpathtjointisdirtshutiltrmtreetunlink(tfntdirname((s9/usr/lib/python2.7/site-packages/pip/_vendor/re-vendor.pytclean s cCsGtjddtddgx$tjdD]}tj|q,WdS(Ntinstalls-ts-rs vendor.txts *.egg-info(tpiptmainRtglobR R (R ((s9/usr/lib/python2.7/site-packages/pip/_vendor/re-vendor.pytvendorst__main__iiRR(RRRRR RtabspathR t__file__RRRRt__name__tlentargv(((s9/usr/lib/python2.7/site-packages/pip/_vendor/re-vendor.pyts            _vendor/distro.pyo000064400000106157152527136320010255 0ustar00 abc@sdZddlZddlZddlZddlZddlZddlZddlZejj d re dj ejndZ dZ iZidd6d d 6Zid d 6Zejd Zejd Zddde dfZedZdZedZeedZedZedZedZedZdZdZ eedZ!dZ"dZ#dZ$d Z%d!Z&d"Z'd#e(fd$YZ)e)Z*d%Z+e,d&kre+ndS('s, The ``distro`` package (``distro`` stands for Linux Distribution) provides information about the Linux distribution it runs on, such as a reliable machine-readable distro ID, or version information. It is a renewed alternative implementation for Python's original :py:func:`platform.linux_distribution` function, but it provides much more functionality. An alternative implementation became necessary because Python 3.5 deprecated this function, and Python 3.7 is expected to remove it altogether. Its predecessor function :py:func:`platform.dist` was already deprecated since Python 2.6 and is also expected to be removed in Python 3.7. Still, there are many cases in which access to Linux distribution information is needed. See `Python issue 1322 `_ for more information. iNtlinuxsUnsupported platform: {0}s/etcs os-releasetoracletenterpriseenterprisetrheltredhatenterpriseworkstationtredhatsA(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)s(\w+)[-_](release|version)$tdebian_versions lsb-releases oem-releasessystem-releasecCs tj|S(s$ Return information about the current Linux distribution as a tuple ``(id_name, version, codename)`` with items as follows: * ``id_name``: If *full_distribution_name* is false, the result of :func:`distro.id`. Otherwise, the result of :func:`distro.name`. * ``version``: The result of :func:`distro.version`. * ``codename``: The result of :func:`distro.codename`. The interface of this function is compatible with the original :py:func:`platform.linux_distribution` function, supporting a subset of its parameters. The data it returns may not exactly be the same, because it uses more data sources than the original function, and that may lead to different data if the Linux distribution is not consistent across multiple data sources it provides (there are indeed such distributions ...). Another reason for differences is the fact that the :func:`distro.id` method normalizes the distro ID string to a reliable machine-readable value for a number of popular Linux distributions. (t_distrotlinux_distribution(tfull_distribution_name((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR`scCs tjS(s Return the distro ID of the current Linux distribution, as a machine-readable string. For a number of Linux distributions, the returned distro ID value is *reliable*, in the sense that it is documented and that it does not change across releases of the distribution. This package maintains the following reliable distro ID values: ============== ========================================= Distro ID Distribution ============== ========================================= "ubuntu" Ubuntu "debian" Debian "rhel" RedHat Enterprise Linux "centos" CentOS "fedora" Fedora "sles" SUSE Linux Enterprise Server "opensuse" openSUSE "amazon" Amazon Linux "arch" Arch Linux "cloudlinux" CloudLinux OS "exherbo" Exherbo Linux "gentoo" GenToo Linux "ibm_powerkvm" IBM PowerKVM "kvmibm" KVM for IBM z Systems "linuxmint" Linux Mint "mageia" Mageia "mandriva" Mandriva Linux "parallels" Parallels "pidora" Pidora "raspbian" Raspbian "oracle" Oracle Linux (and Oracle Enterprise Linux) "scientific" Scientific Linux "slackware" Slackware "xenserver" XenServer ============== ========================================= If you have a need to get distros for reliable IDs added into this set, or if you find that the :func:`distro.id` function returns a different distro ID for one of the listed distros, please create an issue in the `distro issue tracker`_. **Lookup hierarchy and transformations:** First, the ID is obtained from the following sources, in the specified order. The first available and non-empty value is used: * the value of the "ID" attribute of the os-release file, * the value of the "Distributor ID" attribute returned by the lsb_release command, * the first part of the file name of the distro release file, The so determined ID value then passes the following transformations, before it is returned by this method: * it is translated to lower case, * blanks (which should not be there anyway) are translated to underscores, * a normalization of the ID is performed, based upon `normalization tables`_. The purpose of this normalization is to ensure that the ID is as reliable as possible, even across incompatible changes in the Linux distributions. A common reason for an incompatible change is the addition of an os-release file, or the addition of the lsb_release command, with ID values that differ from what was previously determined from the distro release file name. (Rtid(((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR |sHcCs tj|S(sn Return the name of the current Linux distribution, as a human-readable string. If *pretty* is false, the name is returned without version or codename. (e.g. "CentOS Linux") If *pretty* is true, the version and codename are appended. (e.g. "CentOS Linux 7.1.1503 (Core)") **Lookup hierarchy:** The name is obtained from the following sources, in the specified order. The first available and non-empty value is used: * If *pretty* is false: - the value of the "NAME" attribute of the os-release file, - the value of the "Distributor ID" attribute returned by the lsb_release command, - the value of the "" field of the distro release file. * If *pretty* is true: - the value of the "PRETTY_NAME" attribute of the os-release file, - the value of the "Description" attribute returned by the lsb_release command, - the value of the "" field of the distro release file, appended with the value of the pretty version ("" and "" fields) of the distro release file, if available. (Rtname(tpretty((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR s$cCstj||S(sy Return the version of the current Linux distribution, as a human-readable string. If *pretty* is false, the version is returned without codename (e.g. "7.0"). If *pretty* is true, the codename in parenthesis is appended, if the codename is non-empty (e.g. "7.0 (Maipo)"). Some distributions provide version numbers with different precisions in the different sources of distribution information. Examining the different sources in a fixed priority order does not always yield the most precise version (e.g. for Debian 8.2, or CentOS 7.1). The *best* parameter can be used to control the approach for the returned version: If *best* is false, the first non-empty version number in priority order of the examined sources is returned. If *best* is true, the most precise version number out of all examined sources is returned. **Lookup hierarchy:** In all cases, the version number is obtained from the following sources. If *best* is false, this order represents the priority order: * the value of the "VERSION_ID" attribute of the os-release file, * the value of the "Release" attribute returned by the lsb_release command, * the version number parsed from the "" field of the first line of the distro release file, * the version number parsed from the "PRETTY_NAME" attribute of the os-release file, if it follows the format of the distro release files. * the version number parsed from the "Description" attribute returned by the lsb_release command, if it follows the format of the distro release files. (Rtversion(R tbest((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR s)cCs tj|S(s Return the version of the current Linux distribution as a tuple ``(major, minor, build_number)`` with items as follows: * ``major``: The result of :func:`distro.major_version`. * ``minor``: The result of :func:`distro.minor_version`. * ``build_number``: The result of :func:`distro.build_number`. For a description of the *best* parameter, see the :func:`distro.version` method. (Rt version_parts(R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs tj|S(s8 Return the major version of the current Linux distribution, as a string, if provided. Otherwise, the empty string is returned. The major version is the first part of the dot-separated version string. For a description of the *best* parameter, see the :func:`distro.version` method. (Rt major_version(R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR+s cCs tj|S(s9 Return the minor version of the current Linux distribution, as a string, if provided. Otherwise, the empty string is returned. The minor version is the second part of the dot-separated version string. For a description of the *best* parameter, see the :func:`distro.version` method. (Rt minor_version(R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR8s cCs tj|S(s6 Return the build number of the current Linux distribution, as a string, if provided. Otherwise, the empty string is returned. The build number is the third part of the dot-separated version string. For a description of the *best* parameter, see the :func:`distro.version` method. (Rt build_number(R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyREs cCs tjS(s Return a space-separated list of distro IDs of distributions that are closely related to the current Linux distribution in regards to packaging and programming interfaces, for example distributions the current distribution is a derivative from. **Lookup hierarchy:** This information item is only provided by the os-release file. For details, see the description of the "ID_LIKE" attribute in the `os-release man page `_. (Rtlike(((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRRscCs tjS(s Return the codename for the release of the current Linux distribution, as a string. If the distribution does not have a codename, an empty string is returned. Note that the returned codename is not always really a codename. For example, openSUSE returns "x86_64". This function does not handle such cases in any special way and just returns the string it finds, if any. **Lookup hierarchy:** * the codename within the "VERSION" attribute of the os-release file, if provided, * the value of the "Codename" attribute returned by the lsb_release command, * the value of the "" field of the distro release file. (Rtcodename(((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRcscCstj||S(s Return certain machine-readable information items about the current Linux distribution in a dictionary, as shown in the following example: .. sourcecode:: python { 'id': 'rhel', 'version': '7.0', 'version_parts': { 'major': '7', 'minor': '0', 'build_number': '' }, 'like': 'fedora', 'codename': 'Maipo' } The dictionary structure and keys are always the same, regardless of which information items are available in the underlying data sources. The values for the various keys are as follows: * ``id``: The result of :func:`distro.id`. * ``version``: The result of :func:`distro.version`. * ``version_parts -> major``: The result of :func:`distro.major_version`. * ``version_parts -> minor``: The result of :func:`distro.minor_version`. * ``version_parts -> build_number``: The result of :func:`distro.build_number`. * ``like``: The result of :func:`distro.like`. * ``codename``: The result of :func:`distro.codename`. For a description of the *pretty* and *best* parameters, see the :func:`distro.version` method. (Rtinfo(R R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR{s)cCs tjS(s Return a dictionary containing key-value pairs for the information items from the os-release file data source of the current Linux distribution. See `os-release file`_ for details about these information items. (Rtos_release_info(((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs tjS(s Return a dictionary containing key-value pairs for the information items from the lsb_release command data source of the current Linux distribution. See `lsb_release command output`_ for details about these information items. (Rtlsb_release_info(((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs tjS(s Return a dictionary containing key-value pairs for the information items from the distro release file data source of the current Linux distribution. See `distro release file`_ for details about these information items. (Rtdistro_release_info(((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs tj|S(s Return a single named information item from the os-release file data source of the current Linux distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `os-release file`_ for details about these information items. (Rtos_release_attr(t attribute((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs tj|S(s Return a single named information item from the lsb_release command output data source of the current Linux distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `lsb_release command output`_ for details about these information items. (Rtlsb_release_attr(R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs tj|S(s Return a single named information item from the distro release file data source of the current Linux distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `distro release file`_ for details about these information items. (Rtdistro_release_attr(R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRstLinuxDistributioncBs1eZdZedddZdZedZdZedZ eedZ edZ ed Z ed Z ed Zd Zd ZeedZdZdZdZdZdZdZdZedZdZedZdZdZedZRS(s Provides information about a Linux distribution. This package creates a private module-global instance of this class with default initialization arguments, that is used by the `consolidated accessor functions`_ and `single source accessor functions`_. By using default initialization arguments, that module-global instance returns data about the current Linux distribution (i.e. the distro this package runs on). Normally, it is not necessary to create additional instances of this class. However, in situations where control is needed over the exact data sources that are used, instances of this class can be created with a specific distro release file, or a specific os-release file, or without invoking the lsb_release command. tcCsj|ptjjtt|_|p'd|_|j|_|rN|j ni|_ |j |_ dS(s8 The initialization method of this class gathers information from the available data sources, and stores that in private instance attributes. Subsequent access to the information items uses these private instance attributes, so that the data sources are read only once. Parameters: * ``include_lsb`` (bool): Controls whether the `lsb_release command output`_ is included as a data source. If the lsb_release command is not available in the program execution path, the data source for the lsb_release command will be empty. * ``os_release_file`` (string): The path name of the `os-release file`_ that is to be used as a data source. An empty string (the default) will cause the default path name to be used (see `os-release file`_ for details). If the specified or defaulted os-release file does not exist, the data source for the os-release file will be empty. * ``distro_release_file`` (string): The path name of the `distro release file`_ that is to be used as a data source. An empty string (the default) will cause a default search algorithm to be used (see `distro release file`_ for details). If the specified distro release file does not exist, or if no default distro release file can be found, the data source for the distro release file will be empty. Public instance attributes: * ``os_release_file`` (string): The path name of the `os-release file`_ that is actually used as a data source. The empty string if no distro release file is used as a data source. * ``distro_release_file`` (string): The path name of the `distro release file`_ that is actually used as a data source. The empty string if no distro release file is used as a data source. Raises: * :py:exc:`IOError`: Some I/O issue with an os-release file or distro release file. * :py:exc:`subprocess.CalledProcessError`: The lsb_release command had some issue (other than not being available in the program execution path). * :py:exc:`UnicodeError`: A data source has unexpected characters or uses an unexpected encoding. RN( tostpathtjoint _UNIXCONFDIRt_OS_RELEASE_BASENAMEtos_release_filetdistro_release_filet_get_os_release_infot_os_release_infot_get_lsb_release_infot_lsb_release_infot_get_distro_release_infot_distro_release_info(tselft include_lsbR$R%((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyt__init__s ;cCs(dj|j|j|j|j|jS(s Return repr of all info sLinuxDistribution(os_release_file={0!r}, distro_release_file={1!r}, _os_release_info={2!r}, _lsb_release_info={3!r}, _distro_release_info={4!r})(tformatR$R%R'R)R+(R,((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyt__repr__Us cCs1|r|jn |j|j|jfS(s Return information about the Linux distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters. For details, see :func:`distro.linux_distribution`. (R R R R(R,R ((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRes  cCssd}|jd}|r+||tS|jd}|rM||tS|jd}|ro||tSdS(srReturn the distro ID of the Linux distribution, as a string. For details, see :func:`distro.id`. cSs(|jjdd}|j||S(Nt t_(tlowertreplacetget(t distro_idttable((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyt normalizexsR tdistributor_idR(RtNORMALIZED_OS_IDRtNORMALIZED_LSB_IDRtNORMALIZED_DISTRO_ID(R,R8R6((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR ss    cCs|jdp*|jdp*|jd}|r|jdpN|jd}|s|jd}|jdt}|r|d|}qqn|pdS(sx Return the name of the Linux distribution, as a string. For details, see :func:`distro.name`. R R9t pretty_namet descriptionR R1R(RRRR tTrue(R,R R R ((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR scCs|jd|jd|jd|j|jdjdd|j|jdjddg}d}|rxk|D]9}|jd|jdks|dkr|}qqWn'x$|D]}|dkr|}PqqW|r|r|jrdj||j}n|S(s~ Return the version of the Linux distribution, as a string. For details, see :func:`distro.version`. t version_idtreleaseR=RR>t.u {0} ({1})(RRRt_parse_distro_release_contentR5tcountRR/(R,R RtversionsR tv((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR s&   ! *  cCsq|jd|}|rmtjd}|j|}|rm|j\}}}||p]d|pfdfSndS(s Return the version of the Linux distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`. Rs(\d+)\.?(\d+)?\.?(\d+)?R(RRR(R tretcompiletmatchtgroups(R,Rt version_strt version_regextmatchestmajortminorR((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs|j|dS(s Return the major version number of the current distribution. For details, see :func:`distro.major_version`. i(R(R,R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs|j|dS(s Return the minor version number of the Linux distribution. For details, see :func:`distro.minor_version`. i(R(R,R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs|j|dS(s{ Return the build number of the Linux distribution. For details, see :func:`distro.build_number`. i(R(R,R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs|jdpdS(s Return the IDs of distributions that are like the Linux distribution. For details, see :func:`distro.like`. tid_likeR(R(R,((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs1|jdp0|jdp0|jdp0dS(ss Return the codename of the Linux distribution. For details, see :func:`distro.codename`. RR(RRR(R,((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCsstd|jd|j||dtd|j|d|j|d|j|d|jd|jS( s Return certain machine-readable information about the Linux distribution. For details, see :func:`distro.info`. R R RRNRORRR(tdictR R RRRRR(R,R R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRs  cCs|jS(s Return a dictionary containing key-value pairs for the information items from the os-release file data source of the Linux distribution. For details, see :func:`distro.os_release_info`. (R'(R,((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR scCs|jS(s Return a dictionary containing key-value pairs for the information items from the lsb_release command data source of the Linux distribution. For details, see :func:`distro.lsb_release_info`. (R)(R,((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs|jS(s Return a dictionary containing key-value pairs for the information items from the distro release file data source of the Linux distribution. For details, see :func:`distro.distro_release_info`. (R+(R,((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyRscCs|jj|dS(s Return a single named information item from the os-release file data source of the Linux distribution. For details, see :func:`distro.os_release_attr`. R(R'R5(R,R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR)scCs|jj|dS(s Return a single named information item from the lsb_release command output data source of the Linux distribution. For details, see :func:`distro.lsb_release_attr`. R(R)R5(R,R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR2scCs|jj|dS(s Return a single named information item from the distro release file data source of the Linux distribution. For details, see :func:`distro.distro_release_attr`. R(R+R5(R,R((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR;scCsAtjj|jr=t|j}|j|SWdQXniS(s Get the information items from the specified os-release file. Returns: A dictionary containing all information items. N(RR tisfileR$topent_parse_os_release_content(R,t release_file((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pyR&DscCsNi}tj|dt}t|_tjddkrat|jtra|jjd|_nt |}x|D]}d|krt|j dd\}}t|tr|jd}n|||j <|dkrFt j d |}|r6|j}|jd }|jd }|j}||d sLinux distro info tools--jsons-jthelps!Output in machine readable formattactiont store_truetindentit sort_keyssName: %sR s Version: %ss Codename: %s(targparsetloggingt getLoggerRtsetLeveltDEBUGt addHandlert StreamHandlerR\RntArgumentParsert add_argumentt parse_argstjsonRtdumpsR?R R R(Rtloggertparsertargstdistribution_versiontdistribution_codename((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pytmains(   ( t__main__(-RRRGR\RRZRRptplatformt startswitht ImportErrorR/R"R#R:R;R<RHRRRR?RR RR R RRRRRRRRRRRRRtobjectRRRR(((s6/usr/lib/python2.7/site-packages/pip/_vendor/distro.pytsd                K ',   ,      _vendor/packaging/requirements.pyo000064400000011741152527136320013412 0ustar00 abc@`sYddlmZmZmZddlZddlZddlmZmZm Z m Z ddlm Z m Z m Z mZmZddlmZddlmZddlmZmZdd lmZmZmZd efd YZe ejejZ ed j!Z"ed j!Z#edj!Z$edj!Z%edj!Z&edj!Z'edj!Z(e dZ)e e e)e BZ*ee e e*Z+e+dZ,e+Z-eddZ.e(e.Z/e-e e&e-Z0e"e e0e#dZ1eej2ej3ej4BZ5eej2ej3ej4BZ6e5e6AZ7ee7e e&e7ddde8dZ9e e$e9e%e9BZ:e:j;de e:dZ<e<j;de edZej;de'Z=e=eZ>e<e e>Z?e/e e>Z@e,e e1e@e?BZAeeAeZBd eCfd!YZDdS("i(tabsolute_importtdivisiontprint_functionN(t stringStartt stringEndtoriginalTextFortParseException(t ZeroOrMoretWordtOptionaltRegextCombine(tLiteral(tparsei(t MARKER_EXPRtMarker(tLegacySpecifiert Specifiert SpecifierSettInvalidRequirementcB`seZdZRS(sJ An invalid requirement was found, users should refer to PEP 508. (t__name__t __module__t__doc__(((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyRst[t]t(t)t,t;t@s-_.tnames[^ ]+turltextrast joinStringtadjacentt _raw_speccC`s |jp dS(Nt(R#(tstltt((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt8R$t specifiercC`s|dS(Ni((R%R&R'((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyR(;R$tmarkercC`st||j|j!S(N(Rt_original_startt _original_end(R%R&R'((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyR(?R$t RequirementcB`s)eZdZdZdZdZRS(sParse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. cC`sytj|}Wn9tk rN}tdj||j|jd!nX|j|_|jrtj|j}|j o|j s|j r|j rtdn|j|_n d|_t |j r|j jng|_ t|j|_|jr|jnd|_dS(Ns+Invalid requirement, parse error at "{0!r}"isInvalid URL given(t REQUIREMENTt parseStringRRtformattlocRRturlparsetschemetnetloctNonetsetR tasListRR)R*(tselftrequirement_stringtreqtet parsed_url((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt__init__Zs"!   'cC`s|jg}|jr@|jdjdjt|jn|jrb|jt|jn|jr|jdj|jn|j r|jdj|j ndj|S(Ns[{0}]Rs@ {0}s; {0}R$( RR tappendR0tjointsortedR)tstrRR*(R8tparts((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt__str__os  +   cC`sdjt|S(Ns(R0RA(R8((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt__repr__s(RRRR=RCRD(((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyR-Ms  (Et __future__RRRtstringtretpip._vendor.pyparsingRRRRRRR R R R tLtpip._vendor.six.moves.urllibR R2tmarkersRRt specifiersRRRt ValueErrorRt ascii_letterstdigitstALPHANUMtsuppresstLBRACKETtRBRACKETtLPARENtRPARENtCOMMAt SEMICOLONtATt PUNCTUATIONtIDENTIFIER_ENDt IDENTIFIERtNAMEtEXTRAtURItURLt EXTRAS_LISTtEXTRASt _regex_strtVERBOSEt IGNORECASEtVERSION_PEP440tVERSION_LEGACYt VERSION_ONEtFalset VERSION_MANYt _VERSION_SPECtsetParseActiont VERSION_SPECtMARKER_SEPERATORtMARKERtVERSION_AND_MARKERtURL_AND_MARKERtNAMED_REQUIREMENTR.tobjectR-(((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pytsZ  "(      _vendor/packaging/_structures.py000064400000002610152527136320013065 0ustar00# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function class Infinity(object): def __repr__(self): return "Infinity" def __hash__(self): return hash(repr(self)) def __lt__(self, other): return False def __le__(self, other): return False def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not isinstance(other, self.__class__) def __gt__(self, other): return True def __ge__(self, other): return True def __neg__(self): return NegativeInfinity Infinity = Infinity() class NegativeInfinity(object): def __repr__(self): return "-Infinity" def __hash__(self): return hash(repr(self)) def __lt__(self, other): return True def __le__(self, other): return True def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not isinstance(other, self.__class__) def __gt__(self, other): return False def __ge__(self, other): return False def __neg__(self): return Infinity NegativeInfinity = NegativeInfinity() _vendor/packaging/__about__.pyo000064400000001416152527136320012573 0ustar00 abc@`srddlmZmZmZdddddddd gZd Zd Zd Zd ZdZ dZ dZ de Z dS(i(tabsolute_importtdivisiontprint_functiont __title__t __summary__t__uri__t __version__t __author__t __email__t __license__t __copyright__t packagings"Core utilities for Python packagess!https://github.com/pypa/packagings16.8s)Donald Stufft and individual contributorssdonald@stufft.ios"BSD or Apache License, Version 2.0sCopyright 2014-2016 %sN( t __future__RRRt__all__RRRRRRR R (((sC/usr/lib/python2.7/site-packages/pip/_vendor/packaging/__about__.pyts_vendor/packaging/version.py000064400000026444152527136320012203 0ustar00# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import collections import itertools import re from ._structures import Infinity __all__ = [ "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN" ] _Version = collections.namedtuple( "_Version", ["epoch", "release", "dev", "pre", "post", "local"], ) def parse(version): """ Parse the given version string and return either a :class:`Version` object or a :class:`LegacyVersion` object depending on if the given version is a valid PEP 440 version or a legacy version. """ try: return Version(version) except InvalidVersion: return LegacyVersion(version) class InvalidVersion(ValueError): """ An invalid version was found, users should refer to PEP 440. """ class _BaseVersion(object): def __hash__(self): return hash(self._key) def __lt__(self, other): return self._compare(other, lambda s, o: s < o) def __le__(self, other): return self._compare(other, lambda s, o: s <= o) def __eq__(self, other): return self._compare(other, lambda s, o: s == o) def __ge__(self, other): return self._compare(other, lambda s, o: s >= o) def __gt__(self, other): return self._compare(other, lambda s, o: s > o) def __ne__(self, other): return self._compare(other, lambda s, o: s != o) def _compare(self, other, method): if not isinstance(other, _BaseVersion): return NotImplemented return method(self._key, other._key) class LegacyVersion(_BaseVersion): def __init__(self, version): self._version = str(version) self._key = _legacy_cmpkey(self._version) def __str__(self): return self._version def __repr__(self): return "".format(repr(str(self))) @property def public(self): return self._version @property def base_version(self): return self._version @property def local(self): return None @property def is_prerelease(self): return False @property def is_postrelease(self): return False _legacy_version_component_re = re.compile( r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE, ) _legacy_version_replacement_map = { "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@", } def _parse_version_parts(s): for part in _legacy_version_component_re.split(s): part = _legacy_version_replacement_map.get(part, part) if not part or part == ".": continue if part[:1] in "0123456789": # pad for numeric comparison yield part.zfill(8) else: yield "*" + part # ensure that alpha/beta/candidate are before final yield "*final" def _legacy_cmpkey(version): # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch # greater than or equal to 0. This will effectively put the LegacyVersion, # which uses the defacto standard originally implemented by setuptools, # as before all PEP 440 versions. epoch = -1 # This scheme is taken from pkg_resources.parse_version setuptools prior to # it's adoption of the packaging library. parts = [] for part in _parse_version_parts(version.lower()): if part.startswith("*"): # remove "-" before a prerelease tag if part < "*final": while parts and parts[-1] == "*final-": parts.pop() # remove trailing zeros from each series of numeric parts while parts and parts[-1] == "00000000": parts.pop() parts.append(part) parts = tuple(parts) return epoch, parts # Deliberately not anchored to the start and end of the string, to make it # easier for 3rd party code to reuse VERSION_PATTERN = r""" v? (?: (?:(?P[0-9]+)!)? # epoch (?P[0-9]+(?:\.[0-9]+)*) # release segment (?P
                                          # pre-release
            [-_\.]?
            (?P(a|b|c|rc|alpha|beta|pre|preview))
            [-_\.]?
            (?P[0-9]+)?
        )?
        (?P                                         # post release
            (?:-(?P[0-9]+))
            |
            (?:
                [-_\.]?
                (?Ppost|rev|r)
                [-_\.]?
                (?P[0-9]+)?
            )
        )?
        (?P                                          # dev release
            [-_\.]?
            (?Pdev)
            [-_\.]?
            (?P[0-9]+)?
        )?
    )
    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
"""


class Version(_BaseVersion):

    _regex = re.compile(
        r"^\s*" + VERSION_PATTERN + r"\s*$",
        re.VERBOSE | re.IGNORECASE,
    )

    def __init__(self, version):
        # Validate the version and parse it into pieces
        match = self._regex.search(version)
        if not match:
            raise InvalidVersion("Invalid version: '{0}'".format(version))

        # Store the parsed out pieces of the version
        self._version = _Version(
            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
            release=tuple(int(i) for i in match.group("release").split(".")),
            pre=_parse_letter_version(
                match.group("pre_l"),
                match.group("pre_n"),
            ),
            post=_parse_letter_version(
                match.group("post_l"),
                match.group("post_n1") or match.group("post_n2"),
            ),
            dev=_parse_letter_version(
                match.group("dev_l"),
                match.group("dev_n"),
            ),
            local=_parse_local_version(match.group("local")),
        )

        # Generate a key which will be used for sorting
        self._key = _cmpkey(
            self._version.epoch,
            self._version.release,
            self._version.pre,
            self._version.post,
            self._version.dev,
            self._version.local,
        )

    def __repr__(self):
        return "".format(repr(str(self)))

    def __str__(self):
        parts = []

        # Epoch
        if self._version.epoch != 0:
            parts.append("{0}!".format(self._version.epoch))

        # Release segment
        parts.append(".".join(str(x) for x in self._version.release))

        # Pre-release
        if self._version.pre is not None:
            parts.append("".join(str(x) for x in self._version.pre))

        # Post-release
        if self._version.post is not None:
            parts.append(".post{0}".format(self._version.post[1]))

        # Development release
        if self._version.dev is not None:
            parts.append(".dev{0}".format(self._version.dev[1]))

        # Local version segment
        if self._version.local is not None:
            parts.append(
                "+{0}".format(".".join(str(x) for x in self._version.local))
            )

        return "".join(parts)

    @property
    def public(self):
        return str(self).split("+", 1)[0]

    @property
    def base_version(self):
        parts = []

        # Epoch
        if self._version.epoch != 0:
            parts.append("{0}!".format(self._version.epoch))

        # Release segment
        parts.append(".".join(str(x) for x in self._version.release))

        return "".join(parts)

    @property
    def local(self):
        version_string = str(self)
        if "+" in version_string:
            return version_string.split("+", 1)[1]

    @property
    def is_prerelease(self):
        return bool(self._version.dev or self._version.pre)

    @property
    def is_postrelease(self):
        return bool(self._version.post)


def _parse_letter_version(letter, number):
    if letter:
        # We consider there to be an implicit 0 in a pre-release if there is
        # not a numeral associated with it.
        if number is None:
            number = 0

        # We normalize any letters to their lower case form
        letter = letter.lower()

        # We consider some words to be alternate spellings of other words and
        # in those cases we want to normalize the spellings to our preferred
        # spelling.
        if letter == "alpha":
            letter = "a"
        elif letter == "beta":
            letter = "b"
        elif letter in ["c", "pre", "preview"]:
            letter = "rc"
        elif letter in ["rev", "r"]:
            letter = "post"

        return letter, int(number)
    if not letter and number:
        # We assume if we are given a number, but we are not given a letter
        # then this is using the implicit post release syntax (e.g. 1.0-1)
        letter = "post"

        return letter, int(number)


_local_version_seperators = re.compile(r"[\._-]")


def _parse_local_version(local):
    """
    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
    """
    if local is not None:
        return tuple(
            part.lower() if not part.isdigit() else int(part)
            for part in _local_version_seperators.split(local)
        )


def _cmpkey(epoch, release, pre, post, dev, local):
    # When we compare a release version, we want to compare it with all of the
    # trailing zeros removed. So we'll use a reverse the list, drop all the now
    # leading zeros until we come to something non zero, then take the rest
    # re-reverse it back into the correct order and make it a tuple and use
    # that for our sorting key.
    release = tuple(
        reversed(list(
            itertools.dropwhile(
                lambda x: x == 0,
                reversed(release),
            )
        ))
    )

    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
    # We'll do this by abusing the pre segment, but we _only_ want to do this
    # if there is not a pre or a post segment. If we have one of those then
    # the normal sorting rules will handle this case correctly.
    if pre is None and post is None and dev is not None:
        pre = -Infinity
    # Versions without a pre-release (except as noted above) should sort after
    # those with one.
    elif pre is None:
        pre = Infinity

    # Versions without a post segment should sort before those with one.
    if post is None:
        post = -Infinity

    # Versions without a development segment should sort after those with one.
    if dev is None:
        dev = Infinity

    if local is None:
        # Versions without a local segment should sort before those with one.
        local = -Infinity
    else:
        # Versions with a local segment need that segment parsed to implement
        # the sorting rules in PEP440.
        # - Alpha numeric segments sort before numeric segments
        # - Alpha numeric segments sort lexicographically
        # - Numeric segments sort numerically
        # - Shorter versions sort before longer versions when the prefixes
        #   match exactly
        local = tuple(
            (i, "") if isinstance(i, int) else (-Infinity, i)
            for i in local
        )

    return epoch, release, pre, post, dev, local
_vendor/packaging/markers.pyo000064400000026462152527136320012341 0ustar00
abc@`suddlmZmZmZddlZddlZddlZddlZddlm	Z	m
Z
mZmZddlm
Z
mZmZmZddlmZddlmZddlmZmZd	d
ddd
gZd	efdYZd
efdYZdefdYZdefdYZdefdYZdefdYZ defdYZ!ededBedBedBedBedBedBed Bed!Bed"Bed#Bed$Bed%Bed&Bed'Bed(Bed)Bed*BZ"id#d$6d"d%6dd&6dd'6dd(6dd)6Z#e"j$d+ed,ed-Bed.Bed/Bed0Bed1Bed2Bed3BZ%e%ed4Bed5BZ&e&j$d6ed7ed8BZ'e'j$d9ed:ed;BZ(e"e'BZ)ee)e&e)Z*e*j$d<ed=j+Z,ed>j+Z-eZ.e*ee,e.e-BZ/e.e/e
e(e.>ee.eZ0d?Z1e2d@Z3idAd56dBd46ej4d36ej5d/6ej6d-6ej7d06ej8d.6ej9d26Z:dCZ;eZ<dDZ=dEZ>dFZ?dGZ@defdHYZAdS(Ii(tabsolute_importtdivisiontprint_functionN(tParseExceptiontParseResultststringStartt	stringEnd(t
ZeroOrMoretGrouptForwardtQuotedString(tLiterali(tstring_types(t	SpecifiertInvalidSpecifiert
InvalidMarkertUndefinedComparisontUndefinedEnvironmentNametMarkertdefault_environmentcB`seZdZRS(sE
    An invalid marker was found, users should refer to PEP 508.
    (t__name__t
__module__t__doc__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscB`seZdZRS(sP
    An invalid operation was attempted on a value that doesn't support it.
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!scB`seZdZRS(s\
    A name was attempted to be used that does not exist inside of the
    environment.
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR'stNodecB`s,eZdZdZdZdZRS(cC`s
||_dS(N(tvalue(tselfR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt__init__0scC`s
t|jS(N(tstrR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt__str__3scC`sdj|jjt|S(Ns<{0}({1!r})>(tformatt	__class__RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt__repr__6scC`s
tdS(N(tNotImplementedError(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt	serialize9s(RRRRRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR.s			tVariablecB`seZdZRS(cC`s
t|S(N(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!?s(RRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR"=stValuecB`seZdZRS(cC`s
dj|S(Ns"{0}"(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!Es(RRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR#CstOpcB`seZdZRS(cC`s
t|S(N(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!Ks(RRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR$Istimplementation_versiontplatform_python_implementationtimplementation_nametpython_full_versiontplatform_releasetplatform_versiontplatform_machinetplatform_systemtpython_versiontsys_platformtos_namesos.namessys.platformsplatform.versionsplatform.machinesplatform.python_implementationtpython_implementationtextracC`sttj|d|dS(Ni(R"tALIASEStget(tstltt((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pytkts===s==s>=s<=s!=s~=t>tst RARB(RCtlisttlenR@RHtjoinR!(tmarkerRGtinnerRK((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRHs!
&cC`s
||kS(N((tlhstrhs((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR7R8cC`s
||kS(N((RRRS((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR7R8cC`sy%tdj|j|g}Wntk
r8nX|j|Stj|j}|dkrtdj	|||n|||S(NR8s#Undefined {0!r} on {1!r} and {2!r}.(
R
ROR!Rtcontainst
_operatorsR3tNoneRR(RRtopRStspectoper((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt_eval_ops%

cC`s:|j|t}|tkr6tdj|n|S(Ns/{0!r} does not exist in evaluation environment.(R3t
_undefinedRR(tenvironmenttnameR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt_get_envs
c	C`sgg}x|D]}t|trB|djt||qt|tr|\}}}t|trt||j}|j}n|j}t||j}|djt|||q|dkr|jgqqWt	d|DS(NiR?cs`s|]}t|VqdS(N(tall(RJtitem((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pys	s(
RCRMtappendt_evaluate_markersR@R"R^RRZtany(	tmarkersR\tgroupsRPRRRWRSt	lhs_valuet	rhs_value((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRbs	
	 cC`sFdj|}|j}|dkrB||dt|j7}n|S(Ns{0.major}.{0.minor}.{0.micro}tfinali(RtreleaselevelRtserial(tinfotversiontkind((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pytformat_full_versions
	cC`sttdr0ttjj}tjj}nd}d}i|d6|d6tjd6tjd6tj	d6tj
d	6tjd
6tjd6tjd6tjd
 d6tjd6S(Ntimplementationt0R8R'R%R/R+R)R,R*R(R&iR-R.(
thasattrtsysRnRoRlR]tostplatformtmachinetreleasetsystemR-R0(tiverR'((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRs"






cB`s/eZdZdZdZddZRS(cC`seyttj||_WnBtk
r`}dj|||j|jd!}t|nXdS(Ns+Invalid marker: {0!r}, parse error at {1!r}i(RDtMARKERtparseStringt_markersRRtlocR(RRPteterr_str((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscC`s
t|jS(N(RHR{(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscC`sdjt|S(Ns(RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscC`s5t}|dk	r%|j|nt|j|S(s$Evaluate a marker.

        Return the boolean from evaluating the given marker against the
        environment. environment is an optional argument to override all or
        part of the determined environment.

        The environment is determined from the current Python process.
        N(RRVtupdateRbR{(RR\tcurrent_environment((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pytevaluate"s		N(RRRRRRVR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRs			(Bt
__future__RRRtoperatorRsRtRrtpip._vendor.pyparsingRRRRRRR	R
RtLt_compatRt
specifiersR
Rt__all__t
ValueErrorRRRtobjectRR"R#R$tVARIABLER2tsetParseActiontVERSION_CMPt	MARKER_OPtMARKER_VALUEtBOOLOPt
MARKER_VARtMARKER_ITEMtsuppresstLPARENtRPARENtMARKER_EXPRtMARKER_ATOMRyRDtTrueRHtlttleteqtnetgetgtRURZR[R^RbRnRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyts|""	

	E

		







						_vendor/packaging/_compat.py000064400000001534152527136320012131 0ustar00# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function

import sys


PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3

# flake8: noqa

if PY3:
    string_types = str,
else:
    string_types = basestring,


def with_metaclass(meta, *bases):
    """
    Create a base class with a metaclass.
    """
    # This requires a bit of explanation: the basic idea is to make a dummy
    # metaclass for one level of class instantiation that replaces itself with
    # the actual metaclass.
    class metaclass(meta):
        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)
    return type.__new__(metaclass, 'temporary_class', (), {})
_vendor/packaging/_structures.pyc000064400000007672152527136320013245 0ustar00
abc@`s^ddlmZmZmZdefdYZeZdefdYZeZdS(i(tabsolute_importtdivisiontprint_functiontInfinitycB`sYeZdZdZdZdZdZdZdZdZ	dZ
RS(	cC`sdS(NR((tself((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__repr__	scC`stt|S(N(thashtrepr(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__hash__scC`stS(N(tFalse(Rtother((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__lt__scC`stS(N(R	(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__le__scC`st||jS(N(t
isinstancet	__class__(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__eq__scC`st||jS(N(R
R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__ne__scC`stS(N(tTrue(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__gt__scC`stS(N(R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__ge__scC`stS(N(tNegativeInfinity(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__neg__!s(t__name__t
__module__RRRRRRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyRs								RcB`sYeZdZdZdZdZdZdZdZdZ	dZ
RS(	cC`sdS(Ns	-Infinity((R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR)scC`stt|S(N(RR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR,scC`stS(N(R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR/scC`stS(N(R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR2scC`st||jS(N(R
R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR5scC`st||jS(N(R
R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR8scC`stS(N(R	(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR;scC`stS(N(R	(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR>scC`stS(N(R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyRAs(RRRRRRRRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR's								N(t
__future__RRRtobjectRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyts	_vendor/packaging/__init__.pyc000064400000001134152527136320012405 0ustar00
abc@`sxddlmZmZmZddlmZmZmZmZm	Z	m
Z
mZmZdddddd	d
dgZ
dS(
i(tabsolute_importtdivisiontprint_functioni(t
__author__t
__copyright__t	__email__t__license__t__summary__t	__title__t__uri__t__version__RRR	R
RRRRN(t
__future__RRRt	__about__RRRRRRR	R
t__all__(((sB/usr/lib/python2.7/site-packages/pip/_vendor/packaging/__init__.pyts:_vendor/packaging/utils.pyo000064400000001104152527136320012017 0ustar00
abc@`sDddlmZmZmZddlZejdZdZdS(i(tabsolute_importtdivisiontprint_functionNs[-_.]+cC`stjd|jS(Nt-(t_canonicalize_regextsubtlower(tname((s?/usr/lib/python2.7/site-packages/pip/_vendor/packaging/utils.pytcanonicalize_names(t
__future__RRRtretcompileRR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/packaging/utils.pyts_vendor/packaging/version.pyo000064400000033423152527136320012355 0ustar00
abc@`snddlmZmZmZddlZddlZddlZddlmZddddd	gZ	ej
d
ddd
dddgZdZde
fdYZdefdYZdefdYZejdejZidd6dd6dd6dd6dd
6ZdZdZdZdefd YZd!Zejd"Zd#Zd$ZdS(%i(tabsolute_importtdivisiontprint_functionNi(tInfinitytparsetVersiont
LegacyVersiontInvalidVersiontVERSION_PATTERNt_VersiontepochtreleasetdevtpretposttlocalcC`s-yt|SWntk
r(t|SXdS(s
    Parse the given version string and return either a :class:`Version` object
    or a :class:`LegacyVersion` object depending on if the given version is
    a valid PEP 440 version or a legacy version.
    N(RRR(tversion((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRs
cB`seZdZRS(sF
    An invalid version was found, users should refer to PEP 440.
    (t__name__t
__module__t__doc__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR$st_BaseVersioncB`sPeZdZdZdZdZdZdZdZdZ	RS(cC`s
t|jS(N(thasht_key(tself((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__hash__,scC`s|j|dS(NcS`s
||kS(N((tsto((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt0t(t_compare(Rtother((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__lt__/scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR3R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__le__2scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR6R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__eq__5scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR9R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__ge__8scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR<R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__gt__;scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR?R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__ne__>scC`s&t|tstS||j|jS(N(t
isinstanceRtNotImplementedR(RRtmethod((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRAs(
RRRRR R!R"R#R$R(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR*s							cB`sneZdZdZdZedZedZedZedZ	edZ
RS(cC`s%t||_t|j|_dS(N(tstrt_versiont_legacy_cmpkeyR(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__init__JscC`s|jS(N(R)(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__str__NscC`sdjtt|S(Ns(tformattreprR((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__repr__QscC`s|jS(N(R)(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pytpublicTscC`s|jS(N(R)(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pytbase_versionXscC`sdS(N(tNone(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR\scC`stS(N(tFalse(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt
is_prerelease`scC`stS(N(R3(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pytis_postreleaseds(RRR+R,R/tpropertyR0R1RR4R5(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRHs			s(\d+ | [a-z]+ | \.| -)tctpreviewsfinal-t-trct@cc`sxxltj|D][}tj||}|s|dkrAqn|d dkrb|jdVqd|VqWdVdS(Nt.it
0123456789it*s*final(t_legacy_version_component_retsplitt_legacy_version_replacement_maptgettzfill(Rtpart((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt_parse_version_partsrs
cC`sd}g}xt|jD]}|jdr|dkrjx'|rf|ddkrf|jqCWnx'|r|ddkr|jqmWn|j|qWt|}||fS(NiR>s*finals*final-t00000000(REtlowert
startswithtpoptappendttuple(RR
tpartsRD((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR*ss
    v?
    (?:
        (?:(?P[0-9]+)!)?                           # epoch
        (?P[0-9]+(?:\.[0-9]+)*)                  # release segment
        (?P
                                          # pre-release
            [-_\.]?
            (?P(a|b|c|rc|alpha|beta|pre|preview))
            [-_\.]?
            (?P[0-9]+)?
        )?
        (?P                                         # post release
            (?:-(?P[0-9]+))
            |
            (?:
                [-_\.]?
                (?Ppost|rev|r)
                [-_\.]?
                (?P[0-9]+)?
            )
        )?
        (?P                                          # dev release
            [-_\.]?
            (?Pdev)
            [-_\.]?
            (?P[0-9]+)?
        )?
    )
    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
cB`seZejdedejejBZdZdZ	dZ
edZedZ
edZedZed	ZRS(
s^\s*s\s*$cC`s[|jj|}|s0tdj|ntd|jdrZt|jdnddtd|jdjdDdt	|jd|jd	d
t	|jd|jdp|jd
dt	|jd|jddt
|jd|_t|jj
|jj|jj|jj|jj|jj|_dS(NsInvalid version: '{0}'R
iRcs`s|]}t|VqdS(N(tint(t.0ti((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	sR<R
tpre_ltpre_nRtpost_ltpost_n1tpost_n2Rtdev_ltdev_nR(t_regextsearchRR-R	tgroupRMRKR@t_parse_letter_versiont_parse_local_versionR)t_cmpkeyR
RR
RRRR(RRtmatch((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR+s.*(!					cC`sdjtt|S(Ns(R-R.R((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR/scC`sSg}|jjdkr7|jdj|jjn|jdjd|jjD|jjdk	r|jdjd|jjDn|jjdk	r|jdj|jjdn|jj	dk	r|jd	j|jj	dn|jj
dk	rF|jd
jdjd|jj
Dndj|S(Nis{0}!R<cs`s|]}t|VqdS(N(R((RNtx((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	sRcs`s|]}t|VqdS(N(R((RNR^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	ss.post{0}is.dev{0}s+{0}cs`s|]}t|VqdS(N(R((RNR^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	s(R)R
RJR-tjoinRR
R2RRR(RRL((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR,s&)##,cC`st|jdddS(Nt+ii(R(R@(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR0
scC`sjg}|jjdkr7|jdj|jjn|jdjd|jjDdj|S(Nis{0}!R<cs`s|]}t|VqdS(N(R((RNR^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	sR(R)R
RJR-R_R(RRL((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR1s
&cC`s0t|}d|kr,|jdddSdS(NR`i(R(R@(Rtversion_string((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRscC`st|jjp|jjS(N(tboolR)RR
(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR4!scC`st|jjS(N(RbR)R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR5%s(RRtretcompileRtVERBOSEt
IGNORECASERWR+R/R,R6R0R1RR4R5(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRs	#		
cC`s|r|dkrd}n|j}|dkr<d}n?|dkrQd}n*|d
krfd	}n|dkr{d}n|t|fS|r|rd}|t|fSdS(NitalphatatbetatbR7R
R8R:trevtrR(R7R
R8(RkRl(R2RGRM(tlettertnumber((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRZ*s 					
s[\._-]cC`s-|dk	r)tdtj|DSdS(sR
    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
    cs`s3|])}|js!|jn	t|VqdS(N(tisdigitRGRM(RNRD((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	RsN(R2RKt_local_version_seperatorsR@(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR[LscC`sttttjdt|}|dkr[|dkr[|dk	r[t}n|dkrpt}n|dkrt}n|dkrt}n|dkrt}ntd|D}||||||fS(NcS`s
|dkS(Ni((R^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR`Rcs`s7|]-}t|tr$|dfn
t|fVqdS(RN(R%RMR(RNRO((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	s(RKtreversedtlistt	itertoolst	dropwhileR2R(R
RR
RRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR\Ws&	$
	
	
	
(t
__future__RRRtcollectionsRsRct_structuresRt__all__t
namedtupleR	Rt
ValueErrorRtobjectRRRdReR?RARER*RRRZRpR[R\(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyts0	!&		9k		_vendor/packaging/markers.py000064400000020046152527136320012152 0ustar00# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function

import operator
import os
import platform
import sys

from pip._vendor.pyparsing import (
    ParseException, ParseResults, stringStart, stringEnd,
)
from pip._vendor.pyparsing import ZeroOrMore, Group, Forward, QuotedString
from pip._vendor.pyparsing import Literal as L  # noqa

from ._compat import string_types
from .specifiers import Specifier, InvalidSpecifier


__all__ = [
    "InvalidMarker", "UndefinedComparison", "UndefinedEnvironmentName",
    "Marker", "default_environment",
]


class InvalidMarker(ValueError):
    """
    An invalid marker was found, users should refer to PEP 508.
    """


class UndefinedComparison(ValueError):
    """
    An invalid operation was attempted on a value that doesn't support it.
    """


class UndefinedEnvironmentName(ValueError):
    """
    A name was attempted to be used that does not exist inside of the
    environment.
    """


class Node(object):

    def __init__(self, value):
        self.value = value

    def __str__(self):
        return str(self.value)

    def __repr__(self):
        return "<{0}({1!r})>".format(self.__class__.__name__, str(self))

    def serialize(self):
        raise NotImplementedError


class Variable(Node):

    def serialize(self):
        return str(self)


class Value(Node):

    def serialize(self):
        return '"{0}"'.format(self)


class Op(Node):

    def serialize(self):
        return str(self)


VARIABLE = (
    L("implementation_version") |
    L("platform_python_implementation") |
    L("implementation_name") |
    L("python_full_version") |
    L("platform_release") |
    L("platform_version") |
    L("platform_machine") |
    L("platform_system") |
    L("python_version") |
    L("sys_platform") |
    L("os_name") |
    L("os.name") |  # PEP-345
    L("sys.platform") |  # PEP-345
    L("platform.version") |  # PEP-345
    L("platform.machine") |  # PEP-345
    L("platform.python_implementation") |  # PEP-345
    L("python_implementation") |  # undocumented setuptools legacy
    L("extra")
)
ALIASES = {
    'os.name': 'os_name',
    'sys.platform': 'sys_platform',
    'platform.version': 'platform_version',
    'platform.machine': 'platform_machine',
    'platform.python_implementation': 'platform_python_implementation',
    'python_implementation': 'platform_python_implementation'
}
VARIABLE.setParseAction(lambda s, l, t: Variable(ALIASES.get(t[0], t[0])))

VERSION_CMP = (
    L("===") |
    L("==") |
    L(">=") |
    L("<=") |
    L("!=") |
    L("~=") |
    L(">") |
    L("<")
)

MARKER_OP = VERSION_CMP | L("not in") | L("in")
MARKER_OP.setParseAction(lambda s, l, t: Op(t[0]))

MARKER_VALUE = QuotedString("'") | QuotedString('"')
MARKER_VALUE.setParseAction(lambda s, l, t: Value(t[0]))

BOOLOP = L("and") | L("or")

MARKER_VAR = VARIABLE | MARKER_VALUE

MARKER_ITEM = Group(MARKER_VAR + MARKER_OP + MARKER_VAR)
MARKER_ITEM.setParseAction(lambda s, l, t: tuple(t[0]))

LPAREN = L("(").suppress()
RPAREN = L(")").suppress()

MARKER_EXPR = Forward()
MARKER_ATOM = MARKER_ITEM | Group(LPAREN + MARKER_EXPR + RPAREN)
MARKER_EXPR << MARKER_ATOM + ZeroOrMore(BOOLOP + MARKER_EXPR)

MARKER = stringStart + MARKER_EXPR + stringEnd


def _coerce_parse_result(results):
    if isinstance(results, ParseResults):
        return [_coerce_parse_result(i) for i in results]
    else:
        return results


def _format_marker(marker, first=True):
    assert isinstance(marker, (list, tuple, string_types))

    # Sometimes we have a structure like [[...]] which is a single item list
    # where the single item is itself it's own list. In that case we want skip
    # the rest of this function so that we don't get extraneous () on the
    # outside.
    if (isinstance(marker, list) and len(marker) == 1 and
            isinstance(marker[0], (list, tuple))):
        return _format_marker(marker[0])

    if isinstance(marker, list):
        inner = (_format_marker(m, first=False) for m in marker)
        if first:
            return " ".join(inner)
        else:
            return "(" + " ".join(inner) + ")"
    elif isinstance(marker, tuple):
        return " ".join([m.serialize() for m in marker])
    else:
        return marker


_operators = {
    "in": lambda lhs, rhs: lhs in rhs,
    "not in": lambda lhs, rhs: lhs not in rhs,
    "<": operator.lt,
    "<=": operator.le,
    "==": operator.eq,
    "!=": operator.ne,
    ">=": operator.ge,
    ">": operator.gt,
}


def _eval_op(lhs, op, rhs):
    try:
        spec = Specifier("".join([op.serialize(), rhs]))
    except InvalidSpecifier:
        pass
    else:
        return spec.contains(lhs)

    oper = _operators.get(op.serialize())
    if oper is None:
        raise UndefinedComparison(
            "Undefined {0!r} on {1!r} and {2!r}.".format(op, lhs, rhs)
        )

    return oper(lhs, rhs)


_undefined = object()


def _get_env(environment, name):
    value = environment.get(name, _undefined)

    if value is _undefined:
        raise UndefinedEnvironmentName(
            "{0!r} does not exist in evaluation environment.".format(name)
        )

    return value


def _evaluate_markers(markers, environment):
    groups = [[]]

    for marker in markers:
        assert isinstance(marker, (list, tuple, string_types))

        if isinstance(marker, list):
            groups[-1].append(_evaluate_markers(marker, environment))
        elif isinstance(marker, tuple):
            lhs, op, rhs = marker

            if isinstance(lhs, Variable):
                lhs_value = _get_env(environment, lhs.value)
                rhs_value = rhs.value
            else:
                lhs_value = lhs.value
                rhs_value = _get_env(environment, rhs.value)

            groups[-1].append(_eval_op(lhs_value, op, rhs_value))
        else:
            assert marker in ["and", "or"]
            if marker == "or":
                groups.append([])

    return any(all(item) for item in groups)


def format_full_version(info):
    version = '{0.major}.{0.minor}.{0.micro}'.format(info)
    kind = info.releaselevel
    if kind != 'final':
        version += kind[0] + str(info.serial)
    return version


def default_environment():
    if hasattr(sys, 'implementation'):
        iver = format_full_version(sys.implementation.version)
        implementation_name = sys.implementation.name
    else:
        iver = '0'
        implementation_name = ''

    return {
        "implementation_name": implementation_name,
        "implementation_version": iver,
        "os_name": os.name,
        "platform_machine": platform.machine(),
        "platform_release": platform.release(),
        "platform_system": platform.system(),
        "platform_version": platform.version(),
        "python_full_version": platform.python_version(),
        "platform_python_implementation": platform.python_implementation(),
        "python_version": platform.python_version()[:3],
        "sys_platform": sys.platform,
    }


class Marker(object):

    def __init__(self, marker):
        try:
            self._markers = _coerce_parse_result(MARKER.parseString(marker))
        except ParseException as e:
            err_str = "Invalid marker: {0!r}, parse error at {1!r}".format(
                marker, marker[e.loc:e.loc + 8])
            raise InvalidMarker(err_str)

    def __str__(self):
        return _format_marker(self._markers)

    def __repr__(self):
        return "".format(str(self))

    def evaluate(self, environment=None):
        """Evaluate a marker.

        Return the boolean from evaluating the given marker against the
        environment. environment is an optional argument to override all or
        part of the determined environment.

        The environment is determined from the current Python process.
        """
        current_environment = default_environment()
        if environment is not None:
            current_environment.update(environment)

        return _evaluate_markers(self._markers, current_environment)
_vendor/packaging/specifiers.pyc000064400000060376152527136320013017 0ustar00
abc@`s<ddlmZmZmZddlZddlZddlZddlZddlm	Z	m
Z
ddlmZm
Z
mZdefdYZde
ejefd	YZd
efdYZdefd
YZdZdefdYZejdZdZdZdefdYZdS(i(tabsolute_importtdivisiontprint_functionNi(tstring_typestwith_metaclass(tVersiont
LegacyVersiontparsetInvalidSpecifiercB`seZdZRS(sH
    An invalid specifier was found, users should refer to PEP 440.
    (t__name__t
__module__t__doc__(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRst
BaseSpecifiercB`seZejdZejdZejdZejdZejdZ	e	j
dZ	ejddZejddZ
RS(	cC`sdS(s
        Returns the str representation of this Specifier like object. This
        should be representative of the Specifier itself.
        N((tself((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__str__tcC`sdS(sF
        Returns a hash value for this Specifier like object.
        N((R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__hash__RcC`sdS(sq
        Returns a boolean representing whether or not the two Specifier like
        objects are equal.
        N((R
tother((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__eq__$RcC`sdS(su
        Returns a boolean representing whether or not the two Specifier like
        objects are not equal.
        N((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__ne__+RcC`sdS(sg
        Returns whether or not pre-releases as a whole are allowed by this
        specifier.
        N((R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytprereleases2RcC`sdS(sd
        Sets whether or not pre-releases as a whole are allowed by this
        specifier.
        N((R
tvalue((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR9RcC`sdS(sR
        Determines if the given item is contained within this specifier.
        N((R
titemR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytcontains@RcC`sdS(s
        Takes an iterable of items and filters them so that only items which
        are contained within this specifier are allowed in it.
        N((R
titerableR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytfilterFRN(R	R
tabctabstractmethodRRRRtabstractpropertyRtsettertNoneRR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRst_IndividualSpecifiercB`seZiZdddZdZdZdZdZdZ	dZ
dZed	Z
ed
ZedZejdZd
ZddZddZRS(RcC`sj|jj|}|s0tdj|n|jdj|jdjf|_||_dS(NsInvalid specifier: '{0}'toperatortversion(t_regextsearchRtformattgrouptstript_spect_prereleases(R
tspecRtmatch((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__init__RscC`sF|jdk	r!dj|jnd}dj|jjt||S(Ns, prereleases={0!r}Rs<{0}({1!r}{2})>(R(RR$Rt	__class__R	tstr(R
tpre((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__repr___s!		cC`sdj|jS(Ns{0}{1}(R$R'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRlscC`s
t|jS(N(thashR'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRoscC`s`t|tr:y|j|}WqPtk
r6tSXnt||jsPtS|j|jkS(N(t
isinstanceRR,RtNotImplementedR'(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRrs
cC`s`t|tr:y|j|}WqPtk
r6tSXnt||jsPtS|j|jkS(N(R1RR,RR2R'(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR}s
cC`st|dj|j|S(Ns_compare_{0}(tgetattrR$t
_operators(R
top((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt
_get_operatorscC`s(t|ttfs$t|}n|S(N(R1RRR(R
R!((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_coerce_versionscC`s|jdS(Ni(R'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR scC`s|jdS(Ni(R'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR!scC`s|jS(N(R((R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
||_dS(N(R((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
|j|S(N(R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__contains__scC`sW|dkr|j}n|j|}|jr;|r;tS|j|j||jS(N(RRR7t
is_prereleasetFalseR6R R!(R
RR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscc`st}g}i|dk	r!|ntd6}xf|D]^}|j|}|j||r2|jr|pn|jr|j|qt}|Vq2q2W|r|rx|D]}|VqWndS(NR(R:RtTrueR7RR9Rtappend(R
RRtyieldedtfound_prereleasestkwR!tparsed_version((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs
	

N(R	R
R4RR+R/RRRRR6R7tpropertyR R!RRR8RR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRNs 
	
							tLegacySpecifiercB`seZdZejdedejejBZidd6dd6dd6d	d
6dd6d
d6ZdZ	dZ
dZdZdZ
dZdZRS(s
        (?P(==|!=|<=|>=|<|>))
        \s*
        (?P
            [^,;\s)]* # Since this is a "legacy" specifier, and the version
                      # string can be just about anything, we match everything
                      # except for whitespace, a semi-colon for marker support,
                      # a closing paren since versions can be enclosed in
                      # them, and a comma since it's a version separator.
        )
        s^\s*s\s*$tequals==t	not_equals!=tless_than_equals<=tgreater_than_equals>=t	less_thantcC`s(t|ts$tt|}n|S(N(R1RR-(R
R!((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR7scC`s||j|kS(N(R7(R
tprospectiveR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_not_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_less_than_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_greater_than_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_less_thanscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_greater_thans(R	R
t
_regex_strtretcompiletVERBOSEt
IGNORECASER"R4R7RLRMRNRORPRQ(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRBs"

						c`s"tjfd}|S(Nc`s#t|tstS|||S(N(R1RR:(R
RKR)(tfn(sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytwrappeds(t	functoolstwraps(RWRX((RWsD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_require_version_compare
st	SpecifiercB`seZdZejdedejejBZidd6dd6dd6d	d
6dd6d
d6dd6dd6Ze	dZ
e	dZe	dZe	dZ
e	dZe	dZe	dZdZedZejdZRS(s
        (?P(~=|==|!=|<=|>=|<|>|===))
        (?P
            (?:
                # The identity operators allow for an escape hatch that will
                # do an exact string match of the version you wish to install.
                # This will not be parsed by PEP 440 and we cannot determine
                # any semantic meaning from it. This operator is discouraged
                # but included entirely as an escape hatch.
                (?<====)  # Only match for the identity operator
                \s*
                [^\s]*    # We just match everything, except for whitespace
                          # since we are only testing for strict identity.
            )
            |
            (?:
                # The (non)equality operators allow for wild card and local
                # versions to be specified so we have to define these two
                # operators separately to enable that.
                (?<===|!=)            # Only match for equals and not equals

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)*   # release
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?

                # You cannot use a wild card and a dev or local version
                # together so group them with a | and make them optional.
                (?:
                    (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
                    (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
                    |
                    \.\*  # Wild card syntax of .*
                )?
            )
            |
            (?:
                # The compatible operator requires at least two digits in the
                # release segment.
                (?<=~=)               # Only match for the compatible operator

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?
                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
            )
            |
            (?:
                # All other operators only allow a sub set of what the
                # (non)equality operators do. Specifically they do not allow
                # local versions to be specified nor do they allow the prefix
                # matching wild cards.
                (?=RGRHRIRJt	arbitrarys===cC`sfdjttjdt|d }|d7}|jd||oe|jd||S(Nt.cS`s|jdo|jdS(Ntposttdev(t
startswith(tx((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytsis.*s>=s==(tjointlistt	itertoolst	takewhilet_version_splitR6(R
RKR)tprefix((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_compatibles

cC`s|jdrht|j}t|d }tt|}|t| }t||\}}n't|}|jst|j}n||kS(Ns.*i(tendswithRtpublicRiR-tlent_pad_versiontlocal(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRLs	cC`s|j||S(N(RL(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRMscC`s|t|kS(N(R(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRNscC`s|t|kS(N(R(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyROscC`sXt|}||kstS|jrT|jrTt|jt|jkrTtSntS(N(RR:R9tbase_versionR;(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRPscC`st|}||kstS|jrT|jrTt|jt|jkrTtSn|jdk	rt|jt|jkrtSntS(N(RR:tis_postreleaseRqRpRR;(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRQscC`s"t|jt|jkS(N(R-tlower(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_arbitraryscC`ss|jdk	r|jS|j\}}|dkro|dkrY|jdrY|d }nt|jrotSntS(	Ns==s>=s<=s~=s===s.*i(s==s>=s<=s~=s===(R(RR'RlRR9R;R:(R
R R!((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs
cC`s
||_dS(N(R((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs(R	R
RRRSRTRURVR"R4R[RkRLRMRNRORPRQRtRARR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR\s,^
#	s^([0-9]+)((?:a|b|c|rc)[0-9]+)$cC`s\g}xO|jdD]>}tj|}|rG|j|jq|j|qW|S(NR_(tsplitt
_prefix_regexR#textendtgroupsR<(R!tresultRR*((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRi'sc	C`sgg}}|jttjd||jttjd||j|t|d|j|t|d|jddgtdt|dt|d|jddgtdt|dt|dttj|ttj|fS(NcS`s
|jS(N(tisdigit(Rc((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRd6RcS`s
|jS(N(Rz(Rc((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRd7Riit0(R<RfRgRhRntinserttmaxtchain(tlefttrightt
left_splittright_split((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRo2s
""//tSpecifierSetcB`seZdddZdZdZdZdZdZdZ	dZ
d	Zed
Z
e
jdZ
dZdd
ZddZRS(RcC`sg|jdD]}|jr|j^q}t}xL|D]D}y|jt|WqDtk
r|jt|qDXqDWt||_||_	dS(Nt,(
RuR&tsettaddR\RRBt	frozensett_specsR((R
t
specifiersRtstparsedt	specifier((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR+Os4	

cC`s=|jdk	r!dj|jnd}djt||S(Ns, prereleases={0!r}Rs(R(RR$RR-(R
R.((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR/ds!cC`s djtd|jDS(NRcs`s|]}t|VqdS(N(R-(t.0R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pys	ns(RetsortedR(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRmscC`s
t|jS(N(R0R(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRpscC`st|trt|}nt|ts1tSt}t|j|jB|_|jdkr|jdk	r|j|_nZ|jdk	r|jdkr|j|_n-|j|jkr|j|_ntd|S(NsFCannot combine SpecifierSets with True and False prerelease overrides.(	R1RRR2RRR(Rt
ValueError(R
RR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__and__ss		cC`set|trt|}n7t|trBtt|}nt|tsUtS|j|jkS(N(R1RRRR-R2R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`set|trt|}n7t|trBtt|}nt|tsUtS|j|jkS(N(R1RRRR-R2R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
t|jS(N(RnR(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__len__scC`s
t|jS(N(titerR(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__iter__scC`s:|jdk	r|jS|js#dStd|jDS(Ncs`s|]}|jVqdS(N(R(RR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pys	s(R(RRtany(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs
	cC`s
||_dS(N(R((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
|j|S(N(R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR8sc`sptttfs$tndkr<|jnrPjrPtStfd|j	DS(Nc3`s$|]}|jdVqdS(RN(R(RR(RR(sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pys	s(
R1RRRRRR9R:tallR(R
RR((RRsD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s|dkr|j}n|jrTx,|jD]!}|j|dt|}q+W|Sg}g}x|D]{}t|ttfst|}n|}t|trqgn|j	r|r|s|j
|qqg|j
|qgW|r|r|dkr|S|SdS(NR(RRRRtboolR1RRRR9R<(R
RRR)tfilteredR>RR@((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs*	
N(R	R
RR+R/RRRRRRRRARRR8RR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRMs						
	
			(t
__future__RRRRRYRgRSt_compatRRR!RRRRRtABCMetatobjectRRRBR[R\RTRvRiRoR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyts""94				_vendor/packaging/__init__.pyo000064400000001134152527136320012421 0ustar00
abc@`sxddlmZmZmZddlmZmZmZmZm	Z	m
Z
mZmZdddddd	d
dgZ
dS(
i(tabsolute_importtdivisiontprint_functioni(t
__author__t
__copyright__t	__email__t__license__t__summary__t	__title__t__uri__t__version__RRR	R
RRRRN(t
__future__RRRt	__about__RRRRRRR	R
t__all__(((sB/usr/lib/python2.7/site-packages/pip/_vendor/packaging/__init__.pyts:_vendor/packaging/markers.pyc000064400000026674152527136320012332 0ustar00
abc@`suddlmZmZmZddlZddlZddlZddlZddlm	Z	m
Z
mZmZddlm
Z
mZmZmZddlmZddlmZddlmZmZd	d
ddd
gZd	efdYZd
efdYZdefdYZdefdYZdefdYZdefdYZ defdYZ!ededBedBedBedBedBedBed Bed!Bed"Bed#Bed$Bed%Bed&Bed'Bed(Bed)Bed*BZ"id#d$6d"d%6dd&6dd'6dd(6dd)6Z#e"j$d+ed,ed-Bed.Bed/Bed0Bed1Bed2Bed3BZ%e%ed4Bed5BZ&e&j$d6ed7ed8BZ'e'j$d9ed:ed;BZ(e"e'BZ)ee)e&e)Z*e*j$d<ed=j+Z,ed>j+Z-eZ.e*ee,e.e-BZ/e.e/e
e(e.>ee.eZ0d?Z1e2d@Z3idAd56dBd46ej4d36ej5d/6ej6d-6ej7d06ej8d.6ej9d26Z:dCZ;eZ<dDZ=dEZ>dFZ?dGZ@defdHYZAdS(Ii(tabsolute_importtdivisiontprint_functionN(tParseExceptiontParseResultststringStartt	stringEnd(t
ZeroOrMoretGrouptForwardtQuotedString(tLiterali(tstring_types(t	SpecifiertInvalidSpecifiert
InvalidMarkertUndefinedComparisontUndefinedEnvironmentNametMarkertdefault_environmentcB`seZdZRS(sE
    An invalid marker was found, users should refer to PEP 508.
    (t__name__t
__module__t__doc__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscB`seZdZRS(sP
    An invalid operation was attempted on a value that doesn't support it.
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!scB`seZdZRS(s\
    A name was attempted to be used that does not exist inside of the
    environment.
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR'stNodecB`s,eZdZdZdZdZRS(cC`s
||_dS(N(tvalue(tselfR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt__init__0scC`s
t|jS(N(tstrR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt__str__3scC`sdj|jjt|S(Ns<{0}({1!r})>(tformatt	__class__RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt__repr__6scC`s
tdS(N(tNotImplementedError(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt	serialize9s(RRRRRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR.s			tVariablecB`seZdZRS(cC`s
t|S(N(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!?s(RRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR"=stValuecB`seZdZRS(cC`s
dj|S(Ns"{0}"(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!Es(RRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR#CstOpcB`seZdZRS(cC`s
t|S(N(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR!Ks(RRR!(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR$Istimplementation_versiontplatform_python_implementationtimplementation_nametpython_full_versiontplatform_releasetplatform_versiontplatform_machinetplatform_systemtpython_versiontsys_platformtos_namesos.namessys.platformsplatform.versionsplatform.machinesplatform.python_implementationtpython_implementationtextracC`sttj|d|dS(Ni(R"tALIASEStget(tstltt((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pytkts===s==s>=s<=s!=s~=t>tst RARB(	RCtlistR@RtAssertionErrortlenRHtjoinR!(tmarkerRGtinnerRK((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRHs!
&cC`s
||kS(N((tlhstrhs((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR7R8cC`s
||kS(N((RSRT((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyR7R8cC`sy%tdj|j|g}Wntk
r8nX|j|Stj|j}|dkrtdj	|||n|||S(NR8s#Undefined {0!r} on {1!r} and {2!r}.(
R
RPR!Rtcontainst
_operatorsR3tNoneRR(RStopRTtspectoper((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt_eval_ops%

cC`s:|j|t}|tkr6tdj|n|S(Ns/{0!r} does not exist in evaluation environment.(R3t
_undefinedRR(tenvironmenttnameR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyt_get_envs
c	C`s,gg}x|D]}t|tttfs4tt|tr`|djt||qt|tr|\}}}t|trt||j	}|j	}n|j	}t||j	}|djt
|||q|dkst|dkr|jgqqWtd|DS(NiR>R?cs`s|]}t|VqdS(N(tall(RJtitem((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pys	s(R>R?(RCRMR@RRNtappendt_evaluate_markersR"R_RR[tany(	tmarkersR]tgroupsRQRSRXRTt	lhs_valuet	rhs_value((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRcs"	
	 cC`sFdj|}|j}|dkrB||dt|j7}n|S(Ns{0.major}.{0.minor}.{0.micro}tfinali(RtreleaselevelRtserial(tinfotversiontkind((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pytformat_full_versions
	cC`sttdr0ttjj}tjj}nd}d}i|d6|d6tjd6tjd6tj	d6tj
d	6tjd
6tjd6tjd6tjd
 d6tjd6S(Ntimplementationt0R8R'R%R/R+R)R,R*R(R&iR-R.(
thasattrtsysRoRpRmR^tostplatformtmachinetreleasetsystemR-R0(tiverR'((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRs"






cB`s/eZdZdZdZddZRS(cC`seyttj||_WnBtk
r`}dj|||j|jd!}t|nXdS(Ns+Invalid marker: {0!r}, parse error at {1!r}i(RDtMARKERtparseStringt_markersRRtlocR(RRQteterr_str((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscC`s
t|jS(N(RHR|(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscC`sdjt|S(Ns(RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRscC`s5t}|dk	r%|j|nt|j|S(s$Evaluate a marker.

        Return the boolean from evaluating the given marker against the
        environment. environment is an optional argument to override all or
        part of the determined environment.

        The environment is determined from the current Python process.
        N(RRWtupdateRcR|(RR]tcurrent_environment((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pytevaluate"s		N(RRRRRRWR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyRs			(Bt
__future__RRRtoperatorRtRuRstpip._vendor.pyparsingRRRRRRR	R
RtLt_compatRt
specifiersR
Rt__all__t
ValueErrorRRRtobjectRR"R#R$tVARIABLER2tsetParseActiontVERSION_CMPt	MARKER_OPtMARKER_VALUEtBOOLOPt
MARKER_VARtMARKER_ITEMtsuppresstLPARENtRPARENtMARKER_EXPRtMARKER_ATOMRzRDtTrueRHtlttleteqtnetgetgtRVR[R\R_RcRoRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/markers.pyts|""	

	E

		







						_vendor/packaging/utils.py000064400000000645152527136320011651 0ustar00# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function

import re


_canonicalize_regex = re.compile(r"[-_.]+")


def canonicalize_name(name):
    # This is taken from PEP 503.
    return _canonicalize_regex.sub("-", name).lower()
_vendor/packaging/__about__.py000064400000001320152527136320012406 0ustar00# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function

__all__ = [
    "__title__", "__summary__", "__uri__", "__version__", "__author__",
    "__email__", "__license__", "__copyright__",
]

__title__ = "packaging"
__summary__ = "Core utilities for Python packages"
__uri__ = "https://github.com/pypa/packaging"

__version__ = "16.8"

__author__ = "Donald Stufft and individual contributors"
__email__ = "donald@stufft.io"

__license__ = "BSD or Apache License, Version 2.0"
__copyright__ = "Copyright 2014-2016 %s" % __author__
_vendor/packaging/specifiers.pyo000064400000060376152527136320013033 0ustar00
abc@`s<ddlmZmZmZddlZddlZddlZddlZddlm	Z	m
Z
ddlmZm
Z
mZdefdYZde
ejefd	YZd
efdYZdefd
YZdZdefdYZejdZdZdZdefdYZdS(i(tabsolute_importtdivisiontprint_functionNi(tstring_typestwith_metaclass(tVersiont
LegacyVersiontparsetInvalidSpecifiercB`seZdZRS(sH
    An invalid specifier was found, users should refer to PEP 440.
    (t__name__t
__module__t__doc__(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRst
BaseSpecifiercB`seZejdZejdZejdZejdZejdZ	e	j
dZ	ejddZejddZ
RS(	cC`sdS(s
        Returns the str representation of this Specifier like object. This
        should be representative of the Specifier itself.
        N((tself((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__str__tcC`sdS(sF
        Returns a hash value for this Specifier like object.
        N((R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__hash__RcC`sdS(sq
        Returns a boolean representing whether or not the two Specifier like
        objects are equal.
        N((R
tother((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__eq__$RcC`sdS(su
        Returns a boolean representing whether or not the two Specifier like
        objects are not equal.
        N((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__ne__+RcC`sdS(sg
        Returns whether or not pre-releases as a whole are allowed by this
        specifier.
        N((R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytprereleases2RcC`sdS(sd
        Sets whether or not pre-releases as a whole are allowed by this
        specifier.
        N((R
tvalue((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR9RcC`sdS(sR
        Determines if the given item is contained within this specifier.
        N((R
titemR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytcontains@RcC`sdS(s
        Takes an iterable of items and filters them so that only items which
        are contained within this specifier are allowed in it.
        N((R
titerableR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytfilterFRN(R	R
tabctabstractmethodRRRRtabstractpropertyRtsettertNoneRR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRst_IndividualSpecifiercB`seZiZdddZdZdZdZdZdZ	dZ
dZed	Z
ed
ZedZejdZd
ZddZddZRS(RcC`sj|jj|}|s0tdj|n|jdj|jdjf|_||_dS(NsInvalid specifier: '{0}'toperatortversion(t_regextsearchRtformattgrouptstript_spect_prereleases(R
tspecRtmatch((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__init__RscC`sF|jdk	r!dj|jnd}dj|jjt||S(Ns, prereleases={0!r}Rs<{0}({1!r}{2})>(R(RR$Rt	__class__R	tstr(R
tpre((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__repr___s!		cC`sdj|jS(Ns{0}{1}(R$R'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRlscC`s
t|jS(N(thashR'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRoscC`s`t|tr:y|j|}WqPtk
r6tSXnt||jsPtS|j|jkS(N(t
isinstanceRR,RtNotImplementedR'(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRrs
cC`s`t|tr:y|j|}WqPtk
r6tSXnt||jsPtS|j|jkS(N(R1RR,RR2R'(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR}s
cC`st|dj|j|S(Ns_compare_{0}(tgetattrR$t
_operators(R
top((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt
_get_operatorscC`s(t|ttfs$t|}n|S(N(R1RRR(R
R!((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_coerce_versionscC`s|jdS(Ni(R'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR scC`s|jdS(Ni(R'(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR!scC`s|jS(N(R((R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
||_dS(N(R((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
|j|S(N(R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__contains__scC`sW|dkr|j}n|j|}|jr;|r;tS|j|j||jS(N(RRR7t
is_prereleasetFalseR6R R!(R
RR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscc`st}g}i|dk	r!|ntd6}xf|D]^}|j|}|j||r2|jr|pn|jr|j|qt}|Vq2q2W|r|rx|D]}|VqWndS(NR(R:RtTrueR7RR9Rtappend(R
RRtyieldedtfound_prereleasestkwR!tparsed_version((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs
	

N(R	R
R4RR+R/RRRRR6R7tpropertyR R!RRR8RR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRNs 
	
							tLegacySpecifiercB`seZdZejdedejejBZidd6dd6dd6d	d
6dd6d
d6ZdZ	dZ
dZdZdZ
dZdZRS(s
        (?P(==|!=|<=|>=|<|>))
        \s*
        (?P
            [^,;\s)]* # Since this is a "legacy" specifier, and the version
                      # string can be just about anything, we match everything
                      # except for whitespace, a semi-colon for marker support,
                      # a closing paren since versions can be enclosed in
                      # them, and a comma since it's a version separator.
        )
        s^\s*s\s*$tequals==t	not_equals!=tless_than_equals<=tgreater_than_equals>=t	less_thantcC`s(t|ts$tt|}n|S(N(R1RR-(R
R!((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR7scC`s||j|kS(N(R7(R
tprospectiveR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_not_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_less_than_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_greater_than_equalscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_less_thanscC`s||j|kS(N(R7(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_greater_thans(R	R
t
_regex_strtretcompiletVERBOSEt
IGNORECASER"R4R7RLRMRNRORPRQ(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRBs"

						c`s"tjfd}|S(Nc`s#t|tstS|||S(N(R1RR:(R
RKR)(tfn(sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytwrappeds(t	functoolstwraps(RWRX((RWsD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_require_version_compare
st	SpecifiercB`seZdZejdedejejBZidd6dd6dd6d	d
6dd6d
d6dd6dd6Ze	dZ
e	dZe	dZe	dZ
e	dZe	dZe	dZdZedZejdZRS(s
        (?P(~=|==|!=|<=|>=|<|>|===))
        (?P
            (?:
                # The identity operators allow for an escape hatch that will
                # do an exact string match of the version you wish to install.
                # This will not be parsed by PEP 440 and we cannot determine
                # any semantic meaning from it. This operator is discouraged
                # but included entirely as an escape hatch.
                (?<====)  # Only match for the identity operator
                \s*
                [^\s]*    # We just match everything, except for whitespace
                          # since we are only testing for strict identity.
            )
            |
            (?:
                # The (non)equality operators allow for wild card and local
                # versions to be specified so we have to define these two
                # operators separately to enable that.
                (?<===|!=)            # Only match for equals and not equals

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)*   # release
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?

                # You cannot use a wild card and a dev or local version
                # together so group them with a | and make them optional.
                (?:
                    (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
                    (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
                    |
                    \.\*  # Wild card syntax of .*
                )?
            )
            |
            (?:
                # The compatible operator requires at least two digits in the
                # release segment.
                (?<=~=)               # Only match for the compatible operator

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?
                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
            )
            |
            (?:
                # All other operators only allow a sub set of what the
                # (non)equality operators do. Specifically they do not allow
                # local versions to be specified nor do they allow the prefix
                # matching wild cards.
                (?=RGRHRIRJt	arbitrarys===cC`sfdjttjdt|d }|d7}|jd||oe|jd||S(Nt.cS`s|jdo|jdS(Ntposttdev(t
startswith(tx((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pytsis.*s>=s==(tjointlistt	itertoolst	takewhilet_version_splitR6(R
RKR)tprefix((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_compatibles

cC`s|jdrht|j}t|d }tt|}|t| }t||\}}n't|}|jst|j}n||kS(Ns.*i(tendswithRtpublicRiR-tlent_pad_versiontlocal(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRLs	cC`s|j||S(N(RL(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRMscC`s|t|kS(N(R(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRNscC`s|t|kS(N(R(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyROscC`sXt|}||kstS|jrT|jrTt|jt|jkrTtSntS(N(RR:R9tbase_versionR;(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRPscC`st|}||kstS|jrT|jrTt|jt|jkrTtSn|jdk	rt|jt|jkrtSntS(N(RR:tis_postreleaseRqRpRR;(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRQscC`s"t|jt|jkS(N(R-tlower(R
RKR)((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt_compare_arbitraryscC`ss|jdk	r|jS|j\}}|dkro|dkrY|jdrY|d }nt|jrotSntS(	Ns==s>=s<=s~=s===s.*i(s==s>=s<=s~=s===(R(RR'RlRR9R;R:(R
R R!((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs
cC`s
||_dS(N(R((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs(R	R
RRRSRTRURVR"R4R[RkRLRMRNRORPRQRtRARR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR\s,^
#	s^([0-9]+)((?:a|b|c|rc)[0-9]+)$cC`s\g}xO|jdD]>}tj|}|rG|j|jq|j|qW|S(NR_(tsplitt
_prefix_regexR#textendtgroupsR<(R!tresultRR*((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRi'sc	C`sgg}}|jttjd||jttjd||j|t|d|j|t|d|jddgtdt|dt|d|jddgtdt|dt|dttj|ttj|fS(NcS`s
|jS(N(tisdigit(Rc((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRd6RcS`s
|jS(N(Rz(Rc((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRd7Riit0(R<RfRgRhRntinserttmaxtchain(tlefttrightt
left_splittright_split((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRo2s
""//tSpecifierSetcB`seZdddZdZdZdZdZdZdZ	dZ
d	Zed
Z
e
jdZ
dZdd
ZddZRS(RcC`sg|jdD]}|jr|j^q}t}xL|D]D}y|jt|WqDtk
r|jt|qDXqDWt||_||_	dS(Nt,(
RuR&tsettaddR\RRBt	frozensett_specsR((R
t
specifiersRtstparsedt	specifier((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR+Os4	

cC`s=|jdk	r!dj|jnd}djt||S(Ns, prereleases={0!r}Rs(R(RR$RR-(R
R.((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR/ds!cC`s djtd|jDS(NRcs`s|]}t|VqdS(N(R-(t.0R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pys	ns(RetsortedR(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRmscC`s
t|jS(N(R0R(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRpscC`st|trt|}nt|ts1tSt}t|j|jB|_|jdkr|jdk	r|j|_nZ|jdk	r|jdkr|j|_n-|j|jkr|j|_ntd|S(NsFCannot combine SpecifierSets with True and False prerelease overrides.(	R1RRR2RRR(Rt
ValueError(R
RR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__and__ss		cC`set|trt|}n7t|trBtt|}nt|tsUtS|j|jkS(N(R1RRRR-R2R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`set|trt|}n7t|trBtt|}nt|tsUtS|j|jkS(N(R1RRRR-R2R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
t|jS(N(RnR(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__len__scC`s
t|jS(N(titerR(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyt__iter__scC`s:|jdk	r|jS|js#dStd|jDS(Ncs`s|]}|jVqdS(N(R(RR((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pys	s(R(RRtany(R
((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs
	cC`s
||_dS(N(R((R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s
|j|S(N(R(R
R((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyR8sc`sptttfs$tndkr<|jnrPjrPtStfd|j	DS(Nc3`s$|]}|jdVqdS(RN(R(RR(RR(sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pys	s(
R1RRRRRR9R:tallR(R
RR((RRsD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRscC`s|dkr|j}n|jrTx,|jD]!}|j|dt|}q+W|Sg}g}x|D]{}t|ttfst|}n|}t|trqgn|j	r|r|s|j
|qqg|j
|qgW|r|r|dkr|S|SdS(NR(RRRRtboolR1RRRR9R<(R
RRR)tfilteredR>RR@((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRs*	
N(R	R
RR+R/RRRRRRRRARRR8RR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyRMs						
	
			(t
__future__RRRRRYRgRSt_compatRRR!RRRRRtABCMetatobjectRRRBR[R\RTRvRiRoR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.pyts""94				_vendor/packaging/version.pyc000064400000033423152527136320012341 0ustar00
abc@`snddlmZmZmZddlZddlZddlZddlmZddddd	gZ	ej
d
ddd
dddgZdZde
fdYZdefdYZdefdYZejdejZidd6dd6dd6dd6dd
6ZdZdZdZdefd YZd!Zejd"Zd#Zd$ZdS(%i(tabsolute_importtdivisiontprint_functionNi(tInfinitytparsetVersiont
LegacyVersiontInvalidVersiontVERSION_PATTERNt_VersiontepochtreleasetdevtpretposttlocalcC`s-yt|SWntk
r(t|SXdS(s
    Parse the given version string and return either a :class:`Version` object
    or a :class:`LegacyVersion` object depending on if the given version is
    a valid PEP 440 version or a legacy version.
    N(RRR(tversion((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRs
cB`seZdZRS(sF
    An invalid version was found, users should refer to PEP 440.
    (t__name__t
__module__t__doc__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR$st_BaseVersioncB`sPeZdZdZdZdZdZdZdZdZ	RS(cC`s
t|jS(N(thasht_key(tself((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__hash__,scC`s|j|dS(NcS`s
||kS(N((tsto((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt0t(t_compare(Rtother((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__lt__/scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR3R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__le__2scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR6R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__eq__5scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR9R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__ge__8scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR<R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__gt__;scC`s|j|dS(NcS`s
||kS(N((RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR?R(R(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__ne__>scC`s&t|tstS||j|jS(N(t
isinstanceRtNotImplementedR(RRtmethod((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRAs(
RRRRR R!R"R#R$R(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR*s							cB`sneZdZdZdZedZedZedZedZ	edZ
RS(cC`s%t||_t|j|_dS(N(tstrt_versiont_legacy_cmpkeyR(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__init__JscC`s|jS(N(R)(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__str__NscC`sdjtt|S(Ns(tformattreprR((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt__repr__QscC`s|jS(N(R)(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pytpublicTscC`s|jS(N(R)(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pytbase_versionXscC`sdS(N(tNone(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR\scC`stS(N(tFalse(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt
is_prerelease`scC`stS(N(R3(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pytis_postreleaseds(RRR+R,R/tpropertyR0R1RR4R5(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRHs			s(\d+ | [a-z]+ | \.| -)tctpreviewsfinal-t-trct@cc`sxxltj|D][}tj||}|s|dkrAqn|d dkrb|jdVqd|VqWdVdS(Nt.it
0123456789it*s*final(t_legacy_version_component_retsplitt_legacy_version_replacement_maptgettzfill(Rtpart((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyt_parse_version_partsrs
cC`sd}g}xt|jD]}|jdr|dkrjx'|rf|ddkrf|jqCWnx'|r|ddkr|jqmWn|j|qWt|}||fS(NiR>s*finals*final-t00000000(REtlowert
startswithtpoptappendttuple(RR
tpartsRD((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR*ss
    v?
    (?:
        (?:(?P[0-9]+)!)?                           # epoch
        (?P[0-9]+(?:\.[0-9]+)*)                  # release segment
        (?P
                                          # pre-release
            [-_\.]?
            (?P(a|b|c|rc|alpha|beta|pre|preview))
            [-_\.]?
            (?P[0-9]+)?
        )?
        (?P                                         # post release
            (?:-(?P[0-9]+))
            |
            (?:
                [-_\.]?
                (?Ppost|rev|r)
                [-_\.]?
                (?P[0-9]+)?
            )
        )?
        (?P                                          # dev release
            [-_\.]?
            (?Pdev)
            [-_\.]?
            (?P[0-9]+)?
        )?
    )
    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
cB`seZejdedejejBZdZdZ	dZ
edZedZ
edZedZed	ZRS(
s^\s*s\s*$cC`s[|jj|}|s0tdj|ntd|jdrZt|jdnddtd|jdjdDdt	|jd|jd	d
t	|jd|jdp|jd
dt	|jd|jddt
|jd|_t|jj
|jj|jj|jj|jj|jj|_dS(NsInvalid version: '{0}'R
iRcs`s|]}t|VqdS(N(tint(t.0ti((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	sR<R
tpre_ltpre_nRtpost_ltpost_n1tpost_n2Rtdev_ltdev_nR(t_regextsearchRR-R	tgroupRMRKR@t_parse_letter_versiont_parse_local_versionR)t_cmpkeyR
RR
RRRR(RRtmatch((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR+s.*(!					cC`sdjtt|S(Ns(R-R.R((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR/scC`sSg}|jjdkr7|jdj|jjn|jdjd|jjD|jjdk	r|jdjd|jjDn|jjdk	r|jdj|jjdn|jj	dk	r|jd	j|jj	dn|jj
dk	rF|jd
jdjd|jj
Dndj|S(Nis{0}!R<cs`s|]}t|VqdS(N(R((RNtx((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	sRcs`s|]}t|VqdS(N(R((RNR^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	ss.post{0}is.dev{0}s+{0}cs`s|]}t|VqdS(N(R((RNR^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	s(R)R
RJR-tjoinRR
R2RRR(RRL((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR,s&)##,cC`st|jdddS(Nt+ii(R(R@(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR0
scC`sjg}|jjdkr7|jdj|jjn|jdjd|jjDdj|S(Nis{0}!R<cs`s|]}t|VqdS(N(R((RNR^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	sR(R)R
RJR-R_R(RRL((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR1s
&cC`s0t|}d|kr,|jdddSdS(NR`i(R(R@(Rtversion_string((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRscC`st|jjp|jjS(N(tboolR)RR
(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR4!scC`st|jjS(N(RbR)R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR5%s(RRtretcompileRtVERBOSEt
IGNORECASERWR+R/R,R6R0R1RR4R5(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRs	#		
cC`s|r|dkrd}n|j}|dkr<d}n?|dkrQd}n*|d
krfd	}n|dkr{d}n|t|fS|r|rd}|t|fSdS(NitalphatatbetatbR7R
R8R:trevtrR(R7R
R8(RkRl(R2RGRM(tlettertnumber((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyRZ*s 					
s[\._-]cC`s-|dk	r)tdtj|DSdS(sR
    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
    cs`s3|])}|js!|jn	t|VqdS(N(tisdigitRGRM(RNRD((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	RsN(R2RKt_local_version_seperatorsR@(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR[LscC`sttttjdt|}|dkr[|dkr[|dk	r[t}n|dkrpt}n|dkrt}n|dkrt}n|dkrt}ntd|D}||||||fS(NcS`s
|dkS(Ni((R^((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR`Rcs`s7|]-}t|tr$|dfn
t|fVqdS(RN(R%RMR(RNRO((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pys	s(RKtreversedtlistt	itertoolst	dropwhileR2R(R
RR
RRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyR\Ws&	$
	
	
	
(t
__future__RRRtcollectionsRsRct_structuresRt__all__t
namedtupleR	Rt
ValueErrorRtobjectRRRdReR?RARER*RRRZRpR[R\(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/version.pyts0	!&		9k		_vendor/packaging/utils.pyc000064400000001104152527136320012003 0ustar00
abc@`sDddlmZmZmZddlZejdZdZdS(i(tabsolute_importtdivisiontprint_functionNs[-_.]+cC`stjd|jS(Nt-(t_canonicalize_regextsubtlower(tname((s?/usr/lib/python2.7/site-packages/pip/_vendor/packaging/utils.pytcanonicalize_names(t
__future__RRRtretcompileRR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/packaging/utils.pyts_vendor/packaging/__about__.pyc000064400000001416152527136320012557 0ustar00
abc@`srddlmZmZmZdddddddd	gZd
ZdZdZd
ZdZ	dZ
dZde	ZdS(i(tabsolute_importtdivisiontprint_functiont	__title__t__summary__t__uri__t__version__t
__author__t	__email__t__license__t
__copyright__t	packagings"Core utilities for Python packagess!https://github.com/pypa/packagings16.8s)Donald Stufft and individual contributorssdonald@stufft.ios"BSD or Apache License, Version 2.0sCopyright 2014-2016 %sN(
t
__future__RRRt__all__RRRRRRR	R
(((sC/usr/lib/python2.7/site-packages/pip/_vendor/packaging/__about__.pyts_vendor/packaging/_compat.pyc000064400000002300152527136320012264 0ustar00
abc@`svddlmZmZmZddlZejddkZejddkZer`efZ	n	e
fZ	dZdS(i(tabsolute_importtdivisiontprint_functionNiic`s5dffdY}tj|ddiS(s/
    Create a base class with a metaclass.
    t	metaclassc`seZfdZRS(c`s||S(N((tclstnamet
this_basestd(tbasestmeta(sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pyt__new__s(t__name__t
__module__R
((RR	(sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pyRsttemporary_class((ttypeR
(R	RR((RR	sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pytwith_metaclasss(t
__future__RRRtsystversion_infotPY2tPY3tstrtstring_typest
basestringR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pyts	_vendor/packaging/requirements.pyc000064400000011741152527136320013376 0ustar00
abc@`sYddlmZmZmZddlZddlZddlmZmZm	Z	m
Z
ddlmZmZm
Z
mZmZddlmZddlmZddlmZmZdd	lmZmZmZd
efdYZeejejZ edj!Z"ed
j!Z#edj!Z$edj!Z%edj!Z&edj!Z'edj!Z(edZ)e ee)e BZ*ee ee*Z+e+dZ,e+Z-eddZ.e(e.Z/e-ee&e-Z0e"e
e0e#dZ1eej2ej3ej4BZ5eej2ej3ej4BZ6e5e6AZ7ee7ee&e7ddde8dZ9e
e$e9e%e9BZ:e:j;de	e:dZ<e<j;de	edZej;de'Z=e=eZ>e<e
e>Z?e/e
e>Z@e,e
e1e@e?BZAeeAeZBd eCfd!YZDdS("i(tabsolute_importtdivisiontprint_functionN(tstringStartt	stringEndtoriginalTextFortParseException(t
ZeroOrMoretWordtOptionaltRegextCombine(tLiteral(tparsei(tMARKER_EXPRtMarker(tLegacySpecifiert	SpecifiertSpecifierSettInvalidRequirementcB`seZdZRS(sJ
    An invalid requirement was found, users should refer to PEP 508.
    (t__name__t
__module__t__doc__(((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyRst[t]t(t)t,t;t@s-_.tnames[^ ]+turltextrast
joinStringtadjacentt	_raw_speccC`s
|jpdS(Nt(R#(tstltt((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt8R$t	specifiercC`s|dS(Ni((R%R&R'((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyR(;R$tmarkercC`st||j|j!S(N(Rt_original_startt
_original_end(R%R&R'((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyR(?R$tRequirementcB`s)eZdZdZdZdZRS(sParse a requirement.

    Parse a given requirement string into its parts, such as name, specifier,
    URL, and extras. Raises InvalidRequirement on a badly-formed requirement
    string.
    cC`sytj|}Wn9tk
rN}tdj||j|jd!nX|j|_|jrtj|j}|j	o|j
s|j	r|j
rtdn|j|_n	d|_t|j
r|j
jng|_
t|j|_|jr|jnd|_dS(Ns+Invalid requirement, parse error at "{0!r}"isInvalid URL given(tREQUIREMENTtparseStringRRtformattlocRRturlparsetschemetnetloctNonetsetR tasListRR)R*(tselftrequirement_stringtreqtet
parsed_url((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt__init__Zs"!		'cC`s|jg}|jr@|jdjdjt|jn|jrb|jt|jn|jr|jdj|jn|j	r|jdj|j	ndj|S(Ns[{0}]Rs@ {0}s; {0}R$(
RR tappendR0tjointsortedR)tstrRR*(R8tparts((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt__str__os	+			cC`sdjt|S(Ns(R0RA(R8((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyt__repr__s(RRRR=RCRD(((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pyR-Ms		(Et
__future__RRRtstringtretpip._vendor.pyparsingRRRRRRR	R
RRtLtpip._vendor.six.moves.urllibR
R2tmarkersRRt
specifiersRRRt
ValueErrorRt
ascii_letterstdigitstALPHANUMtsuppresstLBRACKETtRBRACKETtLPARENtRPARENtCOMMAt	SEMICOLONtATtPUNCTUATIONtIDENTIFIER_ENDt
IDENTIFIERtNAMEtEXTRAtURItURLtEXTRAS_LISTtEXTRASt
_regex_strtVERBOSEt
IGNORECASEtVERSION_PEP440tVERSION_LEGACYtVERSION_ONEtFalsetVERSION_MANYt
_VERSION_SPECtsetParseActiontVERSION_SPECtMARKER_SEPERATORtMARKERtVERSION_AND_MARKERtURL_AND_MARKERtNAMED_REQUIREMENTR.tobjectR-(((sF/usr/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.pytsZ"(



_vendor/packaging/__init__.py000064400000001001152527136320012233 0ustar00# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function

from .__about__ import (
    __author__, __copyright__, __email__, __license__, __summary__, __title__,
    __uri__, __version__
)

__all__ = [
    "__title__", "__summary__", "__uri__", "__version__", "__author__",
    "__email__", "__license__", "__copyright__",
]
_vendor/packaging/specifiers.py000064400000066571152527136320012657 0ustar00# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function

import abc
import functools
import itertools
import re

from ._compat import string_types, with_metaclass
from .version import Version, LegacyVersion, parse


class InvalidSpecifier(ValueError):
    """
    An invalid specifier was found, users should refer to PEP 440.
    """


class BaseSpecifier(with_metaclass(abc.ABCMeta, object)):

    @abc.abstractmethod
    def __str__(self):
        """
        Returns the str representation of this Specifier like object. This
        should be representative of the Specifier itself.
        """

    @abc.abstractmethod
    def __hash__(self):
        """
        Returns a hash value for this Specifier like object.
        """

    @abc.abstractmethod
    def __eq__(self, other):
        """
        Returns a boolean representing whether or not the two Specifier like
        objects are equal.
        """

    @abc.abstractmethod
    def __ne__(self, other):
        """
        Returns a boolean representing whether or not the two Specifier like
        objects are not equal.
        """

    @abc.abstractproperty
    def prereleases(self):
        """
        Returns whether or not pre-releases as a whole are allowed by this
        specifier.
        """

    @prereleases.setter
    def prereleases(self, value):
        """
        Sets whether or not pre-releases as a whole are allowed by this
        specifier.
        """

    @abc.abstractmethod
    def contains(self, item, prereleases=None):
        """
        Determines if the given item is contained within this specifier.
        """

    @abc.abstractmethod
    def filter(self, iterable, prereleases=None):
        """
        Takes an iterable of items and filters them so that only items which
        are contained within this specifier are allowed in it.
        """


class _IndividualSpecifier(BaseSpecifier):

    _operators = {}

    def __init__(self, spec="", prereleases=None):
        match = self._regex.search(spec)
        if not match:
            raise InvalidSpecifier("Invalid specifier: '{0}'".format(spec))

        self._spec = (
            match.group("operator").strip(),
            match.group("version").strip(),
        )

        # Store whether or not this Specifier should accept prereleases
        self._prereleases = prereleases

    def __repr__(self):
        pre = (
            ", prereleases={0!r}".format(self.prereleases)
            if self._prereleases is not None
            else ""
        )

        return "<{0}({1!r}{2})>".format(
            self.__class__.__name__,
            str(self),
            pre,
        )

    def __str__(self):
        return "{0}{1}".format(*self._spec)

    def __hash__(self):
        return hash(self._spec)

    def __eq__(self, other):
        if isinstance(other, string_types):
            try:
                other = self.__class__(other)
            except InvalidSpecifier:
                return NotImplemented
        elif not isinstance(other, self.__class__):
            return NotImplemented

        return self._spec == other._spec

    def __ne__(self, other):
        if isinstance(other, string_types):
            try:
                other = self.__class__(other)
            except InvalidSpecifier:
                return NotImplemented
        elif not isinstance(other, self.__class__):
            return NotImplemented

        return self._spec != other._spec

    def _get_operator(self, op):
        return getattr(self, "_compare_{0}".format(self._operators[op]))

    def _coerce_version(self, version):
        if not isinstance(version, (LegacyVersion, Version)):
            version = parse(version)
        return version

    @property
    def operator(self):
        return self._spec[0]

    @property
    def version(self):
        return self._spec[1]

    @property
    def prereleases(self):
        return self._prereleases

    @prereleases.setter
    def prereleases(self, value):
        self._prereleases = value

    def __contains__(self, item):
        return self.contains(item)

    def contains(self, item, prereleases=None):
        # Determine if prereleases are to be allowed or not.
        if prereleases is None:
            prereleases = self.prereleases

        # Normalize item to a Version or LegacyVersion, this allows us to have
        # a shortcut for ``"2.0" in Specifier(">=2")
        item = self._coerce_version(item)

        # Determine if we should be supporting prereleases in this specifier
        # or not, if we do not support prereleases than we can short circuit
        # logic if this version is a prereleases.
        if item.is_prerelease and not prereleases:
            return False

        # Actually do the comparison to determine if this item is contained
        # within this Specifier or not.
        return self._get_operator(self.operator)(item, self.version)

    def filter(self, iterable, prereleases=None):
        yielded = False
        found_prereleases = []

        kw = {"prereleases": prereleases if prereleases is not None else True}

        # Attempt to iterate over all the values in the iterable and if any of
        # them match, yield them.
        for version in iterable:
            parsed_version = self._coerce_version(version)

            if self.contains(parsed_version, **kw):
                # If our version is a prerelease, and we were not set to allow
                # prereleases, then we'll store it for later incase nothing
                # else matches this specifier.
                if (parsed_version.is_prerelease and not
                        (prereleases or self.prereleases)):
                    found_prereleases.append(version)
                # Either this is not a prerelease, or we should have been
                # accepting prereleases from the begining.
                else:
                    yielded = True
                    yield version

        # Now that we've iterated over everything, determine if we've yielded
        # any values, and if we have not and we have any prereleases stored up
        # then we will go ahead and yield the prereleases.
        if not yielded and found_prereleases:
            for version in found_prereleases:
                yield version


class LegacySpecifier(_IndividualSpecifier):

    _regex_str = (
        r"""
        (?P(==|!=|<=|>=|<|>))
        \s*
        (?P
            [^,;\s)]* # Since this is a "legacy" specifier, and the version
                      # string can be just about anything, we match everything
                      # except for whitespace, a semi-colon for marker support,
                      # a closing paren since versions can be enclosed in
                      # them, and a comma since it's a version separator.
        )
        """
    )

    _regex = re.compile(
        r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE)

    _operators = {
        "==": "equal",
        "!=": "not_equal",
        "<=": "less_than_equal",
        ">=": "greater_than_equal",
        "<": "less_than",
        ">": "greater_than",
    }

    def _coerce_version(self, version):
        if not isinstance(version, LegacyVersion):
            version = LegacyVersion(str(version))
        return version

    def _compare_equal(self, prospective, spec):
        return prospective == self._coerce_version(spec)

    def _compare_not_equal(self, prospective, spec):
        return prospective != self._coerce_version(spec)

    def _compare_less_than_equal(self, prospective, spec):
        return prospective <= self._coerce_version(spec)

    def _compare_greater_than_equal(self, prospective, spec):
        return prospective >= self._coerce_version(spec)

    def _compare_less_than(self, prospective, spec):
        return prospective < self._coerce_version(spec)

    def _compare_greater_than(self, prospective, spec):
        return prospective > self._coerce_version(spec)


def _require_version_compare(fn):
    @functools.wraps(fn)
    def wrapped(self, prospective, spec):
        if not isinstance(prospective, Version):
            return False
        return fn(self, prospective, spec)
    return wrapped


class Specifier(_IndividualSpecifier):

    _regex_str = (
        r"""
        (?P(~=|==|!=|<=|>=|<|>|===))
        (?P
            (?:
                # The identity operators allow for an escape hatch that will
                # do an exact string match of the version you wish to install.
                # This will not be parsed by PEP 440 and we cannot determine
                # any semantic meaning from it. This operator is discouraged
                # but included entirely as an escape hatch.
                (?<====)  # Only match for the identity operator
                \s*
                [^\s]*    # We just match everything, except for whitespace
                          # since we are only testing for strict identity.
            )
            |
            (?:
                # The (non)equality operators allow for wild card and local
                # versions to be specified so we have to define these two
                # operators separately to enable that.
                (?<===|!=)            # Only match for equals and not equals

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)*   # release
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?

                # You cannot use a wild card and a dev or local version
                # together so group them with a | and make them optional.
                (?:
                    (?:[-_\.]?dev[-_\.]?[0-9]*)?         # dev release
                    (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local
                    |
                    \.\*  # Wild card syntax of .*
                )?
            )
            |
            (?:
                # The compatible operator requires at least two digits in the
                # release segment.
                (?<=~=)               # Only match for the compatible operator

                \s*
                v?
                (?:[0-9]+!)?          # epoch
                [0-9]+(?:\.[0-9]+)+   # release  (We have a + instead of a *)
                (?:                   # pre release
                    [-_\.]?
                    (a|b|c|rc|alpha|beta|pre|preview)
                    [-_\.]?
                    [0-9]*
                )?
                (?:                                   # post release
                    (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*)
                )?
                (?:[-_\.]?dev[-_\.]?[0-9]*)?          # dev release
            )
            |
            (?:
                # All other operators only allow a sub set of what the
                # (non)equality operators do. Specifically they do not allow
                # local versions to be specified nor do they allow the prefix
                # matching wild cards.
                (?=": "greater_than_equal",
        "<": "less_than",
        ">": "greater_than",
        "===": "arbitrary",
    }

    @_require_version_compare
    def _compare_compatible(self, prospective, spec):
        # Compatible releases have an equivalent combination of >= and ==. That
        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to
        # implement this in terms of the other specifiers instead of
        # implementing it ourselves. The only thing we need to do is construct
        # the other specifiers.

        # We want everything but the last item in the version, but we want to
        # ignore post and dev releases and we want to treat the pre-release as
        # it's own separate segment.
        prefix = ".".join(
            list(
                itertools.takewhile(
                    lambda x: (not x.startswith("post") and not
                               x.startswith("dev")),
                    _version_split(spec),
                )
            )[:-1]
        )

        # Add the prefix notation to the end of our string
        prefix += ".*"

        return (self._get_operator(">=")(prospective, spec) and
                self._get_operator("==")(prospective, prefix))

    @_require_version_compare
    def _compare_equal(self, prospective, spec):
        # We need special logic to handle prefix matching
        if spec.endswith(".*"):
            # In the case of prefix matching we want to ignore local segment.
            prospective = Version(prospective.public)
            # Split the spec out by dots, and pretend that there is an implicit
            # dot in between a release segment and a pre-release segment.
            spec = _version_split(spec[:-2])  # Remove the trailing .*

            # Split the prospective version out by dots, and pretend that there
            # is an implicit dot in between a release segment and a pre-release
            # segment.
            prospective = _version_split(str(prospective))

            # Shorten the prospective version to be the same length as the spec
            # so that we can determine if the specifier is a prefix of the
            # prospective version or not.
            prospective = prospective[:len(spec)]

            # Pad out our two sides with zeros so that they both equal the same
            # length.
            spec, prospective = _pad_version(spec, prospective)
        else:
            # Convert our spec string into a Version
            spec = Version(spec)

            # If the specifier does not have a local segment, then we want to
            # act as if the prospective version also does not have a local
            # segment.
            if not spec.local:
                prospective = Version(prospective.public)

        return prospective == spec

    @_require_version_compare
    def _compare_not_equal(self, prospective, spec):
        return not self._compare_equal(prospective, spec)

    @_require_version_compare
    def _compare_less_than_equal(self, prospective, spec):
        return prospective <= Version(spec)

    @_require_version_compare
    def _compare_greater_than_equal(self, prospective, spec):
        return prospective >= Version(spec)

    @_require_version_compare
    def _compare_less_than(self, prospective, spec):
        # Convert our spec to a Version instance, since we'll want to work with
        # it as a version.
        spec = Version(spec)

        # Check to see if the prospective version is less than the spec
        # version. If it's not we can short circuit and just return False now
        # instead of doing extra unneeded work.
        if not prospective < spec:
            return False

        # This special case is here so that, unless the specifier itself
        # includes is a pre-release version, that we do not accept pre-release
        # versions for the version mentioned in the specifier (e.g. <3.1 should
        # not match 3.1.dev0, but should match 3.0.dev0).
        if not spec.is_prerelease and prospective.is_prerelease:
            if Version(prospective.base_version) == Version(spec.base_version):
                return False

        # If we've gotten to here, it means that prospective version is both
        # less than the spec version *and* it's not a pre-release of the same
        # version in the spec.
        return True

    @_require_version_compare
    def _compare_greater_than(self, prospective, spec):
        # Convert our spec to a Version instance, since we'll want to work with
        # it as a version.
        spec = Version(spec)

        # Check to see if the prospective version is greater than the spec
        # version. If it's not we can short circuit and just return False now
        # instead of doing extra unneeded work.
        if not prospective > spec:
            return False

        # This special case is here so that, unless the specifier itself
        # includes is a post-release version, that we do not accept
        # post-release versions for the version mentioned in the specifier
        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).
        if not spec.is_postrelease and prospective.is_postrelease:
            if Version(prospective.base_version) == Version(spec.base_version):
                return False

        # Ensure that we do not allow a local version of the version mentioned
        # in the specifier, which is techincally greater than, to match.
        if prospective.local is not None:
            if Version(prospective.base_version) == Version(spec.base_version):
                return False

        # If we've gotten to here, it means that prospective version is both
        # greater than the spec version *and* it's not a pre-release of the
        # same version in the spec.
        return True

    def _compare_arbitrary(self, prospective, spec):
        return str(prospective).lower() == str(spec).lower()

    @property
    def prereleases(self):
        # If there is an explicit prereleases set for this, then we'll just
        # blindly use that.
        if self._prereleases is not None:
            return self._prereleases

        # Look at all of our specifiers and determine if they are inclusive
        # operators, and if they are if they are including an explicit
        # prerelease.
        operator, version = self._spec
        if operator in ["==", ">=", "<=", "~=", "==="]:
            # The == specifier can include a trailing .*, if it does we
            # want to remove before parsing.
            if operator == "==" and version.endswith(".*"):
                version = version[:-2]

            # Parse the version, and if it is a pre-release than this
            # specifier allows pre-releases.
            if parse(version).is_prerelease:
                return True

        return False

    @prereleases.setter
    def prereleases(self, value):
        self._prereleases = value


_prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$")


def _version_split(version):
    result = []
    for item in version.split("."):
        match = _prefix_regex.search(item)
        if match:
            result.extend(match.groups())
        else:
            result.append(item)
    return result


def _pad_version(left, right):
    left_split, right_split = [], []

    # Get the release segment of our versions
    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))
    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))

    # Get the rest of our versions
    left_split.append(left[len(left_split[0]):])
    right_split.append(right[len(right_split[0]):])

    # Insert our padding
    left_split.insert(
        1,
        ["0"] * max(0, len(right_split[0]) - len(left_split[0])),
    )
    right_split.insert(
        1,
        ["0"] * max(0, len(left_split[0]) - len(right_split[0])),
    )

    return (
        list(itertools.chain(*left_split)),
        list(itertools.chain(*right_split)),
    )


class SpecifierSet(BaseSpecifier):

    def __init__(self, specifiers="", prereleases=None):
        # Split on , to break each indidivual specifier into it's own item, and
        # strip each item to remove leading/trailing whitespace.
        specifiers = [s.strip() for s in specifiers.split(",") if s.strip()]

        # Parsed each individual specifier, attempting first to make it a
        # Specifier and falling back to a LegacySpecifier.
        parsed = set()
        for specifier in specifiers:
            try:
                parsed.add(Specifier(specifier))
            except InvalidSpecifier:
                parsed.add(LegacySpecifier(specifier))

        # Turn our parsed specifiers into a frozen set and save them for later.
        self._specs = frozenset(parsed)

        # Store our prereleases value so we can use it later to determine if
        # we accept prereleases or not.
        self._prereleases = prereleases

    def __repr__(self):
        pre = (
            ", prereleases={0!r}".format(self.prereleases)
            if self._prereleases is not None
            else ""
        )

        return "".format(str(self), pre)

    def __str__(self):
        return ",".join(sorted(str(s) for s in self._specs))

    def __hash__(self):
        return hash(self._specs)

    def __and__(self, other):
        if isinstance(other, string_types):
            other = SpecifierSet(other)
        elif not isinstance(other, SpecifierSet):
            return NotImplemented

        specifier = SpecifierSet()
        specifier._specs = frozenset(self._specs | other._specs)

        if self._prereleases is None and other._prereleases is not None:
            specifier._prereleases = other._prereleases
        elif self._prereleases is not None and other._prereleases is None:
            specifier._prereleases = self._prereleases
        elif self._prereleases == other._prereleases:
            specifier._prereleases = self._prereleases
        else:
            raise ValueError(
                "Cannot combine SpecifierSets with True and False prerelease "
                "overrides."
            )

        return specifier

    def __eq__(self, other):
        if isinstance(other, string_types):
            other = SpecifierSet(other)
        elif isinstance(other, _IndividualSpecifier):
            other = SpecifierSet(str(other))
        elif not isinstance(other, SpecifierSet):
            return NotImplemented

        return self._specs == other._specs

    def __ne__(self, other):
        if isinstance(other, string_types):
            other = SpecifierSet(other)
        elif isinstance(other, _IndividualSpecifier):
            other = SpecifierSet(str(other))
        elif not isinstance(other, SpecifierSet):
            return NotImplemented

        return self._specs != other._specs

    def __len__(self):
        return len(self._specs)

    def __iter__(self):
        return iter(self._specs)

    @property
    def prereleases(self):
        # If we have been given an explicit prerelease modifier, then we'll
        # pass that through here.
        if self._prereleases is not None:
            return self._prereleases

        # If we don't have any specifiers, and we don't have a forced value,
        # then we'll just return None since we don't know if this should have
        # pre-releases or not.
        if not self._specs:
            return None

        # Otherwise we'll see if any of the given specifiers accept
        # prereleases, if any of them do we'll return True, otherwise False.
        return any(s.prereleases for s in self._specs)

    @prereleases.setter
    def prereleases(self, value):
        self._prereleases = value

    def __contains__(self, item):
        return self.contains(item)

    def contains(self, item, prereleases=None):
        # Ensure that our item is a Version or LegacyVersion instance.
        if not isinstance(item, (LegacyVersion, Version)):
            item = parse(item)

        # Determine if we're forcing a prerelease or not, if we're not forcing
        # one for this particular filter call, then we'll use whatever the
        # SpecifierSet thinks for whether or not we should support prereleases.
        if prereleases is None:
            prereleases = self.prereleases

        # We can determine if we're going to allow pre-releases by looking to
        # see if any of the underlying items supports them. If none of them do
        # and this item is a pre-release then we do not allow it and we can
        # short circuit that here.
        # Note: This means that 1.0.dev1 would not be contained in something
        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0
        if not prereleases and item.is_prerelease:
            return False

        # We simply dispatch to the underlying specs here to make sure that the
        # given version is contained within all of them.
        # Note: This use of all() here means that an empty set of specifiers
        #       will always return True, this is an explicit design decision.
        return all(
            s.contains(item, prereleases=prereleases)
            for s in self._specs
        )

    def filter(self, iterable, prereleases=None):
        # Determine if we're forcing a prerelease or not, if we're not forcing
        # one for this particular filter call, then we'll use whatever the
        # SpecifierSet thinks for whether or not we should support prereleases.
        if prereleases is None:
            prereleases = self.prereleases

        # If we have any specifiers, then we want to wrap our iterable in the
        # filter method for each one, this will act as a logical AND amongst
        # each specifier.
        if self._specs:
            for spec in self._specs:
                iterable = spec.filter(iterable, prereleases=bool(prereleases))
            return iterable
        # If we do not have any specifiers, then we need to have a rough filter
        # which will filter out any pre-releases, unless there are no final
        # releases, and which will filter out LegacyVersion in general.
        else:
            filtered = []
            found_prereleases = []

            for item in iterable:
                # Ensure that we some kind of Version class for this item.
                if not isinstance(item, (LegacyVersion, Version)):
                    parsed_version = parse(item)
                else:
                    parsed_version = item

                # Filter out any item which is parsed as a LegacyVersion
                if isinstance(parsed_version, LegacyVersion):
                    continue

                # Store any item which is a pre-release for later unless we've
                # already found a final version or we are accepting prereleases
                if parsed_version.is_prerelease and not prereleases:
                    if not filtered:
                        found_prereleases.append(item)
                else:
                    filtered.append(item)

            # If we've found no items except for pre-releases, then we'll go
            # ahead and use the pre-releases
            if not filtered and found_prereleases and prereleases is None:
                return found_prereleases

            return filtered
_vendor/packaging/_compat.pyo000064400000002300152527136320012300 0ustar00
abc@`svddlmZmZmZddlZejddkZejddkZer`efZ	n	e
fZ	dZdS(i(tabsolute_importtdivisiontprint_functionNiic`s5dffdY}tj|ddiS(s/
    Create a base class with a metaclass.
    t	metaclassc`seZfdZRS(c`s||S(N((tclstnamet
this_basestd(tbasestmeta(sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pyt__new__s(t__name__t
__module__R
((RR	(sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pyRsttemporary_class((ttypeR
(R	RR((RR	sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pytwith_metaclasss(t
__future__RRRtsystversion_infotPY2tPY3tstrtstring_typest
basestringR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.pyts	_vendor/packaging/_structures.pyo000064400000007672152527136320013261 0ustar00
abc@`s^ddlmZmZmZdefdYZeZdefdYZeZdS(i(tabsolute_importtdivisiontprint_functiontInfinitycB`sYeZdZdZdZdZdZdZdZdZ	dZ
RS(	cC`sdS(NR((tself((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__repr__	scC`stt|S(N(thashtrepr(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__hash__scC`stS(N(tFalse(Rtother((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__lt__scC`stS(N(R	(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__le__scC`st||jS(N(t
isinstancet	__class__(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__eq__scC`st||jS(N(R
R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__ne__scC`stS(N(tTrue(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__gt__scC`stS(N(R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__ge__scC`stS(N(tNegativeInfinity(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyt__neg__!s(t__name__t
__module__RRRRRRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyRs								RcB`sYeZdZdZdZdZdZdZdZdZ	dZ
RS(	cC`sdS(Ns	-Infinity((R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR)scC`stt|S(N(RR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR,scC`stS(N(R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR/scC`stS(N(R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR2scC`st||jS(N(R
R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR5scC`st||jS(N(R
R(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR8scC`stS(N(R	(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR;scC`stS(N(R	(RR
((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR>scC`stS(N(R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyRAs(RRRRRRRRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyR's								N(t
__future__RRRtobjectRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.pyts	_vendor/packaging/requirements.py000064400000010347152527136320013234 0ustar00# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function

import string
import re

from pip._vendor.pyparsing import (
    stringStart, stringEnd, originalTextFor, ParseException
)
from pip._vendor.pyparsing import ZeroOrMore, Word, Optional, Regex, Combine
from pip._vendor.pyparsing import Literal as L  # noqa
from pip._vendor.six.moves.urllib import parse as urlparse

from .markers import MARKER_EXPR, Marker
from .specifiers import LegacySpecifier, Specifier, SpecifierSet


class InvalidRequirement(ValueError):
    """
    An invalid requirement was found, users should refer to PEP 508.
    """


ALPHANUM = Word(string.ascii_letters + string.digits)

LBRACKET = L("[").suppress()
RBRACKET = L("]").suppress()
LPAREN = L("(").suppress()
RPAREN = L(")").suppress()
COMMA = L(",").suppress()
SEMICOLON = L(";").suppress()
AT = L("@").suppress()

PUNCTUATION = Word("-_.")
IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM)
IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END))

NAME = IDENTIFIER("name")
EXTRA = IDENTIFIER

URI = Regex(r'[^ ]+')("url")
URL = (AT + URI)

EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA)
EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras")

VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE)
VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE)

VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY
VERSION_MANY = Combine(VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE),
                       joinString=",", adjacent=False)("_raw_spec")
_VERSION_SPEC = Optional(((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY))
_VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or '')

VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier")
VERSION_SPEC.setParseAction(lambda s, l, t: t[1])

MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker")
MARKER_EXPR.setParseAction(
    lambda s, l, t: Marker(s[t._original_start:t._original_end])
)
MARKER_SEPERATOR = SEMICOLON
MARKER = MARKER_SEPERATOR + MARKER_EXPR

VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER)
URL_AND_MARKER = URL + Optional(MARKER)

NAMED_REQUIREMENT = \
    NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER)

REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd


class Requirement(object):
    """Parse a requirement.

    Parse a given requirement string into its parts, such as name, specifier,
    URL, and extras. Raises InvalidRequirement on a badly-formed requirement
    string.
    """

    # TODO: Can we test whether something is contained within a requirement?
    #       If so how do we do that? Do we need to test against the _name_ of
    #       the thing as well as the version? What about the markers?
    # TODO: Can we normalize the name and extra name?

    def __init__(self, requirement_string):
        try:
            req = REQUIREMENT.parseString(requirement_string)
        except ParseException as e:
            raise InvalidRequirement(
                "Invalid requirement, parse error at \"{0!r}\"".format(
                    requirement_string[e.loc:e.loc + 8]))

        self.name = req.name
        if req.url:
            parsed_url = urlparse.urlparse(req.url)
            if not (parsed_url.scheme and parsed_url.netloc) or (
                    not parsed_url.scheme and not parsed_url.netloc):
                raise InvalidRequirement("Invalid URL given")
            self.url = req.url
        else:
            self.url = None
        self.extras = set(req.extras.asList() if req.extras else [])
        self.specifier = SpecifierSet(req.specifier)
        self.marker = req.marker if req.marker else None

    def __str__(self):
        parts = [self.name]

        if self.extras:
            parts.append("[{0}]".format(",".join(sorted(self.extras))))

        if self.specifier:
            parts.append(str(self.specifier))

        if self.url:
            parts.append("@ {0}".format(self.url))

        if self.marker:
            parts.append("; {0}".format(self.marker))

        return "".join(parts)

    def __repr__(self):
        return "".format(str(self))
_vendor/distro.py000064400000112715152527136320010073 0ustar00# Copyright 2015,2016 Nir Cohen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
The ``distro`` package (``distro`` stands for Linux Distribution) provides
information about the Linux distribution it runs on, such as a reliable
machine-readable distro ID, or version information.

It is a renewed alternative implementation for Python's original
:py:func:`platform.linux_distribution` function, but it provides much more
functionality. An alternative implementation became necessary because Python
3.5 deprecated this function, and Python 3.7 is expected to remove it
altogether. Its predecessor function :py:func:`platform.dist` was already
deprecated since Python 2.6 and is also expected to be removed in Python 3.7.
Still, there are many cases in which access to Linux distribution information
is needed. See `Python issue 1322 `_ for
more information.
"""

import os
import re
import sys
import json
import shlex
import logging
import subprocess


if not sys.platform.startswith('linux'):
    raise ImportError('Unsupported platform: {0}'.format(sys.platform))

_UNIXCONFDIR = '/etc'
_OS_RELEASE_BASENAME = 'os-release'

#: Translation table for normalizing the "ID" attribute defined in os-release
#: files, for use by the :func:`distro.id` method.
#:
#: * Key: Value as defined in the os-release file, translated to lower case,
#:   with blanks translated to underscores.
#:
#: * Value: Normalized value.
NORMALIZED_OS_ID = {}

#: Translation table for normalizing the "Distributor ID" attribute returned by
#: the lsb_release command, for use by the :func:`distro.id` method.
#:
#: * Key: Value as returned by the lsb_release command, translated to lower
#:   case, with blanks translated to underscores.
#:
#: * Value: Normalized value.
NORMALIZED_LSB_ID = {
    'enterpriseenterprise': 'oracle',  # Oracle Enterprise Linux
    'redhatenterpriseworkstation': 'rhel',  # RHEL 6.7
}

#: Translation table for normalizing the distro ID derived from the file name
#: of distro release files, for use by the :func:`distro.id` method.
#:
#: * Key: Value as derived from the file name of a distro release file,
#:   translated to lower case, with blanks translated to underscores.
#:
#: * Value: Normalized value.
NORMALIZED_DISTRO_ID = {
    'redhat': 'rhel',  # RHEL 6.x, 7.x
}

# Pattern for content of distro release file (reversed)
_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
    r'(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)')

# Pattern for base file name of distro release file
_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(
    r'(\w+)[-_](release|version)$')

# Base file names to be ignored when searching for distro release file
_DISTRO_RELEASE_IGNORE_BASENAMES = (
    'debian_version',
    'lsb-release',
    'oem-release',
    _OS_RELEASE_BASENAME,
    'system-release'
)


def linux_distribution(full_distribution_name=True):
    """
    Return information about the current Linux distribution as a tuple
    ``(id_name, version, codename)`` with items as follows:

    * ``id_name``:  If *full_distribution_name* is false, the result of
      :func:`distro.id`. Otherwise, the result of :func:`distro.name`.

    * ``version``:  The result of :func:`distro.version`.

    * ``codename``:  The result of :func:`distro.codename`.

    The interface of this function is compatible with the original
    :py:func:`platform.linux_distribution` function, supporting a subset of
    its parameters.

    The data it returns may not exactly be the same, because it uses more data
    sources than the original function, and that may lead to different data if
    the Linux distribution is not consistent across multiple data sources it
    provides (there are indeed such distributions ...).

    Another reason for differences is the fact that the :func:`distro.id`
    method normalizes the distro ID string to a reliable machine-readable value
    for a number of popular Linux distributions.
    """
    return _distro.linux_distribution(full_distribution_name)


def id():
    """
    Return the distro ID of the current Linux distribution, as a
    machine-readable string.

    For a number of Linux distributions, the returned distro ID value is
    *reliable*, in the sense that it is documented and that it does not change
    across releases of the distribution.

    This package maintains the following reliable distro ID values:

    ==============  =========================================
    Distro ID       Distribution
    ==============  =========================================
    "ubuntu"        Ubuntu
    "debian"        Debian
    "rhel"          RedHat Enterprise Linux
    "centos"        CentOS
    "fedora"        Fedora
    "sles"          SUSE Linux Enterprise Server
    "opensuse"      openSUSE
    "amazon"        Amazon Linux
    "arch"          Arch Linux
    "cloudlinux"    CloudLinux OS
    "exherbo"       Exherbo Linux
    "gentoo"        GenToo Linux
    "ibm_powerkvm"  IBM PowerKVM
    "kvmibm"        KVM for IBM z Systems
    "linuxmint"     Linux Mint
    "mageia"        Mageia
    "mandriva"      Mandriva Linux
    "parallels"     Parallels
    "pidora"        Pidora
    "raspbian"      Raspbian
    "oracle"        Oracle Linux (and Oracle Enterprise Linux)
    "scientific"    Scientific Linux
    "slackware"     Slackware
    "xenserver"     XenServer
    ==============  =========================================

    If you have a need to get distros for reliable IDs added into this set,
    or if you find that the :func:`distro.id` function returns a different
    distro ID for one of the listed distros, please create an issue in the
    `distro issue tracker`_.

    **Lookup hierarchy and transformations:**

    First, the ID is obtained from the following sources, in the specified
    order. The first available and non-empty value is used:

    * the value of the "ID" attribute of the os-release file,

    * the value of the "Distributor ID" attribute returned by the lsb_release
      command,

    * the first part of the file name of the distro release file,

    The so determined ID value then passes the following transformations,
    before it is returned by this method:

    * it is translated to lower case,

    * blanks (which should not be there anyway) are translated to underscores,

    * a normalization of the ID is performed, based upon
      `normalization tables`_. The purpose of this normalization is to ensure
      that the ID is as reliable as possible, even across incompatible changes
      in the Linux distributions. A common reason for an incompatible change is
      the addition of an os-release file, or the addition of the lsb_release
      command, with ID values that differ from what was previously determined
      from the distro release file name.
    """
    return _distro.id()


def name(pretty=False):
    """
    Return the name of the current Linux distribution, as a human-readable
    string.

    If *pretty* is false, the name is returned without version or codename.
    (e.g. "CentOS Linux")

    If *pretty* is true, the version and codename are appended.
    (e.g. "CentOS Linux 7.1.1503 (Core)")

    **Lookup hierarchy:**

    The name is obtained from the following sources, in the specified order.
    The first available and non-empty value is used:

    * If *pretty* is false:

      - the value of the "NAME" attribute of the os-release file,

      - the value of the "Distributor ID" attribute returned by the lsb_release
        command,

      - the value of the "" field of the distro release file.

    * If *pretty* is true:

      - the value of the "PRETTY_NAME" attribute of the os-release file,

      - the value of the "Description" attribute returned by the lsb_release
        command,

      - the value of the "" field of the distro release file, appended
        with the value of the pretty version ("" and ""
        fields) of the distro release file, if available.
    """
    return _distro.name(pretty)


def version(pretty=False, best=False):
    """
    Return the version of the current Linux distribution, as a human-readable
    string.

    If *pretty* is false, the version is returned without codename (e.g.
    "7.0").

    If *pretty* is true, the codename in parenthesis is appended, if the
    codename is non-empty (e.g. "7.0 (Maipo)").

    Some distributions provide version numbers with different precisions in
    the different sources of distribution information. Examining the different
    sources in a fixed priority order does not always yield the most precise
    version (e.g. for Debian 8.2, or CentOS 7.1).

    The *best* parameter can be used to control the approach for the returned
    version:

    If *best* is false, the first non-empty version number in priority order of
    the examined sources is returned.

    If *best* is true, the most precise version number out of all examined
    sources is returned.

    **Lookup hierarchy:**

    In all cases, the version number is obtained from the following sources.
    If *best* is false, this order represents the priority order:

    * the value of the "VERSION_ID" attribute of the os-release file,
    * the value of the "Release" attribute returned by the lsb_release
      command,
    * the version number parsed from the "" field of the first line
      of the distro release file,
    * the version number parsed from the "PRETTY_NAME" attribute of the
      os-release file, if it follows the format of the distro release files.
    * the version number parsed from the "Description" attribute returned by
      the lsb_release command, if it follows the format of the distro release
      files.
    """
    return _distro.version(pretty, best)


def version_parts(best=False):
    """
    Return the version of the current Linux distribution as a tuple
    ``(major, minor, build_number)`` with items as follows:

    * ``major``:  The result of :func:`distro.major_version`.

    * ``minor``:  The result of :func:`distro.minor_version`.

    * ``build_number``:  The result of :func:`distro.build_number`.

    For a description of the *best* parameter, see the :func:`distro.version`
    method.
    """
    return _distro.version_parts(best)


def major_version(best=False):
    """
    Return the major version of the current Linux distribution, as a string,
    if provided.
    Otherwise, the empty string is returned. The major version is the first
    part of the dot-separated version string.

    For a description of the *best* parameter, see the :func:`distro.version`
    method.
    """
    return _distro.major_version(best)


def minor_version(best=False):
    """
    Return the minor version of the current Linux distribution, as a string,
    if provided.
    Otherwise, the empty string is returned. The minor version is the second
    part of the dot-separated version string.

    For a description of the *best* parameter, see the :func:`distro.version`
    method.
    """
    return _distro.minor_version(best)


def build_number(best=False):
    """
    Return the build number of the current Linux distribution, as a string,
    if provided.
    Otherwise, the empty string is returned. The build number is the third part
    of the dot-separated version string.

    For a description of the *best* parameter, see the :func:`distro.version`
    method.
    """
    return _distro.build_number(best)


def like():
    """
    Return a space-separated list of distro IDs of distributions that are
    closely related to the current Linux distribution in regards to packaging
    and programming interfaces, for example distributions the current
    distribution is a derivative from.

    **Lookup hierarchy:**

    This information item is only provided by the os-release file.
    For details, see the description of the "ID_LIKE" attribute in the
    `os-release man page
    `_.
    """
    return _distro.like()


def codename():
    """
    Return the codename for the release of the current Linux distribution,
    as a string.

    If the distribution does not have a codename, an empty string is returned.

    Note that the returned codename is not always really a codename. For
    example, openSUSE returns "x86_64". This function does not handle such
    cases in any special way and just returns the string it finds, if any.

    **Lookup hierarchy:**

    * the codename within the "VERSION" attribute of the os-release file, if
      provided,

    * the value of the "Codename" attribute returned by the lsb_release
      command,

    * the value of the "" field of the distro release file.
    """
    return _distro.codename()


def info(pretty=False, best=False):
    """
    Return certain machine-readable information items about the current Linux
    distribution in a dictionary, as shown in the following example:

    .. sourcecode:: python

        {
            'id': 'rhel',
            'version': '7.0',
            'version_parts': {
                'major': '7',
                'minor': '0',
                'build_number': ''
            },
            'like': 'fedora',
            'codename': 'Maipo'
        }

    The dictionary structure and keys are always the same, regardless of which
    information items are available in the underlying data sources. The values
    for the various keys are as follows:

    * ``id``:  The result of :func:`distro.id`.

    * ``version``:  The result of :func:`distro.version`.

    * ``version_parts -> major``:  The result of :func:`distro.major_version`.

    * ``version_parts -> minor``:  The result of :func:`distro.minor_version`.

    * ``version_parts -> build_number``:  The result of
      :func:`distro.build_number`.

    * ``like``:  The result of :func:`distro.like`.

    * ``codename``:  The result of :func:`distro.codename`.

    For a description of the *pretty* and *best* parameters, see the
    :func:`distro.version` method.
    """
    return _distro.info(pretty, best)


def os_release_info():
    """
    Return a dictionary containing key-value pairs for the information items
    from the os-release file data source of the current Linux distribution.

    See `os-release file`_ for details about these information items.
    """
    return _distro.os_release_info()


def lsb_release_info():
    """
    Return a dictionary containing key-value pairs for the information items
    from the lsb_release command data source of the current Linux distribution.

    See `lsb_release command output`_ for details about these information
    items.
    """
    return _distro.lsb_release_info()


def distro_release_info():
    """
    Return a dictionary containing key-value pairs for the information items
    from the distro release file data source of the current Linux distribution.

    See `distro release file`_ for details about these information items.
    """
    return _distro.distro_release_info()


def os_release_attr(attribute):
    """
    Return a single named information item from the os-release file data source
    of the current Linux distribution.

    Parameters:

    * ``attribute`` (string): Key of the information item.

    Returns:

    * (string): Value of the information item, if the item exists.
      The empty string, if the item does not exist.

    See `os-release file`_ for details about these information items.
    """
    return _distro.os_release_attr(attribute)


def lsb_release_attr(attribute):
    """
    Return a single named information item from the lsb_release command output
    data source of the current Linux distribution.

    Parameters:

    * ``attribute`` (string): Key of the information item.

    Returns:

    * (string): Value of the information item, if the item exists.
      The empty string, if the item does not exist.

    See `lsb_release command output`_ for details about these information
    items.
    """
    return _distro.lsb_release_attr(attribute)


def distro_release_attr(attribute):
    """
    Return a single named information item from the distro release file
    data source of the current Linux distribution.

    Parameters:

    * ``attribute`` (string): Key of the information item.

    Returns:

    * (string): Value of the information item, if the item exists.
      The empty string, if the item does not exist.

    See `distro release file`_ for details about these information items.
    """
    return _distro.distro_release_attr(attribute)


class LinuxDistribution(object):
    """
    Provides information about a Linux distribution.

    This package creates a private module-global instance of this class with
    default initialization arguments, that is used by the
    `consolidated accessor functions`_ and `single source accessor functions`_.
    By using default initialization arguments, that module-global instance
    returns data about the current Linux distribution (i.e. the distro this
    package runs on).

    Normally, it is not necessary to create additional instances of this class.
    However, in situations where control is needed over the exact data sources
    that are used, instances of this class can be created with a specific
    distro release file, or a specific os-release file, or without invoking the
    lsb_release command.
    """

    def __init__(self,
                 include_lsb=True,
                 os_release_file='',
                 distro_release_file=''):
        """
        The initialization method of this class gathers information from the
        available data sources, and stores that in private instance attributes.
        Subsequent access to the information items uses these private instance
        attributes, so that the data sources are read only once.

        Parameters:

        * ``include_lsb`` (bool): Controls whether the
          `lsb_release command output`_ is included as a data source.

          If the lsb_release command is not available in the program execution
          path, the data source for the lsb_release command will be empty.

        * ``os_release_file`` (string): The path name of the
          `os-release file`_ that is to be used as a data source.

          An empty string (the default) will cause the default path name to
          be used (see `os-release file`_ for details).

          If the specified or defaulted os-release file does not exist, the
          data source for the os-release file will be empty.

        * ``distro_release_file`` (string): The path name of the
          `distro release file`_ that is to be used as a data source.

          An empty string (the default) will cause a default search algorithm
          to be used (see `distro release file`_ for details).

          If the specified distro release file does not exist, or if no default
          distro release file can be found, the data source for the distro
          release file will be empty.

        Public instance attributes:

        * ``os_release_file`` (string): The path name of the
          `os-release file`_ that is actually used as a data source. The
          empty string if no distro release file is used as a data source.

        * ``distro_release_file`` (string): The path name of the
          `distro release file`_ that is actually used as a data source. The
          empty string if no distro release file is used as a data source.

        Raises:

        * :py:exc:`IOError`: Some I/O issue with an os-release file or distro
          release file.

        * :py:exc:`subprocess.CalledProcessError`: The lsb_release command had
          some issue (other than not being available in the program execution
          path).

        * :py:exc:`UnicodeError`: A data source has unexpected characters or
          uses an unexpected encoding.
        """
        self.os_release_file = os_release_file or \
            os.path.join(_UNIXCONFDIR, _OS_RELEASE_BASENAME)
        self.distro_release_file = distro_release_file or ''  # updated later
        self._os_release_info = self._get_os_release_info()
        self._lsb_release_info = self._get_lsb_release_info() \
            if include_lsb else {}
        self._distro_release_info = self._get_distro_release_info()

    def __repr__(self):
        """Return repr of all info
        """
        return \
            "LinuxDistribution(" \
            "os_release_file={0!r}, " \
            "distro_release_file={1!r}, " \
            "_os_release_info={2!r}, " \
            "_lsb_release_info={3!r}, " \
            "_distro_release_info={4!r})".format(
                self.os_release_file,
                self.distro_release_file,
                self._os_release_info,
                self._lsb_release_info,
                self._distro_release_info)

    def linux_distribution(self, full_distribution_name=True):
        """
        Return information about the Linux distribution that is compatible
        with Python's :func:`platform.linux_distribution`, supporting a subset
        of its parameters.

        For details, see :func:`distro.linux_distribution`.
        """
        return (
            self.name() if full_distribution_name else self.id(),
            self.version(),
            self.codename()
        )

    def id(self):
        """Return the distro ID of the Linux distribution, as a string.

        For details, see :func:`distro.id`.
        """
        def normalize(distro_id, table):
            distro_id = distro_id.lower().replace(' ', '_')
            return table.get(distro_id, distro_id)

        distro_id = self.os_release_attr('id')
        if distro_id:
            return normalize(distro_id, NORMALIZED_OS_ID)

        distro_id = self.lsb_release_attr('distributor_id')
        if distro_id:
            return normalize(distro_id, NORMALIZED_LSB_ID)

        distro_id = self.distro_release_attr('id')
        if distro_id:
            return normalize(distro_id, NORMALIZED_DISTRO_ID)

        return ''

    def name(self, pretty=False):
        """
        Return the name of the Linux distribution, as a string.

        For details, see :func:`distro.name`.
        """
        name = self.os_release_attr('name') \
            or self.lsb_release_attr('distributor_id') \
            or self.distro_release_attr('name')
        if pretty:
            name = self.os_release_attr('pretty_name') \
                or self.lsb_release_attr('description')
            if not name:
                name = self.distro_release_attr('name')
                version = self.version(pretty=True)
                if version:
                    name = name + ' ' + version
        return name or ''

    def version(self, pretty=False, best=False):
        """
        Return the version of the Linux distribution, as a string.

        For details, see :func:`distro.version`.
        """
        versions = [
            self.os_release_attr('version_id'),
            self.lsb_release_attr('release'),
            self.distro_release_attr('version_id'),
            self._parse_distro_release_content(
                self.os_release_attr('pretty_name')).get('version_id', ''),
            self._parse_distro_release_content(
                self.lsb_release_attr('description')).get('version_id', '')
        ]
        version = ''
        if best:
            # This algorithm uses the last version in priority order that has
            # the best precision. If the versions are not in conflict, that
            # does not matter; otherwise, using the last one instead of the
            # first one might be considered a surprise.
            for v in versions:
                if v.count(".") > version.count(".") or version == '':
                    version = v
        else:
            for v in versions:
                if v != '':
                    version = v
                    break
        if pretty and version and self.codename():
            version = u'{0} ({1})'.format(version, self.codename())
        return version

    def version_parts(self, best=False):
        """
        Return the version of the Linux distribution, as a tuple of version
        numbers.

        For details, see :func:`distro.version_parts`.
        """
        version_str = self.version(best=best)
        if version_str:
            version_regex = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?')
            matches = version_regex.match(version_str)
            if matches:
                major, minor, build_number = matches.groups()
                return major, minor or '', build_number or ''
        return '', '', ''

    def major_version(self, best=False):
        """
        Return the major version number of the current distribution.

        For details, see :func:`distro.major_version`.
        """
        return self.version_parts(best)[0]

    def minor_version(self, best=False):
        """
        Return the minor version number of the Linux distribution.

        For details, see :func:`distro.minor_version`.
        """
        return self.version_parts(best)[1]

    def build_number(self, best=False):
        """
        Return the build number of the Linux distribution.

        For details, see :func:`distro.build_number`.
        """
        return self.version_parts(best)[2]

    def like(self):
        """
        Return the IDs of distributions that are like the Linux distribution.

        For details, see :func:`distro.like`.
        """
        return self.os_release_attr('id_like') or ''

    def codename(self):
        """
        Return the codename of the Linux distribution.

        For details, see :func:`distro.codename`.
        """
        return self.os_release_attr('codename') \
            or self.lsb_release_attr('codename') \
            or self.distro_release_attr('codename') \
            or ''

    def info(self, pretty=False, best=False):
        """
        Return certain machine-readable information about the Linux
        distribution.

        For details, see :func:`distro.info`.
        """
        return dict(
            id=self.id(),
            version=self.version(pretty, best),
            version_parts=dict(
                major=self.major_version(best),
                minor=self.minor_version(best),
                build_number=self.build_number(best)
            ),
            like=self.like(),
            codename=self.codename(),
        )

    def os_release_info(self):
        """
        Return a dictionary containing key-value pairs for the information
        items from the os-release file data source of the Linux distribution.

        For details, see :func:`distro.os_release_info`.
        """
        return self._os_release_info

    def lsb_release_info(self):
        """
        Return a dictionary containing key-value pairs for the information
        items from the lsb_release command data source of the Linux
        distribution.

        For details, see :func:`distro.lsb_release_info`.
        """
        return self._lsb_release_info

    def distro_release_info(self):
        """
        Return a dictionary containing key-value pairs for the information
        items from the distro release file data source of the Linux
        distribution.

        For details, see :func:`distro.distro_release_info`.
        """
        return self._distro_release_info

    def os_release_attr(self, attribute):
        """
        Return a single named information item from the os-release file data
        source of the Linux distribution.

        For details, see :func:`distro.os_release_attr`.
        """
        return self._os_release_info.get(attribute, '')

    def lsb_release_attr(self, attribute):
        """
        Return a single named information item from the lsb_release command
        output data source of the Linux distribution.

        For details, see :func:`distro.lsb_release_attr`.
        """
        return self._lsb_release_info.get(attribute, '')

    def distro_release_attr(self, attribute):
        """
        Return a single named information item from the distro release file
        data source of the Linux distribution.

        For details, see :func:`distro.distro_release_attr`.
        """
        return self._distro_release_info.get(attribute, '')

    def _get_os_release_info(self):
        """
        Get the information items from the specified os-release file.

        Returns:
            A dictionary containing all information items.
        """
        if os.path.isfile(self.os_release_file):
            with open(self.os_release_file) as release_file:
                return self._parse_os_release_content(release_file)
        return {}

    @staticmethod
    def _parse_os_release_content(lines):
        """
        Parse the lines of an os-release file.

        Parameters:

        * lines: Iterable through the lines in the os-release file.
                 Each line must be a unicode string or a UTF-8 encoded byte
                 string.

        Returns:
            A dictionary containing all information items.
        """
        props = {}
        lexer = shlex.shlex(lines, posix=True)
        lexer.whitespace_split = True

        # The shlex module defines its `wordchars` variable using literals,
        # making it dependent on the encoding of the Python source file.
        # In Python 2.6 and 2.7, the shlex source file is encoded in
        # 'iso-8859-1', and the `wordchars` variable is defined as a byte
        # string. This causes a UnicodeDecodeError to be raised when the
        # parsed content is a unicode object. The following fix resolves that
        # (... but it should be fixed in shlex...):
        if sys.version_info[0] == 2 and isinstance(lexer.wordchars, bytes):
            lexer.wordchars = lexer.wordchars.decode('iso-8859-1')

        tokens = list(lexer)
        for token in tokens:
            # At this point, all shell-like parsing has been done (i.e.
            # comments processed, quotes and backslash escape sequences
            # processed, multi-line values assembled, trailing newlines
            # stripped, etc.), so the tokens are now either:
            # * variable assignments: var=value
            # * commands or their arguments (not allowed in os-release)
            if '=' in token:
                k, v = token.split('=', 1)
                if isinstance(v, bytes):
                    v = v.decode('utf-8')
                props[k.lower()] = v
                if k == 'VERSION':
                    # this handles cases in which the codename is in
                    # the `(CODENAME)` (rhel, centos, fedora) format
                    # or in the `, CODENAME` format (Ubuntu).
                    codename = re.search(r'(\(\D+\))|,(\s+)?\D+', v)
                    if codename:
                        codename = codename.group()
                        codename = codename.strip('()')
                        codename = codename.strip(',')
                        codename = codename.strip()
                        # codename appears within paranthese.
                        props['codename'] = codename
                    else:
                        props['codename'] = ''
            else:
                # Ignore any tokens that are not variable assignments
                pass
        return props

    def _get_lsb_release_info(self):
        """
        Get the information items from the lsb_release command output.

        Returns:
            A dictionary containing all information items.
        """
        cmd = 'lsb_release -a'
        process = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')
        code = process.returncode
        if code == 0:
            content = stdout.splitlines()
            return self._parse_lsb_release_content(content)
        elif code == 127:  # Command not found
            return {}
        else:
            if sys.version_info[:2] >= (3, 5):
                raise subprocess.CalledProcessError(code, cmd, stdout, stderr)
            elif sys.version_info[:2] >= (2, 7):
                raise subprocess.CalledProcessError(code, cmd, stdout)
            elif sys.version_info[:2] == (2, 6):
                raise subprocess.CalledProcessError(code, cmd)

    @staticmethod
    def _parse_lsb_release_content(lines):
        """
        Parse the output of the lsb_release command.

        Parameters:

        * lines: Iterable through the lines of the lsb_release output.
                 Each line must be a unicode string or a UTF-8 encoded byte
                 string.

        Returns:
            A dictionary containing all information items.
        """
        props = {}
        for line in lines:
            line = line.decode('utf-8') if isinstance(line, bytes) else line
            kv = line.strip('\n').split(':', 1)
            if len(kv) != 2:
                # Ignore lines without colon.
                continue
            k, v = kv
            props.update({k.replace(' ', '_').lower(): v.strip()})
        return props

    def _get_distro_release_info(self):
        """
        Get the information items from the specified distro release file.

        Returns:
            A dictionary containing all information items.
        """
        if self.distro_release_file:
            # If it was specified, we use it and parse what we can, even if
            # its file name or content does not match the expected pattern.
            distro_info = self._parse_distro_release_file(
                self.distro_release_file)
            basename = os.path.basename(self.distro_release_file)
            # The file name pattern for user-specified distro release files
            # is somewhat more tolerant (compared to when searching for the
            # file), because we want to use what was specified as best as
            # possible.
            match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
            if match:
                distro_info['id'] = match.group(1)
            return distro_info
        else:
            basenames = os.listdir(_UNIXCONFDIR)
            # We sort for repeatability in cases where there are multiple
            # distro specific files; e.g. CentOS, Oracle, Enterprise all
            # containing `redhat-release` on top of their own.
            basenames.sort()
            for basename in basenames:
                if basename in _DISTRO_RELEASE_IGNORE_BASENAMES:
                    continue
                match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
                if match:
                    filepath = os.path.join(_UNIXCONFDIR, basename)
                    distro_info = self._parse_distro_release_file(filepath)
                    if 'name' in distro_info:
                        # The name is always present if the pattern matches
                        self.distro_release_file = filepath
                        distro_info['id'] = match.group(1)
                        return distro_info
            return {}

    def _parse_distro_release_file(self, filepath):
        """
        Parse a distro release file.

        Parameters:

        * filepath: Path name of the distro release file.

        Returns:
            A dictionary containing all information items.
        """
        if os.path.isfile(filepath):
            with open(filepath) as fp:
                # Only parse the first line. For instance, on SLES there
                # are multiple lines. We don't want them...
                return self._parse_distro_release_content(fp.readline())
        return {}

    @staticmethod
    def _parse_distro_release_content(line):
        """
        Parse a line from a distro release file.

        Parameters:
        * line: Line from the distro release file. Must be a unicode string
                or a UTF-8 encoded byte string.

        Returns:
            A dictionary containing all information items.
        """
        if isinstance(line, bytes):
            line = line.decode('utf-8')
        matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(
            line.strip()[::-1])
        distro_info = {}
        if matches:
            # regexp ensures non-None
            distro_info['name'] = matches.group(3)[::-1]
            if matches.group(2):
                distro_info['version_id'] = matches.group(2)[::-1]
            if matches.group(1):
                distro_info['codename'] = matches.group(1)[::-1]
        elif line:
            distro_info['name'] = line.strip()
        return distro_info


_distro = LinuxDistribution()


def main():
    import argparse

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))

    parser = argparse.ArgumentParser(description="Linux distro info tool")
    parser.add_argument(
        '--json',
        '-j',
        help="Output in machine readable format",
        action="store_true")
    args = parser.parse_args()

    if args.json:
        logger.info(json.dumps(info(), indent=4, sort_keys=True))
    else:
        logger.info('Name: %s', name(pretty=True))
        distribution_version = version(pretty=True)
        if distribution_version:
            logger.info('Version: %s', distribution_version)
        distribution_codename = codename()
        if distribution_codename:
            logger.info('Codename: %s', distribution_codename)


if __name__ == '__main__':
    main()
_vendor/progress/helpers.py000064400000005446152527136320012077 0ustar00# Copyright (c) 2012 Giorgos Verigakis 
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from __future__ import print_function


HIDE_CURSOR = '\x1b[?25l'
SHOW_CURSOR = '\x1b[?25h'


class WriteMixin(object):
    hide_cursor = False

    def __init__(self, message=None, **kwargs):
        super(WriteMixin, self).__init__(**kwargs)
        self._width = 0
        if message:
            self.message = message

        if self.file.isatty():
            if self.hide_cursor:
                print(HIDE_CURSOR, end='', file=self.file)
            print(self.message, end='', file=self.file)
            self.file.flush()

    def write(self, s):
        if self.file.isatty():
            b = '\b' * self._width
            c = s.ljust(self._width)
            print(b + c, end='', file=self.file)
            self._width = max(self._width, len(s))
            self.file.flush()

    def finish(self):
        if self.file.isatty() and self.hide_cursor:
            print(SHOW_CURSOR, end='', file=self.file)


class WritelnMixin(object):
    hide_cursor = False

    def __init__(self, message=None, **kwargs):
        super(WritelnMixin, self).__init__(**kwargs)
        if message:
            self.message = message

        if self.file.isatty() and self.hide_cursor:
            print(HIDE_CURSOR, end='', file=self.file)

    def clearln(self):
        if self.file.isatty():
            print('\r\x1b[K', end='', file=self.file)

    def writeln(self, line):
        if self.file.isatty():
            self.clearln()
            print(line, end='', file=self.file)
            self.file.flush()

    def finish(self):
        if self.file.isatty():
            print(file=self.file)
            if self.hide_cursor:
                print(SHOW_CURSOR, end='', file=self.file)


from signal import signal, SIGINT
from sys import exit


class SigIntMixin(object):
    """Registers a signal handler that calls finish on SIGINT"""

    def __init__(self, *args, **kwargs):
        super(SigIntMixin, self).__init__(*args, **kwargs)
        signal(SIGINT, self._sigint_handler)

    def _sigint_handler(self, signum, frame):
        self.finish()
        exit(0)
_vendor/progress/spinner.py000064400000002442152527136320012104 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2012 Giorgos Verigakis 
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from . import Infinite
from .helpers import WriteMixin


class Spinner(WriteMixin, Infinite):
    message = ''
    phases = ('-', '\\', '|', '/')
    hide_cursor = True

    def update(self):
        i = self.index % len(self.phases)
        self.write(self.phases[i])


class PieSpinner(Spinner):
    phases = [u'◷', u'◶', u'◵', u'◴']


class MoonSpinner(Spinner):
    phases = [u'◑', u'◒', u'◐', u'◓']


class LineSpinner(Spinner):
    phases = [u'⎺', u'⎻', u'⎼', u'⎽', u'⎼', u'⎻']
_vendor/progress/__init__.pyc000064400000012264152527136320012333 0ustar00
abc@ sddlmZddlmZddlmZddlmZddlm	Z	ddl
m
Z
dZdefd	YZ
d
e
fdYZdS(
i(tdivision(tdeque(t	timedelta(tceil(tstderr(ttimes1.2tInfinitecB seZeZdZdZdZedZedZ	edZ
dZdZdZ
d	d
ZdZRS(i
cO sgd|_t|_|j|_td|j|_x*|jD]\}}t|||qCWdS(Nitmaxlen(	tindexRtstart_tst_tsRt
sma_windowt_dttitemstsetattr(tselftargstkwargstkeytval((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyt__init__s	cC s#|jdrdSt||dS(Nt_(t
startswithtNonetgetattr(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyt__getitem__'scC s'|jr#t|jt|jSdS(Ni(Rtsumtlen(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytavg,scC stt|jS(N(tintRR	(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytelapsed0scC std|jS(Ntseconds(RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyt
elapsed_td4scC sdS(N((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytupdate8scC sdS(N((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytstart;scC sdS(N((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytfinish>sicC s`|dkrBt}||j|}|jj|||_n|j||_|jdS(Ni(RR
RtappendRR!(Rtntnowtdt((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytnextAs	cc s.x|D]}|V|jqW|jdS(N(R(R#(Rtittx((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytiterKs
(t__name__t
__module__RtfileRRRtpropertyRRR R!R"R#R(R+(((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyRs					
tProgresscB sweZdZedZedZedZedZedZdZ	dZ
dZRS(	cO s2tt|j|||jdd|_dS(Ntmaxid(tsuperR0RtgetR1(RRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyRSscC stt|j|jS(N(RRRt	remaining(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytetaWscC std|jS(NR(RR5(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyteta_td[scC s|jdS(Nid(tprogress(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytpercent_scC std|j|jS(Ni(tminRR1(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR7cscC st|j|jdS(Ni(R1R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR4gscC s|jdS(N(R!(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR"kscC s||j}|j|dS(N(RR((RRtincr((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytgotons
cc sUyt||_Wntk
r&nXx|D]}|V|jq.W|jdS(N(RR1t	TypeErrorR(R#(RR)R*((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR+rs

(R,R-RR/R5R6R8R7R4R"R;R+(((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR0Rs			N(t
__future__RtcollectionsRtdatetimeRtmathRtsysRRt__version__tobjectRR0(((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyts7_vendor/progress/counter.py000064400000002736152527136320012113 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2012 Giorgos Verigakis 
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from . import Infinite, Progress
from .helpers import WriteMixin


class Counter(WriteMixin, Infinite):
    message = ''
    hide_cursor = True

    def update(self):
        self.write(str(self.index))


class Countdown(WriteMixin, Progress):
    hide_cursor = True

    def update(self):
        self.write(str(self.remaining))


class Stack(WriteMixin, Progress):
    phases = (u' ', u'▁', u'▂', u'▃', u'▄', u'▅', u'▆', u'▇', u'█')
    hide_cursor = True

    def update(self):
        nphases = len(self.phases)
        i = min(nphases - 1, int(self.progress * nphases))
        self.write(self.phases[i])


class Pie(Stack):
    phases = (u'○', u'◔', u'◑', u'◕', u'●')
_vendor/progress/bar.py000064400000005175152527136320011200 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2012 Giorgos Verigakis 
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from . import Progress
from .helpers import WritelnMixin


class Bar(WritelnMixin, Progress):
    width = 32
    message = ''
    suffix = '%(index)d/%(max)d'
    bar_prefix = ' |'
    bar_suffix = '| '
    empty_fill = ' '
    fill = '#'
    hide_cursor = True

    def update(self):
        filled_length = int(self.width * self.progress)
        empty_length = self.width - filled_length

        message = self.message % self
        bar = self.fill * filled_length
        empty = self.empty_fill * empty_length
        suffix = self.suffix % self
        line = ''.join([message, self.bar_prefix, bar, empty, self.bar_suffix,
                        suffix])
        self.writeln(line)


class ChargingBar(Bar):
    suffix = '%(percent)d%%'
    bar_prefix = ' '
    bar_suffix = ' '
    empty_fill = u'∙'
    fill = u'█'


class FillingSquaresBar(ChargingBar):
    empty_fill = u'▢'
    fill = u'▣'


class FillingCirclesBar(ChargingBar):
    empty_fill = u'◯'
    fill = u'◉'


class IncrementalBar(Bar):
    phases = (u' ', u'▏', u'▎', u'▍', u'▌', u'▋', u'▊', u'▉', u'█')

    def update(self):
        nphases = len(self.phases)
        expanded_length = int(nphases * self.width * self.progress)
        filled_length = int(self.width * self.progress)
        empty_length = self.width - filled_length
        phase = expanded_length - (filled_length * nphases)

        message = self.message % self
        bar = self.phases[-1] * filled_length
        current = self.phases[phase] if phase > 0 else ''
        empty = self.empty_fill * max(0, empty_length - len(current))
        suffix = self.suffix % self
        line = ''.join([message, self.bar_prefix, bar, current, empty,
                        self.bar_suffix, suffix])
        self.writeln(line)


class ShadyBar(IncrementalBar):
    phases = (u' ', u'░', u'▒', u'▓', u'█')
_vendor/progress/spinner.pyc000064400000003076152527136320012253 0ustar00
abc@sddlmZddlmZdeefdYZdefdYZdefdYZd	efd
YZdS(i(tInfinite(t
WriteMixintSpinnercBs#eZdZdZeZdZRS(tt-s\t|t/cCs.|jt|j}|j|j|dS(N(tindextlentphasestwrite(tselfti((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pytupdates(Rs\RR(t__name__t
__module__tmessageR	tTruethide_cursorR
(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyRst
PieSpinnercBseZddddgZRS(u◷u◶u◵u◴(RRR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyRstMoonSpinnercBseZddddgZRS(u◑u◒u◐u◓(RRR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyR#stLineSpinnercBs eZddddddgZRS(u⎺u⎻u⎼u⎽(RRR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyR'sN(RRthelpersRRRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyts

_vendor/progress/helpers.pyo000064400000007435152527136320012256 0ustar00
abc@sddlmZdZdZdefdYZdefdYZddlmZmZdd	l	m
Z
d
efdYZdS(
i(tprint_functions[?25ls[?25ht
WriteMixincBs,eZeZddZdZdZRS(cKstt|j|d|_|r1||_n|jjr|jrett	ddd|jnt|jddd|j|jj
ndS(Nitendttfile(tsuperRt__init__t_widthtmessageRtisattythide_cursortprinttHIDE_CURSORtflush(tselfRtkwargs((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRs		cCsz|jjrvd|j}|j|j}t||ddd|jt|jt||_|jjndS(NsRRR(RR	RtljustRtmaxtlenR
(Rtstbtc((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytwrite%s
cCs8|jjr4|jr4ttddd|jndS(NRRR(RR	R
RtSHOW_CURSOR(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytfinish-sN(t__name__t
__module__tFalseR
tNoneRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRs	tWritelnMixincBs5eZeZddZdZdZdZRS(cKs`tt|j||r(||_n|jjr\|jr\ttddd|jndS(NRRR(	RRRRRR	R
RR(RRR((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR5s
cCs/|jjr+tdddd|jndS(Ns
RRR(RR	R(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytclearln=scCsF|jjrB|jt|ddd|j|jjndS(NRRR(RR	RRR
(Rtline((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytwritelnAs
cCsK|jjrGtd|j|jrGttddd|jqGndS(NRRR(RR	RR
R(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRGs	N(	RRRR
RRRR R(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR2s
		(tsignaltSIGINT(texittSigIntMixincBs eZdZdZdZRS(s6Registers a signal handler that calls finish on SIGINTcOs-tt|j||tt|jdS(N(RR$RR!R"t_sigint_handler(RtargsR((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRUscCs|jtddS(Ni(RR#(Rtsignumtframe((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR%Ys
(RRt__doc__RR%(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR$Rs	N(t
__future__RRRtobjectRRR!R"tsysR#R$(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyts_vendor/progress/helpers.pyc000064400000007435152527136320012242 0ustar00
abc@sddlmZdZdZdefdYZdefdYZddlmZmZdd	l	m
Z
d
efdYZdS(
i(tprint_functions[?25ls[?25ht
WriteMixincBs,eZeZddZdZdZRS(cKstt|j|d|_|r1||_n|jjr|jrett	ddd|jnt|jddd|j|jj
ndS(Nitendttfile(tsuperRt__init__t_widthtmessageRtisattythide_cursortprinttHIDE_CURSORtflush(tselfRtkwargs((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRs		cCsz|jjrvd|j}|j|j}t||ddd|jt|jt||_|jjndS(NsRRR(RR	RtljustRtmaxtlenR
(Rtstbtc((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytwrite%s
cCs8|jjr4|jr4ttddd|jndS(NRRR(RR	R
RtSHOW_CURSOR(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytfinish-sN(t__name__t
__module__tFalseR
tNoneRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRs	tWritelnMixincBs5eZeZddZdZdZdZRS(cKs`tt|j||r(||_n|jjr\|jr\ttddd|jndS(NRRR(	RRRRRR	R
RR(RRR((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR5s
cCs/|jjr+tdddd|jndS(Ns
RRR(RR	R(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytclearln=scCsF|jjrB|jt|ddd|j|jjndS(NRRR(RR	RRR
(Rtline((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pytwritelnAs
cCsK|jjrGtd|j|jrGttddd|jqGndS(NRRR(RR	RR
R(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRGs	N(	RRRR
RRRR R(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR2s
		(tsignaltSIGINT(texittSigIntMixincBs eZdZdZdZRS(s6Registers a signal handler that calls finish on SIGINTcOs-tt|j||tt|jdS(N(RR$RR!R"t_sigint_handler(RtargsR((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyRUscCs|jtddS(Ni(RR#(Rtsignumtframe((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR%Ys
(RRt__doc__RR%(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyR$Rs	N(t
__future__RRRtobjectRRR!R"tsysR#R$(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/helpers.pyts_vendor/progress/__init__.pyo000064400000012264152527136320012347 0ustar00
abc@ sddlmZddlmZddlmZddlmZddlm	Z	ddl
m
Z
dZdefd	YZ
d
e
fdYZdS(
i(tdivision(tdeque(t	timedelta(tceil(tstderr(ttimes1.2tInfinitecB seZeZdZdZdZedZedZ	edZ
dZdZdZ
d	d
ZdZRS(i
cO sgd|_t|_|j|_td|j|_x*|jD]\}}t|||qCWdS(Nitmaxlen(	tindexRtstart_tst_tsRt
sma_windowt_dttitemstsetattr(tselftargstkwargstkeytval((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyt__init__s	cC s#|jdrdSt||dS(Nt_(t
startswithtNonetgetattr(RR((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyt__getitem__'scC s'|jr#t|jt|jSdS(Ni(Rtsumtlen(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytavg,scC stt|jS(N(tintRR	(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytelapsed0scC std|jS(Ntseconds(RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyt
elapsed_td4scC sdS(N((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytupdate8scC sdS(N((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytstart;scC sdS(N((R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytfinish>sicC s`|dkrBt}||j|}|jj|||_n|j||_|jdS(Ni(RR
RtappendRR!(Rtntnowtdt((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytnextAs	cc s.x|D]}|V|jqW|jdS(N(R(R#(Rtittx((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytiterKs
(t__name__t
__module__RtfileRRRtpropertyRRR R!R"R#R(R+(((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyRs					
tProgresscB sweZdZedZedZedZedZedZdZ	dZ
dZRS(	cO s2tt|j|||jdd|_dS(Ntmaxid(tsuperR0RtgetR1(RRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyRSscC stt|j|jS(N(RRRt	remaining(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytetaWscC std|jS(NR(RR5(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyteta_td[scC s|jdS(Nid(tprogress(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytpercent_scC std|j|jS(Ni(tminRR1(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR7cscC st|j|jdS(Ni(R1R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR4gscC s|jdS(N(R!(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR"kscC s||j}|j|dS(N(RR((RRtincr((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pytgotons
cc sUyt||_Wntk
r&nXx|D]}|V|jq.W|jdS(N(RR1t	TypeErrorR(R#(RR)R*((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR+rs

(R,R-RR/R5R6R8R7R4R"R;R+(((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyR0Rs			N(t
__future__RtcollectionsRtdatetimeRtmathRtsysRRt__version__tobjectRR0(((sA/usr/lib/python2.7/site-packages/pip/_vendor/progress/__init__.pyts7_vendor/progress/bar.pyc000064400000006141152527136320011335 0ustar00
abc@sddlmZddlmZdeefdYZdefdYZdefdYZd	efd
YZdefdYZd
efdYZ	dS(i(tProgress(tWritelnMixintBarcBsAeZdZdZdZdZdZdZdZe	Z
dZRS(i ts%(index)d/%(max)ds |s| t t#cCst|j|j}|j|}|j|}|j|}|j|}|j|}dj||j|||j	|g}|j
|dS(NR(tinttwidthtprogresstmessagetfillt
empty_filltsuffixtjoint
bar_prefixt
bar_suffixtwriteln(tselft
filled_lengthtempty_lengthR	tbartemptyRtline((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pytupdates




(t__name__t
__module__RR	RRRRR
tTruethide_cursorR(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyRstChargingBarcBs&eZdZdZdZdZdZRS(s
%(percent)d%%Ru∙u█(RRRRRRR
(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR,s
tFillingSquaresBarcBseZdZdZRS(u▢u▣(RRRR
(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR4stFillingCirclesBarcBseZdZdZRS(u◯u◉(RRRR
(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR9stIncrementalBarc	BseZd
Zd	ZRS(u u▏u▎u▍u▌u▋u▊u▉u█cCst|j}t||j|j}t|j|j}|j|}|||}|j|}|jd|}|dkr|j|nd}|jtd|t|}	|j|}
dj	||j
|||	|j|
g}|j|dS(NiiR(
tlentphasesRRRR	RtmaxRR
RRR(Rtnphasestexpanded_lengthRRtphaseR	RtcurrentRRR((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyRAs

 
(	u u▏u▎u▍u▌u▋u▊u▉u█(RRR!R(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR>stShadyBarcBseZdZRS(u u░u▒u▓u█(u u░u▒u▓u█(RRR!(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR'RsN(
RRthelpersRRRRRRR'(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyts_vendor/progress/counter.pyc000064400000004127152527136320012252 0ustar00
abc@sddlmZmZddlmZdeefdYZdeefdYZdeefdYZd	efd
YZdS(i(tInfinitetProgress(t
WriteMixintCountercBseZdZeZdZRS(tcCs|jt|jdS(N(twritetstrtindex(tself((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pytupdates(t__name__t
__module__tmessagetTruethide_cursorR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyRst	CountdowncBseZeZdZRS(cCs|jt|jdS(N(RRt	remaining(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR	 s(R
RR
RR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyRstStackc	BseZd
ZeZd	ZRS(u u▁u▂u▃u▄u▅u▆u▇u█cCsGt|j}t|dt|j|}|j|j|dS(Ni(tlentphasestmintinttprogressR(Rtnphasesti((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR	(s (	u u▁u▂u▃u▄u▅u▆u▇u█(R
RRR
RR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR$stPiecBseZdZRS(u○u◔u◑u◕u●(u○u◔u◑u◕u●(R
RR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR.sN(	RRRthelpersRRRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyts

_vendor/progress/counter.pyo000064400000004127152527136320012266 0ustar00
abc@sddlmZmZddlmZdeefdYZdeefdYZdeefdYZd	efd
YZdS(i(tInfinitetProgress(t
WriteMixintCountercBseZdZeZdZRS(tcCs|jt|jdS(N(twritetstrtindex(tself((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pytupdates(t__name__t
__module__tmessagetTruethide_cursorR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyRst	CountdowncBseZeZdZRS(cCs|jt|jdS(N(RRt	remaining(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR	 s(R
RR
RR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyRstStackc	BseZd
ZeZd	ZRS(u u▁u▂u▃u▄u▅u▆u▇u█cCsGt|j}t|dt|j|}|j|j|dS(Ni(tlentphasestmintinttprogressR(Rtnphasesti((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR	(s (	u u▁u▂u▃u▄u▅u▆u▇u█(R
RRR
RR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR$stPiecBseZdZRS(u○u◔u◑u◕u●(u○u◔u◑u◕u●(R
RR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyR.sN(	RRRthelpersRRRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/counter.pyts

_vendor/progress/__init__.py000064400000005717152527136320012175 0ustar00# Copyright (c) 2012 Giorgos Verigakis 
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from __future__ import division

from collections import deque
from datetime import timedelta
from math import ceil
from sys import stderr
from time import time


__version__ = '1.2'


class Infinite(object):
    file = stderr
    sma_window = 10

    def __init__(self, *args, **kwargs):
        self.index = 0
        self.start_ts = time()
        self._ts = self.start_ts
        self._dt = deque(maxlen=self.sma_window)
        for key, val in kwargs.items():
            setattr(self, key, val)

    def __getitem__(self, key):
        if key.startswith('_'):
            return None
        return getattr(self, key, None)

    @property
    def avg(self):
        return sum(self._dt) / len(self._dt) if self._dt else 0

    @property
    def elapsed(self):
        return int(time() - self.start_ts)

    @property
    def elapsed_td(self):
        return timedelta(seconds=self.elapsed)

    def update(self):
        pass

    def start(self):
        pass

    def finish(self):
        pass

    def next(self, n=1):
        if n > 0:
            now = time()
            dt = (now - self._ts) / n
            self._dt.append(dt)
            self._ts = now

        self.index = self.index + n
        self.update()

    def iter(self, it):
        for x in it:
            yield x
            self.next()
        self.finish()


class Progress(Infinite):
    def __init__(self, *args, **kwargs):
        super(Progress, self).__init__(*args, **kwargs)
        self.max = kwargs.get('max', 100)

    @property
    def eta(self):
        return int(ceil(self.avg * self.remaining))

    @property
    def eta_td(self):
        return timedelta(seconds=self.eta)

    @property
    def percent(self):
        return self.progress * 100

    @property
    def progress(self):
        return min(1, self.index / self.max)

    @property
    def remaining(self):
        return max(self.max - self.index, 0)

    def start(self):
        self.update()

    def goto(self, index):
        incr = index - self.index
        self.next(incr)

    def iter(self, it):
        try:
            self.max = len(it)
        except TypeError:
            pass

        for x in it:
            yield x
            self.next()
        self.finish()
_vendor/progress/spinner.pyo000064400000003076152527136320012267 0ustar00
abc@sddlmZddlmZdeefdYZdefdYZdefdYZd	efd
YZdS(i(tInfinite(t
WriteMixintSpinnercBs#eZdZdZeZdZRS(tt-s\t|t/cCs.|jt|j}|j|j|dS(N(tindextlentphasestwrite(tselfti((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pytupdates(Rs\RR(t__name__t
__module__tmessageR	tTruethide_cursorR
(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyRst
PieSpinnercBseZddddgZRS(u◷u◶u◵u◴(RRR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyRstMoonSpinnercBseZddddgZRS(u◑u◒u◐u◓(RRR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyR#stLineSpinnercBs eZddddddgZRS(u⎺u⎻u⎼u⎽(RRR	(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyR'sN(RRthelpersRRRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/progress/spinner.pyts

_vendor/progress/bar.pyo000064400000006141152527136320011351 0ustar00
abc@sddlmZddlmZdeefdYZdefdYZdefdYZd	efd
YZdefdYZd
efdYZ	dS(i(tProgress(tWritelnMixintBarcBsAeZdZdZdZdZdZdZdZe	Z
dZRS(i ts%(index)d/%(max)ds |s| t t#cCst|j|j}|j|}|j|}|j|}|j|}|j|}dj||j|||j	|g}|j
|dS(NR(tinttwidthtprogresstmessagetfillt
empty_filltsuffixtjoint
bar_prefixt
bar_suffixtwriteln(tselft
filled_lengthtempty_lengthR	tbartemptyRtline((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pytupdates




(t__name__t
__module__RR	RRRRR
tTruethide_cursorR(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyRstChargingBarcBs&eZdZdZdZdZdZRS(s
%(percent)d%%Ru∙u█(RRRRRRR
(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR,s
tFillingSquaresBarcBseZdZdZRS(u▢u▣(RRRR
(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR4stFillingCirclesBarcBseZdZdZRS(u◯u◉(RRRR
(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR9stIncrementalBarc	BseZd
Zd	ZRS(u u▏u▎u▍u▌u▋u▊u▉u█cCst|j}t||j|j}t|j|j}|j|}|||}|j|}|jd|}|dkr|j|nd}|jtd|t|}	|j|}
dj	||j
|||	|j|
g}|j|dS(NiiR(
tlentphasesRRRR	RtmaxRR
RRR(Rtnphasestexpanded_lengthRRtphaseR	RtcurrentRRR((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyRAs

 
(	u u▏u▎u▍u▌u▋u▊u▉u█(RRR!R(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR>stShadyBarcBseZdZRS(u u░u▒u▓u█(u u░u▒u▓u█(RRR!(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyR'RsN(
RRthelpersRRRRRRR'(((s</usr/lib/python2.7/site-packages/pip/_vendor/progress/bar.pyts_vendor/__init__.pyc000064400000006210152527136320010461 0ustar00
abc@@sKdZddlmZddlZddlZddlZeZej	j
ej	jeZ
dZerGejej	je
dej	ej	(edededed	ed
ededed
ededededededededededededededededededed ed!ed"ed#ed$ed%ed&ed'ed(ed)ed*ed+ed,ed-ed.ed/ed0ndS(1s
pip._vendor is for vendoring dependencies of pip to prevent needing pip to
depend on something external.

Files inside of pip._vendor should be considered immutable and should only be
updated to versions from upstream.
i(tabsolute_importNcC@sdjt|}y t|ttddWntk
ry t|ttddWntk
ruqXtj|tj|<|jdd\}}t	tj||tj|nXdS(Ns{0}.{1}tlevelit.i(
tformatt__name__t
__import__tglobalstlocalstImportErrortsystmodulestrsplittsetattr(t
modulenamet
vendored_nametbasethead((s8/usr/lib/python2.7/site-packages/pip/_vendor/__init__.pytvendoreds 
 
	s*.whltcachecontroltcoloramatdistlibtdistrothtml5libtlockfiletsixs	six.movesssix.moves.urllibt	packagingspackaging.versionspackaging.specifierst
pkg_resourcestprogresstretryingtrequestssrequests.packagessrequests.packages.urllib3s&requests.packages.urllib3._collectionss$requests.packages.urllib3.connections(requests.packages.urllib3.connectionpools!requests.packages.urllib3.contribs*requests.packages.urllib3.contrib.ntlmpools+requests.packages.urllib3.contrib.pyopenssls$requests.packages.urllib3.exceptionss requests.packages.urllib3.fieldss"requests.packages.urllib3.fileposts"requests.packages.urllib3.packagess/requests.packages.urllib3.packages.ordered_dicts&requests.packages.urllib3.packages.sixs5requests.packages.urllib3.packages.ssl_match_hostnamesErequests.packages.urllib3.packages.ssl_match_hostname._implementations%requests.packages.urllib3.poolmanagers!requests.packages.urllib3.requests"requests.packages.urllib3.responsesrequests.packages.urllib3.utils)requests.packages.urllib3.util.connections&requests.packages.urllib3.util.requests'requests.packages.urllib3.util.responses$requests.packages.urllib3.util.retrys#requests.packages.urllib3.util.ssl_s&requests.packages.urllib3.util.timeouts"requests.packages.urllib3.util.url(t__doc__t
__future__Rtglobtos.pathtosR	tFalset	DEBUNDLEDtpathtabspathtdirnamet__file__t	WHEEL_DIRRtjoin(((s8/usr/lib/python2.7/site-packages/pip/_vendor/__init__.pytsh	)









































_vendor/requests/adapters.pyo000064400000045043152527136320012423 0ustar00
abc@s5dZddlZddlZddlmZmZddlmZddl	m
Zddlm
Z
ddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZm Z ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-m.Z.m/Z/mZmZm0Z0m1Z1ddl2m3Z3yddl4m5Z5Wne6k
rdZ5nXe7Z8dZ9dZ:dZ<de=fdYZ>de>fd YZ?dS(!s
requests.adapters
~~~~~~~~~~~~~~~~~

This module contains the transport adapters that Requests uses to define
and maintain connections.
iN(tPoolManagertproxy_from_url(tHTTPResponse(tTimeout(tRetry(tClosedPoolError(tConnectTimeoutError(t	HTTPError(t
MaxRetryError(tNewConnectionError(t
ProxyError(t
ProtocolError(tReadTimeoutError(tSSLError(t
ResponseErrori(tResponse(turlparset
basestring(tDEFAULT_CA_BUNDLE_PATHtget_encoding_from_headerstprepend_scheme_if_neededtget_auth_from_urlt
urldefragauthtselect_proxy(tCaseInsensitiveDict(textract_cookies_to_jar(tConnectionErrortConnectTimeouttReadTimeoutR
R
t
RetryErrort
InvalidSchema(t_basic_auth_str(tSOCKSProxyManagercOstddS(Ns'Missing dependencies for SOCKS support.(R(targstkwargs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR +si
itBaseAdaptercBs8eZdZdZededddZdZRS(sThe Base Transport AdaptercCstt|jdS(N(tsuperR#t__init__(tself((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR%7scCs
tdS(sCSends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest ` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        N(tNotImplementedError(R&trequesttstreamttimeouttverifytcerttproxies((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytsend:scCs
tdS(s!Cleans up adapter specific items.N(R'(R&((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytcloseLsN(	t__name__t
__module__t__doc__R%tFalsetNonetTrueR.R/(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR#4s
		tHTTPAdaptercBseZdZdddddgZeeeedZdZdZ	ed	Z
d
ZdZdZ
dd
ZdZdZdZdZededddZRS(sThe built-in HTTP Adapter for urllib3.

    Provides a general-case interface for Requests sessions to contact HTTP and
    HTTPS urls by implementing the Transport Adapter interface. This class will
    usually be created by the :class:`Session ` class under the
    covers.

    :param pool_connections: The number of urllib3 connection pools to cache.
    :param pool_maxsize: The maximum number of connections to save in the pool.
    :param max_retries: The maximum number of retries each connection
        should attempt. Note, this applies only to failed DNS lookups, socket
        connections and connection timeouts, never to requests where data has
        made it to the server. By default, Requests does not retry failed
        connections. If you need granular control over the conditions under
        which we retry a request, import urllib3's ``Retry`` class and pass
        that instead.
    :param pool_block: Whether the connection pool should block for connections.

    Usage::

      >>> import requests
      >>> s = requests.Session()
      >>> a = requests.adapters.HTTPAdapter(max_retries=3)
      >>> s.mount('http://', a)
    tmax_retriestconfigt_pool_connectionst
_pool_maxsizet_pool_blockcCs|tkr$tddt|_ntj||_i|_i|_tt|j	||_
||_||_|j
||d|dS(Nitreadtblock(tDEFAULT_RETRIESRR3R7tfrom_intR8t
proxy_managerR$R6R%R9R:R;tinit_poolmanager(R&tpool_connectionstpool_maxsizeR7t
pool_block((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR%ns					cstfdjDS(Nc3s'|]}|t|dfVqdS(N(tgetattrR4(t.0tattr(R&(sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pys	s(tdictt	__attrs__(R&((R&sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyt__getstate__scCsbi|_i|_x*|jD]\}}t|||qW|j|j|jd|jdS(NR=(R@R8titemstsetattrRAR9R:R;(R&tstateRGtvalue((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyt__setstate__s		c
KsF||_||_||_td|d|d|dt||_dS(sInitializes a urllib3 PoolManager.

        This method should not be called from user code, and is only
        exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param connections: The number of urllib3 connection pools to cache.
        :param maxsize: The maximum number of connections to save in the pool.
        :param block: Block when no free connections are available.
        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
        t	num_poolstmaxsizeR=tstrictN(R9R:R;RR5tpoolmanager(R&tconnectionsRQR=tpool_kwargs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyRAs

			c
Ks||jkr|j|}n|jjdrt|\}}t|d|d|d|jd|jd|j|}|j|`.

        :param proxy: The proxy to return a urllib3 ProxyManager for.
        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
        :returns: ProxyManager
        :rtype: urllib3.ProxyManager
        tsockstusernametpasswordRPRQR=t
proxy_headers(
R@tlowert
startswithRR R9R:R;RYR(R&tproxytproxy_kwargstmanagerRWRXRY((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytproxy_manager_fors*				cCs|jjdr|rd	}|tk	r6|}n|sEt}n|s_tjj|rwtdj	|nd|_
tjj|s||_q||_
nd|_
d	|_d	|_
|rt|ts|d|_|d|_n||_d	|_|jrCtjj|jrCtdj	|jn|jrtjj|jrtdj	|jqnd	S(
sAVerify a SSL certificate. This method should not be called from user
        code, and is only exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param conn: The urllib3 connection object associated with the cert.
        :param url: The requested URL.
        :param verify: Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use
        :param cert: The SSL certificate to verify.
        thttpssFCould not find a suitable TLS CA certificate bundle, invalid path: {0}t
CERT_REQUIREDt	CERT_NONEiis:Could not find the TLS certificate file, invalid path: {0}s2Could not find the TLS key file, invalid path: {0}N(RZR[R4R5RtostpathtexiststIOErrortformatt	cert_reqstisdirtca_certstca_cert_dirt
isinstanceRt	cert_filetkey_file(R&tconnturlR+R,tcert_loc((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytcert_verifys8							
				cCst}t|dd|_tt|di|_t|j|_||_|jj	|_	t
|jtr|jj
d|_n|j|_t|j||||_||_|S(sBuilds a :class:`Response ` object from a urllib3
        response. This should not be called from user code, and is only exposed
        for use when subclassing the
        :class:`HTTPAdapter `

        :param req: The :class:`PreparedRequest ` used to generate the response.
        :param resp: The urllib3 response object.
        :rtype: requests.Response
        tstatustheaderssutf-8N(RRER4tstatus_codeRRtRtencodingtrawtreasonRlRptbytestdecodeRtcookiesR(t
connection(R&treqtresptresponse((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytbuild_responses
				cCsst||}|rEt|d}|j|}|j|}n*t|}|j}|jj|}|S(sReturns a urllib3 connection for the given URL. This should not be
        called from user code, and is only exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param url: The URL to connect to.
        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
        :rtype: urllib3.ConnectionPool
        thttp(RRR_tconnection_from_urlRtgeturlRS(R&RpR-R\R@Rotparsed((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytget_connection"s	cCs5|jjx!|jjD]}|jqWdS(sDisposes of any internal state.

        Currently, this closes the PoolManager and any active ProxyManager,
        which closes any pooled connections.
        N(RStclearR@tvalues(R&R\((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR/9s
c	Cst|j|}t|jj}|o3|dk}t}|rit|jj}|jd}n|j}|r|rt|j}n|S(s?Obtain the url to use when making the final request.

        If the message is being sent through a HTTP proxy, the full URL has to
        be used. Otherwise, we should only use the path portion of the URL.

        This should not be called from user code, and is only exposed for use
        when subclassing the
        :class:`HTTPAdapter `.

        :param request: The :class:`PreparedRequest ` being sent.
        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
        :rtype: str
        R`RV(	RRpRtschemeR3RZR[tpath_urlR(	R&R(R-R\Rtis_proxied_http_requesttusing_socks_proxytproxy_schemeRp((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytrequest_urlCs	
cKsdS(s"Add any headers needed by the connection. As of v2.0 this does
        nothing by default, but is left for overriding by users that subclass
        the :class:`HTTPAdapter `.

        This should not be called from user code, and is only exposed for use
        when subclassing the
        :class:`HTTPAdapter `.

        :param request: The :class:`PreparedRequest ` to add headers to.
        :param kwargs: The keyword arguments from the call to send().
        N((R&R(R"((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytadd_headers`scCs8i}t|\}}|r4t|||d`.

        :param proxies: The url of the proxy being used for this request.
        :rtype: dict
        sProxy-Authorization(RR(R&R\RtRWRX((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyRYns
cCs}|j|j|}|j||j|||j||}|j||jdkphd|jk}	t|t	ry%|\}
}t
d|
d|}Wqtk
r}dj|}
t|
qXn't|t
rnt
d|d|}y|	s[|j
d|jd|d|jd|jd	td
tdtdtd
|jd|
}nft|drv|j}n|jdt}y"|j|j|dtx-|jjD]\}}|j||qW|jx^|jD]S}|jtt|djd|jd|j||jdqW|jdy|jdt}Wntk
r|j}nXt j!|d|d|dtdt}Wn|j"nXWnt#t$j%fk
r}
t&|
d|n{t'k
r}t|j(t)r=t|j(t*s=t+|d|q=nt|j(t,rdt-|d|nt|j(t.rt/|d|nt|j(t0rt1|d|nt&|d|nt2k
r}t&|d|nt.k
r	}t/|ndt0t3fk
rl}t|t0rBt1|d|qmt|t4rft5|d|qmnX|j6||S(sSends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest ` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple or urllib3 Timeout object
        :param verify: (optional) Either a boolean, in which case it controls whether
            we verify the server's TLS certificate, or a string, in which case it
            must be a path to a CA bundle to use
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        :rtype: requests.Response
        sContent-LengthtconnectR<ssInvalid timeout {0}. Pass a (connect, read) timeout tuple, or a single float to set both timeouts to the same valuetmethodRptbodyRttredirecttassert_same_hosttpreload_contenttdecode_contenttretriesR*t
proxy_pooltskip_accept_encodingisutf-8s
s0

t	bufferingtpoolR|R(N(7RRpRrRRRR4RtRlttupletTimeoutSaucet
ValueErrorRgturlopenRR3R7thasattrRt	_get_conntDEFAULT_POOL_TIMEOUTt
putrequestR5RKt	putheadert
endheadersR.thextlentencodetgetresponset	TypeErrorRtfrom_httplibR/RtsocketterrorRRRxRR	RRRt_ProxyErrorR
t	_SSLErrorR
Rt
_HTTPErrorRRR(R&R(R)R*R+R,R-RoRptchunkedRR<teterrR~tlow_conntheaderRNtitr((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR.s
						
&





N(R0R1R2RItDEFAULT_POOLSIZER>tDEFAULT_POOLBLOCKR%RJRORAR_RrRR4RR/RRRYR3R5R.(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR6Qs$				%	4	%	
			(@R2tos.pathRcRtpip._vendor.urllib3.poolmanagerRRtpip._vendor.urllib3.responseRtpip._vendor.urllib3.utilRRtpip._vendor.urllib3.util.retryRtpip._vendor.urllib3.exceptionsRRRRRR	R
RRRR
RRtmodelsRtcompatRRtutilsRRRRRRt
structuresRR{Rt
exceptionsRRRRRtauthRt!pip._vendor.urllib3.contrib.socksR tImportErrorR3RRR>R4RtobjectR#R6(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyt	sB.4

_vendor/requests/_internal_utils.py000064400000002110152527136320013620 0ustar00# -*- coding: utf-8 -*-

"""
requests._internal_utils
~~~~~~~~~~~~~~

Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
"""

from .compat import is_py2, builtin_str, str


def to_native_string(string, encoding='ascii'):
    """Given a string object, regardless of type, returns a representation of
    that string in the native string type, encoding and decoding where
    necessary. This assumes ASCII unless told otherwise.
    """
    if isinstance(string, builtin_str):
        out = string
    else:
        if is_py2:
            out = string.encode(encoding)
        else:
            out = string.decode(encoding)

    return out


def unicode_is_ascii(u_string):
    """Determine if unicode string only contains ASCII characters.

    :param str u_string: unicode string to check. Must be unicode
        and not Python 2 `str`.
    :rtype: bool
    """
    assert isinstance(u_string, str)
    try:
        u_string.encode('ascii')
        return True
    except UnicodeEncodeError:
        return False
_vendor/requests/hooks.py000064400000001377152527136320011566 0ustar00# -*- coding: utf-8 -*-

"""
requests.hooks
~~~~~~~~~~~~~~

This module provides the capabilities for the Requests hooks system.

Available hooks:

``response``:
    The response generated from a Request.
"""
HOOKS = ['response']


def default_hooks():
    return dict((event, []) for event in HOOKS)

# TODO: response is the only one


def dispatch_hook(key, hooks, hook_data, **kwargs):
    """Dispatches a hook dictionary on a given piece of data."""
    hooks = hooks or dict()
    hooks = hooks.get(key)
    if hooks:
        if hasattr(hooks, '__call__'):
            hooks = [hooks]
        for hook in hooks:
            _hook_data = hook(hook_data, **kwargs)
            if _hook_data is not None:
                hook_data = _hook_data
    return hook_data
_vendor/requests/exceptions.pyo000064400000015406152527136320013001 0ustar00
abc@sdZddlmZdefdYZdefdYZdefdYZd	efd
YZdefdYZd
efdYZ	dee	fdYZ
de	fdYZdefdYZdefdYZ
deefdYZdeefdYZdeefdYZdeefdYZdefd YZd!eefd"YZd#eefd$YZd%efd&YZd'efd(YZd)efd*YZd+eefd,YZd-efd.YZd/S(0s`
requests.exceptions
~~~~~~~~~~~~~~~~~~~

This module contains the set of Requests' exceptions.
i(t	HTTPErrortRequestExceptioncBseZdZdZRS(sTThere was an ambiguous exception that occurred while handling your
    request.
    cOs|jdd}||_|jdd|_|dk	rg|jrgt|drg|jj|_ntt|j||dS(sBInitialize RequestException with `request` and `response` objects.tresponsetrequestN(tpoptNoneRRthasattrtsuperRt__init__(tselftargstkwargsR((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRs	(t__name__t
__module__t__doc__R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRsRcBseZdZRS(sAn HTTP error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRstConnectionErrorcBseZdZRS(sA Connection error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR st
ProxyErrorcBseZdZRS(sA proxy error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR$stSSLErrorcBseZdZRS(sAn SSL error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR(stTimeoutcBseZdZRS(sThe request timed out.

    Catching this error will catch both
    :exc:`~requests.exceptions.ConnectTimeout` and
    :exc:`~requests.exceptions.ReadTimeout` errors.
    (RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR,stConnectTimeoutcBseZdZRS(sThe request timed out while trying to connect to the remote server.

    Requests that produced this error are safe to retry.
    (RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR5stReadTimeoutcBseZdZRS(s@The server did not send any data in the allotted amount of time.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR<stURLRequiredcBseZdZRS(s*A valid URL is required to make a request.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR@stTooManyRedirectscBseZdZRS(sToo many redirects.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRDst
MissingSchemacBseZdZRS(s/The URL schema (e.g. http or https) is missing.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRHst
InvalidSchemacBseZdZRS(s"See defaults.py for valid schemas.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRLst
InvalidURLcBseZdZRS(s%The URL provided was somehow invalid.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRPst
InvalidHeadercBseZdZRS(s.The header value provided was somehow invalid.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRTstChunkedEncodingErrorcBseZdZRS(s?The server declared chunked encoding but sent an invalid chunk.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRXstContentDecodingErrorcBseZdZRS(s!Failed to decode response content(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR\stStreamConsumedErrorcBseZdZRS(s2The content for this response was already consumed(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR`st
RetryErrorcBseZdZRS(sCustom retries logic failed(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRdstUnrewindableBodyErrorcBseZdZRS(s:Requests encountered an error when trying to rewind a body(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRhstRequestsWarningcBseZdZRS(sBase warning for Requests.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR nstFileModeWarningcBseZdZRS(sJA file was opened in text mode, but Requests determined its binary length.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR!sstRequestsDependencyWarningcBseZdZRS(s@An imported dependency doesn't match the expected version range.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR"xsN(Rtpip._vendor.urllib3.exceptionsRt
BaseHTTPErrortIOErrorRRRRRRRRRt
ValueErrorRRRRRRt	TypeErrorRRRtWarningR tDeprecationWarningR!R"(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyts.	_vendor/requests/hooks.pyc000064400000002323152527136320011721 0ustar00
abc@s%dZdgZdZdZdS(s
requests.hooks
~~~~~~~~~~~~~~

This module provides the capabilities for the Requests hooks system.

Available hooks:

``response``:
    The response generated from a Request.
tresponsecCstdtDS(Ncss|]}|gfVqdS(N((t.0tevent((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pys	s(tdicttHOOKS(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pyt
default_hooksscKs{|pt}|j|}|rwt|dr?|g}nx5|D]*}|||}|dk	rF|}qFqFWn|S(s6Dispatches a hook dictionary on a given piece of data.t__call__N(RtgetthasattrtNone(tkeythookst	hook_datatkwargsthookt
_hook_data((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pyt
dispatch_hooks
N(t__doc__RRR(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pyt
s		_vendor/requests/help.py000064400000007123152527136320011366 0ustar00"""Module containing bug report helper(s)."""
from __future__ import print_function

import json
import platform
import sys
import ssl

from pip._vendor import idna
from pip._vendor import urllib3
from pip._vendor import chardet

from . import __version__ as requests_version

try:
    from .packages.urllib3.contrib import pyopenssl
except ImportError:
    pyopenssl = None
    OpenSSL = None
    cryptography = None
else:
    import OpenSSL
    import cryptography


def _implementation():
    """Return a dict with the Python implementation and version.

    Provide both the name and the version of the Python implementation
    currently running. For example, on CPython 2.7.5 it will return
    {'name': 'CPython', 'version': '2.7.5'}.

    This function works best on CPython and PyPy: in particular, it probably
    doesn't work for Jython or IronPython. Future investigation should be done
    to work out the correct shape of the code for those platforms.
    """
    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'

    return {'name': implementation, 'version': implementation_version}


def info():
    """Generate information for a bug report."""
    try:
        platform_info = {
            'system': platform.system(),
            'release': platform.release(),
        }
    except IOError:
        platform_info = {
            'system': 'Unknown',
            'release': 'Unknown',
        }

    implementation_info = _implementation()
    urllib3_info = {'version': urllib3.__version__}
    chardet_info = {'version': chardet.__version__}

    pyopenssl_info = {
        'version': None,
        'openssl_version': '',
    }
    if OpenSSL:
        pyopenssl_info = {
            'version': OpenSSL.__version__,
            'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER,
        }
    cryptography_info = {
        'version': getattr(cryptography, '__version__', ''),
    }
    idna_info = {
        'version': getattr(idna, '__version__', ''),
    }

    # OPENSSL_VERSION_NUMBER doesn't exist in the Python 2.6 ssl module.
    system_ssl = getattr(ssl, 'OPENSSL_VERSION_NUMBER', None)
    system_ssl_info = {
        'version': '%x' % system_ssl if system_ssl is not None else ''
    }

    return {
        'platform': platform_info,
        'implementation': implementation_info,
        'system_ssl': system_ssl_info,
        'using_pyopenssl': pyopenssl is not None,
        'pyOpenSSL': pyopenssl_info,
        'urllib3': urllib3_info,
        'chardet': chardet_info,
        'cryptography': cryptography_info,
        'idna': idna_info,
        'requests': {
            'version': requests_version,
        },
    }


def main():
    """Pretty-print the bug information as JSON."""
    print(json.dumps(info(), sort_keys=True, indent=2))


if __name__ == '__main__':
    main()
_vendor/requests/__version__.pyo000064400000001113152527136320013067 0ustar00
abc@s@dZdZdZdZdZdZdZdZdZd	Z	d
S(trequestssPython HTTP for Humans.shttp://python-requests.orgs2.18.4is
Kenneth Reitzsme@kennethreitz.orgs
Apache 2.0sCopyright 2017 Kenneth Reitzu✨ 🍰 ✨N(
t	__title__t__description__t__url__t__version__t	__build__t
__author__t__author_email__t__license__t
__copyright__t__cake__(((sD/usr/lib/python2.7/site-packages/pip/_vendor/requests/__version__.pyts_vendor/requests/compat.pyc000064400000003465152527136320012071 0ustar00
abc@s5dZddlmZddlZejZeddkZeddkZddlZerGddl	m
Z
mZmZm
Z
mZmZmZmZmZddlmZmZmZmZmZdd	lmZddlZdd
lmZddlmZddlmZe Z!e Z"e#Z e$Z$e%e&e'fZ(e%e&fZ)ner1dd
l*mZmZmZmZmZm
Z
mZmZm
Z
mZddl+mZmZmZmZmZddl,m-Zdd
l.mZddl/mZddl0mZe Z!e Z e"Z"e e"fZ$e%e'fZ(e%fZ)ndS(sq
requests.compat
~~~~~~~~~~~~~~~

This module handles import compatibility issues between Python 2 and
Python 3.
i(tchardetNiii(	tquotetunquotet
quote_plustunquote_plust	urlencodet
getproxiestproxy_bypasstproxy_bypass_environmenttgetproxies_environment(turlparset
urlunparseturljointurlsplitt	urldefrag(tparse_http_list(tMorsel(tStringIO(tOrderedDict(
R
RRR
RRRRRR(RRRRR	(t	cookiejar(1t__doc__tpip._vendorRtsystversion_infot_vertis_py2tis_py3tjsonturllibRRRRRRRRR	R
RRR
Rturllib2Rt	cookielibtCookieRRt)pip._vendor.urllib3.packages.ordered_dictRtstrtbuiltin_strtbytestunicodet
basestringtinttlongtfloatt
numeric_typest
integer_typesturllib.parseturllib.requestthttpRthttp.cookiestiotcollections(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/compat.pyt	sB	@(F(_vendor/requests/structures.pyc000064400000012453152527136320013026 0ustar00
abc@sUdZddlZddlmZdejfdYZdefdYZdS(	sO
requests.structures
~~~~~~~~~~~~~~~~~~~

Data structures that power Requests.
iNi(tOrderedDicttCaseInsensitiveDictcBskeZdZddZdZdZdZdZdZ	dZ
dZd	Zd
Z
RS(sA case-insensitive ``dict``-like object.

    Implements all methods and operations of
    ``collections.MutableMapping`` as well as dict's ``copy``. Also
    provides ``lower_items``.

    All keys are expected to be strings. The structure remembers the
    case of the last key to be set, and ``iter(instance)``,
    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
    will contain case-sensitive keys. However, querying and contains
    testing is case insensitive::

        cid = CaseInsensitiveDict()
        cid['Accept'] = 'application/json'
        cid['aCCEPT'] == 'application/json'  # True
        list(cid) == ['Accept']  # True

    For example, ``headers['content-encoding']`` will return the
    value of a ``'Content-Encoding'`` response header, regardless
    of how the header name was originally stored.

    If the constructor, ``.update``, or equality comparison
    operations are given keys that have equal ``.lower()``s, the
    behavior is undefined.
    cKs5t|_|dkr!i}n|j||dS(N(Rt_storetNonetupdate(tselftdatatkwargs((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__init__*s	cCs||f|j|j<s(Rtvalues(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__iter__;scCs
t|jS(N(tlenR(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__len__>scCsd|jjDS(s.Like iteritems(), but with all lowercase keys.css%|]\}}||dfVqdS(iN((Rtlowerkeytkeyval((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pys	Ds(Rtitems(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pytlower_itemsAscCsGt|tjr!t|}ntSt|jt|jkS(N(t
isinstancetcollectionstMappingRtNotImplementedtdictR(Rtother((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__eq__IscCst|jjS(N(RRR(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pytcopyRscCstt|jS(N(tstrRR(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__repr__UsN(t__name__t
__module__t__doc__RRRR
RRRRR R!R#(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyRs									t
LookupDictcBs8eZdZddZdZdZddZRS(sDictionary lookup object.cCs ||_tt|jdS(N(tnametsuperR'R(RR(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR\s	cCsd|jS(Ns
(R((R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR#`scCs|jj|dS(N(t__dict__tgetR(RR
((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR
cscCs|jj||S(N(R*R+(RR
tdefault((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR+hsN(R$R%R&RRR#R
R+(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR'Ys
		(R&RtcompatRtMutableMappingRRR'(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pytsJ_vendor/requests/api.pyo000064400000015624152527136320011373 0ustar00
abc@sqdZddlmZdZddZdZdZdddZddZ	dd	Z
d
ZdS(s
requests.api
~~~~~~~~~~~~

This module implements the Requests API.

:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
i(tsessionsc
Ks2tj }|jd|d||SWdQXdS(s	Constructs and sends a :class:`Request `.

    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) ` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response ` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      
    tmethodturlN(RtSessiontrequest(RRtkwargstsession((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRs)cKs&|jdttd|d||S(sOSends a GET request.

    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tallow_redirectstgettparams(t
setdefaulttTrueR(RR	R((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyR=s
cKs |jdttd||S(sSends an OPTIONS request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    Rtoptions(R
RR(RR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRKs	cKs |jdttd||S(sSends a HEAD request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    Rthead(R
tFalseR(RR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyR
Xs	cKstd|d|d||S(sSends a POST request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tposttdatatjson(R(RRRR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRescKstd|d||S(sSends a PUT request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tputR(R(RRR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRsscKstd|d||S(sSends a PATCH request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tpatchR(R(RRR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRscKstd||S(sSends a DELETE request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tdelete(R(RR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRs	N(t__doc__tRRtNoneRRR
RRRR(((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyts	-	
	
_vendor/requests/cookies.pyo000064400000053604152527136320012256 0ustar00
abc@sQdZddlZddlZddlZddlZddlmZddlmZm	Z	m
Z
mZyddlZWne
k
rddlZnXdefdYZdefd	YZd
ZdZdddZd
efdYZdejejfdYZdZdZdZdedZdZ dS(s
requests.cookies
~~~~~~~~~~~~~~~~

Compatibility code to be able to use `cookielib.CookieJar` with requests.

requests.utils imports from here, so be careful with imports.
iNi(tto_native_string(t	cookielibturlparset
urlunparsetMorseltMockRequestcBseZdZdZdZdZdZdZdZdZ	ddZd	Zd
Z
dZedZed
ZedZRS(sWraps a `requests.Request` to mimic a `urllib2.Request`.

    The code in `cookielib.CookieJar` expects this interface in order to correctly
    manage cookie policies, i.e., determine whether a cookie can be set, given the
    domains of the request and the cookie.

    The original request object is read-only. The client is responsible for collecting
    the new headers via `get_new_headers()` and interpreting them appropriately. You
    probably want `get_cookie_header`, defined below.
    cCs.||_i|_t|jjj|_dS(N(t_rt_new_headersRturltschemettype(tselftrequest((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt__init__&s		cCs|jS(N(R
(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_type+scCst|jjjS(N(RRRtnetloc(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_host.scCs
|jS(N(R(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_origin_req_host1scCsx|jjjds|jjSt|jjddd}t|jj}t|j||j|j	|j
|jgS(NtHosttencodingsutf-8(RtheaderstgetRRRRR	tpathtparamstquerytfragment(Rthosttparsed((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_full_url4s
cCstS(N(tTrue(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytis_unverifiableBscCs||jjkp||jkS(N(RRR(Rtname((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
has_headerEscCs%|jjj||jj||S(N(RRRR(RRtdefault((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
get_headerHscCstddS(sMcookielib has no legitimate use for this method; add it back if you find one.s=Cookie headers should be added with add_unredirected_header()N(tNotImplementedError(Rtkeytval((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
add_headerKscCs||j|(RR'RQtresulttbadargsterr((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyROs0
	
cCs!d}|dr_y$ttjt|d}Wqtk
r[td|dqXn2|drd}tjtj|d|}ntd|ddt	|ddt
d|dd|d	|jd
|d
dddi|d
d6dt
dt	|dd|jd|dpd
S(sBConvert a Morsel object into a Cookie containing the one k/v pair.smax-agesmax-age: %s must be integerRs%a, %d-%b-%Y %H:%M:%S GMTRRRRBRRRRthttponlyRRRR'RiN(
R/tintttimet
ValueErrorRtcalendarttimegmtstrptimeRORR`R$R'(tmorselRt
time_template((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyRNs0
$



	
	cCs|dkrt}n|dk	rg|D]}|j^q+}x@|D]5}|s_||krG|jt|||qGqGWn|S(s-Returns a CookieJar from a key/value dictionary.

    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :param cookiejar: (optional) A cookiejar to add the cookies to.
    :param overwrite: (optional) If False, will not replace cookies
        already in the jar with new ones.
    N(R/RJRRPRO(tcookie_dictREt	overwriteRGtnames_from_jarR((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytcookiejar_from_dicts
$cCst|tjs!tdnt|trKt|d|dt}nXt|tjry|j|Wqtk
rx|D]}|j	|qWqXn|S(sAdd cookies to cookiejar and returns a merged CookieJar.

    :param cookiejar: CookieJar object to add the cookies to.
    :param cookies: Dictionary or CookieJar object to be added.
    s!You can only merge into CookieJarRER(
RMRRoRRRR`RqtAttributeErrorRP(REtcookiest
cookie_in_jar((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
merge_cookiess

(!R.RpRRtcollectionst_internal_utilsRtcompatRRRRRztImportErrortdummy_threadingtobjectRR1R=RAR/RHtRuntimeErrorRIRotMutableMappingRJRRORNRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
s,"
H				#	_vendor/requests/api.pyc000064400000015624152527136320011357 0ustar00
abc@sqdZddlmZdZddZdZdZdddZddZ	dd	Z
d
ZdS(s
requests.api
~~~~~~~~~~~~

This module implements the Requests API.

:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
i(tsessionsc
Ks2tj }|jd|d||SWdQXdS(s	Constructs and sends a :class:`Request `.

    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) ` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response ` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      
    tmethodturlN(RtSessiontrequest(RRtkwargstsession((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRs)cKs&|jdttd|d||S(sOSends a GET request.

    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tallow_redirectstgettparams(t
setdefaulttTrueR(RR	R((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyR=s
cKs |jdttd||S(sSends an OPTIONS request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    Rtoptions(R
RR(RR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRKs	cKs |jdttd||S(sSends a HEAD request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    Rthead(R
tFalseR(RR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyR
Xs	cKstd|d|d||S(sSends a POST request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tposttdatatjson(R(RRRR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRescKstd|d||S(sSends a PUT request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tputR(R(RRR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRsscKstd|d||S(sSends a PATCH request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tpatchR(R(RRR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRscKstd||S(sSends a DELETE request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    tdelete(R(RR((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyRs	N(t__doc__tRRtNoneRRR
RRRR(((s</usr/lib/python2.7/site-packages/pip/_vendor/requests/api.pyts	-	
	
_vendor/requests/certs.pyo000064400000001152152527136320011731 0ustar00
abc@s1dZddlmZedkr-eGHndS(sF
requests.certs
~~~~~~~~~~~~~~

This module returns the preferred default CA certificate bundle. There is
only one — the one from the certifi package.

If you are packaging Requests, e.g., for a Linux distribution or a managed
environment, you can change the definition of where() to return a separately
packaged CA bundle.
i(twheret__main__N(t__doc__tpip._vendor.certifiRt__name__(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/certs.pyts_vendor/requests/exceptions.pyc000064400000015406152527136320012765 0ustar00
abc@sdZddlmZdefdYZdefdYZdefdYZd	efd
YZdefdYZd
efdYZ	dee	fdYZ
de	fdYZdefdYZdefdYZ
deefdYZdeefdYZdeefdYZdeefdYZdefd YZd!eefd"YZd#eefd$YZd%efd&YZd'efd(YZd)efd*YZd+eefd,YZd-efd.YZd/S(0s`
requests.exceptions
~~~~~~~~~~~~~~~~~~~

This module contains the set of Requests' exceptions.
i(t	HTTPErrortRequestExceptioncBseZdZdZRS(sTThere was an ambiguous exception that occurred while handling your
    request.
    cOs|jdd}||_|jdd|_|dk	rg|jrgt|drg|jj|_ntt|j||dS(sBInitialize RequestException with `request` and `response` objects.tresponsetrequestN(tpoptNoneRRthasattrtsuperRt__init__(tselftargstkwargsR((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRs	(t__name__t
__module__t__doc__R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRsRcBseZdZRS(sAn HTTP error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRstConnectionErrorcBseZdZRS(sA Connection error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR st
ProxyErrorcBseZdZRS(sA proxy error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR$stSSLErrorcBseZdZRS(sAn SSL error occurred.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR(stTimeoutcBseZdZRS(sThe request timed out.

    Catching this error will catch both
    :exc:`~requests.exceptions.ConnectTimeout` and
    :exc:`~requests.exceptions.ReadTimeout` errors.
    (RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR,stConnectTimeoutcBseZdZRS(sThe request timed out while trying to connect to the remote server.

    Requests that produced this error are safe to retry.
    (RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR5stReadTimeoutcBseZdZRS(s@The server did not send any data in the allotted amount of time.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR<stURLRequiredcBseZdZRS(s*A valid URL is required to make a request.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR@stTooManyRedirectscBseZdZRS(sToo many redirects.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRDst
MissingSchemacBseZdZRS(s/The URL schema (e.g. http or https) is missing.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRHst
InvalidSchemacBseZdZRS(s"See defaults.py for valid schemas.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRLst
InvalidURLcBseZdZRS(s%The URL provided was somehow invalid.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRPst
InvalidHeadercBseZdZRS(s.The header value provided was somehow invalid.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRTstChunkedEncodingErrorcBseZdZRS(s?The server declared chunked encoding but sent an invalid chunk.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRXstContentDecodingErrorcBseZdZRS(s!Failed to decode response content(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR\stStreamConsumedErrorcBseZdZRS(s2The content for this response was already consumed(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR`st
RetryErrorcBseZdZRS(sCustom retries logic failed(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRdstUnrewindableBodyErrorcBseZdZRS(s:Requests encountered an error when trying to rewind a body(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyRhstRequestsWarningcBseZdZRS(sBase warning for Requests.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR nstFileModeWarningcBseZdZRS(sJA file was opened in text mode, but Requests determined its binary length.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR!sstRequestsDependencyWarningcBseZdZRS(s@An imported dependency doesn't match the expected version range.(RR
R(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyR"xsN(Rtpip._vendor.urllib3.exceptionsRt
BaseHTTPErrortIOErrorRRRRRRRRRt
ValueErrorRRRRRRt	TypeErrorRRRtWarningR tDeprecationWarningR!R"(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/exceptions.pyts.	_vendor/requests/adapters.py000064400000051030152527136320012235 0ustar00# -*- coding: utf-8 -*-

"""
requests.adapters
~~~~~~~~~~~~~~~~~

This module contains the transport adapters that Requests uses to define
and maintain connections.
"""

import os.path
import socket

from pip._vendor.urllib3.poolmanager import PoolManager, proxy_from_url
from pip._vendor.urllib3.response import HTTPResponse
from pip._vendor.urllib3.util import Timeout as TimeoutSauce
from pip._vendor.urllib3.util.retry import Retry
from pip._vendor.urllib3.exceptions import ClosedPoolError
from pip._vendor.urllib3.exceptions import ConnectTimeoutError
from pip._vendor.urllib3.exceptions import HTTPError as _HTTPError
from pip._vendor.urllib3.exceptions import MaxRetryError
from pip._vendor.urllib3.exceptions import NewConnectionError
from pip._vendor.urllib3.exceptions import ProxyError as _ProxyError
from pip._vendor.urllib3.exceptions import ProtocolError
from pip._vendor.urllib3.exceptions import ReadTimeoutError
from pip._vendor.urllib3.exceptions import SSLError as _SSLError
from pip._vendor.urllib3.exceptions import ResponseError

from .models import Response
from .compat import urlparse, basestring
from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,
                    prepend_scheme_if_needed, get_auth_from_url, urldefragauth,
                    select_proxy)
from .structures import CaseInsensitiveDict
from .cookies import extract_cookies_to_jar
from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
                         ProxyError, RetryError, InvalidSchema)
from .auth import _basic_auth_str

try:
    from pip._vendor.urllib3.contrib.socks import SOCKSProxyManager
except ImportError:
    def SOCKSProxyManager(*args, **kwargs):
        raise InvalidSchema("Missing dependencies for SOCKS support.")

DEFAULT_POOLBLOCK = False
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0
DEFAULT_POOL_TIMEOUT = None


class BaseAdapter(object):
    """The Base Transport Adapter"""

    def __init__(self):
        super(BaseAdapter, self).__init__()

    def send(self, request, stream=False, timeout=None, verify=True,
             cert=None, proxies=None):
        """Sends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest ` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        """
        raise NotImplementedError

    def close(self):
        """Cleans up adapter specific items."""
        raise NotImplementedError


class HTTPAdapter(BaseAdapter):
    """The built-in HTTP Adapter for urllib3.

    Provides a general-case interface for Requests sessions to contact HTTP and
    HTTPS urls by implementing the Transport Adapter interface. This class will
    usually be created by the :class:`Session ` class under the
    covers.

    :param pool_connections: The number of urllib3 connection pools to cache.
    :param pool_maxsize: The maximum number of connections to save in the pool.
    :param max_retries: The maximum number of retries each connection
        should attempt. Note, this applies only to failed DNS lookups, socket
        connections and connection timeouts, never to requests where data has
        made it to the server. By default, Requests does not retry failed
        connections. If you need granular control over the conditions under
        which we retry a request, import urllib3's ``Retry`` class and pass
        that instead.
    :param pool_block: Whether the connection pool should block for connections.

    Usage::

      >>> import requests
      >>> s = requests.Session()
      >>> a = requests.adapters.HTTPAdapter(max_retries=3)
      >>> s.mount('http://', a)
    """
    __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',
                 '_pool_block']

    def __init__(self, pool_connections=DEFAULT_POOLSIZE,
                 pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
                 pool_block=DEFAULT_POOLBLOCK):
        if max_retries == DEFAULT_RETRIES:
            self.max_retries = Retry(0, read=False)
        else:
            self.max_retries = Retry.from_int(max_retries)
        self.config = {}
        self.proxy_manager = {}

        super(HTTPAdapter, self).__init__()

        self._pool_connections = pool_connections
        self._pool_maxsize = pool_maxsize
        self._pool_block = pool_block

        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)

    def __getstate__(self):
        return dict((attr, getattr(self, attr, None)) for attr in
                    self.__attrs__)

    def __setstate__(self, state):
        # Can't handle by adding 'proxy_manager' to self.__attrs__ because
        # self.poolmanager uses a lambda function, which isn't pickleable.
        self.proxy_manager = {}
        self.config = {}

        for attr, value in state.items():
            setattr(self, attr, value)

        self.init_poolmanager(self._pool_connections, self._pool_maxsize,
                              block=self._pool_block)

    def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
        """Initializes a urllib3 PoolManager.

        This method should not be called from user code, and is only
        exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param connections: The number of urllib3 connection pools to cache.
        :param maxsize: The maximum number of connections to save in the pool.
        :param block: Block when no free connections are available.
        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
        """
        # save these values for pickling
        self._pool_connections = connections
        self._pool_maxsize = maxsize
        self._pool_block = block

        self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
                                       block=block, strict=True, **pool_kwargs)

    def proxy_manager_for(self, proxy, **proxy_kwargs):
        """Return urllib3 ProxyManager for the given proxy.

        This method should not be called from user code, and is only
        exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param proxy: The proxy to return a urllib3 ProxyManager for.
        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
        :returns: ProxyManager
        :rtype: urllib3.ProxyManager
        """
        if proxy in self.proxy_manager:
            manager = self.proxy_manager[proxy]
        elif proxy.lower().startswith('socks'):
            username, password = get_auth_from_url(proxy)
            manager = self.proxy_manager[proxy] = SOCKSProxyManager(
                proxy,
                username=username,
                password=password,
                num_pools=self._pool_connections,
                maxsize=self._pool_maxsize,
                block=self._pool_block,
                **proxy_kwargs
            )
        else:
            proxy_headers = self.proxy_headers(proxy)
            manager = self.proxy_manager[proxy] = proxy_from_url(
                proxy,
                proxy_headers=proxy_headers,
                num_pools=self._pool_connections,
                maxsize=self._pool_maxsize,
                block=self._pool_block,
                **proxy_kwargs)

        return manager

    def cert_verify(self, conn, url, verify, cert):
        """Verify a SSL certificate. This method should not be called from user
        code, and is only exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param conn: The urllib3 connection object associated with the cert.
        :param url: The requested URL.
        :param verify: Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use
        :param cert: The SSL certificate to verify.
        """
        if url.lower().startswith('https') and verify:

            cert_loc = None

            # Allow self-specified cert location.
            if verify is not True:
                cert_loc = verify

            if not cert_loc:
                cert_loc = DEFAULT_CA_BUNDLE_PATH

            if not cert_loc or not os.path.exists(cert_loc):
                raise IOError("Could not find a suitable TLS CA certificate bundle, "
                              "invalid path: {0}".format(cert_loc))

            conn.cert_reqs = 'CERT_REQUIRED'

            if not os.path.isdir(cert_loc):
                conn.ca_certs = cert_loc
            else:
                conn.ca_cert_dir = cert_loc
        else:
            conn.cert_reqs = 'CERT_NONE'
            conn.ca_certs = None
            conn.ca_cert_dir = None

        if cert:
            if not isinstance(cert, basestring):
                conn.cert_file = cert[0]
                conn.key_file = cert[1]
            else:
                conn.cert_file = cert
                conn.key_file = None
            if conn.cert_file and not os.path.exists(conn.cert_file):
                raise IOError("Could not find the TLS certificate file, "
                              "invalid path: {0}".format(conn.cert_file))
            if conn.key_file and not os.path.exists(conn.key_file):
                raise IOError("Could not find the TLS key file, "
                              "invalid path: {0}".format(conn.key_file))

    def build_response(self, req, resp):
        """Builds a :class:`Response ` object from a urllib3
        response. This should not be called from user code, and is only exposed
        for use when subclassing the
        :class:`HTTPAdapter `

        :param req: The :class:`PreparedRequest ` used to generate the response.
        :param resp: The urllib3 response object.
        :rtype: requests.Response
        """
        response = Response()

        # Fallback to None if there's no status_code, for whatever reason.
        response.status_code = getattr(resp, 'status', None)

        # Make headers case-insensitive.
        response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))

        # Set encoding.
        response.encoding = get_encoding_from_headers(response.headers)
        response.raw = resp
        response.reason = response.raw.reason

        if isinstance(req.url, bytes):
            response.url = req.url.decode('utf-8')
        else:
            response.url = req.url

        # Add new cookies from the server.
        extract_cookies_to_jar(response.cookies, req, resp)

        # Give the Response some context.
        response.request = req
        response.connection = self

        return response

    def get_connection(self, url, proxies=None):
        """Returns a urllib3 connection for the given URL. This should not be
        called from user code, and is only exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param url: The URL to connect to.
        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
        :rtype: urllib3.ConnectionPool
        """
        proxy = select_proxy(url, proxies)

        if proxy:
            proxy = prepend_scheme_if_needed(proxy, 'http')
            proxy_manager = self.proxy_manager_for(proxy)
            conn = proxy_manager.connection_from_url(url)
        else:
            # Only scheme should be lower case
            parsed = urlparse(url)
            url = parsed.geturl()
            conn = self.poolmanager.connection_from_url(url)

        return conn

    def close(self):
        """Disposes of any internal state.

        Currently, this closes the PoolManager and any active ProxyManager,
        which closes any pooled connections.
        """
        self.poolmanager.clear()
        for proxy in self.proxy_manager.values():
            proxy.clear()

    def request_url(self, request, proxies):
        """Obtain the url to use when making the final request.

        If the message is being sent through a HTTP proxy, the full URL has to
        be used. Otherwise, we should only use the path portion of the URL.

        This should not be called from user code, and is only exposed for use
        when subclassing the
        :class:`HTTPAdapter `.

        :param request: The :class:`PreparedRequest ` being sent.
        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
        :rtype: str
        """
        proxy = select_proxy(request.url, proxies)
        scheme = urlparse(request.url).scheme

        is_proxied_http_request = (proxy and scheme != 'https')
        using_socks_proxy = False
        if proxy:
            proxy_scheme = urlparse(proxy).scheme.lower()
            using_socks_proxy = proxy_scheme.startswith('socks')

        url = request.path_url
        if is_proxied_http_request and not using_socks_proxy:
            url = urldefragauth(request.url)

        return url

    def add_headers(self, request, **kwargs):
        """Add any headers needed by the connection. As of v2.0 this does
        nothing by default, but is left for overriding by users that subclass
        the :class:`HTTPAdapter `.

        This should not be called from user code, and is only exposed for use
        when subclassing the
        :class:`HTTPAdapter `.

        :param request: The :class:`PreparedRequest ` to add headers to.
        :param kwargs: The keyword arguments from the call to send().
        """
        pass

    def proxy_headers(self, proxy):
        """Returns a dictionary of the headers to add to any request sent
        through a proxy. This works with urllib3 magic to ensure that they are
        correctly sent to the proxy, rather than in a tunnelled request if
        CONNECT is being used.

        This should not be called from user code, and is only exposed for use
        when subclassing the
        :class:`HTTPAdapter `.

        :param proxies: The url of the proxy being used for this request.
        :rtype: dict
        """
        headers = {}
        username, password = get_auth_from_url(proxy)

        if username:
            headers['Proxy-Authorization'] = _basic_auth_str(username,
                                                             password)

        return headers

    def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
        """Sends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest ` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple or urllib3 Timeout object
        :param verify: (optional) Either a boolean, in which case it controls whether
            we verify the server's TLS certificate, or a string, in which case it
            must be a path to a CA bundle to use
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        :rtype: requests.Response
        """

        conn = self.get_connection(request.url, proxies)

        self.cert_verify(conn, request.url, verify, cert)
        url = self.request_url(request, proxies)
        self.add_headers(request)

        chunked = not (request.body is None or 'Content-Length' in request.headers)

        if isinstance(timeout, tuple):
            try:
                connect, read = timeout
                timeout = TimeoutSauce(connect=connect, read=read)
            except ValueError as e:
                # this may raise a string formatting error.
                err = ("Invalid timeout {0}. Pass a (connect, read) "
                       "timeout tuple, or a single float to set "
                       "both timeouts to the same value".format(timeout))
                raise ValueError(err)
        elif isinstance(timeout, TimeoutSauce):
            pass
        else:
            timeout = TimeoutSauce(connect=timeout, read=timeout)

        try:
            if not chunked:
                resp = conn.urlopen(
                    method=request.method,
                    url=url,
                    body=request.body,
                    headers=request.headers,
                    redirect=False,
                    assert_same_host=False,
                    preload_content=False,
                    decode_content=False,
                    retries=self.max_retries,
                    timeout=timeout
                )

            # Send the request.
            else:
                if hasattr(conn, 'proxy_pool'):
                    conn = conn.proxy_pool

                low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)

                try:
                    low_conn.putrequest(request.method,
                                        url,
                                        skip_accept_encoding=True)

                    for header, value in request.headers.items():
                        low_conn.putheader(header, value)

                    low_conn.endheaders()

                    for i in request.body:
                        low_conn.send(hex(len(i))[2:].encode('utf-8'))
                        low_conn.send(b'\r\n')
                        low_conn.send(i)
                        low_conn.send(b'\r\n')
                    low_conn.send(b'0\r\n\r\n')

                    # Receive the response from the server
                    try:
                        # For Python 2.7+ versions, use buffering of HTTP
                        # responses
                        r = low_conn.getresponse(buffering=True)
                    except TypeError:
                        # For compatibility with Python 2.6 versions and back
                        r = low_conn.getresponse()

                    resp = HTTPResponse.from_httplib(
                        r,
                        pool=conn,
                        connection=low_conn,
                        preload_content=False,
                        decode_content=False
                    )
                except:
                    # If we hit any problems here, clean up the connection.
                    # Then, reraise so that we can handle the actual exception.
                    low_conn.close()
                    raise

        except (ProtocolError, socket.error) as err:
            raise ConnectionError(err, request=request)

        except MaxRetryError as e:
            if isinstance(e.reason, ConnectTimeoutError):
                # TODO: Remove this in 3.0.0: see #2811
                if not isinstance(e.reason, NewConnectionError):
                    raise ConnectTimeout(e, request=request)

            if isinstance(e.reason, ResponseError):
                raise RetryError(e, request=request)

            if isinstance(e.reason, _ProxyError):
                raise ProxyError(e, request=request)

            if isinstance(e.reason, _SSLError):
                # This branch is for urllib3 v1.22 and later.
                raise SSLError(e, request=request)

            raise ConnectionError(e, request=request)

        except ClosedPoolError as e:
            raise ConnectionError(e, request=request)

        except _ProxyError as e:
            raise ProxyError(e)

        except (_SSLError, _HTTPError) as e:
            if isinstance(e, _SSLError):
                # This branch is for urllib3 versions earlier than v1.22
                raise SSLError(e, request=request)
            elif isinstance(e, ReadTimeoutError):
                raise ReadTimeout(e, request=request)
            else:
                raise

        return self.build_response(request, resp)
_vendor/requests/cookies.pyc000064400000053604152527136320012242 0ustar00
abc@sQdZddlZddlZddlZddlZddlmZddlmZm	Z	m
Z
mZyddlZWne
k
rddlZnXdefdYZdefd	YZd
ZdZdddZd
efdYZdejejfdYZdZdZdZdedZdZ dS(s
requests.cookies
~~~~~~~~~~~~~~~~

Compatibility code to be able to use `cookielib.CookieJar` with requests.

requests.utils imports from here, so be careful with imports.
iNi(tto_native_string(t	cookielibturlparset
urlunparsetMorseltMockRequestcBseZdZdZdZdZdZdZdZdZ	ddZd	Zd
Z
dZedZed
ZedZRS(sWraps a `requests.Request` to mimic a `urllib2.Request`.

    The code in `cookielib.CookieJar` expects this interface in order to correctly
    manage cookie policies, i.e., determine whether a cookie can be set, given the
    domains of the request and the cookie.

    The original request object is read-only. The client is responsible for collecting
    the new headers via `get_new_headers()` and interpreting them appropriately. You
    probably want `get_cookie_header`, defined below.
    cCs.||_i|_t|jjj|_dS(N(t_rt_new_headersRturltschemettype(tselftrequest((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt__init__&s		cCs|jS(N(R
(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_type+scCst|jjjS(N(RRRtnetloc(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_host.scCs
|jS(N(R(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_origin_req_host1scCsx|jjjds|jjSt|jjddd}t|jj}t|j||j|j	|j
|jgS(NtHosttencodingsutf-8(RtheaderstgetRRRRR	tpathtparamstquerytfragment(Rthosttparsed((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytget_full_url4s
cCstS(N(tTrue(R((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytis_unverifiableBscCs||jjkp||jkS(N(RRR(Rtname((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
has_headerEscCs%|jjj||jj||S(N(RRRR(RRtdefault((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
get_headerHscCstddS(sMcookielib has no legitimate use for this method; add it back if you find one.s=Cookie headers should be added with add_unredirected_header()N(tNotImplementedError(Rtkeytval((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
add_headerKscCs||j|(RR'RQtresulttbadargsterr((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyROs0
	
cCs!d}|dr_y$ttjt|d}Wqtk
r[td|dqXn2|drd}tjtj|d|}ntd|ddt	|ddt
d|dd|d	|jd
|d
dddi|d
d6dt
dt	|dd|jd|dpd
S(sBConvert a Morsel object into a Cookie containing the one k/v pair.smax-agesmax-age: %s must be integerRs%a, %d-%b-%Y %H:%M:%S GMTRRRRBRRRRthttponlyRRRR'RiN(
R/tintttimet
ValueErrorRtcalendarttimegmtstrptimeRORR`R$R'(tmorselRt
time_template((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyRNs0
$



	
	cCs|dkrt}n|dk	rg|D]}|j^q+}x@|D]5}|s_||krG|jt|||qGqGWn|S(s-Returns a CookieJar from a key/value dictionary.

    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :param cookiejar: (optional) A cookiejar to add the cookies to.
    :param overwrite: (optional) If False, will not replace cookies
        already in the jar with new ones.
    N(R/RJRRPRO(tcookie_dictREt	overwriteRGtnames_from_jarR((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pytcookiejar_from_dicts
$cCst|tjs!tdnt|trKt|d|dt}nXt|tjry|j|Wqtk
rx|D]}|j	|qWqXn|S(sAdd cookies to cookiejar and returns a merged CookieJar.

    :param cookiejar: CookieJar object to add the cookies to.
    :param cookies: Dictionary or CookieJar object to be added.
    s!You can only merge into CookieJarRER(
RMRRoRRRR`RqtAttributeErrorRP(REtcookiest
cookie_in_jar((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
merge_cookiess

(!R.RpRRtcollectionst_internal_utilsRtcompatRRRRRztImportErrortdummy_threadingtobjectRR1R=RAR/RHtRuntimeErrorRIRotMutableMappingRJRRORNRRR(((s@/usr/lib/python2.7/site-packages/pip/_vendor/requests/cookies.pyt
s,"
H				#	_vendor/requests/__init__.pyc000064400000007420152527136320012340 0ustar00
abc@stdZddlmZddlmZddlZddlmZdZyeejejWn9e	e
fk
rejdjejejenXdd	l
mZejd
eddlmZmZmZmZddlmZmZmZmZdd
lmZmZddlmZddlmZddlmZmZmZddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*m+Z+ddl,m-Z-ddlm.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6ddl7Z7yddl7m8Z8Wn*e9k
r@de7j:fdYZ8nXe7j;e<j=e8ejde4de>dS(s
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~

Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:

   >>> import requests
   >>> r = requests.get('https://www.python.org')
   >>> r.status_code
   200
   >>> 'Python is a programming language' in r.content
   True

... or POST:

   >>> payload = dict(key1='value1', key2='value2')
   >>> r = requests.post('http://httpbin.org/post', data=payload)
   >>> print(r.text)
   {
     ...
     "form": {
       "key2": "value2",
       "key1": "value1"
     },
     ...
   }

The other HTTP methods are supported - see `requests.api`. Full documentation
is at .

:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
i(turllib3(tchardetNi(tRequestsDependencyWarningcCs-|jd}|dgks$tt|dkrF|jdn|\}}}t|t|t|}}}|dkst|dkst|dkst|jdd \}}}t|t|t|}}}|dkst|dkst|dks)tdS(	Nt.tdevit0iiii(tsplittAssertionErrortlentappendtint(turllib3_versiontchardet_versiontmajortminortpatch((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pytcheck_compatibility1s&&sAurllib3 ({0}) or chardet ({1}) doesn't match a supported version!(tDependencyWarningtignore(t	__title__t__description__t__url__t__version__(t	__build__t
__author__t__author_email__t__license__(t
__copyright__t__cake__(tutils(tpackages(tRequesttResponsetPreparedRequest(trequesttgettheadtpostRtputtdeletetoptions(tsessiontSession(tcodes(	tRequestExceptiontTimeouttURLRequiredtTooManyRedirectst	HTTPErrortConnectionErrortFileModeWarningtConnectTimeouttReadTimeout(tNullHandlerR5cBseZdZRS(cCsdS(N((tselftrecord((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pytemitss(t__name__t
__module__R8(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pyR5rstdefaultR	(?t__doc__tpip._vendorRRtwarningst
exceptionsRRRRt
ValueErrortwarntformattpip._vendor.urllib3.exceptionsRtsimplefilterRRRRRRRRRtRRtmodelsRR R!tapiR"R#R$R%RR&R'R(tsessionsR)R*tstatus_codesR+R,R-R.R/R0R1R2R3R4tloggingR5tImportErrortHandlert	getLoggerR9t
addHandlertTrue(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pyt)s<	
"":@
_vendor/requests/certs.pyc000064400000001152152527136320011715 0ustar00
abc@s1dZddlmZedkr-eGHndS(sF
requests.certs
~~~~~~~~~~~~~~

This module returns the preferred default CA certificate bundle. There is
only one — the one from the certifi package.

If you are packaging Requests, e.g., for a Linux distribution or a managed
environment, you can change the definition of where() to return a separately
packaged CA bundle.
i(twheret__main__N(t__doc__tpip._vendor.certifiRt__name__(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/certs.pyts_vendor/requests/utils.pyo000064400000062046152527136320011762 0ustar00
abc@s\dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZddl
mZddlmZddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!dd	l"m#Z#dd
l$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*d@Z+ej,Z-idd6dd6Z.ej/dkrdZ0dZndZ1dZ2e3dZ4dZ5dZ6dZ7dZ8dZ9e3dZ:dZ;dZ<d Z=d!Z>d"Z?d#Z@d$ZAeBd%d&ZCd'ZDd(ZEd)ZFd*ZGd+ZHd,ZIejJd-ZKd.ZLdd/ZNd0ZOd1d2ZPd3ZQd4ZRd5jSd6ZTeTd7ZUeTd8ZVd9ZWd:ZXd;ZYejZd<Z[ejZd<Z\d=Z]d>Z^d?Z_dS(As
requests.utils
~~~~~~~~~~~~~~

This module provides utility functions that are used within Requests
that are also useful for external consumption.
iNi(t__version__(tcerts(tto_native_string(tparse_http_list(tquoteturlparsetbyteststrtOrderedDicttunquotet
getproxiestproxy_bypasst
urlunparset
basestringt
integer_typestis_py3tproxy_bypass_environmenttgetproxies_environment(tcookiejar_from_dict(tCaseInsensitiveDict(t
InvalidURLt
InvalidHeadertFileModeWarningtUnrewindableBodyErrors.netrct_netrciPthttpithttpstWindowscCs"trddl}nddl}yE|j|jd}|j|dd}|j|dd}Wntk
rztSX|s|rtS|jd}x|D]w}|dkrd|krt	Sn|j
dd	}|j
d
d}|j
dd}tj||tj
rt	SqWtS(
Nis;Software\Microsoft\Windows\CurrentVersion\Internet SettingstProxyEnableit
ProxyOverridet;st.s\.t*s.*t?(Rtwinregt_winregtOpenKeytHKEY_CURRENT_USERtQueryValueExtOSErrortFalsetsplittTruetreplacetretmatchtI(thostR"tinternetSettingstproxyEnablet
proxyOverridettest((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytproxy_bypass_registry.s2		
	

cCs!trt|St|SdS(sReturn True, if the host should be bypassed.

        Checks proxy settings gathered from the environment, if specified,
        or the registry.
        N(RRR4(R/((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyROs	
cCs"t|dr|j}n|S(s/Returns an internal sequence dictionary update.titems(thasattrR5(td((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdict_to_sequence[scCsd}d}t|dr*t|}nt|drE|j}nmt|dry|j}Wntjk
rzqXtj|j}d|j	krt
jdtqnt|drty|j
}Wn,ttfk
r|dk	rq|}qqqtXt|drt|dkrty3|jdd	|j
}|j|pIdWqqttfk
rmd}qqXqtn|dkrd}ntd||S(
Nit__len__tlentfilenotbs%Requests has determined the content-length for this request using the binary size of the file: however, the file has been opened in text mode (i.e. without the 'b' flag in the mode). This may lead to an incorrect content-length. In Requests 3.0, support will be removed for files in text mode.ttelltseeki(tNoneR6R:R;tiotUnsupportedOperationtostfstattst_sizetmodetwarningstwarnRR=R'tIOErrorR>tmax(tottotal_lengthtcurrent_positionR;((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt	super_lends@

	cCseyGddlm}m}d}x^tD]V}ytjjdj|}Wntk
r_dSXtjj	|r&|}Pq&q&W|dkrdSt
|}d}t|tr|j
d}n|jj|d}	yG||j|	}
|
r|
drdnd}|
||
d	fSWn#|tfk
rE|rFqFnXWnttfk
r`nXdS(
s;Returns the Requests tuple auth for a given url from netrc.i(tnetrctNetrcParseErrors~/{0}Nt:tasciiiii(RNROR?tNETRC_FILESRBtpatht
expandusertformattKeyErrortexistsRt
isinstanceRtdecodetnetlocR)tauthenticatorsRHtImportErrortAttributeError(turltraise_errorsRNROt
netrc_pathtftloctritsplitstrR/Rtlogin_i((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_netrc_auths8

cCs[t|dd}|rWt|trW|ddkrW|ddkrWtjj|SdS(s0Tries to guess the filename of the given object.tnameitN(tgetattrR?RXR
RBRStbasename(tobjRg((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytguess_filenames%cCsD|dkrdSt|ttttfr:tdnt|S(sTake an object and test to see if it can be represented as a
    dictionary. Unless it can not be represented as such, return an
    OrderedDict, e.g.,

    ::

        >>> from_key_val_list([('key', 'val')])
        OrderedDict([('key', 'val')])
        >>> from_key_val_list('string')
        ValueError: need more than 1 value to unpack
        >>> from_key_val_list({'key': 'val'})
        OrderedDict([('key', 'val')])

    :rtype: OrderedDict
    s+cannot encode objects that are not 2-tuplesN(R?RXRRtbooltintt
ValueErrorR(tvalue((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytfrom_key_val_lists
cCse|dkrdSt|ttttfr:tdnt|tjr[|j	}nt
|S(sTake an object and test to see if it can be represented as a
    dictionary. If it can be, return a list of tuples, e.g.,

    ::

        >>> to_key_val_list([('key', 'val')])
        [('key', 'val')]
        >>> to_key_val_list({'key': 'val'})
        [('key', 'val')]
        >>> to_key_val_list('string')
        ValueError: cannot encode objects that are not 2-tuples.

    :rtype: list
    s+cannot encode objects that are not 2-tuplesN(R?RXRRRnRoRptcollectionstMappingR5tlist(Rq((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytto_key_val_listscCshg}x[t|D]M}|d |dko8dknrSt|dd!}n|j|qW|S(sParse lists as described by RFC 2068 Section 2.

    In particular, parse comma-separated lists where the elements of
    the list may include quoted-strings.  A quoted-string could
    contain a comma.  A non-quoted string could have quotes in the
    middle.  Quotes are removed automatically after parsing.

    It basically works like :func:`parse_set_header` just that items
    may appear multiple times and case sensitivity is preserved.

    The return value is a standard :class:`list`:

    >>> parse_list_header('token, "quoted value"')
    ['token', 'quoted value']

    To create a header from the :class:`list` again, use the
    :func:`dump_header` function.

    :param value: a string with a list header.
    :return: :class:`list`
    :rtype: list
    iit"(t_parse_list_headertunquote_header_valuetappend(Rqtresulttitem((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytparse_list_headers$cCsi}xt|D]~}d|kr5d||>> d = parse_dict_header('foo="is a fish", bar="as well"')
    >>> type(d) is dict
    True
    >>> sorted(d.items())
    [('bar', 'as well'), ('foo', 'is a fish')]

    If there is no value for a key it will be `None`:

    >>> parse_dict_header('key_without_value')
    {'key_without_value': None}

    To create a header from the :class:`dict` again, use the
    :func:`dump_header` function.

    :param value: a string with a dict header.
    :return: :class:`dict`
    :rtype: dict
    t=iiRwN(RxR?R)Ry(RqR{R|Rg((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytparse_dict_header1s
$cCsq|rm|d|dko%dknrm|dd!}|sN|d dkrm|jddjddSn|S(	sUnquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    :rtype: str
    iiRwiis\\s\s\"(R+(Rqtis_filename((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyRyTs
*
cCs+i}x|D]}|j||j/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdict_from_cookiejarms
cCs
t||S(sReturns a CookieJar from a key/value dictionary.

    :param cj: CookieJar to insert cookies into.
    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :rtype: CookieJar
    (R(RR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytadd_dict_to_cookiejar|scCsvtjdttjddtj}tjddtj}tjd}|j||j||j|S(slReturns encodings from given content string.

    :param content: bytestring to extract encodings from.
    sIn requests 3.0, get_encodings_from_content will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)s!]tflagss+]s$^<\?xml.*?encoding=["\']*(.+?)["\'>](RFRGtDeprecationWarningR,tcompileR.tfindall(tcontentt
charset_ret	pragma_retxml_re((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_encodings_from_contentscCs_|jd}|sdStj|\}}d|krK|djdSd|kr[dSdS(s}Returns encodings from given HTTP Header Dict.

    :param headers: dictionary to extract encoding from.
    :rtype: str
    scontent-typetcharsets'"ttexts
ISO-8859-1N(tgetR?tcgitparse_headertstrip(theaderstcontent_typetparams((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_encoding_from_headerssccs|jdkr)x|D]}|VqWdStj|jdd}x+|D]#}|j|}|rK|VqKqKW|jddt}|r|VndS(sStream decodes a iterator.NterrorsR+ttfinal(tencodingR?tcodecstgetincrementaldecoderRYR*(titeratortrR|tdecodertchunktrv((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytstream_decode_response_unicodes
	
ccsdd}|dks|dkr-t|}nx0|t|kr_||||!V||7}q0WdS(s Iterate over slices of a string.iN(R?R:(tstringtslice_lengthtpos((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytiter_slicesscCstjdtg}t|j}|rcyt|j|SWqctk
r_|j|qcXnyt|j|ddSWnt	k
r|jSXdS(sReturns the requested content back in unicode.

    :param r: Response object to get unicode content from.

    Tried:

    1. charset from content-type
    2. fall back and replace all unicode characters

    :rtype: str
    sIn requests 3.0, get_unicode_from_response will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)RR+N(
RFRGRRRRRtUnicodeErrorRzt	TypeError(Rttried_encodingsR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_unicode_from_responses

t4ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzs0123456789-._~cCs|jd}xtdt|D]}||dd!}t|dkr|jrytt|d}Wn!tk
rtd|nX|tkr|||d||/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytunquote_unreserveds
cCsKd}d}ytt|d|SWntk
rFt|d|SXdS(sRe-quote the given URI.

    This function passes the given URI through an unquote/quote cycle to
    ensure that it is fully and consistently quoted.

    :rtype: str
    s!#$%&'()*+,/:;=?@[]~s!#$&'()*+,/:;=?@[]~tsafeN(RRR(Rtsafe_with_percenttsafe_without_percent((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytrequote_uri
s
cCstjdtj|d}|jd\}}tjdtjtt|d}tjdtj|d|@}||@||@kS(sThis function allows you to check if an IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    s=Lit/(tstructtunpacktsockett	inet_atonR)tdotted_netmaskRo(tiptnettipaddrtnetaddrtbitstnetmasktnetwork((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytaddress_in_network#s
+#cCs/ddd|>dA}tjtjd|S(sConverts mask from /xx format to xxx.xxx.xxx.xxx

    Example: if mask is 24 function returns 255.255.255.0

    :rtype: str
    Iii s>I(Rt	inet_ntoaRtpack(tmaskR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyR2scCs-ytj|Wntjk
r(tSXtS(s
    :rtype: bool
    (RRterrorR(R*(t	string_ip((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytis_ipv4_address=s
cCs|jddkryt|jdd}Wntk
rFtSX|dks_|dkrctSytj|jddWqtjk
rtSXntStS(sV
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    Rii i(	tcountRoR)RpR(RRRR*(tstring_networkR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt
is_valid_cidrHs
ccst|dk	}|r4tjj|}|tj|/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytset_environ`s	
c	
Cscd}|}|d	kr*|d}nt|j}|rd|jddjdD}|jdd}t|rx|D]8}t|rt||rtSq||krtSqWqx@|D]5}|j	|s|jddj	|rtSqWnt
d|8yt|}Wn tt
jfk
rNt}nXWd	QX|r_tStS(
sL
    Returns whether we should bypass proxies or not.

    :rtype: bool
    cSs(tjj|p'tjj|jS(N(RBRRtupper(tk((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt|Rtno_proxycss|]}|r|VqdS(N((t.0R/((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pys	st Rt,RPiN(R?RRZR+R)RRRR*tendswithRRRRtgaierrorR((	R^Rt	get_proxytno_proxy_argRZRtproxy_ipR/tbypass((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytshould_bypass_proxiesvs4	%

+cCs!t|d|riStSdS(sA
    Return a dict of environment proxies.

    :rtype: dict
    RN(RR
(R^R((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_environ_proxiesscCs|p	i}t|}|jdkrC|j|j|jdS|jd|j|jd|jdg}d}x(|D] }||krz||}PqzqzW|S(sSelect a proxy for the url, if applicable.

    :param url: The url being for the request
    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
    talls://sall://N(RthostnameR?Rtscheme(R^tproxiesturlpartst
proxy_keystproxyt	proxy_key((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytselect_proxys
	

spython-requestscCsd|tfS(sO
    Return a string representing the default user agent.

    :rtype: str
    s%s/%s(R(Rg((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdefault_user_agentscCs2titd6djd
d6dd6dd	6S(s9
    :rtype: requests.structures.CaseInsensitiveDict
    s
User-Agents, tgziptdeflatesAccept-Encodings*/*tAccepts
keep-alivet
Connection(RR(RRR(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdefault_headerss

c	Csg}d}xtjd|D]}y|jdd\}}Wntk
ra|d}}nXi|jdd6}xa|jdD]P}y|jd\}}Wntk
rPnX|j|||j|; rel=front; type="image/jpeg",; rel=back;type="image/jpeg"

    :rtype: list
    s '"s, * '"R^R~(R,R)RpRRz(	Rqtlinkst
replace_charstvalR^Rtlinktparamtkey((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytparse_header_linkss 

 sRQiicCs|d }|tjtjfkr&dS|d tjkr=dS|d tjtjfkr]dS|jt}|dkr|dS|dkr|d	d	dtkrd
S|dd	dtkrdSn|dkr|d t	krd
S|dt	krdSnd	S(s
    :rtype: str
    isutf-32is	utf-8-sigisutf-16isutf-8Ns	utf-16-beis	utf-16-les	utf-32-bes	utf-32-le(RtBOM_UTF32_LEtBOM_UTF32_BEtBOM_UTF8tBOM_UTF16_LEtBOM_UTF16_BERt_nullt_null2t_null3R?(tdatatsamplet	nullcount((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytguess_json_utfs*
cCsSt||\}}}}}}|s7||}}nt||||||fS(sGiven a URL that may or may not have a scheme, prepend the given scheme.
    Does not replace a present scheme with the one provided as an argument.

    :rtype: str
    (RR(R^t
new_schemeRRZRSRtquerytfragment((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytprepend_scheme_if_needed1s!cCsRt|}y"t|jt|jf}Wnttfk
rMd}nX|S(s{Given a url with authentication components, extract them into a tuple of
    username,password.

    :rtype: (str,str)
    R(RR(RR	tusernametpasswordR]R(R^tparsedtauth((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_auth_from_urlBs"
s^\S[^\r\n]*$|^$cCs|\}}t|tr$t}nt}y&|j|sOtd|nWn0tk
rtd||t|fnXdS(sVerifies that header value is a string which doesn't contain
    leading whitespace or return characters. This prevents unintended
    header injection.

    :param header: tuple, in the format (name, value).
    s7Invalid return character or leading space in header: %ss>Value for header {%s: %s} must be of type str or bytes, not %sN(RXRt_CLEAN_HEADER_REGEX_BYTEt_CLEAN_HEADER_REGEX_STRR-RRttype(theaderRgRqtpat((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytcheck_header_validityWs	
cCsft|\}}}}}}|s4||}}n|jddd}t|||||dfS(sW
    Given a url remove the fragment and the authentication part.

    :rtype: str
    t@iiR(RtrsplitR(R^RRZRSRRR
((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt
urldefragauthls
cCs}t|jdd}|dk	rmt|jtrmy||jWqyttfk
ritdqyXntddS(sfMove file pointer back to its recorded starting position
    so it can be read again on redirect.
    R>s;An error occurred when rewinding request body for redirect.s+Unable to rewind request body for redirect.N(	RjtbodyR?RXt_body_positionRRHR'R(tprepared_requestt	body_seek((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytrewind_body}s(s.netrcR(`t__doc__RRRst
contextlibR@RBtplatformR,RRRFRRRt_internal_utilsRtcompatRRxRRRRRR	R
RRR
RRRRtcookiesRt
structuresRt
exceptionsRRRRRRtwheretDEFAULT_CA_BUNDLE_PATHt
DEFAULT_PORTStsystemR4R8RMR(RfRmRrRvR}RRyRRRRRRRt	frozensetRRRRRRRtcontextmanagerRRR?RRRRRtencodeRRRR
RRRRRRRR!(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt	s^"	!			=3				 	#						
	%
							9				"

	 				_vendor/requests/models.py000064400000102403152527136320011716 0ustar00# -*- coding: utf-8 -*-

"""
requests.models
~~~~~~~~~~~~~~~

This module contains the primary objects that power Requests.
"""

import collections
import datetime
import sys

# Import encoding now, to avoid implicit import later.
# Implicit import within threads may cause LookupError when standard library is in a ZIP,
# such as in Embedded Python. See https://github.com/requests/requests/issues/3578.
import encodings.idna

from pip._vendor.urllib3.fields import RequestField
from pip._vendor.urllib3.filepost import encode_multipart_formdata
from pip._vendor.urllib3.util import parse_url
from pip._vendor.urllib3.exceptions import (
    DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)

from io import UnsupportedOperation
from .hooks import default_hooks
from .structures import CaseInsensitiveDict

from .auth import HTTPBasicAuth
from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar
from .exceptions import (
    HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,
    ContentDecodingError, ConnectionError, StreamConsumedError)
from ._internal_utils import to_native_string, unicode_is_ascii
from .utils import (
    guess_filename, get_auth_from_url, requote_uri,
    stream_decode_response_unicode, to_key_val_list, parse_header_links,
    iter_slices, guess_json_utf, super_len, check_header_validity)
from .compat import (
    cookielib, urlunparse, urlsplit, urlencode, str, bytes,
    is_py2, chardet, builtin_str, basestring)
from .compat import json as complexjson
from .status_codes import codes

#: The set of HTTP status codes that indicate an automatically
#: processable redirect.
REDIRECT_STATI = (
    codes.moved,               # 301
    codes.found,               # 302
    codes.other,               # 303
    codes.temporary_redirect,  # 307
    codes.permanent_redirect,  # 308
)

DEFAULT_REDIRECT_LIMIT = 30
CONTENT_CHUNK_SIZE = 10 * 1024
ITER_CHUNK_SIZE = 512


class RequestEncodingMixin(object):
    @property
    def path_url(self):
        """Build the path URL to use."""

        url = []

        p = urlsplit(self.url)

        path = p.path
        if not path:
            path = '/'

        url.append(path)

        query = p.query
        if query:
            url.append('?')
            url.append(query)

        return ''.join(url)

    @staticmethod
    def _encode_params(data):
        """Encode parameters in a piece of data.

        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
        if parameters are supplied as a dict.
        """

        if isinstance(data, (str, bytes)):
            return data
        elif hasattr(data, 'read'):
            return data
        elif hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data):
                if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
                    vs = [vs]
                for v in vs:
                    if v is not None:
                        result.append(
                            (k.encode('utf-8') if isinstance(k, str) else k,
                             v.encode('utf-8') if isinstance(v, str) else v))
            return urlencode(result, doseq=True)
        else:
            return data

    @staticmethod
    def _encode_files(files, data):
        """Build the body for a multipart/form-data request.

        Will successfully encode files when passed as a dict or a list of
        tuples. Order is retained if data is a list of tuples but arbitrary
        if parameters are supplied as a dict.
        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
        or 4-tuples (filename, fileobj, contentype, custom_headers).
        """
        if (not files):
            raise ValueError("Files must be provided.")
        elif isinstance(data, basestring):
            raise ValueError("Data must not be a string.")

        new_fields = []
        fields = to_key_val_list(data or {})
        files = to_key_val_list(files or {})

        for field, val in fields:
            if isinstance(val, basestring) or not hasattr(val, '__iter__'):
                val = [val]
            for v in val:
                if v is not None:
                    # Don't call str() on bytestrings: in Py3 it all goes wrong.
                    if not isinstance(v, bytes):
                        v = str(v)

                    new_fields.append(
                        (field.decode('utf-8') if isinstance(field, bytes) else field,
                         v.encode('utf-8') if isinstance(v, str) else v))

        for (k, v) in files:
            # support for explicit filename
            ft = None
            fh = None
            if isinstance(v, (tuple, list)):
                if len(v) == 2:
                    fn, fp = v
                elif len(v) == 3:
                    fn, fp, ft = v
                else:
                    fn, fp, ft, fh = v
            else:
                fn = guess_filename(v) or k
                fp = v

            if isinstance(fp, (str, bytes, bytearray)):
                fdata = fp
            else:
                fdata = fp.read()

            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
            rf.make_multipart(content_type=ft)
            new_fields.append(rf)

        body, content_type = encode_multipart_formdata(new_fields)

        return body, content_type


class RequestHooksMixin(object):
    def register_hook(self, event, hook):
        """Properly register a hook."""

        if event not in self.hooks:
            raise ValueError('Unsupported event specified, with event name "%s"' % (event))

        if isinstance(hook, collections.Callable):
            self.hooks[event].append(hook)
        elif hasattr(hook, '__iter__'):
            self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))

    def deregister_hook(self, event, hook):
        """Deregister a previously registered hook.
        Returns True if the hook existed, False if not.
        """

        try:
            self.hooks[event].remove(hook)
            return True
        except ValueError:
            return False


class Request(RequestHooksMixin):
    """A user-created :class:`Request ` object.

    Used to prepare a :class:`PreparedRequest `, which is sent to the server.

    :param method: HTTP method to use.
    :param url: URL to send.
    :param headers: dictionary of headers to send.
    :param files: dictionary of {filename: fileobject} files to multipart upload.
    :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.
    :param json: json for the body to attach to the request (if files or data is not specified).
    :param params: dictionary of URL parameters to append to the URL.
    :param auth: Auth handler or (user, pass) tuple.
    :param cookies: dictionary or CookieJar of cookies to attach to this request.
    :param hooks: dictionary of callback hooks, for internal usage.

    Usage::

      >>> import requests
      >>> req = requests.Request('GET', 'http://httpbin.org/get')
      >>> req.prepare()
      
    """

    def __init__(self,
            method=None, url=None, headers=None, files=None, data=None,
            params=None, auth=None, cookies=None, hooks=None, json=None):

        # Default empty dicts for dict params.
        data = [] if data is None else data
        files = [] if files is None else files
        headers = {} if headers is None else headers
        params = {} if params is None else params
        hooks = {} if hooks is None else hooks

        self.hooks = default_hooks()
        for (k, v) in list(hooks.items()):
            self.register_hook(event=k, hook=v)

        self.method = method
        self.url = url
        self.headers = headers
        self.files = files
        self.data = data
        self.json = json
        self.params = params
        self.auth = auth
        self.cookies = cookies

    def __repr__(self):
        return '' % (self.method)

    def prepare(self):
        """Constructs a :class:`PreparedRequest ` for transmission and returns it."""
        p = PreparedRequest()
        p.prepare(
            method=self.method,
            url=self.url,
            headers=self.headers,
            files=self.files,
            data=self.data,
            json=self.json,
            params=self.params,
            auth=self.auth,
            cookies=self.cookies,
            hooks=self.hooks,
        )
        return p


class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
    """The fully mutable :class:`PreparedRequest ` object,
    containing the exact bytes that will be sent to the server.

    Generated from either a :class:`Request ` object or manually.

    Usage::

      >>> import requests
      >>> req = requests.Request('GET', 'http://httpbin.org/get')
      >>> r = req.prepare()
      

      >>> s = requests.Session()
      >>> s.send(r)
      
    """

    def __init__(self):
        #: HTTP verb to send to the server.
        self.method = None
        #: HTTP URL to send the request to.
        self.url = None
        #: dictionary of HTTP headers.
        self.headers = None
        # The `CookieJar` used to create the Cookie header will be stored here
        # after prepare_cookies is called
        self._cookies = None
        #: request body to send to the server.
        self.body = None
        #: dictionary of callback hooks, for internal usage.
        self.hooks = default_hooks()
        #: integer denoting starting position of a readable file-like body.
        self._body_position = None

    def prepare(self,
            method=None, url=None, headers=None, files=None, data=None,
            params=None, auth=None, cookies=None, hooks=None, json=None):
        """Prepares the entire request with the given parameters."""

        self.prepare_method(method)
        self.prepare_url(url, params)
        self.prepare_headers(headers)
        self.prepare_cookies(cookies)
        self.prepare_body(data, files, json)
        self.prepare_auth(auth, url)

        # Note that prepare_auth must be last to enable authentication schemes
        # such as OAuth to work on a fully prepared request.

        # This MUST go after prepare_auth. Authenticators could add a hook
        self.prepare_hooks(hooks)

    def __repr__(self):
        return '' % (self.method)

    def copy(self):
        p = PreparedRequest()
        p.method = self.method
        p.url = self.url
        p.headers = self.headers.copy() if self.headers is not None else None
        p._cookies = _copy_cookie_jar(self._cookies)
        p.body = self.body
        p.hooks = self.hooks
        p._body_position = self._body_position
        return p

    def prepare_method(self, method):
        """Prepares the given HTTP method."""
        self.method = method
        if self.method is not None:
            self.method = to_native_string(self.method.upper())

    @staticmethod
    def _get_idna_encoded_host(host):
        import idna

        try:
            host = idna.encode(host, uts46=True).decode('utf-8')
        except idna.IDNAError:
            raise UnicodeError
        return host

    def prepare_url(self, url, params):
        """Prepares the given HTTP URL."""
        #: Accept objects that have string representations.
        #: We're unable to blindly call unicode/str functions
        #: as this will include the bytestring indicator (b'')
        #: on python 3.x.
        #: https://github.com/requests/requests/pull/2238
        if isinstance(url, bytes):
            url = url.decode('utf8')
        else:
            url = unicode(url) if is_py2 else str(url)

        # Remove leading whitespaces from url
        url = url.lstrip()

        # Don't do any URL preparation for non-HTTP schemes like `mailto`,
        # `data` etc to work around exceptions from `url_parse`, which
        # handles RFC 3986 only.
        if ':' in url and not url.lower().startswith('http'):
            self.url = url
            return

        # Support for unicode domain names and paths.
        try:
            scheme, auth, host, port, path, query, fragment = parse_url(url)
        except LocationParseError as e:
            raise InvalidURL(*e.args)

        if not scheme:
            error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")
            error = error.format(to_native_string(url, 'utf8'))

            raise MissingSchema(error)

        if not host:
            raise InvalidURL("Invalid URL %r: No host supplied" % url)

        # In general, we want to try IDNA encoding the hostname if the string contains
        # non-ASCII characters. This allows users to automatically get the correct IDNA
        # behaviour. For strings containing only ASCII characters, we need to also verify
        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
        if not unicode_is_ascii(host):
            try:
                host = self._get_idna_encoded_host(host)
            except UnicodeError:
                raise InvalidURL('URL has an invalid label.')
        elif host.startswith(u'*'):
            raise InvalidURL('URL has an invalid label.')

        # Carefully reconstruct the network location
        netloc = auth or ''
        if netloc:
            netloc += '@'
        netloc += host
        if port:
            netloc += ':' + str(port)

        # Bare domains aren't valid URLs.
        if not path:
            path = '/'

        if is_py2:
            if isinstance(scheme, str):
                scheme = scheme.encode('utf-8')
            if isinstance(netloc, str):
                netloc = netloc.encode('utf-8')
            if isinstance(path, str):
                path = path.encode('utf-8')
            if isinstance(query, str):
                query = query.encode('utf-8')
            if isinstance(fragment, str):
                fragment = fragment.encode('utf-8')

        if isinstance(params, (str, bytes)):
            params = to_native_string(params)

        enc_params = self._encode_params(params)
        if enc_params:
            if query:
                query = '%s&%s' % (query, enc_params)
            else:
                query = enc_params

        url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
        self.url = url

    def prepare_headers(self, headers):
        """Prepares the given HTTP headers."""

        self.headers = CaseInsensitiveDict()
        if headers:
            for header in headers.items():
                # Raise exception on invalid header value.
                check_header_validity(header)
                name, value = header
                self.headers[to_native_string(name)] = value

    def prepare_body(self, data, files, json=None):
        """Prepares the given HTTP body data."""

        # Check if file, fo, generator, iterator.
        # If not, run through normal process.

        # Nottin' on you.
        body = None
        content_type = None

        if not data and json is not None:
            # urllib3 requires a bytes-like body. Python 2's json.dumps
            # provides this natively, but Python 3 gives a Unicode string.
            content_type = 'application/json'
            body = complexjson.dumps(json)
            if not isinstance(body, bytes):
                body = body.encode('utf-8')

        is_stream = all([
            hasattr(data, '__iter__'),
            not isinstance(data, (basestring, list, tuple, collections.Mapping))
        ])

        try:
            length = super_len(data)
        except (TypeError, AttributeError, UnsupportedOperation):
            length = None

        if is_stream:
            body = data

            if getattr(body, 'tell', None) is not None:
                # Record the current file position before reading.
                # This will allow us to rewind a file in the event
                # of a redirect.
                try:
                    self._body_position = body.tell()
                except (IOError, OSError):
                    # This differentiates from None, allowing us to catch
                    # a failed `tell()` later when trying to rewind the body
                    self._body_position = object()

            if files:
                raise NotImplementedError('Streamed bodies and files are mutually exclusive.')

            if length:
                self.headers['Content-Length'] = builtin_str(length)
            else:
                self.headers['Transfer-Encoding'] = 'chunked'
        else:
            # Multi-part file uploads.
            if files:
                (body, content_type) = self._encode_files(files, data)
            else:
                if data:
                    body = self._encode_params(data)
                    if isinstance(data, basestring) or hasattr(data, 'read'):
                        content_type = None
                    else:
                        content_type = 'application/x-www-form-urlencoded'

            self.prepare_content_length(body)

            # Add content-type if it wasn't explicitly provided.
            if content_type and ('content-type' not in self.headers):
                self.headers['Content-Type'] = content_type

        self.body = body

    def prepare_content_length(self, body):
        """Prepare Content-Length header based on request method and body"""
        if body is not None:
            length = super_len(body)
            if length:
                # If length exists, set it. Otherwise, we fallback
                # to Transfer-Encoding: chunked.
                self.headers['Content-Length'] = builtin_str(length)
        elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
            # Set Content-Length to 0 for methods that can have a body
            # but don't provide one. (i.e. not GET or HEAD)
            self.headers['Content-Length'] = '0'

    def prepare_auth(self, auth, url=''):
        """Prepares the given HTTP auth data."""

        # If no Auth is explicitly provided, extract it from the URL first.
        if auth is None:
            url_auth = get_auth_from_url(self.url)
            auth = url_auth if any(url_auth) else None

        if auth:
            if isinstance(auth, tuple) and len(auth) == 2:
                # special-case basic HTTP auth
                auth = HTTPBasicAuth(*auth)

            # Allow auth to make its changes.
            r = auth(self)

            # Update self to reflect the auth changes.
            self.__dict__.update(r.__dict__)

            # Recompute Content-Length
            self.prepare_content_length(self.body)

    def prepare_cookies(self, cookies):
        """Prepares the given HTTP cookie data.

        This function eventually generates a ``Cookie`` header from the
        given cookies using cookielib. Due to cookielib's design, the header
        will not be regenerated if it already exists, meaning this function
        can only be called once for the life of the
        :class:`PreparedRequest ` object. Any subsequent calls
        to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
        header is removed beforehand.
        """
        if isinstance(cookies, cookielib.CookieJar):
            self._cookies = cookies
        else:
            self._cookies = cookiejar_from_dict(cookies)

        cookie_header = get_cookie_header(self._cookies, self)
        if cookie_header is not None:
            self.headers['Cookie'] = cookie_header

    def prepare_hooks(self, hooks):
        """Prepares the given hooks."""
        # hooks can be passed as None to the prepare method and to this
        # method. To prevent iterating over None, simply use an empty list
        # if hooks is False-y
        hooks = hooks or []
        for event in hooks:
            self.register_hook(event, hooks[event])


class Response(object):
    """The :class:`Response ` object, which contains a
    server's response to an HTTP request.
    """

    __attrs__ = [
        '_content', 'status_code', 'headers', 'url', 'history',
        'encoding', 'reason', 'cookies', 'elapsed', 'request'
    ]

    def __init__(self):
        self._content = False
        self._content_consumed = False
        self._next = None

        #: Integer Code of responded HTTP Status, e.g. 404 or 200.
        self.status_code = None

        #: Case-insensitive Dictionary of Response Headers.
        #: For example, ``headers['content-encoding']`` will return the
        #: value of a ``'Content-Encoding'`` response header.
        self.headers = CaseInsensitiveDict()

        #: File-like object representation of response (for advanced usage).
        #: Use of ``raw`` requires that ``stream=True`` be set on the request.
        # This requirement does not apply for use internally to Requests.
        self.raw = None

        #: Final URL location of Response.
        self.url = None

        #: Encoding to decode with when accessing r.text.
        self.encoding = None

        #: A list of :class:`Response ` objects from
        #: the history of the Request. Any redirect responses will end
        #: up here. The list is sorted from the oldest to the most recent request.
        self.history = []

        #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
        self.reason = None

        #: A CookieJar of Cookies the server sent back.
        self.cookies = cookiejar_from_dict({})

        #: The amount of time elapsed between sending the request
        #: and the arrival of the response (as a timedelta).
        #: This property specifically measures the time taken between sending
        #: the first byte of the request and finishing parsing the headers. It
        #: is therefore unaffected by consuming the response content or the
        #: value of the ``stream`` keyword argument.
        self.elapsed = datetime.timedelta(0)

        #: The :class:`PreparedRequest ` object to which this
        #: is a response.
        self.request = None

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def __getstate__(self):
        # Consume everything; accessing the content attribute makes
        # sure the content has been fully read.
        if not self._content_consumed:
            self.content

        return dict(
            (attr, getattr(self, attr, None))
            for attr in self.__attrs__
        )

    def __setstate__(self, state):
        for name, value in state.items():
            setattr(self, name, value)

        # pickled objects do not have .raw
        setattr(self, '_content_consumed', True)
        setattr(self, 'raw', None)

    def __repr__(self):
        return '' % (self.status_code)

    def __bool__(self):
        """Returns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        """
        return self.ok

    def __nonzero__(self):
        """Returns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        """
        return self.ok

    def __iter__(self):
        """Allows you to use a response as an iterator."""
        return self.iter_content(128)

    @property
    def ok(self):
        """Returns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        """
        try:
            self.raise_for_status()
        except HTTPError:
            return False
        return True

    @property
    def is_redirect(self):
        """True if this Response is a well-formed HTTP redirect that could have
        been processed automatically (by :meth:`Session.resolve_redirects`).
        """
        return ('location' in self.headers and self.status_code in REDIRECT_STATI)

    @property
    def is_permanent_redirect(self):
        """True if this Response one of the permanent versions of redirect."""
        return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))

    @property
    def next(self):
        """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
        return self._next

    @property
    def apparent_encoding(self):
        """The apparent encoding, provided by the chardet library."""
        return chardet.detect(self.content)['encoding']

    def iter_content(self, chunk_size=1, decode_unicode=False):
        """Iterates over the response data.  When stream=True is set on the
        request, this avoids reading the content at once into memory for
        large responses.  The chunk size is the number of bytes it should
        read into memory.  This is not necessarily the length of each item
        returned as decoding can take place.

        chunk_size must be of type int or None. A value of None will
        function differently depending on the value of `stream`.
        stream=True will read data as it arrives in whatever size the
        chunks are received. If stream=False, data is returned as
        a single chunk.

        If decode_unicode is True, content will be decoded using the best
        available encoding based on the response.
        """

        def generate():
            # Special case for urllib3.
            if hasattr(self.raw, 'stream'):
                try:
                    for chunk in self.raw.stream(chunk_size, decode_content=True):
                        yield chunk
                except ProtocolError as e:
                    raise ChunkedEncodingError(e)
                except DecodeError as e:
                    raise ContentDecodingError(e)
                except ReadTimeoutError as e:
                    raise ConnectionError(e)
            else:
                # Standard file-like object.
                while True:
                    chunk = self.raw.read(chunk_size)
                    if not chunk:
                        break
                    yield chunk

            self._content_consumed = True

        if self._content_consumed and isinstance(self._content, bool):
            raise StreamConsumedError()
        elif chunk_size is not None and not isinstance(chunk_size, int):
            raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))
        # simulate reading small chunks of the content
        reused_chunks = iter_slices(self._content, chunk_size)

        stream_chunks = generate()

        chunks = reused_chunks if self._content_consumed else stream_chunks

        if decode_unicode:
            chunks = stream_decode_response_unicode(chunks, self)

        return chunks

    def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
        """Iterates over the response data, one line at a time.  When
        stream=True is set on the request, this avoids reading the
        content at once into memory for large responses.

        .. note:: This method is not reentrant safe.
        """

        pending = None

        for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):

            if pending is not None:
                chunk = pending + chunk

            if delimiter:
                lines = chunk.split(delimiter)
            else:
                lines = chunk.splitlines()

            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
                pending = lines.pop()
            else:
                pending = None

            for line in lines:
                yield line

        if pending is not None:
            yield pending

    @property
    def content(self):
        """Content of the response, in bytes."""

        if self._content is False:
            # Read the contents.
            if self._content_consumed:
                raise RuntimeError(
                    'The content for this response was already consumed')

            if self.status_code == 0 or self.raw is None:
                self._content = None
            else:
                self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()

        self._content_consumed = True
        # don't need to release the connection; that's been handled by urllib3
        # since we exhausted the data.
        return self._content

    @property
    def text(self):
        """Content of the response, in unicode.

        If Response.encoding is None, encoding will be guessed using
        ``chardet``.

        The encoding of the response content is determined based solely on HTTP
        headers, following RFC 2616 to the letter. If you can take advantage of
        non-HTTP knowledge to make a better guess at the encoding, you should
        set ``r.encoding`` appropriately before accessing this property.
        """

        # Try charset from content-type
        content = None
        encoding = self.encoding

        if not self.content:
            return str('')

        # Fallback to auto-detected encoding.
        if self.encoding is None:
            encoding = self.apparent_encoding

        # Decode unicode from given encoding.
        try:
            content = str(self.content, encoding, errors='replace')
        except (LookupError, TypeError):
            # A LookupError is raised if the encoding was not found which could
            # indicate a misspelling or similar mistake.
            #
            # A TypeError can be raised if encoding is None
            #
            # So we try blindly encoding.
            content = str(self.content, errors='replace')

        return content

    def json(self, **kwargs):
        r"""Returns the json-encoded content of a response, if any.

        :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
        :raises ValueError: If the response body does not contain valid json.
        """

        if not self.encoding and self.content and len(self.content) > 3:
            # No encoding set. JSON RFC 4627 section 3 states we should expect
            # UTF-8, -16 or -32. Detect which one to use; If the detection or
            # decoding fails, fall back to `self.text` (using chardet to make
            # a best guess).
            encoding = guess_json_utf(self.content)
            if encoding is not None:
                try:
                    return complexjson.loads(
                        self.content.decode(encoding), **kwargs
                    )
                except UnicodeDecodeError:
                    # Wrong UTF codec detected; usually because it's not UTF-8
                    # but some other 8-bit codec.  This is an RFC violation,
                    # and the server didn't bother to tell us what codec *was*
                    # used.
                    pass
        return complexjson.loads(self.text, **kwargs)

    @property
    def links(self):
        """Returns the parsed header links of the response, if any."""

        header = self.headers.get('link')

        # l = MultiDict()
        l = {}

        if header:
            links = parse_header_links(header)

            for link in links:
                key = link.get('rel') or link.get('url')
                l[key] = link

        return l

    def raise_for_status(self):
        """Raises stored :class:`HTTPError`, if one occurred."""

        http_error_msg = ''
        if isinstance(self.reason, bytes):
            # We attempt to decode utf-8 first because some servers
            # choose to localize their reason strings. If the string
            # isn't utf-8, we fall back to iso-8859-1 for all other
            # encodings. (See PR #3538)
            try:
                reason = self.reason.decode('utf-8')
            except UnicodeDecodeError:
                reason = self.reason.decode('iso-8859-1')
        else:
            reason = self.reason

        if 400 <= self.status_code < 500:
            http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)

        elif 500 <= self.status_code < 600:
            http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)

        if http_error_msg:
            raise HTTPError(http_error_msg, response=self)

    def close(self):
        """Releases the connection back to the pool. Once this method has been
        called the underlying ``raw`` object must not be accessed again.

        *Note: Should not normally need to be called explicitly.*
        """
        if not self._content_consumed:
            self.raw.close()

        release_conn = getattr(self.raw, 'release_conn', None)
        if release_conn is not None:
            release_conn()
_vendor/requests/auth.py000064400000023000152527136320011367 0ustar00# -*- coding: utf-8 -*-

"""
requests.auth
~~~~~~~~~~~~~

This module contains the authentication handlers for Requests.
"""

import os
import re
import time
import hashlib
import threading
import warnings

from base64 import b64encode

from .compat import urlparse, str, basestring
from .cookies import extract_cookies_to_jar
from ._internal_utils import to_native_string
from .utils import parse_dict_header

CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
CONTENT_TYPE_MULTI_PART = 'multipart/form-data'


def _basic_auth_str(username, password):
    """Returns a Basic Auth string."""

    # "I want us to put a big-ol' comment on top of it that
    # says that this behaviour is dumb but we need to preserve
    # it because people are relying on it."
    #    - Lukasa
    #
    # These are here solely to maintain backwards compatibility
    # for things like ints. This will be removed in 3.0.0.
    if not isinstance(username, basestring):
        warnings.warn(
            "Non-string usernames will no longer be supported in Requests "
            "3.0.0. Please convert the object you've passed in ({0!r}) to "
            "a string or bytes object in the near future to avoid "
            "problems.".format(username),
            category=DeprecationWarning,
        )
        username = str(username)

    if not isinstance(password, basestring):
        warnings.warn(
            "Non-string passwords will no longer be supported in Requests "
            "3.0.0. Please convert the object you've passed in ({0!r}) to "
            "a string or bytes object in the near future to avoid "
            "problems.".format(password),
            category=DeprecationWarning,
        )
        password = str(password)
    # -- End Removal --

    if isinstance(username, str):
        username = username.encode('latin1')

    if isinstance(password, str):
        password = password.encode('latin1')

    authstr = 'Basic ' + to_native_string(
        b64encode(b':'.join((username, password))).strip()
    )

    return authstr


class AuthBase(object):
    """Base class that all auth implementations derive from"""

    def __call__(self, r):
        raise NotImplementedError('Auth hooks must be callable.')


class HTTPBasicAuth(AuthBase):
    """Attaches HTTP Basic Authentication to the given Request object."""

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def __eq__(self, other):
        return all([
            self.username == getattr(other, 'username', None),
            self.password == getattr(other, 'password', None)
        ])

    def __ne__(self, other):
        return not self == other

    def __call__(self, r):
        r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
        return r


class HTTPProxyAuth(HTTPBasicAuth):
    """Attaches HTTP Proxy Authentication to a given Request object."""

    def __call__(self, r):
        r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
        return r


class HTTPDigestAuth(AuthBase):
    """Attaches HTTP Digest Authentication to the given Request object."""

    def __init__(self, username, password):
        self.username = username
        self.password = password
        # Keep state in per-thread local storage
        self._thread_local = threading.local()

    def init_per_thread_state(self):
        # Ensure state is initialized just once per-thread
        if not hasattr(self._thread_local, 'init'):
            self._thread_local.init = True
            self._thread_local.last_nonce = ''
            self._thread_local.nonce_count = 0
            self._thread_local.chal = {}
            self._thread_local.pos = None
            self._thread_local.num_401_calls = None

    def build_digest_header(self, method, url):
        """
        :rtype: str
        """

        realm = self._thread_local.chal['realm']
        nonce = self._thread_local.chal['nonce']
        qop = self._thread_local.chal.get('qop')
        algorithm = self._thread_local.chal.get('algorithm')
        opaque = self._thread_local.chal.get('opaque')
        hash_utf8 = None

        if algorithm is None:
            _algorithm = 'MD5'
        else:
            _algorithm = algorithm.upper()
        # lambdas assume digest modules are imported at the top level
        if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':
            def md5_utf8(x):
                if isinstance(x, str):
                    x = x.encode('utf-8')
                return hashlib.md5(x).hexdigest()
            hash_utf8 = md5_utf8
        elif _algorithm == 'SHA':
            def sha_utf8(x):
                if isinstance(x, str):
                    x = x.encode('utf-8')
                return hashlib.sha1(x).hexdigest()
            hash_utf8 = sha_utf8

        KD = lambda s, d: hash_utf8("%s:%s" % (s, d))

        if hash_utf8 is None:
            return None

        # XXX not implemented yet
        entdig = None
        p_parsed = urlparse(url)
        #: path is request-uri defined in RFC 2616 which should not be empty
        path = p_parsed.path or "/"
        if p_parsed.query:
            path += '?' + p_parsed.query

        A1 = '%s:%s:%s' % (self.username, realm, self.password)
        A2 = '%s:%s' % (method, path)

        HA1 = hash_utf8(A1)
        HA2 = hash_utf8(A2)

        if nonce == self._thread_local.last_nonce:
            self._thread_local.nonce_count += 1
        else:
            self._thread_local.nonce_count = 1
        ncvalue = '%08x' % self._thread_local.nonce_count
        s = str(self._thread_local.nonce_count).encode('utf-8')
        s += nonce.encode('utf-8')
        s += time.ctime().encode('utf-8')
        s += os.urandom(8)

        cnonce = (hashlib.sha1(s).hexdigest()[:16])
        if _algorithm == 'MD5-SESS':
            HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))

        if not qop:
            respdig = KD(HA1, "%s:%s" % (nonce, HA2))
        elif qop == 'auth' or 'auth' in qop.split(','):
            noncebit = "%s:%s:%s:%s:%s" % (
                nonce, ncvalue, cnonce, 'auth', HA2
            )
            respdig = KD(HA1, noncebit)
        else:
            # XXX handle auth-int.
            return None

        self._thread_local.last_nonce = nonce

        # XXX should the partial digests be encoded too?
        base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
               'response="%s"' % (self.username, realm, nonce, path, respdig)
        if opaque:
            base += ', opaque="%s"' % opaque
        if algorithm:
            base += ', algorithm="%s"' % algorithm
        if entdig:
            base += ', digest="%s"' % entdig
        if qop:
            base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)

        return 'Digest %s' % (base)

    def handle_redirect(self, r, **kwargs):
        """Reset num_401_calls counter on redirects."""
        if r.is_redirect:
            self._thread_local.num_401_calls = 1

    def handle_401(self, r, **kwargs):
        """
        Takes the given response and tries digest-auth, if needed.

        :rtype: requests.Response
        """

        # If response is not 4xx, do not auth
        # See https://github.com/requests/requests/issues/3772
        if not 400 <= r.status_code < 500:
            self._thread_local.num_401_calls = 1
            return r

        if self._thread_local.pos is not None:
            # Rewind the file position indicator of the body to where
            # it was to resend the request.
            r.request.body.seek(self._thread_local.pos)
        s_auth = r.headers.get('www-authenticate', '')

        if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:

            self._thread_local.num_401_calls += 1
            pat = re.compile(r'digest ', flags=re.IGNORECASE)
            self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))

            # Consume content and release the original connection
            # to allow our new request to reuse the same one.
            r.content
            r.close()
            prep = r.request.copy()
            extract_cookies_to_jar(prep._cookies, r.request, r.raw)
            prep.prepare_cookies(prep._cookies)

            prep.headers['Authorization'] = self.build_digest_header(
                prep.method, prep.url)
            _r = r.connection.send(prep, **kwargs)
            _r.history.append(r)
            _r.request = prep

            return _r

        self._thread_local.num_401_calls = 1
        return r

    def __call__(self, r):
        # Initialize per-thread state, if needed
        self.init_per_thread_state()
        # If we have a saved nonce, skip the 401
        if self._thread_local.last_nonce:
            r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
        try:
            self._thread_local.pos = r.body.tell()
        except AttributeError:
            # In the case of HTTPDigestAuth being reused and the body of
            # the previous request was a file-like object, pos has the
            # file position of the previous body. Ensure it's set to
            # None.
            self._thread_local.pos = None
        r.register_hook('response', self.handle_401)
        r.register_hook('response', self.handle_redirect)
        self._thread_local.num_401_calls = 1

        return r

    def __eq__(self, other):
        return all([
            self.username == getattr(other, 'username', None),
            self.password == getattr(other, 'password', None)
        ])

    def __ne__(self, other):
        return not self == other
_vendor/requests/api.py000064400000014135152527136320011210 0ustar00# -*- coding: utf-8 -*-

"""
requests.api
~~~~~~~~~~~~

This module implements the Requests API.

:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""

from . import sessions


def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request `.

    :param method: method for the new :class:`Request` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) ` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response ` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'http://httpbin.org/get')
      
    """

    # By using the 'with' statement we are sure the session is closed, thus we
    # avoid leaving sockets open which can trigger a ResourceWarning in some
    # cases, and look like a memory leak in others.
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)


def get(url, params=None, **kwargs):
    r"""Sends a GET request.

    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)


def options(url, **kwargs):
    r"""Sends an OPTIONS request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('options', url, **kwargs)


def head(url, **kwargs):
    r"""Sends a HEAD request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', False)
    return request('head', url, **kwargs)


def post(url, data=None, json=None, **kwargs):
    r"""Sends a POST request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    """

    return request('post', url, data=data, json=json, **kwargs)


def put(url, data=None, **kwargs):
    r"""Sends a PUT request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    """

    return request('put', url, data=data, **kwargs)


def patch(url, data=None, **kwargs):
    r"""Sends a PATCH request.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    """

    return request('patch', url, data=data, **kwargs)


def delete(url, **kwargs):
    r"""Sends a DELETE request.

    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response ` object
    :rtype: requests.Response
    """

    return request('delete', url, **kwargs)
_vendor/requests/hooks.pyo000064400000002323152527136320011735 0ustar00
abc@s%dZdgZdZdZdS(s
requests.hooks
~~~~~~~~~~~~~~

This module provides the capabilities for the Requests hooks system.

Available hooks:

``response``:
    The response generated from a Request.
tresponsecCstdtDS(Ncss|]}|gfVqdS(N((t.0tevent((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pys	s(tdicttHOOKS(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pyt
default_hooksscKs{|pt}|j|}|rwt|dr?|g}nx5|D]*}|||}|dk	rF|}qFqFWn|S(s6Dispatches a hook dictionary on a given piece of data.t__call__N(RtgetthasattrtNone(tkeythookst	hook_datatkwargsthookt
_hook_data((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pyt
dispatch_hooks
N(t__doc__RRR(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/hooks.pyt
s		_vendor/requests/__version__.py000064400000000664152527136320012722 0ustar00# .-. .-. .-. . . .-. .-. .-. .-.
# |(  |-  |.| | | |-  `-.  |  `-.
# ' ' `-' `-`.`-' `-' `-'  '  `-'

__title__ = 'requests'
__description__ = 'Python HTTP for Humans.'
__url__ = 'http://python-requests.org'
__version__ = '2.18.4'
__build__ = 0x021804
__author__ = 'Kenneth Reitz'
__author_email__ = 'me@kennethreitz.org'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2017 Kenneth Reitz'
__cake__ = u'\u2728 \U0001f370 \u2728'
_vendor/requests/structures.py000064400000005704152527136320012664 0ustar00# -*- coding: utf-8 -*-

"""
requests.structures
~~~~~~~~~~~~~~~~~~~

Data structures that power Requests.
"""

import collections

from .compat import OrderedDict


class CaseInsensitiveDict(collections.MutableMapping):
    """A case-insensitive ``dict``-like object.

    Implements all methods and operations of
    ``collections.MutableMapping`` as well as dict's ``copy``. Also
    provides ``lower_items``.

    All keys are expected to be strings. The structure remembers the
    case of the last key to be set, and ``iter(instance)``,
    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
    will contain case-sensitive keys. However, querying and contains
    testing is case insensitive::

        cid = CaseInsensitiveDict()
        cid['Accept'] = 'application/json'
        cid['aCCEPT'] == 'application/json'  # True
        list(cid) == ['Accept']  # True

    For example, ``headers['content-encoding']`` will return the
    value of a ``'Content-Encoding'`` response header, regardless
    of how the header name was originally stored.

    If the constructor, ``.update``, or equality comparison
    operations are given keys that have equal ``.lower()``s, the
    behavior is undefined.
    """

    def __init__(self, data=None, **kwargs):
        self._store = OrderedDict()
        if data is None:
            data = {}
        self.update(data, **kwargs)

    def __setitem__(self, key, value):
        # Use the lowercased key for lookups, but store the actual
        # key alongside the value.
        self._store[key.lower()] = (key, value)

    def __getitem__(self, key):
        return self._store[key.lower()][1]

    def __delitem__(self, key):
        del self._store[key.lower()]

    def __iter__(self):
        return (casedkey for casedkey, mappedvalue in self._store.values())

    def __len__(self):
        return len(self._store)

    def lower_items(self):
        """Like iteritems(), but with all lowercase keys."""
        return (
            (lowerkey, keyval[1])
            for (lowerkey, keyval)
            in self._store.items()
        )

    def __eq__(self, other):
        if isinstance(other, collections.Mapping):
            other = CaseInsensitiveDict(other)
        else:
            return NotImplemented
        # Compare insensitively
        return dict(self.lower_items()) == dict(other.lower_items())

    # Copy is required
    def copy(self):
        return CaseInsensitiveDict(self._store.values())

    def __repr__(self):
        return str(dict(self.items()))


class LookupDict(dict):
    """Dictionary lookup object."""

    def __init__(self, name=None):
        self.name = name
        super(LookupDict, self).__init__()

    def __repr__(self):
        return '' % (self.name)

    def __getitem__(self, key):
        # We allow fall-through here, so values default to None

        return self.__dict__.get(key, None)

    def get(self, key, default=None):
        return self.__dict__.get(key, default)
_vendor/requests/packages.pyo000064400000001102152527136320012362 0ustar00
abc@sddlZxdD]ZdeZeeees

_vendor/requests/sessions.py000064400000070021152527136320012301 0ustar00# -*- coding: utf-8 -*-

"""
requests.session
~~~~~~~~~~~~~~~~

This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
"""
import os
import platform
import time
from collections import Mapping
from datetime import timedelta

from .auth import _basic_auth_str
from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse
from .cookies import (
    cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)
from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT
from .hooks import default_hooks, dispatch_hook
from ._internal_utils import to_native_string
from .utils import to_key_val_list, default_headers
from .exceptions import (
    TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)

from .structures import CaseInsensitiveDict
from .adapters import HTTPAdapter

from .utils import (
    requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,
    get_auth_from_url, rewind_body, DEFAULT_PORTS
)

from .status_codes import codes

# formerly defined here, reexposed here for backward compatibility
from .models import REDIRECT_STATI

# Preferred clock, based on which one is more accurate on a given system.
if platform.system() == 'Windows':
    try:  # Python 3.3+
        preferred_clock = time.perf_counter
    except AttributeError:  # Earlier than Python 3.
        preferred_clock = time.clock
else:
    preferred_clock = time.time


def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
    """Determines appropriate setting for a given request, taking into account
    the explicit setting on that request, and the setting in the session. If a
    setting is a dictionary, they will be merged together using `dict_class`
    """

    if session_setting is None:
        return request_setting

    if request_setting is None:
        return session_setting

    # Bypass if not a dictionary (e.g. verify)
    if not (
            isinstance(session_setting, Mapping) and
            isinstance(request_setting, Mapping)
    ):
        return request_setting

    merged_setting = dict_class(to_key_val_list(session_setting))
    merged_setting.update(to_key_val_list(request_setting))

    # Remove keys that are set to None. Extract keys first to avoid altering
    # the dictionary during iteration.
    none_keys = [k for (k, v) in merged_setting.items() if v is None]
    for key in none_keys:
        del merged_setting[key]

    return merged_setting


def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
    """Properly merges both requests and session hooks.

    This is necessary because when request_hooks == {'response': []}, the
    merge breaks Session hooks entirely.
    """
    if session_hooks is None or session_hooks.get('response') == []:
        return request_hooks

    if request_hooks is None or request_hooks.get('response') == []:
        return session_hooks

    return merge_setting(request_hooks, session_hooks, dict_class)


class SessionRedirectMixin(object):

    def get_redirect_target(self, resp):
        """Receives a Response. Returns a redirect URI or ``None``"""
        # Due to the nature of how requests processes redirects this method will
        # be called at least once upon the original response and at least twice
        # on each subsequent redirect response (if any).
        # If a custom mixin is used to handle this logic, it may be advantageous
        # to cache the redirect location onto the response object as a private
        # attribute.
        if resp.is_redirect:
            location = resp.headers['location']
            # Currently the underlying http module on py3 decode headers
            # in latin1, but empirical evidence suggests that latin1 is very
            # rarely used with non-ASCII characters in HTTP headers.
            # It is more likely to get UTF8 header rather than latin1.
            # This causes incorrect handling of UTF8 encoded location headers.
            # To solve this, we re-encode the location in latin1.
            if is_py3:
                location = location.encode('latin1')
            return to_native_string(location, 'utf8')
        return None


    def should_strip_auth(self, old_url, new_url):
        """Decide whether Authorization header should be removed when redirecting"""
        old_parsed = urlparse(old_url)
        new_parsed = urlparse(new_url)
        if old_parsed.hostname != new_parsed.hostname:
            return True
        # Special case: allow http -> https redirect when using the standard
        # ports. This isn't specified by RFC 7235, but is kept to avoid
        # breaking backwards compatibility with older versions of requests
        # that allowed any redirects on the same host.
        if (old_parsed.scheme == 'http' and old_parsed.port in (80, None)
                and new_parsed.scheme == 'https' and new_parsed.port in (443, None)):
            return False

        # Handle default port usage corresponding to scheme.
        changed_port = old_parsed.port != new_parsed.port
        changed_scheme = old_parsed.scheme != new_parsed.scheme
        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
        if (not changed_scheme and old_parsed.port in default_port
                and new_parsed.port in default_port):
            return False

        # Standard case: root URI must match
        return changed_port or changed_scheme

    def resolve_redirects(self, resp, req, stream=False, timeout=None,
                          verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
        """Receives a Response. Returns a generator of Responses or Requests."""

        hist = []  # keep track of history

        url = self.get_redirect_target(resp)
        while url:
            prepared_request = req.copy()

            # Update history and keep track of redirects.
            # resp.history must ignore the original request in this loop
            hist.append(resp)
            resp.history = hist[1:]

            try:
                resp.content  # Consume socket so it can be released
            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
                resp.raw.read(decode_content=False)

            if len(resp.history) >= self.max_redirects:
                raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)

            # Release the connection back into the pool.
            resp.close()

            # Handle redirection without scheme (see: RFC 1808 Section 4)
            if url.startswith('//'):
                parsed_rurl = urlparse(resp.url)
                url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)

            # The scheme should be lower case...
            parsed = urlparse(url)
            url = parsed.geturl()

            # Facilitate relative 'location' headers, as allowed by RFC 7231.
            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
            # Compliant with RFC3986, we percent encode the url.
            if not parsed.netloc:
                url = urljoin(resp.url, requote_uri(url))
            else:
                url = requote_uri(url)

            prepared_request.url = to_native_string(url)

            self.rebuild_method(prepared_request, resp)

            # https://github.com/requests/requests/issues/1084
            if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
                # https://github.com/requests/requests/issues/3490
                purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')
                for header in purged_headers:
                    prepared_request.headers.pop(header, None)
                prepared_request.body = None

            headers = prepared_request.headers
            try:
                del headers['Cookie']
            except KeyError:
                pass

            # Extract any cookies sent on the response to the cookiejar
            # in the new request. Because we've mutated our copied prepared
            # request, use the old one that we haven't yet touched.
            extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
            merge_cookies(prepared_request._cookies, self.cookies)
            prepared_request.prepare_cookies(prepared_request._cookies)

            # Rebuild auth and proxy information.
            proxies = self.rebuild_proxies(prepared_request, proxies)
            self.rebuild_auth(prepared_request, resp)

            # A failed tell() sets `_body_position` to `object()`. This non-None
            # value ensures `rewindable` will be True, allowing us to raise an
            # UnrewindableBodyError, instead of hanging the connection.
            rewindable = (
                prepared_request._body_position is not None and
                ('Content-Length' in headers or 'Transfer-Encoding' in headers)
            )

            # Attempt to rewind consumed file-like object.
            if rewindable:
                rewind_body(prepared_request)

            # Override the original request.
            req = prepared_request

            if yield_requests:
                yield req
            else:

                resp = self.send(
                    req,
                    stream=stream,
                    timeout=timeout,
                    verify=verify,
                    cert=cert,
                    proxies=proxies,
                    allow_redirects=False,
                    **adapter_kwargs
                )

                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)

                # extract redirect url, if any, for the next loop
                url = self.get_redirect_target(resp)
                yield resp

    def rebuild_auth(self, prepared_request, response):
        """When being redirected we may want to strip authentication from the
        request to avoid leaking credentials. This method intelligently removes
        and reapplies authentication where possible to avoid credential loss.
        """
        headers = prepared_request.headers
        url = prepared_request.url

        if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):
            # If we get redirected to a new host, we should strip out any
            # authentication headers.
            del headers['Authorization']

        # .netrc might have more auth for us on our new host.
        new_auth = get_netrc_auth(url) if self.trust_env else None
        if new_auth is not None:
            prepared_request.prepare_auth(new_auth)

        return

    def rebuild_proxies(self, prepared_request, proxies):
        """This method re-evaluates the proxy configuration by considering the
        environment variables. If we are redirected to a URL covered by
        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
        proxy keys for this URL (in case they were stripped by a previous
        redirect).

        This method also replaces the Proxy-Authorization header where
        necessary.

        :rtype: dict
        """
        proxies = proxies if proxies is not None else {}
        headers = prepared_request.headers
        url = prepared_request.url
        scheme = urlparse(url).scheme
        new_proxies = proxies.copy()
        no_proxy = proxies.get('no_proxy')

        bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)
        if self.trust_env and not bypass_proxy:
            environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)

            proxy = environ_proxies.get(scheme, environ_proxies.get('all'))

            if proxy:
                new_proxies.setdefault(scheme, proxy)

        if 'Proxy-Authorization' in headers:
            del headers['Proxy-Authorization']

        try:
            username, password = get_auth_from_url(new_proxies[scheme])
        except KeyError:
            username, password = None, None

        if username and password:
            headers['Proxy-Authorization'] = _basic_auth_str(username, password)

        return new_proxies

    def rebuild_method(self, prepared_request, response):
        """When being redirected we may want to change the method of the request
        based on certain specs or browser behavior.
        """
        method = prepared_request.method

        # http://tools.ietf.org/html/rfc7231#section-6.4.4
        if response.status_code == codes.see_other and method != 'HEAD':
            method = 'GET'

        # Do what the browsers do, despite standards...
        # First, turn 302s into GETs.
        if response.status_code == codes.found and method != 'HEAD':
            method = 'GET'

        # Second, if a POST is responded to with a 301, turn it into a GET.
        # This bizarre behaviour is explained in Issue 1704.
        if response.status_code == codes.moved and method == 'POST':
            method = 'GET'

        prepared_request.method = method


class Session(SessionRedirectMixin):
    """A Requests session.

    Provides cookie persistence, connection-pooling, and configuration.

    Basic Usage::

      >>> import requests
      >>> s = requests.Session()
      >>> s.get('http://httpbin.org/get')
      

    Or as a context manager::

      >>> with requests.Session() as s:
      >>>     s.get('http://httpbin.org/get')
      
    """

    __attrs__ = [
        'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
        'cert', 'prefetch', 'adapters', 'stream', 'trust_env',
        'max_redirects',
    ]

    def __init__(self):

        #: A case-insensitive dictionary of headers to be sent on each
        #: :class:`Request ` sent from this
        #: :class:`Session `.
        self.headers = default_headers()

        #: Default Authentication tuple or object to attach to
        #: :class:`Request `.
        self.auth = None

        #: Dictionary mapping protocol or protocol and host to the URL of the proxy
        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
        #: be used on each :class:`Request `.
        self.proxies = {}

        #: Event-handling hooks.
        self.hooks = default_hooks()

        #: Dictionary of querystring data to attach to each
        #: :class:`Request `. The dictionary values may be lists for
        #: representing multivalued query parameters.
        self.params = {}

        #: Stream response content default.
        self.stream = False

        #: SSL Verification default.
        self.verify = True

        #: SSL client certificate default, if String, path to ssl client
        #: cert file (.pem). If Tuple, ('cert', 'key') pair.
        self.cert = None

        #: Maximum number of redirects allowed. If the request exceeds this
        #: limit, a :class:`TooManyRedirects` exception is raised.
        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
        #: 30.
        self.max_redirects = DEFAULT_REDIRECT_LIMIT

        #: Trust environment settings for proxy configuration, default
        #: authentication and similar.
        self.trust_env = True

        #: A CookieJar containing all currently outstanding cookies set on this
        #: session. By default it is a
        #: :class:`RequestsCookieJar `, but
        #: may be any other ``cookielib.CookieJar`` compatible object.
        self.cookies = cookiejar_from_dict({})

        # Default connection adapters.
        self.adapters = OrderedDict()
        self.mount('https://', HTTPAdapter())
        self.mount('http://', HTTPAdapter())

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def prepare_request(self, request):
        """Constructs a :class:`PreparedRequest ` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request ` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        :rtype: requests.PreparedRequest
        """
        cookies = request.cookies or {}

        # Bootstrap CookieJar.
        if not isinstance(cookies, cookielib.CookieJar):
            cookies = cookiejar_from_dict(cookies)

        # Merge with session cookies
        merged_cookies = merge_cookies(
            merge_cookies(RequestsCookieJar(), self.cookies), cookies)

        # Set environment's basic authentication if not explicitly set.
        auth = request.auth
        if self.trust_env and not auth and not self.auth:
            auth = get_netrc_auth(request.url)

        p = PreparedRequest()
        p.prepare(
            method=request.method.upper(),
            url=request.url,
            files=request.files,
            data=request.data,
            json=request.json,
            headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
            params=merge_setting(request.params, self.params),
            auth=merge_setting(auth, self.auth),
            cookies=merged_cookies,
            hooks=merge_hooks(request.hooks, self.hooks),
        )
        return p

    def request(self, method, url,
            params=None, data=None, headers=None, cookies=None, files=None,
            auth=None, timeout=None, allow_redirects=True, proxies=None,
            hooks=None, stream=None, verify=None, cert=None, json=None):
        """Constructs a :class:`Request `, prepares it and sends it.
        Returns :class:`Response ` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query
            string for the :class:`Request`.
        :param data: (optional) Dictionary, bytes, or file-like object to send
            in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the
            :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the
            :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the
            :class:`Request`.
        :param files: (optional) Dictionary of ``'filename': file-like-objects``
            for multipart encoding upload.
        :param auth: (optional) Auth tuple or callable to enable
            Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol or protocol and
            hostname to the URL of the proxy.
        :param stream: (optional) whether to immediately download the response
            content. Defaults to ``False``.
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        """
        # Create the Request.
        req = Request(
            method=method.upper(),
            url=url,
            headers=headers,
            files=files,
            data=data or {},
            json=json,
            params=params or {},
            auth=auth,
            cookies=cookies,
            hooks=hooks,
        )
        prep = self.prepare_request(req)

        proxies = proxies or {}

        settings = self.merge_environment_settings(
            prep.url, proxies, stream, verify, cert
        )

        # Send the request.
        send_kwargs = {
            'timeout': timeout,
            'allow_redirects': allow_redirects,
        }
        send_kwargs.update(settings)
        resp = self.send(prep, **send_kwargs)

        return resp

    def get(self, url, **kwargs):
        r"""Sends a GET request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        kwargs.setdefault('allow_redirects', True)
        return self.request('GET', url, **kwargs)

    def options(self, url, **kwargs):
        r"""Sends a OPTIONS request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        kwargs.setdefault('allow_redirects', True)
        return self.request('OPTIONS', url, **kwargs)

    def head(self, url, **kwargs):
        r"""Sends a HEAD request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        kwargs.setdefault('allow_redirects', False)
        return self.request('HEAD', url, **kwargs)

    def post(self, url, data=None, json=None, **kwargs):
        r"""Sends a POST request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        return self.request('POST', url, data=data, json=json, **kwargs)

    def put(self, url, data=None, **kwargs):
        r"""Sends a PUT request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        return self.request('PUT', url, data=data, **kwargs)

    def patch(self, url, data=None, **kwargs):
        r"""Sends a PATCH request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        return self.request('PATCH', url, data=data, **kwargs)

    def delete(self, url, **kwargs):
        r"""Sends a DELETE request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        """

        return self.request('DELETE', url, **kwargs)

    def send(self, request, **kwargs):
        """Send a given PreparedRequest.

        :rtype: requests.Response
        """
        # Set defaults that the hooks can utilize to ensure they always have
        # the correct parameters to reproduce the previous request.
        kwargs.setdefault('stream', self.stream)
        kwargs.setdefault('verify', self.verify)
        kwargs.setdefault('cert', self.cert)
        kwargs.setdefault('proxies', self.proxies)

        # It's possible that users might accidentally send a Request object.
        # Guard against that specific failure case.
        if isinstance(request, Request):
            raise ValueError('You can only send PreparedRequests.')

        # Set up variables needed for resolve_redirects and dispatching of hooks
        allow_redirects = kwargs.pop('allow_redirects', True)
        stream = kwargs.get('stream')
        hooks = request.hooks

        # Get the appropriate adapter to use
        adapter = self.get_adapter(url=request.url)

        # Start time (approximately) of the request
        start = preferred_clock()

        # Send the request
        r = adapter.send(request, **kwargs)

        # Total elapsed time of the request (approximately)
        elapsed = preferred_clock() - start
        r.elapsed = timedelta(seconds=elapsed)

        # Response manipulation hooks
        r = dispatch_hook('response', hooks, r, **kwargs)

        # Persist cookies
        if r.history:

            # If the hooks create history then we want those cookies too
            for resp in r.history:
                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)

        extract_cookies_to_jar(self.cookies, request, r.raw)

        # Redirect resolving generator.
        gen = self.resolve_redirects(r, request, **kwargs)

        # Resolve redirects if allowed.
        history = [resp for resp in gen] if allow_redirects else []

        # Shuffle things around if there's history.
        if history:
            # Insert the first (original) request at the start
            history.insert(0, r)
            # Get the last request made
            r = history.pop()
            r.history = history

        # If redirects aren't being followed, store the response on the Request for Response.next().
        if not allow_redirects:
            try:
                r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs))
            except StopIteration:
                pass

        if not stream:
            r.content

        return r

    def merge_environment_settings(self, url, proxies, stream, verify, cert):
        """
        Check the environment and merge it with some settings.

        :rtype: dict
        """
        # Gather clues from the surrounding environment.
        if self.trust_env:
            # Set environment's proxies.
            no_proxy = proxies.get('no_proxy') if proxies is not None else None
            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
            for (k, v) in env_proxies.items():
                proxies.setdefault(k, v)

            # Look for requests environment configuration and be compatible
            # with cURL.
            if verify is True or verify is None:
                verify = (os.environ.get('REQUESTS_CA_BUNDLE') or
                          os.environ.get('CURL_CA_BUNDLE'))

        # Merge all the kwargs.
        proxies = merge_setting(proxies, self.proxies)
        stream = merge_setting(stream, self.stream)
        verify = merge_setting(verify, self.verify)
        cert = merge_setting(cert, self.cert)

        return {'verify': verify, 'proxies': proxies, 'stream': stream,
                'cert': cert}

    def get_adapter(self, url):
        """
        Returns the appropriate connection adapter for the given URL.

        :rtype: requests.adapters.BaseAdapter
        """
        for (prefix, adapter) in self.adapters.items():

            if url.lower().startswith(prefix):
                return adapter

        # Nothing matches :-/
        raise InvalidSchema("No connection adapters were found for '%s'" % url)

    def close(self):
        """Closes all adapters and as such the session"""
        for v in self.adapters.values():
            v.close()

    def mount(self, prefix, adapter):
        """Registers a connection adapter to a prefix.

        Adapters are sorted in descending order by prefix length.
        """
        self.adapters[prefix] = adapter
        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]

        for key in keys_to_move:
            self.adapters[key] = self.adapters.pop(key)

    def __getstate__(self):
        state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
        return state

    def __setstate__(self, state):
        for attr, value in state.items():
            setattr(self, attr, value)


def session():
    """
    Returns a :class:`Session` for context-management.

    :rtype: Session
    """

    return Session()
_vendor/requests/__init__.pyo000064400000007147152527136320012362 0ustar00
abc@stdZddlmZddlmZddlZddlmZdZyeejejWn9e	e
fk
rejdjejejenXdd	l
mZejd
eddlmZmZmZmZddlmZmZmZmZdd
lmZmZddlmZddlmZddlmZmZmZddl m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*m+Z+ddl,m-Z-ddlm.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6ddl7Z7yddl7m8Z8Wn*e9k
r@de7j:fdYZ8nXe7j;e<j=e8ejde4de>dS(s
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~

Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:

   >>> import requests
   >>> r = requests.get('https://www.python.org')
   >>> r.status_code
   200
   >>> 'Python is a programming language' in r.content
   True

... or POST:

   >>> payload = dict(key1='value1', key2='value2')
   >>> r = requests.post('http://httpbin.org/post', data=payload)
   >>> print(r.text)
   {
     ...
     "form": {
       "key2": "value2",
       "key1": "value1"
     },
     ...
   }

The other HTTP methods are supported - see `requests.api`. Full documentation
is at .

:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
i(turllib3(tchardetNi(tRequestsDependencyWarningcCs|jd}t|dkr1|jdn|\}}}t|t|t|}}}|jdd \}}}t|t|t|}}}dS(Nt.it0i(tsplittlentappendtint(turllib3_versiontchardet_versiontmajortminortpatch((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pytcheck_compatibility1s&&sAurllib3 ({0}) or chardet ({1}) doesn't match a supported version!(tDependencyWarningtignore(t	__title__t__description__t__url__t__version__(t	__build__t
__author__t__author_email__t__license__(t
__copyright__t__cake__(tutils(tpackages(tRequesttResponsetPreparedRequest(trequesttgettheadtpostR
tputtdeletetoptions(tsessiontSession(tcodes(	tRequestExceptiontTimeouttURLRequiredtTooManyRedirectst	HTTPErrortConnectionErrortFileModeWarningtConnectTimeouttReadTimeout(tNullHandlerR3cBseZdZRS(cCsdS(N((tselftrecord((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pytemitss(t__name__t
__module__R6(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pyR3rstdefaultR(?t__doc__tpip._vendorRRtwarningst
exceptionsRRRtAssertionErrort
ValueErrortwarntformattpip._vendor.urllib3.exceptionsRtsimplefilterRRRRRRRRRtRRtmodelsRRRtapiR R!R"R#R
R$R%R&tsessionsR'R(tstatus_codesR)R*R+R,R-R.R/R0R1R2tloggingR3tImportErrortHandlert	getLoggerR7t
addHandlertTrue(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/__init__.pyt)s<	
"":@
_vendor/requests/adapters.pyc000064400000045043152527136320012407 0ustar00
abc@s5dZddlZddlZddlmZmZddlmZddl	m
Zddlm
Z
ddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZm Z ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-m.Z.m/Z/mZmZm0Z0m1Z1ddl2m3Z3yddl4m5Z5Wne6k
rdZ5nXe7Z8dZ9dZ:dZ<de=fdYZ>de>fd YZ?dS(!s
requests.adapters
~~~~~~~~~~~~~~~~~

This module contains the transport adapters that Requests uses to define
and maintain connections.
iN(tPoolManagertproxy_from_url(tHTTPResponse(tTimeout(tRetry(tClosedPoolError(tConnectTimeoutError(t	HTTPError(t
MaxRetryError(tNewConnectionError(t
ProxyError(t
ProtocolError(tReadTimeoutError(tSSLError(t
ResponseErrori(tResponse(turlparset
basestring(tDEFAULT_CA_BUNDLE_PATHtget_encoding_from_headerstprepend_scheme_if_neededtget_auth_from_urlt
urldefragauthtselect_proxy(tCaseInsensitiveDict(textract_cookies_to_jar(tConnectionErrortConnectTimeouttReadTimeoutR
R
t
RetryErrort
InvalidSchema(t_basic_auth_str(tSOCKSProxyManagercOstddS(Ns'Missing dependencies for SOCKS support.(R(targstkwargs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR +si
itBaseAdaptercBs8eZdZdZededddZdZRS(sThe Base Transport AdaptercCstt|jdS(N(tsuperR#t__init__(tself((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR%7scCs
tdS(sCSends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest ` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        N(tNotImplementedError(R&trequesttstreamttimeouttverifytcerttproxies((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytsend:scCs
tdS(s!Cleans up adapter specific items.N(R'(R&((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytcloseLsN(	t__name__t
__module__t__doc__R%tFalsetNonetTrueR.R/(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR#4s
		tHTTPAdaptercBseZdZdddddgZeeeedZdZdZ	ed	Z
d
ZdZdZ
dd
ZdZdZdZdZededddZRS(sThe built-in HTTP Adapter for urllib3.

    Provides a general-case interface for Requests sessions to contact HTTP and
    HTTPS urls by implementing the Transport Adapter interface. This class will
    usually be created by the :class:`Session ` class under the
    covers.

    :param pool_connections: The number of urllib3 connection pools to cache.
    :param pool_maxsize: The maximum number of connections to save in the pool.
    :param max_retries: The maximum number of retries each connection
        should attempt. Note, this applies only to failed DNS lookups, socket
        connections and connection timeouts, never to requests where data has
        made it to the server. By default, Requests does not retry failed
        connections. If you need granular control over the conditions under
        which we retry a request, import urllib3's ``Retry`` class and pass
        that instead.
    :param pool_block: Whether the connection pool should block for connections.

    Usage::

      >>> import requests
      >>> s = requests.Session()
      >>> a = requests.adapters.HTTPAdapter(max_retries=3)
      >>> s.mount('http://', a)
    tmax_retriestconfigt_pool_connectionst
_pool_maxsizet_pool_blockcCs|tkr$tddt|_ntj||_i|_i|_tt|j	||_
||_||_|j
||d|dS(Nitreadtblock(tDEFAULT_RETRIESRR3R7tfrom_intR8t
proxy_managerR$R6R%R9R:R;tinit_poolmanager(R&tpool_connectionstpool_maxsizeR7t
pool_block((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR%ns					cstfdjDS(Nc3s'|]}|t|dfVqdS(N(tgetattrR4(t.0tattr(R&(sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pys	s(tdictt	__attrs__(R&((R&sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyt__getstate__scCsbi|_i|_x*|jD]\}}t|||qW|j|j|jd|jdS(NR=(R@R8titemstsetattrRAR9R:R;(R&tstateRGtvalue((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyt__setstate__s		c
KsF||_||_||_td|d|d|dt||_dS(sInitializes a urllib3 PoolManager.

        This method should not be called from user code, and is only
        exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param connections: The number of urllib3 connection pools to cache.
        :param maxsize: The maximum number of connections to save in the pool.
        :param block: Block when no free connections are available.
        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
        t	num_poolstmaxsizeR=tstrictN(R9R:R;RR5tpoolmanager(R&tconnectionsRQR=tpool_kwargs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyRAs

			c
Ks||jkr|j|}n|jjdrt|\}}t|d|d|d|jd|jd|j|}|j|`.

        :param proxy: The proxy to return a urllib3 ProxyManager for.
        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
        :returns: ProxyManager
        :rtype: urllib3.ProxyManager
        tsockstusernametpasswordRPRQR=t
proxy_headers(
R@tlowert
startswithRR R9R:R;RYR(R&tproxytproxy_kwargstmanagerRWRXRY((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytproxy_manager_fors*				cCs|jjdr|rd	}|tk	r6|}n|sEt}n|s_tjj|rwtdj	|nd|_
tjj|s||_q||_
nd|_
d	|_d	|_
|rt|ts|d|_|d|_n||_d	|_|jrCtjj|jrCtdj	|jn|jrtjj|jrtdj	|jqnd	S(
sAVerify a SSL certificate. This method should not be called from user
        code, and is only exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param conn: The urllib3 connection object associated with the cert.
        :param url: The requested URL.
        :param verify: Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use
        :param cert: The SSL certificate to verify.
        thttpssFCould not find a suitable TLS CA certificate bundle, invalid path: {0}t
CERT_REQUIREDt	CERT_NONEiis:Could not find the TLS certificate file, invalid path: {0}s2Could not find the TLS key file, invalid path: {0}N(RZR[R4R5RtostpathtexiststIOErrortformatt	cert_reqstisdirtca_certstca_cert_dirt
isinstanceRt	cert_filetkey_file(R&tconnturlR+R,tcert_loc((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytcert_verifys8							
				cCst}t|dd|_tt|di|_t|j|_||_|jj	|_	t
|jtr|jj
d|_n|j|_t|j||||_||_|S(sBuilds a :class:`Response ` object from a urllib3
        response. This should not be called from user code, and is only exposed
        for use when subclassing the
        :class:`HTTPAdapter `

        :param req: The :class:`PreparedRequest ` used to generate the response.
        :param resp: The urllib3 response object.
        :rtype: requests.Response
        tstatustheaderssutf-8N(RRER4tstatus_codeRRtRtencodingtrawtreasonRlRptbytestdecodeRtcookiesR(t
connection(R&treqtresptresponse((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytbuild_responses
				cCsst||}|rEt|d}|j|}|j|}n*t|}|j}|jj|}|S(sReturns a urllib3 connection for the given URL. This should not be
        called from user code, and is only exposed for use when subclassing the
        :class:`HTTPAdapter `.

        :param url: The URL to connect to.
        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
        :rtype: urllib3.ConnectionPool
        thttp(RRR_tconnection_from_urlRtgeturlRS(R&RpR-R\R@Rotparsed((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytget_connection"s	cCs5|jjx!|jjD]}|jqWdS(sDisposes of any internal state.

        Currently, this closes the PoolManager and any active ProxyManager,
        which closes any pooled connections.
        N(RStclearR@tvalues(R&R\((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR/9s
c	Cst|j|}t|jj}|o3|dk}t}|rit|jj}|jd}n|j}|r|rt|j}n|S(s?Obtain the url to use when making the final request.

        If the message is being sent through a HTTP proxy, the full URL has to
        be used. Otherwise, we should only use the path portion of the URL.

        This should not be called from user code, and is only exposed for use
        when subclassing the
        :class:`HTTPAdapter `.

        :param request: The :class:`PreparedRequest ` being sent.
        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
        :rtype: str
        R`RV(	RRpRtschemeR3RZR[tpath_urlR(	R&R(R-R\Rtis_proxied_http_requesttusing_socks_proxytproxy_schemeRp((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytrequest_urlCs	
cKsdS(s"Add any headers needed by the connection. As of v2.0 this does
        nothing by default, but is left for overriding by users that subclass
        the :class:`HTTPAdapter `.

        This should not be called from user code, and is only exposed for use
        when subclassing the
        :class:`HTTPAdapter `.

        :param request: The :class:`PreparedRequest ` to add headers to.
        :param kwargs: The keyword arguments from the call to send().
        N((R&R(R"((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pytadd_headers`scCs8i}t|\}}|r4t|||d`.

        :param proxies: The url of the proxy being used for this request.
        :rtype: dict
        sProxy-Authorization(RR(R&R\RtRWRX((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyRYns
cCs}|j|j|}|j||j|||j||}|j||jdkphd|jk}	t|t	ry%|\}
}t
d|
d|}Wqtk
r}dj|}
t|
qXn't|t
rnt
d|d|}y|	s[|j
d|jd|d|jd|jd	td
tdtdtd
|jd|
}nft|drv|j}n|jdt}y"|j|j|dtx-|jjD]\}}|j||qW|jx^|jD]S}|jtt|djd|jd|j||jdqW|jdy|jdt}Wntk
r|j}nXt j!|d|d|dtdt}Wn|j"nXWnt#t$j%fk
r}
t&|
d|n{t'k
r}t|j(t)r=t|j(t*s=t+|d|q=nt|j(t,rdt-|d|nt|j(t.rt/|d|nt|j(t0rt1|d|nt&|d|nt2k
r}t&|d|nt.k
r	}t/|ndt0t3fk
rl}t|t0rBt1|d|qmt|t4rft5|d|qmnX|j6||S(sSends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest ` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple or urllib3 Timeout object
        :param verify: (optional) Either a boolean, in which case it controls whether
            we verify the server's TLS certificate, or a string, in which case it
            must be a path to a CA bundle to use
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        :rtype: requests.Response
        sContent-LengthtconnectR<ssInvalid timeout {0}. Pass a (connect, read) timeout tuple, or a single float to set both timeouts to the same valuetmethodRptbodyRttredirecttassert_same_hosttpreload_contenttdecode_contenttretriesR*t
proxy_pooltskip_accept_encodingisutf-8s
s0

t	bufferingtpoolR|R(N(7RRpRrRRRR4RtRlttupletTimeoutSaucet
ValueErrorRgturlopenRR3R7thasattrRt	_get_conntDEFAULT_POOL_TIMEOUTt
putrequestR5RKt	putheadert
endheadersR.thextlentencodetgetresponset	TypeErrorRtfrom_httplibR/RtsocketterrorRRRxRR	RRRt_ProxyErrorR
t	_SSLErrorR
Rt
_HTTPErrorRRR(R&R(R)R*R+R,R-RoRptchunkedRR<teterrR~tlow_conntheaderRNtitr((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR.s
						
&





N(R0R1R2RItDEFAULT_POOLSIZER>tDEFAULT_POOLBLOCKR%RJRORAR_RrRR4RR/RRRYR3R5R.(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyR6Qs$				%	4	%	
			(@R2tos.pathRcRtpip._vendor.urllib3.poolmanagerRRtpip._vendor.urllib3.responseRtpip._vendor.urllib3.utilRRtpip._vendor.urllib3.util.retryRtpip._vendor.urllib3.exceptionsRRRRRR	R
RRRR
RRtmodelsRtcompatRRtutilsRRRRRRt
structuresRR{Rt
exceptionsRRRRRtauthRt!pip._vendor.urllib3.contrib.socksR tImportErrorR3RRR>R4RtobjectR#R6(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/adapters.pyt	sB.4

_vendor/requests/status_codes.pyc000064400000011031152527136320013272 0ustar00
abc@skddlmZiDdd6dd6dd6dd	6dd6dd6dd6dd6dd6dd6dd 6dd#6dd(6dd*6dd,6dd.6dd26dd46dd76dd96dd;6dd=6ddA6ddE6ddH6ddJ6ddM6ddO6ddR6ddU6ddW6dd[6dd^6dd`6ddb6ddd6ddg6ddi6ddk6ddo6dds6ddu6ddy6dd{6dd~6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6ZeddZxcejD]U\ZZxFeD]>Zeeeeej	ds!eeej
eq!q!WqWdS(i(t
LookupDicttcontinueidtswitching_protocolsiet
processingift
checkpointigturi_too_longtrequest_uri_too_longiztoktokaytall_oktall_okaytall_goods\o/s✓itcreateditaccepteditnon_authoritative_infotnon_authoritative_informationit
no_contentit
reset_contenttresetitpartial_contenttpartialitmulti_statustmultiple_statustmulti_statitmultiple_statiitalready_reporteditim_useditmultiple_choicesi,tmoved_permanentlytmoveds\o-i-tfoundi.t	see_othertotheri/tnot_modifiedi0t	use_proxyi1tswitch_proxyi2ttemporary_redirectttemporary_movedt	temporaryi3tpermanent_redirecttresume_incompletetresumei4tbad_requesttbaditunauthorizeditpayment_requiredtpaymentit	forbiddenit	not_founds-o-itmethod_not_allowedtnot_alloweditnot_acceptableitproxy_authentication_requiredt
proxy_authtproxy_authenticationitrequest_timeoutttimeoutitconflictitgoneitlength_requireditprecondition_failedtpreconditionitrequest_entity_too_largeitrequest_uri_too_largeitunsupported_media_typetunsupported_mediat
media_typeitrequested_range_not_satisfiabletrequested_rangetrange_not_satisfiableitexpectation_faileditim_a_teapottteapott
i_am_a_teapotitmisdirected_requestitunprocessable_entityt
unprocessableitlockeditfailed_dependencyt
dependencyitunordered_collectiont	unordereditupgrade_requiredtupgradeitprecondition_requiredittoo_many_requeststtoo_manyitheader_fields_too_largetfields_too_largeitno_responsetnoneit
retry_withtretryit$blocked_by_windows_parental_controlstparental_controlsitunavailable_for_legal_reasonst
legal_reasonsitclient_closed_requestitinternal_server_errortserver_errors/o\s✗itnot_implementeditbad_gatewayitservice_unavailabletunavailableitgateway_timeoutithttp_version_not_supportedthttp_versionitvariant_also_negotiatesitinsufficient_storageitbandwidth_limit_exceededt	bandwidthitnot_extendeditnetwork_authentication_requiredtnetwork_authtnetwork_authenticationitnametstatus_codess\t/N(R(R(R(R(RR(RRR	R
Rs\o/s✓(R(R
(RR(R(RR(RR(RRRR(R(R(R(RRs\o-(R(RR (R!(R"(R#(R$R%R&(R'R(R)(R*R+(R,(R-R.(R/(R0s-o-(R1R2(R3(R4R5R6(R7R8(R9(R:(R;(R<R=(R>(R?(R@RARB(RCRDRE(RF(RGRHRI(RJ(RKRL(RM(RNRO(RPRQ(RRRS(RTR=(RURV(RWRX(RYRZ(R[R\(R]R^(R_R`(Ra(RbRcs/o\s✗(Rd(Re(RfRg(Rh(RiRj(Rk(Rl(RmRn(Ro(RpRqRr(s\Ru(t
structuresRt_codestcodestitemstcodettitlesttitletsetattrt
startswithtupper(((sE/usr/lib/python2.7/site-packages/pip/_vendor/requests/status_codes.pyts

_vendor/requests/auth.pyc000064400000023304152527136320011541 0ustar00
abc@sdZddlZddlZddlZddlZddlZddlZddlmZddl	m
Z
mZmZddl
mZddlmZddlmZd	Zd
ZdZdefd
YZdefdYZdefdYZdefdYZdS(s]
requests.auth
~~~~~~~~~~~~~

This module contains the authentication handlers for Requests.
iN(t	b64encodei(turlparsetstrt
basestring(textract_cookies_to_jar(tto_native_string(tparse_dict_headers!application/x-www-form-urlencodedsmultipart/form-datacCst|ts:tjdj|dtt|}nt|tsttjdj|dtt|}nt|tr|jd}nt|tr|jd}ndtt	dj
||fj}|S(sReturns a Basic Auth string.sNon-string usernames will no longer be supported in Requests 3.0.0. Please convert the object you've passed in ({0!r}) to a string or bytes object in the near future to avoid problems.tcategorysNon-string passwords will no longer be supported in Requests 3.0.0. Please convert the object you've passed in ({0!r}) to a string or bytes object in the near future to avoid problems.tlatin1sBasic t:(t
isinstanceRtwarningstwarntformattDeprecationWarningRtencodeRRtjointstrip(tusernametpasswordtauthstr((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt_basic_auth_strs&
		%tAuthBasecBseZdZdZRS(s4Base class that all auth implementations derive fromcCstddS(NsAuth hooks must be callable.(tNotImplementedError(tselftr((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__call__Ks(t__name__t
__module__t__doc__R(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyRHst
HTTPBasicAuthcBs2eZdZdZdZdZdZRS(s?Attaches HTTP Basic Authentication to the given Request object.cCs||_||_dS(N(RR(RRR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__init__Rs	cCs:t|jt|ddk|jt|ddkgS(NRR(tallRtgetattrtNoneR(Rtother((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__eq__VscCs||kS(N((RR#((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__ne__\scCs t|j|j|jd<|S(Nt
Authorization(RRRtheaders(RR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyR_s(RRRRR$R%R(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyROs
			t
HTTPProxyAuthcBseZdZdZRS(s=Attaches HTTP Proxy Authentication to a given Request object.cCs t|j|j|jd<|S(NsProxy-Authorization(RRRR'(RR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyRgs(RRRR(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyR(dstHTTPDigestAuthcBsVeZdZdZdZdZdZdZdZdZ	dZ
RS(	s@Attaches HTTP Digest Authentication to the given Request object.cCs%||_||_tj|_dS(N(RRt	threadingtlocalt
_thread_local(RRR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyRos		cCsat|jds]t|j_d|j_d|j_i|j_d|j_d|j_	ndS(Ntinitti(
thasattrR,tTrueR-t
last_noncetnonce_counttchalR"tpost
num_401_calls(R((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytinit_per_thread_stateuscsN|jjd}|jjd}|jjjd}|jjjd}|jjjd}d|dkrzd}n|j}|dks|dkrd}	|	n|d	krd
}
|
nfd}dkrdSd}t|}
|
jpd}|
jr+|d
|
j7}nd|j||j	f}d||f}|}|}||jj
kr|jjd7_nd|j_d|jj}t|jjj
d}||j
d7}|tjj
d7}|tjd7}tj|jd }|dkrJd|||f}n|sl||d||f}nP|dksd|jdkrd|||d|f}|||}ndS||j_
d|j||||f}|r|d|7}n|r|d|7}n|r)|d|7}n|rF|d||f7}nd|S(s
        :rtype: str
        trealmtnoncetqopt	algorithmtopaquetMD5sMD5-SESScSs4t|tr!|jd}ntj|jS(Nsutf-8(R
RRthashlibtmd5t	hexdigest(tx((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytmd5_utf8stSHAcSs4t|tr!|jd}ntj|jS(Nsutf-8(R
RRR=tsha1R?(R@((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytsha_utf8scsd||fS(Ns%s:%s((tstd(t	hash_utf8(s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytR.t/t?s%s:%s:%ss%s:%sis%08xsutf-8iitautht,s%s:%s:%s:%s:%ss>username="%s", realm="%s", nonce="%s", uri="%s", response="%s"s
, opaque="%s"s, algorithm="%s"s
, digest="%s"s , qop="auth", nc=%s, cnonce="%s"s	Digest %sN(R,R3tgetR"tupperRtpathtqueryRRR1R2RRttimetctimetosturandomR=RCR?tsplit(RtmethodturlR7R8R9R:R;t
_algorithmRARDtKDtentdigtp_parsedROtA1tA2tHA1tHA2tncvalueREtcnoncetrespdigtnoncebittbase((RGs=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytbuild_digest_headersr						!cKs|jrd|j_ndS(s)Reset num_401_calls counter on redirects.iN(tis_redirectR,R5(RRtkwargs((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pythandle_redirects	cKsd|jkodkns/d|j_|S|jjdk	r]|jjj|jjn|jj	dd}d|j
kr~|jjdkr~|jjd7_tjdd	tj
}t|jd|d
d|j_|j|j|jj}t|j|j|j|j|j|j|j|j|jd<|jj||}|jj|||_|Sd|j_|S(
so
        Takes the given response and tries digest-auth, if needed.

        :rtype: requests.Response
        iiiswww-authenticateR.tdigestisdigest tflagstcountR&N(tstatus_codeR,R5R4R"trequesttbodytseekR'RMtlowertretcompilet
IGNORECASERtsubR3tcontenttclosetcopyRt_cookiestrawtprepare_cookiesReRVRWt
connectiontsendthistorytappend(RRRgts_authtpattprept_r((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt
handle_401s.	$$
	cCs|j|jjr8|j|j|j|jds$	,_vendor/requests/exceptions.py000064400000006053152527136320012620 0ustar00# -*- coding: utf-8 -*-

"""
requests.exceptions
~~~~~~~~~~~~~~~~~~~

This module contains the set of Requests' exceptions.
"""
from pip._vendor.urllib3.exceptions import HTTPError as BaseHTTPError


class RequestException(IOError):
    """There was an ambiguous exception that occurred while handling your
    request.
    """

    def __init__(self, *args, **kwargs):
        """Initialize RequestException with `request` and `response` objects."""
        response = kwargs.pop('response', None)
        self.response = response
        self.request = kwargs.pop('request', None)
        if (response is not None and not self.request and
                hasattr(response, 'request')):
            self.request = self.response.request
        super(RequestException, self).__init__(*args, **kwargs)


class HTTPError(RequestException):
    """An HTTP error occurred."""


class ConnectionError(RequestException):
    """A Connection error occurred."""


class ProxyError(ConnectionError):
    """A proxy error occurred."""


class SSLError(ConnectionError):
    """An SSL error occurred."""


class Timeout(RequestException):
    """The request timed out.

    Catching this error will catch both
    :exc:`~requests.exceptions.ConnectTimeout` and
    :exc:`~requests.exceptions.ReadTimeout` errors.
    """


class ConnectTimeout(ConnectionError, Timeout):
    """The request timed out while trying to connect to the remote server.

    Requests that produced this error are safe to retry.
    """


class ReadTimeout(Timeout):
    """The server did not send any data in the allotted amount of time."""


class URLRequired(RequestException):
    """A valid URL is required to make a request."""


class TooManyRedirects(RequestException):
    """Too many redirects."""


class MissingSchema(RequestException, ValueError):
    """The URL schema (e.g. http or https) is missing."""


class InvalidSchema(RequestException, ValueError):
    """See defaults.py for valid schemas."""


class InvalidURL(RequestException, ValueError):
    """The URL provided was somehow invalid."""


class InvalidHeader(RequestException, ValueError):
    """The header value provided was somehow invalid."""


class ChunkedEncodingError(RequestException):
    """The server declared chunked encoding but sent an invalid chunk."""


class ContentDecodingError(RequestException, BaseHTTPError):
    """Failed to decode response content"""


class StreamConsumedError(RequestException, TypeError):
    """The content for this response was already consumed"""


class RetryError(RequestException):
    """Custom retries logic failed"""


class UnrewindableBodyError(RequestException):
    """Requests encountered an error when trying to rewind a body"""

# Warnings


class RequestsWarning(Warning):
    """Base warning for Requests."""
    pass


class FileModeWarning(RequestsWarning, DeprecationWarning):
    """A file was opened in text mode, but Requests determined its binary length."""
    pass


class RequestsDependencyWarning(RequestsWarning):
    """An imported dependency doesn't match the expected version range."""
    pass
_vendor/requests/help.pyo000064400000006503152527136320011546 0ustar00
abc@s
dZddlmZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZ
ydd	lmZWn#ek
rdZdZdZnXddlZddlZd
ZdZdZed
kr	endS(s'Module containing bug report helper(s).i(tprint_functionN(tidna(turllib3(tchardeti(t__version__(t	pyopensslcCstj}|dkr'tj}n|dkrdtjjtjjtjjf}tjjdkrdj	|tjjg}qn<|dkrtj}n!|dkrtj}nd}i|d	6|d
6S(sReturn a dict with the Python implementation and version.

    Provide both the name and the version of the Python implementation
    currently running. For example, on CPython 2.7.5 it will return
    {'name': 'CPython', 'version': '2.7.5'}.

    This function works best on CPython and PyPy: in particular, it probably
    doesn't work for Jython or IronPython. Future investigation should be done
    to work out the correct shape of the code for those platforms.
    tCPythontPyPys%s.%s.%stfinalttJythont
IronPythontUnknowntnametversion(
tplatformtpython_implementationtpython_versiontsystpypy_version_infotmajortminortmicrotreleaseleveltjoin(timplementationtimplementation_version((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pyt_implementations 	c	Csqy$itjd6tjd6}Wn%tk
rKidd6dd6}nXt}itjd6}itjd6}idd6dd6}t	rit	jd6dt	j
jd6}nitt
ddd6}ittddd6}ttd	d}i|dk	rd|ndd6}i
|d
6|d6|d6tdk	d
6|d6|d6|d6|d6|d6itd6d6S(s&Generate information for a bug report.tsystemtreleaseRRR	topenssl_versions%xRtOPENSSL_VERSION_NUMBERRRt
system_ssltusing_pyopensslt	pyOpenSSLRRtcryptographyRtrequestsN(RRRtIOErrorRRRRtNonetOpenSSLtSSLRtgetattrR#RtsslRtrequests_version(	t
platform_infotimplementation_infoturllib3_infotchardet_infotpyopenssl_infotcryptography_infot	idna_infoR tsystem_ssl_info((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pytinfo;sJ

	

 
cCs&ttjtdtdddS(s)Pretty-print the bug information as JSON.t	sort_keystindentiN(tprinttjsontdumpsR4tTrue(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pytmainrst__main__(t__doc__t
__future__RR8RRR*tpip._vendorRRRR	RR+tpackages.urllib3.contribRtImportErrorR&R'R#RR4R;t__name__(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pyts,

	!	7	_vendor/requests/cookies.py000064400000043440152527136320012074 0ustar00# -*- coding: utf-8 -*-

"""
requests.cookies
~~~~~~~~~~~~~~~~

Compatibility code to be able to use `cookielib.CookieJar` with requests.

requests.utils imports from here, so be careful with imports.
"""

import copy
import time
import calendar
import collections

from ._internal_utils import to_native_string
from .compat import cookielib, urlparse, urlunparse, Morsel

try:
    import threading
except ImportError:
    import dummy_threading as threading


class MockRequest(object):
    """Wraps a `requests.Request` to mimic a `urllib2.Request`.

    The code in `cookielib.CookieJar` expects this interface in order to correctly
    manage cookie policies, i.e., determine whether a cookie can be set, given the
    domains of the request and the cookie.

    The original request object is read-only. The client is responsible for collecting
    the new headers via `get_new_headers()` and interpreting them appropriately. You
    probably want `get_cookie_header`, defined below.
    """

    def __init__(self, request):
        self._r = request
        self._new_headers = {}
        self.type = urlparse(self._r.url).scheme

    def get_type(self):
        return self.type

    def get_host(self):
        return urlparse(self._r.url).netloc

    def get_origin_req_host(self):
        return self.get_host()

    def get_full_url(self):
        # Only return the response's URL if the user hadn't set the Host
        # header
        if not self._r.headers.get('Host'):
            return self._r.url
        # If they did set it, retrieve it and reconstruct the expected domain
        host = to_native_string(self._r.headers['Host'], encoding='utf-8')
        parsed = urlparse(self._r.url)
        # Reconstruct the URL as we expect it
        return urlunparse([
            parsed.scheme, host, parsed.path, parsed.params, parsed.query,
            parsed.fragment
        ])

    def is_unverifiable(self):
        return True

    def has_header(self, name):
        return name in self._r.headers or name in self._new_headers

    def get_header(self, name, default=None):
        return self._r.headers.get(name, self._new_headers.get(name, default))

    def add_header(self, key, val):
        """cookielib has no legitimate use for this method; add it back if you find one."""
        raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")

    def add_unredirected_header(self, name, value):
        self._new_headers[name] = value

    def get_new_headers(self):
        return self._new_headers

    @property
    def unverifiable(self):
        return self.is_unverifiable()

    @property
    def origin_req_host(self):
        return self.get_origin_req_host()

    @property
    def host(self):
        return self.get_host()


class MockResponse(object):
    """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.

    ...what? Basically, expose the parsed HTTP headers from the server response
    the way `cookielib` expects to see them.
    """

    def __init__(self, headers):
        """Make a MockResponse for `cookielib` to read.

        :param headers: a httplib.HTTPMessage or analogous carrying the headers
        """
        self._headers = headers

    def info(self):
        return self._headers

    def getheaders(self, name):
        self._headers.getheaders(name)


def extract_cookies_to_jar(jar, request, response):
    """Extract the cookies from the response into a CookieJar.

    :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
    :param request: our own requests.Request object
    :param response: urllib3.HTTPResponse object
    """
    if not (hasattr(response, '_original_response') and
            response._original_response):
        return
    # the _original_response field is the wrapped httplib.HTTPResponse object,
    req = MockRequest(request)
    # pull out the HTTPMessage with the headers and put it in the mock:
    res = MockResponse(response._original_response.msg)
    jar.extract_cookies(res, req)


def get_cookie_header(jar, request):
    """
    Produce an appropriate Cookie header string to be sent with `request`, or None.

    :rtype: str
    """
    r = MockRequest(request)
    jar.add_cookie_header(r)
    return r.get_new_headers().get('Cookie')


def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
    """Unsets a cookie by name, by default over all domains and paths.

    Wraps CookieJar.clear(), is O(n).
    """
    clearables = []
    for cookie in cookiejar:
        if cookie.name != name:
            continue
        if domain is not None and domain != cookie.domain:
            continue
        if path is not None and path != cookie.path:
            continue
        clearables.append((cookie.domain, cookie.path, cookie.name))

    for domain, path, name in clearables:
        cookiejar.clear(domain, path, name)


class CookieConflictError(RuntimeError):
    """There are two cookies that meet the criteria specified in the cookie jar.
    Use .get and .set and include domain and path args in order to be more specific.
    """


class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
    """Compatibility class; is a cookielib.CookieJar, but exposes a dict
    interface.

    This is the CookieJar we create by default for requests and sessions that
    don't specify one, since some clients may expect response.cookies and
    session.cookies to support dict operations.

    Requests does not use the dict interface internally; it's just for
    compatibility with external client code. All requests code should work
    out of the box with externally provided instances of ``CookieJar``, e.g.
    ``LWPCookieJar`` and ``FileCookieJar``.

    Unlike a regular CookieJar, this class is pickleable.

    .. warning:: dictionary operations that are normally O(1) may be O(n).
    """

    def get(self, name, default=None, domain=None, path=None):
        """Dict-like get() that also supports optional domain and path args in
        order to resolve naming collisions from using one cookie jar over
        multiple domains.

        .. warning:: operation is O(n), not O(1).
        """
        try:
            return self._find_no_duplicates(name, domain, path)
        except KeyError:
            return default

    def set(self, name, value, **kwargs):
        """Dict-like set() that also supports optional domain and path args in
        order to resolve naming collisions from using one cookie jar over
        multiple domains.
        """
        # support client code that unsets cookies by assignment of a None value:
        if value is None:
            remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
            return

        if isinstance(value, Morsel):
            c = morsel_to_cookie(value)
        else:
            c = create_cookie(name, value, **kwargs)
        self.set_cookie(c)
        return c

    def iterkeys(self):
        """Dict-like iterkeys() that returns an iterator of names of cookies
        from the jar.

        .. seealso:: itervalues() and iteritems().
        """
        for cookie in iter(self):
            yield cookie.name

    def keys(self):
        """Dict-like keys() that returns a list of names of cookies from the
        jar.

        .. seealso:: values() and items().
        """
        return list(self.iterkeys())

    def itervalues(self):
        """Dict-like itervalues() that returns an iterator of values of cookies
        from the jar.

        .. seealso:: iterkeys() and iteritems().
        """
        for cookie in iter(self):
            yield cookie.value

    def values(self):
        """Dict-like values() that returns a list of values of cookies from the
        jar.

        .. seealso:: keys() and items().
        """
        return list(self.itervalues())

    def iteritems(self):
        """Dict-like iteritems() that returns an iterator of name-value tuples
        from the jar.

        .. seealso:: iterkeys() and itervalues().
        """
        for cookie in iter(self):
            yield cookie.name, cookie.value

    def items(self):
        """Dict-like items() that returns a list of name-value tuples from the
        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
        vanilla python dict of key value pairs.

        .. seealso:: keys() and values().
        """
        return list(self.iteritems())

    def list_domains(self):
        """Utility method to list all the domains in the jar."""
        domains = []
        for cookie in iter(self):
            if cookie.domain not in domains:
                domains.append(cookie.domain)
        return domains

    def list_paths(self):
        """Utility method to list all the paths in the jar."""
        paths = []
        for cookie in iter(self):
            if cookie.path not in paths:
                paths.append(cookie.path)
        return paths

    def multiple_domains(self):
        """Returns True if there are multiple domains in the jar.
        Returns False otherwise.

        :rtype: bool
        """
        domains = []
        for cookie in iter(self):
            if cookie.domain is not None and cookie.domain in domains:
                return True
            domains.append(cookie.domain)
        return False  # there is only one domain in jar

    def get_dict(self, domain=None, path=None):
        """Takes as an argument an optional domain and path and returns a plain
        old Python dict of name-value pairs of cookies that meet the
        requirements.

        :rtype: dict
        """
        dictionary = {}
        for cookie in iter(self):
            if (
                (domain is None or cookie.domain == domain) and
                (path is None or cookie.path == path)
            ):
                dictionary[cookie.name] = cookie.value
        return dictionary

    def __contains__(self, name):
        try:
            return super(RequestsCookieJar, self).__contains__(name)
        except CookieConflictError:
            return True

    def __getitem__(self, name):
        """Dict-like __getitem__() for compatibility with client code. Throws
        exception if there are more than one cookie with name. In that case,
        use the more explicit get() method instead.

        .. warning:: operation is O(n), not O(1).
        """
        return self._find_no_duplicates(name)

    def __setitem__(self, name, value):
        """Dict-like __setitem__ for compatibility with client code. Throws
        exception if there is already a cookie of that name in the jar. In that
        case, use the more explicit set() method instead.
        """
        self.set(name, value)

    def __delitem__(self, name):
        """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
        ``remove_cookie_by_name()``.
        """
        remove_cookie_by_name(self, name)

    def set_cookie(self, cookie, *args, **kwargs):
        if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
            cookie.value = cookie.value.replace('\\"', '')
        return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)

    def update(self, other):
        """Updates this jar with cookies from another CookieJar or dict-like"""
        if isinstance(other, cookielib.CookieJar):
            for cookie in other:
                self.set_cookie(copy.copy(cookie))
        else:
            super(RequestsCookieJar, self).update(other)

    def _find(self, name, domain=None, path=None):
        """Requests uses this method internally to get cookie values.

        If there are conflicting cookies, _find arbitrarily chooses one.
        See _find_no_duplicates if you want an exception thrown if there are
        conflicting cookies.

        :param name: a string containing name of cookie
        :param domain: (optional) string containing domain of cookie
        :param path: (optional) string containing path of cookie
        :return: cookie.value
        """
        for cookie in iter(self):
            if cookie.name == name:
                if domain is None or cookie.domain == domain:
                    if path is None or cookie.path == path:
                        return cookie.value

        raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))

    def _find_no_duplicates(self, name, domain=None, path=None):
        """Both ``__get_item__`` and ``get`` call this function: it's never
        used elsewhere in Requests.

        :param name: a string containing name of cookie
        :param domain: (optional) string containing domain of cookie
        :param path: (optional) string containing path of cookie
        :raises KeyError: if cookie is not found
        :raises CookieConflictError: if there are multiple cookies
            that match name and optionally domain and path
        :return: cookie.value
        """
        toReturn = None
        for cookie in iter(self):
            if cookie.name == name:
                if domain is None or cookie.domain == domain:
                    if path is None or cookie.path == path:
                        if toReturn is not None:  # if there are multiple cookies that meet passed in criteria
                            raise CookieConflictError('There are multiple cookies with name, %r' % (name))
                        toReturn = cookie.value  # we will eventually return this as long as no cookie conflict

        if toReturn:
            return toReturn
        raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))

    def __getstate__(self):
        """Unlike a normal CookieJar, this class is pickleable."""
        state = self.__dict__.copy()
        # remove the unpickleable RLock object
        state.pop('_cookies_lock')
        return state

    def __setstate__(self, state):
        """Unlike a normal CookieJar, this class is pickleable."""
        self.__dict__.update(state)
        if '_cookies_lock' not in self.__dict__:
            self._cookies_lock = threading.RLock()

    def copy(self):
        """Return a copy of this RequestsCookieJar."""
        new_cj = RequestsCookieJar()
        new_cj.update(self)
        return new_cj


def _copy_cookie_jar(jar):
    if jar is None:
        return None

    if hasattr(jar, 'copy'):
        # We're dealing with an instance of RequestsCookieJar
        return jar.copy()
    # We're dealing with a generic CookieJar instance
    new_jar = copy.copy(jar)
    new_jar.clear()
    for cookie in jar:
        new_jar.set_cookie(copy.copy(cookie))
    return new_jar


def create_cookie(name, value, **kwargs):
    """Make a cookie from underspecified parameters.

    By default, the pair of `name` and `value` will be set for the domain ''
    and sent on every request (this is sometimes called a "supercookie").
    """
    result = dict(
        version=0,
        name=name,
        value=value,
        port=None,
        domain='',
        path='/',
        secure=False,
        expires=None,
        discard=True,
        comment=None,
        comment_url=None,
        rest={'HttpOnly': None},
        rfc2109=False,)

    badargs = set(kwargs) - set(result)
    if badargs:
        err = 'create_cookie() got unexpected keyword arguments: %s'
        raise TypeError(err % list(badargs))

    result.update(kwargs)
    result['port_specified'] = bool(result['port'])
    result['domain_specified'] = bool(result['domain'])
    result['domain_initial_dot'] = result['domain'].startswith('.')
    result['path_specified'] = bool(result['path'])

    return cookielib.Cookie(**result)


def morsel_to_cookie(morsel):
    """Convert a Morsel object into a Cookie containing the one k/v pair."""

    expires = None
    if morsel['max-age']:
        try:
            expires = int(time.time() + int(morsel['max-age']))
        except ValueError:
            raise TypeError('max-age: %s must be integer' % morsel['max-age'])
    elif morsel['expires']:
        time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
        expires = calendar.timegm(
            time.strptime(morsel['expires'], time_template)
        )
    return create_cookie(
        comment=morsel['comment'],
        comment_url=bool(morsel['comment']),
        discard=False,
        domain=morsel['domain'],
        expires=expires,
        name=morsel.key,
        path=morsel['path'],
        port=None,
        rest={'HttpOnly': morsel['httponly']},
        rfc2109=False,
        secure=bool(morsel['secure']),
        value=morsel.value,
        version=morsel['version'] or 0,
    )


def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
    """Returns a CookieJar from a key/value dictionary.

    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :param cookiejar: (optional) A cookiejar to add the cookies to.
    :param overwrite: (optional) If False, will not replace cookies
        already in the jar with new ones.
    """
    if cookiejar is None:
        cookiejar = RequestsCookieJar()

    if cookie_dict is not None:
        names_from_jar = [cookie.name for cookie in cookiejar]
        for name in cookie_dict:
            if overwrite or (name not in names_from_jar):
                cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))

    return cookiejar


def merge_cookies(cookiejar, cookies):
    """Add cookies to cookiejar and returns a merged CookieJar.

    :param cookiejar: CookieJar object to add the cookies to.
    :param cookies: Dictionary or CookieJar object to be added.
    """
    if not isinstance(cookiejar, cookielib.CookieJar):
        raise ValueError('You can only merge into CookieJar')

    if isinstance(cookies, dict):
        cookiejar = cookiejar_from_dict(
            cookies, cookiejar=cookiejar, overwrite=False)
    elif isinstance(cookies, cookielib.CookieJar):
        try:
            cookiejar.update(cookies)
        except AttributeError:
            for cookie_in_jar in cookies:
                cookiejar.set_cookie(cookie_in_jar)

    return cookiejar
_vendor/requests/models.pyc000064400000071030152527136320012062 0ustar00
abc@sdZddlZddlZddlZddlZddlmZddlm	Z	ddl
mZddlm
Z
mZmZmZddlmZdd	lmZdd
lmZddlmZddlmZmZmZdd
lmZmZm Z m!Z!m"Z"m#Z#m$Z$ddl%m&Z&m'Z'ddl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=ddl3m>Z?ddl@mAZAeAjBeAjCeAjDeAjEeAjFfZGdZHddZIdZJdeKfdYZLdeKfdYZMdeMfdYZNdeLeMfdYZOdeKfd YZPdS(!s`
requests.models
~~~~~~~~~~~~~~~

This module contains the primary objects that power Requests.
iN(tRequestField(tencode_multipart_formdata(t	parse_url(tDecodeErrortReadTimeoutErrort
ProtocolErrortLocationParseError(tUnsupportedOperationi(t
default_hooks(tCaseInsensitiveDict(t
HTTPBasicAuth(tcookiejar_from_dicttget_cookie_headert_copy_cookie_jar(t	HTTPErrort
MissingSchemat
InvalidURLtChunkedEncodingErrortContentDecodingErrortConnectionErrortStreamConsumedError(tto_native_stringtunicode_is_ascii(
tguess_filenametget_auth_from_urltrequote_uritstream_decode_response_unicodetto_key_val_listtparse_header_linkstiter_slicestguess_json_utft	super_lentcheck_header_validity(
t	cookielibt
urlunparseturlsplitt	urlencodetstrtbytestis_py2tchardettbuiltin_strt
basestring(tjson(tcodesii
iitRequestEncodingMixincBs5eZedZedZedZRS(cCssg}t|j}|j}|s-d}n|j||j}|rf|jd|j|ndj|S(sBuild the path URL to use.t/t?t(R#turltpathtappendtquerytjoin(tselfR1tpR2R4((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytpath_url=s		
	
cCst|ttfr|St|dr,|St|drg}xt|D]\}}t|tsyt|dr|g}nxl|D]d}|dk	r|jt|tr|jdn|t|tr|jdn|fqqWqNWt	|dt
S|SdS(sEncode parameters in a piece of data.

        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
        if parameters are supplied as a dict.
        treadt__iter__sutf-8tdoseqN(t
isinstanceR%R&thasattrRR*tNoneR3tencodeR$tTrue(tdatatresulttktvstv((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt_encode_paramsRs 	
!3c
Cs]|stdnt|tr3tdng}t|pEi}t|pWi}x|D]\}}t|tst|dr|g}nx|D]}|dk	rt|tst|}n|jt|tr|j	dn|t|tr|j
dn|fqqWqdWx|D]
\}}d}d}	t|ttfrt
|dkr|\}
}qt
|dkr|\}
}}q|\}
}}}	nt|p|}
|}t|tttfr|}n|j}td|d|d	|
d
|	}
|
jd||j|
q3Wt|\}}||fS(
sBuild the body for a multipart/form-data request.

        Will successfully encode files when passed as a dict or a list of
        tuples. Order is retained if data is a list of tuples but arbitrary
        if parameters are supplied as a dict.
        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
        or 4-tuples (filename, fileobj, contentype, custom_headers).
        sFiles must be provided.sData must not be a string.R:sutf-8iitnameRAtfilenametheaderstcontent_typeN(t
ValueErrorR<R*RR=R>R&R%R3tdecodeR?ttupletlisttlenRt	bytearrayR9Rtmake_multipartR(tfilesRAt
new_fieldstfieldstfieldtvalRERCtfttfhtfntfptfdatatrftbodyRJ((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt
_encode_filesmsH

!3	!(t__name__t
__module__tpropertyR8tstaticmethodRFR^(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR-<stRequestHooksMixincBseZdZdZRS(cCs||jkr"td|nt|tjrK|j|j|n0t|dr{|j|jd|DndS(sProperly register a hook.s1Unsupported event specified, with event name "%s"R:css'|]}t|tjr|VqdS(N(R<tcollectionstCallable(t.0th((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pys	sN(thooksRKR<RdReR3R=textend(R6teventthook((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt
register_hookscCs5y|j|j|tSWntk
r0tSXdS(siDeregister a previously registered hook.
        Returns True if the hook existed, False if not.
        N(RhtremoveR@RKtFalse(R6RjRk((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytderegister_hooks

(R_R`RlRo(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRcs	tRequestcBsGeZdZddddddddddd
ZdZdZRS(sA user-created :class:`Request ` object.

    Used to prepare a :class:`PreparedRequest `, which is sent to the server.

    :param method: HTTP method to use.
    :param url: URL to send.
    :param headers: dictionary of headers to send.
    :param files: dictionary of {filename: fileobject} files to multipart upload.
    :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.
    :param json: json for the body to attach to the request (if files or data is not specified).
    :param params: dictionary of URL parameters to append to the URL.
    :param auth: Auth handler or (user, pass) tuple.
    :param cookies: dictionary or CookieJar of cookies to attach to this request.
    :param hooks: dictionary of callback hooks, for internal usage.

    Usage::

      >>> import requests
      >>> req = requests.Request('GET', 'http://httpbin.org/get')
      >>> req.prepare()
      
    c
Cs|dkrgn|}|dkr*gn|}|dkrBin|}|dkrZin|}|	dkrrin|	}	t|_x6t|	jD]"\}}|jd|d|qW||_||_||_||_	||_
|
|_||_||_
||_dS(NRjRk(R>RRhRNtitemsRltmethodR1RIRRRAR+tparamstauthtcookies(
R6RrR1RIRRRARsRtRuRhR+RCRE((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__init__s"								cCsd|jS(Ns(Rr(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__repr__scCsqt}|jd|jd|jd|jd|jd|jd|jd|jd|j	d	|j
d
|j
|S(sXConstructs a :class:`PreparedRequest ` for transmission and returns it.RrR1RIRRRAR+RsRtRuRh(tPreparedRequesttprepareRrR1RIRRRAR+RsRtRuRh(R6R7((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRys											
N(R_R`t__doc__R>RvRwRy(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRps
	RxcBseZdZdZddddddddddd
ZdZdZdZe	dZ
dZdZdd	Z
d
ZddZd
ZdZRS(sThe fully mutable :class:`PreparedRequest ` object,
    containing the exact bytes that will be sent to the server.

    Generated from either a :class:`Request ` object or manually.

    Usage::

      >>> import requests
      >>> req = requests.Request('GET', 'http://httpbin.org/get')
      >>> r = req.prepare()
      

      >>> s = requests.Session()
      >>> s.send(r)
      
    cCsFd|_d|_d|_d|_d|_t|_d|_dS(N(	R>RrR1RIt_cookiesR]RRht_body_position(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRvs					cCsk|j||j|||j||j||j|||
|j|||j|	dS(s6Prepares the entire request with the given parameters.N(tprepare_methodtprepare_urltprepare_headerstprepare_cookiestprepare_bodytprepare_autht
prepare_hooks(R6RrR1RIRRRARsRtRuRhR+((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRy+s


cCsd|jS(Ns(Rr(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRw=scCst}|j|_|j|_|jdk	r?|jjnd|_t|j|_|j|_|j	|_	|j
|_
|S(N(RxRrR1RIR>tcopyR
R{R]RhR|(R6R7((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR@s	'cCs7||_|jdk	r3t|jj|_ndS(sPrepares the given HTTP method.N(RrR>Rtupper(R6Rr((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR}Ks	cCsOddl}y"|j|dtjd}Wn|jk
rJtnX|S(Nituts46sutf-8(tidnaR?R@RLt	IDNAErrortUnicodeError(thostR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt_get_idna_encoded_hostQs"
cCst|tr!|jd}ntr3t|n	t|}|j}d|krz|jjdrz||_	dSy%t
|\}}}}}}}	Wn"tk
r}
t|
j
nX|sd}|jt|d}t|n|std|nt|sRy|j|}Wqptk
rNtdqpXn|jdrptdn|pyd	}|r|d
7}n||7}|r|dt|7}n|sd}ntrst|tr|jd}nt|tr
|jd}nt|tr.|jd}nt|trO|jd}nt|	trs|	jd}	qsnt|ttfrt|}n|j|}
|
r|rd
||
f}q|
}ntt|||d||	g}||_	dS(sPrepares the given HTTP URL.tutf8t:thttpNsDInvalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?s Invalid URL %r: No host suppliedsURL has an invalid label.u*R0t@R.sutf-8s%s&%s(R<R&RLR'tunicodeR%tlstriptlowert
startswithR1RRRtargstformatRRRRRR?RFRR"R>(R6R1RstschemeRtRtportR2R4tfragmentteterrortnetloct
enc_params((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR~[sh"	%


		$cCsYt|_|rUx@|jD]/}t||\}}||jt|tcomplexjsontdumpsR<R&R?tallR=R*RNRMRdtMappingRt	TypeErrortAttributeErrorRtgetattrRR|tIOErrortOSErrortobjecttNotImplementedErrorR)RIR^RFtprepare_content_lengthR](R6RARRR+R]RJt	is_streamtlength((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRsJ%
		
cCsr|dk	r7t|}|rnt||jdPrepare Content-Length header based on request method and bodysContent-LengthtGETtHEADt0N(RR(R>RR)RIRrtget(R6R]R((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs'R0cCs|dkr6t|j}t|r-|nd}n|rt|trlt|dkrlt|}n||}|jj	|j|j
|jndS(s"Prepares the given HTTP auth data.iN(R>RR1tanyR<RMROR
t__dict__tupdateRR](R6RtR1turl_authtr((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs!cCs_t|tjr||_nt||_t|j|}|dk	r[||jd` object. Any subsequent calls
        to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
        header is removed beforehand.
        tCookieN(R<R!t	CookieJarR{RRR>RI(R6Rut
cookie_header((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR$scCs5|p	g}x"|D]}|j|||qWdS(sPrepares the given hooks.N(Rl(R6RhRj((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR8s
N(R_R`RzRvR>RyRwRR}RbRR~RRRRRR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRxs				
	V	E	
	tResponsec
Bs7eZdZddddddddd	d
g
ZdZdZd
ZdZdZdZ	dZ
dZdZe
dZe
dZe
dZe
dZe
dZdedZed"d"dZe
dZe
dZdZe
dZd Zd!ZRS(#shThe :class:`Response ` object, which contains a
    server's response to an HTTP request.
    t_contenttstatus_codeRIR1thistorytencodingtreasonRutelapsedtrequestcCst|_t|_d|_d|_t|_d|_d|_	d|_
g|_d|_t
i|_tjd|_d|_dS(Ni(RnRt_content_consumedR>t_nextRR	RItrawR1RRRRRutdatetimet	timedeltaRR(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRvLs									cCs|S(N((R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt	__enter__{scGs|jdS(N(tclose(R6R((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__exit__~scs0jsjntfdjDS(Nc3s'|]}|t|dfVqdS(N(RR>(Rftattr(R6(s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pys	s(Rtcontenttdictt	__attrs__(R6((R6s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__getstate__s
	
cCsQx*|jD]\}}t|||q
Wt|dtt|dddS(NRR(RqtsetattrR@R>(R6tstateRGR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__setstate__scCsd|jS(Ns(R(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRwscCs|jS(skReturns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        (tok(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__bool__scCs|jS(skReturns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        (R(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__nonzero__scCs
|jdS(s,Allows you to use a response as an iterator.i(titer_content(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR:scCs'y|jWntk
r"tSXtS(skReturns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        (traise_for_statusRRnR@(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs
	
cCsd|jko|jtkS(sTrue if this Response is a well-formed HTTP redirect that could have
        been processed automatically (by :meth:`Session.resolve_redirects`).
        tlocation(RIRtREDIRECT_STATI(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytis_redirectscCs(d|jko'|jtjtjfkS(s@True if this Response one of the permanent versions of redirect.R(RIRR,tmoved_permanentlytpermanent_redirect(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytis_permanent_redirectscCs|jS(sTReturns a PreparedRequest for the next request in a redirect chain, if there is one.(R(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytnextscCstj|jdS(s7The apparent encoding, provided by the chardet library.R(R(tdetectR(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytapparent_encodingsicsfd}jr9tjtr9tn5dk	rnttrntdtnt	j}|}jr|n|}|rt
|}n|S(sIterates over the response data.  When stream=True is set on the
        request, this avoids reading the content at once into memory for
        large responses.  The chunk size is the number of bytes it should
        read into memory.  This is not necessarily the length of each item
        returned as decoding can take place.

        chunk_size must be of type int or None. A value of None will
        function differently depending on the value of `stream`.
        stream=True will read data as it arrives in whatever size the
        chunks are received. If stream=False, data is returned as
        a single chunk.

        If decode_unicode is True, content will be decoded using the best
        available encoding based on the response.
        c3stjdry,x%jjdtD]}|Vq.WWqtk
r_}t|qtk
r}}t|qtk
r}t	|qXn.x+trjj
}|sPn|VqWt_dS(Ntstreamtdecode_content(R=RRR@RRRRRRR9R(tchunkR(t
chunk_sizeR6(s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytgenerates 
		s.chunk_size must be an int, it is instead a %s.N(RR<RtboolRR>tintRttypeRR(R6Rtdecode_unicodeRt
reused_chunkst
stream_chunkstchunks((RR6s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs	ccsd}x|jd|d|D]}|dk	r>||}n|rV|j|}n|j}|r|dr|r|dd|dkr|j}nd}x|D]}|VqWqW|dk	r|VndS(sIterates over the response data, one line at a time.  When
        stream=True is set on the request, this avoids reading the
        content at once into memory for large responses.

        .. note:: This method is not reentrant safe.
        RRiN(R>Rtsplitt
splitlinestpop(R6RRt	delimitertpendingRtlinestline((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt
iter_liness
.

cCs|jtkr{|jr'tdn|jdksE|jdkrQd|_q{tj|j	t
prt|_nt|_|jS(s"Content of the response, in bytes.s2The content for this response was already consumediN(RRnRtRuntimeErrorRRR>R&R5RtCONTENT_CHUNK_SIZER@(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR*s	*	cCsd}|j}|js"tdS|jdkr=|j}nyt|j|dd}Wn,ttfk
rt|jdd}nX|S(sContent of the response, in unicode.

        If Response.encoding is None, encoding will be guessed using
        ``chardet``.

        The encoding of the response content is determined based solely on HTTP
        headers, following RFC 2616 to the letter. If you can take advantage of
        non-HTTP knowledge to make a better guess at the encoding, you should
        set ``r.encoding`` appropriately before accessing this property.
        R0terrorstreplaceN(R>RRR%RtLookupErrorR(R6RR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyttext>s		
cKs|jr}|jr}t|jdkr}t|j}|dk	r}y tj|jj||SWqztk
rvqzXq}ntj|j	|S(sReturns the json-encoded content of a response, if any.

        :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
        :raises ValueError: If the response body does not contain valid json.
        iN(
RRRORR>RtloadsRLtUnicodeDecodeErrorR(R6tkwargsR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR+ds(

cCsj|jjd}i}|rft|}x9|D].}|jdpR|jd}|||(R6R((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs
	N(R_R`RzRRvRRRRRwRRR:RaRRRRRRnRtITER_CHUNK_SIZER>RRRR+RRR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRBs2	/						
	
	7&		(QRzRdRtsystencodings.idnat	encodingstpip._vendor.urllib3.fieldsRtpip._vendor.urllib3.filepostRtpip._vendor.urllib3.utilRtpip._vendor.urllib3.exceptionsRRRRtioRRhRt
structuresR	RtR
RuRRR
t
exceptionsRRRRRRRt_internal_utilsRRtutilsRRRRRRRRRR tcompatR!R"R#R$R%R&R'R(R)R*R+Rtstatus_codesR,tmovedtfoundtotherttemporary_redirectRRtDEFAULT_REDIRECT_LIMITRRRR-RcRpRxR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytsB"4FF
nF;_vendor/requests/utils.py000064400000066057152527136320011611 0ustar00# -*- coding: utf-8 -*-

"""
requests.utils
~~~~~~~~~~~~~~

This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""

import cgi
import codecs
import collections
import contextlib
import io
import os
import platform
import re
import socket
import struct
import warnings

from .__version__ import __version__
from . import certs
# to_native_string is unused here, but imported here for backwards compatibility
from ._internal_utils import to_native_string
from .compat import parse_http_list as _parse_list_header
from .compat import (
    quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,
    proxy_bypass, urlunparse, basestring, integer_types, is_py3,
    proxy_bypass_environment, getproxies_environment)
from .cookies import cookiejar_from_dict
from .structures import CaseInsensitiveDict
from .exceptions import (
    InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)

NETRC_FILES = ('.netrc', '_netrc')

DEFAULT_CA_BUNDLE_PATH = certs.where()

DEFAULT_PORTS = {'http': 80, 'https': 443}

if platform.system() == 'Windows':
    # provide a proxy_bypass version on Windows without DNS lookups

    def proxy_bypass_registry(host):
        if is_py3:
            import winreg
        else:
            import _winreg as winreg
        try:
            internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
            proxyEnable = winreg.QueryValueEx(internetSettings,
                                              'ProxyEnable')[0]
            proxyOverride = winreg.QueryValueEx(internetSettings,
                                                'ProxyOverride')[0]
        except OSError:
            return False
        if not proxyEnable or not proxyOverride:
            return False

        # make a check value list from the registry entry: replace the
        # '' string by the localhost entry and the corresponding
        # canonical entry.
        proxyOverride = proxyOverride.split(';')
        # now check if we match one of the registry values.
        for test in proxyOverride:
            if test == '':
                if '.' not in host:
                    return True
            test = test.replace(".", r"\.")     # mask dots
            test = test.replace("*", r".*")     # change glob sequence
            test = test.replace("?", r".")      # change glob char
            if re.match(test, host, re.I):
                return True
        return False

    def proxy_bypass(host):  # noqa
        """Return True, if the host should be bypassed.

        Checks proxy settings gathered from the environment, if specified,
        or the registry.
        """
        if getproxies_environment():
            return proxy_bypass_environment(host)
        else:
            return proxy_bypass_registry(host)


def dict_to_sequence(d):
    """Returns an internal sequence dictionary update."""

    if hasattr(d, 'items'):
        d = d.items()

    return d


def super_len(o):
    total_length = None
    current_position = 0

    if hasattr(o, '__len__'):
        total_length = len(o)

    elif hasattr(o, 'len'):
        total_length = o.len

    elif hasattr(o, 'fileno'):
        try:
            fileno = o.fileno()
        except io.UnsupportedOperation:
            pass
        else:
            total_length = os.fstat(fileno).st_size

            # Having used fstat to determine the file length, we need to
            # confirm that this file was opened up in binary mode.
            if 'b' not in o.mode:
                warnings.warn((
                    "Requests has determined the content-length for this "
                    "request using the binary size of the file: however, the "
                    "file has been opened in text mode (i.e. without the 'b' "
                    "flag in the mode). This may lead to an incorrect "
                    "content-length. In Requests 3.0, support will be removed "
                    "for files in text mode."),
                    FileModeWarning
                )

    if hasattr(o, 'tell'):
        try:
            current_position = o.tell()
        except (OSError, IOError):
            # This can happen in some weird situations, such as when the file
            # is actually a special file descriptor like stdin. In this
            # instance, we don't know what the length is, so set it to zero and
            # let requests chunk it instead.
            if total_length is not None:
                current_position = total_length
        else:
            if hasattr(o, 'seek') and total_length is None:
                # StringIO and BytesIO have seek but no useable fileno
                try:
                    # seek to end of file
                    o.seek(0, 2)
                    total_length = o.tell()

                    # seek back to current position to support
                    # partially read file-like objects
                    o.seek(current_position or 0)
                except (OSError, IOError):
                    total_length = 0

    if total_length is None:
        total_length = 0

    return max(0, total_length - current_position)


def get_netrc_auth(url, raise_errors=False):
    """Returns the Requests tuple auth for a given url from netrc."""

    try:
        from netrc import netrc, NetrcParseError

        netrc_path = None

        for f in NETRC_FILES:
            try:
                loc = os.path.expanduser('~/{0}'.format(f))
            except KeyError:
                # os.path.expanduser can fail when $HOME is undefined and
                # getpwuid fails. See http://bugs.python.org/issue20164 &
                # https://github.com/requests/requests/issues/1846
                return

            if os.path.exists(loc):
                netrc_path = loc
                break

        # Abort early if there isn't one.
        if netrc_path is None:
            return

        ri = urlparse(url)

        # Strip port numbers from netloc. This weird `if...encode`` dance is
        # used for Python 3.2, which doesn't support unicode literals.
        splitstr = b':'
        if isinstance(url, str):
            splitstr = splitstr.decode('ascii')
        host = ri.netloc.split(splitstr)[0]

        try:
            _netrc = netrc(netrc_path).authenticators(host)
            if _netrc:
                # Return with login / password
                login_i = (0 if _netrc[0] else 1)
                return (_netrc[login_i], _netrc[2])
        except (NetrcParseError, IOError):
            # If there was a parsing error or a permissions issue reading the file,
            # we'll just skip netrc auth unless explicitly asked to raise errors.
            if raise_errors:
                raise

    # AppEngine hackiness.
    except (ImportError, AttributeError):
        pass


def guess_filename(obj):
    """Tries to guess the filename of the given object."""
    name = getattr(obj, 'name', None)
    if (name and isinstance(name, basestring) and name[0] != '<' and
            name[-1] != '>'):
        return os.path.basename(name)


def from_key_val_list(value):
    """Take an object and test to see if it can be represented as a
    dictionary. Unless it can not be represented as such, return an
    OrderedDict, e.g.,

    ::

        >>> from_key_val_list([('key', 'val')])
        OrderedDict([('key', 'val')])
        >>> from_key_val_list('string')
        ValueError: need more than 1 value to unpack
        >>> from_key_val_list({'key': 'val'})
        OrderedDict([('key', 'val')])

    :rtype: OrderedDict
    """
    if value is None:
        return None

    if isinstance(value, (str, bytes, bool, int)):
        raise ValueError('cannot encode objects that are not 2-tuples')

    return OrderedDict(value)


def to_key_val_list(value):
    """Take an object and test to see if it can be represented as a
    dictionary. If it can be, return a list of tuples, e.g.,

    ::

        >>> to_key_val_list([('key', 'val')])
        [('key', 'val')]
        >>> to_key_val_list({'key': 'val'})
        [('key', 'val')]
        >>> to_key_val_list('string')
        ValueError: cannot encode objects that are not 2-tuples.

    :rtype: list
    """
    if value is None:
        return None

    if isinstance(value, (str, bytes, bool, int)):
        raise ValueError('cannot encode objects that are not 2-tuples')

    if isinstance(value, collections.Mapping):
        value = value.items()

    return list(value)


# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
    """Parse lists as described by RFC 2068 Section 2.

    In particular, parse comma-separated lists where the elements of
    the list may include quoted-strings.  A quoted-string could
    contain a comma.  A non-quoted string could have quotes in the
    middle.  Quotes are removed automatically after parsing.

    It basically works like :func:`parse_set_header` just that items
    may appear multiple times and case sensitivity is preserved.

    The return value is a standard :class:`list`:

    >>> parse_list_header('token, "quoted value"')
    ['token', 'quoted value']

    To create a header from the :class:`list` again, use the
    :func:`dump_header` function.

    :param value: a string with a list header.
    :return: :class:`list`
    :rtype: list
    """
    result = []
    for item in _parse_list_header(value):
        if item[:1] == item[-1:] == '"':
            item = unquote_header_value(item[1:-1])
        result.append(item)
    return result


# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
    """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
    convert them into a python dict:

    >>> d = parse_dict_header('foo="is a fish", bar="as well"')
    >>> type(d) is dict
    True
    >>> sorted(d.items())
    [('bar', 'as well'), ('foo', 'is a fish')]

    If there is no value for a key it will be `None`:

    >>> parse_dict_header('key_without_value')
    {'key_without_value': None}

    To create a header from the :class:`dict` again, use the
    :func:`dump_header` function.

    :param value: a string with a dict header.
    :return: :class:`dict`
    :rtype: dict
    """
    result = {}
    for item in _parse_list_header(value):
        if '=' not in item:
            result[item] = None
            continue
        name, value = item.split('=', 1)
        if value[:1] == value[-1:] == '"':
            value = unquote_header_value(value[1:-1])
        result[name] = value
    return result


# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
    r"""Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    :rtype: str
    """
    if value and value[0] == value[-1] == '"':
        # this is not the real unquoting, but fixing this so that the
        # RFC is met will result in bugs with internet explorer and
        # probably some other browsers as well.  IE for example is
        # uploading files with "C:\foo\bar.txt" as filename
        value = value[1:-1]

        # if this is a filename and the starting characters look like
        # a UNC path, then just return the value without quotes.  Using the
        # replace sequence below on a UNC path has the effect of turning
        # the leading double slash into a single slash and then
        # _fix_ie_filename() doesn't work correctly.  See #458.
        if not is_filename or value[:2] != '\\\\':
            return value.replace('\\\\', '\\').replace('\\"', '"')
    return value


def dict_from_cookiejar(cj):
    """Returns a key/value dictionary from a CookieJar.

    :param cj: CookieJar object to extract cookies from.
    :rtype: dict
    """

    cookie_dict = {}

    for cookie in cj:
        cookie_dict[cookie.name] = cookie.value

    return cookie_dict


def add_dict_to_cookiejar(cj, cookie_dict):
    """Returns a CookieJar from a key/value dictionary.

    :param cj: CookieJar to insert cookies into.
    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :rtype: CookieJar
    """

    return cookiejar_from_dict(cookie_dict, cj)


def get_encodings_from_content(content):
    """Returns encodings from given content string.

    :param content: bytestring to extract encodings from.
    """
    warnings.warn((
        'In requests 3.0, get_encodings_from_content will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    charset_re = re.compile(r']', flags=re.I)
    pragma_re = re.compile(r']', flags=re.I)
    xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')

    return (charset_re.findall(content) +
            pragma_re.findall(content) +
            xml_re.findall(content))


def get_encoding_from_headers(headers):
    """Returns encodings from given HTTP Header Dict.

    :param headers: dictionary to extract encoding from.
    :rtype: str
    """

    content_type = headers.get('content-type')

    if not content_type:
        return None

    content_type, params = cgi.parse_header(content_type)

    if 'charset' in params:
        return params['charset'].strip("'\"")

    if 'text' in content_type:
        return 'ISO-8859-1'


def stream_decode_response_unicode(iterator, r):
    """Stream decodes a iterator."""

    if r.encoding is None:
        for item in iterator:
            yield item
        return

    decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
    for chunk in iterator:
        rv = decoder.decode(chunk)
        if rv:
            yield rv
    rv = decoder.decode(b'', final=True)
    if rv:
        yield rv


def iter_slices(string, slice_length):
    """Iterate over slices of a string."""
    pos = 0
    if slice_length is None or slice_length <= 0:
        slice_length = len(string)
    while pos < len(string):
        yield string[pos:pos + slice_length]
        pos += slice_length


def get_unicode_from_response(r):
    """Returns the requested content back in unicode.

    :param r: Response object to get unicode content from.

    Tried:

    1. charset from content-type
    2. fall back and replace all unicode characters

    :rtype: str
    """
    warnings.warn((
        'In requests 3.0, get_unicode_from_response will be removed. For '
        'more information, please see the discussion on issue #2266. (This'
        ' warning should only appear once.)'),
        DeprecationWarning)

    tried_encodings = []

    # Try charset from content-type
    encoding = get_encoding_from_headers(r.headers)

    if encoding:
        try:
            return str(r.content, encoding)
        except UnicodeError:
            tried_encodings.append(encoding)

    # Fall back:
    try:
        return str(r.content, encoding, errors='replace')
    except TypeError:
        return r.content


# The unreserved URI characters (RFC 3986)
UNRESERVED_SET = frozenset(
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")


def unquote_unreserved(uri):
    """Un-escape any percent-escape sequences in a URI that are unreserved
    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.

    :rtype: str
    """
    parts = uri.split('%')
    for i in range(1, len(parts)):
        h = parts[i][0:2]
        if len(h) == 2 and h.isalnum():
            try:
                c = chr(int(h, 16))
            except ValueError:
                raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)

            if c in UNRESERVED_SET:
                parts[i] = c + parts[i][2:]
            else:
                parts[i] = '%' + parts[i]
        else:
            parts[i] = '%' + parts[i]
    return ''.join(parts)


def requote_uri(uri):
    """Re-quote the given URI.

    This function passes the given URI through an unquote/quote cycle to
    ensure that it is fully and consistently quoted.

    :rtype: str
    """
    safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
    safe_without_percent = "!#$&'()*+,/:;=?@[]~"
    try:
        # Unquote only the unreserved characters
        # Then quote only illegal characters (do not quote reserved,
        # unreserved, or '%')
        return quote(unquote_unreserved(uri), safe=safe_with_percent)
    except InvalidURL:
        # We couldn't unquote the given URI, so let's try quoting it, but
        # there may be unquoted '%'s in the URI. We need to make sure they're
        # properly quoted so they do not cause issues elsewhere.
        return quote(uri, safe=safe_without_percent)


def address_in_network(ip, net):
    """This function allows you to check if an IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask)


def dotted_netmask(mask):
    """Converts mask from /xx format to xxx.xxx.xxx.xxx

    Example: if mask is 24 function returns 255.255.255.0

    :rtype: str
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits))


def is_ipv4_address(string_ip):
    """
    :rtype: bool
    """
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True


def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True


@contextlib.contextmanager
def set_environ(env_name, value):
    """Set the environment variable 'env_name' to 'value'

    Save previous value, yield, and then restore the previous value stored in
    the environment variable 'env_name'.

    If 'value' is None, do nothing"""
    value_changed = value is not None
    if value_changed:
        old_value = os.environ.get(env_name)
        os.environ[env_name] = value
    try:
        yield
    finally:
        if value_changed:
            if old_value is None:
                del os.environ[env_name]
            else:
                os.environ[env_name] = old_value


def should_bypass_proxies(url, no_proxy):
    """
    Returns whether we should bypass proxies or not.

    :rtype: bool
    """
    get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())

    # First check whether no_proxy is defined. If it is, check that the URL
    # we're getting isn't in the no_proxy list.
    no_proxy_arg = no_proxy
    if no_proxy is None:
        no_proxy = get_proxy('no_proxy')
    netloc = urlparse(url).netloc

    if no_proxy:
        # We need to check whether we match here. We need to see if we match
        # the end of the netloc, both with and without the port.
        no_proxy = (
            host for host in no_proxy.replace(' ', '').split(',') if host
        )

        ip = netloc.split(':')[0]
        if is_ipv4_address(ip):
            for proxy_ip in no_proxy:
                if is_valid_cidr(proxy_ip):
                    if address_in_network(ip, proxy_ip):
                        return True
                elif ip == proxy_ip:
                    # If no_proxy ip was defined in plain IP notation instead of cidr notation &
                    # matches the IP of the index
                    return True
        else:
            for host in no_proxy:
                if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
                    # The URL does match something in no_proxy, so we don't want
                    # to apply the proxies on this URL.
                    return True

    # If the system proxy settings indicate that this URL should be bypassed,
    # don't proxy.
    # The proxy_bypass function is incredibly buggy on OS X in early versions
    # of Python 2.6, so allow this call to fail. Only catch the specific
    # exceptions we've seen, though: this call failing in other ways can reveal
    # legitimate problems.
    with set_environ('no_proxy', no_proxy_arg):
        try:
            bypass = proxy_bypass(netloc)
        except (TypeError, socket.gaierror):
            bypass = False

    if bypass:
        return True

    return False


def get_environ_proxies(url, no_proxy=None):
    """
    Return a dict of environment proxies.

    :rtype: dict
    """
    if should_bypass_proxies(url, no_proxy=no_proxy):
        return {}
    else:
        return getproxies()


def select_proxy(url, proxies):
    """Select a proxy for the url, if applicable.

    :param url: The url being for the request
    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
    """
    proxies = proxies or {}
    urlparts = urlparse(url)
    if urlparts.hostname is None:
        return proxies.get(urlparts.scheme, proxies.get('all'))

    proxy_keys = [
        urlparts.scheme + '://' + urlparts.hostname,
        urlparts.scheme,
        'all://' + urlparts.hostname,
        'all',
    ]
    proxy = None
    for proxy_key in proxy_keys:
        if proxy_key in proxies:
            proxy = proxies[proxy_key]
            break

    return proxy


def default_user_agent(name="python-requests"):
    """
    Return a string representing the default user agent.

    :rtype: str
    """
    return '%s/%s' % (name, __version__)


def default_headers():
    """
    :rtype: requests.structures.CaseInsensitiveDict
    """
    return CaseInsensitiveDict({
        'User-Agent': default_user_agent(),
        'Accept-Encoding': ', '.join(('gzip', 'deflate')),
        'Accept': '*/*',
        'Connection': 'keep-alive',
    })


def parse_header_links(value):
    """Return a dict of parsed link headers proxies.

    i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg"

    :rtype: list
    """

    links = []

    replace_chars = ' \'"'

    for val in re.split(', *<', value):
        try:
            url, params = val.split(';', 1)
        except ValueError:
            url, params = val, ''

        link = {'url': url.strip('<> \'"')}

        for param in params.split(';'):
            try:
                key, value = param.split('=')
            except ValueError:
                break

            link[key.strip(replace_chars)] = value.strip(replace_chars)

        links.append(link)

    return links


# Null bytes; no need to recreate these on each call to guess_json_utf
_null = '\x00'.encode('ascii')  # encoding to ASCII for Python 3
_null2 = _null * 2
_null3 = _null * 3


def guess_json_utf(data):
    """
    :rtype: str
    """
    # JSON always starts with two ASCII characters, so detection is as
    # easy as counting the nulls and from their location and count
    # determine the encoding. Also detect a BOM, if present.
    sample = data[:4]
    if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
        return 'utf-32'     # BOM included
    if sample[:3] == codecs.BOM_UTF8:
        return 'utf-8-sig'  # BOM included, MS style (discouraged)
    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
        return 'utf-16'     # BOM included
    nullcount = sample.count(_null)
    if nullcount == 0:
        return 'utf-8'
    if nullcount == 2:
        if sample[::2] == _null2:   # 1st and 3rd are null
            return 'utf-16-be'
        if sample[1::2] == _null2:  # 2nd and 4th are null
            return 'utf-16-le'
        # Did not detect 2 valid UTF-16 ascii-range characters
    if nullcount == 3:
        if sample[:3] == _null3:
            return 'utf-32-be'
        if sample[1:] == _null3:
            return 'utf-32-le'
        # Did not detect a valid UTF-32 ascii-range character
    return None


def prepend_scheme_if_needed(url, new_scheme):
    """Given a URL that may or may not have a scheme, prepend the given scheme.
    Does not replace a present scheme with the one provided as an argument.

    :rtype: str
    """
    scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)

    # urlparse is a finicky beast, and sometimes decides that there isn't a
    # netloc present. Assume that it's being over-cautious, and switch netloc
    # and path if urlparse decided there was no netloc.
    if not netloc:
        netloc, path = path, netloc

    return urlunparse((scheme, netloc, path, params, query, fragment))


def get_auth_from_url(url):
    """Given a url with authentication components, extract them into a tuple of
    username,password.

    :rtype: (str,str)
    """
    parsed = urlparse(url)

    try:
        auth = (unquote(parsed.username), unquote(parsed.password))
    except (AttributeError, TypeError):
        auth = ('', '')

    return auth


# Moved outside of function to avoid recompile every call
_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')


def check_header_validity(header):
    """Verifies that header value is a string which doesn't contain
    leading whitespace or return characters. This prevents unintended
    header injection.

    :param header: tuple, in the format (name, value).
    """
    name, value = header

    if isinstance(value, bytes):
        pat = _CLEAN_HEADER_REGEX_BYTE
    else:
        pat = _CLEAN_HEADER_REGEX_STR
    try:
        if not pat.match(value):
            raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
    except TypeError:
        raise InvalidHeader("Value for header {%s: %s} must be of type str or "
                            "bytes, not %s" % (name, value, type(value)))


def urldefragauth(url):
    """
    Given a url remove the fragment and the authentication part.

    :rtype: str
    """
    scheme, netloc, path, params, query, fragment = urlparse(url)

    # see func:`prepend_scheme_if_needed`
    if not netloc:
        netloc, path = path, netloc

    netloc = netloc.rsplit('@', 1)[-1]

    return urlunparse((scheme, netloc, path, params, query, ''))


def rewind_body(prepared_request):
    """Move file pointer back to its recorded starting position
    so it can be read again on redirect.
    """
    body_seek = getattr(prepared_request.body, 'seek', None)
    if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
        try:
            body_seek(prepared_request._body_position)
        except (IOError, OSError):
            raise UnrewindableBodyError("An error occurred when rewinding request "
                                        "body for redirect.")
    else:
        raise UnrewindableBodyError("Unable to rewind request body for redirect.")
_vendor/requests/certs.py000064400000000721152527136320011553 0ustar00#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
requests.certs
~~~~~~~~~~~~~~

This module returns the preferred default CA certificate bundle. There is
only one — the one from the certifi package.

If you are packaging Requests, e.g., for a Linux distribution or a managed
environment, you can change the definition of where() to return a separately
packaged CA bundle.
"""
from pip._vendor.certifi import where

if __name__ == '__main__':
    print(where())
_vendor/requests/compat.py000064400000003132152527136320011715 0ustar00# -*- coding: utf-8 -*-

"""
requests.compat
~~~~~~~~~~~~~~~

This module handles import compatibility issues between Python 2 and
Python 3.
"""

from pip._vendor import chardet

import sys

# -------
# Pythons
# -------

# Syntax sugar.
_ver = sys.version_info

#: Python 2.x?
is_py2 = (_ver[0] == 2)

#: Python 3.x?
is_py3 = (_ver[0] == 3)

# try:
#     import simplejson as json
# except ImportError:
import json

# ---------
# Specifics
# ---------

if is_py2:
    from urllib import (
        quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,
        proxy_bypass, proxy_bypass_environment, getproxies_environment)
    from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
    from urllib2 import parse_http_list
    import cookielib
    from Cookie import Morsel
    from StringIO import StringIO

    from pip._vendor.urllib3.packages.ordered_dict import OrderedDict

    builtin_str = str
    bytes = str
    str = unicode
    basestring = basestring
    numeric_types = (int, long, float)
    integer_types = (int, long)

elif is_py3:
    from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag
    from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment
    from http import cookiejar as cookielib
    from http.cookies import Morsel
    from io import StringIO
    from collections import OrderedDict

    builtin_str = str
    str = str
    bytes = bytes
    basestring = (str, bytes)
    numeric_types = (int, float)
    integer_types = (int,)
_vendor/requests/_internal_utils.pyo000064400000002713152527136320014010 0ustar00
abc@s;dZddlmZmZmZddZdZdS(s
requests._internal_utils
~~~~~~~~~~~~~~

Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
i(tis_py2tbuiltin_strtstrtasciicCsCt|tr|}n'tr0|j|}n|j|}|S(sGiven a string object, regardless of type, returns a representation of
    that string in the native string type, encoding and decoding where
    necessary. This assumes ASCII unless told otherwise.
    (t
isinstanceRRtencodetdecode(tstringtencodingtout((sH/usr/lib/python2.7/site-packages/pip/_vendor/requests/_internal_utils.pytto_native_strings	cCs.y|jdtSWntk
r)tSXdS(sDetermine if unicode string only contains ASCII characters.

    :param str u_string: unicode string to check. Must be unicode
        and not Python 2 `str`.
    :rtype: bool
    RN(RtTruetUnicodeEncodeErrortFalse(tu_string((sH/usr/lib/python2.7/site-packages/pip/_vendor/requests/_internal_utils.pytunicode_is_asciis


N(t__doc__tcompatRRRR
R(((sH/usr/lib/python2.7/site-packages/pip/_vendor/requests/_internal_utils.pyt	s_vendor/requests/models.pyo000064400000071030152527136320012076 0ustar00
abc@sdZddlZddlZddlZddlZddlmZddlm	Z	ddl
mZddlm
Z
mZmZmZddlmZdd	lmZdd
lmZddlmZddlmZmZmZdd
lmZmZm Z m!Z!m"Z"m#Z#m$Z$ddl%m&Z&m'Z'ddl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=ddl3m>Z?ddl@mAZAeAjBeAjCeAjDeAjEeAjFfZGdZHddZIdZJdeKfdYZLdeKfdYZMdeMfdYZNdeLeMfdYZOdeKfd YZPdS(!s`
requests.models
~~~~~~~~~~~~~~~

This module contains the primary objects that power Requests.
iN(tRequestField(tencode_multipart_formdata(t	parse_url(tDecodeErrortReadTimeoutErrort
ProtocolErrortLocationParseError(tUnsupportedOperationi(t
default_hooks(tCaseInsensitiveDict(t
HTTPBasicAuth(tcookiejar_from_dicttget_cookie_headert_copy_cookie_jar(t	HTTPErrort
MissingSchemat
InvalidURLtChunkedEncodingErrortContentDecodingErrortConnectionErrortStreamConsumedError(tto_native_stringtunicode_is_ascii(
tguess_filenametget_auth_from_urltrequote_uritstream_decode_response_unicodetto_key_val_listtparse_header_linkstiter_slicestguess_json_utft	super_lentcheck_header_validity(
t	cookielibt
urlunparseturlsplitt	urlencodetstrtbytestis_py2tchardettbuiltin_strt
basestring(tjson(tcodesii
iitRequestEncodingMixincBs5eZedZedZedZRS(cCssg}t|j}|j}|s-d}n|j||j}|rf|jd|j|ndj|S(sBuild the path URL to use.t/t?t(R#turltpathtappendtquerytjoin(tselfR1tpR2R4((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytpath_url=s		
	
cCst|ttfr|St|dr,|St|drg}xt|D]\}}t|tsyt|dr|g}nxl|D]d}|dk	r|jt|tr|jdn|t|tr|jdn|fqqWqNWt	|dt
S|SdS(sEncode parameters in a piece of data.

        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
        if parameters are supplied as a dict.
        treadt__iter__sutf-8tdoseqN(t
isinstanceR%R&thasattrRR*tNoneR3tencodeR$tTrue(tdatatresulttktvstv((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt_encode_paramsRs 	
!3c
Cs]|stdnt|tr3tdng}t|pEi}t|pWi}x|D]\}}t|tst|dr|g}nx|D]}|dk	rt|tst|}n|jt|tr|j	dn|t|tr|j
dn|fqqWqdWx|D]
\}}d}d}	t|ttfrt
|dkr|\}
}qt
|dkr|\}
}}q|\}
}}}	nt|p|}
|}t|tttfr|}n|j}td|d|d	|
d
|	}
|
jd||j|
q3Wt|\}}||fS(
sBuild the body for a multipart/form-data request.

        Will successfully encode files when passed as a dict or a list of
        tuples. Order is retained if data is a list of tuples but arbitrary
        if parameters are supplied as a dict.
        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
        or 4-tuples (filename, fileobj, contentype, custom_headers).
        sFiles must be provided.sData must not be a string.R:sutf-8iitnameRAtfilenametheaderstcontent_typeN(t
ValueErrorR<R*RR=R>R&R%R3tdecodeR?ttupletlisttlenRt	bytearrayR9Rtmake_multipartR(tfilesRAt
new_fieldstfieldstfieldtvalRERCtfttfhtfntfptfdatatrftbodyRJ((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt
_encode_filesmsH

!3	!(t__name__t
__module__tpropertyR8tstaticmethodRFR^(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR-<stRequestHooksMixincBseZdZdZRS(cCs||jkr"td|nt|tjrK|j|j|n0t|dr{|j|jd|DndS(sProperly register a hook.s1Unsupported event specified, with event name "%s"R:css'|]}t|tjr|VqdS(N(R<tcollectionstCallable(t.0th((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pys	sN(thooksRKR<RdReR3R=textend(R6teventthook((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt
register_hookscCs5y|j|j|tSWntk
r0tSXdS(siDeregister a previously registered hook.
        Returns True if the hook existed, False if not.
        N(RhtremoveR@RKtFalse(R6RjRk((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytderegister_hooks

(R_R`RlRo(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRcs	tRequestcBsGeZdZddddddddddd
ZdZdZRS(sA user-created :class:`Request ` object.

    Used to prepare a :class:`PreparedRequest `, which is sent to the server.

    :param method: HTTP method to use.
    :param url: URL to send.
    :param headers: dictionary of headers to send.
    :param files: dictionary of {filename: fileobject} files to multipart upload.
    :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.
    :param json: json for the body to attach to the request (if files or data is not specified).
    :param params: dictionary of URL parameters to append to the URL.
    :param auth: Auth handler or (user, pass) tuple.
    :param cookies: dictionary or CookieJar of cookies to attach to this request.
    :param hooks: dictionary of callback hooks, for internal usage.

    Usage::

      >>> import requests
      >>> req = requests.Request('GET', 'http://httpbin.org/get')
      >>> req.prepare()
      
    c
Cs|dkrgn|}|dkr*gn|}|dkrBin|}|dkrZin|}|	dkrrin|	}	t|_x6t|	jD]"\}}|jd|d|qW||_||_||_||_	||_
|
|_||_||_
||_dS(NRjRk(R>RRhRNtitemsRltmethodR1RIRRRAR+tparamstauthtcookies(
R6RrR1RIRRRARsRtRuRhR+RCRE((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__init__s"								cCsd|jS(Ns(Rr(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__repr__scCsqt}|jd|jd|jd|jd|jd|jd|jd|jd|j	d	|j
d
|j
|S(sXConstructs a :class:`PreparedRequest ` for transmission and returns it.RrR1RIRRRAR+RsRtRuRh(tPreparedRequesttprepareRrR1RIRRRAR+RsRtRuRh(R6R7((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRys											
N(R_R`t__doc__R>RvRwRy(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRps
	RxcBseZdZdZddddddddddd
ZdZdZdZe	dZ
dZdZdd	Z
d
ZddZd
ZdZRS(sThe fully mutable :class:`PreparedRequest ` object,
    containing the exact bytes that will be sent to the server.

    Generated from either a :class:`Request ` object or manually.

    Usage::

      >>> import requests
      >>> req = requests.Request('GET', 'http://httpbin.org/get')
      >>> r = req.prepare()
      

      >>> s = requests.Session()
      >>> s.send(r)
      
    cCsFd|_d|_d|_d|_d|_t|_d|_dS(N(	R>RrR1RIt_cookiesR]RRht_body_position(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRvs					cCsk|j||j|||j||j||j|||
|j|||j|	dS(s6Prepares the entire request with the given parameters.N(tprepare_methodtprepare_urltprepare_headerstprepare_cookiestprepare_bodytprepare_autht
prepare_hooks(R6RrR1RIRRRARsRtRuRhR+((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRy+s


cCsd|jS(Ns(Rr(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRw=scCst}|j|_|j|_|jdk	r?|jjnd|_t|j|_|j|_|j	|_	|j
|_
|S(N(RxRrR1RIR>tcopyR
R{R]RhR|(R6R7((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR@s	'cCs7||_|jdk	r3t|jj|_ndS(sPrepares the given HTTP method.N(RrR>Rtupper(R6Rr((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR}Ks	cCsOddl}y"|j|dtjd}Wn|jk
rJtnX|S(Nituts46sutf-8(tidnaR?R@RLt	IDNAErrortUnicodeError(thostR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt_get_idna_encoded_hostQs"
cCst|tr!|jd}ntr3t|n	t|}|j}d|krz|jjdrz||_	dSy%t
|\}}}}}}}	Wn"tk
r}
t|
j
nX|sd}|jt|d}t|n|std|nt|sRy|j|}Wqptk
rNtdqpXn|jdrptdn|pyd	}|r|d
7}n||7}|r|dt|7}n|sd}ntrst|tr|jd}nt|tr
|jd}nt|tr.|jd}nt|trO|jd}nt|	trs|	jd}	qsnt|ttfrt|}n|j|}
|
r|rd
||
f}q|
}ntt|||d||	g}||_	dS(sPrepares the given HTTP URL.tutf8t:thttpNsDInvalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?s Invalid URL %r: No host suppliedsURL has an invalid label.u*R0t@R.sutf-8s%s&%s(R<R&RLR'tunicodeR%tlstriptlowert
startswithR1RRRtargstformatRRRRRR?RFRR"R>(R6R1RstschemeRtRtportR2R4tfragmentteterrortnetloct
enc_params((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR~[sh"	%


		$cCsYt|_|rUx@|jD]/}t||\}}||jt|tcomplexjsontdumpsR<R&R?tallR=R*RNRMRdtMappingRt	TypeErrortAttributeErrorRtgetattrRR|tIOErrortOSErrortobjecttNotImplementedErrorR)RIR^RFtprepare_content_lengthR](R6RARRR+R]RJt	is_streamtlength((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRsJ%
		
cCsr|dk	r7t|}|rnt||jdPrepare Content-Length header based on request method and bodysContent-LengthtGETtHEADt0N(RR(R>RR)RIRrtget(R6R]R((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs'R0cCs|dkr6t|j}t|r-|nd}n|rt|trlt|dkrlt|}n||}|jj	|j|j
|jndS(s"Prepares the given HTTP auth data.iN(R>RR1tanyR<RMROR
t__dict__tupdateRR](R6RtR1turl_authtr((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs!cCs_t|tjr||_nt||_t|j|}|dk	r[||jd` object. Any subsequent calls
        to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
        header is removed beforehand.
        tCookieN(R<R!t	CookieJarR{RRR>RI(R6Rut
cookie_header((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR$scCs5|p	g}x"|D]}|j|||qWdS(sPrepares the given hooks.N(Rl(R6RhRj((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR8s
N(R_R`RzRvR>RyRwRR}RbRR~RRRRRR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRxs				
	V	E	
	tResponsec
Bs7eZdZddddddddd	d
g
ZdZdZd
ZdZdZdZ	dZ
dZdZe
dZe
dZe
dZe
dZe
dZdedZed"d"dZe
dZe
dZdZe
dZd Zd!ZRS(#shThe :class:`Response ` object, which contains a
    server's response to an HTTP request.
    t_contenttstatus_codeRIR1thistorytencodingtreasonRutelapsedtrequestcCst|_t|_d|_d|_t|_d|_d|_	d|_
g|_d|_t
i|_tjd|_d|_dS(Ni(RnRt_content_consumedR>t_nextRR	RItrawR1RRRRRutdatetimet	timedeltaRR(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRvLs									cCs|S(N((R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt	__enter__{scGs|jdS(N(tclose(R6R((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__exit__~scs0jsjntfdjDS(Nc3s'|]}|t|dfVqdS(N(RR>(Rftattr(R6(s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pys	s(Rtcontenttdictt	__attrs__(R6((R6s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__getstate__s
	
cCsQx*|jD]\}}t|||q
Wt|dtt|dddS(NRR(RqtsetattrR@R>(R6tstateRGR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__setstate__scCsd|jS(Ns(R(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRwscCs|jS(skReturns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        (tok(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__bool__scCs|jS(skReturns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        (R(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt__nonzero__scCs
|jdS(s,Allows you to use a response as an iterator.i(titer_content(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR:scCs'y|jWntk
r"tSXtS(skReturns True if :attr:`status_code` is less than 400.

        This attribute checks if the status code of the response is between
        400 and 600 to see if there was a client error or a server error. If
        the status code, is between 200 and 400, this will return True. This
        is **not** a check to see if the response code is ``200 OK``.
        (traise_for_statusRRnR@(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs
	
cCsd|jko|jtkS(sTrue if this Response is a well-formed HTTP redirect that could have
        been processed automatically (by :meth:`Session.resolve_redirects`).
        tlocation(RIRtREDIRECT_STATI(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytis_redirectscCs(d|jko'|jtjtjfkS(s@True if this Response one of the permanent versions of redirect.R(RIRR,tmoved_permanentlytpermanent_redirect(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytis_permanent_redirectscCs|jS(sTReturns a PreparedRequest for the next request in a redirect chain, if there is one.(R(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytnextscCstj|jdS(s7The apparent encoding, provided by the chardet library.R(R(tdetectR(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytapparent_encodingsicsfd}jr9tjtr9tn5dk	rnttrntdtnt	j}|}jr|n|}|rt
|}n|S(sIterates over the response data.  When stream=True is set on the
        request, this avoids reading the content at once into memory for
        large responses.  The chunk size is the number of bytes it should
        read into memory.  This is not necessarily the length of each item
        returned as decoding can take place.

        chunk_size must be of type int or None. A value of None will
        function differently depending on the value of `stream`.
        stream=True will read data as it arrives in whatever size the
        chunks are received. If stream=False, data is returned as
        a single chunk.

        If decode_unicode is True, content will be decoded using the best
        available encoding based on the response.
        c3stjdry,x%jjdtD]}|Vq.WWqtk
r_}t|qtk
r}}t|qtk
r}t	|qXn.x+trjj
}|sPn|VqWt_dS(Ntstreamtdecode_content(R=RRR@RRRRRRR9R(tchunkR(t
chunk_sizeR6(s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytgenerates 
		s.chunk_size must be an int, it is instead a %s.N(RR<RtboolRR>tintRttypeRR(R6Rtdecode_unicodeRt
reused_chunkst
stream_chunkstchunks((RR6s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs	ccsd}x|jd|d|D]}|dk	r>||}n|rV|j|}n|j}|r|dr|r|dd|dkr|j}nd}x|D]}|VqWqW|dk	r|VndS(sIterates over the response data, one line at a time.  When
        stream=True is set on the request, this avoids reading the
        content at once into memory for large responses.

        .. note:: This method is not reentrant safe.
        RRiN(R>Rtsplitt
splitlinestpop(R6RRt	delimitertpendingRtlinestline((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyt
iter_liness
.

cCs|jtkr{|jr'tdn|jdksE|jdkrQd|_q{tj|j	t
prt|_nt|_|jS(s"Content of the response, in bytes.s2The content for this response was already consumediN(RRnRtRuntimeErrorRRR>R&R5RtCONTENT_CHUNK_SIZER@(R6((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR*s	*	cCsd}|j}|js"tdS|jdkr=|j}nyt|j|dd}Wn,ttfk
rt|jdd}nX|S(sContent of the response, in unicode.

        If Response.encoding is None, encoding will be guessed using
        ``chardet``.

        The encoding of the response content is determined based solely on HTTP
        headers, following RFC 2616 to the letter. If you can take advantage of
        non-HTTP knowledge to make a better guess at the encoding, you should
        set ``r.encoding`` appropriately before accessing this property.
        R0terrorstreplaceN(R>RRR%RtLookupErrorR(R6RR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyttext>s		
cKs|jr}|jr}t|jdkr}t|j}|dk	r}y tj|jj||SWqztk
rvqzXq}ntj|j	|S(sReturns the json-encoded content of a response, if any.

        :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
        :raises ValueError: If the response body does not contain valid json.
        iN(
RRRORR>RtloadsRLtUnicodeDecodeErrorR(R6tkwargsR((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyR+ds(

cCsj|jjd}i}|rft|}x9|D].}|jdpR|jd}|||(R6R((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRs
	N(R_R`RzRRvRRRRRwRRR:RaRRRRRRnRtITER_CHUNK_SIZER>RRRR+RRR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pyRBs2	/						
	
	7&		(QRzRdRtsystencodings.idnat	encodingstpip._vendor.urllib3.fieldsRtpip._vendor.urllib3.filepostRtpip._vendor.urllib3.utilRtpip._vendor.urllib3.exceptionsRRRRtioRRhRt
structuresR	RtR
RuRRR
t
exceptionsRRRRRRRt_internal_utilsRRtutilsRRRRRRRRRR tcompatR!R"R#R$R%R&R'R(R)R*R+Rtstatus_codesR,tmovedtfoundtotherttemporary_redirectRRtDEFAULT_REDIRECT_LIMITRRRR-RcRpRxR(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/models.pytsB"4FF
nF;_vendor/requests/utils.pyc000064400000062046152527136320011746 0ustar00
abc@s\dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZddl
mZddlmZddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!dd	l"m#Z#dd
l$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*d@Z+ej,Z-idd6dd6Z.ej/dkrdZ0dZndZ1dZ2e3dZ4dZ5dZ6dZ7dZ8dZ9e3dZ:dZ;dZ<d Z=d!Z>d"Z?d#Z@d$ZAeBd%d&ZCd'ZDd(ZEd)ZFd*ZGd+ZHd,ZIejJd-ZKd.ZLdd/ZNd0ZOd1d2ZPd3ZQd4ZRd5jSd6ZTeTd7ZUeTd8ZVd9ZWd:ZXd;ZYejZd<Z[ejZd<Z\d=Z]d>Z^d?Z_dS(As
requests.utils
~~~~~~~~~~~~~~

This module provides utility functions that are used within Requests
that are also useful for external consumption.
iNi(t__version__(tcerts(tto_native_string(tparse_http_list(tquoteturlparsetbyteststrtOrderedDicttunquotet
getproxiestproxy_bypasst
urlunparset
basestringt
integer_typestis_py3tproxy_bypass_environmenttgetproxies_environment(tcookiejar_from_dict(tCaseInsensitiveDict(t
InvalidURLt
InvalidHeadertFileModeWarningtUnrewindableBodyErrors.netrct_netrciPthttpithttpstWindowscCs"trddl}nddl}yE|j|jd}|j|dd}|j|dd}Wntk
rztSX|s|rtS|jd}x|D]w}|dkrd|krt	Sn|j
dd	}|j
d
d}|j
dd}tj||tj
rt	SqWtS(
Nis;Software\Microsoft\Windows\CurrentVersion\Internet SettingstProxyEnableit
ProxyOverridet;st.s\.t*s.*t?(Rtwinregt_winregtOpenKeytHKEY_CURRENT_USERtQueryValueExtOSErrortFalsetsplittTruetreplacetretmatchtI(thostR"tinternetSettingstproxyEnablet
proxyOverridettest((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytproxy_bypass_registry.s2		
	

cCs!trt|St|SdS(sReturn True, if the host should be bypassed.

        Checks proxy settings gathered from the environment, if specified,
        or the registry.
        N(RRR4(R/((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyROs	
cCs"t|dr|j}n|S(s/Returns an internal sequence dictionary update.titems(thasattrR5(td((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdict_to_sequence[scCsd}d}t|dr*t|}nt|drE|j}nmt|dry|j}Wntjk
rzqXtj|j}d|j	krt
jdtqnt|drty|j
}Wn,ttfk
r|dk	rq|}qqqtXt|drt|dkrty3|jdd	|j
}|j|pIdWqqttfk
rmd}qqXqtn|dkrd}ntd||S(
Nit__len__tlentfilenotbs%Requests has determined the content-length for this request using the binary size of the file: however, the file has been opened in text mode (i.e. without the 'b' flag in the mode). This may lead to an incorrect content-length. In Requests 3.0, support will be removed for files in text mode.ttelltseeki(tNoneR6R:R;tiotUnsupportedOperationtostfstattst_sizetmodetwarningstwarnRR=R'tIOErrorR>tmax(tottotal_lengthtcurrent_positionR;((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt	super_lends@

	cCseyGddlm}m}d}x^tD]V}ytjjdj|}Wntk
r_dSXtjj	|r&|}Pq&q&W|dkrdSt
|}d}t|tr|j
d}n|jj|d}	yG||j|	}
|
r|
drdnd}|
||
d	fSWn#|tfk
rE|rFqFnXWnttfk
r`nXdS(
s;Returns the Requests tuple auth for a given url from netrc.i(tnetrctNetrcParseErrors~/{0}Nt:tasciiiii(RNROR?tNETRC_FILESRBtpatht
expandusertformattKeyErrortexistsRt
isinstanceRtdecodetnetlocR)tauthenticatorsRHtImportErrortAttributeError(turltraise_errorsRNROt
netrc_pathtftloctritsplitstrR/Rtlogin_i((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_netrc_auths8

cCs[t|dd}|rWt|trW|ddkrW|ddkrWtjj|SdS(s0Tries to guess the filename of the given object.tnameitN(tgetattrR?RXR
RBRStbasename(tobjRg((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytguess_filenames%cCsD|dkrdSt|ttttfr:tdnt|S(sTake an object and test to see if it can be represented as a
    dictionary. Unless it can not be represented as such, return an
    OrderedDict, e.g.,

    ::

        >>> from_key_val_list([('key', 'val')])
        OrderedDict([('key', 'val')])
        >>> from_key_val_list('string')
        ValueError: need more than 1 value to unpack
        >>> from_key_val_list({'key': 'val'})
        OrderedDict([('key', 'val')])

    :rtype: OrderedDict
    s+cannot encode objects that are not 2-tuplesN(R?RXRRtbooltintt
ValueErrorR(tvalue((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytfrom_key_val_lists
cCse|dkrdSt|ttttfr:tdnt|tjr[|j	}nt
|S(sTake an object and test to see if it can be represented as a
    dictionary. If it can be, return a list of tuples, e.g.,

    ::

        >>> to_key_val_list([('key', 'val')])
        [('key', 'val')]
        >>> to_key_val_list({'key': 'val'})
        [('key', 'val')]
        >>> to_key_val_list('string')
        ValueError: cannot encode objects that are not 2-tuples.

    :rtype: list
    s+cannot encode objects that are not 2-tuplesN(R?RXRRRnRoRptcollectionstMappingR5tlist(Rq((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytto_key_val_listscCshg}x[t|D]M}|d |dko8dknrSt|dd!}n|j|qW|S(sParse lists as described by RFC 2068 Section 2.

    In particular, parse comma-separated lists where the elements of
    the list may include quoted-strings.  A quoted-string could
    contain a comma.  A non-quoted string could have quotes in the
    middle.  Quotes are removed automatically after parsing.

    It basically works like :func:`parse_set_header` just that items
    may appear multiple times and case sensitivity is preserved.

    The return value is a standard :class:`list`:

    >>> parse_list_header('token, "quoted value"')
    ['token', 'quoted value']

    To create a header from the :class:`list` again, use the
    :func:`dump_header` function.

    :param value: a string with a list header.
    :return: :class:`list`
    :rtype: list
    iit"(t_parse_list_headertunquote_header_valuetappend(Rqtresulttitem((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytparse_list_headers$cCsi}xt|D]~}d|kr5d||>> d = parse_dict_header('foo="is a fish", bar="as well"')
    >>> type(d) is dict
    True
    >>> sorted(d.items())
    [('bar', 'as well'), ('foo', 'is a fish')]

    If there is no value for a key it will be `None`:

    >>> parse_dict_header('key_without_value')
    {'key_without_value': None}

    To create a header from the :class:`dict` again, use the
    :func:`dump_header` function.

    :param value: a string with a dict header.
    :return: :class:`dict`
    :rtype: dict
    t=iiRwN(RxR?R)Ry(RqR{R|Rg((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytparse_dict_header1s
$cCsq|rm|d|dko%dknrm|dd!}|sN|d dkrm|jddjddSn|S(	sUnquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    :rtype: str
    iiRwiis\\s\s\"(R+(Rqtis_filename((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyRyTs
*
cCs+i}x|D]}|j||j/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdict_from_cookiejarms
cCs
t||S(sReturns a CookieJar from a key/value dictionary.

    :param cj: CookieJar to insert cookies into.
    :param cookie_dict: Dict of key/values to insert into CookieJar.
    :rtype: CookieJar
    (R(RR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytadd_dict_to_cookiejar|scCsvtjdttjddtj}tjddtj}tjd}|j||j||j|S(slReturns encodings from given content string.

    :param content: bytestring to extract encodings from.
    sIn requests 3.0, get_encodings_from_content will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)s!]tflagss+]s$^<\?xml.*?encoding=["\']*(.+?)["\'>](RFRGtDeprecationWarningR,tcompileR.tfindall(tcontentt
charset_ret	pragma_retxml_re((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_encodings_from_contentscCs_|jd}|sdStj|\}}d|krK|djdSd|kr[dSdS(s}Returns encodings from given HTTP Header Dict.

    :param headers: dictionary to extract encoding from.
    :rtype: str
    scontent-typetcharsets'"ttexts
ISO-8859-1N(tgetR?tcgitparse_headertstrip(theaderstcontent_typetparams((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_encoding_from_headerssccs|jdkr)x|D]}|VqWdStj|jdd}x+|D]#}|j|}|rK|VqKqKW|jddt}|r|VndS(sStream decodes a iterator.NterrorsR+ttfinal(tencodingR?tcodecstgetincrementaldecoderRYR*(titeratortrR|tdecodertchunktrv((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytstream_decode_response_unicodes
	
ccsdd}|dks|dkr-t|}nx0|t|kr_||||!V||7}q0WdS(s Iterate over slices of a string.iN(R?R:(tstringtslice_lengthtpos((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytiter_slicesscCstjdtg}t|j}|rcyt|j|SWqctk
r_|j|qcXnyt|j|ddSWnt	k
r|jSXdS(sReturns the requested content back in unicode.

    :param r: Response object to get unicode content from.

    Tried:

    1. charset from content-type
    2. fall back and replace all unicode characters

    :rtype: str
    sIn requests 3.0, get_unicode_from_response will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)RR+N(
RFRGRRRRRtUnicodeErrorRzt	TypeError(Rttried_encodingsR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_unicode_from_responses

t4ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzs0123456789-._~cCs|jd}xtdt|D]}||dd!}t|dkr|jrytt|d}Wn!tk
rtd|nX|tkr|||d||/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytunquote_unreserveds
cCsKd}d}ytt|d|SWntk
rFt|d|SXdS(sRe-quote the given URI.

    This function passes the given URI through an unquote/quote cycle to
    ensure that it is fully and consistently quoted.

    :rtype: str
    s!#$%&'()*+,/:;=?@[]~s!#$&'()*+,/:;=?@[]~tsafeN(RRR(Rtsafe_with_percenttsafe_without_percent((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytrequote_uri
s
cCstjdtj|d}|jd\}}tjdtjtt|d}tjdtj|d|@}||@||@kS(sThis function allows you to check if an IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    s=Lit/(tstructtunpacktsockett	inet_atonR)tdotted_netmaskRo(tiptnettipaddrtnetaddrtbitstnetmasktnetwork((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytaddress_in_network#s
+#cCs/ddd|>dA}tjtjd|S(sConverts mask from /xx format to xxx.xxx.xxx.xxx

    Example: if mask is 24 function returns 255.255.255.0

    :rtype: str
    Iii s>I(Rt	inet_ntoaRtpack(tmaskR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyR2scCs-ytj|Wntjk
r(tSXtS(s
    :rtype: bool
    (RRterrorR(R*(t	string_ip((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytis_ipv4_address=s
cCs|jddkryt|jdd}Wntk
rFtSX|dks_|dkrctSytj|jddWqtjk
rtSXntStS(sV
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    Rii i(	tcountRoR)RpR(RRRR*(tstring_networkR((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt
is_valid_cidrHs
ccst|dk	}|r4tjj|}|tj|/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytset_environ`s	
c	
Cscd}|}|d	kr*|d}nt|j}|rd|jddjdD}|jdd}t|rx|D]8}t|rt||rtSq||krtSqWqx@|D]5}|j	|s|jddj	|rtSqWnt
d|8yt|}Wn tt
jfk
rNt}nXWd	QX|r_tStS(
sL
    Returns whether we should bypass proxies or not.

    :rtype: bool
    cSs(tjj|p'tjj|jS(N(RBRRtupper(tk((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt|Rtno_proxycss|]}|r|VqdS(N((t.0R/((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pys	st Rt,RPiN(R?RRZR+R)RRRR*tendswithRRRRtgaierrorR((	R^Rt	get_proxytno_proxy_argRZRtproxy_ipR/tbypass((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytshould_bypass_proxiesvs4	%

+cCs!t|d|riStSdS(sA
    Return a dict of environment proxies.

    :rtype: dict
    RN(RR
(R^R((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_environ_proxiesscCs|p	i}t|}|jdkrC|j|j|jdS|jd|j|jd|jdg}d}x(|D] }||krz||}PqzqzW|S(sSelect a proxy for the url, if applicable.

    :param url: The url being for the request
    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
    talls://sall://N(RthostnameR?Rtscheme(R^tproxiesturlpartst
proxy_keystproxyt	proxy_key((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytselect_proxys
	

spython-requestscCsd|tfS(sO
    Return a string representing the default user agent.

    :rtype: str
    s%s/%s(R(Rg((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdefault_user_agentscCs2titd6djd
d6dd6dd	6S(s9
    :rtype: requests.structures.CaseInsensitiveDict
    s
User-Agents, tgziptdeflatesAccept-Encodings*/*tAccepts
keep-alivet
Connection(RR(RRR(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytdefault_headerss

c	Csg}d}xtjd|D]}y|jdd\}}Wntk
ra|d}}nXi|jdd6}xa|jdD]P}y|jd\}}Wntk
rPnX|j|||j|; rel=front; type="image/jpeg",; rel=back;type="image/jpeg"

    :rtype: list
    s '"s, * '"R^R~(R,R)RpRRz(	Rqtlinkst
replace_charstvalR^Rtlinktparamtkey((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytparse_header_linkss 

 sRQiicCs|d }|tjtjfkr&dS|d tjkr=dS|d tjtjfkr]dS|jt}|dkr|dS|dkr|d	d	dtkrd
S|dd	dtkrdSn|dkr|d t	krd
S|dt	krdSnd	S(s
    :rtype: str
    isutf-32is	utf-8-sigisutf-16isutf-8Ns	utf-16-beis	utf-16-les	utf-32-bes	utf-32-le(RtBOM_UTF32_LEtBOM_UTF32_BEtBOM_UTF8tBOM_UTF16_LEtBOM_UTF16_BERt_nullt_null2t_null3R?(tdatatsamplet	nullcount((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytguess_json_utfs*
cCsSt||\}}}}}}|s7||}}nt||||||fS(sGiven a URL that may or may not have a scheme, prepend the given scheme.
    Does not replace a present scheme with the one provided as an argument.

    :rtype: str
    (RR(R^t
new_schemeRRZRSRtquerytfragment((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytprepend_scheme_if_needed1s!cCsRt|}y"t|jt|jf}Wnttfk
rMd}nX|S(s{Given a url with authentication components, extract them into a tuple of
    username,password.

    :rtype: (str,str)
    R(RR(RR	tusernametpasswordR]R(R^tparsedtauth((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytget_auth_from_urlBs"
s^\S[^\r\n]*$|^$cCs|\}}t|tr$t}nt}y&|j|sOtd|nWn0tk
rtd||t|fnXdS(sVerifies that header value is a string which doesn't contain
    leading whitespace or return characters. This prevents unintended
    header injection.

    :param header: tuple, in the format (name, value).
    s7Invalid return character or leading space in header: %ss>Value for header {%s: %s} must be of type str or bytes, not %sN(RXRt_CLEAN_HEADER_REGEX_BYTEt_CLEAN_HEADER_REGEX_STRR-RRttype(theaderRgRqtpat((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytcheck_header_validityWs	
cCsft|\}}}}}}|s4||}}n|jddd}t|||||dfS(sW
    Given a url remove the fragment and the authentication part.

    :rtype: str
    t@iiR(RtrsplitR(R^RRZRSRRR
((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt
urldefragauthls
cCs}t|jdd}|dk	rmt|jtrmy||jWqyttfk
ritdqyXntddS(sfMove file pointer back to its recorded starting position
    so it can be read again on redirect.
    R>s;An error occurred when rewinding request body for redirect.s+Unable to rewind request body for redirect.N(	RjtbodyR?RXt_body_positionRRHR'R(tprepared_requestt	body_seek((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pytrewind_body}s(s.netrcR(`t__doc__RRRst
contextlibR@RBtplatformR,RRRFRRRt_internal_utilsRtcompatRRxRRRRRR	R
RRR
RRRRtcookiesRt
structuresRt
exceptionsRRRRRRtwheretDEFAULT_CA_BUNDLE_PATHt
DEFAULT_PORTStsystemR4R8RMR(RfRmRrRvR}RRyRRRRRRRt	frozensetRRRRRRRtcontextmanagerRRR?RRRRRtencodeRRRR
RRRRRRRR!(((s>/usr/lib/python2.7/site-packages/pip/_vendor/requests/utils.pyt	s^"	!			=3				 	#						
	%
							9				"

	 				_vendor/requests/__version__.pyc000064400000001113152527136320013053 0ustar00
abc@s@dZdZdZdZdZdZdZdZdZd	Z	d
S(trequestssPython HTTP for Humans.shttp://python-requests.orgs2.18.4is
Kenneth Reitzsme@kennethreitz.orgs
Apache 2.0sCopyright 2017 Kenneth Reitzu✨ 🍰 ✨N(
t	__title__t__description__t__url__t__version__t	__build__t
__author__t__author_email__t__license__t
__copyright__t__cake__(((sD/usr/lib/python2.7/site-packages/pip/_vendor/requests/__version__.pyts_vendor/requests/sessions.pyo000064400000053544152527136320012473 0ustar00
abc@s+dZddlZddlZddlZddlmZddlmZddlm	Z	ddl
mZmZm
Z
mZmZddlmZmZmZmZdd	lmZmZmZdd
lmZmZddlmZddlmZm Z dd
l!m"Z"m#Z#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddlm*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0ddl1m2Z2ddlm3Z3ej4dkry
ej5Z6Wne7k
rej8Z6nXn	ejZ6e
dZ9e
dZ:de;fdYZ<de<fdYZ=dZ>dS(s
requests.session
~~~~~~~~~~~~~~~~

This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
iN(tMapping(t	timedeltai(t_basic_auth_str(t	cookielibtis_py3tOrderedDictturljointurlparse(tcookiejar_from_dicttextract_cookies_to_jartRequestsCookieJart
merge_cookies(tRequesttPreparedRequesttDEFAULT_REDIRECT_LIMIT(t
default_hookst
dispatch_hook(tto_native_string(tto_key_val_listtdefault_headers(tTooManyRedirectst
InvalidSchematChunkedEncodingErrortContentDecodingError(tCaseInsensitiveDict(tHTTPAdapter(trequote_uritget_environ_proxiestget_netrc_authtshould_bypass_proxiestget_auth_from_urltrewind_bodyt
DEFAULT_PORTS(tcodes(tREDIRECT_STATItWindowscCs|dkr|S|dkr |St|to;t|tsB|S|t|}|jt|g|jD]\}}|dkrt|^qt}x|D]
}||=qW|S(sDetermines appropriate setting for a given request, taking into account
    the explicit setting on that request, and the setting in the session. If a
    setting is a dictionary, they will be merged together using `dict_class`
    N(tNonet
isinstanceRRtupdatetitems(trequest_settingtsession_settingt
dict_classtmerged_settingtktvt	none_keystkey((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt
merge_setting2s1
cCsZ|dks!|jdgkr%|S|dksF|jdgkrJ|St|||S(sProperly merges both requests and session hooks.

    This is necessary because when request_hooks == {'response': []}, the
    merge breaks Session hooks entirely.
    tresponseN(R$tgetR0(t
request_hookst
session_hooksR*((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytmerge_hooksQs
!!tSessionRedirectMixincBsPeZdZdZededdedZdZdZ	dZ
RS(cCs?|jr;|jd}tr.|jd}nt|dSdS(s7Receives a Response. Returns a redirect URI or ``None``tlocationtlatin1tutf8N(tis_redirecttheadersRtencodeRR$(tselftrespR7((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytget_redirect_targetbs	

cCst|}t|}|j|jkr.tS|jdkrn|jdkrn|jdkrn|jdkrntS|j|jk}|j|jk}tj|jddf}|r|j|kr|j|krtS|p|S(sFDecide whether Authorization header should be removed when redirectingthttpiPthttpsiN(iPN(iN(	RthostnametTruetschemetportR$tFalseR R2(R=told_urltnew_urlt
old_parsedt
new_parsedtchanged_porttchanged_schemetdefault_port((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytshould_strip_authxsc	ksg}
|j|}x|r|j}|
j||
d|_y|jWn-tttfk
r~|jj	dt
nXt|j|jkrt
d|jd|n|j|jdrt|j}
dt|
j|f}nt|}|j}|js3t|jt|}nt|}t||_|j|||jtjtjfkrd}x!|D]}|jj|dqWd|_ n|j}y|d
=Wnt!k
rnXt"|j#||jt$|j#|j%|j&|j#|j'||}|j(|||j)dk	oVd|kpVd	|k}|rlt*|n|}|r|Vq|j+|d|d|d
|d|d|dt
|	}t"|j%||j|j|}|VqWdS(sBReceives a Response. Returns a generator of Responses or Requests.itdecode_contentsExceeded %s redirects.R1s//s%s:%ssContent-LengthsContent-TypesTransfer-EncodingtCookietstreamttimeouttverifytcerttproxiestallow_redirectsN(sContent-LengthsContent-TypesTransfer-Encoding(,R?tcopytappendthistorytcontentRRtRuntimeErrortrawtreadRFtlent
max_redirectsRtcloset
startswithRturlRRDtgeturltnetlocRRtrebuild_methodtstatus_codeR!ttemporary_redirecttpermanent_redirectR;tpopR$tbodytKeyErrorR	t_cookiesRtcookiestprepare_cookiestrebuild_proxiestrebuild_autht_body_positionRtsend(R=R>treqRQRRRSRTRUtyield_requeststadapter_kwargsthistRbtprepared_requesttparsed_rurltparsedtpurged_headerstheaderR;t
rewindable((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytresolve_redirectssr	


	
	

	cCs{|j}|j}d|kr@|j|jj|r@|d=n|jrUt|nd}|dk	rw|j|ndS(sWhen being redirected we may want to strip authentication from the
        request to avoid leaking credentials. This method intelligently removes
        and reapplies authentication where possible to avoid credential loss.
        t
AuthorizationN(R;RbRNtrequestt	trust_envRR$tprepare_auth(R=RwR1R;Rbtnew_auth((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRps		$
c
Cs5|dk	r|ni}|j}|j}t|j}|j}|jd}t|d|}|jr|rt	|d|}	|	j||	jd}
|
r|j
||
qnd|kr|d=nyt||\}}Wntk
rd\}}nX|r1|r1t
|||d>> import requests
      >>> s = requests.Session()
      >>> s.get('http://httpbin.org/get')
      

    Or as a context manager::

      >>> with requests.Session() as s:
      >>>     s.get('http://httpbin.org/get')
      
    R;RmtauthRUthookstparamsRSRTtprefetchtadaptersRQRR_cCst|_d|_i|_t|_i|_t|_	t
|_d|_t
|_t
|_ti|_t|_|jdt|jdtdS(Nshttps://shttp://(RR;R$RRURRRRFRQRCRSRTRR_RRRmRRtmountR(R=((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__init__js								cCs|S(N((R=((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt	__enter__scGs|jdS(N(R`(R=targs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__exit__scCs*|jpi}t|tjs0t|}nttt|j|}|j}|jr|r|jrt	|j
}nt}|jd|j
jd|j
d|jd|jd|jdt|j|jdtdt|j|jd	t||jd
|dt|j|j
|S(sConstructs a :class:`PreparedRequest ` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request ` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        :rtype: requests.PreparedRequest
        RRbtfilestdatatjsonR;R*RRRmR(RmR%Rt	CookieJarRRR
RRRRbR
tprepareRtupperRRRR0R;RRR5R(R=RRmtmerged_cookiesRtp((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytprepare_requests*
							cCstd|jd|d|d|d|p-id|d|p?id|d	|d
|
}|j|}|poi}|j|j||
||}i|	d6|
d6}|j||j||}|S(
sConstructs a :class:`Request `, prepares it and sends it.
        Returns :class:`Response ` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query
            string for the :class:`Request`.
        :param data: (optional) Dictionary, bytes, or file-like object to send
            in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the
            :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the
            :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the
            :class:`Request`.
        :param files: (optional) Dictionary of ``'filename': file-like-objects``
            for multipart encoding upload.
        :param auth: (optional) Auth tuple or callable to enable
            Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol or protocol and
            hostname to the URL of the proxy.
        :param stream: (optional) whether to immediately download the response
            content. Defaults to ``False``.
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        RRbR;RRRRRRmRRRRV(RRRtmerge_environment_settingsRbR&Rr(R=RRbRRR;RmRRRRRVRURRQRSRTRRstpreptsettingstsend_kwargsR>((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRs*)	

cKs#|jdt|jd||S(sSends a GET request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RVR(RRCR(R=Rbtkwargs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyR2scKs#|jdt|jd||S(sSends a OPTIONS request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RVtOPTIONS(RRCR(R=RbR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytoptions!scKs#|jdt|jd||S(sSends a HEAD request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RVR(RRFR(R=RbR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pythead,scKs|jd|d|d||S(sSends a POST request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RRR(R(R=RbRRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytpost7s
cKs|jd|d||S(sYSends a PUT request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        tPUTR(R(R=RbRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytputCs	cKs|jd|d||S(s[Sends a PATCH request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        tPATCHR(R(R=RbRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytpatchNs	cKs|jd||S(sSends a DELETE request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        tDELETE(R(R=RbR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytdeleteYsc
Ks|jd|j|jd|j|jd|j|jd|jt|trjtdn|jdt	}|j
d}|j}|jd|j
}t}|j||}t|}	td|	|_td	|||}|jr1x-|jD]}
t|j|
j|
jqWnt|j||j|j|||}|r{g|D]}
|
^qing}|r|jd
||j}||_n|sy(t|j||dt	||_Wqtk
rqXn|s|jn|S(sISend a given PreparedRequest.

        :rtype: requests.Response
        RQRSRTRUs#You can only send PreparedRequests.RVRbtsecondsR1iRt(RRQRSRTRUR%Rt
ValueErrorRiRCR2Rtget_adapterRbtpreferred_clockRrRtelapsedRRYR	RmRR\R}tinserttnextt_nextt
StopIterationRZ(
R=RRRVRQRtadaptertstarttrRR>tgenRY((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRrcsB		
	 %(

c
Cs|jr|dk	r$|jdnd}t|d|}x*|jD]\}}	|j||	qIW|tks|dkrtjjdptjjd}qnt	||j
}t	||j}t	||j}t	||j
}i|d6|d6|d6|d6S(	s^
        Check the environment and merge it with some settings.

        :rtype: dict
        RtREQUESTS_CA_BUNDLEtCURL_CA_BUNDLERSRURQRTN(RR$R2RR'RRCtostenvironR0RURQRSRT(
R=RbRURQRSRTRtenv_proxiesR,R-((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRs	!cCsMx6|jjD]%\}}|jj|r|SqWtd|dS(s~
        Returns the appropriate connection adapter for the given URL.

        :rtype: requests.adapters.BaseAdapter
        s*No connection adapters were found for '%s'N(RR'tlowerRaR(R=RbtprefixR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRscCs(x!|jjD]}|jqWdS(s+Closes all adapters and as such the sessionN(RtvaluesR`(R=R-((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyR`scCso||j|s(tdictt	__attrs__(R=tstate((R=sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__getstate__scCs1x*|jD]\}}t|||q
WdS(N(R'tsetattr(R=RRtvalue((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__setstate__sN(RRt__doc__RRRRRR$RCRR2RRRRRRRrRRR`RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRQs2		7			)D				
	I					cCstS(sQ
    Returns a :class:`Session` for context-management.

    :rtype: Session
    (R(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytsessions(?RRtplatformttimetcollectionsRtdatetimeRRRtcompatRRRRRRmRR	R
RtmodelsRR
RRRRt_internal_utilsRtutilsRRt
exceptionsRRRRt
structuresRRRRRRRRRR tstatus_codesR!R"tsystemtperf_counterRtAttributeErrortclockR0R5tobjectR6RR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt	s<(""4

	_vendor/requests/sessions.pyc000064400000053544152527136320012457 0ustar00
abc@s+dZddlZddlZddlZddlmZddlmZddlm	Z	ddl
mZmZm
Z
mZmZddlmZmZmZmZdd	lmZmZmZdd
lmZmZddlmZddlmZm Z dd
l!m"Z"m#Z#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddlm*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0ddl1m2Z2ddlm3Z3ej4dkry
ej5Z6Wne7k
rej8Z6nXn	ejZ6e
dZ9e
dZ:de;fdYZ<de<fdYZ=dZ>dS(s
requests.session
~~~~~~~~~~~~~~~~

This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
iN(tMapping(t	timedeltai(t_basic_auth_str(t	cookielibtis_py3tOrderedDictturljointurlparse(tcookiejar_from_dicttextract_cookies_to_jartRequestsCookieJart
merge_cookies(tRequesttPreparedRequesttDEFAULT_REDIRECT_LIMIT(t
default_hookst
dispatch_hook(tto_native_string(tto_key_val_listtdefault_headers(tTooManyRedirectst
InvalidSchematChunkedEncodingErrortContentDecodingError(tCaseInsensitiveDict(tHTTPAdapter(trequote_uritget_environ_proxiestget_netrc_authtshould_bypass_proxiestget_auth_from_urltrewind_bodyt
DEFAULT_PORTS(tcodes(tREDIRECT_STATItWindowscCs|dkr|S|dkr |St|to;t|tsB|S|t|}|jt|g|jD]\}}|dkrt|^qt}x|D]
}||=qW|S(sDetermines appropriate setting for a given request, taking into account
    the explicit setting on that request, and the setting in the session. If a
    setting is a dictionary, they will be merged together using `dict_class`
    N(tNonet
isinstanceRRtupdatetitems(trequest_settingtsession_settingt
dict_classtmerged_settingtktvt	none_keystkey((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt
merge_setting2s1
cCsZ|dks!|jdgkr%|S|dksF|jdgkrJ|St|||S(sProperly merges both requests and session hooks.

    This is necessary because when request_hooks == {'response': []}, the
    merge breaks Session hooks entirely.
    tresponseN(R$tgetR0(t
request_hookst
session_hooksR*((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytmerge_hooksQs
!!tSessionRedirectMixincBsPeZdZdZededdedZdZdZ	dZ
RS(cCs?|jr;|jd}tr.|jd}nt|dSdS(s7Receives a Response. Returns a redirect URI or ``None``tlocationtlatin1tutf8N(tis_redirecttheadersRtencodeRR$(tselftrespR7((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytget_redirect_targetbs	

cCst|}t|}|j|jkr.tS|jdkrn|jdkrn|jdkrn|jdkrntS|j|jk}|j|jk}tj|jddf}|r|j|kr|j|krtS|p|S(sFDecide whether Authorization header should be removed when redirectingthttpiPthttpsiN(iPN(iN(	RthostnametTruetschemetportR$tFalseR R2(R=told_urltnew_urlt
old_parsedt
new_parsedtchanged_porttchanged_schemetdefault_port((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytshould_strip_authxsc	ksg}
|j|}x|r|j}|
j||
d|_y|jWn-tttfk
r~|jj	dt
nXt|j|jkrt
d|jd|n|j|jdrt|j}
dt|
j|f}nt|}|j}|js3t|jt|}nt|}t||_|j|||jtjtjfkrd}x!|D]}|jj|dqWd|_ n|j}y|d
=Wnt!k
rnXt"|j#||jt$|j#|j%|j&|j#|j'||}|j(|||j)dk	oVd|kpVd	|k}|rlt*|n|}|r|Vq|j+|d|d|d
|d|d|dt
|	}t"|j%||j|j|}|VqWdS(sBReceives a Response. Returns a generator of Responses or Requests.itdecode_contentsExceeded %s redirects.R1s//s%s:%ssContent-LengthsContent-TypesTransfer-EncodingtCookietstreamttimeouttverifytcerttproxiestallow_redirectsN(sContent-LengthsContent-TypesTransfer-Encoding(,R?tcopytappendthistorytcontentRRtRuntimeErrortrawtreadRFtlent
max_redirectsRtcloset
startswithRturlRRDtgeturltnetlocRRtrebuild_methodtstatus_codeR!ttemporary_redirecttpermanent_redirectR;tpopR$tbodytKeyErrorR	t_cookiesRtcookiestprepare_cookiestrebuild_proxiestrebuild_autht_body_positionRtsend(R=R>treqRQRRRSRTRUtyield_requeststadapter_kwargsthistRbtprepared_requesttparsed_rurltparsedtpurged_headerstheaderR;t
rewindable((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytresolve_redirectssr	


	
	

	cCs{|j}|j}d|kr@|j|jj|r@|d=n|jrUt|nd}|dk	rw|j|ndS(sWhen being redirected we may want to strip authentication from the
        request to avoid leaking credentials. This method intelligently removes
        and reapplies authentication where possible to avoid credential loss.
        t
AuthorizationN(R;RbRNtrequestt	trust_envRR$tprepare_auth(R=RwR1R;Rbtnew_auth((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRps		$
c
Cs5|dk	r|ni}|j}|j}t|j}|j}|jd}t|d|}|jr|rt	|d|}	|	j||	jd}
|
r|j
||
qnd|kr|d=nyt||\}}Wntk
rd\}}nX|r1|r1t
|||d>> import requests
      >>> s = requests.Session()
      >>> s.get('http://httpbin.org/get')
      

    Or as a context manager::

      >>> with requests.Session() as s:
      >>>     s.get('http://httpbin.org/get')
      
    R;RmtauthRUthookstparamsRSRTtprefetchtadaptersRQRR_cCst|_d|_i|_t|_i|_t|_	t
|_d|_t
|_t
|_ti|_t|_|jdt|jdtdS(Nshttps://shttp://(RR;R$RRURRRRFRQRCRSRTRR_RRRmRRtmountR(R=((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__init__js								cCs|S(N((R=((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt	__enter__scGs|jdS(N(R`(R=targs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__exit__scCs*|jpi}t|tjs0t|}nttt|j|}|j}|jr|r|jrt	|j
}nt}|jd|j
jd|j
d|jd|jd|jdt|j|jdtdt|j|jd	t||jd
|dt|j|j
|S(sConstructs a :class:`PreparedRequest ` for
        transmission and returns it. The :class:`PreparedRequest` has settings
        merged from the :class:`Request ` instance and those of the
        :class:`Session`.

        :param request: :class:`Request` instance to prepare with this
            session's settings.
        :rtype: requests.PreparedRequest
        RRbtfilestdatatjsonR;R*RRRmR(RmR%Rt	CookieJarRRR
RRRRbR
tprepareRtupperRRRR0R;RRR5R(R=RRmtmerged_cookiesRtp((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytprepare_requests*
							cCstd|jd|d|d|d|p-id|d|p?id|d	|d
|
}|j|}|poi}|j|j||
||}i|	d6|
d6}|j||j||}|S(
sConstructs a :class:`Request `, prepares it and sends it.
        Returns :class:`Response ` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query
            string for the :class:`Request`.
        :param data: (optional) Dictionary, bytes, or file-like object to send
            in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the
            :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the
            :class:`Request`.
        :param cookies: (optional) Dict or CookieJar object to send with the
            :class:`Request`.
        :param files: (optional) Dictionary of ``'filename': file-like-objects``
            for multipart encoding upload.
        :param auth: (optional) Auth tuple or callable to enable
            Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) ` tuple.
        :type timeout: float or tuple
        :param allow_redirects: (optional) Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol or protocol and
            hostname to the URL of the proxy.
        :param stream: (optional) whether to immediately download the response
            content. Defaults to ``False``.
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
        :param cert: (optional) if String, path to ssl client cert file (.pem).
            If Tuple, ('cert', 'key') pair.
        :rtype: requests.Response
        RRbR;RRRRRRmRRRRV(RRRtmerge_environment_settingsRbR&Rr(R=RRbRRR;RmRRRRRVRURRQRSRTRRstpreptsettingstsend_kwargsR>((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRs*)	

cKs#|jdt|jd||S(sSends a GET request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RVR(RRCR(R=Rbtkwargs((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyR2scKs#|jdt|jd||S(sSends a OPTIONS request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RVtOPTIONS(RRCR(R=RbR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytoptions!scKs#|jdt|jd||S(sSends a HEAD request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RVR(RRFR(R=RbR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pythead,scKs|jd|d|d||S(sSends a POST request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        RRR(R(R=RbRRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytpost7s
cKs|jd|d||S(sYSends a PUT request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        tPUTR(R(R=RbRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytputCs	cKs|jd|d||S(s[Sends a PATCH request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        tPATCHR(R(R=RbRR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytpatchNs	cKs|jd||S(sSends a DELETE request. Returns :class:`Response` object.

        :param url: URL for the new :class:`Request` object.
        :param \*\*kwargs: Optional arguments that ``request`` takes.
        :rtype: requests.Response
        tDELETE(R(R=RbR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytdeleteYsc
Ks|jd|j|jd|j|jd|j|jd|jt|trjtdn|jdt	}|j
d}|j}|jd|j
}t}|j||}t|}	td|	|_td	|||}|jr1x-|jD]}
t|j|
j|
jqWnt|j||j|j|||}|r{g|D]}
|
^qing}|r|jd
||j}||_n|sy(t|j||dt	||_Wqtk
rqXn|s|jn|S(sISend a given PreparedRequest.

        :rtype: requests.Response
        RQRSRTRUs#You can only send PreparedRequests.RVRbtsecondsR1iRt(RRQRSRTRUR%Rt
ValueErrorRiRCR2Rtget_adapterRbtpreferred_clockRrRtelapsedRRYR	RmRR\R}tinserttnextt_nextt
StopIterationRZ(
R=RRRVRQRtadaptertstarttrRR>tgenRY((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRrcsB		
	 %(

c
Cs|jr|dk	r$|jdnd}t|d|}x*|jD]\}}	|j||	qIW|tks|dkrtjjdptjjd}qnt	||j
}t	||j}t	||j}t	||j
}i|d6|d6|d6|d6S(	s^
        Check the environment and merge it with some settings.

        :rtype: dict
        RtREQUESTS_CA_BUNDLEtCURL_CA_BUNDLERSRURQRTN(RR$R2RR'RRCtostenvironR0RURQRSRT(
R=RbRURQRSRTRtenv_proxiesR,R-((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRs	!cCsMx6|jjD]%\}}|jj|r|SqWtd|dS(s~
        Returns the appropriate connection adapter for the given URL.

        :rtype: requests.adapters.BaseAdapter
        s*No connection adapters were found for '%s'N(RR'tlowerRaR(R=RbtprefixR((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRscCs(x!|jjD]}|jqWdS(s+Closes all adapters and as such the sessionN(RtvaluesR`(R=R-((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyR`scCso||j|s(tdictt	__attrs__(R=tstate((R=sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__getstate__scCs1x*|jD]\}}t|||q
WdS(N(R'tsetattr(R=RRtvalue((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt__setstate__sN(RRt__doc__RRRRRR$RCRR2RRRRRRRrRRR`RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyRQs2		7			)D				
	I					cCstS(sQ
    Returns a :class:`Session` for context-management.

    :rtype: Session
    (R(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pytsessions(?RRtplatformttimetcollectionsRtdatetimeRRRtcompatRRRRRRmRR	R
RtmodelsRR
RRRRt_internal_utilsRtutilsRRt
exceptionsRRRRt
structuresRRRRRRRRRR tstatus_codesR!R"tsystemtperf_counterRtAttributeErrortclockR0R5tobjectR6RR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/requests/sessions.pyt	s<(""4

	_vendor/requests/auth.pyo000064400000023304152527136320011555 0ustar00
abc@sdZddlZddlZddlZddlZddlZddlZddlmZddl	m
Z
mZmZddl
mZddlmZddlmZd	Zd
ZdZdefd
YZdefdYZdefdYZdefdYZdS(s]
requests.auth
~~~~~~~~~~~~~

This module contains the authentication handlers for Requests.
iN(t	b64encodei(turlparsetstrt
basestring(textract_cookies_to_jar(tto_native_string(tparse_dict_headers!application/x-www-form-urlencodedsmultipart/form-datacCst|ts:tjdj|dtt|}nt|tsttjdj|dtt|}nt|tr|jd}nt|tr|jd}ndtt	dj
||fj}|S(sReturns a Basic Auth string.sNon-string usernames will no longer be supported in Requests 3.0.0. Please convert the object you've passed in ({0!r}) to a string or bytes object in the near future to avoid problems.tcategorysNon-string passwords will no longer be supported in Requests 3.0.0. Please convert the object you've passed in ({0!r}) to a string or bytes object in the near future to avoid problems.tlatin1sBasic t:(t
isinstanceRtwarningstwarntformattDeprecationWarningRtencodeRRtjointstrip(tusernametpasswordtauthstr((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt_basic_auth_strs&
		%tAuthBasecBseZdZdZRS(s4Base class that all auth implementations derive fromcCstddS(NsAuth hooks must be callable.(tNotImplementedError(tselftr((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__call__Ks(t__name__t
__module__t__doc__R(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyRHst
HTTPBasicAuthcBs2eZdZdZdZdZdZRS(s?Attaches HTTP Basic Authentication to the given Request object.cCs||_||_dS(N(RR(RRR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__init__Rs	cCs:t|jt|ddk|jt|ddkgS(NRR(tallRtgetattrtNoneR(Rtother((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__eq__VscCs||kS(N((RR#((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt__ne__\scCs t|j|j|jd<|S(Nt
Authorization(RRRtheaders(RR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyR_s(RRRRR$R%R(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyROs
			t
HTTPProxyAuthcBseZdZdZRS(s=Attaches HTTP Proxy Authentication to a given Request object.cCs t|j|j|jd<|S(NsProxy-Authorization(RRRR'(RR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyRgs(RRRR(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyR(dstHTTPDigestAuthcBsVeZdZdZdZdZdZdZdZdZ	dZ
RS(	s@Attaches HTTP Digest Authentication to the given Request object.cCs%||_||_tj|_dS(N(RRt	threadingtlocalt
_thread_local(RRR((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyRos		cCsat|jds]t|j_d|j_d|j_i|j_d|j_d|j_	ndS(Ntinitti(
thasattrR,tTrueR-t
last_noncetnonce_counttchalR"tpost
num_401_calls(R((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytinit_per_thread_stateuscsN|jjd}|jjd}|jjjd}|jjjd}|jjjd}d|dkrzd}n|j}|dks|dkrd}	|	n|d	krd
}
|
nfd}dkrdSd}t|}
|
jpd}|
jr+|d
|
j7}nd|j||j	f}d||f}|}|}||jj
kr|jjd7_nd|j_d|jj}t|jjj
d}||j
d7}|tjj
d7}|tjd7}tj|jd }|dkrJd|||f}n|sl||d||f}nP|dksd|jdkrd|||d|f}|||}ndS||j_
d|j||||f}|r|d|7}n|r|d|7}n|r)|d|7}n|rF|d||f7}nd|S(s
        :rtype: str
        trealmtnoncetqopt	algorithmtopaquetMD5sMD5-SESScSs4t|tr!|jd}ntj|jS(Nsutf-8(R
RRthashlibtmd5t	hexdigest(tx((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytmd5_utf8stSHAcSs4t|tr!|jd}ntj|jS(Nsutf-8(R
RRR=tsha1R?(R@((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytsha_utf8scsd||fS(Ns%s:%s((tstd(t	hash_utf8(s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytR.t/t?s%s:%s:%ss%s:%sis%08xsutf-8iitautht,s%s:%s:%s:%s:%ss>username="%s", realm="%s", nonce="%s", uri="%s", response="%s"s
, opaque="%s"s, algorithm="%s"s
, digest="%s"s , qop="auth", nc=%s, cnonce="%s"s	Digest %sN(R,R3tgetR"tupperRtpathtqueryRRR1R2RRttimetctimetosturandomR=RCR?tsplit(RtmethodturlR7R8R9R:R;t
_algorithmRARDtKDtentdigtp_parsedROtA1tA2tHA1tHA2tncvalueREtcnoncetrespdigtnoncebittbase((RGs=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pytbuild_digest_headersr						!cKs|jrd|j_ndS(s)Reset num_401_calls counter on redirects.iN(tis_redirectR,R5(RRtkwargs((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pythandle_redirects	cKsd|jkodkns/d|j_|S|jjdk	r]|jjj|jjn|jj	dd}d|j
kr~|jjdkr~|jjd7_tjdd	tj
}t|jd|d
d|j_|j|j|jj}t|j|j|j|j|j|j|j|j|jd<|jj||}|jj|||_|Sd|j_|S(
so
        Takes the given response and tries digest-auth, if needed.

        :rtype: requests.Response
        iiiswww-authenticateR.tdigestisdigest tflagstcountR&N(tstatus_codeR,R5R4R"trequesttbodytseekR'RMtlowertretcompilet
IGNORECASERtsubR3tcontenttclosetcopyRt_cookiestrawtprepare_cookiesReRVRWt
connectiontsendthistorytappend(RRRgts_authtpattprept_r((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/auth.pyt
handle_401s.	$$
	cCs|j|jjr8|j|j|j|jds$	,_vendor/requests/status_codes.pyo000064400000011031152527136320013306 0ustar00
abc@skddlmZiDdd6dd6dd6dd	6dd6dd6dd6dd6dd6dd6dd 6dd#6dd(6dd*6dd,6dd.6dd26dd46dd76dd96dd;6dd=6ddA6ddE6ddH6ddJ6ddM6ddO6ddR6ddU6ddW6dd[6dd^6dd`6ddb6ddd6ddg6ddi6ddk6ddo6dds6ddu6ddy6dd{6dd~6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6ZeddZxcejD]U\ZZxFeD]>Zeeeeej	ds!eeej
eq!q!WqWdS(i(t
LookupDicttcontinueidtswitching_protocolsiet
processingift
checkpointigturi_too_longtrequest_uri_too_longiztoktokaytall_oktall_okaytall_goods\o/s✓itcreateditaccepteditnon_authoritative_infotnon_authoritative_informationit
no_contentit
reset_contenttresetitpartial_contenttpartialitmulti_statustmultiple_statustmulti_statitmultiple_statiitalready_reporteditim_useditmultiple_choicesi,tmoved_permanentlytmoveds\o-i-tfoundi.t	see_othertotheri/tnot_modifiedi0t	use_proxyi1tswitch_proxyi2ttemporary_redirectttemporary_movedt	temporaryi3tpermanent_redirecttresume_incompletetresumei4tbad_requesttbaditunauthorizeditpayment_requiredtpaymentit	forbiddenit	not_founds-o-itmethod_not_allowedtnot_alloweditnot_acceptableitproxy_authentication_requiredt
proxy_authtproxy_authenticationitrequest_timeoutttimeoutitconflictitgoneitlength_requireditprecondition_failedtpreconditionitrequest_entity_too_largeitrequest_uri_too_largeitunsupported_media_typetunsupported_mediat
media_typeitrequested_range_not_satisfiabletrequested_rangetrange_not_satisfiableitexpectation_faileditim_a_teapottteapott
i_am_a_teapotitmisdirected_requestitunprocessable_entityt
unprocessableitlockeditfailed_dependencyt
dependencyitunordered_collectiont	unordereditupgrade_requiredtupgradeitprecondition_requiredittoo_many_requeststtoo_manyitheader_fields_too_largetfields_too_largeitno_responsetnoneit
retry_withtretryit$blocked_by_windows_parental_controlstparental_controlsitunavailable_for_legal_reasonst
legal_reasonsitclient_closed_requestitinternal_server_errortserver_errors/o\s✗itnot_implementeditbad_gatewayitservice_unavailabletunavailableitgateway_timeoutithttp_version_not_supportedthttp_versionitvariant_also_negotiatesitinsufficient_storageitbandwidth_limit_exceededt	bandwidthitnot_extendeditnetwork_authentication_requiredtnetwork_authtnetwork_authenticationitnametstatus_codess\t/N(R(R(R(R(RR(RRR	R
Rs\o/s✓(R(R
(RR(R(RR(RR(RRRR(R(R(R(RRs\o-(R(RR (R!(R"(R#(R$R%R&(R'R(R)(R*R+(R,(R-R.(R/(R0s-o-(R1R2(R3(R4R5R6(R7R8(R9(R:(R;(R<R=(R>(R?(R@RARB(RCRDRE(RF(RGRHRI(RJ(RKRL(RM(RNRO(RPRQ(RRRS(RTR=(RURV(RWRX(RYRZ(R[R\(R]R^(R_R`(Ra(RbRcs/o\s✗(Rd(Re(RfRg(Rh(RiRj(Rk(Rl(RmRn(Ro(RpRqRr(s\Ru(t
structuresRt_codestcodestitemstcodettitlesttitletsetattrt
startswithtupper(((sE/usr/lib/python2.7/site-packages/pip/_vendor/requests/status_codes.pyts

_vendor/requests/packages.py000064400000001267152527136320012217 0ustar00import sys

# This code exists for backwards compatibility reasons.
# I don't like it either. Just look the other way. :)

for package in ('urllib3', 'idna', 'chardet'):
    vendored_package = "pip._vendor." + package
    locals()[package] = __import__(vendored_package)
    # This traversal is apparently necessary such that the identities are
    # preserved (requests.packages.urllib3.* is urllib3.*)
    for mod in list(sys.modules):
        if mod == vendored_package or mod.startswith(vendored_package + '.'):
            unprefixed_mod = mod[len("pip._vendor."):]
            sys.modules['pip._vendor.requests.packages.' + unprefixed_mod] = sys.modules[mod]

# Kinda cool, though, right?
_vendor/requests/packages.pyc000064400000001102152527136320012346 0ustar00
abc@sddlZxdD]ZdeZeeees

_vendor/requests/__init__.py000064400000006767152527136320012212 0ustar00# -*- coding: utf-8 -*-

#   __
#  /__)  _  _     _   _ _/   _
# / (   (- (/ (/ (- _)  /  _)
#          /

"""
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~

Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:

   >>> import requests
   >>> r = requests.get('https://www.python.org')
   >>> r.status_code
   200
   >>> 'Python is a programming language' in r.content
   True

... or POST:

   >>> payload = dict(key1='value1', key2='value2')
   >>> r = requests.post('http://httpbin.org/post', data=payload)
   >>> print(r.text)
   {
     ...
     "form": {
       "key2": "value2",
       "key1": "value1"
     },
     ...
   }

The other HTTP methods are supported - see `requests.api`. Full documentation
is at .

:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
"""

from pip._vendor import urllib3
from pip._vendor import chardet
import warnings
from .exceptions import RequestsDependencyWarning


def check_compatibility(urllib3_version, chardet_version):
    urllib3_version = urllib3_version.split('.')
    assert urllib3_version != ['dev']  # Verify urllib3 isn't installed from git.

    # Sometimes, urllib3 only reports its version as 16.1.
    if len(urllib3_version) == 2:
        urllib3_version.append('0')

    # Check urllib3 for compatibility.
    major, minor, patch = urllib3_version  # noqa: F811
    major, minor, patch = int(major), int(minor), int(patch)
    # urllib3 >= 1.21.1, <= 1.22
    assert major == 1
    assert minor >= 21
    assert minor <= 22

    # Check chardet for compatibility.
    major, minor, patch = chardet_version.split('.')[:3]
    major, minor, patch = int(major), int(minor), int(patch)
    # chardet >= 3.0.2, < 3.1.0
    assert major == 3
    assert minor < 1
    assert patch >= 2


# Check imported dependencies for compatibility.
try:
    check_compatibility(urllib3.__version__, chardet.__version__)
except (AssertionError, ValueError):
    warnings.warn("urllib3 ({0}) or chardet ({1}) doesn't match a supported "
                  "version!".format(urllib3.__version__, chardet.__version__),
                  RequestsDependencyWarning)

# Attempt to enable urllib3's SNI support, if possible
# try:
#     from pip._vendor.urllib3.contrib import pyopenssl
#     pyopenssl.inject_into_urllib3()
# except ImportError:
#     pass

# urllib3's DependencyWarnings should be silenced.
from pip._vendor.urllib3.exceptions import DependencyWarning
warnings.simplefilter('ignore', DependencyWarning)

from .__version__ import __title__, __description__, __url__, __version__
from .__version__ import __build__, __author__, __author_email__, __license__
from .__version__ import __copyright__, __cake__

from . import utils
from . import packages
from .models import Request, Response, PreparedRequest
from .api import request, get, head, post, patch, put, delete, options
from .sessions import session, Session
from .status_codes import codes
from .exceptions import (
    RequestException, Timeout, URLRequired,
    TooManyRedirects, HTTPError, ConnectionError,
    FileModeWarning, ConnectTimeout, ReadTimeout
)

# Set default logging handler to avoid "No handler found" warnings.
import logging
try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

logging.getLogger(__name__).addHandler(NullHandler())

# FileModeWarnings go off per the default.
warnings.simplefilter('default', FileModeWarning, append=True)
_vendor/requests/status_codes.py000064400000006373152527136320013144 0ustar00# -*- coding: utf-8 -*-

from .structures import LookupDict

_codes = {

    # Informational.
    100: ('continue',),
    101: ('switching_protocols',),
    102: ('processing',),
    103: ('checkpoint',),
    122: ('uri_too_long', 'request_uri_too_long'),
    200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
    201: ('created',),
    202: ('accepted',),
    203: ('non_authoritative_info', 'non_authoritative_information'),
    204: ('no_content',),
    205: ('reset_content', 'reset'),
    206: ('partial_content', 'partial'),
    207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
    208: ('already_reported',),
    226: ('im_used',),

    # Redirection.
    300: ('multiple_choices',),
    301: ('moved_permanently', 'moved', '\\o-'),
    302: ('found',),
    303: ('see_other', 'other'),
    304: ('not_modified',),
    305: ('use_proxy',),
    306: ('switch_proxy',),
    307: ('temporary_redirect', 'temporary_moved', 'temporary'),
    308: ('permanent_redirect',
          'resume_incomplete', 'resume',),  # These 2 to be removed in 3.0

    # Client Error.
    400: ('bad_request', 'bad'),
    401: ('unauthorized',),
    402: ('payment_required', 'payment'),
    403: ('forbidden',),
    404: ('not_found', '-o-'),
    405: ('method_not_allowed', 'not_allowed'),
    406: ('not_acceptable',),
    407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
    408: ('request_timeout', 'timeout'),
    409: ('conflict',),
    410: ('gone',),
    411: ('length_required',),
    412: ('precondition_failed', 'precondition'),
    413: ('request_entity_too_large',),
    414: ('request_uri_too_large',),
    415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
    416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
    417: ('expectation_failed',),
    418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
    421: ('misdirected_request',),
    422: ('unprocessable_entity', 'unprocessable'),
    423: ('locked',),
    424: ('failed_dependency', 'dependency'),
    425: ('unordered_collection', 'unordered'),
    426: ('upgrade_required', 'upgrade'),
    428: ('precondition_required', 'precondition'),
    429: ('too_many_requests', 'too_many'),
    431: ('header_fields_too_large', 'fields_too_large'),
    444: ('no_response', 'none'),
    449: ('retry_with', 'retry'),
    450: ('blocked_by_windows_parental_controls', 'parental_controls'),
    451: ('unavailable_for_legal_reasons', 'legal_reasons'),
    499: ('client_closed_request',),

    # Server Error.
    500: ('internal_server_error', 'server_error', '/o\\', '✗'),
    501: ('not_implemented',),
    502: ('bad_gateway',),
    503: ('service_unavailable', 'unavailable'),
    504: ('gateway_timeout',),
    505: ('http_version_not_supported', 'http_version'),
    506: ('variant_also_negotiates',),
    507: ('insufficient_storage',),
    509: ('bandwidth_limit_exceeded', 'bandwidth'),
    510: ('not_extended',),
    511: ('network_authentication_required', 'network_auth', 'network_authentication'),
}

codes = LookupDict(name='status_codes')

for code, titles in _codes.items():
    for title in titles:
        setattr(codes, title, code)
        if not title.startswith(('\\', '/')):
            setattr(codes, title.upper(), code)
_vendor/requests/structures.pyo000064400000012453152527136320013042 0ustar00
abc@sUdZddlZddlmZdejfdYZdefdYZdS(	sO
requests.structures
~~~~~~~~~~~~~~~~~~~

Data structures that power Requests.
iNi(tOrderedDicttCaseInsensitiveDictcBskeZdZddZdZdZdZdZdZ	dZ
dZd	Zd
Z
RS(sA case-insensitive ``dict``-like object.

    Implements all methods and operations of
    ``collections.MutableMapping`` as well as dict's ``copy``. Also
    provides ``lower_items``.

    All keys are expected to be strings. The structure remembers the
    case of the last key to be set, and ``iter(instance)``,
    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
    will contain case-sensitive keys. However, querying and contains
    testing is case insensitive::

        cid = CaseInsensitiveDict()
        cid['Accept'] = 'application/json'
        cid['aCCEPT'] == 'application/json'  # True
        list(cid) == ['Accept']  # True

    For example, ``headers['content-encoding']`` will return the
    value of a ``'Content-Encoding'`` response header, regardless
    of how the header name was originally stored.

    If the constructor, ``.update``, or equality comparison
    operations are given keys that have equal ``.lower()``s, the
    behavior is undefined.
    cKs5t|_|dkr!i}n|j||dS(N(Rt_storetNonetupdate(tselftdatatkwargs((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__init__*s	cCs||f|j|j<s(Rtvalues(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__iter__;scCs
t|jS(N(tlenR(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__len__>scCsd|jjDS(s.Like iteritems(), but with all lowercase keys.css%|]\}}||dfVqdS(iN((Rtlowerkeytkeyval((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pys	Ds(Rtitems(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pytlower_itemsAscCsGt|tjr!t|}ntSt|jt|jkS(N(t
isinstancetcollectionstMappingRtNotImplementedtdictR(Rtother((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__eq__IscCst|jjS(N(RRR(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pytcopyRscCstt|jS(N(tstrRR(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyt__repr__UsN(t__name__t
__module__t__doc__RRRR
RRRRR R!R#(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyRs									t
LookupDictcBs8eZdZddZdZdZddZRS(sDictionary lookup object.cCs ||_tt|jdS(N(tnametsuperR'R(RR(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR\s	cCsd|jS(Ns
(R((R((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR#`scCs|jj|dS(N(t__dict__tgetR(RR
((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR
cscCs|jj||S(N(R*R+(RR
tdefault((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR+hsN(R$R%R&RRR#R
R+(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pyR'Ys
		(R&RtcompatRtMutableMappingRRR'(((sC/usr/lib/python2.7/site-packages/pip/_vendor/requests/structures.pytsJ_vendor/requests/help.pyc000064400000006503152527136320011532 0ustar00
abc@s
dZddlmZddlZddlZddlZddlZddlmZddlm	Z	ddlm
Z
ddlmZ
ydd	lmZWn#ek
rdZdZdZnXddlZddlZd
ZdZdZed
kr	endS(s'Module containing bug report helper(s).i(tprint_functionN(tidna(turllib3(tchardeti(t__version__(t	pyopensslcCstj}|dkr'tj}n|dkrdtjjtjjtjjf}tjjdkrdj	|tjjg}qn<|dkrtj}n!|dkrtj}nd}i|d	6|d
6S(sReturn a dict with the Python implementation and version.

    Provide both the name and the version of the Python implementation
    currently running. For example, on CPython 2.7.5 it will return
    {'name': 'CPython', 'version': '2.7.5'}.

    This function works best on CPython and PyPy: in particular, it probably
    doesn't work for Jython or IronPython. Future investigation should be done
    to work out the correct shape of the code for those platforms.
    tCPythontPyPys%s.%s.%stfinalttJythont
IronPythontUnknowntnametversion(
tplatformtpython_implementationtpython_versiontsystpypy_version_infotmajortminortmicrotreleaseleveltjoin(timplementationtimplementation_version((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pyt_implementations 	c	Csqy$itjd6tjd6}Wn%tk
rKidd6dd6}nXt}itjd6}itjd6}idd6dd6}t	rit	jd6dt	j
jd6}nitt
ddd6}ittddd6}ttd	d}i|dk	rd|ndd6}i
|d
6|d6|d6tdk	d
6|d6|d6|d6|d6|d6itd6d6S(s&Generate information for a bug report.tsystemtreleaseRRR	topenssl_versions%xRtOPENSSL_VERSION_NUMBERRRt
system_ssltusing_pyopensslt	pyOpenSSLRRtcryptographyRtrequestsN(RRRtIOErrorRRRRtNonetOpenSSLtSSLRtgetattrR#RtsslRtrequests_version(	t
platform_infotimplementation_infoturllib3_infotchardet_infotpyopenssl_infotcryptography_infot	idna_infoR tsystem_ssl_info((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pytinfo;sJ

	

 
cCs&ttjtdtdddS(s)Pretty-print the bug information as JSON.t	sort_keystindentiN(tprinttjsontdumpsR4tTrue(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pytmainrst__main__(t__doc__t
__future__RR8RRR*tpip._vendorRRRR	RR+tpackages.urllib3.contribRtImportErrorR&R'R#RR4R;t__name__(((s=/usr/lib/python2.7/site-packages/pip/_vendor/requests/help.pyts,

	!	7	_vendor/requests/compat.pyo000064400000003465152527136320012105 0ustar00
abc@s5dZddlmZddlZejZeddkZeddkZddlZerGddl	m
Z
mZmZm
Z
mZmZmZmZmZddlmZmZmZmZmZdd	lmZddlZdd
lmZddlmZddlmZe Z!e Z"e#Z e$Z$e%e&e'fZ(e%e&fZ)ner1dd
l*mZmZmZmZmZm
Z
mZmZm
Z
mZddl+mZmZmZmZmZddl,m-Zdd
l.mZddl/mZddl0mZe Z!e Z e"Z"e e"fZ$e%e'fZ(e%fZ)ndS(sq
requests.compat
~~~~~~~~~~~~~~~

This module handles import compatibility issues between Python 2 and
Python 3.
i(tchardetNiii(	tquotetunquotet
quote_plustunquote_plust	urlencodet
getproxiestproxy_bypasstproxy_bypass_environmenttgetproxies_environment(turlparset
urlunparseturljointurlsplitt	urldefrag(tparse_http_list(tMorsel(tStringIO(tOrderedDict(
R
RRR
RRRRRR(RRRRR	(t	cookiejar(1t__doc__tpip._vendorRtsystversion_infot_vertis_py2tis_py3tjsonturllibRRRRRRRRR	R
RRR
Rturllib2Rt	cookielibtCookieRRt)pip._vendor.urllib3.packages.ordered_dictRtstrtbuiltin_strtbytestunicodet
basestringtinttlongtfloatt
numeric_typest
integer_typesturllib.parseturllib.requestthttpRthttp.cookiestiotcollections(((s?/usr/lib/python2.7/site-packages/pip/_vendor/requests/compat.pyt	sB	@(F(_vendor/requests/_internal_utils.pyc000064400000002777152527136320014006 0ustar00
abc@s;dZddlmZmZmZddZdZdS(s
requests._internal_utils
~~~~~~~~~~~~~~

Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
i(tis_py2tbuiltin_strtstrtasciicCsCt|tr|}n'tr0|j|}n|j|}|S(sGiven a string object, regardless of type, returns a representation of
    that string in the native string type, encoding and decoding where
    necessary. This assumes ASCII unless told otherwise.
    (t
isinstanceRRtencodetdecode(tstringtencodingtout((sH/usr/lib/python2.7/site-packages/pip/_vendor/requests/_internal_utils.pytto_native_strings	cCsCt|tsty|jdtSWntk
r>tSXdS(sDetermine if unicode string only contains ASCII characters.

    :param str u_string: unicode string to check. Must be unicode
        and not Python 2 `str`.
    :rtype: bool
    RN(RRtAssertionErrorRtTruetUnicodeEncodeErrortFalse(tu_string((sH/usr/lib/python2.7/site-packages/pip/_vendor/requests/_internal_utils.pytunicode_is_asciis

N(t__doc__tcompatRRRR
R(((sH/usr/lib/python2.7/site-packages/pip/_vendor/requests/_internal_utils.pyt	s_vendor/webencodings/labels.py000064400000021423152527136320012473 0ustar00"""

    webencodings.labels
    ~~~~~~~~~~~~~~~~~~~

    Map encoding labels to their name.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

# XXX Do not edit!
# This file is automatically generated by mklabels.py

LABELS = {
    'unicode-1-1-utf-8':   'utf-8',
    'utf-8':               'utf-8',
    'utf8':                'utf-8',
    '866':                 'ibm866',
    'cp866':               'ibm866',
    'csibm866':            'ibm866',
    'ibm866':              'ibm866',
    'csisolatin2':         'iso-8859-2',
    'iso-8859-2':          'iso-8859-2',
    'iso-ir-101':          'iso-8859-2',
    'iso8859-2':           'iso-8859-2',
    'iso88592':            'iso-8859-2',
    'iso_8859-2':          'iso-8859-2',
    'iso_8859-2:1987':     'iso-8859-2',
    'l2':                  'iso-8859-2',
    'latin2':              'iso-8859-2',
    'csisolatin3':         'iso-8859-3',
    'iso-8859-3':          'iso-8859-3',
    'iso-ir-109':          'iso-8859-3',
    'iso8859-3':           'iso-8859-3',
    'iso88593':            'iso-8859-3',
    'iso_8859-3':          'iso-8859-3',
    'iso_8859-3:1988':     'iso-8859-3',
    'l3':                  'iso-8859-3',
    'latin3':              'iso-8859-3',
    'csisolatin4':         'iso-8859-4',
    'iso-8859-4':          'iso-8859-4',
    'iso-ir-110':          'iso-8859-4',
    'iso8859-4':           'iso-8859-4',
    'iso88594':            'iso-8859-4',
    'iso_8859-4':          'iso-8859-4',
    'iso_8859-4:1988':     'iso-8859-4',
    'l4':                  'iso-8859-4',
    'latin4':              'iso-8859-4',
    'csisolatincyrillic':  'iso-8859-5',
    'cyrillic':            'iso-8859-5',
    'iso-8859-5':          'iso-8859-5',
    'iso-ir-144':          'iso-8859-5',
    'iso8859-5':           'iso-8859-5',
    'iso88595':            'iso-8859-5',
    'iso_8859-5':          'iso-8859-5',
    'iso_8859-5:1988':     'iso-8859-5',
    'arabic':              'iso-8859-6',
    'asmo-708':            'iso-8859-6',
    'csiso88596e':         'iso-8859-6',
    'csiso88596i':         'iso-8859-6',
    'csisolatinarabic':    'iso-8859-6',
    'ecma-114':            'iso-8859-6',
    'iso-8859-6':          'iso-8859-6',
    'iso-8859-6-e':        'iso-8859-6',
    'iso-8859-6-i':        'iso-8859-6',
    'iso-ir-127':          'iso-8859-6',
    'iso8859-6':           'iso-8859-6',
    'iso88596':            'iso-8859-6',
    'iso_8859-6':          'iso-8859-6',
    'iso_8859-6:1987':     'iso-8859-6',
    'csisolatingreek':     'iso-8859-7',
    'ecma-118':            'iso-8859-7',
    'elot_928':            'iso-8859-7',
    'greek':               'iso-8859-7',
    'greek8':              'iso-8859-7',
    'iso-8859-7':          'iso-8859-7',
    'iso-ir-126':          'iso-8859-7',
    'iso8859-7':           'iso-8859-7',
    'iso88597':            'iso-8859-7',
    'iso_8859-7':          'iso-8859-7',
    'iso_8859-7:1987':     'iso-8859-7',
    'sun_eu_greek':        'iso-8859-7',
    'csiso88598e':         'iso-8859-8',
    'csisolatinhebrew':    'iso-8859-8',
    'hebrew':              'iso-8859-8',
    'iso-8859-8':          'iso-8859-8',
    'iso-8859-8-e':        'iso-8859-8',
    'iso-ir-138':          'iso-8859-8',
    'iso8859-8':           'iso-8859-8',
    'iso88598':            'iso-8859-8',
    'iso_8859-8':          'iso-8859-8',
    'iso_8859-8:1988':     'iso-8859-8',
    'visual':              'iso-8859-8',
    'csiso88598i':         'iso-8859-8-i',
    'iso-8859-8-i':        'iso-8859-8-i',
    'logical':             'iso-8859-8-i',
    'csisolatin6':         'iso-8859-10',
    'iso-8859-10':         'iso-8859-10',
    'iso-ir-157':          'iso-8859-10',
    'iso8859-10':          'iso-8859-10',
    'iso885910':           'iso-8859-10',
    'l6':                  'iso-8859-10',
    'latin6':              'iso-8859-10',
    'iso-8859-13':         'iso-8859-13',
    'iso8859-13':          'iso-8859-13',
    'iso885913':           'iso-8859-13',
    'iso-8859-14':         'iso-8859-14',
    'iso8859-14':          'iso-8859-14',
    'iso885914':           'iso-8859-14',
    'csisolatin9':         'iso-8859-15',
    'iso-8859-15':         'iso-8859-15',
    'iso8859-15':          'iso-8859-15',
    'iso885915':           'iso-8859-15',
    'iso_8859-15':         'iso-8859-15',
    'l9':                  'iso-8859-15',
    'iso-8859-16':         'iso-8859-16',
    'cskoi8r':             'koi8-r',
    'koi':                 'koi8-r',
    'koi8':                'koi8-r',
    'koi8-r':              'koi8-r',
    'koi8_r':              'koi8-r',
    'koi8-u':              'koi8-u',
    'csmacintosh':         'macintosh',
    'mac':                 'macintosh',
    'macintosh':           'macintosh',
    'x-mac-roman':         'macintosh',
    'dos-874':             'windows-874',
    'iso-8859-11':         'windows-874',
    'iso8859-11':          'windows-874',
    'iso885911':           'windows-874',
    'tis-620':             'windows-874',
    'windows-874':         'windows-874',
    'cp1250':              'windows-1250',
    'windows-1250':        'windows-1250',
    'x-cp1250':            'windows-1250',
    'cp1251':              'windows-1251',
    'windows-1251':        'windows-1251',
    'x-cp1251':            'windows-1251',
    'ansi_x3.4-1968':      'windows-1252',
    'ascii':               'windows-1252',
    'cp1252':              'windows-1252',
    'cp819':               'windows-1252',
    'csisolatin1':         'windows-1252',
    'ibm819':              'windows-1252',
    'iso-8859-1':          'windows-1252',
    'iso-ir-100':          'windows-1252',
    'iso8859-1':           'windows-1252',
    'iso88591':            'windows-1252',
    'iso_8859-1':          'windows-1252',
    'iso_8859-1:1987':     'windows-1252',
    'l1':                  'windows-1252',
    'latin1':              'windows-1252',
    'us-ascii':            'windows-1252',
    'windows-1252':        'windows-1252',
    'x-cp1252':            'windows-1252',
    'cp1253':              'windows-1253',
    'windows-1253':        'windows-1253',
    'x-cp1253':            'windows-1253',
    'cp1254':              'windows-1254',
    'csisolatin5':         'windows-1254',
    'iso-8859-9':          'windows-1254',
    'iso-ir-148':          'windows-1254',
    'iso8859-9':           'windows-1254',
    'iso88599':            'windows-1254',
    'iso_8859-9':          'windows-1254',
    'iso_8859-9:1989':     'windows-1254',
    'l5':                  'windows-1254',
    'latin5':              'windows-1254',
    'windows-1254':        'windows-1254',
    'x-cp1254':            'windows-1254',
    'cp1255':              'windows-1255',
    'windows-1255':        'windows-1255',
    'x-cp1255':            'windows-1255',
    'cp1256':              'windows-1256',
    'windows-1256':        'windows-1256',
    'x-cp1256':            'windows-1256',
    'cp1257':              'windows-1257',
    'windows-1257':        'windows-1257',
    'x-cp1257':            'windows-1257',
    'cp1258':              'windows-1258',
    'windows-1258':        'windows-1258',
    'x-cp1258':            'windows-1258',
    'x-mac-cyrillic':      'x-mac-cyrillic',
    'x-mac-ukrainian':     'x-mac-cyrillic',
    'chinese':             'gbk',
    'csgb2312':            'gbk',
    'csiso58gb231280':     'gbk',
    'gb2312':              'gbk',
    'gb_2312':             'gbk',
    'gb_2312-80':          'gbk',
    'gbk':                 'gbk',
    'iso-ir-58':           'gbk',
    'x-gbk':               'gbk',
    'gb18030':             'gb18030',
    'hz-gb-2312':          'hz-gb-2312',
    'big5':                'big5',
    'big5-hkscs':          'big5',
    'cn-big5':             'big5',
    'csbig5':              'big5',
    'x-x-big5':            'big5',
    'cseucpkdfmtjapanese': 'euc-jp',
    'euc-jp':              'euc-jp',
    'x-euc-jp':            'euc-jp',
    'csiso2022jp':         'iso-2022-jp',
    'iso-2022-jp':         'iso-2022-jp',
    'csshiftjis':          'shift_jis',
    'ms_kanji':            'shift_jis',
    'shift-jis':           'shift_jis',
    'shift_jis':           'shift_jis',
    'sjis':                'shift_jis',
    'windows-31j':         'shift_jis',
    'x-sjis':              'shift_jis',
    'cseuckr':             'euc-kr',
    'csksc56011987':       'euc-kr',
    'euc-kr':              'euc-kr',
    'iso-ir-149':          'euc-kr',
    'korean':              'euc-kr',
    'ks_c_5601-1987':      'euc-kr',
    'ks_c_5601-1989':      'euc-kr',
    'ksc5601':             'euc-kr',
    'ksc_5601':            'euc-kr',
    'windows-949':         'euc-kr',
    'csiso2022kr':         'iso-2022-kr',
    'iso-2022-kr':         'iso-2022-kr',
    'utf-16be':            'utf-16be',
    'utf-16':              'utf-16le',
    'utf-16le':            'utf-16le',
    'x-user-defined':      'x-user-defined',
}
_vendor/webencodings/x_user_defined.py000064400000010322152527136320014210 0ustar00# coding: utf8
"""

    webencodings.x_user_defined
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~

    An implementation of the x-user-defined encoding.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

from __future__ import unicode_literals

import codecs


### Codec APIs

class Codec(codecs.Codec):

    def encode(self, input, errors='strict'):
        return codecs.charmap_encode(input, errors, encoding_table)

    def decode(self, input, errors='strict'):
        return codecs.charmap_decode(input, errors, decoding_table)


class IncrementalEncoder(codecs.IncrementalEncoder):
    def encode(self, input, final=False):
        return codecs.charmap_encode(input, self.errors, encoding_table)[0]


class IncrementalDecoder(codecs.IncrementalDecoder):
    def decode(self, input, final=False):
        return codecs.charmap_decode(input, self.errors, decoding_table)[0]


class StreamWriter(Codec, codecs.StreamWriter):
    pass


class StreamReader(Codec, codecs.StreamReader):
    pass


### encodings module API

codec_info = codecs.CodecInfo(
    name='x-user-defined',
    encode=Codec().encode,
    decode=Codec().decode,
    incrementalencoder=IncrementalEncoder,
    incrementaldecoder=IncrementalDecoder,
    streamreader=StreamReader,
    streamwriter=StreamWriter,
)


### Decoding Table

# Python 3:
# for c in range(256): print('    %r' % chr(c if c < 128 else c + 0xF700))
decoding_table = (
    '\x00'
    '\x01'
    '\x02'
    '\x03'
    '\x04'
    '\x05'
    '\x06'
    '\x07'
    '\x08'
    '\t'
    '\n'
    '\x0b'
    '\x0c'
    '\r'
    '\x0e'
    '\x0f'
    '\x10'
    '\x11'
    '\x12'
    '\x13'
    '\x14'
    '\x15'
    '\x16'
    '\x17'
    '\x18'
    '\x19'
    '\x1a'
    '\x1b'
    '\x1c'
    '\x1d'
    '\x1e'
    '\x1f'
    ' '
    '!'
    '"'
    '#'
    '$'
    '%'
    '&'
    "'"
    '('
    ')'
    '*'
    '+'
    ','
    '-'
    '.'
    '/'
    '0'
    '1'
    '2'
    '3'
    '4'
    '5'
    '6'
    '7'
    '8'
    '9'
    ':'
    ';'
    '<'
    '='
    '>'
    '?'
    '@'
    'A'
    'B'
    'C'
    'D'
    'E'
    'F'
    'G'
    'H'
    'I'
    'J'
    'K'
    'L'
    'M'
    'N'
    'O'
    'P'
    'Q'
    'R'
    'S'
    'T'
    'U'
    'V'
    'W'
    'X'
    'Y'
    'Z'
    '['
    '\\'
    ']'
    '^'
    '_'
    '`'
    'a'
    'b'
    'c'
    'd'
    'e'
    'f'
    'g'
    'h'
    'i'
    'j'
    'k'
    'l'
    'm'
    'n'
    'o'
    'p'
    'q'
    'r'
    's'
    't'
    'u'
    'v'
    'w'
    'x'
    'y'
    'z'
    '{'
    '|'
    '}'
    '~'
    '\x7f'
    '\uf780'
    '\uf781'
    '\uf782'
    '\uf783'
    '\uf784'
    '\uf785'
    '\uf786'
    '\uf787'
    '\uf788'
    '\uf789'
    '\uf78a'
    '\uf78b'
    '\uf78c'
    '\uf78d'
    '\uf78e'
    '\uf78f'
    '\uf790'
    '\uf791'
    '\uf792'
    '\uf793'
    '\uf794'
    '\uf795'
    '\uf796'
    '\uf797'
    '\uf798'
    '\uf799'
    '\uf79a'
    '\uf79b'
    '\uf79c'
    '\uf79d'
    '\uf79e'
    '\uf79f'
    '\uf7a0'
    '\uf7a1'
    '\uf7a2'
    '\uf7a3'
    '\uf7a4'
    '\uf7a5'
    '\uf7a6'
    '\uf7a7'
    '\uf7a8'
    '\uf7a9'
    '\uf7aa'
    '\uf7ab'
    '\uf7ac'
    '\uf7ad'
    '\uf7ae'
    '\uf7af'
    '\uf7b0'
    '\uf7b1'
    '\uf7b2'
    '\uf7b3'
    '\uf7b4'
    '\uf7b5'
    '\uf7b6'
    '\uf7b7'
    '\uf7b8'
    '\uf7b9'
    '\uf7ba'
    '\uf7bb'
    '\uf7bc'
    '\uf7bd'
    '\uf7be'
    '\uf7bf'
    '\uf7c0'
    '\uf7c1'
    '\uf7c2'
    '\uf7c3'
    '\uf7c4'
    '\uf7c5'
    '\uf7c6'
    '\uf7c7'
    '\uf7c8'
    '\uf7c9'
    '\uf7ca'
    '\uf7cb'
    '\uf7cc'
    '\uf7cd'
    '\uf7ce'
    '\uf7cf'
    '\uf7d0'
    '\uf7d1'
    '\uf7d2'
    '\uf7d3'
    '\uf7d4'
    '\uf7d5'
    '\uf7d6'
    '\uf7d7'
    '\uf7d8'
    '\uf7d9'
    '\uf7da'
    '\uf7db'
    '\uf7dc'
    '\uf7dd'
    '\uf7de'
    '\uf7df'
    '\uf7e0'
    '\uf7e1'
    '\uf7e2'
    '\uf7e3'
    '\uf7e4'
    '\uf7e5'
    '\uf7e6'
    '\uf7e7'
    '\uf7e8'
    '\uf7e9'
    '\uf7ea'
    '\uf7eb'
    '\uf7ec'
    '\uf7ed'
    '\uf7ee'
    '\uf7ef'
    '\uf7f0'
    '\uf7f1'
    '\uf7f2'
    '\uf7f3'
    '\uf7f4'
    '\uf7f5'
    '\uf7f6'
    '\uf7f7'
    '\uf7f8'
    '\uf7f9'
    '\uf7fa'
    '\uf7fb'
    '\uf7fc'
    '\uf7fd'
    '\uf7fe'
    '\uf7ff'
)

### Encoding table
encoding_table = codecs.charmap_build(decoding_table)
_vendor/webencodings/tests.pyo000064400000006233152527136320012554 0ustar00
abc@sdZddlmZddlmZmZmZmZmZm	Z	m
Z
mZmZdZ
dZdZdZd	Zd
ZdZdZd
ZdS(u

    webencodings.tests
    ~~~~~~~~~~~~~~~~~~

    A basic test suite for Encoding.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

i(tunicode_literalsi(	tlookuptLABELStdecodetencodetiter_decodetiter_encodetIncrementalDecodertIncrementalEncodertUTF8cOs:y|||Wn|k
r%dSXtd|dS(NuDid not raise %s.(tAssertionError(t	exceptiontfunctiontargstkwargs((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyt
assert_raisess

cCsdS(N((((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_labelsscCsx\tD]T}x3dddgD]"}tdg||\}}qWt|}t|}qWxttjD]}qrWdS(Niiit(RRRRtsettvalues(tlabeltrepeattoutputt_tdecodertencodertname((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_all_labels0s
cCsptttddtttddtttgdtttgdtttdtttddS(Nséuinvalidué(RtLookupErrorRRRRRR(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_invalid_labelCscCsdS(N((((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_decodeLscCsdS(N((((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_encodebscCs
d}dS(NcSs"t||\}}dj|S(Nu(Rtjoin(tinputtfallback_encodingRt	_encoding((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pytiter_decode_to_stringls((R$((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_iter_decodeks	cCsdS(N((((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_iter_encodescCsd}d}d}d}dS(Ns2,O#ɻtϨu2,O#ttaauaa((tencodedtdecoded((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_x_user_defineds
N(t__doc__t
__future__RRRRRRRRRRR	RRRRRRR%R&R*(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyts@											_vendor/webencodings/x_user_defined.pyo000064400000006454152527136320014402 0ustar00
abc@sdZddlmZddlZdejfdYZdejfdYZdejfd	YZd
eejfdYZdeejfd
YZej	dddej
dejdedededeZdZ
eje
ZdS(u

    webencodings.x_user_defined
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~

    An implementation of the x-user-defined encoding.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

i(tunicode_literalsNtCodeccBs eZddZddZRS(ustrictcCstj||tS(N(tcodecstcharmap_encodetencoding_table(tselftinputterrors((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pytencodescCstj||tS(N(Rtcharmap_decodetdecoding_table(RRR((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pytdecodes(t__name__t
__module__RR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyRstIncrementalEncodercBseZedZRS(cCstj||jtdS(Ni(RRRR(RRtfinal((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyRs(RR
tFalseR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyRstIncrementalDecodercBseZedZRS(cCstj||jtdS(Ni(RR	RR
(RRR((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR$s(RR
RR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR#stStreamWritercBseZRS((RR
(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR(stStreamReadercBseZRS((RR
(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR,stnameux-user-definedRRtincrementalencodertincrementaldecodertstreamreadertstreamwriteru	

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~(t__doc__t
__future__RRRRRRRt	CodecInfoRRt
codec_infoR
t
charmap_buildR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyts$				_vendor/webencodings/labels.pyo000064400000012302152527136320012646 0ustar00
abc@sdZidd6dd6dd6dd6dd6dd6dd6dd	6dd6dd
6dd6dd6dd
6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6dd!6dd"6d#d$6d#d%6d#d#6d#d&6d#d'6d#d(6d#d)6d#d*6d+d,6d+d-6d+d.6d+d/6d+d06d+d16d+d+6d+d26d+d36d+d46d+d56d+d66d+d76d+d86d9d:6d9d;6d9d<6d9d=6d9d>6d9d96d9d?6d9d@6d9dA6d9dB6d9dC6d9dD6dEdF6dEdG6dEdH6dEdE6dEdI6dEdJ6dEdK6dEdL6dEdM6dEdN6dEdO6dPdQ6dPdP6dPdR6dSdT6dSdS6dSdU6dSdV6dSdW6dSdX6dSdY6dZdZ6dZd[6dZd\6d]d]6d]d^6d]d_6d`da6d`d`6d`db6d`dc6d`dd6d`de6dfdf6dgdh6dgdi6dgdj6dgdg6dgdk6dldl6dmdn6dmdo6dmdm6dmdp6dqdr6dqds6dqdt6dqdu6dqdv6dqdq6dwdx6dwdw6dwdy6dzd{6dzdz6dzd|6d}d~6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d}6d}d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6ZdS(s

    webencodings.labels
    ~~~~~~~~~~~~~~~~~~~

    Map encoding labels to their name.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

sutf-8sunicode-1-1-utf-8tutf8tibm866t866tcp866tcsibm866s
iso-8859-2tcsisolatin2s
iso-ir-101s	iso8859-2tiso88592s
iso_8859-2siso_8859-2:1987tl2tlatin2s
iso-8859-3tcsisolatin3s
iso-ir-109s	iso8859-3tiso88593s
iso_8859-3siso_8859-3:1988tl3tlatin3s
iso-8859-4tcsisolatin4s
iso-ir-110s	iso8859-4tiso88594s
iso_8859-4siso_8859-4:1988tl4tlatin4s
iso-8859-5tcsisolatincyrillictcyrillics
iso-ir-144s	iso8859-5tiso88595s
iso_8859-5siso_8859-5:1988s
iso-8859-6tarabicsasmo-708tcsiso88596etcsiso88596itcsisolatinarabicsecma-114siso-8859-6-esiso-8859-6-is
iso-ir-127s	iso8859-6tiso88596s
iso_8859-6siso_8859-6:1987s
iso-8859-7tcsisolatingreeksecma-118telot_928tgreektgreek8s
iso-ir-126s	iso8859-7tiso88597s
iso_8859-7siso_8859-7:1987tsun_eu_greeks
iso-8859-8tcsiso88598etcsisolatinhebrewthebrewsiso-8859-8-es
iso-ir-138s	iso8859-8tiso88598s
iso_8859-8siso_8859-8:1988tvisualsiso-8859-8-itcsiso88598itlogicalsiso-8859-10tcsisolatin6s
iso-ir-157s
iso8859-10t	iso885910tl6tlatin6siso-8859-13s
iso8859-13t	iso885913siso-8859-14s
iso8859-14t	iso885914siso-8859-15tcsisolatin9s
iso8859-15t	iso885915siso_8859-15tl9siso-8859-16skoi8-rtcskoi8rtkoitkoi8tkoi8_rskoi8-ut	macintoshtcsmacintoshtmacsx-mac-romanswindows-874sdos-874siso-8859-11s
iso8859-11t	iso885911stis-620swindows-1250tcp1250sx-cp1250swindows-1251tcp1251sx-cp1251swindows-1252sansi_x3.4-1968tasciitcp1252tcp819tcsisolatin1tibm819s
iso-8859-1s
iso-ir-100s	iso8859-1tiso88591s
iso_8859-1siso_8859-1:1987tl1tlatin1sus-asciisx-cp1252swindows-1253tcp1253sx-cp1253swindows-1254tcp1254tcsisolatin5s
iso-8859-9s
iso-ir-148s	iso8859-9tiso88599s
iso_8859-9siso_8859-9:1989tl5tlatin5sx-cp1254swindows-1255tcp1255sx-cp1255swindows-1256tcp1256sx-cp1256swindows-1257tcp1257sx-cp1257swindows-1258tcp1258sx-cp1258sx-mac-cyrillicsx-mac-ukrainiantgbktchinesetcsgb2312tcsiso58gb231280tgb2312tgb_2312s
gb_2312-80s	iso-ir-58sx-gbktgb18030s
hz-gb-2312tbig5s
big5-hkscsscn-big5tcsbig5sx-x-big5seuc-jptcseucpkdfmtjapanesesx-euc-jpsiso-2022-jptcsiso2022jpt	shift_jist
csshiftjistms_kanjis	shift-jistsjisswindows-31jsx-sjisseuc-krtcseuckrt
csksc56011987s
iso-ir-149tkoreansks_c_5601-1987sks_c_5601-1989tksc5601tksc_5601swindows-949siso-2022-krtcsiso2022krsutf-16besutf-16lesutf-16sx-user-definedN(t__doc__tLABELS(((sC/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/labels.pyts_vendor/webencodings/__init__.pyc000064400000026315152527136320013140 0ustar00
abc@s6dZddlmZddlZddlmZdZidd6d	d
6dd6d
d6ZiZdZ	dZ
dZdefdYZ
e
dZe
dZe
dZddZdZeddZddZdZeddZdZd efd!YZd"efd#YZdS($u

    webencodings
    ~~~~~~~~~~~~

    This is a Python implementation of the `WHATWG Encoding standard
    `. See README for details.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

i(tunicode_literalsNi(tLABELSu0.5u
iso-8859-8uiso-8859-8-iumac-cyrillicux-mac-cyrillicu	mac-romanu	macintoshucp874uwindows-874cCs|jdjjdS(u9Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.

    :param string: An Unicode string.
    :returns: A new Unicode string.

    This is used for `ASCII case-insensitive
    `_
    matching of encoding labels.
    The same matching is also used, among other things,
    for `CSS keywords `_.

    This is different from the :meth:`~py:str.lower` method of Unicode strings
    which also affect non-ASCII characters,
    sometimes mapping them into the ASCII range:

        >>> keyword = u'Bac\N{KELVIN SIGN}ground'
        >>> assert keyword.lower() == u'background'
        >>> assert ascii_lower(keyword) != keyword.lower()
        >>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground'

    uutf8(tencodetlowertdecode(tstring((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pytascii_lower#scCst|jd}tj|}|dkr4dStj|}|dkr|dkrnddlm}n!tj||}t	j
|}t||}|t|`_ algorithm.
    Supported labels are listed there.

    :param label: A string.
    :returns:
        An :class:`Encoding` object, or :obj:`None` for an unknown label.

    u	

 ux-user-definedi(t
codec_infoN(RtstripRtgettNonetCACHEtx_user_definedRtPYTHON_NAMEStcodecstlookuptEncoding(tlabeltnametencodingRtpython_name((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR=s

cCsBt|dr|St|}|dkr>td|n|S(u
    Accept either an encoding object or label.

    :param encoding: An :class:`Encoding` object or a label string.
    :returns: An :class:`Encoding` object.
    :raises: :exc:`~exceptions.LookupError` for an unknown label.

    u
codec_infouUnknown encoding label: %rN(thasattrRR
tLookupError(tencoding_or_labelR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt
_get_encoding[s	RcBs eZdZdZdZRS(uOReresents a character encoding such as UTF-8,
    that can be used for decoding or encoding.

    .. attribute:: name

        Canonical name of the encoding

    .. attribute:: codec_info

        The actual implementation of the encoding,
        a stdlib :class:`~codecs.CodecInfo` object.
        See :func:`codecs.register`.

    cCs||_||_dS(N(RR(tselfRR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt__init__|s	cCsd|jS(Nu
(R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt__repr__s(t__name__t
__module__t__doc__RR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRms	uutf-8uutf-16leuutf-16beureplacecCsGt|}t|\}}|p'|}|jj||d|fS(u
    Decode a single string.

    :param input: A byte string
    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :return:
        A ``(output, encoding)`` tuple of an Unicode string
        and an :obj:`Encoding`.

    i(Rt_detect_bomRR(tinputtfallback_encodingterrorstbom_encodingR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRscCsa|jdrt|dfS|jdr:t|dfS|jdrWt|dfSd|fS(uBReturn (bom_encoding, input), with any BOM removed from the input.sissiN(t
startswitht_UTF16LEt_UTF16BEtUTF8R
(R ((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRsustrictcCst|jj||dS(u;
    Encode a single string.

    :param input: An Unicode string.
    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :return: A byte string.

    i(RRR(R RR"((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRscCs4t||}t||}t|}||fS(u
    "Pull"-based decoder.

    :param input:
        An iterable of byte strings.

        The input is first consumed just enough to determine the encoding
        based on the precense of a BOM,
        then consumed on demand when the return value is.
    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :returns:
        An ``(output, encoding)`` tuple.
        :obj:`output` is an iterable of Unicode strings,
        :obj:`encoding` is the :obj:`Encoding` that is being used.

    (tIncrementalDecodert_iter_decode_generatortnext(R R!R"tdecodert	generatorR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pytiter_decodesccs|j}t|}x|D]>}||}|r|jdk	sIt|jV|VPqqW|ddt}|jdk	st|jV|r|VndSx(|D] }||}|r|VqqW|ddt}|r|VndS(uqReturn a generator that first yields the :obj:`Encoding`,
    then yields output chukns as Unicode strings.

    ttfinalN(RtiterRR
tAssertionErrortTrue(R R+Rtchuncktoutput((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR)s,	

cCst||j}t||S(uY
    “Pull”-based encoder.

    :param input: An iterable of Unicode strings.
    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :returns: An iterable of byte strings.

    (tIncrementalEncoderRt_iter_encode_generator(R RR"R((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pytiter_encodesccsOx(|D] }||}|r|VqqW|ddt}|rK|VndS(NuR/(R2(R RR3R4((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR6s
R(cBs&eZdZddZedZRS(uO
    “Push”-based decoder.

    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.

    ureplacecCs7t||_||_d|_d|_d|_dS(NR.(Rt_fallback_encodingt_errorst_bufferR
t_decoderR(RR!R"((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRs
			cCs|j}|dk	r"|||S|j|}t|\}}|dkrt|dkrs|rs||_dS|j}n|jj|jj	}||_||_
|||S(uDecode one chunk of the input.

        :param input: A byte string.
        :param final:
            Indicate that no more input is available.
            Must be :obj:`True` if this is the last call.
        :returns: An Unicode string.

        iuN(R;R
R:RtlenR8RtincrementaldecoderR9RR(RR R/R+R((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR's
	

			(RRRRtFalseR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR(s
R5cBseZdZeddZRS(u
    “Push”-based encoder.

    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.

    .. method:: encode(input, final=False)

        :param input: An Unicode string.
        :param final:
            Indicate that no more input is available.
            Must be :obj:`True` if this is the last call.
        :returns: A byte string.

    ustrictcCs(t|}|jj|j|_dS(N(RRtincrementalencoderR(RRR"((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRTs(RRRR'R(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR5Cs(Rt
__future__RRtlabelsRtVERSIONR
RRRRtobjectRR'R%R&RRRR-R)R7R6R(R5(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt
s4
					 	
3_vendor/webencodings/mklabels.pyo000064400000004224152527136320013202 0ustar00
abc@szdZddlZyddlmZWn!ek
rIddlmZnXdZdZedkrvedGHndS(s

    webencodings.mklabels
    ~~~~~~~~~~~~~~~~~~~~~

    Regenarate the webencodings.labels module.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

iN(turlopencCs|S(N((tstring((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pytassert_lowerscsdg}gtjt|jjdD]\}|dD]K}|dD]:}tt|jdt|djdf^qJq<q.}td|D|j	fd|D|j
d	d
j|S(Ns"""

    webencodings.labels
    ~~~~~~~~~~~~~~~~~~~

    Map encoding labels to their name.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

# XXX Do not edit!
# This file is automatically generated by mklabels.py

LABELS = {
tasciit	encodingstlabelstutnamecss!|]\}}t|VqdS(N(tlen(t.0tlabelR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pys	2sc3s6|],\}}d|dt||fVqdS(s    %s:%s %s,
t N(R(R	R
R(tmax_len(sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pys	4st}t(tjsontloadsRtreadtdecodetreprRtlstriptmaxtextendtappendtjoin(turltpartstcategorytencodingR
R((RsE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pytgenerates	(N
t__main__s.http://encoding.spec.whatwg.org/encodings.json(	t__doc__RturllibRtImportErrorturllib.requestRRt__name__(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pyts
		!_vendor/webencodings/mklabels.py000064400000002431152527136320013021 0ustar00"""

    webencodings.mklabels
    ~~~~~~~~~~~~~~~~~~~~~

    Regenarate the webencodings.labels module.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

import json
try:
    from urllib import urlopen
except ImportError:
    from urllib.request import urlopen


def assert_lower(string):
    assert string == string.lower()
    return string


def generate(url):
    parts = ['''\
"""

    webencodings.labels
    ~~~~~~~~~~~~~~~~~~~

    Map encoding labels to their name.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

# XXX Do not edit!
# This file is automatically generated by mklabels.py

LABELS = {
''']
    labels = [
        (repr(assert_lower(label)).lstrip('u'),
         repr(encoding['name']).lstrip('u'))
        for category in json.loads(urlopen(url).read().decode('ascii'))
        for encoding in category['encodings']
        for label in encoding['labels']]
    max_len = max(len(label) for label, name in labels)
    parts.extend(
        '    %s:%s %s,\n' % (label, ' ' * (max_len - len(label)), name)
        for label, name in labels)
    parts.append('}')
    return ''.join(parts)


if __name__ == '__main__':
    print(generate('http://encoding.spec.whatwg.org/encodings.json'))
_vendor/webencodings/__init__.pyo000064400000026207152527136320013154 0ustar00
abc@s6dZddlmZddlZddlmZdZidd6d	d
6dd6d
d6ZiZdZ	dZ
dZdefdYZ
e
dZe
dZe
dZddZdZeddZddZdZeddZdZd efd!YZd"efd#YZdS($u

    webencodings
    ~~~~~~~~~~~~

    This is a Python implementation of the `WHATWG Encoding standard
    `. See README for details.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

i(tunicode_literalsNi(tLABELSu0.5u
iso-8859-8uiso-8859-8-iumac-cyrillicux-mac-cyrillicu	mac-romanu	macintoshucp874uwindows-874cCs|jdjjdS(u9Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.

    :param string: An Unicode string.
    :returns: A new Unicode string.

    This is used for `ASCII case-insensitive
    `_
    matching of encoding labels.
    The same matching is also used, among other things,
    for `CSS keywords `_.

    This is different from the :meth:`~py:str.lower` method of Unicode strings
    which also affect non-ASCII characters,
    sometimes mapping them into the ASCII range:

        >>> keyword = u'Bac\N{KELVIN SIGN}ground'
        >>> assert keyword.lower() == u'background'
        >>> assert ascii_lower(keyword) != keyword.lower()
        >>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground'

    uutf8(tencodetlowertdecode(tstring((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pytascii_lower#scCst|jd}tj|}|dkr4dStj|}|dkr|dkrnddlm}n!tj||}t	j
|}t||}|t|`_ algorithm.
    Supported labels are listed there.

    :param label: A string.
    :returns:
        An :class:`Encoding` object, or :obj:`None` for an unknown label.

    u	

 ux-user-definedi(t
codec_infoN(RtstripRtgettNonetCACHEtx_user_definedRtPYTHON_NAMEStcodecstlookuptEncoding(tlabeltnametencodingRtpython_name((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR=s

cCsBt|dr|St|}|dkr>td|n|S(u
    Accept either an encoding object or label.

    :param encoding: An :class:`Encoding` object or a label string.
    :returns: An :class:`Encoding` object.
    :raises: :exc:`~exceptions.LookupError` for an unknown label.

    u
codec_infouUnknown encoding label: %rN(thasattrRR
tLookupError(tencoding_or_labelR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt
_get_encoding[s	RcBs eZdZdZdZRS(uOReresents a character encoding such as UTF-8,
    that can be used for decoding or encoding.

    .. attribute:: name

        Canonical name of the encoding

    .. attribute:: codec_info

        The actual implementation of the encoding,
        a stdlib :class:`~codecs.CodecInfo` object.
        See :func:`codecs.register`.

    cCs||_||_dS(N(RR(tselfRR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt__init__|s	cCsd|jS(Nu
(R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt__repr__s(t__name__t
__module__t__doc__RR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRms	uutf-8uutf-16leuutf-16beureplacecCsGt|}t|\}}|p'|}|jj||d|fS(u
    Decode a single string.

    :param input: A byte string
    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :return:
        A ``(output, encoding)`` tuple of an Unicode string
        and an :obj:`Encoding`.

    i(Rt_detect_bomRR(tinputtfallback_encodingterrorstbom_encodingR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRscCsa|jdrt|dfS|jdr:t|dfS|jdrWt|dfSd|fS(uBReturn (bom_encoding, input), with any BOM removed from the input.sissiN(t
startswitht_UTF16LEt_UTF16BEtUTF8R
(R ((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRsustrictcCst|jj||dS(u;
    Encode a single string.

    :param input: An Unicode string.
    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :return: A byte string.

    i(RRR(R RR"((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRscCs4t||}t||}t|}||fS(u
    "Pull"-based decoder.

    :param input:
        An iterable of byte strings.

        The input is first consumed just enough to determine the encoding
        based on the precense of a BOM,
        then consumed on demand when the return value is.
    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :returns:
        An ``(output, encoding)`` tuple.
        :obj:`output` is an iterable of Unicode strings,
        :obj:`encoding` is the :obj:`Encoding` that is being used.

    (tIncrementalDecodert_iter_decode_generatortnext(R R!R"tdecodert	generatorR((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pytiter_decodesccs|j}t|}x]|D])}||}|r|jV|VPqqW|ddt}|jV|rq|VndSx(|D] }||}|r||Vq|q|W|ddt}|r|VndS(uqReturn a generator that first yields the :obj:`Encoding`,
    then yields output chukns as Unicode strings.

    ttfinalN(RtiterRtTrue(R R+Rtchuncktoutput((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR)s(	

cCst||j}t||S(uY
    “Pull”-based encoder.

    :param input: An iterable of Unicode strings.
    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :returns: An iterable of byte strings.

    (tIncrementalEncoderRt_iter_encode_generator(R RR"R((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pytiter_encodesccsOx(|D] }||}|r|VqqW|ddt}|rK|VndS(NuR/(R1(R RR2R3((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR5s
R(cBs&eZdZddZedZRS(uO
    “Push”-based decoder.

    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.

    ureplacecCs7t||_||_d|_d|_d|_dS(NR.(Rt_fallback_encodingt_errorst_bufferR
t_decoderR(RR!R"((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRs
			cCs|j}|dk	r"|||S|j|}t|\}}|dkrt|dkrs|rs||_dS|j}n|jj|jj	}||_||_
|||S(uDecode one chunk of the input.

        :param input: A byte string.
        :param final:
            Indicate that no more input is available.
            Must be :obj:`True` if this is the last call.
        :returns: An Unicode string.

        iuN(R:R
R9RtlenR7RtincrementaldecoderR8RR(RR R/R+R((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR's
	

			(RRRRtFalseR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR(s
R4cBseZdZeddZRS(u
    “Push”-based encoder.

    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.

    .. method:: encode(input, final=False)

        :param input: An Unicode string.
        :param final:
            Indicate that no more input is available.
            Must be :obj:`True` if this is the last call.
        :returns: A byte string.

    ustrictcCs(t|}|jj|j|_dS(N(RRtincrementalencoderR(RRR"((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyRTs(RRRR'R(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyR4Cs(Rt
__future__RRtlabelsRtVERSIONR
RRRRtobjectRR'R%R&RRRR-R)R6R5R(R4(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/__init__.pyt
s4
					 	
3_vendor/webencodings/x_user_defined.pyc000064400000006454152527136320014366 0ustar00
abc@sdZddlmZddlZdejfdYZdejfdYZdejfd	YZd
eejfdYZdeejfd
YZej	dddej
dejdedededeZdZ
eje
ZdS(u

    webencodings.x_user_defined
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~

    An implementation of the x-user-defined encoding.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

i(tunicode_literalsNtCodeccBs eZddZddZRS(ustrictcCstj||tS(N(tcodecstcharmap_encodetencoding_table(tselftinputterrors((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pytencodescCstj||tS(N(Rtcharmap_decodetdecoding_table(RRR((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pytdecodes(t__name__t
__module__RR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyRstIncrementalEncodercBseZedZRS(cCstj||jtdS(Ni(RRRR(RRtfinal((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyRs(RR
tFalseR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyRstIncrementalDecodercBseZedZRS(cCstj||jtdS(Ni(RR	RR
(RRR((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR$s(RR
RR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR#stStreamWritercBseZRS((RR
(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR(stStreamReadercBseZRS((RR
(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyR,stnameux-user-definedRRtincrementalencodertincrementaldecodertstreamreadertstreamwriteru	

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~(t__doc__t
__future__RRRRRRRt	CodecInfoRRt
codec_infoR
t
charmap_buildR(((sK/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/x_user_defined.pyts$				_vendor/webencodings/tests.pyc000064400000015254152527136320012543 0ustar00
abc@sdZddlmZddlmZmZmZmZmZm	Z	m
Z
mZmZdZ
dZdZdZd	Zd
ZdZdZd
ZdS(u

    webencodings.tests
    ~~~~~~~~~~~~~~~~~~

    A basic test suite for Encoding.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

i(tunicode_literalsi(	tlookuptLABELStdecodetencodetiter_decodetiter_encodetIncrementalDecodertIncrementalEncodertUTF8cOs:y|||Wn|k
r%dSXtd|dS(NuDid not raise %s.(tAssertionError(t	exceptiontfunctiontargstkwargs((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyt
assert_raisess

cCstdjdksttdjdks6ttdjdksQttdjdkslttdjdksttdjdksttdjdksttddksttddksttd	jd
ksttdjd
ks#ttdjd
ks>ttd
jd
ksYttddksqttddkstdS(Nuutf-8uUtf-8uUTF-8uutf8uutf8 u 
utf8	uu8uutf-8 uUS-ASCIIuwindows-1252u
iso-8859-1ulatin1uLATIN1ulatin-1uLATİN1(RtnameR
tNone(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_labelsscCsxVtD]N}td|dt|fks4ttd|dksOtxsdddgD]b}tdg||\}}t|gkstttdg||gks_tq_Wt|}|jddkst|jddt	dks
tt
|}|jddks4t|jddt	dkstqWx5ttjD]!}t|j
|ksltqlWdS(Ntuiiitfinal(RRRR
RRtlistRRtTrueRtsettvaluesR(tlabeltrepeattoutputt_tdecodertencoderR((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_all_labels0s
',!%cCsptttddtttddtttgdtttgdtttdtttddS(Nséuinvalidué(RtLookupErrorRRRRRR(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_invalid_labelCscCsztdddtdfks'ttdtddtdfksTttdddtdfks{ttdtdtdfksttdddtdfksttd	ddtdfksttd
ddtdfksttdddtd
fks>ttdddtdfksettdddtd
fksttdddtdfksttdddtd
fksttdddtd
fksttdddtdfks(ttdddtd
fksOttdddtd
fksvtdS(Nsulatin1u€séuutf8uéuasciiuésésuutf-16besuutf-16lesussuUTF-16BEsuUTF-16LEuUTF-16(RRR
R	(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_decodeLs '-'''''''''''''cCstdddksttdddks6ttdddksQttdddkslttdddksttdd	d
kstdS(Nuéulatin1suutf8séuutf-16suutf-16leuutf-16bes(RR
(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_encodebscCs>d}|gddks$t|dgddksBt|dgddks`t|dgddks~t|d	d
gddkst|ddgddkst|d
gddkst|dgddkst|dddgddks t|dddgddksDt|ddddddgddksqt|dgddkst|dgddkst|dgddkst|dgddkst|ddddddgddkst|ddd
gdd ks:tdS(!NcSs"t||\}}dj|S(Nu(Rtjoin(tinputtfallback_encodingRt	_encoding((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pytiter_decode_to_stringlsulatin1uRsuéthellouhellothetllothelltoséuéséssstaua�sssuï»sssssshux-user-defineduhllo(R
(R(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_iter_decodeks.	!!!!**cCsfdjtgddks$tdjtdgddksKtdjtdgddksrtdjtddddgddkstdjtddddgddkstdjtddddgddkstdjtddddgd	d
ks2tdjtddddgd
dksbtdS(NRulatin1uuésuutf-16suutf-16leuutf-16besuhulloux-user-definedshllo(R$RR
(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_iter_encodes$''0000	cCs^d}d}d}d}t|d|tdfks?tt|d|ksZtdS(Ns2,O#ɻtϨu2,O#ttaauaaux-user-defined(RRR
R(tencodedtdecoded((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyttest_x_user_defineds'N(t__doc__t
__future__RRRRRRRRRRR	RRRR!R"R#R/R0R4(((sB/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/tests.pyts@											_vendor/webencodings/tests.py000064400000014642152527136320012400 0ustar00# coding: utf8
"""

    webencodings.tests
    ~~~~~~~~~~~~~~~~~~

    A basic test suite for Encoding.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

from __future__ import unicode_literals

from . import (lookup, LABELS, decode, encode, iter_decode, iter_encode,
               IncrementalDecoder, IncrementalEncoder, UTF8)


def assert_raises(exception, function, *args, **kwargs):
    try:
        function(*args, **kwargs)
    except exception:
        return
    else:  # pragma: no cover
        raise AssertionError('Did not raise %s.' % exception)


def test_labels():
    assert lookup('utf-8').name == 'utf-8'
    assert lookup('Utf-8').name == 'utf-8'
    assert lookup('UTF-8').name == 'utf-8'
    assert lookup('utf8').name == 'utf-8'
    assert lookup('utf8').name == 'utf-8'
    assert lookup('utf8 ').name == 'utf-8'
    assert lookup(' \r\nutf8\t').name == 'utf-8'
    assert lookup('u8') is None  # Python label.
    assert lookup('utf-8 ') is None  # Non-ASCII white space.

    assert lookup('US-ASCII').name == 'windows-1252'
    assert lookup('iso-8859-1').name == 'windows-1252'
    assert lookup('latin1').name == 'windows-1252'
    assert lookup('LATIN1').name == 'windows-1252'
    assert lookup('latin-1') is None
    assert lookup('LATİN1') is None  # ASCII-only case insensitivity.


def test_all_labels():
    for label in LABELS:
        assert decode(b'', label) == ('', lookup(label))
        assert encode('', label) == b''
        for repeat in [0, 1, 12]:
            output, _ = iter_decode([b''] * repeat, label)
            assert list(output) == []
            assert list(iter_encode([''] * repeat, label)) == []
        decoder = IncrementalDecoder(label)
        assert decoder.decode(b'') == ''
        assert decoder.decode(b'', final=True) == ''
        encoder = IncrementalEncoder(label)
        assert encoder.encode('') == b''
        assert encoder.encode('', final=True) == b''
    # All encoding names are valid labels too:
    for name in set(LABELS.values()):
        assert lookup(name).name == name


def test_invalid_label():
    assert_raises(LookupError, decode, b'\xEF\xBB\xBF\xc3\xa9', 'invalid')
    assert_raises(LookupError, encode, 'é', 'invalid')
    assert_raises(LookupError, iter_decode, [], 'invalid')
    assert_raises(LookupError, iter_encode, [], 'invalid')
    assert_raises(LookupError, IncrementalDecoder, 'invalid')
    assert_raises(LookupError, IncrementalEncoder, 'invalid')


def test_decode():
    assert decode(b'\x80', 'latin1') == ('€', lookup('latin1'))
    assert decode(b'\x80', lookup('latin1')) == ('€', lookup('latin1'))
    assert decode(b'\xc3\xa9', 'utf8') == ('é', lookup('utf8'))
    assert decode(b'\xc3\xa9', UTF8) == ('é', lookup('utf8'))
    assert decode(b'\xc3\xa9', 'ascii') == ('é', lookup('ascii'))
    assert decode(b'\xEF\xBB\xBF\xc3\xa9', 'ascii') == ('é', lookup('utf8'))  # UTF-8 with BOM

    assert decode(b'\xFE\xFF\x00\xe9', 'ascii') == ('é', lookup('utf-16be'))  # UTF-16-BE with BOM
    assert decode(b'\xFF\xFE\xe9\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM
    assert decode(b'\xFE\xFF\xe9\x00', 'ascii') == ('\ue900', lookup('utf-16be'))
    assert decode(b'\xFF\xFE\x00\xe9', 'ascii') == ('\ue900', lookup('utf-16le'))

    assert decode(b'\x00\xe9', 'UTF-16BE') == ('é', lookup('utf-16be'))
    assert decode(b'\xe9\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))
    assert decode(b'\xe9\x00', 'UTF-16') == ('é', lookup('utf-16le'))

    assert decode(b'\xe9\x00', 'UTF-16BE') == ('\ue900', lookup('utf-16be'))
    assert decode(b'\x00\xe9', 'UTF-16LE') == ('\ue900', lookup('utf-16le'))
    assert decode(b'\x00\xe9', 'UTF-16') == ('\ue900', lookup('utf-16le'))


def test_encode():
    assert encode('é', 'latin1') == b'\xe9'
    assert encode('é', 'utf8') == b'\xc3\xa9'
    assert encode('é', 'utf8') == b'\xc3\xa9'
    assert encode('é', 'utf-16') == b'\xe9\x00'
    assert encode('é', 'utf-16le') == b'\xe9\x00'
    assert encode('é', 'utf-16be') == b'\x00\xe9'


def test_iter_decode():
    def iter_decode_to_string(input, fallback_encoding):
        output, _encoding = iter_decode(input, fallback_encoding)
        return ''.join(output)
    assert iter_decode_to_string([], 'latin1') == ''
    assert iter_decode_to_string([b''], 'latin1') == ''
    assert iter_decode_to_string([b'\xe9'], 'latin1') == 'é'
    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'
    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'
    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'
    assert iter_decode_to_string([b'\xc3\xa9'], 'latin1') == 'é'
    assert iter_decode_to_string([b'\xEF\xBB\xBF\xc3\xa9'], 'latin1') == 'é'
    assert iter_decode_to_string([
        b'\xEF\xBB\xBF', b'\xc3', b'\xa9'], 'latin1') == 'é'
    assert iter_decode_to_string([
        b'\xEF\xBB\xBF', b'a', b'\xc3'], 'latin1') == 'a\uFFFD'
    assert iter_decode_to_string([
        b'', b'\xEF', b'', b'', b'\xBB\xBF\xc3', b'\xa9'], 'latin1') == 'é'
    assert iter_decode_to_string([b'\xEF\xBB\xBF'], 'latin1') == ''
    assert iter_decode_to_string([b'\xEF\xBB'], 'latin1') == 'ï»'
    assert iter_decode_to_string([b'\xFE\xFF\x00\xe9'], 'latin1') == 'é'
    assert iter_decode_to_string([b'\xFF\xFE\xe9\x00'], 'latin1') == 'é'
    assert iter_decode_to_string([
        b'', b'\xFF', b'', b'', b'\xFE\xe9', b'\x00'], 'latin1') == 'é'
    assert iter_decode_to_string([
        b'', b'h\xe9', b'llo'], 'x-user-defined') == 'h\uF7E9llo'


def test_iter_encode():
    assert b''.join(iter_encode([], 'latin1')) == b''
    assert b''.join(iter_encode([''], 'latin1')) == b''
    assert b''.join(iter_encode(['é'], 'latin1')) == b'\xe9'
    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\xe9'
    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\xe9\x00'
    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\xe9\x00'
    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\x00\xe9'
    assert b''.join(iter_encode([
        '', 'h\uF7E9', '', 'llo'], 'x-user-defined')) == b'h\xe9llo'


def test_x_user_defined():
    encoded = b'2,\x0c\x0b\x1aO\xd9#\xcb\x0f\xc9\xbbt\xcf\xa8\xca'
    decoded = '2,\x0c\x0b\x1aO\uf7d9#\uf7cb\x0f\uf7c9\uf7bbt\uf7cf\uf7a8\uf7ca'
    encoded = b'aa'
    decoded = 'aa'
    assert decode(encoded, 'x-user-defined') == (decoded, lookup('x-user-defined'))
    assert encode(decoded, 'x-user-defined') == encoded
_vendor/webencodings/labels.pyc000064400000012302152527136320012632 0ustar00
abc@sdZidd6dd6dd6dd6dd6dd6dd6dd	6dd6dd
6dd6dd6dd
6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6dd!6dd"6d#d$6d#d%6d#d#6d#d&6d#d'6d#d(6d#d)6d#d*6d+d,6d+d-6d+d.6d+d/6d+d06d+d16d+d+6d+d26d+d36d+d46d+d56d+d66d+d76d+d86d9d:6d9d;6d9d<6d9d=6d9d>6d9d96d9d?6d9d@6d9dA6d9dB6d9dC6d9dD6dEdF6dEdG6dEdH6dEdE6dEdI6dEdJ6dEdK6dEdL6dEdM6dEdN6dEdO6dPdQ6dPdP6dPdR6dSdT6dSdS6dSdU6dSdV6dSdW6dSdX6dSdY6dZdZ6dZd[6dZd\6d]d]6d]d^6d]d_6d`da6d`d`6d`db6d`dc6d`dd6d`de6dfdf6dgdh6dgdi6dgdj6dgdg6dgdk6dldl6dmdn6dmdo6dmdm6dmdp6dqdr6dqds6dqdt6dqdu6dqdv6dqdq6dwdx6dwdw6dwdy6dzd{6dzdz6dzd|6d}d~6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d6d}d}6d}d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6ZdS(s

    webencodings.labels
    ~~~~~~~~~~~~~~~~~~~

    Map encoding labels to their name.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

sutf-8sunicode-1-1-utf-8tutf8tibm866t866tcp866tcsibm866s
iso-8859-2tcsisolatin2s
iso-ir-101s	iso8859-2tiso88592s
iso_8859-2siso_8859-2:1987tl2tlatin2s
iso-8859-3tcsisolatin3s
iso-ir-109s	iso8859-3tiso88593s
iso_8859-3siso_8859-3:1988tl3tlatin3s
iso-8859-4tcsisolatin4s
iso-ir-110s	iso8859-4tiso88594s
iso_8859-4siso_8859-4:1988tl4tlatin4s
iso-8859-5tcsisolatincyrillictcyrillics
iso-ir-144s	iso8859-5tiso88595s
iso_8859-5siso_8859-5:1988s
iso-8859-6tarabicsasmo-708tcsiso88596etcsiso88596itcsisolatinarabicsecma-114siso-8859-6-esiso-8859-6-is
iso-ir-127s	iso8859-6tiso88596s
iso_8859-6siso_8859-6:1987s
iso-8859-7tcsisolatingreeksecma-118telot_928tgreektgreek8s
iso-ir-126s	iso8859-7tiso88597s
iso_8859-7siso_8859-7:1987tsun_eu_greeks
iso-8859-8tcsiso88598etcsisolatinhebrewthebrewsiso-8859-8-es
iso-ir-138s	iso8859-8tiso88598s
iso_8859-8siso_8859-8:1988tvisualsiso-8859-8-itcsiso88598itlogicalsiso-8859-10tcsisolatin6s
iso-ir-157s
iso8859-10t	iso885910tl6tlatin6siso-8859-13s
iso8859-13t	iso885913siso-8859-14s
iso8859-14t	iso885914siso-8859-15tcsisolatin9s
iso8859-15t	iso885915siso_8859-15tl9siso-8859-16skoi8-rtcskoi8rtkoitkoi8tkoi8_rskoi8-ut	macintoshtcsmacintoshtmacsx-mac-romanswindows-874sdos-874siso-8859-11s
iso8859-11t	iso885911stis-620swindows-1250tcp1250sx-cp1250swindows-1251tcp1251sx-cp1251swindows-1252sansi_x3.4-1968tasciitcp1252tcp819tcsisolatin1tibm819s
iso-8859-1s
iso-ir-100s	iso8859-1tiso88591s
iso_8859-1siso_8859-1:1987tl1tlatin1sus-asciisx-cp1252swindows-1253tcp1253sx-cp1253swindows-1254tcp1254tcsisolatin5s
iso-8859-9s
iso-ir-148s	iso8859-9tiso88599s
iso_8859-9siso_8859-9:1989tl5tlatin5sx-cp1254swindows-1255tcp1255sx-cp1255swindows-1256tcp1256sx-cp1256swindows-1257tcp1257sx-cp1257swindows-1258tcp1258sx-cp1258sx-mac-cyrillicsx-mac-ukrainiantgbktchinesetcsgb2312tcsiso58gb231280tgb2312tgb_2312s
gb_2312-80s	iso-ir-58sx-gbktgb18030s
hz-gb-2312tbig5s
big5-hkscsscn-big5tcsbig5sx-x-big5seuc-jptcseucpkdfmtjapanesesx-euc-jpsiso-2022-jptcsiso2022jpt	shift_jist
csshiftjistms_kanjis	shift-jistsjisswindows-31jsx-sjisseuc-krtcseuckrt
csksc56011987s
iso-ir-149tkoreansks_c_5601-1987sks_c_5601-1989tksc5601tksc_5601swindows-949siso-2022-krtcsiso2022krsutf-16besutf-16lesutf-16sx-user-definedN(t__doc__tLABELS(((sC/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/labels.pyts_vendor/webencodings/__init__.py000064400000024520152527136320012771 0ustar00# coding: utf8
"""

    webencodings
    ~~~~~~~~~~~~

    This is a Python implementation of the `WHATWG Encoding standard
    `. See README for details.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

from __future__ import unicode_literals

import codecs

from .labels import LABELS


VERSION = '0.5'


# Some names in Encoding are not valid Python aliases. Remap these.
PYTHON_NAMES = {
    'iso-8859-8-i': 'iso-8859-8',
    'x-mac-cyrillic': 'mac-cyrillic',
    'macintosh': 'mac-roman',
    'windows-874': 'cp874'}

CACHE = {}


def ascii_lower(string):
    r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.

    :param string: An Unicode string.
    :returns: A new Unicode string.

    This is used for `ASCII case-insensitive
    `_
    matching of encoding labels.
    The same matching is also used, among other things,
    for `CSS keywords `_.

    This is different from the :meth:`~py:str.lower` method of Unicode strings
    which also affect non-ASCII characters,
    sometimes mapping them into the ASCII range:

        >>> keyword = u'Bac\N{KELVIN SIGN}ground'
        >>> assert keyword.lower() == u'background'
        >>> assert ascii_lower(keyword) != keyword.lower()
        >>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground'

    """
    # This turns out to be faster than unicode.translate()
    return string.encode('utf8').lower().decode('utf8')


def lookup(label):
    """
    Look for an encoding by its label.
    This is the spec’s `get an encoding
    `_ algorithm.
    Supported labels are listed there.

    :param label: A string.
    :returns:
        An :class:`Encoding` object, or :obj:`None` for an unknown label.

    """
    # Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020.
    label = ascii_lower(label.strip('\t\n\f\r '))
    name = LABELS.get(label)
    if name is None:
        return None
    encoding = CACHE.get(name)
    if encoding is None:
        if name == 'x-user-defined':
            from .x_user_defined import codec_info
        else:
            python_name = PYTHON_NAMES.get(name, name)
            # Any python_name value that gets to here should be valid.
            codec_info = codecs.lookup(python_name)
        encoding = Encoding(name, codec_info)
        CACHE[name] = encoding
    return encoding


def _get_encoding(encoding_or_label):
    """
    Accept either an encoding object or label.

    :param encoding: An :class:`Encoding` object or a label string.
    :returns: An :class:`Encoding` object.
    :raises: :exc:`~exceptions.LookupError` for an unknown label.

    """
    if hasattr(encoding_or_label, 'codec_info'):
        return encoding_or_label

    encoding = lookup(encoding_or_label)
    if encoding is None:
        raise LookupError('Unknown encoding label: %r' % encoding_or_label)
    return encoding


class Encoding(object):
    """Reresents a character encoding such as UTF-8,
    that can be used for decoding or encoding.

    .. attribute:: name

        Canonical name of the encoding

    .. attribute:: codec_info

        The actual implementation of the encoding,
        a stdlib :class:`~codecs.CodecInfo` object.
        See :func:`codecs.register`.

    """
    def __init__(self, name, codec_info):
        self.name = name
        self.codec_info = codec_info

    def __repr__(self):
        return '' % self.name


#: The UTF-8 encoding. Should be used for new content and formats.
UTF8 = lookup('utf-8')

_UTF16LE = lookup('utf-16le')
_UTF16BE = lookup('utf-16be')


def decode(input, fallback_encoding, errors='replace'):
    """
    Decode a single string.

    :param input: A byte string
    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :return:
        A ``(output, encoding)`` tuple of an Unicode string
        and an :obj:`Encoding`.

    """
    # Fail early if `encoding` is an invalid label.
    fallback_encoding = _get_encoding(fallback_encoding)
    bom_encoding, input = _detect_bom(input)
    encoding = bom_encoding or fallback_encoding
    return encoding.codec_info.decode(input, errors)[0], encoding


def _detect_bom(input):
    """Return (bom_encoding, input), with any BOM removed from the input."""
    if input.startswith(b'\xFF\xFE'):
        return _UTF16LE, input[2:]
    if input.startswith(b'\xFE\xFF'):
        return _UTF16BE, input[2:]
    if input.startswith(b'\xEF\xBB\xBF'):
        return UTF8, input[3:]
    return None, input


def encode(input, encoding=UTF8, errors='strict'):
    """
    Encode a single string.

    :param input: An Unicode string.
    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :return: A byte string.

    """
    return _get_encoding(encoding).codec_info.encode(input, errors)[0]


def iter_decode(input, fallback_encoding, errors='replace'):
    """
    "Pull"-based decoder.

    :param input:
        An iterable of byte strings.

        The input is first consumed just enough to determine the encoding
        based on the precense of a BOM,
        then consumed on demand when the return value is.
    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :returns:
        An ``(output, encoding)`` tuple.
        :obj:`output` is an iterable of Unicode strings,
        :obj:`encoding` is the :obj:`Encoding` that is being used.

    """

    decoder = IncrementalDecoder(fallback_encoding, errors)
    generator = _iter_decode_generator(input, decoder)
    encoding = next(generator)
    return generator, encoding


def _iter_decode_generator(input, decoder):
    """Return a generator that first yields the :obj:`Encoding`,
    then yields output chukns as Unicode strings.

    """
    decode = decoder.decode
    input = iter(input)
    for chunck in input:
        output = decode(chunck)
        if output:
            assert decoder.encoding is not None
            yield decoder.encoding
            yield output
            break
    else:
        # Input exhausted without determining the encoding
        output = decode(b'', final=True)
        assert decoder.encoding is not None
        yield decoder.encoding
        if output:
            yield output
        return

    for chunck in input:
        output = decode(chunck)
        if output:
            yield output
    output = decode(b'', final=True)
    if output:
        yield output


def iter_encode(input, encoding=UTF8, errors='strict'):
    """
    “Pull”-based encoder.

    :param input: An iterable of Unicode strings.
    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
    :returns: An iterable of byte strings.

    """
    # Fail early if `encoding` is an invalid label.
    encode = IncrementalEncoder(encoding, errors).encode
    return _iter_encode_generator(input, encode)


def _iter_encode_generator(input, encode):
    for chunck in input:
        output = encode(chunck)
        if output:
            yield output
    output = encode('', final=True)
    if output:
        yield output


class IncrementalDecoder(object):
    """
    “Push”-based decoder.

    :param fallback_encoding:
        An :class:`Encoding` object or a label string.
        The encoding to use if :obj:`input` does note have a BOM.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.

    """
    def __init__(self, fallback_encoding, errors='replace'):
        # Fail early if `encoding` is an invalid label.
        self._fallback_encoding = _get_encoding(fallback_encoding)
        self._errors = errors
        self._buffer = b''
        self._decoder = None
        #: The actual :class:`Encoding` that is being used,
        #: or :obj:`None` if that is not determined yet.
        #: (Ie. if there is not enough input yet to determine
        #: if there is a BOM.)
        self.encoding = None  # Not known yet.

    def decode(self, input, final=False):
        """Decode one chunk of the input.

        :param input: A byte string.
        :param final:
            Indicate that no more input is available.
            Must be :obj:`True` if this is the last call.
        :returns: An Unicode string.

        """
        decoder = self._decoder
        if decoder is not None:
            return decoder(input, final)

        input = self._buffer + input
        encoding, input = _detect_bom(input)
        if encoding is None:
            if len(input) < 3 and not final:  # Not enough data yet.
                self._buffer = input
                return ''
            else:  # No BOM
                encoding = self._fallback_encoding
        decoder = encoding.codec_info.incrementaldecoder(self._errors).decode
        self._decoder = decoder
        self.encoding = encoding
        return decoder(input, final)


class IncrementalEncoder(object):
    """
    “Push”-based encoder.

    :param encoding: An :class:`Encoding` object or a label string.
    :param errors: Type of error handling. See :func:`codecs.register`.
    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.

    .. method:: encode(input, final=False)

        :param input: An Unicode string.
        :param final:
            Indicate that no more input is available.
            Must be :obj:`True` if this is the last call.
        :returns: A byte string.

    """
    def __init__(self, encoding=UTF8, errors='strict'):
        encoding = _get_encoding(encoding)
        self.encode = encoding.codec_info.incrementalencoder(errors).encode
_vendor/webencodings/mklabels.pyc000064400000004313152527136320013165 0ustar00
abc@szdZddlZyddlmZWn!ek
rIddlmZnXdZdZedkrvedGHndS(s

    webencodings.mklabels
    ~~~~~~~~~~~~~~~~~~~~~

    Regenarate the webencodings.labels module.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

iN(turlopencCs||jkst|S(N(tlowertAssertionError(tstring((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pytassert_lowerscsdg}gtjt|jjdD]\}|dD]K}|dD]:}tt|jdt|djdf^qJq<q.}td|D|j	fd|D|j
d	d
j|S(Ns"""

    webencodings.labels
    ~~~~~~~~~~~~~~~~~~~

    Map encoding labels to their name.

    :copyright: Copyright 2012 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

# XXX Do not edit!
# This file is automatically generated by mklabels.py

LABELS = {
tasciit	encodingstlabelstutnamecss!|]\}}t|VqdS(N(tlen(t.0tlabelR	((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pys	2sc3s6|],\}}d|dt||fVqdS(s    %s:%s %s,
t N(R
(RRR	(tmax_len(sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pys	4st}t(tjsontloadsRtreadtdecodetreprRtlstriptmaxtextendtappendtjoin(turltpartstcategorytencodingRR((RsE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pytgenerates	(N
t__main__s.http://encoding.spec.whatwg.org/encodings.json(	t__doc__RturllibRtImportErrorturllib.requestRRt__name__(((sE/usr/lib/python2.7/site-packages/pip/_vendor/webencodings/mklabels.pyts
		!_vendor/lockfile/sqlitelockfile.pyc000064400000011137152527136320013530 0ustar00
abc@`sddlmZmZddlZddlZyeWnek
rOeZnXddlm	Z	m
Z
mZmZm
Z
de	fdYZdS(i(tabsolute_importtdivisionNi(tLockBaset	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedtSQLiteLockFilecB`s\eZdZdZeddZddZdZdZ	dZ
dZdZRS(	sDemonstrate SQL-based locking.c
C`stj||||t|j|_t|j|_tjdkrddl}|j	\}}t
j|t
j|~~|t_nddl
}|jtj|_|jj}y|jdWn|jk
rn0X|jjddl}	|	jt
jtjdS(su
        >>> lock = SQLiteLockFile('somefile')
        >>> lock = SQLiteLockFile('somefile', threaded=False)
        iNsGcreate table locks(   lock_file varchar(32),   unique_name varchar(32))(Rt__init__tunicodet	lock_filetunique_nameRttestdbtNonettempfiletmkstemptostclosetunlinktsqlite3tconnectt
connectiontcursortexecutetOperationalErrortcommittatexittregister(
tselftpathtthreadedttimeoutRt_fdRRtcR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyRs(


cC`s|dk	r|n|j}tj}|dk	rL|dkrL||7}n|dkrad}n|dkrvd}n
|d}|jj}x;tr|js.|jd|j|j	f|jj
|jd|j	f|j}t|dkr'|jd|j	f|jj
qfdSn8|jd|j	f|j}t|dkrfdS|dk	rtj|kr|dkrt
d|jqtd	|jntj|qWdS(
Nig?i
s;insert into locks  (lock_file, unique_name)  values  (?, ?)s*select * from locks  where unique_name = ?is(delete from locks  where unique_name = ?s&Timeout waiting to acquire lock for %ss%s is already locked(R
RttimeRRtTruet	is_lockedRR
RRtfetchalltlenRRRtsleep(RRtend_timetwaitRtrows((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pytacquire5sD
		
		
	
	
	
cC`s|js"td|jn|jsPtd|j|jfn|jj}|j	d|jf|jj
dS(Ns%s is not lockeds#%s is locked, but not by me (by %s)s(delete from locks  where unique_name = ?(R$RRti_am_lockingRRt_who_is_lockingRRRR(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pytreleasets	
cC`s3|jj}|jd|jf|jdS(Ns2select unique_name from locks  where lock_file = ?i(RRRR
tfetchone(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyR-s	
cC`s7|jj}|jd|jf|j}|S(Ns(select * from locks  where lock_file = ?(RRRR
R%(RRR*((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyR$s
	
cC`s7|jj}|jd|j|jf|jS(Ns?select * from locks  where lock_file = ?    and unique_name = ?(RRRR
RR%(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyR,s	cC`s6|jj}|jd|jf|jjdS(Ns&delete from locks  where lock_file = ?(RRRR
R(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyt
break_locks	
N(
t__name__t
__module__t__doc__R
RR#RR+R.R-R$R,R0(((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyRs"?				(t
__future__RRR"RR	t	NameErrortstrtRRRRRR(((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyts

(_vendor/lockfile/mkdirlockfile.pyc000064400000006542152527136320013341 0ustar00
abc@`sddlmZmZddlZddlZddlZddlZddlmZm	Z	m
Z
mZmZm
Z
defdYZdS(i(tabsolute_importtdivisionNi(tLockBaset
LockFailedt	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedt
MkdirLockFilecB`sMeZdZeddZddZdZdZdZ	dZ
RS(s"Lock file by creating a directory.cC`sKtj||||tjj|jd|j|j|jf|_	dS(ss
        >>> lock = MkdirLockFile('somefile')
        >>> lock = MkdirLockFile('somefile', threaded=False)
        s%s.%s%sN(
Rt__init__tostpathtjoint	lock_filethostnamettnametpidtunique_name(tselfRtthreadedttimeout((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyR	s
	cC`s{|dk	r|n|j}tj}|dk	rL|dkrL||7}n|dkrad}ntd|d}xtrvytj|jWntk
rXt	j
d}|jtjkrBtj
j|jrdS|dk	r2tj|kr2|dkrtd|j
q2td|j
ntj|qstd|jqwXt|jdjdSqwWdS(	Nig?i
is&Timeout waiting to acquire lock for %ss%s is already lockedsfailed to create %stwb(tNoneRttimetmaxtTrueR
tmkdirR
tOSErrortsystexc_infoterrnotEEXISTRtexistsRRRtsleepRtopentclose(RRtend_timetwaitterr((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pytacquires2
		
cC`sq|js"td|jn+tjj|jsMtd|jntj|jtj|j	dS(Ns%s is not lockeds%s is locked, but not by me(
t	is_lockedRRR
R RRtunlinktrmdirR
(R((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pytreleaseAscC`stjj|jS(N(R
RR R
(R((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyR(IscC`s|jotjj|jS(N(R(R
RR R(R((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyti_am_lockingLscC`shtjj|jrdx9tj|jD]%}tjtjj|j|q(Wtj|jndS(N(R
RR R
tlistdirR)RR*(Rtname((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyt
break_lockPs#N(t__name__t
__module__t__doc__RRR	R'R+R(R,R/(((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyRs
&			(t
__future__RRRR
RRtRRRRRRR(((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyts._vendor/lockfile/mkdirlockfile.py000064400000006030152527136320013166 0ustar00from __future__ import absolute_import, division

import time
import os
import sys
import errno

from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout,
               AlreadyLocked)


class MkdirLockFile(LockBase):
    """Lock file by creating a directory."""
    def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = MkdirLockFile('somefile')
        >>> lock = MkdirLockFile('somefile', threaded=False)
        """
        LockBase.__init__(self, path, threaded, timeout)
        # Lock file itself is a directory.  Place the unique file name into
        # it.
        self.unique_name = os.path.join(self.lock_file,
                                        "%s.%s%s" % (self.hostname,
                                                     self.tname,
                                                     self.pid))

    def acquire(self, timeout=None):
        timeout = timeout if timeout is not None else self.timeout
        end_time = time.time()
        if timeout is not None and timeout > 0:
            end_time += timeout

        if timeout is None:
            wait = 0.1
        else:
            wait = max(0, timeout / 10)

        while True:
            try:
                os.mkdir(self.lock_file)
            except OSError:
                err = sys.exc_info()[1]
                if err.errno == errno.EEXIST:
                    # Already locked.
                    if os.path.exists(self.unique_name):
                        # Already locked by me.
                        return
                    if timeout is not None and time.time() > end_time:
                        if timeout > 0:
                            raise LockTimeout("Timeout waiting to acquire"
                                              " lock for %s" %
                                              self.path)
                        else:
                            # Someone else has the lock.
                            raise AlreadyLocked("%s is already locked" %
                                                self.path)
                    time.sleep(wait)
                else:
                    # Couldn't create the lock for some other reason
                    raise LockFailed("failed to create %s" % self.lock_file)
            else:
                open(self.unique_name, "wb").close()
                return

    def release(self):
        if not self.is_locked():
            raise NotLocked("%s is not locked" % self.path)
        elif not os.path.exists(self.unique_name):
            raise NotMyLock("%s is locked, but not by me" % self.path)
        os.unlink(self.unique_name)
        os.rmdir(self.lock_file)

    def is_locked(self):
        return os.path.exists(self.lock_file)

    def i_am_locking(self):
        return (self.is_locked() and
                os.path.exists(self.unique_name))

    def break_lock(self):
        if os.path.exists(self.lock_file):
            for name in os.listdir(self.lock_file):
                os.unlink(os.path.join(self.lock_file, name))
            os.rmdir(self.lock_file)
_vendor/lockfile/symlinklockfile.pyo000064400000005411152527136320013727 0ustar00
abc@@sjddlmZddlZddlZddlmZmZmZmZm	Z	defdYZ
dS(i(tabsolute_importNi(tLockBaset	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedtSymlinkLockFilecB@sMeZdZeddZddZdZdZdZ	dZ
RS(s'Lock access to a file using symlink(2).cC@s6tj||||tjj|jd|_dS(Ni(Rt__init__tostpathtsplittunique_name(tselfR	tthreadedttimeout((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR
scC@s|dk	r|n|j}tj}|dk	rL|dkrL||7}nxtrytj|j|jWntk
r|j	rdS|dk	rtj|kr|dkrt
d|jqtd|jntj
|dk	r|dndqOXdSqOWdS(Nis&Timeout waiting to acquire lock for %ss%s is already lockedi
g?(tNoneRttimetTrueRtsymlinkRt	lock_filetOSErrorti_am_lockingRR	Rtsleep(RRtend_time((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pytacquires$
	
'cC@sX|js"td|jn"|jsDtd|jntj|jdS(Ns%s is not lockeds%s is locked, but not by me(t	is_lockedRR	RRRtunlinkR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pytrelease6s
cC@stjj|jS(N(RR	tislinkR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR=scC@s.tjj|jo-tj|j|jkS(N(RR	RRtreadlinkR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR@scC@s,tjj|jr(tj|jndS(N(RR	RRR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyt
break_lockDsN(t__name__t
__module__t__doc__RRRRRRRR(((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR
s#			(t
__future__RRRtRRRRRR(((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyts(_vendor/lockfile/linklockfile.py000064400000005134152527136320013021 0ustar00from __future__ import absolute_import

import time
import os

from . import (LockBase, LockFailed, NotLocked, NotMyLock, LockTimeout,
               AlreadyLocked)


class LinkLockFile(LockBase):
    """Lock access to a file using atomic property of link(2).

    >>> lock = LinkLockFile('somefile')
    >>> lock = LinkLockFile('somefile', threaded=False)
    """

    def acquire(self, timeout=None):
        try:
            open(self.unique_name, "wb").close()
        except IOError:
            raise LockFailed("failed to create %s" % self.unique_name)

        timeout = timeout if timeout is not None else self.timeout
        end_time = time.time()
        if timeout is not None and timeout > 0:
            end_time += timeout

        while True:
            # Try and create a hard link to it.
            try:
                os.link(self.unique_name, self.lock_file)
            except OSError:
                # Link creation failed.  Maybe we've double-locked?
                nlinks = os.stat(self.unique_name).st_nlink
                if nlinks == 2:
                    # The original link plus the one I created == 2.  We're
                    # good to go.
                    return
                else:
                    # Otherwise the lock creation failed.
                    if timeout is not None and time.time() > end_time:
                        os.unlink(self.unique_name)
                        if timeout > 0:
                            raise LockTimeout("Timeout waiting to acquire"
                                              " lock for %s" %
                                              self.path)
                        else:
                            raise AlreadyLocked("%s is already locked" %
                                                self.path)
                    time.sleep(timeout is not None and timeout / 10 or 0.1)
            else:
                # Link creation succeeded.  We're good to go.
                return

    def release(self):
        if not self.is_locked():
            raise NotLocked("%s is not locked" % self.path)
        elif not os.path.exists(self.unique_name):
            raise NotMyLock("%s is locked, but not by me" % self.path)
        os.unlink(self.unique_name)
        os.unlink(self.lock_file)

    def is_locked(self):
        return os.path.exists(self.lock_file)

    def i_am_locking(self):
        return (self.is_locked() and
                os.path.exists(self.unique_name) and
                os.stat(self.unique_name).st_nlink == 2)

    def break_lock(self):
        if os.path.exists(self.lock_file):
            os.unlink(self.lock_file)
_vendor/lockfile/__init__.pyc000064400000027520152527136320012260 0ustar00
abc
@@sdZddlmZddlZddlZddlZddlZddlZeedspej	e_
neejdsejjej_
ndddd	d
ddd
dddddg
ZdefdYZdefdYZdefdYZd	efdYZd
efdYZdefdYZdefdYZd
efdYZdefdYZdefdYZdZdZd Zd!Zdd"Z eed#rd$d%l!m"Z#e#j$Z%nd$d&l!m&Z'e'j(Z%e%Z)dS('s
lockfile.py - Platform-independent advisory file locks.

Requires Python 2.5 unless you apply 2.4.diff
Locking is done on a per-thread basis instead of a per-process basis.

Usage:

>>> lock = LockFile('somefile')
>>> try:
...     lock.acquire()
... except AlreadyLocked:
...     print 'somefile', 'is locked already.'
... except LockFailed:
...     print 'somefile', 'can\'t be locked.'
... else:
...     print 'got lock'
got lock
>>> print lock.is_locked()
True
>>> lock.release()

>>> lock = LockFile('somefile')
>>> print lock.is_locked()
False
>>> with lock:
...    print lock.is_locked()
True
>>> print lock.is_locked()
False

>>> lock = LockFile('somefile')
>>> # It is okay to lock twice from the same thread...
>>> with lock:
...     lock.acquire()
...
>>> # Though no counter is kept, so you can't unlock multiple times...
>>> print lock.is_locked()
False

Exceptions:

    Error - base class for other exceptions
        LockError - base class for all locking exceptions
            AlreadyLocked - Another thread or process already holds the lock
            LockFailed - Lock failed for some other reason
        UnlockError - base class for all unlocking exceptions
            AlreadyUnlocked - File was not locked.
            NotMyLock - File was locked but not by the current thread/process
i(tabsolute_importNtcurrent_threadtget_nametErrort	LockErrortLockTimeoutt
AlreadyLockedt
LockFailedtUnlockErrort	NotLockedt	NotMyLocktLinkFileLockt
MkdirFileLocktSQLiteFileLocktLockBasetlockedcB@seZdZRS(sw
    Base class for other exceptions.

    >>> try:
    ...   raise Error
    ... except Exception:
    ...   pass
    (t__name__t
__module__t__doc__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRJscB@seZdZRS(s
    Base class for error arising from attempts to acquire the lock.

    >>> try:
    ...   raise LockError
    ... except Error:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRVscB@seZdZRS(sRaised when lock creation fails within a user-defined period of time.

    >>> try:
    ...   raise LockTimeout
    ... except LockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRbscB@seZdZRS(sSome other thread/process is locking the file.

    >>> try:
    ...   raise AlreadyLocked
    ... except LockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRmscB@seZdZRS(sLock file creation failed for some other reason.

    >>> try:
    ...   raise LockFailed
    ... except LockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRxscB@seZdZRS(s
    Base class for errors arising from attempts to release the lock.

    >>> try:
    ...   raise UnlockError
    ... except Error:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRscB@seZdZRS(sRaised when an attempt is made to unlock an unlocked file.

    >>> try:
    ...   raise NotLocked
    ... except UnlockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyR	scB@seZdZRS(sRaised when an attempt is made to unlock a file someone else locked.

    >>> try:
    ...   raise NotMyLock
    ... except UnlockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyR
st_SharedBasecB@sAeZdZddZdZdZdZdZRS(cC@s
||_dS(N(tpath(tselfR((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt__init__scC@stddS(s
        Acquire the lock.

        * If timeout is omitted (or None), wait forever trying to lock the
          file.

        * If timeout > 0, try to acquire the lock for that many seconds.  If
          the lock period expires and the file is still locked, raise
          LockTimeout.

        * If timeout <= 0, raise AlreadyLocked immediately if the file is
          already locked.
        simplement in subclassN(tNotImplemented(Rttimeout((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pytacquirescC@stddS(sX
        Release the lock.

        If the file is not locked, raise NotLocked.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pytreleasescC@s|j|S(s*
        Context manager support.
        (R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt	__enter__s
cG@s|jdS(s*
        Context manager support.
        N(R(Rt_exc((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt__exit__scC@sd|jj|jfS(Ns<%s: %r>(t	__class__RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt__repr__sN(	RRRtNoneRRRRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRs				cB@sAeZdZeddZdZdZdZdZ	RS(s.Base class for platform-specific lock classes.cC@stt|j|tjj|d|_tj|_	tj
|_|rtj
}t|dt|}d|d@|_n	d|_tjj|j}tjj|d|j	|j|jt|jf|_||_dS(si
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        s.locktidents-%xIts	%s%s.%s%sN(tsuperRRtosRtabspatht	lock_filetsockettgethostnamethostnametgetpidtpidt	threadingRtgetattrthashttnametdirnametjointunique_nameR(RRtthreadedRttR!R0((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRs 			cC@stddS(s9
        Tell whether or not the file is locked.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt	is_lockedscC@stddS(sA
        Return True if this object is locking the file.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyti_am_lockingscC@stddS(sN
        Remove a lock.  Useful if a locking thread failed to unlock.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt
break_lockscC@sd|jj|j|jfS(Ns<%s: %r -- %r>(RRR2R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRsN(
RRRtTrueR RR5R6R7R(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRs!			cO@smtjd|tddt|dts:|d}nt|dkr`|r`t|d4sF	-:					_vendor/lockfile/sqlitelockfile.py000064400000012602152527136320013363 0ustar00from __future__ import absolute_import, division

import time
import os

try:
    unicode
except NameError:
    unicode = str

from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked


class SQLiteLockFile(LockBase):
    "Demonstrate SQL-based locking."

    testdb = None

    def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = SQLiteLockFile('somefile')
        >>> lock = SQLiteLockFile('somefile', threaded=False)
        """
        LockBase.__init__(self, path, threaded, timeout)
        self.lock_file = unicode(self.lock_file)
        self.unique_name = unicode(self.unique_name)

        if SQLiteLockFile.testdb is None:
            import tempfile
            _fd, testdb = tempfile.mkstemp()
            os.close(_fd)
            os.unlink(testdb)
            del _fd, tempfile
            SQLiteLockFile.testdb = testdb

        import sqlite3
        self.connection = sqlite3.connect(SQLiteLockFile.testdb)

        c = self.connection.cursor()
        try:
            c.execute("create table locks"
                      "("
                      "   lock_file varchar(32),"
                      "   unique_name varchar(32)"
                      ")")
        except sqlite3.OperationalError:
            pass
        else:
            self.connection.commit()
            import atexit
            atexit.register(os.unlink, SQLiteLockFile.testdb)

    def acquire(self, timeout=None):
        timeout = timeout if timeout is not None else self.timeout
        end_time = time.time()
        if timeout is not None and timeout > 0:
            end_time += timeout

        if timeout is None:
            wait = 0.1
        elif timeout <= 0:
            wait = 0
        else:
            wait = timeout / 10

        cursor = self.connection.cursor()

        while True:
            if not self.is_locked():
                # Not locked.  Try to lock it.
                cursor.execute("insert into locks"
                               "  (lock_file, unique_name)"
                               "  values"
                               "  (?, ?)",
                               (self.lock_file, self.unique_name))
                self.connection.commit()

                # Check to see if we are the only lock holder.
                cursor.execute("select * from locks"
                               "  where unique_name = ?",
                               (self.unique_name,))
                rows = cursor.fetchall()
                if len(rows) > 1:
                    # Nope.  Someone else got there.  Remove our lock.
                    cursor.execute("delete from locks"
                                   "  where unique_name = ?",
                                   (self.unique_name,))
                    self.connection.commit()
                else:
                    # Yup.  We're done, so go home.
                    return
            else:
                # Check to see if we are the only lock holder.
                cursor.execute("select * from locks"
                               "  where unique_name = ?",
                               (self.unique_name,))
                rows = cursor.fetchall()
                if len(rows) == 1:
                    # We're the locker, so go home.
                    return

            # Maybe we should wait a bit longer.
            if timeout is not None and time.time() > end_time:
                if timeout > 0:
                    # No more waiting.
                    raise LockTimeout("Timeout waiting to acquire"
                                      " lock for %s" %
                                      self.path)
                else:
                    # Someone else has the lock and we are impatient..
                    raise AlreadyLocked("%s is already locked" % self.path)

            # Well, okay.  We'll give it a bit longer.
            time.sleep(wait)

    def release(self):
        if not self.is_locked():
            raise NotLocked("%s is not locked" % self.path)
        if not self.i_am_locking():
            raise NotMyLock("%s is locked, but not by me (by %s)" %
                            (self.unique_name, self._who_is_locking()))
        cursor = self.connection.cursor()
        cursor.execute("delete from locks"
                       "  where unique_name = ?",
                       (self.unique_name,))
        self.connection.commit()

    def _who_is_locking(self):
        cursor = self.connection.cursor()
        cursor.execute("select unique_name from locks"
                       "  where lock_file = ?",
                       (self.lock_file,))
        return cursor.fetchone()[0]

    def is_locked(self):
        cursor = self.connection.cursor()
        cursor.execute("select * from locks"
                       "  where lock_file = ?",
                       (self.lock_file,))
        rows = cursor.fetchall()
        return not not rows

    def i_am_locking(self):
        cursor = self.connection.cursor()
        cursor.execute("select * from locks"
                       "  where lock_file = ?"
                       "    and unique_name = ?",
                       (self.lock_file, self.unique_name))
        return not not cursor.fetchall()

    def break_lock(self):
        cursor = self.connection.cursor()
        cursor.execute("delete from locks"
                       "  where lock_file = ?",
                       (self.lock_file,))
        self.connection.commit()
_vendor/lockfile/pidlockfile.pyo000064400000013425152527136320013021 0ustar00
abc@@sdZddlmZddlZddlZddlZddlmZmZm	Z	m
Z
mZmZdefdYZ
dZd	Zd
ZdS(s8 Lockfile behaviour implemented via Unix PID files.
    i(tabsolute_importNi(tLockBaset
AlreadyLockedt
LockFailedt	NotLockedt	NotMyLocktLockTimeouttPIDLockFilecB@sVeZdZeddZdZdZdZddZ	dZ
dZRS(	sA Lockfile implemented as a Unix PID file.

    The lock file is a normal file named by the attribute `path`.
    A lock's PID file contains a single line of text, containing
    the process ID (PID) of the process that acquired the lock.

    >>> lock = PIDLockFile('somefile')
    >>> lock = PIDLockFile('somefile')
    cC@s&tj||t||j|_dS(N(Rt__init__tFalsetpathtunique_name(tselfR
tthreadedttimeout((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyR$scC@s
t|jS(s- Get the PID from the lock file.
            (tread_pid_from_pidfileR
(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pytread_pid*scC@stjj|jS(sv Test if the lock is currently held.

            The lock is held if the PID file for this lock exists.

            (tosR
texists(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyt	is_locked/scC@s"|jo!tj|jkS(s Test if the lock is held by the current process.

        Returns ``True`` if the current process ID matches the
        number stored in the PID file.
        (RRtgetpidR(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyti_am_locking7scC@s)|dk	r|n|j}tj}|dk	rL|dkrL||7}nxtr$yt|jWntk
r}|jtjkrtj|kr|dk	r|dkrt	d|jqt
d|jntj|dk	r|dpdq!td|jqOXdSqOWdS(s Acquire the lock.

        Creates the PID file for this lock, or raises an error if
        the lock could not be acquired.
        is&Timeout waiting to acquire lock for %ss%s is already lockedi
g?sfailed to create %sN(
tNoneRttimetTruetwrite_pid_to_pidfileR
tOSErrorterrnotEEXISTRRtsleepR(RRtend_timetexc((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pytacquire?s$
	&cC@sU|js"td|jn|jsDtd|jnt|jdS(s Release the lock.

            Removes the PID file to release the lock, or raises an
            error if the current process does not hold the lock.

            s%s is not lockeds%s is locked, but not by meN(RRR
RRtremove_existing_pidfile(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pytrelease_s
cC@st|jdS(s Break an existing lock.

            Removes the PID file if it already exists, otherwise does
            nothing.

            N(R!R
(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyt
break_locklsN(t__name__t
__module__t__doc__R	RRRRRR R"R#(((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyRs				 	
cC@sqd}yt|d}Wntk
r,nAX|jj}yt|}Wntk
rbnX|j|S(s Read the PID recorded in the named PID file.

        Read and return the numeric PID recorded as text in the named
        PID file. If the PID file cannot be read, or if the content is
        not a valid PID, return ``None``.

        trN(RtopentIOErrortreadlinetstriptintt
ValueErrortclose(tpidfile_pathtpidtpidfiletline((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyRvs


cC@sotjtjBtjB}d}tj|||}tj|d}tj}|jd||jdS(s Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        itws%s
N(	RtO_CREATtO_EXCLtO_WRONLYR(tfdopenRtwriteR.(R/t
open_flagst	open_modet
pidfile_fdR1R0((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyRs	cC@sCytj|Wn+tk
r>}|jtjkr8q?nXdS(s Remove the named PID file if it exists.

        Removing a PID file that doesn't already exist puts us in the
        desired state, so we ignore the condition if the file does not
        exist.

        N(RtremoveRRtENOENT(R/R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyR!s(R&t
__future__RRRRtRRRRRRRRRR!(((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyt
s.]	"	_vendor/lockfile/mkdirlockfile.pyo000064400000006542152527136320013355 0ustar00
abc@`sddlmZmZddlZddlZddlZddlZddlmZm	Z	m
Z
mZmZm
Z
defdYZdS(i(tabsolute_importtdivisionNi(tLockBaset
LockFailedt	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedt
MkdirLockFilecB`sMeZdZeddZddZdZdZdZ	dZ
RS(s"Lock file by creating a directory.cC`sKtj||||tjj|jd|j|j|jf|_	dS(ss
        >>> lock = MkdirLockFile('somefile')
        >>> lock = MkdirLockFile('somefile', threaded=False)
        s%s.%s%sN(
Rt__init__tostpathtjoint	lock_filethostnamettnametpidtunique_name(tselfRtthreadedttimeout((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyR	s
	cC`s{|dk	r|n|j}tj}|dk	rL|dkrL||7}n|dkrad}ntd|d}xtrvytj|jWntk
rXt	j
d}|jtjkrBtj
j|jrdS|dk	r2tj|kr2|dkrtd|j
q2td|j
ntj|qstd|jqwXt|jdjdSqwWdS(	Nig?i
is&Timeout waiting to acquire lock for %ss%s is already lockedsfailed to create %stwb(tNoneRttimetmaxtTrueR
tmkdirR
tOSErrortsystexc_infoterrnotEEXISTRtexistsRRRtsleepRtopentclose(RRtend_timetwaitterr((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pytacquires2
		
cC`sq|js"td|jn+tjj|jsMtd|jntj|jtj|j	dS(Ns%s is not lockeds%s is locked, but not by me(
t	is_lockedRRR
R RRtunlinktrmdirR
(R((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pytreleaseAscC`stjj|jS(N(R
RR R
(R((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyR(IscC`s|jotjj|jS(N(R(R
RR R(R((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyti_am_lockingLscC`shtjj|jrdx9tj|jD]%}tjtjj|j|q(Wtj|jndS(N(R
RR R
tlistdirR)RR*(Rtname((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyt
break_lockPs#N(t__name__t
__module__t__doc__RRR	R'R+R(R,R/(((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyRs
&			(t
__future__RRRR
RRtRRRRRRR(((sF/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/mkdirlockfile.pyts._vendor/lockfile/__init__.pyo000064400000027520152527136320012274 0ustar00
abc
@@sdZddlmZddlZddlZddlZddlZddlZeedspej	e_
neejdsejjej_
ndddd	d
ddd
dddddg
ZdefdYZdefdYZdefdYZd	efdYZd
efdYZdefdYZdefdYZd
efdYZdefdYZdefdYZdZdZd Zd!Zdd"Z eed#rd$d%l!m"Z#e#j$Z%nd$d&l!m&Z'e'j(Z%e%Z)dS('s
lockfile.py - Platform-independent advisory file locks.

Requires Python 2.5 unless you apply 2.4.diff
Locking is done on a per-thread basis instead of a per-process basis.

Usage:

>>> lock = LockFile('somefile')
>>> try:
...     lock.acquire()
... except AlreadyLocked:
...     print 'somefile', 'is locked already.'
... except LockFailed:
...     print 'somefile', 'can\'t be locked.'
... else:
...     print 'got lock'
got lock
>>> print lock.is_locked()
True
>>> lock.release()

>>> lock = LockFile('somefile')
>>> print lock.is_locked()
False
>>> with lock:
...    print lock.is_locked()
True
>>> print lock.is_locked()
False

>>> lock = LockFile('somefile')
>>> # It is okay to lock twice from the same thread...
>>> with lock:
...     lock.acquire()
...
>>> # Though no counter is kept, so you can't unlock multiple times...
>>> print lock.is_locked()
False

Exceptions:

    Error - base class for other exceptions
        LockError - base class for all locking exceptions
            AlreadyLocked - Another thread or process already holds the lock
            LockFailed - Lock failed for some other reason
        UnlockError - base class for all unlocking exceptions
            AlreadyUnlocked - File was not locked.
            NotMyLock - File was locked but not by the current thread/process
i(tabsolute_importNtcurrent_threadtget_nametErrort	LockErrortLockTimeoutt
AlreadyLockedt
LockFailedtUnlockErrort	NotLockedt	NotMyLocktLinkFileLockt
MkdirFileLocktSQLiteFileLocktLockBasetlockedcB@seZdZRS(sw
    Base class for other exceptions.

    >>> try:
    ...   raise Error
    ... except Exception:
    ...   pass
    (t__name__t
__module__t__doc__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRJscB@seZdZRS(s
    Base class for error arising from attempts to acquire the lock.

    >>> try:
    ...   raise LockError
    ... except Error:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRVscB@seZdZRS(sRaised when lock creation fails within a user-defined period of time.

    >>> try:
    ...   raise LockTimeout
    ... except LockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRbscB@seZdZRS(sSome other thread/process is locking the file.

    >>> try:
    ...   raise AlreadyLocked
    ... except LockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRmscB@seZdZRS(sLock file creation failed for some other reason.

    >>> try:
    ...   raise LockFailed
    ... except LockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRxscB@seZdZRS(s
    Base class for errors arising from attempts to release the lock.

    >>> try:
    ...   raise UnlockError
    ... except Error:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRscB@seZdZRS(sRaised when an attempt is made to unlock an unlocked file.

    >>> try:
    ...   raise NotLocked
    ... except UnlockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyR	scB@seZdZRS(sRaised when an attempt is made to unlock a file someone else locked.

    >>> try:
    ...   raise NotMyLock
    ... except UnlockError:
    ...   pass
    (RRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyR
st_SharedBasecB@sAeZdZddZdZdZdZdZRS(cC@s
||_dS(N(tpath(tselfR((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt__init__scC@stddS(s
        Acquire the lock.

        * If timeout is omitted (or None), wait forever trying to lock the
          file.

        * If timeout > 0, try to acquire the lock for that many seconds.  If
          the lock period expires and the file is still locked, raise
          LockTimeout.

        * If timeout <= 0, raise AlreadyLocked immediately if the file is
          already locked.
        simplement in subclassN(tNotImplemented(Rttimeout((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pytacquirescC@stddS(sX
        Release the lock.

        If the file is not locked, raise NotLocked.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pytreleasescC@s|j|S(s*
        Context manager support.
        (R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt	__enter__s
cG@s|jdS(s*
        Context manager support.
        N(R(Rt_exc((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt__exit__scC@sd|jj|jfS(Ns<%s: %r>(t	__class__RR(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt__repr__sN(	RRRtNoneRRRRR(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRs				cB@sAeZdZeddZdZdZdZdZ	RS(s.Base class for platform-specific lock classes.cC@stt|j|tjj|d|_tj|_	tj
|_|rtj
}t|dt|}d|d@|_n	d|_tjj|j}tjj|d|j	|j|jt|jf|_||_dS(si
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        s.locktidents-%xIts	%s%s.%s%sN(tsuperRRtosRtabspatht	lock_filetsockettgethostnamethostnametgetpidtpidt	threadingRtgetattrthashttnametdirnametjointunique_nameR(RRtthreadedRttR!R0((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRs 			cC@stddS(s9
        Tell whether or not the file is locked.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt	is_lockedscC@stddS(sA
        Return True if this object is locking the file.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyti_am_lockingscC@stddS(sN
        Remove a lock.  Useful if a locking thread failed to unlock.
        simplement in subclassN(R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyt
break_lockscC@sd|jj|j|jfS(Ns<%s: %r -- %r>(RRR2R(R((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRsN(
RRRtTrueR RR5R6R7R(((sA/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/__init__.pyRs!			cO@smtjd|tddt|dts:|d}nt|dkr`|r`t|d4sF	-:					_vendor/lockfile/linklockfile.pyc000064400000005535152527136320013171 0ustar00
abc@@spddlmZddlZddlZddlmZmZmZmZm	Z	m
Z
defdYZdS(i(tabsolute_importNi(tLockBaset
LockFailedt	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedtLinkLockFilecB@s>eZdZddZdZdZdZdZRS(sLock access to a file using atomic property of link(2).

    >>> lock = LinkLockFile('somefile')
    >>> lock = LinkLockFile('somefile', threaded=False)
    cC@s~yt|jdjWn$tk
r@td|jnX|dk	rS|n|j}tj}|dk	r|dkr||7}nxtryyt	j
|j|jWntk
rqt	j
|jj}|dkrdS|dk	rKtj|krKt	j|j|dkr5td|jqKtd|jntj|dk	rg|dpjdqXdSqWdS(	Ntwbsfailed to create %siis&Timeout waiting to acquire lock for %ss%s is already lockedi
g?(topentunique_nametclosetIOErrorRtNonettimeoutttimetTruetostlinkt	lock_filetOSErrortstattst_nlinktunlinkRtpathRtsleep(tselfRtend_timetnlinks((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pytacquires0

	
'cC@sq|js"td|jn+tjj|jsMtd|jntj|jtj|jdS(Ns%s is not lockeds%s is locked, but not by me(	t	is_lockedRRRtexistsR
RRR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pytrelease7scC@stjj|jS(N(RRRR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyR?scC@s:|jo9tjj|jo9tj|jjdkS(Ni(RRRRR
RR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyti_am_lockingBscC@s,tjj|jr(tj|jndS(N(RRRRR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyt
break_lockGsN(	t__name__t
__module__t__doc__R
RR RR!R"(((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyR
s&			(t
__future__RRRtRRRRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyts._vendor/lockfile/pidlockfile.pyc000064400000013425152527136320013005 0ustar00
abc@@sdZddlmZddlZddlZddlZddlmZmZm	Z	m
Z
mZmZdefdYZ
dZd	Zd
ZdS(s8 Lockfile behaviour implemented via Unix PID files.
    i(tabsolute_importNi(tLockBaset
AlreadyLockedt
LockFailedt	NotLockedt	NotMyLocktLockTimeouttPIDLockFilecB@sVeZdZeddZdZdZdZddZ	dZ
dZRS(	sA Lockfile implemented as a Unix PID file.

    The lock file is a normal file named by the attribute `path`.
    A lock's PID file contains a single line of text, containing
    the process ID (PID) of the process that acquired the lock.

    >>> lock = PIDLockFile('somefile')
    >>> lock = PIDLockFile('somefile')
    cC@s&tj||t||j|_dS(N(Rt__init__tFalsetpathtunique_name(tselfR
tthreadedttimeout((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyR$scC@s
t|jS(s- Get the PID from the lock file.
            (tread_pid_from_pidfileR
(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pytread_pid*scC@stjj|jS(sv Test if the lock is currently held.

            The lock is held if the PID file for this lock exists.

            (tosR
texists(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyt	is_locked/scC@s"|jo!tj|jkS(s Test if the lock is held by the current process.

        Returns ``True`` if the current process ID matches the
        number stored in the PID file.
        (RRtgetpidR(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyti_am_locking7scC@s)|dk	r|n|j}tj}|dk	rL|dkrL||7}nxtr$yt|jWntk
r}|jtjkrtj|kr|dk	r|dkrt	d|jqt
d|jntj|dk	r|dpdq!td|jqOXdSqOWdS(s Acquire the lock.

        Creates the PID file for this lock, or raises an error if
        the lock could not be acquired.
        is&Timeout waiting to acquire lock for %ss%s is already lockedi
g?sfailed to create %sN(
tNoneRttimetTruetwrite_pid_to_pidfileR
tOSErrorterrnotEEXISTRRtsleepR(RRtend_timetexc((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pytacquire?s$
	&cC@sU|js"td|jn|jsDtd|jnt|jdS(s Release the lock.

            Removes the PID file to release the lock, or raises an
            error if the current process does not hold the lock.

            s%s is not lockeds%s is locked, but not by meN(RRR
RRtremove_existing_pidfile(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pytrelease_s
cC@st|jdS(s Break an existing lock.

            Removes the PID file if it already exists, otherwise does
            nothing.

            N(R!R
(R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyt
break_locklsN(t__name__t
__module__t__doc__R	RRRRRR R"R#(((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyRs				 	
cC@sqd}yt|d}Wntk
r,nAX|jj}yt|}Wntk
rbnX|j|S(s Read the PID recorded in the named PID file.

        Read and return the numeric PID recorded as text in the named
        PID file. If the PID file cannot be read, or if the content is
        not a valid PID, return ``None``.

        trN(RtopentIOErrortreadlinetstriptintt
ValueErrortclose(tpidfile_pathtpidtpidfiletline((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyRvs


cC@sotjtjBtjB}d}tj|||}tj|d}tj}|jd||jdS(s Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        itws%s
N(	RtO_CREATtO_EXCLtO_WRONLYR(tfdopenRtwriteR.(R/t
open_flagst	open_modet
pidfile_fdR1R0((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyRs	cC@sCytj|Wn+tk
r>}|jtjkr8q?nXdS(s Remove the named PID file if it exists.

        Removing a PID file that doesn't already exist puts us in the
        desired state, so we ignore the condition if the file does not
        exist.

        N(RtremoveRRtENOENT(R/R((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyR!s(R&t
__future__RRRRtRRRRRRRRRR!(((sD/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.pyt
s.]	"	_vendor/lockfile/sqlitelockfile.pyo000064400000011137152527136320013544 0ustar00
abc@`sddlmZmZddlZddlZyeWnek
rOeZnXddlm	Z	m
Z
mZmZm
Z
de	fdYZdS(i(tabsolute_importtdivisionNi(tLockBaset	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedtSQLiteLockFilecB`s\eZdZdZeddZddZdZdZ	dZ
dZdZRS(	sDemonstrate SQL-based locking.c
C`stj||||t|j|_t|j|_tjdkrddl}|j	\}}t
j|t
j|~~|t_nddl
}|jtj|_|jj}y|jdWn|jk
rn0X|jjddl}	|	jt
jtjdS(su
        >>> lock = SQLiteLockFile('somefile')
        >>> lock = SQLiteLockFile('somefile', threaded=False)
        iNsGcreate table locks(   lock_file varchar(32),   unique_name varchar(32))(Rt__init__tunicodet	lock_filetunique_nameRttestdbtNonettempfiletmkstemptostclosetunlinktsqlite3tconnectt
connectiontcursortexecutetOperationalErrortcommittatexittregister(
tselftpathtthreadedttimeoutRt_fdRRtcR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyRs(


cC`s|dk	r|n|j}tj}|dk	rL|dkrL||7}n|dkrad}n|dkrvd}n
|d}|jj}x;tr|js.|jd|j|j	f|jj
|jd|j	f|j}t|dkr'|jd|j	f|jj
qfdSn8|jd|j	f|j}t|dkrfdS|dk	rtj|kr|dkrt
d|jqtd	|jntj|qWdS(
Nig?i
s;insert into locks  (lock_file, unique_name)  values  (?, ?)s*select * from locks  where unique_name = ?is(delete from locks  where unique_name = ?s&Timeout waiting to acquire lock for %ss%s is already locked(R
RttimeRRtTruet	is_lockedRR
RRtfetchalltlenRRRtsleep(RRtend_timetwaitRtrows((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pytacquire5sD
		
		
	
	
	
cC`s|js"td|jn|jsPtd|j|jfn|jj}|j	d|jf|jj
dS(Ns%s is not lockeds#%s is locked, but not by me (by %s)s(delete from locks  where unique_name = ?(R$RRti_am_lockingRRt_who_is_lockingRRRR(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pytreleasets	
cC`s3|jj}|jd|jf|jdS(Ns2select unique_name from locks  where lock_file = ?i(RRRR
tfetchone(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyR-s	
cC`s7|jj}|jd|jf|j}|S(Ns(select * from locks  where lock_file = ?(RRRR
R%(RRR*((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyR$s
	
cC`s7|jj}|jd|j|jf|jS(Ns?select * from locks  where lock_file = ?    and unique_name = ?(RRRR
RR%(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyR,s	cC`s6|jj}|jd|jf|jjdS(Ns&delete from locks  where lock_file = ?(RRRR
R(RR((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyt
break_locks	
N(
t__name__t
__module__t__doc__R
RR#RR+R.R-R$R,R0(((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyRs"?				(t
__future__RRR"RR	t	NameErrortstrtRRRRRR(((sG/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.pyts

(_vendor/lockfile/symlinklockfile.py000064400000005070152527136320013551 0ustar00from __future__ import absolute_import

import os
import time

from . import (LockBase, NotLocked, NotMyLock, LockTimeout,
               AlreadyLocked)


class SymlinkLockFile(LockBase):
    """Lock access to a file using symlink(2)."""

    def __init__(self, path, threaded=True, timeout=None):
        # super(SymlinkLockFile).__init(...)
        LockBase.__init__(self, path, threaded, timeout)
        # split it back!
        self.unique_name = os.path.split(self.unique_name)[1]

    def acquire(self, timeout=None):
        # Hopefully unnecessary for symlink.
        # try:
        #     open(self.unique_name, "wb").close()
        # except IOError:
        #     raise LockFailed("failed to create %s" % self.unique_name)
        timeout = timeout if timeout is not None else self.timeout
        end_time = time.time()
        if timeout is not None and timeout > 0:
            end_time += timeout

        while True:
            # Try and create a symbolic link to it.
            try:
                os.symlink(self.unique_name, self.lock_file)
            except OSError:
                # Link creation failed.  Maybe we've double-locked?
                if self.i_am_locking():
                    # Linked to out unique name. Proceed.
                    return
                else:
                    # Otherwise the lock creation failed.
                    if timeout is not None and time.time() > end_time:
                        if timeout > 0:
                            raise LockTimeout("Timeout waiting to acquire"
                                              " lock for %s" %
                                              self.path)
                        else:
                            raise AlreadyLocked("%s is already locked" %
                                                self.path)
                    time.sleep(timeout / 10 if timeout is not None else 0.1)
            else:
                # Link creation succeeded.  We're good to go.
                return

    def release(self):
        if not self.is_locked():
            raise NotLocked("%s is not locked" % self.path)
        elif not self.i_am_locking():
            raise NotMyLock("%s is locked, but not by me" % self.path)
        os.unlink(self.lock_file)

    def is_locked(self):
        return os.path.islink(self.lock_file)

    def i_am_locking(self):
        return (os.path.islink(self.lock_file)
                and os.readlink(self.lock_file) == self.unique_name)

    def break_lock(self):
        if os.path.islink(self.lock_file):  # exists && link
            os.unlink(self.lock_file)
_vendor/lockfile/__init__.py000064400000022233152527136320012111 0ustar00# -*- coding: utf-8 -*-

"""
lockfile.py - Platform-independent advisory file locks.

Requires Python 2.5 unless you apply 2.4.diff
Locking is done on a per-thread basis instead of a per-process basis.

Usage:

>>> lock = LockFile('somefile')
>>> try:
...     lock.acquire()
... except AlreadyLocked:
...     print 'somefile', 'is locked already.'
... except LockFailed:
...     print 'somefile', 'can\\'t be locked.'
... else:
...     print 'got lock'
got lock
>>> print lock.is_locked()
True
>>> lock.release()

>>> lock = LockFile('somefile')
>>> print lock.is_locked()
False
>>> with lock:
...    print lock.is_locked()
True
>>> print lock.is_locked()
False

>>> lock = LockFile('somefile')
>>> # It is okay to lock twice from the same thread...
>>> with lock:
...     lock.acquire()
...
>>> # Though no counter is kept, so you can't unlock multiple times...
>>> print lock.is_locked()
False

Exceptions:

    Error - base class for other exceptions
        LockError - base class for all locking exceptions
            AlreadyLocked - Another thread or process already holds the lock
            LockFailed - Lock failed for some other reason
        UnlockError - base class for all unlocking exceptions
            AlreadyUnlocked - File was not locked.
            NotMyLock - File was locked but not by the current thread/process
"""

from __future__ import absolute_import

import functools
import os
import socket
import threading
import warnings

# Work with PEP8 and non-PEP8 versions of threading module.
if not hasattr(threading, "current_thread"):
    threading.current_thread = threading.currentThread
if not hasattr(threading.Thread, "get_name"):
    threading.Thread.get_name = threading.Thread.getName

__all__ = ['Error', 'LockError', 'LockTimeout', 'AlreadyLocked',
           'LockFailed', 'UnlockError', 'NotLocked', 'NotMyLock',
           'LinkFileLock', 'MkdirFileLock', 'SQLiteFileLock',
           'LockBase', 'locked']


class Error(Exception):
    """
    Base class for other exceptions.

    >>> try:
    ...   raise Error
    ... except Exception:
    ...   pass
    """
    pass


class LockError(Error):
    """
    Base class for error arising from attempts to acquire the lock.

    >>> try:
    ...   raise LockError
    ... except Error:
    ...   pass
    """
    pass


class LockTimeout(LockError):
    """Raised when lock creation fails within a user-defined period of time.

    >>> try:
    ...   raise LockTimeout
    ... except LockError:
    ...   pass
    """
    pass


class AlreadyLocked(LockError):
    """Some other thread/process is locking the file.

    >>> try:
    ...   raise AlreadyLocked
    ... except LockError:
    ...   pass
    """
    pass


class LockFailed(LockError):
    """Lock file creation failed for some other reason.

    >>> try:
    ...   raise LockFailed
    ... except LockError:
    ...   pass
    """
    pass


class UnlockError(Error):
    """
    Base class for errors arising from attempts to release the lock.

    >>> try:
    ...   raise UnlockError
    ... except Error:
    ...   pass
    """
    pass


class NotLocked(UnlockError):
    """Raised when an attempt is made to unlock an unlocked file.

    >>> try:
    ...   raise NotLocked
    ... except UnlockError:
    ...   pass
    """
    pass


class NotMyLock(UnlockError):
    """Raised when an attempt is made to unlock a file someone else locked.

    >>> try:
    ...   raise NotMyLock
    ... except UnlockError:
    ...   pass
    """
    pass


class _SharedBase(object):
    def __init__(self, path):
        self.path = path

    def acquire(self, timeout=None):
        """
        Acquire the lock.

        * If timeout is omitted (or None), wait forever trying to lock the
          file.

        * If timeout > 0, try to acquire the lock for that many seconds.  If
          the lock period expires and the file is still locked, raise
          LockTimeout.

        * If timeout <= 0, raise AlreadyLocked immediately if the file is
          already locked.
        """
        raise NotImplemented("implement in subclass")

    def release(self):
        """
        Release the lock.

        If the file is not locked, raise NotLocked.
        """
        raise NotImplemented("implement in subclass")

    def __enter__(self):
        """
        Context manager support.
        """
        self.acquire()
        return self

    def __exit__(self, *_exc):
        """
        Context manager support.
        """
        self.release()

    def __repr__(self):
        return "<%s: %r>" % (self.__class__.__name__, self.path)


class LockBase(_SharedBase):
    """Base class for platform-specific lock classes."""
    def __init__(self, path, threaded=True, timeout=None):
        """
        >>> lock = LockBase('somefile')
        >>> lock = LockBase('somefile', threaded=False)
        """
        super(LockBase, self).__init__(path)
        self.lock_file = os.path.abspath(path) + ".lock"
        self.hostname = socket.gethostname()
        self.pid = os.getpid()
        if threaded:
            t = threading.current_thread()
            # Thread objects in Python 2.4 and earlier do not have ident
            # attrs.  Worm around that.
            ident = getattr(t, "ident", hash(t))
            self.tname = "-%x" % (ident & 0xffffffff)
        else:
            self.tname = ""
        dirname = os.path.dirname(self.lock_file)

        # unique name is mostly about the current process, but must
        # also contain the path -- otherwise, two adjacent locked
        # files conflict (one file gets locked, creating lock-file and
        # unique file, the other one gets locked, creating lock-file
        # and overwriting the already existing lock-file, then one
        # gets unlocked, deleting both lock-file and unique file,
        # finally the last lock errors out upon releasing.
        self.unique_name = os.path.join(dirname,
                                        "%s%s.%s%s" % (self.hostname,
                                                       self.tname,
                                                       self.pid,
                                                       hash(self.path)))
        self.timeout = timeout

    def is_locked(self):
        """
        Tell whether or not the file is locked.
        """
        raise NotImplemented("implement in subclass")

    def i_am_locking(self):
        """
        Return True if this object is locking the file.
        """
        raise NotImplemented("implement in subclass")

    def break_lock(self):
        """
        Remove a lock.  Useful if a locking thread failed to unlock.
        """
        raise NotImplemented("implement in subclass")

    def __repr__(self):
        return "<%s: %r -- %r>" % (self.__class__.__name__, self.unique_name,
                                   self.path)


def _fl_helper(cls, mod, *args, **kwds):
    warnings.warn("Import from %s module instead of lockfile package" % mod,
                  DeprecationWarning, stacklevel=2)
    # This is a bit funky, but it's only for awhile.  The way the unit tests
    # are constructed this function winds up as an unbound method, so it
    # actually takes three args, not two.  We want to toss out self.
    if not isinstance(args[0], str):
        # We are testing, avoid the first arg
        args = args[1:]
    if len(args) == 1 and not kwds:
        kwds["threaded"] = True
    return cls(*args, **kwds)


def LinkFileLock(*args, **kwds):
    """Factory function provided for backwards compatibility.

    Do not use in new code.  Instead, import LinkLockFile from the
    lockfile.linklockfile module.
    """
    from . import linklockfile
    return _fl_helper(linklockfile.LinkLockFile, "lockfile.linklockfile",
                      *args, **kwds)


def MkdirFileLock(*args, **kwds):
    """Factory function provided for backwards compatibility.

    Do not use in new code.  Instead, import MkdirLockFile from the
    lockfile.mkdirlockfile module.
    """
    from . import mkdirlockfile
    return _fl_helper(mkdirlockfile.MkdirLockFile, "lockfile.mkdirlockfile",
                      *args, **kwds)


def SQLiteFileLock(*args, **kwds):
    """Factory function provided for backwards compatibility.

    Do not use in new code.  Instead, import SQLiteLockFile from the
    lockfile.mkdirlockfile module.
    """
    from . import sqlitelockfile
    return _fl_helper(sqlitelockfile.SQLiteLockFile, "lockfile.sqlitelockfile",
                      *args, **kwds)


def locked(path, timeout=None):
    """Decorator which enables locks for decorated function.

    Arguments:
     - path: path for lockfile.
     - timeout (optional): Timeout for acquiring lock.

     Usage:
         @locked('/var/run/myname', timeout=0)
         def myname(...):
             ...
    """
    def decor(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            lock = FileLock(path, timeout=timeout)
            lock.acquire()
            try:
                return func(*args, **kwargs)
            finally:
                lock.release()
        return wrapper
    return decor


if hasattr(os, "link"):
    from . import linklockfile as _llf
    LockFile = _llf.LinkLockFile
else:
    from . import mkdirlockfile as _mlf
    LockFile = _mlf.MkdirLockFile

FileLock = LockFile
_vendor/lockfile/linklockfile.pyo000064400000005535152527136320013205 0ustar00
abc@@spddlmZddlZddlZddlmZmZmZmZm	Z	m
Z
defdYZdS(i(tabsolute_importNi(tLockBaset
LockFailedt	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedtLinkLockFilecB@s>eZdZddZdZdZdZdZRS(sLock access to a file using atomic property of link(2).

    >>> lock = LinkLockFile('somefile')
    >>> lock = LinkLockFile('somefile', threaded=False)
    cC@s~yt|jdjWn$tk
r@td|jnX|dk	rS|n|j}tj}|dk	r|dkr||7}nxtryyt	j
|j|jWntk
rqt	j
|jj}|dkrdS|dk	rKtj|krKt	j|j|dkr5td|jqKtd|jntj|dk	rg|dpjdqXdSqWdS(	Ntwbsfailed to create %siis&Timeout waiting to acquire lock for %ss%s is already lockedi
g?(topentunique_nametclosetIOErrorRtNonettimeoutttimetTruetostlinkt	lock_filetOSErrortstattst_nlinktunlinkRtpathRtsleep(tselfRtend_timetnlinks((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pytacquires0

	
'cC@sq|js"td|jn+tjj|jsMtd|jntj|jtj|jdS(Ns%s is not lockeds%s is locked, but not by me(	t	is_lockedRRRtexistsR
RRR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pytrelease7scC@stjj|jS(N(RRRR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyR?scC@s:|jo9tjj|jo9tj|jjdkS(Ni(RRRRR
RR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyti_am_lockingBscC@s,tjj|jr(tj|jndS(N(RRRRR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyt
break_lockGsN(	t__name__t
__module__t__doc__R
RR RR!R"(((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyR
s&			(t
__future__RRRtRRRRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/linklockfile.pyts._vendor/lockfile/pidlockfile.py000064400000013712152527136320012641 0ustar00# -*- coding: utf-8 -*-

# pidlockfile.py
#
# Copyright © 2008–2009 Ben Finney 
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.

""" Lockfile behaviour implemented via Unix PID files.
    """

from __future__ import absolute_import

import errno
import os
import time

from . import (LockBase, AlreadyLocked, LockFailed, NotLocked, NotMyLock,
               LockTimeout)


class PIDLockFile(LockBase):
    """ Lockfile implemented as a Unix PID file.

    The lock file is a normal file named by the attribute `path`.
    A lock's PID file contains a single line of text, containing
    the process ID (PID) of the process that acquired the lock.

    >>> lock = PIDLockFile('somefile')
    >>> lock = PIDLockFile('somefile')
    """

    def __init__(self, path, threaded=False, timeout=None):
        # pid lockfiles don't support threaded operation, so always force
        # False as the threaded arg.
        LockBase.__init__(self, path, False, timeout)
        self.unique_name = self.path

    def read_pid(self):
        """ Get the PID from the lock file.
            """
        return read_pid_from_pidfile(self.path)

    def is_locked(self):
        """ Test if the lock is currently held.

            The lock is held if the PID file for this lock exists.

            """
        return os.path.exists(self.path)

    def i_am_locking(self):
        """ Test if the lock is held by the current process.

        Returns ``True`` if the current process ID matches the
        number stored in the PID file.
        """
        return self.is_locked() and os.getpid() == self.read_pid()

    def acquire(self, timeout=None):
        """ Acquire the lock.

        Creates the PID file for this lock, or raises an error if
        the lock could not be acquired.
        """

        timeout = timeout if timeout is not None else self.timeout
        end_time = time.time()
        if timeout is not None and timeout > 0:
            end_time += timeout

        while True:
            try:
                write_pid_to_pidfile(self.path)
            except OSError as exc:
                if exc.errno == errno.EEXIST:
                    # The lock creation failed.  Maybe sleep a bit.
                    if time.time() > end_time:
                        if timeout is not None and timeout > 0:
                            raise LockTimeout("Timeout waiting to acquire"
                                              " lock for %s" %
                                              self.path)
                        else:
                            raise AlreadyLocked("%s is already locked" %
                                                self.path)
                    time.sleep(timeout is not None and timeout / 10 or 0.1)
                else:
                    raise LockFailed("failed to create %s" % self.path)
            else:
                return

    def release(self):
        """ Release the lock.

            Removes the PID file to release the lock, or raises an
            error if the current process does not hold the lock.

            """
        if not self.is_locked():
            raise NotLocked("%s is not locked" % self.path)
        if not self.i_am_locking():
            raise NotMyLock("%s is locked, but not by me" % self.path)
        remove_existing_pidfile(self.path)

    def break_lock(self):
        """ Break an existing lock.

            Removes the PID file if it already exists, otherwise does
            nothing.

            """
        remove_existing_pidfile(self.path)


def read_pid_from_pidfile(pidfile_path):
    """ Read the PID recorded in the named PID file.

        Read and return the numeric PID recorded as text in the named
        PID file. If the PID file cannot be read, or if the content is
        not a valid PID, return ``None``.

        """
    pid = None
    try:
        pidfile = open(pidfile_path, 'r')
    except IOError:
        pass
    else:
        # According to the FHS 2.3 section on PID files in /var/run:
        #
        #   The file must consist of the process identifier in
        #   ASCII-encoded decimal, followed by a newline character.
        #
        #   Programs that read PID files should be somewhat flexible
        #   in what they accept; i.e., they should ignore extra
        #   whitespace, leading zeroes, absence of the trailing
        #   newline, or additional lines in the PID file.

        line = pidfile.readline().strip()
        try:
            pid = int(line)
        except ValueError:
            pass
        pidfile.close()

    return pid


def write_pid_to_pidfile(pidfile_path):
    """ Write the PID in the named PID file.

        Get the numeric process ID (“PID”) of the current process
        and write it to the named file as a line of text.

        """
    open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    open_mode = 0o644
    pidfile_fd = os.open(pidfile_path, open_flags, open_mode)
    pidfile = os.fdopen(pidfile_fd, 'w')

    # According to the FHS 2.3 section on PID files in /var/run:
    #
    #   The file must consist of the process identifier in
    #   ASCII-encoded decimal, followed by a newline character. For
    #   example, if crond was process number 25, /var/run/crond.pid
    #   would contain three characters: two, five, and newline.

    pid = os.getpid()
    pidfile.write("%s\n" % pid)
    pidfile.close()


def remove_existing_pidfile(pidfile_path):
    """ Remove the named PID file if it exists.

        Removing a PID file that doesn't already exist puts us in the
        desired state, so we ignore the condition if the file does not
        exist.

        """
    try:
        os.remove(pidfile_path)
    except OSError as exc:
        if exc.errno == errno.ENOENT:
            pass
        else:
            raise
_vendor/lockfile/symlinklockfile.pyc000064400000005411152527136320013713 0ustar00
abc@@sjddlmZddlZddlZddlmZmZmZmZm	Z	defdYZ
dS(i(tabsolute_importNi(tLockBaset	NotLockedt	NotMyLocktLockTimeoutt
AlreadyLockedtSymlinkLockFilecB@sMeZdZeddZddZdZdZdZ	dZ
RS(s'Lock access to a file using symlink(2).cC@s6tj||||tjj|jd|_dS(Ni(Rt__init__tostpathtsplittunique_name(tselfR	tthreadedttimeout((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR
scC@s|dk	r|n|j}tj}|dk	rL|dkrL||7}nxtrytj|j|jWntk
r|j	rdS|dk	rtj|kr|dkrt
d|jqtd|jntj
|dk	r|dndqOXdSqOWdS(Nis&Timeout waiting to acquire lock for %ss%s is already lockedi
g?(tNoneRttimetTrueRtsymlinkRt	lock_filetOSErrorti_am_lockingRR	Rtsleep(RRtend_time((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pytacquires$
	
'cC@sX|js"td|jn"|jsDtd|jntj|jdS(Ns%s is not lockeds%s is locked, but not by me(t	is_lockedRR	RRRtunlinkR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pytrelease6s
cC@stjj|jS(N(RR	tislinkR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR=scC@s.tjj|jo-tj|j|jkS(N(RR	RRtreadlinkR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR@scC@s,tjj|jr(tj|jndS(N(RR	RRR(R((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyt
break_lockDsN(t__name__t
__module__t__doc__RRRRRRRR(((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyR
s#			(t
__future__RRRtRRRRRR(((sH/usr/lib/python2.7/site-packages/pip/_vendor/lockfile/symlinklockfile.pyts(_vendor/html5lib/_ihatexml.pyc000064400000036273152527136320012430 0ustar00
abc@`sZddlmZmZmZddlZddlZddlmZdZdZ	dZ
dZd	Zd
j
ee	gZd
j
eeddd
e
egZd
j
ed
gZejdZejdZdZdZeddZdZdZdZdZejdZejdZejdZdefdYZ dS(i(tabsolute_importtdivisiontunicode_literalsNi(tDataLossWarningu^
[#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] |
[#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] |
[#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] |
[#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 |
[#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] |
[#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] |
[#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] |
[#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] |
[#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 |
[#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] |
[#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] |
[#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D |
[#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] |
[#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] |
[#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] |
[#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] |
[#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] |
[#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] |
[#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 |
[#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] |
[#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] |
[#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] |
[#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] |
[#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] |
[#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] |
[#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] |
[#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] |
[#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] |
[#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] |
[#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A |
#x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 |
#x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] |
#x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] |
[#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] |
[#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C |
#x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 |
[#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] |
[#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] |
[#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 |
[#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] |
[#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B |
#x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE |
[#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] |
[#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 |
[#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] |
[#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3]u*[#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029]u
[#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] |
[#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 |
[#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] |
[#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] |
#x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] |
[#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] |
[#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 |
#x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] |
[#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC |
[#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] |
#x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] |
[#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] |
[#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] |
[#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] |
[#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] |
[#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] |
#x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 |
[#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] |
#x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] |
[#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] |
[#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] |
#x3099 | #x309Au
[#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] |
[#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] |
[#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] |
[#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29]u}
#x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 |
#[#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE]u | u.u-u_u#x([\d|A-F]{4,4})u'\[#x([\d|A-F]{4,4})-#x([\d|A-F]{4,4})\]cC`s#g|jdD]}|j^q}g}x|D]}t}xttfD]}|j|}|dk	rN|jg|jD]}t	|^qt
|ddkr|dd|dt_((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pytcoerceCharacterss
	cC`s|}xHtj|D]7}tjdt|j|}|j||}qW|jr|jddkrtjdt|jd|jd}n|S(NuCoercing non-XML pubidu'iu!Pubid cannot contain single quote(	tnonPubidCharRegexptfindallR6R7RtgetReplacementCharacterR'R1tfind(R3R>t
dataOutputR*treplacement((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pytcoercePubidsc
C`s|d}|d}tj|}|rKtjdt|j|}n|}|}ttj|}x?|D]7}tjdt|j|}	|j	||	}qsW||S(NiiuCoercing non-XML name(
tnonXmlNameFirstBMPRegexpR	R6R7RRFtsettnonXmlNameBMPRegexpRER'(
R3R9t	nameFirsttnameResttmtnameFirstOutputtnameRestOutputtreplaceCharsR*RI((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyR8s


cC`s2||jkr|j|}n|j|}|S(N(R2t
escapeChar(R3R*RI((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyRFscC`sBx;t|jj|D]!}|j||j|}qW|S(N(RLtreplacementRegexpRER'tunescapeChar(R3R9R((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pytfromXmlNamescC`s!dt|}||j|<|S(NuU%05X(RR2(R3R*RI((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyRTs
cC`stt|ddS(Nii(R"R%(R3tcharcode((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyRVsN(t__name__t
__module__tretcompileRURRR4R
R;R<R?RCRJR8RFRWRTRV(((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyR+s"		
						(!t
__future__RRRR[R6t	constantsRtbaseChartideographictcombiningCharactertdigittextenderR#tletterR9RNR\RRRRR%RR R$R
R!RMRKRDtobjectR+(((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyts20							_vendor/html5lib/_inputstream.pyo000064400000065135152527136320013203 0ustar00
abc!@`sddlmZmZmZddlmZmZddlmZm	Z	ddl
Z
ddlZddlm
Z
ddlmZmZmZmZddlmZdd	lmZdd
lmZyddlmZWnek
reZnXegeD]Zejd^qZegeD]Zejd^q"ZegeD]Zejd^qJZeed
dgBZ dZ!ej"rej#e!d e$ddZ%nej#e!Z%e&dddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2g Z'ej#d3Z(iZ)d4e*fd5YZ+d6Z,d7e*fd8YZ-d9e-fd:YZ.d;e/fd<YZ0d=e*fd>YZ1d?e*fd@YZ2dAZ3dS(Bi(tabsolute_importtdivisiontunicode_literals(t	text_typetbinary_type(thttp_clientturllibN(twebencodingsi(tEOFtspaceCharacterstasciiLetterstasciiUppercase(tReparseException(t_utils(tStringIO(tBytesIOuasciit>tt|j||krL|t|j|8}|d7}qW||g|_dS(Nii(RRR(RRtoffsetti((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytseekLscC`sp|js|j|S|jdt|jkr_|jdt|jdkr_|j|S|j|SdS(Niii(Rt_readStreamRRt_readFromBuffer(Rtbytes((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytreadUs	
 
cC`s&tg|jD]}t|^q
S(N(tsumRR(Rtitem((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyt_bufferedBytes^scC`sL|jj|}|jj||jdcd7 Normalized stream from source
        for use by html5lib.

        source can be either a file-object, local filename or a string.

        The optional encoding parameter must be a string that indicates
        the encoding.  If specified, that encoding will be used,
        regardless of any BOM or later declaration (such as in a meta
        element)

        u􏿿iiuutf-8ucertainN(
R
tsupports_lone_surrogatestNonetreportCharacterErrorsRtcharacterErrorsUCS4tcharacterErrorsUCS2tnewLinestlookupEncodingtcharEncodingt
openStreamt
dataStreamtreset(RR>((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRs	cC`sCd|_d|_d|_g|_d|_d|_d|_dS(Nui(Rt	chunkSizetchunkOffsetterrorstprevNumLinestprevNumColsREt_bufferedCharacter(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRNs						cC`s(t|dr|}nt|}|S(uvProduces a file object from source.

        source can be either a file object, local filename or a string.

        uread(R9R(RR>R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRLs	cC`st|j}|jdd|}|j|}|jdd|}|dkr\|j|}n||d}||fS(Nu
iii(RtcountRRtrfindRS(RRRtnLinestpositionLinetlastLinePostpositionColumn((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyt	_positions	
cC`s&|j|j\}}|d|fS(u:Returns (line, col) of the current position in the stream.i(R[RP(Rtlinetcol((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRscC`sL|j|jkr%|js%tSn|j}|j|}|d|_|S(uo Read one character from the stream or queue if available. Return
            EOF when EOF is reached.
        i(RPROt	readChunkRR(RRPtchar((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyR_s	

cC`sO|dkr|j}n|j|j\|_|_d|_d|_d|_|jj	|}|j
r|j
|}d|_
n
|stSt|dkrt
|d}|dksd|kodknr|d|_
|d }qn|jr|j|n|jdd	}|jd
d	}||_t||_tS(Nuiiii
iiu
u
u
(REt_defaultChunkSizeR[RORRRSRRPRMR"RTR8RtordRFtreplacetTrue(RROR'tlastv((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyR^s0				
(
		cC`s:x3tttj|D]}|jjdqWdS(Nuinvalid-codepoint(trangeRtinvalid_unicode_retfindallRQR&(RR't_((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRG%s"cC`st}xtj|D]}|r(qnt|j}|j}tj|||d!rtj|||d!}|t	kr|j
jdnt}q|dkr|dkr|t
|dkr|j
jdqt}|j
jdqWdS(Niuinvalid-codepointiii(R8RftfinditerRatgrouptstartR
tisSurrogatePairtsurrogatePairToCodepointtnon_bmp_invalid_codepointsRQR&RcR(RR'tskiptmatcht	codepointRtchar_val((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRH)s 	c
C`sTyt||f}Wnqtk
rdjg|D]}dt|^q1}|scd|}ntjd|}t||f Normalized stream from source
        for use by html5lib.

        source can be either a file-object, local filename or a string.

        The optional encoding parameter must be a string that indicates
        the encoding.  If specified, that encoding will be used,
        regardless of any BOM or later declaration (such as in a meta
        element)

        iidN(RLt	rawStreamR<RtnumBytesMetatnumBytesChardettoverride_encodingttransport_encodingtsame_origin_parent_encodingtlikely_encodingtdefault_encodingtdetermineEncodingRKRN(RR>RRRRRt
useChardet((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRs							cC`s3|jdjj|jd|_tj|dS(Niureplace(RKt
codec_infotstreamreaderRRMR<RN(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRNs"cC`sUt|dr|}nt|}y|j|jWnt|}nX|S(uvProduces a file object from source.

        source can be either a file object, local filename or a string.

        uread(R9RRRR(RR>R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRLs	cC`s|jdf}|ddk	r&|St|jdf}|ddk	rO|St|jdf}|ddk	rx|S|jdf}|ddk	r|St|jdf}|ddk	r|djjdr|St|j	df}|ddk	r|S|ryddl
m}Wntk
r4qXg}|}xF|j
s|jj|j}|soPn|j||j|qGW|jt|jd}|jjd|dk	r|dfSnt|jdf}|ddk	r|StddfS(Nucertainiu	tentativeuutf-16(tUniversalDetectoruencodinguwindows-1252(t	detectBOMRERJRRtdetectEncodingMetaRtnamet
startswithRtchardet.universaldetectorRtImportErrortdoneRR"RR&tfeedtclosetresultRR(RtchardetRKRtbufferstdetectorRtencoding((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRsP'
	


cC`st|}|dkrdS|jdkr:td}nr||jdkrf|jddf|_nF|jjd|df|_|jtd|jd|fdS(Nuutf-16beuutf-16leuutf-8iucertainuEncoding changed from %s to %s(uutf-16beuutf-16le(RJRERRKRRRNR(RtnewEncoding((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytchangeEncodings
cC`sidtj6dtj6dtj6dtj6dtj6}|jjd}|j|d }d}|s|j|}d}|s|j|d }d}qn|r|jj	|t
|S|jj	d	d
Sd
S(uAttempts to detect at BOM at the start of the stream. If
        an encoding can be determined from the BOM return the name of the
        encoding otherwise return Noneuutf-8uutf-16leuutf-16beuutf-32leuutf-32beiiiiN(tcodecstBOM_UTF8tBOM_UTF16_LEtBOM_UTF16_BEtBOM_UTF32_LEtBOM_UTF32_BERR"tgetRRJRE(RtbomDicttstringRR((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRs$

cC`sk|jj|j}t|}|jjd|j}|dk	rg|jdkrgtd}n|S(u9Report the encoding declared by the meta element
        iuutf-16beuutf-16leuutf-8N(uutf-16beuutf-16le(	RR"RtEncodingParserRtgetEncodingRERRJ(RRtparserR((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyR9sN(R0R1R2RERcRRNRLRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyR=s(		>		"t
EncodingBytescB`seZdZdZdZdZdZdZdZdZ	dZ
ee
e	Zd	Z
ee
Zed
ZdZdZd
ZRS(uString-like object with an associated position and various extra methods
    If the position is ever greater than the string length then an exception is
    raisedcC`stj||jS(N(R!t__new__tlower(Rtvalue((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRLscC`s
d|_dS(Ni(R[(RR((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRPscC`s|S(N((R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyt__iter__TscC`sS|jd}|_|t|kr/tn|dkrDtn|||d!S(Nii(R[Rt
StopIterationR;(Rtp((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyt__next__Ws		cC`s
|jS(N(R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytnext_scC`sY|j}|t|kr$tn|dkr9tn|d|_}|||d!S(Nii(R[RRR;(RR((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytpreviouscs			cC`s+|jt|krtn||_dS(N(R[RR(RR((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytsetPositionls	cC`s<|jt|krtn|jdkr4|jSdSdS(Ni(R[RRRE(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytgetPositionqs
	cC`s||j|jd!S(Ni(R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytgetCurrentByte{scC`sc|j}xJ|t|krU|||d!}||krH||_|S|d7}qW||_dS(uSkip past a list of charactersiN(RRR[RE(RRzRR{((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRos			cC`sc|j}xJ|t|krU|||d!}||krH||_|S|d7}qW||_dS(Ni(RRR[RE(RRzRR{((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyt	skipUntils			cC`sQ|j}|||t|!}|j|}|rM|jt|7_n|S(uLook for a sequence of bytes at the start of a string. If the bytes
        are found return True and advance the position to the byte after the
        match. Otherwise return False and leave the position alone(RRR(RR!RR'R+((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyt
matchBytess	cC`sh||jj|}|dkr^|jdkr=d|_n|j|t|d7_tStdS(uLook for the next sequence of bytes matching a given sequence. If
        a match is found advance the position to the last byte of the matchiiiN(RtfindR[RRcR(RR!tnewPosition((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytjumpTos(R0R1R2RRRRRRRRtpropertyRRtcurrentBytetspaceCharactersBytesRoRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRHs 												RcB`s_eZdZdZdZdZdZdZdZdZ	dZ
d	ZRS(
u?Mini parser for detecting character encoding from meta elementscC`st||_d|_dS(u3string - the data to work on for encoding detectionN(RR'RER(RR'((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRscC`sd|jfd|jfd|jfd|jfd|jfd|jff}xv|jD]k}t}xR|D]J\}}|jj|rky|}PWqtk
rt	}PqXqkqkW|sXPqXqXW|j
S(Ns(R'R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRscC`sK|jjtkrtSt}d}x"trF|j}|dkrGtS|ddkr|ddk}|rC|dk	rC||_tSq%|ddkr|d}t|}|dk	rC||_tSq%|ddkr%t	t
|d}|j}|dk	rCt|}|dk	r@|r4||_tS|}q@qCq%q%WdS(Nis
http-equiviscontent-typetcharsettcontent(R'RRRcR8REtgetAttributeRRJtContentAttrParserRtparse(Rt	hasPragmatpendingEncodingtattrttentativeEncodingtcodect
contentParser((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRs:		
		cC`s
|jtS(N(thandlePossibleTagR8(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRscC`st|j|jtS(N(RR'RRc(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRs
cC`s|j}|jtkr9|r5|j|jntS|jt}|dkra|jn+|j}x|dk	r|j}qpWtS(NR(
R'RtasciiLettersBytesRRRcRtspacesAngleBracketsRRE(RtendTagR'R{R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRs	


cC`s|jjdS(NR(R'R(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRscC`s|j}|jttdgB}|dkr5dSg}g}xtr|dkr`|r`Pnz|tkr||j}Pn^|d	krdj|dfS|tkr|j|j	n|dkrdS|j|t
|}qDW|dkr|jdj|dfSt
||j}|d
kr|}xtrt
|}||krt
|dj|dj|fS|tkr|j|j	q>|j|q>Wn^|dkrdj|dfS|tkr|j|j	n|dkr	dS|j|x}trt
|}|tkrSdj|dj|fS|tkru|j|j	q|dkrdS|j|qWdS(u_Return a name,value pair for the next attribute in the stream,
        if one is found, or Nonet/Rt=R(t't"N(RN(RR(RR(
R'RoRt	frozensetRERcR)tasciiUppercaseBytesR&RRRR(RR'R{tattrNamet	attrValuet	quoteChar((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRsf		


	

	(R0R1R2RRRRRRRRR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRs				$				RcB`seZdZdZRS(cC`s
||_dS(N(R'(RR'((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRfscC`s:y!|jjd|jjd7_|jj|jjdksHdS|jjd7_|jj|jjdkr|jj}|jjd7_|jj}|jj|r|j||jj!SdSnP|jj}y(|jjt|j||jj!SWntk
r|j|SXWntk
r5dSXdS(NRiRRR(RR(	R'RRRoRRERRR(Rt	quoteMarktoldPosition((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRjs.



(R0R1RR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRes	cC`swt|tr:y|jd}Wq:tk
r6dSXn|dk	roytj|SWqstk
rkdSXndSdS(u{Return the python codec name corresponding to an encoding or None if the
    string doesn't correspond to a valid encoding.uasciiN(R3RtdecodetUnicodeDecodeErrorRERtlookuptAttributeError(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pyRJs

(4t
__future__RRRtpip._vendor.sixRRtpip._vendor.six.movesRRRRutpip._vendorRt	constantsRR	R
RRR(R
tioRRRRR$tencodeRRRRtinvalid_unicode_no_surrogateRDRvtevalRftsetRntascii_punctuation_reRstobjectRRCR<R=R!RRRRJ(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_inputstream.pytsP"

(((	
J	h'_vendor/html5lib/html5parser.pyc000064400000361376152527136320012731 0ustar00
abc@`sddlmZmZmZddlmZmZmZddlZyddl	m
Z
Wn!ek
r{ddlm
Z
nXddl
mZddl
mZddl
mZdd	lmZdd
l
mZddlmZmZmZmZmZmZmZmZmZmZmZm Z!m"Z"m#Z#m$Z$m%Z%de&d
Z'dde&dZ(dZ)de*fdYZ+ej,dZ-dZ.de/e0dZ1de2fdYZ3dS(i(tabsolute_importtdivisiontunicode_literals(twith_metaclasstviewkeystPY3N(tOrderedDicti(t_inputstream(t
_tokenizer(ttreebuilders(tMarker(t_utils(tspaceCharacterstasciiUpper2LowertspecialElementstheadingElementst
cdataElementstrcdataElementst
tokenTypest
tagTokenTypest
namespacesthtmlIntegrationPointElementst"mathmlTextIntegrationPointElementstadjustForeignAttributestadjustMathMLAttributestadjustSVGAttributestEtReparseExceptionuetreecK`s1tj|}t|d|}|j||S(u.Parse a string or file-like object into a treetnamespaceHTMLElements(R	tgetTreeBuildert
HTMLParsertparse(tdocttreebuilderRtkwargsttbtp((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRsudivcK`s7tj|}t|d|}|j|d||S(NRt	container(R	RRt
parseFragment(R R%R!RR"R#R$((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR&&sc`s dtffdY}|S(Nt	Decoratedc`seZfdZRS(c`s^xE|jD]7\}}t|tjr:|}n|||tphasetinsertHtmlElementtresetInsertionModeR9t	lastPhasetbeforeRCDataPhasetTruet
framesetOK(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRI^s*
					

			cC`s't|dsdS|jjjdjS(uThe name of the character encoding
        that was used to decode the input stream,
        or :obj:`None` if that is not determined yet.

        u	tokenizeriN(thasattrR9RHRKtcharEncodingRA(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytdocumentEncodingscC`se|jdkrK|jtdkrKd|jkoJ|jdjtdkS|j|jftkSdS(Nuannotation-xmlumathmluencodingu	text/htmluapplication/xhtml+xml(u	text/htmluapplication/xhtml+xml(RAt	namespaceRt
attributest	translateR
R(R?telement((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytisHTMLIntegrationPoints
cC`s|j|jftkS(N(RaRAR(R?Rd((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytisMathMLTextIntegrationPointscC`sBtd}td}td}td}td}td}td}x|jD]}d}	|}
x=|
dk	r|
}	|jjr|jjdnd}|r|jnd}|r|jnd}
|
d	}||kr|j|
d
|
jdid}
qht	|jjdks||jj
ks|j|rx||krf|d
tddgks|||fks|t
dkr|
dkr||kr|d
dks|j|r||||fkr|j}n
|jd}||kr|j|
}
qh||kr)|j|
}
qh||krG|j|
}
qh||kre|j|
}
qh||kr|j|
}
qh||krh|j|
}
qhqhW||krS|	drS|	drS|jdi|	d
d
6qSqSWt}g}xG|r=|j|j|jj}|r|j|ks:tqqWdS(Nu
CharactersuSpaceCharactersuStartTaguEndTaguCommentuDoctypeu
ParseErroriutypeudataudatavarsiunameumglyphu
malignmarkumathmluannotation-xmlusvguinForeignContentuselfClosinguselfClosingAcknowledgedu&non-void-element-with-trailing-solidus(RtnormalizedTokensR9R:topenElementsRaRAt
parseErrortgettlentdefaultNamespaceRft	frozensetRReRWR>tprocessCharacterstprocessSpaceCharacterstprocessStartTagt
processEndTagtprocessCommenttprocessDoctypeR\tappendt
processEOFtAssertionError(R?tCharactersTokentSpaceCharactersTokent
StartTagTokentEndTagTokentCommentTokentDoctypeTokentParseErrorTokenttokent
prev_tokent	new_tokentcurrentNodetcurrentNodeNamespacetcurrentNodeNameR,RWt	reprocessR>((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRJsp






"
 	
		cc`s&x|jD]}|j|Vq
WdS(N(RHtnormalizeToken(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRgscO`s&|j|td|||jjS(uParse a HTML document into a well-formed tree

        stream - a filelike object or string containing the HTML to be parsed

        The optional encoding parameter must be a string that indicates
        the encoding.  If specified, that encoding will be used,
        regardless of any BOM or later declaration (such as in a meta
        element)

        scripting - treat noscript elements as if javascript was turned on
        N(RMRNR9R:tgetDocument(R?RKtargsR"((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscO`s#|j|t|||jjS(u2Parse a HTML fragment into a well-formed tree fragment

        container - name of the element we're setting the innerHTML property
        if set to None, default to 'div'

        stream - a filelike object or string containing the HTML to be parsed

        The optional encoding parameter must be a string that indicates
        the encoding.  If specified, that encoding will be used,
        regardless of any BOM or later declaration (such as in a meta
        element)

        scripting - treat noscript elements as if javascript was turned on
        (RMR\R:tgetFragment(R?RKRR"((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR&suXXX-undefined-errorcC`s^|dkri}n|jj|jjj||f|jrZtt||ndS(N(	R9R;RtRHRKtpositionR8t
ParseErrorR(R?t	errorcodetdatavars((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRis
	%	cC`sr|dtdkrn|d}t||dRW(R?tlasttnewModestnodetnodeNamet	new_phase((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRY!sD
 	
cC`su|dkst|jj||dkrC|jj|j_n|jj|j_|j|_|j	d|_dS(uYGeneric RCDATA/RAWTEXT Parsing algorithm
        contentType - RCDATA or RAWTEXT
        uRAWTEXTuRCDATAutextN(uRAWTEXTuRCDATA(
RvR:t
insertElementRHRURTRSRWt
originalPhaseR>(R?R~tcontentType((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytparseRCDataRawtextMsN(R5R6t__doc__R9RNR\RCRMRItpropertyR`ReRfRJRgRR&RiRRRRRRYR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR8s&	"	
		C									,c`sTd}d}dt|||fdYdfdY}dfdY}d	ffd
Y}dffdY}d
ffdY}dffdY}dffdY}	dffdY}
dffdY}dffdY}dffdY}
dffdY}dffdY}dffd Y}d!ffd"Y}d#ffd$Y}d%ffd&Y}d'ffd(Y}d)ffd*Y}d+ffd,Y}d-ffd.Y}d/ffd0Y}d1ffd2Y}i|d36|d46|d56|d66|d76|d86|	d96|
d:6|d;6|d<6|
d=6|d>6|d?6|d@6|dA6|dB6|dC6|dD6|dE6|dF6|dG6|dH6|dI6S(JNc`s2tdtjDfd}|S(u4Logger that records which phase processes each tokencs`s!|]\}}||fVqdS(N((t.0tkeytvalue((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pys	csc`sjjdrt|dkr|d}yi|dd6}Wn
nX|dtkru|d|dRW(R?R~RAtpublicIdtsystemIdtcorrect((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRss



						cS`s&d|j_|jjd|j_dS(Nuquirksu
beforeHtml(RDRQR>RW(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytanythingElsescS`s|jjd|j|S(Nuexpected-doctype-but-got-chars(RDRiR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRns
cS`s,|jjdi|dd6|j|S(Nu"expected-doctype-but-got-start-taguname(RDRiR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRps
cS`s,|jjdi|dd6|j|S(Nu expected-doctype-but-got-end-taguname(RDRiR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRqs
cS`s|jjd|jtS(Nuexpected-doctype-but-got-eof(RDRiRR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu%s
(
R5R6RoRrRsRRnRpRqRu(((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs			_				tBeforeHtmlPhasecB`sGeZdZdZdZdZdZdZdZRS(cS`s3|jjtdd|jjd|j_dS(NuhtmluStartTagu
beforeHead(R:t
insertRoottimpliedTagTokenRDR>RW(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRX,scS`s|jtS(N(RXR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu1s
cS`s|jj||jjdS(N(R:RR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRr5scS`sdS(N((R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRo8scS`s|j|S(N(RX(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn;s
cS`s-|ddkrt|j_n|j|S(Nunameuhtml(R\RDRORX(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRp?s
cS`sC|ddkr1|jjdi|dd6n|j|SdS(Nunameuheadubodyuhtmlubruunexpected-end-tag-before-html(uheadubodyuhtmlubr(RDRiRX(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRqEs

(	R5R6RXRuRrRoRnRpRq(((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR*s						tBeforeHeadPhasec`s_eZfdZdZdZdZdZdZdZdZ	dZ
RS(	c`s}j|||tjd|jfd|jfg|_|j|j_tjd|jfg|_	|j
|j	_dS(Nuhtmluheadubodyubr(uheadubodyuhtmlubr(RCRtMethodDispatcherRtstartTagHeadRt
startTagOthertdefaulttendTagImplyHeadRtendTagOther(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCNscS`s|jtddtS(NuheaduStartTag(RRR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu\scS`sdS(N((R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRo`scS`s|jtdd|S(NuheaduStartTag(RR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRncscS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRgscS`s@|jj||jjd|j_|jjd|j_dS(NiuinHead(R:RRhtheadPointerRDR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRjscS`s|jtdd|S(NuheaduStartTag(RR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRoscS`s|jtdd|S(NuheaduStartTag(RR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRsscS`s"|jjdi|dd6dS(Nuend-tag-after-implied-rootuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRws(R5R6RCRuRoRnRRRRR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRMs							tInHeadPhasec`seZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZd
ZdZdZRS(c`sj|||tjd|jfd|jfd|jfd|jfd|jfd|jfd|j	fd
|j
fg|_|j|j_
tjd
|jfd|jfg|_|j|j_
dS(Nuhtmlutitleunoframesustyleunoscriptuscriptubaseubasefontubgsounducommandulinkumetauheadubrubody(unoframesustyle(ubaseubasefontubgsounducommandulink(ubruhtmlubody(RCRRRt
startTagTitletstartTagNoFramesStyletstartTagNoscripttstartTagScripttstartTagBaseLinkCommandtstartTagMetaRRRRt
endTagHeadtendTagHtmlBodyBrRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC|s 	cS`s|jtS(N(RR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRus
cS`s|j|S(N(R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRns
cS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|jjddS(Nu!two-heads-are-not-better-than-one(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s.|jj||jjjt|dRW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`sT|jj||jjj|jj_|jj|j_|jjd|j_dS(Nutext(	R:RRDRHtscriptDataStateRTRWRR>(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|j|S(N(R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`sQ|jjjj}|jdks7td|j|jjd|j_dS(NuheaduExpected head got %su	afterHead(RDR:RhRRARvR>RW(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs"cS`s|j|S(N(R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`s"|jjdi|dd6dS(Nuunexpected-end-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|jtddS(Nuhead(RR(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs(R5R6RCRuRnRRRRRRRRRRRRR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR{s 														tInHeadNoscriptPhasec`seZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZRS(
c`sj|||tjd|jfd|jfd|jfg|_|j|j_tjd	|j	fd
|j
fg|_|j|j_dS(
Nuhtmlubasefontubgsoundulinkumetaunoframesustyleuheadunoscriptubr(ubasefontubgsoundulinkumetaunoframesustyle(uheadunoscript(
RCRRRRtstartTagHeadNoscriptRRRtendTagNoscripttendTagBrRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCscS`s|jjd|jtS(Nueof-in-head-noscript(RDRiRR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRus
cS`s|jjdj|S(NuinHead(RDR>Rr(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRrscS`s|jjd|j|S(Nuchar-in-head-noscript(RDRiR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRns
cS`s|jjdj|S(NuinHead(RDR>Ro(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRoscS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|jjdj|S(NuinHead(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s"|jjdi|dd6dS(Nuunexpected-start-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	scS`s,|jjdi|dd6|j|S(Nuunexpected-inhead-noscript-taguname(RDRiR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`sQ|jjjj}|jdks7td|j|jjd|j_dS(NunoscriptuExpected noscript got %suinHead(RDR:RhRRARvR>RW(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs"cS`s,|jjdi|dd6|j|S(Nuunexpected-inhead-noscript-taguname(RDRiR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`s"|jjdi|dd6dS(Nuunexpected-end-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|jtddS(Nunoscript(RR(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs(R5R6RCRuRrRnRoRRRRRRRR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs											tAfterHeadPhasec`szeZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
RS(c
`sj|||tjd|jfd|jfd|jfd|jfd
|jfg|_|j	|j_
tjd|jfg|_|j
|j_
dS(Nuhtmlubodyuframesetubaseubasefontubgsoundulinkumetaunoframesuscriptustyleutitleuheadubr(	ubaseubasefontubgsoundulinkumetaunoframesuscriptustyleutitle(ubodyuhtmlubr(RCRRRtstartTagBodytstartTagFramesettstartTagFromHeadRRRRRRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC#s		cS`s|jtS(N(RR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu4s
cS`s|j|S(N(R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn8s
cS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR<scS`s6t|j_|jj||jjd|j_dS(NuinBody(RNRDR]R:RR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR?scS`s*|jj||jjd|j_dS(Nu
inFrameset(R:RRDR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRDscS`s|jjdi|dd6|jjj|jj|jjdj|xG|jjdddD],}|jdkrh|jjj	|PqhqhWdS(Nu#unexpected-start-tag-out-of-my-headunameuinHeadiuhead(
RDRiR:RhRtRR>RpRAtremove(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRHs cS`s"|jjdi|dd6dS(Nuunexpected-start-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRRscS`s|j|S(N(R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRUs
cS`s|j|S(N(R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRYs
cS`s"|jjdi|dd6dS(Nuunexpected-end-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR]scS`s?|jjtdd|jjd|j_t|j_dS(NubodyuStartTaguinBody(R:RRRDR>RWR\R](R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR`s(R5R6RCRuRnRRRRRRRRR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR"s						
				tInBodyPhasec`seZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0d/Z1d0Z2d1Z3d2Z4RS(3c,`sij||||j|_tjd|jfdd|jfd|jfd|jfde|j	ft
|jfdf|jfd&|j
fdg|jfd*|jfd+|jfdh|jfd8|jfd9|jfdi|jfd=|jfd>|jfdj|jfdk|jfdH|jfdI|jfdJ|jfdK|jfdL|jfdM|jfdN|jfdl|j fdQ|j!fdm|j"fdn|j#fdV|j$fdW|j%fdo|j&fg!|_'|j(|j'_)tjd|j*fd|j+fdp|j,fd&|j-fd |j.fdq|j/ft
|j0fdr|j1fds|j2fd@|j3fg
|_4|j5|j4_)dS(tNuhtmlubaseubasefontubgsounducommandulinkumetauscriptustyleutitleubodyuframesetuaddressuarticleuasideu
blockquoteucenterudetailsudirudivudlufieldsetu
figcaptionufigureufooteruheaderuhgroupumainumenuunavuolupusectionusummaryuulupreulistinguformuliuddudtu	plaintextuaububigucodeuemufontuiususmallustrikeustronguttuuunobrubuttonuappletumarqueeuobjectuxmputableuareaubruembeduimgukeygenuwbruparamusourceutrackuinputuhruimageuisindexutextareauiframeunoscriptunoembedunoframesuselecturpurtuoptionuoptgroupumathusvgucaptionucolucolgroupuframeuheadutbodyutdutfootuthutheadutrudialog(	ubaseubasefontubgsounducommandulinkumetauscriptustyleutitle(uaddressuarticleuasideu
blockquoteucenterudetailsudirudivudlufieldsetu
figcaptionufigureufooteruheaderuhgroupumainumenuunavuolupusectionusummaryuul(upreulisting(uliuddudt(ububigucodeuemufontuiususmallustrikeustronguttuu(uappletumarqueeuobject(uareaubruembeduimgukeygenuwbr(uparamusourceutrack(unoembedunoframes(urpurt(uoptionuoptgroup(ucaptionucolucolgroupuframeuheadutbodyutdutfootuthutheadutr(uaddressuarticleuasideu
blockquoteubuttonucenterudetailsudialogudirudivudlufieldsetu
figcaptionufigureufooteruheaderuhgroupulistingumainumenuunavuolupreusectionusummaryuul(uddudtuli(uaububigucodeuemufontuiunobrususmallustrikeustronguttuu(uappletumarqueeuobject(6RCtprocessSpaceCharactersNonPreRoRRRtstartTagProcessInHeadRRtstartTagClosePRtstartTagHeadingtstartTagPreListingtstartTagFormtstartTagListItemtstartTagPlaintextt	startTagAtstartTagFormattingtstartTagNobrtstartTagButtontstartTagAppletMarqueeObjecttstartTagXmpt
startTagTabletstartTagVoidFormattingtstartTagParamSourcet
startTagInputt
startTagHrt
startTagImagetstartTagIsIndextstartTagTextareatstartTagIFrameRtstartTagRawtexttstartTagSelecttstartTagRpRttstartTagOpttstartTagMathtstartTagSvgtstartTagMisplacedRRRt
endTagBodyt
endTagHtmltendTagBlockt
endTagFormtendTagPtendTagListItemt
endTagHeadingtendTagFormattingtendTagAppletMarqueeObjectRRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRChs~			cS`s4|j|jko3|j|jko3|j|jkS(N(RARaRb(R?tnode1tnode2((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytisMatchingFormattingElementscS`s|jj||jjd}g}xS|jjdddD]8}|tkrVPq@|j||r@|j|q@q@Wt|dkstt|dkr|jjj	|dn|jjj|dS(Nii(
R:RRhtactiveFormattingElementsR
RRtRkRvR(R?R~RdtmatchingElementsR((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytaddFormattingElements c
S`sWtd}xD|jjddd
D])}|j|kr&|jjdPq&q&WdS(Nuddudtuliuputbodyutdutfootuthutheadutrubodyuhtmliu expected-closing-tag-but-got-eof(uddudtuliuputbodyutdutfootuthutheadutrubodyuhtml(RmR:RhRARDRi(R?tallowed_elementsR((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRus	 cS`s|d}|j|_|jdrb|jjdjdkrb|jjdjrb|d}n|r|jj|jj|ndS(	Nudatau
iupreulistingutextareai(upreulistingutextarea(	RRoRR:RhRAt
hasContentt#reconstructActiveFormattingElementsR(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyt!processSpaceCharactersDropNewlines


cS`s}|ddkrdS|jj|jj|d|jjrytg|dD]}|tk^qOryt|j_ndS(Nudatau(R:RRRDR]tanyRRN(R?R~tchar((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRns
#cS`s%|jj|jj|ddS(Nudata(R:RR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`s|jjdj|S(NuinHead(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|jjdidd6t|jjdksK|jjdjdkr`|jjstn`t|j_	xQ|dj
D]?\}}||jjdjkr}||jjdj|RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs1'cS`sB|jjdddr.|jtdn|jj|dS(Nuptvariantubutton(R:telementInScopeRRR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	scS`sZ|jjdddr.|jtdn|jj|t|j_|j|_	dS(NupRubutton(
R:RRRRRNRDR]R
Ro(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`s|jjr)|jjdidd6nT|jjdddrW|jtdn|jj||jjd|j_dS(Nuunexpected-start-taguformunameupRubuttoni(	R:tformPointerRDRiRRRRRh(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`st|j_idgd6ddgd6ddgd6}||d}xnt|jjD]Z}|j|kr|jjjt	|jdPn|j
tkrW|jdkrWPqWqWW|jjdd	d
r|jjjt	ddn|jj
|dS(NuliudtuddunameuEndTaguaddressudivupRubutton(uaddressudivup(RNRDR]treversedR:RhRARWRqRt	nameTupleRRR(R?R~tstopNamesMapt	stopNamesR((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs"

cS`sZ|jjdddr.|jtdn|jj||jjj|jj_dS(NupRubutton(	R:RRRRRDRHRVRT(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR4scS`s|jjdddr.|jtdn|jjdjtkrx|jjdi|dd6|jjj	n|jj
|dS(NupRubuttoniuunexpected-start-taguname(R:RRRRhRARRDRiRR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR:scS`s|jjd}|r|jjdidd6dd6|jtd||jjkrt|jjj|n||jjkr|jjj|qn|jj	|j
|dS(Nuau$unexpected-start-tag-implies-end-tagu	startNameuendName(R:t!elementInActiveFormattingElementsRDRiRRRhRRRR	(R?R~tafeAElement((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRBs
cS`s|jj|j|dS(N(R:RR	(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyROs
cS`st|jj|jjdrc|jjdidd6dd6|jtd|jjn|j|dS(Nunobru$unexpected-start-tag-implies-end-tagu	startNameuendName(R:RRRDRiRqRR	(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRSs
cS`sw|jjdrJ|jjdidd6dd6|jtd|S|jj|jj|t|j_	dS(Nubuttonu$unexpected-start-tag-implies-end-tagu	startNameuendName(
R:RRDRiRqRRRRNR](R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR]s
cS`s@|jj|jj||jjjtt|j_dS(N(	R:RRRRtR
RNRDR](R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRhs
cS`s^|jjdddr.|jtdn|jjt|j_|jj|ddS(NupRubuttonuRAWTEXT(	R:RRRRRNRDR]R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRns

cS`sy|jjdkrC|jjdddrC|jtdqCn|jj|t|j_|jj	d|j_
dS(NuquirksupRubuttonuinTable(RDRQR:RRqRRRNR]R>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRuscS`sG|jj|jj||jjjt|d(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs




cS`s_|jjdrK|jj|jjdjdkrK|jjqKn|jj|dS(Nurubyi(R:RtgenerateImpliedEndTagsRhRARDRiR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs

cS`sv|jj|jj||jj|td|d<|jj||drr|jjjt	|dRW(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR!s
		cS`s-|jjdr)|jtd|SdS(Nubody(R:RRR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR3scS`s|ddkr|j|_n|jj|d}|rK|jjn|jjdj|dkr|jjdi|dd6n|r|jjj	}x,|j|dkr|jjj	}qWndS(Nunameupreiuend-tag-too-early(
RRoR:RRRhRARDRiR(R?R~tinScopeR((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR9s!cS`s|jj}d|j_|dks7|jj|rT|jjdidd6nS|jj|jjd|kr|jjdidd6n|jjj|dS(Nuunexpected-end-taguformunameiuend-tag-too-early-ignored(	R:RR9RRDRiRRhR(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRGs
cS`s|ddkrd}nd}|jj|dd|s\|jjdi|dd6n|jjd|d|jjdj|dkr|jjdi|dd6n|jjj}x)|j|dkr|jjj}qWdS(	NunameuliulistRuunexpected-end-tagtexcludeiuend-tag-too-early(	R9R:RRDRiRRhRAR(R?R~RR((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRTs	!	cS`sx1tD])}|jj|r|jjPqqW|jjdj|dkrr|jjdi|dd6nx^tD]V}|jj|ry|jjj}x%|jtkr|jjj}qWPqyqyWdS(Niunameuend-tag-too-early(	RR:RRRhRARDRiR(R?R~titem((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRes

!
cS`s3d}x&|dkr.|d7}|jj|d}|sd||jjkru|jj|jru|j|dS||jjkr|jjdi|dd6|jjj	|dS|jj|js|jjdi|dd6dS||jjdkr*|jjd	i|dd6n|jjj
|}d}x1|jj|D]}|jt
krV|}PqVqVW|dkr|jjj}x"||kr|jjj}qW|jjj	|dS|jj|d}|jjj
|}|}	}
d}|jjj
|
}x|d
kr9|d7}|d8}|jj|}
|
|jjkr|jjj	|
q$n|
|krPn|	|kr|jjj
|
d}n|
j}
|
|jj|jjj
|
<|
|jj|jjj
|
<|
}
|	jr#|	jj|	n|
j|	|
}	q$W|	jrV|	jj|	n|jtdkr|jj\}}|j|	|n
|j|	|j}
|j|
|j|
|jjj	||jjj||
|jjj	||jjj|jjj
|d|
q	WdS(u)The much-feared adoption agency algorithmiiiunameNuadoption-agency-1.2uadoption-agency-4.4iuadoption-agency-1.3iutableutbodyutfootutheadutr(utableutbodyutfootutheadutr(R:RRhRRARRDRiRRtindexR9RRRt	cloneNodeRRtappendChildRmtgetTableMisnestedNodePositiontinsertBeforetreparentChildrentinsert(R?R~touterLoopCountertformattingElementtafeIndext
furthestBlockRdtcommonAncestortbookmarktlastNodeRtinnerLoopCounterR#tcloneRR'((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRts

	

!



	

	


cS`s|jj|dr&|jjn|jjdj|dkrd|jjdi|dd6n|jj|dr|jjj}x)|j|dkr|jjj}qW|jjndS(Nunameiuend-tag-too-early(	R:RRRhRARDRiRtclearActiveFormattingElements(R?R~Rd((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs!cS`s[|jjdidd6dd6|jj|jjtdd|jjjdS(Nuunexpected-end-tag-treated-asubruoriginalNameu
br elementunewNameuStartTag(RDRiR:RRRRhR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR#s

cS`sx|jjdddD]}|j|dkr|jjd|d|jjdj|dkr|jjdi|dd6nx|jjj|krqWPq|jtkr|jjdi|dd6PqqWdS(NiunameR!uunexpected-end-tag(	R:RhRARRDRiRRR(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR*s !(5R5R6RCRR	RuR
RnRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyResfG			
	
													
		
																							
				
					t	TextPhasec`sDeZfdZdZdZdZdZdZRS(c`sej|||tjg|_|j|j_tjd|jfg|_|j|j_dS(Nuscript(	RCRRRRRtendTagScriptRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC9scS`s|jj|ddS(Nudata(R:R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnAscS`sM|jjdi|jjdjd6|jjj|jj|j_tS(Nu&expected-named-closing-tag-but-got-eofiuname(	RDRiR:RhRARRRWR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRuDs
cS`ststd|ddS(Nu4Tried to process start tag %s in RCDATA/RAWTEXT modeuname(RNRv(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRKscS`s=|jjj}|jdks't|jj|j_dS(Nuscript(R:RhRRARvRDRRW(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR5NscS`s&|jjj|jj|j_dS(N(R:RhRRDRRW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRUs(R5R6RCRnRuRR5R((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR48s				tInTablePhasec`seZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZd
ZdZdZdZdZdZRS(c
`sj|||tjd|jfd|jfd|jfd|jfd|jfd|jfd|j	fd|j
fd|jfd|jfg
|_
|j|j
_tjd|jfd|jfg|_|j|j_dS(Nuhtmlucaptionucolgroupucolutbodyutfootutheadutduthutrutableustyleuscriptuinputuformubody(utbodyutfootuthead(utduthutr(ustyleuscript(ubodyucaptionucolucolgroupuhtmlutbodyutdutfootuthutheadutr(RCRRRtstartTagCaptiontstartTagColgrouptstartTagColtstartTagRowGrouptstartTagImplyTbodyRtstartTagStyleScriptRRRRRtendTagTabletendTagIgnoreRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC[s$cS`s4x-|jjdjdkr/|jjjqWdS(Niutableuhtml(utableuhtml(R:RhRAR(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytclearStackToTableContextsscS`sB|jjdjdkr,|jjdn|jjs>tdS(Niuhtmlueof-in-table(R:RhRARDRiRLRv(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu|scS`sH|jj}|jjd|j_||jj_|jjj|dS(NuinTableText(RDRWR>RRo(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRoscS`sH|jj}|jjd|j_||jj_|jjj|dS(NuinTableText(RDRWR>RRn(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnscS`s3t|j_|jjdj|t|j_dS(NuinBody(R\R:tinsertFromTableRDR>RnRN(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`sG|j|jjjt|jj||jjd|j_dS(Nu	inCaption(	R?R:RRtR
RRDR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR7s
cS`s4|j|jj||jjd|j_dS(Nu
inColumnGroup(R?R:RRDR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR8s
cS`s|jtdd|S(NucolgroupuStartTag(R8R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR9scS`s4|j|jj||jjd|j_dS(NuinTableBody(R?R:RRDR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR:s
cS`s|jtdd|S(NutbodyuStartTag(R:R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR;scS`sN|jjdidd6dd6|jjjtd|jjsJ|SdS(Nu$unexpected-start-tag-implies-end-tagutableu	startNameuendName(RDRiRWRqRRL(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`s|jjdj|S(NuinHead(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR<scS`sqd|dkr`|ddjtdkr`|jjd|jj||jjjn
|j|dS(Nutypeudatauhiddenu unexpected-hidden-input-in-table(	RcR
RDRiR:RRhRR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s_|jjd|jjdkr[|jj||jjd|j_|jjjndS(Nuunexpected-form-in-tablei(RDRiR:RR9RRhR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`sQ|jjdi|dd6t|j_|jjdj|t|j_dS(Nu)unexpected-start-tag-implies-table-voodoounameuinBody(RDRiR\R:R@R>RpRN(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|jjdddr|jj|jjdjdkro|jjdidd6|jjdjd6nx-|jjdjdkr|jjjqrW|jjj|jjn|jj	st
|jjdS(NutableRiuend-tag-too-early-namedugotNameuexpectedName(R:RRRhRARDRiRRYRLRv(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR=s

cS`s"|jjdi|dd6dS(Nuunexpected-end-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR>scS`sQ|jjdi|dd6t|j_|jjdj|t|j_dS(Nu'unexpected-end-tag-implies-table-voodoounameuinBody(RDRiR\R:R@R>RqRN(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs(R5R6RCR?RuRoRnRR7R8R9R:R;RR<RRRR=R>R((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR6Ys&														
				tInTableTextPhasec`sVeZfdZdZdZdZdZdZdZdZ	RS(c`s)j|||d|_g|_dS(N(RCR9RtcharacterTokens(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCs	cS`sdjg|jD]}|d^q}tg|D]}|tk^q3ritdd6|d6}|jjdj|n|r|jj|ng|_dS(Nuudatau
CharactersutypeuinTable(	tjoinRBRRRRDR>RR:(R?R"RR~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytflushCharacterss)%cS`s|j|j|j_|S(N(RDRRDRW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRrs
cS`s|j|j|j_tS(N(RDRRDRWR\(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRus
cS`s(|ddkrdS|jj|dS(Nudatau(RBRt(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnscS`s|jj|dS(N(RBRt(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRoscS`s|j|j|j_|S(N(RDRRDRW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRp
s
cS`s|j|j|j_|S(N(RDRRDRW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRqs
(
R5R6RCRDRrRuRnRoRpRq((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRAs							tInCaptionPhasec`sheZfdZdZdZdZdZdZdZdZ	dZ
d	ZRS(
c
`sj|||tjd|jfd
|jfg|_|j|j_tjd|jfd|j	fd|j
fg|_|j|j_dS(Nuhtmlucaptionucolucolgrouputbodyutdutfootuthutheadutrutableubody(	ucaptionucolucolgrouputbodyutdutfootuthutheadutr(
ubodyucolucolgroupuhtmlutbodyutdutfootuthutheadutr(
RCRRRtstartTagTableElementRRRt
endTagCaptionR=R>RR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCscS`s|jjdddS(NucaptionRutable(R:R(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytignoreEndTagCaption+scS`s|jjdjdS(NuinBody(RDR>Ru(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu.scS`s|jjdj|S(NuinBody(RDR>Rn(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn1scS`s@|jj|j}|jjjtd|s<|SdS(Nucaption(RDRiRHRWRqR(R?R~tignoreEndTag((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRF4s

cS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR<scS`s|js|jj|jjdjdkrc|jjdidd6|jjdjd6nx-|jjdjdkr|jjjqfW|jjj|jj|jj	d|j_
n|jjst|jjdS(Niucaptionu$expected-one-end-tag-but-got-anotherugotNameuexpectedNameuinTable(
RHR:RRhRARDRiRR3R>RWRLRv(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRG?s


cS`s@|jj|j}|jjjtd|s<|SdS(Nucaption(RDRiRHRWRqR(R?R~RI((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR=Qs

cS`s"|jjdi|dd6dS(Nuunexpected-end-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR>XscS`s|jjdj|S(NuinBody(RDR>Rq(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR[s(R5R6RCRHRuRnRFRRGR=R>R((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyREs								tInColumnGroupPhasec`s_eZfdZdZdZdZdZdZdZdZ	dZ
RS(	c`sj|||tjd|jfd|jfg|_|j|j_tjd|jfd|j	fg|_
|j|j
_dS(Nuhtmlucolucolgroup(RCRRRR9RRRtendTagColgroupt	endTagColRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCascS`s|jjdjdkS(Niuhtml(R:RhRA(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytignoreEndTagColgrouppscS`s\|jjdjdkr/|jjs+tdS|j}|jtd|sXt	SdS(Niuhtmlucolgroup(
R:RhRARDRLRvRMRKRR\(R?RI((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRusscS`s-|j}|jtd|s)|SdS(Nucolgroup(RMRKR(R?R~RI((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn}scS`s.|jj||jjjt|dRW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRKs
cS`s|jjdidd6dS(Nu
no-end-tagucoluname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRLscS`s-|j}|jtd|s)|SdS(Nucolgroup(RMRKR(R?R~RI((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs(R5R6RCRMRuRnR9RRKRLR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRJ^s		
						tInTableBodyPhasec`seZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZRS(
c`sj|||tjd|jfd|jfd
|jfd|jfg|_|j|j_	tjd|j
fd|jfd|jfg|_
|j|j
_	dS(Nuhtmlutrutduthucaptionucolucolgrouputbodyutfootutheadutableubody(utduth(ucaptionucolucolgrouputbodyutfootuthead(utbodyutfootuthead(ubodyucaptionucolucolgroupuhtmlutduthutr(RCRRRt
startTagTrtstartTagTableCelltstartTagTableOtherRRRtendTagTableRowGroupR=R>RR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCscS`sbx-|jjdjdkr/|jjjqW|jjdjdkr^|jjs^tndS(Niutbodyutfootutheaduhtml(utbodyutfootutheaduhtml(R:RhRARRDRLRv(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytclearStackToTableBodyContexts
	cS`s|jjdjdS(NuinTable(RDR>Ru(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRuscS`s|jjdj|S(NuinTable(RDR>Ro(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRoscS`s|jjdj|S(NuinTable(RDR>Rn(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnscS`s4|j|jj||jjd|j_dS(NuinRow(RSR:RRDR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyROs
cS`s8|jjdi|dd6|jtdd|S(Nuunexpected-cell-in-table-bodyunameutruStartTag(RDRiROR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRPscS`s|jjdddsH|jjdddsH|jjdddrv|j|jt|jjdj|S|jjst	|jj
dS(NutbodyRutableutheadutfooti(R:RRSRRRRhRARDRLRvRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRQs
cS`s|jjdj|S(NuinTable(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`sq|jj|dddrO|j|jjj|jjd|j_n|jjdi|dd6dS(NunameRutableuinTableu unexpected-end-tag-in-table-body(	R:RRSRhRRDR>RWRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRRs
cS`s|jjdddsH|jjdddsH|jjdddrv|j|jt|jjdj|S|jjst	|jj
dS(NutbodyRutableutheadutfooti(R:RRSRRRRhRARDRLRvRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR=s
cS`s"|jjdi|dd6dS(Nu unexpected-end-tag-in-table-bodyuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR>scS`s|jjdj|S(NuinTable(RDR>Rq(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs(R5R6RCRSRuRoRnRORPRQRRRR=R>R((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRNs	
										
	t
InRowPhasec`seZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZd
ZRS(c`sj|||tjd|jfd
|jfd|jfg|_|j|j_tjd
|j	fd|j
fd|jfd|jfg|_
|j|j
_dS(Nuhtmlutduthucaptionucolucolgrouputbodyutfootutheadutrutableubody(utduth(ucaptionucolucolgrouputbodyutfootutheadutr(utbodyutfootuthead(ubodyucaptionucolucolgroupuhtmlutduth(RCRRRRPRQRRRtendTagTrR=RRR>RR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCscS`s[xT|jjdjdkrV|jjdi|jjdjd6|jjjqWdS(Niutruhtmlu'unexpected-implied-end-tag-in-table-rowuname(utruhtml(R:RhRARDRiR(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytclearStackToTableRowContextscS`s|jjdddS(NutrRutable(R:R(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pytignoreEndTagTrscS`s|jjdjdS(NuinTable(RDR>Ru(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu"scS`s|jjdj|S(NuinTable(RDR>Ro(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRo%scS`s|jjdj|S(NuinTable(RDR>Rn(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn(scS`sG|j|jj||jjd|j_|jjjtdS(NuinCell(	RVR:RRDR>RWRRtR
(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRP+s
cS`s-|j}|jtd|s)|SdS(Nutr(RWRUR(R?R~RI((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRQ1scS`s|jjdj|S(NuinTable(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR8scS`sb|js?|j|jjj|jjd|j_n|jjsQt	|jj
dS(NuinTableBody(RWRVR:RhRRDR>RWRLRvRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRU;s
cS`s-|j}|jtd|s)|SdS(Nutr(RWRUR(R?R~RI((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR=EscS`sD|jj|dddr3|jtd|S|jjdS(NunameRutableutr(R:RRURRDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRRMscS`s"|jjdi|dd6dS(Nuunexpected-end-tag-in-table-rowuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR>TscS`s|jjdj|S(NuinTable(RDR>Rq(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRXs(R5R6RCRVRWRuRoRnRPRQRRUR=RRR>R((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRTs									
			tInCellPhasec`sheZfdZdZdZdZdZdZdZdZ	dZ
d	ZRS(
c`sj|||tjd|jfd
|jfg|_|j|j_tjd|jfd|j	fd|j
fg|_|j|j_dS(Nuhtmlucaptionucolucolgrouputbodyutdutfootuthutheadutrubodyutable(	ucaptionucolucolgrouputbodyutdutfootuthutheadutr(utduth(ubodyucaptionucolucolgroupuhtml(utableutbodyutfootutheadutr(
RCRRRRQRRRtendTagTableCellR>tendTagImplyRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC]scS`s`|jjdddr.|jtdn.|jjdddr\|jtdndS(NutdRutableuth(R:RRYR(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyt	closeCellnscS`s|jjdjdS(NuinBody(RDR>Ru(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRuuscS`s|jjdj|S(NuinBody(RDR>Rn(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnxscS`sa|jjddds0|jjdddr>|j|S|jjsPt|jjdS(NutdRutableuth(R:RR[RDRLRvRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRQ{s
cS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s|jj|dddr|jj|d|jjdj|dkr|jjdi|dd6xFtr|jjj}|j|dkrnPqnqnWn|jjj|jj	|jj
d|j_n|jjdi|dd6dS(NunameRutableiuunexpected-cell-end-taguinRowuunexpected-end-tag(R:RRRhRARDRiR\RR3R>RW(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRYs	
cS`s"|jjdi|dd6dS(Nuunexpected-end-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR>scS`s;|jj|dddr*|j|S|jjdS(NunameRutable(R:RR[RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRZs
cS`s|jjdj|S(NuinBody(RDR>Rq(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs(R5R6RCR[RuRnRQRRYR>RZR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRX[s				
				t
InSelectPhasec`seZfdZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZ
dZRS(
c`sj|||tjd|jfd|jfd|jfd|jfd	|jfd|jfg|_	|j
|j	_tjd|jfd|j
fd|jfg|_|j|j_dS(
Nuhtmluoptionuoptgroupuselectuinputukeygenutextareauscript(uinputukeygenutextarea(RCRRRtstartTagOptiontstartTagOptgroupRRRRRRtendTagOptiontendTagOptgrouptendTagSelectRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCscS`sB|jjdjdkr,|jjdn|jjs>tdS(Niuhtmlu
eof-in-select(R:RhRARDRiRLRv(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRuscS`s,|ddkrdS|jj|ddS(Nudatau(R:R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnscS`s@|jjdjdkr,|jjjn|jj|dS(Niuoption(R:RhRARR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR]scS`sl|jjdjdkr,|jjjn|jjdjdkrX|jjjn|jj|dS(Niuoptionuoptgroup(R:RhRARR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR^s
cS`s'|jjd|jtddS(Nuunexpected-select-in-selectuselect(RDRiRaR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`sU|jjd|jjdddr?|jtd|S|jjsQtdS(Nuunexpected-input-in-selectuselectR(RDRiR:RRaRRLRv(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRs
cS`s|jjdj|S(NuinHead(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`s"|jjdi|dd6dS(Nuunexpected-start-tag-in-selectuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRscS`sJ|jjdjdkr,|jjjn|jjdidd6dS(Niuoptionuunexpected-end-tag-in-selectuname(R:RhRARRDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR_scS`s|jjdjdkrE|jjdjdkrE|jjjn|jjdjdkrq|jjjn|jjdidd6dS(Niuoptioniuoptgroupuunexpected-end-tag-in-selectuname(R:RhRARRDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR`scS`s|jjdddrb|jjj}x%|jdkrQ|jjj}q-W|jjn|jjstt|jj	dS(NuselectR(
R:RRhRRARDRYRLRvRi(R?R~R((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRascS`s"|jjdi|dd6dS(Nuunexpected-end-tag-in-selectuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	s(R5R6RCRuRnR]R^RRRRR_R`RaR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR\s										
	tInSelectInTablePhasec`sMeZfdZdZdZdZdZdZdZRS(c	`sqj|||tjd	|jfg|_|j|j_tjd
|jfg|_|j	|j_dS(Nucaptionutableutbodyutfootutheadutrutduth(ucaptionutableutbodyutfootutheadutrutduth(ucaptionutableutbodyutfootutheadutrutduth(
RCRRRRRRR=RR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC	scS`s|jjdjdS(NuinSelect(RDR>Ru(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu	scS`s|jjdj|S(NuinSelect(RDR>Rn(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn	scS`s5|jjdi|dd6|jtd|S(Nu5unexpected-table-element-start-tag-in-select-in-tableunameuselect(RDRiRR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR!	scS`s|jjdj|S(NuinSelect(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR&	scS`sU|jjdi|dd6|jj|dddrQ|jtd|SdS(Nu3unexpected-table-element-end-tag-in-select-in-tableunameRutableuselect(RDRiR:RRR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR=)	scS`s|jjdj|S(NuinSelect(RDR>Rq(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR/	s(	R5R6RCRuRnRRR=R((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRb	s					tInForeignContentPhasec-`seZedddddddddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+g,Zfd,Zd-Zfd.Zd/Zd0ZRS(1ububigu
blockquoteubodyubrucenterucodeuddudivudludtuemuembeduh1uh2uh3uh4uh5uh6uheaduhruiuimguliulistingumenuumetaunobruolupupreurubyususmalluspanustrongustrikeusubusuputableuttuuuuluvarc`sj|||dS(N(RC(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC<	scS`s+i$dd6dd6dd6dd6d	d
6dd6d
d6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d!d"6d#d$6d%d&6d'd(6d)d*6d+d,6d-d.6d/d06d1d26d3d46d5d66d7d86d9d:6d;d<6d=d>6d?d@6dAdB6dCdD6dEdF6dGdH6}|dI|kr'||dI|dIl	s(RDR]RRNRn(R?R~(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnh	s
cS`s|jjd}|d|jks\|ddkrt|djtdddg@r|jjdi|dd6xm|jjdj|jjkr|jj	|jjdr|jj
|jjdr|jjjq}W|S|jtd	kr|jj
|n3|jtd
krG|j||jj|n|jj||j|d<|jj||dr|jjjt|d
RDRRRvR9RaRlRq(R?R~t	nodeIndexRR((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRq	s(!	
(	R5R6RmRfRCReRnRpRq((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRc2	s	)	tAfterBodyPhasec`sVeZfdZdZdZdZdZdZdZdZ	RS(c`sqj|||tjd|jfg|_|j|j_tjd|jfg|_|j	|j_dS(Nuhtml(
RCRRRRRRRRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC	scS`sdS(N((R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu	scS`s!|jj||jjddS(Ni(R:RRh(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRr	scS`s*|jjd|jjd|j_|S(Nuunexpected-char-after-bodyuinBody(RDRiR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn	scS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	scS`s8|jjdi|dd6|jjd|j_|S(Nuunexpected-start-tag-after-bodyunameuinBody(RDRiR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	scS`s9|jjr|jjdn|jjd|j_dS(Nu'unexpected-end-tag-after-body-innerhtmluafterAfterBody(RDRLRiR>RW(R?RA((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	scS`s8|jjdi|dd6|jjd|j_|S(Nuunexpected-end-tag-after-bodyunameuinBody(RDRiR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	s(
R5R6RCRuRrRnRRRR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRj	s						tInFramesetPhasec`s_eZfdZdZdZdZdZdZdZdZ	dZ
RS(	c`sj|||tjd|jfd|jfd|jfd|jfg|_|j|j_	tjd|j
fg|_|j|j_	dS(Nuhtmluframesetuframeunoframes(
RCRRRRt
startTagFrametstartTagNoframesRRRtendTagFramesetRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC	scS`sB|jjdjdkr,|jjdn|jjs>tdS(Niuhtmlueof-in-frameset(R:RhRARDRiRLRv(R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu	scS`s|jjddS(Nuunexpected-char-in-frameset(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn	scS`s|jj|dS(N(R:R(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	scS`s$|jj||jjjdS(N(R:RRhR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRl	scS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRm	scS`s"|jjdi|dd6dS(Nu unexpected-start-tag-in-framesetuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	scS`s|jjdjdkr,|jjdn|jjj|jjr{|jjdjdkr{|jjd|j_ndS(Niuhtmlu)unexpected-frameset-in-frameset-innerhtmluframesetu
afterFrameset(	R:RhRARDRiRRLR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn	s
cS`s"|jjdi|dd6dS(Nuunexpected-end-tag-in-framesetuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR	
s(R5R6RCRuRnRRlRmRRnR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRk	s							tAfterFramesetPhasec`sMeZfdZdZdZdZdZdZdZRS(c`s}j|||tjd|jfd|jfg|_|j|j_tjd|jfg|_	|j
|j	_dS(Nuhtmlunoframes(RCRRRRmRRRRRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC
scS`sdS(N((R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu
scS`s|jjddS(Nuunexpected-char-after-frameset(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn!
scS`s|jjdj|S(NuinHead(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRm$
scS`s"|jjdi|dd6dS(Nu#unexpected-start-tag-after-framesetuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR'
scS`s|jjd|j_dS(NuafterAfterFrameset(RDR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR+
scS`s"|jjdi|dd6dS(Nu!unexpected-end-tag-after-framesetuname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR.
s(	R5R6RCRuRnRmRRR((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRo
s					tAfterAfterBodyPhasec`sVeZfdZdZdZdZdZdZdZdZ	RS(c`sDj|||tjd|jfg|_|j|j_dS(Nuhtml(RCRRRRRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRC3
scS`sdS(N((R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRu;
scS`s|jj||jjdS(N(R:RR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRr>
scS`s|jjdj|S(NuinBody(RDR>Ro(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRoA
scS`s*|jjd|jjd|j_|S(Nuexpected-eof-but-got-charuinBody(RDRiR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnD
scS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRI
scS`s8|jjdi|dd6|jjd|j_|S(Nuexpected-eof-but-got-start-tagunameuinBody(RDRiR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRL
scS`s8|jjdi|dd6|jjd|j_|S(Nuexpected-eof-but-got-end-tagunameuinBody(RDRiR>RW(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRqR
s(
R5R6RCRuRrRoRnRRRq((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRp2
s						tAfterAfterFramesetPhasec`s_eZfdZdZdZdZdZdZdZdZ	dZ
RS(	c`sPj|||tjd|jfd|jfg|_|j|j_dS(Nuhtmlunoframes(RCRRRtstartTagNoFramesRRR(R?RDR:(R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRCY
s
cS`sdS(N((R?((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRub
scS`s|jj||jjdS(N(R:RR(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRre
scS`s|jjdj|S(NuinBody(RDR>Ro(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRoh
scS`s|jjddS(Nuexpected-eof-but-got-char(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRnk
scS`s|jjdj|S(NuinBody(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRn
scS`s|jjdj|S(NuinHead(RDR>Rp(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRrq
scS`s"|jjdi|dd6dS(Nuexpected-eof-but-got-start-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRt
scS`s"|jjdi|dd6dS(Nuexpected-eof-but-got-end-taguname(RDRi(R?R~((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRqx
s(R5R6RCRuRrRoRnRRrRRq((R(sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyRqX
s								uinitialu
beforeHtmlu
beforeHeaduinHeaduinHeadNoscriptu	afterHeaduinBodyutextuinTableuinTableTextu	inCaptionu
inColumnGroupuinTableBodyuinRowuinCelluinSelectuinSelectInTableuinForeignContentu	afterBodyu
inFramesetu
afterFramesetuafterAfterBodyuafterAfterFrameset(R(R@RPRRRRRRRRR4R6RARERJRNRTRXR\RbRcRjRkRoRpRq((RsD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR=_sh		%)#.g@C!-GBbYLd's/9%&%c`s}tstjr,t|dt@}nt|dt@}|rytfd|djD|d
s(RRtPY27RRmRR((R~Rdtneeds_adjustment((RdsD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR
suEndTagcC`s9|dkri}nit|d6|d6|d6|d6S(NutypeunameudatauselfClosing(R9R(RAR,RbR((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR
s	RcB`seZdZRS(uError in parsed document(R5R6R(((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyR
s(4t
__future__RRRtpip._vendor.sixRRRR*tcollectionsRtImportErrortpip._vendor.ordereddicttRRR	ttreebuilders.baseR
Rt	constantsRR
RRRRRRRRRRRRRRRR\RR&R7tobjectRtmemoizeR=RR9RNRt	ExceptionR(((sD/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/html5parser.pyts>
j
	(C	
_vendor/html5lib/_ihatexml.pyo000064400000036157152527136320012445 0ustar00
abc@`sZddlmZmZmZddlZddlZddlmZdZdZ	dZ
dZd	Zd
j
ee	gZd
j
eeddd
e
egZd
j
ed
gZejdZejdZdZdZeddZdZdZdZdZejdZejdZejdZdefdYZ dS(i(tabsolute_importtdivisiontunicode_literalsNi(tDataLossWarningu^
[#x0041-#x005A] | [#x0061-#x007A] | [#x00C0-#x00D6] | [#x00D8-#x00F6] |
[#x00F8-#x00FF] | [#x0100-#x0131] | [#x0134-#x013E] | [#x0141-#x0148] |
[#x014A-#x017E] | [#x0180-#x01C3] | [#x01CD-#x01F0] | [#x01F4-#x01F5] |
[#x01FA-#x0217] | [#x0250-#x02A8] | [#x02BB-#x02C1] | #x0386 |
[#x0388-#x038A] | #x038C | [#x038E-#x03A1] | [#x03A3-#x03CE] |
[#x03D0-#x03D6] | #x03DA | #x03DC | #x03DE | #x03E0 | [#x03E2-#x03F3] |
[#x0401-#x040C] | [#x040E-#x044F] | [#x0451-#x045C] | [#x045E-#x0481] |
[#x0490-#x04C4] | [#x04C7-#x04C8] | [#x04CB-#x04CC] | [#x04D0-#x04EB] |
[#x04EE-#x04F5] | [#x04F8-#x04F9] | [#x0531-#x0556] | #x0559 |
[#x0561-#x0586] | [#x05D0-#x05EA] | [#x05F0-#x05F2] | [#x0621-#x063A] |
[#x0641-#x064A] | [#x0671-#x06B7] | [#x06BA-#x06BE] | [#x06C0-#x06CE] |
[#x06D0-#x06D3] | #x06D5 | [#x06E5-#x06E6] | [#x0905-#x0939] | #x093D |
[#x0958-#x0961] | [#x0985-#x098C] | [#x098F-#x0990] | [#x0993-#x09A8] |
[#x09AA-#x09B0] | #x09B2 | [#x09B6-#x09B9] | [#x09DC-#x09DD] |
[#x09DF-#x09E1] | [#x09F0-#x09F1] | [#x0A05-#x0A0A] | [#x0A0F-#x0A10] |
[#x0A13-#x0A28] | [#x0A2A-#x0A30] | [#x0A32-#x0A33] | [#x0A35-#x0A36] |
[#x0A38-#x0A39] | [#x0A59-#x0A5C] | #x0A5E | [#x0A72-#x0A74] |
[#x0A85-#x0A8B] | #x0A8D | [#x0A8F-#x0A91] | [#x0A93-#x0AA8] |
[#x0AAA-#x0AB0] | [#x0AB2-#x0AB3] | [#x0AB5-#x0AB9] | #x0ABD | #x0AE0 |
[#x0B05-#x0B0C] | [#x0B0F-#x0B10] | [#x0B13-#x0B28] | [#x0B2A-#x0B30] |
[#x0B32-#x0B33] | [#x0B36-#x0B39] | #x0B3D | [#x0B5C-#x0B5D] |
[#x0B5F-#x0B61] | [#x0B85-#x0B8A] | [#x0B8E-#x0B90] | [#x0B92-#x0B95] |
[#x0B99-#x0B9A] | #x0B9C | [#x0B9E-#x0B9F] | [#x0BA3-#x0BA4] |
[#x0BA8-#x0BAA] | [#x0BAE-#x0BB5] | [#x0BB7-#x0BB9] | [#x0C05-#x0C0C] |
[#x0C0E-#x0C10] | [#x0C12-#x0C28] | [#x0C2A-#x0C33] | [#x0C35-#x0C39] |
[#x0C60-#x0C61] | [#x0C85-#x0C8C] | [#x0C8E-#x0C90] | [#x0C92-#x0CA8] |
[#x0CAA-#x0CB3] | [#x0CB5-#x0CB9] | #x0CDE | [#x0CE0-#x0CE1] |
[#x0D05-#x0D0C] | [#x0D0E-#x0D10] | [#x0D12-#x0D28] | [#x0D2A-#x0D39] |
[#x0D60-#x0D61] | [#x0E01-#x0E2E] | #x0E30 | [#x0E32-#x0E33] |
[#x0E40-#x0E45] | [#x0E81-#x0E82] | #x0E84 | [#x0E87-#x0E88] | #x0E8A |
#x0E8D | [#x0E94-#x0E97] | [#x0E99-#x0E9F] | [#x0EA1-#x0EA3] | #x0EA5 |
#x0EA7 | [#x0EAA-#x0EAB] | [#x0EAD-#x0EAE] | #x0EB0 | [#x0EB2-#x0EB3] |
#x0EBD | [#x0EC0-#x0EC4] | [#x0F40-#x0F47] | [#x0F49-#x0F69] |
[#x10A0-#x10C5] | [#x10D0-#x10F6] | #x1100 | [#x1102-#x1103] |
[#x1105-#x1107] | #x1109 | [#x110B-#x110C] | [#x110E-#x1112] | #x113C |
#x113E | #x1140 | #x114C | #x114E | #x1150 | [#x1154-#x1155] | #x1159 |
[#x115F-#x1161] | #x1163 | #x1165 | #x1167 | #x1169 | [#x116D-#x116E] |
[#x1172-#x1173] | #x1175 | #x119E | #x11A8 | #x11AB | [#x11AE-#x11AF] |
[#x11B7-#x11B8] | #x11BA | [#x11BC-#x11C2] | #x11EB | #x11F0 | #x11F9 |
[#x1E00-#x1E9B] | [#x1EA0-#x1EF9] | [#x1F00-#x1F15] | [#x1F18-#x1F1D] |
[#x1F20-#x1F45] | [#x1F48-#x1F4D] | [#x1F50-#x1F57] | #x1F59 | #x1F5B |
#x1F5D | [#x1F5F-#x1F7D] | [#x1F80-#x1FB4] | [#x1FB6-#x1FBC] | #x1FBE |
[#x1FC2-#x1FC4] | [#x1FC6-#x1FCC] | [#x1FD0-#x1FD3] | [#x1FD6-#x1FDB] |
[#x1FE0-#x1FEC] | [#x1FF2-#x1FF4] | [#x1FF6-#x1FFC] | #x2126 |
[#x212A-#x212B] | #x212E | [#x2180-#x2182] | [#x3041-#x3094] |
[#x30A1-#x30FA] | [#x3105-#x312C] | [#xAC00-#xD7A3]u*[#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029]u
[#x0300-#x0345] | [#x0360-#x0361] | [#x0483-#x0486] | [#x0591-#x05A1] |
[#x05A3-#x05B9] | [#x05BB-#x05BD] | #x05BF | [#x05C1-#x05C2] | #x05C4 |
[#x064B-#x0652] | #x0670 | [#x06D6-#x06DC] | [#x06DD-#x06DF] |
[#x06E0-#x06E4] | [#x06E7-#x06E8] | [#x06EA-#x06ED] | [#x0901-#x0903] |
#x093C | [#x093E-#x094C] | #x094D | [#x0951-#x0954] | [#x0962-#x0963] |
[#x0981-#x0983] | #x09BC | #x09BE | #x09BF | [#x09C0-#x09C4] |
[#x09C7-#x09C8] | [#x09CB-#x09CD] | #x09D7 | [#x09E2-#x09E3] | #x0A02 |
#x0A3C | #x0A3E | #x0A3F | [#x0A40-#x0A42] | [#x0A47-#x0A48] |
[#x0A4B-#x0A4D] | [#x0A70-#x0A71] | [#x0A81-#x0A83] | #x0ABC |
[#x0ABE-#x0AC5] | [#x0AC7-#x0AC9] | [#x0ACB-#x0ACD] | [#x0B01-#x0B03] |
#x0B3C | [#x0B3E-#x0B43] | [#x0B47-#x0B48] | [#x0B4B-#x0B4D] |
[#x0B56-#x0B57] | [#x0B82-#x0B83] | [#x0BBE-#x0BC2] | [#x0BC6-#x0BC8] |
[#x0BCA-#x0BCD] | #x0BD7 | [#x0C01-#x0C03] | [#x0C3E-#x0C44] |
[#x0C46-#x0C48] | [#x0C4A-#x0C4D] | [#x0C55-#x0C56] | [#x0C82-#x0C83] |
[#x0CBE-#x0CC4] | [#x0CC6-#x0CC8] | [#x0CCA-#x0CCD] | [#x0CD5-#x0CD6] |
[#x0D02-#x0D03] | [#x0D3E-#x0D43] | [#x0D46-#x0D48] | [#x0D4A-#x0D4D] |
#x0D57 | #x0E31 | [#x0E34-#x0E3A] | [#x0E47-#x0E4E] | #x0EB1 |
[#x0EB4-#x0EB9] | [#x0EBB-#x0EBC] | [#x0EC8-#x0ECD] | [#x0F18-#x0F19] |
#x0F35 | #x0F37 | #x0F39 | #x0F3E | #x0F3F | [#x0F71-#x0F84] |
[#x0F86-#x0F8B] | [#x0F90-#x0F95] | #x0F97 | [#x0F99-#x0FAD] |
[#x0FB1-#x0FB7] | #x0FB9 | [#x20D0-#x20DC] | #x20E1 | [#x302A-#x302F] |
#x3099 | #x309Au
[#x0030-#x0039] | [#x0660-#x0669] | [#x06F0-#x06F9] | [#x0966-#x096F] |
[#x09E6-#x09EF] | [#x0A66-#x0A6F] | [#x0AE6-#x0AEF] | [#x0B66-#x0B6F] |
[#x0BE7-#x0BEF] | [#x0C66-#x0C6F] | [#x0CE6-#x0CEF] | [#x0D66-#x0D6F] |
[#x0E50-#x0E59] | [#x0ED0-#x0ED9] | [#x0F20-#x0F29]u}
#x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | #x0E46 | #x0EC6 | #x3005 |
#[#x3031-#x3035] | [#x309D-#x309E] | [#x30FC-#x30FE]u | u.u-u_u#x([\d|A-F]{4,4})u'\[#x([\d|A-F]{4,4})-#x([\d|A-F]{4,4})\]cC`sg|jdD]}|j^q}g}x|D]}t}xttfD]}|j|}|dk	rN|jg|jD]}t	|^qt
|ddkr|dd|dRBRIR7RERVRSRU(((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyR*s"		
						(!t
__future__RRRRZR5t	constantsRtbaseChartideographictcombiningCharactertdigittextenderR"tletterR8RMR[RRRRR$RRR#R
R RLRJRCtobjectR*(((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_ihatexml.pyts20							_vendor/html5lib/__init__.pyc000064400000002112152527136320012176 0ustar00
abc@`sdZddlmZmZmZddlmZmZmZddl	m
Z
ddlmZddl
mZdd	d
ddd
gZdZdS(uM
HTML parsing library based on the WHATWG "HTML5"
specification. The parser is designed to be compatible with existing
HTML found in the wild and implements well-defined error recovery that
is largely compatible with modern desktop web browsers.

Example usage:

import html5lib
f = open("my_document.html")
tree = html5lib.parse(f)
i(tabsolute_importtdivisiontunicode_literalsi(t
HTMLParsertparset
parseFragment(tgetTreeBuilder(t
getTreeWalker(t	serializeu
HTMLParseruparseu
parseFragmentugetTreeBuilderu
getTreeWalkeru	serializeu1.0b10N(t__doc__t
__future__RRRthtml5parserRRRttreebuildersRttreewalkersRt
serializerRt__all__t__version__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/__init__.pyts_vendor/html5lib/serializer.py000064400000033541152527136320012457 0ustar00from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type

import re

from codecs import register_error, xmlcharrefreplace_errors

from .constants import voidElements, booleanAttributes, spaceCharacters
from .constants import rcdataElements, entities, xmlEntities
from . import treewalkers, _utils
from xml.sax.saxutils import escape

_quoteAttributeSpecChars = "".join(spaceCharacters) + "\"'=<>`"
_quoteAttributeSpec = re.compile("[" + _quoteAttributeSpecChars + "]")
_quoteAttributeLegacy = re.compile("[" + _quoteAttributeSpecChars +
                                   "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n"
                                   "\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15"
                                   "\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
                                   "\x20\x2f\x60\xa0\u1680\u180e\u180f\u2000"
                                   "\u2001\u2002\u2003\u2004\u2005\u2006\u2007"
                                   "\u2008\u2009\u200a\u2028\u2029\u202f\u205f"
                                   "\u3000]")


_encode_entity_map = {}
_is_ucs4 = len("\U0010FFFF") == 1
for k, v in list(entities.items()):
    # skip multi-character entities
    if ((_is_ucs4 and len(v) > 1) or
            (not _is_ucs4 and len(v) > 2)):
        continue
    if v != "&":
        if len(v) == 2:
            v = _utils.surrogatePairToCodepoint(v)
        else:
            v = ord(v)
        if v not in _encode_entity_map or k.islower():
            # prefer < over < and similarly for &, >, etc.
            _encode_entity_map[v] = k


def htmlentityreplace_errors(exc):
    if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)):
        res = []
        codepoints = []
        skip = False
        for i, c in enumerate(exc.object[exc.start:exc.end]):
            if skip:
                skip = False
                continue
            index = i + exc.start
            if _utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]):
                codepoint = _utils.surrogatePairToCodepoint(exc.object[index:index + 2])
                skip = True
            else:
                codepoint = ord(c)
            codepoints.append(codepoint)
        for cp in codepoints:
            e = _encode_entity_map.get(cp)
            if e:
                res.append("&")
                res.append(e)
                if not e.endswith(";"):
                    res.append(";")
            else:
                res.append("&#x%s;" % (hex(cp)[2:]))
        return ("".join(res), exc.end)
    else:
        return xmlcharrefreplace_errors(exc)

register_error("htmlentityreplace", htmlentityreplace_errors)


def serialize(input, tree="etree", encoding=None, **serializer_opts):
    # XXX: Should we cache this?
    walker = treewalkers.getTreeWalker(tree)
    s = HTMLSerializer(**serializer_opts)
    return s.render(walker(input), encoding)


class HTMLSerializer(object):

    # attribute quoting options
    quote_attr_values = "legacy"  # be secure by default
    quote_char = '"'
    use_best_quote_char = True

    # tag syntax options
    omit_optional_tags = True
    minimize_boolean_attributes = True
    use_trailing_solidus = False
    space_before_trailing_solidus = True

    # escaping options
    escape_lt_in_attrs = False
    escape_rcdata = False
    resolve_entities = True

    # miscellaneous options
    alphabetical_attributes = False
    inject_meta_charset = True
    strip_whitespace = False
    sanitize = False

    options = ("quote_attr_values", "quote_char", "use_best_quote_char",
               "omit_optional_tags", "minimize_boolean_attributes",
               "use_trailing_solidus", "space_before_trailing_solidus",
               "escape_lt_in_attrs", "escape_rcdata", "resolve_entities",
               "alphabetical_attributes", "inject_meta_charset",
               "strip_whitespace", "sanitize")

    def __init__(self, **kwargs):
        """Initialize HTMLSerializer.

        Keyword options (default given first unless specified) include:

        inject_meta_charset=True|False
          Whether it insert a meta element to define the character set of the
          document.
        quote_attr_values="legacy"|"spec"|"always"
          Whether to quote attribute values that don't require quoting
          per legacy browser behaviour, when required by the standard, or always.
        quote_char=u'"'|u"'"
          Use given quote character for attribute quoting. Default is to
          use double quote unless attribute value contains a double quote,
          in which case single quotes are used instead.
        escape_lt_in_attrs=False|True
          Whether to escape < in attribute values.
        escape_rcdata=False|True
          Whether to escape characters that need to be escaped within normal
          elements within rcdata elements such as style.
        resolve_entities=True|False
          Whether to resolve named character entities that appear in the
          source tree. The XML predefined entities < > & " '
          are unaffected by this setting.
        strip_whitespace=False|True
          Whether to remove semantically meaningless whitespace. (This
          compresses all whitespace to a single space except within pre.)
        minimize_boolean_attributes=True|False
          Shortens boolean attributes to give just the attribute value,
          for example  becomes .
        use_trailing_solidus=False|True
          Includes a close-tag slash at the end of the start tag of void
          elements (empty elements whose end tag is forbidden). E.g. 
. space_before_trailing_solidus=True|False Places a space immediately before the closing slash in a tag using a trailing solidus. E.g.
. Requires use_trailing_solidus. sanitize=False|True Strip all unsafe or unknown constructs from output. See `html5lib user documentation`_ omit_optional_tags=True|False Omit start/end tags that are optional. alphabetical_attributes=False|True Reorder attributes to be in alphabetical order. .. _html5lib user documentation: http://code.google.com/p/html5lib/wiki/UserDocumentation """ unexpected_args = frozenset(kwargs) - frozenset(self.options) if len(unexpected_args) > 0: raise TypeError("__init__() got an unexpected keyword argument '%s'" % next(iter(unexpected_args))) if 'quote_char' in kwargs: self.use_best_quote_char = False for attr in self.options: setattr(self, attr, kwargs.get(attr, getattr(self, attr))) self.errors = [] self.strict = False def encode(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, "htmlentityreplace") else: return string def encodeStrict(self, string): assert(isinstance(string, text_type)) if self.encoding: return string.encode(self.encoding, "strict") else: return string def serialize(self, treewalker, encoding=None): # pylint:disable=too-many-nested-blocks self.encoding = encoding in_cdata = False self.errors = [] if encoding and self.inject_meta_charset: from .filters.inject_meta_charset import Filter treewalker = Filter(treewalker, encoding) # Alphabetical attributes is here under the assumption that none of # the later filters add or change order of attributes; it needs to be # before the sanitizer so escaped elements come out correctly if self.alphabetical_attributes: from .filters.alphabeticalattributes import Filter treewalker = Filter(treewalker) # WhitespaceFilter should be used before OptionalTagFilter # for maximum efficiently of this latter filter if self.strip_whitespace: from .filters.whitespace import Filter treewalker = Filter(treewalker) if self.sanitize: from .filters.sanitizer import Filter treewalker = Filter(treewalker) if self.omit_optional_tags: from .filters.optionaltags import Filter treewalker = Filter(treewalker) for token in treewalker: type = token["type"] if type == "Doctype": doctype = "= 0: if token["systemId"].find("'") >= 0: self.serializeError("System identifer contains both single and double quote characters") quote_char = "'" else: quote_char = '"' doctype += " %s%s%s" % (quote_char, token["systemId"], quote_char) doctype += ">" yield self.encodeStrict(doctype) elif type in ("Characters", "SpaceCharacters"): if type == "SpaceCharacters" or in_cdata: if in_cdata and token["data"].find("= 0: self.serializeError("Unexpected ") elif type == "EndTag": name = token["name"] if name in rcdataElements: in_cdata = False elif in_cdata: self.serializeError("Unexpected child element of a CDATA element") yield self.encodeStrict("" % name) elif type == "Comment": data = token["data"] if data.find("--") >= 0: self.serializeError("Comment contains --") yield self.encodeStrict("" % token["data"]) elif type == "Entity": name = token["name"] key = name + ";" if key not in entities: self.serializeError("Entity %s not recognized" % name) if self.resolve_entities and key not in xmlEntities: data = entities[key] else: data = "&%s;" % name yield self.encodeStrict(data) else: self.serializeError(token["data"]) def render(self, treewalker, encoding=None): if encoding: return b"".join(list(self.serialize(treewalker, encoding))) else: return "".join(list(self.serialize(treewalker))) def serializeError(self, data="XXX ERROR MESSAGE NEEDED"): # XXX The idea is to make data mandatory. self.errors.append(data) if self.strict: raise SerializeError class SerializeError(Exception): """Error in serialized tree""" pass _vendor/html5lib/_tokenizer.pyc000064400000151156152527136320012625 0ustar00 abc@`sddlmZmZmZddlmZddlmZddl m Z ddl m Z ddl m Z m Z ddl mZmZmZdd l mZmZdd l mZdd lmZdd lmZee Zd efdYZdS(i(tabsolute_importtdivisiontunicode_literals(tunichr(tdequei(tspaceCharacters(tentities(t asciiLetterstasciiUpper2Lower(tdigitst hexDigitstEOF(t tokenTypest tagTokenTypes(treplacementCharacters(tHTMLInputStream(tTriet HTMLTokenizercB`seZdZdJdZdZdZdJedZdZ dZ dZ dZ d Z d Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#d Z$d!Z%d"Z&d#Z'd$Z(d%Z)d&Z*d'Z+d(Z,d)Z-d*Z.d+Z/d,Z0d-Z1d.Z2d/Z3d0Z4d1Z5d2Z6d3Z7d4Z8d5Z9d6Z:d7Z;d8Z<d9Z=d:Z>d;Z?d<Z@d=ZAd>ZBd?ZCd@ZDdAZEdBZFdCZGdDZHdEZIdFZJdGZKdHZLdIZMRS(Ku  This class takes care of tokenizing HTML. * self.currentToken Holds the token that is currently being processed. * self.state Holds a reference to the method to be invoked... XXX * self.stream Points to HTMLInputStream object. cK`sbt|||_||_t|_g|_|j|_t|_d|_ t t |j dS(N(RtstreamtparsertFalset escapeFlagt lastFourCharst dataStatetstatetescapetNonet currentTokentsuperRt__init__(tselfRRtkwargs((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyR"s      cc`s}tg|_xg|jrxx6|jjrVitdd6|jjjdd6Vq!Wx|jrt|jjVqZWqWdS(u This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested. u ParseErrorutypeiudataN(Rt tokenQueueRRterrorsR tpoptpopleft(R((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyt__iter__1s * c %C`st}d}|r!t}d}ng}|jj}x8||krp|tk rp|j||jj}q9Wtdj||}|tkrt|}|j jit dd6dd6i|d6d 6nd |kod kns|d kr3d }|j jit dd6dd6i|d6d 6nrd|koJdknsd|kofdknsd|kodknsd|kodkns|t ddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d g#krQ|j jit dd6dd6i|d6d 6nyt |}WnAt k r|d8}t d |d?Bt d9|d:@B}nX|d;kr|j jit dd6d<d6|jj|n|S(=uThis function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked. i iuu ParseErrorutypeu$illegal-codepoint-for-numeric-entityudatau charAsIntudatavarsiiiu�iiiiiiiii iiiiiiiiiiiiiiiiiii i i i i i i i i i iiiiiiiiu;u numeric-entity-without-semicolon(R R RtcharR tappendtinttjoinRR R t frozensettchrt ValueErrortunget( RtisHextallowedtradixt charStacktct charAsIntR%tv((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pytconsumeNumberEntityAs`              *  c C`sd}|jjg}|dtks]|dtddfks]|dk rt||dkrt|jj|dn|ddkrpt}|j|jj|ddkrt}|j|jjn|r|dt ks| r"|dt kr"|jj|d|j |}q7|j jit dd 6d d 6|jj|jdd j|}nxF|dtk rtjd j|sPn|j|jjqsWy,tjd j|d }t|}Wntk rd}nX|dk r|dd kr@|j jit dd 6dd 6n|dd kr|r||tks||t ks||dkr|jj|jdd j|}q7t|}|jj|j|d j||7}nK|j jit dd 6dd 6|jj|jdd j|}|r[|jd ddc|7u ParseErroru'expected-tag-name-but-got-right-bracketu Charactersu<>u?u'expected-tag-name-but-got-question-markuexpected-tag-nameu<(RR%tmarkupDeclarationOpenStateRtcloseTagOpenStateRR RRt tagNameStateR R&RR,tbogusCommentStateR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRHis6      "   " cC`s?|jj}|tkrSitdd6|d6gd6td6|_|j|_n|dkr|jj itdd6dd6|j |_n|t kr|jj itdd6d d6|jj itd d6d d6|j |_nL|jj itdd6d d6i|d6d 6|jj ||j |_tS(NuEndTagutypeunameudatau selfClosingu>u ParseErroru*expected-closing-tag-but-got-right-bracketu expected-closing-tag-but-got-eofu Charactersuu ParseErrorutypeueof-in-tag-nameudatau/uuinvalid-codepointunameu�(RR%RtbeforeAttributeNameStateRRFR R R&R RtselfClosingStartTagStateRR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRVs"        cC`su|jj}|dkr3d|_|j|_n>|jjitdd6dd6|jj||j |_t S(Nu/uu Charactersutypeu|jjitdd6dd6|jj ||j |_t S(Nu Charactersutypeuu Charactersu|jjitdd6dd6|jj||j |_t S(Nu/uu Charactersutypeu|jjitdd6dd6|jj ||j |_t S(Nu Charactersutypeuu Charactersu|jjitdd6dd6|jj ||j |_t S( Nu/uu!u Charactersutypeu|jjitdd6dd6|jj ||j |_t S(Nu Charactersutypeuu Charactersuuu ParseErroruinvalid-codepointu�( RR%R R&R RgRRRRhR RR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRes& %  "    " cC`s|jj}|dkr3d|_|j|_n|tkr}|jjitdd6d|d6||_|j |_n>|jjitdd6dd6|jj ||j |_t S(Nu/uu Charactersutypeu|jjitdd6dd6|jj ||j |_t S(Nu Charactersutypeuu Charactersuu Charactersutypeudatauscript(u/u>(RR%RR)R R&R RZR]tscriptDataDoubleEscapedStateRRhRR,R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRjs" " cC`s?|jj}|dkrL|jjitdd6dd6|j|_n|dkr|jjitdd6dd6|j|_n|dkr|jjitdd6dd6|jjitdd6d d6n_|tkr|jjitdd6d d6|j |_n"|jjitdd6|d6t S( Nu-u Charactersutypeudatauuu ParseErroruinvalid-codepointu�ueof-in-script-in-script( RR%R R&R RnRRRRlR RR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRos, % " "     " cC`su|jj}|dkrU|jjitdd6dd6d|_|j|_n|jj||j |_t S(Nu/u Charactersutypeudatau( RR%R R&R RZtscriptDataDoubleEscapeEndStateRR,RlR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRn0s "  cC`s|jj}|ttdBkrz|jjitdd6|d6|jjdkrk|j |_ q|j |_ n\|t kr|jjitdd6|d6|j|7_n|jj ||j |_ tS(Nu/u>u Charactersutypeudatauscript(u/u>(RR%RR)R R&R RZR]RhRRlRR,R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRp;s" " cC`s|jj}|tkr1|jjttnz|tkrf|jdj|dg|j|_ nE|dkr|j n,|dkr|j |_ n|dkr|j jit d d 6d d6|jdj|dg|j|_ n|d krH|j jit d d 6d d6|jdjddg|j|_ nc|tkr|j jit d d 6dd6|j|_ n&|jdj|dg|j|_ tS(Nudatauu>u/u'u"u=uu/uu ParseErrorutypeuinvalid-codepointu�u'u"uudatauu/uu ParseErrorutypeuinvalid-codepointu�u'u"uu ParseErrorutypeu.expected-attribute-value-but-got-right-bracketudatauuinvalid-codepointiiu�u=u               cC`s|jj}|dkr*|j|_n|dkrF|jdn|dkr|jjitdd6dd6|jddd cd 7u"u'u=uu"u'u=u|jj it dd6dd6|jj ||j|_t S(Nu>u/u ParseErrorutypeu$unexpected-EOF-after-attribute-valueudatau*unexpected-character-after-attribute-value(RR%RRXRRFRYR R R&R R,RR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyR{ s"        cC`s|jj}|dkr5t|jd<|jn|tkr|jjitdd6dd6|jj ||j |_ n>|jjitdd6dd6|jj ||j |_ tS(Nu>u selfClosingu ParseErrorutypeu#unexpected-EOF-after-solidus-in-tagudatau)unexpected-character-after-solidus-in-tag( RR%R5RRFR R R&R R,RRRX(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRY4s       cC`sc|jjd}|jdd}|jjitdd6|d6|jj|j|_t S(Nu>uu�uCommentutypeudata( RRItreplaceR R&R R%RRR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRWFs   cC`sB|jjg}|ddkrv|j|jj|ddkritdd6dd6|_|j|_tSnw|ddkr(t}xPdd d!d"d#d$fD]6}|j|jj|d|krt}PqqW|ritdd6dd6dd6dd6td6|_|j |_tSn|ddkr|j dk r|j j j r|j j j dj|j j jkrt}xPd dddddgD]6}|j|jj|d|krt}PqqW|r|j|_tSn|jjitdd6dd6x |r1|jj|jqW|j|_tS(%Niu-uCommentutypeuudatauduDuouOucuCutuTuyuYupuPueuEuDoctypeunameupublicIdusystemIducorrectu[uAu ParseErroruexpected-dashes-or-doctype(uduD(uouO(ucuC(utuT(uyuY(upuP(ueuE(RR%R&R RtcommentStartStateRR5RRt doctypeStateRttreet openElementst namespacetdefaultNamespacetcdataSectionStateR R,R"RW(RR0tmatchedtexpected((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRTUsR    %    cC`s1|jj}|dkr*|j|_n|dkrn|jjitdd6dd6|jdcd7uincorrect-commentueof-in-comment( RR%tcommentStartDashStateRR R&R RRR t commentStateR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyR}s(        cC`s5|jj}|dkr*|j|_n|dkrn|jjitdd6dd6|jdcd7uincorrect-commentueof-in-comment( RR%tcommentEndStateRR R&R RRR RR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs(        cC`s|jj}|dkr*|j|_n|dkrn|jjitdd6dd6|jdcd7uu ParseErrorutypeuinvalid-codepointudatau--�u!u,unexpected-bang-after-double-dash-in-commentu-u,unexpected-dash-after-double-dash-in-commentueof-in-comment-double-dashuunexpected-char-in-commentu--( RR%R R&RRRR RtcommentEndBangStateR R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs6           cC`s2|jj}|dkr=|jj|j|j|_n|dkrk|jdcd7<|j|_n|dkr|jjitdd6dd6|jdcd 7<|j |_ns|t kr |jjitdd6d d6|jj|j|j|_n#|jdcd|7<|j |_t S( Nu>u-udatau--!uu ParseErrorutypeuinvalid-codepointu--!�ueof-in-comment-end-bang-state( RR%R R&RRRRR RR R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs(       cC`s|jj}|tkr*|j|_n|tkr|jjitdd6dd6t |j d<|jj|j |j |_n>|jjitdd6dd6|jj ||j|_t S(Nu ParseErrorutypeu!expected-doctype-name-but-got-eofudataucorrectuneed-space-after-doctype(RR%RtbeforeDoctypeNameStateRR R R&R RRRR,R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyR~ s      cC`s?|jj}|tkrn|dkr{|jjitdd6dd6t|jd<|jj|j|j|_ n|dkr|jjitdd6dd6d |jd <|j |_ nv|t kr"|jjitdd6d d6t|jd<|jj|j|j|_ n||jd <|j |_ t S( Nu>u ParseErrorutypeu+expected-doctype-name-but-got-right-bracketudataucorrectuuinvalid-codepointu�unameu!expected-doctype-name-but-got-eof( RR%RR R&R RRRRtdoctypeNameStateR R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs.            cC`ss|jj}|tkrG|jdjt|jd<|j|_n(|dkr|jdjt|jd<|jj |j|j |_n|dkr|jj it dd6dd6|jdcd7<|j |_n|t kr\|jj it dd6d d6t|jd <|jdjt|jd<|jj |j|j |_n|jdc|7uu ParseErrorutypeuinvalid-codepointudatau�ueof-in-doctype-nameucorrect(RR%RRRDRtafterDoctypeNameStateRR R&RR RR RR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyR6s,       cC`s|jj}|tkrn|dkrL|jj|j|j|_n|tkrt |jd<|jj ||jjit dd6dd6|jj|j|j|_n9|dkr)t }xBd d!d"d#d$fD]+}|jj}||krt }PqqW|r|j |_t Snp|d%krt }xBd&d'd(d)d*fD]+}|jj}||krQt }PqQqQW|r|j|_t Sn|jj ||jjit dd6dd6i|d6d6t |jd<|j|_t S(+Nu>ucorrectu ParseErrorutypeueof-in-doctypeudataupuPuuuUubuBuluLuiuIucuCusuSuyuYutuTueuEumuMu*expected-space-or-right-bracket-in-doctypeudatavars(upuP(uuuU(ubuB(uluL(uiuI(ucuC(usuS(uyuY(usuS(utuT(ueuE(umuM(RR%RR R&RRRR RR,R R5tafterDoctypePublicKeywordStatetafterDoctypeSystemKeywordStatetbogusDoctypeState(RRJRR((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyROsT               cC`s|jj}|tkr*|j|_n|d krw|jjitdd6dd6|jj||j|_ny|t kr|jjitdd6dd6t |j d<|jj|j |j |_n|jj||j|_t S( Nu'u"u ParseErrorutypeuunexpected-char-in-doctypeudataueof-in-doctypeucorrect(u'u"(RR%Rt"beforeDoctypePublicIdentifierStateRR R&R R,R RRRR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs"       cC`sg|jj}|tkrnE|dkrFd|jd<|j|_n|dkrnd|jd<|j|_n|dkr|jjit dd6dd 6t |jd <|jj|j|j |_n|t kr(|jjit dd6d d 6t |jd <|jj|j|j |_n;|jjit dd6d d 6t |jd <|j |_tS( Nu"uupublicIdu'u>u ParseErrorutypeuunexpected-end-of-doctypeudataucorrectueof-in-doctypeuunexpected-char-in-doctype(RR%RRt(doctypePublicIdentifierDoubleQuotedStateRt(doctypePublicIdentifierSingleQuotedStateR R&R RRR RR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs4              cC`s?|jj}|dkr*|j|_n|dkrn|jjitdd6dd6|jdcd7uunexpected-end-of-doctypeucorrectueof-in-doctype( RR%t!afterDoctypePublicIdentifierStateRR R&R RRRR R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs*         cC`s?|jj}|dkr*|j|_n|dkrn|jjitdd6dd6|jdcd7uunexpected-end-of-doctypeucorrectueof-in-doctype( RR%RRR R&R RRRR R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs*         cC`s|jj}|tkr*|j|_nZ|dkrX|jj|j|j|_n,|dkr|jjit dd6dd6d|jd<|j |_n|d kr|jjit dd6dd6d|jd<|j |_n|t krI|jjit dd6d d6t |jd <|jj|j|j|_n;|jjit dd6dd6t |jd <|j|_tS( Nu>u"u ParseErrorutypeuunexpected-char-in-doctypeudatauusystemIdu'ueof-in-doctypeucorrect(RR%Rt-betweenDoctypePublicAndSystemIdentifiersStateRR R&RRR t(doctypeSystemIdentifierDoubleQuotedStatet(doctypeSystemIdentifierSingleQuotedStateR RRR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs6              cC`s8|jj}|tkrn|dkrL|jj|j|j|_n|dkrtd|jd<|j|_n|dkrd|jd<|j |_n|t kr|jjit dd6dd 6t |jd <|jj|j|j|_n;|jjit dd6d d 6t |jd <|j |_tS( Nu>u"uusystemIdu'u ParseErrorutypeueof-in-doctypeudataucorrectuunexpected-char-in-doctype(RR%RR R&RRRRRR R RRR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs.            cC`s|jj}|tkr*|j|_n|d krw|jjitdd6dd6|jj||j|_ny|t kr|jjitdd6dd6t |j d<|jj|j |j |_n|jj||j|_t S( Nu'u"u ParseErrorutypeuunexpected-char-in-doctypeudataueof-in-doctypeucorrect(u'u"(RR%Rt"beforeDoctypeSystemIdentifierStateRR R&R R,R RRRR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs"       cC`sg|jj}|tkrnE|dkrFd|jd<|j|_n|dkrnd|jd<|j|_n|dkr|jjit dd6dd 6t |jd <|jj|j|j |_n|t kr(|jjit dd6d d 6t |jd <|jj|j|j |_n;|jjit dd6dd 6t |jd <|j |_tS( Nu"uusystemIdu'u>u ParseErrorutypeuunexpected-char-in-doctypeudataucorrectueof-in-doctype(RR%RRRRRR R&R RRR RR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyR/s4              cC`s?|jj}|dkr*|j|_n|dkrn|jjitdd6dd6|jdcd7uunexpected-end-of-doctypeucorrectueof-in-doctype( RR%t!afterDoctypeSystemIdentifierStateRR R&R RRRR R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRLs*         cC`s?|jj}|dkr*|j|_n|dkrn|jjitdd6dd6|jdcd7uunexpected-end-of-doctypeucorrectueof-in-doctype( RR%RRR R&R RRRR R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRds*         cC`s|jj}|tkrn|dkrL|jj|j|j|_n|tkr|jjit dd6dd6t |jd<|jj|j|j|_n.|jjit dd6dd6|j |_t S(Nu>u ParseErrorutypeueof-in-doctypeudataucorrectuunexpected-char-in-doctype( RR%RR R&RRRR R RRR5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyR|s        cC`s|jj}|dkr=|jj|j|j|_n>|tkr{|jj||jj|j|j|_nt S(Nu>( RR%R R&RRRR R,R5(RRJ((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs  cC`s`g}xtr|j|jjd|j|jjd|jj}|tkr`Pq |dksrt|dddkr|dd |diiu]]uuiu ParseErrorutypeuinvalid-codepointudatau�u Characters(R5R&RRIR%R tAssertionErrorR(tcounttrangeR R R|RR(RRJR%t nullCountRw((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs0    N(Nt__name__t __module__t__doc__RRR$R4RRBRCRFRRGRNRLRPRRRSRHRURVRMR[R\ROR_R`RQRaRcRbRdRhRfReRgRiRkRjRlRmRoRnRpRXRqRsRrRxRzRyR{RYRWRTR}RRRRRR~RRRRRRRRRRRRRRRR(((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyRs    HP          #                  6 "       -          3            N(t __future__RRRtpip._vendor.sixRR*t collectionsRt constantsRRRRR R R R R Rt _inputstreamRt_trieRR6tobjectR(((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_tokenizer.pyts _vendor/html5lib/constants.pyo000064400000242000152527136320012471 0ustar00 abcP@`sNddlmZmZmZddlZdZidd6dd6dd6d d 6d d 6d d6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d!d"6d#d$6d%d&6d'd(6d)d*6d+d,6d-d.6d/d06d1d26d3d46d5d66d7d86d9d:6d;d<6d=d>6d?d@6dAdB6dCdD6dEdF6dGdH6dIdJ6dKdL6dMdN6dOdP6dQdR6dSdT6dUdV6dWdX6dYdZ6d[d\6dUd]6dUd^6d_d`6dadb6dcdd6dedf6dgdh6didj6dkdl6dmdn6dodp6dqdr6dsdt6dudv6dwdx6dydz6d{d|6d}d~6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6Zidd6dd6d d 6d d 6d d6dd6Ze eddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfed dfed dfed d fgZ e edd!fedd"fedd#fedd$fedd%fedd&fedd'fedd(fedd)fedd*fedd+fedd,fedd-fedd.fgZ e edd/feddfedd0fedd1fedd2fedd3fedd4fedd5fedd6fedd7fedd8fedd9feddfedd:fedd;fedd<fedd=fedd>fedd?fedd@feddAfeddBfeddCfeddDfeddEfeddFfeddGfeddHfeddIfeddJfeddKfeddLfeddMfeddNfeddOfeddPfeddQfeddRfeddSfeddfeddTfeddUfeddVfeddWfeddXfeddYfeddZfedd[feddfedd\fedd]fedd^fedd_fedd`feddafeddfeddbfeddcfedddfeddefeddffeddgfeddhfeddifeddjfeddfeddkfeddfeddlfeddmfeddfeddnfedd feddofeddpfeddqfeddrfed dfgNZ e eddsfed dfed dfed d fgZ e eddfeddfeddfeddfeddfgZi>dtdu6dvdw6dxdy6dzd{6d|d}6d~d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6Zidd6Zi d ded fd6d ded fd6d ded fd6d ded fd6d ded fd6d d ed fd6d ded fd6dd3edfd6ddedfd6ddedfd6ddedfd6dd edfd6ZegejD]'\Z\ZZZeefef^q Ze ddddd gZe ddkdmdndogZe ejZe ejZe ejZ e ej!Z!e ej"Z#egejD]$Z$e%e$e%e$j&f^q Z'dZ(e d3d=d dZd]dSd8dVdDddd0d;dWd d gZ)e d dlgZ*e djdgdrdTd_d`dagZ+ie d gd6e dgdj6e dgdV6e ddgd6e ddgd6e ddgdg6e dgd?6e ddgd6e ddddgd=6e dgdS6e dgd\6e dd gdE6e dd d!gd"6e dd gd#6e dd$gd96e dd d%d$ddgdW6e dd d$dgdi6e dd gd&6Z,dZ-e dCdDdEdFdGgZ.idHdI6dHdJ6dKdL6dKdM6dNdO6dNdP6dQdR6dSdT6dSdU6dVdW6dXdY6dZd[6dZd\6d]d^6d_d`6dadb6dcdd6dedf6dgdh6didj6didk6dldm6dndo6dpdq6dpdr6dsdt6dsdu6dvdw6dxdy6dzd{6d|d}6d~d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d d 6d d 6dd6dd6dd6dd6dd6dd6dd6dd6dd6d d!6d"d#6d$d%6d&d'6d(d)6d*d+6d,d-6d.d/6d0d16d2d36dd46d5d66d7d86d9d:6d;d<6d;d=6d>d?6d>d@6dAdB6dCdD6dCdE6dFdG6dHdI6dJdK6dLdM6dLdN6dOdP6dQdR6dSdT6dUdV6dWdX6dYdZ6d[d\6d]d^6d_d`6dadb6dcdd6dedf6dgdh6didj6didk6dldm6dndo6dpdq6drds6dtdu6dvdw6dxdy6dzd{6d|d}6d|d~6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d d 6d d 6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d!d"6d#d$6d%d&6d'd(6d)d*6d+d,6d-d.6d/d06d1d26d3d46d5d66d7d86d9d:6d;d<6d=d>6d?d@6dAdB6dCdD6dEdF6dGdH6dIdJ6dKdL6dMdN6dOdP6dQdR6dSdT6dUdV6ddW6ddX6dYdZ6d[d\6d]d^6d_d`6dadb6dcdd6dedf6dgdh6didj6dkdl6dmdn6dodp6dqdr6d ds6d dt6ddu6dvdw6dxdy6dzd{6dd|6d}d~6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d d 6d d 6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6dd!6d"d#6d"d$6d%d&6d'd(6d)d*6d+d,6d+d-6d.d/6d0d16d2d36d4d56d6d76d8d96d:d;6d<d=6d>d?6d>d@6dAdB6dAdC6dDdE6dFdG6dFdH6dIdJ6dKdL6dMdN6dOdP6dQdR6dSdT6dUdV6dWdX6dYdZ6d[d\6dd]6d^d_6d`da6dbdc6ddde6dfdg6dhdi6djdk6dldm6ddn6dodp6dqdr6dsdt6dudv6dudw6dxdy6dzd{6d|d}6d~d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d)d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6dd 6d d 6d d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6dd!6d"d#6d$d%6d&d'6dd(6d)d*6d+d,6d-d.6d/d06d1d26d3d46d5d66d7d86d9d:6d;d<6d=d>6d?d@6dAdB6dCdD6dEdF6dGdH6dIdJ6dKdL6dKdM6dNdO6dPdQ6dRdS6dTdU6dVdW6dVdX6dYdZ6d[d\6d]d^6d_d`6d_da6dbdc6ddde6dfdg6dhdi6djdk6dldm6dndo6dpdq6drds6ddt6dudv6dwdx6dydz6d{d|6d}d~6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dgd6dd6dd6dd 6d d 6d d 6d d6dd6dd6dKd6dKdE6dd6dd6dd6dd6dd6dd6d d!6dd"6d#d$6d%d&6d'd(6d)d*6d+d,6d-d.6d/d06d1d26d3d46d5d66d7d86d9d:6d;d<6did=6d>d?6d@dA6dBdC6dAdD6dEdF6dGdH6dIdJ6dKdL6dMdF6dAdN6dIdO6dPdQ6dPdR6dSdT6dUdV6dAdW6ddX6dYdZ6dYd[6d\d]6d\d^6dd_6d`da6dbdc6ddde6dfdg6dhdi6djdk6dldm6dndo6dpdq6dpdr6dhds6dtdu6dddv6dwdx6dydz6d~d{6d~d|6d}d~6dfd6dd6dd6dd6dd6dd6dd6dd6dld6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dvd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d}d6d}d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d d 6d d 6d d6dd6dd6dd6dd6dd6dhd6dd6dd6dd6dd6d d!6djd"6dld#6d$d%6d&d'6d(d)6d*d+6d*d,6dd-6d.d/6dd06dd16d2d36d4d56d6d76d8d96d:d;6d<d=6d>d?6d@dA6dBdC6ddD6dEdF6dGdH6dIdJ6dIdK6dLdM6dNdO6dPdQ6dRdS6ddT6ddU6dVdW6dXdY6dXdZ6dd[6d\d]6d^d_6d`da6d`db6dcdd6dedf6dgdh6didj6dkdl6dmdn6dodp6ddq6drds6dtdu6dvdw6dxdy6dkdz6d{d|6d}d~6dd6dd6dd6dd6dnd6dnd6dd6dd6dd6dd6dd6dd6d?d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d?d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d5d6dd 6dd 6dd 6d d 6d d 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dd 6dd 6d d 6d d! 6d" d# 6d$ d% 6dzd& 6dd' 6dd( 6d5d) 6dd* 6d~d+ 6d, d- 6d. d/ 6d0 d1 6d2 d3 6d4 d5 6d6 d7 6d8 d9 6d: d; 6dd< 6dd= 6dd> 6d? d@ 6dA dB 6dC dD 6ddE 6d dF 6dG dH 6dG dI 6dJ dK 6dL dM 6dN dO 6dP dQ 6dP dR 6dS dT 6dU dV 6dW dX 6dndY 6dZ d[ 6d\ d] 6d^ d_ 6d` da 6d` db 6dc dd 6de df 6dg dh 6di dj 6dk dl 6dm dn 6do dp 6dq dr 6ds dt 6ds du 6ds dv 6dw dx 6dy dz 6d{ d| 6d} d~ 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dN d 6dS d 6d_d 6dc d 6dm d 6d d 6d d 6dd 6d d 6d d 6d d 6d d 6d d 6dd 6d_d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dld 6dcd 6dnd 6dZ d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dzd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dd 6dd 6dd 6dd 6dd 6dd 6d d 6d d 6d d 6d d 6d d 6d d! 6d" d# 6dd$ 6dd% 6d& d' 6d( d) 6dd* 6d+ d, 6d- d. 6d/ d0 6d1 d2 6d3 d4 6d3 d5 6d6 d7 6d6 d8 6d1 d9 6d: d; 6d< d= 6dd> 6d? d@ 6ddA 6dB dC 6dD dE 6ddF 6ddD6dG dH 6dI dJ 6dK dL 6dM dN 6dO dP 6d dQ 6dR dS 6dK dT 6ddU 6d dV 6ddW 6ddX 6dY dZ 6dY d[ 6dd\ 6dd] 6d d^ 6dd_ 6d` da 6d;db 6dc dd 6de df 6dg dh 6di dj 6dk dl 6dk dm 6dn do 6dp dq 6dr ds 6dt du 6dv dw 6dx dy 6dz d{ 6d| d} 6d~ d 6d d 6d d 6d d 6dg d 6d d 6d d 6dd 6d d 6d d 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6dd 6d d 6d d 6d d 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6dd 6dd 6dd 6d d 6d d 6d d 6dOd 6d d 6d d 6d d 6d d 6dd 6d d 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dOd 6d d 6d d 6d d 6d d 6dOd 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6did 6dd 6d d 6d d 6d[d 6d d 6d d 6d d 6d d 6dd 6d d 6d'd 6d d 6d'd 6d! d" 6d# d$ 6d# d% 6d)d& 6d+d' 6d( d) 6d* d+ 6d| d, 6d- d. 6d/ d0 6d1 d2 6d3 d4 6d5 d6 6d7 d8 6d9 d: 6d; d< 6d= d> 6d? d@ 6dA dB 6dC dD 6dE dF 6dG dH 6dI dJ 6dK dL 6dM dN 6d/dO 6dA dP 6dQ dR 6dS dT 6d6dU 6dydV 6dW dX 6dY dZ 6d[ d\ 6d] d^ 6d)d_ 6d3 d` 6d&da 6dSdb 6dc dd 6d;de 6d-df 6ddg 6de dh 6di dj 6dYdk 6d] dl 6d[dm 6dadn 6dado 6dp dq 6dr ds 6dt du 6dv dw 6dx dy 6dz d{ 6d! d| 6d} d~ 6dYd 6d d 6d]d 6dcd 6d d 6d9d 6d d 6d]d 6d d 6d&d 6dSd 6d d 6d d 6d d 6dd 6dc d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d1d 6dmd 6dod 6d d 6dqd 6d- d 6d d 6d d 6d d 6d d 6d d 6d d 6ddd 6d d 6d d 6dd 6d d 6d d 6d-d 6d, d 6dd 6d d 6d d 6d d 6d d 6d d 6d}d 6dcd 6d d 6d d 6dC d 6d8d 6d d 6d d 6dd 6ddC6d d 6d d 6d} d 6di d 6d d 6d d 6d d 6d d 6d d 6dId 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dd 6dd 6d2d 6dAd 6dd 6d d 6d d 6d d 6d d 6d#d 6d d 6d d 6d d 6d d 6dd 6dUd 6d d 6dd 6dd! 6d" d# 6dd$ 6d d% 6d& d' 6d( d) 6dn d* 6dd+ 6d, d- 6d. d/ 6dd0 6d1 d2 6dd3 6d4 d5 6d6 d7 6d6 d8 6d9 d: 6d; d< 6dd= 6d> d? 6d@ dA 6dB dC 6dD dE 6ddF 6dG dH 6dI dJ 6dK dL 6ddM 6dN dO 6dP dQ 6ddR 6dS dT 6dU dV 6dW dX 6ddY 6dZ d[ 6dZ d\ 6dd] 6dd^ 6dd_ 6dd` 6dda 6db dc 6dd de 6df dg 6ddh 6di dj 6dk dl 6dm dn 6do dp 6ddq 6dr ds 6dt du 6ddv 6ddw 6dx dy 6ddz 6d{ d| 6dd} 6dd~ 6dd 6d d 6dd 6dd 6dd 6dd 6dd 6dd 6dd 6dd 6dd 6d@ d 6d d 6d d 6dd 6d d 6d d 6dd 6d d 6d> d 6d d 6d d 6d d 6dd 6d d 6d d 6dd 6d d 6dd 6dd 6dd 6dd 6dd 6dd 6dd 6dd 6d d 6d d 6d d 6dd 6d d 6d d 6dd 6d d 6d d 6dd 6dd 6d d 6d d 6dd 6dd 6d d 6d d 6d d 6dd 6dd 6dd 6dd 6dd 6dG d 6d d 6d d 6d d 6d d 6dd 6dd 6dd 6dd 6dd 6d d 6dd 6dd 6d d 6dd 6dd 6dd 6dd 6dd 6dd 6d d 6d d 6dd 6dd 6dd 6d d 6dd 6dd 6d d 6d d 6d d 6dd 6d d 6d d 6dd 6d d 6d d 6dd 6dd 6dd 6dd 6dd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6d! d" 6d# d$ 6d% d& 6d' d( 6dd) 6dd* 6d+ d, 6drd- 6d. d/ 6d. d0 6dtd1 6dvd2 6d3 d4 6d3 d5 6d6 d7 6dxd8 6d9 d: 6d; d< 6dd= 6d> d? 6d@ dA 6dB dC 6dD dE 6dF dG 6dH dI 6dH dJ 6dK dL 6dM dN 6d0dO 6ddP 6dmdQ 6dR dS 6dT dU 6dIdV 6dW dX 6dY dZ 6d[ d\ 6d] d^ 6d_ d` 6dda 6db dc 6dd de 6df dg 6ddh 6di dj 6dodk 6dl dm 6dn do 6dn dp 6dq dr 6dq ds 6dt du 6dt dv 6dw dx 6dy dz 6d{ d| 6d} d~ 6dn d 6d d 6d d 6d d 6d d 6d d 6dd 6d d 6d d 6d d 6d d 6dd 6d d 6d d 6dd 6d d 6d d 6dQd 6d d 6d d 6d d 6d d 6d}d 6d d 6d d 6d d 6d d 6dd 6d d 6d d 6d d 6d d 6dg d 6d d 6dg d 6d d 6d d 6dd 6d d 6d" d 6d d 6d d 6d[d 6d[d 6d d 6d d 6d[d 6d d 6d d 6d d 6d d 6dbd 6d d 6d d 6dfd 6ddd 6dbd 6d d 6dfd 6ddd 6d d 6d d 6d d 6dhd 6d d 6d^d 6d d 6d d 6d d 6dld 6d d 6d d 6d d 6dod 6dod 6dhd 6d d 6d d 6d d 6d d 6d d 6d d 6d d 6dd6dd6dd6dd6dd6d d 6dud 6dudG6dd 6dd 6d d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6dd!6dd"6d#d$6dd%6d&d'6d(d)6d*d+6d~ d,6d d-6d.d/6d0d16d2d36d4d56d6d76d8d96dzd:6dd;6d<d=6d>d?6d@dA6dBdC6dDdE6dFdG6dHdI6dJdK6ddL6d>dM6dNdO6dPdQ6dRdS6ddT6ddU6dVdW6ddX6ddY6ddZ6dd[6d\d]6dd^6dd_6d`da6ddb6dcdd6d,de6ddf6dgdh6didj6dkdl6ddm6d2dn6d,do6ddp6ddq6dadr6dsdt6d4du6dvdw6dxdy6d dz6dd{6dad|6d}d~6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dsd6dd6dd6dd6d@d6dd6dd6dvd6dd6dd6dd6dd6dd6dd6dd6dd6d d6d d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d$ d6dd6dd6dt d6dzd6dzd6dd6dd6dd6dd6dvd6dvd6dd6dd6d d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6d;d6dd6d=d6d=d6dd6dd6dd6dd6dd6dd6dd6d)d6dvd6dd6dd6dd 6d d 6d d 6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d!d"6dd#6d$d%6dd&6dd'6dd(6dd)6dd*6dd+6dd,6dd-6dd.6dd/6dvd06dvd16dd26d3d46dvd56d d66dd76d8d96dd:6d d;6d d<6d d=6d>d?6d@dA6dBdC6d dD6dEdF6dGdH6dIdJ6dKdL6dMdN6dOdP6d>dQ6d dR6d@dS6dKdT6dIdU6dVdW6dXdY6dZd[6d d\6dd]6dd^6dd_6dd`6dda6ddb6ddc6ddd6dedf6dgdh6dgdi6djdk6djdl6dmdn6dmdo6ddp6dqdr6dsdt6dudv6ddw6dxdy6dzd{6d|d}6d~d6dd6dd6dd6dd6dd6dd6dqd6dd6dd6dd6dd6dd6dd6dv d6dxd6dxd6dd6dd6dd6dd6dd6dMd6dd6dd6dd6dEd6dd6dd6d3d6d3d6dd6dd6dd6dAd6d;d6d9d6dAd6d;d6dd6dd6dd6dd6dd6dd6dd6dd6d d6d{ d6d0d6dd6dd6dd6dd6dd6dd6d"d6dd6d: d6d d6dId6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dwd6dd6d{d6d d 6d d 6d d6d d6dOd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd 6d!d"6dd#6dyd$6dOd%6dd&6dnd'6d(d)6dd*6d(d+6d,d-6d.d/6d.d06d1d26d3d46d5d66d7d86d9d:6d;d<6dd=6dd>6d,d?6d@dA6d@dB6dCdD6ddE6dFdG6dHdI6ddJ6dKdL6d dM6d dN6ds dO6d dP6d dQ6dodR6dydS6dkdT6ddU6dVdW6dXdY6dZd[6d\d]6dd^6dEd_6dd`6dadb6ddc6di dd6dedf6dgdh6didj6ddk6ddl6dmdn6dEdo6ddp6ddq6drds6dodt6ddu6dvdw6dXdx6dVdy6d\dz6dZd{6d|d}6d~d6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dld6dd6dd6d d6dod6dd6d d6dmd6d d6dd6dd6dd6dd6dd6dd6dqd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6Z/i"dd6d d6d d6dd6d d6d d6dyd6dn d6dd6dd6did6d d6dd6d d6dd6dd6dd6dd6dd6d8d6dd6d6d6dd6d*d6do d6d d6dd6d"d6dd6dd6d@ d6dd6dd6dd6Z0idd6dd6d d 6d d 6d d6dd6dd6dd6Z1e e1d e1de1dgZ2egejD]\Z3Z4e4e3f^qDNZ5de5d' instead.u'expected-tag-name-but-got-right-bracketuSExpected tag name. Got '?' instead. (HTML doesn't support processing instructions.)u'expected-tag-name-but-got-question-marku-Expected tag name. Got something else insteaduexpected-tag-nameu6Expected closing tag. Got '>' instead. Ignoring ''.u*expected-closing-tag-but-got-right-bracketu-Expected closing tag. Unexpected end of file.u expected-closing-tag-but-got-eofu<Expected closing tag. Unexpected character '%(data)s' found.u!expected-closing-tag-but-got-charu'Unexpected end of file in the tag name.ueof-in-tag-nameu8Unexpected end of file. Expected attribute name instead.u#expected-attribute-name-but-got-eofu)Unexpected end of file in attribute name.ueof-in-attribute-nameu#Invalid character in attribute nameu#invalid-character-in-attribute-nameu#Dropped duplicate attribute on tag.uduplicate-attributeu1Unexpected end of file. Expected = or end of tag.u$expected-end-of-tag-name-but-got-eofu1Unexpected end of file. Expected attribute value.u$expected-attribute-value-but-got-eofu*Expected attribute value. Got '>' instead.u.expected-attribute-value-but-got-right-bracketu"Unexpected = in unquoted attributeu"equals-in-unquoted-attribute-valueu*Unexpected character in unquoted attributeu0unexpected-character-in-unquoted-attribute-valueu*Unexpected character after attribute name.u&invalid-character-after-attribute-nameu+Unexpected character after attribute value.u*unexpected-character-after-attribute-valueu.Unexpected end of file in attribute value (").u#eof-in-attribute-value-double-quoteu.Unexpected end of file in attribute value (').u#eof-in-attribute-value-single-quoteu*Unexpected end of file in attribute value.u eof-in-attribute-value-no-quotesu)Unexpected end of file in tag. Expected >u#unexpected-EOF-after-solidus-in-tagu/Unexpected character after / in tag. Expected >u)unexpected-character-after-solidus-in-tagu&Expected '--' or 'DOCTYPE'. Not found.uexpected-dashes-or-doctypeu Unexpected ! after -- in commentu,unexpected-bang-after-double-dash-in-commentu$Unexpected space after -- in commentu-unexpected-space-after-double-dash-in-commentuIncorrect comment.uincorrect-commentu"Unexpected end of file in comment.ueof-in-commentu%Unexpected end of file in comment (-)ueof-in-comment-end-dashu+Unexpected '-' after '--' found in comment.u,unexpected-dash-after-double-dash-in-commentu'Unexpected end of file in comment (--).ueof-in-comment-double-dashueof-in-comment-end-space-stateueof-in-comment-end-bang-stateu&Unexpected character in comment found.uunexpected-char-in-commentu(No space after literal string 'DOCTYPE'.uneed-space-after-doctypeu.Unexpected > character. Expected DOCTYPE name.u+expected-doctype-name-but-got-right-bracketu.Unexpected end of file. Expected DOCTYPE name.u!expected-doctype-name-but-got-eofu'Unexpected end of file in DOCTYPE name.ueof-in-doctype-nameu"Unexpected end of file in DOCTYPE.ueof-in-doctypeu%Expected space or '>'. Got '%(data)s'u*expected-space-or-right-bracket-in-doctypeuUnexpected end of DOCTYPE.uunexpected-end-of-doctypeu Unexpected character in DOCTYPE.uunexpected-char-in-doctypeuXXX innerHTML EOFueof-in-innerhtmluUnexpected DOCTYPE. Ignored.uunexpected-doctypeu%html needs to be the first start tag.u non-html-rootu)Unexpected End of file. Expected DOCTYPE.uexpected-doctype-but-got-eofuErroneous DOCTYPE.uunknown-doctypeu2Unexpected non-space characters. Expected DOCTYPE.uexpected-doctype-but-got-charsu2Unexpected start tag (%(name)s). Expected DOCTYPE.u"expected-doctype-but-got-start-tagu0Unexpected end tag (%(name)s). Expected DOCTYPE.u expected-doctype-but-got-end-tagu?Unexpected end tag (%(name)s) after the (implied) root element.uend-tag-after-implied-rootu4Unexpected end of file. Expected end tag (%(name)s).u&expected-named-closing-tag-but-got-eofu4Unexpected start tag head in existing head. Ignored.u!two-heads-are-not-better-than-oneu'Unexpected end tag (%(name)s). Ignored.uunexpected-end-tagu;Unexpected start tag (%(name)s) that can be in head. Moved.u#unexpected-start-tag-out-of-my-headu Unexpected start tag (%(name)s).uunexpected-start-taguMissing end tag (%(name)s).umissing-end-taguMissing end tags (%(name)s).umissing-end-tagsuCUnexpected start tag (%(startName)s) implies end tag (%(endName)s).u$unexpected-start-tag-implies-end-tagu@Unexpected start tag (%(originalName)s). Treated as %(newName)s.uunexpected-start-tag-treated-asu,Unexpected start tag %(name)s. Don't use it!udeprecated-tagu'Unexpected start tag %(name)s. Ignored.uunexpected-start-tag-ignoreduEUnexpected end tag (%(gotName)s). Missing end tag (%(expectedName)s).u$expected-one-end-tag-but-got-anotheru:End tag (%(name)s) seen too early. Expected other end tag.uend-tag-too-earlyuFUnexpected end tag (%(gotName)s). Expected end tag (%(expectedName)s).uend-tag-too-early-namedu+End tag (%(name)s) seen too early. Ignored.uend-tag-too-early-ignoreduQEnd tag (%(name)s) violates step 1, paragraph 1 of the adoption agency algorithm.uadoption-agency-1.1uQEnd tag (%(name)s) violates step 1, paragraph 2 of the adoption agency algorithm.uadoption-agency-1.2uQEnd tag (%(name)s) violates step 1, paragraph 3 of the adoption agency algorithm.uadoption-agency-1.3uQEnd tag (%(name)s) violates step 4, paragraph 4 of the adoption agency algorithm.uadoption-agency-4.4u>Unexpected end tag (%(originalName)s). Treated as %(newName)s.uunexpected-end-tag-treated-asu'This element (%(name)s) has no end tag.u no-end-tagu9Unexpected implied end tag (%(name)s) in the table phase.u#unexpected-implied-end-tag-in-tableu>Unexpected implied end tag (%(name)s) in the table body phase.u(unexpected-implied-end-tag-in-table-bodyuDUnexpected non-space characters in table context caused voodoo mode.u$unexpected-char-implies-table-voodoou3Unexpected input with type hidden in table context.u unexpected-hidden-input-in-tableu!Unexpected form in table context.uunexpected-form-in-tableuDUnexpected start tag (%(name)s) in table context caused voodoo mode.u)unexpected-start-tag-implies-table-voodoouBUnexpected end tag (%(name)s) in table context caused voodoo mode.u'unexpected-end-tag-implies-table-voodoouCUnexpected table cell start tag (%(name)s) in the table body phase.uunexpected-cell-in-table-bodyuFGot table cell end tag (%(name)s) while required end tags are missing.uunexpected-cell-end-tagu?Unexpected end tag (%(name)s) in the table body phase. Ignored.u unexpected-end-tag-in-table-bodyu=Unexpected implied end tag (%(name)s) in the table row phase.u'unexpected-implied-end-tag-in-table-rowu>Unexpected end tag (%(name)s) in the table row phase. Ignored.uunexpected-end-tag-in-table-rowuJUnexpected select start tag in the select phase treated as select end tag.uunexpected-select-in-selectu/Unexpected input start tag in the select phase.uunexpected-input-in-selectuBUnexpected start tag token (%(name)s in the select phase. Ignored.uunexpected-start-tag-in-selectu;Unexpected end tag (%(name)s) in the select phase. Ignored.uunexpected-end-tag-in-selectuKUnexpected table element start tag (%(name)s) in the select in table phase.u5unexpected-table-element-start-tag-in-select-in-tableuIUnexpected table element end tag (%(name)s) in the select in table phase.u3unexpected-table-element-end-tag-in-select-in-tableu8Unexpected non-space characters in the after body phase.uunexpected-char-after-bodyu>Unexpected start tag token (%(name)s) in the after body phase.uunexpected-start-tag-after-bodyu<Unexpected end tag token (%(name)s) in the after body phase.uunexpected-end-tag-after-bodyu@Unexpected characters in the frameset phase. Characters ignored.uunexpected-char-in-framesetuEUnexpected start tag token (%(name)s) in the frameset phase. Ignored.u unexpected-start-tag-in-framesetuFUnexpected end tag token (frameset) in the frameset phase (innerHTML).u)unexpected-frameset-in-frameset-innerhtmluCUnexpected end tag token (%(name)s) in the frameset phase. Ignored.uunexpected-end-tag-in-framesetuEUnexpected non-space characters in the after frameset phase. Ignored.uunexpected-char-after-framesetuEUnexpected start tag (%(name)s) in the after frameset phase. Ignored.u#unexpected-start-tag-after-framesetuCUnexpected end tag (%(name)s) in the after frameset phase. Ignored.u!unexpected-end-tag-after-framesetu(Unexpected end tag after body(innerHtml)u'unexpected-end-tag-after-body-innerhtmlu6Unexpected non-space characters. Expected end of file.uexpected-eof-but-got-charu6Unexpected start tag (%(name)s). Expected end of file.uexpected-eof-but-got-start-tagu4Unexpected end tag (%(name)s). Expected end of file.uexpected-eof-but-got-end-tagu/Unexpected end of file. Expected table content.u eof-in-tableu0Unexpected end of file. Expected select content.u eof-in-selectu2Unexpected end of file. Expected frameset content.ueof-in-framesetu0Unexpected end of file. Expected script content.ueof-in-script-in-scriptu0Unexpected end of file. Expected foreign contentueof-in-foreign-landsu0Trailing solidus not allowed on element %(name)su&non-void-element-with-trailing-solidusu2Element %(name)s not allowed in a non-html contextu*unexpected-html-element-in-foreign-contentu*Unexpected end tag (%(name)s) before html.uunexpected-end-tag-before-htmlu9Element %(name)s not allowed in a inhead-noscript contextuunexpected-inhead-noscript-tagu8Unexpected end of file. Expected inhead-noscript contentueof-in-head-noscriptu@Unexpected non-space character. Expected inhead-noscript contentuchar-in-head-noscriptu0Undefined error (this sucks and should be fixed)uXXX-undefined-erroruhttp://www.w3.org/1999/xhtmluhtmlu"http://www.w3.org/1998/Math/MathMLumathmluhttp://www.w3.org/2000/svgusvguhttp://www.w3.org/1999/xlinkuxlinku$http://www.w3.org/XML/1998/namespaceuxmluhttp://www.w3.org/2000/xmlns/uxmlnsuappletucaptionumarqueeuobjectutableutduthumiumoumnumsumtextuannotation-xmlu foreignObjectudescutitleuaububigucodeuemufontuiunobrususmallustrikeustronguttuuuaddressuareauarticleuasideubaseubasefontubgsoundu blockquoteubodyubrubuttonucenterucolucolgroupucommanduddudetailsudirudivudludtuembedufieldsetufigureufooteruformuframeuframesetuh1uh2uh3uh4uh5uh6uheaduheaderuhruiframeuimageuimguinputuisindexuliulinkulistingumenuumetaunavunoembedunoframesunoscriptuolupuparamu plaintextupreuscriptusectionuselectustyleutbodyutextareautfootutheadutruuluwbruxmpu annotaion-xmlu attributeNameu attributenameu attributeTypeu attributetypeu baseFrequencyu basefrequencyu baseProfileu baseprofileucalcModeucalcmodeu clipPathUnitsu clippathunitsucontentScriptTypeucontentscripttypeucontentStyleTypeucontentstyletypeudiffuseConstantudiffuseconstantuedgeModeuedgemodeuexternalResourcesRequireduexternalresourcesrequiredu filterResu filterresu filterUnitsu filterunitsuglyphRefuglyphrefugradientTransformugradienttransformu gradientUnitsu gradientunitsu kernelMatrixu kernelmatrixukernelUnitLengthukernelunitlengthu keyPointsu keypointsu keySplinesu keysplinesukeyTimesukeytimesu lengthAdjustu lengthadjustulimitingConeAngleulimitingconeangleu markerHeightu markerheightu markerUnitsu markerunitsu markerWidthu markerwidthumaskContentUnitsumaskcontentunitsu maskUnitsu maskunitsu numOctavesu numoctavesu pathLengthu pathlengthupatternContentUnitsupatterncontentunitsupatternTransformupatterntransformu patternUnitsu patternunitsu pointsAtXu pointsatxu pointsAtYu pointsatyu pointsAtZu pointsatzu preserveAlphau preservealphaupreserveAspectRatioupreserveaspectratiouprimitiveUnitsuprimitiveunitsurefXurefxurefYurefyu repeatCountu repeatcountu repeatDuru repeatdururequiredExtensionsurequiredextensionsurequiredFeaturesurequiredfeaturesuspecularConstantuspecularconstantuspecularExponentuspecularexponentu spreadMethodu spreadmethodu startOffsetu startoffsetu stdDeviationu stddeviationu stitchTilesu stitchtilesu surfaceScaleu surfacescaleusystemLanguageusystemlanguageu tableValuesu tablevaluesutargetXutargetxutargetYutargetyu textLengthu textlengthuviewBoxuviewboxu viewTargetu viewtargetuxChannelSelectoruxchannelselectoruyChannelSelectoruychannelselectoru zoomAndPanu zoomandpanu definitionURLu definitionurluactuateu xlink:actuateuarcroleu xlink:arcroleuhrefu xlink:hrefuroleu xlink:roleushowu xlink:showu xlink:titleutypeu xlink:typeuxml:baseulanguxml:languspaceu xml:spaceu xmlns:xlinku u u u u u event-sourceusourceutracku irrelevantuuscopeduismapuautoplayucontrolsuaudiouvideoudeferuasyncuopenumultipleudisabledudatagriduhiddenucheckedudefaultunoshadeu autosubmitureadonlyuselecteduoptionuoptgroupu autofocusurequireduoutputi ii ii i& i i! ii0 i`i9 iRi}i i i i i" i i ii"!iai: iSi~ixult;ugt;uamp;uapos;uquot;uÆuAEliguAElig;u&uAMPuAMP;uÁuAacuteuAacute;uĂuAbreve;uÂuAcircuAcirc;uАuAcy;u𝔄uAfr;uÀuAgraveuAgrave;uΑuAlpha;uĀuAmacr;u⩓uAnd;uĄuAogon;u𝔸uAopf;u⁡uApplyFunction;uÅuAringuAring;u𝒜uAscr;u≔uAssign;uÃuAtildeuAtilde;uÄuAumluAuml;u∖u Backslash;u⫧uBarv;u⌆uBarwed;uБuBcy;u∵uBecause;uℬu Bernoullis;uΒuBeta;u𝔅uBfr;u𝔹uBopf;u˘uBreve;uBscr;u≎uBumpeq;uЧuCHcy;u©uCOPYuCOPY;uĆuCacute;u⋒uCap;uⅅuCapitalDifferentialD;uℭuCayleys;uČuCcaron;uÇuCcediluCcedil;uĈuCcirc;u∰uCconint;uĊuCdot;u¸uCedilla;u·u CenterDot;uCfr;uΧuChi;u⊙u CircleDot;u⊖u CircleMinus;u⊕u CirclePlus;u⊗u CircleTimes;u∲uClockwiseContourIntegral;u”uCloseCurlyDoubleQuote;u’uCloseCurlyQuote;u∷uColon;u⩴uColone;u≡u Congruent;u∯uConint;u∮uContourIntegral;uℂuCopf;u∐u Coproduct;u∳u CounterClockwiseContourIntegral;u⨯uCross;u𝒞uCscr;u⋓uCup;u≍uCupCap;uDD;u⤑u DDotrahd;uЂuDJcy;uЅuDScy;uЏuDZcy;u‡uDagger;u↡uDarr;u⫤uDashv;uĎuDcaron;uДuDcy;u∇uDel;uΔuDelta;u𝔇uDfr;u´uDiacriticalAcute;u˙uDiacriticalDot;u˝uDiacriticalDoubleAcute;u`uDiacriticalGrave;u˜uDiacriticalTilde;u⋄uDiamond;uⅆuDifferentialD;u𝔻uDopf;u¨uDot;u⃜uDotDot;u≐u DotEqual;uDoubleContourIntegral;u DoubleDot;u⇓uDoubleDownArrow;u⇐uDoubleLeftArrow;u⇔uDoubleLeftRightArrow;uDoubleLeftTee;u⟸uDoubleLongLeftArrow;u⟺uDoubleLongLeftRightArrow;u⟹uDoubleLongRightArrow;u⇒uDoubleRightArrow;u⊨uDoubleRightTee;u⇑uDoubleUpArrow;u⇕uDoubleUpDownArrow;u∥uDoubleVerticalBar;u↓u DownArrow;u⤓u DownArrowBar;u⇵uDownArrowUpArrow;ȗu DownBreve;u⥐uDownLeftRightVector;u⥞uDownLeftTeeVector;u↽uDownLeftVector;u⥖uDownLeftVectorBar;u⥟uDownRightTeeVector;u⇁uDownRightVector;u⥗uDownRightVectorBar;u⊤uDownTee;u↧u DownTeeArrow;u Downarrow;u𝒟uDscr;uĐuDstrok;uŊuENG;uÐuETHuETH;uÉuEacuteuEacute;uĚuEcaron;uÊuEcircuEcirc;uЭuEcy;uĖuEdot;u𝔈uEfr;uÈuEgraveuEgrave;u∈uElement;uĒuEmacr;u◻uEmptySmallSquare;u▫uEmptyVerySmallSquare;uĘuEogon;u𝔼uEopf;uΕuEpsilon;u⩵uEqual;u≂u EqualTilde;u⇌u Equilibrium;uℰuEscr;u⩳uEsim;uΗuEta;uËuEumluEuml;u∃uExists;uⅇu ExponentialE;uФuFcy;u𝔉uFfr;u◼uFilledSmallSquare;u▪uFilledVerySmallSquare;u𝔽uFopf;u∀uForAll;uℱu Fouriertrf;uFscr;uЃuGJcy;u>uGTuGT;uΓuGamma;uϜuGammad;uĞuGbreve;uĢuGcedil;uĜuGcirc;uГuGcy;uĠuGdot;u𝔊uGfr;u⋙uGg;u𝔾uGopf;u≥u GreaterEqual;u⋛uGreaterEqualLess;u≧uGreaterFullEqual;u⪢uGreaterGreater;u≷u GreaterLess;u⩾uGreaterSlantEqual;u≳u GreaterTilde;u𝒢uGscr;u≫uGt;uЪuHARDcy;uˇuHacek;u^uHat;uĤuHcirc;uℌuHfr;uℋu HilbertSpace;uℍuHopf;u─uHorizontalLine;uHscr;uĦuHstrok;u HumpDownHump;u≏u HumpEqual;uЕuIEcy;uIJuIJlig;uЁuIOcy;uÍuIacuteuIacute;uÎuIcircuIcirc;uИuIcy;uİuIdot;uℑuIfr;uÌuIgraveuIgrave;uIm;uĪuImacr;uⅈu ImaginaryI;uImplies;u∬uInt;u∫u Integral;u⋂u Intersection;u⁣uInvisibleComma;u⁢uInvisibleTimes;uĮuIogon;u𝕀uIopf;uΙuIota;uℐuIscr;uĨuItilde;uІuIukcy;uÏuIumluIuml;uĴuJcirc;uЙuJcy;u𝔍uJfr;u𝕁uJopf;u𝒥uJscr;uЈuJsercy;uЄuJukcy;uХuKHcy;uЌuKJcy;uΚuKappa;uĶuKcedil;uКuKcy;u𝔎uKfr;u𝕂uKopf;u𝒦uKscr;uЉuLJcy;u⃒unvgt;u⧞unvinfin;u⤂unvlArr;u≤⃒unvle;u<⃒unvlt;u⊴⃒unvltrie;u⤃unvrArr;u⊵⃒unvrtrie;u∼⃒unvsim;u⇖unwArr;u⤣unwarhk;unwarr;unwarrow;u⤧unwnear;uoS;uóuoacuteuoacute;uoast;uocir;uôuocircuocirc;uоuocy;uodash;uőuodblac;u⨸uodiv;uodot;u⦼uodsold;uœuoelig;u⦿uofcir;u𝔬uofr;u˛uogon;uòuograveuograve;u⧁uogt;u⦵uohbar;uohm;uoint;uolarr;u⦾uolcir;u⦻uolcross;uoline;u⧀uolt;uōuomacr;uωuomega;uοuomicron;u⦶uomid;uominus;u𝕠uoopf;u⦷uopar;u⦹uoperp;uoplus;u∨uor;uorarr;u⩝uord;uℴuorder;uorderof;uªuordfuordf;uºuordmuordm;u⊶uorigof;u⩖uoror;u⩗uorslope;u⩛uorv;uoscr;uøuoslashuoslash;u⊘uosol;uõuotildeuotilde;uotimes;u⨶u otimesas;uöuoumluouml;u⌽uovbar;upar;u¶uparaupara;u parallel;u⫳uparsim;u⫽uparsl;upart;uпupcy;u%upercnt;u.uperiod;u‰upermil;uperp;u‱upertenk;u𝔭upfr;uφuphi;uϕuphiv;uphmmat;u☎uphone;uπupi;u pitchfork;uϖupiv;uplanck;uℎuplanckh;uplankv;u+uplus;u⨣u plusacir;uplusb;u⨢upluscir;uplusdo;u⨥uplusdu;u⩲upluse;uplusmnuplusmn;u⨦uplussim;u⨧uplustwo;upm;u⨕u pointint;u𝕡upopf;u£upoundupound;upr;u⪳uprE;u⪷uprap;uprcue;upre;uprec;u precapprox;u preccurlyeq;upreceq;u⪹u precnapprox;u⪵u precneqq;u⋨u precnsim;uprecsim;u′uprime;uprimes;uprnE;uprnap;uprnsim;uprod;u⌮u profalar;u⌒u profline;u⌓u profsurf;uprop;upropto;uprsim;u⊰uprurel;u𝓅upscr;uψupsi;u upuncsp;u𝔮uqfr;uqint;u𝕢uqopf;u⁗uqprime;u𝓆uqscr;u quaternions;u⨖uquatint;u?uquest;uquesteq;uquoturAarr;urArr;u⤜urAtail;urBarr;u⥤urHar;u∽̱urace;uŕuracute;uradic;u⦳u raemptyv;urang;u⦒urangd;u⦥urange;urangle;u»uraquouraquo;urarr;u⥵urarrap;urarrb;u⤠urarrbfs;u⤳urarrc;u⤞urarrfs;urarrhk;urarrlp;u⥅urarrpl;u⥴urarrsim;u↣urarrtl;u↝urarrw;u⤚uratail;u∶uratio;u rationals;urbarr;u❳urbbrk;u}urbrace;u]urbrack;u⦌urbrke;u⦎urbrksld;u⦐urbrkslu;uřurcaron;uŗurcedil;urceil;urcub;uрurcy;u⤷urdca;u⥩urdldhar;urdquo;urdquor;u↳urdsh;ureal;urealine;u realpart;ureals;u▭urect;uregureg;u⥽urfisht;urfloor;u𝔯urfr;urhard;urharu;u⥬urharul;uρurho;uϱurhov;u rightarrow;urightarrowtail;urightharpoondown;urightharpoonup;urightleftarrows;urightleftharpoons;u⇉urightrightarrows;urightsquigarrow;u⋌urightthreetimes;u˚uring;u risingdotseq;urlarr;urlhar;u‏urlm;u⎱urmoust;u rmoustache;u⫮urnmid;u⟭uroang;u⇾uroarr;urobrk;u⦆uropar;u𝕣uropf;u⨮uroplus;u⨵urotimes;u)urpar;u⦔urpargt;u⨒u rppolint;urrarr;u›ursaquo;u𝓇urscr;ursh;ursqb;ursquo;ursquor;urthree;u⋊urtimes;u▹urtri;urtrie;urtrif;u⧎u rtriltri;u⥨uruluhar;u℞urx;uśusacute;usbquo;usc;u⪴uscE;u⪸uscap;ušuscaron;usccue;usce;uşuscedil;uŝuscirc;u⪶uscnE;u⪺uscnap;u⋩uscnsim;u⨓u scpolint;uscsim;uсuscy;u⋅usdot;usdotb;u⩦usdote;u⇘useArr;usearhk;usearr;usearrow;u§usectusect;u;usemi;u⤩useswar;u setminus;usetmn;u✶usext;u𝔰usfr;usfrown;u♯usharp;uщushchcy;uшushcy;u shortmid;ushortparallel;u­ushyushy;uσusigma;uςusigmaf;usigmav;usim;u⩪usimdot;usime;usimeq;u⪞usimg;u⪠usimgE;u⪝usiml;u⪟usimlE;u≆usimne;u⨤usimplus;u⥲usimrarr;uslarr;usmallsetminus;u⨳usmashp;u⧤u smeparsl;usmid;u⌣usmile;u⪪usmt;u⪬usmte;u⪬︀usmtes;uьusoftcy;u/usol;u⧄usolb;u⌿usolbar;u𝕤usopf;u♠uspades;u spadesuit;uspar;usqcap;u⊓︀usqcaps;usqcup;u⊔︀usqcups;usqsub;usqsube;u sqsubset;u sqsubseteq;usqsup;usqsupe;u sqsupset;u sqsupseteq;usqu;usquare;usquarf;usquf;usrarr;u𝓈usscr;ussetmn;ussmile;usstarf;u☆ustar;ustarf;ustraightepsilon;u straightphi;ustrns;u⊂usub;u⫅usubE;u⪽usubdot;usube;u⫃usubedot;u⫁usubmult;u⫋usubnE;u⊊usubne;u⪿usubplus;u⥹usubrarr;usubset;u subseteq;u subseteqq;u subsetneq;u subsetneqq;u⫇usubsim;u⫕usubsub;u⫓usubsup;usucc;u succapprox;u succcurlyeq;usucceq;u succnapprox;u succneqq;u succnsim;usuccsim;usum;u♪usung;u¹usup1usup1;u²usup2usup2;u³usup3usup3;usup;u⫆usupE;u⪾usupdot;u⫘usupdsub;usupe;u⫄usupedot;u⟉usuphsol;u⫗usuphsub;u⥻usuplarr;u⫂usupmult;u⫌usupnE;u⊋usupne;u⫀usupplus;usupset;u supseteq;u supseteqq;u supsetneq;u supsetneqq;u⫈usupsim;u⫔usupsub;u⫖usupsup;u⇙uswArr;uswarhk;uswarr;uswarrow;u⤪uswnwar;ußuszliguszlig;u⌖utarget;uτutau;utbrk;uťutcaron;uţutcedil;uтutcy;utdot;u⌕utelrec;u𝔱utfr;uthere4;u therefore;uθutheta;uϑu thetasym;uthetav;u thickapprox;u thicksim;uthinsp;uthkap;uthksim;uþuthornuthorn;utilde;u×utimesutimes;utimesb;u⨱u timesbar;u⨰utimesd;utint;utoea;utop;u⌶utopbot;u⫱utopcir;u𝕥utopf;u⫚utopfork;utosa;u‴utprime;utrade;u▵u triangle;u triangledown;u triangleleft;utrianglelefteq;u≜u triangleq;utriangleright;utrianglerighteq;u◬utridot;utrie;u⨺u triminus;u⨹utriplus;u⧍utrisb;u⨻utritime;u⏢u trpezium;u𝓉utscr;uцutscy;uћutshcy;uŧutstrok;utwixt;utwoheadleftarrow;utwoheadrightarrow;uuArr;u⥣uuHar;uúuuacuteuuacute;uuarr;uўuubrcy;uŭuubreve;uûuucircuucirc;uуuucy;uudarr;uűuudblac;uudhar;u⥾uufisht;u𝔲uufr;uùuugraveuugrave;uuharl;uuharr;u▀uuhblk;u⌜uulcorn;u ulcorner;u⌏uulcrop;u◸uultri;uūuumacr;uumluuml;uųuuogon;u𝕦uuopf;uuparrow;u updownarrow;uupharpoonleft;uupharpoonright;uuplus;uυuupsi;uupsih;uupsilon;u⇈u upuparrows;u⌝uurcorn;u urcorner;u⌎uurcrop;uůuuring;u◹uurtri;u𝓊uuscr;u⋰uutdot;uũuutilde;uutri;uutrif;uuuarr;uüuuumluuuml;u⦧uuwangle;uvArr;u⫨uvBar;u⫩uvBarv;uvDash;u⦜uvangrt;u varepsilon;u varkappa;u varnothing;uvarphi;uvarpi;u varpropto;uvarr;uvarrho;u varsigma;u⊊︀u varsubsetneq;u⫋︀uvarsubsetneqq;u⊋︀u varsupsetneq;u⫌︀uvarsupsetneqq;u vartheta;uvartriangleleft;uvartriangleright;uвuvcy;uvdash;uvee;u⊻uveebar;u≚uveeeq;u⋮uvellip;uverbar;uvert;u𝔳uvfr;uvltri;uvnsub;uvnsup;u𝕧uvopf;uvprop;uvrtri;u𝓋uvscr;uvsubnE;uvsubne;uvsupnE;uvsupne;u⦚uvzigzag;uŵuwcirc;u⩟uwedbar;uwedge;u≙uwedgeq;u℘uweierp;u𝔴uwfr;u𝕨uwopf;uwp;uwr;uwreath;u𝓌uwscr;uxcap;uxcirc;uxcup;uxdtri;u𝔵uxfr;uxhArr;uxharr;uξuxi;uxlArr;uxlarr;uxmap;u⋻uxnis;uxodot;u𝕩uxopf;uxoplus;uxotime;uxrArr;uxrarr;u𝓍uxscr;uxsqcup;uxuplus;uxutri;uxvee;uxwedge;uýuyacuteuyacute;uяuyacy;uŷuycirc;uыuycy;u¥uyenuyen;u𝔶uyfr;uїuyicy;u𝕪uyopf;u𝓎uyscr;uюuyucy;uÿuyumluyuml;uźuzacute;užuzcaron;uзuzcy;użuzdot;uzeetrf;uζuzeta;u𝔷uzfr;uжuzhcy;u⇝uzigrarr;u𝕫uzopf;u𝓏uzscr;u‍uzwj;u‌uzwnj;u�i iuiiiiiiiiiiiiuiiuiuiiiiiiiiiiiiiuiiiuDoctypeiu CharactersiuSpaceCharactersiuStartTagiuEndTagiuEmptyTagiuCommentiu ParseErrorumathtDataLossWarningcB`seZRS((t__name__t __module__(((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/constants.pyR| stReparseExceptioncB`seZRS((RR(((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/constants.pyR s(uh1uh2uh3uh4uh5uh6( i ii ii i& i i! ii0 i`i9 iRii}iii i i i i" i i ii"!iai: iSii~ix(:t __future__RRRtstringtNonetEOFtEt namespacest frozensettscopingElementstformattingElementstspecialElementsthtmlIntegrationPointElementst"mathmlTextIntegrationPointElementstadjustSVGAttributestadjustMathMLAttributestadjustForeignAttributestdicttitemstqnametprefixtlocaltnstunadjustForeignAttributestspaceCharactersttableInsertModeElementstascii_lowercasetasciiLowercasetascii_uppercasetasciiUppercaset ascii_letterst asciiLetterstdigitst hexdigitst hexDigitstctordtlowertasciiUpper2LowertheadingElementst voidElementst cdataElementstrcdataElementstbooleanAttributestentitiesWindows1252t xmlEntitiestentitiestreplacementCharacterst tokenTypest tagTokenTypestktvtprefixest UserWarningRt ExceptionR(((sB/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/constants.pytsL                                                                                                                      :  4     1 _vendor/html5lib/serializer.pyo000064400000026760152527136320012643 0ustar00 abc@`sddlmZmZmZddlmZddlZddlmZm Z ddl m Z m Z m Z ddl mZmZmZddlmZmZdd lmZd je d Zejd ed Zejd edZiZeddkZxeejD]\Z Z!er<ee!dkse r[ee!dkr[qne!dkree!dkrej"e!Z!n e#e!Z!e!ekse j$re ee!`u[u]u_  /`  ᠎᠏           

   ]u􏿿iu&c C`st|ttfrqg}g}t}xt|j|j|j!D]\}}|rbt}qDn||j}tj |j|t |j|dg!rtj |j||d!}t }n t |}|j|qDWxz|D]r}tj|} | r<|jd|j| | jdsW|jdqWq|jdt|dqWdj||jfSt|SdS(Niu&u;u&#x%s;u(t isinstancetUnicodeEncodeErrortUnicodeTranslateErrortFalset enumeratetobjecttstarttendR tisSurrogatePairtmintsurrogatePairToCodepointtTruetordtappendt_encode_entity_maptgettendswiththextjoinR( texctrest codepointstskiptitctindext codepointtcpte((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pythtmlentityreplace_errors*s0) ,     uhtmlentityreplaceuetreecK`s1tj|}t|}|j|||S(N(R t getTreeWalkertHTMLSerializertrender(tinputttreetencodingtserializer_optstwalkerts((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyt serializeJs R.cB`seZdZdZeZeZeZeZ eZ eZ eZ eZ eZeZeZeZdZdZdZdZddZddZddZRS(ulegacyu"uquote_attr_valuesu quote_charuuse_best_quote_charuomit_optional_tagsuminimize_boolean_attributesuuse_trailing_solidususpace_before_trailing_solidusuescape_lt_in_attrsu escape_rcdatauresolve_entitiesualphabetical_attributesuinject_meta_charsetustrip_whitespaceusanitizec K`st|t|j}t|dkrJtdtt|nd|krbt|_nx6|jD]+}t|||j |t ||qlWg|_ t|_ dS(u6 Initialize HTMLSerializer. Keyword options (default given first unless specified) include: inject_meta_charset=True|False Whether it insert a meta element to define the character set of the document. quote_attr_values="legacy"|"spec"|"always" Whether to quote attribute values that don't require quoting per legacy browser behaviour, when required by the standard, or always. quote_char=u'"'|u"'" Use given quote character for attribute quoting. Default is to use double quote unless attribute value contains a double quote, in which case single quotes are used instead. escape_lt_in_attrs=False|True Whether to escape < in attribute values. escape_rcdata=False|True Whether to escape characters that need to be escaped within normal elements within rcdata elements such as style. resolve_entities=True|False Whether to resolve named character entities that appear in the source tree. The XML predefined entities < > & " ' are unaffected by this setting. strip_whitespace=False|True Whether to remove semantically meaningless whitespace. (This compresses all whitespace to a single space except within pre.) minimize_boolean_attributes=True|False Shortens boolean attributes to give just the attribute value, for example becomes . use_trailing_solidus=False|True Includes a close-tag slash at the end of the start tag of void elements (empty elements whose end tag is forbidden). E.g.
. space_before_trailing_solidus=True|False Places a space immediately before the closing slash in a tag using a trailing solidus. E.g.
. Requires use_trailing_solidus. sanitize=False|True Strip all unsafe or unknown constructs from output. See `html5lib user documentation`_ omit_optional_tags=True|False Omit start/end tags that are optional. alphabetical_attributes=False|True Reorder attributes to be in alphabetical order. .. _html5lib user documentation: http://code.google.com/p/html5lib/wiki/UserDocumentation iu2__init__() got an unexpected keyword argument '%s'u quote_charN( t frozensettoptionstlent TypeErrortnexttiterRtuse_best_quote_chartsetattrRtgetattrterrorststrict(tselftkwargstunexpected_argstattr((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyt__init__ps.  ) cC`s$|jr|j|jdS|SdS(Nuhtmlentityreplace(R2tencode(RBtstring((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyRGs cC`s$|jr|j|jdS|SdS(Nustrict(R2RG(RBRH((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyt encodeStricts cc`sn||_t}g|_|rI|jrIddlm}|||}n|jrqddlm}||}n|jrddl m}||}n|j rddl m}||}n|j rddl m}||}nx~|D]v}|d}|dkrd|d}|dr9|d|d7}n|d rP|d 7}n|d r|d jd d kr|d jd d kr|jdnd }nd }|d||d |f7}n|d7}|j|Vq|d3kra|dks|rF|r1|djdd kr1|jdn|j|dVqf|jt|dVq|d4kr.|d} |jd| V| tkr|j rt}n|r|jdnx|djD] \\} } } | } | }|jdV|j| V|j sI| tj| tkr| tjdtkr|jdV|jdksxt|d krt}nZ|jdkrtj|dk }n3|jdkrt j|dk }n t!d |j"d!d"}|j#r |j"d#d$}n|r|j$}|j%rhd |krDd |krDd }qhd |krhd |krhd }qhn|d kr|j"d d%}n|j"d d&}|j|V|j|V|j|Vq|j|VqqW| t&kr|j'r|j(r |jd'Vq|jd(Vn|jdVq|d)kr|d} | tkrYt}n|ro|jdn|jd*| Vq|d+kr|d}|jd,d kr|jd-n|jd.|dVq|d/krU|d} | d0}|t)kr|jd1| n|j*r:|t+kr:t)|}n d2| }|j|Vq|j|dqWdS(5Ni(tFilterutypeuDoctypeu u CharactersuSpaceCharactersudatauuCommentu--uComment contains --u uEntityu;uEntity %s not recognizedu&%s;(u CharactersuSpaceCharacters(uStartTaguEmptyTag(,R2RR@tinject_meta_charsettfilters.inject_meta_charsetRJtalphabetical_attributestfilters.alphabeticalattributeststrip_whitespacetfilters.whitespacetsanitizetfilters.sanitizertomit_optional_tagstfilters.optionaltagstfindtserializeErrorRIRGRR t escape_rcdataRtitemstminimize_boolean_attributesRRttupletquote_attr_valuesR9t_quoteAttributeSpectsearchtNonet_quoteAttributeLegacyt ValueErrortreplacetescape_lt_in_attrst quote_charR=Rtuse_trailing_solidustspace_before_trailing_solidusR tresolve_entitiesR (RBt treewalkerR2tin_cdataRJttokenttypetdoctypeRctnamet_t attr_namet attr_valuetktvt quote_attrtdatatkey((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyR6s                   # !                     cC`sE|r%djt|j||Sdjt|j|SdS(Ntu(R!tlistR6(RBRgR2((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyR/?suXXX ERROR MESSAGE NEEDEDcC`s&|jj||jr"tndS(N(R@RRAtSerializeError(RBRs((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyRVEs (uquote_attr_valuesu quote_charuuse_best_quote_charuomit_optional_tagsuminimize_boolean_attributesuuse_trailing_solidususpace_before_trailing_solidusuescape_lt_in_attrsu escape_rcdatauresolve_entitiesualphabetical_attributesuinject_meta_charsetustrip_whitespaceusanitizeN(t__name__t __module__R[RcRR=RSRYRRdReRbRWRfRMRKRORQR8RFRGRIR^R6R/RV(((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyR.Qs4 8   RwcB`seZdZRS(uError in serialized tree(RxRyt__doc__(((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyRwLs(,t __future__RRRtpip._vendor.sixRtretcodecsRRt constantsRRRR R R RuR R txml.sax.saxutilsRR!t_quoteAttributeSpecCharstcompileR\R_RR9t_is_ucs4RvRXRpRqRRtislowerR,R^R6RR.t ExceptionRw(((sC/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/serializer.pyts8       _vendor/html5lib/__init__.pyo000064400000002112152527136320012212 0ustar00 abc@`sdZddlmZmZmZddlmZmZmZddl m Z ddl m Z ddl mZdd d d d d gZdZdS(uM HTML parsing library based on the WHATWG "HTML5" specification. The parser is designed to be compatible with existing HTML found in the wild and implements well-defined error recovery that is largely compatible with modern desktop web browsers. Example usage: import html5lib f = open("my_document.html") tree = html5lib.parse(f) i(tabsolute_importtdivisiontunicode_literalsi(t HTMLParsertparset parseFragment(tgetTreeBuilder(t getTreeWalker(t serializeu HTMLParseruparseu parseFragmentugetTreeBuilderu getTreeWalkeru serializeu1.0b10N(t__doc__t __future__RRRt html5parserRRRt treebuildersRt treewalkersRt serializerRt__all__t __version__(((sA/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/__init__.pyt s  _vendor/html5lib/_utils.py000064400000010000152527136320011566 0ustar00from __future__ import absolute_import, division, unicode_literals import sys from types import ModuleType from pip._vendor.six import text_type try: import xml.etree.cElementTree as default_etree except ImportError: import xml.etree.ElementTree as default_etree __all__ = ["default_etree", "MethodDispatcher", "isSurrogatePair", "surrogatePairToCodepoint", "moduleFactoryFactory", "supports_lone_surrogates", "PY27"] PY27 = sys.version_info[0] == 2 and sys.version_info[1] >= 7 # Platforms not supporting lone surrogates (\uD800-\uDFFF) should be # caught by the below test. In general this would be any platform # using UTF-16 as its encoding of unicode strings, such as # Jython. This is because UTF-16 itself is based on the use of such # surrogates, and there is no mechanism to further escape such # escapes. try: _x = eval('"\\uD800"') # pylint:disable=eval-used if not isinstance(_x, text_type): # We need this with u"" because of http://bugs.jython.org/issue2039 _x = eval('u"\\uD800"') # pylint:disable=eval-used assert isinstance(_x, text_type) except: # pylint:disable=bare-except supports_lone_surrogates = False else: supports_lone_surrogates = True class MethodDispatcher(dict): """Dict with 2 special properties: On initiation, keys that are lists, sets or tuples are converted to multiple keys so accessing any one of the items in the original list-like object returns the matching value md = MethodDispatcher({("foo", "bar"):"baz"}) md["foo"] == "baz" A default value which can be set through the default attribute. """ def __init__(self, items=()): # Using _dictEntries instead of directly assigning to self is about # twice as fast. Please do careful performance testing before changing # anything here. _dictEntries = [] for name, value in items: if isinstance(name, (list, tuple, frozenset, set)): for item in name: _dictEntries.append((item, value)) else: _dictEntries.append((name, value)) dict.__init__(self, _dictEntries) assert len(self) == len(_dictEntries) self.default = None def __getitem__(self, key): return dict.get(self, key, self.default) # Some utility functions to deal with weirdness around UCS2 vs UCS4 # python builds def isSurrogatePair(data): return (len(data) == 2 and ord(data[0]) >= 0xD800 and ord(data[0]) <= 0xDBFF and ord(data[1]) >= 0xDC00 and ord(data[1]) <= 0xDFFF) def surrogatePairToCodepoint(data): char_val = (0x10000 + (ord(data[0]) - 0xD800) * 0x400 + (ord(data[1]) - 0xDC00)) return char_val # Module Factory Factory (no, this isn't Java, I know) # Here to stop this being duplicated all over the place. def moduleFactoryFactory(factory): moduleCache = {} def moduleFactory(baseModule, *args, **kwargs): if isinstance(ModuleType.__name__, type("")): name = "_%s_factory" % baseModule.__name__ else: name = b"_%s_factory" % baseModule.__name__ kwargs_tuple = tuple(kwargs.items()) try: return moduleCache[name][args][kwargs_tuple] except KeyError: mod = ModuleType(name) objs = factory(baseModule, *args, **kwargs) mod.__dict__.update(objs) if "name" not in moduleCache: moduleCache[name] = {} if "args" not in moduleCache[name]: moduleCache[name][args] = {} if "kwargs" not in moduleCache[name][args]: moduleCache[name][args][kwargs_tuple] = {} moduleCache[name][args][kwargs_tuple] = mod return mod return moduleFactory def memoize(func): cache = {} def wrapped(*args, **kwargs): key = (tuple(args), tuple(kwargs.items())) if key not in cache: cache[key] = func(*args, **kwargs) return cache[key] return wrapped _vendor/html5lib/filters/whitespace.py000064400000002163152527136320014106 0ustar00from __future__ import absolute_import, division, unicode_literals import re from . import base from ..constants import rcdataElements, spaceCharacters spaceCharacters = "".join(spaceCharacters) SPACES_REGEX = re.compile("[%s]+" % spaceCharacters) class Filter(base.Filter): spacePreserveElements = frozenset(["pre", "textarea"] + list(rcdataElements)) def __iter__(self): preserve = 0 for token in base.Filter.__iter__(self): type = token["type"] if type == "StartTag" \ and (preserve or token["name"] in self.spacePreserveElements): preserve += 1 elif type == "EndTag" and preserve: preserve -= 1 elif not preserve and type == "SpaceCharacters" and token["data"]: # Test on token["data"] above to not introduce spaces where there were not token["data"] = " " elif not preserve and type == "Characters": token["data"] = collapse_spaces(token["data"]) yield token def collapse_spaces(text): return SPACES_REGEX.sub(' ', text) _vendor/html5lib/filters/whitespace.pyc000064400000003177152527136320014257 0ustar00 abc@`sddlmZmZmZddlZddlmZddlmZm Z dj e Z ej de Z d ej fd YZ d ZdS( i(tabsolute_importtdivisiontunicode_literalsNi(tbasei(trcdataElementstspaceCharactersuu[%s]+tFiltercB`s-eZeddgeeZdZRS(upreutextareacc`sd}xtjj|D]}|d}|dkr[|sN|d|jkr[|d7}ns|dkrz|rz|d8}nT| r|dkr|drd |ds _vendor/html5lib/filters/optionaltags.pyc000064400000010464152527136320014624 0ustar00 abc@`sIddlmZmZmZddlmZdejfdYZdS(i(tabsolute_importtdivisiontunicode_literalsi(tbasetFiltercB`s,eZdZdZdZdZRS(cc`shd}}x:|jD]/}|dk r7|||fVn|}|}qW|dk rd||dfVndS(N(tNonetsource(tselft previous1t previous2ttoken((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pytsliders    cc`sx|jD]\}}}|d}|dkra|dsV|j|d|| r|Vqq |dkr|j|d|s|Vqq |Vq WdS(NutypeuStartTagudataunameuEndTag(R tis_optional_starttis_optional_end(RtpreviousR tnextttype((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyt__iter__s      cC`s*|r|dpd}|dkr,|dkS|dkre|dkrHtS|dkr&|d dkSn|d kr|dkrtS|dkr|d dkStSn|d kr|dkr|d dkStSnW|dkr&|dkr|r|ddkr|d dkrtS|d dkStSntS(NutypeuhtmluCommentuSpaceCharactersuheaduStartTaguEmptyTaguEndTagunameubodyuscriptustyleucolgroupucolutbodyutheadutfootutr(uCommentuSpaceCharacters(uStartTaguEmptyTag(uCommentuSpaceCharacters(uscriptustyle(uStartTaguEmptyTag(utbodyutheadutfoot(RtTruetFalse(RttagnameRRR((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyR s4            cC`s|r|dpd}|d5kr,|d6kS|d7krk|d krR|d |kS|d kpg|dkSn|d8kr|d kr|d d9kS|dkr|d kp|dkStSn|dkr|d:kr|d d;kS|d kp|dkSn|d,kr8|d kr|d d<kS|d kp4|dkSnI|d=krw|d kr^|d d>kS|d kps|dkSn |d/kr|d?krtS|d kr|d d/kStSn|d@kr|d kr|d dAkS|d1kr|d kp|dkStSn~|d2krB|d kr)|d d1kS|d kp>|dkSn?|dBkr|d krh|d dCkS|d kp}|dkSntS(DNutypeuhtmluheadubodyuCommentuSpaceCharactersuliuoptgrouputruStartTagunameuEndTagudtuddupuEmptyTaguaddressuarticleuasideu blockquoteudatagridudialogudirudivudlufieldsetufooteruformuh1uh2uh3uh4uh5uh6uheaderuhrumenuunavuolupreusectionutableuuluoptionurturpucolgrouputheadutbodyutfootutduth(uhtmluheadubody(uCommentuSpaceCharacters(uliuoptgrouputr(udtudd(udtudd(uStartTaguEmptyTag(uaddressuarticleuasideu blockquoteudatagridudialogudirudivudlufieldsetufooteruformuh1uh2uh3uh4uh5uh6uheaderuhrumenuunavuolupupreusectionutableuul(uoptionuoptgroup(urturp(urturp(uCommentuSpaceCharacters(utheadutbody(utbodyutfoot(utduth(utduth(RRR(RRRR((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyR Wsf                     (t__name__t __module__R RR R (((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyRs 9N(t __future__RRRtRR(((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyts_vendor/html5lib/filters/inject_meta_charset.pyo000064400000004315152527136320016125 0ustar00 abc@`sIddlmZmZmZddlmZdejfdYZdS(i(tabsolute_importtdivisiontunicode_literalsi(tbasetFiltercB`seZdZdZRS(cC`s tjj||||_dS(N(RRt__init__tencoding(tselftsourceR((sT/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/inject_meta_charset.pyRsc c`sd}|jdk}g}xvtjj|D]b}|d}|dkrl|djdkrod}qon|dkr|djdkr^t}xE|d jD]~\\}}} |dk rqq|jd kr|j|d ||fs_vendor/html5lib/filters/sanitizer.py000064400000061030152527136320013760 0ustar00from __future__ import absolute_import, division, unicode_literals import re from xml.sax.saxutils import escape, unescape from pip._vendor.six.moves import urllib_parse as urlparse from . import base from ..constants import namespaces, prefixes __all__ = ["Filter"] allowed_elements = frozenset(( (namespaces['html'], 'a'), (namespaces['html'], 'abbr'), (namespaces['html'], 'acronym'), (namespaces['html'], 'address'), (namespaces['html'], 'area'), (namespaces['html'], 'article'), (namespaces['html'], 'aside'), (namespaces['html'], 'audio'), (namespaces['html'], 'b'), (namespaces['html'], 'big'), (namespaces['html'], 'blockquote'), (namespaces['html'], 'br'), (namespaces['html'], 'button'), (namespaces['html'], 'canvas'), (namespaces['html'], 'caption'), (namespaces['html'], 'center'), (namespaces['html'], 'cite'), (namespaces['html'], 'code'), (namespaces['html'], 'col'), (namespaces['html'], 'colgroup'), (namespaces['html'], 'command'), (namespaces['html'], 'datagrid'), (namespaces['html'], 'datalist'), (namespaces['html'], 'dd'), (namespaces['html'], 'del'), (namespaces['html'], 'details'), (namespaces['html'], 'dfn'), (namespaces['html'], 'dialog'), (namespaces['html'], 'dir'), (namespaces['html'], 'div'), (namespaces['html'], 'dl'), (namespaces['html'], 'dt'), (namespaces['html'], 'em'), (namespaces['html'], 'event-source'), (namespaces['html'], 'fieldset'), (namespaces['html'], 'figcaption'), (namespaces['html'], 'figure'), (namespaces['html'], 'footer'), (namespaces['html'], 'font'), (namespaces['html'], 'form'), (namespaces['html'], 'header'), (namespaces['html'], 'h1'), (namespaces['html'], 'h2'), (namespaces['html'], 'h3'), (namespaces['html'], 'h4'), (namespaces['html'], 'h5'), (namespaces['html'], 'h6'), (namespaces['html'], 'hr'), (namespaces['html'], 'i'), (namespaces['html'], 'img'), (namespaces['html'], 'input'), (namespaces['html'], 'ins'), (namespaces['html'], 'keygen'), (namespaces['html'], 'kbd'), (namespaces['html'], 'label'), (namespaces['html'], 'legend'), (namespaces['html'], 'li'), (namespaces['html'], 'm'), (namespaces['html'], 'map'), (namespaces['html'], 'menu'), (namespaces['html'], 'meter'), (namespaces['html'], 'multicol'), (namespaces['html'], 'nav'), (namespaces['html'], 'nextid'), (namespaces['html'], 'ol'), (namespaces['html'], 'output'), (namespaces['html'], 'optgroup'), (namespaces['html'], 'option'), (namespaces['html'], 'p'), (namespaces['html'], 'pre'), (namespaces['html'], 'progress'), (namespaces['html'], 'q'), (namespaces['html'], 's'), (namespaces['html'], 'samp'), (namespaces['html'], 'section'), (namespaces['html'], 'select'), (namespaces['html'], 'small'), (namespaces['html'], 'sound'), (namespaces['html'], 'source'), (namespaces['html'], 'spacer'), (namespaces['html'], 'span'), (namespaces['html'], 'strike'), (namespaces['html'], 'strong'), (namespaces['html'], 'sub'), (namespaces['html'], 'sup'), (namespaces['html'], 'table'), (namespaces['html'], 'tbody'), (namespaces['html'], 'td'), (namespaces['html'], 'textarea'), (namespaces['html'], 'time'), (namespaces['html'], 'tfoot'), (namespaces['html'], 'th'), (namespaces['html'], 'thead'), (namespaces['html'], 'tr'), (namespaces['html'], 'tt'), (namespaces['html'], 'u'), (namespaces['html'], 'ul'), (namespaces['html'], 'var'), (namespaces['html'], 'video'), (namespaces['mathml'], 'maction'), (namespaces['mathml'], 'math'), (namespaces['mathml'], 'merror'), (namespaces['mathml'], 'mfrac'), (namespaces['mathml'], 'mi'), (namespaces['mathml'], 'mmultiscripts'), (namespaces['mathml'], 'mn'), (namespaces['mathml'], 'mo'), (namespaces['mathml'], 'mover'), (namespaces['mathml'], 'mpadded'), (namespaces['mathml'], 'mphantom'), (namespaces['mathml'], 'mprescripts'), (namespaces['mathml'], 'mroot'), (namespaces['mathml'], 'mrow'), (namespaces['mathml'], 'mspace'), (namespaces['mathml'], 'msqrt'), (namespaces['mathml'], 'mstyle'), (namespaces['mathml'], 'msub'), (namespaces['mathml'], 'msubsup'), (namespaces['mathml'], 'msup'), (namespaces['mathml'], 'mtable'), (namespaces['mathml'], 'mtd'), (namespaces['mathml'], 'mtext'), (namespaces['mathml'], 'mtr'), (namespaces['mathml'], 'munder'), (namespaces['mathml'], 'munderover'), (namespaces['mathml'], 'none'), (namespaces['svg'], 'a'), (namespaces['svg'], 'animate'), (namespaces['svg'], 'animateColor'), (namespaces['svg'], 'animateMotion'), (namespaces['svg'], 'animateTransform'), (namespaces['svg'], 'clipPath'), (namespaces['svg'], 'circle'), (namespaces['svg'], 'defs'), (namespaces['svg'], 'desc'), (namespaces['svg'], 'ellipse'), (namespaces['svg'], 'font-face'), (namespaces['svg'], 'font-face-name'), (namespaces['svg'], 'font-face-src'), (namespaces['svg'], 'g'), (namespaces['svg'], 'glyph'), (namespaces['svg'], 'hkern'), (namespaces['svg'], 'linearGradient'), (namespaces['svg'], 'line'), (namespaces['svg'], 'marker'), (namespaces['svg'], 'metadata'), (namespaces['svg'], 'missing-glyph'), (namespaces['svg'], 'mpath'), (namespaces['svg'], 'path'), (namespaces['svg'], 'polygon'), (namespaces['svg'], 'polyline'), (namespaces['svg'], 'radialGradient'), (namespaces['svg'], 'rect'), (namespaces['svg'], 'set'), (namespaces['svg'], 'stop'), (namespaces['svg'], 'svg'), (namespaces['svg'], 'switch'), (namespaces['svg'], 'text'), (namespaces['svg'], 'title'), (namespaces['svg'], 'tspan'), (namespaces['svg'], 'use'), )) allowed_attributes = frozenset(( # HTML attributes (None, 'abbr'), (None, 'accept'), (None, 'accept-charset'), (None, 'accesskey'), (None, 'action'), (None, 'align'), (None, 'alt'), (None, 'autocomplete'), (None, 'autofocus'), (None, 'axis'), (None, 'background'), (None, 'balance'), (None, 'bgcolor'), (None, 'bgproperties'), (None, 'border'), (None, 'bordercolor'), (None, 'bordercolordark'), (None, 'bordercolorlight'), (None, 'bottompadding'), (None, 'cellpadding'), (None, 'cellspacing'), (None, 'ch'), (None, 'challenge'), (None, 'char'), (None, 'charoff'), (None, 'choff'), (None, 'charset'), (None, 'checked'), (None, 'cite'), (None, 'class'), (None, 'clear'), (None, 'color'), (None, 'cols'), (None, 'colspan'), (None, 'compact'), (None, 'contenteditable'), (None, 'controls'), (None, 'coords'), (None, 'data'), (None, 'datafld'), (None, 'datapagesize'), (None, 'datasrc'), (None, 'datetime'), (None, 'default'), (None, 'delay'), (None, 'dir'), (None, 'disabled'), (None, 'draggable'), (None, 'dynsrc'), (None, 'enctype'), (None, 'end'), (None, 'face'), (None, 'for'), (None, 'form'), (None, 'frame'), (None, 'galleryimg'), (None, 'gutter'), (None, 'headers'), (None, 'height'), (None, 'hidefocus'), (None, 'hidden'), (None, 'high'), (None, 'href'), (None, 'hreflang'), (None, 'hspace'), (None, 'icon'), (None, 'id'), (None, 'inputmode'), (None, 'ismap'), (None, 'keytype'), (None, 'label'), (None, 'leftspacing'), (None, 'lang'), (None, 'list'), (None, 'longdesc'), (None, 'loop'), (None, 'loopcount'), (None, 'loopend'), (None, 'loopstart'), (None, 'low'), (None, 'lowsrc'), (None, 'max'), (None, 'maxlength'), (None, 'media'), (None, 'method'), (None, 'min'), (None, 'multiple'), (None, 'name'), (None, 'nohref'), (None, 'noshade'), (None, 'nowrap'), (None, 'open'), (None, 'optimum'), (None, 'pattern'), (None, 'ping'), (None, 'point-size'), (None, 'poster'), (None, 'pqg'), (None, 'preload'), (None, 'prompt'), (None, 'radiogroup'), (None, 'readonly'), (None, 'rel'), (None, 'repeat-max'), (None, 'repeat-min'), (None, 'replace'), (None, 'required'), (None, 'rev'), (None, 'rightspacing'), (None, 'rows'), (None, 'rowspan'), (None, 'rules'), (None, 'scope'), (None, 'selected'), (None, 'shape'), (None, 'size'), (None, 'span'), (None, 'src'), (None, 'start'), (None, 'step'), (None, 'style'), (None, 'summary'), (None, 'suppress'), (None, 'tabindex'), (None, 'target'), (None, 'template'), (None, 'title'), (None, 'toppadding'), (None, 'type'), (None, 'unselectable'), (None, 'usemap'), (None, 'urn'), (None, 'valign'), (None, 'value'), (None, 'variable'), (None, 'volume'), (None, 'vspace'), (None, 'vrml'), (None, 'width'), (None, 'wrap'), (namespaces['xml'], 'lang'), # MathML attributes (None, 'actiontype'), (None, 'align'), (None, 'columnalign'), (None, 'columnalign'), (None, 'columnalign'), (None, 'columnlines'), (None, 'columnspacing'), (None, 'columnspan'), (None, 'depth'), (None, 'display'), (None, 'displaystyle'), (None, 'equalcolumns'), (None, 'equalrows'), (None, 'fence'), (None, 'fontstyle'), (None, 'fontweight'), (None, 'frame'), (None, 'height'), (None, 'linethickness'), (None, 'lspace'), (None, 'mathbackground'), (None, 'mathcolor'), (None, 'mathvariant'), (None, 'mathvariant'), (None, 'maxsize'), (None, 'minsize'), (None, 'other'), (None, 'rowalign'), (None, 'rowalign'), (None, 'rowalign'), (None, 'rowlines'), (None, 'rowspacing'), (None, 'rowspan'), (None, 'rspace'), (None, 'scriptlevel'), (None, 'selection'), (None, 'separator'), (None, 'stretchy'), (None, 'width'), (None, 'width'), (namespaces['xlink'], 'href'), (namespaces['xlink'], 'show'), (namespaces['xlink'], 'type'), # SVG attributes (None, 'accent-height'), (None, 'accumulate'), (None, 'additive'), (None, 'alphabetic'), (None, 'arabic-form'), (None, 'ascent'), (None, 'attributeName'), (None, 'attributeType'), (None, 'baseProfile'), (None, 'bbox'), (None, 'begin'), (None, 'by'), (None, 'calcMode'), (None, 'cap-height'), (None, 'class'), (None, 'clip-path'), (None, 'color'), (None, 'color-rendering'), (None, 'content'), (None, 'cx'), (None, 'cy'), (None, 'd'), (None, 'dx'), (None, 'dy'), (None, 'descent'), (None, 'display'), (None, 'dur'), (None, 'end'), (None, 'fill'), (None, 'fill-opacity'), (None, 'fill-rule'), (None, 'font-family'), (None, 'font-size'), (None, 'font-stretch'), (None, 'font-style'), (None, 'font-variant'), (None, 'font-weight'), (None, 'from'), (None, 'fx'), (None, 'fy'), (None, 'g1'), (None, 'g2'), (None, 'glyph-name'), (None, 'gradientUnits'), (None, 'hanging'), (None, 'height'), (None, 'horiz-adv-x'), (None, 'horiz-origin-x'), (None, 'id'), (None, 'ideographic'), (None, 'k'), (None, 'keyPoints'), (None, 'keySplines'), (None, 'keyTimes'), (None, 'lang'), (None, 'marker-end'), (None, 'marker-mid'), (None, 'marker-start'), (None, 'markerHeight'), (None, 'markerUnits'), (None, 'markerWidth'), (None, 'mathematical'), (None, 'max'), (None, 'min'), (None, 'name'), (None, 'offset'), (None, 'opacity'), (None, 'orient'), (None, 'origin'), (None, 'overline-position'), (None, 'overline-thickness'), (None, 'panose-1'), (None, 'path'), (None, 'pathLength'), (None, 'points'), (None, 'preserveAspectRatio'), (None, 'r'), (None, 'refX'), (None, 'refY'), (None, 'repeatCount'), (None, 'repeatDur'), (None, 'requiredExtensions'), (None, 'requiredFeatures'), (None, 'restart'), (None, 'rotate'), (None, 'rx'), (None, 'ry'), (None, 'slope'), (None, 'stemh'), (None, 'stemv'), (None, 'stop-color'), (None, 'stop-opacity'), (None, 'strikethrough-position'), (None, 'strikethrough-thickness'), (None, 'stroke'), (None, 'stroke-dasharray'), (None, 'stroke-dashoffset'), (None, 'stroke-linecap'), (None, 'stroke-linejoin'), (None, 'stroke-miterlimit'), (None, 'stroke-opacity'), (None, 'stroke-width'), (None, 'systemLanguage'), (None, 'target'), (None, 'text-anchor'), (None, 'to'), (None, 'transform'), (None, 'type'), (None, 'u1'), (None, 'u2'), (None, 'underline-position'), (None, 'underline-thickness'), (None, 'unicode'), (None, 'unicode-range'), (None, 'units-per-em'), (None, 'values'), (None, 'version'), (None, 'viewBox'), (None, 'visibility'), (None, 'width'), (None, 'widths'), (None, 'x'), (None, 'x-height'), (None, 'x1'), (None, 'x2'), (namespaces['xlink'], 'actuate'), (namespaces['xlink'], 'arcrole'), (namespaces['xlink'], 'href'), (namespaces['xlink'], 'role'), (namespaces['xlink'], 'show'), (namespaces['xlink'], 'title'), (namespaces['xlink'], 'type'), (namespaces['xml'], 'base'), (namespaces['xml'], 'lang'), (namespaces['xml'], 'space'), (None, 'y'), (None, 'y1'), (None, 'y2'), (None, 'zoomAndPan'), )) attr_val_is_uri = frozenset(( (None, 'href'), (None, 'src'), (None, 'cite'), (None, 'action'), (None, 'longdesc'), (None, 'poster'), (None, 'background'), (None, 'datasrc'), (None, 'dynsrc'), (None, 'lowsrc'), (None, 'ping'), (namespaces['xlink'], 'href'), (namespaces['xml'], 'base'), )) svg_attr_val_allows_ref = frozenset(( (None, 'clip-path'), (None, 'color-profile'), (None, 'cursor'), (None, 'fill'), (None, 'filter'), (None, 'marker'), (None, 'marker-start'), (None, 'marker-mid'), (None, 'marker-end'), (None, 'mask'), (None, 'stroke'), )) svg_allow_local_href = frozenset(( (None, 'altGlyph'), (None, 'animate'), (None, 'animateColor'), (None, 'animateMotion'), (None, 'animateTransform'), (None, 'cursor'), (None, 'feImage'), (None, 'filter'), (None, 'linearGradient'), (None, 'pattern'), (None, 'radialGradient'), (None, 'textpath'), (None, 'tref'), (None, 'set'), (None, 'use') )) allowed_css_properties = frozenset(( 'azimuth', 'background-color', 'border-bottom-color', 'border-collapse', 'border-color', 'border-left-color', 'border-right-color', 'border-top-color', 'clear', 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'overflow', 'pause', 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness', 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation', 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent', 'unicode-bidi', 'vertical-align', 'voice-family', 'volume', 'white-space', 'width', )) allowed_css_keywords = frozenset(( 'auto', 'aqua', 'black', 'block', 'blue', 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left', 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive', 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top', 'transparent', 'underline', 'white', 'yellow', )) allowed_svg_properties = frozenset(( 'fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-opacity', )) allowed_protocols = frozenset(( 'ed2k', 'ftp', 'http', 'https', 'irc', 'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal', 'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag', 'ssh', 'sftp', 'rtsp', 'afs', 'data', )) allowed_content_types = frozenset(( 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'text/plain', )) data_content_type = re.compile(r''' ^ # Match a content type / (?P[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+) # Match any character set and encoding (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?) |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?) # Assume the rest is data ,.* $ ''', re.VERBOSE) class Filter(base.Filter): """ sanitization of XHTML+MathML+SVG and of inline style attributes.""" def __init__(self, source, allowed_elements=allowed_elements, allowed_attributes=allowed_attributes, allowed_css_properties=allowed_css_properties, allowed_css_keywords=allowed_css_keywords, allowed_svg_properties=allowed_svg_properties, allowed_protocols=allowed_protocols, allowed_content_types=allowed_content_types, attr_val_is_uri=attr_val_is_uri, svg_attr_val_allows_ref=svg_attr_val_allows_ref, svg_allow_local_href=svg_allow_local_href): super(Filter, self).__init__(source) self.allowed_elements = allowed_elements self.allowed_attributes = allowed_attributes self.allowed_css_properties = allowed_css_properties self.allowed_css_keywords = allowed_css_keywords self.allowed_svg_properties = allowed_svg_properties self.allowed_protocols = allowed_protocols self.allowed_content_types = allowed_content_types self.attr_val_is_uri = attr_val_is_uri self.svg_attr_val_allows_ref = svg_attr_val_allows_ref self.svg_allow_local_href = svg_allow_local_href def __iter__(self): for token in base.Filter.__iter__(self): token = self.sanitize_token(token) if token: yield token # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and # stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style # attributes are parsed, and a restricted set, # specified by # ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through. # attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified # in ALLOWED_PROTOCOLS are allowed. # # sanitize_html('') # => <script> do_nasty_stuff() </script> # sanitize_html('Click here for $100') # => Click here for $100 def sanitize_token(self, token): # accommodate filters which use token_type differently token_type = token["type"] if token_type in ("StartTag", "EndTag", "EmptyTag"): name = token["name"] namespace = token["namespace"] if ((namespace, name) in self.allowed_elements or (namespace is None and (namespaces["html"], name) in self.allowed_elements)): return self.allowed_token(token) else: return self.disallowed_token(token) elif token_type == "Comment": pass else: return token def allowed_token(self, token): if "data" in token: attrs = token["data"] attr_names = set(attrs.keys()) # Remove forbidden attributes for to_remove in (attr_names - self.allowed_attributes): del token["data"][to_remove] attr_names.remove(to_remove) # Remove attributes with disallowed URL values for attr in (attr_names & self.attr_val_is_uri): assert attr in attrs # I don't have a clue where this regexp comes from or why it matches those # characters, nor why we call unescape. I just know it's always been here. # Should you be worried by this comment in a sanitizer? Yes. On the other hand, all # this will do is remove *more* than it otherwise would. val_unescaped = re.sub("[`\x00-\x20\x7f-\xa0\s]+", '', unescape(attrs[attr])).lower() # remove replacement characters from unescaped characters val_unescaped = val_unescaped.replace("\ufffd", "") try: uri = urlparse.urlparse(val_unescaped) except ValueError: uri = None del attrs[attr] if uri and uri.scheme: if uri.scheme not in self.allowed_protocols: del attrs[attr] if uri.scheme == 'data': m = data_content_type.match(uri.path) if not m: del attrs[attr] elif m.group('content_type') not in self.allowed_content_types: del attrs[attr] for attr in self.svg_attr_val_allows_ref: if attr in attrs: attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', ' ', unescape(attrs[attr])) if (token["name"] in self.svg_allow_local_href and (namespaces['xlink'], 'href') in attrs and re.search('^\s*[^#\s].*', attrs[(namespaces['xlink'], 'href')])): del attrs[(namespaces['xlink'], 'href')] if (None, 'style') in attrs: attrs[(None, 'style')] = self.sanitize_css(attrs[(None, 'style')]) token["data"] = attrs return token def disallowed_token(self, token): token_type = token["type"] if token_type == "EndTag": token["data"] = "" % token["name"] elif token["data"]: assert token_type in ("StartTag", "EmptyTag") attrs = [] for (ns, name), v in token["data"].items(): attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v))) token["data"] = "<%s%s>" % (token["name"], ''.join(attrs)) else: token["data"] = "<%s>" % token["name"] if token.get("selfClosing"): token["data"] = token["data"][:-1] + "/>" token["type"] = "Characters" del token["name"] return token def sanitize_css(self, style): # disallow urls style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) # gauntlet if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return '' if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): return '' clean = [] for prop, value in re.findall("([-\w]+)\s*:\s*([^:;]*)", style): if not value: continue if prop.lower() in self.allowed_css_properties: clean.append(prop + ': ' + value + ';') elif prop.split('-')[0].lower() in ['background', 'border', 'margin', 'padding']: for keyword in value.split(): if keyword not in self.allowed_css_keywords and \ not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword): # noqa break else: clean.append(prop + ': ' + value + ';') elif prop.lower() in self.allowed_svg_properties: clean.append(prop + ': ' + value + ';') return ' '.join(clean) _vendor/html5lib/filters/whitespace.pyo000064400000003177152527136320014273 0ustar00 abc@`sddlmZmZmZddlZddlmZddlmZm Z dj e Z ej de Z d ej fd YZ d ZdS( i(tabsolute_importtdivisiontunicode_literalsNi(tbasei(trcdataElementstspaceCharactersuu[%s]+tFiltercB`s-eZeddgeeZdZRS(upreutextareacc`sd}xtjj|D]}|d}|dkr[|sN|d|jkr[|d7}ns|dkrz|rz|d8}nT| r|dkr|drd |ds _vendor/html5lib/filters/base.pyo000064400000002122152527136320013036 0ustar00 abc@`s6ddlmZmZmZdefdYZdS(i(tabsolute_importtdivisiontunicode_literalstFiltercB`s#eZdZdZdZRS(cC`s ||_dS(N(tsource(tselfR((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyt__init__scC`s t|jS(N(titerR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyt__iter__scC`st|j|S(N(tgetattrR(Rtname((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyt __getattr__ s(t__name__t __module__RRR (((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyRs  N(t __future__RRRtobjectR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyts_vendor/html5lib/filters/__init__.pyc000064400000000240152527136320013646 0ustar00 abc@sdS(N((((sI/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/__init__.pytt_vendor/html5lib/filters/lint.pyo000064400000004075152527136320013103 0ustar00 abc@`sddlmZmZmZddlmZddlmZddlm Z m Z ddlm Z dj e Z d ej fd YZ d S( i(tabsolute_importtdivisiontunicode_literals(t text_typei(tbasei(t namespacest voidElements(tspaceCharactersutFiltercB`seZedZdZRS(cC`s#tt|j|||_dS(N(tsuperRt__init__trequire_matching_tags(tselftsourceR ((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyR sc c`sg}xtjj|D]}|d}|dkr|d}|d}| s`|tdkro|tkron|dkr|jr|j||fnx|djD]\\}}}qWn|dkr%|d}|d}| s|tdkr |tkr q|jr|j}qnx|d kr>|d}n_|dkrf|d}|d krqn7|d kr|d}n|d krn|dkrn|VqWdS(NutypeuStartTaguEmptyTagu namespaceunameuhtmludatauEndTaguCommentu CharactersuSpaceCharactersuDoctypeuEntityuSerializerError(uStartTaguEmptyTag(u CharactersuSpaceCharacters( RRt__iter__RRR tappendtitemstpop( R t open_elementsttokenttypet namespacetnametvaluetstarttdata((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyRsF    ##   #           (t__name__t __module__tTrueR R(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyR s N(t __future__RRRtpip._vendor.sixRtRt constantsRRRtjoinR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyts _vendor/html5lib/filters/base.pyc000064400000002122152527136320013022 0ustar00 abc@`s6ddlmZmZmZdefdYZdS(i(tabsolute_importtdivisiontunicode_literalstFiltercB`s#eZdZdZdZRS(cC`s ||_dS(N(tsource(tselfR((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyt__init__scC`s t|jS(N(titerR(R((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyt__iter__scC`st|j|S(N(tgetattrR(Rtname((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyt __getattr__ s(t__name__t __module__RRR (((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyRs  N(t __future__RRRtobjectR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/base.pyts_vendor/html5lib/filters/base.py000064400000000436152527136320012665 0ustar00from __future__ import absolute_import, division, unicode_literals class Filter(object): def __init__(self, source): self.source = source def __iter__(self): return iter(self.source) def __getattr__(self, name): return getattr(self.source, name) _vendor/html5lib/filters/lint.py000064400000006445152527136320012727 0ustar00from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type from . import base from ..constants import namespaces, voidElements from ..constants import spaceCharacters spaceCharacters = "".join(spaceCharacters) class Filter(base.Filter): def __init__(self, source, require_matching_tags=True): super(Filter, self).__init__(source) self.require_matching_tags = require_matching_tags def __iter__(self): open_elements = [] for token in base.Filter.__iter__(self): type = token["type"] if type in ("StartTag", "EmptyTag"): namespace = token["namespace"] name = token["name"] assert namespace is None or isinstance(namespace, text_type) assert namespace != "" assert isinstance(name, text_type) assert name != "" assert isinstance(token["data"], dict) if (not namespace or namespace == namespaces["html"]) and name in voidElements: assert type == "EmptyTag" else: assert type == "StartTag" if type == "StartTag" and self.require_matching_tags: open_elements.append((namespace, name)) for (namespace, name), value in token["data"].items(): assert namespace is None or isinstance(namespace, text_type) assert namespace != "" assert isinstance(name, text_type) assert name != "" assert isinstance(value, text_type) elif type == "EndTag": namespace = token["namespace"] name = token["name"] assert namespace is None or isinstance(namespace, text_type) assert namespace != "" assert isinstance(name, text_type) assert name != "" if (not namespace or namespace == namespaces["html"]) and name in voidElements: assert False, "Void element reported as EndTag token: %(tag)s" % {"tag": name} elif self.require_matching_tags: start = open_elements.pop() assert start == (namespace, name) elif type == "Comment": data = token["data"] assert isinstance(data, text_type) elif type in ("Characters", "SpaceCharacters"): data = token["data"] assert isinstance(data, text_type) assert data != "" if type == "SpaceCharacters": assert data.strip(spaceCharacters) == "" elif type == "Doctype": name = token["name"] assert name is None or isinstance(name, text_type) assert token["publicId"] is None or isinstance(name, text_type) assert token["systemId"] is None or isinstance(name, text_type) elif type == "Entity": assert isinstance(token["name"], text_type) elif type == "SerializerError": assert isinstance(token["data"], text_type) else: assert False, "Unknown token type: %(type)s" % {"type": type} yield token _vendor/html5lib/filters/__init__.pyo000064400000000240152527136320013662 0ustar00 abc@sdS(N((((sI/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/__init__.pytt_vendor/html5lib/filters/sanitizer.pyo000064400000062062152527136320014145 0ustar00 abcE@`s2ddlmZmZmZddlZddlmZmZddlm Z ddl m Z ddl mZmZd gZeed d fed d fed d fed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed d fed d!fed d"fed d#fed d$fed d%fed d&fed d'fed d(fed d)fed d*fed d+fed d,fed d-fed d.fed d/fed d0fed d1fed d2fed d3fed d4fed d5fed d6fed d7fed d8fed d9fed d:fed d;fed d<fed d=fed d>fed d?fed d@fed dAfed dBfed dCfed dDfed dEfed dFfed dGfed dHfed dIfed dJfed dKfed dLfed dMfed dNfed dOfed dPfed dQfed dRfed dSfed dTfed dUfed dVfed dWfed dXfed dYfed dZfed d[fed d\fed d]fed d^fed d_fed d`fed dafed dbfed dcfed ddfed defed dffed dgfed dhfed difed djfed dkfed dlfed dmfedndofedndpfedndqfedndrfedndsfedndtfedndufedndvfedndwfedndxfedndyfedndzfednd{fednd|fednd}fednd~fedndfedndfedndfedndfedndfedndfedndfedndfedndfedndfedndfedd feddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddffZed4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddded1dfddddddddddddddddddddddddddddddddddddddddedOdfedOdPfedOd%fdddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcddedOdfedOdfedOdfedOdfedOdPfedOdfedOd%fed1dfed1dfed1dfdedfdgdhfCZedidjdkdldmdndodpdqdrdsedOdfed1dff Zedtdudvdwdxdydzd{d|d}d~f ZedddddddddddddddfZedZedZedZedZedZejd1ejZd2e j fd3YZ dS(i(tabsolute_importtdivisiontunicode_literalsN(tescapetunescape(t urllib_parsei(tbasei(t namespacestprefixesuFilteruhtmluauabbruacronymuaddressuareauarticleuasideuaudioububigu blockquoteubrubuttonucanvasucaptionucenteruciteucodeucolucolgroupucommandudatagridudatalistuddudeludetailsudfnudialogudirudivudludtuemu event-sourceufieldsetu figcaptionufigureufooterufontuformuheaderuh1uh2uh3uh4uh5uh6uhruiuimguinputuinsukeygenukbdulabelulegenduliumumapumenuumeterumulticolunavunextiduoluoutputuoptgroupuoptionupupreuprogressuqususampusectionuselectusmallusoundusourceuspaceruspanustrikeustrongusubusuputableutbodyutdutextareautimeutfootuthutheadutruttuuuuluvaruvideoumathmlumactionumathumerrorumfracumiu mmultiscriptsumnumoumoverumpaddedumphantomu mprescriptsumrootumrowumspaceumsqrtumstyleumsubumsubsupumsupumtableumtdumtextumtrumunderu munderoverunoneusvguanimateu animateColoru animateMotionuanimateTransformuclipPathucircleudefsudescuellipseu font-faceufont-face-nameu font-face-srcuguglyphuhkernulinearGradientulineumarkerumetadatau missing-glyphumpathupathupolygonupolylineuradialGradienturectusetustopuswitchutextutitleutspanuuseuacceptuaccept-charsetu accesskeyuactionualignualtu autocompleteu autofocusuaxisu backgroundubalanceubgcoloru bgpropertiesuborderu bordercolorubordercolordarkubordercolorlightu bottompaddingu cellpaddingu cellspacinguchu challengeucharucharoffuchoffucharsetucheckeduclassuclearucolorucolsucolspanucompactucontenteditableucontrolsucoordsudataudatafldu datapagesizeudatasrcudatetimeudefaultudelayudisabledu draggableudynsrcuenctypeuendufaceuforuframeu galleryimgugutteruheadersuheightu hidefocusuhiddenuhighuhrefuhreflanguhspaceuiconuidu inputmodeuismapukeytypeu leftspacingulangulistulongdesculoopu loopcountuloopendu loopstartulowulowsrcumaxu maxlengthumediaumethoduminumultipleunameunohrefunoshadeunowrapuopenuoptimumupatternupingu point-sizeuposterupqgupreloadupromptu radiogroupureadonlyurelu repeat-maxu repeat-minureplaceurequiredurevu rightspacingurowsurowspanurulesuscopeuselectedushapeusizeusrcustartustepustyleusummaryusuppressutabindexutargetutemplateu toppaddingutypeu unselectableuusemapuurnuvalignuvalueuvariableuvolumeuvspaceuvrmluwidthuwrapuxmlu actiontypeu columnalignu columnlinesu columnspacingu columnspanudepthudisplayu displaystyleu equalcolumnsu equalrowsufenceu fontstyleu fontweightu linethicknessulspaceumathbackgroundu mathcoloru mathvariantumaxsizeuminsizeuotherurowalignurowlinesu rowspacingurspaceu scriptlevelu selectionu separatorustretchyuxlinkushowu accent-heightu accumulateuadditiveu alphabeticu arabic-formuascentu attributeNameu attributeTypeu baseProfileubboxubeginubyucalcModeu cap-heightu clip-pathucolor-renderingucontentucxucyududxudyudescentudurufillu fill-opacityu fill-ruleu font-familyu font-sizeu font-stretchu font-styleu font-variantu font-weightufromufxufyug1ug2u glyph-nameu gradientUnitsuhangingu horiz-adv-xuhoriz-origin-xu ideographicuku keyPointsu keySplinesukeyTimesu marker-endu marker-midu marker-startu markerHeightu markerUnitsu markerWidthu mathematicaluoffsetuopacityuorientuoriginuoverline-positionuoverline-thicknessupanose-1u pathLengthupointsupreserveAspectRatioururefXurefYu repeatCountu repeatDururequiredExtensionsurequiredFeaturesurestarturotateurxuryuslopeustemhustemvu stop-coloru stop-opacityustrikethrough-positionustrikethrough-thicknessustrokeustroke-dasharrayustroke-dashoffsetustroke-linecapustroke-linejoinustroke-miterlimitustroke-opacityu stroke-widthusystemLanguageu text-anchorutou transformuu1uu2uunderline-positionuunderline-thicknessuunicodeu unicode-rangeu units-per-emuvaluesuversionuviewBoxu visibilityuwidthsuxux-heightux1ux2uactuateuarcroleuroleubaseuspaceuyuy1uy2u zoomAndPanu color-profileucursorufilterumaskualtGlyphufeImageutextpathutrefuazimuthubackground-coloruborder-bottom-coloruborder-collapseu border-coloruborder-left-coloruborder-right-coloruborder-top-coloru directionu elevationufloatuletter-spacingu line-heightuoverflowupauseu pause-afteru pause-beforeupitchu pitch-rangeurichnessuspeaku speak-headeru speak-numeraluspeak-punctuationu speech-rateustressu text-alignutext-decorationu text-indentu unicode-bidiuvertical-alignu voice-familyu white-spaceuautouaquaublackublockublueuboldubothubottomubrownucollapseudashedudottedufuchsiaugrayugreenu !importantuitaliculeftulimeumaroonumediumunavyunormaluoliveupointerupurpleuredurightusolidusilverutealutopu transparentu underlineuwhiteuyellowued2kuftpuhttpuhttpsuircumailtounewsugopherunntputelnetuwebcaluxmppucalltoufeeduaimursyncutagusshusftpurtspuafsu image/pngu image/jpegu image/gifu image/webpu image/bmpu text/plainuL ^ # Match a content type / (?P[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+) # Match any character set and encoding (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?) |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?) # Assume the rest is data ,.* $ tFilterc B`sbeZdZeeeeeee e e e d Z dZdZdZdZdZRS(uA sanitization of XHTML+MathML+SVG and of inline style attributes.c C`sttt|j|||_||_||_||_||_||_||_ | |_ | |_ | |_ dS(N( tsuperR t__init__tallowed_elementstallowed_attributestallowed_css_propertiestallowed_css_keywordstallowed_svg_propertiestallowed_protocolstallowed_content_typestattr_val_is_uritsvg_attr_val_allows_reftsvg_allow_local_href( tselftsourceR R RRRRRRRR((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR s          cc`s>x7tjj|D]#}|j|}|r|VqqWdS(N(RR t__iter__tsanitize_token(Rttoken((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyRscC`s|d}|d kr|d}|d}||f|jksd|dkrqtd|f|jkrq|j|S|j|Sn|dkrn|SdS( NutypeuStartTaguEndTaguEmptyTagunameu namespaceuhtmluComment(uStartTaguEndTaguEmptyTag(R tNoneRt allowed_tokentdisallowed_token(RRt token_typetnamet namespace((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyRs       c C`s9d|kr5|d}t|j}x-||jD]}|d|=|j|q6Wx||j@D]}tjddt||j}|j dd}yt j |}Wnt k rd}||=nX|rf|j rf|j |jkr||=n|j dkr[tj|j}|s3||=qX|jd|jkrX||=qXq[qfqfWxC|jD]8}||kritjddt||||unameudatau %s="%s"u%s:%su<%s%s>uu<%s>u selfClosingiu/>u Characters(titemstappendRRRtjointget(RRRR1tnsRtv((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR2s   #A$ cC`sctjdjd|}tjd|s1dStjd|sGdSg}xtjd|D]\}}|sxq`n|j|jkr|j|d|dq`|jd d jdkr!x|jD],}||j krtjd| rPqqW|j|d|dq`|j|j kr`|j|d|dq`q`Wdj |S(Nuurl\s*\(\s*[^\s)]+?\s*\)\s*u u@^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$uu ^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$u([-\w]+)\s*:\s*([^:;]*)u: u;u-iu backgrounduborderumarginupaddingu\^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$(u backgrounduborderumarginupadding( R$tcompileR%R,tfindallR&RR9tsplitRRR:(Rtstyletcleantproptvaluetkeyword((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR0Fs*  (t__name__t __module__t__doc__R R RRRRRRRRR RRRRR0(((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR s    2 (Nuabbr(Nuaccept(Nuaccept-charset(Nu accesskey(Nuaction(Nualign(Nualt(Nu autocomplete(Nu autofocus(Nuaxis(Nu background(Nubalance(Nubgcolor(Nu bgproperties(Nuborder(Nu bordercolor(Nubordercolordark(Nubordercolorlight(Nu bottompadding(Nu cellpadding(Nu cellspacing(Nuch(Nu challenge(Nuchar(Nucharoff(Nuchoff(Nucharset(Nuchecked(Nucite(Nuclass(Nuclear(Nucolor(Nucols(Nucolspan(Nucompact(Nucontenteditable(Nucontrols(Nucoords(Nudata(Nudatafld(Nu datapagesize(Nudatasrc(Nudatetime(Nudefault(Nudelay(Nudir(Nudisabled(Nu draggable(Nudynsrc(Nuenctype(Nuend(Nuface(Nufor(Nuform(Nuframe(Nu galleryimg(Nugutter(Nuheaders(Nuheight(Nu hidefocus(Nuhidden(Nuhigh(Nuhref(Nuhreflang(Nuhspace(Nuicon(Nuid(Nu inputmode(Nuismap(Nukeytype(Nulabel(Nu leftspacing(Nulang(Nulist(Nulongdesc(Nuloop(Nu loopcount(Nuloopend(Nu loopstart(Nulow(Nulowsrc(Numax(Nu maxlength(Numedia(Numethod(Numin(Numultiple(Nuname(Nunohref(Nunoshade(Nunowrap(Nuopen(Nuoptimum(Nupattern(Nuping(Nu point-size(Nuposter(Nupqg(Nupreload(Nuprompt(Nu radiogroup(Nureadonly(Nurel(Nu repeat-max(Nu repeat-min(Nureplace(Nurequired(Nurev(Nu rightspacing(Nurows(Nurowspan(Nurules(Nuscope(Nuselected(Nushape(Nusize(Nuspan(Nusrc(Nustart(Nustep(Nustyle(Nusummary(Nusuppress(Nutabindex(Nutarget(Nutemplate(Nutitle(Nu toppadding(Nutype(Nu unselectable(Nuusemap(Nuurn(Nuvalign(Nuvalue(Nuvariable(Nuvolume(Nuvspace(Nuvrml(Nuwidth(Nuwrap(Nu actiontype(Nualign(Nu columnalign(Nu columnalign(Nu columnalign(Nu columnlines(Nu columnspacing(Nu columnspan(Nudepth(Nudisplay(Nu displaystyle(Nu equalcolumns(Nu equalrows(Nufence(Nu fontstyle(Nu fontweight(Nuframe(Nuheight(Nu linethickness(Nulspace(Numathbackground(Nu mathcolor(Nu mathvariant(Nu mathvariant(Numaxsize(Numinsize(Nuother(Nurowalign(Nurowalign(Nurowalign(Nurowlines(Nu rowspacing(Nurowspan(Nurspace(Nu scriptlevel(Nu selection(Nu separator(Nustretchy(Nuwidth(Nuwidth(Nu accent-height(Nu accumulate(Nuadditive(Nu alphabetic(Nu arabic-form(Nuascent(Nu attributeName(Nu attributeType(Nu baseProfile(Nubbox(Nubegin(Nuby(NucalcMode(Nu cap-height(Nuclass(Nu clip-path(Nucolor(Nucolor-rendering(Nucontent(Nucx(Nucy(Nud(Nudx(Nudy(Nudescent(Nudisplay(Nudur(Nuend(Nufill(Nu fill-opacity(Nu fill-rule(Nu font-family(Nu font-size(Nu font-stretch(Nu font-style(Nu font-variant(Nu font-weight(Nufrom(Nufx(Nufy(Nug1(Nug2(Nu glyph-name(Nu gradientUnits(Nuhanging(Nuheight(Nu horiz-adv-x(Nuhoriz-origin-x(Nuid(Nu ideographic(Nuk(Nu keyPoints(Nu keySplines(NukeyTimes(Nulang(Nu marker-end(Nu marker-mid(Nu marker-start(Nu markerHeight(Nu markerUnits(Nu markerWidth(Nu mathematical(Numax(Numin(Nuname(Nuoffset(Nuopacity(Nuorient(Nuorigin(Nuoverline-position(Nuoverline-thickness(Nupanose-1(Nupath(Nu pathLength(Nupoints(NupreserveAspectRatio(Nur(NurefX(NurefY(Nu repeatCount(Nu repeatDur(NurequiredExtensions(NurequiredFeatures(Nurestart(Nurotate(Nurx(Nury(Nuslope(Nustemh(Nustemv(Nu stop-color(Nu stop-opacity(Nustrikethrough-position(Nustrikethrough-thickness(Nustroke(Nustroke-dasharray(Nustroke-dashoffset(Nustroke-linecap(Nustroke-linejoin(Nustroke-miterlimit(Nustroke-opacity(Nu stroke-width(NusystemLanguage(Nutarget(Nu text-anchor(Nuto(Nu transform(Nutype(Nuu1(Nuu2(Nuunderline-position(Nuunderline-thickness(Nuunicode(Nu unicode-range(Nu units-per-em(Nuvalues(Nuversion(NuviewBox(Nu visibility(Nuwidth(Nuwidths(Nux(Nux-height(Nux1(Nux2(Nuy(Nuy1(Nuy2(Nu zoomAndPan(Nuhref(Nusrc(Nucite(Nuaction(Nulongdesc(Nuposter(Nu background(Nudatasrc(Nudynsrc(Nulowsrc(Nuping(Nu clip-path(Nu color-profile(Nucursor(Nufill(Nufilter(Numarker(Nu marker-start(Nu marker-mid(Nu marker-end(Numask(Nustroke(NualtGlyph(Nuanimate(Nu animateColor(Nu animateMotion(NuanimateTransform(Nucursor(NufeImage(Nufilter(NulinearGradient(Nupattern(NuradialGradient(Nutextpath(Nutref(Nuset(Nuuse(.uazimuthubackground-coloruborder-bottom-coloruborder-collapseu border-coloruborder-left-coloruborder-right-coloruborder-top-coloruclearucolorucursoru directionudisplayu elevationufloatufontu font-familyu font-sizeu font-styleu font-variantu font-weightuheightuletter-spacingu line-heightuoverflowupauseu pause-afteru pause-beforeupitchu pitch-rangeurichnessuspeaku speak-headeru speak-numeraluspeak-punctuationu speech-rateustressu text-alignutext-decorationu text-indentu unicode-bidiuvertical-alignu voice-familyuvolumeu white-spaceuwidth('uautouaquaublackublockublueuboldubothubottomubrownucenterucollapseudashedudottedufuchsiaugrayugreenu !importantuitaliculeftulimeumaroonumediumunoneunavyunormalunowrapuoliveupointerupurpleuredurightusolidusilverutealutopu transparentu underlineuwhiteuyellow(ufillu fill-opacityu fill-ruleustrokeu stroke-widthustroke-linecapustroke-linejoinustroke-opacity(ued2kuftpuhttpuhttpsuircumailtounewsugopherunntputelnetuwebcaluxmppucalltoufeeduurnuaimursyncutagusshusftpurtspuafsudata(u image/pngu image/jpegu image/gifu image/webpu image/bmpu text/plain(!t __future__RRRR$txml.sax.saxutilsRRtpip._vendor.six.movesRR(tRt constantsRRt__all__t frozensetR RR RRRRRRRRR>tVERBOSER+R (((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyts2                                                                                                                                                                                           _vendor/html5lib/filters/sanitizer.pyc000064400000062253152527136320014133 0ustar00 abcE@`s2ddlmZmZmZddlZddlmZmZddlm Z ddl m Z ddl mZmZd gZeed d fed d fed d fed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed dfed d fed d!fed d"fed d#fed d$fed d%fed d&fed d'fed d(fed d)fed d*fed d+fed d,fed d-fed d.fed d/fed d0fed d1fed d2fed d3fed d4fed d5fed d6fed d7fed d8fed d9fed d:fed d;fed d<fed d=fed d>fed d?fed d@fed dAfed dBfed dCfed dDfed dEfed dFfed dGfed dHfed dIfed dJfed dKfed dLfed dMfed dNfed dOfed dPfed dQfed dRfed dSfed dTfed dUfed dVfed dWfed dXfed dYfed dZfed d[fed d\fed d]fed d^fed d_fed d`fed dafed dbfed dcfed ddfed defed dffed dgfed dhfed difed djfed dkfed dlfed dmfedndofedndpfedndqfedndrfedndsfedndtfedndufedndvfedndwfedndxfedndyfedndzfednd{fednd|fednd}fednd~fedndfedndfedndfedndfedndfedndfedndfedndfedndfedndfedndfedd feddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddfeddffZed4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddded1dfddddddddddddddddddddddddddddddddddddddddedOdfedOdPfedOd%fdddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcddedOdfedOdfedOdfedOdfedOdPfedOdfedOd%fed1dfed1dfed1dfdedfdgdhfCZedidjdkdldmdndodpdqdrdsedOdfed1dff Zedtdudvdwdxdydzd{d|d}d~f ZedddddddddddddddfZedZedZedZedZedZejd1ejZd2e j fd3YZ dS(i(tabsolute_importtdivisiontunicode_literalsN(tescapetunescape(t urllib_parsei(tbasei(t namespacestprefixesuFilteruhtmluauabbruacronymuaddressuareauarticleuasideuaudioububigu blockquoteubrubuttonucanvasucaptionucenteruciteucodeucolucolgroupucommandudatagridudatalistuddudeludetailsudfnudialogudirudivudludtuemu event-sourceufieldsetu figcaptionufigureufooterufontuformuheaderuh1uh2uh3uh4uh5uh6uhruiuimguinputuinsukeygenukbdulabelulegenduliumumapumenuumeterumulticolunavunextiduoluoutputuoptgroupuoptionupupreuprogressuqususampusectionuselectusmallusoundusourceuspaceruspanustrikeustrongusubusuputableutbodyutdutextareautimeutfootuthutheadutruttuuuuluvaruvideoumathmlumactionumathumerrorumfracumiu mmultiscriptsumnumoumoverumpaddedumphantomu mprescriptsumrootumrowumspaceumsqrtumstyleumsubumsubsupumsupumtableumtdumtextumtrumunderu munderoverunoneusvguanimateu animateColoru animateMotionuanimateTransformuclipPathucircleudefsudescuellipseu font-faceufont-face-nameu font-face-srcuguglyphuhkernulinearGradientulineumarkerumetadatau missing-glyphumpathupathupolygonupolylineuradialGradienturectusetustopuswitchutextutitleutspanuuseuacceptuaccept-charsetu accesskeyuactionualignualtu autocompleteu autofocusuaxisu backgroundubalanceubgcoloru bgpropertiesuborderu bordercolorubordercolordarkubordercolorlightu bottompaddingu cellpaddingu cellspacinguchu challengeucharucharoffuchoffucharsetucheckeduclassuclearucolorucolsucolspanucompactucontenteditableucontrolsucoordsudataudatafldu datapagesizeudatasrcudatetimeudefaultudelayudisabledu draggableudynsrcuenctypeuendufaceuforuframeu galleryimgugutteruheadersuheightu hidefocusuhiddenuhighuhrefuhreflanguhspaceuiconuidu inputmodeuismapukeytypeu leftspacingulangulistulongdesculoopu loopcountuloopendu loopstartulowulowsrcumaxu maxlengthumediaumethoduminumultipleunameunohrefunoshadeunowrapuopenuoptimumupatternupingu point-sizeuposterupqgupreloadupromptu radiogroupureadonlyurelu repeat-maxu repeat-minureplaceurequiredurevu rightspacingurowsurowspanurulesuscopeuselectedushapeusizeusrcustartustepustyleusummaryusuppressutabindexutargetutemplateu toppaddingutypeu unselectableuusemapuurnuvalignuvalueuvariableuvolumeuvspaceuvrmluwidthuwrapuxmlu actiontypeu columnalignu columnlinesu columnspacingu columnspanudepthudisplayu displaystyleu equalcolumnsu equalrowsufenceu fontstyleu fontweightu linethicknessulspaceumathbackgroundu mathcoloru mathvariantumaxsizeuminsizeuotherurowalignurowlinesu rowspacingurspaceu scriptlevelu selectionu separatorustretchyuxlinkushowu accent-heightu accumulateuadditiveu alphabeticu arabic-formuascentu attributeNameu attributeTypeu baseProfileubboxubeginubyucalcModeu cap-heightu clip-pathucolor-renderingucontentucxucyududxudyudescentudurufillu fill-opacityu fill-ruleu font-familyu font-sizeu font-stretchu font-styleu font-variantu font-weightufromufxufyug1ug2u glyph-nameu gradientUnitsuhangingu horiz-adv-xuhoriz-origin-xu ideographicuku keyPointsu keySplinesukeyTimesu marker-endu marker-midu marker-startu markerHeightu markerUnitsu markerWidthu mathematicaluoffsetuopacityuorientuoriginuoverline-positionuoverline-thicknessupanose-1u pathLengthupointsupreserveAspectRatioururefXurefYu repeatCountu repeatDururequiredExtensionsurequiredFeaturesurestarturotateurxuryuslopeustemhustemvu stop-coloru stop-opacityustrikethrough-positionustrikethrough-thicknessustrokeustroke-dasharrayustroke-dashoffsetustroke-linecapustroke-linejoinustroke-miterlimitustroke-opacityu stroke-widthusystemLanguageu text-anchorutou transformuu1uu2uunderline-positionuunderline-thicknessuunicodeu unicode-rangeu units-per-emuvaluesuversionuviewBoxu visibilityuwidthsuxux-heightux1ux2uactuateuarcroleuroleubaseuspaceuyuy1uy2u zoomAndPanu color-profileucursorufilterumaskualtGlyphufeImageutextpathutrefuazimuthubackground-coloruborder-bottom-coloruborder-collapseu border-coloruborder-left-coloruborder-right-coloruborder-top-coloru directionu elevationufloatuletter-spacingu line-heightuoverflowupauseu pause-afteru pause-beforeupitchu pitch-rangeurichnessuspeaku speak-headeru speak-numeraluspeak-punctuationu speech-rateustressu text-alignutext-decorationu text-indentu unicode-bidiuvertical-alignu voice-familyu white-spaceuautouaquaublackublockublueuboldubothubottomubrownucollapseudashedudottedufuchsiaugrayugreenu !importantuitaliculeftulimeumaroonumediumunavyunormaluoliveupointerupurpleuredurightusolidusilverutealutopu transparentu underlineuwhiteuyellowued2kuftpuhttpuhttpsuircumailtounewsugopherunntputelnetuwebcaluxmppucalltoufeeduaimursyncutagusshusftpurtspuafsu image/pngu image/jpegu image/gifu image/webpu image/bmpu text/plainuL ^ # Match a content type / (?P[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+) # Match any character set and encoding (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?) |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?) # Assume the rest is data ,.* $ tFilterc B`sbeZdZeeeeeee e e e d Z dZdZdZdZdZRS(uA sanitization of XHTML+MathML+SVG and of inline style attributes.c C`sttt|j|||_||_||_||_||_||_||_ | |_ | |_ | |_ dS(N( tsuperR t__init__tallowed_elementstallowed_attributestallowed_css_propertiestallowed_css_keywordstallowed_svg_propertiestallowed_protocolstallowed_content_typestattr_val_is_uritsvg_attr_val_allows_reftsvg_allow_local_href( tselftsourceR R RRRRRRRR((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR s          cc`s>x7tjj|D]#}|j|}|r|VqqWdS(N(RR t__iter__tsanitize_token(Rttoken((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyRscC`s|d}|d kr|d}|d}||f|jksd|dkrqtd|f|jkrq|j|S|j|Sn|dkrn|SdS( NutypeuStartTaguEndTaguEmptyTagunameu namespaceuhtmluComment(uStartTaguEndTaguEmptyTag(R tNoneRt allowed_tokentdisallowed_token(RRt token_typetnamet namespace((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyRs       c C`sKd|krG|d}t|j}x-||jD]}|d|=|j|q6Wx||j@D]}||ks~ttjddt||j }|j dd}yt j |}Wnt k rd}||=nX|rf|jrf|j|jkr||=n|jdkrmtj|j}|sE||=qj|jd|jkrj||=qjqmqfqfWxC|jD]8}||kr{tjddt||||unameudatauStartTaguEmptyTagu %s="%s"u%s:%su<%s%s>uu<%s>u selfClosingiu/>u Characters(uStartTaguEmptyTag(R$titemstappendRRRtjointget(RRRR2tnsRtv((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR2s   #A$ cC`sctjdjd|}tjd|s1dStjd|sGdSg}xtjd|D]\}}|sxq`n|j|jkr|j|d|dq`|jd d jdkr!x|jD],}||j krtjd| rPqqW|j|d|dq`|j|j kr`|j|d|dq`q`Wdj |S(Nuurl\s*\(\s*[^\s)]+?\s*\)\s*u u@^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$uu ^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$u([-\w]+)\s*:\s*([^:;]*)u: u;u-iu backgrounduborderumarginupaddingu\^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$(u backgrounduborderumarginupadding( R%tcompileR&R-tfindallR'RR:tsplitRRR;(Rtstyletcleantproptvaluetkeyword((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR1Fs*  (t__name__t __module__t__doc__R R RRRRRRRRR RRRRR1(((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyR s    2 (Nuabbr(Nuaccept(Nuaccept-charset(Nu accesskey(Nuaction(Nualign(Nualt(Nu autocomplete(Nu autofocus(Nuaxis(Nu background(Nubalance(Nubgcolor(Nu bgproperties(Nuborder(Nu bordercolor(Nubordercolordark(Nubordercolorlight(Nu bottompadding(Nu cellpadding(Nu cellspacing(Nuch(Nu challenge(Nuchar(Nucharoff(Nuchoff(Nucharset(Nuchecked(Nucite(Nuclass(Nuclear(Nucolor(Nucols(Nucolspan(Nucompact(Nucontenteditable(Nucontrols(Nucoords(Nudata(Nudatafld(Nu datapagesize(Nudatasrc(Nudatetime(Nudefault(Nudelay(Nudir(Nudisabled(Nu draggable(Nudynsrc(Nuenctype(Nuend(Nuface(Nufor(Nuform(Nuframe(Nu galleryimg(Nugutter(Nuheaders(Nuheight(Nu hidefocus(Nuhidden(Nuhigh(Nuhref(Nuhreflang(Nuhspace(Nuicon(Nuid(Nu inputmode(Nuismap(Nukeytype(Nulabel(Nu leftspacing(Nulang(Nulist(Nulongdesc(Nuloop(Nu loopcount(Nuloopend(Nu loopstart(Nulow(Nulowsrc(Numax(Nu maxlength(Numedia(Numethod(Numin(Numultiple(Nuname(Nunohref(Nunoshade(Nunowrap(Nuopen(Nuoptimum(Nupattern(Nuping(Nu point-size(Nuposter(Nupqg(Nupreload(Nuprompt(Nu radiogroup(Nureadonly(Nurel(Nu repeat-max(Nu repeat-min(Nureplace(Nurequired(Nurev(Nu rightspacing(Nurows(Nurowspan(Nurules(Nuscope(Nuselected(Nushape(Nusize(Nuspan(Nusrc(Nustart(Nustep(Nustyle(Nusummary(Nusuppress(Nutabindex(Nutarget(Nutemplate(Nutitle(Nu toppadding(Nutype(Nu unselectable(Nuusemap(Nuurn(Nuvalign(Nuvalue(Nuvariable(Nuvolume(Nuvspace(Nuvrml(Nuwidth(Nuwrap(Nu actiontype(Nualign(Nu columnalign(Nu columnalign(Nu columnalign(Nu columnlines(Nu columnspacing(Nu columnspan(Nudepth(Nudisplay(Nu displaystyle(Nu equalcolumns(Nu equalrows(Nufence(Nu fontstyle(Nu fontweight(Nuframe(Nuheight(Nu linethickness(Nulspace(Numathbackground(Nu mathcolor(Nu mathvariant(Nu mathvariant(Numaxsize(Numinsize(Nuother(Nurowalign(Nurowalign(Nurowalign(Nurowlines(Nu rowspacing(Nurowspan(Nurspace(Nu scriptlevel(Nu selection(Nu separator(Nustretchy(Nuwidth(Nuwidth(Nu accent-height(Nu accumulate(Nuadditive(Nu alphabetic(Nu arabic-form(Nuascent(Nu attributeName(Nu attributeType(Nu baseProfile(Nubbox(Nubegin(Nuby(NucalcMode(Nu cap-height(Nuclass(Nu clip-path(Nucolor(Nucolor-rendering(Nucontent(Nucx(Nucy(Nud(Nudx(Nudy(Nudescent(Nudisplay(Nudur(Nuend(Nufill(Nu fill-opacity(Nu fill-rule(Nu font-family(Nu font-size(Nu font-stretch(Nu font-style(Nu font-variant(Nu font-weight(Nufrom(Nufx(Nufy(Nug1(Nug2(Nu glyph-name(Nu gradientUnits(Nuhanging(Nuheight(Nu horiz-adv-x(Nuhoriz-origin-x(Nuid(Nu ideographic(Nuk(Nu keyPoints(Nu keySplines(NukeyTimes(Nulang(Nu marker-end(Nu marker-mid(Nu marker-start(Nu markerHeight(Nu markerUnits(Nu markerWidth(Nu mathematical(Numax(Numin(Nuname(Nuoffset(Nuopacity(Nuorient(Nuorigin(Nuoverline-position(Nuoverline-thickness(Nupanose-1(Nupath(Nu pathLength(Nupoints(NupreserveAspectRatio(Nur(NurefX(NurefY(Nu repeatCount(Nu repeatDur(NurequiredExtensions(NurequiredFeatures(Nurestart(Nurotate(Nurx(Nury(Nuslope(Nustemh(Nustemv(Nu stop-color(Nu stop-opacity(Nustrikethrough-position(Nustrikethrough-thickness(Nustroke(Nustroke-dasharray(Nustroke-dashoffset(Nustroke-linecap(Nustroke-linejoin(Nustroke-miterlimit(Nustroke-opacity(Nu stroke-width(NusystemLanguage(Nutarget(Nu text-anchor(Nuto(Nu transform(Nutype(Nuu1(Nuu2(Nuunderline-position(Nuunderline-thickness(Nuunicode(Nu unicode-range(Nu units-per-em(Nuvalues(Nuversion(NuviewBox(Nu visibility(Nuwidth(Nuwidths(Nux(Nux-height(Nux1(Nux2(Nuy(Nuy1(Nuy2(Nu zoomAndPan(Nuhref(Nusrc(Nucite(Nuaction(Nulongdesc(Nuposter(Nu background(Nudatasrc(Nudynsrc(Nulowsrc(Nuping(Nu clip-path(Nu color-profile(Nucursor(Nufill(Nufilter(Numarker(Nu marker-start(Nu marker-mid(Nu marker-end(Numask(Nustroke(NualtGlyph(Nuanimate(Nu animateColor(Nu animateMotion(NuanimateTransform(Nucursor(NufeImage(Nufilter(NulinearGradient(Nupattern(NuradialGradient(Nutextpath(Nutref(Nuset(Nuuse(.uazimuthubackground-coloruborder-bottom-coloruborder-collapseu border-coloruborder-left-coloruborder-right-coloruborder-top-coloruclearucolorucursoru directionudisplayu elevationufloatufontu font-familyu font-sizeu font-styleu font-variantu font-weightuheightuletter-spacingu line-heightuoverflowupauseu pause-afteru pause-beforeupitchu pitch-rangeurichnessuspeaku speak-headeru speak-numeraluspeak-punctuationu speech-rateustressu text-alignutext-decorationu text-indentu unicode-bidiuvertical-alignu voice-familyuvolumeu white-spaceuwidth('uautouaquaublackublockublueuboldubothubottomubrownucenterucollapseudashedudottedufuchsiaugrayugreenu !importantuitaliculeftulimeumaroonumediumunoneunavyunormalunowrapuoliveupointerupurpleuredurightusolidusilverutealutopu transparentu underlineuwhiteuyellow(ufillu fill-opacityu fill-ruleustrokeu stroke-widthustroke-linecapustroke-linejoinustroke-opacity(ued2kuftpuhttpuhttpsuircumailtounewsugopherunntputelnetuwebcaluxmppucalltoufeeduurnuaimursyncutagusshusftpurtspuafsudata(u image/pngu image/jpegu image/gifu image/webpu image/bmpu text/plain(!t __future__RRRR%txml.sax.saxutilsRRtpip._vendor.six.movesRR)tRt constantsRRt__all__t frozensetR RR RRRRRRRRR?tVERBOSER,R (((sJ/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/sanitizer.pyts2                                                                                                                                                                                           _vendor/html5lib/filters/inject_meta_charset.py000064400000005266152527136320015754 0ustar00from __future__ import absolute_import, division, unicode_literals from . import base class Filter(base.Filter): def __init__(self, source, encoding): base.Filter.__init__(self, source) self.encoding = encoding def __iter__(self): state = "pre_head" meta_found = (self.encoding is None) pending = [] for token in base.Filter.__iter__(self): type = token["type"] if type == "StartTag": if token["name"].lower() == "head": state = "in_head" elif type == "EmptyTag": if token["name"].lower() == "meta": # replace charset with actual encoding has_http_equiv_content_type = False for (namespace, name), value in token["data"].items(): if namespace is not None: continue elif name.lower() == 'charset': token["data"][(namespace, name)] = self.encoding meta_found = True break elif name == 'http-equiv' and value.lower() == 'content-type': has_http_equiv_content_type = True else: if has_http_equiv_content_type and (None, "content") in token["data"]: token["data"][(None, "content")] = 'text/html; charset=%s' % self.encoding meta_found = True elif token["name"].lower() == "head" and not meta_found: # insert meta into empty head yield {"type": "StartTag", "name": "head", "data": token["data"]} yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} yield {"type": "EndTag", "name": "head"} meta_found = True continue elif type == "EndTag": if token["name"].lower() == "head" and pending: # insert meta into head (if necessary) and flush pending queue yield pending.pop(0) if not meta_found: yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} while pending: yield pending.pop(0) meta_found = True state = "post_head" if state == "in_head": pending.append(token) else: yield token _vendor/html5lib/filters/optionaltags.pyo000064400000010464152527136320014640 0ustar00 abc@`sIddlmZmZmZddlmZdejfdYZdS(i(tabsolute_importtdivisiontunicode_literalsi(tbasetFiltercB`s,eZdZdZdZdZRS(cc`shd}}x:|jD]/}|dk r7|||fVn|}|}qW|dk rd||dfVndS(N(tNonetsource(tselft previous1t previous2ttoken((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pytsliders    cc`sx|jD]\}}}|d}|dkra|dsV|j|d|| r|Vqq |dkr|j|d|s|Vqq |Vq WdS(NutypeuStartTagudataunameuEndTag(R tis_optional_starttis_optional_end(RtpreviousR tnextttype((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyt__iter__s      cC`s*|r|dpd}|dkr,|dkS|dkre|dkrHtS|dkr&|d dkSn|d kr|dkrtS|dkr|d dkStSn|d kr|dkr|d dkStSnW|dkr&|dkr|r|ddkr|d dkrtS|d dkStSntS(NutypeuhtmluCommentuSpaceCharactersuheaduStartTaguEmptyTaguEndTagunameubodyuscriptustyleucolgroupucolutbodyutheadutfootutr(uCommentuSpaceCharacters(uStartTaguEmptyTag(uCommentuSpaceCharacters(uscriptustyle(uStartTaguEmptyTag(utbodyutheadutfoot(RtTruetFalse(RttagnameRRR((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyR s4            cC`s|r|dpd}|d5kr,|d6kS|d7krk|d krR|d |kS|d kpg|dkSn|d8kr|d kr|d d9kS|dkr|d kp|dkStSn|dkr|d:kr|d d;kS|d kp|dkSn|d,kr8|d kr|d d<kS|d kp4|dkSnI|d=krw|d kr^|d d>kS|d kps|dkSn |d/kr|d?krtS|d kr|d d/kStSn|d@kr|d kr|d dAkS|d1kr|d kp|dkStSn~|d2krB|d kr)|d d1kS|d kp>|dkSn?|dBkr|d krh|d dCkS|d kp}|dkSntS(DNutypeuhtmluheadubodyuCommentuSpaceCharactersuliuoptgrouputruStartTagunameuEndTagudtuddupuEmptyTaguaddressuarticleuasideu blockquoteudatagridudialogudirudivudlufieldsetufooteruformuh1uh2uh3uh4uh5uh6uheaderuhrumenuunavuolupreusectionutableuuluoptionurturpucolgrouputheadutbodyutfootutduth(uhtmluheadubody(uCommentuSpaceCharacters(uliuoptgrouputr(udtudd(udtudd(uStartTaguEmptyTag(uaddressuarticleuasideu blockquoteudatagridudialogudirudivudlufieldsetufooteruformuh1uh2uh3uh4uh5uh6uheaderuhrumenuunavuolupupreusectionutableuul(uoptionuoptgroup(urturp(urturp(uCommentuSpaceCharacters(utheadutbody(utbodyutfoot(utduth(utduth(RRR(RRRR((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyR Wsf                     (t__name__t __module__R RR R (((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyRs 9N(t __future__RRRtRR(((sM/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/optionaltags.pyts_vendor/html5lib/filters/optionaltags.py000064400000024446152527136320014466 0ustar00from __future__ import absolute_import, division, unicode_literals from . import base class Filter(base.Filter): def slider(self): previous1 = previous2 = None for token in self.source: if previous1 is not None: yield previous2, previous1, token previous2 = previous1 previous1 = token if previous1 is not None: yield previous2, previous1, None def __iter__(self): for previous, token, next in self.slider(): type = token["type"] if type == "StartTag": if (token["data"] or not self.is_optional_start(token["name"], previous, next)): yield token elif type == "EndTag": if not self.is_optional_end(token["name"], next): yield token else: yield token def is_optional_start(self, tagname, previous, next): type = next and next["type"] or None if tagname in 'html': # An html element's start tag may be omitted if the first thing # inside the html element is not a space character or a comment. return type not in ("Comment", "SpaceCharacters") elif tagname == 'head': # A head element's start tag may be omitted if the first thing # inside the head element is an element. # XXX: we also omit the start tag if the head element is empty if type in ("StartTag", "EmptyTag"): return True elif type == "EndTag": return next["name"] == "head" elif tagname == 'body': # A body element's start tag may be omitted if the first thing # inside the body element is not a space character or a comment, # except if the first thing inside the body element is a script # or style element and the node immediately preceding the body # element is a head element whose end tag has been omitted. if type in ("Comment", "SpaceCharacters"): return False elif type == "StartTag": # XXX: we do not look at the preceding event, so we never omit # the body element's start tag if it's followed by a script or # a style element. return next["name"] not in ('script', 'style') else: return True elif tagname == 'colgroup': # A colgroup element's start tag may be omitted if the first thing # inside the colgroup element is a col element, and if the element # is not immediately preceded by another colgroup element whose # end tag has been omitted. if type in ("StartTag", "EmptyTag"): # XXX: we do not look at the preceding event, so instead we never # omit the colgroup element's end tag when it is immediately # followed by another colgroup element. See is_optional_end. return next["name"] == "col" else: return False elif tagname == 'tbody': # A tbody element's start tag may be omitted if the first thing # inside the tbody element is a tr element, and if the element is # not immediately preceded by a tbody, thead, or tfoot element # whose end tag has been omitted. if type == "StartTag": # omit the thead and tfoot elements' end tag when they are # immediately followed by a tbody element. See is_optional_end. if previous and previous['type'] == 'EndTag' and \ previous['name'] in ('tbody', 'thead', 'tfoot'): return False return next["name"] == 'tr' else: return False return False def is_optional_end(self, tagname, next): type = next and next["type"] or None if tagname in ('html', 'head', 'body'): # An html element's end tag may be omitted if the html element # is not immediately followed by a space character or a comment. return type not in ("Comment", "SpaceCharacters") elif tagname in ('li', 'optgroup', 'tr'): # A li element's end tag may be omitted if the li element is # immediately followed by another li element or if there is # no more content in the parent element. # An optgroup element's end tag may be omitted if the optgroup # element is immediately followed by another optgroup element, # or if there is no more content in the parent element. # A tr element's end tag may be omitted if the tr element is # immediately followed by another tr element, or if there is # no more content in the parent element. if type == "StartTag": return next["name"] == tagname else: return type == "EndTag" or type is None elif tagname in ('dt', 'dd'): # A dt element's end tag may be omitted if the dt element is # immediately followed by another dt element or a dd element. # A dd element's end tag may be omitted if the dd element is # immediately followed by another dd element or a dt element, # or if there is no more content in the parent element. if type == "StartTag": return next["name"] in ('dt', 'dd') elif tagname == 'dd': return type == "EndTag" or type is None else: return False elif tagname == 'p': # A p element's end tag may be omitted if the p element is # immediately followed by an address, article, aside, # blockquote, datagrid, dialog, dir, div, dl, fieldset, # footer, form, h1, h2, h3, h4, h5, h6, header, hr, menu, # nav, ol, p, pre, section, table, or ul, element, or if # there is no more content in the parent element. if type in ("StartTag", "EmptyTag"): return next["name"] in ('address', 'article', 'aside', 'blockquote', 'datagrid', 'dialog', 'dir', 'div', 'dl', 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hr', 'menu', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul') else: return type == "EndTag" or type is None elif tagname == 'option': # An option element's end tag may be omitted if the option # element is immediately followed by another option element, # or if it is immediately followed by an optgroup # element, or if there is no more content in the parent # element. if type == "StartTag": return next["name"] in ('option', 'optgroup') else: return type == "EndTag" or type is None elif tagname in ('rt', 'rp'): # An rt element's end tag may be omitted if the rt element is # immediately followed by an rt or rp element, or if there is # no more content in the parent element. # An rp element's end tag may be omitted if the rp element is # immediately followed by an rt or rp element, or if there is # no more content in the parent element. if type == "StartTag": return next["name"] in ('rt', 'rp') else: return type == "EndTag" or type is None elif tagname == 'colgroup': # A colgroup element's end tag may be omitted if the colgroup # element is not immediately followed by a space character or # a comment. if type in ("Comment", "SpaceCharacters"): return False elif type == "StartTag": # XXX: we also look for an immediately following colgroup # element. See is_optional_start. return next["name"] != 'colgroup' else: return True elif tagname in ('thead', 'tbody'): # A thead element's end tag may be omitted if the thead element # is immediately followed by a tbody or tfoot element. # A tbody element's end tag may be omitted if the tbody element # is immediately followed by a tbody or tfoot element, or if # there is no more content in the parent element. # A tfoot element's end tag may be omitted if the tfoot element # is immediately followed by a tbody element, or if there is no # more content in the parent element. # XXX: we never omit the end tag when the following element is # a tbody. See is_optional_start. if type == "StartTag": return next["name"] in ['tbody', 'tfoot'] elif tagname == 'tbody': return type == "EndTag" or type is None else: return False elif tagname == 'tfoot': # A tfoot element's end tag may be omitted if the tfoot element # is immediately followed by a tbody element, or if there is no # more content in the parent element. # XXX: we never omit the end tag when the following element is # a tbody. See is_optional_start. if type == "StartTag": return next["name"] == 'tbody' else: return type == "EndTag" or type is None elif tagname in ('td', 'th'): # A td element's end tag may be omitted if the td element is # immediately followed by a td or th element, or if there is # no more content in the parent element. # A th element's end tag may be omitted if the th element is # immediately followed by a td or th element, or if there is # no more content in the parent element. if type == "StartTag": return next["name"] in ('td', 'th') else: return type == "EndTag" or type is None return False _vendor/html5lib/filters/inject_meta_charset.pyc000064400000004315152527136320016111 0ustar00 abc@`sIddlmZmZmZddlmZdejfdYZdS(i(tabsolute_importtdivisiontunicode_literalsi(tbasetFiltercB`seZdZdZRS(cC`s tjj||||_dS(N(RRt__init__tencoding(tselftsourceR((sT/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/inject_meta_charset.pyRsc c`sd}|jdk}g}xvtjj|D]b}|d}|dkrl|djdkrod}qon|dkr|djdkr^t}xE|d jD]~\\}}} |dk rqq|jd kr|j|d ||fs_vendor/html5lib/filters/lint.pyc000064400000005726152527136320013073 0ustar00 abc@`sddlmZmZmZddlmZddlmZddlm Z m Z ddlm Z dj e Z d ej fd YZ d S( i(tabsolute_importtdivisiontunicode_literals(t text_typei(tbasei(t namespacest voidElements(tspaceCharactersutFiltercB`seZedZdZRS(cC`s#tt|j|||_dS(N(tsuperRt__init__trequire_matching_tags(tselftsourceR ((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyR sc c`sPg}xCtjj|D]/}|d}|dkr|d}|d}|dksjt|tsjt|dks|tt|tst|dkstt|dtst| s|tdkr|t kr|dkstn|dkst|dkr1|j r1|j ||fnx|dj D]\\}}}|dksut|tsut|dkstt|tst|dkstt|tsBtqBWny|d kr|d}|d}|dks t|ts t|dkstt|ts2t|dksDt| s[|tdkr|t krt std i|d 6qC|j rC|j}|||fkstqCn|d kr|d}t|tsCtn[|dkrR|d}t|tst|dks%t|dkrC|jtdksOtqCn|dkr|d}|dkst|tst|ddkst|tst|ddksCt|tsCtnm|dkrt|dtsCtnE|dkr&t|dtsCtnt sCtdi|d6|VqWdS(NutypeuStartTaguEmptyTagu namespaceunameuudatauhtmluEndTagu.Void element reported as EndTag token: %(tag)sutaguCommentu CharactersuSpaceCharactersuDoctypeupublicIdusystemIduEntityuSerializerErroruUnknown token type: %(type)s(uStartTaguEmptyTag(u CharactersuSpaceCharacters(RRt__iter__tNonet isinstanceRtAssertionErrortdictRRR tappendtitemstFalsetpoptstripR( R t open_elementsttokenttypet namespacetnametvaluetstarttdata((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyRsl    !##!   !#        !  !%(  (t__name__t __module__tTrueR R(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyR s N(t __future__RRRtpip._vendor.sixRtRt constantsRRRtjoinR(((sE/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/lint.pyts _vendor/html5lib/filters/alphabeticalattributes.pyo000064400000002562152527136320016654 0ustar00 abc@`sddlmZmZmZddlmZyddlmZWn!ek rcddl mZnXdej fdYZ dS(i(tabsolute_importtdivisiontunicode_literalsi(tbase(t OrderedDicttFiltercB`seZdZRS(cc`sxtjj|D]k}|ddkryt}x7t|djddD]\}}|||t(uStartTaguEmptyTag(RRt__iter__Rtsortedtitems(tselfttokentattrstnametvalue((sW/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/alphabeticalattributes.pyR s  (t__name__t __module__R (((sW/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/alphabeticalattributes.pyR sN( t __future__RRRR Rt collectionsRt ImportErrort ordereddictR(((sW/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/alphabeticalattributes.pyts  _vendor/html5lib/filters/__init__.py000064400000000000152527136320013475 0ustar00_vendor/html5lib/filters/alphabeticalattributes.py000064400000001155152527136320016472 0ustar00from __future__ import absolute_import, division, unicode_literals from . import base try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict class Filter(base.Filter): def __iter__(self): for token in base.Filter.__iter__(self): if token["type"] in ("StartTag", "EmptyTag"): attrs = OrderedDict() for name, value in sorted(token["data"].items(), key=lambda x: x[0]): attrs[name] = value token["data"] = attrs yield token _vendor/html5lib/filters/alphabeticalattributes.pyc000064400000002562152527136320016640 0ustar00 abc@`sddlmZmZmZddlmZyddlmZWn!ek rcddl mZnXdej fdYZ dS(i(tabsolute_importtdivisiontunicode_literalsi(tbase(t OrderedDicttFiltercB`seZdZRS(cc`sxtjj|D]k}|ddkryt}x7t|djddD]\}}|||t(uStartTaguEmptyTag(RRt__iter__Rtsortedtitems(tselfttokentattrstnametvalue((sW/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/alphabeticalattributes.pyR s  (t__name__t __module__R (((sW/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/alphabeticalattributes.pyR sN( t __future__RRRR Rt collectionsRt ImportErrort ordereddictR(((sW/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/filters/alphabeticalattributes.pyts  _vendor/html5lib/_utils.pyo000064400000010423152527136320011756 0ustar00 abc@`sGddlmZmZmZddlZddlmZddlmZyddl j j Z Wn#e k rddlj jZ nXddddd d d gZejdd koejd dkZy.edZeeesedZnWn eZnXeZdefdYZdZdZdZdZdS(i(tabsolute_importtdivisiontunicode_literalsN(t ModuleType(t text_typeu default_etreeuMethodDispatcheruisSurrogatePairusurrogatePairToCodepointumoduleFactoryFactoryusupports_lone_surrogatesuPY27iiiu"\uD800"u u"\uD800"tMethodDispatchercB`s#eZdZddZdZRS(upDict with 2 special properties: On initiation, keys that are lists, sets or tuples are converted to multiple keys so accessing any one of the items in the original list-like object returns the matching value md = MethodDispatcher({("foo", "bar"):"baz"}) md["foo"] == "baz" A default value which can be set through the default attribute. cC`sg}xi|D]a\}}t|ttttfr[x7|D]}|j||fq;Wq |j||fq Wtj||d|_ dS(N( t isinstancetlistttuplet frozensettsettappendtdictt__init__tNonetdefault(tselftitemst _dictEntriestnametvaluetitem((s?/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_utils.pyR 4s cC`stj|||jS(N(R tgetR(Rtkey((s?/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_utils.pyt __getitem__Cs((t__name__t __module__t__doc__R R(((s?/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_utils.pyR's  cC`sht|dkogt|ddkogt|ddkogt|ddkogt|ddkS(Niiiiiii(tlentord(tdata((s?/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_utils.pytisSurrogatePairJs,cC`s2dt|dddt|dd}|S(Niiiiii(R(Rtchar_val((s?/usr/lib/python2.7/site-packages/pip/_vendor/html5lib/_utils.pytsurrogatePairToCodepointPsc`sifd}|S(Nc`sttjtdr(d|j}n d|j}t|j}y|||SWntk rt|}|||}|jj|dkri|s0    &   #  _vendor/html5lib/html5parser.py000064400000344662152527136320012565 0ustar00from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import with_metaclass, viewkeys, PY3 import types try: from collections import OrderedDict except ImportError: from pip._vendor.ordereddict import OrderedDict from . import _inputstream from . import _tokenizer from . import treebuilders from .treebuilders.base import Marker from . import _utils from .constants import ( spaceCharacters, asciiUpper2Lower, specialElements, headingElements, cdataElements, rcdataElements, tokenTypes, tagTokenTypes, namespaces, htmlIntegrationPointElements, mathmlTextIntegrationPointElements, adjustForeignAttributes as adjustForeignAttributesMap, adjustMathMLAttributes, adjustSVGAttributes, E, ReparseException ) def parse(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs): """Parse a string or file-like object into a tree""" tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) return p.parse(doc, **kwargs) def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs): tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) return p.parseFragment(doc, container=container, **kwargs) def method_decorator_metaclass(function): class Decorated(type): def __new__(meta, classname, bases, classDict): for attributeName, attribute in classDict.items(): if isinstance(attribute, types.FunctionType): attribute = function(attribute) classDict[attributeName] = attribute return type.__new__(meta, classname, bases, classDict) return Decorated class HTMLParser(object): """HTML parser. Generates a tree structure from a stream of (possibly malformed) HTML""" def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False): """ strict - raise an exception when a parse error is encountered tree - a treebuilder class controlling the type of tree that will be returned. Built in treebuilders can be accessed through html5lib.treebuilders.getTreeBuilder(treeType) """ # Raise an exception on the first error encountered self.strict = strict if tree is None: tree = treebuilders.getTreeBuilder("etree") self.tree = tree(namespaceHTMLElements) self.errors = [] self.phases = dict([(name, cls(self, self.tree)) for name, cls in getPhases(debug).items()]) def _parse(self, stream, innerHTML=False, container="div", scripting=False, **kwargs): self.innerHTMLMode = innerHTML self.container = container self.scripting = scripting self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs) self.reset() try: self.mainLoop() except ReparseException: self.reset() self.mainLoop() def reset(self): self.tree.reset() self.firstStartTag = False self.errors = [] self.log = [] # only used with debug mode # "quirks" / "limited quirks" / "no quirks" self.compatMode = "no quirks" if self.innerHTMLMode: self.innerHTML = self.container.lower() if self.innerHTML in cdataElements: self.tokenizer.state = self.tokenizer.rcdataState elif self.innerHTML in rcdataElements: self.tokenizer.state = self.tokenizer.rawtextState elif self.innerHTML == 'plaintext': self.tokenizer.state = self.tokenizer.plaintextState else: # state already is data state # self.tokenizer.state = self.tokenizer.dataState pass self.phase = self.phases["beforeHtml"] self.phase.insertHtmlElement() self.resetInsertionMode() else: self.innerHTML = False # pylint:disable=redefined-variable-type self.phase = self.phases["initial"] self.lastPhase = None self.beforeRCDataPhase = None self.framesetOK = True @property def documentEncoding(self): """The name of the character encoding that was used to decode the input stream, or :obj:`None` if that is not determined yet. """ if not hasattr(self, 'tokenizer'): return None return self.tokenizer.stream.charEncoding[0].name def isHTMLIntegrationPoint(self, element): if (element.name == "annotation-xml" and element.namespace == namespaces["mathml"]): return ("encoding" in element.attributes and element.attributes["encoding"].translate( asciiUpper2Lower) in ("text/html", "application/xhtml+xml")) else: return (element.namespace, element.name) in htmlIntegrationPointElements def isMathMLTextIntegrationPoint(self, element): return (element.namespace, element.name) in mathmlTextIntegrationPointElements def mainLoop(self): CharactersToken = tokenTypes["Characters"] SpaceCharactersToken = tokenTypes["SpaceCharacters"] StartTagToken = tokenTypes["StartTag"] EndTagToken = tokenTypes["EndTag"] CommentToken = tokenTypes["Comment"] DoctypeToken = tokenTypes["Doctype"] ParseErrorToken = tokenTypes["ParseError"] for token in self.normalizedTokens(): prev_token = None new_token = token while new_token is not None: prev_token = new_token currentNode = self.tree.openElements[-1] if self.tree.openElements else None currentNodeNamespace = currentNode.namespace if currentNode else None currentNodeName = currentNode.name if currentNode else None type = new_token["type"] if type == ParseErrorToken: self.parseError(new_token["data"], new_token.get("datavars", {})) new_token = None else: if (len(self.tree.openElements) == 0 or currentNodeNamespace == self.tree.defaultNamespace or (self.isMathMLTextIntegrationPoint(currentNode) and ((type == StartTagToken and token["name"] not in frozenset(["mglyph", "malignmark"])) or type in (CharactersToken, SpaceCharactersToken))) or (currentNodeNamespace == namespaces["mathml"] and currentNodeName == "annotation-xml" and type == StartTagToken and token["name"] == "svg") or (self.isHTMLIntegrationPoint(currentNode) and type in (StartTagToken, CharactersToken, SpaceCharactersToken))): phase = self.phase else: phase = self.phases["inForeignContent"] if type == CharactersToken: new_token = phase.processCharacters(new_token) elif type == SpaceCharactersToken: new_token = phase.processSpaceCharacters(new_token) elif type == StartTagToken: new_token = phase.processStartTag(new_token) elif type == EndTagToken: new_token = phase.processEndTag(new_token) elif type == CommentToken: new_token = phase.processComment(new_token) elif type == DoctypeToken: new_token = phase.processDoctype(new_token) if (type == StartTagToken and prev_token["selfClosing"] and not prev_token["selfClosingAcknowledged"]): self.parseError("non-void-element-with-trailing-solidus", {"name": prev_token["name"]}) # When the loop finishes it's EOF reprocess = True phases = [] while reprocess: phases.append(self.phase) reprocess = self.phase.processEOF() if reprocess: assert self.phase not in phases def normalizedTokens(self): for token in self.tokenizer: yield self.normalizeToken(token) def parse(self, stream, *args, **kwargs): """Parse a HTML document into a well-formed tree stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) scripting - treat noscript elements as if javascript was turned on """ self._parse(stream, False, None, *args, **kwargs) return self.tree.getDocument() def parseFragment(self, stream, *args, **kwargs): """Parse a HTML fragment into a well-formed tree fragment container - name of the element we're setting the innerHTML property if set to None, default to 'div' stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) scripting - treat noscript elements as if javascript was turned on """ self._parse(stream, True, *args, **kwargs) return self.tree.getFragment() def parseError(self, errorcode="XXX-undefined-error", datavars=None): # XXX The idea is to make errorcode mandatory. if datavars is None: datavars = {} self.errors.append((self.tokenizer.stream.position(), errorcode, datavars)) if self.strict: raise ParseError(E[errorcode] % datavars) def normalizeToken(self, token): """ HTML5 specific normalizations to the token stream """ if token["type"] == tokenTypes["StartTag"]: raw = token["data"] token["data"] = OrderedDict(raw) if len(raw) > len(token["data"]): # we had some duplicated attribute, fix so first wins token["data"].update(raw[::-1]) return token def adjustMathMLAttributes(self, token): adjust_attributes(token, adjustMathMLAttributes) def adjustSVGAttributes(self, token): adjust_attributes(token, adjustSVGAttributes) def adjustForeignAttributes(self, token): adjust_attributes(token, adjustForeignAttributesMap) def reparseTokenNormal(self, token): # pylint:disable=unused-argument self.parser.phase() def resetInsertionMode(self): # The name of this method is mostly historical. (It's also used in the # specification.) last = False newModes = { "select": "inSelect", "td": "inCell", "th": "inCell", "tr": "inRow", "tbody": "inTableBody", "thead": "inTableBody", "tfoot": "inTableBody", "caption": "inCaption", "colgroup": "inColumnGroup", "table": "inTable", "head": "inBody", "body": "inBody", "frameset": "inFrameset", "html": "beforeHead" } for node in self.tree.openElements[::-1]: nodeName = node.name new_phase = None if node == self.tree.openElements[0]: assert self.innerHTML last = True nodeName = self.innerHTML # Check for conditions that should only happen in the innerHTML # case if nodeName in ("select", "colgroup", "head", "html"): assert self.innerHTML if not last and node.namespace != self.tree.defaultNamespace: continue if nodeName in newModes: new_phase = self.phases[newModes[nodeName]] break elif last: new_phase = self.phases["inBody"] break self.phase = new_phase def parseRCDataRawtext(self, token, contentType): """Generic RCDATA/RAWTEXT Parsing algorithm contentType - RCDATA or RAWTEXT """ assert contentType in ("RAWTEXT", "RCDATA") self.tree.insertElement(token) if contentType == "RAWTEXT": self.tokenizer.state = self.tokenizer.rawtextState else: self.tokenizer.state = self.tokenizer.rcdataState self.originalPhase = self.phase self.phase = self.phases["text"] @_utils.memoize def getPhases(debug): def log(function): """Logger that records which phase processes each token""" type_names = dict((value, key) for key, value in tokenTypes.items()) def wrapped(self, *args, **kwargs): if function.__name__.startswith("process") and len(args) > 0: token = args[0] try: info = {"type": type_names[token['type']]} except: raise if token['type'] in tagTokenTypes: info["name"] = token['name'] self.parser.log.append((self.parser.tokenizer.state.__name__, self.parser.phase.__class__.__name__, self.__class__.__name__, function.__name__, info)) return function(self, *args, **kwargs) else: return function(self, *args, **kwargs) return wrapped def getMetaclass(use_metaclass, metaclass_func): if use_metaclass: return method_decorator_metaclass(metaclass_func) else: return type # pylint:disable=unused-argument class Phase(with_metaclass(getMetaclass(debug, log))): """Base class for helper object that implements each phase of processing """ def __init__(self, parser, tree): self.parser = parser self.tree = tree def processEOF(self): raise NotImplementedError def processComment(self, token): # For most phases the following is correct. Where it's not it will be # overridden. self.tree.insertComment(token, self.tree.openElements[-1]) def processDoctype(self, token): self.parser.parseError("unexpected-doctype") def processCharacters(self, token): self.tree.insertText(token["data"]) def processSpaceCharacters(self, token): self.tree.insertText(token["data"]) def processStartTag(self, token): return self.startTagHandler[token["name"]](token) def startTagHtml(self, token): if not self.parser.firstStartTag and token["name"] == "html": self.parser.parseError("non-html-root") # XXX Need a check here to see if the first start tag token emitted is # this token... If it's not, invoke self.parser.parseError(). for attr, value in token["data"].items(): if attr not in self.tree.openElements[0].attributes: self.tree.openElements[0].attributes[attr] = value self.parser.firstStartTag = False def processEndTag(self, token): return self.endTagHandler[token["name"]](token) class InitialPhase(Phase): def processSpaceCharacters(self, token): pass def processComment(self, token): self.tree.insertComment(token, self.tree.document) def processDoctype(self, token): name = token["name"] publicId = token["publicId"] systemId = token["systemId"] correct = token["correct"] if (name != "html" or publicId is not None or systemId is not None and systemId != "about:legacy-compat"): self.parser.parseError("unknown-doctype") if publicId is None: publicId = "" self.tree.insertDoctype(token) if publicId != "": publicId = publicId.translate(asciiUpper2Lower) if (not correct or token["name"] != "html" or publicId.startswith( ("+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//")) or publicId in ("-//w3o//dtd w3 html strict 3.0//en//", "-/w3c/dtd html 4.0 transitional/en", "html") or publicId.startswith( ("-//w3c//dtd html 4.01 frameset//", "-//w3c//dtd html 4.01 transitional//")) and systemId is None or systemId and systemId.lower() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"): self.parser.compatMode = "quirks" elif (publicId.startswith( ("-//w3c//dtd xhtml 1.0 frameset//", "-//w3c//dtd xhtml 1.0 transitional//")) or publicId.startswith( ("-//w3c//dtd html 4.01 frameset//", "-//w3c//dtd html 4.01 transitional//")) and systemId is not None): self.parser.compatMode = "limited quirks" self.parser.phase = self.parser.phases["beforeHtml"] def anythingElse(self): self.parser.compatMode = "quirks" self.parser.phase = self.parser.phases["beforeHtml"] def processCharacters(self, token): self.parser.parseError("expected-doctype-but-got-chars") self.anythingElse() return token def processStartTag(self, token): self.parser.parseError("expected-doctype-but-got-start-tag", {"name": token["name"]}) self.anythingElse() return token def processEndTag(self, token): self.parser.parseError("expected-doctype-but-got-end-tag", {"name": token["name"]}) self.anythingElse() return token def processEOF(self): self.parser.parseError("expected-doctype-but-got-eof") self.anythingElse() return True class BeforeHtmlPhase(Phase): # helper methods def insertHtmlElement(self): self.tree.insertRoot(impliedTagToken("html", "StartTag")) self.parser.phase = self.parser.phases["beforeHead"] # other def processEOF(self): self.insertHtmlElement() return True def processComment(self, token): self.tree.insertComment(token, self.tree.document) def processSpaceCharacters(self, token): pass def processCharacters(self, token): self.insertHtmlElement() return token def processStartTag(self, token): if token["name"] == "html": self.parser.firstStartTag = True self.insertHtmlElement() return token def processEndTag(self, token): if token["name"] not in ("head", "body", "html", "br"): self.parser.parseError("unexpected-end-tag-before-html", {"name": token["name"]}) else: self.insertHtmlElement() return token class BeforeHeadPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("head", self.startTagHead) ]) self.startTagHandler.default = self.startTagOther self.endTagHandler = _utils.MethodDispatcher([ (("head", "body", "html", "br"), self.endTagImplyHead) ]) self.endTagHandler.default = self.endTagOther def processEOF(self): self.startTagHead(impliedTagToken("head", "StartTag")) return True def processSpaceCharacters(self, token): pass def processCharacters(self, token): self.startTagHead(impliedTagToken("head", "StartTag")) return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagHead(self, token): self.tree.insertElement(token) self.tree.headPointer = self.tree.openElements[-1] self.parser.phase = self.parser.phases["inHead"] def startTagOther(self, token): self.startTagHead(impliedTagToken("head", "StartTag")) return token def endTagImplyHead(self, token): self.startTagHead(impliedTagToken("head", "StartTag")) return token def endTagOther(self, token): self.parser.parseError("end-tag-after-implied-root", {"name": token["name"]}) class InHeadPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("title", self.startTagTitle), (("noframes", "style"), self.startTagNoFramesStyle), ("noscript", self.startTagNoscript), ("script", self.startTagScript), (("base", "basefont", "bgsound", "command", "link"), self.startTagBaseLinkCommand), ("meta", self.startTagMeta), ("head", self.startTagHead) ]) self.startTagHandler.default = self.startTagOther self.endTagHandler = _utils.MethodDispatcher([ ("head", self.endTagHead), (("br", "html", "body"), self.endTagHtmlBodyBr) ]) self.endTagHandler.default = self.endTagOther # the real thing def processEOF(self): self.anythingElse() return True def processCharacters(self, token): self.anythingElse() return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagHead(self, token): self.parser.parseError("two-heads-are-not-better-than-one") def startTagBaseLinkCommand(self, token): self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True def startTagMeta(self, token): self.tree.insertElement(token) self.tree.openElements.pop() token["selfClosingAcknowledged"] = True attributes = token["data"] if self.parser.tokenizer.stream.charEncoding[1] == "tentative": if "charset" in attributes: self.parser.tokenizer.stream.changeEncoding(attributes["charset"]) elif ("content" in attributes and "http-equiv" in attributes and attributes["http-equiv"].lower() == "content-type"): # Encoding it as UTF-8 here is a hack, as really we should pass # the abstract Unicode string, and just use the # ContentAttrParser on that, but using UTF-8 allows all chars # to be encoded and as a ASCII-superset works. data = _inputstream.EncodingBytes(attributes["content"].encode("utf-8")) parser = _inputstream.ContentAttrParser(data) codec = parser.parse() self.parser.tokenizer.stream.changeEncoding(codec) def startTagTitle(self, token): self.parser.parseRCDataRawtext(token, "RCDATA") def startTagNoFramesStyle(self, token): # Need to decide whether to implement the scripting-disabled case self.parser.parseRCDataRawtext(token, "RAWTEXT") def startTagNoscript(self, token): if self.parser.scripting: self.parser.parseRCDataRawtext(token, "RAWTEXT") else: self.tree.insertElement(token) self.parser.phase = self.parser.phases["inHeadNoscript"] def startTagScript(self, token): self.tree.insertElement(token) self.parser.tokenizer.state = self.parser.tokenizer.scriptDataState self.parser.originalPhase = self.parser.phase self.parser.phase = self.parser.phases["text"] def startTagOther(self, token): self.anythingElse() return token def endTagHead(self, token): node = self.parser.tree.openElements.pop() assert node.name == "head", "Expected head got %s" % node.name self.parser.phase = self.parser.phases["afterHead"] def endTagHtmlBodyBr(self, token): self.anythingElse() return token def endTagOther(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def anythingElse(self): self.endTagHead(impliedTagToken("head")) class InHeadNoscriptPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), (("basefont", "bgsound", "link", "meta", "noframes", "style"), self.startTagBaseLinkCommand), (("head", "noscript"), self.startTagHeadNoscript), ]) self.startTagHandler.default = self.startTagOther self.endTagHandler = _utils.MethodDispatcher([ ("noscript", self.endTagNoscript), ("br", self.endTagBr), ]) self.endTagHandler.default = self.endTagOther def processEOF(self): self.parser.parseError("eof-in-head-noscript") self.anythingElse() return True def processComment(self, token): return self.parser.phases["inHead"].processComment(token) def processCharacters(self, token): self.parser.parseError("char-in-head-noscript") self.anythingElse() return token def processSpaceCharacters(self, token): return self.parser.phases["inHead"].processSpaceCharacters(token) def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagBaseLinkCommand(self, token): return self.parser.phases["inHead"].processStartTag(token) def startTagHeadNoscript(self, token): self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) def startTagOther(self, token): self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) self.anythingElse() return token def endTagNoscript(self, token): node = self.parser.tree.openElements.pop() assert node.name == "noscript", "Expected noscript got %s" % node.name self.parser.phase = self.parser.phases["inHead"] def endTagBr(self, token): self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) self.anythingElse() return token def endTagOther(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def anythingElse(self): # Caller must raise parse error first! self.endTagNoscript(impliedTagToken("noscript")) class AfterHeadPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("body", self.startTagBody), ("frameset", self.startTagFrameset), (("base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "title"), self.startTagFromHead), ("head", self.startTagHead) ]) self.startTagHandler.default = self.startTagOther self.endTagHandler = _utils.MethodDispatcher([(("body", "html", "br"), self.endTagHtmlBodyBr)]) self.endTagHandler.default = self.endTagOther def processEOF(self): self.anythingElse() return True def processCharacters(self, token): self.anythingElse() return token def startTagHtml(self, token): return self.parser.phases["inBody"].processStartTag(token) def startTagBody(self, token): self.parser.framesetOK = False self.tree.insertElement(token) self.parser.phase = self.parser.phases["inBody"] def startTagFrameset(self, token): self.tree.insertElement(token) self.parser.phase = self.parser.phases["inFrameset"] def startTagFromHead(self, token): self.parser.parseError("unexpected-start-tag-out-of-my-head", {"name": token["name"]}) self.tree.openElements.append(self.tree.headPointer) self.parser.phases["inHead"].processStartTag(token) for node in self.tree.openElements[::-1]: if node.name == "head": self.tree.openElements.remove(node) break def startTagHead(self, token): self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) def startTagOther(self, token): self.anythingElse() return token def endTagHtmlBodyBr(self, token): self.anythingElse() return token def endTagOther(self, token): self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) def anythingElse(self): self.tree.insertElement(impliedTagToken("body", "StartTag")) self.parser.phase = self.parser.phases["inBody"] self.parser.framesetOK = True class InBodyPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#parsing-main-inbody # the really-really-really-very crazy mode def __init__(self, parser, tree): Phase.__init__(self, parser, tree) # Set this to the default handler self.processSpaceCharacters = self.processSpaceCharactersNonPre self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), (("base", "basefont", "bgsound", "command", "link", "meta", "script", "style", "title"), self.startTagProcessInHead), ("body", self.startTagBody), ("frameset", self.startTagFrameset), (("address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "main", "menu", "nav", "ol", "p", "section", "summary", "ul"), self.startTagCloseP), (headingElements, self.startTagHeading), (("pre", "listing"), self.startTagPreListing), ("form", self.startTagForm), (("li", "dd", "dt"), self.startTagListItem), ("plaintext", self.startTagPlaintext), ("a", self.startTagA), (("b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u"), self.startTagFormatting), ("nobr", self.startTagNobr), ("button", self.startTagButton), (("applet", "marquee", "object"), self.startTagAppletMarqueeObject), ("xmp", self.startTagXmp), ("table", self.startTagTable), (("area", "br", "embed", "img", "keygen", "wbr"), self.startTagVoidFormatting), (("param", "source", "track"), self.startTagParamSource), ("input", self.startTagInput), ("hr", self.startTagHr), ("image", self.startTagImage), ("isindex", self.startTagIsIndex), ("textarea", self.startTagTextarea), ("iframe", self.startTagIFrame), ("noscript", self.startTagNoscript), (("noembed", "noframes"), self.startTagRawtext), ("select", self.startTagSelect), (("rp", "rt"), self.startTagRpRt), (("option", "optgroup"), self.startTagOpt), (("math"), self.startTagMath), (("svg"), self.startTagSvg), (("caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr"), self.startTagMisplaced) ]) self.startTagHandler.default = self.startTagOther self.endTagHandler = _utils.MethodDispatcher([ ("body", self.endTagBody), ("html", self.endTagHtml), (("address", "article", "aside", "blockquote", "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "main", "menu", "nav", "ol", "pre", "section", "summary", "ul"), self.endTagBlock), ("form", self.endTagForm), ("p", self.endTagP), (("dd", "dt", "li"), self.endTagListItem), (headingElements, self.endTagHeading), (("a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"), self.endTagFormatting), (("applet", "marquee", "object"), self.endTagAppletMarqueeObject), ("br", self.endTagBr), ]) self.endTagHandler.default = self.endTagOther def isMatchingFormattingElement(self, node1, node2): return (node1.name == node2.name and node1.namespace == node2.namespace and node1.attributes == node2.attributes) # helper def addFormattingElement(self, token): self.tree.insertElement(token) element = self.tree.openElements[-1] matchingElements = [] for node in self.tree.activeFormattingElements[::-1]: if node is Marker: break elif self.isMatchingFormattingElement(node, element): matchingElements.append(node) assert len(matchingElements) <= 3 if len(matchingElements) == 3: self.tree.activeFormattingElements.remove(matchingElements[-1]) self.tree.activeFormattingElements.append(element) # the real deal def processEOF(self): allowed_elements = frozenset(("dd", "dt", "li", "p", "tbody", "td", "tfoot", "th", "thead", "tr", "body", "html")) for node in self.tree.openElements[::-1]: if node.name not in allowed_elements: self.parser.parseError("expected-closing-tag-but-got-eof") break # Stop parsing def processSpaceCharactersDropNewline(self, token): # Sometimes (start of
, , and