returns a dict that represents a NetJSON NetworkGraph object
192619
def json(self):
        
        nodes = []
        links = []

        for link in self.link_set.all():
            if self.is_layer2:
                source = link.interface_a.mac
                destination = link.interface_b.mac
            else:
                source = str(link.interface_a.ip_set.first().address)
                destination = str(link.interface_b.ip_set.first().address)
            nodes.append({
                'id': source
            })
            nodes.append({
                'id': destination
            })
            links.append(OrderedDict((
                ('source', source),
                ('target', destination),
                ('cost', link.metric_value)
            )))

        return OrderedDict((
            ('type', 'NetworkGraph'),
            ('protocol', self.parser.protocol),
            ('version', self.parser.version),
            ('metric', self.parser.metric),
            ('nodes', nodes),
            ('links', links)
        ))
929380
def get_network_by_name(self, nwk_name):
        
        ret_net_lst = []
        try:
            body = {}
            net_list = self.neutronclient.list_networks(body=body)
            net_list = net_list.get('networks')
            for net in net_list:
                if net.get('name') == nwk_name:
                    ret_net_lst.append(net)
        except Exception as exc:
            LOG.error("Failed to get network by name %(name)s, "
                      "Exc %(exc)s",
                      {'name': nwk_name, 'exc': str(exc)})
        return ret_net_lst
513107
def to_json(self):
    """"""
    res_dict = {}

    def gen_dep_edge(node, edge, dep_tgt, aliases):
      return {
        'target': dep_tgt.address.spec,
        'dependency_type': self._edge_type(node.concrete_target, edge, dep_tgt),
        'products_used': len(edge.products_used),
        'products_used_ratio': self._used_ratio(dep_tgt, edge),
        'aliases': [alias.address.spec for alias in aliases],
      }

    for node in self._nodes.values():
      res_dict[node.concrete_target.address.spec] = {
        'cost': self._cost(node.concrete_target),
        'cost_transitive': self._trans_cost(node.concrete_target),
        'products_total': node.products_total,
        'dependencies': [gen_dep_edge(node, edge, dep_tgt, node.dep_aliases.get(dep_tgt, {}))
                         for dep_tgt, edge in node.dep_edges.items()],
      }
    yield str(json.dumps(res_dict, indent=2, sort_keys=True))
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
1061358
def to_json(self):
        
        obj = {
            "vertices": [
                {
                    "id": vertex.id,
                    "annotation": vertex.annotation,
                }
                for vertex in self.vertices
            ],
            "edges": [
                {
                    "id": edge.id,
                    "annotation": edge.annotation,
                    "head": edge.head,
                    "tail": edge.tail,
                }
                for edge in self._edges
            ],
        }
        # Ensure that we always return unicode output on Python 2.
        return six.text_type(json.dumps(obj, ensure_ascii=False))
572204
def convert_json_object(obographdoc, **args):
    
    digraph = networkx.MultiDiGraph()
    xref_graph = networkx.MultiGraph()
    logical_definitions = []
    property_chain_axioms = []
    context = obographdoc.get('@context',{})
    logging.info("CONTEXT: {}".format(context))
    mapper = OboJsonMapper(digraph=digraph, context=context)
    ogs = obographdoc['graphs']
    base_og = ogs[0]
    for og in ogs:
        # TODO: refactor this
        mapper.add_obograph_digraph(og, xref_graph=xref_graph,
                                    logical_definitions=logical_definitions,
                                    property_chain_axioms=property_chain_axioms, **args)

    return {
        'id': base_og.get('id'),
        'meta': base_og.get('meta'),
        'graph': mapper.digraph,
        'xref_graph': xref_graph,
        'graphdoc': obographdoc,
        'logical_definitions': logical_definitions,
        'property_chain_axioms': property_chain_axioms
        }
608346
def get_subnet_dict():
  """"""
  subnet_dict = {}
  vpc = get_vpc()
  for subnet in vpc.subnets.all():
    zone = subnet.availability_zone
    assert zone not in subnet_dict, "More than one subnet in %s, why?" % (zone,)
    subnet_dict[zone] = subnet
  return subnet_dict
