def draw_path_collection(self, master_transform, cliprect, clippath,<EOL>clippath_trans, paths, all_transforms, offsets,<EOL>offsetTrans, facecolors, edgecolors, linewidths,<EOL>linestyles, antialiaseds, urls):

path_ids = []<EOL>for path, transform in self._iter_collection_raw_paths(<EOL>master_transform, paths, all_transforms):<EOL><INDENT>path_ids.append((path, transform))<EOL><DEDENT>for xo, yo, path_id, gc, rgbFace in self._iter_collection(<EOL>path_ids, cliprect, clippath, clippath_trans,<EOL>offsets, offsetTrans, facecolors, edgecolors,<EOL>linewidths, linestyles, antialiaseds, urls):<EOL><INDENT>path, transform = path_id<EOL>transform = transforms.Affine2D(transform.get_matrix()).translate(xo, yo)<EOL>self.draw_path(gc, path, transform, rgbFace)<EOL><DEDENT>

Draws a collection of paths, selecting drawing properties from
the lists *facecolors*, *edgecolors*, *linewidths*,
*linestyles* and *antialiaseds*. *offsets* is a list of
offsets to apply to each of the paths.  The offsets in
*offsets* are first transformed by *offsetTrans* before
being applied.

This provides a fallback implementation of
:meth:`draw_path_collection` that makes multiple calls to
draw_path.  Some backends may want to override this in order
to render each set of path data only once, and then reference
that path multiple times with the different offsets, colors,
styles etc.  The generator methods
:meth:`_iter_collection_raw_paths` and
:meth:`_iter_collection` are provided to help with (and
standardize) the implementation across backends.  It is highly
recommended to use those generators, so that changes to the
behavior of :meth:`draw_path_collection` can be made globally.


str = "<STR_LIT>"<EOL>str += "<STR_LIT>"<EOL>warnings.warn(str,DeprecationWarning)<EOL>if timeout <= <NUM_LIT:0>: timeout = np.inf<EOL>timestep = <NUM_LIT><EOL>counter = <NUM_LIT:0><EOL>self._looping = True<EOL>while self._looping and counter*timestep < timeout:<EOL><INDENT>self.flush_events()<EOL>time.sleep(timestep)<EOL>counter += <NUM_LIT:1><EOL><DEDENT>

Start an event loop.  This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.  This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.

This function provides default event loop functionality based
on time.sleep that is meant to be used until event loop
functions for each of the GUI backends can be written.  As
such, it throws a deprecated warning.

Call signature::

    start_event_loop_default(self,timeout=0)

This call blocks until a callback function triggers
stop_event_loop() or *timeout* is reached.  If *timeout* is
<=0, never timeout.


return points<EOL>

Convert points to display units

*points*
    a float or a numpy array of float

return points converted to pixels

