if not isinstance(ip, (IPv4Address, CIDR)):<EOL><INDENT>if str(ip).find('<STR_LIT:/>') == -<NUM_LIT:1>:<EOL><INDENT>ip = IPv4Address(ip)<EOL><DEDENT>else:<EOL><INDENT>ip = CIDR(ip)<EOL><DEDENT><DEDENT>if isinstance(ip, IPv4Address):<EOL><INDENT>if ip < self._first_ip or ip > self._last_ip:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>elif isinstance(ip, CIDR):<EOL><INDENT>if ip._nm._ip_dec == <NUM_LIT>and self._nm._ip_dec != <NUM_LIT>:<EOL><INDENT>compare_to_first = self._net_ip._ip_dec<EOL>compare_to_last = self._bc_ip._ip_dec<EOL><DEDENT>else:<EOL><INDENT>compare_to_first = self._first_ip._ip_dec<EOL>compare_to_last = self._last_ip._ip_dec<EOL><DEDENT>if ip._first_ip._ip_dec < compare_to_first orip._last_ip._ip_dec > compare_to_last:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Return true if the given address in amongst the usable addresses,
        or if the given CIDR is contained in this one.


return self.get()<EOL>


return '<STR_LIT>' % (str(self.get_ip()), str(self.get_netmask()))<EOL>

The representation string for this netmask.


return self.get_ip_number()<EOL>


return self.is_valid_ip(item)<EOL>


for i in range(<NUM_LIT:0>, self._ip_num):<EOL><INDENT>yield IPv4Address(self._first_ip_dec + i, notation=IP_DEC)<EOL><DEDENT>

Iterate over IPv4Address objects, one for every usable IP.


t = float(time.time() * <NUM_LIT:1000>)<EOL>r = float(random.random()*<NUM_LIT>)<EOL>a = random.random() * <NUM_LIT><EOL>data = str(t) + '<STR_LIT:U+0020>' + str(r) + '<STR_LIT:U+0020>' + str(a) + '<STR_LIT:U+0020>' + str(args)<EOL>data = hashlib.md5(data.encode()).hexdigest()[:<NUM_LIT:10>]<EOL>return data<EOL>

Generates a universally unique ID.
Any arguments only create more randomness.


return '<STR_LIT>'.join(random.SystemRandom().choice(ALPHABET)<EOL>for _ in range(length))<EOL>

Generate a random string of the specified length.

The returned string is composed of an alphabet that shouldn't include any
characters that are easily mistakeable for one another (I, 1, O, 0), and
hopefully won't accidentally contain any English-language curse words.


@classmethod<EOL><INDENT>def coerce(cls, key, value):<DEDENT>

if not isinstance(value, MutableDict):<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>return MutableDict(value)<EOL><DEDENT>return Mutable.coerce(key, value)<EOL><DEDENT>else:<EOL><INDENT>return value<EOL><DEDENT>

Convert plain dictionaries to MutableDict.


dict.__setitem__(self, key, value)<EOL>self.changed()<EOL>

Detect dictionary set events and emit change events.


dict.__delitem__(self, key)<EOL>self.changed()<EOL>

Detect dictionary del events and emit change events.


@compiles(utcnow)<EOL>def _default_utcnow(element, compiler, **kw):

return "<STR_LIT>"<EOL>

default compilation handler.

    Note that there is no SQL "utcnow()" function; this is a
    "fake" string so that we can produce SQL strings that are dialect-agnostic,
    such as within tests.


@compiles(utcnow, '<STR_LIT>')<EOL>def _sqlite_utcnow(element, compiler, **kw):

return "<STR_LIT>"<EOL>


return "<STR_LIT>"<EOL>


@compiles(utcnow, '<STR_LIT>')<EOL>def _pg_utcnow(element, compiler, **kw):

return "<STR_LIT>"<EOL>


for lcl, rmt in cls._to_ref:<EOL><INDENT>cls._decl_class_registry[lcl]._reference_table(<EOL>cls._decl_class_registry[rmt].__table__)<EOL><DEDENT>cls._to_ref.clear()<EOL>

declarative hook called within the 'before_configure' mapper event.


<EOL>cols = [(sa.Column(), refcol) for refcol in ref_table.primary_key]<EOL>for col, refcol in cols:<EOL><INDENT>setattr(cls, "<STR_LIT>" % (ref_table.name, refcol.name), col)<EOL><DEDENT>cls.__table__.append_constraint(sa.ForeignKeyConstraint(*zip(*cols)))<EOL>

Create a foreign key reference from the local class to the given remote
        table.

        Adds column references to the declarative class and adds a
        ForeignKeyConstraint.


props = {}<EOL>json_eager_load = set(getattr(self, '<STR_LIT>', []))<EOL>for prop in json_eager_load:<EOL><INDENT>getattr(self, prop, None)<EOL><DEDENT>options = self.__dict__.copy()<EOL>blacklist = set(getattr(self, '<STR_LIT>', []))<EOL>blacklist.update(getattr(self, '<STR_LIT>', []))<EOL>for key in options:<EOL><INDENT>if key in blacklist:<EOL><INDENT>continue<EOL><DEDENT>if key.startswith(('<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>continue<EOL><DEDENT>obj = getattr(self, key)<EOL>if isinstance(obj, (datetime, date, time)):<EOL><INDENT>props[key] = obj.isoformat()<EOL>continue<EOL><DEDENT>attr = getattr(self, key)<EOL>if key in json_eager_load and attr:<EOL><INDENT>if hasattr(attr, '<STR_LIT>'):<EOL><INDENT>props[key] = self.__try_to_json(request, attr)<EOL><DEDENT>else:<EOL><INDENT>props[key] = [self.__try_to_json(request, x) for x in attr]<EOL><DEDENT>continue<EOL><DEDENT>if attr and not isinstance(attr, (int, float)):<EOL><INDENT>try:<EOL><INDENT>props[key] = str(attr)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>props[key] = unicode(attr)  <EOL><DEDENT>continue<EOL><DEDENT>props[key] = attr<EOL><DEDENT>return props<EOL>

Main JSONify method

:param request: Pyramid Request object
:type request: <Request>
:return: dictionary ready to be jsonified
:rtype: <dict>


<EOL>if hasattr(attr, '<STR_LIT>'):<EOL><INDENT>return attr.__json__(request)<EOL><DEDENT>raise TypeError('<STR_LIT>' % str(attr))<EOL>

Try to run __json__ on the given object.
Raise TypeError is __json__ is missing

:param request: Pyramid Request object
:type request: <Request>
:param obj: Object to JSONify
:type obj: any object that has __json__ method
:exception: TypeError


dbsession = session_factory()<EOL>zope.sqlalchemy.register(<EOL>dbsession, transaction_manager=transaction_manager)<EOL>return dbsession<EOL>

Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

This function will hook the session to the transaction manager which
will take care of committing any changes.

- When using pyramid_tm it will automatically be committed or aborted
  depending on whether an exception is raised.

- When using scripts you should wrap the session in a manager yourself.
  For example::

      import transaction

      engine = get_engine(settings)
      session_factory = get_session_factory(engine)
      with transaction.manager:
          dbsession = get_tm_session(session_factory, transaction.manager)


@declared_attr<EOL>def m2o(cls):<EOL><INDENT>cls._references((cls.__name__, clsname))<EOL>return relationship(clsname, **kw)<EOL><DEDENT>return m2o<EOL>

Use an event to build a many-to-one relationship on a class.

    This makes use of the :meth:`.References._reference_table` method
    to generate a full foreign key relationship to the remote table.


@declared_attr<EOL>def o2m(cls):<EOL><INDENT>cls._references((clsname, cls.__name__))<EOL>return relationship(clsname, **kw)<EOL><DEDENT>return o2m<EOL>

Use an event to build a one-to-many relationship on a class.

    This makes use of the :meth:`.References._reference_table` method
    to generate a full foreign key relationship from the remote table.


settings = config.get_settings()<EOL>should_create = asbool(settings.get('<STR_LIT>', False))<EOL>should_drop = asbool(settings.get('<STR_LIT>', False))<EOL>config.add_settings({<EOL>"<STR_LIT>": <NUM_LIT:3>,<EOL>"<STR_LIT>": tm_activate_hook,<EOL>"<STR_LIT>": False,<EOL>})<EOL>config.include('<STR_LIT>')<EOL>config.include('<STR_LIT>')<EOL>engine = get_engine(settings)<EOL>session_factory = get_session_factory(engine)<EOL>config.registry['<STR_LIT>'] = session_factory<EOL>config.add_request_method(<EOL>lambda r: get_tm_session(session_factory, r.tm),<EOL>'<STR_LIT>',<EOL>reify=True<EOL>)<EOL>config.include('<STR_LIT>')<EOL>config.action(None, bind_engine, (engine,), {<EOL>'<STR_LIT>': should_create,<EOL>'<STR_LIT>': should_drop<EOL>}, order=<NUM_LIT:10>)<EOL>

Initialize the model for a Pyramid app.

Activate this setup using ``config.include('baka_model')``.


with open(VERSION_FILE, encoding='<STR_LIT:utf-8>') as fp:<EOL><INDENT>content = fp.read()<EOL><DEDENT>match = re.search(r'<STR_LIT>', content, re.M)<EOL>if match:<EOL><INDENT>return match.group(<NUM_LIT:1>)<EOL><DEDENT>raise RuntimeError("<STR_LIT>")<EOL>


<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>

Get the keywords needed to look up the version information.


<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>

Create, populate and return the VersioneerConfig() object.


def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>

Decorator to mark a method as the handler for a particular VCS.


def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):

assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>


def versions_from_parentdir(parentdir_prefix, root, verbose):

rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root)  <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>

