Overrides GraphService.create() to create the object with some reasonable defaults
970139
public ApplicationReportModel create()
    {
        ApplicationReportModel applicationReportModel = super.create();
        applicationReportModel.setDisplayInApplicationReportIndex(false);
        applicationReportModel.setMainApplicationReport(false);
        applicationReportModel.setReportPriority(Integer.MAX_VALUE);
        return applicationReportModel;
    }
161229
function createClassicNode(
  t: $FlowFixMe,
  path: Object,
  graphqlDefinition: DefinitionNode,
  state: BabelState,
): Object {
  if (graphqlDefinition.kind === 'FragmentDefinition') {
    return createFragmentConcreteNode(t, path, graphqlDefinition, state);
  }

  if (graphqlDefinition.kind === 'OperationDefinition') {
    return createOperationConcreteNode(t, path, graphqlDefinition, state);
  }

  throw new Error(
    'BabelPluginRelay: Expected a fragment, mutation, query, or ' +
      'subscription, got `' +
      graphqlDefinition.kind +
      '`.',
  );
}
889251
@Override
    public void onCreate() {
        super.onCreate();

        graphMonitor = new Graph.Monitor() {
            @Override
            public void onInject(Object target) {
                if (controller != null && target == MvcService.this) {
                    controller.view = MvcService.this;
                }
            }

            @Override
            public void onRelease(Object target) {

            }
        };
        Mvc.graph().registerMonitor(graphMonitor);

        if (getControllerClass() != null) {
            try {
                controller = Mvc.graph().reference(getControllerClass(), null);
            } catch (CircularDependenciesException e) {
                e.printStackTrace();
            } catch (ProvideException e) {
                e.printStackTrace();
            } catch (ProviderMissingException e) {
                throw new IllegalStateException("Unable to inject "
                        + getControllerClass().getName() + ".\n" + e.getMessage(), e);
            }
        }

        Mvc.graph().inject(this);

        eventRegister = new EventRegister(this);
        eventRegister.registerEventBuses();
    }
1130359
function savePrettyGraphSONSync(graph, filename) {
        // Build the GraphSON in memory in Java.
        var ByteArrayOutputStream = Tinkerpop.autoImport('ByteArrayOutputStream');
        var stream = new ByteArrayOutputStream();
        var builder = Tinkerpop.GraphSONWriter.build();
        var mapper = _newGraphSONMapperSync();
        builder.mapper(mapper);
        var writer = builder.create();
        writer.writeGraph(stream, graph);
        // Beautify the JSON.
        var uglyString = stream.toString();
        var prettyString = _prettyGraphSONString(uglyString);
        // Write to the file.
        fs.writeFileSync(filename, prettyString);
        return graph;
    }
901285
@Override
	public ShapeStyle create(GeometryEditService editService, GeometryIndex index)
			throws GeometryIndexNotFoundException {
		if (index == null) {
			return findGeometryStyle(editService, index);
		}
		switch (editService.getIndexService().getType(index)) {
			case TYPE_VERTEX:
				return findVertexStyle(editService, index);
			case TYPE_EDGE:
				return findEdgeStyle(editService, index);
			default:
				return findGeometryStyle(editService, index);
		}
	}
318737
function createGraph(modules, circular, config, options) {
	const g = graphviz.digraph('G');
	const nodes = {};
	const cyclicModules = circular.reduce((a, b) => a.concat(b), []);

	if (config.graphVizPath) {
		g.setGraphVizPath(config.graphVizPath);
	}

	Object.keys(modules).forEach((id) => {
		nodes[id] = nodes[id] || g.addNode(id);

		if (!modules[id].length) {
			setNodeColor(nodes[id], config.noDependencyColor);
		} else if (cyclicModules.indexOf(id) >= 0) {
			setNodeColor(nodes[id], config.cyclicNodeColor);
		}

		modules[id].forEach((depId) => {
			nodes[depId] = nodes[depId] || g.addNode(depId);

			if (!modules[depId]) {
				setNodeColor(nodes[depId], config.noDependencyColor);
			}

			g.addEdge(nodes[id], nodes[depId]);
		});
	});

	return new Promise((resolve, reject) => {
		g.output(options, resolve, (code, out, err) => {
			reject(new Error(err));
		});
	});
}
56186
function GraphBuilder(options){

  options = options || {};

  // Precedence for resolvers.
  this.resolvers = options.resolvers || [
    require('./resolvers/absolute'),
    require('./resolvers/relative'),
    require('./resolvers/environment')
  ];

  this.handlers = options.directives || [];
}
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);
    }
