Esempio n. 1
0
def get_random_word():
    """Return a randomly selected word from dict file."""
    from pycopia import sysrandom
    fo = get_wordfile()
    try:
        point = sysrandom.randrange(fo.size)
        fo.seek(point)
        c = fo.read(1)
        while c != '\n' and fo.tell() > 0:
            fo.seek(-2, 1)
            c = fo.read(1)
        word = fo.readline().strip()
    finally:
        fo.close()
    return word
Esempio n. 2
0
def get_random_word():
    """Return a randomly selected word from dict file."""
    from pycopia import sysrandom
    fo = get_wordfile()
    try:
        point = sysrandom.randrange(fo.size)
        fo.seek(point)
        c = fo.read(1)
        while c != '\n' and fo.tell() > 0:
            fo.seek(-2, 1)
            c = fo.read(1)
        word = fo.readline().strip()
    finally:
        fo.close()
    return word
Esempio n. 3
0
def _make_match_string_from_pattern(parsetree, makebad=False, groups=None):
    collect = []
    if groups is None:
        groups = {}
    for op, val in parsetree:
        if op is sre_constants.LITERAL:
            if makebad:
                collect.append(chr((val ^ 4) & 0xFF))  # flip bit 4
                if random.randint(0, 9) == 0:
                    makebad = False  # don't error everything
            else:
                collect.append(chr(val))
        elif op is sre_constants.CATEGORY:
            collect.append(get_substitute(val, makebad))
        elif op is sre_constants.IN:
            if val[0][0] is sre_constants.CATEGORY:
                collect.append(
                    _make_match_string_from_pattern(val, False, groups))
            else:
                collect.append(chr(random.choice(val)[1]))
        elif op is sre_constants.BRANCH:
            collect.append(
                _make_match_string_from_pattern(val[1][random.randint(0, 1)],
                                                False, groups))
        elif op is sre_constants.SUBPATTERN:
            string = _make_match_string_from_pattern(val[1], False, groups)
            groups[val[0]] = string
            collect.append(string)
        elif op is sre_constants.MAX_REPEAT or op is sre_constants.MIN_REPEAT:
            for i in xrange(random.randint(val[0], min(val[1], 10))):
                collect.append(
                    _make_match_string_from_pattern(val[2], False, groups))
        elif op is sre_constants.ANY:
            collect.append(random.choice(ANYCHAR))
        elif op is sre_constants.GROUPREF:
            collect.append(groups[val])
        elif op is sre_constants.AT:
            pass  # ignore anchors
        else:
            raise UnhandledOpError("Unhandled RE op: %r" % (op, ))
    if makebad:  # in case it didn't get done yet.
        collect.insert(random.randrange(0, len(collect)),
                       random.choice(ascii.printable))
    return "".join(collect)
Esempio n. 4
0
    def __init__(self, guid=None):
        '''Use no args if you want the guid generated (this is the normal method)
       or send a string-typed guid to generate it from the string'''
        if guid is None:
            self.guid = self.__class__.lastguid
            while self.guid == self.__class__.lastguid:
                # time part
                now = long(timelib.now() * 1000)
                self.guid = ("%016x" % now) + self.__class__.hexip
                # random part
                self.guid += ("%03x" % (sysrandom.randrange(0, 4095)))
            self.__class__.lastguid = self.guid

        elif type(guid) == type(self):  # if a GUID object, copy its value
            self.guid = str(guid)

        else:  # if a string, just save its value
            assert self._check(guid), guid + " is not a valid GUID!"
            self.guid = guid
Esempio n. 5
0
    def __init__(self, guid=None):
        '''Use no args if you want the guid generated (this is the normal method)
       or send a string-typed guid to generate it from the string'''
        if guid is None:
            self.guid = self.__class__.lastguid
            while self.guid == self.__class__.lastguid:
                # time part
                now = long(timelib.now() * 1000)
                self.guid = ("%016x" % now) + self.__class__.hexip
                # random part
                self.guid += ("%03x" % (sysrandom.randrange(0, 4095)))
            self.__class__.lastguid = self.guid

        elif type(guid) == type(self): # if a GUID object, copy its value
            self.guid = str(guid)

        else: # if a string, just save its value
            assert self._check(guid), guid + " is not a valid GUID!"
            self.guid = guid