Try to determine the version from the parent directory name.

    Source tarballs conventionally unpack into a directory that includes both
    the project name and a version string. We will also support searching up
    two directory levels for an appropriately named parent directory


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>

Extract version information from the given file.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):

if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information from git keywords.


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>

Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>

Return a + if we don't already have one, else return a .


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>"  <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>

Render the given version pieces into the requested style.


<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>'):<EOL><INDENT>root = os.path.dirname(root)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>try:<EOL><INDENT>pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)<EOL>return render(pieces, cfg.style)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>

Get version information or return default if unable to do so.


result = re.match(line_pattern, line)<EOL>if result:<EOL><INDENT>_, lineno, offset, severity, msg = result.groups()<EOL>lineno = int(lineno or <NUM_LIT:1>)<EOL>offset = int(offset or <NUM_LIT:0>)<EOL>errno = <NUM_LIT:2><EOL>if severity == '<STR_LIT:error>':<EOL><INDENT>errno = <NUM_LIT:1><EOL><DEDENT>diag = {<EOL>'<STR_LIT:source>': '<STR_LIT>',<EOL>'<STR_LIT>': {<EOL>'<STR_LIT:start>': {'<STR_LIT>': lineno - <NUM_LIT:1>, '<STR_LIT>': offset},<EOL>'<STR_LIT:end>': {'<STR_LIT>': lineno - <NUM_LIT:1>, '<STR_LIT>': offset + <NUM_LIT:1>}<EOL>},<EOL>'<STR_LIT:message>': msg,<EOL>'<STR_LIT>': errno<EOL>}<EOL>if document:<EOL><INDENT>word = document.word_at_position(diag['<STR_LIT>']['<STR_LIT:start>'])<EOL>if word:<EOL><INDENT>diag['<STR_LIT>']['<STR_LIT:end>']['<STR_LIT>'] = (<EOL>diag['<STR_LIT>']['<STR_LIT:start>']['<STR_LIT>'] + len(word))<EOL><DEDENT><DEDENT>return diag<EOL><DEDENT>

Return a language-server diagnostic from a line of the Mypy error report;
optionally, use the whole document to provide more context on it.


root = os.path.realpath(os.path.abspath(os.getcwd()))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[<NUM_LIT:0>])))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL><DEDENT>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>err = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise VersioneerBadRootError(err)<EOL><DEDENT>try:<EOL><INDENT>me = os.path.realpath(os.path.abspath(__file__))<EOL>me_dir = os.path.normcase(os.path.splitext(me)[<NUM_LIT:0>])<EOL>vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[<NUM_LIT:0>])<EOL>if me_dir != vsr_dir:<EOL><INDENT>print("<STR_LIT>"<EOL>% (os.path.dirname(me), versioneer_py))<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>return root<EOL>

Get the project root directory.

    We require that all commands are run from the project root, i.e. the
    directory that contains setup.py, setup.cfg, and versioneer.py .


<EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>")  <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>return parser.get("<STR_LIT>", name)<EOL><DEDENT>return None<EOL><DEDENT>cfg = VersioneerConfig()<EOL>cfg.VCS = VCS<EOL>cfg.style = get(parser, "<STR_LIT>") or "<STR_LIT>"<EOL>cfg.versionfile_source = get(parser, "<STR_LIT>")<EOL>cfg.versionfile_build = get(parser, "<STR_LIT>")<EOL>cfg.tag_prefix = get(parser, "<STR_LIT>")<EOL>if cfg.tag_prefix in ("<STR_LIT>", '<STR_LIT>'):<EOL><INDENT>cfg.tag_prefix = "<STR_LIT>"<EOL><DEDENT>cfg.parentdir_prefix = get(parser, "<STR_LIT>")<EOL>cfg.verbose = get(parser, "<STR_LIT>")<EOL>return cfg<EOL>

Read the project setup.cfg file to determine Versioneer config.


def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>

Decorator to mark a method as the handler for a particular VCS.


assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>


if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>


GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>


def do_vcs_install(manifest_in, versionfile_source, ipy):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>files = [manifest_in, versionfile_source]<EOL>if ipy:<EOL><INDENT>files.append(ipy)<EOL><DEDENT>try:<EOL><INDENT>me = __file__<EOL>if me.endswith("<STR_LIT>") or me.endswith("<STR_LIT>"):<EOL><INDENT>me = os.path.splitext(me)[<NUM_LIT:0>] + "<STR_LIT>"<EOL><DEDENT>versioneer_file = os.path.relpath(me)<EOL><DEDENT>except NameError:<EOL><INDENT>versioneer_file = "<STR_LIT>"<EOL><DEDENT>files.append(versioneer_file)<EOL>present = False<EOL>try:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith(versionfile_source):<EOL><INDENT>if "<STR_LIT>" in line.strip().split()[<NUM_LIT:1>:]:<EOL><INDENT>present = True<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if not present:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT>")<EOL>f.write("<STR_LIT>" % versionfile_source)<EOL>f.close()<EOL>files.append("<STR_LIT>")<EOL><DEDENT>run_command(GITS, ["<STR_LIT>", "<STR_LIT>"] + files)<EOL>

Git-specific installation logic for Versioneer.

    For Git, this means creating/changing .gitattributes to mark _version.py
    for export-subst keyword substitution.


rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root)  <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>

Try to determine the version from the parent directory name.

    Source tarballs conventionally unpack into a directory that includes both
    the project name and a version string. We will also support searching up
    two directory levels for an appropriately named parent directory


try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL><DEDENT>if not mo:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return json.loads(mo.group(<NUM_LIT:1>))<EOL>

Try to determine the version from _version.py if present.


os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL>

Write the given version number to the given _version.py file.


if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>

Return a + if we don't already have one, else return a .


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]+gHEX] .

    The ".dev0" means dirty. Note that .dev0 sorts backwards
    (a dirty tree will appear "older" than the corresponding clean one),
    but you shouldn't be releasing software with -dirty anyways.

    Exceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>"  <EOL><DEDENT>if style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_pre(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_post(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_pep440_old(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe(pieces)<EOL><DEDENT>elif style == "<STR_LIT>":<EOL><INDENT>rendered = render_git_describe_long(pieces)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % style)<EOL><DEDENT>return {"<STR_LIT:version>": rendered, "<STR_LIT>": pieces["<STR_LIT>"],<EOL>"<STR_LIT>": pieces["<STR_LIT>"], "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": pieces.get("<STR_LIT:date>")}<EOL>

Render the given version pieces into the requested style.


if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>assert cfg.VCS is not None, "<STR_LIT>"<EOL>handlers = HANDLERS.get(cfg.VCS)<EOL>assert handlers, "<STR_LIT>" % cfg.VCS<EOL>verbose = verbose or cfg.verbose<EOL>assert cfg.versionfile_source is not None,"<STR_LIT>"<EOL>assert cfg.tag_prefix is not None, "<STR_LIT>"<EOL>versionfile_abs = os.path.join(root, cfg.versionfile_source)<EOL>get_keywords_f = handlers.get("<STR_LIT>")<EOL>from_keywords_f = handlers.get("<STR_LIT>")<EOL>if get_keywords_f and from_keywords_f:<EOL><INDENT>try:<EOL><INDENT>keywords = get_keywords_f(versionfile_abs)<EOL>ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>ver = versions_from_file(versionfile_abs)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % (versionfile_abs, ver))<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>from_vcs_f = handlers.get("<STR_LIT>")<EOL>if from_vcs_f:<EOL><INDENT>try:<EOL><INDENT>pieces = from_vcs_f(cfg.tag_prefix, root, verbose)<EOL>ver = render(pieces, cfg.style)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if cfg.parentdir_prefix:<EOL><INDENT>ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % ver)<EOL><DEDENT>return ver<EOL><DEDENT><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>", "<STR_LIT>": None,<EOL>"<STR_LIT>": None, "<STR_LIT:error>": "<STR_LIT>",<EOL>"<STR_LIT:date>": None}<EOL>

Get the project version from whatever source is available.

    Returns dict with two keys: 'version' and 'full'.


return get_versions()["<STR_LIT:version>"]<EOL>

Get the short version string for this project.


