def test_wedge_movement(): param_dict = {'center': ((0, 0), (1, 1), 'set_center'), 'r': (5, 8, 'set_radius'), 'width': (2, 3, 'set_width'), 'theta1': (0, 30, 'set_theta1'), 'theta2': (45, 50, 'set_theta2')} init_args = dict((k, v[0]) for (k, v) in six.iteritems(param_dict)) w = mpatches.Wedge(**init_args) for attr, (old_v, new_v, func) in six.iteritems(param_dict): assert_equal(getattr(w, attr), old_v) getattr(w, func)(new_v) assert_equal(getattr(w, attr), new_v)
def test_wedge_movement(): param_dict = { "center": ((0, 0), (1, 1), "set_center"), "r": (5, 8, "set_radius"), "width": (2, 3, "set_width"), "theta1": (0, 30, "set_theta1"), "theta2": (45, 50, "set_theta2"), } init_args = dict((k, v[0]) for (k, v) in six.iteritems(param_dict)) w = mpatches.Wedge(**init_args) for attr, (old_v, new_v, func) in six.iteritems(param_dict): assert_equal(getattr(w, attr), old_v) getattr(w, func)(new_v) assert_equal(getattr(w, attr), new_v)
def pchanged(self): """ Fire an event when property changed, calling all of the registered callbacks. """ for oid, func in six.iteritems(self._propobservers): func(self)
def update(self, **kwargs): """ Update the current values. If any kwarg is None, default to the current value, if set, otherwise to rc. """ for k, v in six.iteritems(kwargs): if k in self._AllowedKeys: setattr(self, k, v) else: raise AttributeError("%s is unknown keyword" % (k, )) from matplotlib import _pylab_helpers from matplotlib.axes import SubplotBase for figmanager in six.itervalues(_pylab_helpers.Gcf.figs): for ax in figmanager.canvas.figure.axes: # copied from Figure.subplots_adjust if not isinstance(ax, SubplotBase): # Check if sharing a subplots axis if ax._sharex is not None and isinstance( ax._sharex, SubplotBase): if ax._sharex.get_subplotspec().get_gridspec() == self: ax._sharex.update_params() ax.set_position(ax._sharex.figbox) elif ax._sharey is not None and isinstance( ax._sharey, SubplotBase): if ax._sharey.get_subplotspec().get_gridspec() == self: ax._sharey.update_params() ax.set_position(ax._sharey.figbox) else: ss = ax.get_subplotspec().get_topmost_subplotspec() if ss.get_gridspec() == self: ax.update_params() ax.set_position(ax.figbox)
def mark_plot_labels(app, document): """ To make plots referenceable, we need to move the reference from the "htmlonly" (or "latexonly") node to the actual figure node itself. """ for name, explicit in six.iteritems(document.nametypes): if not explicit: continue labelid = document.nameids[name] if labelid is None: continue node = document.ids[labelid] if node.tagname in ('html_only', 'latex_only'): for n in node: if n.tagname == 'figure': sectname = name for c in n: if c.tagname == 'caption': sectname = c.astext() break node['ids'].remove(labelid) node['names'].remove(name) n['ids'].append(labelid) n['names'].append(name) document.settings.env.labels[name] = \ document.settings.env.docname, labelid, sectname break
def __init__ (self, title = 'Save file', parent = None, action = Gtk.FileChooserAction.SAVE, buttons = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE, Gtk.ResponseType.OK), path = None, filetypes = [], default_filetype = None ): super (FileChooserDialog, self).__init__ (title, parent, action, buttons) self.set_default_response (Gtk.ResponseType.OK) if not path: path = os.getcwd() + os.sep # create an extra widget to list supported image formats self.set_current_folder (path) self.set_current_name ('image.' + default_filetype) hbox = Gtk.Box(spacing=10) hbox.pack_start(Gtk.Label(label="File Format:"), False, False, 0) liststore = Gtk.ListStore(GObject.TYPE_STRING) cbox = Gtk.ComboBox() #liststore) cbox.set_model(liststore) cell = Gtk.CellRendererText() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) hbox.pack_start(cbox, False, False, 0) self.filetypes = filetypes self.sorted_filetypes = list(six.iteritems(filetypes)) self.sorted_filetypes.sort() default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): liststore.append(["%s (*.%s)" % (name, ext)]) if ext == default_filetype: default = i cbox.set_active(default) self.ext = default_filetype def cb_cbox_changed (cbox, data=None): """File extension changed""" head, filename = os.path.split(self.get_filename()) root, ext = os.path.splitext(filename) ext = ext[1:] new_ext = self.sorted_filetypes[cbox.get_active()][0] self.ext = new_ext if ext in self.filetypes: filename = root + '.' + new_ext elif ext == '': filename = filename.rstrip('.') + '.' + new_ext self.set_current_name (filename) cbox.connect ("changed", cb_cbox_changed) hbox.show_all() self.set_extra_widget(hbox)
def mark_plot_labels(app, document): """ To make plots referenceable, we need to move the reference from the "htmlonly" (or "latexonly") node to the actual figure node itself. """ for name, explicit in six.iteritems(document.nametypes): if not explicit: continue labelid = document.nameids[name] if labelid is None: continue node = document.ids[labelid] if node.tagname in ('html_only', 'latex_only'): for n in node: if n.tagname == 'figure': sectname = name for c in n: if c.tagname == 'caption': sectname = c.astext() break node['ids'].remove(labelid) node['names'].remove(name) n['ids'].append(labelid) n['names'].append(name) document.settings.env.labels[name] = \ document.settings.env.docname, labelid, sectname break
def _write_svgfonts(self): if not rcParams['svg.fonttype'] == 'svgfont': return writer = self.writer writer.start('defs') for font_fname, chars in six.iteritems(self._fonts): font = get_font(font_fname) font.set_size(72, 72) sfnt = font.get_sfnt() writer.start('font', id=sfnt[(1, 0, 0, 4)]) writer.element( 'font-face', attrib={ 'font-family': font.family_name, 'font-style': font.style_name.lower(), 'units-per-em': '72', 'bbox': ' '.join( short_float_fmt(x / 64.0) for x in font.bbox)}) for char in chars: glyph = font.load_char(char, flags=LOAD_NO_HINTING) verts, codes = font.get_path() path = Path(verts, codes) path_data = self._convert_path(path) # name = font.get_glyph_name(char) writer.element( 'glyph', d=path_data, attrib={ # 'glyph-name': name, 'unicode': unichr(char), 'horiz-adv-x': short_float_fmt(glyph.linearHoriAdvance / 65536.0)}) writer.end('font') writer.end('defs')
def __init__ (self, title = 'Save file', parent = None, action = gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK), path = None, filetypes = [], default_filetype = None ): super(FileChooserDialog, self).__init__ (title, parent, action, buttons) super(FileChooserDialog, self).set_do_overwrite_confirmation(True) self.set_default_response (gtk.RESPONSE_OK) if not path: path = os.getcwd() + os.sep # create an extra widget to list supported image formats self.set_current_folder (path) self.set_current_name ('image.' + default_filetype) hbox = gtk.HBox (spacing=10) hbox.pack_start (gtk.Label ("File Format:"), expand=False) liststore = gtk.ListStore(gobject.TYPE_STRING) cbox = gtk.ComboBox(liststore) cell = gtk.CellRendererText() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) hbox.pack_start (cbox) self.filetypes = filetypes self.sorted_filetypes = list(six.iteritems(filetypes)) self.sorted_filetypes.sort() default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): cbox.append_text ("%s (*.%s)" % (name, ext)) if ext == default_filetype: default = i cbox.set_active(default) self.ext = default_filetype def cb_cbox_changed (cbox, data=None): """File extension changed""" head, filename = os.path.split(self.get_filename()) root, ext = os.path.splitext(filename) ext = ext[1:] new_ext = self.sorted_filetypes[cbox.get_active()][0] self.ext = new_ext if ext in self.filetypes: filename = root + '.' + new_ext elif ext == '': filename = filename.rstrip('.') + '.' + new_ext self.set_current_name (filename) cbox.connect ("changed", cb_cbox_changed) hbox.show_all() self.set_extra_widget(hbox)
def render_mpl_table(data, col_width=0.70, row_height=0.225, font_size=12, header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w', bbox=[0, 0, 1, 1], header_columns=0, ax=None, **kwargs): if ax is None: size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array( [col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs) mpl_table.auto_set_font_size(False) mpl_table.set_fontsize(font_size) for k, cell in six.iteritems(mpl_table._cells): cell.set_edgecolor(edge_color) if k[0] == 0 or k[1] < header_columns: cell.set_text_props(weight='bold', color='w') cell.set_facecolor(header_color) else: cell.set_facecolor(row_colors[k[0] % len(row_colors)]) return ax
def test_wedge_movement(): param_dict = { 'center': ((0, 0), (1, 1), 'set_center'), 'r': (5, 8, 'set_radius'), 'width': (2, 3, 'set_width'), 'theta1': (0, 30, 'set_theta1'), 'theta2': (45, 50, 'set_theta2') } init_args = dict((k, v[0]) for (k, v) in six.iteritems(param_dict)) w = mpatches.Wedge(**init_args) for attr, (old_v, new_v, func) in six.iteritems(param_dict): assert_equal(getattr(w, attr), old_v) getattr(w, func)(new_v) assert_equal(getattr(w, attr), new_v)
def update(self, **kwargs): """ Update the current values. If any kwarg is None, default to the current value, if set, otherwise to rc. """ for k, v in six.iteritems(kwargs): if k in self._AllowedKeys: setattr(self, k, v) else: raise AttributeError("%s is unknown keyword" % (k,)) from matplotlib import _pylab_helpers from matplotlib.axes import SubplotBase for figmanager in six.itervalues(_pylab_helpers.Gcf.figs): for ax in figmanager.canvas.figure.axes: # copied from Figure.subplots_adjust if not isinstance(ax, SubplotBase): # Check if sharing a subplots axis if ax._sharex is not None and isinstance(ax._sharex, SubplotBase): if ax._sharex.get_subplotspec().get_gridspec() == self: ax._sharex.update_params() ax.set_position(ax._sharex.figbox) elif ax._sharey is not None and isinstance(ax._sharey,SubplotBase): if ax._sharey.get_subplotspec().get_gridspec() == self: ax._sharey.update_params() ax.set_position(ax._sharey.figbox) else: ss = ax.get_subplotspec().get_topmost_subplotspec() if ss.get_gridspec() == self: ax.update_params() ax.set_position(ax.figbox)
def pchanged(self): """ Fire an event when property changed, calling all of the registered callbacks. """ for oid, func in six.iteritems(self._propobservers): func(self)
def allquality(interpolator='nn', allfuncs=allfuncs, data=data, n=33): results = {} kv = list(six.iteritems(data)) kv.sort() for name, mesh in kv: reslist = results.setdefault(name, []) for func in allfuncs: reslist.append(quality(func, mesh, interpolator, n)) return results
def depth_getter(obj, current_depth=0, depth_stack=None, nest_info='top level object'): """ Returns a dictionary mapping: id(obj): (shallowest_depth, obj, nest_info) for the given object (and its subordinates). This, in conjunction with recursive_pickle, can be used to debug pickling issues, although finding others is sometimes a case of trial and error. """ if depth_stack is None: depth_stack = {} if id(obj) in depth_stack: stack = depth_stack[id(obj)] if stack[0] > current_depth: del depth_stack[id(obj)] else: return depth_stack depth_stack[id(obj)] = (current_depth, obj, nest_info) if isinstance(obj, (list, tuple)): for i, item in enumerate(obj): depth_getter(item, current_depth=current_depth + 1, depth_stack=depth_stack, nest_info=('list/tuple item #%s in ' '(%s)' % (i, nest_info))) else: if isinstance(obj, dict): state = obj elif hasattr(obj, '__getstate__'): state = obj.__getstate__() if not isinstance(state, dict): state = {} elif hasattr(obj, '__dict__'): state = obj.__dict__ else: state = {} for key, value in six.iteritems(state): depth_getter(value, current_depth=current_depth + 1, depth_stack=depth_stack, nest_info=('attribute "%s" in ' '(%s)' % (key, nest_info))) return depth_stack
def set(self, **kwargs): """ A tkstyle set command, pass *kwargs* to set properties """ ret = [] for k, v in six.iteritems(kwargs): k = k.lower() funcName = "set_%s" % k func = getattr(self, funcName) ret.extend([func(v)]) return ret
def generate_css(attrib={}): if attrib: output = io.StringIO() attrib = list(six.iteritems(attrib)) attrib.sort() for k, v in attrib: k = escape_attrib(k) v = escape_attrib(v) output.write("%s:%s;" % (k, v)) return output.getvalue() return ''
def depth_getter(obj, current_depth=0, depth_stack=None, nest_info="top level object"): """ Returns a dictionary mapping: id(obj): (shallowest_depth, obj, nest_info) for the given object (and its subordinates). This, in conjunction with recursive_pickle, can be used to debug pickling issues, although finding others is sometimes a case of trial and error. """ if depth_stack is None: depth_stack = {} if id(obj) in depth_stack: stack = depth_stack[id(obj)] if stack[0] > current_depth: del depth_stack[id(obj)] else: return depth_stack depth_stack[id(obj)] = (current_depth, obj, nest_info) if isinstance(obj, (list, tuple)): for i, item in enumerate(obj): depth_getter( item, current_depth=current_depth + 1, depth_stack=depth_stack, nest_info=("list/tuple item #%s in " "(%s)" % (i, nest_info)), ) else: if isinstance(obj, dict): state = obj elif hasattr(obj, "__getstate__"): state = obj.__getstate__() if not isinstance(state, dict): state = {} elif hasattr(obj, "__dict__"): state = obj.__dict__ else: state = {} for key, value in six.iteritems(state): depth_getter( value, current_depth=current_depth + 1, depth_stack=depth_stack, nest_info=('attribute "%s" in ' "(%s)" % (key, nest_info)), ) return depth_stack
def generate_css(attrib={}): if attrib: output = io.StringIO() attrib = list(six.iteritems(attrib)) attrib.sort() for k, v in attrib: k = escape_attrib(k) v = escape_attrib(v) output.write("%s:%s;" % (k, v)) return output.getvalue() return ''
def set(self, **kwargs): """ A tkstyle set command, pass *kwargs* to set properties """ ret = [] for k, v in six.iteritems(kwargs): k = k.lower() funcName = "set_%s" % k func = getattr(self, funcName) ret.extend([func(v)]) return ret
def output_args(self): # The %dk adds 'k' as a suffix so that ffmpeg treats our bitrate as in # kbps args = ["-vcodec", self.codec] if self.bitrate > 0: args.extend(["-b", "%dk" % self.bitrate]) if self.extra_args: args.extend(self.extra_args) for k, v in six.iteritems(self.metadata): args.extend(["-metadata", "%s=%s" % (k, v)]) return args + ["-y", self.outfile]
def delete_row(self, row): key = tuple(row) thisiter = self.iterd[key] self.model.remove(thisiter) del self.datad[key] del self.iterd[key] self.rownumd[len(self.iters)] = key self.iters.remove(thisiter) for rownum, thiskey in list(six.iteritems(self.rownumd)): if thiskey == key: del self.rownumd[rownum]
def fileFilters(self): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = list(six.iteritems(filetypes)) sorted_filetypes.sort() filters = [] for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) filters.append(filter) return filters
def output_args(self): # The %dk adds 'k' as a suffix so that ffmpeg treats our bitrate as in # kbps args = ['-vcodec', self.codec] if self.bitrate > 0: args.extend(['-b', '%dk' % self.bitrate]) if self.extra_args: args.extend(self.extra_args) for k, v in six.iteritems(self.metadata): args.extend(['-metadata', '%s=%s' % (k, v)]) return args + ['-y', self.outfile]
def delete_row(self, row): key = tuple(row) thisiter = self.iterd[key] self.model.remove(thisiter) del self.datad[key] del self.iterd[key] self.rownumd[len(self.iters)] = key self.iters.remove(thisiter) for rownum, thiskey in list(six.iteritems(self.rownumd)): if thiskey==key: del self.rownumd[rownum]
def trigger(self, *args): from matplotlib.externals.six.moves import tkinter_tkfiledialog, tkinter_messagebox filetypes = self.figure.canvas.get_supported_filetypes().copy() default_filetype = self.figure.canvas.get_default_filetype() # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first default_filetype_name = filetypes[default_filetype] del filetypes[default_filetype] sorted_filetypes = list(six.iteritems(filetypes)) sorted_filetypes.sort() sorted_filetypes.insert(0, (default_filetype, default_filetype_name)) tk_filetypes = [ (name, '*.%s' % ext) for (ext, name) in sorted_filetypes] # adding a default extension seems to break the # asksaveasfilename dialog when you choose various save types # from the dropdown. Passing in the empty string seems to # work - JDH! # defaultextension = self.figure.canvas.get_default_filetype() defaultextension = '' initialdir = rcParams.get('savefig.directory', '') initialdir = os.path.expanduser(initialdir) initialfile = self.figure.canvas.get_default_filename() fname = tkinter_tkfiledialog.asksaveasfilename( master=self.figure.canvas.manager.window, title='Save the figure', filetypes=tk_filetypes, defaultextension=defaultextension, initialdir=initialdir, initialfile=initialfile, ) if fname == "" or fname == (): return else: if initialdir == '': # explicitly missing key or empty str signals to use cwd rcParams['savefig.directory'] = initialdir else: # save dir for next time rcParams['savefig.directory'] = os.path.dirname( six.text_type(fname)) try: # This method will handle the delegation to the correct type self.figure.canvas.print_figure(fname) except Exception as e: tkinter_messagebox.showerror("Error saving file", str(e))
def update_nested_dict(main_dict, new_dict): """Update nested dict (only level of nesting) with new values. Unlike dict.update, this assumes that the values of the parent dict are dicts (or dict-like), so you shouldn't replace the nested dict if it already exists. Instead you should update the sub-dict. """ # update named styles specified by user for name, rc_dict in six.iteritems(new_dict): if name in main_dict: main_dict[name].update(rc_dict) else: main_dict[name] = rc_dict return main_dict
def update_nested_dict(main_dict, new_dict): """Update nested dict (only level of nesting) with new values. Unlike dict.update, this assumes that the values of the parent dict are dicts (or dict-like), so you shouldn't replace the nested dict if it already exists. Instead you should update the sub-dict. """ # update named styles specified by user for name, rc_dict in six.iteritems(new_dict): if name in main_dict: main_dict[name].update(rc_dict) else: main_dict[name] = rc_dict return main_dict
def rc_params(fail_on_error=False): """Return a :class:`matplotlib.RcParams` instance from the default matplotlib rc file. """ fname = matplotlib_fname() if not os.path.exists(fname): # this should never happen, default in mpl-data should always be found message = 'could not find rc file; returning defaults' ret = RcParams([(key, default) for key, (default, _) in six.iteritems(defaultParams) if key not in _all_deprecated]) warnings.warn(message) return ret return rc_params_from_file(fname, fail_on_error)
def _do_cell_alignment(self): """ Calculate row heights and column widths. Position cells accordingly. """ # Calculate row/column widths widths = {} heights = {} for (row, col), cell in six.iteritems(self._cells): 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()) # work out left position for each column xpos = 0 lefts = {} cols = list(six.iterkeys(widths)) cols.sort() for col in cols: lefts[col] = xpos xpos += widths[col] ypos = 0 bottoms = {} rows = list(six.iterkeys(heights)) rows.sort() rows.reverse() for row in rows: bottoms[row] = ypos ypos += heights[row] # set cell positions for (row, col), cell in six.iteritems(self._cells): cell.set_x(lefts[col]) cell.set_y(bottoms[row])
def _do_cell_alignment(self): """ Calculate row heights and column widths. Position cells accordingly. """ # Calculate row/column widths widths = {} heights = {} for (row, col), cell in six.iteritems(self._cells): 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()) # work out left position for each column xpos = 0 lefts = {} cols = list(six.iterkeys(widths)) cols.sort() for col in cols: lefts[col] = xpos xpos += widths[col] ypos = 0 bottoms = {} rows = list(six.iterkeys(heights)) rows.sort() rows.reverse() for row in rows: bottoms[row] = ypos ypos += heights[row] # set cell positions for (row, col), cell in six.iteritems(self._cells): cell.set_x(lefts[col]) cell.set_y(bottoms[row])
def output_args(self): self._remap_metadata() lavcopts = {'vcodec': self.codec} if self.bitrate > 0: lavcopts.update(vbitrate=self.bitrate) args = ['-o', self.outfile, '-ovc', 'lavc', '-lavcopts', ':'.join(itertools.starmap('{0}={1}'.format, lavcopts.items()))] if self.extra_args: args.extend(self.extra_args) if self.metadata: args.extend(['-info', ':'.join('%s=%s' % (k, v) for k, v in six.iteritems(self.metadata) if k in self.allowed_metadata)]) return args
def add_tools_to_manager(toolmanager, tools=default_tools): """ Add multiple tools to `ToolManager` Parameters ---------- toolmanager: ToolManager `backend_managers.ToolManager` object that will get the tools added tools : {str: class_like}, optional The tools to add in a {name: tool} dict, see `add_tool` for more info. """ for name, tool in six.iteritems(tools): toolmanager.add_tool(name, tool)
def add_tools_to_manager(toolmanager, tools=default_tools): """ Add multiple tools to `ToolManager` Parameters ---------- toolmanager: ToolManager `backend_managers.ToolManager` object that will get the tools added tools : {str: class_like}, optional The tools to add in a {name: tool} dict, see `add_tool` for more info. """ for name, tool in six.iteritems(tools): toolmanager.add_tool(name, tool)
def rc_params(fail_on_error=False): """Return a :class:`matplotlib.RcParams` instance from the default matplotlib rc file. """ fname = matplotlib_fname() if not os.path.exists(fname): # this should never happen, default in mpl-data should always be found message = 'could not find rc file; returning defaults' ret = RcParams([(key, default) for key, (default, _) in six.iteritems(defaultParams) if key not in _all_deprecated]) warnings.warn(message) return ret return rc_params_from_file(fname, fail_on_error)
def revcmap(data): """Can only handle specification *data* in dictionary format.""" data_r = {} for key, val in six.iteritems(data): if six.callable(val): valnew = _reverser(val) # This doesn't work: lambda x: val(1-x) # The same "val" (the first one) is used # each time, so the colors are identical # and the result is shades of gray. else: # Flip x and exchange the y values facing x = 0 and x = 1. valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)] data_r[key] = valnew return data_r
def set_fontconfig_pattern(self, pattern): """ Set the properties by parsing a fontconfig *pattern*. See the documentation on `fontconfig patterns <http://www.fontconfig.org/fontconfig-user.html>`_. This support does not require fontconfig to be installed or support for it to be enabled. We are merely borrowing its pattern syntax for use here. """ for key, val in six.iteritems(self._parse_fontconfig_pattern(pattern)): if type(val) == list: getattr(self, "set_" + key)(val[0]) else: getattr(self, "set_" + key)(val)
def set_fontconfig_pattern(self, pattern): """ Set the properties by parsing a fontconfig *pattern*. See the documentation on `fontconfig patterns <http://www.fontconfig.org/fontconfig-user.html>`_. This support does not require fontconfig to be installed or support for it to be enabled. We are merely borrowing its pattern syntax for use here. """ for key, val in six.iteritems(self._parse_fontconfig_pattern(pattern)): if type(val) == list: getattr(self, "set_" + key)(val[0]) else: getattr(self, "set_" + key)(val)
def get_tool_keymap(self, name): """ Get the keymap associated with the specified tool Parameters ---------- name : string Name of the Tool Returns ---------- list : list of keys associated with the Tool """ keys = [k for k, i in six.iteritems(self._keys) if i == name] return keys
def _auto_set_font_size(self, renderer): if len(self._cells) == 0: return fontsize = list(six.itervalues(self._cells))[0].get_fontsize() cells = [] for key, cell in six.iteritems(self._cells): # ignore auto-sized columns if key[1] in self._autoColumns: continue size = cell.auto_set_font_size(renderer) fontsize = min(fontsize, size) cells.append(cell) # now set all fontsizes equal for cell in six.itervalues(self._cells): cell.set_fontsize(fontsize)
def _auto_set_font_size(self, renderer): if len(self._cells) == 0: return fontsize = list(six.itervalues(self._cells))[0].get_fontsize() cells = [] for key, cell in six.iteritems(self._cells): # ignore auto-sized columns if key[1] in self._autoColumns: continue size = cell.auto_set_font_size(renderer) fontsize = min(fontsize, size) cells.append(cell) # now set all fontsizes equal for cell in six.itervalues(self._cells): cell.set_fontsize(fontsize)
def output_args(self): # The %dk adds 'k' as a suffix so that ffmpeg treats our bitrate as in # kbps args = ['-vcodec', self.codec] # For h264, the default format is yuv444p, which is not compatible # with quicktime (and others). Specifying yuv420p fixes playback on # iOS,as well as HTML5 video in firefox and safari (on both Win and # OSX). Also fixes internet explorer. This is as of 2015/10/29. if self.codec == 'h264' and '-pix_fmt' not in self.extra_args: args.extend(['-pix_fmt', 'yuv420p']) if self.bitrate > 0: args.extend(['-b', '%dk' % self.bitrate]) if self.extra_args: args.extend(self.extra_args) for k, v in six.iteritems(self.metadata): args.extend(['-metadata', '%s=%s' % (k, v)]) return args + ['-y', self.outfile]
def output_args(self): # The %dk adds 'k' as a suffix so that ffmpeg treats our bitrate as in # kbps args = ['-vcodec', self.codec] # For h264, the default format is yuv444p, which is not compatible # with quicktime (and others). Specifying yuv420p fixes playback on # iOS,as well as HTML5 video in firefox and safari (on both Win and # OSX). Also fixes internet explorer. This is as of 2015/10/29. if self.codec == 'h264' and '-pix_fmt' not in self.extra_args: args.extend(['-pix_fmt', 'yuv420p']) if self.bitrate > 0: args.extend(['-b', '%dk' % self.bitrate]) if self.extra_args: args.extend(self.extra_args) for k, v in six.iteritems(self.metadata): args.extend(['-metadata', '%s=%s' % (k, v)]) return args + ['-y', self.outfile]
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): """Return :class:`matplotlib.RcParams` from the contents of the given file. Parameters ---------- fname : str Name of file parsed for matplotlib settings. fail_on_error : bool If True, raise an error when the parser fails to convert a parameter. use_default_template : bool If True, initialize with default parameters before updating with those in the given file. If False, the configuration class only contains the parameters specified in the file. (Useful for updating dicts.) """ config_from_file = _rc_params_in_file(fname, fail_on_error) if not use_default_template: return config_from_file iter_params = six.iteritems(defaultParams) config = RcParams([(key, default) for key, (default, _) in iter_params if key not in _all_deprecated]) config.update(config_from_file) verbose.set_level(config['verbose.level']) verbose.set_fileo(config['verbose.fileo']) if config['datapath'] is None: config['datapath'] = get_data_path() if not config['text.latex.preamble'] == ['']: verbose.report( """ ***************************************************************** You have the following UNSUPPORTED LaTeX preamble customizations: %s Please do not ask for support with these customizations active. ***************************************************************** """ % '\n'.join(config['text.latex.preamble']), 'helpful') verbose.report('loaded rc file %s' % fname) return config
def _update_gc(self, gc, new_gc_dict): """ Update the given GraphicsCollection with the given dictionary of properties. The keys in the dictionary are used to identify the appropriate set_ method on the gc. """ new_gc_dict = new_gc_dict.copy() dashes = new_gc_dict.pop("dashes", None) if dashes: gc.set_dashes(**dashes) for k, v in six.iteritems(new_gc_dict): set_method = getattr(gc, 'set_' + k, None) if set_method is None or not six.callable(set_method): raise AttributeError('Unknown property {0}'.format(k)) set_method(v) return gc
def _update_gc(self, gc, new_gc_dict): """ Update the given GraphicsCollection with the given dictionary of properties. The keys in the dictionary are used to identify the appropriate set_ method on the gc. """ new_gc_dict = new_gc_dict.copy() dashes = new_gc_dict.pop("dashes", None) if dashes: gc.set_dashes(**dashes) for k, v in six.iteritems(new_gc_dict): set_method = getattr(gc, 'set_' + k, None) if set_method is None or not six.callable(set_method): raise AttributeError('Unknown property {0}'.format(k)) set_method(v) return gc
def start(self, tag, attrib={}, **extra): self.__flush() tag = escape_cdata(tag) self.__data = [] self.__tags.append(tag) self.__write(self.__indentation[:len(self.__tags) - 1]) self.__write("<%s" % tag) if attrib or extra: attrib = attrib.copy() attrib.update(extra) attrib = list(six.iteritems(attrib)) attrib.sort() for k, v in attrib: if not v == '': k = escape_cdata(k) v = escape_attrib(v) self.__write(" %s=\"%s\"" % (k, v)) self.__open = 1 return len(self.__tags) - 1
def start(self, tag, attrib={}, **extra): self.__flush() tag = escape_cdata(tag) self.__data = [] self.__tags.append(tag) self.__write(self.__indentation[:len(self.__tags) - 1]) self.__write("<%s" % tag) if attrib or extra: attrib = attrib.copy() attrib.update(extra) attrib = list(six.iteritems(attrib)) attrib.sort() for k, v in attrib: if not v == '': k = escape_cdata(k) v = escape_attrib(v) self.__write(" %s=\"%s\"" % (k, v)) self.__open = 1 return len(self.__tags)-1
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): """Return :class:`matplotlib.RcParams` from the contents of the given file. Parameters ---------- fname : str Name of file parsed for matplotlib settings. fail_on_error : bool If True, raise an error when the parser fails to convert a parameter. use_default_template : bool If True, initialize with default parameters before updating with those in the given file. If False, the configuration class only contains the parameters specified in the file. (Useful for updating dicts.) """ config_from_file = _rc_params_in_file(fname, fail_on_error) if not use_default_template: return config_from_file iter_params = six.iteritems(defaultParams) config = RcParams([(key, default) for key, (default, _) in iter_params if key not in _all_deprecated]) config.update(config_from_file) verbose.set_level(config['verbose.level']) verbose.set_fileo(config['verbose.fileo']) if config['datapath'] is None: config['datapath'] = get_data_path() if not config['text.latex.preamble'] == ['']: verbose.report(""" ***************************************************************** You have the following UNSUPPORTED LaTeX preamble customizations: %s Please do not ask for support with these customizations active. ***************************************************************** """ % '\n'.join(config['text.latex.preamble']), 'helpful') verbose.report('loaded rc file %s' % fname) return config
def temp_style(style_name, settings=None): """Context manager to create a style sheet in a temporary directory.""" settings = DUMMY_SETTINGS temp_file = '%s.%s' % (style_name, STYLE_EXTENSION) # Write style settings to file in the temp directory. tempdir = tempfile.mkdtemp() with open(os.path.join(tempdir, temp_file), 'w') as f: for k, v in six.iteritems(settings): f.write('%s: %s' % (k, v)) # Add temp directory to style path and reload so we can access this style. USER_LIBRARY_PATHS.append(tempdir) style.reload_library() try: yield finally: shutil.rmtree(tempdir) style.reload_library()
def _write_svgfonts(self): if not rcParams['svg.fonttype'] == 'svgfont': return writer = self.writer writer.start('defs') for font_fname, chars in six.iteritems(self._fonts): font = get_font(font_fname) font.set_size(72, 72) sfnt = font.get_sfnt() writer.start('font', id=sfnt[(1, 0, 0, 4)]) writer.element('font-face', attrib={ 'font-family': font.family_name, 'font-style': font.style_name.lower(), 'units-per-em': '72', 'bbox': ' '.join( six.text_type(x / 64.0) for x in font.bbox) }) for char in chars: glyph = font.load_char(char, flags=LOAD_NO_HINTING) verts, codes = font.get_path() path = Path(verts, codes) path_data = self._convert_path(path) # name = font.get_glyph_name(char) writer.element( 'glyph', d=path_data, attrib={ # 'glyph-name': name, 'unicode': unichr(char), 'horiz-adv-x': six.text_type(glyph.linearHoriAdvance / 65536.0) }) writer.end('font') writer.end('defs')
def _writeHatches(self): hatchDict = dict() sidelen = 72.0 for hatch_style, name in six.iteritems(self.hatchPatterns): ob = self.reserveObject('hatch pattern') hatchDict[name] = ob res = { 'Procsets': [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()] } self.beginStream( ob.id, None, { 'Type': Name('Pattern'), 'PatternType': 1, 'PaintType': 1, 'TilingType': 1, 'BBox': [0, 0, sidelen, sidelen], 'XStep': sidelen, 'YStep': sidelen, 'Resources': res }) stroke_rgb, fill_rgb, path = hatch_style self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2], Op.setrgb_stroke) if fill_rgb is not None: self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2], Op.setrgb_nonstroke, 0, 0, sidelen, sidelen, Op.rectangle, Op.fill) self.output(customWidth, Op.setlinewidth) # TODO: We could make this dpi-dependent, but that would be # an API change self.output(*self.pathOperations( Path.hatch(path), Affine2D().scale(sidelen), simplify=False)) self.output(Op.stroke) self.endStream() self.writeObject(self.hatchObject, hatchDict)
def update(self, props): """ Update the properties of this :class:`Artist` from the dictionary *prop*. """ store = self.eventson self.eventson = False changed = False for k, v in six.iteritems(props): if k in ["axes"]: setattr(self, k, v) else: func = getattr(self, "set_" + k, None) if func is None or not six.callable(func): raise AttributeError("Unknown property %s" % k) func(v) changed = True self.eventson = store if changed: self.pchanged() self.stale = True
def update(self, props): """ Update the properties of this :class:`Artist` from the dictionary *prop*. """ store = self.eventson self.eventson = False changed = False for k, v in six.iteritems(props): if k in ['axes']: setattr(self, k, v) else: func = getattr(self, 'set_' + k, None) if func is None or not six.callable(func): raise AttributeError('Unknown property %s' % k) func(v) changed = True self.eventson = store if changed: self.pchanged() self.stale = True