def Grayscale(alpha=<NUM_LIT:0>, from_colorspace="<STR_LIT>", name=None, deterministic=False, random_state=None):

if name is None:<EOL><INDENT>name = "<STR_LIT>" % (ia.caller_name(),)<EOL><DEDENT>return ChangeColorspace(to_colorspace=ChangeColorspace.GRAY, alpha=alpha, from_colorspace=from_colorspace,<EOL>name=name, deterministic=deterministic, random_state=random_state)<EOL>

Augmenter to convert images to their grayscale versions.

NOTE: Number of output channels is still 3, i.e. this augmenter just "removes" color.

TODO check dtype support

dtype support::

    * ``uint8``: yes; fully tested
    * ``uint16``: ?
    * ``uint32``: ?
    * ``uint64``: ?
    * ``int8``: ?
    * ``int16``: ?
    * ``int32``: ?
    * ``int64``: ?
    * ``float16``: ?
    * ``float32``: ?
    * ``float64``: ?
    * ``float128``: ?
    * ``bool``: ?

Parameters
----------
alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
    The alpha value of the grayscale image when overlayed over the
    old image. A value close to 1.0 means, that mostly the new grayscale
    image is visible. A value close to 0.0 means, that mostly the
    old image is visible.

        * If a number, exactly that value will always be used.
        * If a tuple ``(a, b)``, a random value from the range ``a <= x <= b`` will
          be sampled per image.
        * If a list, then a random value will be sampled from that list per image.
        * If a StochasticParameter, a value will be sampled from the
          parameter per image.

from_colorspace : str, optional
    The source colorspace (of the input images).
    Allowed strings are: ``RGB``, ``BGR``, ``GRAY``, ``CIE``, ``YCrCb``, ``HSV``, ``HLS``, ``Lab``, ``Luv``.
    See :func:`imgaug.augmenters.color.ChangeColorspace.__init__`.

name : None or str, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

deterministic : bool, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

random_state : None or int or numpy.random.RandomState, optional
    See :func:`imgaug.augmenters.meta.Augmenter.__init__`.

Examples
--------
>>> aug = iaa.Grayscale(alpha=1.0)

creates an augmenter that turns images to their grayscale versions.

>>> aug = iaa.Grayscale(alpha=(0.0, 1.0))

creates an augmenter that turns images to their grayscale versions with
an alpha value in the range ``0 <= alpha <= 1``. An alpha value of 0.5 would
mean, that the output image is 50 percent of the input image and 50
percent of the grayscale image (i.e. 50 percent of color removed).


@staticmethod<EOL><INDENT>def create_for_noise(other_param, threshold=(-<NUM_LIT:10>, <NUM_LIT:10>), activated=True):<DEDENT>

return Sigmoid(other_param, threshold, activated, mul=<NUM_LIT:20>, add=-<NUM_LIT:10>)<EOL>

Creates a Sigmoid that is adjusted to be used with noise parameters,
i.e. with parameters which's output values are in the range [0.0, 1.0].

Parameters
----------
other_param : imgaug.parameters.StochasticParameter
    See :func:`imgaug.parameters.Sigmoid.__init__`.

threshold : number or tuple of number or iterable of number or imgaug.parameters.StochasticParameter,\
            optional
    See :func:`imgaug.parameters.Sigmoid.__init__`.

activated : bool or number, optional
    See :func:`imgaug.parameters.Sigmoid.__init__`.

Returns
-------
Sigmoid
    A sigmoid adjusted to be used with noise.


return self.draw_samples(<NUM_LIT:1>, random_state=random_state)[<NUM_LIT:0>]<EOL>

Draws a single sample value from this parameter.

Parameters
----------
random_state : None or numpy.random.RandomState, optional
    A random state to use during the sampling process.
    If None, the libraries global random state will be used.

Returns
-------
any
    A single sample value.


def draw_distribution_graph(self, title=None, size=(<NUM_LIT:1000>, <NUM_LIT:1000>), bins=<NUM_LIT:100>):

<EOL>import matplotlib.pyplot as plt<EOL>points = []<EOL>for _ in sm.xrange(size[<NUM_LIT:0>]):<EOL><INDENT>points.append(self.draw_samples(size[<NUM_LIT:1>:]).flatten())<EOL><DEDENT>points = np.concatenate(points)<EOL>fig = plt.figure()<EOL>fig.add_subplot(<NUM_LIT>)<EOL>ax = fig.gca()<EOL>heights, bins = np.histogram(points, bins=bins)<EOL>heights = heights / sum(heights)<EOL>ax.bar(bins[:-<NUM_LIT:1>], heights, width=(max(bins) - min(bins))/len(bins), color="<STR_LIT>", alpha=<NUM_LIT>)<EOL>if title is None:<EOL><INDENT>title = str(self)<EOL><DEDENT>if title is not False:<EOL><INDENT>title_fragments = [title[i:i+<NUM_LIT:50>] for i in sm.xrange(<NUM_LIT:0>, len(title), <NUM_LIT:50>)]<EOL>ax.set_title("<STR_LIT:\n>".join(title_fragments))<EOL><DEDENT>fig.tight_layout(pad=<NUM_LIT:0>)<EOL>with tempfile.NamedTemporaryFile(suffix="<STR_LIT>") as f:<EOL><INDENT>fig.savefig(f.name)<EOL>data = imageio.imread(f)[..., <NUM_LIT:0>:<NUM_LIT:3>]<EOL><DEDENT>plt.close()<EOL>return data<EOL>

Generate a plot (image) that shows the parameter's distribution of
values.

Parameters
----------
title : None or False or str, optional
    Title of the plot. None is automatically replaced by a title
    derived from ``str(param)``. If set to False, no title will be
    shown.

size : tuple of int
    Number of points to sample. This is always expected to have at
    least two values. The first defines the number of sampling runs,
    the second (and further) dimensions define the size assigned
    to each :func:`imgaug.parameters.StochasticParameter.draw_samples`
    call. E.g. ``(10, 20, 15)`` will lead to ``10`` calls of
    ``draw_samples(size=(20, 15))``. The results will be merged to a single 1d array.

bins : int
    Number of bins in the plot histograms.

Returns
-------
data : (H,W,3) ndarray
    Image of the plot.


return copy_module.deepcopy(self)<EOL>

Create a deep copy of this parameter.

Returns
-------
imgaug.parameters.StochasticParameter
    Deep copy.


def Negative(other_param, mode="<STR_LIT>", reroll_count_max=<NUM_LIT:2>):

return ForceSign(<EOL>other_param=other_param,<EOL>positive=False,<EOL>mode=mode,<EOL>reroll_count_max=reroll_count_max<EOL>)<EOL>

Converts another parameter's results to negative values.

Parameters
----------
other_param : imgaug.parameters.StochasticParameter
    Other parameter which's sampled values are to be
    modified.

mode : {'invert', 'reroll'}, optional
    How to change the signs. Valid values are ``invert`` and ``reroll``.
    ``invert`` means that wrong signs are simply flipped.
    ``reroll`` means that all samples with wrong signs are sampled again,
    optionally many times, until they randomly end up having the correct
    sign.

reroll_count_max : int, optional
    If `mode` is set to ``reroll``, this determines how often values may
    be rerolled before giving up and simply flipping the sign (as in
    ``mode="invert"``). This shouldn't be set too high, as rerolling is
    expensive.

Examples
--------
>>> param = Negative(Normal(0, 1), mode="reroll")

Generates a normal distribution that has only negative values.


with open('<STR_LIT>', '<STR_LIT:a>') as logfile:<EOL><INDENT>logfile.write("<STR_LIT:->"*<NUM_LIT> + '<STR_LIT:\n>')<EOL>logfile.write('<STR_LIT>' % (msg, datetime.now()))<EOL>logfile.write("<STR_LIT:->"*<NUM_LIT> + '<STR_LIT:\n>')<EOL><DEDENT>return<EOL>

A convenience method to mark sections of a continuous log file.


return self._get('<STR_LIT>')<EOL>

Get json with info about all the projects.


def _delete(self, sub_url=None, data=None):

return self._dispatch("<STR_LIT>", sub_url, data)<EOL>

Thin wrapper around _dispatch function using method DELETE


def _get(self, sub_url=None, data=None):

return self._dispatch('<STR_LIT:GET>', sub_url, data)<EOL>

Thin wrapper around _dispatch function using method GET


def _post(self, sub_url=None, data=None):

return self._dispatch("<STR_LIT:POST>", sub_url, data)<EOL>

Thin wrapper around _dispatch function using method POST


return self._post('<STR_LIT>', {"<STR_LIT>": self.project_id})<EOL>


return {"<STR_LIT>": self.file_metadata.toJSON(),<EOL>"<STR_LIT:content>": self.file_content}<EOL>

Get a JSON dict of the data in this file.


sim_info = self.simulation_info()<EOL>try:<EOL><INDENT>progress_info = sim_info['<STR_LIT>']<EOL>ret = progress_info['<STR_LIT>']<EOL><DEDENT>except KeyError:  <EOL><INDENT>ret = False<EOL><DEDENT>return ret<EOL>

Check if the current simulation is running.


Add a file to the project

file_object -- a Kappa_common.File


Start the simulation from the last parsed model.

        Inputs
        ------
        simulation_parameter -- (optional) a kappa_common.SimulationParameter
            instance. The default is set using the `set_default_sim_param`
            method.


if self.__default_param is None:<EOL><INDENT>raise KappaError("<STR_LIT>")<EOL><DEDENT>return self.__default_param<EOL>

Get the default SimulationParameter instance.


def add_model_string(self, model_str, position=<NUM_LIT:1>, file_id=None):

if file_id is None:<EOL><INDENT>file_id = self.make_unique_id('<STR_LIT>')<EOL><DEDENT>ret_data = self.file_create(File.from_string(model_str, position,<EOL>file_id))<EOL>return ret_data<EOL>

Add a kappa model given in a string to the project.


@classmethod<EOL><INDENT>def from_file(cls, fpath, position=<NUM_LIT:1>, file_id=None):<DEDENT>

if file_id is None:<EOL><INDENT>file_id = fpath<EOL><DEDENT>with open(fpath) as f:<EOL><INDENT>code = f.read()<EOL>file_content = str(code)<EOL>file_metadata = FileMetadata(file_id, position)<EOL>return cls(file_metadata, file_content)<EOL><DEDENT>

Convience method to create a kappa file object from a file on disk

Inputs
------
fpath -- path to the file on disk
position -- (default 1) rank among all files of the model while parsing
    see FileMetadata
file_id -- (default = fpath) the file_id that will be used by kappa.


Lists files generated by $PRINT during the simulation


start = datetime.now()<EOL>while self.get_is_sim_running():<EOL><INDENT>sleep(<NUM_LIT:0.5>)<EOL>if timeout is not None:<EOL><INDENT>if (datetime.now() - start).seconds >= timeout:<EOL><INDENT>ret = None<EOL>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>ret = self.simulation_info()<EOL><DEDENT>return ret<EOL>

Block until the simulation is done or timeout seconds exceeded.

        If the simulation stops before timeout, siminfo is returned.


Returns state and progress of the simulation


Returns the file file_line_id generated by $PRINT interventions


Returns a bunch of invarients on the last parsed model


Returns the contact of the last parsed model

Input
-----
accuracy -- \"high\" means take into account reachability from
   initial state. \"low\" means don't.


return map(lambda info: cls(**info), metadata_list)<EOL>

Get metadata objects from a list of metadata.


Returns the influence_map of the last parsed model

Input
-----
accuracy -- level can be \"low\", \"medium\", \"high\" or \"full\".
    Default is medium.


@classmethod<EOL><INDENT>def from_string(cls, content, position=<NUM_LIT:1>, file_id=None):<DEDENT>

if file_id is None:<EOL><INDENT>file_id = '<STR_LIT>'<EOL><DEDENT>return cls(FileMetadata(file_id, position), content)<EOL>

Convenience method to create a file from a string.

This file object's metadata will have the id 'inlined_input'.

Inputs
------
content -- the content of the file (a string).
position -- (default 1) rank among all files of the model while parsing
    see FileMetadata
file_id -- (default 'inlined_input') the file_id that will be used by
    kappa.


io = StringIO.StringIO()<EOL>io.write('<STR_LIT:">')<EOL>for c in value:<EOL><INDENT>if c in _ESCAPES:<EOL><INDENT>io.write(_ESCAPES[c])<EOL><DEDENT>elif c in _SIMPLE_CHARS:<EOL><INDENT>io.write(c)<EOL><DEDENT>else:<EOL><INDENT>io.write(r'<STR_LIT>'.format(ord(c)))<EOL><DEDENT><DEDENT>io.write('<STR_LIT:">')<EOL>return io.getvalue()<EOL>

Returns value as a valid Go string literal.


self.indent(n)<EOL>yield<EOL>self.dedent(n)<EOL>

A context manager that indents by n on entry and dedents on exit.


Outputs the boilerplate necessary for code blocks like functions.

        Args:
          block_: The Block object representing the code block.
          body: String containing Go code making up the body of the code block.


