Пример #1
0
def genpassword():
    generator = whrandom.whrandom()
    password = 0
    for i in range(numpassfragments):
        password = password + passfragments[generator.randint(
            o, len(passfragments))]
    return password
Пример #2
0
def genpassword():
    generator = whrandom.whrandom()
    password = ''
    for i in range(numpassfragments):
        fragment = generator.choice(passfragments)
        fragment = string.upper(fragment[0]) + fragment[1:]
        password = password + fragment
    return password
Пример #3
0
def random(n, lmin=0.0, lmax=1.0):
    """
    Returns a random vector of length n.
    """
    import whrandom
    new = vector([])
    gen = whrandom.whrandom()
    dl = lmax - lmin
    return vector(map(lambda x: dl * gen.random(), range(n)))
Пример #4
0
def random(n, lmin=0.0, lmax=1.0):
    """
    Returns a random vector of length n.
    """
    import whrandom
    new = vector([])
    gen = whrandom.whrandom()
    dl = lmax-lmin
    return vector(map(lambda x: dl*gen.random(),
		       range(n)))
Пример #5
0
    def funcUpdates(self,*args,**kw):
        """ benchmark concurrent catalog/uncatalog operations """

        uncat_conflicts = cat_conflicts = 0
        cat,msg_ids = self.get_catalog()


        msgs = self.setupUpdatesMethod(kw["numUpdates"])
        keys = msgs.keys()

        rdgen = whrandom.whrandom()
        rdgen.seed(int(time.time()) % 256,int(time.time()) % 256,int(time.time()) % 256)

        env = self.th_setup()

        for i in range(len(keys)):

            r = rdgen.randint(0,len(msgs)-1)

            mid = keys[r]
            obj = msgs[mid]

            try:
                cat.uncatalog_object(mid)

                if kw.get("commit",1)==1:
                    get_transaction().commit()
                    time.sleep(0.1)
            except ZODB.POSException.ConflictError:
                uncat_conflicts = uncat_conflicts + 1

            try:
                cat.catalog_object(obj,mid)

                if kw.get("commit",1)==1:
                    get_transaction().commit()
                    time.sleep(0.1)

            except ZODB.POSException.ConflictError:
                cat_conflicts = cat_conflicts + 1

        try:
            get_transaction().commit()
        except: pass


        self.th_teardown(env,cat_conflicts=cat_conflicts,uncat_conflicts=uncat_conflicts)
Пример #6
0
def random(n, lmin=0.0, lmax=1.0, indlist=None):
    """
    Returns a sparse vector of length n with random
    values in the range [lmin,lmax] in the specified
    positions (default: max(5,n/100) random positions).
    """
    import whrandom
    import random
    gen = whrandom.whrandom()
    dl = lmax - lmin
    rv = SparseVector(n, {})
    if indlist is None:
        nval = max(5, n / 100)
        indlist = random.sample(xrange(n), nval)
    for k in indlist:
        rv.values[k] = dl * gen.random()
    return rv
Пример #7
0
 def newToonRandom(self, seed = None, gender = 'm'):
     if seed:
         (seedx, seedy) = divmod(seed, 100)
         seedz = seed & 255
         generator = whrandom.whrandom()
         generator.seed(seedx, seedy, seedz)
     else:
         generator = whrandom
     self.type = 't'
     self.legs = generator.choice(toonLegTypes + [
         'm',
         'l',
         'l',
         'l'])
     self.gender = gender
     self.head = generator.choice(toonHeadTypes)
     (top, topColor, sleeve, sleeveColor) = getRandomTop(gender, generator = generator)
     (bottom, bottomColor) = getRandomBottom(gender, generator = generator)
     if gender == 'm':
         self.torso = generator.choice(toonTorsoTypes[:3])
         self.topTex = top
         self.topTexColor = topColor
         self.sleeveTex = sleeve
         self.sleeveTexColor = sleeveColor
         self.botTex = bottom
         self.botTexColor = bottomColor
         color = generator.choice(defaultBoyColorList)
         self.armColor = color
         self.legColor = color
         self.headColor = color
     else:
         self.torso = generator.choice(toonTorsoTypes[:6])
         self.topTex = top
         self.topTexColor = topColor
         self.sleeveTex = sleeve
         self.sleeveTexColor = sleeveColor
         if self.torso[1] == 'd':
             self.botTex = getRandomGirlBottom(SKIRT)
         else:
             self.botTex = getRandomGirlBottom(SHORTS)
         self.botTexColor = bottomColor
         color = generator.choice(defaultGirlColorList)
         self.armColor = color
         self.legColor = color
         self.headColor = color
     self.gloveColor = self.defaultColor()
