Function creating an array of edges for the given type.

@param  {Graph}   graph - Target Graph instance.
@param  {string}  type  - Type of edges to retrieve.
@return {array}         - Array of edges.
558363
function createEdgeArray(graph, type) {
  if (graph.size === 0)
    return [];

  if (type === 'mixed' || type === graph.type)
    return take(graph._edges.keys(), graph._edges.size);

  const size = type === 'undirected' ?
    graph.undirectedSize :
    graph.directedSize;

  const list = new Array(size),
        mask = type === 'undirected';

  let i = 0;

  graph._edges.forEach((data, edge) => {

    if ((data instanceof UndirectedEdgeData) === mask)
      list[i++] = edge;
  });

  return list;
}
786267
def types(self) -> GraphQLTypeList:
        """"""
        try:
            types = resolve_thunk(self._types)
        except GraphQLError:
            raise
        except Exception as error:
            raise TypeError(f"{self.name} types cannot be resolved: {error}")
        if types is None:
            types = []
        if not isinstance(types, (list, tuple)):
            raise TypeError(
                f"{self.name} types must be a list/tuple"
                " or a function which returns a list/tuple."
            )
        if not all(isinstance(value, GraphQLObjectType) for value in types):
            raise TypeError(f"{self.name} types must be GraphQLObjectType objects.")
        return types[:]