You need to override this function (unless your backend
doesn't have a dpi, eg, postscript or svg).  Some imaging
systems assume some value for pixels per inch::

    points to pixels = points * pixels_per_inch/72.0 * dpi/72.0


def draw_path(self, gc, path, transform, rgbFace=None):

raise NotImplementedError<EOL>

Draws a :class:`~matplotlib.path.Path` instance using the
given affine transform.


if self._texmanager is None:<EOL><INDENT>from matplotlib.texmanager import TexManager<EOL>self._texmanager = TexManager()<EOL><DEDENT>return self._texmanager<EOL>

return the :class:`matplotlib.texmanager.TexManager` instance


return self._capstyle<EOL>

Return the capstyle as a string in ('butt', 'round', 'projecting')


pass<EOL>

Draw a cursor in the event.axes if inaxes is not None.  Use
native GUI drawing for efficiency if possible


if <NUM_LIT:0> <= byte <= <NUM_LIT>: self._set_char(byte)<EOL>elif byte == <NUM_LIT>: self._set_char(self._arg(<NUM_LIT:1>))<EOL>elif byte == <NUM_LIT>: self._set_char(self._arg(<NUM_LIT:2>))<EOL>elif byte == <NUM_LIT>: self._set_char(self._arg(<NUM_LIT:3>))<EOL>elif byte == <NUM_LIT>: self._set_char(self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._set_rule(self._arg(<NUM_LIT:4>, True), self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._put_char(self._arg(<NUM_LIT:1>))<EOL>elif byte == <NUM_LIT>: self._put_char(self._arg(<NUM_LIT:2>))<EOL>elif byte == <NUM_LIT>: self._put_char(self._arg(<NUM_LIT:3>))<EOL>elif byte == <NUM_LIT>: self._put_char(self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._put_rule(self._arg(<NUM_LIT:4>, True), self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._nop()<EOL>elif byte == <NUM_LIT>: self._bop(*[self._arg(<NUM_LIT:4>, True) for i in range(<NUM_LIT:11>)])<EOL>elif byte == <NUM_LIT>: self._eop()<EOL>elif byte == <NUM_LIT>: self._push()<EOL>elif byte == <NUM_LIT>: self._pop()<EOL>elif byte == <NUM_LIT>: self._right(self._arg(<NUM_LIT:1>, True))<EOL>elif byte == <NUM_LIT>: self._right(self._arg(<NUM_LIT:2>, True))<EOL>elif byte == <NUM_LIT>: self._right(self._arg(<NUM_LIT:3>, True))<EOL>elif byte == <NUM_LIT>: self._right(self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._right_w(None)<EOL>elif byte == <NUM_LIT>: self._right_w(self._arg(<NUM_LIT:1>, True))<EOL>elif byte == <NUM_LIT>: self._right_w(self._arg(<NUM_LIT:2>, True))<EOL>elif byte == <NUM_LIT>: self._right_w(self._arg(<NUM_LIT:3>, True))<EOL>elif byte == <NUM_LIT>: self._right_w(self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._right_x(None)<EOL>elif byte == <NUM_LIT>: self._right_x(self._arg(<NUM_LIT:1>, True))<EOL>elif byte == <NUM_LIT>: self._right_x(self._arg(<NUM_LIT:2>, True))<EOL>elif byte == <NUM_LIT>: self._right_x(self._arg(<NUM_LIT:3>, True))<EOL>elif byte == <NUM_LIT>: self._right_x(self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._down(self._arg(<NUM_LIT:1>, True))<EOL>elif byte == <NUM_LIT>: self._down(self._arg(<NUM_LIT:2>, True))<EOL>elif byte == <NUM_LIT>: self._down(self._arg(<NUM_LIT:3>, True))<EOL>elif byte == <NUM_LIT>: self._down(self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._down_y(None)<EOL>elif byte == <NUM_LIT>: self._down_y(self._arg(<NUM_LIT:1>, True))<EOL>elif byte == <NUM_LIT>: self._down_y(self._arg(<NUM_LIT:2>, True))<EOL>elif byte == <NUM_LIT>: self._down_y(self._arg(<NUM_LIT:3>, True))<EOL>elif byte == <NUM_LIT>: self._down_y(self._arg(<NUM_LIT:4>, True))<EOL>elif byte == <NUM_LIT>: self._down_z(None)<EOL>elif byte == <NUM_LIT>: self._down_z(self._arg(<NUM_LIT:1>, True))<EOL>elif byte == <NUM_LIT>: self._down_z(self._arg(<NUM_LIT:2>, True))<EOL>elif byte == <NUM_LIT>: self._down_z(self._arg(<NUM_LIT:3>, True))<EOL>elif byte == <NUM_LIT>: self._down_z(self._arg(<NUM_LIT:4>, True))<EOL>elif <NUM_LIT> <= byte <= <NUM_LIT>: self._fnt_num(byte-<NUM_LIT>)<EOL>elif byte == <NUM_LIT>: self._fnt_num(self._arg(<NUM_LIT:1>))<EOL>elif byte == <NUM_LIT>: self._fnt_num(self._arg(<NUM_LIT:2>))<EOL>elif byte == <NUM_LIT>: self._fnt_num(self._arg(<NUM_LIT:3>))<EOL>elif byte == <NUM_LIT>: self._fnt_num(self._arg(<NUM_LIT:4>, True))<EOL>elif <NUM_LIT> <= byte <= <NUM_LIT>:<EOL><INDENT>len = self._arg(byte-<NUM_LIT>)<EOL>special = self.file.read(len)<EOL>self._xxx(special)<EOL><DEDENT>elif <NUM_LIT> <= byte <= <NUM_LIT>:<EOL><INDENT>k = self._arg(byte-<NUM_LIT>, byte==<NUM_LIT>)<EOL>c, s, d, a, l = [ self._arg(x) for x in (<NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:1>, <NUM_LIT:1>) ]<EOL>n = self.file.read(a+l)<EOL>self._fnt_def(k, c, s, d, a, l, n)<EOL><DEDENT>elif byte == <NUM_LIT>:<EOL><INDENT>i, num, den, mag, k = [ self._arg(x) for x in (<NUM_LIT:1>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:4>, <NUM_LIT:1>) ]<EOL>x = self.file.read(k)<EOL>self._pre(i, num, den, mag, x)<EOL><DEDENT>elif byte == <NUM_LIT>: self._post()<EOL>elif byte == <NUM_LIT>: self._post_post()<EOL>else:<EOL><INDENT>raise ValueError("<STR_LIT>"%byte)<EOL><DEDENT>

Based on the opcode "byte", read the correct kinds of
arguments from the dvi file and call the method implementing
that opcode with those arguments.


mapping = self._mapping<EOL>for key, val in list(mapping.items()):<EOL><INDENT>if key() is None:<EOL><INDENT>del mapping[key]<EOL>val.remove(key)<EOL><DEDENT><DEDENT>

Clean dead weak references from the dictionary


if not len(seq): return False<EOL>for val in seq:<EOL><INDENT>if val: return True<EOL><DEDENT>return False<EOL>

Return *True* if one element of *seq* is *True*.  It *seq* is
empty, return *False*.


sLen = <NUM_LIT:0><EOL>for (word, ind) in zip(seq, list(range(len(seq)))):<EOL><INDENT>sLen += len(word) + <NUM_LIT:1>  <EOL>if sLen>=N: return ind<EOL><DEDENT>return len(seq)<EOL>

*seq* is a list of words.  Return the index into seq such that::

    len(' '.join(seq[:ind])<=N


def listFiles(root, patterns='<STR_LIT:*>', recurse=<NUM_LIT:1>, return_folders=<NUM_LIT:0>):

import os.path, fnmatch<EOL>pattern_list = patterns.split('<STR_LIT:;>')<EOL>class Bunch:<EOL><INDENT>def __init__(self, **kwds): self.__dict__.update(kwds)<EOL><DEDENT>arg = Bunch(recurse=recurse, pattern_list=pattern_list,<EOL>return_folders=return_folders, results=[])<EOL>def visit(arg, dirname, files):<EOL><INDENT>for name in files:<EOL><INDENT>fullname = os.path.normpath(os.path.join(dirname, name))<EOL>if arg.return_folders or os.path.isfile(fullname):<EOL><INDENT>for pattern in arg.pattern_list:<EOL><INDENT>if fnmatch.fnmatch(name, pattern):<EOL><INDENT>arg.results.append(fullname)<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if not arg.recurse: files[:]=[]<EOL><DEDENT>os.path.walk(root, visit, arg)<EOL>return arg.results<EOL>

Recursively list files

from Parmar and Martelli in the Python Cookbook


def unmasked_index_ranges(mask, compressed = True):

mask = mask.reshape(mask.size)<EOL>m = np.concatenate(((<NUM_LIT:1>,), mask, (<NUM_LIT:1>,)))<EOL>indices = np.arange(len(mask) + <NUM_LIT:1>)<EOL>mdif = m[<NUM_LIT:1>:] - m[:-<NUM_LIT:1>]<EOL>i0 = np.compress(mdif == -<NUM_LIT:1>, indices)<EOL>i1 = np.compress(mdif == <NUM_LIT:1>, indices)<EOL>assert len(i0) == len(i1)<EOL>if len(i1) == <NUM_LIT:0>:<EOL><INDENT>return None  <EOL><DEDENT>if not compressed:<EOL><INDENT>return np.concatenate((i0[:, np.newaxis], i1[:, np.newaxis]), axis=<NUM_LIT:1>)<EOL><DEDENT>seglengths = i1 - i0<EOL>breakpoints = np.cumsum(seglengths)<EOL>ic0 = np.concatenate(((<NUM_LIT:0>,), breakpoints[:-<NUM_LIT:1>]))<EOL>ic1 = breakpoints<EOL>return np.concatenate((ic0[:, np.newaxis], ic1[:, np.newaxis]), axis=<NUM_LIT:1>)<EOL>

Find index ranges where *mask* is *False*.

*mask* will be flattened if it is not already 1-D.

Returns Nx2 :class:`numpy.ndarray` with each row the start and stop
indices for slices of the compressed :class:`numpy.ndarray`
corresponding to each of *N* uninterrupted runs of unmasked
values.  If optional argument *compressed* is *False*, it returns
the start and stop indices into the original :class:`numpy.ndarray`,
not the compressed :class:`numpy.ndarray`.  Returns *None* if there
are no unmasked values.

Example::

  y = ma.array(np.arange(5), mask = [0,0,1,0,0])
  ii = unmasked_index_ranges(ma.getmaskarray(y))
  # returns array [[0,2,] [2,4,]]

  y.compressed()[ii[1,0]:ii[1,1]]
  # returns array [3,4,]

  ii = unmasked_index_ranges(ma.getmaskarray(y), compressed=False)
  # returns array [[0, 2], [3, 5]]

  y.filled()[ii[1,0]:ii[1,1]]
  # returns array [3,4,]

Prior to the transforms refactoring, this was used to support
masked arrays in Line2D.


self._pos = -<NUM_LIT:1><EOL>self._elements = []<EOL>


start = <NUM_LIT:0><EOL>while <NUM_LIT:1>:<EOL><INDENT>item = seq[start:start+num]<EOL>if not len(item): break<EOL>yield item<EOL>start += num<EOL><DEDENT>


def print_cycles(objects, outstream=sys.stdout, show_progress=False):

import gc<EOL>from types import FrameType<EOL>def print_path(path):<EOL><INDENT>for i, step in enumerate(path):<EOL><INDENT>next = path[(i + <NUM_LIT:1>) % len(path)]<EOL>outstream.write("<STR_LIT>" % str(type(step)))<EOL>if isinstance(step, dict):<EOL><INDENT>for key, val in list(step.items()):<EOL><INDENT>if val is next:<EOL><INDENT>outstream.write("<STR_LIT>" % repr(key))<EOL>break<EOL><DEDENT>if key is next:<EOL><INDENT>outstream.write("<STR_LIT>" % repr(val))<EOL>break<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(step, list):<EOL><INDENT>outstream.write("<STR_LIT>" % step.index(next))<EOL><DEDENT>elif isinstance(step, tuple):<EOL><INDENT>outstream.write("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>outstream.write(repr(step))<EOL><DEDENT>outstream.write("<STR_LIT>")<EOL><DEDENT>outstream.write("<STR_LIT:\n>")<EOL><DEDENT>def recurse(obj, start, all, current_path):<EOL><INDENT>if show_progress:<EOL><INDENT>outstream.write("<STR_LIT>" % len(all))<EOL><DEDENT>all[id(obj)] = None<EOL>referents = gc.get_referents(obj)<EOL>for referent in referents:<EOL><INDENT>if referent is start:<EOL><INDENT>print_path(current_path)<EOL><DEDENT>elif referent is objects or isinstance(referent, FrameType):<EOL><INDENT>continue<EOL><DEDENT>elif id(referent) not in all:<EOL><INDENT>recurse(referent, start, all, current_path + [obj])<EOL><DEDENT><DEDENT><DEDENT>for obj in objects:<EOL><INDENT>outstream.write("<STR_LIT>" % (obj,))<EOL>recurse(obj, obj, { }, [])<EOL><DEDENT>

*objects*
    A list of objects to find cycles in.  It is often useful to
    pass in gc.garbage to find the cycles that are preventing some
    objects from being garbage collected.

*outstream*
    The stream for output.

*show_progress*
    If True, print the number of objects reached as they are found.


return re.compile("<STR_LIT:|>".join(map(re.escape, list(self.keys()))))<EOL>

Build re object based on the keys of the current dictionary


return self.data<EOL>

Return a list of elements from the oldest to the newest.


self._elements = self._elements[:self._pos+<NUM_LIT:1>]<EOL>self._elements.append(o)<EOL>self._pos = len(self._elements)-<NUM_LIT:1><EOL>return self()<EOL>

push object onto stack at current position - all elements
occurring later than the current position are discarded


files = []<EOL>for arg in args:<EOL><INDENT>if os.path.isfile(arg):<EOL><INDENT>files.append(arg)<EOL>continue<EOL><DEDENT>if os.path.isdir(arg):<EOL><INDENT>newfiles = listFiles(arg, recurse=<NUM_LIT:1>, return_folders=<NUM_LIT:1>)<EOL>files.extend(newfiles)<EOL><DEDENT><DEDENT>return [f for f in files if not os.path.islink(f)]<EOL>

Recurs all the files and dirs in *args* ignoring symbolic links
and return the files as a list of strings


pid = os.getpid()<EOL>if sys.platform=='<STR_LIT>':<EOL><INDENT>a2 = os.popen('<STR_LIT>' % pid).readlines()<EOL>mem = int(a2[-<NUM_LIT:1>].strip())<EOL><DEDENT>elif sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>a2 = os.popen('<STR_LIT>' % pid).readlines()<EOL>mem = int(a2[<NUM_LIT:1>].split()[<NUM_LIT:1>])<EOL><DEDENT>elif sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>a2 = os.popen('<STR_LIT>' % pid).readlines()<EOL>mem = int(a2[<NUM_LIT:1>].split()[<NUM_LIT:0>])<EOL><DEDENT>return mem<EOL>


if not iterable(obj): return False<EOL>if is_string_like(obj): return False<EOL>for o in obj:<EOL><INDENT>if not is_string_like(o): return False<EOL><DEDENT>return True<EOL>

Returns true if *obj* is iterable and contains strings


self.clean()<EOL>mapping = self._mapping<EOL>try:<EOL><INDENT>return mapping[ref(a)] is mapping[ref(b)]<EOL><DEDENT>except KeyError:<EOL><INDENT>return False<EOL><DEDENT>

Returns True if *a* and *b* are members of the same set.


try: obj+<NUM_LIT:1><EOL>except TypeError: return False<EOL>else: return True<EOL>

return true if *obj* looks like a number


if o not in self._elements:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>old = self._elements[:]<EOL>self.clear()<EOL>bubbles = []<EOL>for thiso in old:<EOL><INDENT>if thiso==o: bubbles.append(thiso)<EOL>else: self.push(thiso)<EOL><DEDENT>for thiso in bubbles:<EOL><INDENT>self.push(o)<EOL><DEDENT>return o<EOL>

raise *o* to the top of the stack and return *o*.  *o* must be
in the stack


self.signals = set(signals)<EOL>self.callbacks = dict([(s, dict()) for s in signals])<EOL>self._cid = <NUM_LIT:0><EOL>

*signals* is a sequence of valid signals


def to_filehandle(fname, flag='<STR_LIT:r>', return_opened=False):

if is_string_like(fname):<EOL><INDENT>if fname.endswith('<STR_LIT>'):<EOL><INDENT>import gzip<EOL>fh = gzip.open(fname, flag)<EOL><DEDENT>else:<EOL><INDENT>fh = file(fname, flag)<EOL><DEDENT>opened = True<EOL><DEDENT>elif hasattr(fname, '<STR_LIT>'):<EOL><INDENT>fh = fname<EOL>opened = False<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if return_opened:<EOL><INDENT>return fh, opened<EOL><DEDENT>return fh<EOL>

*fname* can be a filename or a file handle.  Support for gzipped
files is automatic, if the filename ends in .gz.  *flag* is a
read/write flag for :func:`file`


if not len(args):<EOL><INDENT>return ()<EOL><DEDENT>if (is_string_like(args[<NUM_LIT:0>]) or not iterable(args[<NUM_LIT:0>])):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>nrecs = len(args[<NUM_LIT:0>])<EOL>margs = []<EOL>seqlist = [False] * len(args)<EOL>for i, x in enumerate(args):<EOL><INDENT>if (not is_string_like(x)) and iterable(x) and len(x) == nrecs:<EOL><INDENT>seqlist[i] = True<EOL>if ma.isMA(x):<EOL><INDENT>if x.ndim > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>x = np.asarray(x)<EOL><DEDENT><DEDENT>margs.append(x)<EOL><DEDENT>masks = []    <EOL>for i, x in enumerate(margs):<EOL><INDENT>if seqlist[i]:<EOL><INDENT>if x.ndim > <NUM_LIT:1>:<EOL><INDENT>continue  <EOL><DEDENT>if ma.isMA(x):<EOL><INDENT>masks.append(~ma.getmaskarray(x))  <EOL>xd = x.data<EOL><DEDENT>else:<EOL><INDENT>xd = x<EOL><DEDENT>try:<EOL><INDENT>mask = np.isfinite(xd)<EOL>if isinstance(mask, np.ndarray):<EOL><INDENT>masks.append(mask)<EOL><DEDENT><DEDENT>except: <EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>if len(masks):<EOL><INDENT>mask = reduce(np.logical_and, masks)<EOL>igood = mask.nonzero()[<NUM_LIT:0>]<EOL>if len(igood) < nrecs:<EOL><INDENT>for i, x in enumerate(margs):<EOL><INDENT>if seqlist[i]:<EOL><INDENT>margs[i] = x.take(igood, axis=<NUM_LIT:0>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>for i, x in enumerate(margs):<EOL><INDENT>if seqlist[i] and ma.isMA(x):<EOL><INDENT>margs[i] = x.filled()<EOL><DEDENT><DEDENT>return margs<EOL>

Find all masked and/or non-finite points in a set of arguments,
and return the arguments with only the unmasked points remaining.

Arguments can be in any of 5 categories:

1) 1-D masked arrays
2) 1-D ndarrays
3) ndarrays with more than one dimension
4) other non-string iterables
5) anything else

The first argument must be in one of the first four categories;
any argument with a length differing from that of the first
argument (and hence anything in category 5) then will be
passed through unchanged.

Masks are obtained from all arguments of the correct length
in categories 1, 2, and 4; a point is bad if masked in a masked
array or if it is a nan or inf.  No attempt is made to
extract a mask from categories 2, 3, and 4 if :meth:`np.isfinite`
does not yield a Boolean array.

All input arguments that are not passed unchanged are returned
as ndarrays after removing the points or rows corresponding to
masks in any of the arguments.

A vastly simpler version of this function was originally
written as a helper for Axes.scatter().


for item in seq:<EOL><INDENT>if scalarp(item): yield item<EOL>else:<EOL><INDENT>for subitem in flatten(item, scalarp):<EOL><INDENT>yield subitem<EOL><DEDENT><DEDENT><DEDENT>

this generator flattens nested containers such as

>>> l=( ('John', 'Hunter'), (1,23), [[[[42,(5,23)]]]])

so that

>>> for i in flatten(l): print i,
John Hunter 1 23 42 5 23

By: Composite of Holger Krekel and Luther Blissett
From: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/121294
and Recipe 1.12 in cookbook


return list(dict([ (val, <NUM_LIT:1>) for val in x]).keys())<EOL>


N = len(self._elements)<EOL>if self._pos<N-<NUM_LIT:1>: self._pos += <NUM_LIT:1><EOL>return self()<EOL>

move the position forward and return the current element


for i in range(len(seq)): seq.pop()<EOL>


return self[match.group(<NUM_LIT:0>)]<EOL>


if not len(seq): return False<EOL>for val in seq:<EOL><INDENT>if not val: return False<EOL><DEDENT>return True<EOL>

Return *True* if all elements of *seq* evaluate to *True*.  If
*seq* is empty, return *False*.


def quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y):

<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.quad2cubic(q0x, q0y, q1x, q1y, q2x, q2y)<EOL>

This function has been moved to matplotlib.mlab -- please import
it from there


<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.is_closed_polygon(X)<EOL>


<EOL>soundex_digits = '<STR_LIT>'<EOL>sndx = '<STR_LIT>'<EOL>fc = '<STR_LIT>'<EOL>for c in name.upper():<EOL><INDENT>if c.isalpha():<EOL><INDENT>if not fc: fc = c   <EOL>d = soundex_digits[ord(c)-ord('<STR_LIT:A>')]<EOL>if not sndx or (d != sndx[-<NUM_LIT:1>]):<EOL><INDENT>sndx += d<EOL><DEDENT><DEDENT><DEDENT>sndx = fc + sndx[<NUM_LIT:1>:]<EOL>sndx = sndx.replace('<STR_LIT:0>', '<STR_LIT>')<EOL>return (sndx + (len * '<STR_LIT:0>'))[:len]<EOL>

soundex module conforming to Odell-Russell algorithm


def vector_lengths( X, P=<NUM_LIT>, axis=None ):

<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.vector_lengths( X, P=<NUM_LIT>, axis=axis )<EOL>


self.clean()<EOL>siblings = self._mapping.get(ref(a), [ref(a)])<EOL>return [x() for x in siblings]<EOL>

Returns all of the items joined with *a*, including itself.


def less_simple_linear_interpolation( x, y, xi, extrap=False ):

<EOL>warnings.warn('<STR_LIT>', DeprecationWarning)<EOL>import matplotlib.mlab as mlab<EOL>return mlab.less_simple_linear_interpolation( x, y, xi, extrap=extrap )<EOL>


if isinstance(obj, str): return True<EOL>if ma.isMaskedArray(obj):<EOL><INDENT>if obj.ndim == <NUM_LIT:0> and obj.dtype.kind in '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>try: obj + '<STR_LIT>'<EOL>except (TypeError, ValueError): return False<EOL>return True<EOL>

Return True if *obj* looks like a string


try: len(obj)<EOL>except: return False<EOL>return True<EOL>


def get_window_extent(self, *args, **kwargs):

return self.bbox<EOL>

get the figure bounding box in display space; kwargs are void


def set_size_inches(self, *args, **kwargs):

forward = kwargs.get('<STR_LIT>', False)<EOL>if len(args)==<NUM_LIT:1>:<EOL><INDENT>w,h = args[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>w,h = args<EOL><DEDENT>dpival = self.dpi<EOL>self.bbox_inches.p1 = w, h<EOL>if forward:<EOL><INDENT>dpival = self.dpi<EOL>canvasw = w*dpival<EOL>canvash = h*dpival<EOL>manager = getattr(self.canvas, '<STR_LIT>', None)<EOL>if manager is not None:<EOL><INDENT>manager.resize(int(canvasw), int(canvash))<EOL><DEDENT><DEDENT>

set_size_inches(w,h, forward=False)

Set the figure size in inches

Usage::

     fig.set_size_inches(w,h)  # OR
     fig.set_size_inches((w,h) )

optional kwarg *forward=True* will cause the canvas size to be
automatically updated; eg you can resize the figure window
from the shell

WARNING: forward=True is broken on all backends except GTK*
and WX*

ACCEPTS: a w,h tuple with w,h in inches


self.clf()<EOL>


def fixitems(items):<EOL><INDENT>ret = []<EOL>for k, v in items:<EOL><INDENT>if iterable(v): v = tuple(v)<EOL>ret.append((k,v))<EOL><DEDENT>return tuple(ret)<EOL><DEDENT>def fixlist(args):<EOL><INDENT>ret = []<EOL>for a in args:<EOL><INDENT>if iterable(a): a = tuple(a)<EOL>ret.append(a)<EOL><DEDENT>return tuple(ret)<EOL><DEDENT>key = fixlist(args), fixitems(kwargs.items())<EOL>return key<EOL>

make a hashable key out of args and kwargs


def __init__(self, left=None, bottom=None, right=None, top=None,<EOL>wspace=None, hspace=None):

self.validate = True<EOL>self.update(left, bottom, right, top, wspace, hspace)<EOL>

All dimensions are fraction of the figure width or height.
All values default to their rc params

The following attributes are available

*left*  = 0.125
    the left side of the subplots of the figure
*right* = 0.9
    the right side of the subplots of the figure
*bottom* = 0.1
    the bottom of the subplots of the figure
*top* = 0.9
    the top of the subplots of the figure
*wspace* = 0.2
    the amount of width reserved for blank space between subplots
*hspace* = 0.2
    the amount of height reserved for white space between subplots
*validate*
    make sure the params are in a legal state (*left*<*right*, etc)


Set the face color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)


return self.dpi<EOL>


self.suppressComposite = None<EOL>self.callbacks = cbook.CallbackRegistry(('<STR_LIT>', ))<EOL>for ax in tuple(self.axes):  <EOL><INDENT>ax.cla()<EOL>self.delaxes(ax)         <EOL><DEDENT>toolbar = getattr(self.canvas, '<STR_LIT>', None)<EOL>if toolbar is not None:<EOL><INDENT>toolbar.update()<EOL><DEDENT>self._axstack.clear()<EOL>self._seen = {}<EOL>self.artists = []<EOL>self.lines = []<EOL>self.patches = []<EOL>self.texts=[]<EOL>self.images = []<EOL>self.legends = []<EOL>self._axobservers = []<EOL>


ax = self._axstack()<EOL>if ax is not None:<EOL><INDENT>ispolar = kwargs.get('<STR_LIT>', False)<EOL>projection = kwargs.get('<STR_LIT>', None)<EOL>if ispolar:<EOL><INDENT>if projection is not None and projection != '<STR_LIT>':<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>" %<EOL>projection)<EOL><DEDENT>projection = '<STR_LIT>'<EOL><DEDENT>projection_class = get_projection_class(projection)<EOL>if isinstance(ax, projection_class):<EOL><INDENT>return ax<EOL><DEDENT><DEDENT>return self.add_subplot(<NUM_LIT>, **kwargs)<EOL>

Return the current axes, creating one if necessary

The following kwargs are supported
%(Axes)s


self.canvas = canvas<EOL>

Set the canvas the contains the figure

ACCEPTS: a FigureCanvas instance


Set the edge color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)


x = kwargs.pop('<STR_LIT:x>', <NUM_LIT:0.5>)<EOL>y = kwargs.pop('<STR_LIT:y>', <NUM_LIT>)<EOL>if ('<STR_LIT>' not in kwargs) and ('<STR_LIT>' not in kwargs):<EOL><INDENT>kwargs['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if ('<STR_LIT>' not in kwargs) and ('<STR_LIT>' not in kwargs):<EOL><INDENT>kwargs['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>t = self.text(x, y, t, **kwargs)<EOL>return t<EOL>

Add a centered title to the figure.

kwargs are :class:`matplotlib.text.Text` properties.  Using figure
coordinates, the defaults are:

  - *x* = 0.5
      the x location of text in figure coords

  - *y* = 0.98
      the y location of the text in figure coords

  - *horizontalalignment* = 'center'
      the horizontal alignment of the text

  - *verticalalignment* = 'top'
      the vertical alignment of the text

A :class:`matplotlib.text.Text` instance is returned.

Example::

  fig.subtitle('this is the figure title', fontsize=12)


blocking_input = BlockingKeyMouseInput(self)<EOL>return blocking_input(timeout=timeout)<EOL>

call signature::

  waitforbuttonpress(self, timeout=-1)

Blocking call to interact with the figure.

This will return True is a key was pressed, False if a mouse
button was pressed and None if *timeout* was reached without
either being pressed.

If *timeout* is negative, does not timeout.


for key in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>if key not in kwargs:<EOL><INDENT>kwargs[key] = rcParams['<STR_LIT>'%key]<EOL><DEDENT><DEDENT>transparent = kwargs.pop('<STR_LIT>', False)<EOL>if transparent:<EOL><INDENT>original_figure_alpha = self.patch.get_alpha()<EOL>self.patch.set_alpha(<NUM_LIT:0.0>)<EOL>original_axes_alpha = []<EOL>for ax in self.axes:<EOL><INDENT>patch = ax.patch<EOL>original_axes_alpha.append(patch.get_alpha())<EOL>patch.set_alpha(<NUM_LIT:0.0>)<EOL><DEDENT><DEDENT>self.canvas.print_figure(*args, **kwargs)<EOL>if transparent:<EOL><INDENT>self.patch.set_alpha(original_figure_alpha)<EOL>for ax, alpha in zip(self.axes, original_axes_alpha):<EOL><INDENT>ax.patch.set_alpha(alpha)<EOL><DEDENT><DEDENT>

call signature::

  savefig(fname, dpi=None, facecolor='w', edgecolor='w',
          orientation='portrait', papertype=None, format=None,
          transparent=False):

Save the current figure.

The output formats available depend on the backend being used.

Arguments:

  *fname*:
    A string containing a path to a filename, or a Python file-like object.

    If *format* is *None* and *fname* is a string, the output
    format is deduced from the extension of the filename.

Keyword arguments:

  *dpi*: [ None | scalar > 0 ]
    The resolution in dots per inch.  If *None* it will default to
    the value ``savefig.dpi`` in the matplotlibrc file.

  *facecolor*, *edgecolor*:
    the colors of the figure rectangle

  *orientation*: [ 'landscape' | 'portrait' ]
    not supported on all backends; currently only on postscript output

  *papertype*:
    One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
    'a10', 'b0' through 'b10'. Only supported for postscript
    output.

  *format*:
    One of the file extensions supported by the active
    backend.  Most backends support png, pdf, ps, eps and svg.

  *transparent*:
    If *True*, the figure patch and axes patches will all be
    transparent.  This is useful, for example, for displaying
    a plot on top of a colored background on a web page.  The
    transparency of these patches will be restored to their
    original values upon exit of this function.


if not self._hold: self.clf()<EOL>im = FigureImage(self, cmap, norm, xo, yo, origin)<EOL>im.set_array(X)<EOL>im.set_alpha(alpha)<EOL>if norm is None:<EOL><INDENT>im.set_clim(vmin, vmax)<EOL><DEDENT>self.images.append(im)<EOL>return im<EOL>

call signatures::

  figimage(X, **kwargs)

adds a non-resampled array *X* to the figure.

::

  figimage(X, xo, yo)

with pixel offsets *xo*, *yo*,

*X* must be a float array:

* If *X* is MxN, assume luminance (grayscale)
* If *X* is MxNx3, assume RGB
* If *X* is MxNx4, assume RGBA

Optional keyword arguments:

  =========   ==========================================================
  Keyword     Description
  =========   ==========================================================
  xo or yo    An integer, the *x* and *y* image offset in pixels
  cmap        a :class:`matplotlib.cm.ColorMap` instance, eg cm.jet.
              If None, default to the rc ``image.cmap`` value
  norm        a :class:`matplotlib.colors.Normalize` instance. The
              default is normalization().  This scales luminance -> 0-1
  vmin|vmax   are used to scale a luminance image to 0-1.  If either is
              None, the min and max of the luminance values will be
              used.  Note if you pass a norm instance, the settings for
              *vmin* and *vmax* will be ignored.
  alpha       the alpha blending value, default is 1.0
  origin      [ 'upper' | 'lower' ] Indicates where the [0,0] index of
              the array is in the upper left or lower left corner of
              the axes. Defaults to the rc image.origin value
  =========   ==========================================================

figimage complements the axes image
(:meth:`~matplotlib.axes.Axes.imshow`) which will be resampled
to fit the current axes.  If you want a resampled image to
fill the entire figure, you can define an
:class:`~matplotlib.axes.Axes` with size [0,1,0,1].

An :class:`matplotlib.image.FigureImage` instance is returned.

.. plot:: mpl_examples/pylab_examples/figimage_demo.py


if b is None: self._hold = not self._hold<EOL>else: self._hold = b<EOL>

Set the hold state.  If hold is None (default), toggle the
hold state.  Else set the hold state to boolean value b.

Eg::

    hold()      # toggle hold
    hold(True)  # hold is on
    hold(False) # hold is off


return self.frameon<EOL>


def autofmt_xdate(self, bottom=<NUM_LIT>, rotation=<NUM_LIT:30>, ha='<STR_LIT:right>'):

allsubplots = np.alltrue([hasattr(ax, '<STR_LIT>') for ax in self.axes])<EOL>if len(self.axes)==<NUM_LIT:1>:<EOL><INDENT>for label in ax.get_xticklabels():<EOL><INDENT>label.set_ha(ha)<EOL>label.set_rotation(rotation)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if allsubplots:<EOL><INDENT>for ax in self.get_axes():<EOL><INDENT>if ax.is_last_row():<EOL><INDENT>for label in ax.get_xticklabels():<EOL><INDENT>label.set_ha(ha)<EOL>label.set_rotation(rotation)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for label in ax.get_xticklabels():<EOL><INDENT>label.set_visible(False)<EOL><DEDENT>ax.set_xlabel('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if allsubplots:<EOL><INDENT>self.subplots_adjust(bottom=bottom)<EOL><DEDENT>

Date ticklabels often overlap, so it is useful to rotate them
and right align them.  Also, a common use case is a number of
subplots with shared xaxes where the x-axis is date data.  The
ticklabels are often long, and it helps to rotate them on the
bottom subplot and turn them off on other subplots, as well as
turn off xlabels.

*bottom*
    the bottom of the subplots for :meth:`subplots_adjust`
*rotation*
    the rotation of the xtick labels
*ha*
    the horizontal alignment of the xticklabels


key = self._make_key(*args, **kwargs)<EOL>if key in self._seen:<EOL><INDENT>ax = self._seen[key]<EOL>self.sca(ax)<EOL>return ax<EOL><DEDENT>if not len(args): return<EOL>if isinstance(args[<NUM_LIT:0>], Axes):<EOL><INDENT>a = args[<NUM_LIT:0>]<EOL>assert(a.get_figure() is self)<EOL><DEDENT>else:<EOL><INDENT>rect = args[<NUM_LIT:0>]<EOL>ispolar = kwargs.pop('<STR_LIT>', False)<EOL>projection = kwargs.pop('<STR_LIT>', None)<EOL>if ispolar:<EOL><INDENT>if projection is not None and projection != '<STR_LIT>':<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>" %<EOL>projection)<EOL><DEDENT>projection = '<STR_LIT>'<EOL><DEDENT>a = projection_factory(projection, self, rect, **kwargs)<EOL><DEDENT>self.axes.append(a)<EOL>self._axstack.push(a)<EOL>self.sca(a)<EOL>self._seen[key] = a<EOL>return a<EOL>

Add an a axes with axes rect [*left*, *bottom*, *width*,
*height*] where all quantities are in fractions of figure
width and height.  kwargs are legal
:class:`~matplotlib.axes.Axes` kwargs plus *projection* which
sets the projection type of the axes.  (For backward
compatibility, ``polar=True`` may also be provided, which is
equivalent to ``projection='polar'``).  Valid values for
*projection* are: %(list)s.  Some of these projections support
additional kwargs, which may be provided to :meth:`add_axes`::

    rect = l,b,w,h
    fig.add_axes(rect)
    fig.add_axes(rect, frameon=False, axisbg='g')
    fig.add_axes(rect, polar=True)
    fig.add_axes(rect, projection='polar')
    fig.add_axes(ax)   # add an Axes instance

If the figure already has an axes with the same parameters,
then it will simply make that axes current and return it.  If
you do not want this behavior, eg. you want to force the
creation of a new axes, you must use a unique set of args and
kwargs.  The axes :attr:`~matplotlib.axes.Axes.label`
attribute has been exposed for this purpose.  Eg., if you want
two axes that are otherwise identical to be added to the
figure, make sure you give them unique labels::

    fig.add_axes(rect, label='axes1')
    fig.add_axes(rect, label='axes2')

The :class:`~matplotlib.axes.Axes` instance will be returned.

The following kwargs are supported:

%(Axes)s


whenever the axes state change, func(self) will be called


def embedTTF(self, filename, characters):

font = FT2Font(str(filename))<EOL>fonttype = rcParams['<STR_LIT>']<EOL>def cvt(length, upe=font.units_per_EM, nearest=True):<EOL><INDENT>"<STR_LIT>"<EOL>value = length / upe * <NUM_LIT:1000><EOL>if nearest: return round(value)<EOL>if value < <NUM_LIT:0>: return floor(value)<EOL>else: return ceil(value)<EOL><DEDENT>def embedTTFType3(font, characters, descriptor):<EOL><INDENT>"""<STR_LIT>"""<EOL>widthsObject = self.reserveObject('<STR_LIT>')<EOL>fontdescObject = self.reserveObject('<STR_LIT>')<EOL>fontdictObject = self.reserveObject('<STR_LIT>')<EOL>charprocsObject = self.reserveObject('<STR_LIT>')<EOL>differencesArray = []<EOL>firstchar, lastchar = <NUM_LIT:0>, <NUM_LIT:255><EOL>bbox = [cvt(x, nearest=False) for x in font.bbox]<EOL>fontdict = {<EOL>'<STR_LIT>'            : Name('<STR_LIT>'),<EOL>'<STR_LIT>'        : ps_name,<EOL>'<STR_LIT>'       : firstchar,<EOL>'<STR_LIT>'        : lastchar,<EOL>'<STR_LIT>'  : fontdescObject,<EOL>'<STR_LIT>'         : Name('<STR_LIT>'),<EOL>'<STR_LIT:Name>'            : descriptor['<STR_LIT>'],<EOL>'<STR_LIT>'        : bbox,<EOL>'<STR_LIT>'      : [ <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:0> ],<EOL>'<STR_LIT>'       : charprocsObject,<EOL>'<STR_LIT>'        : {<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>' : differencesArray},<EOL>'<STR_LIT>'          : widthsObject<EOL>}<EOL>from encodings import cp1252<EOL>if hasattr(cp1252, '<STR_LIT>'):<EOL><INDENT>def decode_char(charcode):<EOL><INDENT>return cp1252.decoding_map[charcode] or <NUM_LIT:0><EOL><DEDENT><DEDENT>else:<EOL><INDENT>def decode_char(charcode):<EOL><INDENT>return ord(cp1252.decoding_table[charcode])<EOL><DEDENT><DEDENT>def get_char_width(charcode):<EOL><INDENT>str = decode_char(charcode)<EOL>width = font.load_char(str, flags=LOAD_NO_SCALE|LOAD_NO_HINTING).horiAdvance<EOL>return cvt(width)<EOL><DEDENT>widths = [ get_char_width(charcode) for charcode in range(firstchar, lastchar+<NUM_LIT:1>) ]<EOL>descriptor['<STR_LIT>'] = max(widths)<EOL>cmap = font.get_charmap()<EOL>glyph_ids = []<EOL>differences = []<EOL>multi_byte_chars = set()<EOL>for c in characters:<EOL><INDENT>ccode = c<EOL>gind = cmap.get(ccode) or <NUM_LIT:0><EOL>glyph_ids.append(gind)<EOL>glyph_name = font.get_glyph_name(gind)<EOL>if ccode <= <NUM_LIT:255>:<EOL><INDENT>differences.append((ccode, glyph_name))<EOL><DEDENT>else:<EOL><INDENT>multi_byte_chars.add(glyph_name)<EOL><DEDENT><DEDENT>differences.sort()<EOL>last_c = -<NUM_LIT:2><EOL>for c, name in differences:<EOL><INDENT>if c != last_c + <NUM_LIT:1>:<EOL><INDENT>differencesArray.append(c)<EOL><DEDENT>differencesArray.append(Name(name))<EOL>last_c = c<EOL><DEDENT>rawcharprocs = ttconv.get_pdf_charprocs(filename, glyph_ids)<EOL>charprocs = {}<EOL>charprocsRef = {}<EOL>for charname, stream in list(rawcharprocs.items()):<EOL><INDENT>charprocDict = { '<STR_LIT>': len(stream) }<EOL>if charname in multi_byte_chars:<EOL><INDENT>charprocDict['<STR_LIT>'] = Name('<STR_LIT>')<EOL>charprocDict['<STR_LIT>'] = Name('<STR_LIT>')<EOL>charprocDict['<STR_LIT>'] = bbox<EOL>stream = stream[stream.find("<STR_LIT>") + <NUM_LIT:2>:]<EOL><DEDENT>charprocObject = self.reserveObject('<STR_LIT>')<EOL>self.beginStream(charprocObject.id, None, charprocDict)<EOL>self.currentstream.write(stream)<EOL>self.endStream()<EOL>if charname in multi_byte_chars:<EOL><INDENT>name = self._get_xobject_symbol_name(filename, charname)<EOL>self.multi_byte_charprocs[name] = charprocObject<EOL><DEDENT>else:<EOL><INDENT>charprocs[charname] = charprocObject<EOL><DEDENT><DEDENT>self.writeObject(fontdictObject, fontdict)<EOL>self.writeObject(fontdescObject, descriptor)<EOL>self.writeObject(widthsObject, widths)<EOL>self.writeObject(charprocsObject, charprocs)<EOL>return fontdictObject<EOL><DEDENT>def embedTTFType42(font, characters, descriptor):<EOL><INDENT>"""<STR_LIT>"""<EOL>fontdescObject = self.reserveObject('<STR_LIT>')<EOL>cidFontDictObject = self.reserveObject('<STR_LIT>')<EOL>type0FontDictObject = self.reserveObject('<STR_LIT>')<EOL>cidToGidMapObject = self.reserveObject('<STR_LIT>')<EOL>fontfileObject = self.reserveObject('<STR_LIT>')<EOL>wObject = self.reserveObject('<STR_LIT>')<EOL>toUnicodeMapObject = self.reserveObject('<STR_LIT>')<EOL>cidFontDict = {<EOL>'<STR_LIT>'           : Name('<STR_LIT>'),<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>'       : ps_name,<EOL>'<STR_LIT>'  : {<EOL>'<STR_LIT>'   : '<STR_LIT>',<EOL>'<STR_LIT>'   : '<STR_LIT>',<EOL>'<STR_LIT>' : <NUM_LIT:0> },<EOL>'<STR_LIT>' : fontdescObject,<EOL>'<STR_LIT>'              : wObject,<EOL>'<STR_LIT>'    : cidToGidMapObject<EOL>}<EOL>type0FontDict = {<EOL>'<STR_LIT>'            : Name('<STR_LIT>'),<EOL>'<STR_LIT>'         : Name('<STR_LIT>'),<EOL>'<STR_LIT>'        : ps_name,<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>' : [cidFontDictObject],<EOL>'<STR_LIT>'       : toUnicodeMapObject<EOL>}<EOL>descriptor['<STR_LIT>'] = fontfileObject<EOL>length1Object = self.reserveObject('<STR_LIT>')<EOL>self.beginStream(<EOL>fontfileObject.id,<EOL>self.reserveObject('<STR_LIT>'),<EOL>{'<STR_LIT>': length1Object})<EOL>fontfile = open(filename, '<STR_LIT:rb>')<EOL>length1 = <NUM_LIT:0><EOL>while True:<EOL><INDENT>data = fontfile.read(<NUM_LIT>)<EOL>if not data: break<EOL>length1 += len(data)<EOL>self.currentstream.write(data)<EOL><DEDENT>fontfile.close()<EOL>self.endStream()<EOL>self.writeObject(length1Object, length1)<EOL>cid_to_gid_map = ['<STR_LIT>'] * <NUM_LIT><EOL>cmap = font.get_charmap()<EOL>unicode_mapping = []<EOL>widths = []<EOL>max_ccode = <NUM_LIT:0><EOL>for c in characters:<EOL><INDENT>ccode = c<EOL>gind = cmap.get(ccode) or <NUM_LIT:0><EOL>glyph = font.load_char(ccode, flags=LOAD_NO_HINTING)<EOL>widths.append((ccode, glyph.horiAdvance / <NUM_LIT:6>))<EOL>if ccode < <NUM_LIT>:<EOL><INDENT>cid_to_gid_map[ccode] = chr(gind)<EOL><DEDENT>max_ccode = max(ccode, max_ccode)<EOL><DEDENT>widths.sort()<EOL>cid_to_gid_map = cid_to_gid_map[:max_ccode + <NUM_LIT:1>]<EOL>last_ccode = -<NUM_LIT:2><EOL>w = []<EOL>max_width = <NUM_LIT:0><EOL>unicode_groups = []<EOL>for ccode, width in widths:<EOL><INDENT>if ccode != last_ccode + <NUM_LIT:1>:<EOL><INDENT>w.append(ccode)<EOL>w.append([width])<EOL>unicode_groups.append([ccode, ccode])<EOL><DEDENT>else:<EOL><INDENT>w[-<NUM_LIT:1>].append(width)<EOL>unicode_groups[-<NUM_LIT:1>][<NUM_LIT:1>] = ccode<EOL><DEDENT>max_width = max(max_width, width)<EOL>last_ccode = ccode<EOL><DEDENT>unicode_bfrange = []<EOL>for start, end in unicode_groups:<EOL><INDENT>unicode_bfrange.append(<EOL>"<STR_LIT>" %<EOL>(start, end,<EOL>"<STR_LIT:U+0020>".join(["<STR_LIT>" % x for x in range(start, end+<NUM_LIT:1>)])))<EOL><DEDENT>unicode_cmap = (self._identityToUnicodeCMap %<EOL>(len(unicode_groups),<EOL>"<STR_LIT:\n>".join(unicode_bfrange)))<EOL>cid_to_gid_map = "<STR_LIT>".join(cid_to_gid_map).encode("<STR_LIT>")<EOL>self.beginStream(cidToGidMapObject.id,<EOL>None,<EOL>{'<STR_LIT>':  len(cid_to_gid_map)})<EOL>self.currentstream.write(cid_to_gid_map)<EOL>self.endStream()<EOL>self.beginStream(toUnicodeMapObject.id,<EOL>None,<EOL>{'<STR_LIT>': unicode_cmap})<EOL>self.currentstream.write(unicode_cmap)<EOL>self.endStream()<EOL>descriptor['<STR_LIT>'] = max_width<EOL>self.writeObject(cidFontDictObject, cidFontDict)<EOL>self.writeObject(type0FontDictObject, type0FontDict)<EOL>self.writeObject(fontdescObject, descriptor)<EOL>self.writeObject(wObject, w)<EOL>return type0FontDictObject<EOL><DEDENT>ps_name = Name(font.get_sfnt()[(<NUM_LIT:1>,<NUM_LIT:0>,<NUM_LIT:0>,<NUM_LIT:6>)])<EOL>pclt = font.get_sfnt_table('<STR_LIT>')or { '<STR_LIT>': <NUM_LIT:0>, '<STR_LIT>': <NUM_LIT:0> }<EOL>post = font.get_sfnt_table('<STR_LIT>')or { '<STR_LIT>': (<NUM_LIT:0>,<NUM_LIT:0>) }<EOL>ff = font.face_flags<EOL>sf = font.style_flags<EOL>flags = <NUM_LIT:0><EOL>symbolic = False <EOL>if ff & FIXED_WIDTH: flags |= <NUM_LIT:1> << <NUM_LIT:0><EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT:1> <EOL>if symbolic: flags |= <NUM_LIT:1> << <NUM_LIT:2><EOL>else: flags |= <NUM_LIT:1> << <NUM_LIT:5><EOL>if sf & ITALIC: flags |= <NUM_LIT:1> << <NUM_LIT:6><EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT:16> <EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT> <EOL>if <NUM_LIT:0>: flags |= <NUM_LIT:1> << <NUM_LIT> <EOL>descriptor = {<EOL>'<STR_LIT>'        : Name('<STR_LIT>'),<EOL>'<STR_LIT>'    : ps_name,<EOL>'<STR_LIT>'       : flags,<EOL>'<STR_LIT>'    : [ cvt(x, nearest=False) for x in font.bbox ],<EOL>'<STR_LIT>'      : cvt(font.ascender, nearest=False),<EOL>'<STR_LIT>'     : cvt(font.descender, nearest=False),<EOL>'<STR_LIT>'   : cvt(pclt['<STR_LIT>'], nearest=False),<EOL>'<STR_LIT>'     : cvt(pclt['<STR_LIT>']),<EOL>'<STR_LIT>' : post['<STR_LIT>'][<NUM_LIT:1>], <EOL>'<STR_LIT>'       : <NUM_LIT:0> <EOL>}<EOL>if is_opentype_cff_font(filename):<EOL><INDENT>fonttype = <NUM_LIT><EOL>warnings.warn(("<STR_LIT>" +<EOL>"<STR_LIT>") %<EOL>os.path.basename(filename))<EOL><DEDENT>if fonttype == <NUM_LIT:3>:<EOL><INDENT>return embedTTFType3(font, characters, descriptor)<EOL><DEDENT>elif fonttype == <NUM_LIT>:<EOL><INDENT>return embedTTFType42(font, characters, descriptor)<EOL><DEDENT>

Embed the TTF font from the named file into the document.


if isinstance(font, str):<EOL><INDENT>fname = font<EOL><DEDENT>else:<EOL><INDENT>fname = font.fname<EOL><DEDENT>realpath, stat_key = get_realpath_and_stat(fname)<EOL>used_characters = self.used_characters.setdefault(<EOL>stat_key, (realpath, set()))<EOL>used_characters[<NUM_LIT:1>].update([ord(x) for x in s])<EOL>

Keeps track of which characters are required from
        each font.


if self.compressobj is None:<EOL><INDENT>self.file.write(data)<EOL><DEDENT>else:<EOL><INDENT>compressed = self.compressobj.compress(data)<EOL>self.file.write(compressed)<EOL><DEDENT>


def markerObject(self, path, trans, fillp, lw):

key = (path, trans, fillp is not None, lw)<EOL>result = self.markers.get(key)<EOL>if result is None:<EOL><INDENT>name = Name('<STR_LIT>' % len(self.markers))<EOL>ob = self.reserveObject('<STR_LIT>' % len(self.markers))<EOL>self.markers[key] = (name, ob, path, trans, fillp, lw)<EOL><DEDENT>else:<EOL><INDENT>name = result[<NUM_LIT:0>]<EOL><DEDENT>return name<EOL>

Return name of a marker XObject representing the given path.


<EOL>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return obj.pdfRepr()<EOL><DEDENT>elif isinstance(obj, float):<EOL><INDENT>if not npy.isfinite(obj):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>r = "<STR_LIT>" % obj<EOL>return r.rstrip('<STR_LIT:0>').rstrip('<STR_LIT:.>')<EOL><DEDENT>elif isinstance(obj, int):<EOL><INDENT>return "<STR_LIT>" % obj<EOL><DEDENT>elif is_string_like(obj):<EOL><INDENT>return '<STR_LIT:(>' + _string_escape_regex.sub(r'<STR_LIT>', obj) + '<STR_LIT:)>'<EOL><DEDENT>elif isinstance(obj, dict):<EOL><INDENT>r = ["<STR_LIT>"]<EOL>r.extend(["<STR_LIT>" % (Name(key).pdfRepr(), pdfRepr(val))<EOL>for key, val in list(obj.items())])<EOL>r.append("<STR_LIT>")<EOL>return fill(r)<EOL><DEDENT>elif isinstance(obj, (list, tuple)):<EOL><INDENT>r = ["<STR_LIT:[>"]<EOL>r.extend([pdfRepr(val) for val in obj])<EOL>r.append("<STR_LIT:]>")<EOL>return fill(r)<EOL><DEDENT>elif isinstance(obj, bool):<EOL><INDENT>return ['<STR_LIT:false>', '<STR_LIT:true>'][obj]<EOL><DEDENT>elif obj is None:<EOL><INDENT>return '<STR_LIT:null>'<EOL><DEDENT>elif isinstance(obj, datetime):<EOL><INDENT>r = obj.strftime('<STR_LIT>')<EOL>if time.daylight: z = time.altzone<EOL>else: z = time.timezone<EOL>if z == <NUM_LIT:0>: r += '<STR_LIT>'<EOL>elif z < <NUM_LIT:0>: r += "<STR_LIT>" % ((-z)//<NUM_LIT>, (-z)%<NUM_LIT>)<EOL>else: r += "<STR_LIT>" % (z//<NUM_LIT>, z%<NUM_LIT>)<EOL>return pdfRepr(r)<EOL><DEDENT>elif isinstance(obj, BboxBase):<EOL><INDENT>return fill([pdfRepr(val) for val in obj.bounds])<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>"% type(obj))<EOL><DEDENT>


self.write("<STR_LIT>")<EOL>self.write(pdfRepr(<EOL>{'<STR_LIT>': self.nextObject,<EOL>'<STR_LIT>': self.rootObject,<EOL>'<STR_LIT>': self.infoObject }))<EOL>self.write("<STR_LIT>" % self.startxref)<EOL>


GraphicsContextBase.copy_properties(self, other)<EOL>self._fillcolor = other._fillcolor<EOL>


if is_string_like(fontprop):<EOL><INDENT>filename = fontprop<EOL><DEDENT>elif rcParams['<STR_LIT>']:<EOL><INDENT>filename = findfont(fontprop, fontext='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>filename = findfont(fontprop)<EOL><DEDENT>Fx = self.fontNames.get(filename)<EOL>if Fx is None:<EOL><INDENT>Fx = Name('<STR_LIT>' % self.nextFont)<EOL>self.fontNames[filename] = Fx<EOL>self.nextFont += <NUM_LIT:1><EOL><DEDENT>return Fx<EOL>

Select a font based on fontprop and return a name suitable for
Op.selectfont. If fontprop is a string, it will be interpreted
as the filename of the font.


if self.compressobj is not None:<EOL><INDENT>compressed = self.compressobj.flush()<EOL>self.file.write(compressed)<EOL>self.compressobj = None<EOL><DEDENT>


for a in self._active:<EOL><INDENT>a.xaxis.zoom(direction)<EOL><DEDENT>self.canvas.draw()<EOL>return True<EOL>


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.window.show()<EOL><DEDENT>if mainloop and gtk.main_level() == <NUM_LIT:0> andlen(Gcf.get_all_fig_managers())><NUM_LIT:0>:<EOL><INDENT>gtk.main()<EOL><DEDENT>

Show all the figures and enter the gtk main loop
This should be the last line of your script


for a in self._active:<EOL><INDENT>a.yaxis.pan(direction)<EOL><DEDENT>self.canvas.draw()<EOL>return True<EOL>


if matplotlib.is_interactive():<EOL><INDENT>figManager =  Gcf.get_active()<EOL>if figManager is not None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT><DEDENT>

Is called after every pylab drawing command


self._renderer = RendererGDK (self, self.figure.dpi)<EOL>

Override by GTK backends to select a different renderer
        Renderer should provide the methods:
            set_pixmap ()
            set_width_height ()
        that are used by
            _render_figure() / _pixmap_prepare()


ind = self.cbox_linestyles.get_active()<EOL>ls = self.linestyles[ind]<EOL>return ls<EOL>


if not self._inited: return<EOL>self._updateson = False<EOL>line = self.get_active_line()<EOL>ls = line.get_linestyle()<EOL>if ls is None: ls = '<STR_LIT:None>'<EOL>self.cbox_linestyles.set_active(self.linestyled[ls])<EOL>marker = line.get_marker()<EOL>if marker is None: marker = '<STR_LIT:None>'<EOL>self.cbox_markers.set_active(self.markerd[marker])<EOL>r,g,b = colorConverter.to_rgb(line.get_color())<EOL>color = gtk.gdk.Color(*[int(val*<NUM_LIT>) for val in (r,g,b)])<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>button.set_color(color)<EOL>r,g,b = colorConverter.to_rgb(line.get_markerfacecolor())<EOL>color = gtk.gdk.Color(*[int(val*<NUM_LIT>) for val in (r,g,b)])<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>button.set_color(color)<EOL>self._updateson = True<EOL>


if not self._inited or not self._updateson: return<EOL>line = self.get_active_line()<EOL>ls = self.get_active_linestyle()<EOL>marker = self.get_active_marker()<EOL>line.set_linestyle(ls)<EOL>line.set_marker(marker)<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>color = button.get_color()<EOL>r, g, b = [val/<NUM_LIT> for val in (color.red, color.green, color.blue)]<EOL>line.set_color((r,g,b))<EOL>button = self.wtree.get_widget('<STR_LIT>')<EOL>color = button.get_color()<EOL>r, g, b = [val/<NUM_LIT> for val in (color.red, color.green, color.blue)]<EOL>line.set_markerfacecolor((r,g,b))<EOL>line.figure.canvas.draw()<EOL>

update the active line props from the widgets


gtk.Toolbar.__init__(self)<EOL>self.canvas = canvas<EOL>self.win    = window<EOL>self.set_style(gtk.TOOLBAR_ICONS)<EOL>if gtk.pygtk_version >= (<NUM_LIT:2>,<NUM_LIT:4>,<NUM_LIT:0>):<EOL><INDENT>self._create_toolitems_2_4()<EOL>self.update = self._update_2_4<EOL>self.fileselect = FileChooserDialog(<EOL>title='<STR_LIT>',<EOL>parent=self.win,<EOL>filetypes=self.canvas.get_supported_filetypes(),<EOL>default_filetype=self.canvas.get_default_filetype())<EOL><DEDENT>else:<EOL><INDENT>self._create_toolitems_2_2()<EOL>self.update = self._update_2_2<EOL>self.fileselect = FileSelection(title='<STR_LIT>',<EOL>parent=self.win)<EOL><DEDENT>self.show_all()<EOL>self.update()<EOL>

figManager is the FigureManagerGTK instance that contains the
toolbar, with attributes figure, window and drawingArea


if _debug: print('<STR_LIT>' % fn_name())<EOL>if GTK_WIDGET_DRAWABLE(self):<EOL><INDENT>if self._need_redraw:<EOL><INDENT>x, y, w, h = self.allocation<EOL>self._pixmap_prepare (w, h)<EOL>self._render_figure(self._pixmap, w, h)<EOL>self._need_redraw = False<EOL><DEDENT>x, y, w, h = event.area<EOL>self.window.draw_drawable (self.style.fg_gc[self.state],<EOL>self._pixmap, x, y, x, y, w, h)<EOL><DEDENT>return False<EOL>

Expose_event for all GTK backends. Should not be overridden.


for a in self._active:<EOL><INDENT>a.xaxis.pan(direction)<EOL><DEDENT>self.canvas.draw()<EOL>return True<EOL>


<EOL>if DEBUG: print('<STR_LIT>', self,self.get_width_height())<EOL>if type(self.replot) is bool: <EOL><INDENT>if self.replot:<EOL><INDENT>FigureCanvasAgg.draw(self)<EOL><DEDENT>if QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian:<EOL><INDENT>stringBuffer = self.renderer._renderer.tostring_bgra()<EOL><DEDENT>else:<EOL><INDENT>stringBuffer = self.renderer._renderer.tostring_argb()<EOL><DEDENT>qImage = QtGui.QImage(stringBuffer, self.renderer.width,<EOL>self.renderer.height,<EOL>QtGui.QImage.Format_ARGB32)<EOL>p = QtGui.QPainter(self)<EOL>p.drawPixmap(QtCore.QPoint(<NUM_LIT:0>, <NUM_LIT:0>), QtGui.QPixmap.fromImage(qImage))<EOL>if self.drawRect:<EOL><INDENT>p.setPen( QtGui.QPen( QtCore.Qt.black, <NUM_LIT:1>, QtCore.Qt.DotLine ) )<EOL>p.drawRect( self.rect[<NUM_LIT:0>], self.rect[<NUM_LIT:1>], self.rect[<NUM_LIT:2>], self.rect[<NUM_LIT:3>] )<EOL><DEDENT>p.end()<EOL><DEDENT>else:<EOL><INDENT>bbox = self.replot<EOL>l, b, r, t = bbox.extents<EOL>w = int(r) - int(l)<EOL>h = int(t) - int(b)<EOL>t = int(b) + h<EOL>reg = self.copy_from_bbox(bbox)<EOL>stringBuffer = reg.to_string_argb()<EOL>qImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32)<EOL>pixmap = QtGui.QPixmap.fromImage(qImage)<EOL>p = QtGui.QPainter( self )<EOL>p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), pixmap)<EOL>p.end()<EOL><DEDENT>self.replot = False<EOL>self.drawRect = False<EOL>

Draw to the Agg backend and then copy the image to the qt.drawable.
In Qt, all drawing should be done inside of here when a widget is
shown onscreen.


if DEBUG: print("<STR_LIT>", self)<EOL>self.replot = True<EOL>FigureCanvasAgg.draw(self)<EOL>self.update()<EOL>QtGui.qApp.processEvents()<EOL>

Draw the figure when xwindows is ready for the update


def new_figure_manager(num, *args, **kwargs):

if _debug: print('<STR_LIT>' % (self.__class__.__name__, _fn_name()))<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas  = FigureCanvasCairo(thisFig)<EOL>manager = FigureManagerBase(canvas, num)<EOL>return manager<EOL>


<EOL>w = event.widget.winfo_containing(event.x_root, event.y_root)<EOL>if w == self._tkcanvas:<EOL><INDENT>x = event.x_root - w.winfo_rootx()<EOL>y = event.y_root - w.winfo_rooty()<EOL>y = self.figure.bbox.height - y<EOL>step = event.delta/<NUM_LIT><EOL>FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=event)<EOL><DEDENT>


_focus = windowing.FocusManager()<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>figure = FigureClass(*args, **kwargs)<EOL>window = Tk.Tk()<EOL>canvas = FigureCanvasTkAgg(figure, master=window)<EOL>figManager = FigureManagerTkAgg(canvas, num, window)<EOL>if matplotlib.is_interactive():<EOL><INDENT>figManager.show()<EOL><DEDENT>return figManager<EOL>


d = self._idle<EOL>self._idle = False<EOL>def idle_draw(*args):<EOL><INDENT>self.draw()<EOL>self._idle = True<EOL><DEDENT>if d:<EOL><INDENT>self._tkcanvas.after_idle(idle_draw)<EOL><DEDENT>


<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasTemplate(thisFig)<EOL>manager = FigureManagerTemplate(canvas, num)<EOL>return manager<EOL>


def print_foo(self, filename, *args, **kwargs):

pass<EOL>

Write out format foo.  The dpi, facecolor and edgecolor are restored
to their original values after this call, so you don't need to
save and restore them.


if matplotlib.is_interactive():<EOL><INDENT>figManager =  Gcf.get_active()<EOL>if figManager != None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT><DEDENT>


def new_figure_manager( num, *args, **kwargs ):

FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass( *args, **kwargs )<EOL>canvas = FigureCanvasQT( thisFig )<EOL>manager = FigureManagerQT( canvas, num )<EOL>return manager<EOL>


def exception_handler( type, value, tb ):

msg = '<STR_LIT>'<EOL>if hasattr(value, '<STR_LIT:filename>') and value.filename != None:<EOL><INDENT>msg = value.filename + '<STR_LIT>'<EOL><DEDENT>if hasattr(value, '<STR_LIT>') and value.strerror != None:<EOL><INDENT>msg += value.strerror<EOL><DEDENT>else:<EOL><INDENT>msg += str(value)<EOL><DEDENT>if len( msg ) : error_msg_qt( msg )<EOL>

Handle uncaught exceptions
    It does not catch SystemExit


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.window.show()<EOL><DEDENT>if DEBUG: print('<STR_LIT>')<EOL>figManager =  Gcf.get_active()<EOL>if figManager != None:<EOL><INDENT>figManager.canvas.draw()<EOL><DEDENT>if _create_qApp.qAppCreatedHere:<EOL><INDENT>qt.qApp.exec_loop()<EOL><DEDENT>

Show all the figures and enter the qt main loop
This should be the last line of your script


if _debug: print('<STR_LIT>' % fn_name())<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasGTKCairo(thisFig)<EOL>return FigureManagerGTK(canvas, num)<EOL>


if _debug: print('<STR_LIT>' % (self.__class__.__name__, _fn_name()))<EOL>self._renderer = RendererGTKCairo (self.figure.dpi)<EOL>

Override to use cairo (rather than GDK) renderer


if self._rasterizing == <NUM_LIT:0>:<EOL><INDENT>self._raster_renderer = self._raster_renderer_class(<EOL>self._width*self.dpi, self._height*self.dpi, self.dpi)<EOL>self._set_current_renderer(self._raster_renderer)<EOL><DEDENT>self._rasterizing += <NUM_LIT:1><EOL>

Enter "raster" mode.  All subsequent drawing commands (until
stop_rasterizing is called) will be drawn with the raster
backend.

If start_rasterizing is called multiple times before
stop_rasterizing is called, this method has no effect.


def __init__(self, width, height, dpi, vector_renderer, raster_renderer_class=None):

if raster_renderer_class is None:<EOL><INDENT>raster_renderer_class = RendererAgg<EOL><DEDENT>self._raster_renderer_class = raster_renderer_class<EOL>self._width = width<EOL>self._height = height<EOL>self.dpi = dpi<EOL>assert not vector_renderer.option_image_nocomposite()<EOL>self._vector_renderer = vector_renderer<EOL>self._raster_renderer = None<EOL>self._rasterizing = <NUM_LIT:0><EOL>self._set_current_renderer(vector_renderer)<EOL>

width: The width of the canvas in logical units

height: The height of the canvas in logical units

dpi: The dpi of the canvas

vector_renderer: An instance of a subclass of RendererBase
that will be used for the vector drawing.

raster_renderer_class: The renderer class to use for the
raster drawing.  If not provided, this will use the Agg
backend (which is currently the only viable option anyway.)


self._rasterizing -= <NUM_LIT:1><EOL>if self._rasterizing == <NUM_LIT:0>:<EOL><INDENT>self._set_current_renderer(self._vector_renderer)<EOL>width, height = self._width * self.dpi, self._height * self.dpi<EOL>buffer, bounds = self._raster_renderer.tostring_rgba_minimized()<EOL>l, b, w, h = bounds<EOL>if w > <NUM_LIT:0> and h > <NUM_LIT:0>:<EOL><INDENT>image = frombuffer(buffer, w, h, True)<EOL>image.is_grayscale = False<EOL>image.flipud_out()<EOL>self._renderer.draw_image(l, height - b - h, image, None)<EOL><DEDENT>self._raster_renderer = None<EOL>self._rasterizing = False<EOL><DEDENT>

Exit "raster" mode.  All of the drawing that was done since
the last start_rasterizing command will be copied to the
vector backend by calling draw_image.

If stop_rasterizing is called multiple times before
start_rasterizing is called, this method has no effect.


l, b, width, height = bbox.get_bounds()<EOL>r = l + width<EOL>t = b + height<EOL>srcBmp = wx.BitmapFromBufferRGBA(int(agg.width), int(agg.height),<EOL>agg.buffer_rgba(<NUM_LIT:0>, <NUM_LIT:0>))<EOL>srcDC = wx.MemoryDC()<EOL>srcDC.SelectObject(srcBmp)<EOL>destBmp = wx.EmptyBitmap(int(width), int(height))<EOL>destDC = wx.MemoryDC()<EOL>destDC.SelectObject(destBmp)<EOL>destDC.BeginDrawing()<EOL>x = int(l)<EOL>y = int(int(agg.height) - t)<EOL>destDC.Blit(<NUM_LIT:0>, <NUM_LIT:0>, int(width), int(height), srcDC, x, y)<EOL>destDC.EndDrawing()<EOL>srcDC.SelectObject(wx.NullBitmap)<EOL>destDC.SelectObject(wx.NullBitmap)<EOL>return destBmp<EOL>

Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.

Note: agg must be a backend_agg.RendererAgg instance.


if bbox is None:<EOL><INDENT>self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)<EOL>self.gui_repaint()<EOL>return<EOL><DEDENT>l, b, w, h = bbox.bounds<EOL>r = l + w<EOL>t = b + h<EOL>x = int(l)<EOL>y = int(self.bitmap.GetHeight() - t)<EOL>srcBmp = _convert_agg_to_wx_bitmap(self.get_renderer(), None)<EOL>srcDC = wx.MemoryDC()<EOL>srcDC.SelectObject(srcBmp)<EOL>destDC = wx.MemoryDC()<EOL>destDC.SelectObject(self.bitmap)<EOL>destDC.BeginDrawing()<EOL>destDC.Blit(x, y, int(w), int(h), srcDC, x, y)<EOL>destDC.EndDrawing()<EOL>destDC.SelectObject(wx.NullBitmap)<EOL>srcDC.SelectObject(wx.NullBitmap)<EOL>self.gui_repaint()<EOL>

Transfer the region of the agg buffer defined by bbox to the display.
If bbox is None, the entire buffer is transferred.


if bbox is None:<EOL><INDENT>image = wx.EmptyImage(int(agg.width), int(agg.height))<EOL>image.SetData(agg.tostring_rgb())<EOL>return image<EOL><DEDENT>else:<EOL><INDENT>return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox))<EOL><DEDENT>

Convert the region of the agg buffer bounded by bbox to a wx.Image.  If
bbox is None, the entire buffer is converted.

Note: agg must be a backend_agg.RendererAgg instance.


global _convert_agg_to_wx_image<EOL>global _convert_agg_to_wx_bitmap<EOL>if getattr(wx, '<STR_LIT>', '<STR_LIT>')[<NUM_LIT:0>:<NUM_LIT:3>] < '<STR_LIT>':<EOL><INDENT>if state and _wxagg is not None:<EOL><INDENT>_convert_agg_to_wx_image  = _wxagg.convert_agg_to_wx_image<EOL>_convert_agg_to_wx_bitmap = _wxagg.convert_agg_to_wx_bitmap<EOL><DEDENT>else:<EOL><INDENT>_convert_agg_to_wx_image  = _py_convert_agg_to_wx_image<EOL>_convert_agg_to_wx_bitmap = _py_convert_agg_to_wx_bitmap<EOL><DEDENT><DEDENT>else:<EOL><INDENT>_convert_agg_to_wx_image  = _py_WX28_convert_agg_to_wx_image<EOL>_convert_agg_to_wx_bitmap = _py_WX28_convert_agg_to_wx_bitmap<EOL><DEDENT>

Enable or disable the WXAgg accelerator, if it is present and is also
compatible with whatever version of wxPython is in use.


if bbox is None:<EOL><INDENT>return wx.BitmapFromImage(_py_convert_agg_to_wx_image(agg, None))<EOL><DEDENT>else:<EOL><INDENT>return _clipped_image_as_bitmap(<EOL>_py_convert_agg_to_wx_image(agg, None),<EOL>bbox)<EOL><DEDENT>

Convert the region of the agg buffer bounded by bbox to a wx.Bitmap.  If
bbox is None, the entire buffer is converted.

Note: agg must be a backend_agg.RendererAgg instance.


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.show()<EOL><DEDENT>if show._needmain:<EOL><INDENT>_thread.start_new_thread(Fltk_run_interactive,())<EOL><DEDENT>show._needmain = False<EOL>

Show all the figures and enter the fltk mainloop in another thread
This allows to keep hand in interractive python session
Warning: does not work under windows
This should be the last line of your script


FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>figure = FigureClass(*args, **kwargs)<EOL>window = Fltk.Fl_Double_Window(<NUM_LIT:10>,<NUM_LIT:10>,<NUM_LIT:30>,<NUM_LIT:30>)<EOL>canvas = FigureCanvasFltkAgg(figure)<EOL>window.end()<EOL>window.show()<EOL>window.make_current()<EOL>figManager = FigureManagerFltkAgg(canvas, num, window)<EOL>if matplotlib.is_interactive():<EOL><INDENT>figManager.show()<EOL><DEDENT>return figManager<EOL>


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>manager.show()<EOL><DEDENT>if show._needmain:<EOL><INDENT>Fltk.Fl.run()<EOL>show._needmain = False<EOL><DEDENT>

Show all the figures and enter the fltk mainloop

This should be the last line of your script


if DEBUG: print('<STR_LIT>')<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass( *args, **kwargs )<EOL>canvas = FigureCanvasQTAgg( thisFig )<EOL>return FigureManagerQTAgg( canvas, num )<EOL>


try:<EOL><INDENT>return self._cached[tuple(rgb)]<EOL><DEDENT>except KeyError:<EOL><INDENT>color = self._cached[tuple(rgb)] =self._cmap.alloc_color(<EOL>int(rgb[<NUM_LIT:0>]*<NUM_LIT>),int(rgb[<NUM_LIT:1>]*<NUM_LIT>),int(rgb[<NUM_LIT:2>]*<NUM_LIT>))<EOL>return color<EOL><DEDENT>

rgb - an RGB tuple (three 0.0-1.0 values)
return an allocated gtk.gdk.Color


if __debug__: verbose.report('<STR_LIT>',<EOL>'<STR_LIT>')<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasAgg(thisFig)<EOL>manager = FigureManagerBase(canvas, num)<EOL>return manager<EOL>


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.select()<EOL>if w><NUM_LIT:0> and w<<NUM_LIT:1>: w = <NUM_LIT:1><EOL>GraphicsContextBase.set_linewidth(self, w)<EOL>lw = int(self.renderer.points_to_pixels(self._linewidth))<EOL>if lw==<NUM_LIT:0>: lw = <NUM_LIT:1><EOL>self._pen.SetWidth(lw)<EOL>self.gfx_ctx.SetPen(self._pen)<EOL>self.unselect()<EOL>


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self._menu = MenuButtonWx(self)<EOL>self.AddControl(self._menu)<EOL>self.AddSeparator()<EOL>

Creates the 'menu' - implemented as a button which opens a
pop-up menu since wxPython does not allow a menu as a control


<EOL>DEBUG_MSG("<STR_LIT>", <NUM_LIT:3>, None)<EOL>_create_wx_app()<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>fig = FigureClass(*args, **kwargs)<EOL>frame = FigureFrameWx(num, fig)<EOL>figmgr = frame.get_figure_manager()<EOL>if matplotlib.is_interactive():<EOL><INDENT>figmgr.frame.Show()<EOL><DEDENT>return figmgr<EOL>


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>if wx.VERSION_STRING < "<STR_LIT>":<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.width  = bitmap.GetWidth()<EOL>self.height = bitmap.GetHeight()<EOL>self.bitmap = bitmap<EOL>self.fontd = {}<EOL>self.dpi = dpi<EOL>self.gc = None<EOL>

Initialise a wxWindows renderer instance.


pass<EOL>

A NULL event handler - does nothing whatsoever


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self.renderer = RendererWx(self.bitmap, self.figure.dpi)<EOL>self.figure.draw(self.renderer)<EOL>self._isDrawn = True<EOL>self.gui_repaint(drawDC=drawDC)<EOL>

Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.


basedir = os.path.join(rcParams['<STR_LIT>'],'<STR_LIT>')<EOL>bmpFilename = os.path.normpath(os.path.join(basedir, filename))<EOL>if not os.path.exists(bmpFilename):<EOL><INDENT>raise IOError('<STR_LIT>'%bmpFilename)<EOL><DEDENT>bmp = wx.Bitmap(bmpFilename)<EOL>return bmp<EOL>

Load a bitmap file from the backends/images subdirectory in which the
matplotlib library is installed. The filename parameter should not
contain any path information as this is determined automatically.

Returns a wx.Bitmap object


if hasattr(self, '<STR_LIT>'):<EOL><INDENT>data = wx.PageSetupDialogData()<EOL>data.SetPrintData(self.printerData)<EOL><DEDENT>else:<EOL><INDENT>data = wx.PageSetupDialogData()<EOL><DEDENT>data.SetMarginTopLeft( (<NUM_LIT:15>, <NUM_LIT:15>) )<EOL>data.SetMarginBottomRight( (<NUM_LIT:15>, <NUM_LIT:15>) )<EOL>dlg = wx.PageSetupDialog(self, data)<EOL>if dlg.ShowModal() == wx.ID_OK:<EOL><INDENT>data = dlg.GetPageSetupData()<EOL>tl = data.GetMarginTopLeft()<EOL>br = data.GetMarginBottomRight()<EOL><DEDENT>self.printerData = wx.PrintData(data.GetPrintData())<EOL>dlg.Destroy()<EOL>

set up figure for printing.  Using the standard wx Printer
        Setup Dialog.


if hasattr(self,'<STR_LIT>'):<EOL><INDENT>if self._event_loop.IsRunning():<EOL><INDENT>self._event_loop.Exit()<EOL><DEDENT>del self._event_loop<EOL><DEDENT>

Stop an event loop.  This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.

Call signature::

stop_event_loop_default(self)


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self._isDrawn = False  <EOL>if hasattr(self,'<STR_LIT>'):<EOL><INDENT>self._idletimer.Restart(IDLE_DELAY)<EOL><DEDENT>else:<EOL><INDENT>self._idletimer = wx.FutureCall(IDLE_DELAY,self._onDrawIdle)<EOL><DEDENT>


return self._lastControl<EOL>

Returns the identity of the last toolbar button pressed.


po1  = PrintoutWx(self, width=self.printer_width,<EOL>margin=self.printer_margin)<EOL>po2  = PrintoutWx(self, width=self.printer_width,<EOL>margin=self.printer_margin)<EOL>self.preview = wx.PrintPreview(po1,po2,self.printerData)<EOL>if not self.preview.Ok():  print("<STR_LIT>")<EOL>self.preview.SetZoom(<NUM_LIT:50>)<EOL>frameInst= self<EOL>while not isinstance(frameInst, wx.Frame):<EOL><INDENT>frameInst= frameInst.GetParent()<EOL><DEDENT>frame = wx.PreviewFrame(self.preview, frameInst, "<STR_LIT>")<EOL>frame.Initialize()<EOL>frame.SetPosition(self.GetPosition())<EOL>frame.SetSize((<NUM_LIT>,<NUM_LIT>))<EOL>frame.Centre(wx.BOTH)<EOL>frame.Show(True)<EOL>self.gui_repaint()<EOL>

generate Print Preview with wx Print mechanism


axis_txt = '<STR_LIT>'<EOL>for e in lst:<EOL><INDENT>axis_txt += '<STR_LIT>' % (e+<NUM_LIT:1>)<EOL><DEDENT>self.SetLabel("<STR_LIT>" % axis_txt[:-<NUM_LIT:1>])<EOL>

Update the list of selected axes in the menu button


def draw_text(self, gc, x, y, s, prop, angle, ismath):

if ismath: s = self.strip_math(s)<EOL>DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>gc.select()<EOL>self.handle_clip_rectangle(gc)<EOL>gfx_ctx = gc.gfx_ctx<EOL>font = self.get_wx_font(s, prop)<EOL>color = gc.get_wxcolour(gc.get_rgb())<EOL>gfx_ctx.SetFont(font, color)<EOL>w, h, d = self.get_text_width_height_descent(s, prop, ismath)<EOL>x = int(x)<EOL>y = int(y-h)<EOL>if angle == <NUM_LIT:0.0>:<EOL><INDENT>gfx_ctx.DrawText(s, x, y)<EOL><DEDENT>else:<EOL><INDENT>rads = angle / <NUM_LIT> * math.pi<EOL>xo = h * math.sin(rads)<EOL>yo = h * math.cos(rads)<EOL>gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)<EOL><DEDENT>gc.unselect()<EOL>

Render the matplotlib.text.Text instance
None)


def get_text_width_height_descent(self, s, prop, ismath):

<EOL>if ismath: s = self.strip_math(s)<EOL>if self.gc is None:<EOL><INDENT>gc = self.new_gc()<EOL><DEDENT>else:<EOL><INDENT>gc = self.gc<EOL><DEDENT>gfx_ctx = gc.gfx_ctx<EOL>font = self.get_wx_font(s, prop)<EOL>gfx_ctx.SetFont(font, wx.BLACK)<EOL>w, h, descent, leading = gfx_ctx.GetFullTextExtent(s)<EOL>return w, h, descent<EOL>

get the width and height in display coords of the string s
with FontPropertry prop


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>self._axes = self.canvas.figure.get_axes()<EOL>self._menu.updateAxes(len(self._axes))<EOL>

Update the toolbar menu - called when (e.g.) a new subplot or axes are added


DEBUG_MSG("<STR_LIT>", <NUM_LIT:2>, self)<EOL>self._width, self._height = self.GetClientSize()<EOL>self.bitmap =wx.EmptyBitmap(self._width, self._height)<EOL>self._isDrawn = False<EOL>if self._width <= <NUM_LIT:1> or self._height <= <NUM_LIT:1>: return <EOL>dpival = self.figure.dpi<EOL>winch = self._width/dpival<EOL>hinch = self._height/dpival<EOL>self.figure.set_size_inches(winch, hinch)<EOL>self.Refresh(eraseBackground=False)<EOL>

Called when wxEventSize is generated.

In this application we attempt to resize to fit the window, so it
is better to take the performance hit and redraw the whole window.


key = self._get_key(evt)<EOL>evt.Skip()<EOL>FigureCanvasBase.key_release_event(self, key, guiEvent=evt)<EOL>


pass<EOL>

Called when window is redrawn; since we are blitting the entire
image, we can leave this blank to suppress flicker.


current = self._menu.IsChecked(evt.GetId())<EOL>if current:<EOL><INDENT>new = False<EOL><DEDENT>else:<EOL><INDENT>new = True<EOL><DEDENT>self._menu.Check(evt.GetId(), new)<EOL>self._toolbar.set_active(self.getActiveAxes())<EOL>evt.Skip()<EOL>

Called whenever one of the specific axis menu items is selected


Set the join style to be one of ('miter', 'round', 'bevel')


DEBUG_MSG("<STR_LIT>", <NUM_LIT:1>, self)<EOL>if len(color) == <NUM_LIT:3>:<EOL><INDENT>r, g, b = color<EOL>r *= <NUM_LIT:255><EOL>g *= <NUM_LIT:255><EOL>b *= <NUM_LIT:255><EOL>return wx.Colour(red=int(r), green=int(g), blue=int(b))<EOL><DEDENT>else:<EOL><INDENT>r, g, b, a = color<EOL>r *= <NUM_LIT:255><EOL>g *= <NUM_LIT:255><EOL>b *= <NUM_LIT:255><EOL>a *= <NUM_LIT:255><EOL>return wx.Colour(red=int(r), green=int(g), blue=int(b), alpha=int(a))<EOL><DEDENT>


initialize printer settings using wx methods


if sys.platform=='<STR_LIT:win32>':<EOL><INDENT>self.dc.SelectObject(wx.NullBitmap)<EOL>self.IsSelected = False<EOL><DEDENT>

Select a Null bitmasp into this wxDC instance


x = evt.GetX()<EOL>y = self.figure.bbox.height - evt.GetY()<EOL>evt.Skip()<EOL>self.CaptureMouse()<EOL>FigureCanvasBase.button_press_event(self, x, y, <NUM_LIT:1>, guiEvent=evt)<EOL>


Set the capstyle as a string in ('butt', 'round', 'projecting')


if len(self._axisId) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>for i in range(len(self._axisId)):<EOL><INDENT>self._menu.Check(self._axisId[i], True)<EOL><DEDENT>self._toolbar.set_active(self.getActiveAxes())<EOL>evt.Skip()<EOL>

Called when the 'select all axes' menu item is selected.


if sys.platform=='<STR_LIT:win32>':<EOL><INDENT>self.dc.SelectObject(self.bitmap)<EOL>self.IsSelected = True<EOL><DEDENT>

Select the current bitmap into this wxDC instance


DEBUG_MSG("<STR_LIT>", <NUM_LIT:3>, None)<EOL>for figwin in Gcf.get_all_fig_managers():<EOL><INDENT>figwin.frame.Show()<EOL><DEDENT>if show._needmain and not matplotlib.is_interactive():<EOL><INDENT>wxapp = wx.GetApp()<EOL>if wxapp is not None:<EOL><INDENT>imlr = getattr(wxapp, '<STR_LIT>', lambda: False)<EOL>if not imlr():<EOL><INDENT>wxapp.MainLoop()<EOL><DEDENT><DEDENT>show._needmain = False<EOL><DEDENT>

Current implementation assumes that matplotlib is executed in a PyCrust
shell. It appears to be possible to execute wxPython applications from
within a PyCrust without having to ensure that wxPython has been created
in a secondary thread (e.g. SciPy gui_thread).

Unfortunately, gui_thread seems to introduce a number of further
dependencies on SciPy modules, which I do not wish to introduce
into the backend at this point. If there is a need I will look
into this in a later release.


FigureCanvasBase.enter_notify_event(self, guiEvent = evt)<EOL>


active = []<EOL>for i in range(len(self._axisId)):<EOL><INDENT>if self._menu.IsChecked(self._axisId[i]):<EOL><INDENT>active.append(i)<EOL><DEDENT><DEDENT>return active<EOL>


thisFig = Figure( *args, **kwargs )<EOL>canvas = FigureCanvasQT( thisFig )<EOL>manager = FigureManagerQT( canvas, num )<EOL>return manager<EOL>


self.window.resize(width, height)<EOL>


if self.lastHandle[type] != handle:<EOL><INDENT>self.emf.SelectObject(handle)<EOL>self.lastHandle[type]=handle<EOL><DEDENT>

Update the EMF file with the current handle, but only if it
isn't the same as the last one.  Don't want to flood the file
with duplicate info.


<EOL>pass<EOL>

Draw the Image instance into the current axes; x is the
distance in pixels from the left hand side of the canvas. y is
the distance from the origin.  That is, if origin is upper, y
is the distance from top.  If origin is lower, y is the
distance from bottom

bbox is a matplotlib.transforms.BBox instance for clipping, or
None


pen=EMFPen(self.emf,gc)<EOL>key=hash(pen)<EOL>handle=self._fontHandle.get(key)<EOL>if handle is None:<EOL><INDENT>handle=pen.get_handle()<EOL>self._fontHandle[key]=handle<EOL><DEDENT>if debugHandle: print("<STR_LIT>" % handle)<EOL>self.set_handle("<STR_LIT>",handle)<EOL>if pen.style != pyemf.PS_NULL:<EOL><INDENT>return pen<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Select a pen that includes the color, line width and line
style.  Return the pen if it will draw a line, or None if the
pen won't produce any output (i.e. the style is PS_NULL)


if debugPrint: print("<STR_LIT>" % len(str(x)))<EOL>if self.select_pen(gc):<EOL><INDENT>points = [(int(x[i]), int(self.height-y[i])) for i in range(len(x))]<EOL>self.emf.Polyline(points)<EOL><DEDENT>

x and y are equal length arrays, draw lines connecting each
point in x, y


key = hash(prop)<EOL>font = _fontd.get(key)<EOL>if font is None:<EOL><INDENT>fname = findfont(prop)<EOL>if debugText: print("<STR_LIT>" % fname)<EOL>font = FT2Font(str(fname))<EOL>_fontd[key] = font<EOL><DEDENT>font.clear()<EOL>size = prop.get_size_in_points()<EOL>font.set_size(size, self.dpi)<EOL>return font<EOL>

get the true type font properties, used because EMFs on
windows will use true type fonts.


def __init__(self, outfile, width, height, dpi):

self.outfile = outfile<EOL>self._cached = {}<EOL>self._fontHandle = {}<EOL>self.lastHandle = {'<STR_LIT>':-<NUM_LIT:1>, '<STR_LIT>':-<NUM_LIT:1>, '<STR_LIT>':-<NUM_LIT:1>}<EOL>self.emf=pyemf.EMF(width,height,dpi,'<STR_LIT>')<EOL>self.width=int(width*dpi)<EOL>self.height=int(height*dpi)<EOL>self.dpi = dpi<EOL>self.pointstodpi = dpi/<NUM_LIT><EOL>self.hackPointsForMathExponent = <NUM_LIT><EOL>self.emf.SetBkMode(pyemf.TRANSPARENT)<EOL>self.emf.SetTextAlign( pyemf.TA_BOTTOM|pyemf.TA_LEFT)<EOL>if debugPrint: print("<STR_LIT>" % (self.width,self.height,outfile,dpi))<EOL>

Initialize the renderer with a gd image instance


for manager in Gcf.get_all_fig_managers():<EOL><INDENT>pass<EOL><DEDENT>

For image backends - is not required
For GUI backends - show() is usually the last line of a pylab script and
tells the backend that it is time to draw.  In interactive mode, this may
be a do nothing func.  See the GTK backend for an example of how to handle
interactive versus batch mode


def draw_text(self, gc, x, y, s, prop, angle, ismath=False):

if debugText: print("<STR_LIT>" % (x,y,angle,s))<EOL>if ismath:<EOL><INDENT>self.draw_math_text(gc,x,y,s,prop,angle)<EOL><DEDENT>else:<EOL><INDENT>self.draw_plain_text(gc,x,y,s,prop,angle)<EOL><DEDENT>

Draw the text.Text instance s at x,y (display coords) with font
properties instance prop at angle in degrees, using GraphicsContext gc

**backend implementers note**

When you are trying to determine if you have gotten your bounding box
right (which is what enables the text layout/alignment to work
properly), it helps to change the line in text.py

          if 0: bbox_artist(self, renderer)

to if 1, and then the actual bounding box will be blotted along with
your text.


<EOL>FigureClass = kwargs.pop('<STR_LIT>', Figure)<EOL>thisFig = FigureClass(*args, **kwargs)<EOL>canvas = FigureCanvasEMF(thisFig)<EOL>manager = FigureManagerEMF(canvas, num)<EOL>return manager<EOL>


if debugPrint: print("<STR_LIT>" % (x,y))<EOL>pen=EMFPen(self.emf,gc)<EOL>self.emf.SetPixel(int(x),int(self.height-y),(pen.r,pen.g,pen.b))<EOL>

Draw a single point at x,y
Where 'point' is a device-unit point (or pixel), not a matplotlib point


Show all the figures and enter the Cocoa mainloop.
    This function will not return until all windows are closed or
    the interpreter exits.


figManager =  Gcf.get_active()<EOL>if figManager is not None:<EOL><INDENT>figManager.canvas.invalidate()<EOL><DEDENT>

For performance reasons, we don't want to redraw the figure after
each draw command. Instead, we mark the figure as invalid, so that
it will be redrawn as soon as the event loop resumes via PyOS_InputHook.
This function should be called after each draw event, even if
matplotlib is not running interactively.


if rgbFace is None:<EOL><INDENT>fill = '<STR_LIT:none>'<EOL><DEDENT>else:<EOL><INDENT>fill = rgb2hex(rgbFace[:<NUM_LIT:3>])<EOL><DEDENT>offset, seq = gc.get_dashes()<EOL>if seq is None:<EOL><INDENT>dashes = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>dashes = '<STR_LIT>' % (<EOL>'<STR_LIT:U+002C>'.join(['<STR_LIT>'%val for val in seq]), offset)<EOL><DEDENT>linewidth = gc.get_linewidth()<EOL>if linewidth:<EOL><INDENT>return '<STR_LIT>''<STR_LIT>' % (<EOL>fill,<EOL>rgb2hex(gc.get_rgb()[:<NUM_LIT:3>]),<EOL>linewidth,<EOL>gc.get_joinstyle(),<EOL>_capstyle_d[gc.get_capstyle()],<EOL>dashes,<EOL>gc.get_alpha(),<EOL>)<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>' % (fill,<EOL>gc.get_alpha(),<EOL>)<EOL><DEDENT>

return the style string.
style is generated from the GraphicsContext, rgbFace and clippath


def _draw_mathtext(self, gc, x, y, s, prop, angle):

width, height, descent, svg_elements, used_characters =self.mathtext_parser.parse(s, <NUM_LIT>, prop)<EOL>svg_glyphs = svg_elements.svg_glyphs<EOL>svg_rects = svg_elements.svg_rects<EOL>color = rgb2hex(gc.get_rgb()[:<NUM_LIT:3>])<EOL>write = self._svgwriter.write<EOL>style = "<STR_LIT>" % color<EOL>if rcParams['<STR_LIT>']:<EOL><INDENT>new_chars = []<EOL>for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:<EOL><INDENT>path = self._add_char_def(font, thetext)<EOL>if path is not None:<EOL><INDENT>new_chars.append(path)<EOL><DEDENT><DEDENT>if len(new_chars):<EOL><INDENT>write('<STR_LIT>')<EOL>for path in new_chars:<EOL><INDENT>write(path)<EOL><DEDENT>write('<STR_LIT>')<EOL><DEDENT>svg = ['<STR_LIT>' % style]<EOL>if angle != <NUM_LIT:0>:<EOL><INDENT>svg.append('<STR_LIT>'<EOL>% (x,y,-angle) )<EOL><DEDENT>else:<EOL><INDENT>svg.append('<STR_LIT>' % (x, y))<EOL><DEDENT>svg.append('<STR_LIT>')<EOL>for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:<EOL><INDENT>charid = self._get_char_def_id(font, thetext)<EOL>svg.append('<STR_LIT>' %<EOL>(charid, new_x, -new_y_mtc, fontsize / self.FONT_SCALE))<EOL><DEDENT>svg.append('<STR_LIT>')<EOL><DEDENT>else: <EOL><INDENT>svg = ['<STR_LIT>' % (style, x, y)]<EOL>if angle != <NUM_LIT:0>:<EOL><INDENT>svg.append('<STR_LIT>'<EOL>% (x,y,-angle,-x,-y) ) <EOL><DEDENT>svg.append('<STR_LIT>')<EOL>curr_x,curr_y = <NUM_LIT:0.0>,<NUM_LIT:0.0><EOL>for font, fontsize, thetext, new_x, new_y_mtc, metrics in svg_glyphs:<EOL><INDENT>new_y = - new_y_mtc<EOL>style = "<STR_LIT>" % (fontsize, font.family_name)<EOL>svg.append('<STR_LIT>' % style)<EOL>xadvance = metrics.advance<EOL>svg.append('<STR_LIT>' % xadvance)<EOL>dx = new_x - curr_x<EOL>if dx != <NUM_LIT:0.0>:<EOL><INDENT>svg.append('<STR_LIT>' % dx)<EOL><DEDENT>dy = new_y - curr_y<EOL>if dy != <NUM_LIT:0.0>:<EOL><INDENT>svg.append('<STR_LIT>' % dy)<EOL><DEDENT>thetext = escape_xml_text(thetext)<EOL>svg.append('<STR_LIT>' % thetext)<EOL>curr_x = new_x + xadvance<EOL>curr_y = new_y<EOL><DEDENT>svg.append('<STR_LIT>')<EOL><DEDENT>if len(svg_rects):<EOL><INDENT>style = "<STR_LIT>" % color<EOL>svg.append('<STR_LIT>' % style)<EOL>if angle != <NUM_LIT:0>:<EOL><INDENT>svg.append('<STR_LIT>'<EOL>% (x,y,-angle) )<EOL><DEDENT>else:<EOL><INDENT>svg.append('<STR_LIT>' % (x, y))<EOL><DEDENT>svg.append('<STR_LIT>')<EOL>for x, y, width, height in svg_rects:<EOL><INDENT>svg.append('<STR_LIT>' % (x, -y + height, width, height))<EOL><DEDENT>svg.append("<STR_LIT>")<EOL><DEDENT>self.open_group("<STR_LIT>")<EOL>write ('<STR_LIT>'.join(svg))<EOL>self.close_group("<STR_LIT>")<EOL>

Draw math text using matplotlib.mathtext


def draw_mathtext(self, gc,<EOL>x, y, s, prop, angle):

if debugPS:<EOL><INDENT>self._pswriter.write("<STR_LIT>")<EOL><DEDENT>width, height, descent, pswriter, used_characters =self.mathtext_parser.parse(s, <NUM_LIT>, prop)<EOL>self.merge_used_characters(used_characters)<EOL>self.set_color(*gc.get_rgb())<EOL>thetext = pswriter.getvalue()<EOL>ps =

Draw the math text using matplotlib.mathtext


def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):

if debugPS: self._pswriter.write('<STR_LIT>')<EOL>write = self._pswriter.write<EOL>if rgbFace:<EOL><INDENT>if rgbFace[<NUM_LIT:0>]==rgbFace[<NUM_LIT:1>] and rgbFace[<NUM_LIT:0>]==rgbFace[<NUM_LIT:2>]:<EOL><INDENT>ps_color = '<STR_LIT>' % rgbFace[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>ps_color = '<STR_LIT>' % rgbFace<EOL><DEDENT><DEDENT>ps_cmd = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'] <EOL>ps_cmd.append(self._convert_path(marker_path, marker_trans))<EOL>if rgbFace:<EOL><INDENT>ps_cmd.extend(['<STR_LIT>', ps_color, '<STR_LIT>', '<STR_LIT>'])<EOL><DEDENT>ps_cmd.extend(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>tpath = trans.transform_path(path)<EOL>for vertices, code in tpath.iter_segments():<EOL><INDENT>if len(vertices):<EOL><INDENT>x, y = vertices[-<NUM_LIT:2>:]<EOL>ps_cmd.append("<STR_LIT>" % (x, y))<EOL><DEDENT><DEDENT>ps = '<STR_LIT:\n>'.join(ps_cmd)<EOL>self._draw_ps(ps, gc, rgbFace, fill=False, stroke=False)<EOL>

Draw the markers defined by path at each of the positions in x
and y.  path coordinates are points, x and y coords will be
transformed by the transform


s=s.replace("<STR_LIT:\\>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT:(>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT:)>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT:'>", "<STR_LIT>")<EOL>s=s.replace("<STR_LIT>", "<STR_LIT>")<EOL>s=re.sub(r"<STR_LIT>", lambda x: r"<STR_LIT>"%ord(x.group()), s)<EOL>return s<EOL>

Quote dangerous characters of S for use in a PostScript string constant.


if seq1 is None:<EOL><INDENT>return seq2 is None<EOL><DEDENT>if seq2 is None:<EOL><INDENT>return False<EOL><DEDENT>if len(seq1) != len(seq2): return False<EOL>return npy.alltrue(npy.equal(seq1, seq2))<EOL>

seq1 and seq2 are either None or sequences or numerix arrays
Return True if both are None or both are seqs with identical
elements


hatches = {'<STR_LIT>':<NUM_LIT:0>, '<STR_LIT>':<NUM_LIT:0>, '<STR_LIT>':<NUM_LIT:0>, '<STR_LIT>':<NUM_LIT:0>}<EOL>for letter in hatch:<EOL><INDENT>if   (letter == '<STR_LIT:/>'):    hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:\\>'):   hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:|>'):    hatches['<STR_LIT>']  += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:->'):    hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>elif (letter == '<STR_LIT:+>'):<EOL><INDENT>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL><DEDENT>elif (letter.lower() == '<STR_LIT:x>'):<EOL><INDENT>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL>hatches['<STR_LIT>'] += <NUM_LIT:1><EOL><DEDENT><DEDENT>def do_hatch(angle, density):<EOL><INDENT>if (density == <NUM_LIT:0>): return "<STR_LIT>"<EOL>return

hatch can be one of:
    /   - diagonal hatching
    \   - back diagonal
    |   - vertical
    -   - horizontal
    +   - crossed
    X   - crossed diagonal

letters can be combined, in which case all the specified
hatchings are done

if same letter repeats, it increases the density of hatching
in that direction


return self.width, self.height<EOL>

return the canvas width and height in display coords


return self.image_magnification<EOL>

Get the factor by which to magnify images passed to draw_image.
Allows a backend to have images at a different resolution to other
artists.


def draw_unicode(self, gc, x, y, s, prop, angle):

if rcParams['<STR_LIT>']:<EOL><INDENT>self.set_color(*gc.get_rgb())<EOL>font = self._get_font_afm(prop)<EOL>fontname = font.get_fontname()<EOL>fontsize = prop.get_size_in_points()<EOL>scale = <NUM_LIT>*fontsize<EOL>thisx = <NUM_LIT:0><EOL>thisy = font.get_str_bbox_and_descent(s)[<NUM_LIT:4>] * scale<EOL>last_name = None<EOL>lines = []<EOL>for c in s:<EOL><INDENT>name = uni2type1.get(ord(c), '<STR_LIT>')<EOL>try:<EOL><INDENT>width = font.get_width_from_char_name(name)<EOL><DEDENT>except KeyError:<EOL><INDENT>name = '<STR_LIT>'<EOL>width = font.get_width_char('<STR_LIT:?>')<EOL><DEDENT>if last_name is not None:<EOL><INDENT>kern = font.get_kern_dist_from_name(last_name, name)<EOL><DEDENT>else:<EOL><INDENT>kern = <NUM_LIT:0><EOL><DEDENT>last_name = name<EOL>thisx += kern * scale<EOL>lines.append('<STR_LIT>'%(thisx, thisy, name))<EOL>thisx += width * scale<EOL><DEDENT>thetext = "<STR_LIT:\n>".join(lines)<EOL>ps = """<STR_LIT>"""gsave<EOL><DEDENT>y)f translate<EOL>f rotate<EOL>t)s<EOL>cals()<EOL>self._pswriter.write(ps)<EOL>

