func main() {
	p := fmt.Print

	p(rand.Intn(100), ",")
	p(rand.Intn(100))
	p("\n")

	p(rand.Float64(), "\n")

	p((rand.Float64()*5)+5, ",")
	p((rand.Float64() * 5) + 5)
	p("\n")

	s1 := rand.NewSource(42)
	r1 := rand.New(s1)

	p(r1.Intn(100), ",")
	p(r1.Intn(100))
	p("\n")

	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	p(r2.Intn(100), ",")
	p(r2.Intn(100))
	p("\n")
}
Example #2
0
func main() {
	//例如,rand.Intn 返回一个随机的整数 n,0 <= n <= 100。
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()
	//rand.Float64 返回一个64位浮点数 f,0.0 <= f <= 1.0。
	fmt.Println(rand.Float64())
	//这个技巧可以用来生成其他范围的随机浮点数,例如5.0 <= f <= 10.0
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()
	//要让伪随机数生成器有确定性,可以给它一个明确的种子。
	s1 := rand.NewSource(42)
	r1 := rand.New(s1)
	//调用上面返回的 rand.Source 的函数和调用 rand 包中函数是相同的。
	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()
	//如果使用相同的种子生成的随机数生成器,将会产生相同的随机数序列。
	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
}
Example #3
0
func main() {
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	fmt.Println(rand.Float64())
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1)

	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
	s3 := rand.NewSource(42)
	r3 := rand.New(s3)
	fmt.Print(r3.Intn(100), ",")
	fmt.Print(r3.Intn(100))
}
Example #4
0
// Fuzz test for N iterations
func testTypeFuzzN(t *testing.T, base interface{}, ff interface{}, n int) {
	require.Implements(t, (*json.Marshaler)(nil), ff)
	require.Implements(t, (*json.Unmarshaler)(nil), ff)
	require.Implements(t, (*marshalerFaster)(nil), ff)
	require.Implements(t, (*unmarshalFaster)(nil), ff)

	if _, ok := base.(unmarshalFaster); ok {
		require.FailNow(t, "base should not have a UnmarshalJSONFFLexer")
	}

	if _, ok := base.(marshalerFaster); ok {
		require.FailNow(t, "base should not have a MarshalJSONBuf")
	}

	f := fuzz.New()
	f.NumElements(0, 1+n/40)
	f.NilChance(0.2)
	f.Funcs(fuzzTime, fuzzTimeSlice)
	for i := 0; i < n; i++ {
		f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
		f.Fuzz(base)
		f.RandSource(rand.New(rand.NewSource(int64(i * 5275))))
		f.Fuzz(ff)

		testSameMarshal(t, base, ff)
		testCycle(t, base, ff)
	}
}
Example #5
0
func main() {
	//For example, rand.Intn returns a random int n, 0 <= n < 100.
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	//rand.Float64 returns a float64 f, 0.0 <= f < 1.0.
	fmt.Println(rand.Float64())

	//This can be used to generate random floats in other ranges, for example 5.0 <= f' < 10.0.
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	//The default number generator is deterministic, so it’ll produce the same sequence of numbers each time by default. To produce varying sequences, give it a seed that changes. Note that this is not safe to use for random numbers you intend to be secret, use crypto/rand for those.
	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1)

	//Call the resulting rand.Rand just like the functions on the rand package.
	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	//If you seed a source with the same number, it produces the same sequence of random numbers.
	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
	s3 := rand.NewSource(42)
	r3 := rand.New(s3)
	fmt.Print(r3.Intn(100), ",")
	fmt.Print(r3.Intn(100))
}
Example #6
0
func main() {
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	fmt.Println(rand.Float64())

	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	s1 := rand.NewSource(42)
	r1 := rand.New(s1)

	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()

}
Example #7
0
// TestbinaryDecoderBlockTable tests many combinations of fountain block ID
// combinations to ensure that the codec has the expected reconstruction
// properties.
func TestBinaryDecoderBlockTable(t *testing.T) {
	c := NewBinaryCodec(13)

	message := []byte("abcdefghijklmnopqrstuvwxyz")
	random := rand.New(rand.NewSource(8234923))

	moreBlocksNeeded := 0
	for i := 0; i < 100; i++ {
		r := rand.New(rand.NewSource(random.Int63()))
		ids := make([]int64, 45)
		for i := range ids {
			ids[i] = int64(r.Intn(100000))
		}
		blocks := EncodeLTBlocks(message, ids, c)

		d := newBinaryDecoder(c.(*binaryCodec), len(message))
		d.AddBlocks(blocks[0:30])
		if !d.matrix.determined() {
			moreBlocksNeeded++
			d.AddBlocks(blocks[31:46])
		}
		decoded := d.Decode()
		if !reflect.DeepEqual(decoded, message) {
			t.Errorf("Decoded message doesn't match original. Got %v, want %v", decoded, message)
		}
	}

	if moreBlocksNeeded > 2 {
		t.Errorf("Needed too many high-block-count decoding sequences: %d", moreBlocksNeeded)
	}
}
Example #8
0
// TestBinaryDecodeMessageTable tests a large number of source messages to make
// sure they are all reconstructed accurately. This provides assurance that the
// decoder is functioning accurately.
func TestBinaryDecodeMessageTable(t *testing.T) {
	c := NewBinaryCodec(10)
	random := rand.New(rand.NewSource(8234982))
	for i := 0; i < 100; i++ {
		r := rand.New(rand.NewSource(random.Int63()))
		messageLen := r.Intn(1000) + 1000
		message := make([]byte, messageLen)
		for j := 0; j < len(message); j++ {
			message[j] = byte(r.Intn(200))
		}
		ids := make([]int64, 50)
		for i := range ids {
			ids[i] = int64(r.Intn(100000))
		}
		blocks := EncodeLTBlocks(message, ids, c)

		d := newBinaryDecoder(c.(*binaryCodec), len(message))
		d.AddBlocks(blocks[0:25])
		if !d.matrix.determined() {
			t.Errorf("Message should be determined after 25 blocks")
		} else {
			decoded := d.Decode()
			if !reflect.DeepEqual(decoded, message) {
				t.Errorf("Incorrect message decode. Length=%d, message=%v", len(message), message)
			}
		}
	}
}
Example #9
0
func TestDecodeMessageTable(t *testing.T) {
	c := NewOnlineCodec(10, 0.2, 7, 0).(*onlineCodec)
	random := rand.New(rand.NewSource(8234982))
	for i := 0; i < 100; i++ {
		c.randomSeed = random.Int63()
		r := rand.New(rand.NewSource(random.Int63()))
		messageLen := r.Intn(1000) + 1000
		message := make([]byte, messageLen)
		for j := 0; j < len(message); j++ {
			message[j] = byte(r.Intn(200))
		}
		ids := make([]int64, 50)
		for i := range ids {
			ids[i] = int64(r.Intn(100000))
		}
		blocks := encodeOnlineBlocks(message, ids, *c)

		d := newOnlineDecoder(c, len(message))
		d.AddBlocks(blocks[0:25])
		if !d.matrix.determined() {
			t.Errorf("Message should be determined after 25 blocks")
		} else {
			decoded := d.Decode()
			if !reflect.DeepEqual(decoded, message) {
				t.Errorf("Incorrect message decode. Length=%d", len(message))
			}
		}
	}
}
Example #10
0
func main() {
	// 例如`rand.Intn`返回一个整型随机数n,0<=n<100
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	// `rand.Float64` 返回一个`float64` `f`,
	// `0.0 <= f < 1.0`
	fmt.Println(rand.Float64())

	// 这个方法可以用来生成其他数值范围内的随机数,
	// 例如`5.0 <= f < 10.0`
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	// 为了使随机数生成器具有确定性,可以给它一个seed
	s1 := rand.NewSource(42)
	r1 := rand.New(s1)

	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	// 如果源使用一个和上面相同的seed,将生成一样的随机数
	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
}
Example #11
0
// Marshals a Message and hands it to the Stack. If toSelf is true,
// the message is also dispatched to the local instance's RecvMsgSync.
func (instance *pbftCore) innerBroadcast(msg *Message) error {
	msgRaw, err := proto.Marshal(msg)
	if err != nil {
		return fmt.Errorf("Cannot marshal message %s", err)
	}

	doByzantine := false
	if instance.byzantine {
		rand1 := rand.New(rand.NewSource(time.Now().UnixNano()))
		doIt := rand1.Intn(3) // go byzantine about 1/3 of the time
		if doIt == 1 {
			doByzantine = true
		}
	}

	// testing byzantine fault.
	if doByzantine {
		rand2 := rand.New(rand.NewSource(time.Now().UnixNano()))
		ignoreidx := rand2.Intn(instance.N)
		for i := 0; i < instance.N; i++ {
			if i != ignoreidx && uint64(i) != instance.id { //Pick a random replica and do not send message
				instance.consumer.unicast(msgRaw, uint64(i))
			} else {
				logger.Debugf("PBFT byzantine: not broadcasting to replica %v", i)
			}
		}
	} else {
		instance.consumer.broadcast(msgRaw)
	}
	return nil
}
Example #12
0
func outOfOrder(l *list.List) {
	iTotal := 25
	if iTotal > l.Len() {
		iTotal = l.Len()
	}
	ll := make([]*list.List, iTotal)

	for i := 0; i < iTotal; i++ {
		ll[i] = list.New()
	}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for e := l.Front(); e != nil; e = e.Next() {
		fpath, ok := e.Value.(string)
		if !ok {
			panic("The path is invalid string")
		}
		if rand.Int()%2 == 0 {
			ll[r.Intn(iTotal)].PushFront(fpath)
		} else {
			ll[r.Intn(iTotal)].PushBack(fpath)
		}
	}

	r0 := rand.New(rand.NewSource(time.Now().UnixNano()))
	l.Init()
	for i := 0; i < iTotal; i++ {
		if r0.Intn(2) == 0 {
			l.PushBackList(ll[i])
		} else {
			l.PushFrontList(ll[i])
		}
		ll[i].Init()
	}
}
Example #13
0
func main() {
	fmt.Print(rand.Intn(100), ",") // rand.Intn returns random in between 0,99
	fmt.Print(rand.Intn(100))
	fmt.Println()
	fmt.Println(rand.Float64) // random float f where 0.0 <= f < 1.0
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5) // float f where 5.0 <= 5 < 10.0
	fmt.Println()

	// default random number generator will produce same sequence of numbers by default
	// give it a seed that changes for varying sequences
	// if you seed a source with the same number, it produces the same sequence of random numbers
	// USE crypto/rand FOR SECRET RANDOM NUMBERS
	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1)
	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
	s3 := rand.NewSource(42)
	r3 := rand.New(s3)
	fmt.Print(r3.Intn(100), ",")
	fmt.Print(r2.Intn(100))
}
Example #14
0
func main() {
	// For example, `rand.Intn` returns a random `int` n,
	// `0 <= n < 100`.
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	// `rand.Float64` returns a `float64` `f`,
	// `0.0 <= f < 1.0`.
	fmt.Println(rand.Float64())

	// To make the psuedo-random generator deterministic,
	// give it a well-known seed.
	s1 := rand.NewSource(42)
	r1 := rand.New(s1)

	// Call the resulting `rand.Source` just like the
	// functions on the `rand` package.
	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	// If you seed a source with the same number, it
	// produces the same sequence of random numbers.
	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
}
Example #15
0
func Test(t *testing.T) {
	t.Parallel()

	Convey("test mathrand", t, func() {
		now := time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)
		c, _ := testclock.UseTime(context.Background(), now)

		// Note that the non-randomness below is because time is fixed at the
		// top of the outer test function. Normally it would evolve with time.
		Convey("unset", func() {
			r := rand.New(rand.NewSource(now.UnixNano()))
			i := r.Int()
			So(Get(c).Int(), ShouldEqual, i)
			So(Get(c).Int(), ShouldEqual, i)
		})

		Convey("set persistance", func() {
			c = Set(c, rand.New(rand.NewSource(now.UnixNano())))
			r := rand.New(rand.NewSource(now.UnixNano()))
			So(Get(c).Int(), ShouldEqual, r.Int())
			So(Get(c).Int(), ShouldEqual, r.Int())
		})

		Convey("nil set", func() {
			c = Set(c, nil)
			r := rand.New(rand.NewSource(now.UnixNano()))
			i := r.Int()
			So(Get(c).Int(), ShouldEqual, i)
			So(Get(c).Int(), ShouldEqual, i)
		})
	})
}
Example #16
0
// MakeAllocator creates a new allocator using the specified StorePool.
func MakeAllocator(storePool *StorePool, options AllocatorOptions) Allocator {
	var randSource rand.Source
	if options.Deterministic {
		randSource = rand.NewSource(777)
	} else {
		randSource = rand.NewSource(rand.Int63())
	}
	a := Allocator{
		storePool: storePool,
		options:   options,
		randGen:   makeAllocatorRand(randSource),
	}

	// Instantiate balancer based on provided options.
	switch options.Mode {
	case BalanceModeUsage:
		a.balancer = usageBalancer{a.randGen}
	case BalanceModeRangeCount:
		a.balancer = rangeCountBalancer{a.randGen}
	default:
		panic(fmt.Sprintf("AllocatorOptions specified invalid BalanceMode %d", options.Mode))
	}

	return a
}
func main() {

	// rand.Intn return a random int n, 0 <= n < 100
	fmt.Print(rand.Intn(100), ",")
	fmt.Print(rand.Intn(100))
	fmt.Println()

	//rand.Float64 returns a float64, 0.0 <= f < 1.0
	fmt.Println(rand.Float64())

	// can be used to generate random floats in other ranges
	// for example 5.0 <= f < 10.0
	fmt.Print((rand.Float64()*5)+5, ",")
	fmt.Print((rand.Float64() * 5) + 5)
	fmt.Println()

	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1)

	fmt.Print(r1.Intn(100), ",")
	fmt.Print(r1.Intn(100))
	fmt.Println()

	s2 := rand.NewSource(42)
	r2 := rand.New(s2)
	fmt.Print(r2.Intn(100), ",")
	fmt.Print(r2.Intn(100))
	fmt.Println()
	s3 := rand.NewSource(42)
	r3 := rand.New(s3)
	fmt.Print(r3.Intn(100), ",")
	fmt.Print(r3.Intn(100))
}
Example #18
0
func New(db database.Database, dbConfig config.DbConfig) strategy.Strategy {
	return &rankStrategy{
		isNewRand: rand.New(rand.NewSource(time.Now().Unix())),
		rankRand:  rand.New(rand.NewSource(time.Now().Add(time.Hour).Unix())),
		db:        db,
		dbConfig:  dbConfig,
	}
}
Example #19
0
func TestTargetRequest(t *testing.T) {
	t.Parallel()

	body := []byte(`{"id": "{foo}", "value": "bar"}`)

	tgt := Target{
		Method: "GET",
		URL:    "http://{foo}:9999/",
		Body:   body,
		Header: http.Header{
			"X-Some-Header":       []string{"1"},
			"X-Some-Other-Header": []string{"2"},
			"X-Some-New-Header":   []string{"3"},
			"Host":                []string{"lolcathost"},
		},
		URLInterpolators: []URLInterpolator{
			&RandomNumericInterpolation{
				Key:   "{foo}",
				Limit: int(^uint(0) >> 1),
				Rand:  rand.New(rand.NewSource(1435875839)),
			},
		},
		BodyInterpolators: []BodyInterpolator{
			&RandomNumericInterpolation{
				Key:   "{foo}",
				Limit: int(^uint(0) >> 1),
				Rand:  rand.New(rand.NewSource(1435875839)),
			},
		},
	}
	req, _ := tgt.Request()

	reqBody, err := ioutil.ReadAll(req.Body)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal([]byte(`{"id": "2290778204292519845", "value": "bar"}`), reqBody) {
		t.Fatalf("Target body wasn't copied correctly")
	}

	if req.URL.String() != "http://2290778204292519845:9999/" {
		t.Fatalf("Target URL wasn't resolved correctly")
	}

	tgt.Header.Set("X-Stuff", "0")
	if req.Header.Get("X-Stuff") == "0" {
		t.Error("Each Target must have its own Header")
	}

	want, got := tgt.Header.Get("Host"), req.Header.Get("Host")
	if want != got {
		t.Fatalf("Target Header wasn't copied correctly. Want: %s, Got: %s", want, got)
	}
	if req.Host != want {
		t.Fatalf("Target Host wasnt copied correctly. Want: %s, Got: %s", want, req.Host)
	}
}
Example #20
0
func TestPregeneratorIdempotency(t *testing.T) {
	seed := time.Now().UnixNano()
	rnga, rngb := rand.NewSource(seed), Pregenerate(rand.NewSource(seed), 1024)
	for i := 0; i < 10000; i++ {
		if a, b := rnga.Int63(), rngb.Int63(); a != b {
			t.Error("mismatch after", i, "iterations")
		}
	}
}
Example #21
0
func TestRandomIntFromDist(t *testing.T) {

	dist := []float64{0.1, 0.2, 0.3, 0.4}

	r := rand.New(rand.NewSource(33))
	res1 := make([]int, 100, 100)
	for range res1 {
		res1 = append(res1, RandIntFromDist(dist, r))
	}

	// Checking that experiments are repeatable.
	r = rand.New(rand.NewSource(33))
	res2 := make([]int, 100, 100)
	for range res2 {
		res2 = append(res2, RandIntFromDist(dist, r))
	}

	gjoa.CompareSliceInt(t, res1, res1, "sequence mismatch")

	r = rand.New(rand.NewSource(33))
	res := make(map[int]float64)
	var n float64 = 100000
	for i := 0.0; i < n; i++ {
		res[RandIntFromDist(dist, r)]++
	}

	actual := make([]float64, len(dist), len(dist))
	for k, v := range res {
		p := v / n
		t.Log(k, v, p)
		actual[k] = p
	}

	gjoa.CompareSliceFloat(t, dist, actual, "probs don't match, error in RandIntFromDist", 0.02)

	// same with log probs
	logDist := make([]float64, len(dist), len(dist))
	for k, v := range dist {
		logDist[k] = math.Log(v)
	}

	r = rand.New(rand.NewSource(33))
	res = make(map[int]float64)
	for i := 0.0; i < n; i++ {
		res[RandIntFromLogDist(logDist, r)]++
	}

	for k, v := range res {
		p := v / n
		t.Log(k, v, p)
		actual[k] = p
	}

	gjoa.CompareSliceFloat(t, dist, actual, "probs don't match, error in RandIntFromLogDist", 0.02)

}
Example #22
0
func TestLRUCache_ConcurrentSetGet(t *testing.T) {
	runtime.GOMAXPROCS(runtime.NumCPU())

	seed := time.Now().UnixNano()
	t.Logf("seed=%d", seed)

	const (
		N = 2000000
		M = 4000
		C = 3
	)

	var set, get uint32

	wg := &sync.WaitGroup{}
	c := NewLRUCache(M / 4)
	for ni := uint64(0); ni < C; ni++ {
		r0 := rand.New(rand.NewSource(seed + int64(ni)))
		r1 := rand.New(rand.NewSource(seed + int64(ni) + 1))
		ns := c.GetNamespace(ni)

		wg.Add(2)
		go func(ns Namespace, r *rand.Rand) {
			for i := 0; i < N; i++ {
				x := uint64(r.Int63n(M))
				o := ns.Get(x, func() (int, interface{}) {
					atomic.AddUint32(&set, 1)
					return 1, x
				})
				if v := o.Value().(uint64); v != x {
					t.Errorf("#%d invalid value, got=%d", x, v)
				}
				o.Release()
			}
			wg.Done()
		}(ns, r0)
		go func(ns Namespace, r *rand.Rand) {
			for i := 0; i < N; i++ {
				x := uint64(r.Int63n(M))
				o := ns.Get(x, nil)
				if o != nil {
					atomic.AddUint32(&get, 1)
					if v := o.Value().(uint64); v != x {
						t.Errorf("#%d invalid value, got=%d", x, v)
					}
					o.Release()
				}
			}
			wg.Done()
		}(ns, r1)
	}

	wg.Wait()

	t.Logf("set=%d get=%d", set, get)
}
Example #23
0
// Returns some random start position for a sun, before starting
// to move it over the galaxy
func getRandomStartPosition(scope int) *vec2d.Vector {
	xSeed := time.Now().UTC().UnixNano()
	ySeed := time.Now().UTC().UnixNano()
	xGenerator := rand.New(rand.NewSource(xSeed))
	yGenerator := rand.New(rand.NewSource(ySeed))
	return vec2d.New(
		float64(xGenerator.Intn(scope)-scope/2),
		float64(yGenerator.Intn(scope)-scope/2),
	)
}
Example #24
0
func main() {
	channel := Channel{tail: 0, head: 0, count: 0}
	channel.init(5)
	channel.startWorkers()
	go ClientThread{channel: &channel, random: rand.New(rand.NewSource(time.Now().Unix()))}.Start("Alice")
	go ClientThread{channel: &channel, random: rand.New(rand.NewSource(time.Now().Unix()))}.Start("Bobby")
	go ClientThread{channel: &channel, random: rand.New(rand.NewSource(time.Now().Unix()))}.Start("Chris")

	select {}
}
Example #25
0
func NewDice(seed int) dice {
	d := dice{}

	if seed != -1 {
		d.r = rand.New(rand.NewSource(int64(seed)))
	} else {
		d.r = rand.New(rand.NewSource(time.Now().UnixNano()))
	}
	return d
}
Example #26
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	requestQueue := RequestQueue{queue: list.New()}
	clientThread := ClientThread{random: rand.New(rand.NewSource(time.Now().UnixNano())), requestQueue: requestQueue}
	serverThread := ServerThread{random: rand.New(rand.NewSource(time.Now().UnixNano())), requestQueue: requestQueue}
	go clientThread.run()
	go serverThread.run()

	select {}
}
Example #27
0
// lostrate: 往返一周丢包率的百分比,默认 10%
// rttmin:rtt最小值,默认 60
// rttmax:rtt最大值,默认 125
//func (p *LatencySimulator)Init(int lostrate = 10, int rttmin = 60, int rttmax = 125, int nmax = 1000):
func (p *LatencySimulator) Init(lostrate, rttmin, rttmax, nmax int) {
	p.r12 = rand.New(rand.NewSource(9))
	p.r21 = rand.New(rand.NewSource(99))
	p.p12 = DelayTunnel{list.New()}
	p.p21 = DelayTunnel{list.New()}
	p.current = iclock()
	p.lostrate = lostrate / 2 // 上面数据是往返丢包率,单程除以2
	p.rttmin = rttmin / 2
	p.rttmax = rttmax / 2
	p.nmax = nmax
}
Example #28
0
func Rand(v ...*big.Int) (*big.Int, error) {
	switch len(v) {
	case 1:
		return new(big.Int).Rand(rand.New(rand.NewSource(time.Now().UnixNano())), v[0]), nil
	case 2:
		delta := new(big.Int).Sub(v[1], v[0])
		r := new(big.Int).Rand(rand.New(rand.NewSource(time.Now().UnixNano())), delta)
		return r.Add(r, v[0]), nil
	}
	return nil, ArgCountErr
}
Example #29
0
func TestGenStar(t *testing.T) {
	t.Parallel()

	Convey("Star", t, func() {
		ConveyGeneratesStringMatchingItself(nil, "a*")

		Convey("HitsDefaultMin", func() {
			regexp := "a*"
			args := &GeneratorArgs{
				RngSource: rand.NewSource(0),
			}
			counts := generateLenHistogram(regexp, DefaultMaxUnboundedRepeatCount, args)

			So(counts[0], ShouldBeGreaterThan, 0)
		})

		Convey("HitsCustomMin", func() {
			regexp := "a*"
			args := &GeneratorArgs{
				RngSource:               rand.NewSource(0),
				MinUnboundedRepeatCount: 200,
			}
			counts := generateLenHistogram(regexp, DefaultMaxUnboundedRepeatCount, args)

			So(counts[200], ShouldBeGreaterThan, 0)
			for i := 0; i < 200; i++ {
				So(counts[i], ShouldEqual, 0)
			}
		})

		Convey("HitsDefaultMax", func() {
			regexp := "a*"
			args := &GeneratorArgs{
				RngSource: rand.NewSource(0),
			}
			counts := generateLenHistogram(regexp, DefaultMaxUnboundedRepeatCount, args)

			So(len(counts), ShouldEqual, DefaultMaxUnboundedRepeatCount+1)
			So(counts[DefaultMaxUnboundedRepeatCount], ShouldBeGreaterThan, 0)
		})

		Convey("HitsCustomMax", func() {
			regexp := "a*"
			args := &GeneratorArgs{
				RngSource:               rand.NewSource(0),
				MaxUnboundedRepeatCount: 200,
			}
			counts := generateLenHistogram(regexp, 200, args)

			So(len(counts), ShouldEqual, 200+1)
			So(counts[200], ShouldBeGreaterThan, 0)
		})
	})
}
Example #30
0
func (c *MaxPDVolumeCountChecker) filterVolumes(volumes []v1.Volume, namespace string, filteredVolumes map[string]bool) error {
	for i := range volumes {
		vol := &volumes[i]
		if id, ok := c.filter.FilterVolume(vol); ok {
			filteredVolumes[id] = true
		} else if vol.PersistentVolumeClaim != nil {
			pvcName := vol.PersistentVolumeClaim.ClaimName
			if pvcName == "" {
				return fmt.Errorf("PersistentVolumeClaim had no name")
			}
			pvc, err := c.pvcInfo.GetPersistentVolumeClaimInfo(namespace, pvcName)
			if err != nil {
				// if the PVC is not found, log the error and count the PV towards the PV limit
				// generate a random volume ID since its required for de-dup
				utilruntime.HandleError(fmt.Errorf("Unable to look up PVC info for %s/%s, assuming PVC matches predicate when counting limits: %v", namespace, pvcName, err))
				source := rand.NewSource(time.Now().UnixNano())
				generatedID := "missingPVC" + strconv.Itoa(rand.New(source).Intn(1000000))
				filteredVolumes[generatedID] = true
				return nil
			}

			if pvc == nil {
				return fmt.Errorf("PersistentVolumeClaim not found: %q", pvcName)
			}

			pvName := pvc.Spec.VolumeName
			if pvName == "" {
				return fmt.Errorf("PersistentVolumeClaim is not bound: %q", pvcName)
			}

			pv, err := c.pvInfo.GetPersistentVolumeInfo(pvName)
			if err != nil {
				// if the PV is not found, log the error
				// and count the PV towards the PV limit
				// generate a random volume ID since its required for de-dup
				utilruntime.HandleError(fmt.Errorf("Unable to look up PV info for %s/%s/%s, assuming PV matches predicate when counting limits: %v", namespace, pvcName, pvName, err))
				source := rand.NewSource(time.Now().UnixNano())
				generatedID := "missingPV" + strconv.Itoa(rand.New(source).Intn(1000000))
				filteredVolumes[generatedID] = true
				return nil
			}

			if pv == nil {
				return fmt.Errorf("PersistentVolume not found: %q", pvName)
			}

			if id, ok := c.filter.FilterPersistentVolume(pv); ok {
				filteredVolumes[id] = true
			}
		}
	}

	return nil
}