904684
function Digraph(pkGloballyUniqueId)
{
    var self = this;

    var pkGuid              = pkGloballyUniqueId;
    var vertexArray         = [];       // Note: these three arrays are kept in parallel for ease of access as well as to increase search speed
    var vertexIdArray       = [];
    var vertexStateArray    = [];

    var startVertexIdArray  = [];       // Note: these two arrays are how directed edges are stored
    var endVertexIdArray    = [];


    /**
     * Is there a vertex in the digraph with that ID?
     *
     * @param {string} vertexId - ID of a vertex
     * @returns {boolean}
     */
    this.hasVertexId = function (vertexId)
    {
        return vertexIdArray.indexOf(vertexId) > -1;
    };

    /**
     * Creates a new vertex in the digraph
     *
     * @param {string} id - ID of the new vertex
     * @param {Object} data - Optional data object associated with the vertex
     * @returns {Vertex}
     */
    this.addVertex = function (id, data)
    {
        if(vertexIdArray.indexOf(id) > -1)
        {
            throw new Error("Duplicate Vertex ID", "Vertex with the ID " + id + " already exists!");
        }
        else
        {
            var newVertex = new Vertex(pkGuid, id, "NOT_READY", data);
            newVertex.parent = self;
            vertexIdArray.push(id);
            vertexStateArray.push("NOT_READY");
            vertexArray.push(newVertex);
            return newVertex;
        }
    };

    /**
     * Adds a directed edge to the digraph from startVertexId to endVertexId
     *
     * @param {string} startVertexId - Where the edge starts
     * @param {string} endVertexId - Where the edge ends
     */
    this.addEdge = function (startVertexId, endVertexId)
    {
        if(vertexIdArray.indexOf(startVertexId) == -1)
        {
            throw new Error("Start Vertex Not Found", "Start vertex (with the ID " + startVertexId + ") not found!");
        }
        else if(vertexIdArray.indexOf(endVertexId) == -1)
        {
            throw new Error("End Vertex Not Found", "End vertex (with the ID " + endVertexId + ") not found!");
        }
        else if(startVertexId == endVertexId)
        {
            throw new Error("Loops Not Allowed", "The start vertex and the end vertex are the same (vertex ID " + startVertexId + ")!");
        }
        else
        {
            var numEdges = startVertexIdArray.length;
            var duplicateEdgeFound = false;

            for(var i = 0; i < numEdges; i++)
            {
                if(startVertexIdArray[i] == startVertexId && endVertexIdArray[i] == endVertexId)
                {
                    duplicateEdgeFound = true;
                    break;
                }
            }

            if(duplicateEdgeFound)
            {
                throw new Error("Edge Already Exists", "Edge (" + startVertexId + ", " + endVertexId + ") already exists!");
            }
            else
            {
                startVertexIdArray.push(startVertexId);
                endVertexIdArray.push(endVertexId);
            }
        }
    };

    /**
     * Removes the vertex with the given vertexId
     *
     * @param {string} vertexId - ID of the vertex to remove
     */
    this.removeVertex = function (vertexId)
    {
        if(vertexIdArray.index(vertexId) == -1)
        {
            throw new Error("Vertex Not Found", "Vertex (with the ID " + vertexId + ") not found!");
        }
        else
        {
            // First, remove it from the vertex arrays
            var vertexIndex = vertexIdArray.indexOf(vertexId);
            vertexIdArray.splice(vertexIndex, 1);
            vertexStateArray.splice(vertexIndex, 1);
            vertexArray.splice(vertexIndex, 1);

            // Now remove the edges
            var numEdges = startVertexIdArray.length;
            for(var i = numEdges-1; i >= 0; i--)
            {
                if(startVertexIdArray[i] == vertexId || endVertexIdArray[i] == vertexId)
                {
                    startVertexIdArray.splice(i, 1);
                    endVertexIdArray.splice(i, 1);
                }
            }
        }
    };

    /**
     * Removes the edge going from startVertexId to endVertexId
     *
     * @param {string} startVertexId - Where the edge starts
     * @param {string} endVertexId - Where the edge ends
     */
    this.removeEdge = function (startVertexId, endVertexId)
    {
        var numEdges = startVertexIdArray.length;
        var edgeIndex = -1;

        // NOTE: this next part assumes that no duplicate edges exist
        for(var i = 0; i < numEdges; i++)
        {
            if(startVertexIdArray[i] == startVertexId && endVertexIdArray[i] == endVertexId)
            {
                edgeIndex = i;
                break;
            }
        }

        if(edgeIndex == -1)
        {
            throw new Error("Edge Doesn't Exist", "Edge (" + startVertexId + ", " + endVertexId + ") does not exist!");
        }
        else
        {
            startVertexIdArray.splice(edgeIndex, 1);
            endVertexIdArray.splice(edgeIndex, 1);
        }
    };

    /**
     * Gets all child vertices (objects) of the vertex with the given parentVertexId
     *
     * @param {string} parentVertexId - ID of the parent vertex
     * @returns {Array}
     */
    this.getChildVertices = function (parentVertexId)
    {
        var numEdges = startVertexIdArray.length;
        var childVertices = [];

        for(var i = 0; i < numEdges; i++)
        {
            if(startVertexIdArray[i] == parentVertexId)
            {
                childVertices.push(vertexArray[vertexIdArray.indexOf(endVertexIdArray[i])]);
            }
        }

        return childVertices;
    };

    /**
     * Gets the IDs of all child vertices of parentVertexId
     *
     * @param {string} parentVertexId - ID of the parent vertex
     * @returns {Array}
     */
    this.getChildVertexIds = function (parentVertexId)
    {
        var numEdges = startVertexIdArray.length;
        var childVertexIds = [];

        for(var i = 0; i < numEdges; i++)
        {
            if(startVertexIdArray[i] == parentVertexId)
            {
                childVertexIds.push(vertexArray[vertexIdArray.indexOf(endVertexIdArray[i])].id);
            }
        }

        return childVertexIds;
    };

    /**
     * Gets all parent vertices (objects) of the vertex with the given childVertexId
     *
     * @param {string} childVertexId - ID of the child vertex
     * @returns {Array}
     */
    this.getParentVertices = function (childVertexId)
    {
        var numEdges = startVertexIdArray.length;
        var parentVertices = [];

        for(var i = 0; i < numEdges; i++)
        {
            if(endVertexIdArray[i] == childVertexId)
            {
                parentVertices.push(vertexArray[vertexIdArray.indexOf(startVertexIdArray[i])]);
            }
        }

        return parentVertices;
    };

    /**
     * Gets the IDs of all parents of the specified vertex
     *
     * @param {string} childVertexId - ID of the child vertex
     * @returns {Array}
     */
    this.getParentVertexIds = function (childVertexId)
    {
        var numEdges = startVertexIdArray.length;
        var parentVertexIds = [];

        for(var i = 0; i < numEdges; i++)
        {
            if(endVertexIdArray[i] == childVertexId)
            {
                parentVertexIds.push(vertexArray[vertexIdArray.indexOf(startVertexIdArray[i])].id);
            }
        }

        return parentVertexIds;
    };

    /**
     * How many edges are coming into this vertex?
     *
     * @param {string} vertexId - The vertex ID
     * @returns {number}
     */
    this.indegree = function (vertexId)
    {
        var numEdges = startVertexIdArray.length;
        var count = 0;

        for(var i = 0; i < numEdges; i++)
        {
            if(endVertexIdArray[i] == vertexId)
            {
                count++;
            }
        }
        return count;
    };

    /**
     * How many edges are leaving from this vertex?
     *
     * @param {string} vertexId - The vertex ID
     * @returns {number}
     */
    this.outdegree = function (vertexId)
    {
        var numEdges = startVertexIdArray.length;
        var count = 0;

        for(var i = 0; i < numEdges; i++)
        {
            if(startVertexIdArray[i] == vertexId)
            {
                count++;
            }
        }
        return count;
    };

    /**
     * Returns list of vertices (objects) with indegree == 0
     *
     * @returns {Array}
     */
    this.getVerticesWithIndegree0 = function ()
    {
        var numVertices = vertexArray.length;
        var verticesWithIndegree0 = [];

        for(var i = 0; i < numVertices; i++)
        {
            if(endVertexIdArray.indexOf(vertexArray[i].id) == -1)
            {
                verticesWithIndegree0.push(vertexArray[i]);
            }
        }

        return verticesWithIndegree0;
    };

    /**
     * Gets vertex (object) with specified ID
     *
     * @param {string} vertexId - The vertex ID
     * @returns {*}
     */
    this.getVertex = function (vertexId)
    {
        var vertexIndex = vertexIdArray.indexOf(vertexId);

        if(vertexIndex == -1)
        {
            throw new Error("Vertex Not Found", "Vertex (with the ID " + vertexId + ") not found!");
        }
        else
        {
            return vertexArray[vertexIndex];
        }
    };

    /**
     * Returns list of the IDs of all the vertices
     *
     * @returns {Array}
     */
    this.getVertexIds = function ()
    {
        var vertexIds = [];
        var numVertices = vertexArray.length;

        for(var i = 0; i < numVertices; i++)
        {
            vertexIds.push(vertexIdArray[i]);
        }

        return vertexIds;
    };

    /**
     * How many vertices are in the digraph?
     *
     * @returns {Number}
     */
    this.vertexCount = function ()
    {
        return vertexArray.length;
    };

    /**
     * How many edges are in the digraph?
     *
     * @returns {Number}
     */
    this.edgeCount = function ()
    {
        return startVertexIdArray.length;
    };

    /**
     * Performs a topological sort on the vertices of the digraph, implemented using Kahn's algorithm <br />
     * See Wikipedia for details: {@link http://en.wikipedia.org/wiki/Topological_sort}
     *
     * @returns {Array}
     */
    this.topologicalSort = function ()
    {
        // Based upon Kahn's algorithm from
        // http://en.wikipedia.org/wiki/Topological_sort

        // Make a copy of the edge set, since Kahn's algorithm will destroy that info!
        // We'll restore the info at the end
        var edgeInfo = this.getEdgeInfo();

        var L = [];
        var S = this.getVerticesWithIndegree0();

        while(S.length > 0)
        {
            var n = S.pop();
            L.push(n);
            var childNodes = this.getChildVertices(n.id);
            var numChildren = childNodes.length;
            for(var i = 0; i < numChildren; i++)
            {
                var m = childNodes[i];
                this.removeEdge(n.id, m.id);

                if(this.indegree(m.id) == 0)
                {
                    S.push(m);
                }
            }
        }
        if(this.edgeCount() > 0)
        {
            this.setEdgeInfo(edgeInfo);
            return [];
        }
        else
        {
            this.setEdgeInfo(edgeInfo);
            return L;
        }
    };

    /**
     * Returns a clone of the start and end vertex arrays - used as part of the topological sort, since it is destructive
     *
     * @returns {{startVertexIdArray: *, endVertexIdArray: *}}
     */
    this.getEdgeInfo = function ()
    {
        var edgeInfo = {
            "startVertexIdArray": clone(startVertexIdArray),
            "endVertexIdArray": clone(endVertexIdArray)
        };

        return edgeInfo;
    };

    /**
     * Sets the start and end vertex arrays - used as part of the topological sort, since it is destructive
     *
     * @param edgeInfo
     */
    this.setEdgeInfo = function (edgeInfo)
    {
        startVertexIdArray = clone(edgeInfo.startVertexIdArray);
        endVertexIdArray = clone(edgeInfo.endVertexIdArray);
    };

    /**
     * Creates a deep copy of a JS object
     * Code from {@link http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object}
     *
     * @private
     * @param {Object} obj - Opject to clone
     * @returns {*}
     */
    function clone(obj)
    {
        // Based upon http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
        if(obj == null || typeof obj != "object")
        {
            return obj;
        }
        else
        {
            var copy = obj.constructor();
            for(var attr in obj)
            {
                if(obj.hasOwnProperty(attr))
                {
                    copy[attr] = obj[attr];
                }
            }
            return copy;
        }
    }

    /**
     * Returns the digraph's vertices and edges, formatted all pretty like
     *
     * @returns {string}
     */
    this.asString = function ()
    {
        var numEdges = startVertexIdArray.length;
        var edgeArray = [];

        for(var i = 0; i < numEdges; i++)
        {
            edgeArray.push({"start":startVertexIdArray[i], "end":endVertexIdArray[i]});
        }

        var str = "";

        str += "{" + "\n";
        str += "     \"vertices\": " + JSON.stringify(vertexArray) + "," + "\n";
        str += "     \"edges\": " + JSON.stringify(edgeArray) + "\n";
        str += "}";

        return str;
    };
}
813543
@SuppressWarnings("serial")
	private DataSet<Vertex<K, VV>> createResultVerticesWithDegrees(Graph<K, VV, EV> graph, EdgeDirection messagingDirection,
			TypeInformation<Tuple2<K, Message>> messageTypeInfo, DataSet<LongValue> numberOfVertices) {

		DataSet<Tuple2<K, Message>> messages;

		this.gatherFunction.setOptDegrees(this.configuration.isOptDegrees());

		DataSet<Tuple2<K, LongValue>> inDegrees = graph.inDegrees();
		DataSet<Tuple2<K, LongValue>> outDegrees = graph.outDegrees();

		DataSet<Tuple3<K, LongValue, LongValue>> degrees = inDegrees.join(outDegrees).where(0).equalTo(0)
				.with(new FlatJoinFunction<Tuple2<K, LongValue>, Tuple2<K, LongValue>, Tuple3<K, LongValue, LongValue>>() {

					@Override
					public void join(Tuple2<K, LongValue> first, Tuple2<K, LongValue> second, Collector<Tuple3<K, LongValue, LongValue>> out) {
						out.collect(new Tuple3<>(first.f0, first.f1, second.f1));
					}
				}).withForwardedFieldsFirst("f0;f1").withForwardedFieldsSecond("f1");

		DataSet<Vertex<K, Tuple3<VV, LongValue, LongValue>>> verticesWithDegrees = initialVertices
				.join(degrees).where(0).equalTo(0)
				.with(new FlatJoinFunction<Vertex<K, VV>, Tuple3<K, LongValue, LongValue>, Vertex<K, Tuple3<VV, LongValue, LongValue>>>() {
					@Override
					public void join(Vertex<K, VV> vertex, Tuple3<K, LongValue, LongValue> degrees,
									Collector<Vertex<K, Tuple3<VV, LongValue, LongValue>>> out) throws Exception {
						out.collect(new Vertex<>(vertex.getId(),
									new Tuple3<>(vertex.getValue(), degrees.f1, degrees.f2)));
					}
				}).withForwardedFieldsFirst("f0");

		// add type info
		TypeInformation<Vertex<K, Tuple3<VV, LongValue, LongValue>>> vertexTypes = verticesWithDegrees.getType();

		final DeltaIteration<Vertex<K, Tuple3<VV, LongValue, LongValue>>, Vertex<K, Tuple3<VV, LongValue, LongValue>>> iteration =
				verticesWithDegrees.iterateDelta(verticesWithDegrees, this.maximumNumberOfIterations, 0);
				setUpIteration(iteration);

		switch (messagingDirection) {
			case IN:
				messages = buildScatterFunctionVerticesWithDegrees(iteration, messageTypeInfo, 1, 0, numberOfVertices);
				break;
			case OUT:
				messages = buildScatterFunctionVerticesWithDegrees(iteration, messageTypeInfo, 0, 0, numberOfVertices);
				break;
			case ALL:
				messages = buildScatterFunctionVerticesWithDegrees(iteration, messageTypeInfo, 1, 0, numberOfVertices)
						.union(buildScatterFunctionVerticesWithDegrees(iteration, messageTypeInfo, 0, 0, numberOfVertices));
				break;
			default:
				throw new IllegalArgumentException("Illegal edge direction");
		}

		@SuppressWarnings({ "unchecked", "rawtypes" })
		GatherUdf<K, Tuple3<VV, LongValue, LongValue>, Message> updateUdf =
				new GatherUdfVVWithDegrees(gatherFunction, vertexTypes);

		// build the update function (co group)
		CoGroupOperator<?, ?, Vertex<K, Tuple3<VV, LongValue, LongValue>>> updates =
				messages.coGroup(iteration.getSolutionSet()).where(0).equalTo(0).with(updateUdf);

		if (this.configuration != null && this.configuration.isOptNumVertices()) {
			updates = updates.withBroadcastSet(numberOfVertices, "number of vertices");
		}

		configureUpdateFunction(updates);

		return iteration.closeWith(updates, updates).map(
				new MapFunction<Vertex<K, Tuple3<VV, LongValue, LongValue>>, Vertex<K, VV>>() {

					public Vertex<K, VV> map(Vertex<K, Tuple3<VV, LongValue, LongValue>> vertex) {
						return new Vertex<>(vertex.getId(), vertex.getValue().f0);
					}
				});
	}