<EOL>with self.block.alloc_temp() as mod,self.block.alloc_temp('<STR_LIT>') as mod_slice:<EOL><INDENT>self.writer.write_checked_call2(<EOL>mod_slice, '<STR_LIT>', util.go_str(imp.name))<EOL>for binding in imp.bindings:<EOL><INDENT>if binding.bind_type == imputil.Import.MODULE:<EOL><INDENT>self.writer.write('<STR_LIT>'.format(<EOL>mod.name, mod_slice.expr, binding.value))<EOL>self.block.bind_var(self.writer, binding.alias, mod.expr)<EOL><DEDENT>else:<EOL><INDENT>self.writer.write('<STR_LIT>'.format(<EOL>mod.name, mod_slice.expr, imp.name.count('<STR_LIT:.>')))<EOL>with self.block.alloc_temp() as member:<EOL><INDENT>self.writer.write_checked_call2(<EOL>member, '<STR_LIT>',<EOL>mod.expr, self.block.root.intern(binding.value))<EOL>self.block.bind_var(self.writer, binding.alias, member.expr)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Generates code that imports a module and binds it to a variable.

        Args:
          imp: Import object representing an import of the form "import x.y.z" or
              "from x.y import z". Expects only a single binding.


<EOL>func_visitor = block.FunctionBlockVisitor(node)<EOL>for child in node.body:<EOL><INDENT>func_visitor.visit(child)<EOL><DEDENT>func_block = block.FunctionBlock(self.block, node.name, func_visitor.vars,<EOL>func_visitor.is_generator)<EOL>visitor = StatementVisitor(func_block, self.future_node)<EOL>with visitor.writer.indent_block():<EOL><INDENT>visitor._visit_each(node.body)  <EOL><DEDENT>result = self.block.alloc_temp()<EOL>with self.block.alloc_temp('<STR_LIT>') as func_args:<EOL><INDENT>args = node.args<EOL>argc = len(args.args)<EOL>self.writer.write('<STR_LIT>'.format(<EOL>func_args.expr, argc))<EOL>defaults = [None] * (argc - len(args.defaults)) + args.defaults<EOL>for i, (a, d) in enumerate(zip(args.args, defaults)):<EOL><INDENT>with self.visit_expr(d) if d else expr.nil_expr as default:<EOL><INDENT>tmpl = '<STR_LIT>'<EOL>self.writer.write_tmpl(tmpl, args=func_args.expr, i=i,<EOL>name=util.go_str(a.arg), default=default.expr)<EOL><DEDENT><DEDENT>flags = []<EOL>if args.vararg:<EOL><INDENT>flags.append('<STR_LIT>')<EOL><DEDENT>if args.kwarg:<EOL><INDENT>flags.append('<STR_LIT>')<EOL><DEDENT>self.writer.write_tmpl(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>result=result.name, name=util.go_str(node.name),<EOL>filename=util.go_str(self.block.root.filename), args=func_args.expr,<EOL>flags='<STR_LIT>'.join(flags) if flags else <NUM_LIT:0>)<EOL>with self.writer.indent_block():<EOL><INDENT>for var in func_block.vars.values():<EOL><INDENT>if var.type != block.Var.TYPE_GLOBAL:<EOL><INDENT>fmt = '<STR_LIT>'<EOL>self.writer.write(fmt.format(<EOL>util.adjust_local_name(var.name), var.init_expr))<EOL><DEDENT><DEDENT>self.writer.write_temp_decls(func_block)<EOL>self.writer.write('<STR_LIT>')<EOL>self.writer.write('<STR_LIT>')<EOL>if func_block.is_generator:<EOL><INDENT>self.writer.write(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>with self.writer.indent_block():<EOL><INDENT>self.writer.write_block(func_block, visitor.writer.getvalue())<EOL>self.writer.write('<STR_LIT>')<EOL><DEDENT>self.writer.write('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.writer.write_block(func_block, visitor.writer.getvalue())<EOL>self.writer.write(textwrap.dedent("""<STR_LIT>"""))<EOL><DEDENT><DEDENT>self.writer.write('<STR_LIT>')<EOL><DEDENT>return result<EOL>

Returns an GeneratedExpr for a function with the given body.


@abc.abstractmethod<EOL><INDENT>def resolve_name(self, writer, name):<DEDENT>

pass<EOL>

Returns a GeneratedExpr object for accessing the named var in this block.

        This is overridden in the different concrete block types since name
        resolution in Python behaves differently depending on where in what kind of
        block its happening within, e.g. local vars are different than globals.

        Args:
          writer: Writer object where intermediate calculations will be printed.
          name: The name of the Python variable.


for v in sorted(self.free_temps, key=lambda k: k.name):<EOL><INDENT>if v.type_ == type_:<EOL><INDENT>self.free_temps.remove(v)<EOL>self.used_temps.add(v)<EOL>return v<EOL><DEDENT><DEDENT>self.temp_index += <NUM_LIT:1><EOL>name = '<STR_LIT>'.format(self.temp_index)<EOL>v = expr.GeneratedTempVar(self, name, type_)<EOL>self.used_temps.add(v)<EOL>return v<EOL>

Create a new temporary Go variable having type type_ for this block.


@abc.abstractmethod<EOL><INDENT>def bind_var(self, writer, name, value):<DEDENT>

pass<EOL>

Writes Go statements for assigning value to named var in this block.

        This is overridden in the different concrete block types since in Python,
        binding a variable in, e.g. a function is quite different than binding at
        global block.

        Args:
          writer: The Writer object where statements will be written.
          name: The name of the Python variable.
          value: A Go expression to assign to the variable.


self.used_temps.remove(v)<EOL>self.free_temps.add(v)<EOL>

Release the GeneratedTempVar v so it can be reused.


def Test(self):<EOL><INDENT>code = textwrap.dedent("""<STR_LIT>""")<EOL>status, output = _GrumpRun(code.format(subscript))<EOL>self.assertEqual(<NUM_LIT:0>, status, output)<EOL>self.assertEqual(want, output.strip())<EOL><DEDENT>return Test<EOL>

Define a test function that evaluates a slice expression.


if expr:<EOL><INDENT>msg = self._formatMessage(msg, "<STR_LIT>" % safe_repr(expr))<EOL>raise self.failureException(msg)<EOL><DEDENT>


if condition:<EOL><INDENT>return skip(reason)<EOL><DEDENT>return _id<EOL>


def assertLessEqual(self, a, b, msg=None):

if not a <= b:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(a), safe_repr(b))<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Just like self.assertTrue(a <= b), but with a nicer default message.


def assertRaises(self, excClass, callableObj=None, *args, **kwargs):

context = _AssertRaisesContext(excClass, self)<EOL>if callableObj is None:<EOL><INDENT>return context<EOL><DEDENT>with context:<EOL><INDENT>callableObj(*args, **kwargs)<EOL><DEDENT>

Fail unless an exception of class excClass is raised
           by callableObj when invoked with arguments args and keyword
           arguments kwargs. If a different type of exception is
           raised, it will not be caught, and the test case will be
           deemed to have suffered an error, exactly as for an
           unexpected exception.

           If called with callableObj omitted or None, will return a
           context object used like this::

                with self.assertRaises(SomeException):
                    do_something()

           The context manager keeps a reference to the exception as
           the 'exception' attribute. This allows you to inspect the
           exception after the assertion::

               with self.assertRaises(SomeException) as cm:
                   do_something()
               the_exception = cm.exception
               self.assertEqual(the_exception.error_code, 3)


if not expr:<EOL><INDENT>msg = self._formatMessage(msg, "<STR_LIT>" % safe_repr(expr))<EOL>raise self.failureException(msg)<EOL><DEDENT>


self._testMethodName = methodName<EOL>self._resultForDoCleanups = None<EOL>try:<EOL><INDENT>testMethod = getattr(self, methodName)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(self.__class__, methodName))<EOL><DEDENT>self._cleanups = []<EOL>self._type_equality_funcs = {}<EOL>self.addTypeEqualityFunc(dict, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(list, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(tuple, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(set, '<STR_LIT>')<EOL>self.addTypeEqualityFunc(frozenset, '<STR_LIT>')<EOL>try:<EOL><INDENT>self.addTypeEqualityFunc(str, '<STR_LIT>')<EOL><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>

Create an instance of the class that will use the named test
           method when executed. Raises a ValueError if the instance does
           not have a method with the specified name.


def assertIsNotNone(self, obj, msg=None):

if obj is None:<EOL><INDENT>standardMsg = '<STR_LIT>'<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Included for symmetry with assertIsNone.


pass<EOL>

Hook method for deconstructing the test fixture after testing it.


def addTypeEqualityFunc(self, typeobj, function):

self._type_equality_funcs[typeobj] = function<EOL>

Add a type specific assertEqual style function to compare a type.

        This method is for use by TestCase subclasses that need to register
        their own type equality functions to provide nicer error messages.

        Args:
            typeobj: The data type to call this function on when both values
                    are of the same type in assertEqual().
            function: The callable taking two arguments and an optional
                    msg= argument that raises self.failureException with a
                    useful error message when the two arguments are not equal.


self.setUp()<EOL>getattr(self, self._testMethodName)()<EOL>self.tearDown()<EOL>while self._cleanups:<EOL><INDENT>function, args, kwargs = self._cleanups.pop(-<NUM_LIT:1>)<EOL>function(*args, **kwargs)<EOL><DEDENT>

Run the test without collecting errors in a TestResult


raise self.failureException(msg)<EOL>

Fail immediately, with the given message.


def assertNotEqual(self, first, second, msg=None):

if not first != second:<EOL><INDENT>msg = self._formatMessage(msg, '<STR_LIT>' % (safe_repr(first),<EOL>safe_repr(second)))<EOL>raise self.failureException(msg)<EOL><DEDENT>

Fail if the two objects are equal as determined by the '!='
           operator.


def assertGreaterEqual(self, a, b, msg=None):

if not a >= b:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(a), safe_repr(b))<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Just like self.assertTrue(a >= b), but with a nicer default message.


def assertEqual(self, first, second, msg=None):

assertion_func = self._getAssertEqualityFunc(first, second)<EOL>assertion_func(first, second, msg=msg)<EOL>

Fail if the two objects are unequal as determined by the '=='
           operator.


def addCleanup(self, function, *args, **kwargs):

self._cleanups.append((function, args, kwargs))<EOL>

Add a function, with arguments, to be called when the test is
        completed. Functions added are called on a LIFO basis and are
        called after tearDown on test failure or success.

        Cleanup items are called even if setUp fails (unlike tearDown).


def _baseAssertEqual(self, first, second, msg=None):

if not first == second:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(first), safe_repr(second))<EOL>msg = self._formatMessage(msg, standardMsg)<EOL>raise self.failureException(msg)<EOL><DEDENT>

The default assertEqual implementation, not type specific.


def assertNotIn(self, member, container, msg=None):

if member in container:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(member),<EOL>safe_repr(container))<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Just like self.assertTrue(a not in b), but with a nicer default message.


def assertMultiLineEqual(self, first, second, msg=None):

self.assertIsInstance(first, str,<EOL>'<STR_LIT>')<EOL>self.assertIsInstance(second, str,<EOL>'<STR_LIT>')<EOL>if first != second:<EOL><INDENT>if (len(first) > self._diffThreshold or<EOL>len(second) > self._diffThreshold):<EOL><INDENT>self._baseAssertEqual(first, second, msg)<EOL><DEDENT>firstlines = first.splitlines(True)<EOL>secondlines = second.splitlines(True)<EOL>if len(firstlines) == <NUM_LIT:1> and first.strip('<STR_LIT:\r\n>') == first:<EOL><INDENT>firstlines = [first + '<STR_LIT:\n>']<EOL>secondlines = [second + '<STR_LIT:\n>']<EOL><DEDENT>standardMsg = '<STR_LIT>' % (safe_repr(first, True),<EOL>safe_repr(second, True))<EOL>diff = '<STR_LIT:\n>' + '<STR_LIT>'.join(difflib.ndiff(firstlines, secondlines))<EOL>standardMsg = self._truncateMessage(standardMsg, diff)<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Assert that two multi-line strings are equal.


if obj is not None:<EOL><INDENT>standardMsg = '<STR_LIT>' % (safe_repr(obj),)<EOL>self.fail(self._formatMessage(msg, standardMsg))<EOL><DEDENT>

Same as self.assertTrue(obj is None), with a nicer default message.


def assertItemsEqual(self, expected_seq, actual_seq, msg=None):

