Rebuilds whole tree in database using `parent` link.
355862
def rebuild_tree(modeladmin, request, queryset=None):
    
    tree = FileNode.tree.rebuild()
    messages.success(request, message=_('The node tree was rebuilt.'))
    return HttpResponseRedirect('')
794081
private function appendDatabaseNode(Database $database, \DOMNode $parentNode)
    {
        $databaseNode = $parentNode->appendChild($this->document->createElement('database'));
        $databaseNode->setAttribute('name', $database->getName());
        $databaseNode->setAttribute('defaultIdMethod', $database->getDefaultIdMethod());

        if ($package = $database->getPackage()) {
            $databaseNode->setAttribute('package', $package);
        }

        if ($schema = $database->getSchema()) {
            $databaseNode->setAttribute('schema', $schema);
        }

        if ($namespace = $database->getNamespace()) {
            $databaseNode->setAttribute('namespace', $namespace);
        }

        if ($baseClass = $database->getBaseClass()) {
            $databaseNode->setAttribute('baseClass', $baseClass);
        }

        if ($baseQueryClass = $database->getBaseQueryClass()) {
            $databaseNode->setAttribute('baseQueryClass', $baseQueryClass);
        }

        if ($defaultNamingMethod = $database->getDefaultPhpNamingMethod()) {
            $databaseNode->setAttribute('defaultPhpNamingMethod', $defaultNamingMethod);
        }

        $defaultAccessorVisibility = $database->getDefaultAccessorVisibility();
        if ($defaultAccessorVisibility !== Database::VISIBILITY_PUBLIC) {
            $databaseNode->setAttribute('defaultAccessorVisibility', $defaultAccessorVisibility);
        }

        $defaultMutatorVisibility = $database->getDefaultMutatorVisibility();
        if ($defaultMutatorVisibility !== Database::VISIBILITY_PUBLIC) {
            $databaseNode->setAttribute('defaultMutatorVisibility', $defaultMutatorVisibility);
        }

        $defaultStringFormat = $database->getDefaultStringFormat();
        if (Database::DEFAULT_STRING_FORMAT !== $defaultStringFormat) {
            $databaseNode->setAttribute('defaultStringFormat', $defaultStringFormat);
        }

        if ($database->isHeavyIndexing()) {
            $databaseNode->setAttribute('heavyIndexing', 'true');
        }

        if ($tablePrefix = $database->getTablePrefix()) {
            $databaseNode->setAttribute('tablePrefix', $tablePrefix);
        }

        if ($database->isIdentifierQuotingEnabled()) {
            $databaseNode->setAttribute('identifierQuoting', 'true');
        }

        /*
            FIXME - Before we can add support for domains in the schema, we need
            to have a method of the Column that indicates whether the column was mapped
            to a SPECIFIC domain (since Column->getDomain() will always return a Domain object)

            foreach ($this->domainMap as $domain) {
                $this->appendDomainNode($databaseNode);
            }
         */
        foreach ($database->getVendorInformation() as $vendorInformation) {
            $this->appendVendorInformationNode($vendorInformation, $databaseNode);
        }

        foreach ($database->getTables() as $table) {
            $this->appendTableNode($table, $databaseNode);
        }
    }
1304421
def rebuild(str)
      extract_root_pivot(str)

      list = (get_array.select {|entry| entry.start_with?(@pivot)}).sort

      @cycler = list.empty? ? nil : list.cycle
    end