270198
@Override
    public Iterable<GraphEdge<V, E>> edges() {
        return F.map(vedges(), new Function<Map.Entry<V, GraphEdge<V, E>>, GraphEdge<V, E>>() {
            @Override
            public GraphEdge<V, E> apply(Map.Entry<V, GraphEdge<V, E>> entry) {
                return entry.getValue();
            }
        });
    }
1041
public static <T> DiGraphIterator<T> getInstance(T root, Function<? super T, ? extends Collection<T>> edges)
    {
        return new DiGraphIterator<>(root, (y)->edges.apply(y).stream());
    }
462908
function topologicalSort(graph) {
    const allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
    Object.keys(graph).forEach((fromNode) => {
        allNodes[fromNode] = true;
        outgoingEdgeCount[fromNode] = graph[fromNode].length;
        graph[fromNode].forEach((toNode) => {
            allNodes[toNode] = true;
            outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
            inverseEdges[toNode] = inverseEdges[toNode] || [];
            inverseEdges[toNode].push(fromNode);
        });
    });
    // https://en.wikipedia.org/wiki/Topological_sorting
    const S = [], L = [];
    Object.keys(allNodes).forEach((node) => {
        if (outgoingEdgeCount[node] === 0) {
            delete outgoingEdgeCount[node];
            S.push(node);
        }
    });
    while (S.length > 0) {
        // Ensure the exact same order all the time with the same inputs
        S.sort();
        const n = S.shift();
        L.push(n);
        const myInverseEdges = inverseEdges[n] || [];
        myInverseEdges.forEach((m) => {
            outgoingEdgeCount[m]--;
            if (outgoingEdgeCount[m] === 0) {
                delete outgoingEdgeCount[m];
                S.push(m);
            }
        });
    }
    if (Object.keys(outgoingEdgeCount).length > 0) {
        throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
    }
    return L;
}
566888
function(posType) {
    posType = posType || "current";

    var root = this.graph.getNode(this.root),
        config = this.config,
        size = this.canvas.getSize(),
        width = size.width,
        height = size.height,
        offset = config.offset,
        levelsToShow = config.constrained ? config.levelsToShow : Number.MAX_VALUE;

    this.controller.onBeforeCompute(root);

    Graph.Util.computeLevels(this.graph, root.id, 0, "ignore");

    var treeDepth = 0;

    Graph.Util.eachLevel(root, 0, false, function (n, d) { if(d > treeDepth) treeDepth = d; });

    var startNode = this.graph.getNode(this.clickedNode && this.clickedNode.id || root.id);
    var maxDepth = Math.min(treeDepth, levelsToShow-1);
    var initialDepth = startNode._depth;
    if(this.layout.horizontal()) {
      this.computeSubtree(startNode, -width/2, -height/2, width/(maxDepth+1), height, initialDepth, maxDepth, posType);
    } else {
      this.computeSubtree(startNode, -width/2, -height/2, width, height/(maxDepth+1), initialDepth, maxDepth, posType);
    }
  }