665912
def from_dict(self, graph_dict):
        

        self.reset_graph()
        for new_node in six.iterkeys(graph_dict):
            self.add_node(new_node)
        for ind_node, dep_nodes in six.iteritems(graph_dict):
            if not isinstance(dep_nodes, list):
                raise TypeError('dict values must be lists')
            for dep_node in dep_nodes:
                self.add_edge(ind_node, dep_node)
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
1258340
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'url') and self.url is not None:
            _dict['url'] = self.url
        if hasattr(self, 'limit_to_starting_hosts'
                  ) and self.limit_to_starting_hosts is not None:
            _dict['limit_to_starting_hosts'] = self.limit_to_starting_hosts
        if hasattr(self, 'crawl_speed') and self.crawl_speed is not None:
            _dict['crawl_speed'] = self.crawl_speed
        if hasattr(self, 'allow_untrusted_certificate'
                  ) and self.allow_untrusted_certificate is not None:
            _dict[
                'allow_untrusted_certificate'] = self.allow_untrusted_certificate
        if hasattr(self, 'maximum_hops') and self.maximum_hops is not None:
            _dict['maximum_hops'] = self.maximum_hops
        if hasattr(self,
                   'request_timeout') and self.request_timeout is not None:
            _dict['request_timeout'] = self.request_timeout
        if hasattr(
                self,
                'override_robots_txt') and self.override_robots_txt is not None:
            _dict['override_robots_txt'] = self.override_robots_txt
        return _dict
1266354
def convert_to_networkx_graph(data, create_using=None, multigraph_input=False):
    """"""
    if isinstance(data, AllegedGraph):
        result = networkx.convert.from_dict_of_dicts(
            data.adj,
            create_using=create_using,
            multigraph_input=data.is_multigraph()
        )
        result.graph = dict(data.graph)
        result.node = {k: dict(v) for k, v in data.node.items()}
        return result
    return networkx.convert.to_networkx_graph(
        data, create_using, multigraph_input
    )
388428
def from_dict(cls, d):
        
        s = Structure.from_dict(d['structure'])
        return cls(s, d['graphs'])
92083
def parse(self, data):
        
        graph = self._init_graph()
        # ensure is NetJSON NetworkGraph object
        if 'type' not in data or data['type'] != 'NetworkGraph':
            raise ParserError('Parse error, not a NetworkGraph object')
        # ensure required keys are present
        required_keys = ['protocol', 'version', 'metric', 'nodes', 'links']
        for key in required_keys:
            if key not in data:
                raise ParserError('Parse error, "{0}" key not found'.format(key))

        # store metadata
        self.protocol = data['protocol']
        self.version = data['version']
        self.revision = data.get('revision')  # optional
        self.metric = data['metric']

        # create graph
        for node in data['nodes']:
            graph.add_node(node['id'],
                           label=node['label'] if 'label' in node else None,
                           local_addresses=node.get('local_addresses', []),
                           **node.get('properties', {}))
        for link in data['links']:
            try:
                source = link["source"]
                dest = link["target"]
                cost = link["cost"]
            except KeyError as e:
                raise ParserError('Parse error, "%s" key not found' % e)
            properties = link.get('properties', {})
            graph.add_edge(source, dest, weight=cost, **properties)
        return graph
653670
def json(self):
        """"""
        return {
            "id": self.ID,
            "steps": self.steps,
            "graph_source": self.source,
            "errored": self.errored
        }
238925
def dict_to_nx(graph, oriented=False):
    """"""
    nxg = nx.DiGraph() if oriented else nx.Graph()
    for node, succs in graph.items():
        for succ in succs:
            nxg.add_edge(node, succ)
    return nxg
463160
def get_networks(self, contents):
        
        schema = NetworksSchema()
        resp = self.service.post(self.base,
                                 params={'process': 'networks'}, json={'contents': contents})
        return self.service.decode(schema, resp)
17557
def to_networkx(self):
        
        return nx_util.to_networkx(self.session.get(self.__url).json())