// crawl over the queue entries to find the head and tail
960755
func getQueueHeadTail(ctx context.Context, name string, datastore datastore.Datastore) (uint64, uint64, error) {
	q := query.Query{}
	results, err := datastore.Query(q)
	if err != nil {
		return 0, 0, err
	}

	var tail uint64
	var head uint64 = math.MaxUint64
	for entry := range results.Next() {
		trimmed := strings.TrimPrefix(entry.Key, "/")
		id, err := strconv.ParseUint(trimmed, 10, 64)
		if err != nil {
			return 0, 0, err
		}

		if id < head {
			head = id
		}

		if (id + 1) > tail {
			tail = (id + 1)
		}
	}
	if err := results.Close(); err != nil {
		return 0, 0, err
	}
	if head == math.MaxUint64 {
		head = 0
	}

	return head, tail, nil
}
298794
func (c *client) Queue() ([]*Stage, error) {
	var out []*Stage
	uri := fmt.Sprintf(pathQueue, c.addr)
	err := c.get(uri, &out)
	return out, err
}
463859
func (t *Terminal) queue(data []rune) {
	t.outBuf = append(t.outBuf, []byte(string(data))...)
}
312355
func (q *UniqueQueue) Head() (TimedValue, bool) {
	q.lock.Lock()
	defer q.lock.Unlock()
	if len(q.queue) == 0 {
		return TimedValue{}, false
	}
	result := q.queue[0]
	return *result, true
}
802699
func Tail(err error) error {
	if tail, ok := err.(errLinkedList); ok {
		return tail.Tail()
	}
	if causable, ok := err.(causableError); ok {
		return causable.Cause()
	}
	if hasTail, ok := err.(hasInner); ok {
		i := hasTail.GetInner()
		if i == err || i == nil {
			return err
		}
		return Tail(i)
	}
	return err
}
137206
func Head(pattern web.PatternType, handler web.HandlerType) {
	DefaultMux.Head(pattern, handler)
}
83462
func (c *Client) Head() *Request {
	req := c.Request()
	req.Method("HEAD")
	return req
}
348398
func (r *marathonClient) Queue() (*Queue, error) {
	var queue *Queue
	err := r.apiGet(marathonAPIQueue, nil, &queue)
	if err != nil {
		return nil, err
	}
	return queue, nil
}
1111040
func (q *NodeQueue) Enqueue(n graph.Node) {
	if len(q.data) == cap(q.data) && q.head > 0 {
		l := q.Len()
		copy(q.data, q.data[q.head:])
		q.head = 0
		q.data = append(q.data[:l], n)
	} else {
		q.data = append(q.data, n)
	}
}
117710
func (r *Route) HeadFunc(f http.HandlerFunc) *Route {
	return r.Head(http.HandlerFunc(f))
}
522958
func (trc *TumblrRestClient) Queue(blogname string, options map[string]string) DraftsResponse {
	requestUrl := fmt.Sprintf("/v2/blog/%s/posts/queue", blogname)
	data := trc.request.Get(requestUrl, options)
	var result DraftsResponse
	json.Unmarshal(data.Response, &result)
	return result
}
357863
func (s *SliceQueue) Dequeue() (interface{}, error) {
	if s.IsEmpty() {
		return nil, errors.New("unable to dequeue element, queue is empty")
	}

	item := s.backing[0]
	// https://github.com/golang/go/wiki/SliceTricks
	s.backing = append(s.backing[:0], s.backing[1:]...)
	s.size--
	return item, nil
}
749694
func (c *Collector) Head(URL string) error {
	return c.scrape(URL, "HEAD", 1, nil, nil, nil, false)
}
376254
func (s *Storage) Tail(c context.Context, project types.ProjectName, path types.StreamPath) (*storage.Entry, error) {
	c = prepareContext(c)
	c = log.SetFields(c, log.Fields{
		"project": project,
		"path":    path,
	})
	iface := s.getIface()

	// Load the "last tail index" from cache. If we have no cache, start at 0.
	var startIdx int64
	if s.Cache != nil {
		startIdx = getLastTailIndex(c, s.Cache, project, path)
	}

	// Iterate through all log keys in the stream. Record the latest contiguous
	// one.
	var (
		rk        = newRowKey(string(project), string(path), startIdx, 0)
		latest    *rowKey
		nextIndex = startIdx
	)
	err := iface.getLogData(c, rk, 0, true, func(rk *rowKey, data []byte) error {
		// If this record is non-contiguous, we're done iterating.
		if rk.firstIndex() != nextIndex {
			return errStop
		}

		latest, nextIndex = rk, rk.index+1
		return nil
	})
	if err != nil && err != errStop {
		log.Fields{
			log.ErrorKey: err,
			"table":      s.LogTable,
		}.Errorf(c, "Failed to scan for tail.")
	}

	if latest == nil {
		// No rows for the specified stream.
		return nil, storage.ErrDoesNotExist
	}

	// Update our cache if the tail index has changed.
	if s.Cache != nil && startIdx != latest.index {
		// We cache the first index in the row so that subsequent cached fetches
		// have the correct "startIdx" expectations.
		putLastTailIndex(c, s.Cache, project, path, latest.firstIndex())
	}

	// Fetch the latest row's data.
	var d []byte
	err = iface.getLogData(c, latest, 1, false, func(rk *rowKey, data []byte) error {
		records, err := recordio.Split(data)
		if err != nil || len(records) == 0 {
			return storage.ErrBadData
		}
		d = records[len(records)-1]
		return errStop
	})
	if err != nil && err != errStop {
		log.Fields{
			log.ErrorKey: err,
			"table":      s.LogTable,
		}.Errorf(c, "Failed to retrieve tail row.")
	}

	return storage.MakeEntry(d, types.MessageIndex(latest.index)), nil
}
706254
func (q *Queue) nextEntry() (datastore.Key, cid.Cid) {
	for {
		if q.head >= q.tail {
			return datastore.Key{}, cid.Undef
		}

		key := q.queueKey(q.head)
		value, err := q.ds.Get(key)

		if err == datastore.ErrNotFound {
			log.Warningf("Error missing entry in queue: %s", key)
			q.head++ // move on
			continue
		} else if err != nil {
			log.Warningf("Error fetching from queue: %s", err)
			continue
		}

		c, err := cid.Parse(value)
		if err != nil {
			log.Warningf("Error marshalling Cid from queue: ", err)
			q.head++
			err = q.ds.Delete(key)
			continue
		}

		return key, c
	}
}
1190007
func (p *simpleResourcePool) queueIdleHandles(handle interface{}) {
	var toClose []*idleHandle
	defer func() {
		// NOTE: Must keep the closure around to late bind the toClose slice.
		p.closeHandles(toClose)
	}()

	now := p.options.getCurrentTime()
	var keepUntil *time.Time
	if p.options.MaxIdleTime != nil {
		// NOTE: Assign to temp variable first to work around compiler bug
		x := now.Add(*p.options.MaxIdleTime)
		keepUntil = &x
	}

	p.mutex.Lock()
	defer p.mutex.Unlock()

	if p.isLameDuck {
		toClose = []*idleHandle{
			{handle: handle},
		}
		return
	}

	p.idleHandles = append(
		p.idleHandles,
		&idleHandle{
			handle:    handle,
			keepUntil: keepUntil,
		})

	nIdleHandles := uint32(len(p.idleHandles))
	if nIdleHandles > p.options.MaxIdleHandles {
		handlesToClose := nIdleHandles - p.options.MaxIdleHandles
		toClose = p.idleHandles[0:handlesToClose]
		p.idleHandles = p.idleHandles[handlesToClose:nIdleHandles]
	}
}
788062
func (b *BackgroundEphemeralPurger) queuePurges(ctx context.Context) bool {
	defer b.Trace(ctx, func() error { return nil }, "queuePurges")()
	b.queueLock.Lock()
	defer b.queueLock.Unlock()

	i := 0
	// Peek into the queue for any expired convs
	for _, item := range b.pq.queue {
		purgeInfo := item.purgeInfo
		now := b.clock.Now()
		nextPurgeTime := purgeInfo.NextPurgeTime.Time()
		if nextPurgeTime.Before(now) || nextPurgeTime.Equal(now) {
			b.addPurgeToConvLoaderLocked(ctx, purgeInfo)
			// Don't spam out to the convloader
			if i > 0 {
				b.Debug(ctx, "queuePurges sleeping for %v", b.delay)
				b.clock.Sleep(b.delay)
			}
			i++
		} else {
			break
		}
	}
	// Maintain the queue and pop off any items we just sent off for purging
	for i > 0 {
		heap.Pop(b.pq)
		i--
	}

	nextItem := b.pq.Peek()
	if nextItem == nil {
		return true
	}
	// Reset our time for the next min item of the queue.
	b.resetTimer(ctx, nextItem.purgeInfo)
	return false
}