1123977
public function rebuildtree() {
		//Rebuild nested set - get cat
		BLog::addToLog('[Items] rebuilding nested sets...');


		$db = \Brilliant\BFactory::getDBO();
		if (empty($db)) {
			return false;
			}
		$r = $db->query('LOCK TABLES `'.$this->tableName.'` WRITE');
		if(!$r){
			BLog::addToLog('[Items] Could not lock table!',LL_ERROR);
			}
		//
		BLog::addToLog('[Items] Invalidating cache...');
		$bcache = \Brilliant\BFactory::getCache();
		if ($bcache) {
			$bcache->invalidate();
			}
		//
		BLog::addToLog('[Items] Get root cats...');
		//
		$catsCount = $this->itemsFilterCount(array());
		BLog::addToLog('[Items] Total categories count:' . $catsCount . '...');
		//
		$rootCatsCount = $this->itemsFilterCount(array('parentisnull'=>true));
		BLog::addToLog('[Items] Root categories count:' . $rootCatsCount. '...');
		//Go th
		$rootCatsOffset = 0;
		while($rootCatsOffset < $rootCatsCount) {
			$paramsRoot = array();
			$paramsRoot['parentisnull']=true;
			$paramsRoot['orderby']='created';
			$paramsRoot['orderdir']='asc';
			$paramsRoot['offset']=$rootCatsOffset;
			$paramsRoot['limit']=1;
			$rootcats = $this->itemsFilter($paramsRoot);
			if(count($rootcats)!=1){
				BLog::addToLog('[Items] Root Category error!',LL_ERROR);
				}
			$rcat = reset($rootcats);
			$groupId = $rcat->getGroupId();
			//
			BLog::addToLog('[Items] Processing group #' . $groupId . ', root = ' . $rcat->id . '...');
			//
			$paramsAll=array();
			$paramsAll['group']=$groupId;
			//$paramsAll['parenttree_lft']
			//$paramsAll['parenttree_rgt']
			$catslist = $this->itemsFilter($paramsAll);


			//Foreach by root categories...
			$rcat->level = 0;
			$lft = 1;
			$rgt = 2;
			$this->rebuildtree_recursive($rcat, $lft, $rgt);
			$rcat->lft = 1;
			$rcat->rgt = $rgt;
			BLog::addToLog('[Items] Updating nested set...');
			foreach ($catslist as $ct) {
				$qr = 'UPDATE `' . $this->tableName . '` set `' . $this->leftKeyName . '`=' . $ct->lft . ', `' . $this->rightKeyName . '`=' . $ct->rgt . ', `' . $this->levelKeyName . '`=' . $ct->level . ' WHERE `' . $this->primaryKeyName . '`=' . $ct->id;
				$q = $db->query($qr);
				if (empty($q)) {
					return false;
					}
				}
			$rootCatsOffset+=1;
			//Invalidate cache after each group...
			$bcache = \Brilliant\BFactory::getCache();
			if ($bcache) {
				$bcache->invalidate();
				}
			}
		return true;
		}
507877
def from_parent_deeper(
        cls, parent_id=None, limit_depth=1000000, db_session=None, *args, **kwargs
    ):
        

        if parent_id:
            limiting_clause = "res.parent_id = :parent_id"
        else:
            limiting_clause = "res.parent_id is null"
        tablename = cls.model.__table__.name
        raw_q = """
            WITH RECURSIVE subtree AS (
                    SELECT res.*, 1 AS depth, LPAD(res.ordering::CHARACTER VARYING, 7, '0') AS sorting,
                    res.resource_id::CHARACTER VARYING AS path
                    FROM {tablename} AS res WHERE {limiting_clause}
                  UNION ALL
                    SELECT res_u.*, depth+1 AS depth,
                    (st.sorting::CHARACTER VARYING || '/' || LPAD(res_u.ordering::CHARACTER VARYING, 7, '0') ) AS sorting,
                    (st.path::CHARACTER VARYING || '/' || res_u.resource_id::CHARACTER VARYING ) AS path
                    FROM {tablename} res_u, subtree st
                    WHERE res_u.parent_id = st.resource_id
            )
            SELECT * FROM subtree WHERE depth<=:depth ORDER BY sorting;
        """.format(
            tablename=tablename, limiting_clause=limiting_clause
        )  # noqa
        db_session = get_db_session(db_session)
        text_obj = sa.text(raw_q)
        query = db_session.query(cls.model, "depth", "sorting", "path")
        query = query.from_statement(text_obj)
        query = query.params(parent_id=parent_id, depth=limit_depth)
        return query
874423
function loadTree (data) {
      // Just need to restore the `parent` parameter
      self.root = data;

      function restoreParent (root) {
        if (root.left) {
          root.left.parent = root;
          restoreParent(root.left);
        }

        if (root.right) {
          root.right.parent = root;
          restoreParent(root.right);
        }
      }

      restoreParent(self.root);
    }
886301
def rebuild(mode=''):
    """"""
    scan_site()  # for good measure
    if not current_user.can_rebuild_site:
        return error('You are not permitted to rebuild the site.</p>'
                     '<p class="lead">Contact an administartor for '
                     'more information.', 401)
    if db is not None:
        db.set('site:needs_rebuild', '-1')
        if not q.fetch_job('build') and not q.fetch_job('orphans'):
            b = q.enqueue_call(func=coil.tasks.build,
                               args=(app.config['REDIS_URL'],
                                     app.config['NIKOLA_ROOT'], mode),
                               job_id='build')
            q.enqueue_call(func=coil.tasks.orphans,
                           args=(app.config['REDIS_URL'],
                                 app.config['NIKOLA_ROOT']), job_id='orphans',
                           depends_on=b)
        return render('coil_rebuild.tmpl', {'title': 'Rebuild'})
    else:
        status, outputb = coil.tasks.build_single(mode)
        _, outputo = coil.tasks.orphans_single()
        site.coil_needs_rebuild = '0'
        return render('coil_rebuild_single.tmpl',
                      {'title': 'Rebuild', 'status': '1' if status else '0',
                       'outputb': outputb, 'outputo': outputo})
857486
def fixup_parents(self, node, parent):
        """"""
        start, finish = 0, self.last_finish
        # We assume anything with a start has a finish.
        needs_range = not hasattr(node, 'start')

        if not hasattr(node, 'parent'):
            node.parent = parent

        for n in node:
            if needs_range and hasattr(n, 'start'):
                if n.start < start: start = n.start
                if n.finish > finish: finish = n.finish

            if hasattr(n, 'offset') and not hasattr(n, 'parent'):
                n.parent = node
            else:
                self.fixup_parents(n, node)
                pass
            pass
        if needs_range:
            node.start, node.finish = start, finish

        return
63440
public function restoreMode() {
		if ( $this->originalMode === null ) {
			throw new TreeBuilderError( "original insertion mode is not set" );
		}
		$mode = $this->mode = $this->originalMode;
		$this->originalMode = null;
		$this->handler = $this->dispatchTable[$mode];
		return $this->handler;
	}
657479
private function fixNodesWithoutParents()
    {
        // fix nodes that have no parent but depth > 0
        $qb = $this->accountRepository->createQueryBuilder('c2')
            ->update()
            ->set('c2.depth', 0)
            ->where('c2.parent IS NULL AND depth != 0');

        $qb->getQuery()->execute();
    }
1162236
def rebuild(str)
      extract_root_pivot(str)

      list = Dir.glob(dress_down(@pivot) + '*')

      @cycler = list.empty? ? nil : list.cycle
    end
885679
def add_child(self, **kwargs):
        """"""
        cls = get_result_class(self.__class__)

        if len(kwargs) == 1 and 'instance' in kwargs:
            # adding the passed (unsaved) instance to the tree
            newobj = kwargs['instance']
            if newobj.pk:
                raise NodeAlreadySaved("Attempted to add a tree node that is "\
                    "already in the database")
        else:
            newobj = cls(**kwargs)

        try:
            newobj._cached_depth = self._cached_depth + 1
        except AttributeError:
            pass
        if not cls.node_order_by:
            try:
                max = cls.objects.filter(parent=self).reverse(
                )[0].sib_order
            except IndexError:
                max = 0
            newobj.sib_order = max + 1
        newobj.parent = self
        newobj.save()
        return newobj