draw a unicode string.  ps doesn't have unicode support, so
        we have to do this the hard way


try: del self.observers[cid]<EOL>except KeyError: pass<EOL>

remove the observer with connection id cid


if self.useblit:<EOL><INDENT>if self.background is not None:<EOL><INDENT>self.canvas.restore_region(self.background)<EOL><DEDENT>self.ax.draw_artist(self.rect)<EOL>self.canvas.blit(self.ax.bbox)<EOL><DEDENT>else:<EOL><INDENT>self.canvas.draw_idle()<EOL><DEDENT>return False<EOL>

draw using newfangled blit or oldfangled draw depending on useblit


return self._owner is o<EOL>


<EOL>if not self.active:<EOL><INDENT>return True<EOL><DEDENT>if not self.canvas.widgetlock.available(self):<EOL><INDENT>return True<EOL><DEDENT>if self.eventpress == None:<EOL><INDENT>return event.inaxes!= self.ax<EOL><DEDENT>return  (event.inaxes!=self.ax or<EOL>event.button != self.eventpress.button)<EOL>


cid = self.cnt<EOL>self.observers[cid] = func<EOL>self.cnt += <NUM_LIT:1><EOL>return cid<EOL>

When the button is clicked, call this func with button label

A connection id is returned which can be used to disconnect


