takes a document graph, converts it into GraphML format and writes it to
    a file.
519128
def write_graphml(docgraph, output_file):
    
    dg_copy = deepcopy(docgraph)
    layerset2str(dg_copy)
    attriblist2str(dg_copy)
    remove_root_metadata(dg_copy)
    nx_write_graphml(dg_copy, output_file)
1340908
private <T,E extends TypedEdge<T>> void write(
                         Multigraph<T,E> g, File f, Map<T,Color> edgeColors, 
                         boolean useColors, Indexer<String> vertexLabels,
                         boolean useLabels) throws IOException {

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
            docBuilder = dbfac.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            throw new IOError(new IOException(pce));
        }
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement("gexf");
        root.setAttribute("xmlns","http://www.gexf.net/1.2draft");
        root.setAttribute("xmlns:viz", "http://www.gexf.net/1.2draft/viz");
        root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.setAttribute("version","1.2");
        root.setAttribute("xsi:schemaLocation","http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd");
        doc.appendChild(root);

        Element graph = doc.createElement("graph");
        graph.setAttribute("defaultedgetype","undirected");
        root.appendChild(graph);

        Element nodes = doc.createElement("nodes");
        graph.appendChild(nodes);
        Element edges = doc.createElement("edges");
        graph.appendChild(edges);

        IntIterator vIter = g.vertices().iterator();
        while (vIter.hasNext()) {
            int vertex = vIter.next();
            Element node = doc.createElement("node");
            node.setAttribute("id", String.valueOf(vertex));
            if (useLabels) 
                node.setAttribute("label", vertexLabels.lookup(vertex));
            else
                node.setAttribute("label", String.valueOf(vertex));
            nodes.appendChild(node);
        }

        ColorGenerator cg = null;
        if (useColors)
            cg = new ColorGenerator();

        int edgeId = 0;
        for (E e : g.edges()) {
            Element edge = doc.createElement("edge");
            edges.appendChild(edge);
            edge.setAttribute("id", "" + (edgeId++));
            edge.setAttribute("source", String.valueOf(e.from()));
            edge.setAttribute("target", String.valueOf(e.to()));
            edge.setAttribute("label", String.valueOf(e.edgeType()));
            if (useColors) {
                Element cEdge = doc.createElement("viz:color");
                edge.appendChild(cEdge);
                Color c = edgeColors.get(e.edgeType());
                if (c == null) {
                    c = cg.next();
                    edgeColors.put(e.edgeType(), c);
                }
                cEdge.setAttribute("r", String.valueOf(c.getRed()));
                cEdge.setAttribute("g", String.valueOf(c.getGreen()));
                cEdge.setAttribute("b", String.valueOf(c.getBlue()));
            }
        }

        // Set up a transformer
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "2");
        
            // Create string from xml tree
            BufferedOutputStream bos = 
                new BufferedOutputStream(new FileOutputStream(f));
            StreamResult result = new StreamResult(bos);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            bos.close();         
        } catch (TransformerException te) {
            throw new IOError(new IOException(te));
        }
    }
1301866
def write_paula(docgraph, output_root_dir, human_readable=False):
    
    paula_document = PaulaDocument(docgraph, human_readable=human_readable)
    error_msg = ("Please specify an output directory.\nPaula documents consist"
                 " of multiple files, so we can't just pipe them to STDOUT.")
    assert isinstance(output_root_dir, str), error_msg
    document_dir = os.path.join(output_root_dir, paula_document.name)
    if not os.path.isdir(document_dir):
        create_dir(document_dir)
    for paula_id in paula_document.files:
        with open(os.path.join(document_dir, paula_id+'.xml'), 'w') as outfile:
            outfile.write(
                paula_etree_to_string(paula_document.files[paula_id],
                                      paula_document.file2dtd[paula_id]))
830965
def write_xml_document(self, document):
        
        self._out.write(ET.tostring(document))
        self._out.flush()
945457
function saveGraphSON(graph, filename, callback) {
        var FileOutputStream = Tinkerpop.autoImport('FileOutputStream');
        var stream = new FileOutputStream(filename);
        return Tinkerpop.GraphSONWriter.buildP()
            .then(function (builder) {
            return _newGraphSONMapper()
                .then(function (mapper) { return builder.mapperP(mapper); });
        })
            .then(function (builder) { return builder.createP(); })
            .then(function (writer) { return writer.writeGraphP(stream, graph); })
            .then(function () { return graph; })
            .nodeify(callback);
    }
