Nesting of reflected entities
503578
private function stackReflections()
    {
        foreach ($this->reflections as &$reflection) {
            foreach ($reflection['fields'] as &$field) {
                if (!empty($field['relatedToSection'])) {
                    if (isset($this->reflections[$field['relatedToSection']])) {
                        $field['sectionDetails'] = $this->reflections[$field['relatedToSection']];
                    }
                }
            }
        }
    }
17874
function flattenNodeGenerator(node, parent, index, settings, stack) {
  const { itemsKey, idKey } = settings;

  return function flattenNode(list) {
    node = settings.initNode(node);
    node[idKey] = node[idKey] || settings.generateUniqueId();
    list.push(node);

    if (node[itemsKey]) {
      for (let i = 0, len = node[itemsKey].length; i < len; i++) {
        stack.push(
          flattenNodeGenerator(
            node[itemsKey][i],
            node,
            i,
            settings,
            stack
          )
        );
      }
    }

    if (parent && parent[itemsKey]) {
      // Records children' id
      parent[itemsKey][index] = node[idKey];
      node.parent = parent[idKey];
    }

    return list;
  };
}
1160114
private void processGeneratedProperties(
			Serializable id,
			Object entity,
			Object[] state,
			SharedSessionContractImplementor session,
			GenerationTiming matchTiming) {

		Tuple tuple = getFreshTuple( EntityKeyBuilder.fromPersister( this, id, session ), session );
		saveSharedTuple( entity, tuple, session );

		if ( tuple == null || tuple.getSnapshot().isEmpty() ) {
			throw log.couldNotRetrieveEntityForRetrievalOfGeneratedProperties( getEntityName(), id );
		}

		int propertyIndex = -1;
		for ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) {
			propertyIndex++;
			final ValueGeneration valueGeneration = attribute.getValueGenerationStrategy();
			if ( isReadRequired( valueGeneration, matchTiming ) ) {
				Object hydratedState = gridPropertyTypes[propertyIndex].hydrate( tuple, getPropertyAliases( "", propertyIndex ), session, entity );
				state[propertyIndex] = gridPropertyTypes[propertyIndex].resolve( hydratedState, session, entity );
				setPropertyValue( entity, propertyIndex, state[propertyIndex] );
			}
		}
	}
344565
public JoinDescription nested(EntityPath<?>... paths) {
        for (EntityPath<?> path : paths) {
            nested(J.left(path));
        }

        return this;
    }
189208
def marshal(self, values):
        
        if values is not None:
            return [super(EntityCollection, self).marshal(v) for v in values]
703078
private Object wrap(Map<String, Object> results, EntityType entityType, Object result, EntityMetadata metadata,
            boolean isIdSet)
    {

        Map<String, Object> relations = new HashMap<String, Object>();
        Object key = null;
        Set<Attribute> attributes = entityType.getAttributes();
        for (Attribute attribute : attributes)
        {
            String fieldName = ((AbstractAttribute) attribute).getJPAColumnName();

            if (!attribute.isAssociation())
            {
                Object fieldValue = results.get(fieldName);

                key = onId(key, attribute, fieldValue);

                if (!isIdSet && key != null)
                {
                    PropertyAccessorHelper.setId(result, metadata, key);
                }

                fieldValue = onEnum(attribute, fieldValue);

                // TODOO:This has to be corrected. Reason is, in case of execute
                // query over composite key. It will not work

                setField(result, key, attribute, fieldValue);
            }

            if (attribute.isAssociation())
            {
                Object fieldValue = results.get(fieldName);
                relations.put(fieldName, fieldValue);
            }
        }
        return relations.isEmpty() ? result : new EnhanceEntity(result, key, relations);
    }
792824
function loadEntities() {
		// Uncompress the base charmap
		charMap = require('./string_entities_map.js');

		HTMLEntities = {};

		for (key in charMap) {
			for (i = 0; i < charMap[key].length; i++) {
				HTMLEntities[charMap[key][i]] = key;
			}
		}
	}
