Add equivalentClass and sameAs relationships

        Uses external resource map located in
        /resources/clique_leader.yaml to determine
        if an NCBITaxon ID space is a clique leader
504460
def _add_gene_equivalencies(self, xrefs, gene_id, taxon):
        

        clique_map = self.open_and_parse_yaml(self.resources['clique_leader'])

        if self.test_mode:
            graph = self.testgraph
        else:
            graph = self.graph
        model = Model(graph)
        filter_out = ['Vega', 'IMGT/GENE-DB', 'Araport']

        # deal with the dbxrefs
        # MIM:614444|HGNC:HGNC:16851|Ensembl:ENSG00000136828|HPRD:11479|Vega:OTTHUMG00000020696

        for dbxref in xrefs.strip().split('|'):
            prefix = ':'.join(dbxref.split(':')[:-1]).strip()
            if prefix in self.localtt:
                prefix = self.localtt[prefix]
            dbxref_curie = ':'.join((prefix, dbxref.split(':')[-1]))

            if dbxref_curie is not None and prefix != '':
                if prefix == 'HPRD':  # proteins are not == genes.
                    model.addTriple(
                        gene_id, self.globaltt['has gene product'], dbxref_curie)
                    continue
                    # skip some of these for now based on curie prefix
                if prefix in filter_out:
                    continue

                if prefix == 'ENSEMBL':
                    model.addXref(gene_id, dbxref_curie)
                if prefix == 'OMIM':
                    if DipperUtil.is_omim_disease(dbxref_curie):
                        continue
                try:
                    if self.class_or_indiv.get(gene_id) == 'C':
                        model.addEquivalentClass(gene_id, dbxref_curie)
                        if taxon in clique_map:
                            if clique_map[taxon] == prefix:
                                model.makeLeader(dbxref_curie)
                            elif clique_map[taxon] == gene_id.split(':')[0]:
                                model.makeLeader(gene_id)
                    else:
                        model.addSameIndividual(gene_id, dbxref_curie)
                except AssertionError as err:
                    LOG.warning("Error parsing %s: %s", gene_id, err)
        return
824180
public boolean mergeIdentical(SubunitCluster other) {

		if (!isIdenticalTo(other))
			return false;

		logger.info("SubunitClusters are identical");

		this.subunits.addAll(other.subunits);
		this.subunitEQR.addAll(other.subunitEQR);

		return true;
	}
1117048
def setup_generic_relations(model_class):
    
    Action = apps.get_model('actstream', 'action')

    if Action is None:
        raise RegistrationError(
            'Unable get actstream.Action. Potential circular imports '
            'in initialisation. Try moving actstream app to come after the '
            'apps which have models to register in the INSTALLED_APPS setting.'
        )

    related_attr_name = 'related_query_name'
    related_attr_value = 'actions_with_%s' % label(model_class)

    relations = {}
    for field in ('actor', 'target', 'action_object'):
        attr = '%s_actions' % field
        attr_value = '%s_as_%s' % (related_attr_value, field)
        kwargs = {
            'content_type_field': '%s_content_type' % field,
            'object_id_field': '%s_object_id' % field,
            related_attr_name: attr_value
        }
        rel = GenericRelation('actstream.Action', **kwargs)
        rel.contribute_to_class(model_class, attr)
        relations[field] = rel

        # @@@ I'm not entirely sure why this works
        setattr(Action, attr_value, None)
    return relations
1219785
@Override
   public void newOneToOneRelationship(Project project, final JavaResource resource, final String fieldName,
            final String fieldType,
            final String inverseFieldName,
            final FetchType fetchType, final boolean required,
            final Iterable<CascadeType> cascadeTypes) throws FileNotFoundException
   {
      JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);
      JavaClassSource entityClass = getJavaClassFrom(resource);
      JavaClassSource fieldEntityClass;
      if (areTypesSame(fieldType, entityClass.getCanonicalName()))
      {
         fieldEntityClass = entityClass;
      }
      else
      {
         fieldEntityClass = findEntity(project, fieldType);
         entityClass.addImport(fieldEntityClass);
      }

      FieldSource<JavaClassSource> localField = addFieldTo(entityClass, fieldEntityClass.getName(), fieldName,
               OneToOne.class.getName());
      AnnotationSource<JavaClassSource> annotation = localField.getAnnotation(OneToOne.class);
      if ((inverseFieldName != null) && !inverseFieldName.isEmpty())
      {
         FieldSource<JavaClassSource> inverseField = addFieldTo(fieldEntityClass, entityClass.getName(),
                  inverseFieldName,
                  OneToOne.class.getName());
         inverseField.getAnnotation(OneToOne.class).setStringValue("mappedBy", localField.getName());
         java.saveJavaSource(fieldEntityClass);
      }

      if (fetchType != null && fetchType != FetchType.EAGER)
      {
         annotation.setEnumValue("fetch", fetchType);
      }
      if (required)
      {
         // Set the optional attribute of @OneToOne/@ManyToOne only when false, since the default value is true
         annotation.setLiteralValue("optional", "false");
      }
      addCascade(cascadeTypes, annotation);
      java.saveJavaSource(entityClass);
   }
