add unvisited node fragments to plan
352197
private static List<Fragment> fragmentsForUnvisitedNodes(Map<NodeId, Node> allNodes, Collection<Node> connectedNodes) {
        List<Fragment> subplan = new LinkedList<>();

        Set<Node> nodeWithFragment = connectedNodes.stream()
                // make sure the fragment either has no dependency or dependencies have been dealt with
                .filter(node -> !node.getFragmentsWithoutDependency().isEmpty() ||
                        !node.getFragmentsWithDependencyVisited().isEmpty())
                .collect(Collectors.toSet());
        while (!nodeWithFragment.isEmpty()) {
            nodeWithFragment.forEach(node -> subplan.addAll(nodeToPlanFragments(node, allNodes, false)));
            nodeWithFragment = connectedNodes.stream()
                    .filter(node -> !node.getFragmentsWithoutDependency().isEmpty() ||
                            !node.getFragmentsWithDependencyVisited().isEmpty())
                    .collect(Collectors.toSet());
        }

        return subplan;
    }
342406
function updateBreadcrumb() {
        breadcrumbs.html("");
        var buffer = [];
        for (var i = 0; i < path.length; i++) {
            var node = path[i];
            if (node.type == FOLDER_TYPE) {
                var divider = "<span class='divider'>/</span>"
                if (i == path.length - 1) { //chk for last item
                    divider = "";
                }
                buffer.push("<li><a href='javascript:;' id='" + node.resourceId + "'>" + node.name + " </a> " + divider + "</li>");
            } else {
                buffer.push("<span  id='" + node.resourceId + "'>" + node.name + " </span>");
                // breadcrumbs.append("<li><span  id='"+ node.resourceId+"'>" + node.name + " </span></li>");
            }
        }

        breadcrumbs.append(buffer.join(""));

        breadcrumbs.find('a').click(function (e) {
            var id = e.currentTarget.id;
            try {
                id = parseInt(id);
            }
            catch (e) {
            }
            renderItemsByFolderId(id);
            while (true) {
                var cur = getCurrentItem();
                if (id == cur.resourceId) {
                    break;
                }
                path.pop();
            }
            updateBreadcrumb();
        });

        //handle disabling of Up node in tree when folderId is zero
        if (folderId === 0) {
            var upNode = resourceTree.find('ul li:first-child');
            if (path.length > 1) {
                upNode.removeClass('disabled');
                upNode.find('i').addClass('icon-arrow-up');
            }
            else {
                upNode.addClass('disabled');
                upNode.find('i').addClass('icon-home');
            }
        }
    }
681116
async def _addNodeFnibOps(self, fnib, editatom, props=None):
        '''
        
        '''
        form, norm, info, buid = fnib

        if form.isrunt:
            raise s_exc.IsRuntForm(mesg='Cannot make runt nodes.',
                                   form=form.full, prop=norm)

        if props is None:
            props = {}
        # Check if this buid is already under construction
        node = editatom.getNodeBeingMade(buid)
        if node is not None:
            return node

        # Check if this buid is already fully made
        node = await self.getNodeByBuid(buid)
        if node is not None:
            return node

        # Another editatom might have created in another task during the above call, so check again
        node = editatom.getNodeBeingMade(buid)
        if node is not None:
            return node

        if props is None:
            props = {}

        # lets build a node...
        node = s_node.Node(self, None)

        node.buid = buid
        node.form = form
        node.ndef = (form.name, norm)

        sops = form.getSetOps(buid, norm)
        editatom.sops.extend(sops)

        editatom.addNode(node)

        # update props with any subs from form value
        subs = info.get('subs')
        if subs is not None:
            for name, valu in subs.items():
                if form.prop(name) is not None:
                    props[name] = valu

        # update props with any defvals we are missing
        for name, valu in form.defvals.items():
            props.setdefault(name, valu)

        # set all the properties with init=True
        for name, valu in props.items():
            await node._setops(name, valu, editatom, init=True)

        # set our global properties
        tick = s_common.now()
        await node._setops('.created', tick, editatom, init=True)

        return None
