Golang Intn示例

说明

golang intn示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: math/rand

示例#1
文件: ikr.go 项目: mjbrender/hustlebot

func (h *ikr) Run(res *hal.Response) error {
	now := time.Now()
	rand.Seed(int64(now.Unix()))
	//only fire half the time
	if rand.Intn(100) >= 50 {
		return nil
	}
	replies := []string{
		"*I know right?!*",
		"*OMG* couldn't agree more",
		":+1:",
		"+1",
		":arrow_up: THAT",
		":arrow_up: you complete me :arrow_up:",
		"so true",
		"agreed.",
		"that's the fact jack",
		"YUUUUUUP",
		"that's what I'm talkin bout",
		"*IKR?!*",
		"singit",
		"^droppin the truth bombs :boom: :boom: :boom:",
		"#legit",
		"/me nodds emphatically in agreement",
		"for REALZ though",
		"FOR REALSIES",
		"it's like you *literally* just read my mind right now",
	}

	reply := replies[rand.Intn(len(replies)-1)]
	hal.Logger.Debug(" *** ikr:Sending response: %s", reply)
	res.Send(reply)
	return nil
}

示例#2
文件: accessors_test.go 项目: Kunde21/numgo

func rnd() (sz []int) {
	sz = make([]int, rand.Intn(8)+1)
	for i := range sz {
		sz[i] = rand.Intn(10) + 1
	}
	return
}

示例#3
文件: chaincode_example02.go 项目: masterDev1985/cc_fat

// Initialize entities to random variables in order to test ledger status consensus
func (t *SimpleChaincode) initRand(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return nil, errors.New("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval = rand.Intn(100)
	B = args[1]
	Bval = rand.Intn(100)
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

示例#4
文件: container_test.go 项目: jcassee/docker

func TestLXCConfig(t *testing.T) {
	runtime := mkRuntime(t)
	defer nuke(runtime)
	// Memory is allocated randomly for testing
	rand.Seed(time.Now().UTC().UnixNano())
	memMin := 33554432
	memMax := 536870912
	mem := memMin + rand.Intn(memMax-memMin)
	// CPU shares as well
	cpuMin := 100
	cpuMax := 10000
	cpu := cpuMin + rand.Intn(cpuMax-cpuMin)
	container, err := runtime.Create(&Config{
		Image: GetTestImage(runtime).ID,
		Cmd:   []string{"/bin/true"},

		Hostname:  "foobar",
		Memory:    int64(mem),
		CpuShares: int64(cpu),
	},
	)
	if err != nil {
		t.Fatal(err)
	}
	defer runtime.Destroy(container)
	container.generateLXCConfig(nil)
	grepFile(t, container.lxcConfigPath(), "lxc.utsname = foobar")
	grepFile(t, container.lxcConfigPath(),
		fmt.Sprintf("lxc.cgroup.memory.limit_in_bytes = %d", mem))
	grepFile(t, container.lxcConfigPath(),
		fmt.Sprintf("lxc.cgroup.memory.memsw.limit_in_bytes = %d", mem*2))
}

示例#5
文件: test1.go 项目: jmptrader/go_backtesting_simulators

func (t1 *Test1) OnTick(account *accounts.Account, exchange *exchanges.Exchange, tick *ticks.Tick, vars *variables.Variables) {
	for _, trade := range account.OpenTrades() {
		someCriteria := true

		if someCriteria {
			exchange.CloseTrade(account, trade, tick)
		}

		return
	}

	lower := vars.GetFloat("ma_crossover_threshold_lower")
	upper := vars.GetFloat("ma_crossover_threshold_upper")

	currentCrossover := 1.23

	lots := 1.0
	stopLoss := 25.0
	takeProfit := 50.0

	if 0 == rand.Intn(1000) || currentCrossover > lower && currentCrossover < upper {
		if 0 == rand.Intn(2) {
			exchange.OpenLong(account, tick, lots, stopLoss, takeProfit)
		} else {
			exchange.OpenShort(account, tick, lots, stopLoss, takeProfit)
		}
	}
}

示例#6
文件: bullet.go 项目: shuhaowu/gopong

func NewBullet(boundary *gt2d.Rectangle) *Bullet {
	rand.Seed(time.Now().UTC().UnixNano())

	bullet := new(Bullet)
	bullet.Boundary = boundary

	// init with a random velocity and direction
	bullet.Velocity = new(gt2d.Vector2D)

	for {
		if abs(bullet.Velocity.X) > 1 && abs(bullet.Velocity.Y) > 1 {
			break
		}
		bullet.Velocity.X = rand.Intn(16) - 8
		bullet.Velocity.Y = rand.Intn(16) - 8
	}

	bullet.CurrentPosition = new(gt2d.Vector2D)
	bullet.LastPosition = new(gt2d.Vector2D)
	bullet.CurrentPosition.X = boundary.Width() / 2
	bullet.CurrentPosition.Y = boundary.Height() / 2
	bullet.LastPosition.X = bullet.CurrentPosition.X
	bullet.LastPosition.Y = bullet.CurrentPosition.Y

	bullet.Rect = gt2d.Rect(bullet.CurrentPosition.X-5, bullet.CurrentPosition.Y-5, bullet.CurrentPosition.X+5, bullet.CurrentPosition.Y+5)
	return bullet
}

示例#7
文件: index_test.go 项目: DeCarabas/goindex

func BenchmarkAddAndQueryPost(b *testing.B) {
	// Pre-build posts and queries so we're not measuring that.
	rand := rand.New(rand.NewSource(time.Now().UnixNano()))
	idx := &PostIndex{}
	posts := createPosts(aliceChain, 100000, rand) // Large number of posts to query
	for _, v := range posts {
		idx.AddPost(v.id, v.words)
	}

	posts = createPosts(aliceChain, b.N, rand) // New posts!
	queries := make([]string, b.N)
	for i := 0; i < len(queries); i++ {
		ql := rand.Intn(4) + 1
		t := aliceChain.Generate(ql, rand)
		w := splitToWords(t)
		queries[i] = randomQuery(w, rand)
	}
	var index int32 = -1 // Count up to N but atomically

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			i := atomic.AddInt32(&index, 1)
			if rand.Intn(5) == 0 {
				p := posts[i]
				idx.AddPost(p.id, p.words)
			} else {
				q := queries[i]
				idx.QueryPosts(q, 100)
			}
		}
	})
}