746798
def store_nested(key, value)
      var = unnest(key).reverse.inject(value) do |memo,k|
              if k.is_a?(Symbol)
                {k => memo}
              else
                ar = []
                ar[k] = memo
                ar
              end
            end
      deep_merge! var
    end
77730
def _nodes(output, parent=None):
    """"""
    # NOTE refactor so all outputs behave the same
    entity = getattr(output, 'entity', output)

    if isinstance(entity, Collection):
        for member in entity.members:
            if parent is not None:
                member = attr.evolve(member, parent=parent)
            yield from _nodes(member)
        yield output
    else:
        yield output
525218
function nest (str, refs, escape) {
		var res = [], match

		var a = 0
		while (match = re.exec(str)) {
			if (a++ > 10e3) throw Error('Circular references in parenthesis')

			res.push(str.slice(0, match.index))

			res.push(nest(refs[match[1]], refs))

			str = str.slice(match.index + match[0].length)
		}

		res.push(str)

		return res
	}
1076928
function(node, out, ufName, rootID, parentClasses) {
			var context = this,
				children = [],
				rootItem,
				itemRootID,
				value,
				propertyName,
				propertyVersion,
				i,
				x,
				y,
				z,
				child;

			children = modules.domUtils.getChildren( node );

			y = 0;
			z = children.length;
			while(y < z) {
				child = children[y];

				// get microformat classes for this single element
				var classes = context.getUfClassNames(child, ufName);

				// a property which is a microformat
				if(classes.root.length > 0 && classes.properties.length > 0 && !child.addedAsRoot) {
					// create object with type, property and value
					rootItem = context.createUfObject(
						classes.root,
						classes.typeVersion,
						modules.text.parse(this.document, child, context.options.textFormat)
					);

					// add the microformat as an array of properties
					propertyName = context.removePropPrefix(classes.properties[0][0]);

					// modifies value with "implied value rule"
					if(parentClasses && parentClasses.root.length === 1 && parentClasses.properties.length === 1){
						if(context.impliedValueRule){
							out = context.impliedValueRule(out, parentClasses.properties[0][0], classes.properties[0][0], value);
						}
					}

					if(out.properties[propertyName]) {
						out.properties[propertyName].push(rootItem);
					} else {
						out.properties[propertyName] = [rootItem];
					}

					context.rootID++;
					// used to stop duplication in heavily nested structures
					child.addedAsRoot = true;


					x = 0;
					i = rootItem.type.length;
					itemRootID = context.rootID;
					while(x < i) {
						context.walkChildren(child, rootItem, rootItem.type, itemRootID, classes);
						x++;
					}
					if(this.impliedRules){
						context.impliedRules(child, rootItem, classes);
					}
					this.cleanUfObject(rootItem);

				}

				// a property which is NOT a microformat and has not been used for a given root element
				if(classes.root.length === 0 && classes.properties.length > 0) {

					x = 0;
					i = classes.properties.length;
					while(x < i) {

						value = context.getValue(child, classes.properties[x][0], out);
						propertyName = context.removePropPrefix(classes.properties[x][0]);
						propertyVersion = classes.properties[x][1];

						// modifies value with "implied value rule"
						if(parentClasses && parentClasses.root.length === 1 && parentClasses.properties.length === 1){
							if(context.impliedValueRule){
								out = context.impliedValueRule(out, parentClasses.properties[0][0], classes.properties[x][0], value);
							}
						}

						// if we have not added this value into a property with the same name already
						if(!context.hasRootID(child, rootID, propertyName)) {
							// check the root and property is the same version or if overlapping versions are allowed
							if( context.isAllowedPropertyVersion( out.typeVersion, propertyVersion ) ){
								// add the property as an array of properties
								if(out.properties[propertyName]) {
									out.properties[propertyName].push(value);
								} else {
									out.properties[propertyName] = [value];
								}
								// add rootid to node so we can track its use
								context.appendRootID(child, rootID, propertyName);
							}
						}

						x++;
					}

					context.walkChildren(child, out, ufName, rootID, classes);
				}

				// if the node has no microformat classes, see if its children have
				if(classes.root.length === 0 && classes.properties.length === 0) {
					context.walkChildren(child, out, ufName, rootID, classes);
				}

				// if the node is a child root add it to the children tree
				if(classes.root.length > 0 && classes.properties.length === 0) {

					// create object with type, property and value
					rootItem = context.createUfObject(
						classes.root,
						classes.typeVersion,
						modules.text.parse(this.document, child, context.options.textFormat)
					);

					// add the microformat as an array of properties
					if(!out.children){
						out.children =  [];
					}

					if(!context.hasRootID(child, rootID, 'child-root')) {
						out.children.push( rootItem );
						context.appendRootID(child, rootID, 'child-root');
						context.rootID++;
					}

					x = 0;
					i = rootItem.type.length;
					itemRootID = context.rootID;
					while(x < i) {
						context.walkChildren(child, rootItem, rootItem.type, itemRootID, classes);
						x++;
					}
					if(this.impliedRules){
						context.impliedRules(child, rootItem, classes);
					}
					context.cleanUfObject( rootItem );

				}



				y++;
			}

		}
