Copy children of $new to $old except where a preserved element or its ancestor must be respected; flow the new elements around those, after invoking recursively where appropriate
347572
function restore($old, $new) {
        // We append the next element after this point. If $after is not yet set, we prepend to $new
        // and then set $after to the node just prepended.
        var $after;
        $new.contents().each(function() {
          var $node = $(this);
          var handled = false;
          var $nodeOld;
          if (is($node, 'preserve')) {
            $nodeOld = findVal($old, 'preserve', attr($node, 'preserve'));
            $after = $nodeOld;
            handled = true;
          } else if (is($node, 'preserves')) {
            $nodeOld = findVal($old, 'preserves', attr($node, 'preserves'));
            if ($nodeOld.length) {
              restore($nodeOld, $node);
              $after = $nodeOld;
              handled = true;
            }
          }
          if (!handled) {
            if ($after) {
              $after.after($node);
            } else {
              $old.prepend($node);
            }
            $after = $node;
          }
        });
      }
1072631
private static List<WComponent> copyChildren(final List<WComponent> children) {
		ArrayList<WComponent> copy;

		if (children == null) {
			copy = new ArrayList<>(1);
		} else {
			copy = new ArrayList<>(children);
		}

		return copy;
	}
343033
private static void expandAllRecursively(JTree tree, TreePath treePath)
    {
        TreeModel model = tree.getModel();
        Object lastPathComponent = treePath.getLastPathComponent();
        int childCount = model.getChildCount(lastPathComponent);
        if (childCount == 0)
        {
            return;
        }
        tree.expandPath(treePath);
        for (int i=0; i<childCount; i++)
        {
            Object child = model.getChild(lastPathComponent, i);
            int grandChildCount = model.getChildCount(child);
            if (grandChildCount > 0)
            {
                class LocalTreePath extends TreePath
                {
                    private static final long serialVersionUID = 0;
                    public LocalTreePath(
                        TreePath parent, Object lastPathComponent)
                    {
                        super(parent, lastPathComponent);
                    }
                }
                TreePath nextTreePath = new LocalTreePath(treePath, child);
                expandAllRecursively(tree, nextTreePath);
            }
        }
    }
477885
function( index ) {
			var cloneChildren = this.children.splice( index, this.children.length - index ),
				clone = this.clone();

			for ( var i = 0; i < cloneChildren.length; ++i )
				cloneChildren[ i ].parent = clone;

			clone.children = cloneChildren;

			if ( cloneChildren[ 0 ] )
				cloneChildren[ 0 ].previous = null;

			if ( index > 0 )
				this.children[ index - 1 ].next = null;

			this.parent.add( clone, this.getIndex() + 1 );

			return clone;
		}
16108
function removeNotNeededNodes(parentElements, newChildren, oldChildren) {
  let remaining = parentElements.childNodes.length;
  if (oldChildren.length !== remaining) {
    console.warn(
      "ZLIQ: Something other then ZLIQ has manipulated the children of the element",
      parentElements,
      ". This can lead to sideffects. Consider using the 'isolated' attribute for this element to prevent updates."
    );
  }

  for (; remaining > newChildren.length; remaining--) {
    let childToRemove = parentElements.childNodes[remaining - 1];
    parentElements.removeChild(childToRemove);

    if (oldChildren.length < remaining) {
      continue;
    } else {
      let { cycle } = oldChildren[remaining - 1];

      triggerLifecycle(childToRemove, { cycle }, "removed");
    }
  }
}
408012
def new_children(self, **kwargs):
        """"""
        for k, v in kwargs.items():
            self.new_child(k, v)

        return self
605314
def rec_new(self, val):
        
        if val not in self.things:
            for child in val.children():
                self.rec_new(child)
            self.new(val)
        return val
651921
def replace_nodes(root, old, new):

    '''
     
    '''

    rep = Replacer(old, new)
    rep.visit(root)
    return
771886
function copyOwn(source, target, inherits, publicStatic, allowInit, isNOTExtendingNative) {
    for (var
      key,
      noFunctionCheck = typeof source !== 'function',
      names = oK(source),
      i = 0; i < names.length; i++
    ) {
      key = names[i];
      if (
        (noFunctionCheck || indexOf.call(nativeFunctionOPN, key) < 0) &&
        isNotASpecialKey(key, allowInit)
      ) {
        if (hOP.call(target, key)) {
          warn('duplicated: ' + key.toString());
        }
        setProperty(inherits, target, key, gOPD(source, key), publicStatic, isNOTExtendingNative);
      }
    }
  }
