Example #1
0
    def run(self):
        self.auge_machen()
        xbew = random.randint(-1,1)/1000
        ybew = random.randint(-1,1)/1000
        zaehler = 0

        while self.pos[2] > self.spielfeldpos[2]+2.5:
            rate(25)
            self.pos -= vector(0,0,1)
            self.rotate(angle=pi/4, axis=(0,1,0))
            self.rotate(angle=pi/4, axis=(0,0,1))
            self.rotate(angle=pi/4, axis=(1,0,0))
            self.pos[0] -= xbew*(zaehler^2)
            self.pos[1] -= ybew*(zaehler^2)
            zaehler    += 1

        augenzahl=2

        if augenzahl == 2:
            self.axis=(0,1,0)
            self.axis=(1,0,0)
            self.axis=(0,0,1)
            self.rotate(angle=pi/2, axis=(1,0,0))

        if augenzahl == 3:
            self.axis=(0,1,0)
            self.axis=(1,0,0)
            self.axis=(0,0,-1)
            
        if augenzahl == 4:
            self.axis=(0,1,0)
            self.axis=(1,0,0)
            self.axis=(0,0,1)
    def enter(self):
        print "You do a dive roll into the Weapon Armory, crouch and scan the room"
        print "for more Gothons that might be hiding. It's dead quiet, too quiet."
        print "You stand up and run to the far side of the room and find the"
        print "neutron bomb in its container. There's a keypad lock on the box"
        print "and you need the code to get the bomb out. If you get the code"
        print "wrong 10 times then the lock closes forever and you can't"
        print "get the bomb. The code is 3 digits."
        code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))

        print code

        guesses = 0

        while guesses < 10:
            guess = raw_input("[keypad]> ")
            if guess == code:
                break
            print "BZZZZEDDD!"
            guesses += 1

        if guess == code:
            print "The container clicks open and the seal breaks, letting gas out."
            print "You grab the neutron bomb and run as fast as you can to the"
            print "bridge where you must place it in the right spot."
            return 'the_bridge'
        else:
            print "The lock buzzes one last time and then you hear a sickening"
            print "melting sound as the mechanism is fused together."
            print "You decide to sit there, and finally the Gothons blow up the"
            print "ship from their ship and you die."
            return 'death'
def comp_attack(computer):
	misses = []
	if computer.hits == []:
		while True:
			x = random.randint(0, 9)
			y = random.randint(0, 9)
			if (x, y) in computer.misses:
				continue
			elif (x, y) in computer.hits:
				continue
			else:
				return (x, y)
	else:
		while True:
			xy = random.choice(computer.hits)
			change = random.choice(((0, 1), (1, 0)))
			xy = update_coordinate(xy, change)
			if xy in computer.misses:
				misses.append(0)
			elif xy in computer.hits:
				misses.append(0)
			else:
				return xy
			if len(misses) >= 5:
				while True:
					x = random.randint(0, 9)
					y = random.randint(0, 9)
					if (x, y) in computer.misses:
						continue
					elif (x, y) in computer.hits:
						continue
					else:
						return (x, y)
Example #4
0
def loop():
    global CAT_POSITION, MICE
    MICE = [Mouse() for i in range(4)]

    while True:
        for e in pg.event.get():
            if e.type == pg.QUIT:
                pg.quit()
                sys.exit()

        # keyboard logic
        key_pressed = pg.key.get_pressed()
        if key_pressed[pg.K_q] == 1 or key_pressed[pg.K_ESCAPE] == 1:
            pg.event.post(pg.event.Event(pg.QUIT))

        if pg.mouse.get_focused():
            CAT_POSITION = set_cat_after_mouse()

        for mouse in MICE:
            if random.randint(0, 30) == 0:
                mouse.direction = random.randint(0, 3)
            mouse.run_away()

        if len(MICE) > 0 and len(MICE) <= 23 and random.randint(0, 50) == 0:
            new_mouse = Mouse()
            new_mouse.position = MICE[-1].position
            MICE.append(new_mouse)

        draw()
        clock.tick(24)