39744
function getType(graffitiModels, { name, description, fields }, path = [], rootType = null) {
  const root = path.length === 0;
  const graphQLType = { name, description };
  rootType = rootType || graphQLType;

  // These references have to be resolved when all type definitions are avaiable
  resolveReference[graphQLType.name] = resolveReference[graphQLType.name] || {};
  const graphQLTypeFields = reduce(fields, (graphQLFields,
      { name, description, type, subtype, reference, nonNull, hidden, hooks,
       fields: subfields, embeddedModel, enumValues }, key) => {
    name = name || key;
    const newPath = [...path, name];

    // Don't add hidden fields to the GraphQLObjectType
    if (hidden || name.startsWith('__')) {
      return graphQLFields;
    }

    const graphQLField = { name, description };

    if (type === 'Array') {
      if (subtype === 'Object') {
        const fields = subfields;
        const nestedObjectName = getTypeFieldName(graphQLType.name, name);
        graphQLField.type = new GraphQLList(
          getType(graffitiModels, { name: nestedObjectName, description, fields }, newPath, rootType));
      } else {
        graphQLField.type = new GraphQLList(stringToGraphQLType(subtype));
        if (reference) {
          resolveReference[rootType.name][name] = {
            name,
            type: reference,
            args: connectionArgs,
            resolve: addHooks((rootValue, args, context, info) => {
              args.id = rootValue[name].map((i) => i.toString());
              return connectionFromModel(graffitiModels[reference], args, context, info);
            }, hooks)
          };
        }
      }
    } else if (type === 'Object') {
      const fields = subfields;
      const nestedObjectName = getTypeFieldName(graphQLType.name, name);
      graphQLField.type = getType(graffitiModels, { name: nestedObjectName, description, fields }, newPath, rootType);
    } else if (type === 'Embedded') {
      const type = types.hasOwnProperty(name)
        ? types[name]
        : getType(graffitiModels, embeddedModel, ['embedded']);
      type.mongooseEmbedded = true;
      graphQLField.type = type;
    } else if (enumValues && type === 'String') {
      graphQLField.type = listToGraphQLEnumType(enumValues, getTypeFieldName(graphQLType.name, `${name}Enum`));
    } else {
      graphQLField.type = stringToGraphQLType(type);
    }

    if (reference && (graphQLField.type === GraphQLID || graphQLField.type === new GraphQLNonNull(GraphQLID))) {
      resolveReference[rootType.name][newPath.join('.')] = {
        name,
        type: reference,
        resolve: addHooks((rootValue, args, context, info) => {
          const resolver = getOneResolver(graffitiModels[reference]);
          return resolver(rootValue, { id: rootValue[name] ? rootValue[name].toString() : null }, context, info);
        }, hooks)
      };
    }

    if (nonNull && graphQLField.type) {
      graphQLField.type = new GraphQLNonNull(graphQLField.type);
    }

    if (!graphQLField.resolve) {
      graphQLField.resolve = addHooks((source) => source[name], hooks);
    }

    graphQLFields[name] = graphQLField;
    return graphQLFields;
  }, {});

  if (root) {
    // Implement the Node interface
    graphQLType.interfaces = [nodeInterface];
    graphQLTypeFields.id = globalIdField(name, (obj) => obj._id);
  }

  // Add fields to the GraphQL type
  graphQLType.fields = () => graphQLTypeFields;

  // Define type
  const GraphQLObjectTypeDefinition = new GraphQLObjectType(graphQLType);

  // Register type
  if (root) {
    addType(name, GraphQLObjectTypeDefinition);
  }

  return GraphQLObjectTypeDefinition;
}
488642
function topologicalSort(graph) {
    var processed = [],
        unprocessed = [],
        queue = [];

    /**
     *
     * @param arr
     * @param callback
     * @this {Object}
     */
    function each(arr, callback) {
        var i = void 0;

        // if Array, then process as array
        if (arr instanceof Array) {
            for (i = 0; i < arr.length; i++) {
                callback.call(arr[i], i);
            }
        }

        // if object, iterate over property/keys
        else {
                for (i in arr) {
                    if (arr.hasOwnProperty(i)) {
                        callback.call(arr[i], i);
                    }
                }
            }
    }

    function processStartingPoint(node) {
        if (node === undefined) {
            throw 'You have a cycle!!';
        }
        each(node.edges, function () {
            node.sortImportance--;
        });
        processed.push(node);
    }

    var populateIndegreesAndUnprocessed = function populateIndegreesAndUnprocessed() {
        each(graph.nodes, function () {
            var self = this;
            unprocessed.push(this);
            if (!Object.prototype.hasOwnProperty.call(self, 'sortImportance')) {
                self.sortImportance = 0;
            }

            each(self.edges, function () {
                self.sortImportance++;
            });
        });
    };

    populateIndegreesAndUnprocessed();

    while (unprocessed.length > 0) {
        for (var i = 0; i < unprocessed.length; i++) {
            var node = unprocessed[i];
            if (node.sortImportance === 0) {
                queue.push(node);
                unprocessed.splice(i, 1); // Remove this node, its all done.
                i--; // decrement i since we just removed that index from the iterated list;
            } else {
                node.sortImportance--;
            }
        }

        if (queue.length > 0) {
            processStartingPoint(queue.shift());
        }
    }

    return processed;
}
361841
def get_node_edges(self,node,type="both"):
    
    if type == "both":
      return [self.__edges[x] for x in self.__edges if node.id in self.__edges[x].get_node_ids()]
    elif type == "outgoing":
      return [self.__edges[x] for x in self.__edges if node.id == self.__edges[x].get_node_ids()[0]]
    elif type == "incoming":
      return [self.__edges[x] for x in self.__edges if node.id == self.__edges[x].get_node_ids()[1]]
    sys.stderr.write("ERROR: type is not a type "+type+"\n")
    sys.exit()
