This descriptor is assigned to both sides of a many-to-many relationship.
To indicate the backwards direction pass `true` for `reverse`.
176959
function manyToManyDescriptor(
    declaredFromModelName,
    declaredToModelName,
    throughModelName,
    throughFields,
    reverse
) {
    return {
        get() {
            const {
                session: {
                    [declaredFromModelName]: DeclaredFromModel,
                    [declaredToModelName]: DeclaredToModel,
                    [throughModelName]: ThroughModel,
                },
            } = this.getClass();

            const ThisModel = reverse
                ? DeclaredToModel
                : DeclaredFromModel;
            const OtherModel = reverse
                ? DeclaredFromModel
                : DeclaredToModel;

            const thisReferencingField = reverse
                ? throughFields.to
                : throughFields.from;
            const otherReferencingField = reverse
                ? throughFields.from
                : throughFields.to;

            const thisId = this.getId();

            const throughQs = ThroughModel.filter({
                [thisReferencingField]: thisId,
            });

            /**
             * all IDs of instances of the other model that are
             * referenced by any instance of the current model
             */
            const referencedOtherIds = new Set(
                throughQs
                    .toRefArray()
                    .map(obj => obj[otherReferencingField])
            );

            /**
             * selects all instances of other model that are referenced
             * by any instance of the current model
             */
            const qs = OtherModel.filter(otherModelInstance => (
                referencedOtherIds.has(
                    otherModelInstance[OtherModel.idAttribute]
                )
            ));

            /**
             * Allows adding OtherModel instances to be referenced by the current instance.
             *
             * E.g. Book.first().authors.add(1, 2) would add the authors with IDs 1 and 2
             * to the first book's list of referenced authors.
             *
             * @return undefined
             */
            qs.add = function add(...entities) {
                const idsToAdd = new Set(
                    entities.map(normalizeEntity)
                );

                const existingQs = throughQs.filter(through => (
                    idsToAdd.has(through[otherReferencingField])
                ));

                if (existingQs.exists()) {
                    const existingIds = existingQs
                        .toRefArray()
                        .map(through => through[otherReferencingField]);

                    throw new Error(`Tried to add already existing ${OtherModel.modelName} id(s) ${existingIds} to the ${ThisModel.modelName} instance with id ${thisId}`);
                }

                idsToAdd.forEach((id) => {
                    ThroughModel.create({
                        [otherReferencingField]: id,
                        [thisReferencingField]: thisId,
                    });
                });
            };

            /**
             * Removes references to all OtherModel instances from the current model.
             *
             * E.g. Book.first().authors.clear() would cause the first book's list
             * of referenced authors to become empty.
             *
             * @return undefined
             */
            qs.clear = function clear() {
                throughQs.delete();
            };

            /**
             * Removes references to all passed OtherModel instances from the current model.
             *
             * E.g. Book.first().authors.remove(1, 2) would cause the authors with
             * IDs 1 and 2 to no longer be referenced by the first book.
             *
             * @return undefined
             */
            qs.remove = function remove(...entities) {
                const idsToRemove = new Set(
                    entities.map(normalizeEntity)
                );

                const entitiesToDelete = throughQs.filter(
                    through => idsToRemove.has(through[otherReferencingField])
                );

                if (entitiesToDelete.count() !== idsToRemove.size) {
                    // Tried deleting non-existing entities.
                    const entitiesToDeleteIds = entitiesToDelete
                        .toRefArray()
                        .map(through => through[otherReferencingField]);

                    const unexistingIds = [...idsToRemove].filter(
                        id => !entitiesToDeleteIds.includes(id)
                    );

                    throw new Error(`Tried to delete non-existing ${OtherModel.modelName} id(s) ${unexistingIds} from the ${ThisModel.modelName} instance with id ${thisId}`);
                }

                entitiesToDelete.delete();
            };

            return qs;
        },

        set() {
            throw new Error('Tried setting a M2M field. Please use the related QuerySet methods add, remove and clear.');
        },
    };
}
327543
public void reverse() {
	// overridden for performance only.
	double tmp;
	int limit=size/2;
	int j=size-1;

	double[] theElements = elements;
	for (int i=0; i<limit;) { //swap
		tmp=theElements[i];
		theElements[i++]=theElements[j];
		theElements[j--]=tmp;
	}
}
1111124
def Many2ManyThroughModel(field):
    ''''''
    from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField
    name_model = field.model._meta.name
    name_relmodel = field.relmodel._meta.name
    # The two models are the same.
    if name_model == name_relmodel:
        name_relmodel += '2'
    through = field.through
    # Create the through model
    if through is None:
        name = '{0}_{1}'.format(name_model, name_relmodel)

        class Meta:
            app_label = field.model._meta.app_label
        through = ModelType(name, (StdModel,), {'Meta': Meta})
        field.through = through
    # The first field
    field1 = ForeignKey(field.model,
                        related_name=field.name,
                        related_manager_class=makeMany2ManyRelatedManager(
                            field.relmodel,
                            name_model,
                            name_relmodel)
                        )
    field1.register_with_model(name_model, through)
    # The second field
    field2 = ForeignKey(field.relmodel,
                        related_name=field.related_name,
                        related_manager_class=makeMany2ManyRelatedManager(
                            field.model,
                            name_relmodel,
                            name_model)
                        )
    field2.register_with_model(name_relmodel, through)
    pk = CompositeIdField(name_model, name_relmodel)
    pk.register_with_model('id', through)