Example #5
0
def main():
    print("Code to look at runtime for insertion sort vs. Python's list sort.")
    
    numDig = 5 #number of digits to output
    
    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    print("\nSorting list with " + str(len(data)) + " elements.\n")
    
    start = time.time()
    insertionSort(data)
    end = time.time()
    print("Insertion sort -> " + str(round(end - start, numDig)) + " seconds.")

    #large list with numElements elements
    numElements = 10000
    data = []
    for i in range(numElements):
        data.append(randint(1, numElements))
        
    start = time.time()
    data.sort()
    end = time.time()
    print("Python's sort -> " + str(round(end - start, numDig)) + " seconds.")
Example #6
0
def growingtree(width, height, pad=1, choose=splitrandom, symmetric=False, startcentre=True):
    maze = initialclosed(width, height, pad)
    if startcentre:
        start = (width//2, height//2)
    else:
        start = (random.randint(0, width-1), random.randint(0, height-1))
    visited = {start}
    active = [start]
    while active:
        src = choose(active)
        dests = []
        # get unvisited neighbours
        for x, y in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            if src[0] + x < 0 or \
               src[0] + x >= width or \
               src[1] + y < 0 or \
               src[1] + y >= height:
                continue  # out of bounds
            if (src[0]+x, src[1]+y) not in visited:
                dests.append((src[0]+x, src[1]+y))
        if dests:  # if unvisited neighbours, pick one and create path to it
            dest = random.choice(dests)
            maze[src[1] + dest[1] + pad][src[0] + dest[0] + pad] = empty  # cool, hey?
            visited.add(dest)
            active.append(dest)
            if symmetric:
                src2 = (width - src[0] - 1, height - src[1] - 1)
                dest2 = (width - dest[0] - 1, height - dest[1] - 1)
                maze[src2[1] + dest2[1] + pad][src2[0] + dest2[0] + pad] = empty
                visited.add(dest2)
        else:  # if no more unvisited neighbours, remove from active
            active.remove(src)
    return maze
Example #7
0
def populate(parent, howmany, max_children):
	to_add = howmany
	if howmany > max_children:
		children = randint(2, max_children)
		distribution = []
		for i in xrange(0, children - 1):
			distribution.append(int(howmany / children))
		distribution.append(howmany - sum(distribution, 0))
		for i in xrange(0, children):
			steal_target = randint(0, children - 1)
			while steal_target == i:
				steal_target = randint(0, children -1)
			steal_count = randint(-1 * distribution[i],
					distribution[steal_target]) / 2
			distribution[i] += steal_count
			distribution[steal_target] -= steal_count
		
		for i in xrange(0, children):
			make_dict = randint(0, 1)
			baby = None
			if make_dict:
				baby = {}
			else:
				baby = []
			populate(baby, distribution[i], max_children)
			if isinstance(parent, dict):
				parent[os.urandom(8).encode("hex")] = baby
			else:
				parent.append(baby)
	else:
		populate_with_leaves(parent, howmany)
    def create_pinned_instance(self, os_conn, cluster_id,
                               name, vcpus, hostname, meta):
        """Boot VM on specific compute with CPU pinning

        :param os_conn: an object of connection to openstack services
        :param cluster_id: an integer number of cluster id
        :param name: a string name of flavor and aggregate
        :param vcpus: an integer number of vcpus for flavor
        :param hostname: a string fqdn name of compute
        :param meta: a dict with metadata for aggregate
        :return:
        """
        aggregate_name = name + str(random.randint(0, 1000))
        aggregate = os_conn.create_aggregate(aggregate_name,
                                             metadata=meta,
                                             hosts=[hostname])

        extra_specs = {'aggregate_instance_extra_specs:pinned': 'true',
                       'hw:cpu_policy': 'dedicated'}

        net_name = self.fuel_web.get_cluster_predefined_networks_name(
            cluster_id)['private_net']
        flavor_id = random.randint(10, 10000)
        flavor = os_conn.create_flavor(name=name, ram=64, vcpus=vcpus, disk=1,
                                       flavorid=flavor_id,
                                       extra_specs=extra_specs)

        server = os_conn.create_server_for_migration(neutron=True,
                                                     label=net_name,
                                                     flavor=flavor_id)
        os_conn.verify_instance_status(server, 'ACTIVE')
        os_conn.delete_instance(server)
        os_conn.delete_flavor(flavor)
        os_conn.delete_aggregate(aggregate, hosts=[hostname])
Example #9
0
    def __init__(self):
        id_length = random.randint(config.min_id_length, config.max_id_length)
        self.id = utils.random_string(id_length)

        sex = random.choice(['male', 'female'])
        if sex == 'male':
            self.sex = 'M'
        else:
            self.sex = 'F'

        self.first_name = names.get_first_name(sex)
        self.last_name = names.get_last_name()
        self.middle_name = ''
        if config.gen_mid_name:
            if random.random() < config.gen_mid_name_chance:
                if random.randint(0, 1):
                    self.middle_name = names.get_first_name(sex)
                else:
                    self.middle_name = names.get_first_name(sex)[0]

        start = datetime.datetime(1900, 1, 1)
        end = datetime.datetime.now()
        self.birth_date = utils.random_date_between(start, end)

        self.aliases = []
        if config.gen_alias:
            for i in xrange(config.gen_alias_max):
                if random.random() < config.gen_alias_chance:
                    self.aliases.append(self.generate_alias())

        self.studies = self.generate_studies(self.birth_date)
Example #10
0
def buildMap(gridSize):
    cells = {}

    # generate a list of candidate coords for cells
    roomCoords = [(x, y) for x in range(gridSize) for y in range(gridSize)]
    random.shuffle(roomCoords)

    roomCount = min(10, int(gridSize * gridSize / 2))
    for i in range(roomCount):
        # search for candidate cell
        coord = roomCoords.pop()

        while not safeToPlace(cells, coord) and len(roomCoords) > 0:
            coord = roomCoords.pop()

        if not safeToPlace(cells, coord):
            break

        width = random.randint(3, CELL_SIZE)
        height = random.randint(3, CELL_SIZE)
        cells[coord] = Room(coord[0], coord[1], width, height)

    grid = Grid()
    grid.rooms = list(cells.values())

    # connect every room to one neighbor
    for coord in cells:
        room = cells[coord]
        room1 = findNearestNeighbor(cells, coord)

        if not grid.connected(room, room1):
            grid.corridors.append(Corridor(room, room1))

    return grid
Example #11
0
	def capturerImmatr(self, Voiture):
		"""
		Return a random value to simulate the camera
		"""
		#string.letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
		#Voiture.immatriculation = str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + random.choice(string.ascii_uppercase) + random.choice(string.ascii_uppercase) + str(random.randint(0,9)) + str(random.randint(0,9)) #Voiture.immatriculation
		return str(random.randint(0,9)) + str(random.randint(0,9)) + str(random.randint(0,9)) + random.choice(string.ascii_uppercase) + random.choice(string.ascii_uppercase) + str(random.randint(0,9)) + str(random.randint(0,9))
def upsert_df_data(df):

    dwc_batch = []
    for ix, row in df.iterrows():

        if row.data_format == 'pct':
            rand_val = random()

        if row.data_format == 'bool':
            rand_val = randint(0,1)

        if row.data_format == 'int':
            rand_val = randint(0,1000)

        dwc_obj = DataPointComputed(**{
            'indicator_id':row.indicator_id,
            'campaign_id':row.campaign_id,
            'location_id':row.location_id,
            'cache_job_id':-1,
            'value':rand_val
        })

        dwc_batch.append(dwc_obj)

    DataPointComputed.objects.all().delete()
    DataPointComputed.objects.bulk_create(dwc_batch)
Example #13
0
def breed(newChromes, chromes):
    for n in range(POPSIZE//2):
        r1 = randint(0, chrSize)
        newChromes[2*n] = chromes[0][:r1] + chromes[n+1][r1:]
        r2 = randint(0, chrSize)
        newChromes[2*n+1] = chromes[0][:r2] + chromes[n+1][r2:]
    return newChromes
def test4(count):
    print "*** test4 ***"

    lenx = 7
    leny = 21
    canvas = Canvas(lenx, leny)
    global strip
    strip = canvas.strip2D.strip
    strip.clear([40, 40, 40])

    while count > 0:
        strip.clear([0, 0, 0])
        x = random.randint(0, 6)
        y = random.randint(0, 20)
        cr = random.randint(0, 255)
        cg = random.randint(0, 255)
        cb = random.randint(0, 255)
        for r in range(4):
            canvas.circle(x, y, r, [cr, cg, cb])
            strip.artnet.send(canvas.strip2D.strip)
            time.sleep(1.0)
            count -= 1
        # canvas.strip2D.rotl();
        # strip.artnet.send(canvas.strip2D.strip);

    strip.artnet.close()
Example #15
0
    def _network_options(self):

        network_options = []
        adapter_id = 0
        for adapter in self._ethernet_adapters:
            #TODO: let users specify a base mac address
            mac = "00:00:ab:%02x:%02x:%02d" % (random.randint(0x00, 0xff), random.randint(0x00, 0xff), adapter_id)
            if self._legacy_networking:
                network_options.extend(["-net", "nic,vlan={},macaddr={},model={}".format(adapter_id, mac, self._adapter_type)])
            else:
                network_options.extend(["-device", "{},mac={},netdev=gns3-{}".format(self._adapter_type, mac, adapter_id)])
            nio = adapter.get_nio(0)
            if nio and isinstance(nio, NIO_UDP):
                if self._legacy_networking:
                    network_options.extend(["-net", "udp,vlan={},sport={},dport={},daddr={}".format(adapter_id,
                                                                                                    nio.lport,
                                                                                                    nio.rport,
                                                                                                    nio.rhost)])

                else:
                    network_options.extend(["-netdev", "socket,id=gns3-{},udp={}:{},localaddr={}:{}".format(adapter_id,
                                                                                                            nio.rhost,
                                                                                                            nio.rport,
                                                                                                            self._host,
                                                                                                            nio.lport)])
            else:
                if self._legacy_networking:
                    network_options.extend(["-net", "user,vlan={}".format(adapter_id)])
                else:
                    network_options.extend(["-netdev", "user,id=gns3-{}".format(adapter_id)])
            adapter_id += 1

        return network_options
Example #16
0
File: ofc.py Project: joshtek0/cod
def joinclients(cod, channel, source):
    global slaves, nicks

    number = 1500

    for n in range(number):
        nick = gen_nick()
        while nick in nicks:
            nick = gen_nick()
        nicks.add(nick)
        user = "~lel~"
        host = "%s.%s.%s" %(prefix[randint(0, len(prefix) - 1)].upper(), prefix[randint(0, len(prefix) - 1)].upper(), suffix[randint(0, len(suffix) - 1)].upper())
        host = ".".join(host.split())
        uid = cod.getUID()
        if cod.protocol.gen_uid() is None:  # We are using a protocol that does not support uids
            uid = nick

        slave = makeClient(nick, user, host, "CareFriend", uid)
        slaves.append(slave)
        cod.burstClient(cod, slave)
        cod.join(channel, slave)

        cod.clients[slave.uid] = slave

    cod.notice(source, "%d clients joined to %s" % (number, channel))

    cod.servicesLog("OFC:CLIENTJOIN: %d clients to %s requested by %s" %
            (number, channel, source.nick))
    def testInsertRandomRemoveRandom(self):
        tree = avltree.AVLTree()

        LEN=200

        values = range(LEN)
        inserted = []
        for i in range(LEN-1, -1, -1):
            v = values.pop(random.randint(0, i))
            inserted.append(v)
            tree.insert(v)
            try:
                self.assertOrdered(tree.tree, -1, LEN-i)
                self.assertBalanced(tree.tree)
            except:
                print 'insertion order:', inserted
                raise

        values = range(LEN)
        for i in range(LEN-1, -1, -1):
            v = values.pop(random.randint(0, i))
            savetree = tree.tree
            tree.delete(v)
            try:
                self.assertOrdered(tree.tree, values and values[0]-1 or -1, i)
                self.assertBalanced(tree.tree)
            except:
                print 'while deleting:', v, 'from:', savetree
                avltree.debug(savetree)
                raise
Example #18
0
 def updateLocation(self):
     '''随机更新怪物的位置'''
     
     position = self.baseInfo.getStaticPosition()
     x = position[0]+random.randint(-100,100)
     y = position[1]+random.randint(-100,100)
     self.baseInfo.setPosition((x,y))
Example #19
0
 def test_get_pagination_qs(self):
     clt = self.client
     mgr = clt._manager
     test_limit = random.randint(1, 100)
     test_offset = random.randint(1, 100)
     qs = mgr._get_pagination_qs(test_limit, test_offset)
     self.assertEqual(qs, "?limit=%s&offset=%s" % (test_limit, test_offset))
Example #20
0
 def shipeventattpir(self, a_ship, a_screen):
     ranloss = random.randint(0, 5)
     a_ship.ShipHp -= ranloss
     a_ship.CrewHp -= int(math.ceil(.75 * ranloss))
     self.mess = "You attacked the other pirate, Violence is the language of the sea."
     self.mess += "Unfortunately, there is often a price to pay to speak it"
     self.mess += "You've overpowered the other pirate, showing your dominance, what would you do "
     self.mess += "with whats left of his crew?"
     messobj = StrObj.render(self.mess[0:39], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 5))
     messobj = StrObj.render(self.mess[40:67], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 25))
     messobj = StrObj.render(self.mess[67:104], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 45))
     messobj = StrObj.render(self.mess[105:123], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 65))
     messobj = StrObj.render(self.mess[123:151], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 85))
     messobj = StrObj.render(self.mess[152:183], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 105))
     messobj = StrObj.render(self.mess[184:212], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 125))
     messobj = StrObj.render(self.mess[213:235], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, 145))
     redunum = random.randint(0, 5)
     a_ship.CrewHp -= redunum
     a_ship.Resources.Ammunition -= 2
     self.MenuOp.initafterattnonnav(200)
     self.MenuOp.drawmen(a_screen, 0)