516753
void graphToRDF(String graphName, Map<String, Object> graph) {
        // 4.2)
        final List<Quad> triples = new ArrayList<Quad>();
        // 4.3)
        final List<String> subjects = new ArrayList<String>(graph.keySet());
        // Collections.sort(subjects);
        for (final String id : subjects) {
            if (JsonLdUtils.isRelativeIri(id)) {
                continue;
            }
            final Map<String, Object> node = (Map<String, Object>) graph.get(id);
            final List<String> properties = new ArrayList<String>(node.keySet());
            Collections.sort(properties);
            for (String property : properties) {
                final List<Object> values;
                // 4.3.2.1)
                if ("@type".equals(property)) {
                    values = (List<Object>) node.get("@type");
                    property = RDF_TYPE;
                }
                // 4.3.2.2)
                else if (isKeyword(property)) {
                    continue;
                }
                // 4.3.2.3)
                else if (property.startsWith("_:") && !api.opts.getProduceGeneralizedRdf()) {
                    continue;
                }
                // 4.3.2.4)
                else if (JsonLdUtils.isRelativeIri(property)) {
                    continue;
                } else {
                    values = (List<Object>) node.get(property);
                }

                Node subject;
                if (id.indexOf("_:") == 0) {
                    // NOTE: don't rename, just set it as a blank node
                    subject = new BlankNode(id);
                } else {
                    subject = new IRI(id);
                }

                // RDF predicates
                Node predicate;
                if (property.startsWith("_:")) {
                    predicate = new BlankNode(property);
                } else {
                    predicate = new IRI(property);
                }

                for (final Object item : values) {
                    // convert @list to triples
                    if (isList(item)) {
                        final List<Object> list = (List<Object>) ((Map<String, Object>) item)
                                .get("@list");
                        Node last = null;
                        Node firstBNode = nil;
                        if (!list.isEmpty()) {
                            last = objectToRDF(list.get(list.size() - 1));
                            firstBNode = new BlankNode(api.generateBlankNodeIdentifier());
                        }
                        triples.add(new Quad(subject, predicate, firstBNode, graphName));
                        for (int i = 0; i < list.size() - 1; i++) {
                            final Node object = objectToRDF(list.get(i));
                            triples.add(new Quad(firstBNode, first, object, graphName));
                            final Node restBNode = new BlankNode(api.generateBlankNodeIdentifier());
                            triples.add(new Quad(firstBNode, rest, restBNode, graphName));
                            firstBNode = restBNode;
                        }
                        if (last != null) {
                            triples.add(new Quad(firstBNode, first, last, graphName));
                            triples.add(new Quad(firstBNode, rest, nil, graphName));
                        }
                    }
                    // convert value or node object to triple
                    else {
                        final Node object = objectToRDF(item);
                        if (object != null) {
                            triples.add(new Quad(subject, predicate, object, graphName));
                        }
                    }
                }
            }
        }
        put(graphName, triples);
    }