示例#8
文件: dns_udp_test.go 项目: ruflin/beats

// Benchmark that runs with parallelism to help find concurrency related
// issues. To run with parallelism, the 'go test' cpu flag must be set
// greater than 1, otherwise it just runs concurrently but not in parallel.
func BenchmarkParallelUdpParse(b *testing.B) {
	rand.Seed(22)
	numMessages := len(messages)
	dns := newDNS(false)
	client := dns.results.(*publish.ChanTransactions)

	// Drain the results channal while the test is running.
	go func() {
		totalMessages := 0
		for r := range client.Channel {
			_ = r
			totalMessages++
		}
		fmt.Printf("Parsed %d messages.\n", totalMessages)
	}()

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		// Each iteration parses one message, either a request or a response.
		// The request and response could be parsed on different goroutines.
		for pb.Next() {
			q := messages[rand.Intn(numMessages)]
			var packet *protos.Packet
			if rand.Intn(2) == 0 {
				packet = newPacket(forward, q.request)
			} else {
				packet = newPacket(reverse, q.response)
			}
			dns.ParseUDP(packet)
		}
	})

	defer close(client.Channel)
}

示例#9
文件: drawSpiral.go 项目: meysampg/fractals-in-go

func createImage(iterations uint32, degree float64, factor float64) {
	// Declare image size
	width, height := 2048, 1024

	// Create a new image
	img := image.Rect(0, 0, width, height)
	c := NewCanvas(img)
	c.DrawGradient()

	rand.Seed(time.Now().UTC().UnixNano())
	for i := 0; i < 300; i++ {
		x := float64(width) * rand.Float64()
		y := float64(height) * rand.Float64()
		color := color.RGBA{uint8(rand.Intn(255)),
			uint8(rand.Intn(255)),
			uint8(rand.Intn(255)),
			255}
		c.DrawSpiral(color, Coordinate{x, y}, iterations, degree, factor)
	}

	name := fmt.Sprintf("spiral_%d_%f_%f.png", iterations, degree, factor)
	file, err := os.Create(name)
	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()
	png.Encode(file, c)
}

示例#10
文件: util.go 项目: wmwwmv/syncthing

func generateOneFile(fd io.ReadSeeker, p1 string, s int64) error {
	src := io.LimitReader(&inifiteReader{fd}, int64(s))
	dst, err := os.Create(p1)
	if err != nil {
		return err
	}

	_, err = io.Copy(dst, src)
	if err != nil {
		return err
	}

	err = dst.Close()
	if err != nil {
		return err
	}

	_ = os.Chmod(p1, os.FileMode(rand.Intn(0777)|0400))

	t := time.Now().Add(-time.Duration(rand.Intn(30*86400)) * time.Second)
	err = os.Chtimes(p1, t, t)
	if err != nil {
		return err
	}

	return nil
}

示例#11
文件: testsuites.go 项目: jhadvig/origin

// TestList checks the returned list of keys after populating a directory tree.
func (suite *DriverSuite) TestList(c *check.C) {
	rootDirectory := "/" + randomFilename(int64(8+rand.Intn(8)))
	defer suite.StorageDriver.Delete(rootDirectory)

	parentDirectory := rootDirectory + "/" + randomFilename(int64(8+rand.Intn(8)))
	childFiles := make([]string, 50)
	for i := 0; i < len(childFiles); i++ {
		childFile := parentDirectory + "/" + randomFilename(int64(8+rand.Intn(8)))
		childFiles[i] = childFile
		err := suite.StorageDriver.PutContent(childFile, randomContents(32))
		c.Assert(err, check.IsNil)
	}
	sort.Strings(childFiles)

	keys, err := suite.StorageDriver.List("/")
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.DeepEquals, []string{rootDirectory})

	keys, err = suite.StorageDriver.List(rootDirectory)
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.DeepEquals, []string{parentDirectory})

	keys, err = suite.StorageDriver.List(parentDirectory)
	c.Assert(err, check.IsNil)

	sort.Strings(keys)
	c.Assert(keys, check.DeepEquals, childFiles)

	// A few checks to add here (check out #819 for more discussion on this):
	// 1. Ensure that all paths are absolute.
	// 2. Ensure that listings only include direct children.
	// 3. Ensure that we only respond to directory listings that end with a slash (maybe?).
}

示例#12
文件: go4096.go 项目: ZetaoYang/gamekits

/* 检查游戏是否已经胜利,没有胜利的情况下随机将值为0的元素
*随机设置为2或者4
 */
func (t *G4096) checkWinOrAdd() Status2 {
	// 判断4x4中是否有元素的值大于(等于)4096,有则获胜利
	for _, x := range t {
		for _, y := range x {
			if y >= Max2 {
				return Win2
			}
		}
	}
	// 开始随机设置零值元素为2或者4
	i := rand.Intn(len(t))
	j := rand.Intn(len(t))
	for x := 0; x < len(t); x++ {
		for y := 0; y < len(t); y++ {
			if t[i%len(t)][j%len(t)] == 0 {
				t[i%len(t)][j%len(t)] = 2 << (rand.Uint32() % 2)
				return Add2
			}
			j++
		}
		i++
	}

	// 全部元素都不为零(表示已满),则失败
	return Lose2
}

示例#13
文件: mfs_test.go 项目: ccsblueboy/go-ipfs

func randomFile(d *Directory) (*File, error) {
	d, err := randomWalk(d, rand.Intn(6))
	if err != nil {
		return nil, err
	}

	ents, err := d.List()
	if err != nil {
		return nil, err
	}

	var files []string
	for _, e := range ents {
		if e.Type == int(TFile) {
			files = append(files, e.Name)
		}
	}

	if len(files) == 0 {
		return nil, nil
	}

	fname := files[rand.Intn(len(files))]
	fsn, err := d.Child(fname)
	if err != nil {
		return nil, err
	}

	fi, ok := fsn.(*File)
	if !ok {
		return nil, errors.New("file wasnt a file, race?")
	}

	return fi, nil
}

示例#14
文件: mfs_test.go 项目: ccsblueboy/go-ipfs

func actorMakeFile(d *Directory) error {
	d, err := randomWalk(d, rand.Intn(7))
	if err != nil {
		return err
	}

	name := randomName()
	f, err := NewFile(name, &dag.Node{Data: ft.FilePBData(nil, 0)}, d, d.dserv)
	if err != nil {
		return err
	}

	wfd, err := f.Open(OpenWriteOnly, true)
	if err != nil {
		return err
	}

	r := io.LimitReader(randbo.New(), int64(77*rand.Intn(123)))
	_, err = io.Copy(wfd, r)
	if err != nil {
		return err
	}

	err = wfd.Close()
	if err != nil {
		return err
	}

	return nil
}

示例#15
文件: cacphtcode.go 项目: yunkaiyueming/go_code

func NewImage(digits []byte, width, height int) *Image {
	img := new(Image)
	r := image.Rect(img.width, img.height, stdWidth, stdHeight)
	img.NRGBA = image.NewNRGBA(r)

	img.color = &color.NRGBA{
		uint8(rand.Intn(129)),
		uint8(rand.Intn(129)),
		uint8(rand.Intn(129)),
		0xFF,
	}
	// Draw background (10 random circles of random brightness)
	img.calculateSizes(width, height, len(digits))
	img.fillWithCircles(10, img.dotsize)

	maxx := width - (img.width+img.dotsize)*len(digits) - img.dotsize
	maxy := height - img.height - img.dotsize*2

	x := rnd(img.dotsize*2, maxx)
	y := rnd(img.dotsize*2, maxy)

	// Draw digits.
	for _, n := range digits {
		img.drawDigit(font[n], x, y)
		x += img.width + img.dotsize
	}

	// Draw strike-through line.
	img.strikeThrough()
	return img
}

示例#16
文件: fuzzy_test.go 项目: Richardphp/noms

//This function creates variations on tokens without regards as to positions in the file.
func getTokenVariations(t xml.Token) []xml.Token {
	var result []xml.Token = make([]xml.Token, 0)
	switch t := t.(type) {
	case xml.CharData:
		{
			//If the token is a number try some random number
			if _, err := strconv.Atoi(string(t)); err == nil {
				result = append(result, xml.CharData(randInt(rand.Intn(15))))
			}

			result = append(result, xml.CharData(randString(rand.Intn(100))))
			return result
		}
	case xml.StartElement:
		{
			for k := range t.Attr {
				if _, err := strconv.Atoi(string(t.Attr[k].Value)); err == nil {
					start := xml.CopyToken(t).(xml.StartElement)
					start.Attr[k].Value = string(randInt(rand.Intn(15)))
					result = append(result, start)
				}
				start := xml.CopyToken(t).(xml.StartElement)
				start.Attr[k].Value = string(randString(rand.Intn(100)))
				result = append(result, start)
			}
			return result
		}

	default:
		{
			return make([]xml.Token, 0) // No variations on non char tokens yet
		}
	}
}

示例#17
文件: toybrick.go 项目: noscripter/pt

func main() {
	scene := pt.Scene{}
	scene.SetColor(pt.Color{1, 1, 1})
	meshes := []*pt.Mesh{
		CreateBrick(1),  // white
		CreateBrick(21), // bright red
		CreateBrick(23), // bright blue
		CreateBrick(24), // bright yellow
		CreateBrick(26), // black
		CreateBrick(28), // dark green
	}
	for x := -30; x <= 50; x += 2 {
		for y := -50; y <= 20; y += 4 {
			h := rand.Intn(5) + 1
			for i := 0; i < h; i++ {
				dy := 0
				if (x/2+i)%2 == 0 {
					dy = 2
				}
				z := float64(i) * H
				mesh := meshes[rand.Intn(len(meshes))]
				m := pt.Translate(pt.Vector{float64(x), float64(y + dy), z})
				scene.Add(pt.NewTransformedShape(mesh, m))
			}
		}
	}
	// light := pt.LightMaterial(pt.Color{0.2, 0.2, 0.2}, 10, pt.QuadraticAttenuation(0.01))
	// scene.Add(pt.NewSphere(pt.Vector{0, 0, 25}, 1, light))
	camera := pt.LookAt(pt.Vector{-23, 13, 20}, pt.Vector{0, 0, 0}, pt.Vector{0, 0, 1}, 45)
	pt.IterativeRender("out%03d.png", 1000, &scene, &camera, 2560, 1440, -1, 4, 4)
}

示例#18
文件: descriptor_mutation_test.go 项目: YuleiXiao/cockroach

// writeMutation writes the mutation to the table descriptor. If the
// State or the Direction is undefined, these values are populated via
// picking random values before the mutation is written.
func (mt mutationTest) writeMutation(m sqlbase.DescriptorMutation) {
	if m.Direction == sqlbase.DescriptorMutation_NONE {
		// randomly pick ADD/DROP mutation if this is the first mutation, or
		// pick the direction already chosen for the first mutation.
		if len(mt.tableDesc.Mutations) > 0 {
			m.Direction = mt.tableDesc.Mutations[0].Direction
		} else {
			m.Direction = sqlbase.DescriptorMutation_DROP
			if rand.Intn(2) == 0 {
				m.Direction = sqlbase.DescriptorMutation_ADD
			}
		}
	}
	if m.State == sqlbase.DescriptorMutation_UNKNOWN {
		// randomly pick DELETE_ONLY/WRITE_ONLY state.
		r := rand.Intn(2)
		if r == 0 {
			m.State = sqlbase.DescriptorMutation_DELETE_ONLY
		} else {
			m.State = sqlbase.DescriptorMutation_WRITE_ONLY
		}
	}
	mt.tableDesc.Mutations = append(mt.tableDesc.Mutations, m)
	if err := mt.tableDesc.Validate(); err != nil {
		mt.Fatal(err)
	}
	if err := mt.kvDB.Put(
		sqlbase.MakeDescMetadataKey(mt.tableDesc.ID),
		sqlbase.WrapDescriptor(mt.tableDesc),
	); err != nil {
		mt.Fatal(err)
	}
}

示例#19
文件: main.go 项目: 6a68/gorevisit

func noise(src image.Image, dst image.RGBA) error {
	// get the boundary box of the original image
	orig := src.Bounds()

	// copy it into the destination image buffer
	for x := orig.Min.X; x < orig.Max.X; x++ {
		for y := orig.Min.Y; y < orig.Max.Y; y++ {
			dst.Set(x, y, src.At(x, y))
		}
	}

	// shift some colors
	numToMod := (orig.Max.X * orig.Max.Y) / 2
	for i := 0; i < numToMod; i++ {
		x := rand.Intn(orig.Max.X)
		y := rand.Intn(orig.Max.Y)
		if prev, ok := src.At(x, y).(color.RGBA); ok {
			prev.R += 30
			prev.B -= 30
			prev.G += 30
			dst.Set(x, y, prev)
		}
		if prev, ok := src.At(x, y).(color.YCbCr); ok {
			prev.Cr += 30
			prev.Cb -= 30
			prev.Y += 30
			dst.Set(x, y, prev)
		}
	}

	return nil

}

示例#20
文件: rss.go 项目: lingkong7/telegram-chinese-groups

func loopFeed(feed *rss.Feed, url string, chatid int) {
	go func() {
		interval := 7
		stopRssLoop[strconv.Itoa(chatid)+":"+url] = make(chan bool)

		firstLoop := true
		t := time.Tick(time.Minute*time.Duration(interval-1) +
			time.Second*time.Duration(rand.Intn(120)))

	Loop:
		for {
			select {
			case <-stopRssLoop[strconv.Itoa(chatid)+":"+url]:
				break Loop
			case <-t:
				if firstLoop {
					time.Sleep(time.Duration(rand.Intn(interval)) * time.Minute)
					firstLoop = false
				}
				if err := feed.Fetch(url, charsetReader); err != nil {
					loge.Warningf("failed to fetch rss, "+
						"retry in 3 seconds... [ %s ]", url)
					time.Sleep(time.Second * 3)
					continue
				}
			}
		}

	}()
}

