// Once all resources have been retrieved from dcrd, update VoteTracker fields.
3561
func (tracker *VoteTracker) update(voteInfo *dcrjson.GetVoteInfoResult, blocks []int32,
	stakeInfo *dcrjson.GetStakeVersionInfoResult, stakeVersion uint32) {
	// Check if voteCounts are needed
	for idx := range voteInfo.Agendas {
		agenda := &voteInfo.Agendas[idx]
		if agenda.Status != statusDefined && agenda.Status != statusStarted {
			// check the cache
			counts := tracker.cachedCounts(agenda.ID)
			if counts == nil {
				counts = new(voteCount)
				var err error
				counts.yes, counts.abstain, counts.no, err = tracker.voteCounter(agenda.ID)
				if err != nil {
					log.Errorf("Error counting votes for %s: %v", agenda.ID, err)
					continue
				}
				tracker.cacheVoteCounts(agenda.ID, counts)
			}
			for idx := range agenda.Choices {
				choice := &agenda.Choices[idx]
				if choice.ID == choiceYes {
					choice.Count = counts.yes
				} else if choice.ID == choiceNo {
					choice.Count = counts.no
				} else {
					choice.Count = counts.abstain
				}
			}
		}
	}
	tracker.mtx.Lock()
	defer tracker.mtx.Unlock()
	tracker.voteInfo = voteInfo
	tracker.stakeInfo = stakeInfo
	ringLen := int(tracker.params.BlockUpgradeNumToCheck)
	for idx := range blocks {
		tracker.ringIndex = (tracker.ringIndex + 1) % ringLen
		tracker.blockRing[tracker.ringIndex] = blocks[idx]
	}
	tracker.blockVersion = tracker.blockRing[tracker.ringIndex]
	tracker.stakeVersion = stakeVersion
	tracker.ringHeight = voteInfo.CurrentHeight
	tracker.summary = tracker.newVoteSummary()
}
643937
func (c *TxnCollector) AfterRunTransaction(dbName, modelUUID string, ops []txn.Op, err error) {
	for _, op := range ops {
		c.updateMetrics(dbName, op, err)
	}
}
735825
func (fr *fileReader) pollChanges(ctx context.Context) {
	ticker := time.Tick(time.Duration(int64(time.Second) * fr.Cfg.UpdateIntervalSeconds))
	for {
		select {
		case <-ticker:
			if err := fr.startWalkingDisk(); err != nil {
				fr.log.Error("failed to search for dashboards", "error", err)
			}
		case <-ctx.Done():
			return
		}
	}
}
279430
func (fup *folderUpdatePrepper) updateResolutionUsageLockedCache(
	ctx context.Context, lState *kbfssync.LockState, md *RootMetadata,
	bps blockPutState, unmergedChains, mergedChains *crChains,
	mostRecentMergedMD ImmutableRootMetadata,
	refs, unrefs map[data.BlockPointer]bool) error {
	md.SetRefBytes(0)
	md.SetUnrefBytes(0)
	md.SetMDRefBytes(0)
	md.SetDiskUsage(mostRecentMergedMD.DiskUsage())
	md.SetMDDiskUsage(mostRecentMergedMD.MDDiskUsage())

	localBlocks := make(map[data.BlockPointer]data.Block)
	for _, ptr := range bps.ptrs() {
		if block, err := bps.getBlock(ctx, ptr); err == nil && block != nil {
			localBlocks[ptr] = block
		}
	}

	// Add bytes for every ref'd block.
	refPtrsToFetch := make([]data.BlockPointer, 0, len(refs))
	var refSum uint64
	for ptr := range refs {
		if block, ok := localBlocks[ptr]; ok {
			refSum += uint64(block.GetEncodedSize())
		} else {
			refPtrsToFetch = append(refPtrsToFetch, ptr)
		}
		fup.vlog.CLogf(ctx, libkb.VLog1, "Ref'ing block %v", ptr)
	}

	// Look up the total sum of the ref blocks in parallel to get
	// their sizes.
	//
	// TODO: If the blocks weren't already in the cache, this call
	// won't cache them, so it's kind of wasting work.  Furthermore,
	// we might be able to get the encoded size from other sources as
	// well (such as its directory entry or its indirect file block)
	// if we happened to have come across it before.
	refSumFetched, err := fup.blocks.GetCleanEncodedBlocksSizeSum(
		ctx, lState, md.ReadOnly(), refPtrsToFetch, nil, fup.branch(), false)
	if err != nil {
		return err
	}
	refSum += refSumFetched

	fup.vlog.CLogf(ctx, libkb.VLog1, "Ref'ing a total of %d bytes", refSum)
	md.AddRefBytes(refSum)
	md.AddDiskUsage(refSum)

	unrefPtrsToFetch := make([]data.BlockPointer, 0, len(unrefs))
	var unrefSum uint64
	for ptr := range unrefs {
		original, ok := unmergedChains.originals[ptr]
		if !ok {
			original = ptr
		}
		if original != ptr || unmergedChains.isCreated(original) {
			// Only unref pointers that weren't created as part of the
			// unmerged branch.  Either they existed already or they
			// were created as part of the merged branch.
			continue
		}
		// Also make sure this wasn't already removed or overwritten
		// on the merged branch.
		original, ok = mergedChains.originals[ptr]
		if !ok {
			original = ptr
		}
		mergedChain, ok := mergedChains.byOriginal[original]
		if (ok && original != mergedChain.mostRecent && original == ptr) ||
			mergedChains.isDeleted(original) {
			continue
		}

		if info, ok := fup.cachedInfos[ptr]; ok {
			unrefSum += uint64(info.EncodedSize)
		} else {
			unrefPtrsToFetch = append(unrefPtrsToFetch, ptr)
		}
	}

	// Look up the unref blocks in parallel to get their sizes.  Since
	// we don't know whether these are files or directories, just look
	// them up generically.  Ignore any recoverable errors for unrefs.
	// Note that we can't combine these with the above ref fetches
	// since they require a different MD.  If the merged changes
	// didn't change any blocks (in particular, the root block), we
	// can assume all the blocks we are unreferencing were live;
	// otherwise, we need to check with the server to make sure.
	onlyCountIfLive := len(mergedChains.byOriginal) != 0
	unrefSumFetched, err := fup.blocks.GetCleanEncodedBlocksSizeSum(
		ctx, lState, mostRecentMergedMD, unrefPtrsToFetch, unrefs,
		fup.branch(), onlyCountIfLive)
	if err != nil {
		return err
	}
	unrefSum += unrefSumFetched

	// Subtract bytes for every unref'd block that wasn't created in
	// the unmerged branch.
	fup.vlog.CLogf(ctx, libkb.VLog1, "Unref'ing a total of %d bytes", unrefSum)
	md.AddUnrefBytes(unrefSum)
	md.SetDiskUsage(md.DiskUsage() - unrefSum)
	return nil
}
197443
func (s *RemotelyControlledSampler) updateAdaptiveSampler(strategies *sampling.PerOperationSamplingStrategies) {
	if adaptiveSampler, ok := s.sampler.(*adaptiveSampler); ok {
		adaptiveSampler.update(strategies)
	} else {
		s.sampler = newAdaptiveSampler(strategies, s.maxOperations)
	}
}
979647
func (c *nfsCollector) updateNFSRequestsv2Stats(ch chan<- prometheus.Metric, s *nfs.V2Stats) {
	const proto = "2"

	v := reflect.ValueOf(s).Elem()
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)

		ch <- prometheus.MustNewConstMetric(c.nfsProceduresDesc, prometheus.CounterValue,
			float64(field.Uint()), proto, v.Type().Field(i).Name)
	}
}
199122
func (p *Proxy) UpdateRedirectMetrics() {
	result := map[string]int{}
	for _, redirect := range p.redirects {
		result[string(redirect.listener.parserType)]++
	}
	for proto, count := range result {
		metrics.ProxyRedirects.WithLabelValues(proto).Set(float64(count))
	}
}
633921
func (a *API) UpdateResult(domain int, result *Result) (*Result, error) {
	dst := new(Result)
	url := a.BuildURL("/v2/domain/%d/result/%d", domain, result.Id)
	err := a.Put(url, Params{}, result, dst)
	return dst, err
}
1209721
func agendasForVoteVersion(ver uint32, client DeploymentSource) ([]AgendaTagged, error) {
	voteInfo, err := client.GetVoteInfo(ver)
	if err != nil {
		return nil, err
	}

	// Set the agendas slice capacity.
	agendas := make([]AgendaTagged, 0, len(voteInfo.Agendas))
	for i := range voteInfo.Agendas {
		v := &voteInfo.Agendas[i]
		agendas = append(agendas, AgendaTagged{
			ID:             v.ID,
			Description:    v.Description,
			Mask:           v.Mask,
			StartTime:      v.StartTime,
			ExpireTime:     v.ExpireTime,
			Status:         dbtypes.AgendaStatusFromStr(v.Status),
			QuorumProgress: v.QuorumProgress,
			Choices:        v.Choices,
			VoteVersion:    voteInfo.VoteVersion,
		})
	}

	return agendas, nil
}
919900
func (tracker *VoteTracker) cacheVoteCounts(agendaID string, counts *voteCount) {
	tracker.mtx.Lock()
	defer tracker.mtx.Unlock()
	tracker.countCache[agendaID] = counts
}
854679
func (_m *Store) UpdateNodeResource(ctx context.Context, node *types.Node, cpu types.CPUMap, quota float64, mem int64, action string) error {
	ret := _m.Called(ctx, node, cpu, quota, mem, action)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, *types.Node, types.CPUMap, float64, int64, string) error); ok {
		r0 = rf(ctx, node, cpu, quota, mem, action)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
429773
func (c *nfsdCollector) updateNFSdReplyCacheStats(ch chan<- prometheus.Metric, s *nfs.ReplyCache) {
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "reply_cache_hits_total"),
			"Total number of NFSd Reply Cache hits (client lost server response).",
			nil,
			nil,
		),
		prometheus.CounterValue,
		float64(s.Hits))
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "reply_cache_misses_total"),
			"Total number of NFSd Reply Cache an operation that requires caching (idempotent).",
			nil,
			nil,
		),
		prometheus.CounterValue,
		float64(s.Misses))
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc(
			prometheus.BuildFQName(namespace, nfsdSubsystem, "reply_cache_nocache_total"),
			"Total number of NFSd Reply Cache non-idempotent operations (rename/delete/…).",
			nil,
			nil,
		),
		prometheus.CounterValue,
		float64(s.NoCache))
}
401941
func (dd *DirData) UpdateEntry(
	ctx context.Context, name string, newDe DirEntry) (
	unrefs []BlockInfo, err error) {
	return dd.addEntryHelper(ctx, name, newDe, false, true)
}
514914
func (ctx *HookContext) UpdateActionResults(keys []string, value string) error {
	if ctx.actionData == nil {
		return errors.New("not running an action")
	}
	addValueToMap(keys, value, ctx.actionData.ResultsMap)
	return nil
}
496471
func (c *Client) UpdateRP(ctx context.Context, db string, rp string, upd *chronograf.RetentionPolicy) (*chronograf.RetentionPolicy, error) {
	var buffer bytes.Buffer
	buffer.WriteString(fmt.Sprintf(`ALTER RETENTION POLICY "%s" ON "%s"`, rp, db))
	if len(upd.Duration) > 0 {
		buffer.WriteString(" DURATION " + upd.Duration)
	}
	if upd.Replication > 0 {
		buffer.WriteString(" REPLICATION " + fmt.Sprint(upd.Replication))
	}
	if len(upd.ShardDuration) > 0 {
		buffer.WriteString(" SHARD DURATION " + upd.ShardDuration)
	}
	if upd.Default {
		buffer.WriteString(" DEFAULT")
	}
	queryRes, err := c.Query(ctx, chronograf.Query{
		Command: buffer.String(),
		DB:      db,
		RP:      rp,
	})
	if err != nil {
		return nil, err
	}

	// The ALTER RETENTION POLICIES statements puts the error within the results itself
	// So, we have to crack open the results to see what happens
	octets, err := queryRes.MarshalJSON()
	if err != nil {
		return nil, err
	}

	results := make([]struct{ Error string }, 0)
	if err := json.Unmarshal(octets, &results); err != nil {
		return nil, err
	}

	// At last, we can check if there are any error strings
	for _, r := range results {
		if r.Error != "" {
			return nil, fmt.Errorf(r.Error)
		}
	}

	res, err := c.getRP(ctx, db, upd.Name)
	if err != nil {
		return nil, err
	}

	return &res, nil
}
1305355
func (tracker *VoteTracker) refreshRCI() (*dcrjson.GetVoteInfoResult, error) {
	oldVersion := tracker.Version()
	v := oldVersion
	var err error
	var voteInfo, vinfo *dcrjson.GetVoteInfoResult

	// Retrieves the voteinfo for the last stake version supported.
	for {
		vinfo, err = tracker.node.GetVoteInfo(v)
		if err != nil {
			break
		}
		voteInfo = vinfo
		v++
	}

	if voteInfo == nil {
		return nil, fmt.Errorf("Vote information not found: %v", err)
	}
	if v > oldVersion+1 {
		tracker.mtx.Lock()
		tracker.version = v
		tracker.mtx.Unlock()
	}
	return voteInfo, nil
}
271853
func (rc *ResourceController) UpdateHandler(c *gin.Context) {
	resource := models.NewStructForResourceName(rc.Name)
	err := FHIRBind(c, resource)
	if err != nil {
		oo := models.NewOperationOutcome("fatal", "exception", err.Error())
		c.JSON(http.StatusBadRequest, oo)
		return
	}

	createdNew, err := rc.DAL.Put(c.Param("id"), resource)
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	c.Set(rc.Name, resource)
	c.Set("Resource", rc.Name)

	c.Header("Location", responseURL(c.Request, rc.Name, c.Param("id")).String())
	if createdNew {
		c.Set("Action", "create")
		c.JSON(http.StatusCreated, resource)
	} else {
		c.Set("Action", "update")
		c.JSON(http.StatusOK, resource)
	}
}