1001435
def write(graph, fileformat=None, filename=None):
        

        filewriter = None
        if fileformat is None:
            fileformat = 'turtle'
        if filename is not None:

            with open(filename, 'wb') as filewriter:
                LOG.info("Writing triples in %s to %s", fileformat, filename)
                # rdflib serialize
                graph.serialize(filewriter, format=fileformat)
        else:
            print(graph.serialize(fileformat).decode())
        return
706768
def from_graphxml(source)
      listener = MutableGraphParser.new(self)
      REXML::Document.parse_stream(source, listener)
      self
    end
1139266
def graph_draw(dir: '/tmp', format: 'svg'.freeze)
      graph_save do |dotfile|
        base = File.basename(dotfile.path)
        dest = File.join(dir, "#{base}.#{format}")
        system("dot -T#{format} #{dotfile.path} -o #{dest}")
        dest
      end
    end
385097
public int writeGraphToFile(byte[] img, File to)
	{
		try
		{
			FileOutputStream fos = new FileOutputStream(to);
			fos.write(img);
			fos.close();
		} catch (IOException ioe)
		{
			return -1;
		}

		return 1;

	}
891795
function Graph(xml) {
    var _xml = {};

    // Basic Properties
    //------------------
    _xml.els = {
      root: xml.getElementsByTagName('gexf')[0],
      graph: xml.getElementsByTagName('graph')[0],
      meta: xml.getElementsByTagName('meta')[0],
      nodes: xml.getElementsByTagName('node'),
      edges: xml.getElementsByTagName('edge'),
      model: _helpers.getModelTags(xml)
    };

    // Information
    _xml.hasViz = !!_helpers.getAttributeNS(_xml.els.root, 'xmlns', 'viz');
    _xml.version = _xml.els.root.getAttribute('version') || '1.0';
    _xml.mode = _xml.els.graph.getAttribute('mode') || 'static';

    var edgeType = _xml.els.graph.getAttribute('defaultedgetype');
    _xml.defaultEdgetype = edgeType || 'undirected';

    // Parser Functions
    //------------------

    // Meta Data
    function _metaData() {

      var metas = {};
      if (!_xml.els.meta)
        return metas;

      // Last modified date
      metas.lastmodifieddate = _xml.els.meta.getAttribute('lastmodifieddate');

      // Other information
      _helpers.nodeListEach(_xml.els.meta.childNodes, function(child) {
        metas[child.tagName.toLowerCase()] = child.textContent;
      });

      return metas;
    }

    // Model
    function _model(cls) {
      var attributes = [];

      // Iterating through attributes
      if (_xml.els.model[cls])
        _helpers.nodeListEach(_xml.els.model[cls], function(attr) {

          // Properties
          var properties = {
            id: attr.getAttribute('id') || attr.getAttribute('for'),
            type: attr.getAttribute('type') || 'string',
            title: attr.getAttribute('title') || ''
          };

          // Defaults
          var default_el = _helpers.nodeListToArray(attr.childNodes);

          if (default_el.length > 0)
            properties.defaultValue = default_el[0].textContent;

          // Creating attribute
          attributes.push(properties);
        });

      return attributes.length > 0 ? attributes : false;
    }

    // Data from nodes or edges
    function _data(model, node_or_edge) {

      var data = {};
      var attvalues_els = node_or_edge.getElementsByTagName('attvalue');

      // Getting Node Indicated Attributes
      var ah = _helpers.nodeListToHash(attvalues_els, function(el) {
        var attributes = _helpers.namedNodeMapToObject(el.attributes);
        var key = attributes.id || attributes['for'];

        // Returning object
        return {key: key, value: attributes.value};
      });


      // Iterating through model
      model.map(function(a) {

        // Default value?
        data[a.id] = !(a.id in ah) && 'defaultValue' in a ?
          _helpers.enforceType(a.type, a.defaultValue) :
          _helpers.enforceType(a.type, ah[a.id]);

      });

      return data;
    }

    // Nodes
    function _nodes(model) {
      var nodes = [];

      // Iteration through nodes
      _helpers.nodeListEach(_xml.els.nodes, function(n) {

        // Basic properties
        var properties = {
          id: n.getAttribute('id'),
          label: n.getAttribute('label') || ''
        };

        // Retrieving data from nodes if any
        if (model)
          properties.attributes = _data(model, n);

        // Retrieving viz information
        if (_xml.hasViz)
          properties.viz = _nodeViz(n);

        // Pushing node
        nodes.push(Node(properties));
      });

      return nodes;
    }

    // Viz information from nodes
    function _nodeViz(node) {
      var viz = {};

      // Color
      var color_el = _helpers.getFirstElementByTagNS(node, 'viz', 'color');

      if (color_el) {
        var color = ['r', 'g', 'b', 'a'].map(function(c) {
          return color_el.getAttribute(c);
        });

        viz.color = _helpers.getRGB(color);
      }

      // Position
      var pos_el = _helpers.getFirstElementByTagNS(node, 'viz', 'position');

      if (pos_el) {
        viz.position = {};

        ['x', 'y', 'z'].map(function(p) {
          viz.position[p] = +pos_el.getAttribute(p);
        });
      }

      // Size
      var size_el = _helpers.getFirstElementByTagNS(node, 'viz', 'size');
      if (size_el)
        viz.size = +size_el.getAttribute('value');

      // Shape
      var shape_el = _helpers.getFirstElementByTagNS(node, 'viz', 'shape');
      if (shape_el)
        viz.shape = shape_el.getAttribute('value');

      return viz;
    }

    // Edges
    function _edges(model, default_type) {
      var edges = [];

      // Iteration through edges
      _helpers.nodeListEach(_xml.els.edges, function(e) {

        // Creating the edge
        var properties = _helpers.namedNodeMapToObject(e.attributes);
        if (!('type' in properties)) {
          properties.type = default_type;
        }

        // Retrieving edge data
        if (model)
          properties.attributes = _data(model, e);


        // Retrieving viz information
        if (_xml.hasViz)
          properties.viz = _edgeViz(e);

        edges.push(Edge(properties));
      });

      return edges;
    }

    // Viz information from edges
    function _edgeViz(edge) {
      var viz = {};

      // Color
      var color_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'color');

      if (color_el) {
        var color = ['r', 'g', 'b', 'a'].map(function(c) {
          return color_el.getAttribute(c);
        });

        viz.color = _helpers.getRGB(color);
      }

      // Shape
      var shape_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'shape');
      if (shape_el)
        viz.shape = shape_el.getAttribute('value');

      // Thickness
      var thick_el = _helpers.getFirstElementByTagNS(edge, 'viz', 'thickness');
      if (thick_el)
        viz.thickness = +thick_el.getAttribute('value');

      return viz;
    }


    // Returning the Graph
    //---------------------
    var nodeModel = _model('node'),
        edgeModel = _model('edge');

    var graph = {
      version: _xml.version,
      mode: _xml.mode,
      defaultEdgeType: _xml.defaultEdgetype,
      meta: _metaData(),
      model: {},
      nodes: _nodes(nodeModel),
      edges: _edges(edgeModel, _xml.defaultEdgetype)
    };

    if (nodeModel)
      graph.model.node = nodeModel;
    if (edgeModel)
      graph.model.edge = edgeModel;

    return graph;
  }
