Exemple #1
0
func (g *GeneticElement) Crossover(m *GeneticElement, f *GeneticElement) {
	var mMask uint64
	var fMask uint64
	if m.initialized && f.initialized {
		guess := rand.Int() % 10
		if guess < 6 { //euristic value for ricombination
			cxIndex := uint(rand.Int() % len(f.tRef))
			mMask = 0xFFFFFFFFFFFFFFFF << cxIndex
			fMask = 0xFFFFFFFFFFFFFFFF ^ mMask
			g.chromosome = (fMask & f.chromosome) | (mMask & m.chromosome)
		} else {
			g.chromosome = f.chromosome
		}
		guess = rand.Int() % 100 // generate a mutation into genoma
		if guess <= 1 {
			mutatedbit := uint(rand.Int() % len(f.tRef))
			mMask = 0x1 << mutatedbit
			g.chromosome = g.chromosome ^ mMask
		}

		g.tRef = f.tRef
		g.target = f.target
		g.value, g.weight = evalutate(g.chromosome, g.tRef)
		g.fitness = generate_fitness(g.weight, g.target)
		g.initialized = true
	}
}
func (nv StrValue) Create() string {
	if nv.size == 128 {
		substrs := [...]string{"ning", "izzy", "ariel", "nick",
			"mazur", "ryan", "hugg", "yankeesfan", "volt", "runs",
			"with", "scissors", "blue", "awesome", "weak", "sauce",
			"chicken", "strength", "vikram", "bobbi", "jarr", "bungee",
			"banjo", "arrow", "trinity", "coffee", "pvc"}
		cnt := (rand.Int() % 10) + 1
		vals := make([]string, cnt)

		for i := 0; i < cnt; i++ {
			vals[i] = substrs[rand.Int()%len(substrs)]
		}
		return strings.Join(vals, "")
	} else if nv.size == 4 {
		substrs := [...]string{"a", "b", "c", "d"}
		cnt := 4
		vals := make([]string, cnt)

		for i := 0; i < cnt; i++ {
			vals[i] = substrs[rand.Int()%len(substrs)]
		}
		return strings.Join(vals, "")
	}
	panic("Invalid string size.")
}
Exemple #3
0
func (g *GeneticElement) Crossover(m *GeneticElement, f *GeneticElement) {
	var mMask uint64
	var fMask uint64
	if m.initialized && f.initialized {
		guess := rand.Int() % 10
		if guess < 6 { //euristic value for ricombination
			cxIndex := uint(rand.Int() % 36)
			mMask = 0xFFFFFFFFFFFFFFFF << cxIndex
			fMask = 0xFFFFFFFFFFFFFFFF ^ mMask
			g.chromosome = (fMask & f.chromosome) | (mMask & m.chromosome)
		} else {
			g.chromosome = f.chromosome
		}
		guess = rand.Int() % 100 // generate a mutation into genoma
		if guess <= 1 {
			mutatedbit := uint(rand.Int() % 36)
			mMask = 0x1 << mutatedbit
			g.chromosome = g.chromosome ^ mMask
		}

		g.maptable = f.maptable
		g.computeFitness()
		g.initialized = true
	}
}
Exemple #4
0
func main() {
	flag.Parse()
	//	prime();
	var blocks [1]struct {
		base *byte
		siz  uintptr
	}
	for i := 0; i < 1<<10; i++ {
		if i%(1<<10) == 0 && *chatty {
			println(i)
		}
		b := rand.Int() % len(blocks)
		if blocks[b].base != nil {
			//	println("Free", blocks[b].siz, blocks[b].base);
			runtime.Free(blocks[b].base)
			blocks[b].base = nil
			allocated -= uint64(blocks[b].siz)
			continue
		}
		siz := uintptr(rand.Int() >> (11 + rand.Uint32()%20))
		base := runtime.Alloc(siz)
		//	ptr := uintptr(syscall.BytePtr(base))+uintptr(siz/2);
		//	obj, size, ref, ok := allocator.find(ptr);
		//	if obj != base || *ref != 0 || !ok {
		//		panicln("find", siz, obj, ref, ok);
		//	}
		blocks[b].base = base
		blocks[b].siz = siz
		allocated += uint64(siz)
		//	println("Alloc", siz, base);
		memset(base, 0xbb, siz)
		bigger()
	}
}
Exemple #5
0
func randInts() []int {
	r := rand.Int() % 30
	d := make([]int, r)
	for i := 0; i < r; i++ {
		d[i] = rand.Int() % 30
	}
	return d
}
func createSchema() ([]NValue, []string) {
	schema := make([]NValue, (rand.Int()%maxIdxColumns)+1)
	abbrev := make([]string, len(schema))
	for ii := 0; ii < len(schema); ii++ {
		schemaType := voltIdxTypes[rand.Int()%len(voltIdxTypes)]
		schema[ii] = nvalueFactory(schemaType)
		abbrev[ii] = schemaType
	}
	return schema, abbrev
}
Exemple #7
0
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)
	}
}
Exemple #8
0
func (p *GeneticElement) InitRand(e []Element, target int) {
	bitNum := rand.Int() % len(e)
	p.chromosome = uint64(0)
	for i := 0; i <= bitNum; i++ {
		tmp := uint64(1) << uint(rand.Int()%len(e))
		p.chromosome = p.chromosome | tmp
	}
	p.tRef = e[0:]
	p.target = target
	p.value, p.weight = evalutate(p.chromosome, e[0:])
	p.fitness = generate_fitness(p.weight, target)
	p.initialized = true
}
func TestKeyValue(t *testing.T) {
	look_up_table := Make(true)
	for i := 0; i < 2000; i++ {
		look_up_table.Insert(key_value{rand.Int(), rand.Int()})
	}
	for kvi := range look_up_table.Iter(IN_ORDER) {
		kv := kvi.(key_value)
		val, found := look_up_table.Find(key_value{kv.key, 0})
		if !found || kv.value != val.(key_value).value {
			t.Errorf("Bad value: %v : %v != %v\n", kv, kv.value, val.(key_value).value)
		}
	}
}
func sign() int {
	sign := rand.Int() % 2
	if sign == 0 {
		return 1
	}
	return -1
}
Exemple #11
0
func insert1000Records(t *testing.T, db *Client) map[uint64][]string {
	stmt, err := db.InitStmt()
	if err != nil {
		t.Fatalf("InitStmt: %v", err)
	}

	err = stmt.Prepare(INSERT_SIMPLE_STMT)
	if err != nil {
		t.Logf("Prepare insert: %v", err)
	}

	t.Logf("Insert 1000 records")
	rowMap := make(map[uint64][]string)
	for i := 0; i < 1000; i++ {
		num, str1, str2 := rand.Int(), randString(32), randString(128)
		err = stmt.BindParams(num, str1, str2)
		if err != nil {
			t.Fatalf("Error %s", err)
		}
		err = stmt.Execute()
		if err != nil {
			t.Fatalf("Error %s", err)
		}
		row := []string{fmt.Sprintf("%d", num), str1, str2}
		rowMap[stmt.LastInsertId] = row
	}
	return rowMap
}
Exemple #12
0
// This is simple today - it returns the first listed service that matches the request
// Load balancing needs to be applied here somewhere.
func GetRandomClientByProvides(provides string) (*rpc.Client, os.Error) {
	var providesList = make([]*Service, 0)

	var newClient *rpc.Client
	var err os.Error

	for _, v := range NS.Services {
		if v != nil {
			if v.Provides == provides {
				providesList = append(providesList, v)
			}

		}
	}

	if len(providesList) > 0 {
		random := rand.Int() % len(providesList)
		s := providesList[random]

		portString := fmt.Sprintf("%s:%d", s.IPAddress, s.Port)
		newClient, err = rpc.DialHTTP("tcp", portString)
		if err != nil {
			LogError(WARN, fmt.Sprintf("Found %d Clients to service %s request.", len(providesList), provides))
			return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, provides)
		}

	} else {
		return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, provides)
	}
	return newClient, nil
}
Exemple #13
0
func findRand(t *testing.T, conn *db.Connection, ch chan *vector.Vector) {
	stmt, sErr := conn.Prepare(
		"SELECT * FROM t WHERE i != ? ORDER BY RAND()")
	if sErr != nil {
		error(t, sErr, "Couldn't prepare")
	}

	rs, cErr := conn.Execute(stmt, rand.Int())
	if cErr != nil {
		error(t, cErr, "Couldn't select")
	}

	vout := new(vector.Vector)
	for res := range rs.Iter() {
		if res.Error() != nil {
			error(t, res.Error(), "Couldn't fetch")
		}
		vout.Push(res.Data())
	}

	if vout.Len() != len(tableT) {
		t.Error("Invalid length")
	}

	stmt.Close()
	ch <- vout
}
func serveTestFiles(t *testing.T) (l net.Listener, err os.Error) {
	foundValidPort := false
	var port_str string
	for !foundValidPort {
		port := (rand.Int() & 0x7FFF) + 0x08000
		port_str = strconv.Itoa(port)
		addr, err := net.ResolveTCPAddr("127.0.0.1:" + port_str)
		if err != nil {
			t.Error("Create TCP Address: ", err.String())
			return nil, err
		}
		l, err = net.ListenTCP("tcp4", addr)
		if err != nil {
			if err == os.EADDRINUSE || strings.LastIndex(err.String(), os.EADDRINUSE.String()) != -1 {
				continue
			}
			t.Error("Unable to listen on TCP port: ", err.String())
			return l, err
		}
		foundValidPort = true
	}
	OverrideRapleafHostPort("127.0.0.1", port_str)
	go http.Serve(l, http.HandlerFunc(ServeTestHTTP))
	return l, err
}
Exemple #15
0
// DialUri connects to one of the doozer servers given in `uri`. If `uri`
// contains a secret key, then DialUri will call `Access` with the secret.
func DialUri(uri string) (*Conn, os.Error) {
	if !strings.HasPrefix(uri, uriPrefix) {
		return nil, ErrInvalidUri
	}

	q := uri[len(uriPrefix):]
	p, err := http.ParseQuery(q)
	if err != nil {
		return nil, err
	}

	addrs, ok := p["ca"]
	if !ok {
		return nil, ErrInvalidUri
	}

	c, err := Dial(addrs[rand.Int()%len(addrs)])
	if err != nil {
		return nil, err
	}

	secret, ok := p["sk"]
	if ok {
		err = c.Access(secret[0])
		if err != nil {
			c.Close()
			return nil, err
		}
	}

	return c, nil
}
Exemple #16
0
func (c *client) send(method string, stm string) ([]byte, os.Error) {
	conn, err := net.Dial("tcp", "", c.server)
	if err != nil {
		return nil, err
	}
	if len(c.password) > 0 {
		salt := make([]byte, 8)
		for n := 0; n < len(salt); n++ {
			salt[n] = uint8(rand.Int() % 256)
		}
		d := md5.New()
		d.Write([]byte(c.password))
		d.Write(salt)
		hash := d.Sum()
		d.Reset()
		d.Write(hash)
		s := fmt.Sprintf("%x.%x", d.Sum(), salt)
		conn.Write([]byte(
			"GNTP/1.0 " + method + " NONE MD5:" + s + "\r\n" + stm + "\r\n"))
	} else {
		conn.Write([]byte(
			"GNTP/1.0 " + method + " NONE\r\n" + stm + "\r\n"))
	}
	return ioutil.ReadAll(conn)
}
Exemple #17
0
func makeVector(size int, shape string) vector.Vector {

	var v vector.Vector

	switch shape {

	case "xor":
		for i := 0; i < size; i++ {
			v.Push(&record{0xff & (i ^ 0xab), i})
		}

	case "sorted":
		for i := 0; i < size; i++ {
			v.Push(&record{i, i})
		}

	case "revsorted":
		for i := 0; i < size; i++ {
			v.Push(&record{size - i, i})
		}

	case "random":
		rand.Seed(1)

		for i := 0; i < size; i++ {
			v.Push(&record{rand.Int(), i})
		}

	default:
		panic(shape)
	}

	return v
}
Exemple #18
0
// This is simple today - it returns the first listed service that matches the request
// Load balancing needs to be applied here somewhere.
func GetRandomClientByService(classname string) (*rpc.Client, os.Error) {
	var newClient *rpc.Client
	var err os.Error
	serviceList := GetAllServiceProviders(classname)

	if len(serviceList) > 0 {
		chosen := rand.Int() % len(serviceList)
		s := serviceList[chosen]

		hostString := fmt.Sprintf("%s:%d", s.IPAddress, s.Port)
		protocol := strings.ToLower(s.Protocol) // to be safe
		switch protocol {
		default:
			newClient, err = rpc.DialHTTP("tcp", hostString)
		case "json":
			newClient, err = jsonrpc.Dial("tcp", hostString)
		}

		if err != nil {
			LogWarn(fmt.Sprintf("Found %d nodes to provide service %s requested on %s, but failed to connect.",
				len(serviceList), classname, hostString))
			return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, classname)
		}

	} else {
		LogWarn(fmt.Sprintf("Found no node to provide service %s.", classname))
		return nil, NewError(NO_CLIENT_PROVIDES_SERVICE, classname)
	}
	return newClient, nil
}
Exemple #19
0
func rndName(n int) string {
	b := make([]byte, n)
	for i := 0; i < n; i++ {
		b[i] = byte('a' + rand.Int()%26)
	}
	return string(b)
}
Exemple #20
0
func TestWriter(t *testing.T) {
	largeData := make([]byte, 1<<17)
	for i := range largeData {
		largeData[i] = byte(rand.Int())
	}
	writeTests[1].Data = largeData
	defer func() {
		writeTests[1].Data = nil
	}()

	// write a zip file
	buf := new(bytes.Buffer)
	w := NewWriter(buf)

	for _, wt := range writeTests {
		testCreate(t, w, &wt)
	}

	if err := w.Close(); err != nil {
		t.Fatal(err)
	}

	// read it back
	r, err := NewReader(sliceReaderAt(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		t.Fatal(err)
	}
	for i, wt := range writeTests {
		testReadFile(t, r.File[i], &wt)
	}
}
Exemple #21
0
func TestRect(t *testing.T) {
	const n = 10
	// testing with float64
	for i := 0; i < n; i++ {
		llx, lly := rand.NormFloat64(), rand.NormFloat64()
		urx, ury := rand.NormFloat64(), rand.NormFloat64()
		r := newRect(llx, lly, urx, ury)
		a := []float64{llx, lly, urx, ury}
		if bytes.Compare(r.output(), output(a)) != 0 {
			t.Errorf("newRect(%f, %f, %f, %f) doesn't work",
				llx, lly, urx, ury)
		}
	}
	// testing with int
	for i := 0; i < n; i++ {
		// random function that returns both positive and negative
		rnd := func() int {
			sign := 1
			if rand.Intn(2) == 0 {
				sign = -1
			}
			return sign * rand.Int()
		}

		llx, lly, urx, ury := rnd(), rnd(), rnd(), rnd()
		r := newRectInt(llx, lly, urx, ury)
		a := []int{llx, lly, urx, ury}
		if bytes.Compare(r.output(), output(a)) != 0 {
			t.Errorf("newRect(%d, %d, %d, %d) doesn't work",
				llx, lly, urx, ury)
		}
	}
}
Exemple #22
0
func main() {
	runtime.GOMAXPROCS(2) //Dual core
	args := flag.Args()

	if len(args) < 4 {
		fmt.Println("Usage: CallGenerator <numberOfAgents> <numberOfCalls> <maxCallDuration> <maxCallInterval>")
		return
	}
	num_agents, _ := strconv.Atoi(args[0])
	num_calls, _ := strconv.Atoi(args[1])
	max_dur, _ := strconv.Atoi(args[2])
	max_int, _ := strconv.Atoi(args[3])

	queue := make(chan *Call, 10000)
	clock_in := make(chan bool)
	clock_out := make(chan bool)

	call_center := &CallCenter{num_agents, queue, clock_in, clock_out}

	begin := time.Nanoseconds()

	call_center.Open()

	for i := 0; i < num_calls; i++ {
		time.Sleep(int64(max_int))
		queue <- &Call{i, rand.Int() * max_dur, time.Nanoseconds()}
	}

	call_center.Close()

	end := time.Nanoseconds()

	fmt.Printf("Simulation elapsed time: %d seconds\n", (end-begin)/1000000000)
}
Exemple #23
0
func genKey() string {
	key := make([]byte, keyLen)
	for i := 0; i < keyLen; i++ {
		key[i] = byte(rand.Int())
	}
	return string(key)
}
func root(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	clientTemplate := template.Must(template.ParseFile("client.html"))
	token_value := strconv.Itoa(rand.Int())
	token_key, _ := channel.Create(c, token_value)
	clientTemplate.Execute(w, token_key)
	map_clients[token_key] = token_value
}
Exemple #25
0
// Test rand module
func TestRandModule(t *testing.T) {
	rand.Seed(1234567890)
	var p int
	for i := 0; i < 10; i++ {
		p = rand.Int()
		println("Rand.Int() returns ", p)
	}
}
Exemple #26
0
func randomizeSet(n int) *IntTreap {
	s := Init([]int{})
	for i := 0; i < n; i++ {
		p := rand.Int()
		s = s.Insert(p)
	}
	return s
}
Exemple #27
0
func NewIntLeaf(x int) *IntTreap {
	l := new(IntTreap)
	l.x = x
	l.p = rand.Int()
	l.left = nil
	l.right = nil
	return l
}
func (nv DecValue) Create() string {
	vals := make([]string, 3)
	lhs := rand.Int() * sign()
	vals[0] = fmt.Sprint(lhs)
	vals[1] = "."
	vals[2] = fmt.Sprint(rand.Intn(99999999))
	return strings.Join(vals, "")
}
func randomize(x [][]int, row, col int) {
	for i := 0; i < row; i++ {
		//x[i]=make([]int,col)
		for j := 0; j < col; j++ {
			x[i][j] = rand.Int() % 10
		}
	}
}
Exemple #30
0
func (db *buttress) UnusedSlot() int {
	for {
		s := rand.Int()
		if _, ok := db.recs[s]; !ok {
			return s
		}
	}
	panic("unreach")
}