Exemple #1
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
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)
Exemple #3
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)
Exemple #4
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 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)
Exemple #6
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']
    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'
Exemple #8
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)
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.")
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)
Exemple #11
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)
Exemple #12
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))
Exemple #13
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 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
Exemple #15
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
Exemple #16
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()
Exemple #17
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
Exemple #18
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))
Exemple #19
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)
Exemple #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)
Exemple #21
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"
Exemple #22
0
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 = "******"
        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 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])
Exemple #24
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
Exemple #25
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))
Exemple #26
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 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)
Exemple #28
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)
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()
Exemple #30
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))
Exemple #31
0
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
Exemple #32
0
def shuffleCluster(i_bins, c_bins, tracks_map, groups,
                   difference, s_max, i, clusters_dict,
                   s_bins_max, s_bins_min, s_bins_width):

    s_bins = list(range(s_bins_min, s_bins_max+1, s_bins_width,))

    counts = np.zeros((len(i_bins)+1, len(c_bins)+1, len(s_bins)+1))

    indices = {(key1, key2, key3): []
               for key1 in np.digitize(i_bins, i_bins)
               for key2 in np.digitize(c_bins, c_bins)
               for key3 in np.digitize(s_bins, s_bins)}

    for iteration in range(0,  i):
        E.info("performing shuffling iteration number %i.." % (iteration + 1))
        for size in s_bins:
            group1_mean = []
            group2_mean = []
            g1_rand_s = []
            g2_rand_s = []
            g1_rand = np.random.permutation(list(clusters_dict.keys()))
            g2_rand = np.random.permutation(list(clusters_dict.keys()))
            for perm in range(0, len(g1_rand)):
                cluster1 = clusters_dict[g1_rand[perm]].ix[
                    :, tracks_map[groups[0]]]
                cluster2 = clusters_dict[g2_rand[perm]].ix[
                    :, tracks_map[groups[1]]]

                c1_rand_s = random.randint(
                    min(cluster1.index), max(cluster1.index)-size)
                c1_e = int(c1_rand_s + size)
                c2_rand_s = random.randint(
                    min(cluster2.index), max(cluster2.index)-size)
                c2_e = int(c2_rand_s + size)

                c1_mean = np.mean(np.mean(cluster1.ix[c1_rand_s: c1_e]))
                c2_mean = np.mean(np.mean(cluster2.ix[c2_rand_s: c2_e]))
                group1_mean.append(c1_mean)
                group2_mean.append(c2_mean)
                g1_rand_s.append(c1_rand_s)
                g2_rand_s.append(c2_rand_s)

            change_idx, initial_idx,  = means2idxarrays(
                group1_mean, group2_mean, i_bins,
                c_bins,  difference)
            size_idx = np.digitize([size]*len(initial_idx), s_bins)
            for idx, coord in enumerate(zip(
                    initial_idx, change_idx, size_idx)):
                if counts[coord] < s_max:
                    counts[coord] += 1
                    cluster1_ix = clusters_dict[g1_rand[idx]].index.values
                    cluster1_start = cluster1_ix[0]
                    cluster1_end = cluster1_ix[-1]
                    cluster2_ix = clusters_dict[g2_rand[idx]].index.values
                    cluster2_start = cluster2_ix[0]
                    cluster2_end = cluster2_ix[-1]
                    c1_rand_s = g1_rand_s[idx]
                    c1_rand_e = int(c1_rand_s + size)
                    c2_rand_s = g2_rand_s[idx]
                    c2_rand_e = int(c2_rand_s + size)
                    indices[coord].append((
                        cluster1_start, cluster1_end, cluster2_start,
                        cluster2_end, c1_rand_s, c1_rand_e, c2_rand_s,
                        c2_rand_e))
    return indices, counts
Exemple #33
0
import random as r
ans = r.randint(1, 99)
min = 0
max = 100
count = 7

while count > 0:
    guess = int(input('(%d次)請輸入數字 %d ~ %d :' % (count, min, max)))
    count -= 1
    if guess <= min or guess >= max:
        print('請重新輸入')
        continue
    if guess == ans:
        print('恭喜')
        break
    elif guess < ans:
        min = guess
    else:
        max = guess
Exemple #34
0
        quickSort(a, l, i - 1)
        quickSort(a, i + 1, r)


def checkSort(a, n):
    isSorted = True
    for i in range(1, n):
        if (a[i] > a[i + 1]):
            isSorted = False
        if (not isSorted):
            break
    if isSorted:
        print('정렬 완료')
    else:
        print('정렬 오류 발생')


import random, time

N = 100000
M = 15
a = []
a.append(-1)
for i in range(N):
    a.append(random.randint(1, N))
start_time = time.time()
quickSort(a, 1, N)
end_time = time.time() - start_time
print('퀵 정렬의 실행 시간 (N = %d) : %0.3f' % (N, end_time))
checkSort(a, N)
Exemple #35
0
import random

import requests

METADATA_EXCHANGE = 1 << 20

PEER_ID = b"-MD100A-" + bytes([random.randint(0, 255) for _ in range(12)])

MAX_PACKET_SIZE = 2 ** 15

EXTENDED_ID_METADATA = 1