540799
private void connectCTENodesIfAny(SeqScanPlanNode node) {
        if (! node.isCommonTableScan()) {
            return;
        }
        Integer CTEBaseNodeId = node.getCTEBaseNodeId();
        assert(CTEBaseNodeId != null);
        AbstractPlanNode CTEBaseNode = m_planNodesListMap.get(CTEBaseNodeId).get(0);
        assert(CTEBaseNode instanceof CommonTablePlanNode);
        node.setCTEBaseNode(CTEBaseNode);

        CommonTablePlanNode cteNode = (CommonTablePlanNode)CTEBaseNode;
        Integer CTERecursiveNodeId = cteNode.getRecursiveNodeId();
        if (CTERecursiveNodeId != null) {
            cteNode.setRecursiveNode(m_planNodesListMap.get(CTERecursiveNodeId).get(0));
        }
    }
920479
protected void prunePlanAlternatives(List<PlanNode> plans) {
		if (plans.isEmpty()) {
			throw new CompilerException("No plan meeting the requirements could be created @ " + this + ". Most likely reason: Too restrictive plan hints.");
		}
		// shortcut for the simple case
		if (plans.size() == 1) {
			return;
		}
		
		// we can only compare plan candidates that made equal choices
		// at the branching points. for each choice at a branching point,
		// we need to keep the cheapest (wrt. interesting properties).
		// if we do not keep candidates for each branch choice, we might not
		// find branch compatible candidates when joining the branches back.
		
		// for pruning, we are quasi AFTER the node, so in the presence of
		// branches, we need form the per-branch-choice groups by the choice
		// they made at the latest un-joined branching node. Note that this is
		// different from the check for branch compatibility of candidates, as
		// this happens on the input sub-plans and hence BEFORE the node (therefore
		// it is relevant to find the latest (partially) joined branch point.
		
		if (this.openBranches == null || this.openBranches.isEmpty()) {
			prunePlanAlternativesWithCommonBranching(plans);
		} else {
			// partition the candidates into groups that made the same sub-plan candidate
			// choice at the latest unclosed branch point
			
			final OptimizerNode[] branchDeterminers = new OptimizerNode[this.openBranches.size()];
			
			for (int i = 0; i < branchDeterminers.length; i++) {
				branchDeterminers[i] = this.openBranches.get(this.openBranches.size() - 1 - i).getBranchingNode();
			}
			
			// this sorter sorts by the candidate choice at the branch point
			Comparator<PlanNode> sorter = new Comparator<PlanNode>() {
				
				@Override
				public int compare(PlanNode o1, PlanNode o2) {
					for (OptimizerNode branchDeterminer : branchDeterminers) {
						PlanNode n1 = o1.getCandidateAtBranchPoint(branchDeterminer);
						PlanNode n2 = o2.getCandidateAtBranchPoint(branchDeterminer);
						int hash1 = System.identityHashCode(n1);
						int hash2 = System.identityHashCode(n2);

						if (hash1 != hash2) {
							return hash1 - hash2;
						}
					}
					return 0;
				}
			};
			Collections.sort(plans, sorter);
			
			List<PlanNode> result = new ArrayList<PlanNode>();
			List<PlanNode> turn = new ArrayList<PlanNode>();
			
			final PlanNode[] determinerChoice = new PlanNode[branchDeterminers.length];

			while (!plans.isEmpty()) {
				// take one as the determiner
				turn.clear();
				PlanNode determiner = plans.remove(plans.size() - 1);
				turn.add(determiner);
				
				for (int i = 0; i < determinerChoice.length; i++) {
					determinerChoice[i] = determiner.getCandidateAtBranchPoint(branchDeterminers[i]);
				}

				// go backwards through the plans and find all that are equal
				boolean stillEqual = true;
				for (int k = plans.size() - 1; k >= 0 && stillEqual; k--) {
					PlanNode toCheck = plans.get(k);
					
					for (int i = 0; i < branchDeterminers.length; i++) {
						PlanNode checkerChoice = toCheck.getCandidateAtBranchPoint(branchDeterminers[i]);
					
						if (checkerChoice != determinerChoice[i]) {
							// not the same anymore
							stillEqual = false;
							break;
						}
					}
					
					if (stillEqual) {
						// the same
						plans.remove(k);
						turn.add(toCheck);
					}
				}

				// now that we have only plans with the same branch alternatives, prune!
				if (turn.size() > 1) {
					prunePlanAlternativesWithCommonBranching(turn);
				}
				result.addAll(turn);
			}

			// after all turns are complete
			plans.clear();
			plans.addAll(result);
		}
	}
1360054
def addinnode(self, otherplus, node, objectname):
        
        # do a test for unique object here
        newelement = otherplus.dt[node.upper()]