1220842
static void reverse(double[] d, DenseMatrix V) {
        int m = V.nrows();
        int n = d.length;
        int half = n / 2;
        for (int i = 0; i < half; i++) {
            double tmp = d[i];
            d[i] = d[n - i - 1];
            d[n - i - 1] = tmp;
        }
        for (int j = 0; j < half; j++) {
            for (int i = 0; i < m; i++) {
                double tmp = V.get(i, j);
                V.set(i, j, V.get(i, n - j - 1));
                V.set(i, n - j - 1, tmp);
            }
        }
    }
778898
protected function generateReversedRelationships()
    {

        foreach ($this->context->output['models'] as $modelFromKey => $modelFrom) {

            foreach ($modelFrom['relationships']['normal'] as $relationName => $relationship) {

                // skip negative references for now, don't reverse them
                if ($relationship['negative']) {
                    $this->context->log(
                        "Skipped negative relationship for reversing (model: {$modelFromKey} to "
                        . "{$relationship['model']}, field: {$relationship['field']})"
                    );
                    continue;
                }

                // also skip any relationship we've overridden not to reverse
                if (array_get($relationship, 'prevent_reverse')) {
                    $this->context->log(
                        "Skipped relationship for reversing due to override (model: {$modelFromKey} to "
                        . "{$relationship['model']}, field: {$relationship['field']})"
                    );
                    continue;
                }

                // special case, referencing model is itself
                $selfReference     = ($modelFromKey == $relationship['model']);
                $partOfMultiple    = $this->multipleBelongsToRelationsBetweenModels($modelFromKey, $relationship['model']);
                $reverseType       = null;
                $reverseCount      = 0;
                $reverseForeignKey = null;


                // For non-cms_m_references relations, we need to be careful about
                // foreign keys not following the expected laravel convention
                // since they expect the name to be based on the model names, whereas
                // it is actually defined by the field name in the CMS module,
                // which conforms to the relation name of the OPPOSITE relation.
                //
                // Too tricky to determine automatically, so force a foreign key parameter
                // if required.
                if ($relationship['type'] !== Generator::RELATIONSHIP_BELONGS_TO_MANY) {

                    if (array_get($relationship, 'key')) {

                        $reverseForeignKey = $relationship['key'];

                    } elseif ($relationName !== camel_case($this->context->output['models'][ $relationship['model'] ]['name'])) {

                        $reverseForeignKey = $this->normalizeDb($relationName);
                    }
                }

                // determine type and one/many (count) for reverse relationship
                switch ($relationship['type']) {

                    case Generator::RELATIONSHIP_HAS_ONE:
                    case Generator::RELATIONSHIP_HAS_MANY:
                        $reverseType = Generator::RELATIONSHIP_BELONGS_TO;
                        break;

                    case Generator::RELATIONSHIP_BELONGS_TO:
                        // for single-entry modules, a hasOne will do
                        if ($this->data->rawData['modules'][ $modelFromKey ]['max_entries'] == 1) {
                            $reverseType  = Generator::RELATIONSHIP_HAS_ONE;
                            $reverseCount = 1;
                        } else {
                            $reverseType = Generator::RELATIONSHIP_HAS_MANY;
                        }
                        break;

                    case Generator::RELATIONSHIP_BELONGS_TO_MANY:
                        $reverseType = Generator::RELATIONSHIP_BELONGS_TO_MANY;
                        break;

                    // default omitted on purpose
                }

                // pluralize the name if configured to and it's a to many relationship
                $pluralizeName = (
                        $reverseCount !== 1
                    &&  config('pxlcms.generator.models.pluralize_reversed_relationship_names')
                    &&  ! $partOfMultiple
                    &&  (   ! $selfReference
                        ||  config('pxlcms.generator.models.pluralize_reversed_relationship_names_for_self_reference')
                        )
                );

                // name of the relationship reversed
                // default is name of the model referred to
                $baseName = $relationName;

                if ($partOfMultiple) {

                    $baseName = camel_case($modelFrom['name']) . ucfirst($baseName);

                } elseif ( ! $selfReference) {

                    $baseName = $modelFrom['name'];
                }

                if ($pluralizeName) {

                    $baseName = ($this->context->dutchMode) ? $this->dutchPluralize($baseName) : str_plural($baseName);
                }


                if (array_get($relationship, 'reverse_name')) {
                    // hard override is applied without any checks

                    $reverseName = $relationship['reverse_name'];

                } elseif ($selfReference || $partOfMultiple) {
                    // self-referencing is an exception, since using the model name won't be useful
                    // part of multiple belongsto is an exception, to avoid duplicates

                    $reverseName = $baseName
                                 . config('pxlcms.generator.models.relationship_reverse_postfix', 'Reverse');

                } else {

                    $reverseName = camel_case($baseName);
                }

                $reverseNameSnakeCase = snake_case($reverseName);

                // if already taken by an attribute, add custom string
                if (    in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['normal_attributes'])
                    ||  in_array($reverseNameSnakeCase, $this->context->output['models'][ $relationship['model'] ]['translated_attributes'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['normal'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['image'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['file'])
                    ||  in_array($reverseName, $this->context->output['models'][ $relationship['model'] ]['relationships']['checkbox'])
                ) {
                    $reverseName .= config('pxlcms.generator.models.relationship_fallback_postfix', 'Reference');
                }


                $this->context->output['models'][ $relationship['model'] ]['relationships']['reverse'][ $reverseName ] = [
                    'type'     => $reverseType,
                    'model'    => $modelFromKey,
                    'single'   => ($reverseCount == 1),
                    'count'    => $reverseCount,
                    'field'    => $relationship['field'],
                    'key'      => $reverseForeignKey,
                    'negative' => false,
                ];
            }
        }
    }
381909
def assign_value(self, comp_def, value, src_ref):
        
        super().assign_value(comp_def, value, src_ref)
        if self.opposite_property in comp_def.properties:
            del comp_def.properties[self.opposite_property]
707983
@Override
    public void backward() {
        MVecArray<VarTensor> xs = modIn.getOutput();
        MVecArray<VarTensor> xsAdj = modIn.getOutputAdj();
        for (int a=0; a<xsAdj.dim(); a++) {
            VarTensor xAdj = xsAdj.get(a);
            // Compute the product of all the input factors except for a.
            // We compute this cavity by brute force, rather than dividing out from the joint.
            VarTensor prod = new VarTensor(yAdj);
            for (int b=0; b<xsAdj.dim(); b++) {
                if (a == b) { continue; }
                prod.prod(xs.get(b));
            }
            xAdj.add(prod.getMarginal(xAdj.getVars(), false));
        }
    }
96722
def reverse(self):
        
        clone = self._clone()
        assert self._ordering, "You need to set an ordering for reverse"
        ordering = []
        for order in self._ordering:
            for k,v in order.items():
                if v=="asc":
                    ordering.append({k: "desc"})
                else:
                    ordering.append({k: "asc"})
        clone._ordering=ordering
        return clone
876640
@Override
    public void backward() {
        Tensor xAdj = modIn.getOutputAdj();
        xAdj.addTensor(yAdj, dim, idx);
    }
1204533
def reversed(self):
        """"""
        new_cub = CubicBezier(self.end, self.control2, self.control1,
                              self.start)
        if self._length_info['length']:
            new_cub._length_info = self._length_info
            new_cub._length_info['bpoints'] = (
                self.end, self.control2, self.control1, self.start)
        return new_cub
566037
function( relation ) {
			var exists = _.any( this._reverseRelations, function( rel ) {
				return _.all( relation, function( val, key ) {
					return val === rel[ key ];
				});
			});
			
			if ( !exists && relation.model && relation.type ) {
				this._reverseRelations.push( relation );
				
				if ( !relation.model.prototype.relations ) {
					relation.model.prototype.relations = [];
				}
				relation.model.prototype.relations.push( relation );
				
				this.retroFitRelation( relation );
			}
		}
184565
private static void reverse(int first, int last, Swapper swapper) {
	// no more needed since manually inlined
	while (first < --last) {
		swapper.swap(first++,last);
	}
}
723873
def reverse(cls, value, prop, visitor):
        
        return (
            None if isinstance(value, (AttributeError, KeyError)) else
            value
        )
213746
private boolean hasBidirectionalAssociation(Class clazz)
    {
        ClassDescriptor cdesc;
        Collection refs;
        boolean hasBidirAssc;

        if (_withoutBidirAssc.contains(clazz))
        {
            return false;
        }

        if (_withBidirAssc.contains(clazz))
        {
            return true;
        }

        // first time we meet this class, let's look at metadata
        cdesc = _pb.getClassDescriptor(clazz);
        refs = cdesc.getObjectReferenceDescriptors();
        hasBidirAssc = false;
        REFS_CYCLE:
        for (Iterator it = refs.iterator(); it.hasNext(); )
        {
            ObjectReferenceDescriptor ord;
            ClassDescriptor relCDesc;
            Collection relRefs;

            ord = (ObjectReferenceDescriptor) it.next();
            relCDesc = _pb.getClassDescriptor(ord.getItemClass());
            relRefs = relCDesc.getObjectReferenceDescriptors();
            for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )
            {
                ObjectReferenceDescriptor relOrd;

                relOrd = (ObjectReferenceDescriptor) relIt.next();
                if (relOrd.getItemClass().equals(clazz))
                {
                    hasBidirAssc = true;
                    break REFS_CYCLE;
                }
            }
        }
        if (hasBidirAssc)
        {
            _withBidirAssc.add(clazz);
        }
        else
        {
            _withoutBidirAssc.add(clazz);
        }

        return hasBidirAssc;
    }
1284412
function ERDRelationship() {
        type.UndirectedRelationship.apply(this, arguments);

        /** @member {boolean} */
        this.identifying = true;

        /** @member {ERDRelationshipEnd} */
        this.end1 = new ERDRelationshipEnd();
        this.end1._parent = this;

        /** @member {ERDRelationshipEnd} */
        this.end2 = new ERDRelationshipEnd();
        this.end2._parent = this;
    }
468202
protected void reverse() {
    for(int i = 0, j = size - 1; i < j; i++, j--) {
      double tmpd = dists[j];
      dists[j] = dists[i];
      dists[i] = tmpd;
      int tmpi = ids[j];
      ids[j] = ids[i];
      ids[i] = tmpi;
    }
  }
22192
function(property, reverse) {
			reverse = (reverse) ? -1 : 1;
			return function (a, b) {
				a = a[property];
				b = b[property];
				if (a < b) {
					return reverse * -1;
				}
				if (a > b) {
					return reverse * 1;
				}
				return 0;
			};
		}