Render the graph, and return (l)xml etree
765722
def render_tree(self, **kwargs):
        """"""
        self.setup(**kwargs)
        svg = self.svg.root
        for f in self.xml_filters:
            svg = f(svg)
        self.teardown()
        return svg
900034
def to_string(self):
        
        
        
        graph = list()
        
        if self.obj_dict.get('strict', None) is not None:
        
            if self==self.get_parent_graph() and self.obj_dict['strict']:
            
                graph.append('strict ')

        if self.obj_dict['name'] == '':
            if 'show_keyword' in self.obj_dict and self.obj_dict['show_keyword']:
                graph.append( 'subgraph {\n' )
            else:
                graph.append( '{\n' )
        else:
            graph.append( '%s %s {\n' % (self.obj_dict['type'], self.obj_dict['name']) )


        for attr in self.obj_dict['attributes'].iterkeys():
        
            if self.obj_dict['attributes'].get(attr, None) is not None:
       
                val = self.obj_dict['attributes'].get(attr)
                if val is not None:
                    graph.append( '%s=%s' % (attr, quote_if_necessary(val)) )
                else:
                    graph.append( attr )
                    
                graph.append( ';\n' )


        edges_done = set()
        
        edge_obj_dicts = list()
        for e in self.obj_dict['edges'].itervalues():
            edge_obj_dicts.extend(e)
            
        if edge_obj_dicts:
            edge_src_set, edge_dst_set = zip( *[obj['points'] for obj in edge_obj_dicts] )
            edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set)
        else:
            edge_src_set, edge_dst_set = set(), set()
            
        node_obj_dicts = list()
        for e in self.obj_dict['nodes'].itervalues():
            node_obj_dicts.extend(e)

        sgraph_obj_dicts = list()
        for sg in self.obj_dict['subgraphs'].itervalues():
            sgraph_obj_dicts.extend(sg)

        
        obj_list = [ (obj['sequence'], obj) for obj in (edge_obj_dicts + node_obj_dicts + sgraph_obj_dicts) ]
        obj_list.sort()
        
        for idx, obj in obj_list:
        
            if obj['type'] == 'node':

                node = Node(obj_dict=obj)
            
                if self.obj_dict.get('suppress_disconnected', False):
                
                    if (node.get_name() not in edge_src_set and
                        node.get_name() not in edge_dst_set):
                        
                        continue
                        
                graph.append( node.to_string()+'\n' )

            elif obj['type'] == 'edge':

                edge = Edge(obj_dict=obj)
                
                if self.obj_dict.get('simplify', False) and edge in edges_done:
                    continue
                
                graph.append( edge.to_string() + '\n' )
                edges_done.add(edge)
                
            else:
            
                sgraph = Subgraph(obj_dict=obj)
                
                graph.append( sgraph.to_string()+'\n' )

        graph.append( '}\n' )
        
        return ''.join(graph)
1373531
def render(options = {})
      options[:graph_id]    ||= 'scruffy_graph'
      options[:complexity]  ||= (global_complexity || :normal)

      # Allow subclasses to muck with components prior to renders.
      rendertime_renderer = self.clone
      rendertime_renderer.instance_eval { before_render if respond_to?(:before_render) }

      svg = Builder::XmlMarkup.new(:indent => 2)
      unless options[:no_doctype_header]
        svg.instruct!
        svg.declare! :DOCTYPE, :svg, :PUBLIC, "-//W3C//DTD SVG 1.0//EN", "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"
      end
      svg.svg(:xmlns => "http://www.w3.org/2000/svg", 'xmlns:xlink' => "http://www.w3.org/1999/xlink", :width => options[:size].first, :height => options[:size].last) {
        svg.g(:id => options[:graph_id]) {
          rendertime_renderer.components.each do |component|
            component.render(svg, 
                             bounds_for( options[:size], component.position, component.size ), 
                             options)
          end
        }
      }
      svg.target!
    end
604813
def render(self, parsed):
        
        self.renderer.root_node = parsed
        with self.renderer as r:
            return r.render(parsed)