107854
def add_nodes(self, new_nodes):
        """"""
        for unique_id, node in new_nodes.items():
            if unique_id in self.nodes:
                raise_duplicate_resource_name(node, self.nodes[unique_id])
            self.nodes[unique_id] = node
1372333
private void setupForNewPlans(AbstractParsedStmt parsedStmt) {
        m_bestAndOnlyPlanWasGenerated = false;
        m_partitioning.analyzeTablePartitioning(parsedStmt.allScans());

        if (parsedStmt instanceof ParsedUnionStmt) {
            m_parsedUnion = (ParsedUnionStmt) parsedStmt;
            return;
        }

        if (parsedStmt instanceof ParsedSelectStmt) {
            if (tableListIncludesExportOnly(parsedStmt.m_tableList)) {
                throw new PlanningErrorException(
                        "Illegal to read a stream.");
            }

            m_parsedSelect = (ParsedSelectStmt) parsedStmt;
            // Simplify the outer join if possible
            if (m_parsedSelect.m_joinTree instanceof BranchNode) {
                if (! m_parsedSelect.hasJoinOrder()) {
                    simplifyOuterJoin((BranchNode)m_parsedSelect.m_joinTree);
                }

                // Convert RIGHT joins to the LEFT ones
                ((BranchNode)m_parsedSelect.m_joinTree).toLeftJoin();
            }
            m_subAssembler = new SelectSubPlanAssembler(m_catalogDb, m_parsedSelect, m_partitioning);

            // Process the GROUP BY information, decide whether it is group by the partition column
            if (isPartitionColumnInGroupbyList(m_parsedSelect.groupByColumns())) {
                m_parsedSelect.setHasPartitionColumnInGroupby();
            }
            if (isPartitionColumnInWindowedAggregatePartitionByList()) {
                m_parsedSelect.setHasPartitionColumnInWindowedAggregate();
            }

            // FIXME: is the following scheme/comment obsolete?
            // FIXME: turn it on when we are able to push down DISTINCT
//            if (isPartitionColumnInGroupbyList(m_parsedSelect.m_distinctGroupByColumns)) {
//                m_parsedSelect.setHasPartitionColumnInDistinctGroupby();
//            }

            return;
        }

        // @TODO
        // Need to use StmtTableScan instead
        // check that no modification happens to views
        if (tableListIncludesReadOnlyView(parsedStmt.m_tableList)) {
            throw new PlanningErrorException("Illegal to modify a materialized view.");
        }

        m_partitioning.setIsDML();

        // Don't parse a stream and a table.  Note that
        // for swap statements we return here.
        if (parsedStmt instanceof ParsedSwapStmt) {
            assert (parsedStmt.m_tableList.size() == 2);
            if (tableListIncludesExportOnly(parsedStmt.m_tableList)) {
                throw new PlanningErrorException("Illegal to swap a stream.");
            }
            m_parsedSwap = (ParsedSwapStmt) parsedStmt;
            return;
        }

        // Check that only multi-partition writes are made to replicated tables.
        // figure out which table we're updating/deleting
        Table targetTable = parsedStmt.m_tableList.get(0);
        if (targetTable.getIsreplicated()) {
            if (m_partitioning.wasSpecifiedAsSingle()
                    && !m_partitioning.isReplicatedDmlToRunOnAllPartitions()) {
                String msg = "Trying to write to replicated table '" + targetTable.getTypeName()
                        + "' in a single-partition procedure.";
                throw new PlanningErrorException(msg);
            }
        }
        else if (m_partitioning.wasSpecifiedAsSingle() == false) {
            m_partitioning.setPartitioningColumnForDML(targetTable.getPartitioncolumn());
        }

        if (parsedStmt instanceof ParsedInsertStmt) {
            m_parsedInsert = (ParsedInsertStmt) parsedStmt;
            // The currently handled inserts are too simple to even require a subplan assembler. So, done.
            return;
        } else if (parsedStmt instanceof ParsedUpdateStmt) {
            if (tableListIncludesExportOnly(parsedStmt.m_tableList)) {
                throw new PlanningErrorException("Illegal to update a stream.");
            }
            m_parsedUpdate = (ParsedUpdateStmt) parsedStmt;
        } else if (parsedStmt instanceof ParsedDeleteStmt) {
            if (tableListIncludesExportOnly(parsedStmt.m_tableList)) {
                throw new PlanningErrorException("Illegal to delete from a stream.");
            }
            m_parsedDelete = (ParsedDeleteStmt) parsedStmt;
        } else if (parsedStmt instanceof ParsedMigrateStmt) {
            m_parsedMigrate = (ParsedMigrateStmt) parsedStmt;
        } else {
            throw new RuntimeException("Unknown subclass of AbstractParsedStmt.");
        }

        if ( ! m_partitioning.wasSpecifiedAsSingle()) {
            //TODO: When updates and deletes can contain joins, this step may have to be
            // deferred so that the valueEquivalence set can be analyzed per join order.
            // This appears to be an unfortunate side effect of how the HSQL interface
            // misleadingly organizes the placement of join/where filters on the statement tree.
            // This throws off the accounting of equivalence join filters until they can be
            // normalized in analyzeJoinFilters, but that normalization process happens on a
            // per-join-order basis, and so, so must this analysis.
            HashMap<AbstractExpression, Set<AbstractExpression>>
                valueEquivalence = parsedStmt.analyzeValueEquivalence();
            Collection<StmtTableScan> scans = parsedStmt.allScans();
            m_partitioning.analyzeForMultiPartitionAccess(scans, valueEquivalence);
        }
        m_subAssembler = new WriterSubPlanAssembler(m_catalogDb, parsedStmt, m_partitioning);
    }