if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>cmds = {}<EOL>from distutils.core import Command<EOL>class cmd_version(Command):<EOL><INDENT>description = "<STR_LIT>"<EOL>user_options = []<EOL>boolean_options = []<EOL>def initialize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def finalize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def run(self):<EOL><INDENT>vers = get_versions(verbose=True)<EOL>print("<STR_LIT>" % vers["<STR_LIT:version>"])<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT>"))<EOL>print("<STR_LIT>" % vers.get("<STR_LIT:date>"))<EOL>if vers["<STR_LIT:error>"]:<EOL><INDENT>print("<STR_LIT>" % vers["<STR_LIT:error>"])<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT:version>"] = cmd_version<EOL>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.build_py import build_py as _build_py<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.build_py import build_py as _build_py<EOL><DEDENT>class cmd_build_py(_build_py):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>_build_py.run(self)<EOL>if cfg.versionfile_build:<EOL><INDENT>target_versionfile = os.path.join(self.build_lib,<EOL>cfg.versionfile_build)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_py<EOL>if "<STR_LIT>" in sys.modules:  <EOL><INDENT>from cx_Freeze.dist import build_exe as _build_exe<EOL>class cmd_build_exe(_build_exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_build_exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_build_exe<EOL>del cmds["<STR_LIT>"]<EOL><DEDENT>if '<STR_LIT>' in sys.modules:  <EOL><INDENT>try:<EOL><INDENT>from py2exe.distutils_buildexe import py2exe as _py2exe  <EOL><DEDENT>except ImportError:<EOL><INDENT>from py2exe.build_exe import py2exe as _py2exe  <EOL><DEDENT>class cmd_py2exe(_py2exe):<EOL><INDENT>def run(self):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>versions = get_versions()<EOL>target_versionfile = cfg.versionfile_source<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile, versions)<EOL>_py2exe.run(self)<EOL>os.unlink(target_versionfile)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG %<EOL>{"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_py2exe<EOL><DEDENT>if "<STR_LIT>" in sys.modules:<EOL><INDENT>from setuptools.command.sdist import sdist as _sdist<EOL><DEDENT>else:<EOL><INDENT>from distutils.command.sdist import sdist as _sdist<EOL><DEDENT>class cmd_sdist(_sdist):<EOL><INDENT>def run(self):<EOL><INDENT>versions = get_versions()<EOL>self._versioneer_generated_versions = versions<EOL>self.distribution.metadata.version = versions["<STR_LIT:version>"]<EOL>return _sdist.run(self)<EOL><DEDENT>def make_release_tree(self, base_dir, files):<EOL><INDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>_sdist.make_release_tree(self, base_dir, files)<EOL>target_versionfile = os.path.join(base_dir, cfg.versionfile_source)<EOL>print("<STR_LIT>" % target_versionfile)<EOL>write_to_version_file(target_versionfile,<EOL>self._versioneer_generated_versions)<EOL><DEDENT><DEDENT>cmds["<STR_LIT>"] = cmd_sdist<EOL>return cmds<EOL>

Get the custom setuptools/distutils subclasses used by Versioneer.


root = get_root()<EOL>try:<EOL><INDENT>cfg = get_config_from_root(root)<EOL><DEDENT>except (EnvironmentError, configparser.NoSectionError,<EOL>configparser.NoOptionError) as e:<EOL><INDENT>if isinstance(e, (EnvironmentError, configparser.NoSectionError)):<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>with open(os.path.join(root, "<STR_LIT>"), "<STR_LIT:a>") as f:<EOL><INDENT>f.write(SAMPLE_CONFIG)<EOL><DEDENT><DEDENT>print(CONFIG_ERROR, file=sys.stderr)<EOL>return <NUM_LIT:1><EOL><DEDENT>print("<STR_LIT>" % cfg.versionfile_source)<EOL>with open(cfg.versionfile_source, "<STR_LIT:w>") as f:<EOL><INDENT>LONG = LONG_VERSION_PY[cfg.VCS]<EOL>f.write(LONG % {"<STR_LIT>": "<STR_LIT:$>",<EOL>"<STR_LIT>": cfg.style,<EOL>"<STR_LIT>": cfg.tag_prefix,<EOL>"<STR_LIT>": cfg.parentdir_prefix,<EOL>"<STR_LIT>": cfg.versionfile_source,<EOL>})<EOL><DEDENT>ipy = os.path.join(os.path.dirname(cfg.versionfile_source),<EOL>"<STR_LIT>")<EOL>if os.path.exists(ipy):<EOL><INDENT>try:<EOL><INDENT>with open(ipy, "<STR_LIT:r>") as f:<EOL><INDENT>old = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>old = "<STR_LIT>"<EOL><DEDENT>if INIT_PY_SNIPPET not in old:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>with open(ipy, "<STR_LIT:a>") as f:<EOL><INDENT>f.write(INIT_PY_SNIPPET)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % ipy)<EOL>ipy = None<EOL><DEDENT>manifest_in = os.path.join(root, "<STR_LIT>")<EOL>simple_includes = set()<EOL>try:<EOL><INDENT>with open(manifest_in, "<STR_LIT:r>") as f:<EOL><INDENT>for line in f:<EOL><INDENT>if line.startswith("<STR_LIT>"):<EOL><INDENT>for include in line.split()[<NUM_LIT:1>:]:<EOL><INDENT>simple_includes.add(include)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if "<STR_LIT>" not in simple_includes:<EOL><INDENT>print("<STR_LIT>")<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if cfg.versionfile_source not in simple_includes:<EOL><INDENT>print("<STR_LIT>" %<EOL>cfg.versionfile_source)<EOL>with open(manifest_in, "<STR_LIT:a>") as f:<EOL><INDENT>f.write("<STR_LIT>" % cfg.versionfile_source)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>do_vcs_install(manifest_in, cfg.versionfile_source, ipy)<EOL>return <NUM_LIT:0><EOL>

Main VCS-independent setup function for installing Versioneer.


found = set()<EOL>setters = False<EOL>errors = <NUM_LIT:0><EOL>with open("<STR_LIT>", "<STR_LIT:r>") as f:<EOL><INDENT>for line in f.readlines():<EOL><INDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>setters = True<EOL><DEDENT><DEDENT><DEDENT>if len(found) != <NUM_LIT:3>:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>if setters:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>errors += <NUM_LIT:1><EOL><DEDENT>return errors<EOL>

Validate the contents of setup.py against Versioneer's expectations.


if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):<EOL><INDENT>return obj.strftime(default_date_fmt)<EOL><DEDENT>else:<EOL><INDENT>return str(obj)<EOL><DEDENT>

Coerce everything to strings.
    All objects representing time get output according to default_date_fmt.


log_file = os.path.abspath(<EOL>os.path.join(path, target))<EOL>logger = logging.getLogger(logger_name)<EOL>logger.setLevel(level)<EOL>handler = logging.handlers.RotatingFileHandler(<EOL>log_file, maxBytes=maxBytes, backupCount=backupCount)<EOL>handler.setLevel(level)<EOL>handler.setFormatter(<EOL>JsonFormatter(<EOL>application_name=application_name,<EOL>server_hostname=server_hostname,<EOL>fields=fields))<EOL>logger.addHandler(handler)<EOL>

Initialize the zlogger.

    Sets up a rotating file handler to the specified path and file with
    the given size and backup count limits, sets the default
    application_name, server_hostname, and default/whitelist fields.

    :param path: path to write the log file
    :param target: name of the log file
    :param logger_name: name of the logger (defaults to root)
    :param level: log level for this logger (defaults to logging.DEBUG)
    :param maxBytes: size of the file before rotation (default 1MB)
    :param application_name: app name to add to each log entry
    :param server_hostname: hostname to add to each log entry
    :param fields: default/whitelist fields.
    :type path: string
    :type target: string
    :type logger_name: string
    :type level: int
    :type maxBytes: int
    :type backupCount: int
    :type application_name: string
    :type server_hostname: string
    :type fields: dict


pass<EOL>


pass<EOL>

log with pyzlog level ERROR

    exception info is added if it exists


def remove_log(self, path=None, target=None):

path = path if path is not None else self.path<EOL>target = target if target is not None else self.target<EOL>try:<EOL><INDENT>os.remove(os.path.abspath(os.path.join(path, target)))<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>

remove the specified log file.

        Generally called in setUp and tearDown methods to ensure
        isolation.  If path or target are not specified, will default to
        path and target properties on the object.

        :param path: path to find the log file
        :param target: name of the log file
        :type path: string
        :type target: string


def get_log_messages(self, path=None, target=None):

path = path if path is not None else self.path<EOL>target = target if target is not None else self.target<EOL>with open(os.path.abspath(os.path.join(path, target))) as f:<EOL><INDENT>return f.readlines()<EOL><DEDENT>

fetch all log entries in the given file

        Intended to be used to assert that the expected entries were
        written out to the correct log file. If path or target are not
        specified, will default to path and target properties on the
        object.

        :param path: path to find the log file
        :param target: name of the log file
        :type path: string
        :type target: string


def init_logs(self, path=None, target=None, level=None,<EOL>server_hostname=None, extra=None):

path = path if path is not None else self.path<EOL>target = target if target is not None else self.target<EOL>level = level if level is not None else logging.DEBUG<EOL>server_hostname = (server_hostname if server_hostname is not None<EOL>else '<STR_LIT:localhost>')<EOL>extra = extra if extra is not None else {'<STR_LIT>': None}<EOL>init_logs(path=path, target=target, level=level,<EOL>server_hostname=server_hostname, fields=extra)<EOL>

Simple canned way to initialize pyzlog.

        Initialize pyslog for tests. If path or target are not
        specified, will default to path and target properties on the
        object. leve will default to logging.DEBUG, server_hostname
        defaults to localhost, and extra defaults to {'extra': None}

        :param path: path to find the log file
        :param target: name of the log file
        :param level: log level for this instance
        :param server_hostname: hostname to put in each entry
        :param extra: whitelist/defaults of extra fields to add to each entry
        :type path: string
        :type target: string
        :type level: int
        :type server_hostname: string
        :type extra: dict


record_fields = record.__dict__.copy()<EOL>self._set_exc_info(record_fields)<EOL>event_name = '<STR_LIT:default>'<EOL>if record_fields.get('<STR_LIT>'):<EOL><INDENT>event_name = record_fields.pop('<STR_LIT>')<EOL><DEDENT>log_level = '<STR_LIT>'<EOL>if record_fields.get('<STR_LIT>'):<EOL><INDENT>log_level = record_fields.pop('<STR_LIT>')<EOL><DEDENT>[record_fields.pop(k) for k in record_fields.keys()<EOL>if k not in self.fields]<EOL>defaults = self.defaults.copy()<EOL>fields = self.fields.copy()<EOL>fields.update(record_fields)<EOL>filtered_fields = {}<EOL>for k, v in fields.iteritems():<EOL><INDENT>if v is not None:<EOL><INDENT>filtered_fields[k] = v<EOL><DEDENT><DEDENT>defaults.update({<EOL>'<STR_LIT>': self._get_now(),<EOL>'<STR_LIT>': event_name,<EOL>'<STR_LIT>': log_level,<EOL>'<STR_LIT>': filtered_fields})<EOL>return json.dumps(defaults, default=self.json_default)<EOL>