first_seq, second_seq = list(expected_seq), list(actual_seq)<EOL>with warnings.catch_warnings():<EOL><INDENT>if sys.py3kwarning:<EOL><INDENT>for _msg in ["<STR_LIT>",<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"]:<EOL><INDENT>warnings.filterwarnings("<STR_LIT:ignore>", _msg, DeprecationWarning)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>first = collections.Counter(first_seq)<EOL>second = collections.Counter(second_seq)<EOL><DEDENT>except TypeError:<EOL><INDENT>differences = _count_diff_all_purpose(first_seq, second_seq)<EOL><DEDENT>else:<EOL><INDENT>if first == second:<EOL><INDENT>return<EOL><DEDENT>differences = _count_diff_hashable(first_seq, second_seq)<EOL><DEDENT><DEDENT>if differences:<EOL><INDENT>standardMsg = '<STR_LIT>'<EOL>lines = ['<STR_LIT>' % diff for diff in differences]<EOL>diffMsg = '<STR_LIT:\n>'.join(lines)<EOL>standardMsg = self._truncateMessage(standardMsg, diffMsg)<EOL>msg = self._formatMessage(msg, standardMsg)<EOL>self.fail(msg)<EOL><DEDENT>

An unordered sequence specific comparison. It asserts that
        actual_seq and expected_seq have the same element counts.
        Equivalent to::

            self.assertEqual(Counter(iter(actual_seq)),
                             Counter(iter(expected_seq)))

        Asserts that each element has the same count in both sequences.
        Example:
            - [0, 1, 1] and [1, 0, 1] compare equal.
            - [0, 0, 1] and [0, 1] compare unequal.


<EOL>return '<STR_LIT>'<EOL>

Returns a one-line description of the test, or None if no
        description has been provided.

        The default implementation of this method returns the first line of
        the specified test method's docstring.


def assertDictContainsSubset(self, expected, actual, msg=None):

missing = []<EOL>mismatched = []<EOL>for key, value in expected.items():<EOL><INDENT>if key not in actual:<EOL><INDENT>missing.append(key)<EOL><DEDENT>elif value != actual[key]:<EOL><INDENT>mismatched.append('<STR_LIT>' %<EOL>(safe_repr(key), safe_repr(value),<EOL>safe_repr(actual[key])))<EOL><DEDENT><DEDENT>if not (missing or mismatched):<EOL><INDENT>return<EOL><DEDENT>standardMsg = '<STR_LIT>'<EOL>if missing:<EOL><INDENT>standardMsg = '<STR_LIT>' % '<STR_LIT:U+002C>'.join(safe_repr(m) for m in<EOL>missing)<EOL><DEDENT>if mismatched:<EOL><INDENT>if standardMsg:<EOL><INDENT>standardMsg += '<STR_LIT>'<EOL><DEDENT>standardMsg += '<STR_LIT>' % '<STR_LIT:U+002C>'.join(mismatched)<EOL><DEDENT>self.fail(self._formatMessage(msg, standardMsg))<EOL>

Checks whether actual is a superset of expected.


def _formatMessage(self, msg, standardMsg):

if not self.longMessage:<EOL><INDENT>return msg or standardMsg<EOL><DEDENT>if msg is None:<EOL><INDENT>return standardMsg<EOL><DEDENT>try:<EOL><INDENT>return '<STR_LIT>' % (standardMsg, msg)<EOL><DEDENT>except UnicodeDecodeError:<EOL><INDENT>return  '<STR_LIT>' % (safe_repr(standardMsg), safe_repr(msg))<EOL><DEDENT>

Honour the longMessage attribute when generating failure messages.
        If longMessage is False this means:
        * Use only an explicit message if it is provided
        * Otherwise use the standard message for the assert

        If longMessage is True:
        * Use the standard message
        * If an explicit message is provided, plus ' : ' and the explicit message


Hook method for setting up class fixture before running tests in the class.


if not condition:<EOL><INDENT>return skip(reason)<EOL><DEDENT>return _id<EOL>

Skip a test unless the condition is true.


def setdefault(self, key, default=None):

if key in self:<EOL><INDENT>return self[key]<EOL><DEDENT>self[key] = default<EOL>return default<EOL>

od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od


if not isinstance(other, Counter):<EOL><INDENT>return NotImplemented<EOL><DEDENT>result = Counter()<EOL>for elem, count in self.items():<EOL><INDENT>newcount = count + other[elem]<EOL>if newcount > <NUM_LIT:0>:<EOL><INDENT>result[elem] = newcount<EOL><DEDENT><DEDENT>for elem, count in other.items():<EOL><INDENT>if elem not in self and count > <NUM_LIT:0>:<EOL><INDENT>result[elem] = count<EOL><DEDENT><DEDENT>return result<EOL>

Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})


def __delitem__(self, key, dict_delitem=dict.__delitem__):

<EOL>dict_delitem(self, key)<EOL>link_prev, link_next, _ = self.__map.pop(key)<EOL>link_prev[<NUM_LIT:1>] = link_next                        <EOL>link_next[<NUM_LIT:0>] = link_prev                        <EOL>


return KeysView(self)<EOL>

od.viewkeys() -> a set-like object providing a view on od's keys


return ItemsView(self)<EOL>

od.viewitems() -> a set-like object providing a view on od's items


<EOL>return _chain.from_iterable(_starmap(_repeat, self.iteritems()))<EOL>

Iterator over elements repeating each as many times as its count.

        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product
        1836

        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.


if not isinstance(other, Counter):<EOL><INDENT>return NotImplemented<EOL><DEDENT>result = Counter()<EOL>for elem, count in self.items():<EOL><INDENT>newcount = count - other[elem]<EOL>if newcount > <NUM_LIT:0>:<EOL><INDENT>result[elem] = newcount<EOL><DEDENT><DEDENT>for elem, count in other.items():<EOL><INDENT>if elem not in self and count < <NUM_LIT:0>:<EOL><INDENT>result[elem] = <NUM_LIT:0> - count<EOL><DEDENT><DEDENT>return result<EOL>

Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})


if not args:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self = args[<NUM_LIT:0>]<EOL>args = args[<NUM_LIT:1>:]<EOL>if len(args) > <NUM_LIT:1>:<EOL><INDENT>raise TypeError('<STR_LIT>' % len(args))<EOL><DEDENT>try:<EOL><INDENT>self.__root<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.__root = root = []                     <EOL>root[:] = [root, root, None]<EOL>self.__map = {}<EOL><DEDENT>self.__update(*args, **kwds)<EOL>

Initialize an ordered dictionary.  The signature is the same as
        regular dictionaries, but keyword arguments are not recommended because
        their insertion order is arbitrary.


root = self.__root<EOL>root[:] = [root, root, None]<EOL>self.__map.clear()<EOL>dict.clear(self)<EOL>

od.clear() -> None.  Remove all items from od.


<EOL>return <NUM_LIT:0><EOL>

The count of elements not in the Counter is zero.


if not isinstance(other, Counter):<EOL><INDENT>return NotImplemented<EOL><DEDENT>result = Counter()<EOL>for elem, count in self.items():<EOL><INDENT>other_count = other[elem]<EOL>newcount = count if count < other_count else other_count<EOL>if newcount > <NUM_LIT:0>:<EOL><INDENT>result[elem] = newcount<EOL><DEDENT><DEDENT>return result<EOL>

Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})


return self.__class__(self)<EOL>


return _safe_repr(o, {}, None, <NUM_LIT:0>)[<NUM_LIT:0>]<EOL>

Version of repr() which can handle recursive data structures.


def format(self, o, context, maxlevels, level):

return _safe_repr(o, context, maxlevels, level)<EOL>

Format o for a specific context, returning a string
        and flags indicating whether the representation is 'readable'
        and whether the o represents a recursive construct.


@wraps(func)<EOL>def helper(*args, **kwds):<EOL><INDENT>return GeneratorContextManager(func(*args, **kwds))<EOL><DEDENT>return helper<EOL>

@contextmanager decorator.

    Typical usage:

        @contextmanager
        def some_generator(<arguments>):
            <setup>
            try:
                yield <value>
            finally:
                <cleanup>

    This makes this:

        with some_generator(<arguments>) as <variable>:
            <body>

    equivalent to this:

        <setup>
        try:
            <variable> = <value>
            <body>
        finally:
            <cleanup>


if _is_unicode(s):<EOL><INDENT>if '<STR_LIT:%>' not in s:<EOL><INDENT>return s<EOL><DEDENT>bits = _asciire.split(s)<EOL>res = [bits[<NUM_LIT:0>]]<EOL>append = res.append<EOL>for i in range(<NUM_LIT:1>, len(bits), <NUM_LIT:2>):<EOL><INDENT>append(unquote(str(bits[i])).decode('<STR_LIT>'))<EOL>append(bits[i + <NUM_LIT:1>])<EOL><DEDENT>return '<STR_LIT>'.join(res)<EOL><DEDENT>bits = s.split('<STR_LIT:%>')<EOL>if len(bits) == <NUM_LIT:1>:<EOL><INDENT>return s<EOL><DEDENT>res = [bits[<NUM_LIT:0>]]<EOL>append = res.append<EOL>for item in bits[<NUM_LIT:1>:]:<EOL><INDENT>try:<EOL><INDENT>append(_hextochr[item[:<NUM_LIT:2>]])<EOL>append(item[<NUM_LIT:2>:])<EOL><DEDENT>except KeyError:<EOL><INDENT>append('<STR_LIT:%>')<EOL>append(item)<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(res)<EOL>


def _make(cls, iterable, new=tuple.__new__, len=len):

result = new(cls, iterable)<EOL>if len(result) != <NUM_LIT:6>:<EOL><INDENT>raise TypeError('<STR_LIT>' % len(result))<EOL><DEDENT>return result<EOL>

Make a new ParseResult object from a sequence or iterable


def urljoin(base, url, allow_fragments=True):

if not base:<EOL><INDENT>return url<EOL><DEDENT>if not url:<EOL><INDENT>return base<EOL><DEDENT>bscheme, bnetloc, bpath, bparams, bquery, bfragment =urlparse(base, '<STR_LIT>', allow_fragments)<EOL>scheme, netloc, path, params, query, fragment =urlparse(url, bscheme, allow_fragments)<EOL>if scheme != bscheme or scheme not in uses_relative:<EOL><INDENT>return url<EOL><DEDENT>if scheme in uses_netloc:<EOL><INDENT>if netloc:<EOL><INDENT>return urlunparse((scheme, netloc, path,<EOL>params, query, fragment))<EOL><DEDENT>netloc = bnetloc<EOL><DEDENT>if path[:<NUM_LIT:1>] == '<STR_LIT:/>':<EOL><INDENT>return urlunparse((scheme, netloc, path,<EOL>params, query, fragment))<EOL><DEDENT>if not path and not params:<EOL><INDENT>path = bpath<EOL>params = bparams<EOL>if not query:<EOL><INDENT>query = bquery<EOL><DEDENT>return urlunparse((scheme, netloc, path,<EOL>params, query, fragment))<EOL><DEDENT>segments = bpath.split('<STR_LIT:/>')[:-<NUM_LIT:1>] + path.split('<STR_LIT:/>')<EOL>if segments[-<NUM_LIT:1>] == '<STR_LIT:.>':<EOL><INDENT>segments[-<NUM_LIT:1>] = '<STR_LIT>'<EOL><DEDENT>while '<STR_LIT:.>' in segments:<EOL><INDENT>segments.remove('<STR_LIT:.>')<EOL><DEDENT>while <NUM_LIT:1>:<EOL><INDENT>i = <NUM_LIT:1><EOL>n = len(segments) - <NUM_LIT:1><EOL>while i < n:<EOL><INDENT>if (segments[i] == '<STR_LIT:..>'<EOL>and segments[i-<NUM_LIT:1>] not in ('<STR_LIT>', '<STR_LIT:..>')):<EOL><INDENT>del segments[i-<NUM_LIT:1>:i+<NUM_LIT:1>]<EOL>break<EOL><DEDENT>i = i+<NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if segments == ['<STR_LIT>', '<STR_LIT:..>']:<EOL><INDENT>segments[-<NUM_LIT:1>] = '<STR_LIT>'<EOL><DEDENT>elif len(segments) >= <NUM_LIT:2> and segments[-<NUM_LIT:1>] == '<STR_LIT:..>':<EOL><INDENT>segments[-<NUM_LIT:2>:] = ['<STR_LIT>']<EOL><DEDENT>return urlunparse((scheme, netloc, '<STR_LIT:/>'.join(segments),<EOL>params, query, fragment))<EOL>

Join a base URL and a possibly relative URL to form an absolute
    interpretation of the latter.


scheme, netloc, url, query, fragment = data<EOL>if netloc or (scheme and scheme in uses_netloc and url[:<NUM_LIT:2>] != '<STR_LIT>'):<EOL><INDENT>if url and url[:<NUM_LIT:1>] != '<STR_LIT:/>': url = '<STR_LIT:/>' + url<EOL>url = '<STR_LIT>' + (netloc or '<STR_LIT>') + url<EOL><DEDENT>if scheme:<EOL><INDENT>url = scheme + '<STR_LIT::>' + url<EOL><DEDENT>if query:<EOL><INDENT>url = url + '<STR_LIT:?>' + query<EOL><DEDENT>if fragment:<EOL><INDENT>url = url + '<STR_LIT:#>' + fragment<EOL><DEDENT>return url<EOL>

Combine the elements of a tuple as returned by urlsplit() into a
    complete URL as a string. The data argument can be any five-item iterable.
    This may result in a slightly different, but equivalent URL, if the URL that
    was parsed originally had unnecessary delimiters (for example, a ? with an
    empty query; the RFC states that these are equivalent).


scheme, netloc, url, params, query, fragment = data<EOL>if params:<EOL><INDENT>url = "<STR_LIT>" % (url, params)<EOL><DEDENT>return urlunsplit((scheme, netloc, url, query, fragment))<EOL>

Put a parsed URL back together again.  This may result in a
    slightly different, but equivalent URL, if the URL that was parsed
    originally had redundant delimiters, e.g. a ? with an empty query
    (the draft states that these are equivalent).


def parse_qs(qs, keep_blank_values=<NUM_LIT:0>, strict_parsing=<NUM_LIT:0>):

dict = {}<EOL>for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):<EOL><INDENT>if name in dict:<EOL><INDENT>dict[name].append(value)<EOL><DEDENT>else:<EOL><INDENT>dict[name] = [value]<EOL><DEDENT><DEDENT>return dict<EOL>

Parse a query given as a string argument.

        Arguments:

        qs: percent-encoded query string to be parsed

        keep_blank_values: flag indicating whether blank values in
            percent-encoded queries should be treated as blank strings.
            A true value indicates that blanks should be retained as
            blank strings.  The default false value indicates that
            blank values are to be ignored and treated as if they were
            not included.

        strict_parsing: flag indicating what to do with parsing errors.
            If false (the default), errors are silently ignored.
            If true, errors raise a ValueError exception.