134104
def _build_graph(self):
        ''''''

        # Set palette colors if necessary
        if not self.colors:
            self.palette = self.env.get_template('palette.js')
            self.template_vars.update({'palette': self.palette.render()})
            self.colors = {x['name']: 'palette.color()' for x in self.json_data}

        template_vars = []
        for index, dataset in enumerate(self.json_data):
            group = 'datagroup' + str(index)
            template_vars.append({'name': str(dataset['name']),
                                  'color': self.colors[dataset['name']],
                                  'data': 'json[{0}].data'.format(index)})

        variables = {'dataset': template_vars, 'width': self.width,
                     'height': self.height, 'render': self.renderer,
                     'chart_id': self.chart_id}
        if not self.y_zero:
            variables.update({'min': "min: 'auto',"})

        graph = self.env.get_template('graph.js')
        self.template_vars.update({'graph': graph.render(variables)})
14344
def render(self, engine, context):
        
        # We avoid use of the ternary operator for Python 2.4 support.
        def get_unicode(node):
            if type(node) is unicode:
                return node
            return node.render(engine, context)
        parts = map(get_unicode, self._parse_tree)
        s = ''.join(parts)

        return unicode(s)
445887
def html(string)
      ptr = Libcgraph.agstrdup_html(graph.ptr, string)
      string = ptr.read_string
      Libcgraph.agstrfree graph.ptr, ptr

      string
    end
1080062
def draw_tree(node,
              child_iter=lambda n: n.children,
              text_str=str):
    """"""
    return LeftAligned(traverse=Traversal(get_text=text_str,
                                          get_children=child_iter),
                       draw=LegacyStyle())(node)
166641
def render(self, parsed, page=False, minify=False):
        
        # Create a random ID prefix to make sure parses don't receive the
        # same ID, even if they're identical
        id_prefix = uuid.uuid4().hex
        rendered = []
        for i, p in enumerate(parsed):
            if i == 0:
                settings = p.get("settings", {})
                self.direction = settings.get("direction", DEFAULT_DIR)
                self.lang = settings.get("lang", DEFAULT_LANG)
            render_id = "{}-{}".format(id_prefix, i)
            svg = self.render_svg(render_id, p["words"], p["arcs"])
            rendered.append(svg)
        if page:
            content = "".join([TPL_FIGURE.format(content=svg) for svg in rendered])
            markup = TPL_PAGE.format(
                content=content, lang=self.lang, dir=self.direction
            )
        else:
            markup = "".join(rendered)
        if minify:
            return minify_html(markup)
        return markup
924212
def render(self, xml, context, raise_on_errors=True):
        """"""

        if xml:
            self.xml = xml

            # render XSL
            self.render_xsl(self.root, context)

            # create root XSL sheet
            xsl_ns = self.namespaces['xsl']
            rootName = etree.QName(xsl_ns, 'stylesheet')
            root = etree.Element(rootName, nsmap={'xsl': xsl_ns})
            sheet = etree.ElementTree(root)
            template = etree.SubElement(root, etree.QName(xsl_ns, "template"), match='/')

            # put OpenOffice tree into XSLT sheet
            template.append(self.root)
            self.root = root

            # drop XSL styles
            self.remove_style()

            #self.debug(self.xml)

            try:
                # transform XSL
                xsl = etree.XSLT(self.root)
                self.root = xsl(context)

            except etree.Error as e:
                # log errors
                for l in e.error_log:
                    self.error("XSLT error at line %s col %s:" % (l.line, l.column))
                    self.error("    message: %s" % l.message)
                    self.error("    domain: %s (%d)" % (l.domain_name, l.domain))
                    self.error('    type: %s (%d)' % (l.type_name, l.type))
                    self.error('    level: %s (%d)' % (l.level_name, l.level))
                    self.error('    filename: %s' % l.filename)

                if raise_on_errors:
                    raise

            return self.xml

        else:
            return xml
105777
def render_as_xml(func):
    
    if inspect.isclass(func):
        setattr(func, "_renderer", xml_renderer)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, dicttoxml)
        return decorated_view
1260176
def render_response(self, **kwargs):
        """"""
        from flask import Response
        return Response(self.render(**kwargs), mimetype='image/svg+xml')
443823
def render_output_json(self, graph_data, output_file=None):
        """"""
        if output_file:
            with open(output_file, 'wt') as json_output_f:
                json.dump(graph_data, json_output_f)
        else:
            self.stdout.write(json.dumps(graph_data))