221920
private File writeDotSourceToFile(String str) throws java.io.IOException,
			GraphVizException
	{
		File temp;
		try
		{
			temp = File.createTempFile("graph_", ".dot.tmp");
			FileWriter fout = new FileWriter(temp);
			fout.write(str);
			fout.close();
		} catch (Exception e)
		{
			throw new GraphVizException("Error: I/O error while writing the dot source to temp file!");
		}
		return temp;
	}
616738
function saveGraphSONSync(graph, filename) {
        var FileOutputStream = Tinkerpop.autoImport('FileOutputStream');
        var stream = new FileOutputStream(filename);
        var builder = Tinkerpop.GraphSONWriter.build();
        var mapper = _newGraphSONMapperSync();
        builder.mapper(mapper);
        var writer = builder.create();
        writer.writeGraph(stream, graph);
        return graph;
    }
618540
public void writeDocument(String filename, ProvFormat format, Document document) {
        Namespace.withThreadNamespace(document.getNamespace());
        try {
            logger.debug("writing " + format);
            logger.debug("writing " + filename);
            setNamespaces(document);
            switch (format) {
            case PROVN: {
                u.writeDocument(document, filename, pFactory);
                break;
            }
            case XML: {
                ProvSerialiser serial = ProvSerialiser
                        .getThreadProvSerialiser();
                logger.debug("namespaces " + document.getNamespace());
                serial.serialiseDocument(new File(filename), document, true);
                break;
            }
            case TURTLE: {
                new org.openprovenance.prov.rdf.Utility(pFactory, onto)
                        .dumpRDF(document, RDFFormat.TURTLE, filename);
                break;
            }
            case RDFXML: {
                new org.openprovenance.prov.rdf.Utility(pFactory, onto)
                        .dumpRDF(document, RDFFormat.RDFXML, filename);
                break;
            }
            case TRIG: {
                new org.openprovenance.prov.rdf.Utility(pFactory, onto)
                        .dumpRDF(document, RDFFormat.TRIG, filename);
                break;
            }
            case JSON: {
                new org.openprovenance.prov.json.Converter(pFactory)
                        .writeDocument(document, filename);
                break;
            }
            case DOT: {
                String configFile = null; // TODO: get it as option
                ProvToDot toDot = (configFile == null) ? new ProvToDot(
                        ProvToDot.Config.ROLE_NO_LABEL) : new ProvToDot(
                        configFile);
                toDot.setLayout(layout);
                toDot.convert(document, filename, title);
                break;
            }
            case PDF:
            case JPEG:
            case PNG:
            case SVG: {
                String configFile = null; // give it as option
                File tmp = File.createTempFile("viz-", ".dot");

                String dotFileOut = tmp.getAbsolutePath(); // give it as option,
                                                           // if not available
                                                           // create tmp file
                ProvToDot toDot;
                if (configFile != null) {
                    toDot = new ProvToDot(configFile);
                } else {
                    toDot = new ProvToDot(ProvToDot.Config.ROLE_NO_LABEL);
                }
                toDot.setLayout(layout);
                toDot.convert(document, dotFileOut, filename, extensionMap.get(format), title);
                tmp.delete();
                break;
            }

            default:
                break;
            }
        } catch (JAXBException e) {
            if (verbose != null)
                e.printStackTrace();
            throw new InteropException(e);

        } catch (IOException e) {
            if (verbose != null)
                e.printStackTrace();
            throw new InteropException(e);
        }

    }
