示例#1
0
// parseGroups is used to parse a list of group states.
func parseGroups(lines []string) ([]Group, os.Error) {
	var res vector.Vector
	for _, line := range lines {
		ss := strings.Split(strings.TrimSpace(line), " ", 4)
		if len(ss) < 4 {
			return nil, ProtocolError("short group info line: " + line)
		}
		high, err := strconv.Atoi(ss[1])
		if err != nil {
			return nil, ProtocolError("bad number in line: " + line)
		}
		low, err := strconv.Atoi(ss[2])
		if err != nil {
			return nil, ProtocolError("bad number in line: " + line)
		}
		res.Push(&Group{ss[0], high, low, ss[3]})
	}
	realres := make([]Group, res.Len())
	i := 0
	for v := range res.Iter() {
		realres[i] = *v.(*Group)
		i++
	}
	return realres, nil
}
示例#2
0
func CountColor(pngR io.Reader) int {
	/* modify here */
	// uniq := new (vector.Vector[uint32])
	var colorVector vector.Vector
	var rVector vector.IntVector
	var gVector vector.IntVector
	var bVector vector.IntVector
	im, _ := png.Decode(pngR)
	for y := 0; y < im.Bounds().Dy(); y++ {
		for x := 0; x < im.Bounds().Dx(); x++ {
			color := im.At(x, y)
			unique := true
			r, g, b, _ := color.RGBA()
			for i := 0; i < colorVector.Len(); i++ {
				if r == uint32(rVector.At(i)) &&
					g == uint32(gVector.At(i)) &&
					b == uint32(bVector.At(i)) {
					unique = false
				}
			}
			if unique == true {
				colorVector.Push(color)
				rVector.Push(int(r))
				gVector.Push(int(g))
				bVector.Push(int(b))
			}
		}
	}
	return colorVector.Len()
}
示例#3
0
func populateServer(serv *server) []sfs.ReplicateChunkArgs {
	str := fmt.Sprintf("%s:%d", serv.addr.IP.String(), serv.addr.Port)
	log.Printf("master: PopulateServer: populating %s\n", str)
	log.Printf("master: PopulateServer: server heap state:\n%s\n", sHeap.printPresent())

	if len(chunks) == 0 {
		return nil
	}

	thisVec := new(vector.Vector)
	for _, chunk := range chunks {
		//log.Printf("master: PopulateServer: examining chunk %+v, nservers %d\n", *chunk, chunk.servers.Len())
		if chunk.servers.Len() < sfs.NREPLICAS {

			//populate chunk location list
			chunklist := make([]net.TCPAddr, chunk.servers.Len())
			for cnt1 := 0; cnt1 < chunk.servers.Len(); cnt1++ {
				chunklist[cnt1] = chunk.servers.At(cnt1).(*server).addr
			}

			//send rpc call off
			thisVec.Push(sfs.ReplicateChunkArgs{chunk.chunkID, chunklist})
		}
	}

	cnt := thisVec.Len()

	thisSlice := make([]sfs.ReplicateChunkArgs, cnt)
	for i := 0; i < cnt; i++ {
		thisSlice[i] = thisVec.Pop().(sfs.ReplicateChunkArgs) //horribly inefficient but what can you do...
	}

	return thisSlice
}
示例#4
0
func findRand(t *testing.T, conn *db.Connection, ch chan *vector.Vector) {
	stmt, sErr := conn.Prepare(
		"SELECT * FROM t WHERE i != ? ORDER BY RAND()")
	if sErr != nil {
		error(t, sErr, "Couldn't prepare")
	}

	rs, cErr := conn.Execute(stmt, rand.Int())
	if cErr != nil {
		error(t, cErr, "Couldn't select")
	}

	vout := new(vector.Vector)
	for res := range rs.Iter() {
		if res.Error() != nil {
			error(t, res.Error(), "Couldn't fetch")
		}
		vout.Push(res.Data())
	}

	if vout.Len() != len(tableT) {
		t.Error("Invalid length")
	}

	stmt.Close()
	ch <- vout
}
示例#5
0
func test1() {
	var a [1000]*S
	for i := 0; i < len(a); i++ {
		a[i] = new(S).Init(i)
	}

	v := new(vector.Vector)
	for i := 0; i < len(a); i++ {
		v.Insert(0, a[i])
		if v.Len() != i+1 {
			panic("len = ", v.Len(), "\n")
		}
	}

	for i := 0; i < v.Len(); i++ {
		x := v.At(i).(*S)
		if x.val != v.Len()-i-1 {
			panic("expected ", i, ", found ", x.val, "\n")
		}
	}

	for v.Len() > 10 {
		v.Delete(10)
	}
}
示例#6
0
func makeStmtList(list *vector.Vector) []ast.Stmt {
	stats := make([]ast.Stmt, list.Len())
	for i := 0; i < list.Len(); i++ {
		stats[i] = list.At(i).(ast.Stmt)
	}
	return stats
}
示例#7
0
文件: classic.go 项目: lye/go-db
// Fetch all remaining results. If we get no results at
// all, an error will be returned; otherwise it probably
// still occurred but will be hidden.
func ClassicFetchAll(rs ClassicResultSet) (data [][]interface{}, error os.Error) {
	var v vector.Vector
	var d interface{}
	var e os.Error

	for rs.More() {
		r := rs.Fetch()
		d = r.Data()
		if d != nil {
			v.Push(d)
		}
		e = r.Error()
		if e != nil {
			break
		}
	}

	l := v.Len()

	if l > 0 {
		// TODO: how can this be done better?
		data = make([][]interface{}, l)
		for i := 0; i < l; i++ {
			data[i] = v.At(i).([]interface{})
		}
	} else {
		// no results at all, return the error
		error = e
	}

	return
}
示例#8
0
// Next will chose a random point to put a piece.
func (ap *RandomPlayer) Next(m *match.Match) *match.Response {
	color := ap.teban.Color()
	candidates := new(vector.Vector)
	size := m.Board.Size()
	for y := 1; y <= size; y++ {
		for x := 1; x <= size; x++ {
			if m.Board.CanPutAt(color, x, y, m.History) {
				if !m.Board.IsEye(color, x, y) {
					candidates.Push(&point.Point{x, y})
				}
			}
		}
	}

	if candidates.Len() != 0 {
		bs := make([]byte, 1)
		_, err := rand.Read(bs)
		if err == nil {
			p := candidates.At(int(bs[0]) % candidates.Len()).(*point.Point)
			ts, resp := m.Board.PutAt(color, p.X(), p.Y(), m.History)
			if resp == board.OK {
				fmt.Printf("[random] put %d,%d\n", p.X(), p.Y())
				return match.NewPutResponse(p.X(), p.Y(), ts)
			}
		}
	}
	return match.NewPassResponse()
}
示例#9
0
// use win-rate distribution of node to play a legal move in tracker
func (node *Node) seed(t Tracker, path []int) bool {
	if node.parent == nil {
		return false
	}
	dist := new(vector.Vector)
	sum := 0.0
	for sibling := node.parent.Child; sibling != nil; sibling = sibling.Sibling {
		for i := 0; i < len(path); i++ {
			if sibling.Vertex == path[i] {
				continue
			}
		}
		dist.Push(sibling.blendedMean)
		sum += sibling.blendedMean
	}
	node.totalseeds++
	r := rand.Float64() * sum
	for i := 0; i < dist.Len(); i++ {
		r -= dist.At(i).(float64)
		if r <= 0 {
			if t.Legal(node.Color, i) {
				t.Play(node.Color, i)
				node.seeds++
				return true
			}
			return false
		}
	}
	return false
}
示例#10
0
func makeBugDocs(v *vector.Vector) []string {
	d := make([]string, v.Len())
	for i := 0; i < v.Len(); i++ {
		d[i] = CommentText(v.At(i).(*ast.CommentGroup))
	}
	return d
}
示例#11
0
文件: matchers.go 项目: boggle/gospec
// The actual collection must contain all expected elements and nothing else.
// The order of elements is not significant.
func ContainsExactly(actual_ interface{}, expected_ interface{}) (match bool, pos Message, neg Message, err os.Error) {
	actual, err := toArray(actual_)
	if err != nil {
		return
	}
	expected, err := toArray(expected_)
	if err != nil {
		return
	}

	containsAll := true
	remaining := new(vector.Vector)
	remaining.AppendVector((*vector.Vector)(&actual))
	for i := 0; i < len(expected); i++ {
		if idx, found := findIndex(*remaining, expected[i]); found {
			remaining.Delete(idx)
		} else {
			containsAll = false
			break
		}
	}

	match = containsAll && remaining.Len() == 0
	pos = Messagef(actual, "contains exactly “%v”", expected)
	neg = Messagef(actual, "does NOT contain exactly “%v”", expected)
	return
}
示例#12
0
func test0() {
	v := new(vector.Vector)
	if v.Len() != 0 {
		print("len = ", v.Len(), "\n")
		panic("fail")
	}
}
示例#13
0
func (p *parser) parseInterfaceType() *ast.InterfaceType {
	if p.trace {
		defer un(trace(p, "InterfaceType"))
	}

	pos := p.expect(token.INTERFACE)
	lbrace := p.expect(token.LBRACE)
	list := new(vector.Vector)
	for p.tok == token.IDENT {
		m := p.parseMethodSpec()
		if p.tok != token.RBRACE {
			p.expect(token.SEMICOLON)
		}
		m.Comment = p.lineComment
		list.Push(m)
	}
	rbrace := p.expect(token.RBRACE)
	p.optSemi = true

	// convert vector
	methods := make([]*ast.Field, list.Len())
	for i := list.Len() - 1; i >= 0; i-- {
		methods[i] = list.At(i).(*ast.Field)
	}

	return &ast.InterfaceType{pos, lbrace, methods, rbrace, false}
}
示例#14
0
func renderSection(section *sectionElement, context reflect.Value, buf io.Writer) {
    value := lookup(context, section.name)

    valueInd := reflect.Indirect(value)

    var contexts = new(vector.Vector)

    switch val := valueInd.(type) {
    case *reflect.BoolValue:
        if !val.Get() {
            return
        } else {
            contexts.Push(context)
        }
    case *reflect.SliceValue:
        for i := 0; i < val.Len(); i++ {
            contexts.Push(val.Elem(i))
        }
    case *reflect.ArrayValue:
        for i := 0; i < val.Len(); i++ {
            contexts.Push(val.Elem(i))
        }
    default:
        contexts.Push(context)
    }

    //by default we execute the section
    for j := 0; j < contexts.Len(); j++ {
        ctx := contexts.At(j).(reflect.Value)
        for i := 0; i < section.elems.Len(); i++ {
            renderElement(section.elems.At(i), ctx, buf)
        }
    }
}
示例#15
0
func (p *parser) parseStructType() *ast.StructType {
	if p.trace {
		defer un(trace(p, "StructType"))
	}

	pos := p.expect(token.STRUCT)
	lbrace := p.expect(token.LBRACE)
	list := new(vector.Vector)
	for p.tok == token.IDENT || p.tok == token.MUL {
		f := p.parseFieldDecl()
		if p.tok != token.RBRACE {
			p.expect(token.SEMICOLON)
		}
		f.Comment = p.lineComment
		list.Push(f)
	}
	rbrace := p.expect(token.RBRACE)
	p.optSemi = true

	// convert vector
	fields := make([]*ast.Field, list.Len())
	for i := list.Len() - 1; i >= 0; i-- {
		fields[i] = list.At(i).(*ast.Field)
	}

	return &ast.StructType{pos, lbrace, fields, rbrace, false}
}
示例#16
0
// Consume a group of adjacent comments, add it to the parser's
// comments list, and return the line of which the last comment
// in the group ends. An empty line or non-comment token terminates
// a comment group.
//
func (p *parser) consumeCommentGroup() int {
	list := new(vector.Vector)
	endline := p.pos.Line
	for p.tok == token.COMMENT && endline+1 >= p.pos.Line {
		var comment *ast.Comment
		comment, endline = p.consumeComment()
		list.Push(comment)
	}

	// convert list
	group := make([]*ast.Comment, list.Len())
	for i := 0; i < list.Len(); i++ {
		group[i] = list.At(i).(*ast.Comment)
	}

	// add comment group to the comments list
	g := &ast.CommentGroup{group, nil}
	if p.lastComment != nil {
		p.lastComment.Next = g
	} else {
		p.comments = g
	}
	p.lastComment = g

	return endline
}
示例#17
0
func (lex *Lexer) ParseExpression() *vector.Vector {
	tree := new(vector.Vector)
	for lex.current != "" {
		if lex.current == "," {
			break
		} else if lex.current == "(" {
			lex.Consume()
			args := lex.ParseArguments()
			if lex.current == ")" {
				if tree.Len() == 0 {
					tree.Push(NewMessage("", new(vector.Vector)))
				}

				if tree.Last().(IMessage).GetArguments().Len() > 0 {
					println("*** Arguments are empty")
					tree.Push(NewMessage("", new(vector.Vector)))
				}

				tree.Last().(IMessage).SetArguments(args)
			} else {
				println("Syntax Error: ')' expected")
			}
			println(len(*args))
		} else if lex.current == ")" {
			break
		} else {
			println("*** (ParseExpression) / fallback (line: " + strconv.Itoa(lex.line) + ") -- lex.current = " + lex.current + "; lex.next = " + lex.next)
			tree.Push(NewMessage(lex.current, new(vector.Vector)))
			lex.Consume()
		}
	}

	return tree
}
示例#18
0
func (p *parser) parseLiteral() literal {
	s := []byte(p.parseString())

	// A string literal may contain %-format specifiers. To simplify
	// and speed up printing of the literal, split it into segments
	// that start with "%" possibly followed by a last segment that
	// starts with some other character.
	var list vector.Vector
	i0 := 0
	for i := 0; i < len(s); i++ {
		if s[i] == '%' && i+1 < len(s) {
			// the next segment starts with a % format
			if i0 < i {
				// the current segment is not empty, split it off
				list.Push(s[i0:i])
				i0 = i
			}
			i++ // skip %; let loop skip over char after %
		}
	}
	// the final segment may start with any character
	// (it is empty iff the string is empty)
	list.Push(s[i0:])

	// convert list into a literal
	lit := make(literal, list.Len())
	for i := 0; i < list.Len(); i++ {
		lit[i] = list.At(i).([]byte)
	}

	return lit
}
示例#19
0
func TestRecvInvalidPacket(t *testing.T) {
	q := new(vector.Vector)
	x := &net.UDPAddr{net.IP{1, 2, 3, 4}, 5}
	p := recvPacket(q, Packet{x, invalidProtobuf})
	assert.Equal(t, (*packet)(nil), p)
	assert.Equal(t, 0, q.Len())
}
示例#20
0
// takes vector of nodes, returns sequential schedule length
func SeqTime(v vec.Vector) int64 {
	var s int64
	s = 0
	for i := 0; i < v.Len(); i++ {
		s += (v.At(i).(*p.Node)).Ex
	}
	return s
}
示例#21
0
func TestRecvEmptyPacket(t *testing.T) {
	q := new(vector.Vector)
	x := &net.UDPAddr{net.IP{1, 2, 3, 4}, 5}

	p := recvPacket(q, Packet{x, []byte{}})
	assert.Equal(t, (*packet)(nil), p)
	assert.Equal(t, 0, q.Len())
}
示例#22
0
// get the index of a node in a vector given nodes ID
func GetIndexById(v vector.Vector, id int) int {
	for i := 0; i < v.Len(); i++ {
		if v.At(i).(*Node).Id == id {
			return i
		}
	}
	return -1
}
示例#23
0
文件: main.go 项目: nunb/GoForth
func check_stack_size(DataStack *vector.Vector, required int) bool {
	if DataStack.Len() < required {
		log.Fatal("Stack depth is less then " + string(required) + ". Operation is impossible")
		return false
	}

	return true
}
示例#24
0
func process(c Conn, in chan paxos.Packet, out <-chan paxos.Packet) {
	pend := make(map[string]bool)
	h := new(vector.Vector)

	ticker := time.NewTicker(interval / 4)
	defer ticker.Stop()

	rawIn := make(chan paxos.Packet)
	go func() {
		recv(c, rawIn)
		close(rawIn)
	}()

	peek := func() check {
		if h.Len() < 1 {
			return check{at: math.MaxInt64}
		}
		return h.At(0).(check)
	}

	for {
		select {
		case p := <-rawIn:
			if closed(rawIn) {
				return
			}

			if p.Msg.HasFlags(paxos.Ack) {
				if pend[p.Id()] {
					pend[p.Id()] = false, false
				}
				continue
			}

			in <- p

			// send ack
			write(c, p.Msg.Dup().SetFlags(paxos.Ack), p.Addr)
		case p := <-out:
			pend[p.Id()] = true
			write(c, p.Msg, p.Addr)
			t := time.Nanoseconds()
			heap.Push(h, check{p, t + interval, t + timeout})
		case t := <-ticker.C:
			for k := peek(); k.at < t; k = peek() {
				heap.Pop(h)
				if t > k.until {
					pend[k.Id()] = false, false
				}
				if pend[k.Id()] {
					write(c, k.Msg, k.Addr)
					heap.Push(h, check{k.Packet, t + interval, k.until})
				}
			}
		}
	}
}
示例#25
0
func TestRecvPacket(t *testing.T) {
	q := new(vector.Vector)

	recvPacket(q, Packet{"x", mustMarshal(&msg{Seqn: proto.Int64(1)})})
	recvPacket(q, Packet{"x", mustMarshal(&msg{Seqn: proto.Int64(2)})})
	recvPacket(q, Packet{"x", mustMarshal(&msg{Seqn: proto.Int64(3)})})

	assert.Equal(t, 3, q.Len())
}
示例#26
0
func avg(v *vector.Vector) (n int64) {
	t := time.Nanoseconds()
	if v.Len() == 0 {
		return -1
	}
	for _, x := range []interface{}(*v) {
		n += x.(trigger).t - t
	}
	return n / int64(v.Len())
}
示例#27
0
func NewSoyListDataFromVector(o *vector.Vector) SoyListData {
	if o == nil {
		return &soyListData{l: list.New()}
	}
	l := list.New()
	for i := 0; i < o.Len(); i++ {
		l.PushBack(o.At(i))
	}
	a := &soyListData{l: l}
	return a
}
示例#28
0
func TestRecvInvalidPacket(t *testing.T) {
	q := new(vector.Vector)

	// The first element in a protobuf stream is always a varint.
	// The high bit of a varint byte indicates continuation;
	// Here we're supplying a continuation bit without a
	// subsequent byte. See also
	// http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints.
	recvPacket(q, Packet{"x", []byte{0x80}})
	assert.Equal(t, 0, q.Len())
}
示例#29
0
文件: run_test.go 项目: kr/doozerd
func TestRunSchedulesTick(t *testing.T) {
	var r run
	r.seqn = 1
	r.bound = 10
	r.out = make(chan Packet, 100)
	ticks := new(vector.Vector)

	r.update(packet{msg: *newPropose("foo")}, ticks)

	assert.Equal(t, 1, ticks.Len())
}
示例#30
0
// navigate through the tree until a leaf node is found to playout
func (root *Node) step(t Tracker) {
	var start int64
	path := new(vector.Vector)
	start = time.Nanoseconds()
	curr := root.Next(root, t)
	root.next_time += time.Nanoseconds() - start
	root.next_count++
	if curr == nil {
		root.Visits = math.Inf(1)
		return
	}
	for {
		path.Push(curr)
		// apply node's position to the board
		start = time.Nanoseconds()
		t.Play(curr.Color, curr.Vertex)
		root.play_time += time.Nanoseconds() - start
		root.play_count++
		if curr.Visits <= root.config.ExpandAfter {
			var color byte
			if root.config.Seed {
				color = curr.seedPlayout(t)
			} else {
				color = Reverse(curr.Color)
			}
			start = time.Nanoseconds()
			t.Playout(color)
			root.playout_time += time.Nanoseconds() - start
			break
		}
		time.Nanoseconds()
		next := curr.Next(root, t)
		root.next_time += time.Nanoseconds() - start
		root.next_count++
		curr = next
		if curr == nil {
			break
		}
	}
	start = time.Nanoseconds()
	winner := t.Winner()
	root.win_calc_time += time.Nanoseconds() - start
	start = time.Nanoseconds()
	for j := 0; j < path.Len(); j++ {
		path.At(j).(*Node).update(t)
	}
	root.update_time += time.Nanoseconds() - start
	if winner == Reverse(root.Color) {
		root.Wins++
	}
	root.Visits++
	root.Mean = root.Wins / root.Visits
}