Пример #8
0
    def ComputeHint(self, stem):
        import whrandom
        generator = whrandom.whrandom()
        generator.seed(ord(stem[0]), ord(stem[1]), ord(stem[2]))
        nbits = 0
        try_count = 0

        hint_bits = 0
        while nbits < self.codeword_set and try_count < self.codeword_set * 20:
            try_count = try_count + 1
            bit_num = generator.randint(0, self.codeword_len * 8 - 1)
            bit_mask = 1L << bit_num
            if not hint_bits & bit_mask:  # not yet set
                hint_bits = hint_bits | bit_mask
                nbits = nbits + 1

        return hint_bits
Пример #9
0
def random(n, lmin=0.0, lmax=1.0, indlist=None):
    """
    Returns a sparse vector of length n with random
    values in the range [lmin,lmax] in the specified
    positions (default: max(5,n/100) random positions).
    """
    import whrandom
    import random

    gen = whrandom.whrandom()
    dl = lmax - lmin
    rv = SparseVector(n, {})
    if indlist is None:
        nval = max(5, n / 100)
        indlist = random.sample(xrange(n), nval)
    for k in indlist:
        rv.values[k] = dl * gen.random()
    return rv
 def newToonRandom(self, seed=None, gender='m'):
     if seed:
         (seedx, seedy) = divmod(seed, 100)
         seedz = seed & 255
         generator = whrandom.whrandom()
         generator.seed(seedx, seedy, seedz)
     else:
         generator = whrandom
     self.type = 't'
     self.legs = generator.choice(toonLegTypes + ['m', 'l', 'l', 'l'])
     self.gender = gender
     self.head = generator.choice(toonHeadTypes)
     (top, topColor, sleeve,
      sleeveColor) = getRandomTop(gender, generator=generator)
     (bottom, bottomColor) = getRandomBottom(gender, generator=generator)
     if gender == 'm':
         self.torso = generator.choice(toonTorsoTypes[:3])
         self.topTex = top
         self.topTexColor = topColor
         self.sleeveTex = sleeve
         self.sleeveTexColor = sleeveColor
         self.botTex = bottom
         self.botTexColor = bottomColor
         color = generator.choice(defaultBoyColorList)
         self.armColor = color
         self.legColor = color
         self.headColor = color
     else:
         self.torso = generator.choice(toonTorsoTypes[:6])
         self.topTex = top
         self.topTexColor = topColor
         self.sleeveTex = sleeve
         self.sleeveTexColor = sleeveColor
         if self.torso[1] == 'd':
             self.botTex = getRandomGirlBottom(SKIRT)
         else:
             self.botTex = getRandomGirlBottom(SHORTS)
         self.botTexColor = bottomColor
         color = generator.choice(defaultGirlColorList)
         self.armColor = color
         self.legColor = color
         self.headColor = color
     self.gloveColor = self.defaultColor()
Пример #11
0
Файл: SAM.py Проект: rbe/dmerce
 def Generate(self):
     """
     generate a new session id
     - Convert timestamp to hex
     - Add random number between 0 and 65535 (0xffff hex) in hex
     """
     t = '%s' % time.time()
     dot = string.find(t, '.')
     self.__sid = '%8x%03x' % (long(t[:dot]), int(t[dot + 1:]))
     # Add information from HTTP_USER_AGENT
     # self.__posUserAgent = len(self.__sid) + 1
     # self.__sid = '%s,%s' % (self.__sid, str(self.__or.String(self.userAgent))[:-1])
     # Add information from HTTP_REFERER
     # self.__posHttpReferer = len(self.__sid) + 1
     # self.__sid = '%s,%s' % (self.__sid, str(self.__or.String(self.httpReferer))[:-1])
     r = whrandom.whrandom()
     self.__posRandom = len(self.__sid) + 1
     self.__sid = '%s,%04x' % (self.__sid, r.randint(0, 65535))
     return self.__sid
Пример #12
0
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA  02111-1307  USA

See http://www.gnu.org/licenses/licenses.html for more details.
'''

import whrandom
__version__ = "$Id: sample.py,v 1.4 2002/08/21 12:41:49 donp Exp $"

# Note:  it's important to make the generator global.  If you put it into
# one of the functions and call that function rapidly, the generator will
# be initialized using the clock.  If the calls are fast enough, you'll 
# see distinctly nonrandom behavior.

rand_num_generatorG = whrandom.whrandom()

def sample_wor(population_size, sample_size):
    '''Sample without replacement from a set of integers from 1 to 
    population_size.  It returns a tuple of sample_size integers 
    that were selected.  The sampling distribution is 
    hypergeometric.
    '''
    assert type(population_size) == type(0) and            type(sample_size) == type(0)     and            population_size > 0              and            sample_size > 0                  and            sample_size <= population_size
    global rand_num_generatorG
    m = 0  # number of records selected so far
    t = 1  # Candidate integer to select if frac is right
    list = []
    while m < sample_size:    
        unif_rand = rand_num_generatorG.random()
        frac = 1.0 * (sample_size - m) / (population_size - (t-1))
Пример #13
0
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public
License along with this program; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
MA  02111-1307  USA

See http://www.gnu.org/licenses/licenses.html for more details.
'''
import md5, whrandom
__version__ = "$Id: otp.py,v 1.3 2002/08/21 12:41:49 donp Exp $"

whG = whrandom.whrandom()


def GenerateString(seed=0):
    '''Generate a string from a four byte integer.  The string is the
    4 bytes of the integer, each converted to a character.
    '''
    global whG
    if seed:  # seed != 0 means to restart; whrandom seeds from time.
        whG.seed(seed & 0xff, (seed & 0xff00) >> 8, (seed & 0xff0000) >> 16)
    n = whG.randint(0, 2**30 - 1)
    str = ""
    str = str + chr((n & 0xFF000000) >> 24)
    str = str + chr((n & 0x00FF0000) >> 16)
    str = str + chr((n & 0x0000FF00) >> 8)
    str = str + chr((n & 0x000000FF) >> 0)