723211
function create(context) {
    const settings = Object.assign({}, defaults, context.options[0]);

    function check(setting, node, list, format) {
        const val = settings[setting];
        const lines = list.map(line);

        if ((isLongerThan(val, lines) || isAlways(val)) && hasDuplicates(lines)) {
            const message = messages.always[setting];
            const fix = (f) => f.replaceTextRange(node.range, format(node));
            context.report({ node, message, fix });
        }

        if (isNever(val) && hasMultiple(lines)) {
            const message = messages.never[setting];
            context.report({ node, message });
        }
    }

    return {
        CallExpression(node) {
            if (!isAmdCall(node) || node.arguments.length < 2) return;

            const args = withoutModuleId(node.arguments);
            const deps = args[0];
            const func = args[1];

            if (!isArrayExpr(deps) || !isFunctionExpr(func)) return;

            const indent = indentation(func);

            check("paths", deps, deps.elements, formatPaths(indent));
            check("names", func, func.params, formatNames(indent, context));
        }
    };
}
946489
static Converter createDefaultConverter() {
        List<NodeFactory> factories;
        String property = System.getProperty(LIBRARIES_PROPERTY_NAME);

        if (property != null && property.trim().length() > 0) {
            factories = createFactoriesSpecifiedInProperty(property);
        } else {
            factories = createDefaultFactories();
        }

        if (factories.isEmpty()) {
            throw new IllegalStateException("Please add either json.org, Jackson 1.x, Jackson 2.x or Gson to the classpath");
        }
        return new Converter(factories);
    }