formats a logging.Record into a standard json log entry

        :param record: record to be formatted
        :type record: logging.Record
        :return: the formatted json string
        :rtype: string


def render_to_response(self, context, **response_kwargs):

if self.request.is_ajax():<EOL><INDENT>template = self.page_template<EOL><DEDENT>else:<EOL><INDENT>template = self.get_template_names()<EOL><DEDENT>return self.response_class(<EOL>request=self.request,<EOL>template=template,<EOL>context=context,<EOL>**response_kwargs<EOL>)<EOL>

Returns a response with a template depending if the request is ajax
or not and it renders with the given context.


return '<STR_LIT:.>'.join(map(str, VERSION))<EOL>

Return the Django Simple Blog version as a string.


return self.current_announce_date<EOL>

Return the date the query has been using.

:rtype: String, date, Format: YYYY-MM-DD


assignations, announce_date, _ = self.run(ip, announce_date)<EOL>return next((assign for assign in assignations if assign is not None), None), announce_date<EOL>

Give an IP, maybe a date, get the ASN.
This is the fastest command.

:param ip: IP address to search for
:param announce_date: Date of the announcement

:rtype: String, ASN.


def date_asn_block(self, ip, announce_date=None):

assignations, announce_date, keys = self.run(ip, announce_date)<EOL>pos = next((i for i, j in enumerate(assignations) if j is not None), None)<EOL>if pos is not None:<EOL><INDENT>block = keys[pos]<EOL>if block != '<STR_LIT>':<EOL><INDENT>return announce_date, assignations[pos], block<EOL><DEDENT><DEDENT>return None<EOL>

Get the ASN and the IP Block announcing the IP at a specific date.

:param ip: IP address to search for
:param announce_date: Date of the announcement

:rtype: tuple

    .. code-block:: python

        (announce_date, asn, block)

.. note::

    the returned announce_date might be different of the one
    given in parameter because some raw files are missing and we
    don't have the information. In this case, the nearest known
    date will be chosen,


all_dates = sorted(self.routing_db.smembers('<STR_LIT>'), reverse=True)<EOL>if days_limit is not None:<EOL><INDENT>all_dates = all_dates[:days_limit]<EOL><DEDENT>return [self.date_asn_block(ip, date) for date in all_dates]<EOL>

Get the full history of an IP. It takes time.

:param ip: IP address to search for
:param days_limit: Max amount of days to query. (None means no limit)

:rtype: list. For each day in the database: day, asn, block


def aggregate_history(self, ip, days_limit=None):

first_date = None<EOL>last_date = None<EOL>prec_asn = None<EOL>prec_block = None<EOL>for entry in self.history(ip, days_limit):<EOL><INDENT>if entry is None:<EOL><INDENT>continue<EOL><DEDENT>date, asn, block = entry<EOL>if first_date is None:<EOL><INDENT>last_date = date<EOL>first_date = date<EOL>prec_asn = asn<EOL>prec_block = block<EOL><DEDENT>elif prec_asn == asn and prec_block == block:<EOL><INDENT>first_date = date<EOL><DEDENT>else:<EOL><INDENT>yield first_date, last_date, prec_asn, prec_block<EOL>last_date = date<EOL>first_date = date<EOL>prec_asn = asn<EOL>prec_block = block<EOL><DEDENT><DEDENT>if first_date is not None:<EOL><INDENT>yield first_date, last_date, prec_asn, prec_block<EOL><DEDENT>

Get the full history of an IP, aggregate the result instead of
returning one line per day.

:param ip: IP address to search for
:param days_limit: Max amount of days to query. (None means no limit)

:rtype: list. For each change: FirstDay, LastDay, ASN, Block


p = urlparse(url)<EOL>h = HTTPConnection(p[<NUM_LIT:1>])<EOL>h.request('<STR_LIT>', p[<NUM_LIT:2>])<EOL>reply = h.getresponse()<EOL>h.close()<EOL>if reply.status == <NUM_LIT:200>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

Check if the URL exists by getting the header of the response.


urlretrieve(url, os.path.join(c.raw_data, path_temp_bviewfile))<EOL>os.rename(os.path.join(c.raw_data, path_temp_bviewfile), c.path_bviewfile)<EOL>

Inconditianilly download the URL in a temporary directory.
When finished, the file is moved in the real directory.
Like this an other process will not attempt to extract an inclomplete file.


if os.path.exists(c.path_bviewtimesamp):<EOL><INDENT>ts = open(c.path_bviewtimesamp, '<STR_LIT:r>').read().split()<EOL>if ts[<NUM_LIT:0>] == date:<EOL><INDENT>if int(ts[<NUM_LIT:1>]) >= int(hour):<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>open(c.path_bviewtimesamp, '<STR_LIT:w>').write(date + '<STR_LIT:U+0020>' + hour)<EOL>return False<EOL>

Verify that the date and the hour of the file we try to
download is newer than the latest downloaded file.


path_temp_bviewfile = os.path.join(c.raw_data, c.bview_dir, '<STR_LIT>', filename)<EOL>path_bviewfile = os.path.join(c.raw_data, c.bview_dir, filename)<EOL>try:<EOL><INDENT>f = urlopen(url)<EOL><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT>if f.getcode() != <NUM_LIT:200>:<EOL><INDENT>publisher.warning('<STR_LIT>'.format(url, f.getcode()))<EOL>return False<EOL><DEDENT>try:<EOL><INDENT>with open(path_temp_bviewfile, '<STR_LIT:w>') as outfile:<EOL><INDENT>outfile.write(f.read())<EOL><DEDENT>os.rename(path_temp_bviewfile, path_bviewfile)<EOL><DEDENT>except:<EOL><INDENT>os.remove(path_temp_bviewfile)<EOL>return False<EOL><DEDENT>return True<EOL>


cur_file = os.path.join(c.bview_dir, filename)<EOL>old_file = os.path.join(c.bview_dir, '<STR_LIT>', filename)<EOL>if not os.path.exists(cur_file) and not os.path.exists(old_file):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Verify that the file has not already been downloaded.


first_day = parse(interval_first)<EOL>last_day = parse(interval_last)<EOL>format_change = parse('<STR_LIT>')<EOL>one_day = datetime.timedelta(<NUM_LIT:1>)<EOL>cur_day = first_day<EOL>url_list = []<EOL>while cur_day < last_day:<EOL><INDENT>fname = filename.format(day=cur_day.strftime("<STR_LIT>"))<EOL>if cur_day > format_change:<EOL><INDENT>cur_day += one_day<EOL>url = base_url.format(year_month=cur_day.strftime("<STR_LIT>"),<EOL>file_day=cur_day.strftime("<STR_LIT>"))<EOL><DEDENT>else:<EOL><INDENT>url = base_url_old.format(year_month=cur_day.strftime("<STR_LIT>"),<EOL>file_day=cur_day.strftime("<STR_LIT>"))<EOL>cur_day += one_day<EOL><DEDENT>url_list.append((fname, url))<EOL><DEDENT>return sorted(url_list, key=lambda tup: tup[<NUM_LIT:0>], reverse=True)<EOL>

Build interval of urls to download.
We always get the first file of the next day.
Ex: 2013-01-01 => 2013-01-02.0000


dirname = file_to_split + '<STR_LIT>'<EOL>if not os.path.exists(dirname):<EOL><INDENT>os.mkdir(dirname)<EOL><DEDENT>part_file_size = os.path.getsize(file_to_split) / number_of_files + <NUM_LIT:1><EOL>splitted_files = []<EOL>with open(file_to_split, "<STR_LIT:r>") as f:<EOL><INDENT>number = <NUM_LIT:0><EOL>actual = <NUM_LIT:0><EOL>while <NUM_LIT:1>:<EOL><INDENT>prec = actual<EOL>f.seek(part_file_size, os.SEEK_CUR)<EOL>s = f.readline()<EOL>if len(s) == <NUM_LIT:0>:<EOL><INDENT>s = f.readline()<EOL><DEDENT>while len(s) != <NUM_LIT:0> and s != separator:<EOL><INDENT>s = f.readline()<EOL><DEDENT>actual = f.tell()<EOL>new_file = os.path.join(dirname, str(number))<EOL>with open(file_to_split, "<STR_LIT:r>") as temp:<EOL><INDENT>temp.seek(prec)<EOL>copy = temp.read(actual - prec)<EOL>open(new_file, '<STR_LIT:w>').write(copy)<EOL><DEDENT>splitted_files.append(new_file)<EOL>number += <NUM_LIT:1><EOL>if len(s) == <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return splitted_files<EOL>

Split the file and return the list of filenames.


if service is not None:<EOL><INDENT>to_run = ["<STR_LIT>", service]<EOL>if param is not None:<EOL><INDENT>to_run += param<EOL><DEDENT>return subprocess.Popen(to_run)<EOL><DEDENT>return False<EOL>


new_procs = []<EOL>for proc in old_procs:<EOL><INDENT>if proc.poll() is None and check_pid(proc.pid):<EOL><INDENT>publisher.debug(str(proc.pid) + '<STR_LIT>')<EOL>new_procs.append(proc)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>publisher.debug(str(proc.pid) + '<STR_LIT>')<EOL>os.kill(proc.pid, signal.SIGKILL)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>return new_procs<EOL>

Update the list of the running process and return the list


try:<EOL><INDENT>os.kill(pid, <NUM_LIT:0>)<EOL><DEDENT>except OSError:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT>