Пример #14
0
    def CheckHost(self):
	'Check one host using nmap.'
	#
	# Create a tmp file for storing nmap output
	#
	# The tempfile module from python 1.5.2 is stupid
	# two processes runing at aprox the same time gets 
	# the same tempfile...
	# For this reason I use a random suffix for the tmp-file
	# Still not 100% safe, but reduces the risk significally
	# I also inserted checks at various places, so that
	# _if_ two processes in deed get the same tmp-file
	# the only result is a normal error message to nagios
	#
	r=whrandom.whrandom()
	self.tmp_file=tempfile.mktemp('.%s')%r.randint(0,100000)
	if self.debug:
	    print 'Tmpfile is: %s'%self.tmp_file
	#
	# If a range is given, only run nmap on this range
	#
	if self.ranges<>'':
	    global nmap_cmd # needed, to avoid error on next line
	                    # since we assigns to nmap_cmd :)
	    nmap_cmd='%s -p %s' %(nmap_cmd,self.ranges)	
	#
	# Prepare a task
	#
	t=utils.Task('%s %s' %(nmap_cmd,self.host))
	#
	# Configure a time-out handler
	#
	th=utils.TimeoutHandler(t.Kill, time_to_live=self.timeout, 
	                        debug=self.debug)
	#
	#  Fork of nmap cmd
	#
	t.Run(detach=0, stdout=self.tmp_file,stderr='/dev/null')
	#
	# Wait for completition, error or timeout
	#
	nmap_exit_code=t.Wait(idlefunc=th.Check, interval=1)
	#
	# Check for timeout
	#
	if th.WasTimeOut():
	    self.exit_code=self.CRITICAL
	    self.exit_msg='CRITICAL - Plugin timed out after %s seconds' % self.timeout
	    return
	#
	# Check for exit status of subprocess
	# Must do this after check for timeout, since the subprocess
	# also returns error if aborted.
	#
	if nmap_exit_code <> 0:
	    self.exit_code=self.UNKNOWN
	    self.exit_msg='nmap program failed with code %s' % nmap_exit_code
	    return
	#
	# Read output
	#
	try:
	    f = open(self.tmp_file, 'r')
	    output=f.readlines()
	    f.close()
	except:
	    self.exit_code=self.UNKNOWN
            self.exit_msg='Unable to get output from nmap'
	    return

	#
	# Store open ports in list
	#  scans for lines where first word contains '/'
	#  and stores part before '/'
	#
	self.active_ports=[]
	try:
	    for l in output:
		if len(l)<2:
		    continue
		s=string.split(l)[0]
		if string.find(s,'/')<1:
		    continue
		p=string.split(s,'/')[0]
		if string.find(l,'open')>1:
		    self.active_ports.append(int(p))
	except:
	    # failure due to strange output...
	    pass

	if self.debug:
	    print 'Ports found by nmap:   ',self.active_ports
	#
	# Filter out optional ports, we don't check status for them...
	#
	try:
	    for p in self.opt_ports:
		self.active_ports.remove(p)
	    
	    if self.debug and len(self.opt_ports)>0:
		print 'optional ports removed:',self.active_ports
	except:
	    # under extreame loads the remove(p) above failed for me
	    # a few times, this exception hanlder handles
	    # this bug-alike situation...
	    pass

	opened=self.CheckOpen()	
	closed=self.CheckClosed()
	
	if opened <>'':
	    self.exit_code=self.CRITICAL
            self.exit_msg='PORTS CRITICAL - Open:%s Closed:%s'%(opened,closed)
	elif closed <>'':
	    self.exit_code=self.WARNING
	    self.exit_msg='PORTS WARNING - Closed:%s'%closed
	else:
	    self.exit_code=self.OK
	    self.exit_msg='PORTS ok - Only defined ports open'
Пример #15
0
Файл: Math.py Проект: rbe/dmerce
 def __init__(self, kw):
     DMS.MBase.Class.__init__(self, kw)
     self.__r = whrandom.whrandom()
     self.__log = Core.Log.File(debug = self._debug, module = '1[Math].Random')
Пример #16
0
Other have been modified to be consistent with
the Cmask original RNGs.
'''

import time, math
import unittest, doctest

import random as randomBuiltin
# used to be this
# _the_same = whrandom.whrandom() # returns an instances
try:
    _the_same = randomBuiltin.WichmannHill() # 2.3 and greater
except (AttributeError, ImportError):
    import whrandom
    _the_same = whrandom.whrandom() # 2.3 and greater
        

def _AlwaysTheSame():
     return _the_same


from athenaCL.libATH.omde.functional import Function, make_function
from athenaCL.libATH.omde.functional import Generator

# note: undefined 'make' replaced with make_function
# Private classes

class _LehmerRNG:
     """
     Linear-Congruential Random Number Generator.
Пример #17
0
Others have been modified to be consistent with
the original CMask RNGs.
'''

import time, math
import unittest, doctest

import random as randomBuiltin
# used to be this
# _the_same = whrandom.whrandom() # returns an instances
try:
    _the_same = randomBuiltin.Random()  # 2.3 and greater
