Пример #1
0
func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
	if p.trace {
		defer un(trace(p, "CallOrConversion"))
	}

	lparen := p.expect(token.LPAREN)
	p.exprLev++
	var list vector.Vector
	var ellipsis token.Position
	for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
		list.Push(p.parseExpr())
		if p.tok == token.ELLIPSIS {
			ellipsis = p.pos
			p.next()
		}
		if p.tok != token.COMMA {
			break
		}
		p.next()
	}
	p.exprLev--
	rparen := p.expect(token.RPAREN)

	return &ast.CallExpr{fun, lparen, makeExprList(&list), ellipsis, rparen}
}
Пример #2
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
}
Пример #3
0
// PutAt will put a give piece at the given position and return removed pieces and the response code.
func (b *Board) PutAt(c cell.Cell, x int, y int, h *history.History) (vector.Vector, PutResponse) {
	if b.At(x, y) != cell.SPACE {
		return nil, OCCUPIED
	}

	b.putAt(c, x, y)
	takenOffs := vector.Vector{}
	rc := c.Reverse()
	if b.shouldTakeOff(x-1, y, rc) {
		b.takeOff(x-1, y, rc, &takenOffs)
	}
	if b.shouldTakeOff(x+1, y, rc) {
		b.takeOff(x+1, y, rc, &takenOffs)
	}
	if b.shouldTakeOff(x, y-1, rc) {
		b.takeOff(x, y-1, rc, &takenOffs)
	}
	if b.shouldTakeOff(x, y+1, rc) {
		b.takeOff(x, y+1, rc, &takenOffs)
	}

	if b.shouldTakeOff(x, y, c) {
		b.TakeAt(x, y)
		return nil, FORBIDDEN
	}

	if len(takenOffs) == 1 && h.IsKo(c, x, y) {
		b.putAt(cell.SPACE, x, y)
		taken := takenOffs.Last().(point.Point)
		b.putAt(c.Reverse(), taken.X(), taken.Y())
		return nil, KO
	}

	return takenOffs, OK
}
Пример #4
0
// Today this function creates a route in Doozer for the
// RouteService.RouteCreditRequest method - which is CLARITY SPECIFIC
// and adds it too Doozer
func CreateInitialRoute() {

	r := &skylib.Route{}
	r.Name = sName
	r.LastUpdated = time.Seconds()
	r.Revision = 1

	rpcScore := &skylib.RpcCall{Service: "GetUserDataService.GetUserData", Async: false, OkToRetry: false, ErrOnFail: true}

	rl := new(vector.Vector)

	r.RouteList = rl
	rl.Push(rpcScore)

	b, err := json.Marshal(r)
	if err != nil {
		log.Panic(err.String())
	}
	rev, err := skylib.DC.Rev()
	if err != nil {
		log.Panic(err.String())
	}
	_, err = skylib.DC.Set("/routes/RouteService.RouteGetUserDataRequest", rev, b)
	if err != nil {
		log.Panic(err.String())
	}
	return
}
Пример #5
0
func TestGroupBy(t *testing.T) {
	in := IntArray{1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5}
	exp := [][]int{[]int{1}, []int{2, 2}, []int{3, 3, 3}, []int{4, 4, 4, 4}, []int{5, 5, 5, 5, 5}}
	i := 0
	for x := range GroupBy(in, intkey{}).Iter() {
		gr := x.(Group)
		if gr.Key.(int) != i+1 {
			t.Fatal("group key wrong; expected", i+1, "but got", gr.Key.(int))
		}
		vals := Data(gr.Vals)
		assertArraysAreEqual(t, vals, exp[i])
		i++
	}
	if i != 5 {
		t.Fatal("did not return expected number of groups")
	}

	// test 0 length Iterable
	for _ = range GroupBy(IntArray([]int{}), &intkey{}).Iter() {
		t.Fatal("iterator should be empty")
	}

	// test case with only uniques
	var out vector.Vector
	for x := range GroupBy(elevenToTwenty, intkey{}).Iter() {
		out.Push(x.(Group).Key)
	}
	assertArraysAreEqual(t, out.Data(), elevenToTwenty)
}
Пример #6
0
// codewalkDir serves the codewalk directory listing.
// It scans the directory for subdirectories or files named *.xml
// and prepares a table.
func codewalkDir(w http.ResponseWriter, r *http.Request, relpath, abspath string) {
	type elem struct {
		Name  string
		Title string
	}

	dir, err := ioutil.ReadDir(abspath)
	if err != nil {
		log.Print(err)
		serveError(w, r, relpath, err)
		return
	}
	var v vector.Vector
	for _, fi := range dir {
		if fi.IsDirectory() {
			v.Push(&elem{fi.Name + "/", ""})
		} else if strings.HasSuffix(fi.Name, ".xml") {
			cw, err := loadCodewalk(abspath + "/" + fi.Name)
			if err != nil {
				continue
			}
			v.Push(&elem{fi.Name[0 : len(fi.Name)-len(".xml")], cw.Title})
		}
	}

	b := applyTemplate(codewalkdirHTML, "codewalkdir", v)
	servePage(w, "Codewalks", "", "", b)
}
Пример #7
0
func (self Transformer) shorten(arr vec.Vector, index, inside, count int) (rindex int, rinside int) {
	mut := arr[index]
	if IsDeleteMutation(mut) {
		del := toDeleteMutation(mut)
		del.SetCount(del.Count() - count)
		if inside == del.Count() {
			inside = 0
			if del.Count() == 0 {
				arr.Delete(index)
			} else {
				index++
			}
		}
	} else if IsSkipMutation(mut) {
		skip := toSkipMutation(mut)
		skip.SetCount(skip.Count() - 1)
		if inside == skip.Count() {
			inside = 0
			if skip.Count() == 0 {
				arr.Delete(index)
			} else {
				index++
			}
		}
	} else {
		panic("Unsupported mutation for shorten()")
	}

	return index, inside
}
Пример #8
0
// Data returns a slice containing the elements of iter.
func Data(iter Iterable) []interface{} {
	vec := new(vector.Vector)
	for e := range iter.Iter() {
		vec.Push(e)
	}
	return vec.Data()
}
Пример #9
0
// arrayInterface is like array but returns []interface{}.
func (d *decodeState) arrayInterface() []interface{} {
	var v vector.Vector
	for {
		// Look ahead for ] - can only happen on first iteration.
		op := d.scanWhile(scanSkipSpace)
		if op == scanEndArray {
			break
		}

		// Back up so d.value can have the byte we just read.
		d.off--
		d.scan.undo(op)

		v.Push(d.valueInterface())

		// Next token must be , or ].
		op = d.scanWhile(scanSkipSpace)
		if op == scanEndArray {
			break
		}
		if op != scanArrayValue {
			d.error(errPhase)
		}
	}
	return v
}
Пример #10
0
func chooseNextEdgeByGeneration(T *quadratic.Map) *quadratic.Edge {
	ActiveFaces := new(vector.Vector)
	onGeneration := -1
	T.Faces.Do(func(F interface{}) {
		Fac := F.(*quadratic.Face)
		if Fac.Value.(string) != "active" {
			return
		}
		ActiveFaces.Push(Fac)
		Fac.DoEdges(func(e *quadratic.Edge) {
			//fmt.Fprintf(os.Stderr,"edge generation: %v onGen: %v\n",e.Generation,onGeneration)
			if onGeneration < 0 || e.Generation < onGeneration {
				onGeneration = e.Generation
			}
		})
	})
	activeEdges := new(generationOrderedEdges)

	ActiveFaces.Do(func(F interface{}) {
		Fac := F.(*quadratic.Face)
		Fac.DoEdges(func(e *quadratic.Edge) {
			if e.Generation != onGeneration {
				return
			}
			activeEdges.Push(e)
		})
	})
	//fmt.Fprintf(os.Stderr,"onGen: %v have %v active edges\n",onGeneration,activeEdges.Len())
	sort.Sort(activeEdges)
	return activeEdges.At(0).(*quadratic.Edge)
}
Пример #11
0
func makeVector(n int) *vector.Vector {
	v := new(vector.Vector)
	for i := 0; i < n; i++ {
		v.Push(&User{"Mike", 1})
	}
	return v
}
Пример #12
0
func TestDecodeFlushElem(t *testing.T) {
	testVec := new(vector.Vector).Resize(2, 2)
	nb := newDecoder(testVec, 1)
	nb.Float64(3.14159)
	nb.Flush()
	assertResult(t, testVec.Data(), []interface{}{nil, float64(3.14159)})
}
Пример #13
0
func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
	if p.trace {
		defer un(trace(p, keyword.String()+"Decl"))
	}

	doc := p.leadComment
	pos := p.expect(keyword)
	var lparen, rparen token.Position
	var list vector.Vector
	if p.tok == token.LPAREN {
		lparen = p.pos
		p.next()
		for p.tok != token.RPAREN && p.tok != token.EOF {
			list.Push(f(p, p.leadComment))
		}
		rparen = p.expect(token.RPAREN)
		p.expectSemi()
	} else {
		list.Push(f(p, nil))
	}

	// convert vector
	specs := make([]ast.Spec, len(list))
	for i, x := range list {
		specs[i] = x.(ast.Spec)
	}

	return &ast.GenDecl{doc, pos, keyword, lparen, specs, rparen}
}
Пример #14
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())
}
Пример #15
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 {
	var list 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, len(list))
	for i, x := range list {
		group[i] = x.(*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
}
Пример #16
0
func test0() {
	v := new(vector.Vector)
	if v.Len() != 0 {
		print("len = ", v.Len(), "\n")
		panic("fail")
	}
}
Пример #17
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
}
Пример #18
0
func _AppendParamsData(buff *bytes.Buffer, sig string, params *vector.Vector) {
	sigOffset := 0
	prmsOffset := 0
	for ; sigOffset < len(sig); prmsOffset++ {
		offset, _ := _AppendValue(buff, sig[sigOffset:len(sig)], params.At(prmsOffset))
		sigOffset += offset
	}
}
Пример #19
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())
}
Пример #20
0
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
}
Пример #21
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
}
Пример #22
0
// Given the id of a task that has been scheduled on a processor
// return the index of that Task's Event entry
func findInSchedule(v vec.Vector, id int) int {
	for i := 0; i < len(v); i++ {
		if v.At(i).(*Event).id == id {
			return i
		}

	}
	return -1
}
Пример #23
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})
				}
			}
		}
	}
}
Пример #24
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())
}
Пример #25
0
// takeOff will remove a group of cells at a given point.
func (b *Board) takeOff(x int, y int, c cell.Cell, takenOffs *vector.Vector) {
	if b.At(x, y) == c {
		b.TakeAt(x, y)
		takenOffs.Push(point.Point{x, y})
		b.takeOff(x-1, y, c, takenOffs)
		b.takeOff(x+1, y, c, takenOffs)
		b.takeOff(x, y-1, c, takenOffs)
		b.takeOff(x, y+1, c, takenOffs)
	}
}
Пример #26
0
// Durp. Why this originally created its own buffer and then returned the string is beyond me... it's much more efficient to just ask for a io.Writer to begin with.
func (tmpl *Template) Render(wr io.Writer, context ...interface{}) (e os.Error) {
	//var buf bytes.Buffer
	var contextChain vector.Vector
	for _, c := range context {
		val := reflect.ValueOf(c)
		contextChain.Push(val)
	}
	tmpl.renderTemplate(&contextChain, wr)
	return
}
Пример #27
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())
}
Пример #28
0
func (state *State) EvaluateTree(tree vector.Vector) {
	tree.Do(func(elem interface{}) {
		msg := elem.(IMessage)
		println(msg.GetName())
		msg.GetArguments().Do(func(item interface{}) {
			arg := item.(IMessage)
			println(arg.GetName())
		})
	})
}
Пример #29
0
func (tmpl *Template) Render(context ...interface{}) string {
	var buf bytes.Buffer
	var contextChain vector.Vector
	for _, c := range context {
		val := reflect.ValueOf(c)
		contextChain.Push(val)
	}
	tmpl.renderTemplate(&contextChain, &buf)
	return buf.String()
}
Пример #30
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()
}