process and display graph
496054
def process(self, flightmode_selections, _flightmodes, block=True):
        ''''''
        self.msg_types = set()
        self.multiplier = []
        self.field_types = []
        self.xlim = None
        self.flightmode_list = _flightmodes

        # work out msg types we are interested in
        self.x = []
        self.y = []
        self.modes = []
        self.axes = []
        self.first_only = []
        re_caps = re.compile('[A-Z_][A-Z0-9_]+')
        for f in self.fields:
            caps = set(re.findall(re_caps, f))
            self.msg_types = self.msg_types.union(caps)
            self.field_types.append(caps)
            self.y.append([])
            self.x.append([])
            self.axes.append(1)
            self.first_only.append(False)

        timeshift = self.timeshift

        for fi in range(0, len(self.mav_list)):
            mlog = self.mav_list[fi]
            self.process_mav(mlog, flightmode_selections)
1356121
async function main() {
  const csv = fs.readFileSync('fsm.csv', { encoding: 'utf8' })
  const dot = graphViz(parseCSV(csv))
  fs.writeFileSync('fsm.dot', dot)
  const viz = new Viz({ Module, render })
  const svg = await viz.renderString(dot)
  fs.writeFileSync('fsm.svg', svg)
}
678530
private void process(int x,int y)
    {
        int A = getSourcePixel(x-1,y-1);
        int B = getSourcePixel(x,y-1);
        int C = getSourcePixel(x+1,y-1);
        int D = getSourcePixel(x-1,y);
        int E = getSourcePixel(x,y);
        int F = getSourcePixel(x+1,y);
        int G = getSourcePixel(x-1,y+1);
        int H = getSourcePixel(x,y+1);
        int I = getSourcePixel(x+1,y+1);
        int E0 = E;
        int E1 = E;
        int E2 = E;
        int E3 = E;
        int E4 = E;
        int E5 = E;
        int E6 = E;
        int E7 = E;
        int E8 = E;
        
        if (different(B,H) && different(D,F)) {
            E0 = !different(D,B) ? D : E;
            E1 = ((!different(D,B)) && different(E,C)) || ((!different(B,F)) && different(E,A)) ? B : E;
            E2 = !different(B,F) ? F : E;
            E3 = ((!different(D,B)) && different(E,G)) || ((!different(D,H)) && different(E,A)) ? D : E;
            E4 = E;
            E5 = ((!different(B,F)) && different(E,I)) || ((!different(H,F)) && different(E,C)) ? F : E;
            E6 = !different(D,H) ? D : E;
            E7 = ((!different(D,H)) && different(E,I)) || ((!different(H,F)) && different(E,G)) ? H : E;
            E8 = !different(H,F) ? F : E;
        }
        
        setDestPixel((x*3),(y*3),E0);
        setDestPixel((x*3)+1,(y*3),E1);
        setDestPixel((x*3)+2,(y*3),E2);
        setDestPixel((x*3),(y*3)+1,E3);
        setDestPixel((x*3)+1,(y*3)+1,E4);
        setDestPixel((x*3)+2,(y*3)+1,E5);
        setDestPixel((x*3),(y*3)+2,E6);
        setDestPixel((x*3)+1,(y*3)+2,E7);
        setDestPixel((x*3)+2,(y*3)+2,E8);
    }
