desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Create a metadata provider from a zipimporter'
| def __init__(self, importer):
| self.zipinfo = zipimport._zip_directory_cache[importer.archive]
self.zip_pre = (importer.archive + os.sep)
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
else:
self.module_path = importer.archive
self._setup_prefix()
|
'Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional'
| def parse(cls, src, dist=None):
| try:
attrs = extras = ()
(name, value) = src.split('=', 1)
if ('[' in value):
(value, extras) = value.split('[', 1)
req = Requirement.parse(('x[' + extras))
if req.specs:
raise ValueError
extras = req.extras
if (':' in v... |
'Parse an entry point group'
| def parse_group(cls, group, lines, dist=None):
| if (not MODULE(group)):
raise ValueError('Invalid group name', group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if (ep.name in this):
raise ValueError('Duplicate entry point', group, ep.name)
this[ep.name] = ep
return thi... |
'Parse a map of entry point groups'
| def parse_map(cls, data, dist=None):
| if isinstance(data, dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for (group, lines) in data:
if (group is None):
if (not lines):
continue
raise ValueError('Entry points must be listed in groups')
... |
'List of Requirements needed for this distro if `extras` are used'
| def requires(self, extras=()):
| dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(('%s has no such extra feature %r' % (self, ext)))
return deps
|
'Ensure distribution is importable on `path` (default=sys.path)'
| def activate(self, path=None):
| if (path is None):
path = sys.path
self.insert_on(path)
if (path is sys.path):
fixup_namespace_packages(self.location)
map(declare_namespace, self._get_metadata('namespace_packages.txt'))
|
'Return what this distribution\'s standard .egg filename should be'
| def egg_name(self):
| filename = ('%s-%s-py%s' % (to_filename(self.project_name), to_filename(self.version), (self.py_version or PY_MAJOR)))
if self.platform:
filename += ('-' + self.platform)
return filename
|
'Delegate all unrecognized public attributes to .metadata provider'
| def __getattr__(self, attr):
| if attr.startswith('_'):
raise AttributeError, attr
return getattr(self._provider, attr)
|
'Return a ``Requirement`` that matches this distribution exactly'
| def as_requirement(self):
| return Requirement.parse(('%s==%s' % (self.project_name, self.version)))
|
'Return the `name` entry point of `group` or raise ImportError'
| def load_entry_point(self, group, name):
| ep = self.get_entry_info(group, name)
if (ep is None):
raise ImportError(('Entry point %r not found' % ((group, name),)))
return ep.load()
|
'Return the entry point map for `group`, or the full entry map'
| def get_entry_map(self, group=None):
| try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(self._get_metadata('entry_points.txt'), self)
if (group is not None):
return ep_map.get(group, {})
return ep_map
|
'Return the EntryPoint object for `group`+`name`, or ``None``'
| def get_entry_info(self, group, name):
| return self.get_entry_map(group).get(name)
|
'Insert self.location in path before its nearest parent directory'
| def insert_on(self, path, loc=None):
| loc = (loc or self.location)
if (not loc):
return
if (path is sys.path):
self.check_version_conflict()
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
npath = map(_normalize_cached, path)
bp = None
for (p, item) in enumerate(npath):
if (item == nloc):
... |
'Copy this distribution, substituting in any changed keyword args'
| def clone(self, **kw):
| for attr in ('project_name', 'version', 'py_version', 'platform', 'location', 'precedence'):
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provider)
return self.__class__(**kw)
|
'DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!'
| def __init__(self, project_name, specs, extras):
| (self.unsafe_name, project_name) = (project_name, safe_name(project_name))
(self.project_name, self.key) = (project_name, project_name.lower())
index = [(parse_version(v), state_machine[op], op, v) for (op, v) in specs]
index.sort()
self.specs = [(op, ver) for (parsed, trans, op, ver) in index]
... |
'call signature::
clabel(cs, **kwargs)
adds labels to line contours in *cs*, where *cs* is a
:class:`~matplotlib.contour.ContourSet` object returned by
contour.
clabel(cs, v, **kwargs)
only labels contours listed in *v*.
Optional keyword arguments:
*fontsize*:
See http://matplotlib.sf.net/fonts.html
*colors*:
- if *Non... | def clabel(self, *args, **kwargs):
| '\n NOTES on how this all works:\n\n clabel basically takes the input arguments and uses them to\n add a list of "label specific" attributes to the Contou... |
'if contours are too short, don\'t plot a label'
| def print_label(self, linecontour, labelwidth):
| lcsize = len(linecontour)
if (lcsize > (10 * labelwidth)):
return 1
xmax = np.amax(linecontour[:, 0])
xmin = np.amin(linecontour[:, 0])
ymax = np.amax(linecontour[:, 1])
ymin = np.amin(linecontour[:, 1])
lw = labelwidth
if (((xmax - xmin) > (1.2 * lw)) or ((ymax - ymin) > (1.2 * ... |
'if there\'s a label already nearby, find a better place'
| def too_close(self, x, y, lw):
| if (self.labelXYs != []):
dist = [np.sqrt((((x - loc[0]) ** 2) + ((y - loc[1]) ** 2))) for loc in self.labelXYs]
for d in dist:
if (d < (1.2 * lw)):
return 1
else:
return 0
else:
return 0
|
'labels are ploted at a location with the smallest
dispersion of the contour from a straight line
unless there\'s another label nearby, in which case
the second best place on the contour is picked up
if there\'s no good place a label isplotted at the
beginning of the contour'
| def get_label_coords(self, distances, XX, YY, ysize, lw):
| hysize = int((ysize / 2))
adist = np.argsort(distances)
for ind in adist:
(x, y) = (XX[ind][hysize], YY[ind][hysize])
if self.too_close(x, y, lw):
continue
else:
return (x, y, ind)
ind = adist[0]
(x, y) = (XX[ind][hysize], YY[ind][hysize])
return (... |
'get the width of the label in points'
| def get_label_width(self, lev, fmt, fsize):
| if cbook.is_string_like(lev):
lw = (len(lev) * fsize)
else:
lw = (len(self.get_text(lev, fmt)) * fsize)
return lw
|
'This computes actual onscreen label width.
This uses some black magic to determine onscreen extent of non-drawn
label. This magic may not be very robust.'
| def get_real_label_width(self, lev, fmt, fsize):
| xx = np.mean(np.asarray(self.ax.axis()).reshape(2, 2), axis=1)
t = text.Text(xx[0], xx[1])
self.set_label_props(t, self.get_text(lev, fmt), 'k')
bbox = t.get_window_extent(renderer=self.ax.figure.canvas.renderer)
lw = np.diff(bbox.corners()[0::2, 0])[0]
return lw
|
'set the label properties - color, fontsize, text'
| def set_label_props(self, label, text, color):
| label.set_text(text)
label.set_color(color)
label.set_fontproperties(self.labelFontProps)
label.set_clip_box(self.ax.bbox)
|
'get the text of the label'
| def get_text(self, lev, fmt):
| if cbook.is_string_like(lev):
return lev
elif isinstance(fmt, dict):
return fmt[lev]
else:
return (fmt % lev)
|
'find a good place to plot a label (relatively flat
part of the contour) and the angle of rotation for the
text object'
| def locate_label(self, linecontour, labelwidth):
| nsize = len(linecontour)
if (labelwidth > 1):
xsize = int(np.ceil((nsize / labelwidth)))
else:
xsize = 1
if (xsize == 1):
ysize = nsize
else:
ysize = labelwidth
XX = np.resize(linecontour[:, 0], (xsize, ysize))
YY = np.resize(linecontour[:, 1], (xsize, ysize))... |
'This function calculates the appropriate label rotation given
the linecontour coordinates in screen units, the index of the
label location and the label width.
It will also break contour and calculate inlining if *lc* is
not empty (lc defaults to the empty list if None). *spacing*
is the space around the label in pix... | def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5):
| if (lc is None):
lc = []
hlw = (lw / 2.0)
closed = mlab.is_closed_polygon(slc)
if closed:
slc = np.r_[(slc[ind:(-1)], slc[:(ind + 1)])]
if len(lc):
lc = np.r_[(lc[ind:(-1)], lc[:(ind + 1)])]
ind = 0
pl = mlab.path_length(slc)
pl = (pl - pl[ind])
xi... |
'Defaults to removing last label, but any index can be supplied'
| def pop_label(self, index=(-1)):
| self.labelCValues.pop(index)
t = self.labelTexts.pop(index)
t.remove()
|
'Draw contour lines or filled regions, depending on
whether keyword arg \'filled\' is False (default) or True.
The first argument of the initializer must be an axes
object. The remaining arguments and keyword arguments
are described in ContourSet.contour_doc.'
| def __init__(self, ax, *args, **kwargs):
| self.ax = ax
self.levels = kwargs.get('levels', None)
self.filled = kwargs.get('filled', False)
self.linewidths = kwargs.get('linewidths', None)
self.linestyles = kwargs.get('linestyles', 'solid')
self.alpha = kwargs.get('alpha', 1.0)
self.origin = kwargs.get('origin', None)
self.extent ... |
'Select contour levels to span the data.
We need two more levels for filled contours than for
line contours, because for the latter we need to specify
the lower and upper boundary of each range. For example,
a single contour boundary, say at z = 0, requires only
one contour line, but two filled regions, and therefore
t... | def _autolev(self, z, N):
| if (self.locator is None):
if self.logscale:
self.locator = ticker.LogLocator()
else:
self.locator = ticker.MaxNLocator((N + 1))
self.locator.create_dummy_axis()
zmax = self.zmax
zmin = self.zmin
self.locator.set_bounds(zmin, zmax)
lev = self.locator()
... |
'Return X, Y arrays such that contour(Z) will match imshow(Z)
if origin is not None.
The center of pixel Z[i,j] depends on origin:
if origin is None, x = j, y = i;
if origin is \'lower\', x = j + 0.5, y = i + 0.5;
if origin is \'upper\', x = j + 0.5, y = Nrows - i - 0.5
If extent is not None, x and y will be scaled to ... | def _initialize_x_y(self, z):
| if (z.ndim != 2):
raise TypeError('Input must be a 2D array.')
else:
(Ny, Nx) = z.shape
if (self.origin is None):
if (self.extent is None):
return np.meshgrid(np.arange(Nx), np.arange(Ny))
else:
(x0, x1, y0, y1) = self.extent
... |
'For functions like contour, check that the dimensions
of the input arrays match; if x and y are 1D, convert
them to 2D using meshgrid.
Possible change: I think we should make and use an ArgumentError
Exception class (here and elsewhere).'
| def _check_xyz(self, args):
| x = self.ax.convert_xunits(args[0])
y = self.ax.convert_yunits(args[1])
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
z = ma.asarray(args[2], dtype=np.float64)
if (z.ndim != 2):
raise TypeError('Input z must be a 2D array.')
else:
(... |
'Color argument processing for contouring.
Note that we base the color mapping on the contour levels,
not on the actual range of the Z values. This means we
don\'t have to worry about bad values in Z, and we always have
the full dynamic range available for the selected levels.
The color is based on the midpoint of the... | def _process_colors(self):
| self.monochrome = self.cmap.monochrome
if (self.colors is not None):
(i0, i1) = (0, len(self.layers))
if (self.extend in ('both', 'min')):
i0 = (-1)
if (self.extend in ('both', 'max')):
i1 = (i1 + 1)
self.cvalues = range(i0, i1)
self.set_norm(color... |
'returns alpha to be applied to all ContourSet artists'
| def get_alpha(self):
| return self.alpha
|
'sets alpha for all ContourSet artists'
| def set_alpha(self, alpha):
| self.alpha = alpha
self.changed()
|
'Finds contour that is closest to a point. Defaults to
measuring distance in pixels (screen space - useful for manual
contour labeling), but this can be controlled via a keyword
argument.
Returns a tuple containing the contour, segment, index of
segment, x & y of segment point and distance to minimum point.
Call signa... | def find_nearest_contour(self, x, y, indices=None, pixel=True):
| if (indices == None):
indices = range(len(self.levels))
dmin = 10000000000.0
conmin = None
segmin = None
xmin = None
ymin = None
for icon in indices:
con = self.collections[icon]
paths = con.get_paths()
for (segNum, linepath) in enumerate(paths):
l... |
'returns a filename based on a hash of the string, fontsize, and dpi'
| def get_basefile(self, tex, fontsize, dpi=None):
| s = ''.join([tex, self.get_font_config(), ('%f' % fontsize), self.get_custom_preamble(), str((dpi or ''))])
bytes = unicode(s).encode('utf-8')
return os.path.join(self.texcache, md5(bytes).hexdigest())
|
'Reinitializes self if relevant rcParams on have changed.'
| def get_font_config(self):
| if (self._rc_cache is None):
self._rc_cache = dict([(k, None) for k in self._rc_cache_keys])
changed = [par for par in self._rc_cache_keys if (rcParams[par] != self._rc_cache[par])]
if changed:
if DEBUG:
print 'DEBUG following keys changed:', changed
for k in cha... |
'returns a string containing font configuration for the tex preamble'
| def get_font_preamble(self):
| return self._font_preamble
|
'returns a string containing user additions to the tex preamble'
| def get_custom_preamble(self):
| return '\n'.join(rcParams['text.latex.preamble'])
|
'On windows, changing directories can be complicated by the presence of
multiple drives. get_shell_cmd deals with this issue.'
| def _get_shell_cmd(self, *args):
| if (sys.platform == 'win32'):
command = [('%s' % os.path.splitdrive(self.texcache)[0])]
else:
command = []
command.extend(args)
return ' && '.join(command)
|
'Generate a tex file to render the tex string at a specific font size
returns the file name'
| def make_tex(self, tex, fontsize):
| basefile = self.get_basefile(tex, fontsize)
texfile = ('%s.tex' % basefile)
fh = file(texfile, 'w')
custom_preamble = self.get_custom_preamble()
fontcmd = {'sans-serif': '{\\sffamily %s}', 'monospace': '{\\ttfamily %s}'}.get(self.font_family, '{\\rmfamily %s}')
tex = (fontcmd % tex)
... |
'generates a dvi file containing latex\'s layout of tex string
returns the file name'
| def make_dvi(self, tex, fontsize):
| basefile = self.get_basefile(tex, fontsize)
dvifile = ('%s.dvi' % basefile)
if (DEBUG or (not os.path.exists(dvifile))):
texfile = self.make_tex(tex, fontsize)
outfile = (basefile + '.output')
command = self._get_shell_cmd(('cd "%s"' % self.texcache), ('latex -interaction=nonst... |
'generates a png file containing latex\'s rendering of tex string
returns the filename'
| def make_png(self, tex, fontsize, dpi):
| basefile = self.get_basefile(tex, fontsize, dpi)
pngfile = ('%s.png' % basefile)
if (DEBUG or (not os.path.exists(pngfile))):
dvifile = self.make_dvi(tex, fontsize)
outfile = (basefile + '.output')
command = self._get_shell_cmd(('cd "%s"' % self.texcache), ('dvipng -bg Trans... |
'generates a postscript file containing latex\'s rendering of tex string
returns the file name'
| def make_ps(self, tex, fontsize):
| basefile = self.get_basefile(tex, fontsize)
psfile = ('%s.epsf' % basefile)
if (DEBUG or (not os.path.exists(psfile))):
dvifile = self.make_dvi(tex, fontsize)
outfile = (basefile + '.output')
command = self._get_shell_cmd(('cd "%s"' % self.texcache), ('dvips -q -E -o "... |
'returns a list containing the postscript bounding box for latex\'s
rendering of the tex string'
| def get_ps_bbox(self, tex, fontsize):
| psfile = self.make_ps(tex, fontsize)
ps = file(psfile)
for line in ps:
if line.startswith('%%BoundingBox:'):
return [int(val) for val in line.split()[1:]]
raise RuntimeError(('Could not parse %s' % psfile))
|
'returns the alpha channel'
| def get_grey(self, tex, fontsize=None, dpi=None):
| key = (tex, self.get_font_config(), fontsize, dpi)
alpha = self.grey_arrayd.get(key)
if (alpha is None):
pngfile = self.make_png(tex, fontsize, dpi)
X = read_png(os.path.join(self.texcache, pngfile))
if (rcParams['text.dvipnghack'] is not None):
hack = rcParams['text.dvip... |
'Returns latex\'s rendering of the tex string as an rgba array'
| def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
| if (not fontsize):
fontsize = rcParams['font.size']
if (not dpi):
dpi = rcParams['savefig.dpi']
(r, g, b) = rgb
key = (tex, self.get_font_config(), fontsize, dpi, tuple(rgb))
Z = self.rgba_arrayd.get(key)
if (Z is None):
alpha = self.get_grey(tex, fontsize, dpi)
Z... |
'Return the cell Text intance'
| def get_text(self):
| return self._text
|
'Return the cell fontsize'
| def get_fontsize(self):
| return self._text.get_fontsize()
|
'Shrink font size until text fits.'
| def auto_set_font_size(self, renderer):
| fontsize = self.get_fontsize()
required = self.get_required_width(renderer)
while ((fontsize > 1) and (required > self.get_width())):
fontsize -= 1
self.set_fontsize(fontsize)
required = self.get_required_width(renderer)
return fontsize
|
'Set text up so it draws in the right place.
Currently support \'left\', \'center\' and \'right\''
| def _set_text_position(self, renderer):
| bbox = self.get_window_extent(renderer)
(l, b, w, h) = bbox.bounds
self._text.set_verticalalignment('center')
y = (b + (h / 2.0))
if (self._loc == 'center'):
self._text.set_horizontalalignment('center')
x = (l + (w / 2.0))
elif (self._loc == 'left'):
self._text.set_horizo... |
'Get text bounds in axes co-ordinates.'
| def get_text_bounds(self, renderer):
| bbox = self._text.get_window_extent(renderer)
bboxa = bbox.inverse_transformed(self.get_data_transform())
return bboxa.bounds
|
'Get width required for this cell.'
| def get_required_width(self, renderer):
| (l, b, w, h) = self.get_text_bounds(renderer)
return (w * (1.0 + (2.0 * self.PAD)))
|
'update the text properties with kwargs'
| def set_text_props(self, **kwargs):
| self._text.update(kwargs)
|
'Add a cell to the table.'
| def add_cell(self, row, col, *args, **kwargs):
| xy = (0, 0)
cell = Cell(xy, *args, **kwargs)
cell.set_figure(self.figure)
cell.set_transform(self.get_transform())
cell.set_clip_on(False)
self._cells[(row, col)] = cell
|
'Get a bbox, in axes co-ordinates for the cells.
Only include those in the range (0,0) to (maxRow, maxCol)'
| def _get_grid_bbox(self, renderer):
| boxes = [self._cells[pos].get_window_extent(renderer) for pos in self._cells.keys() if ((pos[0] >= 0) and (pos[1] >= 0))]
bbox = Bbox.union(boxes)
return bbox.inverse_transformed(self.get_transform())
|
'Test whether the mouse event occurred in the table.
Returns T/F, {}'
| def contains(self, mouseevent):
| if callable(self._contains):
return self._contains(self, mouseevent)
if (self._cachedRenderer is not None):
boxes = [self._cells[pos].get_window_extent(self._cachedRenderer) for pos in self._cells.keys() if ((pos[0] >= 0) and (pos[1] >= 0))]
bbox = bbox_all(boxes)
return (bbox.co... |
'Return the Artists contained by the table'
| def get_children(self):
| return self._cells.values()
|
'Return the bounding box of the table in window coords'
| def get_window_extent(self, renderer):
| boxes = [c.get_window_extent(renderer) for c in self._cells]
return bbox_all(boxes)
|
'Calculate row heights and column widths.
Position cells accordingly.'
| def _do_cell_alignment(self):
| widths = {}
heights = {}
for ((row, col), cell) in self._cells.iteritems():
height = heights.setdefault(row, 0.0)
heights[row] = max(height, cell.get_height())
width = widths.setdefault(col, 0.0)
widths[col] = max(width, cell.get_width())
xpos = 0
lefts = {}
cols ... |
'Automagically set width for column.'
| def _auto_set_column_width(self, col, renderer):
| cells = [key for key in self._cells if (key[1] == col)]
width = 0
for cell in cells:
c = self._cells[cell]
width = max(c.get_required_width(renderer), width)
for cell in cells:
self._cells[cell].set_width(width)
|
'Automatically set font size.'
| def auto_set_font_size(self, value=True):
| self._autoFontsize = value
|
'Scale column widths by xscale and row heights by yscale.'
| def scale(self, xscale, yscale):
| for c in self._cells.itervalues():
c.set_width((c.get_width() * xscale))
c.set_height((c.get_height() * yscale))
|
'Set the fontsize of the cell text
ACCEPTS: a float in points'
| def set_fontsize(self, size):
| for cell in self._cells.itervalues():
cell.set_fontsize(size)
|
'Move all the artists by ox,oy (axes coords)'
| def _offset(self, ox, oy):
| for c in self._cells.itervalues():
(x, y) = (c.get_x(), c.get_y())
c.set_x((x + ox))
c.set_y((y + oy))
|
'return a dict of cells in the table'
| def get_celld(self):
| return self._cells
|
'Generate index array that picks out unique x,y points.
This appears to be required by the underlying delaunay triangulation
code.'
| def _collapse_duplicate_points(self):
| j_sorted = np.lexsort(keys=(self.x, self.y))
mask_unique = np.hstack([True, ((np.diff(self.x[j_sorted]) != 0) | (np.diff(self.y[j_sorted]) != 0))])
return j_sorted[mask_unique]
|
'Extract the convex hull from the triangulation information.
The output will be a list of point_id\'s in counter-clockwise order
forming the convex hull of the data set.'
| def _compute_convex_hull(self):
| border = (self.triangle_neighbors == (-1))
edges = {}
edges.update(dict(zip(self.triangle_nodes[border[:, 0]][:, 1], self.triangle_nodes[border[:, 0]][:, 2])))
edges.update(dict(zip(self.triangle_nodes[border[:, 1]][:, 2], self.triangle_nodes[border[:, 1]][:, 0])))
edges.update(dict(zip(self.triangl... |
'Get an object which can interpolate within the convex hull by
assigning a plane to each triangle.
z -- an array of floats giving the known function values at each point
in the triangulation.'
| def linear_interpolator(self, z, default_value=np.nan):
| z = np.asarray(z, dtype=np.float64)
if (z.shape != self.old_shape):
raise ValueError('z must be the same shape as x and y')
if (self.j_unique is not None):
z = z[self.j_unique]
return LinearInterpolator(self, z, default_value)
|
'Get an object which can interpolate within the convex hull by
the natural neighbors method.
z -- an array of floats giving the known function values at each point
in the triangulation.'
| def nn_interpolator(self, z, default_value=np.nan):
| z = np.asarray(z, dtype=np.float64)
if (z.shape != self.old_shape):
raise ValueError('z must be the same shape as x and y')
if (self.j_unique is not None):
z = z[self.j_unique]
return NNInterpolator(self, z, default_value)
|
'Return a graph of node_id\'s pointing to node_id\'s.
The arcs of the graph correspond to the edges in the triangulation.
{node_id: set([node_id, ...]), ...}'
| def node_graph(self):
| g = {}
for (i, j) in self.edge_db:
s = g.setdefault(i, set())
s.add(j)
s = g.setdefault(j, set())
s.add(i)
return g
|
'Initialise a wxWindows renderer instance.'
| def __init__(self, bitmap, dpi):
| DEBUG_MSG('__init__()', 1, self)
if (wx.VERSION_STRING < '2.8'):
raise RuntimeError('matplotlib no longer supports wxPython < 2.8 for the Wx backend.\nYou may, however, use the WxAgg backend.')
self.width = bitmap.GetWidth()
self.height = bitmap.Ge... |
'get the width and height in display coords of the string s
with FontPropertry prop'
| def get_text_width_height_descent(self, s, prop, ismath):
| if ismath:
s = self.strip_math(s)
if (self.gc is None):
gc = self.new_gc()
else:
gc = self.gc
gfx_ctx = gc.gfx_ctx
font = self.get_wx_font(s, prop)
gfx_ctx.SetFont(font, wx.BLACK)
(w, h, descent, leading) = gfx_ctx.GetFullTextExtent(s)
return (w, h, descent)
|
'return the canvas width and height in display coords'
| def get_canvas_width_height(self):
| return (self.width, self.height)
|
'Render the matplotlib.text.Text instance
None)'
| def draw_text(self, gc, x, y, s, prop, angle, ismath):
| if ismath:
s = self.strip_math(s)
DEBUG_MSG('draw_text()', 1, self)
gc.select()
self.handle_clip_rectangle(gc)
gfx_ctx = gc.gfx_ctx
font = self.get_wx_font(s, prop)
color = gc.get_wxcolour(gc.get_rgb())
gfx_ctx.SetFont(font, color)
(w, h, d) = self.get_text_width_height_desce... |
'Return an instance of a GraphicsContextWx, and sets the current gc copy'
| def new_gc(self):
| DEBUG_MSG('new_gc()', 2, self)
self.gc = GraphicsContextWx(self.bitmap, self)
self.gc.select()
self.gc.unselect()
return self.gc
|
'Fetch the locally cached gc.'
| def get_gc(self):
| assert (self.gc != None), 'gc must be defined'
return self.gc
|
'Return a wx font. Cache instances in a font dictionary for
efficiency'
| def get_wx_font(self, s, prop):
| DEBUG_MSG('get_wx_font()', 1, self)
key = hash(prop)
fontprop = prop
fontname = fontprop.get_name()
font = self.fontd.get(key)
if (font is not None):
return font
wxFontname = self.fontnames.get(fontname, wx.ROMAN)
wxFacename = ''
size = self.points_to_pixels(fontprop.get_size... |
'convert point measures to pixes using dpi and the pixels per
inch of the display'
| def points_to_pixels(self, points):
| return (points * (((PIXELS_PER_INCH / 72.0) * self.dpi) / 72.0))
|
'Select the current bitmap into this wxDC instance'
| def select(self):
| if (sys.platform == 'win32'):
self.dc.SelectObject(self.bitmap)
self.IsSelected = True
|
'Select a Null bitmasp into this wxDC instance'
| def unselect(self):
| if (sys.platform == 'win32'):
self.dc.SelectObject(wx.NullBitmap)
self.IsSelected = False
|
'Set the foreground color. fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.'
| def set_foreground(self, fg, isRGB=None):
| DEBUG_MSG('set_foreground()', 1, self)
self.select()
GraphicsContextBase.set_foreground(self, fg, isRGB)
self._pen.SetColour(self.get_wxcolour(self.get_rgb()))
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
'Set the foreground color. fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.'
| def set_graylevel(self, frac):
| DEBUG_MSG('set_graylevel()', 1, self)
self.select()
GraphicsContextBase.set_graylevel(self, frac)
self._pen.SetColour(self.get_wxcolour(self.get_rgb()))
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
'Set the line width.'
| def set_linewidth(self, w):
| DEBUG_MSG('set_linewidth()', 1, self)
self.select()
if ((w > 0) and (w < 1)):
w = 1
GraphicsContextBase.set_linewidth(self, w)
lw = int(self.renderer.points_to_pixels(self._linewidth))
if (lw == 0):
lw = 1
self._pen.SetWidth(lw)
self.gfx_ctx.SetPen(self._pen)
self.uns... |
'Set the capstyle as a string in (\'butt\', \'round\', \'projecting\')'
| def set_capstyle(self, cs):
| DEBUG_MSG('set_capstyle()', 1, self)
self.select()
GraphicsContextBase.set_capstyle(self, cs)
self._pen.SetCap(GraphicsContextWx._capd[self._capstyle])
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
'Set the join style to be one of (\'miter\', \'round\', \'bevel\')'
| def set_joinstyle(self, js):
| DEBUG_MSG('set_joinstyle()', 1, self)
self.select()
GraphicsContextBase.set_joinstyle(self, js)
self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle])
self.gfx_ctx.SetPen(self._pen)
self.unselect()
|
'Set the line style to be one of'
| def set_linestyle(self, ls):
| DEBUG_MSG('set_linestyle()', 1, self)
self.select()
GraphicsContextBase.set_linestyle(self, ls)
try:
self._style = GraphicsContextWx._dashd_wx[ls]
except KeyError:
self._style = wx.LONG_DASH
if (wx.Platform == '__WXMSW__'):
self.set_linewidth(1)
self._pen.SetStyle(sel... |
'return a wx.Colour from RGB format'
| def get_wxcolour(self, color):
| DEBUG_MSG('get_wx_color()', 1, self)
if (len(color) == 3):
(r, g, b) = color
r *= 255
g *= 255
b *= 255
return wx.Colour(red=int(r), green=int(g), blue=int(b))
else:
(r, g, b, a) = color
r *= 255
g *= 255
b *= 255
a *= 255
... |
'Initialise a FigureWx instance.
- Initialise the FigureCanvasBase and wxPanel parents.
- Set event handlers for:
EVT_SIZE (Resize event)
EVT_PAINT (Paint event)'
| def __init__(self, parent, id, figure):
| FigureCanvasBase.__init__(self, figure)
(l, b, w, h) = figure.bbox.bounds
w = int(math.ceil(w))
h = int(math.ceil(h))
wx.Panel.__init__(self, parent, id, size=wx.Size(w, h))
def do_nothing(*args, **kwargs):
warnings.warn(('could not find a setinitialsize function for ... |
'copy bitmap of canvas to system clipboard'
| def Copy_to_Clipboard(self, event=None):
| bmp_obj = wx.BitmapDataObject()
bmp_obj.SetBitmap(self.bitmap)
wx.TheClipboard.Open()
wx.TheClipboard.SetData(bmp_obj)
wx.TheClipboard.Close()
|
'initialize printer settings using wx methods'
| def Printer_Init(self):
| self.printerData = wx.PrintData()
self.printerData.SetPaperId(wx.PAPER_LETTER)
self.printerData.SetPrintMode(wx.PRINT_MODE_PRINTER)
self.printerPageData = wx.PageSetupDialogData()
self.printerPageData.SetMarginBottomRight((25, 25))
self.printerPageData.SetMarginTopLeft((25, 25))
self.printer... |
'set up figure for printing. The standard wx Printer
Setup Dialog seems to die easily. Therefore, this setup
simply asks for image width and margin for printing.'
| def Printer_Setup(self, event=None):
| dmsg = 'Width of output figure in inches.\nThe current aspect ration will be kept.'
dlg = wx.Dialog(self, (-1), 'Page Setup for Printing', ((-1), (-1)))
df = dlg.GetFont()
df.SetWeight(wx.NORMAL)
df.SetPointSize(11)
dlg.SetFont(df)
x_wid = wx.TextCtr... |
'set up figure for printing. Using the standard wx Printer
Setup Dialog.'
| def Printer_Setup2(self, event=None):
| if hasattr(self, 'printerData'):
data = wx.PageSetupDialogData()
data.SetPrintData(self.printerData)
else:
data = wx.PageSetupDialogData()
data.SetMarginTopLeft((15, 15))
data.SetMarginBottomRight((15, 15))
dlg = wx.PageSetupDialog(self, data)
if (dlg.ShowModal() == wx.ID... |
'generate Print Preview with wx Print mechanism'
| def Printer_Preview(self, event=None):
| po1 = PrintoutWx(self, width=self.printer_width, margin=self.printer_margin)
po2 = PrintoutWx(self, width=self.printer_width, margin=self.printer_margin)
self.preview = wx.PrintPreview(po1, po2, self.printerData)
if (not self.preview.Ok()):
print 'error with preview'
self.preview.SetZo... |
'Print figure using wx Print mechanism'
| def Printer_Print(self, event=None):
| pdd = wx.PrintDialogData()
pdd.SetPrintData(self.printerData)
pdd.SetToPage(1)
printer = wx.Printer(pdd)
printout = PrintoutWx(self, width=int(self.printer_width), margin=int(self.printer_margin))
print_ok = printer.Print(self, printout, True)
if (wx.VERSION_STRING >= '2.5'):
if ((no... |
'Delay rendering until the GUI is idle.'
| def draw_idle(self):
| DEBUG_MSG('draw_idle()', 1, self)
self._isDrawn = False
if hasattr(self, '_idletimer'):
self._idletimer.Restart(IDLE_DELAY)
else:
self._idletimer = wx.FutureCall(IDLE_DELAY, self._onDrawIdle)
|
'Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.'
| def draw(self, drawDC=None):
| DEBUG_MSG('draw()', 1, self)
self.renderer = RendererWx(self.bitmap, self.figure.dpi)
self.figure.draw(self.renderer)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC)
|
'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.
Call signature::
start_event_loop(self,timeout... | def start_event_loop(self, timeout=0):
| if hasattr(self, '_event_loop'):
raise RuntimeError('Event loop already running')
id = wx.NewId()
timer = wx.Timer(self, id=id)
if (timeout > 0):
timer.Start((timeout * 1000), oneShot=True)
bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id)
self._event_loop = wx.E... |
'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)'
| def stop_event_loop(self, event=None):
| if hasattr(self, '_event_loop'):
if self._event_loop.IsRunning():
self._event_loop.Exit()
del self._event_loop
|
'return the wildcard string for the filesave dialog'
| def _get_imagesave_wildcards(self):
| default_filetype = self.get_default_filetype()
filetypes = self.get_supported_filetypes_grouped()
sorted_filetypes = filetypes.items()
sorted_filetypes.sort()
wildcards = []
extensions = []
filter_index = 0
for (i, (name, exts)) in enumerate(sorted_filetypes):
ext_list = ';'.join... |
'Performs update of the displayed image on the GUI canvas, using the
supplied device context. If drawDC is None, a ClientDC will be used to
redraw the image.'
| def gui_repaint(self, drawDC=None):
| DEBUG_MSG('gui_repaint()', 1, self)
if self.IsShownOnScreen():
if (drawDC is None):
drawDC = wx.ClientDC(self)
drawDC.BeginDrawing()
drawDC.DrawBitmap(self.bitmap, 0, 0)
drawDC.EndDrawing()
else:
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.