547455
def rebuild_index(self):
        """"""
        try:
            os.remove(environ.index_db_re)
        except:
            pass

        self.db_conn = sqlite3.connect(environ.index_db_re)
        self.db_cursor = self.db_conn.cursor()
        self.db_cursor.execute('CREATE TABLE "cplusplus.com" '
                               '(name VARCHAR(255), url VARCHAR(255), std VARCHAR(255))')
        self.db_cursor.execute('CREATE TABLE "cppreference.com" '
                               '(name VARCHAR(255), url VARCHAR(255), std VARCHAR(255))')

        try:
            self.add_url_filter('\.(jpg|jpeg|gif|png|js|css|swf|svg)$')
            self.set_follow_mode(Crawler.F_SAME_PATH)

            # cplusplus.com
            self.crawl('http://www.cplusplus.com/reference/')
            for name, url, std in self.results:
                self.insert_index('cplusplus.com', name, url, std)
            self.db_conn.commit()

            # Rename duplicate entries
            duplicates = self.db_cursor.execute('SELECT name, COUNT(name) '
                                                'AS NON '
                                                'FROM "cplusplus.com" '
                                                'GROUP BY NAME '
                                                'HAVING (NON > 1)').fetchall()
            for name, num in duplicates:
                dump = self.db_cursor.execute('SELECT name, url FROM '
                                              '"cplusplus.com" WHERE name="%s"'
                                              % name).fetchall()
                for n, u in dump:
                    if u not in self.name_exceptions:
                        n2 = n[5:] if n.startswith('std::') else n
                        try:
                            group = re.search('/([^/]+)/%s/$' % n2, u).group(1)
                        except Exception:
                            group = re.search('/([^/]+)/[^/]+/$', u).group(1)

                        new_name = '%s (%s)' % (n, group)
                        self.db_cursor.execute('UPDATE "cplusplus.com" '
                                               'SET name="%s", url="%s" '
                                               'WHERE url="%s"' %
                                               (new_name, u, u))
            self.db_conn.commit()

            # cppreference.com
            self.results = set()
            self.crawl('https://en.cppreference.com/w/cpp', '/w/cpp')

            for name, url, std in self.results:
                self.insert_index('cppreference.com', name, url, std)
            self.db_conn.commit()

        except KeyboardInterrupt:
            os.remove(environ.index_db_re)
            raise KeyboardInterrupt
        finally:
            self.db_conn.close()
768138
def update_all_nodes(self):
        
        item_model_controller = self.item_model_controller
        if item_model_controller:
            if self.__node_counts_dirty:
                for item in self.__mapping.values():
                    if "tree_node" in item.data:  # don't update the root node
                        tree_node = item.data["tree_node"]
                        item.data["display"] = self.__display_for_tree_node(tree_node)
                        item_model_controller.data_changed(item.row, item.parent.row, item.parent.id)
                self.__node_counts_dirty = False
1358222
def RebuildMerkleRoot(self):
        """"""
        logger.debug("Rebuilding merkle root!")
        if self.Transactions is not None and len(self.Transactions) > 0:
            self.MerkleRoot = MerkleTree.ComputeRoot([tx.Hash for tx in self.Transactions])
831501
def refresh_db(root=None):
    '''
    
    '''
    # Remove rtag file to keep multiple refreshes from happening in pkg states
    salt.utils.pkg.clear_rtag(__opts__)
    ret = {}
    out = __zypper__(root=root).refreshable.call('refresh', '--force')

    for line in out.splitlines():
        if not line:
            continue
        if line.strip().startswith('Repository') and '\'' in line:
            try:
                key = line.split('\'')[1].strip()
                if 'is up to date' in line:
                    ret[key] = False
            except IndexError:
                continue
        elif line.strip().startswith('Building') and '\'' in line:
            key = line.split('\'')[1].strip()
            if 'done' in line:
                ret[key] = True
    return ret
782975
function _update() {
  var nodesData = _treeLayout.nodes(_treeData),
      linksData = _getLinks(nodesData);

  _normalize(nodesData);

  var nodes = _g.selectAll('g.node')
    .data(nodesData, _getNodeId);
  _updateNodes(nodes, _treeData);

  var links = _g.selectAll('path.link')
      .data(linksData, _getLinkId);
  _updateLinks(links, _treeData);

  nodesData.forEach(_stashOldPositions);
}