Return Statement as a networkx graph.
18454
def to_graph(self):
        """"""
        def json_node(graph, element, prefix):
            if not element:
                return None
            node_id = '|'.join(prefix)
            if isinstance(element, list):
                graph.add_node(node_id, label='')
                # Enumerate children and add nodes and connect to anchor node
                for i, sub_element in enumerate(element):
                    sub_id = json_node(graph, sub_element, prefix + ['%s' % i])
                    if sub_id:
                        graph.add_edge(node_id, sub_id, label='')
            elif isinstance(element, dict):
                graph.add_node(node_id, label='')
                # Add node recursively for each element
                # Connect to this node with edge label according to key
                for k, v in element.items():
                    if k == 'id':
                        continue
                    elif k == 'name':
                        graph.node[node_id]['label'] = v
                        continue
                    elif k == 'type':
                        graph.node[node_id]['label'] = v
                        continue

                    sub_id = json_node(graph, v, prefix + ['%s' % k])
                    if sub_id:
                        graph.add_edge(node_id, sub_id, label=('%s' % k))
            else:
                if isinstance(element, basestring) and \
                   element.startswith('http'):
                    element = element.split('/')[-1]
                graph.add_node(node_id, label=('%s' % str(element)))
            return node_id
        jd = self.to_json()
        graph = networkx.DiGraph()
        json_node(graph, jd, ['%s' % self.uuid])
        return graph
364191
def nt(graph):
    """"""
    from rdflib import ConjunctiveGraph
    from rdflib.plugin import register, Parser

    register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')

    click.echo(
        ConjunctiveGraph().parse(
            data=_jsonld(graph, 'expand'),
            format='json-ld',
        ).serialize(format='nt')
    )
782436
def to_call_agraph(self):
        

        A = nx.nx_agraph.to_agraph(self.call_graph)
        A.graph_attr.update({"dpi": 227, "fontsize": 20, "fontname": "Menlo"})
        A.node_attr.update(
            {"shape": "rectangle", "color": "#650021", "style": "rounded"}
        )
        A.edge_attr.update({"color": "#650021", "arrowsize": 0.5})
        return A
868948
function dflowFun () {
    var gotReturn = false
    var returnValue
    var outs = {}

    // Inject run-time builtin tasks.

    funcs['this'] = function () { return dflowFun }
    funcs['this.graph'] = function () { return graph }
    injectArguments(funcs, task, arguments)

    /**
     * Execute task.
     */

    function run (taskKey) {
      var args = inputArgs(outs, pipe, taskKey)
      var taskName = task[taskKey]
      var f = funcs[taskName]

      // Behave like a JavaScript function:
      // if found a return, skip all other tasks.

      if (gotReturn) return

      if ((taskName === 'return') && (!gotReturn)) {
        returnValue = args[0]
        gotReturn = true
        return
      }

      // If task is not defined at run time, throw an error.

      if (no(f)) {
        var taskNotFound = new Error('Task not found: ' + taskName + ' [' + taskKey + '] ')
        taskNotFound.taskKey = taskKey
        taskNotFound.taskName = taskName
      }

      // Try to execute task.

      try {
        outs[taskKey] = f.apply(null, args)
      } catch (err) {
        // Enrich error with useful dflow task info.
        err.taskName = taskName
        err.taskKey = taskKey

        throw err
      }
    }

    // Run every graph task, sorted by level.

    Object.keys(task)
      .filter(comments)
      .sort(byLevel)
      .forEach(run)

    return returnValue
  }
1353880
def graph(bare=False, json=False, json_tree=False, reverse=False):
    """"""
    from ..core import do_graph

    do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse)
772610
def nx_to_ontology(graph, source_node, output_path, base_iri):
    
    ontology = owlready.Ontology(base_iri)

    parent_lookup = {
        source_node: types.new_class(source_node, (owlready.Thing,), kwds={"ontology": ontology})
    }

    def recur(pnode):
        for neighbor in graph.neighbors(pnode):
            data = graph.node[neighbor]
            neighbor_class = types.new_class(neighbor, (parent_lookup[pnode],), kwds={"ontology": ontology})
            owlready.ANNOTATIONS[neighbor_class].add_annotation(owlready.rdfs.label, data['label'])
            recur(neighbor)

    recur(source_node)

    ontology.save(filename=output_path)
567281
def get_idb_graph():
    
    digraph = nx.DiGraph()

    for function in functions():
        for xref in itertools.chain(function.xrefs_from, function.xrefs_to):
            frm = _try_get_function_start(xref.frm)
            to = _try_get_function_start(xref.to)

            digraph.add_edge(frm, to)

    return digraph
