Example #1
0
def randomAttackCam(suit, toon, battle, attackDuration, openShotDuration, attackerString = 'suit'):
    if openShotDuration > attackDuration:
        openShotDuration = attackDuration
    
    closeShotDuration = attackDuration - openShotDuration
    if attackerString == 'suit':
        attacker = suit
        defender = toon
        defenderString = 'toon'
    else:
        attacker = toon
        defender = suit
        defenderString = 'suit'
    randomDouble = whrandom.random()
    if randomDouble > 0.59999999999999998:
        openShot = randomActorShot(attacker, battle, openShotDuration, attackerString)
    elif randomDouble > 0.20000000000000001:
        openShot = randomOverShoulderShot(suit, toon, battle, openShotDuration, focus = attackerString)
    else:
        openShot = randomSplitShot(attacker, defender, battle, openShotDuration)
    randomDouble = whrandom.random()
    if randomDouble > 0.59999999999999998:
        closeShot = randomActorShot(defender, battle, closeShotDuration, defenderString)
    elif randomDouble > 0.20000000000000001:
        closeShot = randomOverShoulderShot(suit, toon, battle, closeShotDuration, focus = defenderString)
    else:
        closeShot = randomSplitShot(attacker, defender, battle, closeShotDuration)
    return Track([
        openShot,
        closeShot])
Example #2
0
def gauss(mu, sigma):

	# When x and y are two variables from [0, 1), uniformly
	# distributed, then
	#
	#    cos(2*pi*x)*sqrt(-2*log(1-y))
	#    sin(2*pi*x)*sqrt(-2*log(1-y))
	#
	# are two *independent* variables with normal distribution
	# (mu = 0, sigma = 1).
	# (Lambert Meertens)
	# (corrected version; bug discovered by Mike Miller, fixed by LM)

	# Multithreading note: When two threads call this function
	# simultaneously, it is possible that they will receive the
	# same return value.  The window is very small though.  To
	# avoid this, you have to use a lock around all calls.  (I
	# didn't want to slow this down in the serial case by using a
	# lock here.)

	global gauss_next

	z = gauss_next
	gauss_next = None
	if z is None:
		x2pi = random() * TWOPI
		g2rad = sqrt(-2.0 * log(1.0 - random()))
		z = cos(x2pi) * g2rad
		gauss_next = sin(x2pi) * g2rad

	return mu + z*sigma
Example #3
0
def dosify(f, list):
    "return a DOSified version of f that doesn't already exist in list"
    flds = string.split(f, '.')
    if len(flds) > 2:
	flds = [string.join(flds[0:-1], '-'), flds[-1]]
    elif len(flds) == 1:
	flds.append('')

    if len(flds[0]) > 8 or len(flds[1]) > 3:
	# start with first 7 characters + last
	i = 7
	ext = flds[1][0:3]
	base = flds[0]
	newf = '%s.%s' % (base[0:i]+base[i-8:], ext)
	while i and newf in list:
	    i = i - 1
	    newf = '%s.%s' % (base[0:i]+base[i-8:], ext)

	# if that fails, simply use random three-digit numbers appended
	# to first five characters of base name
	if not i:
	    rnd = int(whrandom.random() * 999)
	    newf = '%s%03d.%s' % (base[0:5], rnd, ext)
	    while newf in list:
		rnd = int(whrandom.random() * 999)
		newf = '%s%03d.%s' % (base[0:5], rnd, ext)

	return newf

    return f
Example #4
0
def vonmisesvariate(mu, kappa):
	# mu:    mean angle (in radians between 0 and 180 degrees)
	# kappa: concentration parameter kappa (>= 0)
	
	# if kappa = 0 generate uniform random angle
	if kappa <= 1e-6:
		return TWOPI * random()

	a = 1.0 + sqrt(1.0 + 4.0 * kappa * kappa)
	b = (a - sqrt(2.0 * a))/(2.0 * kappa)
	r = (1.0 + b * b)/(2.0 * b)

	while 1:
		u1 = random()

		z = cos(pi * u1)
		f = (1.0 + r * z)/(r + z)
		c = kappa * (r - f)

		u2 = random()

		if not (u2 >= c * (2.0 - c) and u2 > c * exp(1.0 - c)):
			break

	u3 = random()
	if u3 > 0.5:
		theta = mu + 0.5*acos(f)
	else:
		theta = mu - 0.5*acos(f)

	return theta % pi
Example #5
0
def expovariate(lambd):
	# lambd: rate lambd = 1/mean
	# ('lambda' is a Python reserved word)

	u = random()
	while u <= 1e-7:
		u = random()
	return -log(u)/lambd