246349
public void addRelation() {

        if (m_relations == null) {
            m_relations = new HashMap<String, List<CmsRelation>>();
        }
        try {
            if (m_resource == null) {
                // skip relation import if the import of the resource failed
                return;
            }
            if (m_throwable != null) {
                // relation data is corrupt, ignore relation
                if (LOG.isWarnEnabled()) {
                    LOG.warn(
                        Messages.get().getBundle().key(
                            Messages.LOG_IMPORTEXPORT_ERROR_IMPORTING_RELATION_1,
                            getCms().getRequestContext().removeSiteRoot(m_resource.getRootPath())),
                        m_throwable);
                }
                getReport().println(m_throwable);
                getReport().addError(m_throwable);
                m_throwable = null;
                return;
            }
            List<CmsRelation> currentRelations = m_relations.get(m_resource.getRootPath());
            if (currentRelations == null) {
                currentRelations = new ArrayList<CmsRelation>();
                m_relations.put(m_resource.getRootPath(), currentRelations);
            }
            currentRelations.add(
                new CmsRelation(
                    m_resource.getStructureId(),
                    m_resource.getRootPath(),
                    m_relationId,
                    m_relationPath,
                    m_relationType));
        } finally {
            m_relationId = null;
            m_relationPath = null;
            m_relationType = null;
        }
    }
757750
public boolean equivalent(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        RepositoryResourceImpl other = (RepositoryResourceImpl) obj;
        if (_asset == null) {
            if (other._asset != null)
                return false;
        } else if (!_asset.equivalent(other._asset))
            return false;
        return true;
    }
53107
def link_reference(self, source, target):
        
        target_uid = api.get_uid(target)
        # get the annotation storage key
        key = self.get_relationship_key(target)
        # get all backreferences from the source
        # N.B. only like this we get the persistent mapping!
        backrefs = get_backreferences(source, relationship=None)
        if key not in backrefs:
            backrefs[key] = PersistentList()
        if target_uid not in backrefs[key]:
            backrefs[key].append(target_uid)
        return True
