Example #1
0
// addToKillRing adds some text to the kill ring. If mode is 0 it adds it to a
// new node in the end of the kill ring, and move the current pointer to the new
// node. If mode is 1 or 2 it appends or prepends the text to the current entry
// of the killRing.
func (s *State) addToKillRing(text []rune, mode int) {
	// Don't use the same underlying array as text
	killLine := make([]rune, len(text))
	copy(killLine, text)

	// Point killRing to a newNode, procedure depends on the killring state and
	// append mode.
	if mode == 0 { // Add new node to killRing
		if s.killRing == nil { // if killring is empty, create a new one
			s.killRing = ring.New(1)
		} else if s.killRing.Len() >= KillRingMax { // if killring is "full"
			s.killRing = s.killRing.Next()
		} else { // Normal case
			s.killRing.Link(ring.New(1))
			s.killRing = s.killRing.Next()
		}
	} else {
		if s.killRing == nil { // if killring is empty, create a new one
			s.killRing = ring.New(1)
			s.killRing.Value = []rune{}
		}
		if mode == 1 { // Append to last entry
			killLine = append(s.killRing.Value.([]rune), killLine...)
		} else if mode == 2 { // Prepend to last entry
			killLine = append(killLine, s.killRing.Value.([]rune)...)
		}
	}

	// Save text in the current killring node
	s.killRing.Value = killLine
}
Example #2
0
func ThreeDRotate(op ThreeDOperation) error {
	newFaceRing := ring.New(8)
	newEdgeRing := ring.New(12)
	trx := ThreeDTransformer{
		newFaceRing, newEdgeRing}
	for _, faceColor := range op.ent[op.cubeId].faceMap[op.face] {
		trx.faceRing.Value = faceColor
		trx.faceRing = trx.faceRing.Next()
	}
	for _, edgeColorPtr := range op.ent[op.cubeId].edgeMap[op.face] {
		trx.edgeRing.Value = *edgeColorPtr
		trx.edgeRing = trx.edgeRing.Next()
	}

	trx.faceRing = trx.faceRing.Move(2 * op.direction)
	trx.edgeRing = trx.edgeRing.Move(3 * op.direction)

	for i, _ := range op.ent[op.cubeId].faceMap[op.face] {
		if v, ok := trx.faceRing.Value.(Color); ok {
			op.ent[op.cubeId].faceMap[op.face][i] = v
		}
		trx.faceRing = trx.faceRing.Next()
	}
	for i, _ := range op.ent[op.cubeId].edgeMap[op.face] {
		if v, ok := trx.edgeRing.Value.(Color); ok {
			*op.ent[op.cubeId].edgeMap[op.face][i] = v
		}
		trx.edgeRing = trx.edgeRing.Next()
	}

	return nil
}
Example #3
0
// Process values coming from ADC
func valueBuffer(d *EKReceiver) {
	last_sample := make([]time.Time, 31)

	for i := 0; i < 31; i++ {
		d.ValueBufferRaw[i] = ring.New(RAW_BUFFER_SIZE)
		d.ValueBuffer[i] = ring.New(BUFFER_SIZE)
	}
	for {
		v := <-d.buffer_chan

		//Move head forwards
		d.ValueBufferRaw[v.Channel] = d.ValueBufferRaw[v.Channel].Next()
		d.ValueBufferRaw[v.Channel].Value = ChannelData{v.Abstimestamp, v.Value} //Set value

		// FIR Calculation
		p0 := d.ValueBufferRaw[v.Channel]
		i := 0
		out := float64(0)
		for ; i < d.FIRTaps && p0.Value != nil; i++ {
			out += p0.Value.(ChannelData).Value
			p0 = p0.Prev()
		}
		out = out / float64(i)
		if v.Abstimestamp.Sub(last_sample[v.Channel]) >= d.SampleTime {
			d.ValueBuffer[v.Channel] = d.ValueBuffer[v.Channel].Next()
			d.ValueBuffer[v.Channel].Value = ChannelData{v.Abstimestamp, out}
			last_sample[v.Channel] = v.Abstimestamp
		}
	}
}
Example #4
0
// Return a channel which serves as a sending proxy to `out`.
// Use a goroutine to receive values from `out` and store them
// in an expanding buffer, so that sending to `out` never blocks.
// See this discussion:
// <http://rogpeppe.wordpress.com/2010/02/10/unlimited-buffering-with-low-overhead>
func sendproxy(out chan<- uint64) chan<- uint64 {
	proxy := make(chan uint64, 1024)
	go func() {
		n := 1024 // the allocated size of the circular queue
		first := ring.New(n)
		last := first
		var c chan<- uint64
		var e uint64
		for {
			c = out
			if first == last {
				// buffer empty: disable output
				c = nil
			} else {
				e = first.Value.(uint64)
			}
			select {
			case e = <-proxy:
				last.Value = e
				if last.Next() == first {
					// buffer full: expand it
					last.Link(ring.New(n))
					n *= 2
				}
				last = last.Next()
			case c <- e:
				first = first.Next()
			}
		}
	}()
	return proxy
}
Example #5
0
func main() {
	r := ring.New(5)
	r.Value = 1
	r.Next().Value = 2
	r.Prev().Value = 5

	plus := ring.New(1)
	plus.Value = 10
	r.Link(plus)
	fmt.Println("len: ", r.Len())
	r.Do(printe)
}
Example #6
0
func init() {

	testBackend.groups["alt.test"] = &groupStorage{
		group: &nntp.Group{"alt.test", "A test.",
			0, 0, 0, nntp.PostingNotPermitted},
		articles: ring.New(maxArticles),
	}

	testBackend.groups["misc.test"] = &groupStorage{
		group: &nntp.Group{"misc.test", "More testing.",
			0, 0, 0, nntp.PostingPermitted},
		articles: ring.New(maxArticles),
	}

}
Example #7
0
// Create a new simple moving percentile expvar.Var. It will be
// published under `name` and maintain `size` values for
// calculating the percentile.
//
// percentile must be between 0 and 1
//
// An empty name will cause it to not be published
func NewSimpleMovingPercentile(name string, percentile float64, size int) *SimpleMovingStat {
	sm := new(SimpleMovingStat)
	sm.size = size
	sm.mutex = new(sync.Mutex)
	sm.values = ring.New(size)

	sm.calculate = func(s *SimpleMovingStat) float64 {
		ary := make([]float64, 0)
		s.values.Do(func(val interface{}) {
			if val != nil {
				ary = append(ary, val.(float64))
			}
		})
		length := len(ary)
		if length == 0 {
			return 0.0
		}
		sort.Float64s(ary)
		mid := int(float64(len(ary)) * percentile)
		return ary[mid]
	}

	if name != "" {
		expvar.Publish(name, sm)
	}
	return sm

}
Example #8
0
func main() {
	sourceAddress := ":3000"

	ports := []string{
		":3333",
		":3334",
	}
	hostRing := ring.New(len(ports))
	for _, port := range ports {
		url, _ := url.Parse("http://127.0.0.1" + port)
		hostRing.Value = url
		hostRing = hostRing.Next()
	}

	mutex := sync.Mutex{}
	director := func(request *http.Request) {
		mutex.Lock()
		defer mutex.Unlock()
		request.URL.Scheme = "http"
		request.URL.Host = hostRing.Value.(*url.URL).Host
		hostRing = hostRing.Next()
		fmt.Println(hostRing)
	}
	proxy := &httputil.ReverseProxy{Director: director}
	server := http.Server{
		Addr:    sourceAddress,
		Handler: proxy,
	}
	server.ListenAndServe()
}
Example #9
0
func testRing() {
	fmt.Println("testRing -----------------------------------------------------")
	// 循环列表
	size := 10
	// 声明和初始化
	r := ring.New(size)

	fmt.Println("len=", r.Len(), ",r=", r, ",r.Prev()=", r.Prev())

	for num, e := 0, r.Prev(); e != nil; e = e.Next() {
		e.Value = num
		num++
		if num >= size {
			break
		}
	}
	for num, e := 0, r.Prev(); e != nil; e = e.Next() {
		fmt.Println("num =", num, ",e.value=", e.Value)
		num++
		if num >= size+1 {
			break
		}
	}

}
Example #10
0
//NewLoadBalancer creates a new instance of a Round Robin load balancer
func (rrf *RoundRobinLoadBalancerFactory) NewLoadBalancer(backendName, caCertPath string, servers []config.ServerConfig) (LoadBalancer, error) {
	var rrlb RoundRobinLoadBalancer

	if backendName == "" {
		return nil, fmt.Errorf("Expected non-empty backend name")
	}

	if len(servers) == 0 {
		return nil, fmt.Errorf("Expected at least one server in servers argument")
	}

	rrlb.backend = backendName
	rrlb.servers = ring.New(len(servers))

	for _, s := range servers {

		lbEndpoint := new(LoadBalancerEndpoint)
		lbEndpoint.Address = fmt.Sprintf("%s:%d", s.Address, s.Port)
		metrics.SetGauge([]string{"endpoint", lbEndpoint.Address}, 1.0)
		lbEndpoint.PingURI = s.PingURI
		lbEndpoint.Up = true
		lbEndpoint.CACertPath = caCertPath

		log.Info("Spawing health check for address ", lbEndpoint.Address)
		healthCheckFunction := MakeHealthCheck(lbEndpoint, s, true)
		go healthCheckFunction()

		log.Info("Adding server with address ", lbEndpoint.Address)
		rrlb.servers.Value = lbEndpoint
		rrlb.servers = rrlb.servers.Next()
	}

	return &rrlb, nil
}
Example #11
0
//初始化redis连接池
func initRedis(confs []*config.Redis) {
	ids = ring.New(len(confs))
	for _, conf := range confs {
		if !conf.Enable {
			continue
		}
		id := &IdAvailable{Id: conf.Id}
		ids.Value = id
		spec := redis.DefaultSpec().Db(conf.DB).Password(conf.Password).Host(conf.Host).Port(conf.Port)
		//log.Info("redis init at ", spec)
		c := make(chan *RedisClient, PoolSize)
		for j := 0; j < PoolSize; j++ {
			if client, err := redis.NewSynchClientWithSpec(spec); err != nil {
				goto err
			} else {
				c <- &RedisClient{Id: conf.Id, Redis: client}
			}
		}
		pool[conf.Id] = c
		id.IsAvailable = true
		ids = ids.Next()
	err: //如果创建CLIENT时出错,就抛弃这个台机器
		errRedis[conf.Id] = conf
		ids = ids.Next()
	}
}
Example #12
0
func main() {
	// Creates a circular list for round-robin HTTP roundtrip.
	hosts := []string{
		":4000",
		":5000",
		":6000",
	}
	hostRing := ring.New(len(hosts))
	for _, host := range hosts {
		hostRing.Value = host
		hostRing = hostRing.Next()
	}

	// Locks by mutex because hostConverter will be executed in parallel.
	mutex := sync.Mutex{}
	hostConverter := func(originalHost string) string {
		mutex.Lock()
		defer mutex.Unlock()
		host := hostRing.Value.(string)
		hostRing = hostRing.Next()
		return host
	}

	// Runs a reverse-proxy server on http://localhost:3000/
	proxy := entoverse.NewProxyWithHostConverter(hostConverter)
	http.ListenAndServe(":3000", proxy)
}
Example #13
0
func TestDo(t *testing.T) {
	r := ring.New(5) // 5個の要素

	if r.Len() != 5 {
		t.Errorf("length = %d", r.Len())
	}

	i := 0
	for initialValue := r.Next(); initialValue != r; initialValue = initialValue.Next() {
		value := HogeValue(i)
		initialValue.Value = &value
		i++
	}

	for p := r.Next(); p != r; p = p.Next() {
		t.Logf("value = %d", *p.Value.(*HogeValue))
	}

	r.Do(func(v interface{}) {
		hoge, ok := v.(*HogeValue)
		if ok {
			hoge.Add(1)
		}
	})

	i = 1
	for p := r.Next(); p != r; p = p.Next() {
		check := p.Value.(*HogeValue)
		if int(*check) != i {
			t.Errorf("check = %d, i = %d", *check, i)
		}
		i++
	}
}
Example #14
0
func main() {
	myArr := string([]rune{
		0x49, 0x53, 0x54, 0x53, 0x2d, 0x59, 0x41, 0x52,
		0x41, 0x2d, 0x45, 0x4e, 0x55, 0x52, 0x0a,
	})
	myStr := "Haha!!!!  Strings won't find this flag. You need to use something else!!"
	promiseRing := ring.New(15)

	result := make([]byte, len(myStr))
	restore := result

	fmt.Println(myStr)

	for i := 0; i < promiseRing.Len(); i++ {
		result = restore
		for j := 0; j < len(myStr); j++ {
			result[j] = myStr[j] ^ myArr[i]
		}
		promiseRing.Value = b64.StdEncoding.EncodeToString(result)
		promiseRing = promiseRing.Next()
	}

	fmt.Println("============")
	promiseRing.Do(func(x interface{}) {
		fmt.Print(x, "\n============\n")
	})

}
Example #15
0
func main() {
	//创建10个元素的闭环
	r := ring.New(10)

	//给闭环中的元素赋值
	for i := 1; i <= r.Len(); i++ {
		r.Value = i
		r = r.Next()
	}

	//循环打印闭环中的元素值
	r.Do(
		func(p interface{}) {
			println(p.(int))
		})

	//获得当前元素之后的第5个元素
	r5 := r.Move(5)
	fmt.Println(r5.Value)
	fmt.Println(r.Value)

	//链接当前元素r与r5,相当于删除了r与r5之间的元素
	r1 := r.Link(r5)
	fmt.Println(r1.Value)
	fmt.Println(r.Value)
}
Example #16
0
func NewInMemoryRegistry() Registry {
	return &inMemoryRegistry{
		taskRegistry:  make(map[string]*T),
		tasksFinished: ring.New(defaultFinishedTasksSize),
		podToTask:     make(map[string]string),
	}
}
Example #17
0
//ring实现了环形链表的操作。
func Test_Ring() {
	r := ring.New(10)
	for i := 1; i <= r.Len(); i++ {
		r.Value = i
		r = r.Next()
	}

	for i := 1; i <= r.Len(); i++ {
		fmt.Println(r.Value)
		r = r.Next()
	}

	r = r.Move(6)                      //移动到6
	fmt.Println("move to 6:", r.Value) //6
	deletedLink := r.Unlink(19)        //移除19%10=9个元素,返回删除以后的数据

	fmt.Println("======delete======")
	for i := 0; i < deletedLink.Len(); i++ {
		fmt.Println(deletedLink.Value)
		deletedLink = deletedLink.Next()
	}

	fmt.Println("=====last======")
	fmt.Println(r.Len())           //10-9=1
	fmt.Println(deletedLink.Len()) //9
	fmt.Println(r)
}
Example #18
0
File: etcd.go Project: noonat/pruxy
// load reloads the proxy config from etcd
func (p *PruxyEtcd) load() error {
	response, err := p.client.Get(p.watchPrefix, false, true)
	if err != nil {
		log.Println("err:", err)
		return err
	}

	p.mu.Lock()
	defer p.mu.Unlock()

	// reinit host configs
	p.Hosts = map[string]*ring.Ring{}
	for _, hostNode := range response.Node.Nodes {
		host := strings.Split(hostNode.Key, "/")[2]
		p.Hosts[host] = ring.New(len(hostNode.Nodes))
		for _, upstreamNode := range hostNode.Nodes {
			upstream := strings.Split(upstreamNode.Key, "/")[3]
			if upstream != "" {
				p.Hosts[host].Value = upstream
				p.Hosts[host] = p.Hosts[host].Next()
				log.Printf("added upstream %s -> %s", host, upstream)
			}
		}
	}
	return nil
}
Example #19
0
func NewMainMenu(mapDir string, w, h int) (m *MainMenu) {
	file, err := os.Open(mapDir)
	defer file.Close()
	if err != nil {
		panic(err)
	}

	fis, err := file.Readdir(0)
	if err != nil {
		panic(err)
	}

	var maps *ring.Ring
	for _, fi := range fis {
		if strings.HasSuffix(fi.Name(), ".txt") {
			name := fi.Name()
			mapName := name[:len(name)-4]
			r := ring.New(1)
			r.Value = mapName
			if maps != nil {
				maps.Link(r)
			} else {
				maps = r
			}
		}
	}
	return &MainMenu{maps, time.Now(), w, h}
}
Example #20
0
File: pingd.go Project: hizel/pingd
func Post(w rest.ResponseWriter, r *rest.Request) {
	host := Host{}
	err := r.DecodeJsonPayload(&host)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	if host.Id == "" {
		rest.Error(w, "id required", 400)
		return
	}
	if host.Address == "" {
		rest.Error(w, "address required", 400)
		return
	}
	ra, err := net.ResolveIPAddr("ip4:icmp", host.Address)
	if err != nil {
		rest.Error(w, err.Error(), 400)
		return
	}
	lock.Lock()
	q := make(chan bool, 1) // chan for stop ping
	store[host.Id] = &HostStore{
		host,
		time.Now(),
		0.0, 0.0, 0.0, 0.0,
		0,
		ring.New(DefCircleLen),
		q}
	go ping(host.Id, ra, time.Second*DefRTT, q, &lock, store)
	lock.Unlock()
	w.WriteJson(&host)
}
Example #21
0
func (e *escalator) escalate(err error) {
	e.queued = e.queued.Next()
	e.queued.Value = notification{time.Now(), hostname, err}
	if time.Since(e.lastEscalation) > e.escalationInterval {
		// Merge all queued notifications.
		// Optimization todo: cache msg.
		msg := make([]byte, 0, 200)
		e.queued.Do(func(v interface{}) {
			if notif, ok := v.(notification); ok {
				msg = append(msg, []byte(notif.String())...)
			}

		})
		for _, n := range e.Notifiers {
			if err := n.notify(msg); err != nil {
				log.Println("notification error:", err)
				log.Printf("Would have written: %q", string(msg))
			} else {
				e.queued = ring.New(maxNotificationLines)
				e.lastEscalation = time.Now()
				log.Println("escalation successful")
				return
			}
		}
		log.Println("IMPORTANT: all escalation methods failed.")
	}
}
Example #22
0
// nextRandomMember returns random member, selected from round robin of all
// members.
//
// Because assigning randomly may not always produce best result, use round
// robin of random order members to get assignment user.
func nextRandomMember() (User, error) {
	membersRMu.Lock()
	defer membersRMu.Unlock()

	if membersRing == nil {
		members, err := listMembers()
		if err != nil {
			return User{}, fmt.Errorf("cannot list memebers: %s", err)
		}
		membersRing = ring.New(len(members))
		for key := range members {
			membersRing.Value = &members[key]
			membersRing = membersRing.Next()
		}

		// skip random number of users, to not always start from the same place
		skip, _ := rand.Int(rand.Reader, big.NewInt(int64(len(members))))
		for i := int64(0); i < skip.Int64(); i++ {
			membersRing = membersRing.Next()
		}
	}

	member := membersRing.Value.(*User)
	membersRing = membersRing.Next()
	return *member, nil
}
Example #23
0
// flushBuffer expects the logging lock to be held, and does not take the lock.
// should call done on the wait group when the buffer is flushed.
// does not 1 to the waitgroup.
func (logger *LoggerImpl) flushBuffer(wait *sync.WaitGroup) {
	if logger.buffer != nil {
		now := time.Now()
		oldBuffer := logger.buffer
		logger.buffer = ring.New(oldBuffer.Len())

		go func() {
			oldBuffer.Do(func(x interface{}) {

				if x == nil {
					return
				}

				record := x.(*LogRecord)
				record.Time = now

				atomic.AddUint64(&logged, 1)
				incomingChannel <- record
			})

			wait.Done()
		}()
	} else {
		wait.Done()
	}
}
Example #24
0
func (s *CJKBigramFilter) Filter(input analysis.TokenStream) analysis.TokenStream {
	r := ring.New(2)
	itemsInRing := 0

	rv := make(analysis.TokenStream, 0, len(input))

	for _, token := range input {
		if token.Type == analysis.Ideographic {
			if itemsInRing > 0 {
				// if items already buffered
				// check to see if this is aligned
				curr := r.Value.(*analysis.Token)
				if token.Start-curr.End != 0 {
					// not aligned flush
					flushToken := s.flush(r, &itemsInRing)
					if flushToken != nil {
						rv = append(rv, flushToken)
					}
				}
			}
			// now we can add this token to the buffer
			r = r.Next()
			r.Value = token
			if itemsInRing < 2 {
				itemsInRing++
			}
			if itemsInRing > 1 && s.outputUnigram {
				unigram := s.buildUnigram(r, &itemsInRing)
				if unigram != nil {
					rv = append(rv, unigram)
				}
			}
			bigramToken := s.outputBigram(r, &itemsInRing)
			if bigramToken != nil {
				rv = append(rv, bigramToken)
			}
		} else {
			// flush anything already buffered
			flushToken := s.flush(r, &itemsInRing)
			if flushToken != nil {
				rv = append(rv, flushToken)
			}
			// output this token as is
			rv = append(rv, token)
		}
	}

	// deal with possible trailing unigram
	if itemsInRing == 1 || s.outputUnigram {
		if itemsInRing == 2 {
			r = r.Next()
		}
		unigram := s.buildUnigram(r, &itemsInRing)
		if unigram != nil {
			rv = append(rv, unigram)
		}
	}
	return rv
}
Example #25
0
func ringXmpl() {
	fmt.Println("Teste Ringe")
	myRing := ring.New(size)
	// "Anfang" merken
	anfang := myRing
	// einige Elemente einfügen
	myRing.Value = element{"a", 1}
	myRing = myRing.Next()
	myRing.Value = element{"b", 2}
	myRing = myRing.Next()
	myRing.Value = element{"c", 3}
	myRing = myRing.Next()
	myRing.Value = element{"d", 4}
	myRing = myRing.Next()
	myRing.Value = element{"e", 5}
	myRing = myRing.Next()
	myRing.Value = element{"f", 6}
	myRing = myRing.Next()
	myRing.Value = element{"g", 7}
	myRing = myRing.Next()
	myRing.Value = element{"h", 8}
	myRing = myRing.Next()
	myRing.Value = element{"i", 9}
	myRing = myRing.Next()
	myRing.Value = element{"j", 10}
	myRing = myRing.Next()
	myRing.Value = element{"k", 11}
	myRing = myRing.Next()
	myRing.Value = element{"l", 12}
	myRing = myRing.Next()

	// Mittels Iterator Elemente ausgeben
	// func (r *Ring) Do(f func(interface{}))
	myRing.Do(elementPrinter())

	// an den Anfang gehen und dahinter
	// einen Subring mit zwei Elementen rausschneiden
	fmt.Println("Schneide Subring")
	myRing = anfang
	subring := myRing.Unlink(2)

	// Ringe nochmal ausgeben
	fmt.Println("Subring ist jetzt")
	myRing.Do(elementPrinter())

	fmt.Println("Ring ist jetzt")
	myRing.Do(elementPrinter())
	// subring hinter e wieder einfügen
	fmt.Println("Vereine Ringe")
	myRing = anfang
	myRing = myRing.Move(2)
	myRing.Link(subring)

	// Und wieder die Elemente ausgeben
	myRing = anfang
	fmt.Println("Ring ist jetzt")
	myRing.Do(elementPrinter())

}
Example #26
0
func NewRoundRobin(strs map[string]string) Backends {
	r := ring.New(len(strs))
	for key, s := range strs {
		r.Value = &backend{key, s}
		r = r.Next()
	}
	return &RoundRobin{r: r}
}
Example #27
0
func RingNewInt64(size int) *ring.Ring {
	r := ring.New(size + 1)
	for i := 0; i < r.Len(); i++ {
		r.Value = int64(0)
		r = r.Next()
	}
	return r
}
Example #28
0
func getRing(size int) (r *ring.Ring) {
	r = ring.New(size)
	for i := 0; i < size; i++ {
		r.Value = WindowData(i)
		r = r.Prev()
	}
	return
}
Example #29
0
// expects the lock.
func (logger *LoggerImpl) setBufferLengthImpl(length int) {

	if length == 0 {
		logger.buffer = nil
	} else if length != logger.buffer.Len() {
		logger.buffer = ring.New(length)
	}
}
Example #30
0
func init() {
	// init the global log_chan and its reader
	log_chan = make(chan LogInfo)
	request_chan = make(chan (chan<- []byte))
	maxRingSize = 1000
	logs = ring.New(maxRingSize)
	go loggerRoutine()
}