Example #6
0
def expovariate(lambd):
    # lambd: rate lambd = 1/mean
    # ('lambda' is a Python reserved word)

    u = random()
    while u <= 1e-7:
        u = random()
    return -log(u) / lambd
 def getLookAtPosition(self, toonHead, toonidx):
     lookAtChoice = whrandom.random()
     if len(self.used_panel_indexs) == 1:
         lookFwdPercent = 0.33000000000000002
         lookAtOthersPercent = 0
     else:
         lookFwdPercent = 0.20000000000000001
         if len(self.used_panel_indexs) == 2:
             lookAtOthersPercent = 0.40000000000000002
         else:
             lookAtOthersPercent = 0.65000000000000002
     lookRandomPercent = 1.0 - lookFwdPercent - lookAtOthersPercent
     if lookAtChoice < lookFwdPercent:
         self.IsLookingAt[toonidx] = 'f'
         return Vec3(0, 1.5, 0)
     elif lookAtChoice < lookRandomPercent + lookFwdPercent or len(self.used_panel_indexs) == 1:
         self.IsLookingAt[toonidx] = 'r'
         return toonHead.getRandomForwardLookAtPoint()
     else:
         other_toon_idxs = []
         for i in range(len(self.IsLookingAt)):
             if self.IsLookingAt[i] == toonidx:
                 other_toon_idxs.append(i)
             
         
         if len(other_toon_idxs) == 1:
             IgnoreStarersPercent = 0.40000000000000002
         else:
             IgnoreStarersPercent = 0.20000000000000001
         NoticeStarersPercent = 0.5
         bStareTargetTurnsToMe = 0
         if len(other_toon_idxs) == 0 or whrandom.random() < IgnoreStarersPercent:
             other_toon_idxs = []
             for i in self.used_panel_indexs:
                 if i != toonidx:
                     other_toon_idxs.append(i)
                 
             
             if whrandom.random() < NoticeStarersPercent:
                 bStareTargetTurnsToMe = 1
             
         
         lookingAtIdx = whrandom.choice(other_toon_idxs)
         if bStareTargetTurnsToMe:
             self.IsLookingAt[lookingAtIdx] = toonidx
             otherToonHead = None
             for panel in self.panelList:
                 if panel.position == lookingAtIdx:
                     otherToonHead = panel.headModel
                 
             
             otherToonHead.doLookAroundToStareAt(otherToonHead, self.getLookAtToPosVec(lookingAtIdx, toonidx))
         
         self.IsLookingAt[toonidx] = lookingAtIdx
         return self.getLookAtToPosVec(toonidx, lookingAtIdx)
Example #8
0
def test(N):
    input = vector(N)
    output = vector(N)
    verify = vector(N)

    for i in range(N):
	input[i] = whrandom.random() + 1j * whrandom.random()

    unscaled_DFT (N, input, output)
    unscaled_DFT (N, input, verify)

    if (dump(output) != dump(verify)):
	print dump(output)
	print dump(verify)
Example #9
0
def make_mtx():
    mat = SparseLinkMat(size, size)
    if tridiagonal:
        for i in range(size):
            mat[i,i] = 4*whrandom.random()
        if symmetric:
            for i in range(0, size-1):
                mat[i,i+1] = whrandom.random() - 0.5
                mat[i+1,i] = mat[i,i+1]
        else:
            for i in range(1, size-1):
                mat[i,i-1] = whrandom.random() - 0.5
                mat[i,i+1] = whrandom.random() - 0.5
            mat[0,1] = whrandom.random() - 0.5
            mat[size-1,size-2] = whrandom.random() - 0.5
    else:
        for i in range(size):
            if symmetric:
                jval = range(i, size)
            else:
                jval = range(0, size)
                for j in jval:
                    if whrandom.random() <= sparseness:
                        mat[i,j] = whrandom.random()
                        if symmetric:
                            mat[j,i] = mat[i,j]
    return mat
Example #10
0
def randomSplitShot(suit, toon, battle, duration):
    suitHeight = suit.getHeight()
    toonHeight = toon.getHeight()
    suitCentralPoint = suit.getPos(battle)
    suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75)
    toonCentralPoint = toon.getPos(battle)
    toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75)
    x = 9 + whrandom.random() * 2
    y = -2 - whrandom.random() * 2
    z = suitHeight * 0.5 + whrandom.random() * suitHeight
    if MovieUtil.shotDirection == 'left':
        x = -x
    
    return focusShot(x, y, z, duration, toonCentralPoint, splitFocusPoint = suitCentralPoint)