return OrderedDict(list(zip(self._fields, self)))<EOL>

Return a new OrderedDict which maps field names to their values


pass<EOL>


result = _self._make(list(map(kwds.pop, ('<STR_LIT>', '<STR_LIT>', '<STR_LIT:path>', '<STR_LIT>', '<STR_LIT>'), _self)))<EOL>if kwds:<EOL><INDENT>raise ValueError('<STR_LIT>' % list(kwds.keys()))<EOL><DEDENT>return result<EOL>

Return a new SplitResult object replacing specified fields with new values


def decode(input, output, header = <NUM_LIT:0>):

if a2b_qp is not None:<EOL><INDENT>data = input.read()<EOL>odata = a2b_qp(data, header = header)<EOL>output.write(odata)<EOL>return<EOL><DEDENT>new = '<STR_LIT>'<EOL>while <NUM_LIT:1>:<EOL><INDENT>line = input.readline()<EOL>if not line: break<EOL>i, n = <NUM_LIT:0>, len(line)<EOL>if n > <NUM_LIT:0> and line[n-<NUM_LIT:1>] == '<STR_LIT:\n>':<EOL><INDENT>partial = <NUM_LIT:0>; n = n-<NUM_LIT:1><EOL>while n > <NUM_LIT:0> and line[n-<NUM_LIT:1>] in "<STR_LIT>":<EOL><INDENT>n = n-<NUM_LIT:1><EOL><DEDENT><DEDENT>else:<EOL><INDENT>partial = <NUM_LIT:1><EOL><DEDENT>while i < n:<EOL><INDENT>c = line[i]<EOL>if c == '<STR_LIT:_>' and header:<EOL><INDENT>new = new + '<STR_LIT:U+0020>'; i = i+<NUM_LIT:1><EOL><DEDENT>elif c != ESCAPE:<EOL><INDENT>new = new + c; i = i+<NUM_LIT:1><EOL><DEDENT>elif i+<NUM_LIT:1> == n and not partial:<EOL><INDENT>partial = <NUM_LIT:1>; break<EOL><DEDENT>elif i+<NUM_LIT:1> < n and line[i+<NUM_LIT:1>] == ESCAPE:<EOL><INDENT>new = new + ESCAPE; i = i+<NUM_LIT:2><EOL><DEDENT>elif i+<NUM_LIT:2> < n and ishex(line[i+<NUM_LIT:1>]) and ishex(line[i+<NUM_LIT:2>]):<EOL><INDENT>new = new + chr(unhex(line[i+<NUM_LIT:1>:i+<NUM_LIT:3>])); i = i+<NUM_LIT:3><EOL><DEDENT>else: <EOL><INDENT>new = new + c; i = i+<NUM_LIT:1><EOL><DEDENT><DEDENT>if not partial:<EOL><INDENT>output.write(new + '<STR_LIT:\n>')<EOL>new = '<STR_LIT>'<EOL><DEDENT><DEDENT>if new:<EOL><INDENT>output.write(new)<EOL><DEDENT>

Read 'input', apply quoted-printable decoding, and write to 'output'.
    'input' and 'output' are files with readline() and write() methods.
    If 'header' is true, decode underscore as space (per RFC 1522).


bits = <NUM_LIT:0><EOL>for c in s:<EOL><INDENT>if '<STR_LIT:0>' <= c <= '<STR_LIT>':<EOL><INDENT>i = ord('<STR_LIT:0>')<EOL><DEDENT>elif '<STR_LIT:a>' <= c <= '<STR_LIT:f>':<EOL><INDENT>i = ord('<STR_LIT:a>')-<NUM_LIT:10><EOL><DEDENT>elif '<STR_LIT:A>' <= c <= '<STR_LIT:F>':<EOL><INDENT>i = ord('<STR_LIT:A>')-<NUM_LIT:10><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT>bits = bits*<NUM_LIT:16> + (ord(c) - i)<EOL><DEDENT>return bits<EOL>

Get the integer value of a hexadecimal number.


if c in '<STR_LIT>':<EOL><INDENT>return quotetabs<EOL><DEDENT>if c == '<STR_LIT:_>':<EOL><INDENT>return header<EOL><DEDENT>return c == ESCAPE or not ('<STR_LIT:U+0020>' <= c <= '<STR_LIT>')<EOL>

Decide whether a particular character needs to be quoted.

    The 'quotetabs' flag indicates whether embedded tabs and spaces should be
    quoted.  Note that line-ending tabs and spaces are always encoded, as per
    RFC 1521.


i = ord(c)<EOL>return ESCAPE + HEX[i//<NUM_LIT:16>] + HEX[i%<NUM_LIT:16>]<EOL>


def encode(input, output, quotetabs, header = <NUM_LIT:0>):

if b2a_qp is not None:<EOL><INDENT>data = input.read()<EOL>odata = b2a_qp(data, quotetabs = quotetabs, header = header)<EOL>output.write(odata)<EOL>return<EOL><DEDENT>def write(s, output=output, lineEnd='<STR_LIT:\n>'):<EOL><INDENT>if s and s[-<NUM_LIT:1>:] in '<STR_LIT>':<EOL><INDENT>output.write(s[:-<NUM_LIT:1>] + quote(s[-<NUM_LIT:1>]) + lineEnd)<EOL><DEDENT>elif s == '<STR_LIT:.>':<EOL><INDENT>output.write(quote(s) + lineEnd)<EOL><DEDENT>else:<EOL><INDENT>output.write(s + lineEnd)<EOL><DEDENT><DEDENT>prevline = None<EOL>while <NUM_LIT:1>:<EOL><INDENT>line = input.readline()<EOL>if not line:<EOL><INDENT>break<EOL><DEDENT>outline = []<EOL>stripped = '<STR_LIT>'<EOL>if line[-<NUM_LIT:1>:] == '<STR_LIT:\n>':<EOL><INDENT>line = line[:-<NUM_LIT:1>]<EOL>stripped = '<STR_LIT:\n>'<EOL><DEDENT>for c in line:<EOL><INDENT>if needsquoting(c, quotetabs, header):<EOL><INDENT>c = quote(c)<EOL><DEDENT>if header and c == '<STR_LIT:U+0020>':<EOL><INDENT>outline.append('<STR_LIT:_>')<EOL><DEDENT>else:<EOL><INDENT>outline.append(c)<EOL><DEDENT><DEDENT>if prevline is not None:<EOL><INDENT>write(prevline)<EOL><DEDENT>thisline = EMPTYSTRING.join(outline)<EOL>while len(thisline) > MAXLINESIZE:<EOL><INDENT>write(thisline[:MAXLINESIZE-<NUM_LIT:1>], lineEnd='<STR_LIT>')<EOL>thisline = thisline[MAXLINESIZE-<NUM_LIT:1>:]<EOL><DEDENT>prevline = thisline<EOL><DEDENT>if prevline is not None:<EOL><INDENT>write(prevline, lineEnd=stripped)<EOL><DEDENT>

Read 'input', apply quoted-printable encoding, and write to 'output'.

    'input' and 'output' are files with readline() and write() methods.
    The 'quotetabs' flag indicates whether embedded tabs and spaces should be
    quoted.  Note that line-ending tabs and spaces are always encoded, as per
    RFC 1521.
    The 'header' flag indicates whether we are encoding spaces as _ as per
    RFC 1522.


return binascii.hexlify(s).upper()<EOL>

Encode a string using Base16.

    s is the string to encode.  The encoded string is returned.


<EOL>encoded = binascii.b2a_base64(s)[:-<NUM_LIT:1>]<EOL>if altchars is not None:<EOL><INDENT>return encoded.translate(string.maketrans(b'<STR_LIT>', altchars[:<NUM_LIT:2>]))<EOL><DEDENT>return encoded<EOL>

Encode a string using Base64.

    s is the string to encode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies an
    alternative alphabet for the '+' and '/' characters.  This allows an
    application to e.g. generate url or filesystem safe Base64 strings.

    The encoded string is returned.


while True:<EOL><INDENT>line = input.readline()<EOL>if not line:<EOL><INDENT>break<EOL><DEDENT>s = binascii.a2b_base64(line)<EOL>output.write(s)<EOL><DEDENT>


if altchars is not None:<EOL><INDENT>s = s.translate(string.maketrans(altchars[:<NUM_LIT:2>], '<STR_LIT>'))<EOL><DEDENT>try:<EOL><INDENT>return binascii.a2b_base64(s)<EOL><DEDENT>except binascii.Error as msg:<EOL><INDENT>raise TypeError(msg)<EOL><DEDENT>

Decode a Base64 encoded string.

    s is the string to decode.  Optional altchars must be a string of at least
    length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the '+' and '/' characters.

    The decoded string is returned.  A TypeError is raised if s is
    incorrectly padded.  Characters that are neither in the normal base-64
    alphabet nor the alternative alphabet are discarded prior to the padding
    check.


return b64encode(s).translate(_urlsafe_encode_translation)<EOL>

Encode a string using the URL- and filesystem-safe Base64 alphabet.

    Argument s is the string to encode.  The encoded string is returned.  The
    alphabet uses '-' instead of '+' and '_' instead of '/'.


parts = []<EOL>quanta, leftover = divmod(len(s), <NUM_LIT:5>)<EOL>if leftover:<EOL><INDENT>s += ('<STR_LIT>' * (<NUM_LIT:5> - leftover))<EOL>quanta += <NUM_LIT:1><EOL><DEDENT>for i in range(quanta):<EOL><INDENT>c1, c2, c3 = struct.unpack('<STR_LIT>', s[i*<NUM_LIT:5>:(i+<NUM_LIT:1>)*<NUM_LIT:5>])<EOL>c2 += (c1 & <NUM_LIT:1>) << <NUM_LIT:16> <EOL>c3 += (c2 & <NUM_LIT:3>) << <NUM_LIT:8>  <EOL>parts.extend([_b32tab[c1 >> <NUM_LIT:11>],         <EOL>_b32tab[(c1 >> <NUM_LIT:6>) & <NUM_LIT>], <EOL>_b32tab[(c1 >> <NUM_LIT:1>) & <NUM_LIT>], <EOL>_b32tab[c2 >> <NUM_LIT:12>],         <EOL>_b32tab[(c2 >> <NUM_LIT:7>) & <NUM_LIT>], <EOL>_b32tab[(c2 >> <NUM_LIT:2>) & <NUM_LIT>], <EOL>_b32tab[c3 >> <NUM_LIT:5>],          <EOL>_b32tab[c3 & <NUM_LIT>],        <EOL>])<EOL><DEDENT>encoded = EMPTYSTRING.join(parts)<EOL>if leftover == <NUM_LIT:1>:<EOL><INDENT>return encoded[:-<NUM_LIT:6>] + '<STR_LIT>'<EOL><DEDENT>elif leftover == <NUM_LIT:2>:<EOL><INDENT>return encoded[:-<NUM_LIT:4>] + '<STR_LIT>'<EOL><DEDENT>elif leftover == <NUM_LIT:3>:<EOL><INDENT>return encoded[:-<NUM_LIT:3>] + '<STR_LIT>'<EOL><DEDENT>elif leftover == <NUM_LIT:4>:<EOL><INDENT>return encoded[:-<NUM_LIT:1>] + '<STR_LIT:=>'<EOL><DEDENT>return encoded<EOL>

Encode a string using Base32.

    s is the string to encode.  The encoded string is returned.


return b64decode(s)<EOL>

Decode a string encoded with the standard Base64 alphabet.

    Argument s is the string to decode.  The decoded string is returned.  A
    TypeError is raised if the string is incorrectly padded.  Characters that
    are not in the standard alphabet are discarded prior to the padding
    check.


code = int(code)<EOL>if not <NUM_LIT:1> <= code <= <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>key = (module, name)<EOL>if (_extension_registry.get(key) == code and<EOL>_inverted_registry.get(code) == key):<EOL><INDENT>return <EOL><DEDENT>if key in _extension_registry:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(key, _extension_registry[key]))<EOL><DEDENT>if code in _inverted_registry:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(code, _inverted_registry[code]))<EOL><DEDENT>_extension_registry[key] = code<EOL>_inverted_registry[code] = key<EOL>


def remove_extension(module, name, code):

key = (module, name)<EOL>if (_extension_registry.get(key) != code or<EOL>_inverted_registry.get(code) != key):<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(key, code))<EOL><DEDENT>del _extension_registry[key]<EOL>del _inverted_registry[code]<EOL>if code in _extension_cache:<EOL><INDENT>del _extension_cache[code]<EOL><DEDENT>

Unregister an extension code.  For testing only.


Blocks until all items in the Queue have been gotten and processed.

        The count of unfinished tasks goes up whenever an item is added to the
        queue. The count goes down whenever a consumer thread calls task_done()
        to indicate the item was retrieved and all work on it is complete.

        When the count of unfinished tasks drops to zero, join() unblocks.


self.all_tasks_done.acquire()<EOL>try:<EOL><INDENT>unfinished = self.unfinished_tasks - <NUM_LIT:1><EOL>if unfinished <= <NUM_LIT:0>:<EOL><INDENT>if unfinished < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.all_tasks_done.notify_all()<EOL><DEDENT>self.unfinished_tasks = unfinished<EOL><DEDENT>finally:<EOL><INDENT>self.all_tasks_done.release()<EOL><DEDENT>

