//Forwards takes a value and walks Backward till 0
505222
func Forwards(to int, fx func(int)) {
	for i := 1; i <= to; i++ {
		fx(i)
	}
}
651143
func (g *AcyclicGraph) ReverseDepthFirstWalk(start []Vertex, f DepthWalkFunc) error {
	defer g.debug.BeginOperation(typeReverseDepthFirstWalk, "").End("")

	seen := make(map[Vertex]struct{})
	frontier := make([]*vertexAtDepth, len(start))
	for i, v := range start {
		frontier[i] = &vertexAtDepth{
			Vertex: v,
			Depth:  0,
		}
	}
	for len(frontier) > 0 {
		// Pop the current vertex
		n := len(frontier)
		current := frontier[n-1]
		frontier = frontier[:n-1]

		// Check if we've seen this already and return...
		if _, ok := seen[current.Vertex]; ok {
			continue
		}
		seen[current.Vertex] = struct{}{}

		// Add next set of targets in a consistent order.
		targets := AsVertexList(g.UpEdges(current.Vertex))
		sort.Sort(byVertexName(targets))
		for _, t := range targets {
			frontier = append(frontier, &vertexAtDepth{
				Vertex: t,
				Depth:  current.Depth + 1,
			})
		}

		// Visit the current node
		if err := f(current.Vertex, current.Depth); err != nil {
			return err
		}
	}

	return nil
}
1108796
func (f *Forwarder) portForward(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) {
	f.Debugf("Port forward: %v. req headers: %v", req.URL.String(), req.Header)
	sess, err := f.getOrCreateClusterSession(*ctx)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	if err := f.setupForwardingHeaders(ctx, sess, req); err != nil {
		f.Debugf("DENIED Port forward: %v.", req.URL.String())
		return nil, trace.Wrap(err)
	}

	dialer, err := f.getDialer(*ctx, sess, req)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	onPortForward := func(addr string, success bool) {
		event := events.PortForward
		if !success {
			event = events.PortForwardFailure
		}
		f.AuditLog.EmitAuditEvent(event, events.EventFields{
			events.EventProtocol:      events.EventProtocolKube,
			events.PortForwardAddr:    addr,
			events.PortForwardSuccess: success,
			events.EventLogin:         ctx.User.GetName(),
			events.EventUser:          ctx.User.GetName(),
			events.LocalAddr:          sess.cluster.targetAddr,
			events.RemoteAddr:         req.RemoteAddr,
		})
	}

	q := req.URL.Query()
	request := portForwardRequest{
		podNamespace:       p.ByName("podNamespace"),
		podName:            p.ByName("podName"),
		ports:              q["ports"],
		context:            req.Context(),
		httpRequest:        req,
		httpResponseWriter: w,
		onPortForward:      onPortForward,
		targetDialer:       dialer,
	}
	f.Debugf("Starting %v.", request)
	err = runPortForwarding(request)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	f.Debugf("Done %v.", request)
	return nil, nil
}
737908
func (b *buffer) wordForward() (err error) {
	for end := false; ; {
		end, err = b.forward()
		if end == true || err != nil || b.data[b.pos] == 32 {
			return
		}
	}
}
503469
func (s *Server) forward(method string, info structs.RPCInfo, args interface{}, reply interface{}) (bool, error) {
	var firstCheck time.Time

	// Handle DC forwarding
	dc := info.RequestDatacenter()
	if dc != s.config.Datacenter {
		err := s.forwardDC(method, dc, args, reply)
		return true, err
	}

	// Check if we can allow a stale read, ensure our local DB is initialized
	if info.IsRead() && info.AllowStaleRead() && !s.raft.LastContact().IsZero() {
		return false, nil
	}

CHECK_LEADER:
	// Fail fast if we are in the process of leaving
	select {
	case <-s.leaveCh:
		return true, structs.ErrNoLeader
	default:
	}

	// Find the leader
	isLeader, leader := s.getLeader()

	// Handle the case we are the leader
	if isLeader {
		return false, nil
	}

	// Handle the case of a known leader
	rpcErr := structs.ErrNoLeader
	if leader != nil {
		rpcErr = s.connPool.RPC(s.config.Datacenter, leader.Addr,
			leader.Version, method, leader.UseTLS, args, reply)
		if rpcErr != nil && canRetry(info, rpcErr) {
			goto RETRY
		}
		return true, rpcErr
	}

RETRY:
	// Gate the request until there is a leader
	if firstCheck.IsZero() {
		firstCheck = time.Now()
	}
	if time.Since(firstCheck) < s.config.RPCHoldTimeout {
		jitter := lib.RandomStagger(s.config.RPCHoldTimeout / jitterFraction)
		select {
		case <-time.After(jitter):
			goto CHECK_LEADER
		case <-s.leaveCh:
		case <-s.shutdownCh:
		}
	}

	// No leader found and hold time exceeded
	return true, rpcErr
}
1278521
func (b *buffer) backward() (start bool, err error) {
	if b.pos == b.promptLen {
		return true, nil
	}
	b.pos--

	// If position is on the same line.
	if _, col := b.pos2xy(b.pos); col != 0 {
		if _, err = term.Output.Write(CursorBackward); err != nil {
			return false, outputError(err.Error())
		}
	} else {
		if _, err = term.Output.Write(CursorUp); err != nil {
			return false, outputError(err.Error())
		}
		if _, err = fmt.Fprintf(term.Output, "\033[%dC", b.columns); err != nil {
			return false, outputError(err.Error())
		}
	}
	return
}
831436
func (r *RecordCompletion) RollForward(c context.Context) (muts []tumble.Mutation, err error) {
	bdg := &model.BackDepGroup{Dependee: *r.For}
	if err = ds.Get(c, bdg); err != nil && err != ds.ErrNoSuchEntity {
		return
	}

	needProp := make([]*model.BackDep, 0, completionLimit)

	q := (ds.NewQuery("BackDep").
		Ancestor(ds.KeyForObj(c, bdg)).
		Eq("Propagated", false).
		Limit(completionLimit))

	if err = ds.GetAll(c, q, &needProp); err != nil {
		return
	}

	if len(needProp) > 0 {
		muts = make([]tumble.Mutation, len(needProp))

		for i, bdep := range needProp {
			bdep.Propagated = true
			muts[i] = &AckFwdDep{bdep.Edge()}
		}

		if len(needProp) == completionLimit {
			// Append ourself if there might be more to do!
			muts = append(muts, r)
		}

		if err = ds.Put(c, needProp); err != nil {
			return
		}
	}

	if !bdg.AttemptFinished {
		bdg.AttemptFinished = true
		if err = ds.Put(c, bdg); err != nil {
			return
		}
	}

	return
}
70487
func (p pfx) Walk(ctx context.Context, path string, fn WalkFn) error {
	return p.fs.Walk(ctx, p.addPrefix(path), func(path string) error {
		path = strings.TrimPrefix(path, p.prefix)
		return fn(path)
	})
}
332838
func (s *CacheBehavior) SetForwardedValues(v *ForwardedValues) *CacheBehavior {
	s.ForwardedValues = v
	return s
}
1149046
func closeForwarders(forwarders []protocol.Forwarder) []error {
	errs := make([]error, len(forwarders))
	wg := sync.WaitGroup{}
	wg.Add(len(forwarders))
	for index, f := range forwarders {
		go func(index int, f protocol.Forwarder, errs []error) {
			errs[index] = f.Close()
			wg.Done()
		}(index, f, errs)
	}
	wg.Wait()
	return errs
}
699365
func (set RoleSet) CheckAgentForward(login string) error {
	// check if we have permission to login and forward agent. we don't check
	// for deny rules because if you can't forward an agent if you can't login
	// in the first place.
	for _, role := range set {
		for _, l := range role.GetLogins(Allow) {
			if role.GetOptions().ForwardAgent.Value() && l == login {
				return nil
			}
		}
	}
	return trace.AccessDenied("%v can not forward agent for %v", set, login)
}
815640
func (pf *PortForwarder) forward() error {
	var err error

	listenSuccess := false
	for _, port := range pf.ports {
		err = pf.listenOnPort(&port)
		switch {
		case err == nil:
			listenSuccess = true
		default:
			glog.Warningf("Unable to listen on port %d: %v", port.Local, err)
		}
	}

	if !listenSuccess {
		return fmt.Errorf("Unable to listen on any of the requested ports: %v", pf.ports)
	}

	close(pf.Ready)

	// wait for interrupt or conn closure
	select {
	case <-pf.stopChan:
	case <-pf.streamConn.CloseChan():
		util.HandleError(errors.New("lost connection to pod"))
	}

	return nil
}
1334372
func (it *Iter) Next() bool {
	if len(it.values) == 0 && it.meta.HasMore && !it.listParams.Single {
		// determine if we're moving forward or backwards in paging
		if it.listParams.EndingBefore != nil {
			it.listParams.EndingBefore = String(listItemID(it.cur))
			it.formValues.Set(EndingBefore, *it.listParams.EndingBefore)
		} else {
			it.listParams.StartingAfter = String(listItemID(it.cur))
			it.formValues.Set(StartingAfter, *it.listParams.StartingAfter)
		}
		it.getPage()
	}
	if len(it.values) == 0 {
		return false
	}
	it.cur = it.values[0]
	it.values = it.values[1:]
	return true
}
310596
func ForwardsSkip(to int, fx func(int, func())) {
	for i := 1; i <= to; i++ {
		fx(i, func() { i++ })
	}
}
1082253
func (r *RuneBuffer) MoveToLineStart() {
	for i := r.idx; i > 0; i-- {
		if r.buf[i-1] == '\n' {
			r.idx = i
			return
		}
	}
	r.idx = 0
}
993100
func (p *gateway) Pipeline() int64 {
	var totalForwarded int64
	for _, f := range p.forwarders {
		totalForwarded += f.Pipeline()
	}
	return totalForwarded
}
548412
func NewForwarder(s *stack.Stack, handler func(*ForwarderRequest)) *Forwarder {
	return &Forwarder{
		stack:   s,
		handler: handler,
	}
}