Example #11
0
def make_mtx():
    mat = SparseLinkMat(size, size)
    if tridiagonal:
        for i in range(size):
            mat[i, i] = 4 * whrandom.random()
        if symmetric:
            for i in range(0, size - 1):
                mat[i, i + 1] = whrandom.random() - 0.5
                mat[i + 1, i] = mat[i, i + 1]
        else:
            for i in range(1, size - 1):
                mat[i, i - 1] = whrandom.random() - 0.5
                mat[i, i + 1] = whrandom.random() - 0.5
            mat[0, 1] = whrandom.random() - 0.5
            mat[size - 1, size - 2] = whrandom.random() - 0.5
    else:
        for i in range(size):
            if symmetric:
                jval = range(i, size)
            else:
                jval = range(0, size)
                for j in jval:
                    if whrandom.random() <= sparseness:
                        mat[i, j] = whrandom.random()
                        if symmetric:
                            mat[j, i] = mat[i, j]
    return mat
Example #12
0
    def writerThread(self, d, howMany, writerNum):
        name = currentThread().getName()
        start = howMany * writerNum
        stop = howMany * (writerNum + 1) - 1
        if verbose:
            print "%s: creating records %d - %d" % (name, start, stop)

        # create a bunch of records
        for x in xrange(start, stop):
            key = '%04d' % x
            dbutils.DeadlockWrap(d.put,
                                 key,
                                 self.makeData(key),
                                 max_retries=12)

            if verbose and x % 100 == 0:
                print "%s: records %d - %d finished" % (name, start, x)

            # do a bit or reading too
            if random() <= 0.05:
                for y in xrange(start, x):
                    key = '%04d' % x
                    data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
                    self.assertEqual(data, self.makeData(key))

        # flush them
        try:
            dbutils.DeadlockWrap(d.sync, max_retries=12)
        except db.DBIncompleteError, val:
            if verbose:
                print "could not complete sync()..."
Example #13
0
 def _DDPlayground__seagulls(self, task):
     if task.time < self.nextSeagullTime:
         return Task.cont
     
     base.playSfx(self.loader.seagullSound)
     self.nextSeagullTime = task.time + whrandom.random() * 4.0 + 8.0
     return Task.cont
Example #14
0
    def __init__(self,
                 display,
                 rect,
                 number_of_stars,
                 angle,
                 speed_sequence,
                 size=1,
                 color=(255, 255, 255)):
        self.display_surface = display
        self.display_rect = rect
        self.angle = angle
        self.fastest_star_speed = speed_sequence[0]
        self.slowest_star_speed = speed_sequence[1]
        self.brightest_color = color
        self.number_of_stars = number_of_stars
        self.timer = Timer()

        # create our stars

        self.stars = []
        for index in range(number_of_stars):
            x_pos = self._random_x()
            y_pos = self._random_y()
            distance = whrandom.random()
            speed = ((distance * \
                      (self.fastest_star_speed - self.slowest_star_speed)) + \
                     self.slowest_star_speed)

            my_star = Star(x_pos, y_pos, distance, angle, speed, size, color)
            self.stars.append(my_star)
Example #15
0
def shuffle(list):
    pairs = []
    for element in list:
        pairs.append([whrandom.random(), element])
    pairs.sort(first_sort)
    result = map(lambda x: x[1], pairs)
    return result
    def IManageYeeshaPage(self):
        vault = ptVault()
                

        if type(vault) != type(None): #is the Vault online?
            entry = vault.findChronicleEntry("VisitedGrsnPrison")
            
            if type(entry) == type(None): 
                vault.addChronicleEntry("VisitedGrsnPrison",1,"yes")
                PtDebugPrint ("grsnPrisonRandomItems: This is your first visit to the Prison. Updated Chronicle.")
                
            else:
                PtDebugPrint ("grsnPrisonRandomItems: You've been to the Prison before.")
                
                chance = whrandom.random()
                ageSDL = PtGetAgeSDL()
                if chance > (1-kChanceOfYP):
                    ageSDL["grsnYeeshaPage02Vis"] = (1,)
                    PtDebugPrint ("grsnPrisonRandomItems: A YP is here.")
                else:
                    ageSDL["grsnYeeshaPage02Vis"] = (0,)
                    PtDebugPrint ("grsnPrisonRandomItems: A YP is NOT here.")
                
                ageSDL.sendToClients("grsnYeeshaPage02Vis")
                        
        else:
            PtDebugPrint("grsnPrisonRandomItems: Error trying to access the Chronicle." )