Indicate that a formerly enqueued task is complete.

        Used by Queue consumer threads.  For each get() used to fetch a task,
        a subsequent call to task_done() tells the queue that the processing
        on the task is complete.

        If a join() is currently blocking, it will resume when all items
        have been processed (meaning that a task_done() call was received
        for every item that had been put() into the queue).

        Raises a ValueError if called more times than there were items
        placed in the queue.


def put(self, item, block=True, timeout=None):

self.not_full.acquire()<EOL>try:<EOL><INDENT>if self.maxsize > <NUM_LIT:0>:<EOL><INDENT>if not block:<EOL><INDENT>if self._qsize() == self.maxsize:<EOL><INDENT>raise Full<EOL><DEDENT><DEDENT>elif timeout is None:<EOL><INDENT>while self._qsize() == self.maxsize:<EOL><INDENT>self.not_full.wait()<EOL><DEDENT><DEDENT>elif timeout < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>endtime = _time() + timeout<EOL>while self._qsize() == self.maxsize:<EOL><INDENT>remaining = endtime - _time()<EOL>if remaining <= <NUM_LIT:0.0>:<EOL><INDENT>raise Full<EOL><DEDENT>self.not_full.wait(remaining)<EOL><DEDENT><DEDENT><DEDENT>self._put(item)<EOL>self.unfinished_tasks += <NUM_LIT:1><EOL>self.not_empty.notify()<EOL><DEDENT>finally:<EOL><INDENT>self.not_full.release()<EOL><DEDENT>

Put an item into the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until a free slot is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Full exception if no free slot was available within that time.
        Otherwise ('block' is false), put an item on the queue if a free slot
        is immediately available, else raise the Full exception ('timeout'
        is ignored in that case).


la, lb = len(self.a), len(self.b)<EOL>return _calculate_ratio(min(la, lb), la + lb)<EOL>

Return an upper bound on ratio() very quickly.

        This isn't defined beyond that it is an upper bound on .ratio(), and
        is faster to compute than either .ratio() or .quick_ratio().


<EOL>beginning = start + <NUM_LIT:1>     <EOL>length = stop - start<EOL>if length == <NUM_LIT:1>:<EOL><INDENT>return '<STR_LIT:%s>' % (beginning)<EOL><DEDENT>if not length:<EOL><INDENT>beginning -= <NUM_LIT:1>        <EOL><DEDENT>return '<STR_LIT>' % (beginning, length)<EOL>


if self.opcodes is not None:<EOL><INDENT>return self.opcodes<EOL><DEDENT>i = j = <NUM_LIT:0><EOL>self.opcodes = answer = []<EOL>for ai, bj, size in self.get_matching_blocks():<EOL><INDENT>tag = '<STR_LIT>'<EOL>if i < ai and j < bj:<EOL><INDENT>tag = '<STR_LIT:replace>'<EOL><DEDENT>elif i < ai:<EOL><INDENT>tag = '<STR_LIT>'<EOL><DEDENT>elif j < bj:<EOL><INDENT>tag = '<STR_LIT>'<EOL><DEDENT>if tag:<EOL><INDENT>answer.append( (tag, i, ai, j, bj) )<EOL><DEDENT>i, j = ai+size, bj+size<EOL>if size:<EOL><INDENT>answer.append( ('<STR_LIT>', ai, i, bj, j) )<EOL><DEDENT><DEDENT>return answer<EOL>

Return list of 5-tuples describing how to turn a into b.

        Each tuple is of the form (tag, i1, i2, j1, j2).  The first tuple
        has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
        tuple preceding it, and likewise for j1 == the previous j2.

        The tags are strings, with these meanings:

        'replace':  a[i1:i2] should be replaced by b[j1:j2]
        'delete':   a[i1:i2] should be deleted.
                    Note that j1==j2 in this case.
        'insert':   b[j1:j2] should be inserted at a[i1:i1].
                    Note that i1==i2 in this case.
        'equal':    a[i1:i2] == b[j1:j2]

        >>> a = "qabxcd"
        >>> b = "abycdf"
        >>> s = SequenceMatcher(None, a, b)
        >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
        ...    print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
        ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
         delete a[0:1] (q) b[0:0] ()
          equal a[1:3] (ab) b[0:2] (ab)
        replace a[3:4] (x) b[2:3] (y)
          equal a[4:6] (cd) b[3:5] (cd)
         insert a[6:6] () b[5:6] (f)


return '<STR_LIT>' % self<EOL>

Return a nicely formatted representation string


matches = reduce(lambda sum, triple: sum + triple[-<NUM_LIT:1>],<EOL>self.get_matching_blocks(), <NUM_LIT:0>)<EOL>return _calculate_ratio(matches, len(self.a) + len(self.b))<EOL>

Return a measure of the sequences' similarity (float in [0,1]).

        Where T is the total number of elements in both sequences, and
        M is the number of matches, this is 2.0*M / T.
        Note that this is 1 if the sequences are identical, and 0 if
        they have nothing in common.

        .ratio() is expensive to compute if you haven't already computed
        .get_matching_blocks() or .get_opcodes(), in which case you may
        want to try .quick_ratio() or .real_quick_ratio() first to get an
        upper bound.

        >>> s = SequenceMatcher(None, "abcd", "bcde")
        >>> s.ratio()
        0.75
        >>> s.quick_ratio()
        0.75
        >>> s.real_quick_ratio()
        1.0


def __init__(self, isjunk=None, a='<STR_LIT>', b='<STR_LIT>', autojunk=True):

<EOL>self.isjunk = isjunk<EOL>self.a = self.b = None<EOL>self.autojunk = autojunk<EOL>self.set_seqs(a, b)<EOL>

Construct a SequenceMatcher.

        Optional arg isjunk is None (the default), or a one-argument
        function that takes a sequence element and returns true iff the
        element is junk.  None is equivalent to passing "lambda x: 0", i.e.
        no elements are considered to be junk.  For example, pass
            lambda x: x in " \\t"
        if you're comparing lines as sequences of characters, and don't
        want to synch up on blanks or hard tabs.

        Optional arg a is the first of two sequences to be compared.  By
        default, an empty string.  The elements of a must be hashable.  See
        also .set_seqs() and .set_seq1().

        Optional arg b is the second of two sequences to be compared.  By
        default, an empty string.  The elements of b must be hashable. See
        also .set_seqs() and .set_seq2().

        Optional arg autojunk should be set to False to disable the
        "automatic junk heuristic" that treats popular elements as junk
        (see module documentation for more information).


try:<EOL><INDENT>tag = {<NUM_LIT:1>: "<STR_LIT>", <NUM_LIT:2>: "<STR_LIT>"}[int(which)]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>% which)<EOL><DEDENT>prefixes = ("<STR_LIT:U+0020>", tag)<EOL>for line in delta:<EOL><INDENT>if line[:<NUM_LIT:2>] in prefixes:<EOL><INDENT>yield line[<NUM_LIT:2>:]<EOL><DEDENT><DEDENT>

r"""
    Generate one of the two sequences that generated a delta.

    Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
    lines originating from file 1 or 2 (parameter `which`), stripping off line
    prefixes.

    Examples:

    >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
    ...              'ore\ntree\nemu\n'.splitlines(1))
    >>> diff = list(diff)
    >>> print ''.join(restore(diff, 1)),
    one
    two
    three
    >>> print ''.join(restore(diff, 2)),
    ore
    tree
    emu


def get_close_matches(word, possibilities, n=<NUM_LIT:3>, cutoff=<NUM_LIT>):

if not n >  <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % (n,))<EOL><DEDENT>if not <NUM_LIT:0.0> <= cutoff <= <NUM_LIT:1.0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % (cutoff,))<EOL><DEDENT>result = []<EOL>s = SequenceMatcher()<EOL>s.set_seq2(word)<EOL>for x in possibilities:<EOL><INDENT>s.set_seq1(x)<EOL>if s.real_quick_ratio() >= cutoff ands.quick_ratio() >= cutoff ands.ratio() >= cutoff:<EOL><INDENT>result.append((s.ratio(), x))<EOL><DEDENT><DEDENT>result = heapq.nlargest(n, result)<EOL>return [x for score, x in result]<EOL>

Use SequenceMatcher to return list of the best "good enough" matches.

    word is a sequence for which close matches are desired (typically a
    string).

    possibilities is a list of sequences against which to match word
    (typically a list of strings).

    Optional arg n (default 3) is the maximum number of close matches to
    return.  n must be > 0.

    Optional arg cutoff (default 0.6) is a float in [0, 1].  Possibilities
    that don't score at least that similar to word are ignored.

    The best (no more than n) matches among the possibilities are returned
    in a list, sorted by similarity score, most similar first.

    >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
    ['apple', 'ape']
    >>> import keyword as _keyword
    >>> get_close_matches("wheel", _keyword.kwlist)
    ['while']
    >>> get_close_matches("apple", _keyword.kwlist)
    []
    >>> get_close_matches("accept", _keyword.kwlist)
    ['except']


def expand_tabs(line):<EOL><INDENT>line = line.replace('<STR_LIT:U+0020>','<STR_LIT>')<EOL>line = line.expandtabs(self._tabsize)<EOL>line = line.replace('<STR_LIT:U+0020>','<STR_LIT:\t>')<EOL>return line.replace('<STR_LIT>','<STR_LIT:U+0020>').rstrip('<STR_LIT:\n>')<EOL><DEDENT>fromlines = [expand_tabs(line) for line in fromlines]<EOL>tolines = [expand_tabs(line) for line in tolines]<EOL>return fromlines,tolines<EOL>

Returns from/to line lists with tabs expanded and newlines removed.

        Instead of tab characters being replaced by the number of spaces
        needed to fill in to the next tab stop, this function will fill
        the space with tab characters.  This is done so that the difference
        algorithms can identify changes in a file when tabs are replaced by
        spaces and vice versa.  At the end of the HTML generation, the tab
        characters will be replaced with a nonbreakable space.


i, n = <NUM_LIT:0>, len(line)<EOL>while i < n and line[i] == ch:<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT>return i<EOL>

Return number of `ch` characters at the start of `line`.

Example:

>>> _count_leading('   abc', ' ')
3


def _fancy_replace(self, a, alo, ahi, b, blo, bhi):

<EOL>best_ratio, cutoff = <NUM_LIT>, <NUM_LIT><EOL>cruncher = SequenceMatcher(self.charjunk)<EOL>eqi, eqj = None, None   <EOL>for j in range(blo, bhi):<EOL><INDENT>bj = b[j]<EOL>cruncher.set_seq2(bj)<EOL>for i in range(alo, ahi):<EOL><INDENT>ai = a[i]<EOL>if ai == bj:<EOL><INDENT>if eqi is None:<EOL><INDENT>eqi, eqj = i, j<EOL><DEDENT>continue<EOL><DEDENT>cruncher.set_seq1(ai)<EOL>if cruncher.real_quick_ratio() > best_ratio andcruncher.quick_ratio() > best_ratio andcruncher.ratio() > best_ratio:<EOL><INDENT>best_ratio, best_i, best_j = cruncher.ratio(), i, j<EOL><DEDENT><DEDENT><DEDENT>if best_ratio < cutoff:<EOL><INDENT>if eqi is None:<EOL><INDENT>for line in self._plain_replace(a, alo, ahi, b, blo, bhi):<EOL><INDENT>yield line<EOL><DEDENT>return<EOL><DEDENT>best_i, best_j, best_ratio = eqi, eqj, <NUM_LIT:1.0><EOL><DEDENT>else:<EOL><INDENT>eqi = None<EOL><DEDENT>for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):<EOL><INDENT>yield line<EOL><DEDENT>aelt, belt = a[best_i], b[best_j]<EOL>if eqi is None:<EOL><INDENT>atags = btags = "<STR_LIT>"<EOL>cruncher.set_seqs(aelt, belt)<EOL>for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():<EOL><INDENT>la, lb = ai2 - ai1, bj2 - bj1<EOL>if tag == '<STR_LIT:replace>':<EOL><INDENT>atags += '<STR_LIT>' * la<EOL>btags += '<STR_LIT>' * lb<EOL><DEDENT>elif tag == '<STR_LIT>':<EOL><INDENT>atags += '<STR_LIT:->' * la<EOL><DEDENT>elif tag == '<STR_LIT>':<EOL><INDENT>btags += '<STR_LIT:+>' * lb<EOL><DEDENT>elif tag == '<STR_LIT>':<EOL><INDENT>atags += '<STR_LIT:U+0020>' * la<EOL>btags += '<STR_LIT:U+0020>' * lb<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % (tag,))<EOL><DEDENT><DEDENT>for line in self._qformat(aelt, belt, atags, btags):<EOL><INDENT>yield line<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield '<STR_LIT:U+0020>' + aelt<EOL><DEDENT>for line in self._fancy_helper(a, best_i+<NUM_LIT:1>, ahi, b, best_j+<NUM_LIT:1>, bhi):<EOL><INDENT>yield line<EOL><DEDENT>

r"""
        When replacing one block of lines with another, search the blocks
        for *similar* lines; the best-matching pair (if any) is used as a
        synch point, and intraline difference marking is done on the
        similar pair. Lots of work, but often worth it.

        Example:

        >>> d = Differ()
        >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
        ...                            ['abcdefGhijkl\n'], 0, 1)
        >>> print ''.join(results),
        - abcDefghiJkl
        ?    ^  ^  ^
        + abcdefGhijkl
        ?    ^  ^  ^


