INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Remove RECORD. jws from a wheel by truncating the zip file. RECORD. jws must be at the end of the archive. The zip file must be an ordinary archive with the compressed files and the directory in the same order and without any non - zip content after the truncation point.
def unsign(wheelfile): """ Remove RECORD.jws from a wheel by truncating the zip file. RECORD.jws must be at the end of the archive. The zip file must be an ordinary archive, with the compressed files and the directory in the same order, and without any non-zip content after the truncation poi...
Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel s own unpack/ install commands verify the manifest against the signature and file contents.
def verify(wheelfile): """Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents. """ wf = WheelFile(wheelfile) sig_name = wf.distinfo_name + '/RECORD.jws'...
Unpack a wheel.
def unpack(wheelfile, dest='.'): """Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory). """ wf = WheelFile(...
Install wheels.: param requirements: A list of requirements or wheel files to install.: param requirements_file: A file containing requirements to install.: param wheel_dirs: A list of directories to search for wheels.: param force: Install a wheel file even if it is not compatible.: param list_files: Only list the fil...
def install(requirements, requirements_file=None, wheel_dirs=None, force=False, list_files=False, dry_run=False): """Install wheels. :param requirements: A list of requirements or wheel files to install. :param requirements_file: A file containing requirements to install. :p...
Regenerate the entry_points console_scripts for the named distribution.
def install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") f...
Sets for the _draw_ and _ldraw_ attributes for each of the graph sub - elements by processing the xdot format of the graph.
def arrange_all(self): """ Sets for the _draw_ and _ldraw_ attributes for each of the graph sub-elements by processing the xdot format of the graph. """ import godot.dot_data_parser parser = godot.dot_data_parser.GodotDataParser() xdot_data = self.create( format = "...
Parses the Xdot attributes of all graph components and adds the components to a new canvas.
def redraw_canvas(self): """ Parses the Xdot attributes of all graph components and adds the components to a new canvas. """ from xdot_parser import XdotAttrParser xdot_parser = XdotAttrParser() canvas = self._component_default() for node in self.nodes: ...
Returns a node given an ID or None if no such node exists.
def get_node(self, ID): """ Returns a node given an ID or None if no such node exists. """ node = super(Graph, self).get_node(ID) if node is not None: return node for graph in self.all_graphs: for each_node in graph.nodes: if each_node.ID ...
Trait initialiser.
def _maxiter_default(self): """ Trait initialiser. """ mode = self.mode if mode == "KK": return 100 * len(self.nodes) elif mode == "major": return 200 else: return 600
Property getter.
def _get_all_graphs(self): """ Property getter. """ top_graph = self def get_subgraphs(graph): assert isinstance(graph, BaseGraph) subgraphs = graph.subgraphs[:] for subgraph in graph.subgraphs: subsubgraphs = get_subgraphs(subgraph) ...
Sets the connection string for all edges.
def _directed_changed(self, new): """ Sets the connection string for all edges. """ if new: conn = "->" else: conn = "--" for edge in [e for g in self.all_graphs for e in g.edges]: edge.conn = conn
Maintains each branch s list of available nodes in order that they may move themselves ( InstanceEditor values ).
def _on_nodes(self): """ Maintains each branch's list of available nodes in order that they may move themselves (InstanceEditor values). """ all_graphs = self.all_graphs all_nodes = [n for g in all_graphs for n in g.nodes] for graph in all_graphs: for edg...
Handles the list of edges for any graph changing.
def _on_edges(self, object, name, old, new): """ Handles the list of edges for any graph changing. """ if name == "edges_items": edges = new.added elif name == "edges": edges = new else: edges = [] all_nodes = [n for g in self.all_grap...
Helper callback.
def _support(self, caller): """Helper callback.""" markdown_content = caller() html_content = markdown.markdown( markdown_content, extensions=[ "markdown.extensions.fenced_code", CodeHiliteExtension(css_class="highlight"), "...
Trait initialiser
def _viewport_default(self): """ Trait initialiser """ viewport = Viewport(component=self.canvas, enable_zoom=True) viewport.tools.append(ViewportPanTool(viewport)) return viewport
Handles the component being changed.
def _component_changed(self, old, new): """ Handles the component being changed. """ canvas = self.canvas if old is not None: canvas.remove(old) if new is not None: canvas.add(new)
Helper callback.
def _code_support(self, language, caller): """Helper callback.""" code = caller() # remove the leading whitespace so the whole block can be indented more easily with flow of page lines = code.splitlines() first_nonempty_line_index = 0 while not lines[first_nonempty_line...
Handles the left mouse button being double - clicked when the tool is in the normal state.
def normal_left_dclick(self, event): """ Handles the left mouse button being double-clicked when the tool is in the 'normal' state. If the event occurred on this tool's component (or any contained component of that component), the method opens a Traits UI view on the object refe...
Trait initialiser
def _diagram_canvas_default(self): """ Trait initialiser """ canvas = Canvas() for tool in self.tools: canvas.tools.append(tool(canvas)) return canvas
Trait initialiser
def _viewport_default(self): """ Trait initialiser """ vp = Viewport(component=self.diagram_canvas, enable_zoom=True) vp.view_position = [0,0] vp.tools.append(ViewportPanTool(vp)) return vp
Handles the diagram canvas being set
def _diagram_canvas_changed(self, new): """ Handles the diagram canvas being set """ logger.debug("Diagram canvas changed!") canvas = self.diagram_canvas for tool in self.tools: if canvas is not None: print "Adding tool: %s" % tool canvas.too...
Removes all components from the canvas
def clear_canvas(self): """ Removes all components from the canvas """ logger.debug("Clearing the diagram canvas!") old_canvas = self.diagram_canvas # logger.debug("Canvas components: %s" % canvas.components) # for component in canvas.components: # canvas.remove(compon...
Handles the domain model changing
def _domain_model_changed_for_diagram(self, obj, name, old, new): """ Handles the domain model changing """ if old is not None: self.unmap_model(old) if new is not None: self.map_model(new)
Maps a domain model to the diagram
def map_model(self, new): """ Maps a domain model to the diagram """ logger.debug("Mapping the domain model!") dot = Dot() self.diagram.clear_canvas() for node_mapping in self.nodes: ct = node_mapping.containment_trait logger.debug("Mapping elements con...
Removes listeners from a domain model
def unmap_model(self, old): """ Removes listeners from a domain model """ for node_mapping in self.nodes: ct = node_mapping.containment_trait if hasattr(old, ct): old_elements = getattr(old, ct) for old_element in old_elements: ...
Handles mapping elements to diagram components
def map_element(self, obj, name, event): """ Handles mapping elements to diagram components """ canvas = self.diagram.diagram_canvas parser = XDotParser() for element in event.added: logger.debug("Mapping new element [%s] to diagram node" % element) for node_map...
Styles a node
def _style_node(self, pydot_node, dot_attrs): """ Styles a node """ pydot_node.set_shape(dot_attrs.shape) pydot_node.set_fixedsize(str(dot_attrs.fixed_size)) pydot_node.set_width(str(dot_attrs.width)) pydot_node.set_height(str(dot_attrs.height)) pydot_node.set_color(rgba...
Parses xdot data and returns the associated components.
def parse_xdot_data(self, data): """ Parses xdot data and returns the associated components. """ parser = self.parser # if pyparsing_version >= "1.2": # parser.parseWithTabs() if data: return parser.parseString(data) else: return []
Defines xdot grammar.
def define_parser(self): """ Defines xdot grammar. @see: http://graphviz.org/doc/info/output.html#d:xdot """ # Common constructs. point = Group(integer.setResultsName("x") + integer.setResultsName("y")) n_points = (integer.setResultsName("n") + ...
The color traits of a Pen instance must be a string of the form ( r g b ) or ( r g b a ) where r g b and a are integers from 0 to 255 a wx. Colour instance an integer which in hex is of the form 0xRRGGBB where RR is red GG is green and BB is blue or a valid color name.
def _proc_color(self, tokens): """ The color traits of a Pen instance must be a string of the form (r,g,b) or (r,g,b,a) where r, g, b, and a are integers from 0 to 255, a wx.Colour instance, an integer which in hex is of the form 0xRRGGBB, where RR is red, GG is green, and BB is blue or ...
Sets the font.
def proc_font(self, tokens): """ Sets the font. """ size = int(tokens["s"]) self.pen.font = "%s %d" % (tokens["b"], size) return []
Returns the components of an ellipse.
def _proc_ellipse(self, tokens, filled): """ Returns the components of an ellipse. """ component = Ellipse(pen=self.pen, x_origin=tokens["x0"], y_origin=tokens["y0"], e_width=tokens["w"], e_h...
Returns the components of a polygon.
def _proc_polygon(self, tokens, filled): """ Returns the components of a polygon. """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = Polygon(pen=self.pen, points=pts, filled=filled) return component
Returns the components of a polyline.
def proc_polyline(self, tokens): """ Returns the components of a polyline. """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = Polyline(pen=self.pen, points=pts) return component
Returns the components of a B - spline ( Bezier curve ).
def _proc_bspline(self, tokens, filled): """ Returns the components of a B-spline (Bezier curve). """ pts = [(p["x"], p["y"]) for p in tokens["points"]] component = BSpline(pen=self.pen, points=pts, filled=filled) return component
Returns text components.
def proc_text(self, tokens): """ Returns text components. """ component = Text(pen=self.pen, text_x=tokens["x"], text_y=tokens["y"], justify=tokens["j"], text_w=tokens["w"], text...
Returns the components of an image.
def proc_image(self, tokens): """ Returns the components of an image. """ print "IMAGE:", tokens, tokens.asList(), tokens.keys() raise NotImplementedError
Allow direct use of GridOut GridFS file wrappers as endpoint responses.
def render_grid_file(context, f): """Allow direct use of GridOut GridFS file wrappers as endpoint responses.""" f.seek(0) # Ensure we are reading from the beginning. response = context.response # Frequently accessed, so made local. Useless optimization on Pypy. if __debug__: # We add some useful diagnostic ...
Save to file.
def save(self, obj): """ Save to file. """ fd = None try: fd = open(self.dot_file.absolute_path, "wb") obj.save_dot(fd) finally: if fd is not None: fd.close() # self.m_time = getmtime(self.adaptee.absolute_path) r...
Load the file.
def load(self): """ Load the file. """ fd = None try: obj = parse_dot_file( self.dot_file.absolute_path ) finally: if fd is not None: fd.close() return obj
Draws the component
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ x_origin = self.x_origin y_origin = self.y_origin gc.save_state() try: # self._draw_bounds(gc) gc.begin_path() gc.translate_ctm(x_origin, y_origin) ...
Test if the point is within this ellipse
def is_in(self, point_x, point_y): """ Test if the point is within this ellipse """ x = self.x_origin y = self.y_origin a = self.e_width#/2 # FIXME: Why divide by two b = self.e_height#/2 return ((point_x-x)**2/(a**2)) + ((point_y-y)**2/(b**2)) < 1.0
Draws the component bounds for testing purposes
def _draw_bounds(self, gc): """ Draws the component bounds for testing purposes """ dx, dy = self.bounds x, y = self.position gc.rect(x, y, dx, dy) gc.stroke_path()
Perform the action.
def perform(self, event): """ Perform the action. """ wizard = NewDotGraphWizard(parent=self.window.control, window=self.window, title="New Graph") # Open the wizard if wizard.open() == OK: wizard.finished = True
Convert from rectangular ( x y ) to polar ( r w ) r = sqrt ( x^2 + y^2 ) w = arctan ( y/ x ) = [ - \ pi \ pi ] = [ - 180 180 ]
def polar(x, y, deg=0): # radian if deg=0; degree if deg=1 """ Convert from rectangular (x,y) to polar (r,w) r = sqrt(x^2 + y^2) w = arctan(y/x) = [-\pi,\pi] = [-180,180] """ if deg: return hypot(x, y), 180.0 * atan2(y, x) / pi else: return hypot(x, y), atan2(y, ...
x^2 + ax + b = 0 ( or ax^2 + bx + c = 0 ) By substituting x = y - t and t = a/ 2 the equation reduces to y^2 + ( b - t^2 ) = 0 which has easy solution y = +/ - sqrt ( t^2 - b )
def quadratic(a, b, c=None): """ x^2 + ax + b = 0 (or ax^2 + bx + c = 0) By substituting x = y-t and t = a/2, the equation reduces to y^2 + (b-t^2) = 0 which has easy solution y = +/- sqrt(t^2-b) """ if c: # (ax^2 + bx + c = 0) a, b = b / float(a), c / float(a) t = a ...
x^3 + ax^2 + bx + c = 0 ( or ax^3 + bx^2 + cx + d = 0 ) With substitution x = y - t and t = a/ 3 the cubic equation reduces to y^3 + py + q = 0 where p = b - 3t^2 and q = c - bt + 2t^3. Then one real root y1 = u + v can be determined by solving w^2 + qw - ( p/ 3 ) ^3 = 0 where w = u^3 v^3. From Vieta s theorem y1 + y2 ...
def cubic(a, b, c, d=None): """ x^3 + ax^2 + bx + c = 0 (or ax^3 + bx^2 + cx + d = 0) With substitution x = y-t and t = a/3, the cubic equation reduces to y^3 + py + q = 0, where p = b-3t^2 and q = c-bt+2t^3. Then, one real root y1 = u+v can be determined by solving w^2 + qw - (p/3)^3 ...
Construct the SQLAlchemy engine and session factory.
def start(self, context): """Construct the SQLAlchemy engine and session factory.""" if __debug__: log.info("Connecting SQLAlchemy database layer.", extra=dict( uri = redact_uri(self.uri), config = self.config, alias = self.alias, )) # Construct the engine. engine = self.engine = cre...
Parses the dot_code string and replaces the existing model.
def _parse_dot_code_fired(self): """ Parses the dot_code string and replaces the existing model. """ parser = GodotDataParser() graph = parser.parse_dot_data(self.dot_code) if graph is not None: self.model = graph
Handles the new Graph action.
def new_model(self, info): """ Handles the new Graph action. """ if info.initialized: retval = confirm(parent = info.ui.control, message = "Replace existing graph?", title = "New Graph", default = YES)...
Handles the open action.
def open_file(self, info): """ Handles the open action. """ if not info.initialized: return # Escape. # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "open", wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" ...
Handles saving the current model to the last file.
def save(self, info): """ Handles saving the current model to the last file. """ save_file = self.save_file if not isfile(save_file): self.save_as(info) else: fd = None try: fd = open(save_file, "wb") dot_code =...
Handles saving the current model to file.
def save_as(self, info): """ Handles saving the current model to file. """ if not info.initialized: return # retval = self.edit_traits(parent=info.ui.control, view="file_view") dlg = FileDialog( action = "save as", wildcard = "Graphviz Files (*.dot, *.xdo...
Handles display of the graph dot traits.
def configure_graph(self, info): """ Handles display of the graph dot traits. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=attr_view)
Handles display of the nodes editor.
def configure_nodes(self, info): """ Handles display of the nodes editor. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=nodes_view)
Handles display of the edges editor.
def configure_edges(self, info): """ Handles display of the edges editor. """ if info.initialized: self.model.edit_traits(parent=info.ui.control, kind="live", view=edges_view)
Handles displaying a view about Godot.
def about_godot(self, info): """ Handles displaying a view about Godot. """ if info.initialized: self.edit_traits(parent=info.ui.control, kind="livemodal", view=about_view)
Handles adding a Node to the graph.
def add_node(self, info): """ Handles adding a Node to the graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is None: return IDs = [v.ID for v in graph.nodes] node = Node(ID=make_unique_name...
Handles adding an Edge to the graph.
def add_edge(self, info): """ Handles adding an Edge to the graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is None: return n_nodes = len(graph.nodes) IDs = [v.ID for v in graph.nodes] ...
Handles adding a Subgraph to the main graph.
def add_subgraph(self, info): """ Handles adding a Subgraph to the main graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is not None: subgraph = Subgraph()#root=graph, parent=graph) retval = sub...
Handles adding a Cluster to the main graph.
def add_cluster(self, info): """ Handles adding a Cluster to the main graph. """ if not info.initialized: return graph = self._request_graph(info.ui.control) if graph is not None: cluster = Cluster()#root=graph, parent=graph) retval = cluster.edit_t...
Displays a dialog for graph selection if more than one exists. Returns None if the dialog is canceled.
def _request_graph(self, parent=None): """ Displays a dialog for graph selection if more than one exists. Returns None if the dialog is canceled. """ if (len(self.all_graphs) > 1) and (self.select_graph): retval = self.edit_traits(parent = parent, ...
Handles display of the options menu.
def godot_options(self, info): """ Handles display of the options menu. """ if info.initialized: self.edit_traits( parent = info.ui.control, kind = "livemodal", view = "options_view" )
Handles display of the dot code in a text editor.
def configure_dot_code(self, info): """ Handles display of the dot code in a text editor. """ if not info.initialized: return self.dot_code = str(self.model) retval = self.edit_traits( parent = info.ui.control, kind = "livemodal",...
Handles the user attempting to exit Godot.
def on_exit(self, info): """ Handles the user attempting to exit Godot. """ if self.prompt_on_exit:# and (not is_ok): retval = confirm(parent = info.ui.control, message = "Exit Godot?", title = "Confirm exit", ...
Components are positioned relative to their container. Use this method to position the bottom - left corner of the components at the origin.
def move_to_origin(components): """ Components are positioned relative to their container. Use this method to position the bottom-left corner of the components at the origin. """ for component in components: if isinstance(component, Ellipse): component.x_origin = componen...
Save the object to a given file like object in the given format.
def save_to_file_like(self, flo, format=None, **kwargs): """ Save the object to a given file like object in the given format. """ format = self.format if format is None else format save = getattr(self, "save_%s" % format, None) if save is None: raise ValueError("Unkno...
Load the object to a given file like object with the given protocol.
def load_from_file_like(cls, flo, format=None): """ Load the object to a given file like object with the given protocol. """ format = self.format if format is None else format load = getattr(cls, "load_%s" % format, None) if load is None: raise ValueError(...
Save the object to file given by filename.
def save_to_file(self, filename, format=None, **kwargs): """ Save the object to file given by filename. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) with file(filename, 'wb') as fp: self.s...
Return an instance of the class that is saved in the file with the given filename in the specified format.
def load_from_file(cls, filename, format=None): """ Return an instance of the class that is saved in the file with the given filename in the specified format. """ if format is None: # try to derive protocol from file extension format = format_from_extension(fi...
Draws the component
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ gc.save_state() try: # Specify the font font = str_to_font(str(self.pen.font)) gc.set_font(font) gc.set_fill_color(self.pen.color_) x = self...
Syntactically concise alias trait but creates a pair of lambda functions for every alias you declare.
def Alias(name, **metadata): """ Syntactically concise alias trait but creates a pair of lambda functions for every alias you declare. class MyClass(HasTraits): line_width = Float(3.0) thickness = Alias("line_width") """ return Property(lambda obj: getattr(obj, name), ...
!DEMO! Simple file parsing generator
def parse(filename, encoding=None): """ !DEMO! Simple file parsing generator Args: filename: absolute or relative path to file on disk encoding: encoding string that is passed to open function """ with open(filename, encoding=encoding) as source: for line in source: ...
!DEMO! Cached list of keys that can be used to generate sentence.
def startwords(self): """ !DEMO! Cached list of keys that can be used to generate sentence. """ if self._start_words is not None: return self._start_words else: self._start_words = list(filter( lambda x: str.isupper(x[0][0]) and x[...
Add chain to current shelve file
def add_chain(self, name, order): """ Add chain to current shelve file Args: name: chain name order: markov chain order """ if name not in self.chains: setattr(self.chains, name, MarkovChain(order=order)) else: raise Value...
Remove chain from current shelve file
def remove_chain(self, name): """ Remove chain from current shelve file Args: name: chain name """ if name in self.chains: delattr(self.chains, name) else: raise ValueError("Chain with this name not found")
Build markov chain from source on top of existin chain
def build_chain(self, source, chain): """ Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source """ ...
!DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit.
def generate_sentence(self, chain): """ !DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit. Args: chain: MarkovChain that will be used to generate sentence """ def weighted_choice(cho...
Creates and returns a representation of the graph using the Graphviz layout program given by prog according to the given format.
def create(self, prog=None, format=None): """ Creates and returns a representation of the graph using the Graphviz layout program given by 'prog', according to the given format. Writes the graph to a temporary dot file and processes it with the program given by '...
Adds a node to the graph.
def add_node(self, node_or_ID, **kwds): """ Adds a node to the graph. """ if not isinstance(node_or_ID, Node): nodeID = str( node_or_ID ) if nodeID in self.nodes: node = self.nodes[ self.nodes.index(nodeID) ] else: if self.defau...
Removes a node from the graph.
def delete_node(self, node_or_ID): """ Removes a node from the graph. """ if isinstance(node_or_ID, Node): # name = node_or_ID.ID node = node_or_ID else: # name = node_or_ID node = self.get_node(node_or_ID) if node is None: ...
Returns the node with the given ID or None.
def get_node(self, ID): """ Returns the node with the given ID or None. """ for node in self.nodes: if node.ID == str(ID): return node return None
Removes an edge from the graph. Returns the deleted edge or None.
def delete_edge(self, tail_node_or_ID, head_node_or_ID): """ Removes an edge from the graph. Returns the deleted edge or None. """ if isinstance(tail_node_or_ID, Node): tail_node = tail_node_or_ID else: tail_node = self.get_node(tail_node_or_ID) if isinst...
Adds an edge to the graph.
def add_edge(self, tail_node_or_ID, head_node_or_ID, **kwds): """ Adds an edge to the graph. """ tail_node = self.add_node(tail_node_or_ID) head_node = self.add_node(head_node_or_ID) # Only top level graphs are directed and/or strict. if "directed" in self.trait_names():...
Adds a subgraph to the graph.
def add_subgraph(self, subgraph_or_ID): """ Adds a subgraph to the graph. """ if not isinstance(subgraph_or_ID, (godot.subgraph.Subgraph, godot.cluster.Cluster)): subgraphID = str( subgraph_or_ID ) if subgraph_or_ID.startswith("c...
Handles the Graphviz layout program selection changing.
def _program_changed(self, new): """ Handles the Graphviz layout program selection changing. """ progs = self.progs if not progs.has_key(prog): logger.warning( 'GraphViz\'s executable "%s" not found' % prog ) if not os.path.exists( progs[prog] ) or not \ ...
Maintains each edge s list of available nodes.
def _set_node_lists(self, new): """ Maintains each edge's list of available nodes. """ for edge in self.edges: edge._nodes = self.nodes
Parses a DOT file and returns a Godot graph.
def parse_dot_file(filename): """ Parses a DOT file and returns a Godot graph. """ parser = GodotDataParser() graph = parser.parse_dot_file(filename) del parser return graph
Return ( ADD_NODE node_name options )
def _proc_node_stmt(self, toks): """ Return (ADD_NODE, node_name, options) """ opts = toks[1] dummy_node = Node("dummy") # Coerce attribute types. for key, value in opts.iteritems(): trait = dummy_node.trait(key) if trait is not None: ...
Returns a tuple of the form ( ADD_EDGE src dest options ).
def _proc_edge_stmt(self, toks): """ Returns a tuple of the form (ADD_EDGE, src, dest, options). """ opts = toks[3] dummy_edge = Edge("dummy1", "dummy2") # Coerce attribute types. for key, value in opts.iteritems(): trait = dummy_edge.trait(key) if...
Returns a graph given a file or a filename.
def parse_dot_file(self, file_or_filename): """ Returns a graph given a file or a filename. """ if isinstance(file_or_filename, basestring): file = None try: file = open(file_or_filename, "rb") data = file.read() except: ...
Build a Godot graph instance from parsed data.
def build_top_graph(self,tokens): """ Build a Godot graph instance from parsed data. """ # Get basic graph information. strict = tokens[0] == 'strict' graphtype = tokens[1] directed = graphtype == 'digraph' graphname = tokens[2] # Build the graph g...
Builds a Godot graph.
def build_graph(self, graph, tokens): """ Builds a Godot graph. """ subgraph = None for element in tokens: cmd = element[0] if cmd == ADD_NODE: cmd, nodename, opts = element graph.add_node(nodename, **opts) elif cmd ==...
Given a duration in seconds determines the best units and multiplier to use to display the time. Return value is a 2 - tuple of units and multiplier.
def get_time_units_and_multiplier(seconds): """ Given a duration in seconds, determines the best units and multiplier to use to display the time. Return value is a 2-tuple of units and multiplier. """ for cutoff, units, multiplier in units_table: if seconds < cutoff: break re...
Formats a number of seconds using the best units.
def format_duration(seconds): """Formats a number of seconds using the best units.""" units, divider = get_time_units_and_multiplier(seconds) seconds *= divider return "%.3f %s" % (seconds, units)
Trait initialiser.
def _name_default(self): """ Trait initialiser. """ # 'obj' is a io.File self.obj.on_trait_change(self.on_path, "path") return basename(self.obj.path)
Handle the file path changing.
def on_path(self, new): """ Handle the file path changing. """ self.name = basename(new) self.graph = self.editor_input.load()
Creates the toolkit - specific control that represents the editor. parent is the toolkit - specific control that is the editor s parent.
def create_ui(self, parent): """ Creates the toolkit-specific control that represents the editor. 'parent' is the toolkit-specific control that is the editor's parent. """ self.graph = self.editor_input.load() view = View(Item(name="graph", editor=graph_tree_edit...
Split a sequence into pieces of length n
def nsplit(seq, n=2): """ Split a sequence into pieces of length n If the length of the sequence isn't a multiple of n, the rest is discarded. Note that nsplit will split strings into individual characters. Examples: >>> nsplit("aabbcc") [("a", "a"), ("b", "b"), ("c", "c")] >>> nsplit("aab...
Code snippet from Python Cookbook 2nd Edition by David Ascher Alex Martelli and Anna Ravenscroft ; O Reilly 2005
def windows(iterable, length=2, overlap=0, padding=True): """ Code snippet from Python Cookbook, 2nd Edition by David Ascher, Alex Martelli and Anna Ravenscroft; O'Reilly 2005 Problem: You have an iterable s and need to make another iterable whose items are sublists (i.e., sliding windows), each of the...