1138886
def etree(self, data, root=None):
        ''''''
        result = self.list() if root is None else root
        if isinstance(data, (self.dict, dict)):
            for key, value in data.items():
                if isinstance(value, (self.dict, dict)):
                    elem = self.element(key)
                    if elem is None:
                        continue
                    result.append(elem)

                    if 'attributes' in value:
                        for k, v in value['attributes'].items():
                            elem.set(k, self._tostring(v))
                    # else:
                    #     raise ValueError('Cobra requires "attributes" key for each element')

                    if 'children' in value:
                        for v in value['children']:
                            self.etree(v, root=elem)
                else:
                    elem = self.element(key)
                    if elem is None:
                        continue
                    elem.text = self._tostring(value)
                    result.append(elem)
        else:
            if root is not None:
                root.text = self._tostring(data)
            else:
                elem = self.element(self._tostring(data))
                if elem is not None:
                    result.append(elem)

        return result
1010963
def to_graphml()
      builder = Builder::XmlMarkup.new(:indent => 1)
      builder.instruct! :xml, :version => "1.0"

      graphml_attribs = {
        "xmlns" => "http://graphml.graphdrawing.org/xmlns",
        "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
        "xmlns:y" => "http://www.yworks.com/xml/graphml",
        "xmlns:yed" => "http://www.yworks.com/xml/yed/3",
        "xsi:schemaLocation" => "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd",
        :directed => "1",
        :label => "test"
      }

      builder.graphml(graphml_attribs) do

        # Define key id's at top of graphml file
        builder.key({:for=>"node", :id=>"d3", "yfiles.type"=>"nodegraphics"})

        # Build Graph 
        #
        builder.graph({:id=>"G"}) do

          vertices.each do |vertex|

            builder.node(:id => compute_key([vertex.name, vertex.object_id])) do

              builder.data({:key=>"d3"}) do
                builder.tag!("y:ShapeNode") do

                  graphics = vertex.data.fetch(:graphics, {})
                  graphics.fetch(:fill, []).each    {|f| builder.tag! "y:Fill",    {:color=>f, :transparent=>"false"}}
                  graphics.fetch(:shape,[]).each    {|s| builder.tag! "y:Shape",   {:type=>s}}
                  graphics.fetch(:geometry,[]).each {|s| builder.tag! "y:Geometry", s}
                  graphics.fetch(:label,[]).each    {|l| builder.tag! "y:NodeLabel", l}
                end
              end
            end
          end

          edges.each do |edge|
            source = edge.origin_vertex
            target = edge.destination_vertex

            options = edge.data[:options]
            label   = ""

            builder.edge(
              :source => s = compute_key([source.name, source.object_id]), 
              :target => t = compute_key([target.name, target.object_id]), 
              :id => compute_key([source.name, target.name, edge.object_id]),
              :label => "#{label}"
            ) do
              #edge[:attributes].each_pair { |k, v| 
              #  id_str = compute_key([k,:edge_attr])
              #  builder.data(v.to_s, {:key=>@guid[id_str]})
              #}
            end
          end
        end
      end
      builder.target!
    end
416492
def graph_to_dot(graph, node_renderer=None, edge_renderer=None):
    """"""
    node_pairs = list(graph.nodes.items())
    edge_pairs = list(graph.edges.items())

    if node_renderer is None:
        node_renderer_wrapper = lambda nid: ''
    else:
        node_renderer_wrapper = lambda nid: ' [%s]' % ','.join(
            ['%s=%s' % tpl for tpl in list(node_renderer(graph, nid).items())])

    # Start the graph
    graph_string = 'digraph G {\n'
    graph_string += 'overlap=scale;\n'

    # Print the nodes (placeholder)
    for node_id, node in node_pairs:
        graph_string += '%i%s;\n' % (node_id, node_renderer_wrapper(node_id))

    # Print the edges
    for edge_id, edge in edge_pairs:
        node_a = edge['vertices'][0]
        node_b = edge['vertices'][1]
        graph_string += '%i -> %i;\n' % (node_a, node_b)

    # Finish the graph
    graph_string += '}'

    return graph_string
284271
def load_graph_xml(xml, filename, load_all=False):
    ''''''
    ret = []
    try:
        root = objectify.fromstring(xml)
    except Exception:
        return []
    if root.tag != 'graphs':
        return []
    if not hasattr(root, 'graph'):
        return []
    for g in root.graph:
        name = g.attrib['name']
        expressions = [e.text for e in g.expression]
        if load_all:
            ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
            continue
        if have_graph(name):
            continue
        for e in expressions:
            if expression_ok(e):
                ret.append(GraphDefinition(name, e, g.description.text, expressions, filename))
                break
    return ret