Example #17
0
def normalvariate(mu, sigma):
	# mu = mean, sigma = standard deviation

	# Uses Kinderman and Monahan method. Reference: Kinderman,
	# A.J. and Monahan, J.F., "Computer generation of random
	# variables using the ratio of uniform deviates", ACM Trans
	# Math Software, 3, (1977), pp257-260.

	while 1:
		u1 = random()
		u2 = random()
		z = NV_MAGICCONST*(u1-0.5)/u2
		zz = z*z/4.0
		if zz <= -log(u2):
			break
	return mu+z*sigma
Example #18
0
    def makeRandom(self):
	"Fill the board with a random pattern"
	import whrandom
	self.state={}
	for i in range(0, self.X): 
            for j in range(0, self.Y):
		if whrandom.random()*10>5.0: self.set(j,i)
Example #19
0
def task2(ident):
	global running
	for i in range(numtrips):
		if ident == 0:
			# give it a good chance to enter the next
			# barrier before the others are all out
			# of the current one
			delay = 0.001
		else:
			whmutex.acquire()
			delay = whrandom.random() * numtasks
			whmutex.release()
		if verbose:
		    print 'task', ident, 'will run for', round(delay, 1), 'sec'
		time.sleep(delay)
		if verbose:
		    print 'task', ident, 'entering barrier', i
		bar.enter()
		if verbose:
		    print 'task', ident, 'leaving barrier', i
	mutex.acquire()
	running = running - 1
	if running == 0:
		done.release()
	mutex.release()
Example #20
0
    def writerThread(self, d, howMany, writerNum):
        name = currentThread().getName()
        start = howMany * writerNum
        stop = howMany * (writerNum + 1) - 1
        if verbose:
            print "%s: creating records %d - %d" % (name, start, stop)

        # create a bunch of records
        for x in xrange(start, stop):
            key = '%04d' % x
            dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                 max_retries=12)

            if verbose and x % 100 == 0:
                print "%s: records %d - %d finished" % (name, start, x)

            # do a bit or reading too
            if random() <= 0.05:
                for y in xrange(start, x):
                    key = '%04d' % x
                    data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
                    self.assertEqual(data, self.makeData(key))

        # flush them
        try:
            dbutils.DeadlockWrap(d.sync, max_retries=12)
        except db.DBIncompleteError, val:
            if verbose:
                print "could not complete sync()..."
Example #21
0
    def __init__(self, display, rect, number_of_stars, angle,
                 speed_sequence, size = 1, color = (255, 255, 255)):
        self.display_surface = display
        self.display_rect = rect
        self.angle = angle
        self.fastest_star_speed = speed_sequence[0]
        self.slowest_star_speed = speed_sequence[1]
        self.brightest_color = color
        self.number_of_stars = number_of_stars
        self.timer = Timer()
        

        # create our stars
        
        self.stars = []
        for index in range(number_of_stars):
            x_pos = self._random_x()
            y_pos = self._random_y()
            distance = whrandom.random()
            speed = ((distance * \
                      (self.fastest_star_speed - self.slowest_star_speed)) + \
                     self.slowest_star_speed)
            
            my_star = Star(x_pos, y_pos, distance, angle, speed, size, color)
            self.stars.append(my_star)
Example #22
0
    def _DDPlayground__seagulls(self, task):
        if task.time < self.nextSeagullTime:
            return Task.cont

        base.playSfx(self.loader.seagullSound)
        self.nextSeagullTime = task.time + whrandom.random() * 4.0 + 8.0
        return Task.cont
Example #23
0
def normalvariate(mu, sigma):
    # mu = mean, sigma = standard deviation

    # Uses Kinderman and Monahan method. Reference: Kinderman,
    # A.J. and Monahan, J.F., "Computer generation of random
    # variables using the ratio of uniform deviates", ACM Trans
    # Math Software, 3, (1977), pp257-260.

    while 1:
        u1 = random()
        u2 = random()
        z = NV_MAGICCONST * (u1 - 0.5) / u2
        zz = z * z / 4.0
        if zz <= -log(u2):
            break
    return mu + z * sigma
    def IManageYeeshaPage(self):
        vault = ptVault()
                

        if type(vault) != type(None): #is the Vault online?
            entry = vault.findChronicleEntry("VisitedGrsnPrison")
            
            if type(entry) == type(None): 
                vault.addChronicleEntry("VisitedGrsnPrison",1,"yes")
                PtDebugPrint ("grsnPrisonRandomItems: This is your first visit to the Prison. Updated Chronicle.")
                
            else:
                PtDebugPrint ("grsnPrisonRandomItems: You've been to the Prison before.")
                
                chance = whrandom.random()
                ageSDL = PtGetAgeSDL()
                if chance > (1-kChanceOfYP):
                    ageSDL["grsnYeeshaPage02Vis"] = (1,)
                    PtDebugPrint ("grsnPrisonRandomItems: A YP is here.")
                else:
                    ageSDL["grsnYeeshaPage02Vis"] = (0,)
                    PtDebugPrint ("grsnPrisonRandomItems: A YP is NOT here.")
                
                ageSDL.sendToClients("grsnYeeshaPage02Vis")
                        
        else:
            PtDebugPrint("grsnPrisonRandomItems: Error trying to access the Chronicle." )