1269730
def write_gexf(docgraph, output_file):
    
    dg_copy = deepcopy(docgraph)
    remove_root_metadata(dg_copy)
    layerset2str(dg_copy)
    attriblist2str(dg_copy)
    nx_write_gexf(dg_copy, output_file)
32385
def _text_to_graphiz(self, text):
        """"""
        dot = Source(text, format='svg')
        return dot.pipe().decode('utf-8')
958841
def generate(self):
        
        logger.info('Generating graphs')
        self._generate_graph(
            'by-version',
            'Downloads by Version',
            self._stats.per_version_data,
            'Version'
        )
        self._generate_graph(
            'by-file-type',
            'Downloads by File Type',
            self._stats.per_file_type_data,
            'File Type'
        )
        self._generate_graph(
            'by-installer',
            'Downloads by Installer',
            self._stats.per_installer_data,
            'Installer'
        )
        self._generate_graph(
            'by-implementation',
            'Downloads by Python Implementation/Version',
            self._stats.per_implementation_data,
            'Implementation/Version'
        )
        self._generate_graph(
            'by-system',
            'Downloads by System Type',
            self._stats.per_system_data,
            'System'
        )
        self._generate_graph(
            'by-country',
            'Downloads by Country',
            self._stats.per_country_data,
            'Country'
        )
        self._generate_graph(
            'by-distro',
            'Downloads by Distro',
            self._stats.per_distro_data,
            'Distro'
        )
        self._generate_badges()
        logger.info('Generating HTML')
        html = self._generate_html()
        html_path = os.path.join(self.output_dir, 'index.html')
        with open(html_path, 'wb') as fh:
            fh.write(html.encode('utf-8'))
        logger.info('HTML report written to %s', html_path)
        logger.info('Writing SVG badges')
        for name, svg in self._badges.items():
            path = os.path.join(self.output_dir, '%s.svg' % name)
            with open(path, 'w') as fh:
                fh.write(svg)
            logger.info('%s badge written to: %s', name, path)
215302
def output_to_trivialgraph(file, namer=_trivialgraph_default_namer, block=None):
    
    graph = net_graph(block)
    node_index_map = {}  # map node -> index

    # print the list of nodes
    for index, node in enumerate(graph):
        print('%d %s' % (index, namer(node, is_edge=False)), file=file)
        node_index_map[node] = index

    print('#', file=file)

    # print the list of edges
    for _from in graph:
        for _to in graph[_from]:
            from_index = node_index_map[_from]
            to_index = node_index_map[_to]
            edge = graph[_from][_to]
            print('%d %d %s' % (from_index, to_index, namer(edge)), file=file)