Returns the node for an if statement
@param from the starting node (a merge node that represents a conditional)
@param graph the graph to search
@return an import state representing the nodes for each scope
173196
public IfImportState nodesForIf(NodeDef from, GraphDef graph) {
        //Assume we start with a switch statement
        int currNodeIndex = graph.getNodeList().indexOf(from);
        val trueDefName = from.getInput(1);
        val falseDefName = from.getInput(0);
        val scopeId = UUID.randomUUID().toString();
        val scopeName = scopeId + "-" + trueDefName.substring(0,trueDefName.indexOf("/"));
        val trueDefScopeName = scopeName + "-true-scope";
        val falseDefScopeName = scopeName + "-false-scope";


        boolean onFalseDefinition = true;
        //start with the true
        boolean onTrueDefinition = false;

        List<NodeDef> falseBodyNodes = new ArrayList<>();
        List<NodeDef> trueBodyNodes = new ArrayList<>();
        List<NodeDef> conditionNodes = new ArrayList<>();
        Set<String> seenNames = new LinkedHashSet<>();
        /**
         * Accumulate a list backwards to get proper ordering.
         *
         */
        for(int i = currNodeIndex; i >= 0; i--) {
            //switch to false names
            if(graph.getNode(i).getName().equals(trueDefName)) {
                onFalseDefinition = false;
                onTrueDefinition = true;
            }

            //on predicate now
            if(graph.getNode(i).getName().contains("pred_id")) {
                onTrueDefinition = false;
            }
            //don't readd the same node, this causes a stackoverflow
            if(onTrueDefinition  && !graph.getNode(i).equals(from)) {
                trueBodyNodes.add(graph.getNode(i));
            }
            else if(onFalseDefinition && !graph.getNode(i).equals(from)) {
                falseBodyNodes.add(graph.getNode(i));
            }
            //condition scope now
            else {
                val currNode = graph.getNode(i);
                if(currNode.equals(from))
                    continue;

                //break only after bootstrapping the first node (the predicate id node)
                if(!seenNames.contains(graph.getNode(i).getName()) && !graph.getNode(i).getName().contains("pred_id")) {
                    break;
                }

                /**
                 * Continuously add inputs seen for each node in the sub graph that occurs.
                 * Starting from the predicate id, any node that has inputs in the condition scope
                 * are by definition within the scope. Any node not encountered after that is considered out of scope.
                 * This means we break.
                 */
                for(int inputIdx = 0; inputIdx < currNode.getInputCount(); inputIdx++) {
                    seenNames.add(currNode.getInput(inputIdx));
                }



                //ensure the "current node" is added as well
                seenNames.add(graph.getNode(i).getName());
                conditionNodes.add(graph.getNode(i));
            }
        }

        /**
         * Since we are going over the graph backwards,
         * we need to reverse the nodes to ensure proper ordering.
         */
        Collections.reverse(falseBodyNodes);
        Collections.reverse(trueBodyNodes);
        Collections.reverse(conditionNodes);


        return IfImportState.builder()
                .condNodes(conditionNodes)
                .falseNodes(falseBodyNodes)
                .trueNodes(trueBodyNodes)
                .conditionBodyScopeName(falseDefScopeName)
                .falseBodyScopeName(falseDefScopeName)
                .trueBodyScopeName(trueDefScopeName)
                .conditionBodyScopeName(scopeName)
                .build();
    }
193179
public void addEdge(int from, int to) {
        Set<Integer> outEdges = edges.get(from);
        if (outEdges == null) {
            outEdges = new TreeSet<Integer>();
            edges.put(from, outEdges);
        }
        outEdges.add(to);
    }
679336
public void addNode(HtmlMatcherGraphNode node) {
    checkNotNull(node);
    if (graphCursor.isPresent()) {
      graphCursor.get().linkActiveEdgeToNode(node);
    }
    setGraphCursorNode(node);
  }