if b is self.b:<EOL><INDENT>return<EOL><DEDENT>self.b = b<EOL>self.matching_blocks = self.opcodes = None<EOL>self.fullbcount = None<EOL>self.__chain_b()<EOL>

Set the second sequence to be compared.

        The first sequence to be compared is not changed.

        >>> s = SequenceMatcher(None, "abcd", "bcde")
        >>> s.ratio()
        0.75
        >>> s.set_seq2("abcd")
        >>> s.ratio()
        1.0
        >>>

        SequenceMatcher computes and caches detailed information about the
        second sequence, so if you want to compare one sequence S against
        many sequences, use .set_seq2(S) once and call .set_seq1(x)
        repeatedly for each of the other sequences.

        See also set_seqs() and set_seq1().


return OrderedDict(list(zip(self._fields, self)))<EOL>

Return a new OrderedDict which maps field names to their values


<EOL>self._make_prefix()<EOL>fromlines,tolines = self._tab_newline_replace(fromlines,tolines)<EOL>if context:<EOL><INDENT>context_lines = numlines<EOL><DEDENT>else:<EOL><INDENT>context_lines = None<EOL><DEDENT>diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,<EOL>charjunk=self._charjunk)<EOL>if self._wrapcolumn:<EOL><INDENT>diffs = self._line_wrapper(diffs)<EOL><DEDENT>fromlist,tolist,flaglist = self._collect_lines(diffs)<EOL>fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(<EOL>fromlist,tolist,flaglist,context,numlines)<EOL>s = []<EOL>fmt = '<STR_LIT>' +'<STR_LIT>'<EOL>for i in range(len(flaglist)):<EOL><INDENT>if flaglist[i] is None:<EOL><INDENT>if i > <NUM_LIT:0>:<EOL><INDENT>s.append('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>s.append( fmt % (next_id[i],next_href[i],fromlist[i],<EOL>next_href[i],tolist[i]))<EOL><DEDENT><DEDENT>if fromdesc or todesc:<EOL><INDENT>header_row = '<STR_LIT>' % (<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % fromdesc,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % todesc)<EOL><DEDENT>else:<EOL><INDENT>header_row = '<STR_LIT>'<EOL><DEDENT>table = self._table_template % dict(<EOL>data_rows='<STR_LIT>'.join(s),<EOL>header_row=header_row,<EOL>prefix=self._prefix[<NUM_LIT:1>])<EOL>return table.replace('<STR_LIT>','<STR_LIT>').replace('<STR_LIT>','<STR_LIT>').replace('<STR_LIT>','<STR_LIT>').replace('<STR_LIT>','<STR_LIT>').replace('<STR_LIT:\t>','<STR_LIT>')<EOL>

Returns HTML table of side by side comparison with change highlights

        Arguments:
        fromlines -- list of "from" lines
        tolines -- list of "to" lines
        fromdesc -- "from" file column header string
        todesc -- "to" file column header string
        context -- set to True for contextual differences (defaults to False
            which shows full differences).
        numlines -- number of context lines.  When context is set True,
            controls number of lines displayed before and after the change.
            When context is False, controls the number of lines to place
            the "next" link anchors before the next change (so click of
            "next" link jumps to just before the change).


return pat(line) is not None<EOL>

r"""
    Return 1 for ignorable line: iff `line` is blank or contains a single '#'.

    Examples:

    >>> IS_LINE_JUNK('\n')
    True
    >>> IS_LINE_JUNK('  #   \n')
    True
    >>> IS_LINE_JUNK('hello\n')
    False


<EOL>if not line_num:<EOL><INDENT>data_list.append((line_num,text))<EOL>return<EOL><DEDENT>size = len(text)<EOL>max = self._wrapcolumn<EOL>if (size <= max) or ((size -(text.count('<STR_LIT>')*<NUM_LIT:3>)) <= max):<EOL><INDENT>data_list.append((line_num,text))<EOL>return<EOL><DEDENT>i = <NUM_LIT:0><EOL>n = <NUM_LIT:0><EOL>mark = '<STR_LIT>'<EOL>while n < max and i < size:<EOL><INDENT>if text[i] == '<STR_LIT>':<EOL><INDENT>i += <NUM_LIT:1><EOL>mark = text[i]<EOL>i += <NUM_LIT:1><EOL><DEDENT>elif text[i] == '<STR_LIT>':<EOL><INDENT>i += <NUM_LIT:1><EOL>mark = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>i += <NUM_LIT:1><EOL>n += <NUM_LIT:1><EOL><DEDENT><DEDENT>line1 = text[:i]<EOL>line2 = text[i:]<EOL>if mark:<EOL><INDENT>line1 = line1 + '<STR_LIT>'<EOL>line2 = '<STR_LIT>' + mark + line2<EOL><DEDENT>data_list.append((line_num,line1))<EOL>self._split_line(data_list,'<STR_LIT:>>',line2)<EOL>

Builds list of text lines by splitting text lines at wrap point

        This function will determine if the input text line needs to be
        wrapped (split) into separate lines.  If so, the first wrap point
        will be determined and the first line appended to the output
        text line list.  This function is used recursively to handle
        the second part of the split line to further split it.


result = _self._make(list(map(kwds.pop, ('<STR_LIT:a>', '<STR_LIT:b>', '<STR_LIT:size>'), _self)))<EOL>if kwds:<EOL><INDENT>raise ValueError('<STR_LIT>' % list(kwds.keys()))<EOL><DEDENT>return result<EOL>

Return a new Match object replacing specified fields with new values


def context_diff(a, b, fromfile='<STR_LIT>', tofile='<STR_LIT>',<EOL>fromfiledate='<STR_LIT>', tofiledate='<STR_LIT>', n=<NUM_LIT:3>, lineterm='<STR_LIT:\n>'):

prefix = dict(insert='<STR_LIT>', delete='<STR_LIT>', replace='<STR_LIT>', equal='<STR_LIT:U+0020>')<EOL>started = False<EOL>for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):<EOL><INDENT>if not started:<EOL><INDENT>started = True<EOL>fromdate = '<STR_LIT>' % (fromfiledate) if fromfiledate else '<STR_LIT>'<EOL>todate = '<STR_LIT>' % (tofiledate) if tofiledate else '<STR_LIT>'<EOL>yield '<STR_LIT>' % (fromfile, fromdate, lineterm)<EOL>yield '<STR_LIT>' % (tofile, todate, lineterm)<EOL><DEDENT>first, last = group[<NUM_LIT:0>], group[-<NUM_LIT:1>]<EOL>yield '<STR_LIT>' + lineterm<EOL>file1_range = _format_range_context(first[<NUM_LIT:1>], last[<NUM_LIT:2>])<EOL>yield '<STR_LIT>' % (file1_range, lineterm)<EOL>if any(tag in ('<STR_LIT:replace>', '<STR_LIT>') for tag, _, _, _, _ in group):<EOL><INDENT>for tag, i1, i2, _, _ in group:<EOL><INDENT>if tag != '<STR_LIT>':<EOL><INDENT>for line in a[i1:i2]:<EOL><INDENT>yield prefix[tag] + line<EOL><DEDENT><DEDENT><DEDENT><DEDENT>file2_range = _format_range_context(first[<NUM_LIT:3>], last[<NUM_LIT:4>])<EOL>yield '<STR_LIT>' % (file2_range, lineterm)<EOL>if any(tag in ('<STR_LIT:replace>', '<STR_LIT>') for tag, _, _, _, _ in group):<EOL><INDENT>for tag, _, _, j1, j2 in group:<EOL><INDENT>if tag != '<STR_LIT>':<EOL><INDENT>for line in b[j1:j2]:<EOL><INDENT>yield prefix[tag] + line<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>

r"""
    Compare two sequences of lines; generate the delta as a context diff.

    Context diffs are a compact way of showing line changes and a few
    lines of context.  The number of context lines is set by 'n' which
    defaults to three.

    By default, the diff control lines (those with *** or ---) are
    created with a trailing newline.  This is helpful so that inputs
    created from file.readlines() result in diffs that are suitable for
    file.writelines() since both the inputs and outputs have trailing
    newlines.

    For inputs that do not have trailing newlines, set the lineterm
    argument to "" so that the output will be uniformly newline free.

    The context diff format normally has a header for filenames and
    modification times.  Any or all of these may be specified using
    strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
    The modification times are normally expressed in the ISO 8601 format.
    If not specified, the strings default to blanks.

    Example:

    >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
    ...       'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current')),
    *** Original
    --- Current
    ***************
    *** 1,4 ****
      one
    ! two
    ! three
      four
    --- 1,4 ----
    + zero
      one
    ! tree
      four


try:<EOL><INDENT>linenum = '<STR_LIT>' % linenum<EOL>id = '<STR_LIT>' % (self._prefix[side],linenum)<EOL><DEDENT>except TypeError:<EOL><INDENT>id = '<STR_LIT>'<EOL><DEDENT>text=text.replace("<STR_LIT:&>","<STR_LIT>").replace("<STR_LIT:>>","<STR_LIT>").replace("<STR_LIT:<>","<STR_LIT>")<EOL>text = text.replace('<STR_LIT:U+0020>','<STR_LIT>').rstrip()<EOL>return '<STR_LIT>'% (id,linenum,text)<EOL>

Returns HTML markup of "from" / "to" text lines

        side -- 0 or 1 indicating "from" or "to" text
        flag -- indicates if difference on line
        linenum -- line number (used for line number column)
        text -- line text to be marked up


if filename in cache:<EOL><INDENT>return cache[filename][<NUM_LIT:2>]<EOL><DEDENT>try:<EOL><INDENT>return updatecache(filename, module_globals)<EOL><DEDENT>except MemoryError:<EOL><INDENT>clearcache()<EOL>return []<EOL><DEDENT>

Get the lines for a file from the cache.
    Update the cache if it doesn't contain an entry for this file already.


if filename in cache:<EOL><INDENT>del cache[filename]<EOL><DEDENT>if not filename or (filename.startswith('<STR_LIT:<>') and filename.endswith('<STR_LIT:>>')):<EOL><INDENT>return []<EOL><DEDENT>fullname = filename<EOL>try:<EOL><INDENT>stat = os.stat(fullname)<EOL><DEDENT>except OSError:<EOL><INDENT>basename = filename<EOL>if module_globals and '<STR_LIT>' in module_globals:<EOL><INDENT>name = module_globals.get('<STR_LIT>')<EOL>loader = module_globals['<STR_LIT>']<EOL>get_source = getattr(loader, '<STR_LIT>', None)<EOL>if name and get_source:<EOL><INDENT>try:<EOL><INDENT>data = get_source(name)<EOL><DEDENT>except (ImportError, IOError):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if data is None:<EOL><INDENT>return []<EOL><DEDENT>cache[filename] = (<EOL>len(data), None,<EOL>[line+'<STR_LIT:\n>' for line in data.splitlines()], fullname<EOL>)<EOL>return cache[filename][<NUM_LIT:2>]<EOL><DEDENT><DEDENT><DEDENT>if os.path.isabs(filename):<EOL><INDENT>return []<EOL><DEDENT>for dirname in sys.path:<EOL><INDENT>try:<EOL><INDENT>fullname = os.path.join(dirname, basename)<EOL><DEDENT>except (TypeError, AttributeError):<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>stat = os.stat(fullname)<EOL>break<EOL><DEDENT>except os.error:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>try:<EOL><INDENT>with open(fullname, '<STR_LIT>') as fp:<EOL><INDENT>lines = fp.readlines()<EOL><DEDENT><DEDENT>except IOError:<EOL><INDENT>return []<EOL><DEDENT>if lines and not lines[-<NUM_LIT:1>].endswith('<STR_LIT:\n>'):<EOL><INDENT>lines[-<NUM_LIT:1>] += '<STR_LIT:\n>'<EOL><DEDENT>size, mtime = stat.st_size, stat.st_mtime<EOL>cache[filename] = size, mtime, lines, fullname<EOL>return lines<EOL>

Update a cache entry and return its list of lines.
    If something's wrong, print a message, discard the cache entry,
    and return an empty list.


global cache<EOL>cache = {}<EOL>


if filename is None:<EOL><INDENT>filenames = cache.keys()<EOL><DEDENT>else:<EOL><INDENT>if filename in cache:<EOL><INDENT>filenames = [filename]<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>for filename in filenames:<EOL><INDENT>size, mtime, lines, fullname = cache[filename]<EOL>if mtime is None:<EOL><INDENT>continue   <EOL><DEDENT>try:<EOL><INDENT>stat = os.stat(fullname)<EOL><DEDENT>except os.error:<EOL><INDENT>del cache[filename]<EOL>continue<EOL><DEDENT>if size != stat.st_size or mtime != stat.st_mtime:<EOL><INDENT>del cache[filename]<EOL><DEDENT><DEDENT>

Discard cache entries that are out of date.
    (This is not checked upon each call!)


m = self.create_message(msg)<EOL>i = <NUM_LIT:0><EOL>for n, a in m.getaddrlist('<STR_LIT:to>') + m.getaddrlist('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>mn, ma = results[i][<NUM_LIT:0>], results[i][<NUM_LIT:1>]<EOL><DEDENT>except IndexError:<EOL><INDENT>print('<STR_LIT>', repr(n), repr(a))<EOL>continue<EOL><DEDENT>i = i + <NUM_LIT:1><EOL>self.assertEqual(mn, n,<EOL>"<STR_LIT>" % (mn, n))<EOL>self.assertEqual(ma, a,<EOL>"<STR_LIT>" % (ma, a))<EOL>if mn == n and ma == a:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>', repr(n), repr(a))<EOL><DEDENT><DEDENT>out = m.getdate('<STR_LIT:date>')<EOL>if out:<EOL><INDENT>self.assertEqual(out,<EOL>(<NUM_LIT>, <NUM_LIT:1>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:0>),<EOL>"<STR_LIT>")<EOL><DEDENT>