125503
def render_graph(result, cfg, **kwargs):
    
    # Mapping from MIME types to formats accepted by RDFlib
    rdflib_formats = {'text/rdf+n3': 'n3',
                      'text/turtle': 'turtle',
                      'application/x-turtle': 'turtle',
                      'text/turtle': 'turtle',
                      'application/rdf+xml': 'xml',
                      'text/rdf': 'xml',
                      'application/rdf+xml': 'xml'}


    try:
        got = kwargs.get('format', 'text/rdf+n3')
        fmt = rdflib_formats[got]
    except KeyError:
        raise KrnlException('Unsupported format for graph processing: {!s}', got)

    g = ConjunctiveGraph()
    g.load(StringInputSource(result), format=fmt)

    display = cfg.dis[0] if is_collection(cfg.dis) else cfg.dis
    if display in ('png', 'svg'):
        try:
            literal = len(cfg.dis) > 1 and cfg.dis[1].startswith('withlit')
            opt = {'lang': cfg.lan, 'literal': literal, 'graphviz': []}
            data, metadata = draw_graph(g, fmt=display, options=opt)
            return {'data': data,
                    'metadata': metadata}
        except Exception as e:
            raise KrnlException('Exception while drawing graph: {!r}', e)
    elif display == 'table':
        it = rdf_iterator(g, set(cfg.lan), add_vtype=cfg.typ)
        n, data = html_table(it, limit=cfg.lmt, withtype=cfg.typ)
        data += div('Shown: {}, Total rows: {}', n if cfg.lmt else 'all',
                    len(g), css="tinfo")
        data = {'text/html': div(data)}
    elif len(g) == 0:
        data = {'text/html': div(div('empty graph', css='krn-warn'))}
    else:
        data = {'text/plain': g.serialize(format='nt').decode('utf-8')}

    return {'data': data,
            'metadata': {}}
201814
function graph (processedTypes, typeTheme) {
  var result = ''

  if (typeTheme.group) {
    result += 'subgraph cluster_' + groupId++ + ' {'
    if (typeTheme.color) {
      result += 'color=' + typeTheme.color + ';'
    }
    if (typeTheme.groupLabel) {
      result += 'label="' + typeTheme.groupLabel + '";'
    }
  }

  result += _.map(processedTypes, v => {
    // sort if desired
    if (this.theme.field.sort) {
      v.fields = _.sortBy(v.fields, 'name')
    }

    var rows = _.map(v.fields, v => {
      return {
        text: createField.call(this, v),
        port: v.name + 'port'
      }
    })

    return createTable.call(this, {
      typeName: getTypeDisplayName(v.name),
      color: typeTheme.color,
      stereotype: typeTheme.stereotype,
      rows: rows
    })
  }).join('\n')

  if (typeTheme.group) {
    result += '}'
  }

  result += '\n\n'
  return result
}
610716
function Graphviz() {
		var sb = []
		function print(x) {
			sb.push(x)
		}
		print("digraph {")

		var seen_nodes = Object.create(null)
		function makeNodeLabel(node) {
			var str = []
			if (node.isObject) {
				str.push("object")
			}
			if (node.isAny) {
				str.push("any")
			}
			if (node.global) {
				str.push("global")
			}
			node.primitives.forEach(function(t) {
				str.push(formatType(t))
			})
			str.push(node.id)
			return str.join(',')
		}
		var tnode_id = 1;
		function makeTypeNodeId() {
			return 'T' + (tnode_id++)
		}
		function visitTypeNode(tnode, id) {
			print(id + ' [shape=diamond]')
		}
		function visitNode(node) {
			node = node.rep()
			if (seen_nodes[node.id])
				return
			seen_nodes[node.id] = true
			print(node.id + ' [shape=box,label="' + escapeLabel(makeNodeLabel(node)) + '"]')
			if (!node.global || isLive(node)) {
				markAsLive(node)
				node.properties.forEach(function(name,dst) {
					if (name in {})
						return // ignore trivial properties
					if (dst.type === 'node') {
						print(node.id + ' -> ' + dst.node.rep().id + ' [label="' + escapeLabel(name) + '"]')
						visitNode(dst.node)
					} else {
						var id = makeTypeNodeId()
						print(node.id + ' -> ' + id + ' [label="' + escapeLabel(name) + '"]')
						visitTypeNode(dst, id)
					}
				})
				node.prototypes.forEach(function(proto) {
					print(node.id + ' -> ' + proto.rep().id + ' [label="[proto]"]')
					visitNode(proto)
				})
			}
		}

		function visitFNode(fnode) {
			visitNode(fnode.self)
			visitNode(fnode.this)
			visitNode(fnode.arguments)
			visitNode(fnode.return)
			if (fnode.env)
				visitNode(fnode.env)
			// todo: calls?
		}
		var calln = 0
		function visitCall(call) {
			visitNode(call.self)
			visitNode(call.this)
			visitNode(call.arguments)
			visitNode(call.return)
			var id = 'call_' + (calln++)
			print(id + ' [shape=record,label="{{<self> self|<this> this|<arguments> arguments|<return> return}}"]')
			print(call.self.rep().id + " -> " + id + ':self')
			print(call.this.rep().id + " -> " + id + ':this')
			print(call.arguments.rep().id + " -> " + id + ':arguments')
			print(call.return.rep().id + " -> " + id + ':return')
		}

		var node2live = Object.create(null)
		function isLive(node) {
			return node2live[node.rep().id]
		}
		function markAsLive(node) {
			node2live[node.rep().id] = true
		}
		function checkLive(node) {
			node = node.rep()
			if (node.id in node2live)
				return node2live[node.id]
			node2live[node.id] = false
			var isLive = false
			node.properties.forEach(function(name,dst) {
				if (dst.type === 'node' && checkLive(dst.node)) {
					isLive = true
				}
			})
			return node2live[node.id] = isLive
		}
		
		function findAdditionalNodes() {
			all_unodes.forEach(function(node) {
				if (checkLive(node)) {
					visitNode(node)
				}
			})
		}

		this.visitNode = visitNode
		this.visitFNode = visitFNode
		this.visitCall = visitCall
		this.finish = function() {
			findAdditionalNodes()
			print("}\n")
			return sb.join('\n')
		}
	}
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
1362743
def latex_output_graph(self, node):
    
    graph = node['graph']
    parts = node['parts']

    graph_hash = get_graph_hash(node)
    name = "inheritance%s" % graph_hash
    dest_path = os.path.abspath(os.path.join(setup.app.builder.outdir, '_images'))
    if not os.path.exists(dest_path):
        os.makedirs(dest_path)
    pdf_path = os.path.abspath(os.path.join(dest_path, name + ".pdf"))

    graph.run_dot(['-Tpdf', '-o%s' % pdf_path],
                  name, parts, graph_options={'size': '"6.0,6.0"'})
    return '\n\\includegraphics{%s}\n\n' % pdf_path