Example #25
0
def suitGroupThreeQuarterLeftBehindShot(avatar, duration):
    if whrandom.random() > 0.5:
        x = 12.369999999999999
        h = 134.61000000000001
    else:
        x = -12.369999999999999
        h = -134.61000000000001
    return heldShot(x, 11.5, 8.1600000000000001, h, -22.699999999999999, 0, duration, 'suitGroupThreeQuarterLeftBehindShot')
Example #26
0
def getNewSID(tag):
	"""Build a new Session ID"""
	t1 = time.time()
	time.sleep( whrandom.random() )
	t2 = time.time()
	base = md5.new( tag + str(t1 +t2) )
	sid = tag + '_' + base.hexdigest()
	return sid
Example #27
0
def getNewSID(tag):
    """Build a new Session ID"""
    t1 = time.time()
    time.sleep(whrandom.random())
    t2 = time.time()
    base = md5.new(tag + str(t1 + t2))
    sid = tag + '_' + base.hexdigest()
    return sid
    def startBlink(self):
        taskMgr.remove(self._ToonHead__blinkName)
        if self._ToonHead__eyes:
            self.openEyes()

        taskMgr.doMethodLater(whrandom.random() * 4.0 + 1,
                              self._ToonHead__blinkCloseEyes,
                              self._ToonHead__blinkName)
Example #29
0
def randomAttackCam(suit,
                    toon,
                    battle,
                    attackDuration,
                    openShotDuration,
                    attackerString='suit'):
    if openShotDuration > attackDuration:
        openShotDuration = attackDuration

    closeShotDuration = attackDuration - openShotDuration
    if attackerString == 'suit':
        attacker = suit
        defender = toon
        defenderString = 'toon'
    else:
        attacker = toon
        defender = suit
        defenderString = 'suit'
    randomDouble = whrandom.random()
    if randomDouble > 0.59999999999999998:
        openShot = randomActorShot(attacker, battle, openShotDuration,
                                   attackerString)
    elif randomDouble > 0.20000000000000001:
        openShot = randomOverShoulderShot(suit,
                                          toon,
                                          battle,
                                          openShotDuration,
                                          focus=attackerString)
    else:
        openShot = randomSplitShot(attacker, defender, battle,
                                   openShotDuration)
    randomDouble = whrandom.random()
    if randomDouble > 0.59999999999999998:
        closeShot = randomActorShot(defender, battle, closeShotDuration,
                                    defenderString)
    elif randomDouble > 0.20000000000000001:
        closeShot = randomOverShoulderShot(suit,
                                           toon,
                                           battle,
                                           closeShotDuration,
                                           focus=defenderString)
    else:
        closeShot = randomSplitShot(attacker, defender, battle,
                                    closeShotDuration)
    return Track([openShot, closeShot])
Example #30
0
 def _Char__blinkOpenEyes(self, task):
     self.openEyes()
     r = whrandom.random()
     if r < 0.10000000000000001:
         t = 0.20000000000000001
     else:
         t = r * 4.0 + 1.0
     taskMgr.doMethodLater(t, self._Char__blinkCloseEyes, self._Char__blinkName)
     return Task.done
Example #31
0
 def __emergeCamera(self):
     if self.cameraSubmerged == 0:
         return
     self.loader.hood.setWhiteFog()
     self.loader.underwaterSound.stop()
     self.nextSeagullTime = whrandom.random() * 8.0
     taskMgr.add(self.__seagulls, 'dd-seagulls')
     self.cameraSubmerged = 0
     self.walkStateData.setSwimSoundAudible(0)
Example #32
0
    def __mkid(self, filename):
        """Create a hopefully unique id for our (mostly anonymous) ExtZSQLMethods.
        """
        # got this from a runyaga post on ZopeLabs. so blame him.
        import whrandom
        from DateTime import DateTime

        return str(DateTime().strftime('%Y%m%d%H%M%S')) + "." + str(
            whrandom.random())[2:]