DEFAULT_TRACKERS = [
    "udp://tracker.coppersurfer.tk:6969/announce",
    "udp://tracker.leechers-paradise.org:6969/announce",
    "udp://tracker.opentrackr.org:1337/announce",
    "udp://p4p.arenabg.com:1337/announce",
    "udp://9.rarbg.to:2710/announce",
    "udp://9.rarbg.me:2710/announce",
    "udp://tracker.pomf.se:80/announce",
    "udp://tracker.openbittorrent.com:80/announce",
    "udp://exodus.desync.com:6969/announce",
    "udp://tracker.tiny-vps.com:6969/announce",
    "udp://tracker.moeking.me:6969/announce",
    "udp://retracker.lanta-net.ru:2710/announce",
    "udp://open.stealth.si:80/announce",
    "udp://denis.stalker.upeer.me:6969/announce",
    "udp://tracker.torrent.eu.org:451/announce",
    "udp://tracker.cyberia.is:6969/announce",
    "udp://open.demonii.si:1337/announce",
    "udp://ipv4.tracker.harry.lu:80/announce",
f.readline()
f.readline()

linhas = f.readlines()
f.close()

categorias=['restaurante', 'cinema', 'balada', 'motel']
MAX = len(categorias) - 1

saida = open("insere_servicos.sql","w")

saida.write("USE GetLove;\n")

for i in linhas:
    id_empresa = int(i.split(',')[0].split("'")[1])
    num_servico = int(i.split(',')[1].split("'")[1])
    categoria = categorias[random.randint(0, MAX)]

    arquivo = 'folder_serv_{}_{}.pdf'.format(id_empresa, num_servico)
    latitude = random.uniform(-90,90)
    longitude = random.uniform(-180,180)

    preco = random.uniform(0,2500)

    sql = "INSERT INTO Servico VALUES({},{},{},'{}','{}',{},{});\n".format(id_empresa, num_servico, preco, categoria, arquivo, latitude, longitude)

    saida.write(sql)

saida.close()
Exemple #37
0
 def setUp(self):
     self.realm = None
     self.realm_name = gen_string('alpha', random.randint(1, 30))
Exemple #38
0
def rndChar():
    return chr(random.randint(65, 90))
def ply_down_sampling(pImg, gImg, plyData, gridSize, methodFlag=SEL_MAX):
    
    # no down-sampling in this case
    if gridSize == 0:
        return plyData.data
    
    # get relationship between ply files and png files, that means each point in the ply file 
    # should have a corresponding pixel in png files, both depth png and gray png
    pHei, pWid = pImg.shape[:2]
    gHei, gWid = gImg.shape[:2]
    if pWid == gWid:
        gPix = np.array(gImg).ravel()
        gIndex = (np.where(gPix>32))
        tInd = gIndex[0]
    else:
        pPix = np.array(pImg)
        pPix = pPix[:, 2:].ravel()
        pIndex = (np.where(pPix != 0))
        
        gPix = np.array(gImg).ravel()
        gIndex = (np.where(gPix>33))
        tInd = np.intersect1d(gIndex[0], pIndex[0])
                          
    nonZeroSize = tInd.size
    
    pointSize = plyData.count
    
    # if point size do not match, return
    if nonZeroSize != pointSize:
        return
    
    # Initial data structures
    gIndexImage = np.zeros(gWid*gHei)
    
    gIndexImage[tInd] = np.arange(1,pointSize+1)
    
    gIndexImage_ = np.reshape(gIndexImage, (-1, gWid))
    
    windowSize = gridSize
    xyScale = 1
    
    relPointData = []

    # move ROI in a window size to do the meta analysis
    for i in np.arange(0+windowSize*xyScale, gWid-windowSize*xyScale, windowSize*xyScale*2):
        for j in np.arange(0+windowSize, gHei-windowSize, windowSize*2):
            if methodFlag == SEL_MAX:
                plyIndices = gIndexImage_[j-windowSize:j+windowSize+1, i-windowSize*xyScale:i+windowSize*xyScale+1]
                plyIndices = plyIndices.ravel()
                plyIndices_ = np.where(plyIndices>0)
                localIndex = plyIndices[plyIndices_[0]].astype('int64')
                localP = plyData.data[localIndex-1]
                if len(localP) == 0:
                    continue
                
                maxZ = localP[np.argmax(localP["z"])]
                relPointData.append(maxZ)
                
            if methodFlag == SEL_RAN:
                nCount = 0
                xRange = [j-windowSize, j+windowSize+1]
                yRange = [i-windowSize*xyScale, i+windowSize*xyScale+1]
                
                
                
                selInd = 0
                while nCount < 10:
                    nCount += 1
                    xInd = random.randint(xRange[0], xRange[1])
                    yInd = random.randint(yRange[0], yRange[1])
                    if gIndexImage_[xInd, yInd] != 0:
                        selInd = gIndexImage_[xInd, yInd].astype('int64')
                        break
                    
                if selInd != 0:
                    relPointData.append(plyData.data[selInd-1])
    
    relPointData = np.asarray(relPointData)
    
    return relPointData
Exemple #40
0
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
    print(items)

print('\nPrinting tuple form of zip and changing order of list')
for l1, l2 in zip(list2, list1):
    print(f"{l1} -> {l2}")

# in operator
print('\nin operator using list')

from random import shuffle
shuffle(list1)
print(list1)

from random import randint

random_number = randint(0, 100)
print(f"Random number: {random_number}")

random_number = randint(0, 100)
print(f"Random number: {random_number}")

#List Comprehension
mylist = []
print('Creating list without list comprehension:')

for num in range(1, 10):
    mylist.append(num * 100)

print(mylist)

#creating same list using list comprehension
import io
import base64
import os
import json
from InstagramAPI import InstagramAPI
import configparser
import random, time

app = flask.Flask(__name__)
#Credentials from config
configPath = os.path.join(os.path.dirname(os.path.realpath('__file__')),
                          'credentials.cfg')
parser = configparser.ConfigParser()
youtubeKey = ''
random.seed(time.time())
youtubeKeyIndex = random.randint(0, 4)
instagramEmail = ''
instagramPassword = ''
tiktokLogin = ''
tiktokPassword = ''
facebookLogin = ''
facebookPassword = ''


def getYoutubeCredentials():
    parser.read_file(open('credentials.cfg', 'r'))
    global youtubeKey
    global youtubeKeyIndex
    youtubeKeys = parser.get('Youtube', 'KEY').split()
    youtubeKey = youtubeKeys[youtubeKeyIndex]
    youtubeKeyIndex = (youtubeKeyIndex + 1) % 5
Exemple #43
0
def down_imgs(img_url, sub_dir):
    path = os.path.join(IMG_DIR, sub_dir)
    fname = os.path.join(path , hash_str(img_url) + '.jpg')
    if not os.path.exists(path):
        os.mkdir(path)
    r = requests.get(img_url)
    with open(fname,"wb+") as f:
        f.write(r.content)
        print("Success      " + hash_str(img_url) + '.jpg')

if not os.path.exists(IMG_DIR):
    os.mkdir(IMG_DIR)
db = sqlite3.connect("spider_tt8.db",check_same_thread=False)
cur = db.cursor()
cur.execute("select name, urls from xiuren")
lines = cur.fetchall()

for line in lines:
    track_name = line[0].strip()
    urls = line[1]
    for url in str(urls).split(","):
        slim_url = url.strip()
        if "http" in slim_url:
            try:
                thread_name = "t" + str(random.randint(0, 9999))
                thread = threading.Thread(target=down_imgs, args=(slim_url, track_name), name=thread_name)
                thread.start()
                time.sleep(0.1)
            except:
                pass
Exemple #44
0
def testProgmonSwitching():
    """
    Tests that all of Progmon A's stats/effects carry over to Progmon B after Progmon Switching
    """
    global myP1
    global progmonNameP1

    myP1.bag = ["healthPotion", "restorePotion"]  # UPDATE PLAYER 1'S BAG
    print(
        "\nTEST #7 (PRE-PROGMON-SWITCHING): Player 1's Progmon and Bag... UNKNOWN"
    )
    print("\tPlayer 1's Progmon =", progmonNameP1)
    print("\tPlayer 1's Health =", myP1.getCurrentHealth())
    print("\tPlayer 1's Bag =", myP1.getBag())
    print("\tPlayer 1's Stat Boost =", myP1.getStatBoost())
    print("\tPlayer 1's Defense Boost =", myP1.getDefenseBoost())

    switchControl = random.randint(1, 3)
    if switchControl == 1:  # SWITCH TO ELECTRIC CAT (OR, IF CURRENTLY ELECTRIC CAT, THEN FINAL BOSS)
        currentHP = myP1.getCurrentHealth()
        currentBag = myP1.getBag()
        currentStatBoost = myP1.getStatBoost()
        currentDefenseBoost = myP1.getDefenseBoost()
        if progmonNameP1 != "ElectricCat":
            myP1 = ElectricCat()
            progmonNameP1 = "Electric Cat"
        else:
            myP1 = FinalBoss()
            progmonNameP1 = "Final Boss"
        myP1.setBag(currentBag)
        myP1.setStatBoost(currentStatBoost)
        myP1.setDefenseBoost(currentDefenseBoost)
        if currentHP < myP1.getHP(
        ):  # IF P1 HAD LESS HEALTH THAN NEW PROGMON'S MAX (BEFORE THE SWITCH), THEN REDUCE HEALTH
            myP1.setCurrentHealth(currentHP)
        print("\tPlayer 1 switched to {}".format(progmonNameP1))
    elif switchControl == 2:  # SWITCH TO FIRE DRAGON (OR, IF CURRENTLY FIRE DRAGON, THEN FINAL BOSS)
        currentHP = myP1.getCurrentHealth()
        currentBag = myP1.getBag()
        currentStatBoost = myP1.getStatBoost()
        currentDefenseBoost = myP1.getDefenseBoost()
        if progmonNameP1 != "Fire Dragon":
            myP1 = FireDragon()
            progmonNameP1 = "Fire Dragon"
        else:
            myP1 = FinalBoss()
            progmonNameP1 = "Final Boss"
        myP1.setBag(currentBag)
        myP1.setStatBoost(currentStatBoost)
        myP1.setDefenseBoost(currentDefenseBoost)
        if currentHP < myP1.getHP(
        ):  # IF P1 HAD LESS HEALTH THAN NEW PROGMON'S MAX (BEFORE THE SWITCH), THEN REDUCE HEALTH
            myP1.setCurrentHealth(currentHP)
        print("\tPlayer 1 switched to {}".format(progmonNameP1))
    elif switchControl == 3:  # SWITCH TO WATER TURTLE (OR, IF CURRENTLY WATER TURTLE, THEN FINAL BOSS)
        currentHP = myP1.getCurrentHealth()
        currentBag = myP1.getBag()
        currentStatBoost = myP1.getStatBoost()
        currentDefenseBoost = myP1.getDefenseBoost()
        if progmonNameP1 != "Water Turtle":
            myP1 = WaterTurtle()
            progmonNameP1 = "Water Turtle"
        else:
            myP1 = FinalBoss()
            progmonNameP1 = "Final Boss"
        myP1.setBag(currentBag)
        myP1.setStatBoost(currentStatBoost)
        myP1.setDefenseBoost(currentDefenseBoost)
        if currentHP < myP1.getHP(
        ):  # IF P1 HAD LESS HEALTH THAN NEW PROGMON'S MAX (BEFORE THE SWITCH), THEN REDUCE HEALTH
            myP1.setCurrentHealth(currentHP)
        print("\tPlayer 1 switched to {}".format(progmonNameP1))

    print(
        "\nTEST #7 (POST-PROGMON-SWITCHING): Player 1's Progmon and Bag... PASSED"
    )
    print("\tPlayer 1's Progmon =", progmonNameP1)
    print("\tPlayer 1's Health =", myP1.getCurrentHealth())
    print("\tPlayer 1's Bag =", myP1.getBag())
    print("\tPlayer 1's Stat Boost =", myP1.getStatBoost())
    print("\tPlayer 1's Defense Boost =", myP1.getDefenseBoost())
Exemple #45
0
def main():

    global SCREEN, FPSCLOCK

    pygame.init()

    FPSCLOCK = pygame.time.Clock()

    # Fullscreen scaled output

    SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT),
                                     pygame.SCALED | pygame.FULLSCREEN)

    pygame.display.set_caption('Flappy Box')

    # numbers sprites for score display

    IMAGES['numbers'] = (
        pygame.image.load('assets/sprites/0.png').convert_alpha(),
        pygame.image.load('assets/sprites/1.png').convert_alpha(),
        pygame.image.load('assets/sprites/2.png').convert_alpha(),
        pygame.image.load('assets/sprites/3.png').convert_alpha(),
        pygame.image.load('assets/sprites/4.png').convert_alpha(),
        pygame.image.load('assets/sprites/5.png').convert_alpha(),
        pygame.image.load('assets/sprites/6.png').convert_alpha(),
        pygame.image.load('assets/sprites/7.png').convert_alpha(),
        pygame.image.load('assets/sprites/8.png').convert_alpha(),
        pygame.image.load('assets/sprites/9.png').convert_alpha())

    # game over sprite

    IMAGES['gameover'] = pygame.image.load(
        'assets/sprites/gameover.png').convert_alpha()

    # message sprite for welcome screen

    IMAGES['message'] = pygame.image.load(
        'assets/sprites/message.png').convert_alpha()

    # base (ground) sprite

    IMAGES['base'] = pygame.image.load(
        'assets/sprites/base.png').convert_alpha()

    # sounds

    soundExt = '.ogg'

    SOUNDS['die'] = pygame.mixer.Sound('assets/audio/die' + soundExt)

    SOUNDS['hit'] = pygame.mixer.Sound('assets/audio/hit' + soundExt)

    SOUNDS['point'] = pygame.mixer.Sound('assets/audio/point' + soundExt)

    SOUNDS['wing'] = pygame.mixer.Sound('assets/audio/wing' + soundExt)

    while True:

        # select random background sprites

        randBg = random.randint(0, len(BACKGROUNDS_LIST) - 1)

        IMAGES['background'] = pygame.image.load(
            BACKGROUNDS_LIST[randBg]).convert()

        # select random player sprites

        randPlayer = random.randint(0, len(PLAYERS_LIST) - 1)

        IMAGES['player'] = (
            pygame.image.load(PLAYERS_LIST[randPlayer][0]).convert_alpha(),
            pygame.image.load(PLAYERS_LIST[randPlayer][1]).convert_alpha(),
            pygame.image.load(PLAYERS_LIST[randPlayer][2]).convert_alpha(),
        )

        # select random pipe sprites

        pipeindex = random.randint(0, len(PIPES_LIST) - 1)

        IMAGES['pipe'] = (
            pygame.transform.flip(
                pygame.image.load(PIPES_LIST[pipeindex]).convert_alpha(),
                False, True),
            pygame.image.load(PIPES_LIST[pipeindex]).convert_alpha(),
        )

        # hismask for pipes

        HITMASKS['pipe'] = (
            getHitmask(IMAGES['pipe'][0]),
            getHitmask(IMAGES['pipe'][1]),
        )

        # hitmask for player

        HITMASKS['player'] = (
            getHitmask(IMAGES['player'][0]),
            getHitmask(IMAGES['player'][1]),
            getHitmask(IMAGES['player'][2]),
        )

        movementInfo = showWelcomeAnimation()

        crashInfo = mainGame(movementInfo)

        showGameOverScreen(crashInfo)
