Esempio n. 1
0
File: mvc.go Progetto: NatkungZ/PRNG
func rand32() uint32 {
	var result uint32 = 0
	result = rand.Uint32()
	result <<= 16
	result |= rand.Uint32()
	return result
}
Esempio n. 2
0
func TestFtoaRandom(t *testing.T) {
	N := int(1e4)
	if testing.Short() {
		N = 100
	}
	t.Logf("testing %d random numbers with fast and slow FormatFloat", N)
	for i := 0; i < N; i++ {
		bits := uint64(rand.Uint32())<<32 | uint64(rand.Uint32())
		x := math.Float64frombits(bits)

		shortFast := FormatFloat(x, 'g', -1, 64)
		SetOptimize(false)
		shortSlow := FormatFloat(x, 'g', -1, 64)
		SetOptimize(true)
		if shortSlow != shortFast {
			t.Errorf("%b printed as %s, want %s", x, shortFast, shortSlow)
		}

		prec := rand.Intn(12) + 5
		shortFast = FormatFloat(x, 'e', prec, 64)
		SetOptimize(false)
		shortSlow = FormatFloat(x, 'e', prec, 64)
		SetOptimize(true)
		if shortSlow != shortFast {
			t.Errorf("%b printed as %s, want %s", x, shortFast, shortSlow)
		}
	}
}
Esempio n. 3
0
File: main.go Progetto: nhooyr/dos
func packet(raddr net.IP) []byte {
	ip := &layers.IPv4{
		Version:           0x4,
		TOS:               0x0,
		TTL:               0x40,
		Protocol:          layers.IPProtocolTCP,
		SrcIP:             net.ParseIP(os.Args[2]),
		DstIP:             raddr,
		WithRawINETSocket: true,
	}
	rand.Seed(time.Now().UnixNano())
	tcp := &layers.TCP{
		SrcPort:    layers.TCPPort(rand.Uint32()),
		DstPort:    0x50,
		Seq:        rand.Uint32(),
		DataOffset: 0x5,
		SYN:        true,
		Window:     0xaaaa,
	}
	tcp.SetNetworkLayerForChecksum(ip)
	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{true, true}
	check(gopacket.SerializeLayers(buf, opts, ip, tcp))
	return buf.Bytes()
}
Esempio n. 4
0
func TestGobNormal(t *testing.T) {
	h, err := NewHLL(10)
	assert.Nil(t, err)
	h.ToNormal()

	var i float64
	for i = 0; i <= 100000; i++ {
		h.Add(fmt.Sprintf("%d-%d", i, rand.Uint32()))
	}
	assert.Equal(t, h.format, NORMAL, "Not using normal mode")

	c := h.Cardinality()
	errorRate := 1.04 / math.Sqrt(float64(h.m1))
	checkErrorBounds(t, c, i, errorRate)
	var buf bytes.Buffer
	err = gob.NewEncoder(&buf).Encode(h)
	assert.Nil(t, err)
	var h2 HLL
	err = gob.NewDecoder(&buf).Decode(&h2)
	assert.Nil(t, err)

	assert.Equal(t, h2.format, NORMAL, "Not using normal mode")
	assert.Equal(t, c, h2.Cardinality())

	for i = 0; i <= 40000; i++ {
		v := rand.Uint32()
		h.Add(fmt.Sprintf("%d-%d", i, v))
		h2.Add(fmt.Sprintf("%d-%d", i, v))
	}

	assert.Equal(t, h.Cardinality(), h2.Cardinality())
}
Esempio n. 5
0
func init() {
	// The atof routines return NumErrors wrapping
	// the error and the string.  Convert the table above.
	for i := range atoftests {
		test := &atoftests[i]
		if test.err != nil {
			test.err = &NumError{"ParseFloat", test.in, test.err}
		}
	}

	// Generate random inputs for tests and benchmarks
	rand.Seed(time.Now().UnixNano())
	if testing.Short() {
		atofRandomTests = make([]atofSimpleTest, 100)
	} else {
		atofRandomTests = make([]atofSimpleTest, 10000)
	}
	for i := range atofRandomTests {
		n := uint64(rand.Uint32())<<32 | uint64(rand.Uint32())
		x := math.Float64frombits(n)
		s := FormatFloat(x, 'g', -1, 64)
		atofRandomTests[i] = atofSimpleTest{x, s}
	}

	for i := range benchmarksRandomBits {
		bits := uint64(rand.Uint32())<<32 | uint64(rand.Uint32())
		x := math.Float64frombits(bits)
		benchmarksRandomBits[i] = FormatFloat(x, 'g', -1, 64)
	}

	for i := range benchmarksRandomNormal {
		x := rand.NormFloat64()
		benchmarksRandomNormal[i] = FormatFloat(x, 'g', -1, 64)
	}
}
Esempio n. 6
0
File: dh64.go Progetto: miffa/crypto
func KeyPair() (privateKey, publicKey uint64) {
	a := uint64(rand.Uint32())
	b := uint64(rand.Uint32()) + 1
	privateKey = (a << 32) | b
	publicKey = PublicKey(privateKey)
	return
}
Esempio n. 7
0
func generateTransactionId() [3]uint32 {
	return [3]uint32{
		rand.Uint32(),
		rand.Uint32(),
		rand.Uint32(),
	}
}
Esempio n. 8
0
func spammer() {
	hostname := "SpamSpamSpam      SpamSpamSpamSpamSpamSpamSpamSpamSpamSpamSpamSpam"

	broadcastConn := openUDPConnOrDie(spamerPort)
	defer broadcastConn.Close()

	addr, err := net.ResolveUDPAddr("udp4", net.IPv4bcast.String()+":"+strconv.Itoa(receiverPort))
	if err != nil {
		log.Fatalf("Cannot resolve broadcast receiver address: %s", err)
	}

	hardwareAddr := make([]byte, 6)
	broadcastCommonData := append(hardwareAddr, byte(len(hostname)))
	broadcastCommonData = append(broadcastCommonData, ([]byte)(hostname)...)

	timestampBuff := make([]byte, 4) //32!!!!
	ticker := time.NewTicker(spamInterval)
	for _ = range ticker.C {
		unixTimestamp := Timestamp(time.Now().Unix())
		endian.PutUint32(timestampBuff, uint32(unixTimestamp))
		endian.PutUint32(broadcastCommonData, rand.Uint32())
		endian.PutUint32(broadcastCommonData[2:], rand.Uint32())
		copy(broadcastCommonData[7:], []byte(net.HardwareAddr(broadcastCommonData[0:6]).String()))
		_, err = broadcastConn.WriteTo(append(broadcastCommonData, timestampBuff...), addr)
		if err != nil {
			log.Fatalf("Unable to broadcast SPAM: %s", err)
		}
	}
}
Esempio n. 9
0
func CheapRandString16() string {
	if !seeded {
		rand.Seed(time.Now().UnixNano())
		seeded = true
	}
	return fmt.Sprintf("%x%x", rand.Uint32(), rand.Uint32())
}
Esempio n. 10
0
func TestReadWriteAtom(t *testing.T) {
	ctx := NewCtx(1)
	a := ctx.newAtom()

	copy(a.data, []byte{'a'})
	testReadWriteAtom(t, a)
	copy(a.data, []byte{'0'})
	testReadWriteAtom(t, a)
	copy(a.data, []byte{'\x00'})
	testReadWriteAtom(t, a)

	for i := 0; i < 100; i++ {
		copy(a.data, []byte{byte(mathrand.Uint32())})
		testReadWriteAtom(t, a)
	}

	ctx2 := NewCtx(2)
	a2 := ctx2.newAtom()
	copy(a2.data, []byte{'a', 'a'})
	testReadWriteAtom(t, a)
	copy(a2.data, []byte{'0', '0'})
	testReadWriteAtom(t, a)
	copy(a2.data, []byte{'\x00', '\x00'})
	testReadWriteAtom(t, a)

	for i := 0; i < 100; i++ {
		r := mathrand.Uint32()
		copy(a.data, []byte{byte(r), byte(r >> 8)})
		testReadWriteAtom(t, a)
	}
}
Esempio n. 11
0
func intPairArray(n int) []KeyValPair {
	a := make([]KeyValPair, n)
	for i := 0; i < n; i++ {
		a[i] = KeyValPair{rand.Uint32(), rand.Uint32()}
	}
	return a
}
Esempio n. 12
0
func CreateClient(uid uint64, password string) {
RECONNECTION:
	//tcpAddr, err := net.ResolveTCPAddr("tcp", "192.168.20.51:9100")
	tcpAddr, err := net.ResolveTCPAddr("tcp", "112.74.66.141:9100")
	//tcpAddr, err := net.ResolveTCPAddr("tcp", "112.74.66.141:9100")
	//tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:9100")
	if err != nil {
		fmt.Println(err)
		return
	}
	clientIP := fmt.Sprintf("127.%v.%v.%v:0", rand.Uint32()%255, rand.Uint32()%255, rand.Uint32()%255)
	locAddr, err := net.ResolveTCPAddr("tcp", clientIP)
	if err != nil {
		panic(err)
	}
	connClient, err := net.DialTCP("tcp", locAddr, tcpAddr)
	if err != nil {
		fmt.Println(err)
		return
	}
	client := &Client{
		conn: connClient,
		uid:  uid,
	}
	log.Println("connect start:", *client)
	err = client.recvPkg()
	if err != nil && err != io.EOF {
		log.Println(err, *client)
		return
		goto RECONNECTION
	} else if err != nil {
		panic(err)
	}
	log.Println("connect end:", *client)
	// 先登录
	client.execArgs("10102", uid, password)
	client.recvPkg()
	cur_count++
	go client.run()

	//select {}
	time.Sleep(3 * time.Minute)
	for {
		// 跑业务
		//second := time.Duration(rand.Uint32()%150) + 30
		time.Sleep(time.Second * 60)
		if client.sid == 0 {
			continue
		}
		uid := int(rand.Uint32())%cur_count + MIN_UID
		g_rwMutex.RLock()
		_, ok := g_client_map[uint64(uid)]
		g_rwMutex.RUnlock()
		if ok {
			client.execArgs("30101", uid)
		}
	}
	client.Close()
}
Esempio n. 13
0
func testDuelingProposal(doneChan chan bool) {
	key := "a"
	randint, _ := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value1 := rand.Uint32()
	value2 := rand.Uint32()
	if _, ok := pt.cliMap[1]; !ok {
		LOGE.Println("FAIL: missing node 1")
		doneChan <- false
		return
	}
	// retChan := make(chan *paxosrpc.ProposeReply, 10)

	pnum1, err1 := pt.GetNextProposalNumber(key, 1)
	pnum2, err2 := pt.GetNextProposalNumber(key, 1)

	fmt.Println("Proposing:", key, value1, pnum1.N)
	// reply1, err := pt.ProposeForDueling(key, value1, pnum1.N, 1, retChan)
	reply1, err1 := pt.Propose(key, value1, pnum1.N, 1)
	fmt.Println(reply1.V)
	fmt.Println("Proposing:", key, value2, pnum2.N)
	reply2, err2 := pt.Propose(key, value2, pnum2.N, 1)
	// reply2, err := pt.ProposeForDueling(key, value2, pnum2.N, 1, retChan)
	fmt.Println(reply2.V)

	if err1 != nil {
		printFailErr("Propose", err1)
		doneChan <- false
		return
	}

	if err2 != nil {
		printFailErr("Propose", err2)
		doneChan <- false
		return
	}

	if !checkProposeReply(reply1, key, value1) {
		doneChan <- false
		return
	}
	fmt.Println("check 1 pass")
	if !checkGetValueAll(key, value2) {
		doneChan <- false
		return
	}

	// if !checkProposeReply(reply2, key, value2) {
	// 	doneChan <- false
	// 	return
	// }

	// if !checkGetValueAll(key, value2) {
	// 	doneChan <- false
	// 	return
	// }

	doneChan <- true
}
Esempio n. 14
0
func (s *PostingSuite) BenchmarkMap(c *C) {
	postings := make(fakePostings, c.N)
	for i := 0; i <= c.N; i++ {
		doctype := rand.Uint32()%100 + 1
		docid := rand.Uint32()%100 + 1
		postings.Add(doctype, docid)
	}
}
Esempio n. 15
0
func BenchmarkWriteControl(b *testing.B) {
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			rand.Uint32()
			rand.Uint32()
		}
	})
}
Esempio n. 16
0
func TestEncodeBigInt(t *testing.T) {
	assertEnc(t, hexChars, 15, "f")
	assertEnc(t, hexChars, 16, "10")
	for i := 0; i < 1000; i++ {
		assertSync(t, hexChars, rand.Uint32())
		assertSync(t, flumChars, rand.Uint32())
	}
}
Esempio n. 17
0
// Make a random integer 0 <= x < p
func mod_rnd() uint64 {
	for {
		x := uint64(rand.Uint32())<<32 + uint64(rand.Uint32())
		if x < MOD_P {
			return x
		}
	}
}
Esempio n. 18
0
func TestFindFunc(t *testing.T) {
	eo := func(cond bool, s string, args ...interface{}) {
		if cond {
			t.Fatalf(s, args...)
		}
	}

	tbl := debug8.NewTable()
	funcs := sortTable(tbl)
	_, f := findFunc(funcs, 1, tbl)
	eo(f != nil, "func not found")

	tbl = &debug8.Table{
		Funcs: map[string]*debug8.Func{
			"f1": {Size: 20, Start: 0},
		},
	}
	funcs = sortTable(tbl)
	_, f = findFunc(funcs, 30, tbl)
	eo(f != nil, "findFunc error")
	_, f = findFunc(funcs, 10, tbl)
	eo(f.Start != 0, "findFunc error")

	tbl = &debug8.Table{
		Funcs: map[string]*debug8.Func{
			"f1": {Size: 20, Start: 0},
			"f2": {Size: 1, Start: 25},
			"f3": {Size: 20, Start: 27},
		},
	}
	funcs = sortTable(tbl)
	_, f = findFunc(funcs, 26, tbl)
	eo(f.Start != 25,
		"pc is %v\n start is %v and length is %v\n", 25, f.Start, f.Size)
	_, f = findFunc(funcs, 24, tbl)
	eo(f != nil, "findFunc error")
	_, f = findFunc(funcs, 50, tbl)
	eo(f != nil, "findFunc error")

	tbl = debug8.NewTable()
	var sum uint32
	for i := 0; i < 100; i++ {
		name := "f" + strconv.Itoa(i)
		size := rand.Uint32()
		tbl.Funcs[name] = &debug8.Func{Size: size, Start: sum}
		sum = sum + size + 1
	}
	pc := rand.Uint32()
	for pc > sum {
		pc = rand.Uint32()
	}
	funcs = sortTable(tbl)
	_, f = findFunc(funcs, pc, tbl)

	eo(f.Start >= pc || f.Size+f.Start <= pc,
		"pc is %v\n func starts %v and length is %v\n", pc, f.Start, f.Size)
}
Esempio n. 19
0
// Generate a new Nid that doesn't exist in the current cluster
func (c *cluster) GenerateNid() Nid {
	c.lock.RLock()
	defer c.lock.RUnlock()

	var result Nid = Nid(rand.Uint32())
	for ; c.nodes[result] != nil; result = Nid(rand.Uint32()) {
	}
	return result
}
Esempio n. 20
0
func randWidthLSBPair() (uint8, uint8) {
	width := uint8(1 + (rand.Uint32() & 0x3F)) // Restrict to range [1, 64]
	lsb := uint8(rand.Uint32() & 0x3F)         // Restrict to range [0, 63]
	for width+lsb > 64 {
		width = uint8(1 + (rand.Uint32() & 0x3F)) // Restrict to range [1, 64]
		lsb = uint8(rand.Uint32() & 0x3F)         // Restrict to range [0, 63]
	}
	return width, lsb
}
Esempio n. 21
0
func dnsQdGen(name, remote string) ([]byte, error) {
	nameBytes, err := nameQdTrans(name)
	if err != nil {
		return []byte{}, err
	}
	dns := dnsHeader{
		Id:      uint16(rand.Uint32() & 0xffff),
		Flags:   _RD, //recursion desired
		QdCount: 1,
	}

	buf := bytes.Buffer{}
	err = binary.Write(&buf, binary.BigEndian, dns)
	if err != nil {
		return []byte{}, qdGenError
	}

	qd := qdHeader{
		name:    nameBytes,
		qdType:  qdTypeA,
		qdClass: qdClassIN,
	}

	compress, _ := qdCompressMap[remote]

	switch compress {
	case qdCompress1:
		n := len(qd.name)
		if qd.name[n-1] == 0 {
			qd.name[n-1] = 0xc0
			rnd := uint8(rand.Intn(4)*2 + 4) //4, 6, 8, 10
			qd.name = append(qd.name, rnd)
		}
		binary.Write(&buf, binary.BigEndian, qd.name)
		binary.Write(&buf, binary.BigEndian, qd.qdType)
		binary.Write(&buf, binary.BigEndian, qd.qdClass)
		break
	case qdCompress2:
		rnd := uint8(rand.Intn(5) + 4) //4-8
		var pos uint8 = 12 + 2 + 2 + 2 + rnd
		binary.Write(&buf, binary.BigEndian, namePtrFlag)
		binary.Write(&buf, binary.BigEndian, pos)
		binary.Write(&buf, binary.BigEndian, qd.qdType)
		binary.Write(&buf, binary.BigEndian, qd.qdClass)
		for i := 0; uint8(i) < rnd; i++ {
			binary.Write(&buf, binary.BigEndian, uint8(rand.Uint32()))
		}
		binary.Write(&buf, binary.BigEndian, qd.name)
		break
	default:
		binary.Write(&buf, binary.BigEndian, qd.name)
		binary.Write(&buf, binary.BigEndian, qd.qdType)
		binary.Write(&buf, binary.BigEndian, qd.qdClass)
	}
	return buf.Bytes(), nil
}
Esempio n. 22
0
func randomColor() color.Color {
	c := color.RGBA{
		R: (uint8)(rand.Uint32()),
		G: (uint8)(rand.Uint32()),
		B: (uint8)(rand.Uint32()),
		A: 255,
	}

	return c
}
Esempio n. 23
0
func testLoop(t *testing.T, j, r, s int) {
	for i := 0; i != j; i++ {
		u := rand.Uint32()%uint32(r) + 1
		m := rand.Uint32()%(u*uint32(s)) + 1
		min := int(m / u)
		if m%u != 0 {
			min++
		}
		testFork(t, int(u), int(m), min)
	}
}
Esempio n. 24
0
/**
 * Tests that the key is correctly updated in each node's storage system.
 */
