当前位置: 首页>>代码示例>>Python>>正文


Python whrandom.choice函数代码示例

本文整理汇总了Python中whrandom.choice函数的典型用法代码示例。如果您正苦于以下问题:Python choice函数的具体用法?Python choice怎么用?Python choice使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了choice函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getNextPos

def getNextPos(currentPos, playground, area, avId = None):
    if avId != None:
        if estateIndexes.has_key(avId):
            unusedI = estateIndexes[avId][0][area]
            usedI = estateIndexes[avId][1][area]
        else:
            return (ButterflyPoints[playground][area][0], 0, 4.0)
    else:
        unusedI = unusedIndexes[playground][area]
        usedI = usedIndexes[playground][area]
    nextPos = currentPos
    while nextPos == currentPos:
        if len(unusedI) == 0:
            index = whrandom.choice(usedI)
            nextPos = ButterflyPoints[playground][area][index]
        else:
            index = whrandom.choice(unusedI)
            nextPos = ButterflyPoints[playground][area][index]
            if nextPos != currentPos:
                unusedI.remove(index)
                usedI.append(index)
            
    dist = Vec3(nextPos - currentPos).length()
    time = dist / BUTTERFLY_SPEED + BUTTERFLY_TAKEOFF[playground] + BUTTERFLY_LANDING[playground]
    return (nextPos, index, time)
开发者ID:Toonerz,项目名称:Toontown-2003,代码行数:25,代码来源:ButterflyGlobals.py

示例2: enter

    def enter(self, toon, shopsVisited = []):
        base.disableMouse()
        self.toon = toon
        self.dna = toon.getStyle()
        colorList = self.getGenderColorList(self.dna)
        if COLORSHOP not in shopsVisited:
            self.headChoice = whrandom.choice(colorList)
            self.armChoice = self.headChoice
            self.legChoice = self.headChoice
            self.startColor = self.headChoice
            self._ColorShop__swapHeadColor(0)
            self._ColorShop__swapArmColor(0)
            self._ColorShop__swapLegColor(0)
            self.allLButton['state'] = DISABLED
            self.headLButton['state'] = DISABLED
            self.armLButton['state'] = DISABLED
            self.legLButton['state'] = DISABLED
        else:
            
            try:
                self.headChoice = colorList.index(self.dna.headColor)
                self.armChoice = colorList.index(self.dna.armColor)
                self.legChoice = colorList.index(self.dna.legColor)
            except:
                self.headChoice = whrandom.choice(colorList)
                self.armChoice = self.headChoice
                self.legChoice = self.headChoice
                self._ColorShop__swapHeadColor(0)
                self._ColorShop__swapArmColor(0)
                self._ColorShop__swapLegColor(0)

        self.acceptOnce('last', self._ColorShop__handleBackward)
        self.acceptOnce('next', self._ColorShop__handleForward)
        return None
开发者ID:Toonerz,项目名称:Toontown-2003,代码行数:34,代码来源:ColorShop.py

示例3: testConfig

def testConfig():
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]
    loggers = ['', 'area1', 'area2']
    for i in xrange(1000):
        logger = logging.getLogger(choice(loggers))
        level = choice(levels)
        logger.log(level, "Message number %d", i)
开发者ID:D3f0,项目名称:txscada,代码行数:7,代码来源:logconfig.py

示例4: createTestCases