quiet = kwargs.get('<STR_LIT>')<EOL>if not filters:<EOL><INDENT>filters = (("<STR_LIT>", Warning),)<EOL>if quiet is None:<EOL><INDENT>quiet = True<EOL><DEDENT><DEDENT>return _filterwarnings(filters, quiet)<EOL>

Context manager to silence warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default True without argument,
         default False if some filters are defined)

    Without argument, it defaults to:
        check_warnings(("", Warning), quiet=True)


if verbose:<EOL><INDENT>runner = unittest.TextTestRunner(sys.stdout, verbosity=<NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>runner = BasicTestRunner()<EOL><DEDENT>result = runner.run(suite)<EOL>if not result.wasSuccessful():<EOL><INDENT>if len(result.errors) == <NUM_LIT:1> and not result.failures:<EOL><INDENT>err = result.errors[<NUM_LIT:0>][<NUM_LIT:1>]<EOL><DEDENT>elif len(result.failures) == <NUM_LIT:1> and not result.errors:<EOL><INDENT>err = result.failures[<NUM_LIT:0>][<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>err = "<STR_LIT>"<EOL>if not verbose:<EOL><INDENT>err += "<STR_LIT>"<EOL><DEDENT><DEDENT>raise TestFailed(err)<EOL><DEDENT>

Run tests from a unittest.TestSuite-derived class.


return {<NUM_LIT:1>:<NUM_LIT:2>, "<STR_LIT>":"<STR_LIT>", "<STR_LIT>":(<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:3>)}<EOL>

Return a dictionary of values which are invariant by storage
        in the object under test.


x = self._empty_mapping()<EOL>for key, value in list(data.items()):<EOL><INDENT>x[key] = value<EOL><DEDENT>return x<EOL>

Return a mapping object with the value contained in data
        dictionary


def loadTestsFromNames(self, names, module=None):

suites = [self.loadTestsFromName(name, module) for name in names]<EOL>return self.suiteClass(suites)<EOL>

Return a suite of all tests cases found using the given sequence
        of string specifiers. See 'loadTestsFromName()'.


def loadTestsFromName(self, name, module=None):

parts = name.split('<STR_LIT:.>')<EOL>if module is None:<EOL><INDENT>parts_copy = parts[:]<EOL>while parts_copy:<EOL><INDENT>try:<EOL><INDENT>module = __import__('<STR_LIT:.>'.join(parts_copy))<EOL>break<EOL><DEDENT>except ImportError:<EOL><INDENT>del parts_copy[-<NUM_LIT:1>]<EOL>if not parts_copy:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>parts = parts[<NUM_LIT:1>:]<EOL><DEDENT>obj = module<EOL>for part in parts:<EOL><INDENT>parent, obj = obj, getattr(obj, part)<EOL><DEDENT>if isinstance(obj, types.ModuleType):<EOL><INDENT>return self.loadTestsFromModule(obj)<EOL><DEDENT>elif isinstance(obj, type) and issubclass(obj, case.TestCase):<EOL><INDENT>return self.loadTestsFromTestCase(obj)<EOL><DEDENT>elif (isinstance(obj, types.UnboundMethodType) and<EOL>isinstance(parent, type) and<EOL>issubclass(parent, case.TestCase)):<EOL><INDENT>name = parts[-<NUM_LIT:1>]<EOL>inst = parent(name)<EOL>return self.suiteClass([inst])<EOL><DEDENT>elif isinstance(obj, suite.TestSuite):<EOL><INDENT>return obj<EOL><DEDENT>elif hasattr(obj, '<STR_LIT>'):<EOL><INDENT>test = obj()<EOL>if isinstance(test, suite.TestSuite):<EOL><INDENT>return test<EOL><DEDENT>elif isinstance(test, case.TestCase):<EOL><INDENT>return self.suiteClass([test])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" %<EOL>(obj, test))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % obj)<EOL><DEDENT>

Return a suite of all tests cases given a string specifier.

        The name may resolve either to a module, a test case class, a
        test method within a test case class, or a callable object which
        returns a TestCase or TestSuite instance.

        The method optionally resolves the names relative to a given module.


<EOL>if subclass in cls._abc_cache:<EOL><INDENT>return True<EOL><DEDENT>if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:<EOL><INDENT>cls._abc_negative_cache = _weakrefset.WeakSet()<EOL>cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter<EOL><DEDENT>elif subclass in cls._abc_negative_cache:<EOL><INDENT>return False<EOL><DEDENT>ok = cls.__subclasshook__(subclass)<EOL>if ok is not NotImplemented:<EOL><INDENT>assert isinstance(ok, bool)<EOL>if ok:<EOL><INDENT>cls._abc_cache.add(subclass)<EOL><DEDENT>else:<EOL><INDENT>cls._abc_negative_cache.add(subclass)<EOL><DEDENT>return ok<EOL><DEDENT>if cls in getattr(subclass, '<STR_LIT>', ()):<EOL><INDENT>cls._abc_cache.add(subclass)<EOL>return True<EOL><DEDENT>for rcls in cls._abc_registry:<EOL><INDENT>if issubclass(subclass, rcls):<EOL><INDENT>cls._abc_cache.add(subclass)<EOL>return True<EOL><DEDENT><DEDENT>for scls in cls.__subclasses__():<EOL><INDENT>if issubclass(subclass, scls):<EOL><INDENT>cls._abc_cache.add(subclass)<EOL>return True<EOL><DEDENT><DEDENT>cls._abc_negative_cache.add(subclass)<EOL>return False<EOL>


funcobj.__isabstractmethod__ = True<EOL>return funcobj<EOL>

A decorator indicating abstract methods.

    Requires that the metaclass is ABCMeta or derived from it.  A
    class that has a metaclass derived from ABCMeta cannot be
    instantiated unless all of its abstract methods are overridden.
    The abstract methods can be called using any of the normal
    'super' call mechanisms.

    Usage:

        class C:
            __metaclass__ = ABCMeta
            @abstractmethod
            def my_abstract_method(self, ...):
                ...


print >> file, "<STR_LIT>" % (cls.__module__, cls.__name__)<EOL>print >> file, "<STR_LIT>" % ABCMeta._abc_invalidation_counter<EOL>for name in sorted(cls.__dict__.keys()):<EOL><INDENT>if name.startswith("<STR_LIT>"):<EOL><INDENT>value = getattr(cls, name)<EOL>print >> file, "<STR_LIT>" % (name, value)<EOL><DEDENT><DEDENT>


<EOL>if (isinstance(etype, BaseException) or<EOL>isinstance(etype, types.InstanceType) or<EOL>etype is None or type(etype) is str):<EOL><INDENT>return [_format_final_exc_line(etype, value)]<EOL><DEDENT>stype = etype.__name__<EOL>if not issubclass(etype, SyntaxError):<EOL><INDENT>return [_format_final_exc_line(stype, value)]<EOL><DEDENT>lines = []<EOL>try:<EOL><INDENT>msg, (filename, lineno, offset, badline) = value.args<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>filename = filename or "<STR_LIT>"<EOL>lines.append('<STR_LIT>' % (filename, lineno))<EOL>if badline is not None:<EOL><INDENT>lines.append('<STR_LIT>' % badline.strip())<EOL>if offset is not None:<EOL><INDENT>caretspace = badline.rstrip('<STR_LIT:\n>')<EOL>offset = min(len(caretspace), offset) - <NUM_LIT:1><EOL>caretspace = caretspace[:offset].lstrip()<EOL>caretspace = ((c.isspace() and c or '<STR_LIT:U+0020>') for c in caretspace)<EOL>lines.append('<STR_LIT>' % '<STR_LIT>'.join(caretspace))<EOL><DEDENT><DEDENT>value = msg<EOL><DEDENT>lines.append(_format_final_exc_line(stype, value))<EOL>return lines<EOL>

Format the exception part of a traceback.

    The arguments are the exception type and value such as given by
    sys.last_type and sys.last_value. The return value is a list of
    strings, each ending in a newline.

    Normally, the list contains a single string; however, for
    SyntaxError exceptions, it contains several lines that (when
    printed) display detailed information about where the syntax
    error occurred.

    The message indicating which exception occurred is always the last
    string in the list.


def extract_stack(f=None, limit = None):

if f is None:<EOL><INDENT>try:<EOL><INDENT>raise ZeroDivisionError<EOL><DEDENT>except ZeroDivisionError:<EOL><INDENT>f = sys.exc_info()[<NUM_LIT:2>].tb_frame.f_back<EOL><DEDENT><DEDENT>if limit is None:<EOL><INDENT>if hasattr(sys, '<STR_LIT>'):<EOL><INDENT>limit = sys.tracebacklimit<EOL><DEDENT><DEDENT>list = []<EOL>n = <NUM_LIT:0><EOL>while f is not None and (limit is None or n < limit):<EOL><INDENT>lineno = f.f_lineno<EOL>co = f.f_code<EOL>filename = co.co_filename<EOL>name = co.co_name<EOL>linecache.checkcache(filename)<EOL>line = linecache.getline(filename, lineno, f.f_globals)<EOL>if line: line = line.strip()<EOL>else: line = None<EOL>list.append((filename, lineno, name, line))<EOL>f = f.f_back<EOL>n = n+<NUM_LIT:1><EOL><DEDENT>list.reverse()<EOL>return list<EOL>

Extract the raw traceback from the current stack frame.

    The return value has the same format as for extract_tb().  The
    optional 'f' and 'limit' arguments have the same meaning as for
    print_stack().  Each item in the list is a quadruple (filename,
    line number, function name, text), and the entries are in order
    from oldest to newest stack frame.


def format_exception(etype, value, tb, limit = None):

if tb:<EOL><INDENT>list = ['<STR_LIT>']<EOL>list = list + format_tb(tb, limit)<EOL><DEDENT>else:<EOL><INDENT>list = []<EOL><DEDENT>list = list + format_exception_only(etype, value)<EOL>return list<EOL>

Format a stack trace and the exception information.

    The arguments have the same meaning as the corresponding arguments
    to print_exception().  The return value is a list of strings, each
    ending in a newline and some containing internal newlines.  When
    these lines are concatenated and printed, exactly the same text is
    printed as does print_exception().


if f is None:<EOL><INDENT>try:<EOL><INDENT>raise ZeroDivisionError<EOL><DEDENT>except ZeroDivisionError:<EOL><INDENT>f = sys.exc_info()[<NUM_LIT:2>].tb_frame.f_back<EOL><DEDENT><DEDENT>return format_list(extract_stack(f, limit))<EOL>

Shorthand for 'format_list(extract_stack(f, limit))'.


def print_exception(etype, value, tb, limit=None, file=None):

if file is None:<EOL><INDENT>file = open('<STR_LIT>', '<STR_LIT:w>')<EOL><DEDENT>if tb:<EOL><INDENT>_print(file, '<STR_LIT>')<EOL>print_tb(tb, limit, file)<EOL><DEDENT>lines = format_exception_only(etype, value)<EOL>for line in lines:<EOL><INDENT>_print(file, line, '<STR_LIT>')<EOL><DEDENT>

Print exception up to 'limit' stack trace entries from 'tb' to 'file'.

    This differs from print_tb() in the following ways: (1) if
    traceback is not None, it prints a header "Traceback (most recent
    call last):"; (2) it prints the exception type and value after the
    stack trace; (3) if type is SyntaxError and value has the
    appropriate format, it prints the line where the syntax error
    occurred with a caret on the next line indicating the approximate
    position of the error.


valuestr = _some_str(value)<EOL>if value is None or not valuestr:<EOL><INDENT>line = "<STR_LIT>" % etype<EOL><DEDENT>else:<EOL><INDENT>line = "<STR_LIT>" % (etype, valuestr)<EOL><DEDENT>return line<EOL>

Return a list of a single line -- normal case for format_exception_only


if limit is None:<EOL><INDENT>if hasattr(sys, '<STR_LIT>'):<EOL><INDENT>limit = sys.tracebacklimit<EOL><DEDENT><DEDENT>list = []<EOL>n = <NUM_LIT:0><EOL>while tb is not None and (limit is None or n < limit):<EOL><INDENT>f = tb.tb_frame<EOL>lineno = tb.tb_lineno<EOL>co = f.f_code<EOL>filename = co.co_filename<EOL>name = co.co_name<EOL>linecache.checkcache(filename)<EOL>line = linecache.getline(filename, lineno, f.f_globals)<EOL>if line: line = line.strip()<EOL>else: line = None<EOL>list.append((filename, lineno, name, line))<EOL>tb = tb.tb_next<EOL>n = n+<NUM_LIT:1><EOL><DEDENT>return list<EOL>

Return list of up to limit pre-processed entries from traceback.

    This is useful for alternate formatting of stack traces.  If
    'limit' is omitted or None, all entries are extracted.  A
    pre-processed stack trace entry is a quadruple (filename, line
    number, function name, text) representing the information that is
    usually printed for a stack trace.  The text is a string with
    leading and trailing whitespace stripped; if the source is not
    available it is None.


def insort_right(a, x, lo=<NUM_LIT:0>, hi=None):

if lo < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if hi is None:<EOL><INDENT>hi = len(a)<EOL><DEDENT>while lo < hi:<EOL><INDENT>mid = (lo+hi)//<NUM_LIT:2><EOL>if x < a[mid]: hi = mid<EOL>else: lo = mid+<NUM_LIT:1><EOL><DEDENT>a.insert(lo, x)<EOL>

Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the right of the rightmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.


if isinstance(text, _unicode):<EOL><INDENT>if self.break_on_hyphens:<EOL><INDENT>pat = self.wordsep_re_uni<EOL><DEDENT>else:<EOL><INDENT>pat = self.wordsep_simple_re_uni<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if self.break_on_hyphens:<EOL><INDENT>pat = self.wordsep_re<EOL><DEDENT>else:<EOL><INDENT>pat = self.wordsep_simple_re<EOL><DEDENT><DEDENT>chunks = pat.split(text)<EOL>chunks = [x for x in chunks if x is not None]<EOL>return chunks<EOL>

_split(text : string) -> [string]

        Split the text to wrap into indivisible chunks.  Chunks are
        not quite the same as words; see _wrap_chunks() for full
        details.  As an example, the text
          Look, goof-ball -- use the -b option!
        breaks into the following chunks:
          'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ',
          'use', ' ', 'the', ' ', '-b', ' ', 'option!'
        if break_on_hyphens is True, or in:
          'Look,', ' ', 'goof-ball', ' ', '--', ' ',
          'use', ' ', 'the', ' ', '-b', ' ', option!'
        otherwise.


lines = []<EOL>if self.width <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>" % self.width)<EOL><DEDENT>chunks.reverse()<EOL>while chunks:<EOL><INDENT>cur_line = []<EOL>cur_len = <NUM_LIT:0><EOL>if lines:<EOL><INDENT>indent = self.subsequent_indent<EOL><DEDENT>else:<EOL><INDENT>indent = self.initial_indent<EOL><DEDENT>width = self.width - len(indent)<EOL>if self.drop_whitespace and chunks[-<NUM_LIT:1>].strip() == '<STR_LIT>' and lines:<EOL><INDENT>chunks.pop()<EOL><DEDENT>while chunks:<EOL><INDENT>l = len(chunks[-<NUM_LIT:1>])<EOL>if cur_len + l <= width:<EOL><INDENT>cur_line.append(chunks.pop())<EOL>cur_len += l<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if chunks and len(chunks[-<NUM_LIT:1>]) > width:<EOL><INDENT>self._handle_long_word(chunks, cur_line, cur_len, width)<EOL><DEDENT>if self.drop_whitespace and cur_line and cur_line[-<NUM_LIT:1>].strip() == '<STR_LIT>':<EOL><INDENT>cur_line.pop()<EOL><DEDENT>if cur_line:<EOL><INDENT>lines.append(indent + '<STR_LIT>'.join(cur_line))<EOL><DEDENT><DEDENT>return lines<EOL>

_wrap_chunks(chunks : [string]) -> [string]

        Wrap a sequence of text chunks and return a list of lines of
        length 'self.width' or less.  (If 'break_long_words' is false,
        some lines may be longer than this.)  Chunks correspond roughly
        to words and the whitespace between them: each chunk is
        indivisible (modulo 'break_long_words'), but a line break can
        come between any two chunks.  Chunks should not have internal
        whitespace; ie. a chunk is either all whitespace or a "word".
        Whitespace chunks will be removed from the beginning and end of
        lines, but apart from that whitespace is preserved.


if self.expand_tabs:<EOL><INDENT>text = '<STR_LIT:U+0020>'.join(('<STR_LIT:U+0020>'.join(text.split('<STR_LIT:\n>'))).split('<STR_LIT:\t>'))<EOL><DEDENT>if self.replace_whitespace:<EOL><INDENT>text = '<STR_LIT:U+0020>'.join('<STR_LIT:U+0020>'.join(text.split('<STR_LIT:\n>')).split('<STR_LIT:\t>'))<EOL><DEDENT>return text<EOL>

_munge_whitespace(text : string) -> string

        Munge whitespace in text: expand tabs and convert all other
        whitespace characters to spaces.  Eg. " foo\\tbar\\n\\nbaz"
        becomes " foo    bar  baz".


def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):