Example #33
0
def suitGroupThreeQuarterLeftBehindShot(avatar, duration):
    if whrandom.random() > 0.5:
        x = 12.369999999999999
        h = 134.61000000000001
    else:
        x = -12.369999999999999
        h = -134.61000000000001
    return heldShot(x, 11.5, 8.1600000000000001, h, -22.699999999999999, 0,
                    duration, 'suitGroupThreeQuarterLeftBehindShot')
Example #34
0
	def setAdvancedCookie(self, name, password, request, response):
		xufid = self._p_oid
		hash = encodestring(sha.new('%s%s%f%f%s'%(
			name, password, time(), whrandom.random(), str(request))).digest())
		token=quote(hash)
		response.setCookie('__aca', token, path='/')
		response.flush()
		request['__aca']=token
		self.cache_addToCookieCache(name, password, hash)
Example #35
0
def randomOverShoulderShot(suit, toon, battle, duration, focus):
    suitHeight = suit.getHeight()
    toonHeight = toon.getHeight()
    suitCentralPoint = suit.getPos(battle)
    suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75)
    toonCentralPoint = toon.getPos(battle)
    toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75)
    x = 2 + whrandom.random() * 10
    if focus == 'toon':
        y = 8 + whrandom.random() * 6
        z = suitHeight * 1.2 + whrandom.random() * suitHeight
    else:
        y = -10 - whrandom.random() * 6
        z = toonHeight * 1.5
    if MovieUtil.shotDirection == 'left':
        x = -x
    
    return focusShot(x, y, z, duration, toonCentralPoint, splitFocusPoint = suitCentralPoint)
Example #36
0
	def addChild(entryList):
		import whrandom
		root = entryList.entry()
		n = int(root.count() * whrandom.random())
		entry = root.child(n)
		global _count
		newEntry = Entry(text='Hello %d' % _count)
		_count = _count + 1
		entry.addChild(newEntry)
Example #37
0
 def __blinkOpenEyes(self, task):
     self.openEyes()
     r = whrandom.random()
     if r < 0.1:
         t = 0.2
     else:
         t = r * 4.0 + 1.0
     taskMgr.doMethodLater(t, self.__blinkCloseEyes, self.__blinkName)
     return Task.done
Example #38
0
 def _ToonHead__blinkOpenEyes(self, task):
     self.eyelids.request('open')
     r = whrandom.random()
     if r < 0.10000000000000001:
         t = 0.20000000000000001
     else:
         t = r * 4.0 + 1.0
     taskMgr.doMethodLater(t, self._ToonHead__blinkCloseEyes, self._ToonHead__blinkName)
     return Task.done
 def addChild(entryList):
     import whrandom
     root = entryList.entry()
     n = int(root.count() * whrandom.random())
     entry = root.child(n)
     global _count
     newEntry = Entry(text='Hello %d' % _count)
     _count = _count + 1
     entry.addChild(newEntry)
Example #40
0
 def _DDPlayground__emergeCamera(self):
     if self.cameraSubmerged == 0:
         return None
     
     self.loader.hood.setWhiteFog()
     self.loader.underwaterSound.stop()
     self.nextSeagullTime = whrandom.random() * 8.0
     taskMgr.add(self._DDPlayground__seagulls, 'dd-seagulls')
     self.cameraSubmerged = 0
     self.walkStateData.setSwimSoundAudible(0)
 def _ToonHead__blinkOpenEyes(self, task):
     self.eyelids.request('open')
     r = whrandom.random()
     if r < 0.10000000000000001:
         t = 0.20000000000000001
     else:
         t = r * 4.0 + 1.0
     taskMgr.doMethodLater(t, self._ToonHead__blinkCloseEyes,
                           self._ToonHead__blinkName)
     return Task.done
Example #42
0
def randomSplitShot(suit, toon, battle, duration):
    suitHeight = suit.getHeight()
    toonHeight = toon.getHeight()
    suitCentralPoint = suit.getPos(battle)
    suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75)
    toonCentralPoint = toon.getPos(battle)
    toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75)
    x = 9 + whrandom.random() * 2
    y = -2 - whrandom.random() * 2
    z = suitHeight * 0.5 + whrandom.random() * suitHeight
    if MovieUtil.shotDirection == 'left':
        x = -x

    return focusShot(x,
                     y,
                     z,
                     duration,
                     toonCentralPoint,
                     splitFocusPoint=suitCentralPoint)
Example #43
0
    def __init__ (self, community='public', version=0):
        if not community:
            raise error.BadArgument('Bad community name')

        if type(version) != types.IntType:
            raise error.BadArgument('Bad SNMP version: ' + str(version))

        self.request_id = long (whrandom.random()*0x7fffffff)
        self.version = version
        self.community = community