252735
protected KeyedGraph<V, E> prepareGraph() throws SQLException {
        LOGGER.info("Loading graph into memory...");
        final long start = System.currentTimeMillis();
        // Initialize the graph.
        KeyedGraph<V, E> graph;
        if (!globalOrientation.equals(GraphFunctionParser.Orientation.UNDIRECTED)) {
            if (weightColumn != null) {
                graph = new DirectedWeightedPseudoG<V, E>(vertexClass, edgeClass);
            } else {
                graph = new DirectedPseudoG<V, E>(vertexClass, edgeClass);
            }
        } else {
            if (weightColumn != null) {
                graph = new WeightedPseudoG<V, E>(vertexClass, edgeClass);
            } else {
                graph = new PseudoG<V, E>(vertexClass, edgeClass);
            }
        }
        final Statement st = connection.createStatement();
        final ResultSet edges = st.executeQuery("SELECT * FROM " +
                TableUtilities.parseInputTable(connection, inputTable));
        // Initialize the indices.
        initIndices(edges);
        try {
            // Add the edges.
            while (edges.next()) {
                loadEdge(graph, edges);
            }
            logTime(LOGGER, start);
            return graph;
        } catch (SQLException e) {
            LOGGER.error("Could not store edges in graph.", e);
            return null;
        } finally {
            edges.close();
            st.close();
        }
    }
1047470
private Node getNode(Object entity, ObjectGraph graph, NodeState initialNodeState)
    {
        if (entity == null)
        {
            return null;
        }
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(),
                entity.getClass());

        // entity metadata could be null.
        if (entityMetadata == null)
        {
            throw new IllegalArgumentException(
                    "Entity object is invalid, operation failed. Please check previous log message for details");
        }

        Object id = PropertyAccessorHelper.getId(entity, entityMetadata);
        // Generate and set Id if @GeneratedValue present.
        if (((Field) entityMetadata.getIdAttribute().getJavaMember()).isAnnotationPresent(GeneratedValue.class))
        {
            if (!isIdSet(id))
            {
                id = idGenerator.generateAndSetId(entity, entityMetadata, pd, pd.getKunderaMetadata());
            }
        }

        if (!validator.isValidEntityObject(entity, entityMetadata))
        {
            throw new IllegalArgumentException(
                    "Entity object is invalid, operation failed. Please check previous log message for details");
        }

        // id = PropertyAccessorHelper.getId(entity, entityMetadata);

        String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass());
        Node node = graph.getNode(nodeId);

        // If this node is already there in graph (may happen for bidirectional
        // relationship, do nothing and return null)
        if (node != null)
        {
            if (node.isGraphCompleted())
            {
                return node;
            }
            return null;
        }

        // Construct this Node first, if one not already there in Persistence
        // Cache
        Node nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId, pd);

        // Make a deep copy of entity data

        if (nodeInPersistenceCache == null)
        {
            node = new Node(nodeId, entity, initialNodeState, persistenceCache, id, pd);
        }
        else
        {
            node = nodeInPersistenceCache;
            node.setPersistenceCache(persistenceCache);

            // Determine whether this node is dirty based on comparison between
            // Node data and entity data
            // If dirty, set the entity data into node and mark it as dirty
            if (!DeepEquals.deepEquals(node.getData(), entity))
            {
                node.setDirty(true);
            }
            else if (node.isProcessed())
            {
                node.setDirty(false);
            }

            node.setData(entity);

            // If node is NOT in managed state, its data needs to be
            // replaced with the one provided in entity object
        }

        // Put this node into object graph
        graph.addNode(nodeId, node);

        // Iterate over relations and construct children nodes
        for (Relation relation : entityMetadata.getRelations())
        {
            if (relation != null)
            {
                // Child Object set in this entity
                Object childObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());

                if (childObject != null && !ProxyHelper.isProxy(childObject))
                {
                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(),
                            PropertyAccessorHelper.getGenericClass(relation.getProperty()));

                    if (metadata != null && relation.isJoinedByPrimaryKey())
                    {
                        PropertyAccessorHelper.setId(childObject, metadata,
                                PropertyAccessorHelper.getId(entity, entityMetadata));
                    }
                    // This child object could be either an entity(1-1 or M-1)
                    // or a
                    // collection/ Map of entities(1-M or M-M)
                    if (Collection.class.isAssignableFrom(childObject.getClass()))
                    {
                        // For each entity in the collection, construct a child
                        // node and add to graph
                        Collection childrenObjects = (Collection) childObject;

                        if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects))

                            for (Object childObj : childrenObjects)
                            {
                                if (childObj != null)
                                {
                                    addChildNodesToGraph(graph, node, relation, childObj,
                                            metadata != null ? getChildNodeState(metadata, childObj) : initialNodeState);
                                }
                            }
                    }
                    else if (Map.class.isAssignableFrom(childObject.getClass()))
                    {
                        Map childrenObjects = (Map) childObject;
                        if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects))
                        {
                            for (Map.Entry entry : (Set<Map.Entry>) childrenObjects.entrySet())
                            {
                                addChildNodesToGraph(graph, node, relation, entry,
                                        metadata != null ? getChildNodeState(metadata, entry) : initialNodeState);
                            }
                        }
                    }
                    else
                    {
                        // Construct child node and add to graph
                        addChildNodesToGraph(graph, node, relation, childObject,
                                metadata != null ? getChildNodeState(metadata, childObject) : initialNodeState);
                    }
                }
            }
        }

        // Means compelte graph is build.
        node.setGraphCompleted(true);
        return node;
    }