1315654
private void copyRelations(CmsDbContext dbc, CmsResource source, CmsResource target) throws CmsException {

        // copy relations all relations
        CmsObject cms = new CmsObject(getSecurityManager(), dbc.getRequestContext());
        Iterator<CmsRelation> itRelations = getRelationsForResource(
            dbc,
            source,
            CmsRelationFilter.TARGETS.filterNotDefinedInContent()).iterator();
        while (itRelations.hasNext()) {
            CmsRelation relation = itRelations.next();
            if (relation.getType().getCopyBehavior() == CopyBehavior.copy) {
                try {
                    CmsResource relTarget = relation.getTarget(cms, CmsResourceFilter.ALL);
                    addRelationToResource(dbc, target, relTarget, relation.getType(), true);
                } catch (CmsVfsResourceNotFoundException e) {
                    // ignore this broken relation
                    if (LOG.isWarnEnabled()) {
                        LOG.warn(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        // repair categories
        repairCategories(dbc, getProjectIdForContext(dbc), target);
    }
1232257
def add_resourcegroup(group, network_id,**kwargs):
    
    group_i                   = ResourceGroup()
    group_i.name              = group.name
    group_i.description       = group.description
    group_i.status            = group.status
    group_i.network_id        = network_id
    db.DBSession.add(group_i)
    db.DBSession.flush()
    return group_i
676307
def get_matching_resource_types(resource_type, resource_id,**kwargs):
    
    resource_i = None
    if resource_type == 'NETWORK':
        resource_i = db.DBSession.query(Network).filter(Network.id==resource_id).one()
    elif resource_type == 'NODE':
        resource_i = db.DBSession.query(Node).filter(Node.id==resource_id).one()
    elif resource_type == 'LINK':
        resource_i = db.DBSession.query(Link).filter(Link.id==resource_id).one()
    elif resource_type == 'GROUP':
        resource_i = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id==resource_id).one()

    matching_types = get_types_by_attr(resource_i)
    return matching_types
1152159
private Set<CmsResource> getDirectlyRelatedResources(CmsResource currentResource) {

        Set<CmsResource> directlyRelatedResources = Sets.newHashSet();
        List<CmsRelation> relations = getRelationsFromResource(currentResource);
        for (CmsRelation relation : relations) {
            LOG.info("Trying to read resource for relation " + relation.getTargetPath());
            CmsResource target = getResource(relation.getTargetId());
            if (target != null) {
                if (relation.getType().isStrong() || shouldAddWeakRelationTarget(target)) {
                    directlyRelatedResources.add(target);
                }
            }
        }
        try {
            CmsResource parentFolder = m_cms.readParentFolder(currentResource.getStructureId());
            if (parentFolder != null) { // parent folder of root folder is null
                if (parentFolder.getState().isNew() || currentResource.isFile()) {
                    directlyRelatedResources.add(parentFolder);
                }
            }
        } catch (CmsException e) {
            LOG.error(
                "Error processing parent folder for " + currentResource.getRootPath() + ": " + e.getLocalizedMessage(),
                e);
        }

        try {
            directlyRelatedResources.addAll(
                m_relatedResourceProvider.getAdditionalRelatedResources(m_cms, currentResource));
        } catch (Exception e) {
            LOG.error(
                "Error processing additional related resource for "
                    + currentResource.getRootPath()
                    + ": "
                    + e.getLocalizedMessage(),
                e);
        }
        return directlyRelatedResources;
    }
390831
public int compareSourceLines(BugCollection lhsCollection, BugCollection rhsCollection, SourceLineAnnotation lhs,
            SourceLineAnnotation rhs) {
        if (lhs == null || rhs == null) {
            return compareNullElements(lhs, rhs);
        }

        // Classes must match fuzzily.
        int cmp = compareClassesByName(lhsCollection, rhsCollection, lhs.getClassName(), rhs.getClassName());
        if (cmp != 0) {
            return cmp;
        }

        return 0;
    }
74894
def add_resource_fragment(fragment, include_related)
      fragment.primary = true

      init_included_relationships(fragment, include_related)

      @fragments[fragment.identity] = fragment
    end
928600
def add_nodes(network_id, nodes,**kwargs):
    
    start_time = datetime.datetime.now()

    names=[]        # used to check uniqueness of node name
    for n_i in nodes:
        if n_i.name in names:
            raise HydraError("Duplicate Node Name: %s"%(n_i.name))
        names.append(n_i.name)

    user_id = kwargs.get('user_id')
    try:
        net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
        net_i.check_write_permission(user_id)
    except NoResultFound:
        raise ResourceNotFoundError("Network %s not found"%(network_id))

    _add_nodes_to_database(net_i, nodes)

    net_i.project_id=net_i.project_id
    db.DBSession.flush()

    node_s =  db.DBSession.query(Node).filter(Node.network_id==network_id).all()

    #Maps temporary node_ids to real node_ids
    node_id_map = dict()

    iface_nodes = dict()
    for n_i in node_s:
        iface_nodes[n_i.name] = n_i

    for node in nodes:
        node_id_map[node.id] = iface_nodes[node.name]

    _bulk_add_resource_attrs(network_id, 'NODE', nodes, iface_nodes)

    log.info("Nodes added in %s", get_timing(start_time))
    return node_s
661374
private Stream<Triple> memberRelations(final FedoraResource container) throws RepositoryException {
        final org.apache.jena.graph.Node memberRelation;

        if (container.hasProperty(LDP_HAS_MEMBER_RELATION)) {
            final Property property = getJcrNode(container).getProperty(LDP_HAS_MEMBER_RELATION);
            memberRelation = createURI(property.getString());
        } else if (container.hasType(LDP_BASIC_CONTAINER)) {
            memberRelation = LDP_MEMBER.asNode();
        } else {
            return empty();
        }

        final String insertedContainerProperty;

        if (container.hasType(LDP_INDIRECT_CONTAINER)) {
            if (container.hasProperty(LDP_INSERTED_CONTENT_RELATION)) {
                insertedContainerProperty = getJcrNode(container).getProperty(LDP_INSERTED_CONTENT_RELATION)
                    .getString();
            } else {
                return empty();
            }
        } else {
            insertedContainerProperty = MEMBER_SUBJECT.getURI();
        }

        return container.getChildren().flatMap(
            UncheckedFunction.uncheck(child -> {
                final org.apache.jena.graph.Node childSubject = uriFor(child.getDescribedResource());

                if (insertedContainerProperty.equals(MEMBER_SUBJECT.getURI())) {
                    return of(create(subject(), memberRelation, childSubject));
                }
                String insertedContentProperty = getPropertyNameFromPredicate(getJcrNode(resource()),
                        createResource(insertedContainerProperty), null);

                if (child.hasProperty(insertedContentProperty)) {
                    // do nothing, insertedContentProperty is good

                } else if (child.hasProperty(getReferencePropertyName(insertedContentProperty))) {
                    // The insertedContentProperty is a pseudo reference property
                    insertedContentProperty = getReferencePropertyName(insertedContentProperty);

                } else {
                    // No property found!
                    return empty();
                }

                return iteratorToStream(new PropertyValueIterator(
                        getJcrNode(child).getProperty(insertedContentProperty)))
                    .map(uncheck(v -> create(subject(), memberRelation,
                        new ValueConverter(getJcrNode(container).getSession(), translator()).convert(v).asNode())));
            }));
    }
410657
private static void addDefaultEqualsMethod(ClassWriter cw, String implClassName)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, INDENT + "adding method : equals (Ljava/lang/Object;)Z");

        // -----------------------------------------------------------------------
        // public boolean equals(Object other)
        // {
        // -----------------------------------------------------------------------
        final String desc = "(Ljava/lang/Object;)Z";
        MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "equals", desc, null, null);
        GeneratorAdapter mg = new GeneratorAdapter(mv, ACC_PUBLIC, "equals", desc);
        mg.visitCode();

        // -----------------------------------------------------------------------
        //    return this == other;
        // -----------------------------------------------------------------------
        mg.loadThis();
        mg.loadArg(0);
        Label not_equal = new Label();
        mv.visitJumpInsn(IF_ACMPNE, not_equal);
        mg.visitInsn(ICONST_1);
        mg.returnValue();

        mg.visitLabel(not_equal);
        mg.visitInsn(ICONST_0);
        mg.returnValue();

        // -----------------------------------------------------------------------
        // }
        // -----------------------------------------------------------------------
        mg.endMethod();
        mg.visitEnd();
    }
1007416
private void setupRelationshipRepositories(Class<?> resourceClass, boolean mapped) {
		MetaLookup metaLookup = mapped ? resourceMetaLookup : jpaMetaLookup;

		Class<? extends MetaDataObject> metaClass = mapped ? MetaJsonObject.class : MetaJpaDataObject.class;
		MetaDataObject meta = metaLookup.getMeta(resourceClass, metaClass);

		for (MetaAttribute attr : meta.getAttributes()) {
			if (!attr.isAssociation()) {
				continue;
			}
			MetaType attrType = attr.getType().getElementType();

			if (attrType instanceof MetaEntity) {
				// normal entity association
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);

				// only include relations that are exposed as repositories
				if (attrConfig != null) {
					RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(attrImplClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
					context.addRepository(relationshipRepository);
				}
			} else if (attrType instanceof MetaResource) {
				Class<?> attrImplClass = attrType.getImplementationClass();
				JpaRepositoryConfig<?> attrConfig = getRepositoryConfig(attrImplClass);
				if (attrConfig == null || attrConfig.getMapper() == null) {
					throw new IllegalStateException("no mapped entity for " + attrType.getName() + " reference by " + attr.getId() + " registered");
				}
				JpaRepositoryConfig<?> targetConfig = getRepositoryConfig(attrImplClass);
				Class<?> targetResourceClass = targetConfig.getResourceClass();

				RelationshipRepositoryV2<?, ?, ?, ?> relationshipRepository = filterRelationshipCreation(targetResourceClass, repositoryFactory.createRelationshipRepository(this, resourceClass, attrConfig));
				context.addRepository(relationshipRepository);
			} else {
				throw new IllegalStateException("unable to process relation: " + attr.getId() + ", neither a entity nor a mapped entity is referenced");
			}
		}
	}