pids = []<EOL>while len(filenames) > <NUM_LIT:0>:<EOL><INDENT>while len(filenames) > <NUM_LIT:0> and len(pids) < max_simultaneous_processes:<EOL><INDENT>filename = filenames.pop()<EOL>pids.append(service_start(service=process_name,<EOL>param=['<STR_LIT>', filename, '<STR_LIT>',<EOL>imported_day]))<EOL><DEDENT>while len(pids) == max_simultaneous_processes:<EOL><INDENT>time.sleep(sleep_timer)<EOL>pids = update_running_pids(pids)<EOL><DEDENT><DEDENT>while len(pids) > <NUM_LIT:0>:<EOL><INDENT>time.sleep(sleep_timer)<EOL>pids = update_running_pids(pids)<EOL><DEDENT>

Run processes which push the routing dump of the RIPE in a redis
database.
The dump has been splitted in multiple files and each process run
on one of this files.


ip = request.remote_addr<EOL>ua = request.headers.get('<STR_LIT>', '<STR_LIT>')<EOL>method = request.json.get('<STR_LIT>')<EOL>if method is None:<EOL><INDENT>__query_logging(ip, ua, method, level='<STR_LIT>')<EOL>return json.dumps({'<STR_LIT:error>': '<STR_LIT>'})<EOL><DEDENT>if method not in authorized_methods:<EOL><INDENT>__query_logging(ip, ua, method, level='<STR_LIT>')<EOL>return json.dumps({'<STR_LIT:error>': '<STR_LIT>'})<EOL><DEDENT>fct = globals().get(method)<EOL>if fct is None:<EOL><INDENT>__query_logging(ip, ua, method, level='<STR_LIT>')<EOL>return json.dumps({'<STR_LIT:error>': '<STR_LIT>'})<EOL><DEDENT>if request.json.get('<STR_LIT>') is None:<EOL><INDENT>__query_logging(ip, ua, method, level='<STR_LIT>')<EOL>return json.dumps({'<STR_LIT:error>': '<STR_LIT>'})<EOL><DEDENT>try:<EOL><INDENT>result = fct(request.json)<EOL>__query_logging(ip, ua, method, request.json.get('<STR_LIT>'),<EOL>request.json.get('<STR_LIT>'), request.json.get('<STR_LIT>'))<EOL>return result<EOL><DEDENT>except Exception:<EOL><INDENT>__query_logging(ip, ua, method, request.json.get('<STR_LIT>'), level='<STR_LIT:error>')<EOL>return json.dumps({'<STR_LIT:error>': '<STR_LIT>'})<EOL><DEDENT>

Function called when an query is made on /json. Expects a JSON
object with at least a 'method' entry.


return CompiledFormat(fmt).pack(*args)<EOL>

Return a bytes object containing the values v1, v2, ... packed
    according to given format string `fmt`. If the total number of
    bits are not a multiple of 8, padding will be added at the end of
    the last byte.

    `fmt` is a string of bitorder-type-length groups, and optionally a
    byteorder identifier after the groups. Bitorder and byteorder may
    be omitted.

    Bitorder is either ``>`` or ``<``, where ``>`` means MSB first and
    ``<`` means LSB first. If bitorder is omitted, the previous
    values' bitorder is used for the current value. For example, in
    the format string ``'u1<u2u3'``, ``u1`` is MSB first and both
    ``u2`` and ``u3`` are LSB first.

    Byteorder is either ``>`` or ``<``, where ``>`` means most
    significant byte first and ``<`` means least significant byte
    first. If byteorder is omitted, most significant byte first is
    used.

    There are eight types; ``u``, ``s``, ``f``, ``b``, ``t``, ``r``,
    ``p`` and ``P``.

    - ``u`` -- unsigned integer
    - ``s`` -- signed integer
    - ``f`` -- floating point number of 16, 32, or 64 bits
    - ``b`` -- boolean
    - ``t`` -- text (ascii or utf-8)
    - ``r`` -- raw, bytes
    - ``p`` -- padding with zeros, ignore
    - ``P`` -- padding with ones, ignore

    Length is the number of bits to pack the value into.

    Example format string with default bit and byte ordering:
    ``'u1u3p7s16'``

    Same format string, but with least significant byte first:
    ``'u1u3p7s16<'``

    Same format string, but with LSB first (``<`` prefix) and least
    significant byte first (``<`` suffix): ``'<u1u3p7s16<'``

    It is allowed to separate groups with a single space for better
    readability.


return CompiledFormat(fmt).unpack(data)<EOL>

Unpack `data` (bytes or bytearray) according to given format string
    `fmt`. The result is a tuple even if it contains exactly one item.


def pack_into(fmt, buf, offset, *args, **kwargs):

return CompiledFormat(fmt).pack_into(buf,<EOL>offset,<EOL>*args,<EOL>**kwargs)<EOL>

Pack given values v1, v2, ... into given bytearray `buf`, starting
    at given bit offset `offset`. Pack according to given format
    string `fmt`. Give `fill_padding` as ``False`` to leave padding
    bits in `buf` unmodified.


def unpack_from(fmt, data, offset=<NUM_LIT:0>):

return CompiledFormat(fmt).unpack_from(data, offset)<EOL>

Unpack `data` (bytes or bytearray) according to given format string
    `fmt`, starting at given bit offset `offset`. The result is a
    tuple even if it contains exactly one item.


return CompiledFormatDict(fmt, names).pack(data)<EOL>

Same as :func:`~bitstruct.pack()`, but data is read from a
    dictionary.

    The names list `names` contains the format group names, used as
    keys in the dictionary.

    >>> pack_dict('u4u4', ['foo', 'bar'], {'foo': 1, 'bar': 2})
    b'\\x12'


return CompiledFormatDict(fmt, names).unpack(data)<EOL>

Same as :func:`~bitstruct.unpack()`, but returns a dictionary.

    See :func:`~bitstruct.pack_dict()` for details on `names`.

    >>> unpack_dict('u4u4', ['foo', 'bar'], b'\\x12')
    {'foo': 1, 'bar': 2}


def pack_into_dict(fmt, names, buf, offset, data, **kwargs):

return CompiledFormatDict(fmt, names).pack_into(buf,<EOL>offset,<EOL>data,<EOL>**kwargs)<EOL>

Same as :func:`~bitstruct.pack_into()`, but data is read from a
    dictionary.

    See :func:`~bitstruct.pack_dict()` for details on `names`.


def unpack_from_dict(fmt, names, data, offset=<NUM_LIT:0>):

return CompiledFormatDict(fmt, names).unpack_from(data, offset)<EOL>

Same as :func:`~bitstruct.unpack_from_dict()`, but returns a
    dictionary.

    See :func:`~bitstruct.pack_dict()` for details on `names`.


return CompiledFormat(fmt).calcsize()<EOL>

Return the number of bits in given format string `fmt`.

    >>> calcsize('u1s3p4')
    8


def byteswap(fmt, data, offset=<NUM_LIT:0>):

data = BytesIO(data)<EOL>data.seek(offset)<EOL>data_swapped = BytesIO()<EOL>for f in fmt:<EOL><INDENT>swapped = data.read(int(f))[::-<NUM_LIT:1>]<EOL>data_swapped.write(swapped)<EOL><DEDENT>return data_swapped.getvalue()<EOL>

Swap bytes in `data` according to `fmt`, starting at byte `offset`
    and return the result. `fmt` must be an iterable, iterating over
    number of bytes to swap. For example, the format string ``'24'``
    applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will
    produce the result ``b'\\x11\\x00\\x55\\x44\\x33\\x22'``.


if names is None:<EOL><INDENT>return CompiledFormat(fmt)<EOL><DEDENT>else:<EOL><INDENT>return CompiledFormatDict(fmt, names)<EOL><DEDENT>

Compile given format string `fmt` and return a compiled format
    object that can be used to pack and/or unpack data multiple times.

    Returns a :class:`~bitstruct.CompiledFormat` object if `names` is
    ``None``, and otherwise a :class:`~bitstruct.CompiledFormatDict`
    object.

    See :func:`~bitstruct.pack_dict()` for details on `names`.


return self._number_of_bits_to_unpack<EOL>

Return the number of bits in the compiled format string.


<EOL>if len(args) < self._number_of_arguments:<EOL><INDENT>raise Error(<EOL>"<STR_LIT>".format(<EOL>self._number_of_arguments,<EOL>len(args)))<EOL><DEDENT>return self.pack_any(args)<EOL>


return self.unpack_from(data)<EOL>


def pack_into(self, buf, offset, *args, **kwargs):

<EOL>if len(args) < self._number_of_arguments:<EOL><INDENT>raise Error(<EOL>"<STR_LIT>".format(<EOL>self._number_of_arguments,<EOL>len(args)))<EOL><DEDENT>self.pack_into_any(buf, offset, args, **kwargs)<EOL>


def unpack_from(self, data, offset=<NUM_LIT:0>):

return tuple([v[<NUM_LIT:1>] for v in self.unpack_from_any(data, offset)])<EOL>


try:<EOL><INDENT>return self.pack_any(data)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>raise Error('<STR_LIT>'.format(str(e)))<EOL><DEDENT>


def pack_into(self, buf, offset, data, **kwargs):

try:<EOL><INDENT>self.pack_into_any(buf, offset, data, **kwargs)<EOL><DEDENT>except KeyError as e:<EOL><INDENT>raise Error('<STR_LIT>'.format(str(e)))<EOL><DEDENT>


return {info.name: v for info, v in self.unpack_from_any(data, offset)}<EOL>


def open(name=None, fileobj=None, closefd=True):

return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)<EOL>

Use all decompressor possible to make the stream