9960
public void serializeMerge(QueryMetadata metadata, RelationalPath<?> entity,
            List<Path<?>> keys, List<Path<?>> columns, List<Expression<?>> values,
            SubQueryExpression<?> subQuery, SQLSerializer context) {
        context.serializeForMerge(metadata, entity, keys, columns, values, subQuery);

        if (!metadata.getFlags().isEmpty()) {
            context.serialize(Position.END, metadata.getFlags());
        }
    }
1108439
function addEntities(schema, entityTypes, propFilter) {
      var contents, entityType, i, j, labelColumn, len, len1, linksSection, ref, reverseJoins, rjTable, rjs, table, tableId; // Keep list of reverse join columns (one to many) to add later. table and column

      reverseJoins = []; // For each entity type, finding reverse joins

      for (i = 0, len = entityTypes.length; i < len; i++) {
        entityType = entityTypes[i];

        _traverseTree(entityType.properties, function (prop) {
          var entityCode, refTable;

          if (propFilter && !propFilter(prop)) {
            return null;
          }

          if (prop.type === "id") {
            if (prop.idTable.match(/^entities\./)) {
              entityCode = prop.idTable.split(".")[1]; // Check that exists

              if (!_.findWhere(entityTypes, {
                code: entityCode
              })) {
                return;
              }

              reverseJoins.push({
                table: prop.idTable,
                column: {
                  id: "!entities.".concat(entityType.code, ".").concat(prop.id),
                  name: pluralize(entityType.name),
                  deprecated: prop.deprecated || entityType.deprecated,
                  type: "join",
                  join: {
                    type: "1-n",
                    toTable: "entities.".concat(entityType.code),
                    inverse: prop.id,
                    fromColumn: "_id",
                    toColumn: prop.id
                  }
                }
              });
            }

            if (prop.idTable === "admin_regions" || prop.idTable.match(/^regions\./)) {
              // Check that table exists
              refTable = schema.getTable(prop.idTable);

              if (!refTable || !refTable.ancestryTable) {
                return;
              } // Create reverse join that takes into account that regions are hierarchical


              return reverseJoins.push({
                table: prop.idTable,
                column: {
                  id: "!entities.".concat(entityType.code, ".").concat(prop.id),
                  name: entityType.name,
                  deprecated: prop.deprecated || entityType.deprecated,
                  type: "join",
                  join: {
                    type: "1-n",
                    toTable: "entities.".concat(entityType.code),
                    inverse: prop.id,
                    jsonql: {
                      type: "op",
                      op: "exists",
                      exprs: [{
                        type: "scalar",
                        expr: null,
                        from: {
                          type: "table",
                          table: refTable.ancestryTable,
                          alias: "subwithin"
                        },
                        where: {
                          type: "op",
                          op: "and",
                          exprs: [{
                            type: "op",
                            op: "=",
                            exprs: [{
                              type: "field",
                              tableAlias: "subwithin",
                              column: "ancestor"
                            }, {
                              type: "field",
                              tableAlias: "{from}",
                              column: refTable.primaryKey
                            }]
                          }, {
                            type: "op",
                            op: "=",
                            exprs: [{
                              type: "field",
                              tableAlias: "subwithin",
                              column: "descendant"
                            }, {
                              type: "field",
                              tableAlias: "{to}",
                              column: prop.id
                            }]
                          }]
                        }
                      }]
                    }
                  }
                }
              });
            }
          }
        });
      } // For each entity type


      for (j = 0, len1 = entityTypes.length; j < len1; j++) {
        entityType = entityTypes[j]; // Get label column

        labelColumn = null; // Add properties

        contents = _mapTree(entityType.properties || [], function (prop) {
          var ref;

          if (propFilter && !propFilter(prop)) {
            return null;
          } // Sections are untouched unless filtered


          if (prop.type === "section") {
            return prop;
          } // Use unique code as label


          if (prop.uniqueCode) {
            labelColumn = prop.id;
          }

          prop = _.pick(prop, "id", "name", "code", "desc", "type", "idTable", "enumValues", "deprecated"); // Don't include roles

          delete prop.roles; // Convert id to join

          if (prop.type === "id") {
            prop.type = "join";
            prop.join = {
              type: "n-1",
              toTable: prop.idTable,
              fromColumn: prop.id,
              toColumn: ((ref = schema.getTable(prop.idTable)) != null ? ref.primaryKey : void 0) || "_id"
            };
            delete prop.idTable;
          } // Pad date fields


          if (prop.type === "date") {
            // rpad(field ,10, '-01-01')
            prop.jsonql = {
              type: "op",
              op: "rpad",
              exprs: [{
                type: "field",
                tableAlias: "{alias}",
                column: prop.id
              }, 10, '-01-01']
            };
          }

          return prop;
        }); // Add extra columns

        contents.push({
          id: "_managed_by",
          name: {
            en: "Managed By"
          },
          desc: {
            en: "User or group that manages the data for this ".concat(formUtils.localizeString(entityType.name))
          },
          type: "join",
          join: {
            type: "n-1",
            toTable: "subjects",
            fromColumn: "_managed_by",
            toColumn: "id"
          }
        });
        contents.push({
          id: "_created_by",
          name: {
            en: "Added by user"
          },
          desc: {
            en: "User that added this ".concat(formUtils.localizeString(entityType.name), " to the database")
          },
          type: "join",
          join: {
            type: "n-1",
            toTable: "users",
            fromColumn: "_created_by",
            toColumn: "_id"
          }
        });
        contents.push({
          id: "_created_on",
          name: {
            en: "Date added"
          },
          desc: {
            en: "Date that this ".concat(formUtils.localizeString(entityType.name), " was added to the database")
          },
          type: "datetime"
        });
        contents.push({
          id: "_modified_by",
          name: {
            en: "Last modified by user"
          },
          desc: {
            en: "User that modified this ".concat(formUtils.localizeString(entityType.name), " last")
          },
          type: "join",
          join: {
            type: "n-1",
            toTable: "users",
            fromColumn: "_modified_by",
            toColumn: "_id"
          }
        });
        contents.push({
          id: "_modified_on",
          name: {
            en: "Date last modified"
          },
          desc: {
            en: "Date that this ".concat(formUtils.localizeString(entityType.name), " was last modified")
          },
          type: "datetime"
        });
        contents.push({
          id: "_merged_entities",
          name: {
            en: "Previous mWater IDs"
          },
          desc: {
            en: "IDs of other ".concat(formUtils.localizeString(entityType.name), " that were merged into this")
          },
          type: 'text[]'
        }); // This gets overridden in the schema map

        contents.push({
          id: "_pending_verifications",
          name: {
            en: "Pending Verifications"
          },
          desc: {
            en: "True if there are verifications pending for this site that have not been verified"
          },
          type: 'boolean'
        }); // Add datasets

        contents.push({
          id: "!datasets",
          name: "Datasets",
          desc: {
            en: "Datasets that this ".concat(formUtils.localizeString(entityType.name), " is a part of")
          },
          type: "join",
          join: {
            type: "n-n",
            toTable: "datasets",
            jsonql: {
              type: "op",
              op: "exists",
              exprs: [{
                type: "query",
                selects: [{
                  type: "select",
                  expr: null,
                  alias: "null_value"
                }],
                from: {
                  type: "table",
                  table: "dataset_members",
                  alias: "members"
                },
                where: {
                  type: "op",
                  op: "and",
                  exprs: [{
                    type: "op",
                    op: "=",
                    exprs: [{
                      type: "field",
                      tableAlias: "members",
                      column: "entity_type"
                    }, entityType.code]
                  }, {
                    type: "op",
                    op: "=",
                    exprs: [{
                      type: "field",
                      tableAlias: "members",
                      column: "entity_id"
                    }, {
                      type: "field",
                      tableAlias: "{from}",
                      column: "_id"
                    }]
                  }, {
                    type: "op",
                    op: "=",
                    exprs: [{
                      type: "field",
                      tableAlias: "members",
                      column: "dataset"
                    }, {
                      type: "field",
                      tableAlias: "{to}",
                      column: "_id"
                    }]
                  }]
                }
              }]
            }
          }
        }); // Add related forms placeholder section

        contents.push({
          type: "section",
          id: "!related_forms",
          name: {
            en: "Related Surveys"
          },
          desc: {
            en: "Surveys that are linked by a question to ".concat(formUtils.localizeString(entityType.name))
          },
          contents: []
        }); // Add related indicators placeholder section

        contents.push({
          type: "section",
          id: "!indicators",
          // Special section name
          name: {
            en: "Related Indicators"
          },
          desc: {
            en: "Indicators are standardized information that are related to this site"
          },
          contents: []
        });
        tableId = "entities.".concat(entityType.code);
        table = {
          id: tableId,
          name: entityType.name,
          desc: entityType.desc,
          primaryKey: "_id",
          label: labelColumn,
          contents: contents,
          deprecated: entityType.deprecated
        }; // Legacy only

        if (entityType.code === "water_point_functionality_report") {
          table.ordering = "date";
        } // Create table


        schema = schema.addTable(table);
      }

      ref = _.groupBy(reverseJoins, "table"); // Add reverse joins, putting them in "!related_entities" section

      for (rjTable in ref) {
        rjs = ref[rjTable];
        table = schema.getTable(rjTable);
        table.contents = table.contents.slice();
        linksSection = _.findWhere(table.contents, {
          id: "!related_entities",
          type: "section"
        });

        if (!linksSection) {
          linksSection = {
            id: "!related_entities",
            type: "section",
            name: {
              _base: "en",
              en: "Related Entities"
            },
            contents: []
          };
          table.contents.push(linksSection);
        }

        linksSection.contents = linksSection.contents.concat(_.pluck(rjs, "column"));
        schema = schema.addTable(table);
      }

      return schema;
    }