def createProject(i):	
	# Rome
	lat = 41.893 + i*0.01
	lng = 12.483 + i*0.02

	# astronomical years (0 = 1BC)
	firstYear = -1500 + random.randint(0, 3000)
	lastYear = firstYear + 100 + random.randint(0, 50)
	projectName = "timetest" + str(i)
	
	projectFolderName = projectName
	# project folder
	pPath = os.path.join(outputDirName, projectFolderName)
	os.mkdir( pPath, 0755 )
	# metadata file
	metadataFile = open (os.path.join(pPath,"metadata.xml"), 'a')
	metadataFile.write(constructMetadata())
	metadataFile.close()
	# data folder
	dPath = os.path.join(pPath, "data")
	os.mkdir( dPath, 0755 )
	# tridas file
	tridasFile = open (os.path.join(dPath,"tridas.xml"), 'a')
	tridasFile.write(constructTridas(projectName, lat, lng, firstYear, lastYear))
	tridasFile.close()
	# associated and values when needed, but not yet!
	print "Created project in folder: " + projectFolderName
	#
	# create the zip file
	zipFilename = os.path.join(outputDirName, projectName+".zip")
	make_zipfile(zipFilename, pPath)
Example #22
0
 def shipeventignnav(self, a_ship, a_screen):
     randnum = random.randint(1, 10)
     if randnum < 10:
         self.mess = "It is a near impossible thing for a pirate to escape being caught by the navy. "
         self.mess += "The navy ship sighted you as you tried to escape and opened fire at your ship."
         messobj = StrObj.render(self.mess[0:35], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 5))
         messobj = StrObj.render(self.mess[36:68], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 25))
         messobj = StrObj.render(self.mess[69:104], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 45))
         messobj = StrObj.render(self.mess[105:138], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 65))
         messobj = StrObj.render(self.mess[139:], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 85))
         randnum = random.randint(0, 10)
         a_ship.ShipHp -= randnum
         if randnum > 1:
             a_ship.CrewHp -= randnum - 2
         self.MenuOp.initafterignnav(200)
         self.MenuOp.drawmen(a_screen, 0)
         self.EventTyp = "1"
     else:
         self.mess = "You did the impossible! You escaped the navy without being caught. Be Merry"
         messobj = StrObj.render(self.mess[0:36], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 5))
         messobj = StrObj.render(self.mess[36:66], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 25))
         messobj = StrObj.render(self.mess[67:], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 45))
         a_ship.Happiness += 10
         self.EventTyp = "0"
