示例#1
0
文件: lda.go 项目: fluhus/gostuff
// Picks a random index from a, with a probability proportional to its value.
// Using a local random-generator to prevent waiting on rand's default source.
func pickRandom(a []float64, rnd *rand.Rand) int {
	if len(a) == 0 {
		panic("Cannot pick element from an empty distribution.")
	}

	sum := float64(0)
	for i := range a {
		if a[i] < 0 {
			panic(fmt.Sprintf("Got negative value in distribution: %v", a[i]))
		}
		sum += a[i]
	}
	if sum == 0 {
		return rnd.Intn(len(a))
	}

	r := rnd.Float64() * sum
	i := 0
	for i < len(a) && r > a[i] {
		r -= a[i]
		i++
	}
	if i == len(a) {
		i--
	}
	return i
}
示例#2
0
func GenerateDense(r *rand.Rand, size int) Undirected {
	for {
		u := Undirected{
			Nodes: make([]NodeID, size),
			Edges: make(map[Edge]struct{}),
		}

		for i := 0; i < size; i++ {
			u.Nodes[i] = NodeID(strconv.Itoa(i))
		}

		// Form a fully-connected graph
		for i := 0; i < size; i++ {
			for j := 0; j < i; j++ {
				u.Add(Edge{u.Nodes[i], u.Nodes[j]})
			}
		}

		// Remove some edges
		for i := r.Intn(size); i > 0; i-- {
			u.Remove(u.RandomEdge(r))
		}

		if u.Graph().Connected() {
			return u
		}
	}
}
示例#3
0
文件: test.go 项目: 9il/pnoise
func random_gradient(r *rand.Rand) Vec2 {
	v := r.Float64() * PI * 2
	return Vec2{
		float32(math.Cos(v)),
		float32(math.Sin(v)),
	}
}
示例#4
0
func NewField(r *rand.Rand, name, value string, typ *index.FieldType) *index.Field {
	if Usually(r) || !typ.Indexed() {
		// most of the time, don't modify the params
		return index.NewStringField(name, value, typ)
	}

	newType := index.NewFieldTypeFrom(typ)
	if !newType.Stored() && r.Intn(2) == 0 {
		newType.SetStored(true) // randonly store it
	}

	if !newType.StoreTermVectors() && r.Intn(2) == 0 {
		newType.SetStoreTermVectors(true)
		if !newType.StoreTermVectorOffsets() {
			newType.SetStoreTermVectorOffsets(r.Intn(2) == 0)
		}
		if !newType.StoreTermVectorPositions() {
			newType.SetStoreTermVectorPositions(r.Intn(2) == 0)

			if newType.StoreTermVectorPositions() && !newType.StoreTermVectorPayloads() && !PREFLEX_IMPERSONATION_IS_ACTIVE {
				newType.SetStoreTermVectorPayloads(r.Intn(2) == 2)
			}
		}
	}

	return index.NewStringField(name, value, newType)
}
示例#5
0
// MakePriority generates a random priority value, biased by the
// specified userPriority. If userPriority=100, the resulting
// priority is 100x more likely to be probabilistically greater
// than a similar invocation with userPriority=1.
func MakePriority(r *rand.Rand, userPriority int32) int32 {
	// A currently undocumented feature allows an explicit priority to
	// be set by specifying priority < 1. The explicit priority is
	// simply -userPriority in this case. This is hacky, but currently
	// used for unittesting. Perhaps this should be documented and allowed.
	if userPriority < 0 {
		return -userPriority
	}
	if userPriority == 0 {
		userPriority = 1
	}
	// The idea here is to bias selection of a random priority from the
	// range [1, 2^31-1) such that if userPriority=100, it's 100x more
	// likely to be a higher int32 than if userPriority=1. The formula
	// below chooses random values according to the following table:
	//   userPriority  |  range
	//   1             |  all positive int32s
	//   10            |  top 9/10ths of positive int32s
	//   100           |  top 99/100ths of positive int32s
	//   1000          |  top 999/1000ths of positive int32s
	//   ...etc
	if r != nil {
		return math.MaxInt32 - r.Int31n(math.MaxInt32/userPriority)
	}
	return math.MaxInt32 - rand.Int31n(math.MaxInt32/userPriority)
}
示例#6
0
文件: quick.go 项目: achanda/go
// randFloat64 generates a random float taking the full range of a float64.
func randFloat64(rand *rand.Rand) float64 {
	f := rand.Float64() * math.MaxFloat64
	if rand.Int()&1 == 1 {
		f = -f
	}
	return f
}
示例#7
0
func Qsort(a Interface, prng *rand.Rand) Interface {
	if a.Len() < 2 {
		return a
	}

	left, right := 0, a.Len()-1

	pivotIndex := prng.Int() % a.Len()
	a.Swap(pivotIndex, right)

	for i := 0; i < a.Len(); i++ {
		if a.Less(i, right) {

			a.Swap(i, left)
			left++
		}
	}

	a.Swap(left, right)

	leftSide, rightSide := a.Partition(left)
	Qsort(leftSide, prng)
	Qsort(rightSide, prng)

	return a
}
示例#8
0
// iterate through the deck, and swap values with
// a random card from another location in the deck
func (sd *StandardDeck) Shuffle(r *rand.Rand) {
	s := sd.Size()
	for k := range sd.cards {
		i := r.Intn(s)
		sd.cards[k], sd.cards[i] = sd.cards[i], sd.cards[k]
	}
}
示例#9
0
func (self *Scene) Emitter(r *rand.Rand) *memit.Emitter {
	if len(self.emitters) == 0 {
		return nil
	}
	i := r.Int() % len(self.emitters)
	return &self.emitters[i]
}
func NewMockDirectoryWrapper(random *rand.Rand, delegate store.Directory) *MockDirectoryWrapper {
	ans := &MockDirectoryWrapper{
		noDeleteOpenFile:                 true,
		preventDoubleWrite:               true,
		trackDiskUsage:                   false,
		wrapLockFactory:                  true,
		openFilesForWrite:                make(map[string]bool),
		openLocks:                        make(map[string]bool),
		openLocksLock:                    &sync.Mutex{},
		throttling:                       THROTTLING_SOMETIMES,
		inputCloneCount:                  0,
		openFileHandles:                  make(map[io.Closer]error),
		failOnCreateOutput:               true,
		failOnOpenInput:                  true,
		assertNoUnreferencedFilesOnClose: true,
	}
	ans.BaseDirectoryWrapperImpl = NewBaseDirectoryWrapper(delegate)
	ans.Locker = &sync.Mutex{}
	// must make a private random since our methods are called from different
	// methods; else test failures may not be reproducible from the original
	// seed
	ans.randomState = rand.New(rand.NewSource(random.Int63()))
	ans.throttledOutput = NewThrottledIndexOutput(
		MBitsToBytes(40+ans.randomState.Intn(10)), 5+ans.randomState.Int63n(5), nil)
	// force wrapping of LockFactory
	ans.myLockFactory = newMockLockFactoryWrapper(ans, delegate.LockFactory())
	ans.init()
	return ans
}
示例#11
0
文件: util.go 项目: MaxHalford/gago
// Shuffle a slice of strings.
func shuffleStrings(strings []string, rng *rand.Rand) []string {
	var shuffled = make([]string, len(strings))
	for i, j := range rng.Perm(len(strings)) {
		shuffled[j] = strings[i]
	}
	return shuffled
}
示例#12
0
func randomData(r *rand.Rand, bytes int) []byte {
	data := make([]byte, bytes)
	for i, _ := range data {
		data[i] = byte(r.Uint32() % 256)
	}
	return data
}
示例#13
0
func MonteCarloPixel(results chan Result, scene *geometry.Scene, diffuseMap /*, causticsMap*/ *kd.KDNode, start, rows int, rand *rand.Rand) {
	samples := Config.NumRays
	var px, py, dy, dx geometry.Float
	var direction, contribution geometry.Vec3

	for y := start; y < start+rows; y++ {
		py = scene.Height - scene.Height*2*geometry.Float(y)/geometry.Float(scene.Rows)
		for x := 0; x < scene.Cols; x++ {
			px = -scene.Width + scene.Width*2*geometry.Float(x)/geometry.Float(scene.Cols)
			var colourSamples geometry.Vec3
			if x >= Config.Skip.Left && x < scene.Cols-Config.Skip.Right &&
				y >= Config.Skip.Top && y < scene.Rows-Config.Skip.Bottom {
				for sample := 0; sample < samples; sample++ {
					dy, dx = geometry.Float(rand.Float32())*scene.PixH, geometry.Float(rand.Float32())*scene.PixW
					direction = geometry.Vec3{
						px + dx - scene.Camera.Origin.X,
						py + dy - scene.Camera.Origin.Y,
						-scene.Camera.Origin.Z,
					}.Normalize()

					contribution = Radiance(geometry.Ray{scene.Camera.Origin, direction}, scene, diffuseMap /*causticsMap,*/, 0, 1.0, rand)
					colourSamples.AddInPlace(contribution)
				}
			}
			results <- Result{x, y, colourSamples.Mult(1.0 / geometry.Float(samples))}
		}
	}
}
示例#14
0
func New(r *rand.Rand) *Simplex {
	var s Simplex
	perm := r.Perm(256)
	copy(s[:256], perm)
	copy(s[256:], perm)
	return &s
}
示例#15
0
文件: parse_test.go 项目: abh/dns
func GenerateDomain(r *rand.Rand, size int) []byte {
	dnLen := size % 70 // artificially limit size so there's less to intrepret if a failure occurs
	var dn []byte
	done := false
	for i := 0; i < dnLen && !done; {
		max := dnLen - i
		if max > 63 {
			max = 63
		}
		lLen := max
		if lLen != 0 {
			lLen = int(r.Int31()) % max
		}
		done = lLen == 0
		if done {
			continue
		}
		l := make([]byte, lLen+1)
		l[0] = byte(lLen)
		for j := 0; j < lLen; j++ {
			l[j+1] = byte(rand.Int31())
		}
		dn = append(dn, l...)
		i += 1 + lLen
	}
	return append(dn, 0)
}
示例#16
0
func main() {

	var (
		nbLigne uint
		result  [][]int
		r       *rand.Rand
		i       uint
	)

	nbLigne = Initialisation()

	result = make([][]int, nbLigne)

	r = rand.New(rand.NewSource(time.Now().UnixNano()))

	for i = 0; i < nbLigne; i++ {
		result[i] = make([]int, 3)
		result[i][0] = int(math.Mod(float64(r.Int()), 200)) - 100
		result[i][1] = int(math.Mod(float64(r.Int()), 200)) - 100
		result[i][2] = int(math.Mod(float64(r.Int()), 9)) + 1

	}

	ecrireFichier("fichierTest", nbLigne, result)
}
示例#17
0
文件: quick.go 项目: achanda/go
// randFloat32 generates a random float taking the full range of a float32.
func randFloat32(rand *rand.Rand) float32 {
	f := rand.Float64() * math.MaxFloat32
	if rand.Int()&1 == 1 {
		f = -f
	}
	return float32(f)
}
示例#18
0
func main() {

	db, err := sql.Open("postgres", "user=postgres host=localhost port=5432 dbname=example_db sslmode=disable")
	if err != nil {
		log.Fatalln(err)
	}

	defer func() {
		fmt.Println("close.")
		if err := db.Close(); err != nil {
			log.Fatalln(err)
		}
	}()

	//	resetDB(db)

	if tx, err := db.Begin(); err != nil {
		log.Fatalln("begin ", err)
	} else {
		var r *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
		if res, err := tx.Exec(INSERT_TEST_TBL, r.Int31(), "hoge", "fugafuga"); err != nil {
			log.Fatalln("insert query ", err)
		} else {
			fmt.Printf("%+v\n", res)
		}

		defer func() {
			fmt.Println("commit.")
			if err := tx.Commit(); err != nil {
				log.Fatalln(err)
			}
		}()
	}
}
示例#19
0
func recordToSink(sink EventSink, event *api.Event, eventCorrelator *EventCorrelator, randGen *rand.Rand, sleepDuration time.Duration) {
	// Make a copy before modification, because there could be multiple listeners.
	// Events are safe to copy like this.
	eventCopy := *event
	event = &eventCopy
	result, err := eventCorrelator.EventCorrelate(event)
	if err != nil {
		utilruntime.HandleError(err)
	}
	if result.Skip {
		return
	}
	tries := 0
	for {
		if recordEvent(sink, result.Event, result.Patch, result.Event.Count > 1, eventCorrelator) {
			break
		}
		tries++
		if tries >= maxTriesPerEvent {
			glog.Errorf("Unable to write event '%#v' (retry limit exceeded!)", event)
			break
		}
		// Randomize the first sleep so that various clients won't all be
		// synced up if the master goes down.
		if tries == 1 {
			time.Sleep(time.Duration(float64(sleepDuration) * randGen.Float64()))
		} else {
			time.Sleep(sleepDuration)
		}
	}
}
示例#20
0
func DuplicateRequest(request *http.Request, r *rand.Rand) (request1 *http.Request, request2 *http.Request) {
	b1 := new(bytes.Buffer)
	b2 := new(bytes.Buffer)
	w := io.MultiWriter(b1, b2)
	io.Copy(w, request.Body)
	defer request.Body.Close()
	if r.Int31n(100) <= int32(*percent) {
		request1 = &http.Request{
			Method:        request.Method,
			URL:           request.URL,
			Proto:         "HTTP/1.1",
			ProtoMajor:    1,
			ProtoMinor:    1,
			Header:        request.Header,
			Body:          nopCloser{b1},
			Host:          request.Host,
			ContentLength: request.ContentLength,
		}
	} else {
		request1 = nil
	}
	request2 = &http.Request{
		Method:        request.Method,
		URL:           request.URL,
		Proto:         "HTTP/1.1",
		ProtoMajor:    1,
		ProtoMinor:    1,
		Header:        request.Header,
		Body:          nopCloser{b2},
		Host:          request.Host,
		ContentLength: request.ContentLength,
	}
	return
}
示例#21
0
// L883
func newTieredMergePolicy(r *rand.Rand) *index.TieredMergePolicy {
	tmp := index.NewTieredMergePolicy()
	if Rarely(r) {
		log.Println("Use crazy value for max merge at once")
		tmp.SetMaxMergeAtOnce(NextInt(r, 2, 9))
		tmp.SetMaxMergeAtOnceExplicit(NextInt(r, 2, 9))
	} else {
		tmp.SetMaxMergeAtOnce(NextInt(r, 10, 50))
		tmp.SetMaxMergeAtOnceExplicit(NextInt(r, 10, 50))
	}
	if Rarely(r) {
		log.Println("Use crazy value for max merge segment MB")
		tmp.SetMaxMergedSegmentMB(0.2 + r.Float64()*100)
	} else {
		tmp.SetMaxMergedSegmentMB(r.Float64() * 100)
	}
	tmp.SetFloorSegmentMB(0.2 + r.Float64()*2)
	tmp.SetForceMergeDeletesPctAllowed(0 + r.Float64()*30)
	if Rarely(r) {
		log.Println("Use crazy value for max merge per tire")
		tmp.SetSegmentsPerTier(float64(NextInt(r, 2, 20)))
	} else {
		tmp.SetSegmentsPerTier(float64(NextInt(r, 10, 50)))
	}
	configureRandom(r, tmp)
	tmp.SetReclaimDeletesWeight(r.Float64() * 4)
	return tmp
}
示例#22
0
// Generate implements testing/quick.Generator.
func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
	m := rand.Intn(len(h))
	for i := len(h) - 1; i > m; i-- {
		h[i] = byte(rand.Uint32())
	}
	return reflect.ValueOf(h)
}
示例#23
0
// Ian: Different from Lucene's default random class initializer, I have to
// explicitly initialize different directory randomly.
func newDirectoryImpl(random *rand.Rand, clazzName string) store.Directory {
	if clazzName == "random" {
		if Rarely(random) {
			switch random.Intn(1) {
			case 0:
				clazzName = "SimpleFSDirectory"
			}
		} else {
			clazzName = "RAMDirectory"
		}
	}
	if clazzName == "RAMDirectory" {
		return store.NewRAMDirectory()
	} else {
		path := TempDir("index")
		if err := os.MkdirAll(path, os.ModeTemporary); err != nil {
			panic(err)
		}
		switch clazzName {
		case "SimpleFSDirectory":
			d, err := store.NewSimpleFSDirectory(path)
			if err != nil {
				panic(err)
			}
			return d
		}
		panic(fmt.Sprintf("not supported yet: %v", clazzName))
	}
}
示例#24
0
文件: ofc.go 项目: jamesbsilva/go-ofc
func doOneStep(sys *StressLattice, alpha, stressNoise float32, R uint8, Ran *rand.Rand) uint {
	maxLoc := sys.FindMaxAllStress()
	currStress := sys.GetStress(maxLoc)
	sys.LoadSystem(sys.failureStress - currStress)
	currStress = sys.failureStress
	newStress := (stressNoise * (Ran.Float32()*2.0 - 1.0)) + sys.residualStress
	stressDistOut := (1.0 - alpha) * (currStress - newStress)

	//distribute stress
	sys.RangedDistStress(maxLoc, stressDistOut, newStress, R, sys.dim)
	eventSize := uint(1)

	// distribute until no more failed sites exist
	for sys.DistributeFailedSites() {
		maxLoc = sys.FindLargestDistributeFail()
		// stress change
		currStress = sys.GetStress(maxLoc)
		newStress = (stressNoise * (Ran.Float32()*2.0 - 1.0)) + sys.residualStress
		// stress to be distributed
		stressDistOut = (1.0 - alpha) * (currStress - newStress)
		sys.RangedDistStress(maxLoc, stressDistOut, newStress, R, sys.dim)
		eventSize = eventSize + 1
	}
	return eventSize
}
func TestPriorityQueue_order_Time(t *testing.T) {
	pq := NewPriorityQueue(Less(func(x, y interface{}) bool {
		return x.(time.Time).Before(y.(time.Time))
	}), 10)

	//Populate the priority queue with random times
	var src rand.Source = rand.NewSource(0)
	var r *rand.Rand = rand.New(src)
	for i := 0; i < 10; i++ {
		assert.True(
			t,
			pq.Length() == i,
			"pq.Length() = %d; want %d", pq.Length(), i,
		)
		pq.Insert(time.Now().Add(time.Hour * time.Duration(r.Int())))
	}
	var prev time.Time = pq.PopTop().(time.Time)
	var next time.Time
	for pq.Length() > 0 {
		next = pq.PopTop().(time.Time)
		assert.True(
			t,
			prev.Before(next),
			"%s sorted before %s; want %s sorted after %s", prev, next, prev, next,
		)
	}
}
示例#26
0
func fillPix(r *rand.Rand, pixs ...[]byte) {
	for _, pix := range pixs {
		for i := range pix {
			pix[i] = uint8(r.Intn(256))
		}
	}
}
示例#27
0
func randomString(r *rand.Rand, n int) []byte {
	b := new(bytes.Buffer)
	for i := 0; i < n; i++ {
		b.WriteByte(' ' + byte(r.Intn(95)))
	}
	return b.Bytes()
}
示例#28
0
func rndBytes(rng *rand.Rand, n int) []byte {
	r := make([]byte, n)
	for i := range r {
		r[i] = byte(rng.Int())
	}
	return r
}
示例#29
0
文件: nat.go 项目: pjump/gcc
// random creates a random integer in [0..limit), using the space in z if
// possible. n is the bit length of limit.
func (z nat) random(rand *rand.Rand, limit nat, n int) nat {
	if alias(z, limit) {
		z = nil // z is an alias for limit - cannot reuse
	}
	z = z.make(len(limit))

	bitLengthOfMSW := uint(n % _W)
	if bitLengthOfMSW == 0 {
		bitLengthOfMSW = _W
	}
	mask := Word((1 << bitLengthOfMSW) - 1)

	for {
		switch _W {
		case 32:
			for i := range z {
				z[i] = Word(rand.Uint32())
			}
		case 64:
			for i := range z {
				z[i] = Word(rand.Uint32()) | Word(rand.Uint32())<<32
			}
		default:
			panic("unknown word size")
		}
		z[len(limit)-1] &= mask
		if z.cmp(limit) < 0 {
			break
		}
	}

	return z.norm()
}
示例#30
0
// There are lots of ways of doing this faster, but this is good
// enough.
func RandomString(rng *rand.Rand, size int) string {
	out := make([]byte, size)
	for i := 0; i < size; i++ {
		out[i] = alphabet[rng.Intn(size)]
	}
	return string(out)
}