Ensure that the graph we want to persist has data with valid cardinality.

@param \Tripod\ExtendedGraph $graph
@throws \Tripod\Exceptions\CardinalityException
502783
protected function validateGraphCardinality(\Tripod\ExtendedGraph $graph)
    {
        $config = $this->getConfigInstance();
        $cardinality = $config->getCardinality($this->getStoreName(), $this->getPodName());
        $namespaces = $config->getNamespaces();
        $graphSubjects = $graph->get_subjects();

        if (empty($cardinality) || $graph->is_empty())
        {
            return;
        }

        foreach ($cardinality as $qname=>$cardinalityValue)
        {
            list($namespace, $predicateName) = explode(':', $qname);
            if (!array_key_exists($namespace, $namespaces))
            {
                //TODO This may be changed to a namespace exception at some point...
                throw new \Tripod\Exceptions\CardinalityException("Namespace '{$namespace}' not defined for qname: {$qname}");
            }

            // NB: The only constraint we currently support is a value of 1 to enforce one triple per subject/predicate.
            if ($cardinalityValue == 1)
            {
                foreach ($graphSubjects as $subjectUri)
                {
                    $predicateUri = $namespaces[$namespace].$predicateName;
                    $predicateValues = $graph->get_subject_property_values($subjectUri, $predicateUri);
                    if (count($predicateValues) > 1)
                    {
                        $v = array();
                        foreach ($predicateValues as $predicateValue)
                        {
                            $v[] = $predicateValue['value'];
                        }
                        throw new \Tripod\Exceptions\CardinalityException("Cardinality failed on {$subjectUri} for '{$qname}' - should only have 1 value and has: ".implode(', ', $v));
                    }
                }
            }
        }
    }
13178
@Override
	public boolean validate(Graph<K, VV, EV> graph) throws Exception {
		DataSet<Tuple1<K>> edgeIds = graph.getEdges()
				.flatMap(new MapEdgeIds<>()).distinct();
		DataSet<K> invalidIds = graph.getVertices().coGroup(edgeIds).where(0)
				.equalTo(0).with(new GroupInvalidIds<>()).first(1);

		return invalidIds.map(new KToTupleMap<>()).count() == 0;
	}
799662
function nodeExtent(graph, attribute) {
  if (!isGraph(graph))
    throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');

  var attributes = [].concat(attribute);

  var nodes = graph.nodes(),
      node,
      data,
      value,
      key,
      a,
      i,
      l;

  var results = {};

  for (a = 0; a < attributes.length; a++) {
    key = attributes[a];

    results[key] = [Infinity, -Infinity];
  }

  for (i = 0, l = nodes.length; i < l; i++) {
    node = nodes[i];
    data = graph.getNodeAttributes(node);

    for (a = 0; a < attributes.length; a++) {
      key = attributes[a];
      value = data[key];

      if (value < results[key][0])
        results[key][0] = value;

      if (value > results[key][1])
        results[key][1] = value;
    }
  }

  return typeof attribute === 'string' ? results[attribute] : results;
}
970906
private static boolean hasMembershipProps(final Graph graph) {
        return graph.contains(null, LDP.membershipResource, null)
                        && (graph.stream(null, LDP.hasMemberRelation, null).count()
                                        + graph.stream(null, LDP.isMemberOfRelation, null).count() == 1L);
    }
6189
public function createImageSrc(Graph $graph)
    {
        $format = $this->format;
        if ($this->format === 'svg' || $this->format === 'svgz') {
            $format = 'svg+xml;charset=' . $graph->getAttribute('graphviz.graph.charset', 'UTF-8');
        }

        return 'data:image/' . $format . ';base64,' . base64_encode($this->createImageData($graph));
    }
58782
@Override
    public void putGraph(URI graphUri, Model data) {
        if (graphUri == null || data == null)
            return;

        // Use HTTP protocol if possible
        if (this.sparqlServiceEndpoint != null) {
            datasetAccessor.putModel(graphUri.toASCIIString(), data);
        } else {
            this.putGraphSparqlQuery(graphUri, data);
        }

        log.info("Graph added to store: {}", graphUri.toASCIIString());
    }
1212550
public static function addGraph($data)
    {
        self::registerView();
        
        if (is_scalar($data)) {
            throw new Exception("Data must be either an array or an object of type luya\web\jsonld\BaseThing.");
        }
        
        Yii::$app->view->params['@context'] = 'https://schema.org';
        Yii::$app->view->params['@graph'][] = $data;
        
        return $data;
    }
451733
public function addEdge(Edge $edge): self
	{
		$id = $edge->getId();

		if (isset($this->rootGraph->edges[$id])) {
			throw new DuplicateEdgeException(sprintf("Edge \"%s\" already present in the graph.", $id));
		}

		// Add element
		$this->edges[$id] = $edge;

		// Update attr indexes
		$this->edgeAttrIndex->insertElement($edge);

		return $this;
	}