def createTestCases(n):
	n=int(n)
	g1 = [[0] * n for i in range(n)]
	for i in range(0,rand.choice(range(n))*rand.choice(range(n))):
    		j=rand.choice(range(n))
    		k=rand.choice(range(n))
		g1[j][k]=g1[k][j]=1
	pi_orig = get_random_isomorphism (len(g1))
	gP = get_isomorphic_graph(g1, pi_orig)
	
	g2 = get_isomorphic_graph(g1, pi_orig)
	si={};
	si["VD"]=[];
	
	for i in range(0,rand.choice(range(n))):
    		j=rand.choice(range(n))
		si["VD"].append(j)
	si["VD"] = list(set(si["VD"]))
	si["VD"].sort(reverse=False);
	for i in si["VD"]:
		g2.insert(i,[0]*len(g2))
		for elements in g2:
			elements.insert(i,0)
			
	si["ER"]=[];
	
	for i in range(0,rand.choice(range(len(g2)))*rand.choice(range(len(g2)))):
    		j=rand.choice(range(len(g2)))
    		k=rand.choice(range(len(g2)))
		if (g2[j][k]==0):
			g2[j][k]=g2[k][j]=1
			si["ER"].append([j,k])
	
        
	fname = "../data/commonInput_%d.txt"%(n)
	fp = open(fname, 'w')
	gname = "../data/proverInput_%d.txt"%(n)
	gp = open(gname, 'w')
 	fp.write("%d\n"%len(g1))
	fp.write(commit.prettyPrintMatrixSpc(g1)+"\n")
 	fp.write("%d\n"%len(g2))
	fp.write(commit.prettyPrintMatrixSpc(g2)+"\n")

	gp.write("ER ")
	for elements in si["ER"]:
		gp.write(str(elements[0])+","+str(elements[1])+" ")
	gp.write("\n")
	gp.write("VD " + " ".join(map(str,si["VD"])) + "\n")
	gp.write(" ".join(map(str,pi_orig.values()))+"\n")

	gp1=get_subgraph(si, g2);
	gp2=get_isomorphic_graph(g1, pi_orig);

	print commit.prettyPrintMatrix(gp1)+"\n"
	print commit.prettyPrintMatrix(gp2)+"\n"
	print commit.prettyPrintMatrix(gP)+"\n"

	return g1,g2,pi_orig,si,gP
开发者ID:asishgeek,项目名称:CS555_Project,代码行数:58,代码来源:process.py

示例5: passcrypt

def passcrypt(passwd, salt=None, method='md5', magic='$1$'):
    """Encrypt a string according to rules in crypt(3)."""
    
    if method.lower() == 'des':
	if not salt:
	    salt = str(whrandom.choice(DES_SALT)) + \
	      str(whrandom.choice(DES_SALT))

	return crypt.crypt(passwd, salt)
    elif method.lower() == 'md5':
	return passcrypt_md5(passwd, salt, magic)
    elif method.lower() == 'clear':
        return passwd
开发者ID:dedene,项目名称:postfix-cyrus-mysql,代码行数:13,代码来源:Auth.py

示例6: __healToon

def __healToon(toon, hp, ineffective):
    notify.debug('healToon() - toon: %d hp: %d ineffective: %d' % (toon.doId, hp, ineffective))
    if ineffective == 1:
        laughter = whrandom.choice(Localizer.MovieHealLaughterMisses)
    else:
        maxDam = AvPropDamage[0][1][0][1]
        if hp >= maxDam - 1:
            laughter = whrandom.choice(Localizer.MovieHealLaughterHits2)
        else:
            laughter = whrandom.choice(Localizer.MovieHealLaughterHits1)
    toon.setChatAbsolute(laughter, CFSpeech | CFTimeout)
    if hp > 0 and toon.hp != None:
        toon.setHp(min(toon.maxHp, toon.hp + hp))
    else:
        notify.debug('__healToon() - toon: %d hp: %d' % (toon.doId, hp))
开发者ID:Toonerz,项目名称:Toontown-2003,代码行数:15,代码来源:MovieHeal.py

示例7: login

def login(req, username, password):

    user = dms.username.get_by_id(username)
    if user and user.username==username:
        if user.password == password:
            if not sessions.has_key(username):
                sessions.add(username, req.connection.remote_addr[0])
    
            # establish random 20 character session_id.
            # 
            chars = string.letters + string.digits
            session_id = ''
            for x in range(20):
                session_id += whrandom.choice(chars)
            user.session_id = session_id
            user.save()
                    
            log(3, 'setting cookie')
            req.headers_out['Set-Cookie']='lampadas=' + session_id + '; path=/; expires=Wed, 09-Nov-2030 23:59:00 GMT'
            uri = URI('home' + referer_lang_ext(req))
            uri.base = '../../'
            return page_factory.page(uri)
        else:
            return "Wrong password"
    else:
        return "User not found"
开发者ID:Fat-Zer,项目名称:LDP,代码行数:26,代码来源:session.py

示例8: nonRedundantSet

def nonRedundantSet(d, threshold, distanceMatrix = 1):
    """
    returns an array consisting of entries having
    a maximum similarity (or distance) of 'threshold'.
    distanceMatrix <> None means matrix elemens are similarities.

    Ref.: Hobohm et al. (1992). Prot. Sci. 1, 409-417

    gives somehow weired results.
    """
    import whrandom #@UnresolvedImport

    d = Numeric.array(d).astype(Float32)
    if not distanceMatrix: d = less(d, threshold)
    else: d = greater(d, threshold)

    s = shape(d)
    d = Numeric.concatenate((reshape(range(s[0]),(-1,1)),d),1)

    ok = 1

    while ok:
        nNeighbours = Numeric.sum(d)
        if len(nNeighbours) <= 1: break
        maxx = max(nNeighbours[1:])
        others = Numeric.nonzero(equal(nNeighbours[1:], maxx))+1
        candidate = whrandom.choice(others)
        ok = nNeighbours[candidate]
        if ok: d = deleteRowAndColumn(d, candidate-1, candidate)
    # end while
    
    return d[:,0]
