Beispiel #1
0
func Delete(e Elem, L *list.List) bool {
	ret := false

	if L.Len() == 0 {
		return ret
	}
	back := L.Back()
	if e.GetTime() > back.Value.(Elem).GetTime() {
		return ret
	}

	el := L.Front()
Loop:
	for i := 0; el != nil; i++ {
		elt := el.Value.(Elem).GetTime()
		if elt > e.GetTime() {
			break Loop
		} else if e.IsEqual(el.Value.(Elem)) {
			L.Remove(el)
			ret = true
			break Loop
		}
		el = el.Next()
	}
	return ret
}
Beispiel #2
0
func recycler(give, get chan []byte) {
	q := new(list.List)

	for {
		//This means that we are getting more than we are giving and memory is not being
		//cleaned up properly
		if q.Len() > 1000 {
			log.Warnf("Memory Recycler Overload (high memory use): %d", q.Len())
		}

		if q.Len() == 0 {
			q.PushFront(make([]byte, defaultMemorySize))
		}

		e := q.Front()

		select {
		case s := <-give:
			q.PushFront(s[:0])

		case get <- e.Value.([]byte):
			q.Remove(e)
		}
	}
}
Beispiel #3
0
// Go through the current buffer for all sounds in the play queue, and sum
// up their values. Multiple sounds playing at the same time mathematically
// (and in the real world) works like this, but in software, we have a minimum/maximum
// value of -1.0/1.0. Thus, if the sum is outside those bounds, "clipping" will occur.
// Let's live with it for v1.
func multiplexSounds(output buffer, queue *list.List) {
	var finished []*list.Element

	multiplexed := make(buffer, bufferSize)
	for e := queue.Front(); e != nil; e = e.Next() {
		// Cast list element to queueItem.
		item := e.Value.(*queueItem)

		// Sum the magnitudes with the multiplier.
		for i, val := range item.contents[item.played] {
			multiplexed[i] += val
		}

		// If we have played all buffers, remove ourselves from the queue.
		item.played++
		if item.played >= len(item.contents) {
			finished = append(finished, e)
		}
	}
	for _, e := range finished {
		queue.Remove(e)
	}

	copy(output, multiplexed)
}
Beispiel #4
0
// Process game events. Implements screen interface.
func (c *config) processEvents(eventq *list.List) (transition int) {
	for e := eventq.Front(); e != nil; e = e.Next() {
		eventq.Remove(e)
		event := e.Value.(*event)
		switch event.id {
		case toggleOptions:
			c.activate(screenDeactive)
			if c.keysRebound {
				saver := newSaver()
				saver.persistBindings(c.keys)
				publish(eventq, keysRebound, c.keys)
			}
			return c.exitTransition
		case rebindKey:
			if rke, ok := event.data.(rebindKeyEvent); ok {
				c.rebindKey(rke.index, rke.key)
			} else {
				logf("options.processEvents: did not receive rebindKeyEvent")
			}
		case quitLevel:
			c.mp.returnToMenu()
			return chooseGame
		case rollCredits:
			c.rollCredits()
		case toggleMute:
			c.toggleMute()
		}

	}
	return configGame
}
Beispiel #5
0
func houseKeeping(get, give chan interface{},
	factory func() interface{}) {
	q := new(list.List)
	for {
		if q.Len() == 0 {
			atomic.AddInt64(&makes, 1)
			q.PushFront(queued{when: time.Now(), data: factory()})
		}

		element := q.Front()
		timeout := time.NewTimer(time.Minute)
		select {
		case b := <-give:
			timeout.Stop()
			q.PushFront(queued{when: time.Now(), data: b})

		case get <- element.Value.(queued).data:
			timeout.Stop()
			q.Remove(element)

		case <-timeout.C:
			e := q.Front()
			for e != nil {
				n := e.Next()
				if time.Since(e.Value.(queued).when) > time.Minute {
					q.Remove(e)
					e.Value = nil
				}
				e = n
			}
		}
	}
}
Beispiel #6
0
func searchRiverStates(queue *list.List) {
	current := queue.Back().Value.(itemState)

	if current.isFinal() {
		// 已经是最后状态了
		printRiver(queue)
	} else {
		if current.currentAction.direct == 0 {
			for i := 0; i < 5; i++ {
				next := current.move(backAction[i])
				//next.printState()
				if next.validate() && !isProcessedRiverState(queue, next) {
					queue.PushBack(next)
					searchRiverStates(queue)
					queue.Remove(queue.Back())
				}
			}
		} else {
			for i := 0; i < 5; i++ {
				next := current.move(goAction[i])
				//next.printState()
				if next.validate() && !isProcessedRiverState(queue, next) {
					queue.PushBack(next)
					searchRiverStates(queue)
					queue.Remove(queue.Back())
				}
			}
		}
	}
}
Beispiel #7
0
func Fetcher(queue *list.List, limit int) chan *WikiArticle {
	articles := make(chan *WikiArticle)
	go func() {
		for i := 0; i < limit; i++ {
			for queue.Front() == nil {
				runtime.Gosched()
			}
			// url := q.PopFront()
			article := queue.Front().Value.(*WikiArticle)
			queue.Remove(queue.Front())

			r, url, e := http.Get(article.url)
			if e != nil {
				println("Failed:", article.url)
				continue
			}
			println("Fetched:", article.depth, url)

			buf := bytes.NewBufferString("")
			io.Copy(buf, r.Body)
			article.content = buf.String()
			r.Body.Close()
			articles <- article
		}
		close(articles)
	}()
	return articles
}
Beispiel #8
0
func listen(mr *MapReduce, stage JobType, completed *int, jobs *list.List) {

	NumOther := 0
	switch stage {
	case Map:
		NumOther = mr.nReduce
	case Reduce:
		NumOther = mr.nMap
	}

	if jobs.Len() != 0 {
		select {
		//wait for worker responses
		case r := <-mr.responses:
			HandleResponse(r, completed, jobs)

		//wait for available if none are available
		case id := <-mr.available:
			w := mr.Workers[id]
			//pop off a job id
			j := jobs.Remove(jobs.Front()).(int)
			args := &DoJobArgs{mr.file, stage, j, NumOther}
			go SendRPC(mr, w, args, j)
		}
	} else {
		r := <-mr.responses
		HandleResponse(r, completed, jobs)
	}
}
Beispiel #9
0
// handleDonePeerMsg deals with peers that have signalled they are done.  It
// removes the peer as a candidate for syncing and in the case where it was
// the current sync peer, attempts to select a new best peer to sync from.  It
// is invoked from the syncHandler goroutine.
func (b *blockManager) handleDonePeerMsg(peers *list.List, p *peer) {
	// Remove the peer from the list of candidate peers.
	for e := peers.Front(); e != nil; e = e.Next() {
		if e.Value == p {
			peers.Remove(e)
			break
		}
	}

	log.Infof("BMGR: Lost peer %s", p)

	// Remove requested transactions from the global map so that they will
	// be fetched from elsewhere next time we get an inv.
	for k := range p.requestedTxns {
		delete(b.requestedTxns, k)
	}

	// Remove requested blocks from the global map so that they will be
	// fetched from elsewhere next time we get an inv.
	// TODO(oga) we could possibly here check which peers have these blocks
	// and request them now to speed things up a little.
	for k := range p.requestedBlocks {
		delete(b.requestedBlocks, k)
	}

	// Attempt to find a new peer to sync from if the quitting peer is the
	// sync peer.
	if b.syncPeer != nil && b.syncPeer == p {
		b.syncPeer = nil
		b.startSync(peers)
	}
}
// removes PCB element from a linked list
func listRemove(p *PCB, ls *list.List) {
	for e := ls.Front(); e != nil; e = e.Next() {
		if e.Value.(*PCB).PID == p.PID {
			ls.Remove(e)
		}
	}
}
// removes RCB element from a linked list
func rcbListRemove(r *RCB, ls *list.List) {
	for e := ls.Front(); e != nil; e = e.Next() {
		if e.Value.(*RCB).RID == r.RID {
			ls.Remove(e)
		}
	}
}
Beispiel #12
0
func (interp *Interp) EvalWords(words *list.List) string {
	var retval string

	frame := interp.stack.PeekFrame()
	words = frame.SubstituteWords(interp, words)

	new_frame := interp.stack.PushFrame()

	name := words.Remove(words.Front()).(Word).String()
	cmd, error := interp.FindCommand(name, words)

	if error != nil {
		fmt.Println(error)
		os.Exit(1)
	}

	new_frame.BindArguments(cmd, words)

	if cmd.native_body == nil {
		retval = new_frame.Eval(interp, cmd.body)
	} else {
		retval = cmd.native_body(interp, new_frame)
	}

	interp.stack.PopFrame()

	return retval
}
Beispiel #13
0
// pushMetric adds the metric to the end of the list and returns a comma separated string of the
// previous 61 entries.  We return 61 instead of 60 (an hour) because the chart on the client
// tracks deltas between these values - there is nothing to compare the first value against.
func pushMetric(history *list.List, ev expvar.Var) string {
	history.PushBack(ev.String())
	if history.Len() > 61 {
		history.Remove(history.Front())
	}
	return JoinStringList(history)
}
func (ss *storageServer) revokeLeases(leaseHolders *list.List, key string) {
	for e := leaseHolders.Front(); e != nil; e = e.Next() {
		leaseWrap := e.Value.(LeaseWrapper)
		// If lease has already expired, don't do anything
		if time.Since(leaseWrap.timeGranted).Seconds() >
			storagerpc.LeaseSeconds+storagerpc.LeaseGuardSeconds {
			leaseHolders.Remove(e)
			continue
		}
		successChan := make(chan error)
		go ss.waitForRevokeLease(leaseWrap.hostport, key, successChan)
	Loop:
		for {
			select {
			case err := <-successChan:
				if err != nil {
					fmt.Println(err)
				} else {
					break Loop
				}
			default:
				if time.Since(leaseWrap.timeGranted).Seconds() >
					storagerpc.LeaseSeconds+storagerpc.LeaseGuardSeconds {
					fmt.Println("timed out")
					break Loop
				}
				//time.Sleep(time.Second)
			}
		}
		leaseHolders.Remove(e)
	}

}
func main() {

	give := make(chan []byte)
	get := make(chan []byte)

	go func() {
		q := new(list.List)

		for {
			if q.Len() == 0 {
				q.PushFront(make([]byte, 100))
			}

			e := q.Front()

			select {
			case s := <-give:
				q.PushFront(s)

			case get <- e.Value.([]byte):
				q.Remove(e)
			}
		}
	}()

	// Gets a new buffer from the recycler.
	buffer := <-get

	// Give it back to the recycler.
	give <- buffer

	// Get the recycled buffer again.
	buffer = <-get
}
Beispiel #16
0
func (frame *Frame) BindArguments(cmd Command, words *list.List) bool {
	len := len(cmd.args)

	for i, arg := range cmd.args {
		name := arg.GetName()
		value := arg.GetValue()

		if i == (len-1) && name == "args" {
			tmp := []string{}

			for words.Len() != 0 {
				word := words.Remove(words.Front()).(Word).String()
				tmp = append(tmp, word)
			}

			value = StringToValueP(strings.Join(tmp, " "))
		} else {
			if words.Len() != 0 {
				word := Value(words.Remove(words.Front()).(Word).String())
				value = &word
			}
		}

		frame.SetValue(name, value)
	}

	return true
}
Beispiel #17
0
//add Nodes we here about in the reply to the shortList, only if that node is not in the sentList
func addResponseNodesToSL(fnodes []FoundNode, shortList *list.List, sentMap map[ID]bool, targetID ID) {
	for i := 0; i < len(fnodes); i++ {
		foundNode := &fnodes[i]
		_, inSentList := sentMap[foundNode.NodeID]
		//if the foundNode is already in sentList, dont add it to shortList
		if inSentList {
			continue
		}
		for e := shortList.Front(); e != nil; e = e.Next() {
			if e.Value.(*FoundNode).NodeID.Equals(foundNode.NodeID) {
				break
			}
			dist := e.Value.(*FoundNode).NodeID.Distance(targetID)
			foundNodeDist := foundNode.NodeID.Distance(targetID)
			//if responseNode is closer than node in ShortList, add it
			if foundNodeDist < dist {
				shortList.InsertBefore(foundNode, e)
				//keep the shortList length < Kconst
				if shortList.Len() > KConst {
					shortList.Remove(shortList.Back())
				}
				//node inserted! getout
				break
			}
		}
	}
}
func bufferRecycler(give, get chan *bytes.Buffer) {
	q := new(list.List)

	for {
		//This means that we are getting more than we are giving and memory is not being
		//cleaned up properly
		if q.Len() > 1000 {
			log.Warnf("Memory Recycler Overload (high memory use): %d", q.Len())
		}

		if q.Len() == 0 {
			q.PushFront(&bytes.Buffer{})
		}

		e := q.Front()

		select {
		case s := <-give:
			s.Reset()
			q.PushFront(s)

		case get <- e.Value.(*bytes.Buffer):
			q.Remove(e)
		}
	}
}
Beispiel #19
0
func trimToSize(l *list.List, size int) {
	if l.Len() > size {
		diff := l.Len() - size
		for i := 0; i < diff; i++ {
			l.Remove(l.Front()) // Remove the first item from the que
		}
	}
}
Beispiel #20
0
func _del(l *list.List, id HandlerID) bool {
	for e := l.Front(); e != nil; e = e.Next() {
		if e.Value.(Handler).Id() == id {
			l.Remove(e)
		}
	}
	return l.Len() == 0
}
Beispiel #21
0
// Removes the first occurrence of toRemove from the given list.
func RemoveIfPresent(fromList *list.List, toRemove interface{}) {
	for e := fromList.Front(); e != nil; e = e.Next() {
		if e.Value == toRemove {
			fromList.Remove(e)
			return
		}
	}
}
Beispiel #22
0
func removeFromActiveFlows(ls *list.List, f *Flow) {
	for e := ls.Front(); e != nil; e = e.Next() {
		if e.Value.(*Flow) == f {
			ls.Remove(e)
			break
		}
	}
}
Beispiel #23
0
func (c *client) getDataMsgFromWriteBuf(buffer *list.List) {
	for buffer.Len() > 0 && c.comm.addDataMsgToWriteSlideWindow(buffer.Front().Value.(*Message)) {
		// fmt.Println("Read Write Win Default: Send ACK")
		c.writeToServer(buffer.Front().Value.(*Message))
		buffer.Remove(buffer.Front())
		// fmt.Println("Add to Write Win")
	}
}
Beispiel #24
0
func matchYank(tokens *list.List, expectedType int) (lib.Token, bool) {
	t := tokens.Front().Value.(lib.Token)
	if t.Type == expectedType {
		tokens.Remove(tokens.Front())
		return t, true
	}
	return t, false
}
Beispiel #25
0
func removeDuplicates(bigList *list.List, littleList *list.List) {
	for l := bigList.Front(); l != nil; l = l.Next() {
		for m := littleList.Front(); m != nil; m = m.Next() {
			if l.Value.(*quadratic.Map).Isomorphic(m.Value.(*quadratic.Map)) {
				littleList.Remove(m)
			}
		}
	}
}
Beispiel #26
0
// assumes the id is only in the list once
func removeFromSorted(l *list.List, id ID) {
	for e := l.Front(); e != nil; e = e.Next() {
		c := e.Value.(Contact)
		if c.NodeID.Equals(id) {
			l.Remove(e)
			return
		}
	}
}
Beispiel #27
0
func (self *Server) removeWorker(l *list.List, sessionId int64) {
	for it := l.Front(); it != nil; it = it.Next() {
		if it.Value.(*Worker).SessionId == sessionId {
			log.Debugf("removeWorker sessionId %d", sessionId)
			l.Remove(it)
			return
		}
	}
}
Beispiel #28
0
/**
Receive message from client.
Listen and wait for content from client. the write to
client will be performed when the current user enters an input
*/
func handlePeer(peer *Peer, peerList *list.List) {
	stopConn := false
	fmt.Println("New node: ", peer.conn.RemoteAddr())

	//send current peer list
	str := peerListToStr(peerList)
	_, err := peer.conn.Write([]byte(CONTROL_MESSAGE_PREAMBLE + " " + port + " " + str)) //transmit string as byte array
	if err != nil {
		fmt.Println("Error sending reply:", err.Error())
	}

	//Listen for the peer messages
	buffer := make([]byte, 1024)

	for !stopConn {
		bytesRead, err := peer.conn.Read(buffer)
		if err != nil { //stop for loop, remove peer from list

			stopConn = true
			fmt.Println("Error in reading from connection", peer.conn.RemoteAddr())
			mutexPeerList.Lock()
			el := getListElement(*peer, peerList)
			if el != nil {
				peerList.Remove(el)
			}
			mutexPeerList.Unlock()

		} else {
			messageStr := string(buffer[0:bytesRead])

			if strings.Contains(messageStr, CONTROL_MESSAGE_PREAMBLE) {
				//pass peer itself to set actual port
				sArr := strings.Split(messageStr, " ")
				fmt.Println("port isSSSSSS: ", sArr[1])

				el := getListElement(*peer, peerList)
				if el != nil {
					p := el.Value.(*Peer)
					p.port = sArr[1]
					//peer.port = sArr[1]
					fmt.Println("setted port to", p.port)
					setPort(*peer, peerList, sArr[1])

					connectToPeers(*peer, messageStr, peerList)
					printlist(peerList)
				}
				fmt.Println(peer.ipport(), " says: ", messageStr)
			} else {
				printlist(peerList)
				fmt.Println(peer.ipport(), " says: ", messageStr)
			}
		}
	}
	fmt.Println("Closing ", peer.conn.RemoteAddr())
	peer.conn.Close()
}
Beispiel #29
0
func DeleteProtectedObject(l *list.List, name string, epoch int32) error {
	for e := l.Front(); e != nil; e = e.Next() {
		o := e.Value.(ProtectedObjectMessage)
		if *o.ProtectedObjId.ObjName == name && *o.ProtectedObjId.ObjEpoch == epoch {
			l.Remove(e)
			break
		}
	}
	return nil
}
Beispiel #30
0
// findSource tries to find corresponding Send event to ev.
func findSource(sends *list.List, ev *trace.Event) *trace.Event {
	for e := sends.Back(); e != nil; e = e.Prev() {
		send := e.Value.(*trace.Event)
		if send.Args[1] == ev.Args[1] && send.Args[0] == ev.Args[0] {
			sends.Remove(e)
			return send
		}
	}
	return nil
}