Exemple #46
0
 def rand(self):
     # Generate a random number which will return a movie of the dataframe
     self.rand_num = randint(0, len(self.movies))
     # Check if the movie have already been selected.
     self.check_film()
Exemple #47
0
	def setupAreas(self, mode, target_classes=None):
		"""
		mode:

			"UNIFORM (VERTICAL)    : the map is subdivided vertically (70 / 15 / 15)
			"UNIFORM (HORIZONTAL)  : the map is subdivided horizontally (70 / 15 / 15)
			"RANDOM"               : the map is subdivided randomly into three non-overlapping part
			"BIOLOGICALLY-INSPIRED": the map is subdivided according to the spatial distribution of the classes
		"""

		# size of the each area is 15% of the entire map
		map_w = self.ortho_image.width()
		map_h = self.ortho_image.height()

		val_area = [0, 0, 0, 0]
		test_area = [0, 0, 0, 0]
		# the train area is represented by the entire map minus the validation and test areas

		if mode == "UNIFORM (VERTICAL)":

			delta = int(self.crop_size / 2)
			ww_val = map_w - delta*2
			hh_val = (map_h - delta*2) * 0.15 - delta
			ww_test = ww_val
			hh_test = (map_h - delta*2) * 0.15 - delta
			val_area = [delta + (map_h - delta * 2) * 0.7, delta, ww_val, hh_val]
			test_area = [2*delta + (map_h - delta*2) * 0.85, delta, ww_test, hh_test]

		elif mode == "UNIFORM (HORIZONTAL)":

			delta = int(self.crop_size / 2)
			ww_val = (map_w - delta*2) * 0.15 - delta
			hh_val = map_h - delta*2
			ww_test = (map_w - delta*2) * 0.15 - delta
			hh_test = hh_val
			val_area = [delta, delta + (map_w - delta*2) * 0.7, ww_val, hh_val]
			test_area = [delta, 2* delta + (map_w - delta*2) * 0.85, ww_test, hh_test]

		elif mode == "RANDOM":

			area_w = int(math.sqrt(0.15) * map_w)
			area_h = int(math.sqrt(0.15) * map_h)

			for j in range(1000):
				px1 = rnd.randint(0, map_w - area_w - 1)
				py1 = rnd.randint(0, map_h - area_h - 1)
				px2 = rnd.randint(0, map_w - area_w - 1)
				py2 = rnd.randint(0, map_h - area_h - 1)

				area1 = [px1, py1, area_w, area_h]
				area2 = [px2, py2, area_w, area_h]

				intersection = self.bbox_intersection(area1, area2)

				if intersection < 1.0:
					val_area = area1
					test_area = area2

		elif mode == "BIOLOGICALLY-INSPIRED":

			val_area, test_area = self.findAreas(target_classes=target_classes)

			print(val_area)
			print(test_area)

		self.val_area = val_area
		self.test_area = test_area
