We need _really_ complicated logic to find just the changed subsites (because we use versions there's no explicit
deletes, just new versions with different members) so just always use all of them
490678
public function extractManipulationWriteState(&$writes)
    {
        $self = get_class($this);
        $tableName = DataObject::getSchema()->tableName(Subsite::class);
        $query = SQLSelect::create('"ID"', '"' . $tableName . '"');
        $subsites = array_merge(['0'], $query->execute()->column());

        foreach ($writes as $key => $write) {
            $applies = $this->appliesTo($write['class'], true);
            if (!$applies) {
                continue;
            }

            if (isset($write['fields'][SiteTree::class . ':SubsiteID'])) {
                $subsitesForWrite = [$write['fields'][SiteTree::class . ':SubsiteID']];
            } elseif (isset($write['fields'][File::class . ':SubsiteID'])
                && (int) $write['fields'][File::class . ':SubsiteID'] !== 0
            ) {
                // files in subsite 0 should be in all subsites as they are global
                $subsitesForWrite = [$write['fields'][File::class . ':SubsiteID']];
            } else {
                $subsitesForWrite = $subsites;
            }

            $next = [];
            foreach ($write['statefulids'] as $i => $statefulid) {
                foreach ($subsitesForWrite as $subsiteID) {
                    $next[] = [
                        'id' => $statefulid['id'],
                        'state' => array_merge(
                            $statefulid['state'],
                            [$self => (string) $subsiteID]
                        ),
                    ];
                }
            }
            $writes[$key]['statefulids'] = $next;
        }
    }
1141462
def pruneChanges(self, changeHorizon):
        

        if not changeHorizon:
            return None

        def thd(conn):
            changes_tbl = self.db.model.changes

            # First, get the list of changes to delete.  This could be written
            # as a subquery but then that subquery would be run for every
            # table, which is very inefficient; also, MySQL's subquery support
            # leaves much to be desired, and doesn't support this particular
            # form.
            q = sa.select([changes_tbl.c.changeid],
                          order_by=[sa.desc(changes_tbl.c.changeid)],
                          offset=changeHorizon)
            res = conn.execute(q)
            ids_to_delete = [r.changeid for r in res]

            # and delete from all relevant tables, in dependency order
            for table_name in ('scheduler_changes', 'change_files',
                               'change_properties', 'changes', 'change_users'):
                remaining = ids_to_delete[:]
                while remaining:
                    batch, remaining = remaining[:100], remaining[100:]
                    table = self.db.model.metadata.tables[table_name]
                    conn.execute(
                        table.delete(table.c.changeid.in_(batch)))
        yield self.db.pool.do(thd)
332095
public function allSites() {
    $multisites = $this->getConfigValue('multisites');
    $this->printSyncMap($multisites);
    $continue = $this->confirm("Continue?", TRUE);
    if (!$continue) {
      return 0;
    }
    foreach ($multisites as $multisite) {
      $this->say("Refreshing site <comment>$multisite</comment>...");
      $this->switchSiteContext($multisite);
      $this->sync();
    }
  }
601172
function reloadSites() {
    function reload() {
      sites.get()
      .then(function(sites) {
        $scope.ui.sites = sites;
      });
    }
    /*
     * Reload sites mutliple times, because sometimes updates to list of sites
     * aren't ready immediately.
     */
    // Reload sites immediately.
    reload();
    // Reload sites again after 5 seconds.
    setTimeout(reload, 1000 * 5);
    // Reload sites again after 15 seconds.
    setTimeout(reload, 1000 * 15);
  }
207128
def _doCleanup(self):
        
        # pass on this if we're not configured yet
        if not self.configured_url:
            return

        d = self.changes.pruneChanges(self.master.config.changeHorizon)
        d.addErrback(log.err, 'while pruning changes')
        return d
810167
def cache_subdirectory(
        reference_name=None,
        annotation_name=None,
        annotation_version=None):
    
    if reference_name is None:
        reference_name = ""
    if annotation_name is None:
        annotation_name = ""
    if annotation_version is None:
        annotation_version = ""
    reference_dir = join(CACHE_BASE_SUBDIR, reference_name)
    annotation_dir = "%s%s" % (annotation_name, annotation_version)
    return join(reference_dir, annotation_dir)