except (AttributeError, ImportError):
    import whrandom
    the_same = whrandom.whrandom()  # 2.3 and greater


def _AlwaysTheSame():
    return _the_same


from athenaCL.libATH.omde.functional import Function, make_function
from athenaCL.libATH.omde.functional import Generator

# note: undefined 'make' replaced with make_function
# Private classes


class _LehmerRNG:
    """
Пример #18
0
import whrandom

# initialize all generators with the same seed
rand1 = whrandom.whrandom(4,7,11)
rand2 = whrandom.whrandom(4,7,11)
rand3 = whrandom.whrandom(4,7,11)

for i in range(5):
    print(rand1.random(), rand2.random(), rand3.random())

## 0.123993532536 0.123993532536 0.123993532536
## 0.180951499518 0.180951499518 0.180951499518
## 0.291924111809 0.291924111809 0.291924111809
## 0.952048889363 0.952048889363 0.952048889363
## 0.969794283643 0.969794283643 0.969794283643
Пример #19
0
            pass
        elif britney.versioncmp(run.unstable.get_version(p), v) != 0:
            ok = 0
            run.writeout(" Version mismatch, %s %s != %s\n" %
                         (p, v, run.unstable.get_version(p)))

    if not ok:
        run.writeout("Not using hint\n")
    elif hintcnt > 5:
        run.writeout("Too many hints already, skipping hint\n")
    else:
        hintcnt += 1
        print map(lambda hp: hp[0], x)
        run.do_all(0, map(lambda hp: hp[0], x[1]))

rand = whrandom.whrandom()
rand.seed(23, 187, 96)
for q in range(datenow):
    rand.random()
q = rand.random()

i = 1
run.writeout("Current value is %f\n" % (q))
if q < 0.05:
    q = 0.05
    run.writeout("Current value bumped to %f\n" % (q))

while 0 and i < len(
        run.packages) and (2000.0 / (1 + len(run.packages)**(i + 1)))**2 > q:
    run.do_all(i)
    i = i + 1
Пример #20
0
import whrandom

# initialize all generators with the same seed
rand1 = whrandom.whrandom(4,7,11)
rand2 = whrandom.whrandom(4,7,11)
rand3 = whrandom.whrandom(4,7,11)

for i in range(5):
    print rand1.random(), rand2.random(), rand3.random()

## 0.123993532536 0.123993532536 0.123993532536
## 0.180951499518 0.180951499518 0.180951499518
## 0.291924111809 0.291924111809 0.291924111809
## 0.952048889363 0.952048889363 0.952048889363
## 0.969794283643 0.969794283643 0.969794283643
Пример #21
0
		elif britney.versioncmp(run.unstable.get_version(p), v) != 0:
			ok = 0
			run.writeout(" Version mismatch, %s %s != %s\n" %
				(p, v, run.unstable.get_version(p)))

	if not ok:
		run.writeout("Not using hint\n")
	elif hintcnt > 5:
		run.writeout("Too many hints already, skipping hint\n")
	else:
		hintcnt += 1
		print map(lambda hp: hp[0], x)
		run.do_all(0, map(lambda hp: hp[0], x[1]))


rand = whrandom.whrandom()
rand.seed(23,187,96)
for q in range(datenow): 
	rand.random()
q = rand.random()

i = 1
run.writeout("Current value is %f\n" % (q))
if q < 0.05:
	q = 0.05
	run.writeout("Current value bumped to %f\n" % (q))

while 0 and i < len(run.packages) and (2000.0 / (1 + len(run.packages) ** (i+1))) ** 2 > q:
	run.do_all(i)
	i = i + 1
Пример #22
0
	def setUp(self):
		gera_rand = whrandom.whrandom(1,1,1) # assegurar séries aleatórias idênticas
		self.fnrand = gera_rand.random
		self.t10 = Tombola(range(10), whrandom.whrandom(1,1,1).random)