开发者ID:VuisterLab,项目名称:cing,代码行数:32,代码来源:statpack.py

示例9: get_drop_point

 def get_drop_point(self, drop_point_list):
     if self.dbg_drop_mode == 0:
         return whrandom.choice(drop_point_list)
     else:
         droppnt = self.current_drop_point % len(drop_point_list)
         self.current_drop_point = (self.current_drop_point + 1) % len(drop_point_list)
         return drop_point_list[droppnt]
开发者ID:Toonerz,项目名称:Toontown-2003,代码行数:7,代码来源:EstateManager.py

示例10: _DistributedPatternGame__buttonPressed

 def _DistributedPatternGame__buttonPressed(self, index):
     if len(self._DistributedPatternGame__localPattern) >= len(self._DistributedPatternGame__serverPattern):
         return None
     
     if self.animTracks[self.localAvId]:
         self.animTracks[self.localAvId].finish()
     
     badd = 0
     if index != self._DistributedPatternGame__serverPattern[len(self._DistributedPatternGame__localPattern)]:
         badd = 1
         acts = [
             'slip-forward',
             'slip-backward']
         ag = whrandom.choice(acts)
         self.animTracks[self.localAvId] = Sequence(Func(self.showX, 'lt'), Func(self.colorStatusBall, 'lt', len(self._DistributedPatternGame__localPattern), 0), ActorInterval(actor = self.lt, animName = ag, duration = 2.3500000000000001), Func(self.lt.loop, 'neutral'), Func(self.hideX, 'lt'))
         self.arrowDict['lt'][0].hide()
         base.playSfx(self.fallSound)
     else:
         self.colorStatusBall('lt', len(self._DistributedPatternGame__localPattern), 1)
         base.playSfx(self._DistributedPatternGame__getButtonSound(index))
         arrowTrack = self.getDanceArrowAnimTrack('lt', [
             index], 1)
         potTrack = self.getDanceSequenceAnimTrack(self.lt, [
             index])
         self.animTracks[self.localAvId] = Parallel(potTrack, arrowTrack)
     self.sendUpdate('reportButtonPress', [
         index,
         badd])
     self.animTracks[self.localAvId].start()
     self._DistributedPatternGame__localPattern.append(index)
     if len(self._DistributedPatternGame__localPattern) == len(self._DistributedPatternGame__serverPattern) or badd:
         self._DistributedPatternGame__doneGettingInput(self._DistributedPatternGame__localPattern)
开发者ID:Toonerz,项目名称:Toontown-2003,代码行数:32,代码来源:DistributedPatternGame.py

示例11: remoteButtonPressed

 def remoteButtonPressed(self, avId, index, wrong):
     if not (self.gameFSM.getCurrentState().getName() in [
         'getUserInput',
         'waitForPlayerPatterns']):
         return None
     
     if avId != self.localAvId:
         if self.animTracks[avId]:
             self.animTracks[avId].finish()
         
         av = self.getAvatar(avId)
         if wrong:
             acts = [
                 'slip-forward',
                 'slip-backward']
             ag = whrandom.choice(acts)
             self.arrowDict[avId][0].hide()
             self.animTracks[avId] = Sequence(Func(self.showX, avId), Func(self.colorStatusBall, avId, self._DistributedPatternGame__otherToonIndex[avId], 0), ActorInterval(actor = av, animName = ag, duration = 2.3500000000000001), Func(av.loop, 'neutral'), Func(self.hideX, avId))
         else:
             self.colorStatusBall(avId, self._DistributedPatternGame__otherToonIndex[avId], 1)
             arrowTrack = self.getDanceArrowAnimTrack(avId, [
                 index], 1)
             potTrack = self.getDanceSequenceAnimTrack(av, [
                 index])
             self.animTracks[avId] = Parallel(potTrack, arrowTrack)
         self._DistributedPatternGame__otherToonIndex[avId] += 1
         self.animTracks[avId].start()