1345553
private void populateGraph(final EntityGraph<?> graph, final Set<String> fetches)
	{
		Map<String, Subgraph<?>> created = new HashMap<>();

		for (String fetch : fetches)
		{
			final String[] parts = StringUtils.split(fetch, '.');

			// Starts of null (meaning parent is the root graph), updated as we go through path segments to refer to the last path segment
			Subgraph<?> parent = null;

			// Iterate over the path segments, adding attributes subgraphs
			for (int i = 0; i < parts.length; i++)
			{
				final String path = StringUtils.join(parts, '.', 0, i + 1);
				final boolean isLeaf = (i == parts.length - 1);

				final Subgraph<?> existing = created.get(path);

				if (existing == null)
				{
					if (parent == null)
					{
						try
						{
							// Relation under root
							graph.addAttributeNodes(parts[i]);

							// Only set up a subgraph if this is not a leaf node
							// This prevents us trying to add a Subgraph for a List of Embeddable
							if (!isLeaf)
								parent = graph.addSubgraph(parts[i]);
						}
						catch (IllegalArgumentException e)
						{
							throw new IllegalArgumentException("Error adding graph member " +
							                                   parts[i] +
							                                   " with isLeaf=" +
							                                   isLeaf +
							                                   " to root as part of " +
							                                   fetch, e);
						}
					}
					else
					{
						try
						{
							// Relation under parent
							parent.addAttributeNodes(parts[i]);

							// Only set up a subgraph if this is not a leaf node
							// This prevents us trying to add a Subgraph for a List of Embeddable
							if (!isLeaf)
								parent = parent.addSubgraph(parts[i]);
						}
						catch (IllegalArgumentException e)
						{
							throw new IllegalArgumentException("Error adding graph member " +
							                                   parts[i] +
							                                   " with isLeaf=" +
							                                   isLeaf +
							                                   " as part of " +
							                                   fetch +
							                                   " with parent.class=" +
							                                   parent.getClassType(), e);
						}
					}

					if (!isLeaf)
						created.put(path, parent);
				}
				else
				{
					// Already seen this graph node before
					parent = existing;
				}
			}
		}
	}
388086
function loadGraphSONSync(graph, filename) {
        var FileInputStream = Tinkerpop.autoImport('FileInputStream');
        var stream = new FileInputStream(filename);
        var builder = Tinkerpop.GraphSONReader.build();
        var mapper = _newGraphSONMapperSync();
        builder.mapper(mapper);
        var reader = builder.create();
        reader.readGraph(stream, graph);
        return graph;
    }
568705
public <T extends Graph> T getGraph(Class<T> clazz, Weighting weighting) {
        if (clazz.equals(Graph.class))
            return (T) baseGraph;

        Collection<CHGraphImpl> chGraphs = getAllCHGraphs();
        if (chGraphs.isEmpty())
            throw new IllegalStateException("Cannot find graph implementation for " + clazz);

        if (weighting == null)
            throw new IllegalStateException("Cannot find CHGraph with null weighting");

        List<Weighting> existing = new ArrayList<>();
        for (CHGraphImpl cg : chGraphs) {
            if (cg.getWeighting() == weighting)
                return (T) cg;

            existing.add(cg.getWeighting());
        }

        throw new IllegalStateException("Cannot find CHGraph for specified weighting: " + weighting + ", existing:" + existing);
    }