1358835
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy):
    
    get_tree = plpy.prepare('''
    WITH RECURSIVE t(node, parent, document, title, childorder, latest, path)
        AS (SELECT tr.nodeid, tr.parent_id, tr.documentid, tr.title,
                   tr.childorder, tr.latest, ARRAY[tr.nodeid]
            FROM trees tr
            WHERE tr.documentid = $1 AND tr.is_collated = 'False'
    UNION ALL
        SELECT c.nodeid, c.parent_id, c.documentid, c.title,
               c.childorder, c.latest, path || ARRAY[c.nodeid]
        FROM trees c JOIN t ON (c.parent_id = t.node)
        WHERE not c.nodeid = ANY(t.path)
    )
    SELECT * FROM t
    ''', ('integer',))

    def get_old_tree():
        return plpy.execute(get_tree, (old_collection_ident,))

    tree = {}  # { old_nodeid: {'data': ...}, ...}
    children = {}  # { nodeid: [child_nodeid, ...], child_nodeid: [...]}
    for i in get_old_tree():
        tree[i['node']] = {'data': i, 'new_nodeid': None}
        children.setdefault(i['parent'], [])
        children[i['parent']].append(i['node'])

    insert_tree = plpy.prepare('''
    INSERT INTO trees (nodeid, parent_id, documentid,
        title, childorder, latest)
    VALUES (DEFAULT, $1, $2, $3, $4, $5)
    RETURNING nodeid
    ''', ('integer', 'integer', 'text', 'integer', 'boolean'))

    def execute(fields):
        results = plpy.execute(insert_tree, fields, 1)
        return results[0]['nodeid']

    root_node = children[None][0]

    def build_tree(node, parent):
        data = tree[node]['data']
        new_node = execute([parent, new_document_id_map.get(data['document'],
                            data['document']), data['title'],
                            data['childorder'], data['latest']])
        for i in children.get(node, []):
            build_tree(i, new_node)
    build_tree(root_node, None)
113107
function reindexNodes () {
  var child = this.node.firstChild;
  this._length = 0;
  
  while (child) {
    this[this._length++] = child;
    child = child.nextSibling;
  }
}
1294610
private static void replaceOrAppend(Element oldElement, Element newElement) {
    assert oldElement != null && newElement != null;

    if (matchesTags(oldElement, appendingTags)) {
      GQuery.$(oldElement).html("").append(newElement);
    } else {
      GQuery.$(oldElement).replaceWith(newElement);

      // copy class
      String c = oldElement.getClassName();
      if (!c.isEmpty()) {
        newElement.addClassName(c);
      }
      // copy id
      newElement.setId(oldElement.getId());
      // ensure no duplicate id
      oldElement.setId("");
    }
  }
255679
def borrow_from_previous_sibling(prev_node)
      if prev_node.keys.length - 1 > min_keys
        index = @parent.search_node_index(self) - 1

        if is_leaf?
          # Move the last key of the previous node to the front of this node
          @keys.unshift(prev_node.keys.pop)
          # Register the new lead key of this node with its parent
          @parent.keys[index] = @keys.first
          # Move the last value of the previous node to the front of this node
          @values.unshift(prev_node.values.pop)
        else
          # For branch nodes the branch key will be the borrowed key.
          @keys.unshift(@parent.keys[index])
          # And the last key of the previous key will become the new branch
          # key for this node.
          @parent.keys[index] = prev_node.keys.pop
          # Move the last child of the previous node to the front of this node
          @children.unshift(node = prev_node.children.pop)
          node.parent = myself
        end

        return true
      end

      false
    end
529294
function (nodeList, newNodes) {
			// Unregister all childNodeLists.
			var oldNodes = nodeLists.unregisterChildren(nodeList);

			newNodes = makeArray(newNodes);

			var oldListLength = nodeList.length;

			// Replace oldNodeLists's contents.
			splice.apply(nodeList, [
				0,
				oldListLength
			].concat(newNodes));

			// Replacements are nodes that have replaced the original element this is on.
			// We can't simply insert elements because stache does children before parents.
			if(nodeList.replacements){
				nodeLists.nestReplacements(nodeList);
				nodeList.deepChildren = nodeList.newDeepChildren;
				nodeList.newDeepChildren = [];
			} else {
				nodeLists.nestList(nodeList);
			}

			return oldNodes;
		}
115206
def copychildren(self, newdoc=None, idsuffix=""):
        
        if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children
        for c in self:
            if isinstance(c, AbstractElement):
                yield c.copy(newdoc,idsuffix)
305231
function () {

            // This check looks a little strange, but it suits what we're trying
            // to do: as we're walking through the children, a child node that has moved
            // from one parent to another will be found but would look like some kind
            // of insert. The check that we're doing here is looking up the current
            // child's ID in the *old* map and seeing if this child used to have a
            // different parent.
            var possiblyMovedElement = oldNodeMap[newChild.tagID];
            if (possiblyMovedElement &&
                    newParent.tagID !== getParentID(possiblyMovedElement)) {
                newEdit = {
                    type: "elementMove",
                    tagID: newChild.tagID,
                    parentID: newChild.parent.tagID
                };
                moves.push(newEdit.tagID);
                newEdits.push(newEdit);

                // this element in the new tree was a move to this spot, so we can move
                // on to the next child in the new tree.
                newIndex++;
                return true;
            }
            return false;
        }
122772
def copy(self, parent=None):
        """"""
        new = Structure(None, parent=parent)
        new.key = self.key
        new.type_ = self.type_
        new.val_guaranteed = self.val_guaranteed
        new.key_guaranteed = self.key_guaranteed
        for child in self.children:
            new.children.append(child.copy(new))
        return new