Exemple #48
0
def fake(n):
    # for dry testing
    import time
    import random as ra
    time.sleep(ra.randint(2,9))
    print(n)
        if player_ships[4] < 5:
            hasHit = True
    return hasHit


bot_ships = [2, 3, 3, 4, 5]  #Number of units left for each of the bots ships.
player_ships = [2, 3, 3, 4,
                5]  #Number of units left for each of the players ships.
ship_names = [
    "Destroyer", "Submarine", "Cruiser", "Battleship", "Aircraft Carrier"
]  #Names for ship referencing.
#End#
#Bot Ship Placement#
i = 0
while i < 5:
    x = randint(0, 9)  #X-Location
    y = randint(0, 9)  #Y-Location
    z = randint(0, 1)  #Is Vertical?
    if z == 1:
        if y + bot_ships[i] <= 9:  #Checks if there is enough horizontal space.
            checkVerified = True
            for j in range(
                    bot_ships[i]):  #Checks if any other ships are present.
                if bot_field[y + j][x] != 0:
                    checkVerified = False
            if checkVerified == True:  #Places current ship and increments i only if all previous checks were successful.
                for j in range(bot_ships[i]):
                    bot_field[y + j][x] = i + 1
                i += 1
    if z == 0:
        if x + bot_ships[i] <= 9:  #Checks if there is enough vertical space.