216246
public Object recursivelyFindEntities(Object entity, Map<String, Object> relationsMap, EntityMetadata m,
            PersistenceDelegator pd, boolean lazilyLoaded, Map<Object, Object> relationStack)
    {
        return handleAssociation(entity, relationsMap, m, pd, lazilyLoaded, relationStack);

    }
1064826
function parseUnits(response) {
  let entities = {};
  Object.keys(response).forEach(key => {
    entities[key] = parseUnit(response[key]);
  });
  return entities;
}
1339349
function splitCascadingData(uri, data) {
  let ops, list;

  // search for _ref with _size greater than 1
  list = references.listDeepObjects(data, isReferencedAndReal);
  ops = _.map(list.reverse(), function (obj) {
    const ref = obj[referenceProperty],
      // since children are before parents, no one will see data below them
      op = {key: ref, value: _.omit(obj, referenceProperty)};

    // omit cloned 1 level deep and we clear what omit cloned from obj
    // so the op gets the first level of data, but it's removed from the main obj
    clearOwnProperties(obj);
    obj[referenceProperty] = ref;

    return op;
  });

  // add the cleaned root object at the end
  ops.push({key: uri, value: data});

  return ops;
}
642703
private void populateCollectionFromJoinTable(Object entity, EntityMetadata entityMetadata,
            PersistenceDelegator delegator, Relation relation)
    {
        JoinTableMetadata jtMetadata = relation.getJoinTableMetadata();
        Client pClient = delegator.getClient(entityMetadata);

        String schema = entityMetadata.getSchema();

        EntityMetadata owningEntityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                relation.getTargetEntity());
        Class columnJavaType = owningEntityMetadata.getIdAttribute().getJavaType();
        if (jtMetadata == null)
        {
            columnJavaType = entityMetadata.getIdAttribute().getJavaType();
            Relation owningEntityMetadataRelation = owningEntityMetadata.getRelation(relation.getMappedBy());
            jtMetadata = owningEntityMetadataRelation.getJoinTableMetadata();
            pClient = delegator.getClient(owningEntityMetadata);
            schema = owningEntityMetadata.getSchema();
        }

        String joinTableName = jtMetadata.getJoinTableName();

        Set<String> joinColumns = jtMetadata.getJoinColumns();
        Set<String> inverseJoinColumns = jtMetadata.getInverseJoinColumns();

        String joinColumnName = (String) joinColumns.toArray()[0];
        String inverseJoinColumnName = (String) inverseJoinColumns.toArray()[0];

        Object entityId = PropertyAccessorHelper.getId(entity, entityMetadata);
        List<?> foreignKeys = pClient.getColumnsById(schema, joinTableName, joinColumnName, inverseJoinColumnName,
                entityId, columnJavaType);

        List childrenEntities = new ArrayList();

        if (foreignKeys != null)
        {
            for (Object foreignKey : foreignKeys)
            {
                EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                        relation.getTargetEntity());

                Object child = delegator.find(relation.getTargetEntity(), foreignKey);
                Object obj = child instanceof EnhanceEntity && child != null ? ((EnhanceEntity) child).getEntity()
                        : child;

                // If child has any bidirectional relationship, process them
                // here
                Field biDirectionalField = relation.getBiDirectionalField();
                boolean isBidirectionalRelation = (biDirectionalField != null);

                if (isBidirectionalRelation && obj != null)
                {
                    Object columnValue = PropertyAccessorHelper.getId(obj, childMetadata);
                    Object[] pKeys = pClient.findIdsByColumn(entityMetadata.getSchema(), joinTableName, joinColumnName,
                            inverseJoinColumnName, columnValue, entityMetadata.getEntityClazz());
                    List parents = delegator.find(entity.getClass(), pKeys);
                    PropertyAccessorHelper.set(obj, biDirectionalField,
                            ObjectUtils.getFieldInstance(parents, biDirectionalField));
                    PersistenceCacheManager.addEntityToPersistenceCache(obj, delegator, columnValue);
                }

                childrenEntities.add(obj);
            }
        }
        Field childField = relation.getProperty();

        try
        {
            PropertyAccessorHelper.set(
                    entity,
                    childField,
                    PropertyAccessorHelper.isCollection(childField.getType()) ? ObjectUtils.getFieldInstance(
                            childrenEntities, childField) : childrenEntities.get(0));
            PersistenceCacheManager.addEntityToPersistenceCache(entity, delegator, entityId);
        }
        catch (PropertyAccessException ex)
        {
            throw new EntityReaderException(ex);
        }
    }