65815
@Override
	public DataSet<Vertex<K, VV>> createResult() {
		if (this.initialVertices == null) {
			throw new IllegalStateException("The input data set has not been set.");
		}

		// prepare some type information
		TypeInformation<K> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0);
		TypeInformation<Tuple2<K, Message>> messageTypeInfo = new TupleTypeInfo<>(keyType, messageType);

		// create a graph
		Graph<K, VV, EV> graph =
				Graph.fromDataSet(initialVertices, edgesWithValue, initialVertices.getExecutionEnvironment());

		// check whether the numVertices option is set and, if so, compute the total number of vertices
		// and set it within the scatter and gather functions

		DataSet<LongValue> numberOfVertices = null;
		if (this.configuration != null && this.configuration.isOptNumVertices()) {
			try {
				numberOfVertices = GraphUtils.count(this.initialVertices);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (this.configuration != null) {
			scatterFunction.setDirection(this.configuration.getDirection());
		} else {
			scatterFunction.setDirection(EdgeDirection.OUT);
		}

		// retrieve the direction in which the updates are made and in which the messages are sent
		EdgeDirection messagingDirection = scatterFunction.getDirection();

		// check whether the degrees option is set and, if so, compute the in and the out degrees and
		// add them to the vertex value
		if (this.configuration != null && this.configuration.isOptDegrees()) {
			return createResultVerticesWithDegrees(graph, messagingDirection, messageTypeInfo, numberOfVertices);
		} else {
			return createResultSimpleVertex(messagingDirection, messageTypeInfo, numberOfVertices);
		}
	}
570980
function (graph, opts, params) {
    if (graph.children.length == 0) return '';

    function getRels(node) {
      var rels = [];
      node.children.forEach(function(childNode) {
        rels.push('(' + node.name + ')-[__rel_' + childNode.name + ':' + childNode.comp.rel + ']->(' + childNode.name + ')');
        rels.push.apply(rels, getRels(childNode));
      });
      return rels;
    }
    
    return 'CREATE UNIQUE ' + getRels(graph).join(',');
  }
81806
private JComponent createJComponent(final DirectedGraph<Object, JobGraphLink> graph) {
        final int vertexCount = graph.getVertexCount();
        logger.debug("Rendering graph with {} vertices", vertexCount);

        final JobGraphLayoutTransformer layoutTransformer = new JobGraphLayoutTransformer(_analysisJobBuilder, graph);
        final Dimension preferredSize = layoutTransformer.getPreferredSize();

        final StaticLayout<Object, JobGraphLink> layout = new StaticLayout<>(graph, layoutTransformer, preferredSize);

        final Collection<Object> vertices = graph.getVertices();
        for (final Object vertex : vertices) {
            // manually initialize all vertices
            layout.apply(vertex);
        }

        if (!vertices.isEmpty() && !layoutTransformer.isTransformed()) {
            throw new IllegalStateException("Layout transformer was never invoked!");
        }

        final VisualizationViewer<Object, JobGraphLink> visualizationViewer =
                new VisualizationViewer<>(layout, preferredSize);
        visualizationViewer.setTransferHandler(new TransferHandler() {

            private static final long serialVersionUID = 1L;

            public boolean canImport(final TransferSupport support) {
                return support.isDataFlavorSupported(DragDropUtils.MODEL_DATA_FLAVOR);
            }

            public boolean importData(final TransferSupport support) {
                final Transferable transferable = support.getTransferable();

                final Object data;
                try {
                    data = transferable.getTransferData(DragDropUtils.MODEL_DATA_FLAVOR);
                } catch (final Exception ex) {
                    logger.warn("Unexpected error while dropping data", ex);
                    return false;
                }

                if (data == null) {
                    return false;
                }

                final Point dropPoint = support.getDropLocation().getDropPoint();

                if (data instanceof Table) {
                    final Table table = (Table) data;
                    // position the table
                    JobGraphMetadata.setPointForTable(_analysisJobBuilder, table, dropPoint.x, dropPoint.y);
                    _analysisJobBuilder.addSourceColumns(table.getColumns());
                }

                if (data instanceof Column) {
                    final Column column = (Column) data;
                    final Table table = column.getTable();
                    final List<MetaModelInputColumn> columnsOfSameTable =
                            _analysisJobBuilder.getSourceColumnsOfTable(table);
                    if (columnsOfSameTable.isEmpty()) {
                        // the table is new - position it
                        JobGraphMetadata.setPointForTable(_analysisJobBuilder, table, dropPoint.x, dropPoint.y);
                    }
                    _analysisJobBuilder.addSourceColumn(column);
                }

                if (data instanceof ComponentDescriptor<?>) {
                    final ComponentDescriptor<?> descriptor = (ComponentDescriptor<?>) data;
                    final Map<String, String> metadata = JobGraphMetadata.createMetadataProperties(dropPoint);
                    _analysisJobBuilder.addComponent(descriptor, null, null, metadata);
                }
                return true;
            }

        });

        GraphUtils.applyStyles(visualizationViewer);
        visualizationViewer.addPreRenderPaintable(new Paintable() {
            @Override
            public boolean useTransform() {
                return false;
            }

            @Override
            public void paint(final Graphics g) {
                final GradientPaint paint = new GradientPaint(0, 0, WidgetUtils.BG_COLOR_BRIGHTEST, 0,
                        visualizationViewer.getHeight(), WidgetUtils.BG_COLOR_BRIGHTEST);
                if (g instanceof Graphics2D) {
                    final Graphics2D g2d = (Graphics2D) g;
                    g2d.setPaint(paint);
                } else {
                    g.setColor(WidgetUtils.BG_COLOR_BRIGHT);
                }
                g.fillRect(0, 0, visualizationViewer.getWidth(), visualizationViewer.getHeight());

                final Dimension size = _panel.getSize();
                if (size.height < adjuster.adjust(300) || size.width < adjuster.adjust(500)) {
                    // don't show the background hints - it will be too
                    // disturbing
                    return;
                }

                final String showCanvasHints = _userPreferences.getAdditionalProperties()
                        .get(JobGraphTransformers.USER_PREFERENCES_PROPERTY_SHOW_CANVAS_HINTS);
                if ("false".equals(showCanvasHints)) {
                    // don't show the background hints - the user has decided
                    // not to have them.
                    return;
                }

                String title;
                String subTitle;
                String imagePath;

                g.setColor(WidgetUtils.BG_COLOR_MEDIUM);
                if (_analysisJobBuilder.getSourceColumns().size() == 0) {
                    title = "Select source ...";
                    subTitle = "Pick table/columns in the tree to the left.\n"
                            + "You can drag it onto this canvas with your mouse.";
                    imagePath = "images/window/canvas-bg-table.png";
                } else if (_analysisJobBuilder.getComponentCount() == 0) {
                    title = "Start building ...";
                    subTitle = "Add components to your job. Right-click the canvas\n"
                            + "to explore the library of available components.";
                    imagePath = "images/window/canvas-bg-plus.png";
                } else if (graph.getEdgeCount() == 0) {
                    title = "Connect the pieces ...";
                    subTitle = "Right-click the source table and select 'Link to ...'.\n"
                            + "This directs the flow of data to the component.";
                    imagePath = "images/window/canvas-bg-connect.png";
                } else if (_analysisJobBuilder.getResultProducingComponentBuilders().size() == 0
                        && _analysisJobBuilder.getConsumedOutputDataStreamsJobBuilders().size() == 0
                        && _analysisJobBuilder.getComponentCount() <= 3) {
                    title = "Your job is almost ready.";
                    subTitle = "Jobs need to either 'Analyze' or 'Write' something.\n"
                            + "So add one or more such components.";
                    imagePath = "images/window/canvas-bg-plus.png";
                } else {
                    title = null;
                    subTitle = null;
                    imagePath = null;

                    try {
                        if (_analysisJobBuilder.isConfigured(true)) {
                            title = "Ready to execute";
                            subTitle =
                                    "Click the 'Execute' button in the upper-right\ncorner when you're ready to run the job.";
                            imagePath = "images/window/canvas-bg-execute.png";
                            g.drawImage(ImageManager.get().getImage("images/window/canvas-bg-execute-hint.png"),
                                    size.width - adjuster.adjust(175), 0, null);
                        } else {
                            title = "Configure the job ...";
                            subTitle = "Job is not correctly configured";
                            imagePath = "images/window/canvas-bg-error.png";
                        }
                    } catch (final Exception ex) {
                        logger.debug("Job not correctly configured", ex);
                        final String errorMessage;
                        if (ex instanceof UnconfiguredConfiguredPropertyException) {
                            final UnconfiguredConfiguredPropertyException unconfiguredConfiguredPropertyException =
                                    (UnconfiguredConfiguredPropertyException) ex;
                            final ConfiguredPropertyDescriptor configuredProperty =
                                    unconfiguredConfiguredPropertyException.getConfiguredProperty();
                            final ComponentBuilder componentBuilder =
                                    unconfiguredConfiguredPropertyException.getComponentBuilder();
                            title = "Configure " + "'" + LabelUtils.getLabel(componentBuilder) + "' ...";
                            errorMessage = "Please set '" + configuredProperty.getName() + "' to continue";
                        } else {
                            title = "Something went wrong ...";
                            errorMessage = ex.getMessage();
                        }
                        subTitle = errorMessage;
                        imagePath = "images/window/canvas-bg-error.png";
                    }
                }

                final int yOffset = size.height - adjuster.adjust(150);
                final int xOffset = adjuster.adjust(150);

                final float titleFontSize;
                final float subTitleFontSize;
                if (size.width < adjuster.adjust(650)) {
                    titleFontSize = adjuster.adjust(30f);
                    subTitleFontSize = adjuster.adjust(17f);
                } else {
                    titleFontSize = adjuster.adjust(35f);
                    subTitleFontSize = adjuster.adjust(20f);
                }

                if (title != null) {
                    g.setFont(WidgetUtils.FONT_BANNER.deriveFont(titleFontSize));
                    g.drawString(title, xOffset, yOffset);
                }

                if (subTitle != null) {
                    final String[] lines = subTitle.split("\n");
                    g.setFont(WidgetUtils.FONT_BANNER.deriveFont(subTitleFontSize));
                    int y = yOffset + adjuster.adjust(10);
                    for (final String line : lines) {
                        y = y + adjuster.adjust(30);
                        g.drawString(line, xOffset, y);
                    }
                }

                if (imagePath != null) {
                    g.drawImage(ImageManager.get().getImage(imagePath), xOffset - adjuster.adjust(120),
                            yOffset - adjuster.adjust(30), null);
                }
            }
        });

        final JobGraphContext graphContext = new JobGraphContext(this, visualizationViewer, _analysisJobBuilder);

        final JobGraphActions actions = new JobGraphActions(graphContext, _windowContext, _presenterRendererFactory,
                _componentConfigurationDialogs, _tableConfigurationDialogs);
        final JobGraphLinkPainter linkPainter = new JobGraphLinkPainter(graphContext, actions);

        final JobGraphLinkPainterMousePlugin linkPainterMousePlugin =
                new JobGraphLinkPainterMousePlugin(linkPainter, graphContext);
        final GraphMouse graphMouse = visualizationViewer.getGraphMouse();
        if (graphMouse instanceof PluggableGraphMouse) {
            final PluggableGraphMouse pluggableGraphMouse = (PluggableGraphMouse) graphMouse;
            pluggableGraphMouse.add(linkPainterMousePlugin);
        }

        final JobGraphMouseListener graphMouseListener =
                new JobGraphMouseListener(graphContext, linkPainter, actions, _windowContext);

        visualizationViewer.addGraphMouseListener(graphMouseListener);
        visualizationViewer.addMouseListener(graphMouseListener);

        final RenderContext<Object, JobGraphLink> renderContext = visualizationViewer.getRenderContext();

        final JobGraphTransformers transformers = new JobGraphTransformers(graph, _userPreferences, _highlighedVertexes);

        // instrument the render context with all our transformers and stuff
        renderContext.setVertexFontTransformer(transformers.getVertexFontTransformer());
        renderContext.setVertexLabelTransformer(JobGraphTransformers.VERTEX_LABEL_TRANSFORMER);
        renderContext.setEdgeArrowPredicate(JobGraphTransformers.EDGE_ARROW_PREDICATE);
        renderContext.setEdgeArrowTransformer(JobGraphTransformers.EDGE_ARROW_TRANSFORMER);
        renderContext.setEdgeLabelTransformer(JobGraphTransformers.EDGE_LABEL_TRANSFORMER);
        renderContext.setEdgeShapeTransformer(transformers.getEdgeShapeTransformer());
        renderContext.setEdgeLabelClosenessTransformer(JobGraphTransformers.EDGE_LABEL_CLOSENESS_TRANSFORMER);
        renderContext.setEdgeLabelRenderer(transformers.getEdgeLabelRenderer());
        renderContext.setVertexIconTransformer(JobGraphTransformers.VERTEX_ICON_TRANSFORMER);
        renderContext.setVertexShapeTransformer(JobGraphTransformers.VERTEX_SHAPE_TRANSFORMER);

        final JButton graphPreferencesButton = createGraphPreferencesButton();
        visualizationViewer.setLayout(new BorderLayout());
        visualizationViewer.add(DCPanel.flow(Alignment.RIGHT, 0, 0, graphPreferencesButton), BorderLayout.SOUTH);

        // we save the values of the scrollbars in order to allow refreshes to
        // retain scroll position.
        final GraphZoomScrollPane scrollPane = new GraphZoomScrollPane(visualizationViewer);
        scrollPane.setCorner(new DCPanel(WidgetUtils.COLOR_DEFAULT_BACKGROUND));
        if (_scrollHorizontal > 0) {
            setScrollbarValue(scrollPane.getHorizontalScrollBar(), _scrollHorizontal);
        }
        if (_scrollVertical > 0) {
            setScrollbarValue(scrollPane.getVerticalScrollBar(), _scrollVertical);
        }
        final AdjustmentListener adjustmentListener = e -> {
            _scrollHorizontal = scrollPane.getHorizontalScrollBar().getValue();
            _scrollVertical = scrollPane.getVerticalScrollBar().getValue();
        };
        scrollPane.getHorizontalScrollBar().addAdjustmentListener(adjustmentListener);
        scrollPane.getVerticalScrollBar().addAdjustmentListener(adjustmentListener);
        new JobGraphBindingsManager(graphContext, actions, scrollPane).register();

        return scrollPane;
    }
434926
function createGraphvizOptions(config) {
	const graphVizOptions = config.graphVizOptions || {};

	return {
		G: Object.assign({
			overlap: false,
			pad: 0.3,
			rankdir: config.rankdir,
			layout: config.layout,
			bgcolor: config.backgroundColor
		}, graphVizOptions.G),
		E: Object.assign({
			color: config.edgeColor
		}, graphVizOptions.E),
		N: Object.assign({
			fontname: config.fontName,
			fontsize: config.fontSize,
			color: config.nodeColor,
			shape: config.nodeShape,
			style: config.nodeStyle,
			height: 0,
			fontcolor: config.nodeColor
		}, graphVizOptions.N)
	};
}
992160
def infect(cls, graph, key, default_scope=None):
        
        func = graph.factory_for(key)
        if isinstance(func, cls):
            func = func.func
        factory = cls(key, func, default_scope)
        graph._registry.factories[key] = factory
        return factory
16979
function factoryObjectGraph(ParentClassGraph) {
  /**
   * Inherited class. Class with methods for control links in graph.
   * Adapted for array collection.
   * 
   * @class
   * @description `import { ObjectGraph as Graph } from 'ancient-graph';`
   */
  class ObjectGraph extends ParentClassGraph {
    
    /**
     * Construct new graph and checks for required adaptation methods.
     * @param {Array[]} collection
     * @param {Object.<string, string>} fields - matching of fields in the link with fields in document
     * @param {Object} [config] - Additional config.
     * @param {Object} [config.aliases]
     * @param {String} [config.aliases.$]
     * @throws {Error} if the adapter methods is not complete
     */
    constructor(collection, fields, config) {
      super(...arguments);
      this.emitter = new EventEmitter();
    }
    
    /**
     * Specifies the id field on insert
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */
    _idGenerator(index, link) {
      return ""+index;
    };
    
    /**
     * Generate insert modifier.
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */
    _insertModifier(link) {
      var _modifier = {};
      for (var f in link) {
        if (this.fields[f]) {
          _modifier[this.fields[f]] = link[this.config.aliases[f]];
        }
      }
      return _modifier;
    };
    
    /**
     * Should insert new link into graph.
     * Return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {Link} link
     * @param {Graph~insertCallback} [callback]
     * @param {Object} [context]
     * @return {number|string} [id]
     */
    insert(link, callback, context) {
      this.callback
      var _modifier = this._insertModifier(link);
      var index, error, id;
      try {
        index = this.collection.push(_modifier) - 1;
        if (!this.collection[index].hasOwnProperty(this.fields[this.config.aliases['id']])) {
          id = this.collection[index][this.fields[this.config.aliases['id']]] = this._idGenerator(index, this.collection[index]);
        }
        this.emitter.emit('insert', this.collection[index]);
      } catch(_error) {
        error = _error;
      }
      if (callback) {
        callback(error, id)
      }
      return id;
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the unique id of inserted link as the second.
     *
     * @callback Graph~insertCallback
     * @param {Error} [error]
     * @param {number|string} [id]
     */
    
    /**
     * Push into link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */
    _updateModifierPush(data, item) {
      data.push(item);
    }
    
    /**
     * Push into link value some item/items if not already exists.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */
    _updateModifierAdd(data, item) {
      if (lodash.isArray(item)) {
        for (var i in item) {
          this._updateModifierAdd(data, item[i]);
        }
      } else {
        var index = lodash.indexOf(data, item);
        if (index < 0) {
          this._updateModifierPush(data, item);
        }
      }
    }
     
    /**
     * Remove from link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */
    _updateModifierRemove(data, item) {
      if (lodash.isArray(item)) {
        for (var i in item) {
          this._updateModifierRemove(data, item[i]);
        }
      } else {
        lodash.remove(data, function(value) {
          return value == item;
        });
      }
    }
  
    /**
     * Generate update modifier.
     * 
     * @param {LinkModifier} modifier 
     * @param {Object} result
     * @return {number|string} id;
     */
    _updateModifier(modifier, result) {
      for (var m in modifier) {
        if (this.fields[m]) {
          if (typeof(modifier[m]) == 'undefined') {
            delete result[this.fields[m]];
          } else {
            if (typeof(modifier[m]) == 'object') {
              if (lodash.isArray(modifier[m])) {
                result[this.fields[m]] = modifier[m];
              } else {
                if (!lodash.isArray(result[this.fields[m]])) {
                  result[this.fields[m]] = result[this.fields[m]]?[result[this.fields[m]]]:[];
                }
                for (var key in modifier[m]) {
                  if (key == 'add') {
                    this._updateModifierAdd(result[this.fields[m]], modifier[m][key]);
                  }
                  if (key == 'push') {
                    this._updateModifierPush(result[this.fields[m]], modifier[m][key]);
                  }
                  if (key == 'remove') {
                    this._updateModifierRemove(result[this.fields[m]], modifier[m][key]);
                  }
                }
              }
            } else {
              result[this.fields[m]] = modifier[m];
            }
          }
        }
      }
    };
    
    /**
     * Should update to new state of modifier object link by unique id or by link query object.
     * If the database allows, it is recommended to return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {string|LinkSelector} selector
     * @param {LinkModifier} modifier
     * @param {Graph~updateCallback} [callback]
     * @param {Object} [context]
     * @return {number} [count]
     */
    update(selector, modifier, callback, context) {
      var results = this._fetch(selector);
      for (var r in results) {
        var oldResult = lodash.cloneDeep(results[r]);
        this._updateModifier(modifier, results[r]);
        this.emitter.emit('update', results[r], oldResult);
      }
      if (callback) callback(undefined, results.length);
      return results.length;
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.
     *
     * @callback Graph~updateCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Should remove link by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @param {Graph~removeCallback} [callback]
     * @param {Object} [context]
     */
    remove(selector, callback, context) {
      var oldLength = this.collection.length;
      var removed = [];
      lodash.remove(this.collection, (result) => {
        var _query = this.query(selector)(result);
        if (_query) removed.push(result)
        return _query;
      });
      for (var r in removed) {
        this.emitter.emit('remove', removed[r]);
      }
      var newLength = this.collection.length;
      if (callback) callback(undefined, oldLength - newLength);
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument.
     *
     * @callback Graph~removeCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Generate adapter for database query for links search by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @return {*} query
     */
    query(selector) {
      var type = typeof(selector);
      if (type == 'string' || type == 'number') {
        return (doc) => { return doc[this.fields[this.config.aliases['id']]] == selector };
      } else if (type == 'object') {
        return (doc) => {
          if (typeof(doc) != 'object') return false;
          for (var m in selector) {
            if (this.fields[m]) {
              if (typeof(selector[m]) == 'undefined') {
                if (doc.hasOwnProperty(this.fields[m])) return false;
              } else {
                if (lodash.isArray(doc[this.fields[m]])) {
                  if (lodash.isArray(selector[m])) {
                    for (var s in selector[m]) {
                      if (!lodash.includes(doc[this.fields[m]], selector[m][s])) {
                        return false;
                      }
                    }
                  } else {
                    if (!lodash.includes(doc[this.fields[m]], selector[m])) {
                      return false;
                    }
                  }
                } else {
                  if (doc[this.fields[m]] != selector[m]) return false;
                }
              }
            }
          }
          return true;
        }
      }
    }
    
    /**
     * Generate adapted for database options object.
     * 
     * @param {Object} [options]
     * @return {*} options - a options suitable for the database
     */
    options(options) {
      var _options = {};
      if (options) {
        if (options.sort) {
          _options.sort = { keys: [], orders: [] };
          for (var s in options.sort) {
            if (this.fields[s]) {
              _options.sort.keys.push(this.fields[s]);
              _options.sort.orders.push(options.sort[s]?'asc':'desc');
            }
          }
        }
        if (typeof(options.skip) == 'number') {
          _options.skip = options.skip;
        }
        if (typeof(options.limit) == 'number') {
          _options.limit = options.limit;
        }
      }
      return _options;
    }
    
    /**
     * Generate Link from document by fields.
     * 
     * @param {Object} document
     * @return {Link} link
     */
    _generateLink(document) {
      var link = {};
      for (var f in this.fields) {
        if (document.hasOwnProperty(this.fields[f])) {
          link[f] = document[this.fields[f]];
        }
      }
      return link;
    }
    
    /**
     * Get one first matching link.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~getCallback} [callback]
     * @return {Link} link - result link object
     */
    get(selector, options, callback) {
      var results = this.fetch(selector, options, (error, results) => {
        if (callback) callback(error, results?results[0]:undefined);
      });
      if (results) return results[0];
    }
    
    /**
     * Fetch native database documents.
     * 
     * @param {string|linkSelector} selector
     * @param {SelectOptions} [options]
     * @return {Object[]} documents - result documents
     */
    _fetch(selector, options) {
      var query = this.query(selector);
      var documents = lodash.filter(this.collection, query); 
      var _options = this.options(options);
      if (_options.sort) documents = lodash.orderBy(documents, _options.sort.keys, _options.orders);
      var skip = _options.skip?_options.skip:0;
      var limit = _options.limit?skip+_options.limit:_options.limit;
      documents = documents.slice(skip, limit);
      return documents;
    }
    
    /**
     * Find and all matching links as an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~fetchCallback} [callback]
     * @return {Link[]} links - result links objects in array
     */
    fetch(selector, options, callback) {
      var documents = this._fetch(selector, options);
      var links = [];
      for (var d in documents) {
        links.push(this._generateLink(documents[d]));
      }
      if (callback) callback(undefined, links);
      return links;
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the result links objects in array.
     *
     * @callback Graph~fetchCallback
     * @param {Error} [error]
     * @param {Link[]} [links]
     */
    
    /**
     * Should call callback once for each matching document, sequentially and synchronously.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~eachCallback} [callback]
     */
    each(selector, options, callback) {
      var links = this.fetch(selector, options);
      for (var l in links) {
        callback(links[l]);
      }
    }
    
    /**
     * @callback Graph~eachCallback
     * @param {Link} [link]
     */
    
    /**
     * Map callback over all matching documents. Returns an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~mapCallback} [callback]
     * @return {Array} results
     */
    map(selector, options, callback) {
      var links = this.fetch(selector, options);
      return links.map(callback);
    }
    
    /**
     * @callback Graph~mapCallback
     * @param {Link} [link]
     * @return {*} result
     */
    
    /**
     * Count all matching documents.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~countCallback} [callback]
     * @return {number} [count]
     */
    count(selector, options, callback) {
      var links = this.fetch(selector, options);
      if (callback) callback(undefined, links.length);
      return links.length;
    }
    
    /**
     * @callback Graph~countCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Should subscribe to the events: link, unlink, insert, update, remove.
     * 
     * @param {string} event - One event name
     * @param {Graph~onCallback} callback
     * @returns {Function} Stops event subscription.
     * @example
     * var counter = 0;
     * var stop = graph.on('update', (oldData, newData) => {
     *   if (oldData.id == '1') console.log(oldData.id, 'is changed');
     *   counter++;
     *   if (counter == 3) stop();
     * });
     */
    on(event, callback) {
      var subscriptions = [];
      
      if (event == 'insert') {
        subscriptions.push(this.emitter.addListener('insert', (document) => {
          callback(undefined, this._generateLink(document));
        }));
      }
      if (event == 'update') {
        subscriptions.push(this.emitter.addListener('update', (newDocument, oldDocument) => {
          callback(this._generateLink(oldDocument), this._generateLink(newDocument));
        }));
      }
      if (event == 'remove') {
        subscriptions.push(this.emitter.addListener('remove', (document) => {
          callback(this._generateLink(document), undefined);
        }));
      }
      if (event == 'link') {
        subscriptions.push(this.emitter.addListener('insert', (document) => {
          callback(undefined, this._generateLink(document));
        }));
        subscriptions.push(this.emitter.addListener('update', (newDocument, oldDocument) => {
          callback(this._generateLink(oldDocument), this._generateLink(newDocument));
        }));
      }
      if (event == 'unlink') {
        subscriptions.push(this.emitter.addListener('update', (newDocument, oldDocument) => {
          callback(this._generateLink(oldDocument), this._generateLink(newDocument));
        }));
        subscriptions.push(this.emitter.addListener('remove', (document) => {
          callback(this._generateLink(document), undefined);
        }));
      }
      
      return () => {
        for (var subscription of subscriptions) {
          subscription.remove();
        }
      };
    }
    
    /**
     * @callback Graph~onCallback
     * @param {Link} [oldLink] - can be undefined on link and insert events
     * @param {Link} [newLink] - can be undefined on unlink and remove events
     * @param {Object} [context] - additional app information, such as context.userId
     */
  }
  
  return ObjectGraph;
}
350773
public static Titan0Vertex createVertex(Titan0Graph graph, Vertex source) {

        if (source == null) {
            return null;
        }
        return new Titan0Vertex(graph, source);
    }