Example #44
0
def try_simplex(h_data):
    now = time.time()
    # vals = map(lambda x: ((x.pstart - (now-86400))*200,x.value),h_data)
    vals = map(lambda x: (x.pstart, x.value), h_data)

    def lin_f(x, par):
        m, b = par
        return (m * x) + b  # y = mx + b

    def simplex_f(args):
        err = 0.0
        for x, y in vals:
            res = abs(lin_f(x, args) - y)
            err = err + res
        return err

        # m = (y-b) / x

    i_b = 0
    i_x, i_y = vals[0]
    i_m = (i_y - i_b) / i_x
    initial = [i_m, i_b]

    initial = [whrandom.random(), whrandom.random()]

    s = Simplex(simplex_f, initial, [whrandom.random(), whrandom.random()])
    values, err, iter = s.minimize()
    print "args = ", values
    print "error = ", err
    print "iterations = ", iter

    def lin_fsolve(y, par):
        m, b = par
        return (y - b) / m  # x = (y-b)/m

        # print 'today: ' , lin_f((time.time() - (now-86399))*200,values)

    print "today: ", lin_f(time.time(), values)
    print "next week: ", lin_f(time.time() + (86400 * 7), values)
    print "next year: ", lin_f(time.time() + (86400 * 365), values)

    print "hit 90 at: ", time.asctime(time.localtime(lin_fsolve(90, values)))
    print "hit 100 at: ", time.asctime(time.localtime(lin_fsolve(100, values)))
Example #45
0
 def findSomethingToLookAt(self):
     if self.lookAtPositionCallbackArgs != None:
         pnt = self.lookAtPositionCallbackArgs[0].getLookAtPosition(self.lookAtPositionCallbackArgs[1], self.lookAtPositionCallbackArgs[2])
         self.startStareAt(self, pnt)
         return
     if whrandom.random() < 0.33:
         lookAtPnt = self.getRandomForwardLookAtPoint()
     else:
         lookAtPnt = self.__defaultStarePoint
     self.lerpLookAt(lookAtPnt, blink=1)
     return
Example #46
0
 def findSomethingToLookAt(self):
     if self.lookAtPositionCallbackArgs != None:
         pnt = self.lookAtPositionCallbackArgs[0].getLookAtPosition(self.lookAtPositionCallbackArgs[1], self.lookAtPositionCallbackArgs[2])
         self.startStareAt(self, pnt)
         return None
     
     if whrandom.random() < 0.33000000000000002:
         lookAtPnt = self.getRandomForwardLookAtPoint()
     else:
         lookAtPnt = self._ToonHead__defaultStarePoint
     self.lerpLookAt(lookAtPnt, blink = 1)
Example #47
0
def timekey():
    """answer a (hopefully unique) string key (18 or more characters).
	The key is based on the time and tends to increase in value with
	time (though keys generated quickly may not increase). The first
	characters of all keys will be very similar, so there may
	be problems indexing or hashing these values. see rtimekey().
	jjk  10/02/98"""
    keyval = time.time()  # start with the current time
    keyval = keyval + (whrandom.random() / 1000)  # randomize sub-milliseconds
    keystr = str(long(keyval * 1000000000))[:-1]  # make 18+ character string
    return keystr
Example #48
0
 def writeTestDirectory(self, htmlstream):
     htmlstream.write(self.tableTitle % "Tests")
     htmlstream.pseudoBreak()
     htmlstream.pushTag('TR', BGCOLOR="white")
     htmlstream.pushTag('TD', COLSPAN=2)
     index = int(whrandom.random() * len(self.testNames))
     htmlstream.write(self.testNames[index] +
                      """<i>- [This is a reminder that there is currently
         no concept to integrate documentation of available tests]""")
     htmlstream.popTag(2)
     htmlstream.write('</TABLE>')
     htmlstream.lineBreak()
Example #49
0
 def new(self, *content):
     """Create a new entry in the pending db, returning cookie for it."""
     now = int(time.time())
     db = self.__load()
     # Generate cookie between 1e5 and 1e6 and not already in the db.
     while 1:
         newcookie = int(whrandom.random() * 1e6)
         if newcookie >= 1e5 and not db.has_key(newcookie):
             break
     db[newcookie] = content + (now,) # Tack on timestamp.
     self.__save(db)
     return newcookie