1152539
function addImportToGraph(importId, parentId, graph, visited) {
  const siblingsId = parentId + '_' + 'siblings'
  const visitedId = parentId + '_' + importId

  if (visited[visitedId] !== VISITED_MARKER) {
    if (!Array.isArray(visited[siblingsId])) visited[siblingsId] = []

    const siblings = visited[siblingsId]

    if (Array.isArray(graph[importId]))
      graph[importId] = graph[importId].concat(siblings)
    else graph[importId] = siblings.slice()

    visited[visitedId] = VISITED_MARKER
    siblings.push(importId)
  }
}
733975
function loadPrettyGraphSON(graph, filename, callback) {
        // We need to create an input stream and a reader, both of which are created asyncrously in parallel.
        // It would be nice to use Bluebird.join() perform those two operations, but the declaration for join()
        // in bluebird.d.ts isn't correct. We instead use .all(), and furthermore we use these two local variables
        // to commuicate the results of the two async operations to the final join operation.
        var theStream;
        var theReader;
        function getStream() {
            var readFileP = BluePromise.promisify(fs.readFile);
            return readFileP(filename, 'utf8')
                .then(function (jsonText) {
                var jsonObjArray = JSON.parse(jsonText);
                var jsonTextArray = _.map(jsonObjArray, JSON.stringify);
                return jsonTextArray.join('\n');
            })
                .then(function (uglyText) {
                var StringInputStream = Tinkerpop.autoImport('StringInputStream');
                theStream = StringInputStream.from(uglyText);
                return theStream;
            });
        }
        function getGraphReader() {
            return Tinkerpop.GraphSONReader.buildP()
                .then(function (builder) {
                return _newGraphSONMapper()
                    .then(function (mapper) { return builder.mapperP(mapper); });
            })
                .then(function (builder) { return builder.createP(); })
                .then(function (reader) { theReader = reader; return theReader; });
        }
        return BluePromise.all([getStream(), getGraphReader()])
            .then(function () { return theReader.readGraphP(theStream, graph); })
            .then(function () { return graph; })
            .nodeify(callback);
    }
670054
public static Predicate<DirectedEdge> hasDestination(final Node node) {
        return input -> {
            assert input != null;
            return input.destination.equals(node);
        };
    }
257436
public Node getNodeFromEntity(Object entity, Object key, GraphDatabaseService graphDb, EntityMetadata m,
            boolean isUpdate)
    {

        // Construct top level node first, making sure unique ID in the index
        Node node = null;
        if (!isUpdate)
        {
            node = getOrCreateNodeWithUniqueFactory(entity, key, m, graphDb);
        }
        else
        {

            node = searchNode(key, m, graphDb, true);
        }

        if (node != null)
        {
            populateNodeProperties(entity, m, node);
        }

        return node;
    }
1222824
View selectOriginNode() {
		double bestScore = 0;
		View best = null;

		if( verbose != null )
			verbose.println("selectOriginNode");
		for (int i = 0; i < graph.nodes.size(); i++) {
			double score = scoreNodeAsOrigin(graph.nodes.get(i));

			if( score > bestScore ) {
				bestScore = score;
				best = graph.nodes.get(i);
			}

			if( verbose != null )
				verbose.printf("  [%2d] score = %s\n",i,score);
		}
		if( verbose != null && best != null )
			verbose.println("     selected = "+best.index);

		return best;
	}
1130219
protected function createEdge($graph, $from_name, $to)
    {
        $to_name = !is_string($to) ? $to->getFullyQualifiedStructuralElementName() : $to;

        if (!isset($this->nodeCache[$from_name])) {
            $this->nodeCache[$from_name] = $this->createEmptyNode($from_name, $graph);
        }
        if (!isset($this->nodeCache[$to_name])) {
            $this->nodeCache[$to_name] = $this->createEmptyNode($to_name, $graph);
        }

        return Edge::create($this->nodeCache[$from_name], $this->nodeCache[$to_name]);
    }
427156
protected boolean flow(DiGraphNode<N, Branch> node) {
    FlowState<L> state = node.getAnnotation();
    if (isForward()) {
      L outBefore = state.out;
      state.out = flowThrough(node.getValue(), state.in);
      return !outBefore.equals(state.out);
    } else {
      L inBefore = state.in;
      state.in = flowThrough(node.getValue(), state.out);
      return !inBefore.equals(state.in);
    }
  }
451289
public static RelationGraph from(@NonNull Collection<RelationEdge> edges) {
      RelationGraph gPrime = new RelationGraph();
      edges.forEach(e -> {
         if (!gPrime.containsVertex(e.getFirstVertex())) {
            gPrime.addVertex(e.getFirstVertex());
         }
         if (!gPrime.containsVertex(e.getSecondVertex())) {
            gPrime.addVertex(e.getSecondVertex());
         }
         gPrime.addEdge(e);
      });
      return gPrime;
   }
225740
def dfs_tree(graph, start=0):
    
    to_visit = [start]
    prec = [None] * len(graph)
    while to_visit:              # an empty queue equals False
        node = to_visit.pop()
        for neighbor in graph[node]:
            if prec[neighbor] is None:
                prec[neighbor] = node
                to_visit.append(neighbor)
    return prec