Exemple #50
0
def create_output_image_location():
    img_file = get_temp_directory() + '/image' + str(random.randint(100000,200000)) + '.jpg'
    return img_file
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)
        if source is None:
            raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))

        pointCount = self.parameterAsDouble(parameters, self.POINTS_NUMBER, context)
        minDistance = self.parameterAsDouble(parameters, self.MIN_DISTANCE, context)

        fields = QgsFields()
        fields.append(QgsField('id', QVariant.Int, '', 10, 0))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               fields, QgsWkbTypes.Point, source.sourceCrs())
        if sink is None:
            raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))

        nPoints = 0
        nIterations = 0
        maxIterations = pointCount * 200
        featureCount = source.featureCount()
        total = 100.0 / pointCount if pointCount else 1

        index = QgsSpatialIndex()
        points = dict()

        da = QgsDistanceArea()
        da.setSourceCrs(source.sourceCrs(), context.transformContext())
        da.setEllipsoid(context.project().ellipsoid())

        request = QgsFeatureRequest()

        random.seed()

        while nIterations < maxIterations and nPoints < pointCount:
            if feedback.isCanceled():
                break

            # pick random feature
            fid = random.randint(0, featureCount - 1)
            f = next(source.getFeatures(request.setFilterFid(fid).setSubsetOfAttributes([])))
            fGeom = f.geometry()

            if fGeom.isMultipart():
                lines = fGeom.asMultiPolyline()
                # pick random line
                lineId = random.randint(0, len(lines) - 1)
                vertices = lines[lineId]
            else:
                vertices = fGeom.asPolyline()

            # pick random segment
            if len(vertices) == 2:
                vid = 0
            else:
                vid = random.randint(0, len(vertices) - 2)
            startPoint = vertices[vid]
            endPoint = vertices[vid + 1]
            length = da.measureLine(startPoint, endPoint)
            dist = length * random.random()

            if dist > minDistance:
                d = dist / (length - dist)
                rx = (startPoint.x() + d * endPoint.x()) / (1 + d)
                ry = (startPoint.y() + d * endPoint.y()) / (1 + d)

                # generate random point
                p = QgsPointXY(rx, ry)
                geom = QgsGeometry.fromPointXY(p)
                if vector.checkMinDistance(p, index, minDistance, points):
                    f = QgsFeature(nPoints)
                    f.initAttributes(1)
                    f.setFields(fields)
                    f.setAttribute('id', nPoints)
                    f.setGeometry(geom)
                    sink.addFeature(f, QgsFeatureSink.FastInsert)
                    index.addFeature(f)
                    points[nPoints] = p
                    nPoints += 1
                    feedback.setProgress(int(nPoints * total))
            nIterations += 1

        if nPoints < pointCount:
            feedback.pushInfo(self.tr('Could not generate requested number of random points. '
                                      'Maximum number of attempts exceeded.'))

        return {self.OUTPUT: dest_id}