func testSingleProposerUpdateKey(doneChan chan bool) {
	key := "b"

	// send first proposal
	randint, _ := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value := rand.Uint32()
	if _, ok := pt.cliMap[1]; !ok {
		LOGE.Println("FAIL: missing node 1")
		doneChan <- false
		return
	}

	pnum, err := pt.GetNextProposalNumber(key, 1)
	reply, err := pt.Propose(key, value, pnum.N, 1)

	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	// send second proposal
	randint, _ = crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
	rand.Seed(randint.Int64())
	value = rand.Uint32()

	pnum2, err := pt.GetNextProposalNumber(key, 1)
	// the proposal numbers should be monotonically increasing
	if pnum.N >= pnum2.N {
		LOGE.Println("FAIL: newer proposal number is less than or equal to older proposal number")
		doneChan <- false
		return
	}

	reply, err = pt.Propose(key, value, pnum2.N, 1)
	if err != nil {
		printFailErr("Propose", err)
		doneChan <- false
		return
	}

	if !checkProposeReply(reply, key, value) {
		doneChan <- false
		return
	}

	if !checkGetValueAll(key, value) {
		doneChan <- false
		return
	}

	doneChan <- true
}
Esempio n. 25
0
func TestMul(t *testing.T) {
	const N = 1e5
	for i := 0; i < N; i++ {
		a := uint64(rand.Uint32())<<32 | uint64(rand.Uint32())
		b := uint64(rand.Uint32())<<32 | uint64(rand.Uint32())
		hi, lo := MulU64(a, b)
		if hi2, lo2 := naiveMul(a, b); hi2 != hi || lo2 != lo {
			t.Errorf("expected %016x%016x got %016x%016x", hi2, lo2, hi, lo)
		}
	}
}
Esempio n. 26
0
func RandomArgs(size int) []uint64 {

	args := make([]uint64, size)

	for i, _ := range args {
		a := uint64(rand.Uint32()) | (uint64(rand.Uint32()) << 32)
		args[i] = a
	}

	return args
}
Esempio n. 27
0
func i64rand() int64 {
	for {
		a := int64(rand.Uint32())
		a = (a << 32) | int64(rand.Uint32())
		a >>= uint(rand.Intn(64))
		if -a != a {
			return a
		}
	}
	return 0 // impossible
}
Esempio n. 28
0
func (s *PostingSuite) BenchmarkPostingLine(c *C) {
	b := make([]byte, 0)
	buf := bytes.NewBuffer(b)
	line := NewPostingLine()
	_, err := buf.WriteTo(line)
	c.Check(err, IsNil)
	for i := 0; i <= c.N; i++ {
		doctype := rand.Uint32()%100 + 1
		docid := rand.Uint32()%100 + 1
		line.AddDocumentId(&document.DocumentID{Doctype: doctype, Docid: docid})
	}
}
Esempio n. 29
0
func TestUint64ToBytes(t *testing.T) {
	v := uint64(math.MaxUint64)
	checkUint64ToBytes(t, v)

	checkUint64ToBytes(t, 23423525)
	checkUint64ToBytes(t, 235463656547)
	checkUint64ToBytes(t, 46235645645665456)

	for a := 0; a < 1000; a++ {
		v = uint64(rand.Uint32())<<32 + uint64(rand.Uint32())
		checkUint64ToBytes(t, v)
	}
}
Esempio n. 30
0
func randItem() *Item {
	str := fmt.Sprintf("%d", rand.Uint32())
	offsets := make([]Offset, rand.Int()%3)
	for idx := range offsets {
		sidx := int32(rand.Uint32() % 20)
		eidx := sidx + int32(rand.Uint32()%20)
		offsets[idx] = Offset{sidx, eidx}
	}
	return &Item{
		text:    []rune(str),
		index:   rand.Uint32(),
		offsets: offsets}
}