if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:0>) and isinstance(fileobj, file):<EOL><INDENT>filename = fileobj.name<EOL>fileobj = io.FileIO(fileobj.fileno(), closefd=False)<EOL>fileobj.name = filename<EOL><DEDENT>assert isinstance(fileobj, io.IOBase),"<STR_LIT>"% type(fileobj)<EOL>return fileobj if fileobj.seekable()else ArchiveTemp(fileobj)<EOL>

If the file-object is not seekable, return  ArchiveTemp of the fileobject,
otherwise return the file-object itself


client = Client(name, port=self.server.port)<EOL>try:<EOL><INDENT>client.drop_index()<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>return client<EOL>

Gets a client client attached to an index name which is ready to be
created


fieldstrs = []<EOL>if len(byfields) == <NUM_LIT:1> and isinstance(byfields[<NUM_LIT:0>], type) andissubclass(byfields[<NUM_LIT:0>], SortDirection):<EOL><INDENT>byfields = [byfields[<NUM_LIT:0>](field)]<EOL><DEDENT>for f in byfields:<EOL><INDENT>fieldstrs += [f.field, f.DIRSTRING]<EOL><DEDENT>args = [field]<EOL>if fieldstrs:<EOL><INDENT>args += ['<STR_LIT>'] + fieldstrs<EOL><DEDENT>super(first_value, self).__init__(*args)<EOL>self._field = field<EOL>

Selects the first value of the given field within the group.

### Parameter

- **field**: Source field used for the value
- **byfields**: How to sort the results. This can be either the
    *class* of `aggregation.Asc` or `aggregation.Desc` in which
    case the field `field` is also used as the sort input.

    `byfields` can also be one or more *instances* of `Asc` or `Desc`
    indicating the sort order for these fields


args = [field, str(size)]<EOL>super(random_sample, self).__init__(*args)<EOL>self._field = field<EOL>

### Parameter

**field**: Field to sample from
**size**: Return this many items (can be less)


def __init__(self, index_name, host='<STR_LIT:localhost>', port=<NUM_LIT>, conn=None):

self.index_name = index_name<EOL>self.redis = conn if conn is not None else Redis(<EOL>connection_pool=ConnectionPool(host=host, port=port))<EOL>

Create a new Client for the given index_name, and optional host and port

If conn is not None, we employ an already existing redis connection


return Client.BatchIndexer(self, chunk_size=chunk_size)<EOL>

Create a new batch indexer from the client with a given chunk size


def create_index(self, fields, no_term_offsets=False,<EOL>no_field_flags=False, stopwords = None):

args = [self.CREATE_CMD, self.index_name]<EOL>if no_term_offsets:<EOL><INDENT>args.append(self.NOOFFSETS)<EOL><DEDENT>if no_field_flags:<EOL><INDENT>args.append(self.NOFIELDS)<EOL><DEDENT>if stopwords is not None and isinstance(stopwords, (list, tuple, set)):<EOL><INDENT>args += [self.STOPWORDS, len(stopwords)]<EOL>if len(stopwords) > <NUM_LIT:0>:<EOL><INDENT>args += list(stopwords)<EOL><DEDENT><DEDENT>args.append('<STR_LIT>')<EOL>args += list(itertools.chain(*(f.redis_args() for f in fields)))<EOL>return self.redis.execute_command(*args)<EOL>

Create the search index. The index must not already exist.

### Parameters:

- **fields**: a list of TextField or NumericField objects
- **no_term_offsets**: If true, we will not save term offsets in the index
- **no_field_flags**: If true, we will not save field flags that allow searching in specific fields
- **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty


return self.redis.execute_command(self.DROP_CMD, self.index_name)<EOL>


def _add_document(self, doc_id, conn=None, nosave=False, score=<NUM_LIT:1.0>, payload=None,<EOL>replace=False, partial=False, language=None, **fields):

if conn is None:<EOL><INDENT>conn = self.redis<EOL><DEDENT>if partial:<EOL><INDENT>replace = True<EOL><DEDENT>args = [self.ADD_CMD, self.index_name, doc_id, score]<EOL>if nosave:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if payload is not None:<EOL><INDENT>args.append('<STR_LIT>')<EOL>args.append(payload)<EOL><DEDENT>if replace:<EOL><INDENT>args.append('<STR_LIT>')<EOL>if partial:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT><DEDENT>if language:<EOL><INDENT>args += ['<STR_LIT>', language]<EOL><DEDENT>args.append('<STR_LIT>')<EOL>args += list(itertools.chain(*fields.items()))<EOL>return conn.execute_command(*args)<EOL>

Internal add_document used for both batch and single doc indexing


def add_document(self, doc_id, nosave=False, score=<NUM_LIT:1.0>, payload=None,<EOL>replace=False, partial=False, language=None, **fields):

return self._add_document(doc_id, conn=None, nosave=nosave, score=score, <EOL>payload=payload, replace=replace,<EOL>partial=partial, language=language, **fields)<EOL>

Add a single document to the index.

### Parameters

- **doc_id**: the id of the saved document.
- **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.
- **score**: the document ranking, between 0.0 and 1.0
- **payload**: optional inner-index payload we can save for fast access in scoring functions
- **replace**: if True, and the document already is in the index, we perform an update and reindex the document
- **partial**: if True, the fields specified will be added to the existing document.
               This has the added benefit that any fields specified with `no_index`
               will not be reindexed again. Implies `replace`
- **language**: Specify the language used for document tokenization.
- **fields** kwargs dictionary of the document fields to be saved and/or indexed.
             NOTE: Geo points shoule be encoded as strings of "lon,lat"


def delete_document(self, doc_id, conn=None):

if conn is None:<EOL><INDENT>conn = self.redis<EOL><DEDENT>return conn.execute_command(self.DEL_CMD, self.index_name, doc_id)<EOL>

Delete a document from index
Returns 1 if the document was deleted, 0 if not


fields = self.redis.hgetall(id)<EOL>if six.PY3:<EOL><INDENT>f2 = {to_string(k): to_string(v) for k, v in fields.items()}<EOL>fields = f2<EOL><DEDENT>try:<EOL><INDENT>del fields['<STR_LIT:id>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>return Document(id=id, **fields)<EOL>


res = self.redis.execute_command('<STR_LIT>', self.index_name)<EOL>it = six.moves.map(to_string, res)<EOL>return dict(six.moves.zip(it, it))<EOL>

Get info an stats about the the current index, including the number of documents, memory consumption, etc


args, query = self._mk_query_args(query)<EOL>st = time.time()<EOL>res = self.redis.execute_command(self.SEARCH_CMD, *args)<EOL>return Result(res,<EOL>not query._no_content,<EOL>duration=(time.time() - st) * <NUM_LIT>,<EOL>has_payload=query._with_payloads)<EOL>

Search the index for a given query, and return a result of documents

### Parameters

- **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries.
             See RediSearch's documentation on query format
- **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}


if isinstance(query, AggregateRequest):<EOL><INDENT>has_schema = query._with_schema<EOL>has_cursor = bool(query._cursor)<EOL>cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args()<EOL><DEDENT>elif isinstance(query, Cursor):<EOL><INDENT>has_schema = False<EOL>has_cursor = True<EOL>cmd = [self.CURSOR_CMD, '<STR_LIT>', self.index_name] + query.build_args()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>', query)<EOL><DEDENT>raw = self.redis.execute_command(*cmd)<EOL>if has_cursor:<EOL><INDENT>if isinstance(query, Cursor):<EOL><INDENT>query.cid = raw[<NUM_LIT:1>]<EOL>cursor = query<EOL><DEDENT>else:<EOL><INDENT>cursor = Cursor(raw[<NUM_LIT:1>])<EOL><DEDENT>raw = raw[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>cursor = None<EOL><DEDENT>if query._with_schema:<EOL><INDENT>schema = raw[<NUM_LIT:0>]<EOL>rows = raw[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>schema = None<EOL>rows = raw[<NUM_LIT:1>:]<EOL><DEDENT>res = AggregateResult(rows, cursor, schema)<EOL>return res<EOL>

Issue an aggregation query

### Parameters

**query**: This can be either an `AggeregateRequest`, or a `Cursor`

An `AggregateResult` object is returned. You can access the rows from its
`rows` property, which will always yield the rows of the result


self._query_string = query_string<EOL>self._offset = <NUM_LIT:0><EOL>self._num = <NUM_LIT:10><EOL>self._no_content = False<EOL>self._no_stopwords = False<EOL>self._fields = None<EOL>self._verbatim = False<EOL>self._with_payloads = False<EOL>self._filters = list()<EOL>self._ids = None<EOL>self._slop = -<NUM_LIT:1><EOL>self._in_order = False<EOL>self._sortby = None<EOL>self._return_fields = []<EOL>self._summarize_fields = []<EOL>self._highlight_fields = []<EOL>self._language = None<EOL>

Create a new query object.
The query string is set in the constructor, and other options have setter functions.


return self._query_string<EOL>

Return the query string of this query only


self._ids = ids<EOL>return self<EOL>

Limit the results to a specific set of pre-known document ids of any length


self._return_fields = fields<EOL>return self<EOL>


def summarize(self, fields=None, context_len=None, num_frags=None, sep=None):

args = ['<STR_LIT>']<EOL>fields = self._mk_field_list(fields)<EOL>if fields:<EOL><INDENT>args += ['<STR_LIT>', str(len(fields))] + fields<EOL><DEDENT>if context_len is not None:<EOL><INDENT>args += ['<STR_LIT>', str(context_len)]<EOL><DEDENT>if num_frags is not None:<EOL><INDENT>args += ['<STR_LIT>', str(num_frags)]<EOL><DEDENT>if sep is not None:<EOL><INDENT>args += ['<STR_LIT>', sep]<EOL><DEDENT>self._summarize_fields = args<EOL>return self<EOL>

Return an abridged format of the field, containing only the segments of
the field which contain the matching term(s).

If `fields` is specified, then only the mentioned fields are
summarized; otherwise all results are summarized.

Server side defaults are used for each option (except `fields`) if not specified

- **fields** List of fields to summarize. All fields are summarized if not specified
- **context_len** Amount of context to include with each fragment
- **num_frags** Number of fragments per document
- **sep** Separator string to separate fragments


def highlight(self, fields=None, tags=None):

args = ['<STR_LIT>']<EOL>fields = self._mk_field_list(fields)<EOL>if fields:<EOL><INDENT>args += ['<STR_LIT>', str(len(fields))] + fields<EOL><DEDENT>if tags:<EOL><INDENT>args += ['<STR_LIT>'] + list(tags)<EOL><DEDENT>self._highlight_fields = args<EOL>return self<EOL>

Apply specified markup to matched term(s) within the returned field(s)

- **fields** If specified then only those mentioned fields are highlighted, otherwise all fields are highlighted
- **tags** A list of two strings to surround the match.


self._language = language<EOL>return self<EOL>

Analyze the query as being in the specified language
:param language: The language (e.g. `chinese` or `english`)


self._slop = slop<EOL>return self<EOL>

Allow a masimum of N intervening non matched terms between phrase terms (0 means exact phrase)


self._in_order = True<EOL>return self<EOL>

Match only documents where the query terms appear in the same order in the document.
i.e. for the query 'hello world', we do not match 'world hello'


args = [self._query_string]<EOL>if self._no_content:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if self._fields:<EOL><INDENT>args.append('<STR_LIT>')<EOL>args.append(len(self._fields))<EOL>args += self._fields<EOL><DEDENT>if self._verbatim:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if self._no_stopwords:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if self._filters:<EOL><INDENT>for flt in self._filters:<EOL><INDENT>assert isinstance(flt, Filter)<EOL>args += flt.args<EOL><DEDENT><DEDENT>if self._with_payloads:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if self._ids:<EOL><INDENT>args.append('<STR_LIT>')<EOL>args.append(len(self._ids))<EOL>args += self._ids<EOL><DEDENT>if self._slop >= <NUM_LIT:0>:<EOL><INDENT>args += ['<STR_LIT>', self._slop]<EOL><DEDENT>if self._in_order:<EOL><INDENT>args.append('<STR_LIT>')<EOL><DEDENT>if self._return_fields:<EOL><INDENT>args.append('<STR_LIT>')<EOL>args.append(len(self._return_fields))<EOL>args += self._return_fields<EOL><DEDENT>if self._sortby:<EOL><INDENT>assert isinstance(self._sortby, SortbyField)<EOL>args.append('<STR_LIT>')<EOL>args += self._sortby.args<EOL><DEDENT>if self._language:<EOL><INDENT>args += ['<STR_LIT>', self._language]<EOL><DEDENT>args += self._summarize_fields + self._highlight_fields<EOL>args += ["<STR_LIT>", self._offset, self._num]<EOL>return args<EOL>

Format the redis arguments for this query and return them


self._offset = offset<EOL>self._num = num<EOL>return self<EOL>

Set the paging for the query (defaults to 0..10).

- **offset**: Paging offset for the results. Defaults to 0
- **num**: How many results do we want


self._verbatim = True<EOL>return self<EOL>

Set the query to be verbatim, i.e. use no query expansion or stemming


self._no_content = True<EOL>return self<EOL>

Set the query to only return ids and not the document content


self._no_stopwords = True<EOL>return self<EOL>

Prevent the query from being filtered for stopwords.
Only useful in very big queries that you are certain contain no stopwords.


self._with_payloads = True<EOL>return self<EOL>

Ask the engine to return document payloads


self._fields = fields<EOL>return self<EOL>

Limit the search to specific TEXT fields only

- **fields**: A list of strings, case sensitive field names from the defined schema


self._filters.append(flt)<EOL>return self<EOL>

Add a numeric or geo filter to the query.
**Currently only one of each filter is supported by the engine**

- **flt**: A NumericFilter or GeoFilter object, used on a corresponding field


self._sortby = SortbyField(field, asc)<EOL>return self<EOL>

Add a sortby field to the query

- **field** - the name of the field to sort by
- **asc** - when `True`, sorting will be done in asceding order


if not t:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return TagValue(*t)<EOL>

Indicate that the values should be matched to a tag field

### Parameters

- **t**: Tags to search for


def between(a, b, inclusive_min=True, inclusive_max=True):

return RangeValue(a, b,<EOL>inclusive_min=inclusive_min, inclusive_max=inclusive_max)<EOL>


return between(n, n)<EOL>


return between(None, n, inclusive_max=False)<EOL>


return between(None, n, inclusive_max=True)<EOL>


return between(n, None, inclusive_min=False)<EOL>


return between(n, None, inclusive_min=True)<EOL>


def geo(lat, lon, radius, unit='<STR_LIT>'):

return GeoValue(lat, lon, radius, unit)<EOL>


return False<EOL>

Whether this type of value may be combined with other values for the same
field. This makes the filter potentially more efficient


if isinstance(v, Value):<EOL><INDENT>return v<EOL><DEDENT>return ScalarValue(v)<EOL>

Convert an object to a value, if it is not a value already


def __init__(self, *children, **kwparams):

self.params = []<EOL>kvparams = {}<EOL>for k, v in kwparams.items():<EOL><INDENT>curvals = kvparams.setdefault(k, [])<EOL>if isinstance(v, (string_types, integer_types, float)):<EOL><INDENT>curvals.append(Value.make_value(v))<EOL><DEDENT>elif isinstance(v, Value):<EOL><INDENT>curvals.append(v)<EOL><DEDENT>else:<EOL><INDENT>curvals.extend(Value.make_value(subv) for subv in v)<EOL><DEDENT><DEDENT>self.params += [Node.to_node(p) for p in children]<EOL>for k, v in kvparams.items():<EOL><INDENT>self.params.extend(self.join_fields(k, v))<EOL><DEDENT>

Create a node

### Parameters

- **children**: One or more sub-conditions. These can be additional
    `intersect`, `disjunct`, `union`, `optional`, or any other `Node`
    type.

    The semantics of multiple conditions are dependent on the type of
    query. For an `intersection` node, this amounts to a logical AND,
    for a `union` node, this amounts to a logical `OR`.

- **kwparams**: key-value parameters. Each key is the name of a field,
    and the value should be a field value. This can be one of the
    following:

    - Simple string (for text field matches)
    - value returned by one of the helper functions
    - list of either a string or a value

### Examples

Field `num` should be between 1 and 10
```
intersect(num=between(1, 10)
```

Name can either be `bob` or `john`

```
union(name=('bob', 'john'))
```

Don't select countries in Israel, Japan, or US

```
disjunct_union(country=('il', 'jp', 'us'))
```


def __init__(self, res, hascontent, duration=<NUM_LIT:0>, has_payload = False):

self.total = res[<NUM_LIT:0>]<EOL>self.duration = duration<EOL>self.docs = []<EOL>step = <NUM_LIT:1><EOL>if hascontent:<EOL><INDENT>step = <NUM_LIT:3> if has_payload else <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>has_payload = False<EOL><DEDENT>for i in xrange(<NUM_LIT:1>, len(res), step):<EOL><INDENT>id = to_string(res[i])<EOL>payload = to_string(res[i+<NUM_LIT:1>]) if has_payload else None<EOL>fields_offset = <NUM_LIT:2> if has_payload else <NUM_LIT:1><EOL>fields = {} <EOL>if hascontent:<EOL><INDENT>fields = dict(<EOL>dict(izip(map(to_string, res[i + fields_offset][::<NUM_LIT:2>]),<EOL>map(to_string, res[i + fields_offset][<NUM_LIT:1>::<NUM_LIT:2>])))<EOL>) if hascontent else {}<EOL><DEDENT>try:<EOL><INDENT>del fields['<STR_LIT:id>']<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>doc = Document(id, payload=payload, **fields)<EOL>self.docs.append(doc)<EOL><DEDENT>

- **snippets**: An optional dictionary of the form {field: snippet_size} for snippet formatting


def __init__(self, key, host='<STR_LIT:localhost>', port=<NUM_LIT>, conn = None):

self.key = key<EOL>self.redis = conn if conn is not None else Redis(<EOL>connection_pool = ConnectionPool(host=host, port=port))<EOL>

Create a new AutoCompleter client for the given key, and optional host and port

If conn is not None, we employ an already existing redis connection


def add_suggestions(self,  *suggestions, **kwargs):

pipe = self.redis.pipeline()<EOL>for sug in suggestions:<EOL><INDENT>args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score]<EOL>if kwargs.get('<STR_LIT>'):<EOL><INDENT>args.append(AutoCompleter.INCR)<EOL><DEDENT>if sug.payload:<EOL><INDENT>args.append('<STR_LIT>')<EOL>args.append(sug.payload)<EOL><DEDENT>pipe.execute_command(*args)<EOL><DEDENT>return pipe.execute()[-<NUM_LIT:1>]<EOL>

Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string.

If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores


return self.redis.execute_command(AutoCompleter.SUGLEN_COMMAND, self.key)<EOL>

Return the number of entries in the AutoCompleter index


return self.redis.execute_command(AutoCompleter.SUGDEL_COMMAND, self.key, string)<EOL>

Delete a string from the AutoCompleter index.
Returns 1 if the string was found and deleted, 0 otherwise


def get_suggestions(self, prefix, fuzzy = False, num = <NUM_LIT:10>, with_scores = False, with_payloads=False):