Exemple #52
0
	def findAreas(self, target_classes):
		"""
		Find the validation and test areas with landscape metrics similar to the ones of the entire map.
		"""

		area_info = []

		map_w = self.ortho_image.width()
		map_h = self.ortho_image.height()

		area_w = int(math.sqrt(0.15) * map_w)
		area_h = int(math.sqrt(0.15) * map_h)

		landscape_number, landscape_coverage, landscape_PSCV = self.calculateMetrics([0, 0, map_w, map_h], target_classes)

		# calculate normalization factor
		numbers = []
		coverages = []
		PSCVs = []
		sn = []
		sc = []
		sP = []
		for i in range(5000):

			aspect_ratio_factor = factor = rnd.uniform(0.4, 2.5)
			w = int(area_w / aspect_ratio_factor)
			h = int(area_h * aspect_ratio_factor)
			px = rnd.randint(0, map_w - w - 1)
			py = rnd.randint(0, map_h - h - 1)

			area_bbox = [py, px, w, h]
			area_number, area_coverage, area_PSCV = self.calculateMetrics(area_bbox, target_classes)
			s1, s2, s3 = self.rangeScore(area_number, area_coverage, area_PSCV, landscape_number, landscape_coverage, landscape_PSCV)

			numbers.append(area_number)
			coverages.append(area_coverage)
			PSCVs.append(area_PSCV)

			sn.append(s1)
			sc.append(s2)
			sP.append(s3)

		sn = np.array(sn)
		sc = np.array(sc)
		sP = np.array(sP)
		self.sn_min = np.min(sn, axis=0)
		self.sn_max = np.max(sn, axis=0)
		self.sc_min = np.min(sc, axis=0)
		self.sc_max = np.max(sc, axis=0)
		self.sP_min = np.min(sP, axis=0)
		self.sP_max = np.max(sP, axis=0)

		for i in range(10000):

			aspect_ratio_factor = factor = rnd.uniform(0.4, 2.5)
			w = int(area_w / aspect_ratio_factor)
			h = int(area_h * aspect_ratio_factor)

			px = rnd.randint(0, map_w - w - 1)
			py = rnd.randint(0, map_h - h - 1)

			area_bbox = [py, px, w, h]

			area_number, area_coverage, area_PSCV = self.calculateMetrics(area_bbox, target_classes)
			scores = self.calculateNormalizedScore(area_number, area_coverage, area_PSCV, landscape_number, landscape_coverage, landscape_PSCV)

			for i, score in enumerate(scores):
				if math.isnan(score):
					scores[i] = 0.0

			aggregated_score = sum(scores) / len(scores)

			area_info.append((area_bbox, scores, aggregated_score))


		area_info.sort(key=lambda x:x[2])
		val_area = area_info[0][0]

		print("*** VALIDATION AREA ***")
		area_number, area_coverage, area_PSCV = self.calculateMetrics(val_area, target_classes)
		scoresNorm = self.calculateNormalizedScore(area_number, area_coverage, area_PSCV, landscape_number,
											   landscape_coverage, landscape_PSCV)
		lc = [value * 100.0 for value in landscape_coverage]
		ac = [value * 100.0 for value in area_coverage]

		for i, score in enumerate(scoresNorm):
			if math.isnan(score):
				scoresNorm[i] = 0.0
		print(scoresNorm)
		print("Normalized score:", sum(scoresNorm) / len(scoresNorm))
		print("Number of corals per class (landscape):", landscape_number)
		print("Coverage of corals per class (landscape):", lc)
		print("PSCV per class (landscape): ", landscape_PSCV)
		print("Number of corals per class (selected area):", area_number)
		print("Coverage of corals per class (selected area):", ac)
		print("PSCV of corals per class (selected area):", area_PSCV)

		for i in range(len(area_info)):
			intersection = self.bbox_intersection(val_area, area_info[i][0])
			if intersection < 10.0:
				test_area = area_info[i][0]
				break

		print("*** TEST AREA ***")
		area_number, area_coverage, area_PSCV = self.calculateMetrics(test_area, target_classes)
		scoresNorm = self.calculateNormalizedScore(area_number, area_coverage, area_PSCV, landscape_number,
											   landscape_coverage, landscape_PSCV)
		lc = [value * 100.0 for value in landscape_coverage]
		ac = [value * 100.0 for value in area_coverage]

		for i, score in enumerate(scoresNorm):
			if math.isnan(score):
				scoresNorm[i] = 0.0
		print(scoresNorm)
		print("Normalized score:", sum(scoresNorm) / len(scoresNorm))
		print("Number of corals per class (landscape):", landscape_number)
		print("Coverage of corals per class (landscape):", lc)
		print("PSCV per class (landscape): ", landscape_PSCV)
		print("Number of corals per class (selected area):", area_number)
		print("Coverage of corals per class (selected area):", ac)
		print("PSCV of corals per class (selected area):", area_PSCV)

		return val_area, test_area