<EOL>if width < <NUM_LIT:1>:<EOL><INDENT>space_left = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>space_left = width - cur_len<EOL><DEDENT>if self.break_long_words:<EOL><INDENT>cur_line.append(reversed_chunks[-<NUM_LIT:1>][:space_left])<EOL>reversed_chunks[-<NUM_LIT:1>] = reversed_chunks[-<NUM_LIT:1>][space_left:]<EOL><DEDENT>elif not cur_line:<EOL><INDENT>cur_line.append(reversed_chunks.pop())<EOL><DEDENT>

_handle_long_word(chunks : [string],
                             cur_line : [string],
                             cur_len : int, width : int)

        Handle a chunk of text (most likely a word, not whitespace) that
        is too long to fit in any line.


i = <NUM_LIT:0><EOL>patsearch = self.sentence_end_re.search<EOL>while i < len(chunks)-<NUM_LIT:1>:<EOL><INDENT>if chunks[i+<NUM_LIT:1>] == "<STR_LIT:U+0020>" and patsearch(chunks[i]):<EOL><INDENT>chunks[i+<NUM_LIT:1>] = "<STR_LIT:U+0020>"<EOL>i += <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>i += <NUM_LIT:1><EOL><DEDENT><DEDENT>

_fix_sentence_endings(chunks : [string])

        Correct for sentence endings buried in 'chunks'.  Eg. when the
        original text contains "... foo.\\nBar ...", munge_whitespace()
        and split() will convert that to [..., "foo.", " ", "Bar", ...]
        which has one too few spaces; this method simply changes the one
        space to two.


global _trace_hook<EOL>_trace_hook = func<EOL>

Set a trace function for all threads started from the threading module.

    The func will be passed to sys.settrace() for each thread, before its run()
    method is called.


Wake up all threads waiting on this condition.

        If the calling thread has not acquired the lock when this method
        is called, a RuntimeError is raised.


assert self.__initialized, "<STR_LIT>"<EOL>return self.__daemonic<EOL>

A boolean value indicating whether this thread is a daemon thread (True) or not (False).

        This must be set before start() is called, otherwise RuntimeError is
        raised. Its initial value is inherited from the creating thread; the
        main thread is not a daemon thread and therefore all threads created in
        the main thread default to daemon = False.

        The entire Python program exits when no alive non-daemon threads are
        left.


try:<EOL><INDENT>if self.__target:<EOL><INDENT>self.__target(*self.__args, **self.__kwargs)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>del self.__target, self.__args, self.__kwargs<EOL><DEDENT>

Method representing the thread's activity.

        You may override this method in a subclass. The standard run() method
        invokes the callable object passed to the object's constructor as the
        target argument, if any, with sequential and keyword arguments taken
        from the args and kwargs arguments, respectively.


return _Semaphore(*args, **kwargs)<EOL>

A factory function that returns a new semaphore.

    Semaphores manage a counter representing the number of release() calls minus
    the number of acquire() calls, plus an initial value. The acquire() method
    blocks if necessary until it can return without making the counter
    negative. If not given, value defaults to 1.


with self.__cond:<EOL><INDENT>self.__flag = True<EOL>self.__cond.notify_all()<EOL><DEDENT>

Set the internal flag to true.

        All threads waiting for the flag to become true are awakened. Threads
        that call wait() once the flag is true will not block at all.


return _Timer(*args, **kwargs)<EOL>

Factory function to create a Timer object.

    Timers call a function after a specified number of seconds:

        t = Timer(30.0, f, args=[], kwargs={})
        t.start()
        t.cancel()     # stop the timer's action if it's still waiting


with _active_limbo_lock:<EOL><INDENT>return list(_active.values()) + list(_limbo.values())<EOL><DEDENT>

Return a list of all Thread objects currently alive.

    The list includes daemonic threads, dummy thread objects created by
    current_thread(), and the main thread. It excludes terminated threads and
    threads that have not yet been started.


assert self.__initialized, "<STR_LIT>"<EOL>return self.__started.is_set() and not self.__stopped<EOL>

Return whether the thread is alive.

        This method returns True just before the run() method starts until just
        after the run() method terminates. The module function enumerate()
        returns a list of all alive threads.


with self.__cond:<EOL><INDENT>self.__flag = False<EOL><DEDENT>

Reset the internal flag to false.

        Subsequently, threads calling wait() will block until set() is called to
        set the internal flag to true again.


with self.__cond:<EOL><INDENT>if not self.__flag:<EOL><INDENT>self.__cond.wait(timeout)<EOL><DEDENT>return self.__flag<EOL><DEDENT>

Block until the internal flag is true.

        If the internal flag is true on entry, return immediately. Otherwise,
        block until another thread calls set() to set the flag to true, or until
        the optional timeout occurs.

        When the timeout argument is present and not None, it should be a
        floating point number specifying a timeout for the operation in seconds
        (or fractions thereof).

        This method returns the internal flag on exit, so it will always return
        True except if a timeout is given and the operation times out.


rc = False<EOL>with self.__cond:<EOL><INDENT>while self.__value == <NUM_LIT:0>:<EOL><INDENT>if not blocking:<EOL><INDENT>break<EOL><DEDENT>if __debug__:<EOL><INDENT>self._note("<STR_LIT>",<EOL>self, blocking, self.__value)<EOL><DEDENT>self.__cond.wait()<EOL><DEDENT>else:<EOL><INDENT>self.__value = self.__value - <NUM_LIT:1><EOL>if __debug__:<EOL><INDENT>self._note("<STR_LIT>",<EOL>self, self.__value)<EOL><DEDENT>rc = True<EOL><DEDENT><DEDENT>return rc<EOL>

Acquire a semaphore, decrementing the internal counter by one.

        When invoked without arguments: if the internal counter is larger than
        zero on entry, decrement it by one and return immediately. If it is zero
        on entry, block, waiting until some other thread has called release() to
        make it larger than zero. This is done with proper interlocking so that
        if multiple acquire() calls are blocked, release() will wake exactly one
        of them up. The implementation may pick one at random, so the order in
        which blocked threads are awakened should not be relied on. There is no
        return value in this case.

        When invoked with blocking set to true, do the same thing as when called
        without arguments, and return true.

        When invoked with blocking set to false, do not block. If a call without
        an argument would block, return false immediately; otherwise, do the
        same thing as when called without arguments, and return true.


return s.index(*args)<EOL>

index(s, sub [,start [,end]]) -> int

    Like find but raises ValueError when the substring is not found.


return s.ljust(width, *args)<EOL>

ljust(s, width[, fillchar]) -> string

    Return a left-justified version of s, in a field of the
    specified width, padded with spaces as needed.  The string is
    never truncated.  If specified the fillchar is used instead of spaces.


return s.count(*args)<EOL>

count(s, sub[, start[,end]]) -> int

    Return the number of occurrences of substring sub in string
    s[start:end].  Optional arguments start and end are
    interpreted as in slice notation.


return s.lower()<EOL>

lower(s) -> string

    Return a copy of the string s converted to lowercase.


return s.rstrip(chars)<EOL>

rstrip(s [,chars]) -> string

    Return a copy of the string s with trailing whitespace removed.
    If chars is given and not None, remove characters in chars instead.


return s.strip(chars)<EOL>

strip(s [,chars]) -> string

    Return a copy of the string s with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping.


return s.rfind(*args)<EOL>

rfind(s, sub [,start [,end]]) -> int

    Return the highest index in s where substring sub is found,
    such that sub is contained within s[start,end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.


return s.rjust(width, *args)<EOL>

rjust(s, width[, fillchar]) -> string

    Return a right-justified version of s, in a field of the
    specified width, padded with spaces as needed.  The string is
    never truncated.  If specified the fillchar is used instead of spaces.


return (sep or '<STR_LIT:U+0020>').join(x.capitalize() for x in s.split(sep))<EOL>

capwords(s [,sep]) -> string

    Split the argument into words using split, capitalize each
    word using capitalize, and join the capitalized words using
    join.  If the optional second argument sep is absent or None,
    runs of whitespace characters are replaced by a single space
    and leading and trailing whitespace are removed, otherwise
    sep is used to split and join the words.


def translate(s, table, deletions="<STR_LIT>"):

if deletions or table is None:<EOL><INDENT>return s.translate(table, deletions)<EOL><DEDENT>else:<EOL><INDENT>return s.translate(table + s[:<NUM_LIT:0>])<EOL><DEDENT>

translate(s,table [,deletions]) -> string

    Return a copy of the string s, where all characters occurring
    in the optional argument deletions are removed, and the
    remaining characters have been mapped through the given
    translation table, which must be a string of length 256.  The
    deletions argument is not allowed for Unicode strings.


return _long(s, base)<EOL>

atol(s [,base]) -> long

    Return the long integer represented by the string s in the
    given base, which defaults to 10.  The string s must consist
    of one or more digits, possibly preceded by a sign.  If base
    is 0, it is chosen from the leading characters of s, 0 for
    octal, 0x or 0X for hexadecimal.  If base is 16, a preceding
    0x or 0X is accepted.  A trailing L or l is not accepted,
    unless base is 0.


def replace(s, old, new, maxreplace=-<NUM_LIT:1>):

return s.replace(old, new, maxreplace)<EOL>

replace (str, old, new[, maxreplace]) -> string

    Return a copy of string str with all occurrences of substring
    old replaced by new. If the optional argument maxreplace is
    given, only the first maxreplace occurrences are replaced.