if event.button !=<NUM_LIT:1>: return<EOL>if event.inaxes != self.ax: return<EOL>val = event.xdata<EOL>if not self.closedmin and val<=self.valmin: return<EOL>if not self.closedmax and val>=self.valmax: return<EOL>if self.slidermin is not None:<EOL><INDENT>if val<=self.slidermin.val: return<EOL><DEDENT>if self.slidermax is not None:<EOL><INDENT>if val>=self.slidermax.val: return<EOL><DEDENT>self.set_val(val)<EOL>


if self.useblit:<EOL><INDENT>if self.background is not None:<EOL><INDENT>self.canvas.restore_region(self.background)<EOL><DEDENT>self.ax.draw_artist(self.to_draw)<EOL>self.canvas.blit(self.ax.bbox)<EOL><DEDENT>else:<EOL><INDENT>self.canvas.draw_idle()<EOL><DEDENT>return False<EOL>


if self.ignore(event): return<EOL>self.buttonDown = True<EOL>self.rect.set_visible(self.visible)<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>self.pressv = event.xdata<EOL><DEDENT>else:<EOL><INDENT>self.pressv = event.ydata<EOL><DEDENT>return False<EOL>


if not self.available(o):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._owner = o<EOL>


if self.pressv is None or self.ignore(event): return<EOL>x, y = event.xdata, event.ydata<EOL>self.prev = x, y<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>v = x<EOL><DEDENT>else:<EOL><INDENT>v = y<EOL><DEDENT>minv, maxv = v, self.pressv<EOL>if minv>maxv: minv, maxv = maxv, minv<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>self.rect.set_x(minv)<EOL>self.rect.set_width(maxv-minv)<EOL><DEDENT>else:<EOL><INDENT>self.rect.set_y(minv)<EOL>self.rect.set_height(maxv-minv)<EOL><DEDENT>if self.onmove_callback is not None:<EOL><INDENT>vmin = self.pressv<EOL>if self.direction == '<STR_LIT>':<EOL><INDENT>vmax = event.xdata or self.prev[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>vmax = event.ydata or self.prev[<NUM_LIT:1>]<EOL><DEDENT>if vmin>vmax: vmin, vmax = vmax, vmin<EOL>self.onmove_callback(vmin, vmax)<EOL><DEDENT>self.update()<EOL>return False<EOL>


def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None):

if rectprops is None:<EOL><INDENT>rectprops = dict(facecolor='<STR_LIT>', alpha=<NUM_LIT:0.5>)<EOL><DEDENT>assert direction in ['<STR_LIT>', '<STR_LIT>'], '<STR_LIT>'<EOL>self.direction = direction<EOL>self.ax = None<EOL>self.canvas = None<EOL>self.visible = True<EOL>self.cids=[]<EOL>self.rect = None<EOL>self.background = None<EOL>self.pressv = None<EOL>self.rectprops = rectprops<EOL>self.onselect = onselect<EOL>self.onmove_callback = onmove_callback<EOL>self.useblit = useblit<EOL>self.minspan = minspan<EOL>self.buttonDown = False<EOL>self.prev = (<NUM_LIT:0>, <NUM_LIT:0>)<EOL>self.new_axes(ax)<EOL>

Create a span selector in ax.  When a selection is made, clear
the span and call onselect with

  onselect(vmin, vmax)

and clear the span.

direction must be 'horizontal' or 'vertical'

If minspan is not None, ignore events smaller than minspan

The span rect is drawn with rectprops; default
  rectprops = dict(facecolor='red', alpha=0.5)

set the visible attribute to False if you want to turn off
the functionality of the span selector


return self.active<EOL>

to get status of active mode (boolean variable)


def __init__(self, ax, label, valmin, valmax, valinit=<NUM_LIT:0.5>, valfmt='<STR_LIT>',<EOL>closedmin=True, closedmax=True, slidermin=None, slidermax=None,<EOL>dragging=True, **kwargs):

self.ax = ax<EOL>self.valmin = valmin<EOL>self.valmax = valmax<EOL>self.val = valinit<EOL>self.valinit = valinit<EOL>self.poly = ax.axvspan(valmin,valinit,<NUM_LIT:0>,<NUM_LIT:1>, **kwargs)<EOL>self.vline = ax.axvline(valinit,<NUM_LIT:0>,<NUM_LIT:1>, color='<STR_LIT:r>', lw=<NUM_LIT:1>)<EOL>self.valfmt=valfmt<EOL>ax.set_yticks([])<EOL>ax.set_xlim((valmin, valmax))<EOL>ax.set_xticks([])<EOL>ax.set_navigate(False)<EOL>ax.figure.canvas.mpl_connect('<STR_LIT>', self._update)<EOL>if dragging:<EOL><INDENT>ax.figure.canvas.mpl_connect('<STR_LIT>', self._update)<EOL><DEDENT>self.label = ax.text(-<NUM_LIT>, <NUM_LIT:0.5>, label, transform=ax.transAxes,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:right>')<EOL>self.valtext = ax.text(<NUM_LIT>, <NUM_LIT:0.5>, valfmt%valinit,<EOL>transform=ax.transAxes,<EOL>verticalalignment='<STR_LIT>',<EOL>horizontalalignment='<STR_LIT:left>')<EOL>self.cnt = <NUM_LIT:0><EOL>self.observers = {}<EOL>self.closedmin = closedmin<EOL>self.closedmax = closedmax<EOL>self.slidermin = slidermin<EOL>self.slidermax = slidermax<EOL>

Create a slider from valmin to valmax in axes ax;

valinit -  the slider initial position

label - the slider label

valfmt - used to format the slider value

closedmin and closedmax - indicate whether the slider interval is closed

slidermin and slidermax - be used to contrain the value of
  this slider to the values of other sliders.

additional kwargs are passed on to self.poly which is the
matplotlib.patches.Rectangle which draws the slider.  See the
matplotlib.patches.Rectangle documentation for legal property
names (eg facecolor, edgecolor, alpha, ...)


self.targetfig = targetfig<EOL>toolfig.subplots_adjust(left=<NUM_LIT>, right=<NUM_LIT>)<EOL>class toolbarfmt:<EOL><INDENT>def __init__(self, slider):<EOL><INDENT>self.slider = slider<EOL><DEDENT>def __call__(self, x, y):<EOL><INDENT>fmt = '<STR_LIT>'%(self.slider.label.get_text(), self.slider.valfmt)<EOL>return fmt%x<EOL><DEDENT><DEDENT>self.axleft = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axleft.set_title('<STR_LIT>')<EOL>self.axleft.set_navigate(False)<EOL>self.sliderleft = Slider(self.axleft, '<STR_LIT:left>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.left, closedmax=False)<EOL>self.sliderleft.on_changed(self.funcleft)<EOL>self.axbottom = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axbottom.set_navigate(False)<EOL>self.sliderbottom = Slider(self.axbottom, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.bottom, closedmax=False)<EOL>self.sliderbottom.on_changed(self.funcbottom)<EOL>self.axright = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axright.set_navigate(False)<EOL>self.sliderright = Slider(self.axright, '<STR_LIT:right>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.right, closedmin=False)<EOL>self.sliderright.on_changed(self.funcright)<EOL>self.axtop = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axtop.set_navigate(False)<EOL>self.slidertop = Slider(self.axtop, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.top, closedmin=False)<EOL>self.slidertop.on_changed(self.functop)<EOL>self.axwspace = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axwspace.set_navigate(False)<EOL>self.sliderwspace = Slider(self.axwspace, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.wspace, closedmax=False)<EOL>self.sliderwspace.on_changed(self.funcwspace)<EOL>self.axhspace = toolfig.add_subplot(<NUM_LIT>)<EOL>self.axhspace.set_navigate(False)<EOL>self.sliderhspace = Slider(self.axhspace, '<STR_LIT>', <NUM_LIT:0>, <NUM_LIT:1>, targetfig.subplotpars.hspace, closedmax=False)<EOL>self.sliderhspace.on_changed(self.funchspace)<EOL>self.sliderleft.slidermax = self.sliderright<EOL>self.sliderright.slidermin = self.sliderleft<EOL>self.sliderbottom.slidermax = self.slidertop<EOL>self.slidertop.slidermin = self.sliderbottom<EOL>bax = toolfig.add_axes([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])<EOL>self.buttonreset = Button(bax, '<STR_LIT>')<EOL>sliders = (self.sliderleft, self.sliderbottom, self.sliderright,<EOL>self.slidertop, self.sliderwspace, self.sliderhspace, )<EOL>def func(event):<EOL><INDENT>thisdrawon = self.drawon<EOL>self.drawon = False<EOL>bs = []<EOL>for slider in sliders:<EOL><INDENT>bs.append(slider.drawon)<EOL>slider.drawon = False<EOL><DEDENT>for slider in sliders:<EOL><INDENT>slider.reset()<EOL><DEDENT>for slider, b in zip(sliders, bs):<EOL><INDENT>slider.drawon = b<EOL><DEDENT>self.drawon = thisdrawon<EOL>if self.drawon:<EOL><INDENT>toolfig.canvas.draw()<EOL>self.targetfig.canvas.draw()<EOL><DEDENT><DEDENT>validate = toolfig.subplotpars.validate<EOL>toolfig.subplotpars.validate = False<EOL>self.buttonreset.on_clicked(func)<EOL>toolfig.subplotpars.validate = validate<EOL>

targetfig is the figure to adjust

toolfig is the figure to embed the the subplot tool into.  If
None, a default pylab figure will be created.  If you are
using this from the GUI


self.active = active<EOL>

Use this to activate / deactivate the RectangleSelector

            from your program with an boolean variable 'active'.


if self.eventpress is None or self.ignore(event): return<EOL>self.to_draw.set_visible(False)<EOL>self.canvas.draw()<EOL>self.eventrelease = event<EOL>if self.spancoords=='<STR_LIT:data>':<EOL><INDENT>xmin, ymin = self.eventpress.xdata, self.eventpress.ydata<EOL>xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata<EOL><DEDENT>elif self.spancoords=='<STR_LIT>':<EOL><INDENT>xmin, ymin = self.eventpress.x, self.eventpress.y<EOL>xmax, ymax = self.eventrelease.x, self.eventrelease.y<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if xmin>xmax: xmin, xmax = xmax, xmin<EOL>if ymin>ymax: ymin, ymax = ymax, ymin<EOL>spanx = xmax - xmin<EOL>spany = ymax - ymin<EOL>xproblems = self.minspanx is not None and spanx<self.minspanx<EOL>yproblems = self.minspany is not None and spany<self.minspany<EOL>if (self.drawtype=='<STR_LIT>')  and (xproblems or  yproblems):<EOL><INDENT>"""<STR_LIT>"""     <EOL>return                 <EOL><DEDENT>if (self.drawtype=='<STR_LIT>') and (xproblems and yproblems):<EOL><INDENT>"""<STR_LIT>"""    <EOL>return                 <EOL><DEDENT>self.onselect(self.eventpress, self.eventrelease)<EOL>self.eventpress = None                <EOL>self.eventrelease = None              <EOL>return False<EOL>


fonttypes = { '<STR_LIT>':    <NUM_LIT:3>,<EOL>'<STR_LIT>': <NUM_LIT> }<EOL>try:<EOL><INDENT>fonttype = validate_int(s)<EOL><DEDENT>except ValueError:<EOL><INDENT>if s.lower() in list(fonttypes.keys()):<EOL><INDENT>return fonttypes[s.lower()]<EOL><DEDENT>raise ValueError('<STR_LIT>' % list(fonttypes.keys()))<EOL><DEDENT>else:<EOL><INDENT>if fonttype not in list(fonttypes.values()):<EOL><INDENT>raise ValueError('<STR_LIT>' % list(fonttypes.values()))<EOL><DEDENT>return fonttype<EOL><DEDENT>

confirm that this is a Postscript of PDF font type that we know how to convert to


try: return int(s)<EOL>except ValueError:<EOL><INDENT>raise ValueError('<STR_LIT>' % s)<EOL><DEDENT>


if type(b) is str:<EOL><INDENT>b = b.lower()<EOL><DEDENT>if b=='<STR_LIT:none>': return None<EOL>if b in ('<STR_LIT:t>', '<STR_LIT:y>', '<STR_LIT:yes>', '<STR_LIT>', '<STR_LIT:true>', '<STR_LIT:1>', <NUM_LIT:1>, True): return True<EOL>elif b in ('<STR_LIT:f>', '<STR_LIT:n>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:false>', '<STR_LIT:0>', <NUM_LIT:0>, False): return False<EOL>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % b)<EOL><DEDENT>


if type(s) is str:<EOL><INDENT>return [ v.strip() for v in s.split('<STR_LIT:U+002C>') ]<EOL><DEDENT>else:<EOL><INDENT>assert type(s) in [list,tuple]<EOL>return [ str(v) for v in s ]<EOL><DEDENT>


if os.path.exists(s): return s<EOL>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>'%s)<EOL><DEDENT>


raise NotImplementedError('<STR_LIT>')<EOL>

Deprecated - needs clean room implementation