Exemple #53
0
def runRMHC(C, D):
    best1 = C
    best2 = D
    dis = np.array([])
    evals = np.array([])
    bestpointsx = np.array([])
    bestpointsy = np.array([])
    # bestdiss = np.array([])
    min_distance = distance(C, D)
    dis = np.append(dis, min_distance)
    evals = np.append(evals, 1)

    for z in range(0, 999999):
        evals = np.append(evals, z + 2)
        best1 = np.array(C)
        best2 = np.array(D)

        min_distance = distance(C, D)

        index1 = random.randint(0, len(C) - 1)
        index2 = random.randint(0, len(C) - 1)
        best1[index1], best1[index2] = best1[index2], best1[index1]
        best2[index1], best2[index2] = best2[index2], best2[index1]

        new_min_distance = distance(best1, best2)
        dis = np.append(dis, new_min_distance)

        # minimum_distance = min(dis)
        if new_min_distance > min_distance:
            #dis2 = np.append(dis2, new_min_distance)
            min_distance = new_min_distance
            C = np.array(best1)
            D = np.array(best2)
            bestpointsx = np.append(bestpointsx, best1)
            bestpointsy = np.append(bestpointsy, best2)
            # bestdiss = np.append(bestdiss, distance(bestpointsx,bestpointsy))
        # print (z)

    bestx = C
    besty = D
    # print (len(evals))
    # print (len(dis))
    # print (min(dis))

    csvfile = open("hc1l_run2.txt", "a")
    for tick in range(len(evals)):
        csvfile.write(str(evals[tick]) + ',')
        csvfile.write(str(dis[tick]) + '\n')
    csvfile.close()

    csvfile1 = open("hc1l_bestpointsrun2.txt", "a")
    for t in range(len(bestpointsx)):
        csvfile1.write(str(bestpointsx[t]) + ',')
        csvfile1.write(str(bestpointsy[t]) + '\n')
    csvfile.close()

    # csvfile2 = open("hc1s_bestdistancerun1.txt", "a")
    # for ti in range(len(bestdiss)):
    #     csvfile2.write(str(bestdiss[ti]) + '\n')
    # csvfile.close()

    csvfile3 = open("hc1l_bestpathrun2.txt", "a")
    for tic in range(len(bestx)):
        csvfile3.write(str(bestx[tic]) + ',')
        csvfile3.write(str(besty[tic]) + '\n')
    csvfile.close()
Exemple #54
0
def PlacerAleat(P, N):
    coord_vides = Coord_cases_vides(N, P)
    coord_alea_vide = coord_vides[r.randint(0, len(coord_vides) - 1)]
    x = coord_alea_vide[0]
    y = coord_alea_vide[1]
    P[x][y] = -1
Exemple #55
0
def commandLoop(inventoryNames, roomContents, roomCounter, contents, rList, equippedWeapon):

    while True:
        response = str(input(""))
        response = response.lower()
        response = response.strip()
        responseTrue = response.rstrip()
        repsonseList = responseTrue.split(" ")
        if repsonseList[0] == "help":
            commands = open("commands.txt", "r")
            printLine()
            for line in commands:
                data = line.split(":")
                print(data[0] + " - " + data[1], end="")
            print("")
            printLine()
        elif repsonseList[0] == "exit":
            exit()
        elif repsonseList[0] == "break":
            printLine()
            print("You started breaking the pots\n")
            i = 0
            while i < contents[3]:
                gennedNum = random.randint(0, 100)
                print("You broke a pot.")
                if gennedNum <= 20:
                    itemAddedInventory("potion", "potion")
                else:
                    print("You got nothing.\n")
                contents[3] = contents[3] - 1
            printLine()
        elif repsonseList[0] == "open":
            if repsonseList[1] == "door":
                roomNum = int(repsonseList[2])
                if roomNum == roomCounter - 1 or roomNum == roomCounter + 1:
                    roomCounter = roomNum
                    enterRoom(roomCounter, roomList)
                else:
                    printLine()
                    print("Sorry that isn't possible.")
                    printLine()
                #returns room counter and puts player in the room equal to counter
            elif repsonseList[1] == "chest":
                if contents[2] == True:
                    createWeapon()
                    contents[2] = False
                else: 
                    print("There is no chest in this room.")
                #change chest present from true to false
        elif repsonseList[0] == "look":
            printLine()
            print("You are in room " + str(roomCounter) + ".")
            i = 0
            boolin = True
            while boolin == True:
                if i < 3:
                    while i < 3:
                        if i == 0 and contents[i] is True:
                            print("You look to see a hulking monster, larger than the average.  You realise that it is a boss.")
                            #print(boss monster type + " Boss")
                            printLine()
                            boolin = False
                            break
                        elif i == 1 and contents[i] is True:
                            #print("There is a " + monsterGennedType)
                            print("A monster is in this room")
                            if roomCounter - 1 == 0:
                                print("There is one door, labelled " + str(roomCounter + 1))
                            else:
                                print("There are two doors, labelled " + str(roomCounter - 1) + " and " + str(roomCounter + 1))
                            boolin = False
                            if contents[3] == 1:
                                print("There is also " + str(contents[3]) + " pot.")
                                printLine()
                                break
                            elif contents[3] != 0:
                                print("There are also " + str(contents[3]) + " pots.")
                                printLine()
                                break
                            else:
                                break
                            break
                        elif i == 2 and contents[i] is True:
                            print("There is a chest in the room.")
                            if roomCounter - 1 == 0:
                                print("There is one door, labelled " + str(roomCounter + 1))
                            else:
                                print("There are two doors, labelled " + str(roomCounter - 1) + " and " + str(
                                    roomCounter + 1))
                            boolin = False
                            if contents[3] == 1:
                                print("There is also " + str(contents[3]) + " pot.")
                                printLine()
                                break
                            elif contents[3] != 0:
                                print("There are also " + str(contents[3]) + " pots.")
                                printLine()
                                break
                            else:
                                break
                            break
                        else:
                            i = i + 1
                else:
                    print("You see nothing of interest in the room.")
                    if roomCounter - 1 == 0:
                        print("There is one door, labelled " + str(roomCounter + 1))
                    else:
                        print("There are two doors, labelled " + str(roomCounter - 1) + " and " + str(roomCounter + 1))
                    if contents[3] == 1:
                        print("There is also " + str(contents[3]) + " pot.")
                        printLine()
                        break
                    elif contents[3] != 0:
                        print("There are also " + str(contents[3]) + " pots.")
                        printLine()
                        break
                    else:
                        break
                    break

        elif repsonseList[0] == "inventory":
            printLine()
            for i in range(len(inventoryNames)):
                print(inventoryNames[i] + " | ", end="")
            print("")
            printLine()

        else:
            printLine()
            print("Sorry. I don't understand what you said.")
            printLine()