开发者ID:Toonerz,项目名称:Toontown-2003,代码行数:27,代码来源:DistributedPatternGame.py

示例12: grab

 def grab(self, n):
     retval = []
     for i in range(min(n, len(self.list))):
         c = whrandom.choice(self.list)
         self.list.remove(c)
         retval.append(c)
     return retval
开发者ID:Who8MyLunch,项目名称:Eat_Words,代码行数:7,代码来源:bag.py

示例13: challengeSend

def challengeSend(f, password):
	cList = []
	for i in range(16):
		cList.append(whrandom.choice(CharSet))
	challenge = string.join(cList, '')
	f.write('%s\n' % x509.RC4(password, challenge, 0, len(challenge)))
	f.flush()
	return challenge
开发者ID:davem22101,项目名称:semanticscience,代码行数:8,代码来源:protocol.py

示例14: warp_password

    def warp_password(self):
        """Warps around the chars in the password."""
        import string

        warps = {}
        # add the alphabet to the warplist
        for x in xrange(ord('a'), ord('z')+1):
            x = chr(x)
            warps[x] = [x, x.upper()]

        # add some specials
        specialchars = (("a", ["@", "4"]),
                        ("e", ["3"]),
                        ("g", ["6"]),
                        ("i", ["1", "|", "!"]),
                        ("l", ["1", "|", "!"]),
                        ("o", ["0"]),
                        ("s", ["5", "z", "Z"]),
                        ("t", ["+", "7"]),
                        ("z", ["s", "S", "2"]))

        for (a,b) in specialchars:
            warps[a] += b

        randoms = 0
        warped_password = ""
        # warp the chars in the password
        for i in self.password:
            if i in warps.keys():
                # 75% probability
                if randint(0, 3):
                    warped_password += choice(warps[i])
                else:
                    warped_password += i
            else:
                warped_password += i

            # add a random character (max two)
            if randint(0, 5) == 0 and randoms < 2:
                warped_password += choice("\/_.,!;:'+-=")
                randoms += 1

#        print "unwarped pass = ", self.password
#        print "warped pass   = ", warped_password

        return warped_password
开发者ID:jacob-carrier,项目名称:code,代码行数:46,代码来源:recipe-65217.py

示例15: response

def response( char, args, target ):
	if not char:
		return False

	if skills.skilltable[ HEALING ][ skills.UNHIDE ] and char.hidden:
		char.removefromview()
		char.hidden = False
		char.update()

	if not target.char:
		char.socket.clilocmessage( 500970, "", 0x3b2, 3 )
		return True
	# will be added : a golem would not healed by bandages

	# count bandage
	if not char.countresource( 0x0e21 ):
		return True

	anatomy = char.skill[ ANATOMY ]
	healing = char.skill[ HEALING ]

	# dead char : res it
	if target.char.dead:
		# you cannot res yourself
		if char == target.char:
			#char.socket.clilocmessage()
			return True
		if healing >= RES_HEALING and anatomy >= RES_ANATOMY:
			res_char( char, target.char, healing, anatomy )
		else:
			char.socket.clilocmessage( 1049656, "", 0x3b2, 3 )
		return True
	if target.char.poisoned:
		if healing >= CURE_HEALING and anatomy >= CURE_ANATOMY:
			cure_char( char, target.char, healing, anatomy )
		#else:
			#char.socket.clilocmessage()
		return True

	# calc total heal amount : used formula from UOSS
	heal_min = 3 + ( char.skill[ ANATOMY ] + char.skill[ HEALING ] ) / 50
	heal_max = 10 + char.skill[ ANATOMY ] / 50 + char.skill[ HEALING ] / 20
	heal_amount = whrandom.choice( range( heal_min, heal_max ) )
	if not heal_amount:
		heal_amount = 1

	# calc total delay : used formula from UOSS
	if char == target.char:
		delay = 9400 + 60 * ( 120 - char.dexterity )
	else:
		delay = HEAL_OTHER_DELAY

	char.socket.clilocmessage( 500956, "", 0x3b2, 3 )
	# loop
	start_time = wolfpack.time.servertime()
	end_time = start_time + delay
	chance = 1
	char.addtimer( CHECK_DELAY, "skills.healing.delay_check", [ resto.serial, chance, start_time, end_time, heal_amount + 2 ] )
开发者ID:BackupTheBerlios,项目名称:wolfpack-svn,代码行数:58,代码来源:healing.py


注:本文中的whrandom.choice函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。