43532
function (plan, callbackName, list) {
        if (list === void 0) { list = []; }
        for (var viewPortName in plan) {
            var viewPortPlan = plan[viewPortName];
            var prevComponent = viewPortPlan.prevComponent;
            if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace)
                && prevComponent) {
                var viewModel = prevComponent.viewModel;
                if (callbackName in viewModel) {
                    list.push(viewModel);
                }
            }
            if (viewPortPlan.strategy === activationStrategy.replace && prevComponent) {
                addPreviousDeactivatable(prevComponent, callbackName, list);
            }
            else if (viewPortPlan.childNavigationInstruction) {
                findDeactivatable(viewPortPlan.childNavigationInstruction.plan, callbackName, list);
            }
        }
        return list;
    }
1330156
private void fragmentizeLayout(UserView view, FragmentDefinition fragment) {
        // if fragment not bound to user or layout empty due to error, return
        if (view.getUserId() == -1 || view.getLayout() == null) {
            return;
        }

        // Choose what types of content to apply from the fragment
        Pattern contentPattern = STANDARD_PATTERN; // default
        boolean allowExpandedContent =
                Boolean.parseBoolean(
                        PropertiesManager.getProperty(PROPERTY_ALLOW_EXPANDED_CONTENT));
        if (allowExpandedContent) {
            contentPattern = EXPANDED_PATTERN;
        }

        // remove all non-regular or hidden top level folders
        // skip root folder that is only child of top level layout element
        Element layout = view.getLayout().getDocumentElement();
        Element root = (Element) layout.getFirstChild();
        NodeList children = root.getChildNodes();

        // process the children backwards since as we delete some the indices
        // shift around
        for (int i = children.getLength() - 1; i >= 0; i--) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("folder")) {
                Element folder = (Element) node;

                // strip out folder types 'header', 'footer' and regular,
                // hidden folder "User Preferences" since users have their own
                boolean isApplicable =
                        contentPattern.matcher(folder.getAttribute("type")).matches();
                if (!isApplicable || folder.getAttribute("hidden").equals("true")) {
                    try {
                        root.removeChild(folder);
                    } catch (Exception e) {
                        throw new RuntimeException(
                                "Anomaly occurred while stripping out "
                                        + " portions of layout for fragment '"
                                        + fragment.getName()
                                        + "'. The fragment will not be available for "
                                        + "inclusion into user layouts.",
                                e);
                    }
                }
            }
        }
        // now re-lable all remaining nodes below root to have a safe system
        // wide id.

        setIdsAndAttribs(
                layout,
                layout.getAttribute(Constants.ATT_ID),
                "" + fragment.getId(),
                "" + fragment.getPrecedence());
    }
126983
def add_nodes(self, nodes):
        '''
        '''
        new_nodes, master_map = self._add_nodes_as_master(nodes)

        for n in new_nodes:
            if n.name not in master_map:
                continue
            master_name = master_map[n.name]
            target = self.get_node(master_name)
            if not target:
                raise NodeNotFound(master_name)
            n.replicate(target.name)
            n.flush_cache()
            target.flush_cache()
1152539
function addImportToGraph(importId, parentId, graph, visited) {
  const siblingsId = parentId + '_' + 'siblings'
  const visitedId = parentId + '_' + importId

  if (visited[visitedId] !== VISITED_MARKER) {
    if (!Array.isArray(visited[siblingsId])) visited[siblingsId] = []

    const siblings = visited[siblingsId]

    if (Array.isArray(graph[importId]))
      graph[importId] = graph[importId].concat(siblings)
    else graph[importId] = siblings.slice()

    visited[visitedId] = VISITED_MARKER
    siblings.push(importId)
  }
}
454595
private void connectNodesIfNecessary(AbstractPlanNode node) {
        NodeSchema outputSchema = node.getOutputSchema();
        if (outputSchema != null) {
            for (SchemaColumn col : outputSchema) {
                connectPredicateStmt(col.getExpression());
            }
        }
        if (node instanceof AbstractScanPlanNode) {
            AbstractScanPlanNode scanNode = (AbstractScanPlanNode)node;
            connectPredicateStmt(scanNode.getPredicate());
            // If this is common table scan, we connect the scan node to the
            // plan nodes for the base and recursive query.
            if (scanNode instanceof SeqScanPlanNode) {
                SeqScanPlanNode seqScanNode = (SeqScanPlanNode)scanNode;
                connectCTENodesIfAny(seqScanNode);
            }
        } else if (node instanceof AbstractJoinPlanNode) {
            AbstractJoinPlanNode joinNode = (AbstractJoinPlanNode)node;
            connectPredicateStmt(joinNode.getPreJoinPredicate());
            connectPredicateStmt(joinNode.getJoinPredicate());
            connectPredicateStmt(joinNode.getWherePredicate());
        } else if (node instanceof AggregatePlanNode) {
            AggregatePlanNode aggNode = (AggregatePlanNode)node;
            connectPredicateStmt(aggNode.getPostPredicate());
        }

        for (AbstractPlanNode inlineNode: node.getInlinePlanNodes().values()) {
            connectNodesIfNecessary(inlineNode);
        }
    }
1334283
def prepend(self, *nodes: Union[str, AbstractNode]) -> None:
        """"""
        node = _to_node_list(nodes)
        if self.firstChild:
            self.insertBefore(node, self.firstChild)
        else:
            self.appendChild(node)
522369
function afterManip( elem, fragClone, callback ) {
		// Provides cloned fragment ready for fixup prior to and after insertion into DOM
		var content = fragClone.nodeType === 11 ?
			jQuery.makeArray(fragClone.childNodes) :
			fragClone.nodeType === 1 ? [fragClone] : [];

		// Return fragment to original caller (e.g. append) for DOM insertion
		callback.call( elem, fragClone );

		// Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
		storeTmplItems( content );
		cloneIndex++;
	}
1310987
@Override
    public void visit(NodeVisitor v) {
        if (v.visit(this)) {
            for (XmlFragment frag : fragments) {
                frag.visit(v);
            }
        }
    }
884689
@Override
    AbstractPlanNode nextPlan() {
        if (!m_generatedPlans) {
            assert (m_parsedStmt.m_joinTree != null);
            // Clone the node to make make sure that analyze expression is called
            // only once on the node.
            JoinNode tableNode = (JoinNode) m_parsedStmt.m_joinTree.clone();
            // Analyze join conditions
            tableNode.analyzeJoinExpressions(m_parsedStmt.m_noTableSelectionList);
            // these just shouldn't happen right?
            assert(m_parsedStmt.m_noTableSelectionList.size() == 0);

            m_generatedPlans = true;
            // This is either UPDATE or DELETE statement. Consolidate all expressions
            // into the WHERE list.
            tableNode.m_whereInnerList.addAll(tableNode.m_joinInnerList);
            tableNode.m_joinInnerList.clear();
            tableNode.m_accessPaths.addAll(getRelevantAccessPathsForTable(tableNode.getTableScan(),
                    null,
                    tableNode.m_whereInnerList,
                    null));

            for (AccessPath path : tableNode.m_accessPaths) {
                tableNode.m_currentAccessPath = path;

                AbstractPlanNode plan = getAccessPlanForTable(tableNode);
                m_plans.add(plan);
            }

        }
        return m_plans.poll();
    }