Exemple #56
0
def gen_string(length):
    return "".join([chr(random.randint(1, 255)) for i in range(length)])
Exemple #57
0
def random_color():
    r = lambda: random.randint(0, 255)
    return '#%02X%02X%02X' % (r(), r(), r())
Exemple #58
0
def createRoom(isBoss, hasMonster, hasChest, roomList):
    potAmount = random.randint(0, 5)
    roomGenned = room(isBoss, hasMonster, hasChest, potAmount)
    roomContents = [roomGenned.listRoomBoss(isBoss), roomGenned.listRoomMonster(hasMonster), roomGenned.listRoomChest(hasChest), potAmount]
    roomList.append(roomGenned)
    return roomContents, roomList
# -*- coding: utf-8 -*-
# @Time    : 2017/10/14 16:08
# @Author  : Sean
# @File    : 3_6_StudentScore.py

from random import randint
from itertools import chain

chinese = [randint(60, 100) for _ in range(40)]
math = [randint(60, 100) for _ in range(40)]
english = [randint(60, 100) for _ in range(40)]

##############################
# solution 1
##############################
total = []
for i in range(len(math)):
    total.append(chinese[i] + math[i] + english[i])

print(total)
##############################
# solution 2
##############################
total = []
for c, m, e in zip(chinese, math, english):
    total.append(c + m + e)
print(total)

#chain of itertools
e1 = [randint(60, 100) for _ in range(42)]
e2 = [randint(60, 100) for _ in range(44)]
Exemple #60
0
import requests, os, urllib.request, json, random, time
os.system("clear")                                                          ban = random.randint(0, 3)
if ban == 0:
    banner = """
    ░░░░░░░░▄███▄▄▄░░▄▄▄███▄░░░░░░░░
    ░░░░░░░██████████████████░░░░░░░
    ░░░░░░░████Termux-Lab████░░░░░░░                                            ░░░░░░░██████████████████░░░░░░░
    ░░░░░░░██████████████████░░░░░░░
    ██▄▄▄██▀▀▀▀██████████▀▀▀▀██▄▄▄██
    ░▀██████▄▄▄░░░░░░░░░░▄▄▄██████▀░
    ░░░▀████████████████████████▀░░░
    ░░▄█▀█▀▀▀▀████████████▀▀▀▀█▀█▄░░                                            ░░█▀░▀░░░░░▄▄░░░░░░▄▄░░░░░▀░▀█░░
    ░░█▄░░░░░░█░░█░░░░█░░█░░░░░░▄█░░
    ░░░▀██▄░░░░▀▀░░█░░░▀▀░░░░▄██▀░░░
    ░░░░░▀█▄░░░░░░░▀▀░░░░░░░▄█▀░░░░░
    ░░░░░░░██▄▄░░░████░░░▄▄██░░░░░░░
    ░░░░░▄███████▄▄▄▄▄▄███████▄░░░░░                                            ░░░░▄██████████████████████▄░░░░
    ░░░▄█████████████SᕼEᖇᒪOᑕK███▄░░░
    ░░▄██████████████████████████▄░░
    """
elif ban == 1:
    banner = """                                                                   ,_                                                                        ,'  `╲,_                                                                    |_,-'_)
     /##c '╲  (
    ' |'  -{.  )
      /╲__-' ╲[]
     /`-_`╲
     '     ╲                TEᖇᗰᑌ-᙭ᒪᗩᗷ                                         ____________________________________
   |VK: @termux_lab  | TG: @termuxlab |
   ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
"""
elif ban == 3: