Example #1
0
func MakeTestTasksN(height, width, connectivity int) graph.Tasks {
	t := make(graph.Tasks)

	levels := make([][]*graph.Task, height)
	for i := range levels {
		levels[i] = make([]*graph.Task, width)
		for j := range levels[i] {
			task := &graph.Task{
				Id:           graph.TaskID(strconv.FormatInt(rand.Int63(), 10)),
				Start:        rand.Int63(),
				End:          rand.Int63(),
				Completed:    rand.Int()%2 == 0,
				Dependencies: graph.MakeTaskIDSet(),
			}
			t[task.Id] = task
			levels[i][j] = task
		}
	}

	for depth, level := range levels[:height-1] {
		for _, task := range level {
			connections := rand.Int31n(int32(connectivity))
			for i := 0; i < int(connections); i++ {
				row, col := rand.Int31n(int32(height-depth-1)), rand.Int31n(int32(width))
				task.Dependencies.Add(levels[depth+int(row)+1][col].Id)
			}
		}
	}
	return t
}
Example #2
0
func send() {
	channelGoCount <- 1
	// fmt.Println("tick")
	conn, err := net.DialTimeout("tcp", fmt.Sprintf("%v:%v", S.ServerAddr, S.Port_to_listen), time.Duration(10+rand.Int31n(delay))*time.Millisecond)
	if err == nil {
		mIndex := rand.Int31n(int32(len(machineInfos)))
		machine := machineInfos[mIndex]
		if machine.M.Ip[0] == '_' {
			fmt.Println("By ID")
			binary.Write(conn, binary.LittleEndian, int16(machine.M.UniqueId))
		}

		for fI, field := range machine.Fields {
			switch {
			case field.FieldType == "INT":
				switch {
				case field.FieldSize == 2:
					binary.Write(conn, binary.BigEndian, int16(1000+fI))
				case field.FieldSize == 4:
					binary.Write(conn, binary.BigEndian, int32(1000+fI))
				}
			}
		}

		time.Sleep(time.Duration(10+rand.Int31n(delay)) * time.Millisecond)
		conn.Close()
	} else {
		fmt.Println("timeout")
	}

	channel <- 0
	channelGoCount <- -1
}
Example #3
0
func TestCMSAccuracy(t *testing.T) {
	seed := int64(7364181)
	rand.Seed(seed)
	msb := int32(20)
	numItems := 1000000
	items := make([]int32, numItems)
	cms := streaming.MakeCMS(0.0001, 0.01, seed)
	for i, _ := range items {
		next_msb := uint32(rand.Int31n(msb))
		items[i] = rand.Int31n(int32(1 << next_msb))
		cms.Update(intToBuf(items[i]), float64(1))
	}

	actual := make([]int32, 1<<uint32(msb))
	for _, x := range items {
		actual[x] += 1
	}

	numErrors := 0
	for item, cnt := range actual {
		est, _ := cms.Count(intToBuf(int32(item)))
		diff := math.Abs(est-float64(cnt)) / float64(numItems)
		if diff > 1.0001 {
			numErrors += 1
		}
	}

	if errorRate := float64(numErrors) / float64(len(actual)); errorRate > 0.01 {
		t.Errorf("errorRate %d  > 0.01", errorRate)
	}
}
Example #4
0
func TestRandomCaps(t *testing.T) {
	rc := &RegionCoverer{}
	for i := 0; i < 1000; i++ {
		rc.MinLevel = int(rand.Int31n(maxLevel + 1))
		rc.MaxLevel = int(rand.Int31n(maxLevel + 1))
		for rc.MinLevel > rc.MaxLevel {
			rc.MinLevel = int(rand.Int31n(maxLevel + 1))
			rc.MaxLevel = int(rand.Int31n(maxLevel + 1))
		}
		rc.LevelMod = int(1 + rand.Int31n(3))
		rc.MaxCells = int(skewedInt(10))

		maxArea := math.Min(4*math.Pi, float64(3*rc.MaxCells+1)*AvgAreaMetric.Value(rc.MinLevel))
		r := Region(randomCap(0.1*AvgAreaMetric.Value(rc.MaxLevel), maxArea))

		covering := rc.Covering(r)
		checkCovering(t, rc, &r, covering, false)
		interior := rc.InteriorCovering(r)
		checkCovering(t, rc, &r, interior, true)

		// Check that Covering is deterministic.
		covering2 := rc.Covering(r)
		if !reflect.DeepEqual(covering, covering2) {
			t.Errorf("Iteration %d, got covering = %v, want covering = %v", i, covering2, covering)
		}

		// Also check Denormalize. The denormalized covering
		// may still be different and smaller than "covering" because
		// s2.RegionCoverer does not guarantee that it will not output all four
		// children of the same parent.
		covering.Denormalize(rc.MinLevel, rc.LevelMod)
		checkCovering(t, rc, &r, covering, false)
	}
}
Example #5
0
func (self *Population) evaluate() {
	for k := 0; k < self.conf.CrossoversCount; k++ {
		if rand.Float64() < self.conf.CrossoverProb {
			g1 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]
			g2 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]

			child := g1.Crossover(g2)

			if rand.Float64() < self.conf.MutationProb {
				child.Mutate()
			}
			child.EvalFitness()

			self.P = append(self.P, child)
		}
	}

	self.sort()
	if self.conf.RemoveDuplicates {
		self.removeDuplicates()
	}
	for i := range self.P {
		self.P[i].EvalFitness()
	}
	if len(self.P) > self.conf.PopulationSize {
		self.P = self.P[:self.conf.PopulationSize]
	}
	//	pretty.Println(self.P)
}
Example #6
0
// runMVCCGet first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCGets.
func runMVCCGet(emk engineMaker, numVersions, valueSize int, b *testing.B) {
	const overhead = 48          // Per key/value overhead (empirically determined)
	const targetSize = 512 << 20 // 512 MB
	// Adjust the number of keys so that each test has approximately the same
	// amount of data.
	numKeys := targetSize / ((overhead + valueSize) * (1 + (numVersions-1)/2))

	eng, _ := setupMVCCData(emk, numVersions, numKeys, valueSize, b)
	defer eng.Close()

	b.SetBytes(int64(valueSize))
	b.ResetTimer()

	keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
	for i := 0; i < b.N; i++ {
		// Choose a random key to retrieve.
		keyIdx := rand.Int31n(int32(numKeys))
		key := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(keyIdx)))
		walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1))
		ts := makeTS(walltime, 0)
		if v, _, err := MVCCGet(context.Background(), eng, key, ts, true, nil); err != nil {
			b.Fatalf("failed get: %s", err)
		} else if v == nil {
			b.Fatalf("failed get (key not found): %d@%d", keyIdx, walltime)
		} else if valueBytes, err := v.GetBytes(); err != nil {
			b.Fatal(err)
		} else if len(valueBytes) != valueSize {
			b.Fatalf("unexpected value size: %d", len(valueBytes))
		}
	}

	b.StopTimer()
}
// BenchmarkInsertRR *only* tests insertRR, not the taskRecord funcs.
func BenchmarkInsertRR(b *testing.B) {
	const (
		clusterSize = 1000
		appCount    = 5
	)
	var (
		slaves = make([]string, clusterSize)
		apps   = make([]string, appCount)
		rg     = &RecordGenerator{
			As:   rrs{},
			SRVs: rrs{},
		}
	)
	for i := 0; i < clusterSize; i++ {
		slaves[i] = "slave" + strconv.Itoa(i)
	}
	for i := 0; i < appCount; i++ {
		apps[i] = "app" + strconv.Itoa(i)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		var (
			si = rand.Int31n(clusterSize)
			ai = rand.Int31n(appCount)
		)
		rg.insertRR(apps[ai], slaves[si], "A")
	}
}
Example #8
0
func genValues() {
	for {
		time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
		value := int(rand.Int31n(10) + 1)
		bi.AddValue(bi.Average, "average", value)
		bi.AddValue(bi.Max, "max", value)
		bi.AddValue(bi.Min, "min", value)
		bi.AddValue(bi.Sum, "sum", value)
		value = int(rand.Int31n(10) + 1)
		bi.AddValue(bi.Average, "a.average", value)
		bi.AddValue(bi.Max, "a.max", value)
		bi.AddValue(bi.Min, "a.min", value)
		bi.AddValue(bi.Sum, "a.sum", value)
		value = int(rand.Int31n(10) + 1)
		bi.AddValue(bi.Average, "a.b.average", value)
		bi.AddValue(bi.Max, "a.b.max", value)
		bi.AddValue(bi.Min, "a.c.min", value)
		bi.AddValue(bi.Sum, "a.c.sum", value)
		value = int(rand.Int31n(10) + 1)
		bi.AddValue(bi.Average, "b.average", value)
		bi.AddValue(bi.Max, "b.max", value)
		bi.AddValue(bi.Min, "b.min", value)
		bi.AddValue(bi.Sum, "b.sum", value)
	}
}
Example #9
0
func TestMatchGeoIP(t *testing.T) {
	if g4 == nil {
		t.Skip("no geoip data")
	}
	matches := 0
	hits := 0
	for i := 0; i < N; i++ {
		ips := fmt.Sprintf("%d.%d.%d.%d", rand.Int31n(256), rand.Int31n(256), rand.Int31n(256), rand.Int31n(256))
		ip := net.ParseIP(ips)
		if ip == nil {
			panic("can't parse ip")
		}

		ccn := ipcc.Lookup(ip)
		ccg, _ := g4.GetCountry(ips)
		ccg = strings.ToLower(ccg)

		if ccn == ccg {
			matches++
			if ccn != "" {
				hits++
			}
		}
	}
	r := float32(matches) / N
	t.Log(r, matches, hits)
	if r < 0.9 {
		t.Error("< 90% matches with geoip db")
	}
}
Example #10
0
func TestRGBAToNRGBA(t *testing.T) {
	test := func(r, g, b, a uint16) {
		r1, g1, b1, a1 := RGBAToNRGBA(uint32(r), uint32(g), uint32(b), uint32(a))
		c := color.NRGBA64Model.Convert(color.RGBA64{r, g, b, a}).(color.NRGBA64)
		r2, g2, b2, a2 := uint32(c.R), uint32(c.G), uint32(c.B), uint32(c.A)
		if r1 != r2 || g1 != g2 || b1 != b2 || a1 != a2 {
			t.Errorf("different color: {%d %d %d %d}: got {%d %d %d %d}, want {%d %d %d %d}", r, g, b, a, r1, g1, b1, a1, r2, g2, b2, a2)
		}
	}
	vals := []uint16{0, 0x4000, 0x8000, 0xc000, 0xffff}
	for i, a := range vals {
		for _, r := range vals[:i+1] {
			for _, g := range vals[:i+1] {
				for _, b := range vals[:i+1] {
					test(r, g, b, a)
				}
			}
		}
	}
	for i := 0; i < 1000; i++ {
		a := uint16(rand.Int31n(1 << 16))
		r := uint16(rand.Int31n(int32(a) + 1))
		g := uint16(rand.Int31n(int32(a) + 1))
		b := uint16(rand.Int31n(int32(a) + 1))
		test(r, g, b, a)
	}
}
Example #11
0
func main() {
	rand.Seed(time.Now().Unix())
	port := flag.Int("port", 8081, "the port of the service")
	ip := flag.String("bind", "127.0.0.1", "the ip of the service")
	consumer := flag.String("consumer", "localhost:8070", "consumer hostname and 'admin' port")
	flag.Parse()
	fmt.Printf("Starting the flaky backend at port [%d]\n", *port)

	ticker := time.NewTicker(5 * time.Second)
	go func(ticker *time.Ticker) {
		uri := fmt.Sprintf("http://%s/worker/%s:%d", *consumer, *ip, *port)
		body := url.Values{}
		for _ = range ticker.C {
			http.PostForm(uri, body)
		}
	}(ticker)

	a := gin.Default()
	a.GET("/", func(c *gin.Context) {
		fakeLoad()
		if 90 < rand.Int31n(100) {
			c.String(500, "Internal server error")
		} else {
			products := ""
			for total := rand.Int31n(20); total > 0; total-- {
				products += MakeProduct()
			}
			c.String(200, fmt.Sprintf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<ProductList>%s\n</ProductList>", products))
		}
	})
	a.Run(fmt.Sprintf(":%d", *port))
}
Example #12
0
func (self *noisy_chan) recv_packet(p *network_packet) {

	self.rx_count++
	self.drop_count++ //pre increase

	//drop by lose rate
	if rand.Int31n(100) < int32(self.lose_rate) {
		return
	}

	//drop by capacity
	if self.capacity > 0 && self.packets.Len() >= self.capacity {
		return
	}

	//drop by packet size
	if self.max_packet_size > 0 && len(p.data) > self.max_packet_size {
		return
	}

	self.drop_count-- //backoff

	item := &nosiy_chan_item{p: p, queued_time: time.Now()}

	//50% change of disorder
	self.packets_mutex.Lock()
	if self.disorder && rand.Int31n(100) < 50 && self.packets.Len() > 0 {
		self.packets.InsertBefore(item, self.packets.Back())
	} else {
		self.packets.PushBack(item)
	}
	self.packets_mutex.Unlock()

	self.send_cond.Signal()
}
Example #13
0
// runMVCCGet first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCGets.
func runMVCCGet(numVersions int, b *testing.B) {
	// Use the same number of keys for all of the mvcc get
	// benchmarks. Using a different number of keys per test gives
	// preferential treatment to tests with fewer keys. Note that the
	// datasets all fit in cache and the cache is pre-warmed.
	const numKeys = 100000

	rocksdb := setupMVCCScanData(numVersions, numKeys, b)
	defer rocksdb.Close()

	prewarmCache(rocksdb)

	b.SetBytes(1024)
	b.ResetTimer()

	b.RunParallel(func(pb *testing.PB) {
		keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
		for pb.Next() {
			// Choose a random key to retrieve.
			keyIdx := rand.Int31n(int32(numKeys))
			key := proto.Key(encoding.EncodeUvarint(keyBuf[0:4], uint64(keyIdx)))
			walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1))
			ts := makeTS(walltime, 0)
			if v, _, err := MVCCGet(rocksdb, key, ts, true, nil); err != nil {
				b.Fatalf("failed get: %s", err)
			} else if len(v.Bytes) != 1024 {
				b.Fatalf("unexpected value size: %d", len(v.Bytes))
			}
		}
	})

	b.StopTimer()
}
Example #14
0
func randomHex() (value string) {
	var length = rand.Int31n(10) + 5
	for x := int32(0); x < length; x += 1 {
		value = fmt.Sprintf("%s%02x", value, rand.Int31n(256))
	}
	return
}
Example #15
0
func test_2() {
	const pauseSec time.Duration = 5
	ansiterm.ClearPage()
	ansiterm.MoveToRC(9, 20)
	fmt.Printf("In a few seconds program will print 1000 X chars")
	ansiterm.MoveToRC(10, 20)
	fmt.Printf("This is slowed by forcing a 10 ms sleep per loop")
	pause(pauseSec)
	ansiterm.ClearPage()
	for i := 0; i < 1000; i++ {
		row := int(rand.Int31n(25))
		col := int(rand.Int31n(80))
		ansiterm.MoveToRC(row, col)
		time.Sleep(time.Duration(0.01 * float64(time.Second)))
		fmt.Printf("X")
	}
	pause(pauseSec)
	ansiterm.ClearPage()
	ansiterm.MoveToRC(9, 20)
	fmt.Printf("In a few seconds program will print 1000 X chars")
	ansiterm.MoveToRC(10, 20)
	fmt.Printf("using the same program at FULL speed - don't blink...")
	pause(pauseSec)
	ansiterm.ClearPage()
	for i := 0; i < 1000; i++ {
		row := int(rand.Int31n(25))
		col := int(rand.Int31n(80))
		ansiterm.MoveToRC(row, col)
		fmt.Printf("X")
	}
	pause(pauseSec)
	ansiterm.ClearPage()
}
Example #16
0
// Generate a random address, of the form '123 Watermelon Ave\nExampleTown, KS'
func Address() string {
	number := rand.Int31n(10000)
	street := strings.Title(Words[rand.Int31n(int32(len(Words)))])
	sType := StreetType[rand.Int31n(int32(len(StreetType)))]
	state := State[rand.Int31n(int32(len(State)))]
	return fmt.Sprintf("%d %s %s\nExampleTown, %s", number, street, sType, state)
}
Example #17
0
// runMVCCScan first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCScans in increments of numRows
// keys over all of the data in the Engine instance, restarting at
// the beginning of the keyspace, as many times as necessary.
func runMVCCScan(emk engineMaker, numRows, numVersions, valueSize int, b *testing.B) {
	// Use the same number of keys for all of the mvcc scan
	// benchmarks. Using a different number of keys per test gives
	// preferential treatment to tests with fewer keys. Note that the
	// datasets all fit in cache and the cache is pre-warmed.
	const numKeys = 100000

	eng, _ := setupMVCCData(emk, numVersions, numKeys, valueSize, b)
	defer eng.Close()

	b.SetBytes(int64(numRows * valueSize))
	b.ResetTimer()

	keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
	for i := 0; i < b.N; i++ {
		// Choose a random key to start scan.
		keyIdx := rand.Int31n(int32(numKeys - numRows))
		startKey := roachpb.Key(encoding.EncodeUvarintAscending(keyBuf[:4], uint64(keyIdx)))
		walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1))
		ts := makeTS(walltime, 0)
		kvs, _, _, err := MVCCScan(context.Background(), eng, startKey, keyMax, int64(numRows), ts, true, nil)
		if err != nil {
			b.Fatalf("failed scan: %s", err)
		}
		if len(kvs) != numRows {
			b.Fatalf("failed to scan: %d != %d", len(kvs), numRows)
		}
	}

	b.StopTimer()
}
Example #18
0
func TestMatchGeoIPv6(t *testing.T) {
	if g6 == nil {
		t.Skip("no geoip data")
	}
	matches := 0
	hits := 0
	for i := 0; i < N; i++ {
		p := []int32{0x2001, 0x2607, 0x2610, 0x2620, 0x2800, 0x2801, 0x2804, 0x2806}
		ips := fmt.Sprintf("%x:%x:%x:%x:%x:%x:%x:%x", p[rand.Int31n(int32(len(p)))], rand.Int31n(0x10000), rand.Int31n(0x10000), rand.Int31n(0x10000), rand.Int31n(0x10000), rand.Int31n(0x10000), rand.Int31n(0x10000), rand.Int31n(0x10000))

		ip := net.ParseIP(ips)
		if ip == nil {
			panic("can't parse ip")
		}

		ccn := ipcc.Lookup(ip)
		ccg, _ := g6.GetCountry_v6(ips)
		ccg = strings.ToLower(ccg)

		if ccn == ccg {
			matches++
			if ccn != "" {
				hits++
			}
		}
	}
	r := float32(matches) / N
	t.Log(r, matches, hits)
	if r < 0.8 {
		t.Error("< 90% matches with geoip db")
	}
}
Example #19
0
// Schedule incoming tasks. Randomly selects 2 workers and inserts new task to both
// work queus.
func (s *Scheduler) Run() {
	var t *Task
	s.running = true

	irr := 0 // round-robin index
	for true {
		t = <-s.inqueue
		if t == nil {
			break
		}

		if len(s.workers) == 1 {
			sendTask(s.workers[0].queue, t)
		} else if s.rrsched || len(s.workers) == 2 {
			// round-robin scheduling
			sendTask(s.workers[irr].queue, t)
			irr = (irr + 1) % len(s.workers)
			sendTask(s.workers[irr].queue, t)
			irr = (irr + 1) % len(s.workers)
		} else {
			var k, j int32
			// random scheduling
			k = rand.Int31n(int32(len(s.workers)))
			for j = k; j == k; j = rand.Int31n(int32(len(s.workers))) {
			}
			sendTask(s.workers[k].queue, t)
			sendTask(s.workers[j].queue, t)
		}
	}
	// stopping
	for _, w := range s.workers {
		w.Stop()
	}
	s.running = false
}
Example #20
0
func TestDotInt32WithDiffLength(t *testing.T) {
	N := 1000 + rand.Intn(1000000)
	M := 1000 + rand.Intn(1000000)
	a := make([]int32, N)
	b := make([]int32, M)
	expected64 := int64(0)
	for i := range a {
		if i < N {
			a[i] = gomath.ScaleInt32(LowInt32, HighInt32, 0, HighInt32, rand.Int31n(HighInt32))
		}
		if i < M {
			b[i] = gomath.ScaleInt32(LowInt32, HighInt32, 0, HighInt32, rand.Int31n(HighInt32))
		}

		if i < N && i < M {
			expected64 += int64(a[i]) * int64(b[i])
		}
	}

	Expected := int32(expected64)
	Computed := DotInt32(a, b)

	if Computed != Expected {
		t.Logf("Expected %d but computed %d\n", Expected, Computed)
		t.FailNow()
	}
}
Example #21
0
// runMVCCScan first creates test data (and resets the benchmarking
// timer). It then performs b.N MVCCScans in increments of numRows
// keys over all of the data in the rocksdb instance, restarting at
// the beginning of the keyspace, as many times as necessary.
func runMVCCScan(numRows, numVersions int, b *testing.B) {
	// Use the same number of keys for all of the mvcc scan
	// benchmarks. Using a different number of keys per test gives
	// preferential treatment to tests with fewer keys. Note that the
	// datasets all fit in cache and the cache is pre-warmed.
	const numKeys = 100000

	rocksdb := setupMVCCScanData(numVersions, numKeys, b)
	defer rocksdb.Close()

	prewarmCache(rocksdb)

	b.SetBytes(int64(numRows * 1024))
	b.ResetTimer()

	b.RunParallel(func(pb *testing.PB) {
		keyBuf := append(make([]byte, 0, 64), []byte("key-")...)
		for pb.Next() {
			// Choose a random key to start scan.
			keyIdx := rand.Int31n(int32(numKeys - numRows))
			startKey := proto.Key(encoding.EncodeUvarint(keyBuf[0:4], uint64(keyIdx)))
			walltime := int64(5 * (rand.Int31n(int32(numVersions)) + 1))
			ts := makeTS(walltime, 0)
			kvs, _, err := MVCCScan(rocksdb, startKey, proto.KeyMax, int64(numRows), ts, true, nil)
			if err != nil {
				b.Fatalf("failed scan: %s", err)
			}
			if len(kvs) != numRows {
				b.Fatalf("failed to scan: %d != %d", len(kvs), numRows)
			}
		}
	})

	b.StopTimer()
}
Example #22
0
func TestTimestampOption(t *testing.T) {
	for i := 0; i < K; i++ {
		t0 := uint32(rand.Int31n(TimestampRange))
		delta := uint32(rand.Int31n(ElapsedRange))
		t1 := t0 + delta
		opt0 := &TimestampOption{t0}
		opt1 := &TimestampOption{t1}
		opt0_, err1 := opt0.Encode()
		opt1_, err2 := opt1.Encode()
		if err1 != nil || err2 != nil {
			t.Fatalf("error encoding timestamp option")
		}
		opt0 = DecodeTimestampOption(opt0_)
		opt1 = DecodeTimestampOption(opt1_)
		if opt0 == nil || opt1 == nil {
			t.Fatalf("decoding timestamp error")
		}
		t0_ := opt0.Timestamp
		t1_ := opt1.Timestamp
		delta_ := TenMicroDiff(t0_, t1_)
		if delta != delta_ {
			t.Errorf("Expecting %d, got %d", delta, delta_)
		}
	}
}
Example #23
0
func randChar() byte {
	start, end := 'a', 'z'
	if rand.Int31n(2) == 1 {
		start, end = 'A', 'Z'
	}
	return byte(rand.Int31n(end-start+1) + start)
}
Example #24
0
func rndUserBody() (string, string) {
	ui := rand.Int31n(int32(len(sampleUsers)))
	bi := rand.Int31n(int32(len(sampleBodies)))
	u := sampleUsers[ui]
	b := sampleBodies[bi]

	return u, b
}
Example #25
0
// Generate a random date, usable for date of birth generation.
func GenerateRandomDate() time.Time {
	day := int(rand.Int31n(27)) + 1
	month := (time.Month)(rand.Int31n(11) + 1)
	if month == time.February && day > 27 {
		day = 27
	}
	year := time.Now().Year() - int(rand.Int31n(90))
	return time.Date(year, month, day, 12, 0, 0, 0, time.UTC)
}
Example #26
0
func nothing(id int64) {
	var i int32
	rep := rand.Int31n(10) + 5
	wa := rand.Int31n(5)
	for i = 0; i < rep; i++ {
		fmt.Printf("Boucle %d avant %d secondes d'attente\n", id, wa)
		time.Sleep(time.Duration(wa) * time.Second)
	}
}
func TestNewWithRandEpsilon(t *testing.T) {

	for i := 0; i < 100; i++ {

		size := 1 + uint64(rand.Int63n(1000))

		// rand.Float64() returns [0,1)
		epsilon := rand.Float64()

		x := New(size, epsilon)

		if nil == x {
			t.Errorf("Expected a non-nil return for epsilon [%v]", epsilon)
		}

		if epsilon != x.epsilon {
			t.Errorf("Stored epsilon and test epsilon are different for size [%+v] and epsilon [%+v] and object [%+v]", size, epsilon, x)
		}

		if size != x.size {
			t.Errorf("Stored size and test size are different for size [%+v] and epsilon [%+v] and object [%+v]", size, epsilon, x)
		}

		if size != uint64(len(x.counts)) {
			t.Errorf("Length of stored counts and test size are different for size [%+v] and epsilon [%+v] and object [%+v]", size, epsilon, x)
		}

		if size != uint64(len(x.values)) {
			t.Errorf("Length of stored values and test size are different for size [%+v] and epsilon [%+v] and object [%+v]", size, epsilon, x)
		}
	}

	for i := 0; i < 100; i++ {

		size := 1 + uint64(rand.Int63n(1000))

		// rand.Float64() returns [0,1)
		epsilon := 1 + rand.Float64()
		if 0 == rand.Int31n(1) {
			epsilon += rand.Float64()
		}
		if 0 == rand.Int31n(1) {
			epsilon *= 1 + rand.Float64()
		}
		if 0 == rand.Int31n(1) {
			epsilon *= -1
		}

		x := New(size, epsilon)

		if nil != x {
			t.Errorf("Expected a nil return for size [%+v] and epsilon [%v]", size, epsilon)
		}
	}

}
Example #28
0
func fakeLoad() {
	rnd := rand.Int31n(100)
	if 20 > rnd {
		time.Sleep(time.Duration(rand.Int31n(10)) * time.Millisecond)
	} else if 70 > rnd {
		time.Sleep(time.Duration(rand.Int31n(50)+50) * time.Millisecond)
	} else if 95 > rnd {
		time.Sleep(time.Duration(rand.Int31n(500)+200) * time.Millisecond)
	}
}
Example #29
0
func generate_mines(field *Minefield) {
	for m := 0; int32(m) < field.Mines; m++ {
		r, c := rand.Int31n(field.Rows), rand.Int31n(field.Cols)
		if field.Fields[r][c] != 0 {
			m -= 1
		} else {
			field.Fields[r][c] = 'x'
		}
	}
}
Example #30
0
func tempSensor(t chan int) {
	tempreading := 32
	for {
		sleepytime := rand.Int31n(10)
		time.Sleep(time.Duration(sleepytime) * time.Second)
		newtemp := int(rand.Int31n(100) + 32)
		tempreading = (tempreading*95 + newtemp*5) / 100
		t <- tempreading
	}
}