840342
def output_component(graph, edge_stack, u, v):
    """"""
    edge_list = []
    while len(edge_stack) > 0:
        edge_id = edge_stack.popleft()
        edge_list.append(edge_id)

        edge = graph.get_edge(edge_id)
        tpl_a = (u, v)
        tpl_b = (v, u)
        if tpl_a == edge['vertices'] or tpl_b == edge['vertices']:
            break

    return edge_list
663835
def draw(args):
    """"""
    if len(args) != 2:
        log.error('Two arguments required: [build target] [output file]')
        app.quit(1)

    target = args[0]
    out = args[1]

    try:
        bb = Butcher()
        bb.load_graph(target)
    except error.BrokenGraph as lolno:
        log.fatal(lolno)
        app.quit(1)

    # Filter down to the target and all of its transitive dependencies.
    # TODO: make it possible to optionally draw the entire graph
    filtered_graph = bb.graph.subgraph(
        networkx.topological_sort(bb.graph, nbunch=[address.new(target)]))

    a = networkx.to_agraph(filtered_graph)
    a.draw(out, prog='dot')
    log.info('Graph written to %s', out)
728796
function main(container)
  {
    // Disables the built-in context menu
    mxEvent.disableContextMenu(container);

    // Creates the graph inside the given container
    var graph = new mxGraph(container);
    graph.setConnectable(true);

    // Enables connect preview for the default edge style
    graph.connectionHandler.createEdgeState = function(me)
    {
      var edge = graph.createEdge(null, null, null, null, null);

      return new mxCellState(this.graph.view, edge, this.graph.getCellStyle(edge));
    };

    // Specifies the default edge style
    graph.getStylesheet().getDefaultEdgeStyle()['edgeStyle'] = 'orthogonalEdgeStyle';

    // Enables rubberband selection
    new mxRubberband(graph);

    // Gets the default parent for inserting new cells. This
    // is normally the first child of the root (ie. layer 0).
    var parent = graph.getDefaultParent();

    // Adds cells to the model in a single step
    graph.getModel().beginUpdate();
    try
    {
      var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
      var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
      var e1 = graph.insertEdge(parent, null, '', v1, v2);
    }
    finally
    {
      // Updates the display
      graph.getModel().endUpdate();
    }
  }