Esempio n. 6
0
def _make_match_string_from_pattern(parsetree, makebad=False, groups=None):
    collect = []
    if groups is None:
        groups = {}
    for op, val in parsetree:
        if op is sre_constants.LITERAL:
            if makebad:
                collect.append(chr((val ^ 4) & 0xFF)) # flip bit 4
                if random.randint(0,9) == 0:
                    makebad = False # don't error everything
            else:
                collect.append(chr(val))
        elif op is sre_constants.CATEGORY:
            collect.append(get_substitute(val, makebad))
        elif op is sre_constants.IN:
            if val[0][0] is sre_constants.CATEGORY:
                collect.append(_make_match_string_from_pattern(val, False, groups))
            else:
                collect.append(chr(random.choice(val)[1]))
        elif op is sre_constants.BRANCH:
            collect.append(_make_match_string_from_pattern(val[1][random.randint(0,1)], False, groups))
        elif op is sre_constants.SUBPATTERN:
            string = _make_match_string_from_pattern(val[1], False, groups)
            groups[val[0]] = string
            collect.append(string)
        elif op is sre_constants.MAX_REPEAT or op is sre_constants.MIN_REPEAT:
            for i in xrange(random.randint(val[0], min(val[1], 10))):
                collect.append(_make_match_string_from_pattern(val[2], False, groups))
        elif op is sre_constants.ANY:
            collect.append(random.choice(ANYCHAR))
        elif op is sre_constants.GROUPREF:
            collect.append(groups[val])
        elif op is sre_constants.AT:
            pass # ignore anchors
        else:
            raise UnhandledOpError("Unhandled RE op: %r" % (op,))
    if makebad: # in case it didn't get done yet.
        collect.insert(random.randrange(0, len(collect)), random.choice(ascii.printable))
    return "".join(collect)
Esempio n. 7
0
class GUID(object):
    '''
     A globally unique identifier that combines ip, time, and random bits.  Since the 
     time is listed first, you can sort records by guid.  You can also extract the time 
     and ip if needed.  
     
     GUIDs make wonderful database keys.  They require no access to the 
     database (to get the max index number), they are extremely unique, and they sort 
     automatically by time.   GUIDs prevent key clashes when merging
     two databases together, combining data, or generating keys in distributed
     systems.
    '''
    ip = ''
    try:
        ip = ifconfig.get_myaddress()
    except (
            socket.gaierror
    ):  # if we don't have an ip, default to someting in the 10.x.x.x private range
        ip = '10'
        for i in range(3):
            ip += '.' + str(sysrandom.randrange(1, 254))
    # leave space for ip v6 (65K in each sub)
    hexip = ''.join(["%04x" % long(i) for i in ip.split('.')])
    lastguid = ""

    def __init__(self, guid=None):
        '''Use no args if you want the guid generated (this is the normal method)
       or send a string-typed guid to generate it from the string'''
        if guid is None:
            self.guid = self.__class__.lastguid
            while self.guid == self.__class__.lastguid:
                # time part
                now = long(timelib.now() * 1000)
                self.guid = ("%016x" % now) + self.__class__.hexip
                # random part
                self.guid += ("%03x" % (sysrandom.randrange(0, 4095)))
            self.__class__.lastguid = self.guid

        elif type(guid) == type(self):  # if a GUID object, copy its value
            self.guid = str(guid)

        else:  # if a string, just save its value
            assert self._check(guid), guid + " is not a valid GUID!"
            self.guid = guid

    def __eq__(self, other):
        '''Return true if both GUID strings are equal'''
        if isinstance(other, self.__class__):
            return str(self) == str(other)
        return 0

    def __str__(self):
        '''Returns the string value of this guid'''
        return self.guid

    def time(self):
        '''Extracts the time portion out of the guid and returns the 
           number of milliseconds since the epoch'''
        return long(self.guid[0:16], 16)

    def ip(self):
        '''Extracts the ip portion out of the guid and returns it
           as a string like 10.10.10.10'''
        ip = []
        index = 16