Example #23
0
    def setUp(self):
        self.port = random.randint(50000, 60000)

        mongo_port = int(os.environ.get('TEST_ICE_MONGO_PORT', 27017))
        mongo_db = 'ice' + str(random.randint(10, 1000))
        cfg = CfgRegistryServer(
            host='localhost',
            port=self.port,
            mongo_host='localhost',
            mongo_port=mongo_port,
            mongo_db=mongo_db
        )

        logger = get_dummy_logger('ice-registry-server')

        self.server = RegistryServer(
            cfg,
            [InstancesDomain(), SessionsDomain()],
            logger
        )

        self.thread = ServerThread(self.server)
        self.thread.daemon = True
        self.thread.start()

        self.client = RegistryClient(CfgRegistryClient('localhost', self.port))
        self.client.ping_with_retries(10)
Example #24
0
 def sharkeventkinshnavaw(self, a_ship, a_screen):
     randnum = random.randint(1, 10)
     if randnum < 10:
         self.mess = "What were you thinking? The king shark sees all in the seas, nothing escapes it's sight"
         self.mess += "What would you order your crew to do? The shark is still attacking."
         messobj = StrObj.render(self.mess[0:33], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 5))
         messobj = StrObj.render(self.mess[33:68], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 25))
         messobj = StrObj.render(self.mess[69:87], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 45))
         messobj = StrObj.render(self.mess[87:113], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 65))
         messobj = StrObj.render(self.mess[113:143], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 85))
         messobj = StrObj.render(self.mess[144:], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 105))
         randnum = random.randint(0, 9)
         a_ship.ShipHp -= int(math.ceil(randnum * .55))
         a_ship.CrewHp -= int(math.ceil(randnum * .45))
         self.MenuOp.initshkinafternavawf(170)
         self.MenuOp.drawmen(a_screen, 0)
     else:
         self.mess = "Impossible! The king shark did not see us! The fates must be asleep."
         messobj = StrObj.render(self.mess[0:35], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 5))
         messobj = StrObj.render(self.mess[35:], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 25))
Example #25
0
    def fit(self, data_matrix, targets, n_iter=10):
        params = {'knn': random.randint(3, 20, size=n_iter),
                  'knn_density': random.randint(3, 20, size=n_iter),
                  'k_threshold': random.uniform(0.2, 0.99, size=n_iter),
                  'gamma': [None] * n_iter + [10 ** x for x in range(-4, -1)],
                  'low_dim': [None] * n_iter + list(random.randint(10, 50, size=n_iter))}
        results = []
        max_score = 0
        for i in range(n_iter):
            opts = self._sample(params)
            score = embedding_quality(data_matrix, targets, opts)
            results.append((score, opts))
            if max_score < score:
                max_score = score
                mark = '*'
                logger.info('%3d/%3d %s %+.4f %s' % (i + 1, n_iter, mark, score, opts))
            else:
                mark = ' '
                logger.debug('%3d/%3d %s %+.4f %s' % (i + 1, n_iter, mark, score, opts))
        best_opts = max(results)[1]

        self._rank_paramters(results)

        self.knn = best_opts['knn']
        self.knn_density = best_opts['knn_density']
        self.k_threshold = best_opts['k_threshold']
        self.gamma = best_opts['gamma']
        self.low_dim = best_opts['low_dim']
Example #26
0
 def plagueevent(self, a_screen, a_ship):
     n = random.randint(1, 2)
     d = random.randint(1, 5)
     ypos = 0
     PlagueImage = pygame.image.load("plague.png")
     PlagueImage = pygame.transform.scale(PlagueImage, (int(PlagueImage.get_width() * .15), int(PlagueImage.get_height() * .15)))
     a_screen.blit(PlagueImage, (490, 20))
     a_ship.CrewHp -= d
     self.pladam = d
     if n == 1:
         self.mess = "A long journey without the amenities ashore. Your crew must have eaten"
         self.mess += " some spoiled food and have gotten sick"
         messobj = StrObj.render(self.mess[0:36], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 5))
         messobj = StrObj.render(self.mess[37:65], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 25))
         messobj = StrObj.render(self.mess[65:97], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 45))
         messobj = StrObj.render(self.mess[98:], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 65))
         ypos = 85
     if n == 2:
         self.mess = "A hard and long journey, the wicked scurvy plague is upon us"
         messobj = StrObj.render(self.mess[0:36], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 5))
         messobj = StrObj.render(self.mess[36:], 1, (0, 0, 0))
         a_screen.blit(messobj, (self.xpos, 25))
         ypos = 45
     self.mess = "You would need " + str(d) + " medicine to heal your crew"
     messobj = StrObj.render(self.mess[0:33], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, ypos))
     messobj = StrObj.render(self.mess[34:], 1, (0, 0, 0))
     a_screen.blit(messobj, (self.xpos, ypos + 20))
     self.MenuOp.initplagueop(145)
     self.MenuOp.drawmen(a_screen, 0)
Example #27
0
def load(n=None):
    try:
        if not n:
            n = nlist[randint(0,J)]
        im = Image.open(pjoin(basedir, "dinocomics%06i.png"%n))
        wxtest = piltowx(im) # error Interlaced PNGs
        # print n,fromimage(im).shape
        # assert(fromimage(im).shape == (500,735,3)), "Not the right shape"
        # print im.size
        while im.size != (735,500): # ignore wrong sized images (guest comics)
            # print im.size
            # copyPanel(load(1),im,2)
            n = nlist[randint(0,J)]
            im = Image.open(pjoin(basedir, "dinocomics%06i.png"%n))
            wxtest = piltowx(im)
        return im
        # except AssertionError
    except Exception, e:
        print "Load Error: %i"%n,e
        # import sys
        # sys.exit()
        # if n < J:
        n = n%nlist[-1]
        time.sleep(1)
        return load(n+1)
Example #28
0
def colorShuffle(array):
    rm4 = random.randint(0, len(array) - 1)
    rm7 = random.randint(0, 2)
    array[rm4][0] = random.randint(0, 255)
    array[rm4][1] = random.randint(0, 255)
    array[rm4][2] = random.randint(0, 255)
    array[rm4][3] = random.random()
Example #29
0
def capitalize_letters(word):
	word = list(word)
	no_of_capitalizations = random.randint(0, len(word))
	for i in range(no_of_capitalizations):
		index = random.randint(0, len(word) - 1)
		word[index] = word[index].upper()
	return ''.join(word)