724060
def return_action(self, text, loc, ret):
        """"""
        exshared.setpos(loc, text)
        if DEBUG > 0:
            print("RETURN:",ret)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        if not self.symtab.same_types(self.shared.function_index, ret.exp[0]):
            raise SemanticException("Incompatible type in return")
        #set register for function's return value to expression value
        reg = self.codegen.take_function_register()
        self.codegen.move(ret.exp[0], reg)
        #after return statement, register for function's return value is available again
        self.codegen.free_register(reg)
        #jump to function's exit
        self.codegen.unconditional_jump(self.codegen.label(self.shared.function_name+"_exit", True))
467407
function (graph, opts, params) {
    var self = this;
    var savedNodes = graph.allNodes.filter(function(node) {
      return node.props[self.db.options.id] != null 
          && !(node.model.uniqueness && node.model.uniqueness.returnOld);
    });

    if (!savedNodes.length) return '';

    var statements = savedNodes.map(function(node) {
      params[node.name + 'id'] = getId(self.db, node.props);
      return node.name + '=node({' + node.name + 'id})';
    });

    return 'START ' + statements.join(',');
  }
249164
def dev_from_index(self, if_index):
        """"""
        try:
            if_index = int(if_index)  # Backward compatibility
            return next(iface for iface in six.itervalues(self)
                        if iface.win_index == if_index)
        except (StopIteration, RuntimeError):
            if str(if_index) == "1":
                # Test if the loopback interface is set up
                if isinstance(scapy.consts.LOOPBACK_INTERFACE, NetworkInterface):  # noqa: E501
                    return scapy.consts.LOOPBACK_INTERFACE
            raise ValueError("Unknown network interface index %r" % if_index)
907765
def tnet_to_nx(df, t=None):
    
    if t is not None:
        df = get_network_when(df, t=t)
    if 'weight' in df.columns:
        nxobj = nx.from_pandas_edgelist(
            df, source='i', target='j', edge_attr='weight')
    else:
        nxobj = nx.from_pandas_edgelist(df, source='i', target='j')
    return nxobj
105737
def _network_show(self, name, network_lst):
        '''
        
        '''
        for net in network_lst:
            if net.label == name:
                return net.__dict__
        return {}
391194
def get_graph_by_id(self, network_id: int) -> BELGraph:
        """"""
        network = self.get_network_by_id(network_id)
        log.debug('converting network [id=%d] %s to bel graph', network_id, network)
        return network.as_bel()
743803
def to_networkx(cyjs, directed=True):
    

    if directed:
        g = nx.MultiDiGraph()
    else:
        g = nx.MultiGraph()

    network_data = cyjs[DATA]
    if network_data is not None:
        for key in network_data.keys():
            g.graph[key] = network_data[key]

    nodes = cyjs[ELEMENTS][NODES]
    edges = cyjs[ELEMENTS][EDGES]

    for node in nodes:
        data = node[DATA]
        g.add_node(data[ID], attr_dict=data)

    for edge in edges:
        data = edge[DATA]
        source = data[SOURCE]
        target = data[TARGET]

        g.add_edge(source, target, attr_dict=data)

    return g
746491
def dump(args):
    """"""
    if len(args) != 1:
        log.error('One target required.')
        app.quit(1)

    try:
        bb = Butcher()
        bb.load_graph(args[0])
    except error.BrokenGraph as lolno:
        log.fatal(lolno)
        app.quit(1)
    print "Nodes:"
    pprint.pprint(bb.graph.node)
    print "Edges:"
    pprint.pprint(bb.graph.edge)
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
128985
def _create_graph(self, return_target_sources=None):
        
        if return_target_sources is None:
            # We set it to a defaultdict in order to be consistent with the
            # actual parameter.
            return_target_sources = defaultdict(list)

        cfg = networkx.DiGraph()
        # The corner case: add a node to the graph if there is only one block
        if len(self._nodes) == 1:
            cfg.add_node(self._nodes[next(iter(self._nodes.keys()))])

        # Adding edges
        for tpl, targets in self._exit_targets.items():
            basic_block = self._nodes[tpl] # Cannot fail :)
            for ex, jumpkind in targets:
                if ex in self._nodes:
                    target_bbl = self._nodes[ex]
                    cfg.add_edge(basic_block, target_bbl, jumpkind=jumpkind)

                    # Add edges for possibly missing returns
                    if basic_block.addr in return_target_sources:
                        for src_irsb_key in \
                                return_target_sources[basic_block.addr]:
                            cfg.add_edge(self._nodes[src_irsb_key],
                                               basic_block, jumpkind="Ijk_Ret")
                else:
                    # Debugging output
                    def addr_formalize(addr):
                        if addr is None:
                            return "None"
                        else:
                            return "%#08x" % addr

                    s = "(["
                    for addr in ex[:-1]:
                        s += addr_formalize(addr) + ", "
                    s += "] %s)" % addr_formalize(ex[-1])
                    l.warning("Key %s does not exist.", s)

        return cfg