Example #50
0
def task(ident):
    global running
    whmutex.acquire()
    delay = whrandom.random() * numtasks
    whmutex.release()
    print 'task', ident, 'will run for', delay, 'sec'
    time.sleep(delay)
    print 'task', ident, 'done'
    mutex.acquire()
    running = running - 1
    if running == 0:
        done.release()
    mutex.release()
Example #51
0
def vonmisesvariate(mu, kappa):
    # mu:    mean angle (in radians between 0 and 2*pi)
    # kappa: concentration parameter kappa (>= 0)
    # if kappa = 0 generate uniform random angle

    # Based upon an algorithm published in: Fisher, N.I.,
    # "Statistical Analysis of Circular Data", Cambridge
    # University Press, 1993.

    # Thanks to Magnus Kessler for a correction to the
    # implementation of step 4.

    if kappa <= 1e-6:
        return TWOPI * random()

    a = 1.0 + sqrt(1.0 + 4.0 * kappa * kappa)
    b = (a - sqrt(2.0 * a)) / (2.0 * kappa)
    r = (1.0 + b * b) / (2.0 * b)

    while 1:
        u1 = random()

        z = cos(pi * u1)
        f = (1.0 + r * z) / (r + z)
        c = kappa * (r - f)

        u2 = random()

        if not (u2 >= c * (2.0 - c) and u2 > c * exp(1.0 - c)):
            break

    u3 = random()
    if u3 > 0.5:
        theta = (mu % TWOPI) + acos(f)
    else:
        theta = (mu % TWOPI) - acos(f)

    return theta
Example #52
0
def randomOverShoulderShot(suit, toon, battle, duration, focus):
    suitHeight = suit.getHeight()
    toonHeight = toon.getHeight()
    suitCentralPoint = suit.getPos(battle)
    suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75)
    toonCentralPoint = toon.getPos(battle)
    toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75)
    x = 2 + whrandom.random() * 10
    if focus == 'toon':
        y = 8 + whrandom.random() * 6
        z = suitHeight * 1.2 + whrandom.random() * suitHeight
    else:
        y = -10 - whrandom.random() * 6
        z = toonHeight * 1.5
    if MovieUtil.shotDirection == 'left':
        x = -x

    return focusShot(x,
                     y,
                     z,
                     duration,
                     toonCentralPoint,
                     splitFocusPoint=suitCentralPoint)
Example #53
0
def gauss(mu, sigma):

    # When x and y are two variables from [0, 1), uniformly
    # distributed, then
    #
    #    cos(2*pi*x)*log(1-y)
    #    sin(2*pi*x)*log(1-y)
    #
    # are two *independent* variables with normal distribution
    # (mu = 0, sigma = 1).
    # (Lambert Meertens)

    global gauss_next

    if gauss_next != None:
        z = gauss_next
        gauss_next = None
    else:
        x2pi = random() * TWOPI
        log1_y = log(1.0 - random())
        z = cos(x2pi) * log1_y
        gauss_next = sin(x2pi) * log1_y

    return mu + z * sigma
Example #54
0
def validate_wichmannhill():
    """
    The WichmannHill validation checks that the same results are produced
    for the crng implementation (in C) as the whrandom implementation (in
    Python) as delivered in the standard Python library. The test checks
    the first 1000 numbers from the same seeds.
    """
    import whrandom
    whrandom.seed(1, 2, 3)
    w = crng.WichmannHill(1, 2, 3)
    for i in range(1, 1001):
        x = "%10.8f" % whrandom.random()
        y = "%10.8f" % w.next()
        if x != y:
            raise crngError, "WichmannHill value (iteration %i) is %s, should be %s" % (
                i, y, x)
Example #55
0
def randomGroupAttackCam(suit, targets, battle, attackDuration,
                         openShotDuration):
    if openShotDuration > attackDuration:
        openShotDuration = attackDuration

    closeShotDuration = attackDuration - openShotDuration
    randomDouble = whrandom.random()
    if randomDouble > 0:
        openShot = randomActorShot(suit,
                                   battle,
                                   openShotDuration,
                                   'suit',
                                   groupShot=0)

    closeShot = randomToonGroupShot(targets, suit, closeShotDuration, battle)
    return Track([openShot, closeShot])
Example #56
0
def shuffle(x, random=random, int=int):
    """x, random=random.random -> shuffle list x in place; return None.

    Optional arg random is a 0-argument function returning a random
    float in [0.0, 1.0); by default, the standard random.random.

    Note that for even rather small len(x), the total number of
    permutations of x is larger than the period of most random number
    generators; this implies that "most" permutations of a long
    sequence can never be generated.
    """

    for i in xrange(len(x) - 1, 0, -1):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random() * (i + 1))
        x[i], x[j] = x[j], x[i]