func init() { SyncChannel = make(chan float64, 100000) fmt.Println(" SyncChannel created") Rgen = rand.New(rand.NewSource(123813541954235)) Rgen2 = rand.New(rand.NewSource(12384235)) fmt.Println("init done") // function called automatically on pacakge load, initializes system channels // create channels SystemChan = make([]*channel, NCh) for i := range SystemChan { c := new(channel) c.i = i c.Emitters = list.New() c.Change = make(chan EmitterInt, 100) go c.changeChan() SystemChan[i] = c } // evaluate overlaping factors of channels overlapN := int(math.Floor(1.0 / (1.0 - float64(roverlap)))) if overlapN < 1 { overlapN = 1 } if roverlap > 0.0 { for i := NChRes; i < NCh; i++ { SystemChan[i].coIntC = make([]coIntChan, overlapN*2) for k := 1; k <= overlapN; k++ { fac := 1.0 - float64(k)*(1.0-roverlap) SystemChan[i].coIntC[overlapN-k].c = i - k SystemChan[i].coIntC[overlapN-k].factor = float64(fac) if i+k < NCh { SystemChan[i].coIntC[overlapN+k-1].c = i + k SystemChan[i].coIntC[overlapN+k-1].factor = float64(fac) } } } } }
func LoadWorldStore(worldPath string) (world *WorldStore, err os.Error) { levelData, err := loadLevelData(worldPath) if err != nil { return } // In both single-player and SMP maps, the 'spawn position' is stored in // the level data. x, xok := levelData.Lookup("Data/SpawnX").(*nbt.Int) y, yok := levelData.Lookup("Data/SpawnY").(*nbt.Int) z, zok := levelData.Lookup("Data/SpawnZ").(*nbt.Int) if !xok || !yok || !zok { err = os.NewError("Invalid map level data: does not contain Spawn{X,Y,Z}") log.Printf("%#v", levelData) return } spawnPosition := BlockXyz{ BlockCoord(x.Value), BlockYCoord(y.Value), BlockCoord(z.Value), } var timeTicks Ticks if timeTag, ok := levelData.Lookup("Data/Time").(*nbt.Long); ok { timeTicks = Ticks(timeTag.Value) } var chunkStores []chunkstore.IChunkStore persistantChunkStore, err := chunkstore.ChunkStoreForLevel(worldPath, levelData, DimensionNormal) if err != nil { return } chunkStores = append(chunkStores, chunkstore.NewChunkService(persistantChunkStore)) var seed int64 if seedNbt, ok := levelData.Lookup("Data/RandomSeed").(*nbt.Long); ok { seed = seedNbt.Value } else { seed = rand.NewSource(time.Seconds()).Int63() } chunkStores = append(chunkStores, chunkstore.NewChunkService(generation.NewTestGenerator(seed))) for _, store := range chunkStores { go store.Serve() } world = &WorldStore{ WorldPath: worldPath, Seed: seed, Time: timeTicks, LevelData: levelData, ChunkStore: chunkstore.NewChunkService(chunkstore.NewMultiStore(chunkStores)), SpawnPosition: spawnPosition, } go world.ChunkStore.Serve() return }
func BenchmarkMonte(b *testing.B) { rng := rand.New(rand.NewSource(1)) start := ALoc(40) l := start n := 0 tn := 0 s := 0 for i := 0; i < b.N*NMonte; i++ { var d maps.Direction for _, d = range maps.Permute5(rng) { s++ if d == maps.NoMovement { break } else if nl := A.LocStep[l][d]; maps.StepableItem[A.Grid[nl]] { l = nl break } } if l == 0 { l = start n++ tn += s s = 0 } } if arenachatty { log.Printf("mean steps to exit %.2f exited %d Steps %d %d", float64(tn)/float64(n), n, tn, b.N) } }
func (b *Bytes) fab(parent string) os.Error { fh, err := os.OpenFile(parent, os.O_RDWR|os.O_APPEND, 0644) if fh == nil { return err } defer fh.Close() rnd := rand.New(rand.NewSource(b.Seed)) for toWrite := b.Length; toWrite > 0; { buf := &bytes.Buffer{} for i := 0; i < CHUNKSIZE && toWrite > 0; i++ { buf.WriteByte(byte(rnd.Int())) toWrite-- } _, err = buf.WriteTo(fh) if err != nil { return err } } return nil }
func (t RoundRobin) Run(array player.Array, match Match) []int { rand := rand.New(rand.NewSource(time.Seconds())) results := make([]int, array.Len()) wins := make([]int, array.Len()) // Every player plays every other once, sort players by number of wins for a := 0; a < array.Len(); a++ { for b := a + 1; b < array.Len(); b++ { winner, _, _ := match.Play(a, b, array, rand) wins[winner]++ } } for i := 0; i < len(results); i++ { best := 0 for j := range wins { if wins[j] > wins[best] { best = j } } results[i] = best wins[best] = -1 } return results }
func main() { api = twitter.NewApi() done = make(chan bool) r = rand.New(rand.NewSource(time.Seconds())) crawl(kStart, 0) <-done }
func NewGame(worldPath string) (game *Game, err os.Error) { worldStore, err := worldstore.LoadWorldStore(worldPath) if err != nil { return nil, err } game = &Game{ players: make(map[EntityId]*player.Player), playerNames: make(map[string]*player.Player), workQueue: make(chan func(*Game), 256), playerConnect: make(chan *player.Player), playerDisconnect: make(chan EntityId), time: worldStore.Time, worldStore: worldStore, } game.entityManager.Init() game.serverId = fmt.Sprintf("%016x", rand.NewSource(worldStore.Seed).Int63()) //game.serverId = "-" game.shardManager = shardserver.NewLocalShardManager(worldStore.ChunkStore, &game.entityManager) // TODO: Load the prefix from a config file gamerules.CommandFramework = command.NewCommandFramework("/") go game.mainLoop() return }
func TestMarshalUnmarshal(t *testing.T) { rand := rand.New(rand.NewSource(0)) for i, iface := range messageTypes { ty := reflect.ValueOf(iface).Type() n := 100 if testing.Short() { n = 5 } for j := 0; j < n; j++ { v, ok := quick.Value(ty, rand) if !ok { t.Errorf("#%d: failed to create value", i) break } m1 := v.Elem().Interface() m2 := iface marshaled := marshal(msgIgnore, m1) if err := unmarshal(m2, marshaled, msgIgnore); err != nil { t.Errorf("#%d failed to unmarshal %#v: %s", i, m1, err) break } if !reflect.DeepEqual(v.Interface(), m2) { t.Errorf("#%d\ngot: %#v\nwant:%#v\n%x", i, m2, m1, marshaled) break } } } }
func NewPerlinNoise(seed int64) *PerlinNoise { gen := &PerlinNoise{ seed: seed, } // The source's seed is reset to seed for each precomputed set so that any // code reordering in this implementation does not alter the noise values // produced for a given seed. source := rand.NewSource(0) rnd := rand.New(source) // Initialize gen.permut. source.Seed(seed) perm := rnd.Perm(len(gen.permut)) for i := range perm { gen.permut[i] = perm[i] } // Initialize gen.g2d. source.Seed(seed) for i := range perm { randVector(gen.g2d[i][:], rnd) normVector(gen.g2d[i][:]) } return gen }
func TestSum(t *testing.T) { var buf [100000]uint8 rnd := rand.New(rand.NewSource(4)) for i := range buf { buf[i] = uint8(rnd.Intn(256)) } sum := func(offset, len int) uint32 { rs := New() for count := offset; count < len; count++ { rs.Roll(buf[count]) } return rs.Digest() } sum1a := sum(0, len(buf)) sum1b := sum(1, len(buf)) sum2a := sum(len(buf)-windowSize*5/2, len(buf)-windowSize) sum2b := sum(0, len(buf)-windowSize) sum3a := sum(0, windowSize+3) sum3b := sum(3, windowSize+3) if sum1a != sum1b { t.Errorf("sum1a=%d sum1b=%d", sum1a, sum1b) } if sum2a != sum2b { t.Errorf("sum2a=%d sum2b=%d", sum2a, sum2b) } if sum3a != sum3b { t.Errorf("sum3a=%d sum3b=%d", sum3a, sum3b) } }
func BenchmarkMonteFull(b *testing.B) { rng := rand.New(rand.NewSource(1)) start := torus.Location(136) l := start n := 0 tn := 0 s := 0 for i := 0; i < b.N*NMonte; i++ { s++ var d maps.Direction for _, d = range maps.Permute5(rng) { if d == maps.NoMovement { break } else if nl := M.LocStep[l][d]; maps.StepableItem[M.Grid[nl]] { l = nl break } } if l == 0 { l = start n++ tn += s s = 0 } } if arenachatty { log.Printf("mean steps to exit %.2f", float64(tn)/float64(n)) } }
func (t SingleElimination) Run(array player.Array, match Match) []int { rand := rand.New(rand.NewSource(time.Seconds())) results := make([]int, array.Len()) num_ranked := len(results) - 1 rounds := make([][]int, intlog(array.Len())+1) rounds[0] = initialSeeds(array.Len()) for r := 1; ; r++ { if len(rounds[r-1])/2 == 0 { break } rounds[r] = make([]int, len(rounds[r-1])/2) for i := range rounds[r] { a := rounds[r-1][2*i] b := rounds[r-1][2*i+1] rounds[r][i], results[num_ranked], _ = match.Play(a, b, array, rand) num_ranked-- } } results[num_ranked] = rounds[len(rounds)-1][0] if num_ranked != 0 { panic("Didn't rank all the players!") } return results }
func initColors(seed int64) { fmt.Printf("%d ", seed) r := rand.New(rand.NewSource(seed)) for i := 0; i < 100; i++ { colors[i] = image.RGBAColor{uint8rand(r), uint8rand(r), uint8rand(r), 255} } }
func TestMakeMatrix3(t *testing.T) { const size = 3 r := rand.New(rand.NewSource(time.Nanoseconds())) data := make([]float32, size*size) for iterations := 0; iterations < 1000; iterations++ { // Initialize the data for i := 0; i < size*size; i++ { data[i] = (Randf(r) - 0.5) * 1000 } m1 := MakeMatrix3(true, data...) m2 := MakeMatrix3(false, data...) for r := 0; r < size; r++ { for c := 0; c < size; c++ { if m1.At(r, c) != data[r*size+c] { t.Errorf("m[%d][%d] (%f) != data[%d] (%f)", r, c, m1.At(r, c), r*size+c, data[r*size+c]) } if m2.At(r, c) != data[c*size+r] { t.Errorf("m[%d][%d] (%f) != data[%d] (%f)", r, c, m1.At(r, c), r*size+c, data[r*size+c]) } } } } }
func TestMatrix3_MultiplyV(t *testing.T) { const size = 3 r := rand.New(rand.NewSource(time.Nanoseconds())) // Simple math test for iterations := 0; iterations < 1000; iterations++ { data1 := (Randf(r) - 0.5) * 1000 data2 := (Randf(r) - 0.5) * 1000 data3 := data1 * data2 for element := 0; element < size*size; element++ { var m Matrix3 m[element] = data1 row_index := element / size col_index := element % size for v_element := 0; v_element < size; v_element++ { var v Vector3 v[v_element] = data2 r1 := m.MultiplyV(v) if col_index != v_element { var r2 Vector3 if !r1.Equals(r2) { t.Error("r1 != r2\n\tm:", m, "\n\r1:", r1, "\n\r2:", r2) } } else { var r2 Vector3 r2[row_index] = data3 if !r1.Equals(r2) { t.Error("r1 != r2\n\tm:", m, "\n\r1:", r1, "\n\r2:", r2) } } } } } // Test identity matrix { data := make([]float32, size) m := MakeMatrix3Identity() for iterations := 0; iterations < 1000; iterations++ { for i := 0; i < size; i++ { data[i] = (Randf(r) - 0.5) * 1000 } v1 := MakeVector3(data...) v2 := m.MultiplyV(v1) if !v1.Equals(v2) { t.Error("v1 != v2\n\tm:", m, "\n\v1:", v1, "\n\v2:", v2) } } } // TODO: Get a bunch of test data to do this input_matrix_data := [...][size * size]float32{} _ = input_matrix_data }
func TestMatrix3_IdentityThis(t *testing.T) { const size = 3 r := rand.New(rand.NewSource(time.Nanoseconds())) data := make([]float32, size*size) for iterations := 0; iterations < 1000; iterations++ { // Initialize the data for i := 0; i < size*size; i++ { data[i] = (Randf(r) - 0.5) * 1000 } m1 := MakeMatrix3(true, data...) m1.IdentityThis() for r := 0; r < size; r++ { for c := 0; c < size; c++ { if r == c { if m1.At(r, c) != 1 { t.Errorf("m[%d][%d] (%f) != 0", r, c, m1.At(r, c)) } } else if m1.At(r, c) != 0 { t.Errorf("m[%d][%d] (%f) != 0", r, c, m1.At(r, c)) } } } } }
func BenchmarkEncodeRGBOpaque(b *testing.B) { b.StopTimer() img := image.NewRGBA(640, 480) // Set all pixels to 0xFF alpha to force opaque mode. bo := img.Bounds() rnd := rand.New(rand.NewSource(123)) for y := bo.Min.Y; y < bo.Max.Y; y++ { for x := bo.Min.X; x < bo.Max.X; x++ { img.Set(x, y, image.RGBAColor{ uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), 255}) } } if !img.Opaque() { panic("expected image to be opaque") } b.SetBytes(640 * 480 * 4) b.StartTimer() options := &Options{Quality: 90} for i := 0; i < b.N; i++ { Encode(ioutil.Discard, img, options) } }
// returns an equivalent but completlely independent copy of b func (b *Board) Copy() *Board { sec, nsec, _ := os.Time() l := b.boardSize * b.boardSize cpy := &Board{ fields: make([]*Group, l), colorOfNextPlay: b.colorOfNextPlay, boardSize: b.boardSize, currentSequence: b.currentSequence, actionOnNextBlackMove: make([]*actionFunc, l), actionOnNextWhiteMove: make([]*actionFunc, l), fieldSequencesBlack: make([]uint32, l), fieldSequencesWhite: make([]uint32, l), rand: rand.New(rand.NewSource(sec + nsec)), prisonersBlack: b.prisonersBlack, prisonersWhite: b.prisonersWhite, } if b.ko != nil { cpy.ko = &koLock{ Pos: b.ko.Pos, Color: b.ko.Color, } } copy(cpy.fieldSequencesBlack, b.fieldSequencesBlack) copy(cpy.fieldSequencesWhite, b.fieldSequencesWhite) // Copy .fields in a seperate loop first. The next loop, in which we set .actionOnNext{Black,White}Move // depends upon correcty and already completely set .fields. Remember to copy each group only once! copiedGroups := make(map[*Group]bool) for i := 0; i < l; i++ { grp := b.fields[i] _, present := copiedGroups[grp] if !present && grp != nil { gcpy := grp.Copy() last := gcpy.Fields.Last() for it := gcpy.Fields.First(); it != last; it = it.Next() { cpy.fields[it.Value()] = gcpy } // remember that we already copied grp copiedGroups[grp] = true } } for i := 0; i < l; i++ { // copy .actionOnNextBlackMove and adjust its context if f := b.actionOnNextBlackMove[i]; f != nil { cpy.actionOnNextBlackMove[i] = NewActionFunc(cpy, nil, f.f) _, cpy.actionOnNextBlackMove[i].context = cpy.getEnvironmentAndContext(i, Black) } // copy .actionOnNextWhiteMove and adjust its context if f := b.actionOnNextWhiteMove[i]; f != nil { cpy.actionOnNextWhiteMove[i] = NewActionFunc(cpy, nil, f.f) _, cpy.actionOnNextWhiteMove[i].context = cpy.getEnvironmentAndContext(i, White) } } return cpy }
func BenchmarkGetTest(b *testing.B) { b.StopTimer() r := rand.New(rand.NewSource(0)) sz := 100000 s := New(uint(sz)) b.StartTimer() for i := 0; i < b.N; i++ { s.Test(uint(r.Int31n(int32(sz)))) } }
/* * Create a pseudo-random block using given seed. */ func randBuf(seed int64) []byte { rnd := rand.New(rand.NewSource(seed)) buf := &bytes.Buffer{} for i := 0; i < fs.BLOCKSIZE; i++ { buf.WriteByte(byte(rnd.Int())) } return buf.Bytes() }
func addHorde() { src := rand.NewSource(time.Nanoseconds()) rng := rand.New(src) horde := make([]*core.User, 20000) // Add the horde. for i, _ := range horde { data := make([]core.DataChange, 4) data[0].Name, data[0].Data = "ip", fmt.Sprintf("%d.%d.%d.%d", rng.Int()%255, rng.Int()%255, rng.Int()%255, rng.Int()%255) data[1].Name, data[1].Data = "hostname", fmt.Sprintf("%d.Horde.FakeUsers.PsuedoUserUnion.org", rng.Int()%1000000) data[2].Name, data[2].Data = "ident", fmt.Sprintf("horde-%d", rng.Int()%1000000) data[3].Name, data[3].Data = "account", fmt.Sprintf("horde-%d", rng.Int()%1000000) horde[i] = core.NewUser("oddcomm/modules/dev/horde", nil, true, "", data) horde[i].SetNick(me, fmt.Sprintf("horde-%d", rng.Int()%1000000), -1) horde[i].PermitRegistration(me) } // Make a huge channel containing the entire horde. core.GetChannel("", "huge").Join(me, horde) // Make 100 channels containing roughly a twentieth of the horde each. // Each horde user is in an average of roughly five. for i := 0; i < 100; i++ { joiners := make([]*core.User, len(horde)/20) for i, _ := range joiners { joiners[i] = horde[rand.Int()%len(horde)] } name := fmt.Sprintf("big_%d", i) core.GetChannel("", name).Join(me, joiners) } // Make 2000 channels containing roughly 1/400th of the horde each. // Each horde user is in an average of roughly five. for i := 0; i < 2000; i++ { joiners := make([]*core.User, len(horde)/400) for i, _ := range joiners { joiners[i] = horde[rand.Int()%len(horde)] } name := fmt.Sprintf("medium_%d", i) core.GetChannel("", name).Join(me, joiners) } // Make horde*2 channels containing roughly four of the horde each. // Each horde user is in an average of roughly eight. for i := 0; i < len(horde)*2; i++ { joiners := make([]*core.User, 4) for i, _ := range joiners { joiners[i] = horde[rand.Int()%len(horde)] } name := fmt.Sprintf("small_%d", i) core.GetChannel("", name).Join(me, joiners) } }
func NewFileSeededSource(filename string) (src rand.Source, err os.Error) { fileSource, err := NewFileBasedSource(filename) defer fileSource.Close() if err != nil { return src, err } var seed int64 = fileSource.Int63() src = rand.NewSource(seed) return src, err }
func NewUnsignedPermanode() map[string]interface{} { m := newCamliMap(1, "permanode") chars := make([]byte, 20) // Don't need cryptographically secure random here, as this // will be GPG signed anyway. rnd := rand.New(rand.NewSource(time.Nanoseconds())) for idx, _ := range chars { chars[idx] = byte(32 + rnd.Intn(126-32)) } m["random"] = string(chars) return m }
func TestFuzz(t *testing.T) { rand := rand.New(rand.NewSource(0)) for _, iface := range tests { m := iface.(testMessage) for j := 0; j < 1000; j++ { len := rand.Intn(100) bytes := randomBytes(len, rand) // This just looks for crashes due to bounds errors etc. m.unmarshal(bytes) } } }
func initGame(obj *Game) *Game { obj.Random = rand.New(rand.NewSource(time.Nanoseconds())) for Y := 0; Y < BOARD_MAX_Y; Y++ { for X := 0; X < BOARD_MAX_X; X++ { if X == 0 || X == LIMIT_X || Y >= LIMIT_Y { obj.Board[Y][X] = 0 } else { obj.Board[Y][X] = -1 } } } return obj }
func TestMatrix3_Equals(t *testing.T) { const size = 3 r := rand.New(rand.NewSource(time.Nanoseconds())) data1 := make([]float32, size*size) data2 := make([]float32, size*size) // Test Equals for iterations := 0; iterations < 1000; iterations++ { // Initialize the data for i := 0; i < size*size; i++ { data1[i] = (Randf(r) - 0.5) * 1000 } m1 := MakeMatrix3(true, data1...) m2 := MakeMatrix3(true, data1...) if !m1.Equals(m2) { t.Error("m1 != m2\n\tm1:", m1, "\n\tm2:", m2) } if !m2.Equals(m1) { t.Error("m2 != m1\n\tm1:", m1, "\n\tm2:", m2) } } // Test !Equals for iterations := 0; iterations < 1000; iterations++ { // Initialize the data for i := 0; i < size*size; i++ { data1[i] = (Randf(r) - 0.5) * 1000 } m1 := MakeMatrix3(true, data1...) for element := 0; element < size*size; element++ { for i := 0; i < size*size; i++ { data2[i] = data1[i] } data2[element] += 1 m2 := MakeMatrix3(true, data2...) if m1.Equals(m2) { t.Error("m1 == m2\n\tm1:", m1, "\n\tm2:", m2) } if m2.Equals(m1) { t.Error("m2 == m1\n\tm1:", m1, "\n\tm2:", m2) } } } }
func calcPartialPI(result chan<- float64, iter int) { var circle, i int rg := rand.New(rand.NewSource(time.Nanoseconds() % 1e9)) for i = 0; i < iter; i++ { x, y := getCoord(rg), getCoord(rg) if (x*x + y*y) < 1.0 { circle++ } } result <- 4 * float64(circle) / float64(i) }
// Creates a new Consumer instance. // - consumerKey and consumerSecret // values you should obtain from the ServiceProvider when you register your application. // // - serviceProvider: // see the documentation for ServiceProvider for how to create this. // func NewConsumer(consumerKey string, consumerSecret string, serviceProvider ServiceProvider) *Consumer { clock := &defaultClock{} return &Consumer{ consumerKey: consumerKey, consumerSecret: consumerSecret, serviceProvider: serviceProvider, clock: clock, HttpClient: &http.Client{}, nonceGenerator: rand.New(rand.NewSource(clock.Seconds())), signer: &SHA1Signer{}, AdditionalParams: make(map[string]string), } }
func NewTestGenerator(seed int64) *TestGenerator { perlin := perlin.NewPerlinNoise(seed) randSource := rand.NewSource(time.Nanoseconds()) randGen := rand.New(randSource) return &TestGenerator{ randSource: randSource, randGen: randGen, heightSource: &Sum{ Inputs: []ISource{ &Turbulence{ Dx: &Scale{50, 1, &Offset{20.1, 0, perlin}}, Dy: &Scale{50, 1, &Offset{10.1, 0, perlin}}, Factor: 50, Source: &Scale{ Wavelength: 200, Amplitude: 50, Source: perlin, }, }, &Turbulence{ Dx: &Scale{40, 1, &Offset{20.1, 0, perlin}}, Dy: &Scale{40, 1, &Offset{10.1, 0, perlin}}, Factor: 10, Source: &Mult{ A: &Scale{ Wavelength: 40, Amplitude: 20, Source: perlin, }, // Local steepness. B: &Scale{ Wavelength: 200, Amplitude: 1, Source: &Add{perlin, 0.6}, }, }, }, &Scale{ Wavelength: 5, Amplitude: 2, Source: perlin, }, }, }, } }
func BenchmarkMatrix3_ScalarMultiply(b *testing.B) { b.StopTimer() const size = 3 r := rand.New(rand.NewSource(time.Nanoseconds())) data1 := make([]float32, size*size) data2 := (Randf(r) - 0.5) * 1000 for i := 0; i < size*size; i++ { data1[i] = (Randf(r) - 0.5) * 1000 } m1 := MakeMatrix3(true, data1...) b.StartTimer() for iterations := 0; iterations < b.N; iterations++ { m1.ScalarMultiply(data2) } }