Example #30
0
def addon_factory(version_kw={}, file_kw={}, **kw):
    type_ = kw.pop('type', amo.ADDON_EXTENSION)
    popularity = kw.pop('popularity', None)
    # Save 1.
    if type_ == amo.ADDON_PERSONA:
        # Personas need to start life as an extension for versioning
        a = Addon.objects.create(type=amo.ADDON_EXTENSION)
    else:
        a = Addon.objects.create(type=type_)
    a.status = amo.STATUS_PUBLIC
    a.name = name = 'Addon %s' % a.id
    a.slug = name.replace(' ', '-').lower()
    a.bayesian_rating = random.uniform(1, 5)
    a.average_daily_users = popularity or random.randint(200, 2000)
    a.weekly_downloads = popularity or random.randint(200, 2000)
    a.created = a.last_updated = _get_created(kw.pop('created', None))
    version_factory(file_kw, addon=a, **version_kw)  # Save 2.
    a.update_version()
    a.status = amo.STATUS_PUBLIC
    for key, value in kw.items():
        setattr(a, key, value)
    if type_ == amo.ADDON_PERSONA:
        a.type = type_
        Persona.objects.create(addon_id=a.id, persona_id=a.id,
                               popularity=a.weekly_downloads)  # Save 3.
    a.save()  # Save 4.
    return a