508459
public function isVertexSource(Vertex $vertex)
    {
        foreach ($vertex->getEdges() as $edge) {
            if ($edge->hasVertexTarget($vertex)) {
                return false;
            }
        }

        // reach this point: no edge to this vertex
        return true;
    }
955374
def _check_graph(self, graph):
        """"""
        if graph.num_vertices != self.size:
            raise TypeError("The number of vertices in the graph does not "
                "match the length of the atomic numbers array.")
        # In practice these are typically the same arrays using the same piece
        # of memory. Just checking to be sure.
        if (self.numbers != graph.numbers).any():
            raise TypeError("The atomic numbers in the graph do not match the "
                "atomic numbers in the molecule.")
95134
public function write(array $data, array $options)
    {
        if (!$this->getUtils()->isDotInstalled()) {
            throw ExportException::create(
                'Can\'t export to a Graphviz image because "dot" binary is not available. Verify that the ' .
                '"graphviz" package is installed on your system.'
            );
        }

        if (!isset($data['node']) || !($data['node'] instanceof NodeInterface)) {
            throw ValidationException::create(
                'Data attribute "node" must be an instance of IronEdge\Component\Graphs\Node\NodeInterface.'
            );
        }

        if (!isset($options['path']) || !is_string($options['path']) || $options['path'] === '') {
            throw ValidationException::create(
                'To be able to export this graph to a graphviz image, you must set option "path" with a string ' .
                'with the path to the target file.'
            );
        }

        /** @var NodeInterface $graph */
        $graph = $data['node'];
        $file = $options['path'];

        $graphvizCode = 'digraph ' . $graph->getId() . ' {' . PHP_EOL;
        $graphAttributes = $graph->getMetadataAttr('graphviz.nodeAttributes', []);

        if ($graphAttributes) {
            foreach ($graphAttributes as $k => $v) {
                $graphvizCode .= '  ' . $k . '=' . $v . ';' . PHP_EOL;
            }

            $graphvizCode .= PHP_EOL;
        }

        $graphvizCode .= $this->generateNodeCode($graph);

        $graphvizCode .= '}';

        $this->generateGraphvizOutputFile($graphvizCode, $file, ['targetType' => 'png']);
    }
806122
public void run(final SocialGraph graph) {
		final Transaction transaction = graph.beginTx();
		if (this.execute(graph)) {
			transaction.success();
		}
		transaction.finish();
		this.servlet.finish();
	}
353920
public function boot($graph): NetworkInterface
    {
        switch (true) {
            case (is_a($graph, Graph::class)):
                break;
            case (is_file($graph)):
                $graph = Graph::loadFile($graph);
                break;
            case is_string($graph) && is_file($graph):
                $graph = Graph::loadFile($graph);
                break;
            case (is_string($graph)):
                $graph = Graph::loadString($graph);
                break;
            default:
                throw new InvalidTypeException(
                    "Graph has to be either a Graph object or a compatible definition file/string"
                );
        }

        $graph->on(self::EVENT_ADD, [$this, 'addNode']);
        $graph->on(self::EVENT_REMOVE, [$this, 'removeNode']);
        $graph->on(self::EVENT_ADD_EDGE, [$this, 'addEdge']);
        $graph->on(self::EVENT_REMOVE_EDGE, [$this, 'removeEdge']);

        /** @todo think of caching graphs here, maybe */
        $this->graph = $graph;
        $this->loadGraph($graph);

        return $this;
    }
872295
public function addGraph( $legend, $color, $data )
	{
		$position	= count( $this->graphs );
		$this->graphs[$position]	= array(
			'legend'	=> $legend,
			'color'		=> $color,
			'values'	=> $data,
		);
	}
473062
public static <V> void addAllVertices(DirectedGraph<V, DefaultEdge> graph, Set<V> vertices) {
        // add all of the new vertices to prep for linking
        for (V vertex : vertices) {
            graph.addVertex(vertex);
        }
    }
1033360
public function saveGraph(
        \EasyRdf_Graph $graph,
        $uri = '',
        $headers = []
    ) {
        // Serialze the rdf.
        $turtle = $graph->serialise('turtle');

        // Checksum it.
        $checksum_value = sha1($turtle);

        // Set headers.
        $headers['Content-Type'] = 'text/turtle';
        $headers['digest'] = 'sha1=' . $checksum_value;

        // Save it.
        return $this->saveResource($uri, $turtle, $headers);
    }
1068045
def validate(self, graph):
        
        if not nx.is_directed_acyclic_graph(graph):
            raise DirectedAcyclicGraphInvalid(graph_name=self._name)