args = [AutoCompleter.SUGGET_COMMAND, self.key, prefix, '<STR_LIT>', num]<EOL>if fuzzy:<EOL><INDENT>args.append(AutoCompleter.FUZZY)<EOL><DEDENT>if with_scores:<EOL><INDENT>args.append(AutoCompleter.WITHSCORES)<EOL><DEDENT>if with_payloads:<EOL><INDENT>args.append(AutoCompleter.WITHPAYLOADS)<EOL><DEDENT>ret = self.redis.execute_command(*args)<EOL>results = []<EOL>if not ret:<EOL><INDENT>return results<EOL><DEDENT>parser = SuggestionParser(with_scores, with_payloads, ret)<EOL>return [s for s in parser]<EOL>

Get a list of suggestions from the AutoCompleter, for a given prefix

### Parameters:
- **prefix**: the prefix we are searching. **Must be valid ascii or utf-8**
- **fuzzy**: If set to true, the prefix search is done in fuzzy mode.
    **NOTE**: Running fuzzy searches on short (<3 letters) prefixes can be very slow, and even scan the entire index.
- **with_scores**: if set to true, we also return the (refactored) score of each suggestion.
  This is normally not needed, and is NOT the original score inserted into the index
- **with_payloads**: Return suggestion payloads
- **num**: The maximum number of results we return. Note that we might return less. The algorithm trims irrelevant suggestions.

Returns a list of Suggestion objects. If with_scores was False, the score of all suggestions is 1.


if alias is FIELDNAME:<EOL><INDENT>if not self._field:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>alias = self._field[<NUM_LIT:1>:]<EOL><DEDENT>self._alias = alias<EOL>return self<EOL>

Set the alias for this reducer.

### Parameters

- **alias**: The value of the alias for this reducer. If this is the
    special value `aggregation.FIELDNAME` then this reducer will be
    aliased using the same name as the field upon which it operates.
    Note that using `FIELDNAME` is only possible on reducers which
    operate on a single field value.

This method returns the `Reducer` object making it suitable for
chaining.


self._query = query<EOL>self._groups = []<EOL>self._projections = []<EOL>self._loadfields = []<EOL>self._limit = Limit()<EOL>self._sortby = []<EOL>self._max = <NUM_LIT:0><EOL>self._with_schema = False<EOL>self._verbatim = False<EOL>self._cursor = []<EOL>

Create an aggregation request. This request may then be passed to
`client.aggregate()`.

In order for the request to be usable, it must contain at least one
group.

- **query** Query string for filtering records.

All member methods (except `build_args()`)
return the object itself, making them useful for chaining.


self._loadfields.extend(fields)<EOL>return self<EOL>

Indicate the fields to be returned in the response. These fields are
returned in addition to any others implicitly specified.

### Parameters

- **fields**: One or more fields in the format of `@field`


group = Group(fields, reducers)<EOL>self._groups.append(group)<EOL>return self<EOL>

Specify by which fields to group the aggregation.

### Parameters

- **fields**: Fields to group by. This can either be a single string,
    or a list of strings. both cases, the field should be specified as
    `@field`.
- **reducers**: One or more reducers. Reducers may be found in the
    `aggregation` module.


for alias, expr in kwexpr.items():<EOL><INDENT>self._projections.append([alias, expr])<EOL><DEDENT>return self<EOL>

Specify one or more projection expressions to add to each result

### Parameters

- **kwexpr**: One or more key-value pairs for a projection. The key is
    the alias for the projection, and the value is the projection
    expression itself, for example `apply(square_root="sqrt(@foo)")`


limit = Limit(offset, num)<EOL>if self._groups:<EOL><INDENT>self._groups[-<NUM_LIT:1>].limit = limit<EOL><DEDENT>else:<EOL><INDENT>self._limit = limit<EOL><DEDENT>return self<EOL>

Sets the limit for the most recent group or query.

If no group has been defined yet (via `group_by()`) then this sets
the limit for the initial pool of results from the query. Otherwise,
this limits the number of items operated on from the previous group.

Setting a limit on the initial search results may be useful when
attempting to execute an aggregation on a sample of a large data set.

### Parameters

- **offset**: Result offset from which to begin paging
- **num**: Number of results to return

Example of sorting the initial results:

```
AggregateRequest('@sale_amount:[10000, inf]')\
    .limit(0, 10)\
    .group_by('@state', r.count())
```

Will only group by the states found in the first 10 results of the
query `@sale_amount:[10000, inf]`. On the other hand,

```
AggregateRequest('@sale_amount:[10000, inf]')\
    .limit(0, 1000)\
    .group_by('@state', r.count()\
    .limit(0, 10)
```

Will group all the results matching the query, but only return the
first 10 groups.

If you only wish to return a *top-N* style query, consider using
`sort_by()` instead.


self._max = kwargs.get('<STR_LIT>', <NUM_LIT:0>)<EOL>if isinstance(fields, (string_types, SortDirection)):<EOL><INDENT>fields = [fields]<EOL><DEDENT>for f in fields:<EOL><INDENT>if isinstance(f, SortDirection):<EOL><INDENT>self._sortby += [f.field, f.DIRSTRING]<EOL><DEDENT>else:<EOL><INDENT>self._sortby.append(f)<EOL><DEDENT><DEDENT>return self<EOL>

Indicate how the results should be sorted. This can also be used for
*top-N* style queries

### Parameters

- **fields**: The fields by which to sort. This can be either a single
    field or a list of fields. If you wish to specify order, you can
    use the `Asc` or `Desc` wrapper classes.
- **max**: Maximum number of results to return. This can be used instead
    of `LIMIT` and is also faster.

Example of sorting by `foo` ascending and `bar` descending:

```
sort_by(Asc('@foo'), Desc('@bar'))
```

Return the top 10 customers:

```
AggregateRequest()\
    .group_by('@customer', r.sum('@paid').alias(FIELDNAME))\
    .sort_by(Desc('@paid'), max=10)
```


self._with_schema = True<EOL>return self<EOL>

If set, the `schema` property will contain a list of `[field, type]`
entries in the result object.


max_depth = <NUM_LIT:1><EOL>if fields and isinstance(fields[<NUM_LIT:0>], int):<EOL><INDENT>max_depth = fields[<NUM_LIT:0>]<EOL>fields = fields[<NUM_LIT:1>:]<EOL><DEDENT>elif "<STR_LIT>" in kwargs:<EOL><INDENT>max_depth = kwargs["<STR_LIT>"]<EOL><DEDENT>if not self.pk:<EOL><INDENT>raise self.DoesNotExist("<STR_LIT>")<EOL><DEDENT>obj = self._qs.read_preference(ReadPreference.PRIMARY).filter(<EOL>**self._object_key).only(*fields).limit(<NUM_LIT:1><EOL>).select_related(max_depth=max_depth)<EOL>if obj:<EOL><INDENT>obj = obj[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise self.DoesNotExist("<STR_LIT>")<EOL><DEDENT>for field in self._fields_ordered:<EOL><INDENT>if not fields or field in fields:<EOL><INDENT>try:<EOL><INDENT>setattr(self, field, self._reload(field, obj[field]))<EOL><DEDENT>except KeyError:<EOL><INDENT>delattr(self, field)<EOL><DEDENT><DEDENT><DEDENT>if not fields:<EOL><INDENT>self._changed_fields = obj._changed_fields<EOL><DEDENT>else:<EOL><INDENT>for field in fields:<EOL><INDENT>field = self._db_field_map.get(field, field)<EOL>if field in self._changed_fields:<EOL><INDENT>self._changed_fields.remove(field)<EOL><DEDENT><DEDENT><DEDENT>self._created = False<EOL>return self<EOL>

Reloads all attributes from the database.
        :param fields: (optional) args list of fields to reload
        :param max_depth: (optional) depth of dereferencing to follow
        .. versionadded:: 0.1.2
        .. versionchanged:: 0.6  Now chainable
        .. versionchanged:: 0.9  Can provide specific fields to reload


defaults = {<EOL>'<STR_LIT:username>': self.get_random_string(),<EOL>'<STR_LIT:email>': '<STR_LIT>',<EOL>'<STR_LIT:password>': self.get_random_string(),<EOL>}<EOL>defaults.update(kwargs)<EOL>return User.objects.create_user(**defaults)<EOL>


def _(*args, **kwargs):<EOL><INDENT>TEMPLATE_DEBUG = getattr(settings, '<STR_LIT>', False)<EOL>return f(*args, **kwargs) if TEMPLATE_DEBUG else '<STR_LIT>'<EOL><DEDENT>return _<EOL>

Decorated function is a no-op if TEMPLATE_DEBUG is False


meta_keys = (key for key in list(var_data.keys())<EOL>if key.startswith('<STR_LIT>'))<EOL>for key in meta_keys:<EOL><INDENT>display_key = key[<NUM_LIT:5>:].capitalize()<EOL>pprint('<STR_LIT>'.format(display_key, var_data.pop(key)))<EOL><DEDENT>pprint(var_data)<EOL>

Given a dictionary of variable attribute data from get_details display the
data in the terminal.


availables = get_variables(context)<EOL>pprint(availables)<EOL>return availables<EOL>

Given a context, return a flat list of variables available in the context.


attrs = get_attributes(var)<EOL>pprint(attrs)<EOL>return attrs<EOL>

Given a variable in the template's context, print and return the list of
attributes thare accessible inside of the template. For example, private
attributes or callables that require arguments are excluded.


var_details = get_details(var)<EOL>_display_details(var_details)<EOL>return var_details<EOL>

Prints a dictionary showing the attributes of a variable, and if possible,
their corresponding values.