1227166
public static <T extends GraphQLType> List<T> sortGraphQLTypes(Collection<T> types) {
        List<T> sorted = new ArrayList<>(types);
        sorted.sort(graphQLTypeComparator());
        return sorted;
    }
377601
public <K> Graph<K, NullValue, NullValue> keyType(Class<K> vertexKey) {

		if (edgeReader == null) {
			throw new RuntimeException("The edge input file cannot be null!");
		}

		DataSet<Edge<K, NullValue>> edges = edgeReader
			.types(vertexKey, vertexKey)
				.name(GraphCsvReader.class.getName())
			.map(new Tuple2ToEdgeMap<>())
				.name("Type conversion");

		return Graph.fromDataSet(edges, executionContext);
	}
452541
function(graph, opt) {

        opt = opt || {};

        var glGraphType = joint.util.pick(opt, 'directed', 'compound', 'multigraph');
        var glGraph = new graphlib.Graph(glGraphType);
        var setNodeLabel = opt.setNodeLabel || joint.util.noop;
        var setEdgeLabel = opt.setEdgeLabel || joint.util.noop;
        var setEdgeName = opt.setEdgeName || joint.util.noop;
        var collection = graph.get('cells');

        for (var i = 0, n = collection.length; i < n; i++) {

            var cell = collection.at(i);
            if (cell.isLink()) {

                var source = cell.get('source');
                var target = cell.get('target');

                // Links that end at a point are ignored.
                if (!source.id || !target.id) break;

                // Note that if we are creating a multigraph we can name the edges. If
                // we try to name edges on a non-multigraph an exception is thrown.
                glGraph.setEdge(source.id, target.id, setEdgeLabel(cell), setEdgeName(cell));

            } else {

                glGraph.setNode(cell.id, setNodeLabel(cell));

                // For the compound graphs we have to take embeds into account.
                if (glGraph.isCompound() && cell.has('parent')) {
                    var parentId = cell.get('parent');
                    if (collection.has(parentId)) {
                        // Make sure the parent cell is included in the graph (this can
                        // happen when the layout is run on part of the graph only).
                        glGraph.setParent(cell.id, parentId);
                    }
                }
            }
        }

        return glGraph;
    }
193521
function processObjectType(object: GraphQLObjectType) {
  return reduce(
    object._typeConfig,
    (def, value, key) => {
      return setDef(
        def,
        key,
        value,
        [
          'description',
          'interfaces',
          'fields',
          'isTypeOf',
          'astNode',
          'onConflict',
        ],
        object,
      );
    },
    { type: 'Object' },
    true,
  );
}
893303
@Override
	public GraphRequest<JsonNode> graph(String object, Param... params) {
		return this.graph(object, JsonNode.class, params);
	}