333949
function _stripOldVersionInfo(versionInfo, buildNumber) {
        // Do a simple linear search. Since we are going in reverse-chronological order, we
        // should get through the search quickly.
        var lastIndex = 0;
        var len = versionInfo.length;
        var versionEntry;
        var validBuildEntries;

        while (lastIndex < len) {
            versionEntry = versionInfo[lastIndex];
            if (versionEntry.buildNumber <= buildNumber) {
                break;
            }
            lastIndex++;
        }

        if (lastIndex > 0) {
            // Filter recent update entries based on applicability to current platform
            validBuildEntries = versionInfo.slice(0, lastIndex).filter(_checkBuildApplicability);
        }

        return validBuildEntries;
    }
6262
public boolean hasModuleResourcesWithUndefinedSite() {

        if (getSite() == null) {
            for (String modRes : getResources()) {
                if (!CmsStringUtil.isPrefixPath("/system/", modRes)
                    && !OpenCms.getSiteManager().startsWithShared(modRes)) {
                    return true;
                }

            }
        }
        return false;
    }
47809
def additions_version():
    '''
    
    '''
    try:
        d = _additions_dir()
    except EnvironmentError:
        return False
    if d and os.listdir(d):
        return re.sub(r'^{0}-'.format(_additions_dir_prefix), '',
                os.path.basename(d))
    return False
78393
def site=(new_site)
      return nil unless updatable? || creatable?

      # unset the site? Use nil or an empty string
      if NON_SITES.include? new_site
        unset_site
        return
      end

      new_id = JSS::Site.valid_id new_site, api: @api
      new_name = JSS::Site.map_all_ids_to(:name, api: @api)[new_id]
      # no change, go home.
      return nil if new_name == @site_name

      raise JSS::NoSuchItemError, "Site '#{new_site}' is not known to the JSS" unless new_id

      @site_name = new_name
      @site_id = new_id
      @need_to_update = true
    end
514443
def find_changed():
    

    session_token = request.headers['session_token']
    repository    = request.headers['repository']

    #===
    current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
    if current_user is False: return fail(user_auth_fail_msg)

    #===
    repository_path = config['repositories'][repository]['path']
    body_data = request.get_json()

    #===
    data_store = versioned_storage(repository_path)
    head = data_store.get_head()
    if head == 'root': return success({}, {'head' : 'root', 'sorted_changes' : {'none' : []}})

    # Find changed items
    client_changes = json.loads(body_data['client_changes'])
    server_changes = data_store.get_changes_since(request.headers["previous_revision"], head)

    # Resolve conflicts
    conflict_resolutions = json.loads(body_data['conflict_resolutions'])
    if conflict_resolutions != []:
        resolutions = {'server' : {},'client' : {}}
        for r in conflict_resolutions:
            if len(r['4_resolution']) != 1 or r['4_resolution'][0] not in ['client', 'server']: return fail(conflict_msg)
            resolutions[r['4_resolution'][0]][r['1_path']] = None

        client_changes = {k : v for k,v in client_changes.iteritems() if v['path'] not in resolutions['server']}
        server_changes = {k : v for k,v in server_changes.iteritems() if v['path'] not in resolutions['client']}

    sorted_changes = merge_client_and_server_changes(server_changes, client_changes)
    return success({}, {'head' : head, 'sorted_changes': sorted_changes})
1340713
function cleanup( $allInstallations = false, $optimize = false )
    {
        if ( $allInstallations === true )
        {
            $optimize = true;
            $deleteQuery = '*:*';
        }
        else
        {
            $deleteQuery = ezfSolrDocumentFieldBase::generateMetaFieldName( 'installation_id' ) . ':' . self::installationID();
        }
        if ( $this->UseMultiLanguageCores == true )
        {
            foreach ( $this->SolrLanguageShards as $shard )
            {
                $shard->deleteDocs( array(), $deleteQuery, true, $optimize );
            }
            return true;
        }
        else
        {
            return $this->Solr->deleteDocs( array(), $deleteQuery, true );
        }

    }
244826
def new_posts subreddit = nil, caching = false
      cache = lambda do |id, &block|
        next block.call unless caching
        require "fileutils"
        FileUtils.mkdir_p "cache"
        filename = "cache/#{Digest::MD5.hexdigest id.inspect}"
        next YAML.load File.read filename if File.exist? filename
        block.call.tap do |data|
          File.write filename, YAML.dump(data)
        end
      end
      Enumerator.new do |e|
        after = {}
        loop do
          # TODO maybe force lib user to prepend "r/" to @subreddit constructor?
          args = [:get, "/#{subreddit || (@subreddit ? "r/#{@subreddit}" : fail)}/new", {limit: 100}.merge(after)]
          result = cache.call(args){ json *args }
          fail if result.keys != %w{ kind data }
          fail if result["kind"] != "Listing"
          fail result["data"].keys.inspect unless result["data"].keys == %w{ after dist modhash whitelist_status children before } ||
                                                  result["data"].keys == %w{ modhash dist children after before }
          @@skip_erroneous_descending_ids[ result["data"]["children"].map do |post|
            fail "unknown type post['kind']: #{post["kind"]}" unless post["kind"] == "t3"
            post["data"]
          end ].each do |data|
            e << data
          end
          break unless marker = result["data"]["after"]
          after = {after: marker}
        end
      end
    end
220101
public function onBeforeDuplicate()
    {
        $subsiteId = SubsiteState::singleton()->getSubsiteId();
        if ($subsiteId !== null) {
            $this->owner->SubsiteID = $subsiteId;
        }
    }
655345
def update_atom_members(old, new):
    
    old_keys = old.members().keys()
    new_keys = new.members().keys()
    for key in old_keys:
        old_obj = getattr(old, key)
        try:
            new_obj = getattr(new, key)
            if old_obj == new_obj:
                continue
        except AttributeError:
            # Remove any obsolete members
            try:
                delattr(old, key)
            except (AttributeError, TypeError):
                pass
            continue

        try:
            #: Update any changed members
            #: TODO: We have to somehow know if this was changed by the user or the code!
            #: and ONLY update if it's due to the code changing! Without this, the entire concept
            #: is broken and useless...
            setattr(old, key, getattr(new, key))
        except (AttributeError, TypeError):
            pass  # skip non-writable attributes

    #: Add any new members
    for key in set(new_keys)-set(old_keys):
        try:
            setattr(old, key, getattr(new, key))
        except (AttributeError, TypeError):
            pass
1066245
private function handle_reassign_sites() {
		$to   = array_map( 'absint', (array) filter_input( INPUT_POST, 'to', FILTER_FORCE_ARRAY ) );
		$from = array_map( 'absint', (array) filter_input( INPUT_POST, 'from', FILTER_FORCE_ARRAY ) );

		// Bail early if no movement.
		if ( empty( $to ) && empty( $from ) ) {
			return;
		}

		$network_id = filter_input( INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT );

		$moving_to   = array();
		$moving_from = array();

		$sites_list = get_sites( array(
			'network_id' => $network_id,
			'fields'     => 'ids',
		) );

		// Move sites out of current network.
		foreach ( $from as $site_id ) {
			if ( in_array( $site_id, $sites_list, true ) ) {
				$moving_from[] = $site_id;
			}
		}

		// Move sites into current network.
		foreach ( $to as $site_id ) {
			if ( ! in_array( $site_id, $sites_list, true ) ) {
				$moving_to[] = $site_id;
			}
		}

		$moving = array_filter( array_merge( $moving_to, $moving_from ) );

		// Loop through and move sites.
		foreach ( $moving as $site_id ) {
			$site = get_site( $site_id );

			// Skip if missing or main site.
			if ( empty( $site ) || is_main_site( $site->id, $site->network_id ) ) {
				continue;
			}

			if ( in_array( $site_id, $to, true ) && ! in_array( $site_id, $sites_list, true ) ) {
				move_site( $site_id, $network_id );
			} elseif ( in_array( $site_id, $from, true ) ) {
				move_site( $site_id, 0 );
			}
		}
	}
638970
def update(site=False, organizations=False, users=False, datasets=False,
           reuses=False):
    ''''''
    do_all = not any((site, organizations, users, datasets, reuses))

    if do_all or site:
        log.info('Update site metrics')
        update_site_metrics()

    if do_all or datasets:
        log.info('Update datasets metrics')
        for dataset in Dataset.objects.timeout(False):
            update_metrics_for(dataset)

    if do_all or reuses:
        log.info('Update reuses metrics')
        for reuse in Reuse.objects.timeout(False):
            update_metrics_for(reuse)

    if do_all or organizations:
        log.info('Update organizations metrics')
        for organization in Organization.objects.timeout(False):
            update_metrics_for(organization)

    if do_all or users:
        log.info('Update user metrics')
        for user in User.objects.timeout(False):
            update_metrics_for(user)

    success('All metrics have been updated')