// Finalizes termbox library, should be called after successful initialization
// when termbox's functionality isn't required anymore.
172072
func Close() {
	// we ignore errors here, because we can't really do anything about them
	Clear(0, 0)
	Flush()

	// stop event producer
	cancel_comm <- true
	set_event(interrupt)
	select {
	case <-input_comm:
	default:
	}
	<-cancel_done_comm

	set_console_screen_buffer_size(out, orig_size)
	set_console_window_info(out, &orig_window)
	set_console_cursor_info(out, &orig_cursor_info)
	set_console_cursor_position(out, coord{})
	set_console_mode(in, orig_mode)
	syscall.Close(in)
	syscall.Close(out)
	syscall.Close(interrupt)
	IsInit = false
}
389734
func (s *Seal) Finalize(_ context.Context) error {
	s.client.Close()
	return nil
}
418206
func (kt *SharedKeybaseTransport) Finalize() {
	kt.mutex.Lock()
	defer kt.mutex.Unlock()
	kt.transport = kt.stagedTransport
	kt.stagedTransport = nil
}
552561
func NewFinalizer() *Finalizer {
	var (
		f   = &Finalizer{seen: make(map[*design.AttributeDefinition]map[*design.AttributeDefinition]*bytes.Buffer)}
		err error
	)
	fm := template.FuncMap{
		"tabs":         Tabs,
		"goify":        Goify,
		"gotyperef":    GoTypeRef,
		"add":          Add,
		"finalizeCode": f.Code,
	}
	f.assignmentT, err = template.New("assignment").Funcs(fm).Parse(assignmentTmpl)
	if err != nil {
		panic(err)
	}
	f.arrayAssignmentT, err = template.New("arrAssignment").Funcs(fm).Parse(arrayAssignmentTmpl)
	if err != nil {
		panic(err)
	}
	return f
}
358836
func (glpeer *GLPeer) Finalize() {
	simlog.FuncIn()

	glpeer.mu.Lock()
	defer glpeer.mu.Unlock()

	glpeer.eng.Release()
	glpeer.fps.Release()
	glpeer.images.Release()
	glpeer.glc.glcontext = nil

	simlog.FuncOut()
}
528125
func (d *namespacedResourcesDeleter) finalizeNamespace(namespace *v1.Namespace) (*v1.Namespace, error) {
	namespaceFinalize := v1.Namespace{}
	namespaceFinalize.ObjectMeta = namespace.ObjectMeta
	namespaceFinalize.Spec = namespace.Spec
	finalizerSet := sets.NewString()
	for i := range namespace.Spec.Finalizers {
		if namespace.Spec.Finalizers[i] != d.finalizerToken {
			finalizerSet.Insert(string(namespace.Spec.Finalizers[i]))
		}
	}
	namespaceFinalize.Spec.Finalizers = make([]v1.FinalizerName, 0, len(finalizerSet))
	for _, value := range finalizerSet.List() {
		namespaceFinalize.Spec.Finalizers = append(namespaceFinalize.Spec.Finalizers, v1.FinalizerName(value))
	}
	namespace, err := d.nsClient.Finalize(&namespaceFinalize)
	if err != nil {
		// it was removed already, so life is good
		if errors.IsNotFound(err) {
			return namespace, nil
		}
	}
	return namespace, err
}
1071809
func (w *Lucene41PostingsWriter) FinishTerm(_state *BlockTermState) error {
	state := _state.Self.(*intBlockTermState)
	assert(state.DocFreq > 0)

	// TODO: wasteful we are couting this (counting # docs for this term) in two places?
	assert2(state.DocFreq == w.docCount, "%v vs %v", state.DocFreq, w.docCount)

	// docFreq == 1, don't write the single docId/freq to a separate
	// file along with a pointer to it.
	var singletonDocId int
	if state.DocFreq == 1 {
		// pulse the singleton docId into the term dictionary, freq is implicitly totalTermFreq
		singletonDocId = w.docDeltaBuffer[0]
	} else {
		singletonDocId = -1
		// vInt encode the remaining doc dealtas and freqs;
		var err error
		for i := 0; i < w.docBufferUpto; i++ {
			docDelta := w.docDeltaBuffer[i]
			freq := w.freqBuffer[i]
			if !w.fieldHasFreqs {
				if err = w.docOut.WriteVInt(int32(docDelta)); err != nil {
					return err
				}
			} else if w.freqBuffer[i] == 1 {
				if err = w.docOut.WriteVInt(int32((docDelta << 1) | 1)); err != nil {
					return err
				}
			} else {
				if err = w.docOut.WriteVInt(int32(docDelta << 1)); err != nil {
					return err
				}
				if err = w.docOut.WriteVInt(int32(freq)); err != nil {
					return err
				}
			}
		}
	}

	var lastPosBlockOffset int64
	if w.fieldHasPositions {
		// totalTermFreq is just total number of positions (or payloads,
		// or offsets) associated with current term.
		assert(state.TotalTermFreq != -1)
		if state.TotalTermFreq > LUCENE41_BLOCK_SIZE {
			// record file offset for last pos in last block
			lastPosBlockOffset = w.posOut.FilePointer() - w.posStartFP
		} else {
			lastPosBlockOffset = -1
		}
		if w.posBufferUpto > 0 {
			// TODO: should we send offsets/payloads to .pay...? seems
			// wasteful (have to store extra vlong for low (< BLOCK_SIZE)
			// DF terms = vast vast majority)

			// vInt encode the remaining positions/payloads/offsets:
			// lastPayloadLength := -1 // force first payload length to be written
			// lastOffsetLength := -1  // force first offset length to be written
			payloadBytesReadUpto := 0
			for i := 0; i < w.posBufferUpto; i++ {
				posDelta := w.posDeltaBuffer[i]
				if w.fieldHasPayloads {
					panic("not implemented yet")
				} else {
					err := w.posOut.WriteVInt(int32(posDelta))
					if err != nil {
						return err
					}
				}

				if w.fieldHasOffsets {
					panic("not implemented yet")
				}
			}

			if w.fieldHasPayloads {
				assert(payloadBytesReadUpto == w.payloadByteUpto)
				w.payloadByteUpto = 0
			}
		}
	} else {
		lastPosBlockOffset = -1
	}

	var skipOffset int64
	if w.docCount > LUCENE41_BLOCK_SIZE {
		n, err := w.skipWriter.WriteSkip(w.docOut)
		if err != nil {
			return err
		}
		skipOffset = n - w.docStartFP
	} else {
		skipOffset = -1
	}

	state.docStartFP = w.docStartFP
	state.posStartFP = w.posStartFP
	state.payStartFP = w.payStartFP
	state.singletonDocID = singletonDocId
	state.skipOffset = skipOffset
	state.lastPosBlockOffset = lastPosBlockOffset
	w.docBufferUpto = 0
	w.posBufferUpto = 0
	w.lastDocId = 0
	w.docCount = 0
	return nil
}
922867
func ClientFinalizer(f ...ClientFinalizerFunc) ClientOption {
	return func(s *Client) { s.finalizer = append(s.finalizer, f...) }
}
766362
func (c *RefCount) Finalize() {
	n := c.NumRef()
	tracebackEvent(c, n, finalizeEvent)

	if n != 0 {
		err := fmt.Errorf("finalize before zero ref count, ref=%d", n)
		panicRef(c, err)
	}

	if f := c.Finalizer(); f != nil {
		f.Finalize()
	}
}
1027227
func (a *Agent) finalizeClientConfig(c *clientconfig.Config) error {
	// Setup the logging
	c.Logger = a.logger
	c.LogOutput = a.logOutput

	// If we are running a server, append both its bind and advertise address so
	// we are able to at least talk to the local server even if that isn't
	// configured explicitly. This handles both running server and client on one
	// host and -dev mode.
	if a.server != nil {
		if a.config.AdvertiseAddrs == nil || a.config.AdvertiseAddrs.RPC == "" {
			return fmt.Errorf("AdvertiseAddrs is nil or empty")
		} else if a.config.normalizedAddrs == nil || a.config.normalizedAddrs.RPC == "" {
			return fmt.Errorf("normalizedAddrs is nil or empty")
		}

		c.Servers = append(c.Servers,
			a.config.normalizedAddrs.RPC,
			a.config.AdvertiseAddrs.RPC)
	}

	// Setup the plugin loaders
	c.PluginLoader = a.pluginLoader
	c.PluginSingletonLoader = a.pluginSingletonLoader

	// Log deprecation messages about Consul related configuration in client
	// options
	var invalidConsulKeys []string
	for key := range c.Options {
		if strings.HasPrefix(key, "consul") {
			invalidConsulKeys = append(invalidConsulKeys, fmt.Sprintf("options.%s", key))
		}
	}
	if len(invalidConsulKeys) > 0 {
		a.logger.Warn("invalid consul keys", "keys", strings.Join(invalidConsulKeys, ","))
		a.logger.Warn(`Nomad client ignores consul related configuration in client options.
		Please refer to the guide https://www.nomadproject.io/docs/agent/configuration/consul.html
		to configure Nomad to work with Consul.`)
	}

	return nil
}
941063
func (agent *ActionAgent) finalizeTabletExternallyReparented(ctx context.Context, si *topo.ShardInfo, ev *events.Reparent) (err error) {
	var wg sync.WaitGroup
	var errs concurrency.AllErrorRecorder
	var oldMasterTablet *topodatapb.Tablet
	oldMasterAlias := si.MasterAlias

	// Update the tablet records concurrently.
	event.DispatchUpdate(ev, "updating old and new master tablet records")
	log.Infof("finalizeTabletExternallyReparented: updating tablet records")
	wg.Add(1)
	go func() {
		defer wg.Done()
		// Update our own record to master.
		_, err := agent.TopoServer.UpdateTabletFields(ctx, agent.TabletAlias,
			func(tablet *topodatapb.Tablet) error {
				tablet.Type = topodatapb.TabletType_MASTER
				return nil
			})
		if err != nil {
			errs.RecordError(err)
		}
	}()

	if !topoproto.TabletAliasIsZero(oldMasterAlias) {
		wg.Add(1)
		go func() {
			defer wg.Done()

			// Forcibly demote the old master in topology, since we can't rely on the
			// old master to be up to change its own record.
			var err error
			oldMasterTablet, err = agent.TopoServer.UpdateTabletFields(ctx, oldMasterAlias,
				func(tablet *topodatapb.Tablet) error {
					tablet.Type = topodatapb.TabletType_REPLICA
					return nil
				})
			if err != nil {
				errs.RecordError(err)
				return
			}

			// We now know more about the old master, so add it to event data.
			ev.OldMaster = *oldMasterTablet
		}()
	}

	tablet := agent.Tablet()

	// Wait for the tablet records to be updated. At that point, any rebuild will
	// see the new master, so we're ready to mark the reparent as done in the
	// global shard record.
	wg.Wait()
	if errs.HasErrors() {
		return errs.Error()
	}

	wg.Add(1)
	go func() {
		defer wg.Done()

		// Update the master field in the global shard record. We don't use a lock
		// here anymore. The lock was only to ensure that the global shard record
		// didn't get modified between the time when we read it and the time when we
		// write it back. Now we use an update loop pattern to do that instead.
		event.DispatchUpdate(ev, "updating global shard record")
		log.Infof("finalizeTabletExternallyReparented: updating global shard record if needed")
		_, err = agent.TopoServer.UpdateShardFields(ctx, tablet.Keyspace, tablet.Shard, func(currentSi *topo.ShardInfo) error {
			if topoproto.TabletAliasEqual(currentSi.MasterAlias, tablet.Alias) {
				return topo.NewError(topo.NoUpdateNeeded, tablet.Alias.String())
			}
			if !topoproto.TabletAliasEqual(currentSi.MasterAlias, oldMasterAlias) {
				log.Warningf("old master alias (%v) not found in the global Shard record i.e. it has changed in the meantime."+
					" We're not overwriting the value with the new master (%v) because the current value is probably newer."+
					" (initial Shard record = %#v, current Shard record = %#v)",
					oldMasterAlias, tablet.Alias, si, currentSi)
				return topo.NewError(topo.NoUpdateNeeded, oldMasterAlias.String())
			}
			currentSi.MasterAlias = tablet.Alias
			return nil
		})
		if err != nil {
			errs.RecordError(err)
		}
	}()
	if !topoproto.TabletAliasIsZero(oldMasterAlias) {
		wg.Add(1)
		go func() {
			defer wg.Done()

			// Tell the old master to re-read its tablet record and change its state.
			// We don't need to put error into errs if this fails, but we need to wait
			// for it to make sure that old master tablet is not stuck in the MASTER
			// state.
			tmc := tmclient.NewTabletManagerClient()
			if err := tmc.RefreshState(ctx, oldMasterTablet); err != nil {
				log.Warningf("Error calling RefreshState on old master %v: %v", topoproto.TabletAliasString(oldMasterTablet.Alias), err)
			}
		}()
	}

	wg.Wait()
	if errs.HasErrors() {
		return errs.Error()
	}

	event.DispatchUpdate(ev, "finished")
	return nil
}
339021
func (a *APIDefinition) Finalize() {
	if len(a.Consumes) == 0 {
		a.Consumes = DefaultDecoders
	}
	if len(a.Produces) == 0 {
		a.Produces = DefaultEncoders
	}
	a.IterateResources(func(r *ResourceDefinition) error {
		returnsError := func(resp *ResponseDefinition) bool {
			if resp.MediaType == ErrorMediaIdentifier {
				if a.MediaTypes == nil {
					a.MediaTypes = make(map[string]*MediaTypeDefinition)
				}
				a.MediaTypes[CanonicalIdentifier(ErrorMediaIdentifier)] = ErrorMedia
				return true
			}
			return false
		}
		for _, resp := range a.Responses {
			if returnsError(resp) {
				return errors.New("done")
			}
		}
		for _, resp := range r.Responses {
			if returnsError(resp) {
				return errors.New("done")
			}
		}
		return r.IterateActions(func(action *ActionDefinition) error {
			for _, resp := range action.Responses {
				if returnsError(resp) {
					return errors.New("done")
				}
			}
			return nil
		})
	})
}
721110
func (m *Metrics) Finalize(rateLimit uint, totalQueries uint) {
	if rateLimit == 0 {
		rateLimit = 1
	}

	for _, s := range m.TimeMetrics {
		sort.Float64s(s.vals)
		cnt := len(s.vals)

		s.Min = Float64(s.vals[0])
		s.Med = Float64(s.vals[(50*cnt)/100]) // median = 50th percentile
		s.P95 = Float64(s.vals[(95*cnt)/100])
		s.Max = Float64(s.vals[cnt-1])
		s.Sum = (s.Sum * float64(rateLimit)) + s.outlierSum
		s.Avg = Float64(s.Sum / float64(totalQueries))
	}

	for _, s := range m.NumberMetrics {
		sort.Sort(byUint64(s.vals))
		cnt := len(s.vals)

		s.Min = Uint64(s.vals[0])
		s.Med = Uint64(s.vals[(50*cnt)/100]) // median = 50th percentile
		s.P95 = Uint64(s.vals[(95*cnt)/100])
		s.Max = Uint64(s.vals[cnt-1])
		s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum
		s.Avg = Uint64(s.Sum / uint64(totalQueries))
	}

	for _, s := range m.BoolMetrics {
		s.Sum = (s.Sum * uint64(rateLimit)) + s.outlierSum
	}
}
671509
func (m *SqlSelect) Finalize() error {
	if m.finalized {
		return nil
	}
	m.finalized = true
	if len(m.From) == 0 {
		return nil
	}
	for _, from := range m.From {
		from.Finalize()
	}

	return nil
}
1325638
func (hc *HealthCheckImpl) finalizeConn(hcc *healthCheckConn) {
	hcc.tabletStats.Up = false
	hcc.setServingState(false, "finalizeConn closing connection")
	// Note: checkConn() exits only when hcc.ctx.Done() is closed. Thus it's
	// safe to simply get Err() value here and assign to LastError.
	hcc.tabletStats.LastError = hcc.ctx.Err()
	hc.updateHealth(hcc.tabletStats.Copy(), nil)
	if hcc.conn != nil {
		// Don't use hcc.ctx because it's already closed.
		// Use a separate context, and add a timeout to prevent unbounded waits.
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		hcc.conn.Close(ctx)
		hcc.conn = nil
	}
}
387884
func (t *Term) Close() error {
	err := syscall.Close(t.fd)
	t.fd = -1
	return err
}
1184842
func (ethash *Ethash) FinalizeAndAssemble(chain consensus.ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) {
	// Accumulate any block and uncle rewards and commit the final state root
	accumulateRewards(chain.Config(), state, header, uncles)
	header.Root = state.IntermediateRoot(chain.Config().IsEIP158(header.Number))

	// Header seems complete, assemble into a block and return
	return types.NewBlock(header, txs, uncles, receipts), nil
}