func TestMap(t *testing.T) {
	func() {
		d := newMapString()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx].id)
		}
		for _, idx := range ix {
			if d.exist(testVals[idx].id) {
				t.Errorf("%s should have not existed!", testVals[idx].id)
			}
		}
	}()

	func() {
		d := newMapPointer()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx].id)
		}
		for _, idx := range ix {
			if d.exist(testVals[idx].id) {
				t.Errorf("%s should have not existed!", testVals[idx].id)
			}
		}
	}()
}
func TestInterface(t *testing.T) {
	func() {
		d := newDataRWMutex()
		ix := rand.Perm(testSize)
		for _, v := range testValues {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testValues[idx])
		}
		for _, idx := range ix {
			if d.exist(testValues[idx]) {
				t.Errorf("%s should have not existed!", testValues[idx])
			}
		}
	}()

	func() {
		d := newDataMutex()
		ix := rand.Perm(testSize)
		for _, v := range testValues {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testValues[idx])
		}
		for _, idx := range ix {
			if d.exist(testValues[idx]) {
				t.Errorf("%s should have not existed!", testValues[idx])
			}
		}
	}()
}
Exemple #3
0
func advanceState(c appengine.Context, h *hunt.Hunt, currentState int) {
	err := datastore.RunInTransaction(c, func(c appengine.Context) error {
		h := hunt.ID(c, h.ID)
		if h == nil || h.State != currentState {
			// TODO(dneal): Return a real error.
			return nil
		}
		switch h.State {
		case hunt.StatePreLaunch:
			teams := team.All(c, h)
			nonPaperOrder := rand.Perm(len(teams))
			paperOrder := rand.Perm(len(teams))
			for i := range teams {
				puzzle.New(c, h, teams[i], nonPaperOrder[i]+1, false)
				puzzle.New(c, h, teams[i], len(teams)+paperOrder[i]+1, true)
			}
		case hunt.StateSurveying:
			tally.BuildFinalTally(c, h)
		}
		h.State++
		h.Write(c)
		broadcast.SendRefresh(c, h)
		return nil
	}, nil)
	if err != nil {
		c.Errorf("Error: %v", err)
	}
}
Exemple #4
0
func TestEdgeX(t *testing.T) {
	mom := rand.Perm(8)
	dad := rand.Perm(8)
	child := make([]int, 8)
	perm.EdgeX(child, mom, dad)
	validate(t, child)
}
Exemple #5
0
func (ag *AvalonGame) assignSpecialCharacters() {
	// === Good ===
	randomOrder := rand.Perm(ag.NumGoods())
	// Merlin
	ag.SpecialCharacters["merlin"] = ag.GoodCharacters[randomOrder[0]]
	// Percival
	if ag.OptionEnabled[OptionMorganaPercival] {
		ag.SpecialCharacters["percival"] = ag.GoodCharacters[randomOrder[1]]
	}

	// === Evil ===
	randIndex := 1
	randomOrder = rand.Perm(ag.NumEvils())
	// Assassin
	ag.SpecialCharacters["assassin"] = ag.EvilCharacters[randomOrder[0]]
	// Mordred
	if ag.OptionEnabled[OptionMordred] {
		ag.SpecialCharacters["mordred"] = ag.EvilCharacters[randomOrder[randIndex]]
		randIndex++
	}
	// Morgana
	if ag.OptionEnabled[OptionMorganaPercival] {
		ag.SpecialCharacters["morgana"] = ag.EvilCharacters[randomOrder[randIndex]]
		randIndex++
	}
	// Oberon
	if ag.OptionEnabled[OptionOberon] {
		ag.SpecialCharacters["oberon"] = ag.EvilCharacters[randomOrder[randIndex]]
		randIndex++
	}
}
Exemple #6
0
func init() {
	for _, val := range rand.Perm(10) {
		data := &TestData{
			Id:    int64(val),
			Value: int64(val),
		}
		skipList.Set(data, nil)
		datas[data.Id] = data
	}

	for _, val := range rand.Perm(20) {
		data := &TestData{
			Id:    int64(val),
			Value: int64(val),
		}
		old, ok := datas[data.Id]
		if ok {
			skipList.Set(data, old)
		} else {
			skipList.Set(data, nil)
		}
	}

	fmt.Println("f**k")
	skipList.Set(&TestData{
		Id:    1,
		Value: 10,
	}, datas[1])
}
Exemple #7
0
func TestBinaryTreeFind(t *testing.T) {
	const count = 100
	for i := 0; i < 10; i++ {
		tree := Tree{Compare: func(a, b interface{}) ComparisonResult {
			aa := a.(int)
			bb := b.(int)
			switch {
			case aa < bb:
				return Less
			case aa > bb:
				return Greater
			default:
				return Equal
			}
		}}
		list := rand.Perm(count)
		for _, j := range list {
			if e := tree.Add(j); e != nil {
				t.Error(e)
			}
		}
		list = rand.Perm(count)
		for _, j := range list {
			if _, _, n := tree.Find(j); n == nil {
				t.Errorf("Should have found %d, but didn't", j)
			} else if v, ok := n.Data.(int); !ok {
				t.Errorf("Unable to cast data to int... %+v", n.Data)
			} else if v != j {
				t.Errorf("Expected to find %d, but got %d", j, v)
			}
		}
	}
}
Exemple #8
0
func TestMapTo(t *testing.T) {
	func() {
		d := newSlice()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx])
		}
		for _, idx := range ix {
			if d.exist(testVals[idx]) {
				t.Errorf("%s should have not existed!", testVals[idx])
			}
		}
	}()

	func() {
		d := newMap()
		ix := rand.Perm(testN)
		for _, v := range testVals {
			d.set(v)
		}
		for _, idx := range ix {
			d.delete(testVals[idx])
		}
		for _, idx := range ix {
			if d.exist(testVals[idx]) {
				t.Errorf("%s should have not existed!", testVals[idx])
			}
		}
	}()
}
func genRandomGenSparseVectorInt(m int) *GenSparseVector {
	l := m * 3 / 4
	values := make([]Value, l)
	for i, v := range rand.Perm(m)[:l] {
		values[i] = Value(v)
	}
	return NewGenSparseVector(IntIndex(rand.Perm(m)[:l]), values)
}
Exemple #10
0
func doStuff(id int,
	res chan<- Result,
	wg *sync.WaitGroup,
	body []byte,
	prot, addr string) {

	defer wg.Done()

	localstats := [256]int64{}

	keys := make([][]byte, *nkeys / *concurrency)
	vbuckets := make([]uint16, *nvbuckets)
	for i := 0; i < len(keys); i++ {
		keys[i] = []byte(fmt.Sprintf("c%d.k%d", id, i))
		vbuckets = append(vbuckets, uint16(rand.Intn(*nvbuckets)))
	}

	client, err := memcached.Connect(prot, addr)
	if err != nil {
		log.Printf("Error connecting to %v/%v: %v", prot, addr, err)
		return
	}

	go handleResponses(client, res)

	applyLocalStats := func() {
		for j, v := range localstats {
			atomic.AddInt64(&stats[j], v)
			localstats[j] = 0
		}
	}

	cmdi := 0
	ids := rand.Perm(len(keys))
	for {
		for i, thisId := range ids {
			key := keys[thisId]
			opcode := cmds.cmds[cmdi]

			sendCommand(client, opcode, vbuckets[thisId], key, body)
			localstats[opcode]++

			if i%1000 == 0 {
				applyLocalStats()
				if atomic.LoadInt32(&isDone) == 1 {
					return
				}
			}
		}
		applyLocalStats()
		cmdi++
		if cmdi >= len(cmds.cmds) {
			cmdi = 0
			ids = rand.Perm(len(keys))
		}
	}
}
Exemple #11
0
func RandomCubieCube() CubieCube {
	var res CubieCube

	// Generate a random permutation for the corners.
	pieces := rand.Perm(8)
	for i, x := range pieces {
		res.Corners[i].Piece = x
	}

	// Generate a random permutation for the edges.
	cornerParity := parity(pieces)
	pieces = rand.Perm(12)
	for i, x := range pieces {
		res.Edges[i].Piece = x
	}

	// Make sure the overall parity is even.
	if cornerParity != parity(pieces) {
		res.Edges[11], res.Edges[10] = res.Edges[10], res.Edges[11]
	}

	// Generate edge orientations.
	lastFlip := false
	for i := 0; i < 11; i++ {
		if rand.Intn(2) == 0 {
			lastFlip = !lastFlip
			res.Edges[i].Flip = true
		}
	}
	res.Edges[11].Flip = lastFlip

	// Generate the corner orientations.
	for i := 0; i < 7; i++ {
		res.Corners[i].Orientation = rand.Intn(3)
	}
	var orientations [8]int
	for i, x := range []int{0, 1, 5, 4, 6, 2, 3, 7} {
		orientations[i] = res.Corners[x].Orientation
	}
	for i := 0; i < 7; i++ {
		thisOrientation := orientations[i]
		nextOrientation := orientations[i+1]
		if thisOrientation == 2 {
			orientations[i+1] = (nextOrientation + 2) % 3
		} else if thisOrientation == 0 {
			orientations[i+1] = (nextOrientation + 1) % 3
		}
	}
	if orientations[7] == 0 {
		res.Corners[7].Orientation = 2
	} else if orientations[7] == 2 {
		res.Corners[7].Orientation = 0
	}

	return res
}
func BenchmarkFind(b *testing.B) {
	bst := new(T)
	for _, i := range rand.Perm(b.N) {
		bst.Insert(i, i)
	}

	b.ResetTimer()
	for _, i := range rand.Perm(b.N) {
		bst.Find(i)
	}
}
func genRandomSparseVector(m int) *SparseVectorUint32 {
	l := m * 3 / 4
	values := make([]Value, l)
	for i, v := range rand.Perm(m)[:l] {
		values[i] = Value(v)
	}
	index := make([]uint32, l)
	for i, v := range rand.Perm(m)[:l] {
		index[i] = uint32(v)
	}
	return NewSparseVectorUint32(index, values)
}
func main() {
	rand.Seed(time.Now().UnixNano())

	indices := rand.Perm(len(SOURCE))
	var output string
	for i := 0; i < 50; i++ {
		if i != 0 && i%7 == 0 {
			indices = rand.Perm(len(SOURCE))
		}
		output += fmt.Sprintf("%c", SOURCE[indices[i%7]])
	}
	fmt.Println(output)
}
Exemple #15
0
func (r *roler) openReplicaRole(shardToMasterAddress map[int]route.Address, shardToReplicaAddress map[int]map[int]route.Address) (int, int, bool) {
	for _, shard := range rand.Perm(r.sharder.NumShards()) {
		addresses := shardToReplicaAddress[shard]
		if len(addresses) < r.numReplicas && !r.hasRoleForShard(shard, shardToMasterAddress, shardToReplicaAddress) {
			for _, index := range rand.Perm(r.numReplicas) {
				if _, ok := addresses[index]; !ok {
					return shard, index, true
				}
			}
		}
	}
	return 0, 0, false
}
func genRandomGenSparseVectorUint32(m int) *GenSparseVector {
	l := m * 3 / 4
	values := make([]Value, l)
	for i, v := range rand.Perm(m)[:l] {
		values[i] = Value(v)
	}
	index := make(Uint32Index, l)
	for i, v := range rand.Perm(m)[:l] {
		index[i] = uint32(v)
	}

	return NewGenSparseVector(index, values)
}
Exemple #17
0
func buildFlowGraph(params VbmapParams) (g *Graph) {
	graphName := fmt.Sprintf("Flow graph for RI (%s)", params)
	g = NewGraph(graphName)

	tags := params.Tags.TagsList()
	tagsNodes := params.Tags.TagsNodesMap()

	maxReplicationsPerTag := 0
	if params.NumReplicas != 0 {
		maxReplicationsPerTag = params.NumSlaves / params.NumReplicas
	}

	nodes := params.Nodes()
	for _, nodeIx := range rand.Perm(len(nodes)) {
		node := nodes[nodeIx]
		nodeTag := params.Tags[node]
		nodeSrcV := NodeSourceVertex(node)
		nodeSinkV := NodeSinkVertex(node)

		g.AddEdge(Source, nodeSrcV, params.NumSlaves, params.NumSlaves)
		g.AddEdge(nodeSinkV, Sink, params.NumSlaves, 0)

		for _, tagIx := range rand.Perm(len(tags)) {
			tag := tags[tagIx]

			if tag == nodeTag {
				continue
			}

			tagNodesCount := len(tagsNodes[tag])
			tagCapacity := Min(tagNodesCount, maxReplicationsPerTag)

			tagV := TagVertex(tag)
			g.AddEdge(nodeSrcV, tagV, tagCapacity, 0)
		}
	}

	for _, tagIx := range rand.Perm(len(tags)) {
		tag := tags[tagIx]
		tagNodes := tagsNodes[tag]
		tagV := TagVertex(tag)

		for _, tagNode := range tagNodes {
			tagNodeV := NodeSinkVertex(tagNode)

			g.AddEdge(tagV, tagNodeV, params.NumSlaves, 0)
		}
	}

	return
}
Exemple #18
0
func TestBinaryTreeAddDelete(t *testing.T) {
	const count = 100
	const sub = 20
	for i := 0; i < 10; i++ {
		tree := Tree{Compare: func(a, b interface{}) ComparisonResult {
			aa := a.(int)
			bb := b.(int)
			switch {
			case aa < bb:
				return Less
			case aa > bb:
				return Greater
			default:
				return Equal
			}
		}}
		list := rand.Perm(count)
		for _, j := range list {
			if e := tree.Add(j); e != nil {
				t.Error(e)
			}
		}
		for k := 0; k < 10; k++ {
			list = rand.Perm(sub)
			a := rand.Intn(count - sub)
			for _, j := range list {
				if e := tree.Delete(a + j); e != nil {
					t.Error(e)
				}
			}
			list = rand.Perm(sub)
			for _, j := range list {
				if e := tree.Add(a + j); e != nil {
					t.Error(e)
				}
			}
		}

		ch := make(chan interface{})
		go func() {
			tree.Root.Walk(ch)
			close(ch)
		}()
		for j := 0; j < count; j++ {
			k := (<-ch).(int)
			if k != j {
				t.Errorf("%d != %d", k, j)
			}
		}
	}
}
Exemple #19
0
func TestRandomAllocateDeallocate(t *testing.T) {
	ds, err := randomLocalStore()
	if err != nil {
		t.Fatal(err)
	}

	numBits := int(16 * blockLen)
	hnd, err := NewHandle("bitseq-test/data/", ds, "test1", uint64(numBits))
	if err != nil {
		t.Fatal(err)
	}

	seed := time.Now().Unix()
	rand.Seed(seed)

	// Allocate all bits using a random pattern
	pattern := rand.Perm(numBits)
	for _, bit := range pattern {
		err := hnd.Set(uint64(bit))
		if err != nil {
			t.Fatalf("Unexpected failure on allocation of %d: %v.\nSeed: %d.\n%s", bit, err, seed, hnd)
		}
	}
	if hnd.Unselected() != 0 {
		t.Fatalf("Expected full sequence. Instead found %d free bits. Seed: %d.\n%s", hnd.unselected, seed, hnd)
	}
	if hnd.head.toString() != "(0xffffffff, 16)->end" {
		t.Fatalf("Unexpected db: %s", hnd.head.toString())
	}

	// Deallocate all bits using a random pattern
	pattern = rand.Perm(numBits)
	for _, bit := range pattern {
		err := hnd.Unset(uint64(bit))
		if err != nil {
			t.Fatalf("Unexpected failure on deallocation of %d: %v.\nSeed: %d.\n%s", bit, err, seed, hnd)
		}
	}
	if hnd.Unselected() != uint64(numBits) {
		t.Fatalf("Expected full sequence. Instead found %d free bits. Seed: %d.\n%s", hnd.unselected, seed, hnd)
	}
	if hnd.head.toString() != "(0x0, 16)->end" {
		t.Fatalf("Unexpected db: %s", hnd.head.toString())
	}

	err = hnd.Destroy()
	if err != nil {
		t.Fatal(err)
	}
}
Exemple #20
0
func BenchmarkRemove(b *testing.B) {
	// Create some initial data and fill the set
	data := rand.Perm(b.N)
	set := New()
	for _, val := range data {
		set.Insert(val)
	}
	// Execute the benchmark (different order)
	rems := rand.Perm(b.N)
	b.ResetTimer()
	for _, val := range rems {
		set.Remove(val)
	}
}
Exemple #21
0
func TestRandomReplace(t *testing.T) {
	tree := New(NaturalSortLessInt)
	n := 100
	perm := rand.Perm(n)
	for i := 0; i < n; i++ {
		tree.ReplaceOrInsert(Int(perm[i]))
	}
	perm = rand.Perm(n)
	for i := 0; i < n; i++ {
		if replaced := tree.ReplaceOrInsert(Int(perm[i])); replaced == nil || replaced.(Int) != Int(perm[i]) {
			t.Errorf("error replacing")
		}
	}
}
Exemple #22
0
func TestRandomReplace(t *testing.T) {
	tree := NewLLRB()
	n := 100
	perm := rand.Perm(n)
	for i := 0; i < n; i++ {
		tree.Upsert(&KeyInt{int64(perm[i]), -1})
	}
	perm = rand.Perm(n)
	for i := 0; i < n; i++ {
		replaced := tree.Upsert(&KeyInt{int64(perm[i]), -1})
		if replaced == nil || replaced.(*KeyInt).Key != int64(perm[i]) {
			t.Errorf("error replacing")
		}
	}
}
//Generate a random MapData given some dimensions
func generate_map(n int) *MapData {
	map_data := *NewMapData(n, n)
	map_data[0][0] = START
	map_data[n-1][n-1] = STOP

	xs := rand.Perm(n - 1)
	ys := rand.Perm(n - 1)

	for i := 1; i < len(xs); i += rand.Intn(4) + 1 {
		for j := 1; j < len(ys); j++ {
			map_data[xs[i]][ys[j]] = WALL
		}
	}
	return &map_data
}
Exemple #24
0
func TestRandomReplace(t *testing.T) {
	tree := New()
	n := 100
	perm := rand.Perm(n)
	for i := 0; i < n; i++ {
		tree.ReplaceOrInsert(uint64(perm[i]))
	}
	perm = rand.Perm(n)
	for i := 0; i < n; i++ {
		v := uint64(perm[i])
		if replaced := tree.ReplaceOrInsert(v); !replaced {
			t.Errorf("error replacing")
		}
	}
}
func BenchmarkExist(b *testing.B) {
	b.StopTimer()
	var d Interface
	if opt == "slice" {
		d = newMapToSlice()
	} else {
		d = newMapToMap()
	}
	k := "A"
	for _, v := range testVals {
		d.set(k, v)
	}

	// to make it not biased towards data structures
	// with an order, such as slice.
	ix := rand.Perm(testN)

	b.StartTimer()
	b.ReportAllocs()

	for _, idx := range ix {
		if !d.exist(k, testVals[idx]) {
			b.Errorf("%s should have existed!", testVals[idx])
		}
	}
}
Exemple #26
0
func (options *ScanOptions) SSLMatchHosts(conn *tls.Conn) []string {
	hosts := make([]string, 0)
	options.hostsMutex.Lock()
	for _, host := range options.inputHosts {
		testhost := host.Host
		if strings.Contains(testhost, ".appspot.com") {
			testhost = "appengine.google.com"
		} else if strings.Contains(testhost, "ggpht.com") {
			testhost = "googleusercontent.com"
		} else if strings.Contains(testhost, ".books.google.com") {
			testhost = "books.google.com"
		} else if strings.Contains(testhost, ".googleusercontent.com") {
			testhost = "googleusercontent.com"
		}
		if conn.VerifyHostname(testhost) == nil {
			hosts = append(hosts, host.Host)
		}
	}
	options.hostsMutex.Unlock()
	dest := make([]string, len(hosts))
	perm := rand.Perm(len(hosts))
	for i, v := range perm {
		dest[v] = hosts[i]
	}
	hosts = dest
	return hosts
}
Exemple #27
0
func Generate(name string) Course {
	holes := make([]Hole, 18)
	for index, pos := range rand.Perm(18) {
		holes[index] = GenerateHole(pars[pos])
	}
	return Course{Name: name, Par: 72, Holes: holes}
}
Exemple #28
0
func getExternalIP() net.IP {
	var currentIP net.IP
	for _, i := range rand.Perm(len(urls)) {
		if verbose {
			fmt.Printf("Connecting to %v...\n", urls[i])
		}

		url := "http://" + urls[i]

		content, err := getResponse(url)
		if err != nil {
			if verbose {
				fmt.Printf("%v\n", err)
			}
			continue
		}

		ip := regex.FindString(content)

		currentIP = net.ParseIP(ip)

		if currentIP != nil {
			return currentIP
		}

		fmt.Println("No valid IP address could be parsed from response.")
	}

	return currentIP
}
Exemple #29
0
func TestBinaryTreeDelete(t *testing.T) {

	keys := rand.Perm(5217)

	tree := new(BinaryTree)

	for _, i := range keys {

		tree.Set(i, fmt.Sprintf("format_%d", i))
	}

	for _, i := range keys {

		if _, err := tree.Get(i); err != nil {

			t.Error(err.Error())
		}
	}

	for _, i := range keys {

		tree.Delete(i)

		if _, err := tree.Get(i); err == nil {

			t.Error("Найдено, а не должно бы")
		}
	}
}
func generatePermSet(mode int) []int {
	if mode == 0 {
		return rand.Perm(1000)
	}

	return make([]int, 0)
}