示例#21
文件: datum_writer_test.go 项目: ruo91/syscol

func randomPrimitiveObject() *primitive {
	p := &primitive{}
	p.BooleanField = rand.Int()%2 == 0

	p.IntField = rand.Int31()
	if p.IntField%3 == 0 {
		p.IntField = -p.IntField
	}

	p.LongField = rand.Int63()
	if p.LongField%3 == 0 {
		p.LongField = -p.LongField
	}

	p.FloatField = rand.Float32()
	if p.BooleanField {
		p.FloatField = -p.FloatField
	}

	p.DoubleField = rand.Float64()
	if !p.BooleanField {
		p.DoubleField = -p.DoubleField
	}

	p.BytesField = randomBytes(rand.Intn(99) + 1)
	p.StringField = randomString(rand.Intn(99) + 1)

	return p
}

示例#22
文件: v2_curl_test.go 项目: achanda/etcd

// cURLPrefixArgs builds the beginning of a curl command for a given key
// addressed to a random URL in the given cluster.
func cURLPrefixArgs(clus *etcdProcessCluster, method string, req cURLReq) []string {
	var (
		cmdArgs = []string{"curl"}
		acurl   = clus.procs[rand.Intn(clus.cfg.clusterSize)].cfg.acurl
	)
	if req.isTLS {
		if clus.cfg.clientTLS != clientTLSAndNonTLS {
			panic("should not use cURLPrefixArgsUseTLS when serving only TLS or non-TLS")
		}
		cmdArgs = append(cmdArgs, "--cacert", caPath, "--cert", certPath, "--key", privateKeyPath)
		acurl = clus.procs[rand.Intn(clus.cfg.clusterSize)].cfg.acurltls
	} else if clus.cfg.clientTLS == clientTLS {
		cmdArgs = append(cmdArgs, "--cacert", caPath, "--cert", certPath, "--key", privateKeyPath)
	}
	ep := acurl + req.endpoint

	if req.username != "" || req.password != "" {
		cmdArgs = append(cmdArgs, "-L", "-u", fmt.Sprintf("%s:%s", req.username, req.password), ep)
	} else {
		cmdArgs = append(cmdArgs, "-L", ep)
	}

	switch method {
	case "PUT":
		dt := req.value
		if !strings.HasPrefix(dt, "{") { // for non-JSON value
			dt = "value=" + dt
		}
		cmdArgs = append(cmdArgs, "-XPUT", "-d", dt)
	}
	return cmdArgs
}

示例#23
文件: rand.go 项目: nathany/learn-go

func main() {
	var num = rand.Intn(10) + 1
	fmt.Println(num)

	num = rand.Intn(10) + 1
	fmt.Println(num)
}

示例#24
文件: diff_test.go 项目: jmptrader/sysinfo_influxdb

func TestRandom(t *testing.T) {
	serie := &influxClient.Point{
		Measurement: fmt.Sprintf("test_rnd"),
		Tags:        map[string]string{"toto": "titi"},
		Fields:      map[string]interface{}{},
	}

	size := rand.Intn(30) + 12

	var oldPts, newPts *map[string]interface{}
	newPts = new(map[string]interface{})

	fillPoints(serie, newPts, size)

	DiffFromLast(serie)

	for h := 0; h < rand.Intn(50)+10; h++ {
		oldPts = newPts
		newPts = new(map[string]interface{})

		fillPoints(serie, newPts, size)
		DiffFromLast(serie)

		// Compare
		for i := 0; i < size; i++ {
			k := fmt.Sprint("col", i)
			if serie.Fields[k] != (*newPts)[k].(int)-(*oldPts)[k].(int) {
				t.Error(fmt.Sprintf("Iteration %d; point %d: expected %d, got %d", h, k,
					(*newPts)[k].(int)-(*oldPts)[k].(int), serie.Fields[k]))
			}
		}
	}
}

示例#25
文件: spworker.go 项目: patrickToca/zmq2

func main() {
	worker, _ := zmq.NewSocket(zmq.REQ)
	defer worker.Close()

	//  Set random identity to make tracing easier
	rand.Seed(time.Now().UnixNano())
	identity := fmt.Sprintf("%04X-%04X", rand.Intn(0x10000), rand.Intn(0x10000))
	worker.SetIdentity(identity)
	worker.Connect("tcp://localhost:5556")

	//  Tell broker we're ready for work
	fmt.Printf("I: (%s) worker ready\n", identity)
	worker.Send(WORKER_READY, 0)

	for cycles := 0; true; {
		msg, err := worker.RecvMessage(0)
		if err != nil {
			break //  Interrupted
		}

		//  Simulate various problems, after a few cycles
		cycles++
		if cycles > 3 && rand.Intn(5) == 0 {
			fmt.Printf("I: (%s) simulating a crash\n", identity)
			break
		} else if cycles > 3 && rand.Intn(5) == 0 {
			fmt.Printf("I: (%s) simulating CPU overload\n", identity)
			time.Sleep(3 * time.Second)
		}

		fmt.Printf("I: (%s) normal reply\n", identity)
		time.Sleep(time.Second) //  Do some heavy work
		worker.SendMessage(msg)
	}
}

示例#26
文件: in_flight_pqueue_test.go 项目: reqshark/nsq

func TestRemove(t *testing.T) {
	c := 100
	pq := newInFlightPqueue(c)

	msgs := make(map[MessageID]*Message)
	for i := 0; i < c; i++ {
		m := &Message{pri: int64(rand.Intn(100000000))}
		copy(m.ID[:], fmt.Sprintf("%016d", m.pri))
		msgs[m.ID] = m
		pq.Push(m)
	}

	for i := 0; i < 10; i++ {
		idx := rand.Intn((c - 1) - i)
		var fm *Message
		for _, m := range msgs {
			if m.index == idx {
				fm = m
				break
			}
		}
		rm := pq.Remove(idx)
		assert.Equal(t, fmt.Sprintf("%s", fm.ID), fmt.Sprintf("%s", rm.ID))
	}

	lastPriority := pq.Pop().pri
	for i := 0; i < (c - 10 - 1); i++ {
		msg := pq.Pop()
		assert.Equal(t, lastPriority <= msg.pri, true)
		lastPriority = msg.pri
	}
}

示例#27
文件: accessors_test.go 项目: Kunde21/numgo

func TestSet(t *testing.T) {
	a := NewArray64(nil, 5, 5, 5)

	for i := 0; i < 20; i++ {
		x, y, z := rand.Intn(6), rand.Intn(6), rand.Intn(6)
		val := rand.Float64() * 100
		v := a.Set(val, x, y, z)
		if v.At(x, y, z) != val && !a.HasErr() {
			t.Logf("Value %d failed.  Expected: %v Received: %v", i, v.At(x, y, z), val)
			t.Log(x, y, z)
			t.Fail()
		}
		if e := a.GetErr(); (x > 4 || y > 4 || z > 4) && e != IndexError {
			t.Log("Error failed.  Expected IndexErr Received", e)
			t.Log(x, y, z)
			t.Fail()
		}
	}

	_ = a.Reshape(0).Set(0, 1, 1, 1)
	if e, d, s := a.GetDebug(); e != ReshapeError {
		t.Log("ReshapeError failed.  Received", e)
		t.Log(d, "\n", s)
		t.Fail()
	}
	_ = a.Set(0, 0, 0, 0, 0)
	if e, d, s := a.GetDebug(); e != InvIndexError {
		t.Log("InvIndexError failed.  Received", e)
		t.Log(d, "\n", s)
		t.Fail()
	}
}

示例#28
文件: character.go 项目: HunterInTheStorm/The-Lagorinth

//makeDecisionWhereToMove determines to which empty tile a character should move to.
//Return true if such a tile exists and its coordinates.
func (npc *NPC) makeDecisionWhereToMove(labyrinth *Labyrinth.Labyrinth) (bool, *Point.Point) {
	frontTile := labyrinth.Labyrinth[npc.Location.X+npc.Orientation.X][npc.Location.Y+npc.Orientation.Y]
	if frontTile != Labyrinth.Wall && frontTile != Labyrinth.Monster && frontTile != Labyrinth.Treasure {
		if rand.Intn(100) < 80 {
			return true, &Point.Point{npc.Location.X + npc.Orientation.X, npc.Location.Y + npc.Orientation.Y, nil}
		}
	} else {
		direction := make([]Point.Point, 0, 4)
		upTile := labyrinth.Labyrinth[npc.Location.X-1][npc.Location.Y]
		if upTile != Labyrinth.Wall && upTile != Labyrinth.Monster && upTile != Labyrinth.Treasure {
			direction = append(direction, Point.Point{npc.Location.X - 1, npc.Location.Y, nil})
		}
		downTile := labyrinth.Labyrinth[npc.Location.X+1][npc.Location.Y]
		if downTile != Labyrinth.Wall && downTile != Labyrinth.Monster && downTile != Labyrinth.Treasure {
			direction = append(direction, Point.Point{npc.Location.X + 1, npc.Location.Y, nil})
		}
		leftTile := labyrinth.Labyrinth[npc.Location.X][npc.Location.Y-1]
		if leftTile != Labyrinth.Wall && leftTile != Labyrinth.Monster && leftTile != Labyrinth.Treasure {
			direction = append(direction, Point.Point{npc.Location.X, npc.Location.Y - 1, nil})
		}
		rightTile := labyrinth.Labyrinth[npc.Location.X][npc.Location.Y+1]
		if rightTile != Labyrinth.Wall && rightTile != Labyrinth.Monster && rightTile != Labyrinth.Treasure {
			direction = append(direction, Point.Point{npc.Location.X, npc.Location.Y + 1, nil})
		}
		if len(direction) != 0 {
			return true, &direction[rand.Intn(len(direction))]
		}
	}
	return false, &Point.Point{-1, -1, nil}
}

示例#29
文件: fstest.go 项目: fjballest/clive

func fwrite(t Fataler, p1, p2 string) bool {
	fd1, err1 := os.OpenFile(p1, os.O_WRONLY, 0)
	if fd1 != nil {
		defer fd1.Close()
	}
	fd2, err2 := os.OpenFile(p2, os.O_WRONLY, 0)
	if fd2 != nil {
		defer fd2.Close()
	}
	if err1 != nil && err2 != nil {
		t.Logf("write %s fails", p1)
		return false
	}
	if err1 != nil || err2 != nil {
		t.Fatalf("errors in remove: %v vs %v", err1, err2)
	}
	pos := rand.Intn(maxSeek)
	sz := rand.Intn(len(wbuf))
	n1, err1 := fd1.WriteAt(wbuf[:sz], int64(pos))
	n2, err2 := fd2.WriteAt(wbuf[:sz], int64(pos))
	if n1 != n2 {
		t.Fatalf("write: %d vs %d bytes", n1, n2)
	}
	if err1 != nil && err2 != nil {
		t.Logf("write %s fails", p1)
		return false
	}
	if err1 != nil || err2 != nil {
		t.Fatalf("errors in write: %v vs %v", err1, err2)
	}
	t.Logf("write %s %d [%d] ok", p1, pos, sz)
	return true
}

示例#30
文件: structs.go 项目: billyninja/slapchop

func (s *SlapchopEntry) ShuffleGrid(grid [][40]string) [][40]string {
	boundY := 1
	boundX := 1
	i := 20

	for i > 0 {

		for x, _ := range grid {
			for y, _ := range grid[x] {
				if grid[x][y] == "" {
					break
				}

				if y > boundY {
					boundY = y
				}
				if x > boundX {
					boundY = x
				}
				rx := rand.Intn(boundX)
				ry := rand.Intn(boundY)
				temp := grid[x][y]
				grid[x][y] = grid[rx][ry]
				grid[rx][ry] = temp
			}
		}
		i--
	}

	return grid
}

展开阅读全文