297977
def main(graph):
    
    args = parse_args(graph)

    if args.drop:
        drop_all(graph)
    create_all(graph)
217494
def graph(data):
    """"""
    title = data['name'] + ' (' + data['rating'] + ') '
    plt.title(title)
    plt.xlabel('Episode Number')
    plt.ylabel('Ratings')
    rf,ef=graphdata(data)
    col=['red', 'green' , 'orange']
    for i in range(len(rf)):
        x,y=ef[i],rf[i]
        k = i + 1
        plt.plot(x, y,color=col[i%3])
    x1, x2, y1, y2 = plt.axis()
    y2 = 10
    if y1 > 7:
        y1 = 7
    plt.axis([x1, x2, y1, y2])
    plt.show()
468166
function graphvizualize(data, cb) {
  var cp = exec('dot -Tsvg');

  // buffer stdout
  var buf = '';
  cp.stdout.on('data', function (data) {
    buf += data;
  });
  cp.on('error', function () {});
  cp.on('close', function (code) {
    cb(null, code > 0 ? '' : buf);
  });

  // set dot to stdin
  cp.stdin.end(data);
}
1274040
def generate_graphs(data_frames, hardware_info, steps, outdir,
                    verbose=False):
    """"""
    _setup_matplotlib()
    # Hash of hosts containing (data, hardware, steps) tuple
    collectl_info = collections.defaultdict(dict)

    for host, data_frame in data_frames.items():
        if verbose:
            print('Generating CPU graph for {}...'.format(host))
        graph, data_cpu = graph_cpu(data_frame, steps, hardware_info[host]['num_cpus'])

        graph.get_figure().savefig(
            os.path.join(outdir, '{}_cpu.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        ifaces = set([series.split('_')[0]
                      for series in data_frame.keys()
                      if series.startswith(('eth', 'ib'))])

        if verbose:
            print('Generating network graphs for {}...'.format(host))
        graph, data_net_bytes = graph_net_bytes(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_bytes.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        graph, data_net_pkts = graph_net_pkts(data_frame, steps, ifaces)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_net_pkts.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating memory graph for {}...'.format(host))
        graph, data_mem = graph_memory(data_frame, steps, hardware_info[host]["memory"])
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_memory.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        if verbose:
            print('Generating storage I/O graph for {}...'.format(host))
        drives = set([
            series.split('_')[0]
            for series in data_frame.keys()
            if series.startswith(('sd', 'vd', 'hd', 'xvd'))
        ])
        graph, data_disk = graph_disk_io(data_frame, steps, drives)
        graph.get_figure().savefig(
            os.path.join(outdir, '{}_disk_io.png'.format(host)),
            bbox_inches='tight', pad_inches=0.25)
        pylab.close()

        print('Serializing output to pickle object for node {}...'.format(host))
        # "Clean" dataframes ready to be plotted
        collectl_info[host] = { "hardware": hardware_info,
                                "steps": steps, "cpu": data_cpu, "mem": data_mem,
                                "disk": data_disk, "net_bytes": data_net_bytes,
                                "net_pkts": data_net_pkts
                              }
    return collectl_info
956527
def graph(self, name, *args, **kwargs):
        
        return Graph(self, name, *args, **kwargs)
817576
def main():
    """"""
    query = ' '.join(sys.stdin.readlines())

    sys.stdout.write(pretty_print_graphql(query))