Python random.randrange() Examples

The following are code examples for showing how to use random.randrange(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: hydrus   Author: HTTP-APIs   File: user.py    MIT License 6 votes vote down vote up
def add_token(request: LocalProxy, session: Session) -> str:
    """
    Create a new token for the user or return a
    valid existing token to the user.
    """
    token = None
    id_ = int(request.authorization['username'])
    try:
        token = session.query(Token).filter(Token.user_id == id_).one()
        if not token.is_valid():
            update_token = '%030x' % randrange(16**30)
            token.id = update_token
            token.timestamp = datetime.now()
            session.commit()
    except NoResultFound:
        token = '%030x' % randrange(16**30)
        new_token = Token(user_id=id_, id=token)
        session.add(new_token)
        session.commit()
        return token
    return token.id 
Example 2
Project: pyblish-win   Author: pyblish   File: utils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <20020201195627.33539.96671@nightshade.la.mastaler.com>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 3
Project: pyblish-win   Author: pyblish   File: generator.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _make_boundary(text=None):
    # Craft a random boundary.  If text is given, ensure that the chosen
    # boundary doesn't appear in the text.
    token = random.randrange(sys.maxint)
    boundary = ('=' * 15) + (_fmt % token) + '=='
    if text is None:
        return boundary
    b = boundary
    counter = 0
    while True:
        cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE)
        if not cre.search(text):
            break
        b = boundary + '.' + str(counter)
        counter += 1
    return b 
Example 4
Project: pyblish-win   Author: pyblish   File: test_richcmp.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_dicts(self):
        # Verify that __eq__ and __ne__ work for dicts even if the keys and
        # values don't support anything other than __eq__ and __ne__ (and
        # __hash__).  Complex numbers are a fine example of that.
        import random
        imag1a = {}
        for i in range(50):
            imag1a[random.randrange(100)*1j] = random.randrange(100)*1j
        items = imag1a.items()
        random.shuffle(items)
        imag1b = {}
        for k, v in items:
            imag1b[k] = v
        imag2 = imag1b.copy()
        imag2[k] = v + 1.0
        self.assertTrue(imag1a == imag1a)
        self.assertTrue(imag1a == imag1b)
        self.assertTrue(imag2 == imag2)
        self.assertTrue(imag1a != imag2)
        for opname in ("lt", "le", "gt", "ge"):
            for op in opmap[opname]:
                self.assertRaises(TypeError, op, imag1a, imag2) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_roundtrip(self):
        def roundtrip(x):
            return fromHex(toHex(x))

        for x in [NAN, INF, self.MAX, self.MIN, self.MIN-self.TINY, self.TINY, 0.0]:
            self.identical(x, roundtrip(x))
            self.identical(-x, roundtrip(-x))

        # fromHex(toHex(x)) should exactly recover x, for any non-NaN float x.
        import random
        for i in xrange(10000):
            e = random.randrange(-1200, 1200)
            m = random.random()
            s = random.choice([1.0, -1.0])
            try:
                x = s*ldexp(m, e)
            except OverflowError:
                pass
            else:
                self.identical(x, fromHex(toHex(x))) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_strtod.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_halfway_cases(self):
        # test halfway cases for the round-half-to-even rule
        for i in xrange(100 * TEST_SIZE):
            # bit pattern for a random finite positive (or +0.0) float
            bits = random.randrange(2047*2**52)

            # convert bit pattern to a number of the form m * 2**e
            e, m = divmod(bits, 2**52)
            if e:
                m, e = m + 2**52, e - 1
            e -= 1074

            # add 0.5 ulps
            m, e = 2*m + 1, e - 1

            # convert to a decimal string
            if e >= 0:
                digits = m << e
                exponent = 0
            else:
                # m * 2**e = (m * 5**-e) * 10**e
                digits = m * 5**-e
                exponent = e
            s = '{}e{}'.format(digits, exponent)
            self.check_strtod(s) 
Example 7
Project: pyblish-win   Author: pyblish   File: test_strtod.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_boundaries(self):
        # boundaries expressed as triples (n, e, u), where
        # n*10**e is an approximation to the boundary value and
        # u*10**e is 1ulp
        boundaries = [
            (10000000000000000000, -19, 1110),   # a power of 2 boundary (1.0)
            (17976931348623159077, 289, 1995),   # overflow boundary (2.**1024)
            (22250738585072013831, -327, 4941),  # normal/subnormal (2.**-1022)
            (0, -327, 4941),                     # zero
            ]
        for n, e, u in boundaries:
            for j in xrange(1000):
                digits = n + random.randrange(-3*u, 3*u)
                exponent = e
                s = '{}e{}'.format(digits, exponent)
                self.check_strtod(s)
                n *= 10
                u *= 10
                e -= 1 
Example 8
Project: pyblish-win   Author: pyblish   File: test_heapq.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_nbest(self):
        # Less-naive "N-best" algorithm, much faster (if len(data) is big
        # enough <wink>) than sorting all of data.  However, if we had a max
        # heap instead of a min heap, it could go faster still via
        # heapify'ing all of data (linear time), then doing 10 heappops
        # (10 log-time steps).
        data = [random.randrange(2000) for i in range(1000)]
        heap = data[:10]
        self.module.heapify(heap)
        for item in data[10:]:
            if item > heap[0]:  # this gets rarer the longer we run
                self.module.heapreplace(heap, item)
        self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])

        self.assertRaises(TypeError, self.module.heapreplace, None)
        self.assertRaises(TypeError, self.module.heapreplace, None, None)
        self.assertRaises(IndexError, self.module.heapreplace, [], None) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_dumbdbm.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_random(self):
        import random
        d = {}  # mirror the database
        for dummy in range(5):
            f = dumbdbm.open(_fname)
            for dummy in range(100):
                k = random.choice('abcdefghijklm')
                if random.random() < 0.2:
                    if k in d:
                        del d[k]
                        del f[k]
                else:
                    v = random.choice('abc') * random.randrange(10000)
                    d[k] = v
                    f[k] = v
                    self.assertEqual(f[k], v)
            f.close()

            f = dumbdbm.open(_fname)
            expected = d.items()
            expected.sort()
            got = f.items()
            got.sort()
            self.assertEqual(expected, got)
            f.close() 
Example 10
Project: pyblish-win   Author: pyblish   File: uuid.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def uuid4():
    """Generate a random UUID."""

    # When the system provides a version-4 UUID generator, use it.
    if _uuid_generate_random:
        _buffer = ctypes.create_string_buffer(16)
        _uuid_generate_random(_buffer)
        return UUID(bytes=_buffer.raw)

    # Otherwise, get randomness from urandom or the 'random' module.
    try:
        import os
        return UUID(bytes=os.urandom(16), version=4)
    except:
        import random
        bytes = [chr(random.randrange(256)) for i in range(16)]
        return UUID(bytes=bytes, version=4) 
Example 11
Project: programsynthesishunting   Author: flexgp   File: latent_tree.py    GNU General Public License v3.0 6 votes vote down vote up
def latent_tree_mutate(g):
    """Produce an offspring genome by mutation through dict
    manipulation. Choose a random key in the dict, and overwrite its
    value with a random int. Later, repair must make sure the
    offspring is valid, including using the mod rule to map from a
    (possibly) large int to the corresponding small one (ie the one
    giving the same production choice) in the range of possible
    choices."""
    
    # FIXME We don't rely on g being a copy, in case the search
    # algorithm sometimes mutates individuals which are original
    # members of the population.
    # See https://github.com/PonyGE/PonyGE2/issues/89.
    g = g.copy()
    k = random.choice(list(g.keys()))
    g[k] = random.randrange(1000000) # there is no true maxint on py 3
    return g 
Example 12
Project: myhoard   Author: aiven   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def indirect_data_generate(self, cursor):
        table_name = f"db1.temp_t{self.temp_table_index}"
        print("Creating temp table", table_name, "start identifier", self.row_count + self.index_offset + 1)
        self.temp_table_index += 1
        cursor.execute(f"CREATE TEMPORARY TABLE {table_name} (id INTEGER, data TEXT)")
        self.temp_tables.append(table_name)
        self.generate_rows(cursor, table_name)

        drop_table = random.random() < 0.9
        if drop_table and len(self.temp_tables) > 20:
            index = random.randrange(0, len(self.temp_tables))
            table_name = self.temp_tables[index]
            self.temp_tables.pop(index)
            print("Inserting rows from temp table", table_name)
            cursor.execute(f"INSERT INTO db1.t1 (id, data) SELECT id, data FROM {table_name}")
            cursor.execute(f"DROP TEMPORARY TABLE {table_name}")
            cursor.execute("COMMIT")
            cursor.execute("SELECT @@GLOBAL.gtid_executed AS gtid_executed")
            gtid_executed = cursor.fetchone()["gtid_executed"]
            print("GTID executed after", table_name, "insert:", gtid_executed) 
Example 13
Project: FarWest1789   Author: ginoingras   File: FW1789_threat.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, image, speed, life):
		pygame.sprite.Sprite.__init__(self)
		self.time = speed #30
		self.life = life #200
		
		self.image = pygame.image.load("Images/%s" %image)
		#tostring(Surface, format, flipped=False) -> string
		self.imageOri = pygame.image.tostring(self.image, "RGBA_PREMULT")
		#fromstring(string, size, format, flipped=False) -> Surface
		#self.image = pygame.image.fromstring(self.imageOri, self.rect, "RGBA_PREMULT")
		
		self.rect = self.image.get_rect()
		self.rect.x = random.randrange(30,760) #random initial position
		self.rect.y = random.randrange(30,540) #random initial position
		self.newrect = self.image.get_rect()
		self.newrect.x = random.randrange(30,760) #random initial position
		self.newrect.y = random.randrange(30,540) #random initial position
		self.movx = (self.newrect.x - self.rect.x)/self.time
		self.movy = (self.newrect.y - self.rect.y)/self.time
		self.counter = int(self.time)
		
		self.shooted(0) #only to blit the life 
Example 14
Project: FarWest1789   Author: ginoingras   File: FW1789_threat.py    GNU General Public License v3.0 6 votes vote down vote up
def update(self): # used for (sprite.Group).update
		"""move linear to new position"""
		self.counter += 1
		if self.counter >= self.time:
			self.newrect.x = random.randrange(30,760)
			self.newrect.y = random.randrange(30,540)
			self.movx = (self.newrect.x - self.rect.x)/self.time
			self.movy = (self.newrect.y - self.rect.y)/self.time
			while (abs(self.movx) < 2) and (abs(self.movy) < 2): # ensure a minimal movement
				self.newrect.x = random.randrange(30,760)
				self.newrect.y = random.randrange(30,540)
				self.movx = (self.newrect.x - self.rect.x)/self.time
				self.movy = (self.newrect.y - self.rect.y)/self.time
			self.counter = 0
		self.rect.x += self.movx
		self.rect.y += self.movy

		#fenetre.blit(self.image, self.rect)
		#instead: threat.draw(fenetre) in main loop 
Example 15
Project: radius-1xtest   Author: shanghai-edu   File: mschap2.py    Apache License 2.0 6 votes vote down vote up
def getAuthAttrs(self, username, password):
		response = ""
		#peerChallenge = "0123456789123456"
		authChallenge = ""
		for x in range(0,16):
			authChallenge += chr(randrange(0, 256))
		peerChallenge = ""
		for x in range(0,16):
			peerChallenge += chr(randrange(0, 256))
		ntResponse = self._GenerateNTResponse(authChallenge, peerChallenge, username, password)
		for x in range (0, 2):
			response += '\x00'
		response += peerChallenge
		for x in range(0, 8):
			response += '\x00'
		response += ntResponse
		#print "[DEBUG] [generate] value response: %s" % upper(hexlify(response))
		returnAttrs= {}
		returnAttrs["MS-CHAP-Challenge"] = authChallenge
		returnAttrs["MS-CHAP2-Response"] = response
		return returnAttrs 
Example 16
Project: EDMC-Canonn   Author: canonn-science   File: fssreports.py    GNU General Public License v3.0 6 votes vote down vote up
def getExcluded(self):

        # sleep a random amount of time to avoid race conditions
        timeDelay = random.randrange(1, 100)
        time.sleep(1/timeDelay)

        if not fssEmitter.fssFlag:
            fssEmitter.fssFlag = True
            debug("Getting FSS exclusions")
            r = requests.get("{}/excludefsses?_limit=1000".format(self.getUrl()))
            debug("{}/excludefsses?_limit=1000".format(self.getUrl()))
            if r.status_code == requests.codes.ok:
                for exc in r.json():
                    fssEmitter.excludefss[exc.get("fssName")] = True
            else:
                debug("FFS exclusion failed")
                debug("status: {}".format(r.status_code)) 
Example 17
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: fake.py    Apache License 2.0 6 votes vote down vote up
def create_vm(name_label, status, **kwargs):
    if status == 'Running':
        domid = random.randrange(1, 1 << 16)
        resident_on = list(_db_content['host'])[0]
    else:
        domid = -1
        resident_on = ''

    vm_rec = kwargs.copy()
    vm_rec.update({'name_label': name_label,
                   'domid': domid,
                   'power_state': status,
                   'blocked_operations': {},
                   'resident_on': resident_on})
    vm_ref = _create_object('VM', vm_rec)
    after_VM_create(vm_ref, vm_rec)
    return vm_ref 
Example 18
Project: procgen   Author: juancroldan   File: white.py    Apache License 2.0 6 votes vote down vote up
def white4D_functional():
	print("Testing correlation for 4D white noise")
	N = 20
	x1 = randrange(-1000, 1000, 1)
	y1 = randrange(-1000, 1000, 1)
	z1 = randrange(-1000, 1000, 1)
	w1 = randrange(-1000, 1000, 1)
	x2 = x1 + randrange(-1000, 1000, 1)
	y2 = y1 + randrange(-1000, 1000, 1)
	z2 = z1 + randrange(-1000, 1000, 1)
	w2 = w1 + randrange(-1000, 1000, 1)
	values1 = [[[[combined(white, x / N, y / N) for x in range(x1, x1 + N)] for y in range(y1, y1 + N)] for z in range(z1, z1 + N)] for w in range(w1, w1 + N)]
	values2 = [[[[combined(white, x / N, y / N) for x in range(x2, x2 + N)] for y in range(y2, y2 + N)] for z in range(z2, z2 + N)] for w in range(w2, w2 + N)]
	rho = spearmanr(values1, values2, axis=None)
	assert abs(rho[0]) < 0.5
	print("rho = %s" % rho[0])
	print("\tNot signifying correlation found") 
Example 19
Project: tpu_pretrain   Author: allenai   File: pregenerate_training_data.py    Apache License 2.0 6 votes vote down vote up
def sample_doc(self, current_idx, sentence_weighted=True):
        # Uses the current iteration counter to ensure we don't sample the same doc twice
        if sentence_weighted:
            # With sentence weighting, we sample docs proportionally to their sentence length
            if self.doc_cumsum is None or len(self.doc_cumsum) != len(self.doc_lengths):
                self._precalculate_doc_weights()
            rand_start = self.doc_cumsum[current_idx]
            rand_end = rand_start + self.cumsum_max - self.doc_lengths[current_idx]
            sentence_index = randrange(rand_start, rand_end) % self.cumsum_max
            sampled_doc_index = np.searchsorted(self.doc_cumsum, sentence_index, side='right')
        else:
            # If we don't use sentence weighting, then every doc has an equal chance to be chosen
            sampled_doc_index = (current_idx + randrange(1, len(self.doc_lengths))) % len(self.doc_lengths)
        assert sampled_doc_index != current_idx
        if self.reduce_memory:
            return self.document_shelf[str(sampled_doc_index)]
        else:
            return self.documents[sampled_doc_index] 
Example 20
Project: Pytorch-Project-Template   Author: moemen95   File: dqn.py    MIT License 6 votes vote down vote up
def select_action(self, state):
        """
        The action selection function, it either uses the model to choose an action or samples one uniformly.
        :param state: current state of the model
        :return:
        """
        if self.cuda:
            state = state.cuda()
        sample = random.random()
        eps_threshold = self.config.eps_start + (self.config.eps_start - self.config.eps_end) * math.exp(
            -1. * self.current_iteration / self.config.eps_decay)
        self.current_iteration += 1
        if sample > eps_threshold:
            with torch.no_grad():
                return self.policy_model(state).max(1)[1].view(1, 1)
        else:
            return torch.tensor([[random.randrange(2)]], device=self.device, dtype=torch.long) 
Example 21
Project: blocksim   Author: blockbirdLabs   File: chain.py    MIT License 6 votes vote down vote up
def get_pow_difficulty(self, block):
        """Get the total difficulty in PoW of a given block"""
        if not block:
            return 0
        key = f'score:{block.header.hash}'
        fills = []
        while key not in self.db:
            fills.insert(0, (block.header.hash, block.header.difficulty))
            key = f'score:{block.header.prevhash}'
            block = self.get_parent(block)
            if block is None:
                return 0
        score = int(self.db.get(key))
        for h, d in fills:
            key = f'score:{h}'
            score = score + d + random.randrange(10**6 + 1)
            self.db.put(key, str(score))
        return score 
Example 22
Project: words_memorizer   Author: kim-yeon-gyu-exlock   File: letters.py    GNU General Public License v3.0 5 votes vote down vote up
def main():
    solved = ""
    num_of_answers = 0
    num_of_solved = 0

    print("누가 만들었을까요? 선린인고 19학번 1-3반 김연규가 만들었습니다 ㅎㅎ")
    print("문제를 푸시다가 잘 모르겠다면 0, 그만 풀고 내가 맞춘 문제 목록을 저장하려면 1을 눌러주세요.\n\n")
    for i in range(0, len(letters.keys())):
        keys = letters.keys()
        rand_num = random.randrange(0, len(keys))

        print(str(i+1)+"번째 문제: "+letters[list(letters.keys())[rand_num]])
        isFailed = False
        while(True):
            value = input()
            if(value == list(letters.keys())[rand_num]):
                print("정답입니다.\n\n\n")
                if isFailed:
                    solved = solved + list(letters.keys())[rand_num] + " △\n"
                else:
                    solved = solved + list(letters.keys())[rand_num] + " ○\n"
                num_of_answers = num_of_answers + 1
                break
            elif value == str(0):
                solved = solved + list(letters.keys())[rand_num] + " X\n"
                print("문제를 넘기셨습니다. 정답은 "+list(letters.keys())
                      [rand_num]+"였습니다.\n\n\n")
                break
            elif value == str(1):
                solved = stop(solved, letters)
                save(i, num_of_answers, solved)
                print("시험지.txt 파일을 확인해주세요.\n결과가 저장되었습니다.\n\n\n")
                return
            else:
                isFailed = True
                print("틀렸습니다. 다시 시도하세요.")
        del letters[list(letters.keys())[rand_num]]
        num_of_solved = num_of_solved + 1
    save(num_of_solved, num_of_answers, solved)
    print("시험지.txt를 확인해주세요. 푼 결과가 저장되었습니다.") 
Example 23
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def randombytes(n):
    """Return n random bytes."""
    # Use /dev/urandom if it is available.  Fall back to random module
    # if not.  It might be worthwhile to extend this function to use
    # other platform-specific mechanisms for getting random bytes.
    if os.path.exists("/dev/urandom"):
        f = open("/dev/urandom")
        s = f.read(n)
        f.close()
        return s
    else:
        L = [chr(random.randrange(0, 256)) for i in range(n)]
        return "".join(L) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_threaded_import.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def task():
    global N, critical_section, done
    import random
    x = random.randrange(1, 3)
    critical_section.acquire()
    N -= 1
    # Must release critical_section before releasing done, else the main
    # thread can exit and set critical_section to None as part of global
    # teardown; then critical_section.release() raises AttributeError.
    finished = N == 0
    critical_section.release()
    if finished:
        done.release() 
Example 25
Project: pyblish-win   Author: pyblish   File: test_sets.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.a = Set([random.randrange(100) for i in xrange(50)])
        self.b = Set([random.randrange(100) for i in xrange(50)]) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_builtin.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_max(self):
        self.assertEqual(max('123123'), '3')
        self.assertEqual(max(1, 2, 3), 3)
        self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
        self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)

        self.assertEqual(max(1, 2L, 3.0), 3.0)
        self.assertEqual(max(1L, 2.0, 3), 3)
        self.assertEqual(max(1.0, 2, 3L), 3L)

        for stmt in (
            "max(key=int)",                 # no args
            "max(1, key=int)",              # single arg not iterable
            "max(1, 2, keystone=int)",      # wrong keyword
            "max(1, 2, key=int, abc=int)",  # two many keywords
            "max(1, 2, key=1)",             # keyfunc is not callable
            ):
            try:
                exec(stmt) in globals()
            except TypeError:
                pass
            else:
                self.fail(stmt)

        self.assertEqual(max((1,), key=neg), 1)     # one elem iterable
        self.assertEqual(max((1,2), key=neg), 1)    # two elem iterable
        self.assertEqual(max(1, 2, key=neg), 1)     # two elems

        data = [random.randrange(200) for i in range(100)]
        keys = dict((elem, random.randrange(50)) for elem in data)
        f = keys.__getitem__
        self.assertEqual(max(data, key=f),
                         sorted(reversed(data), key=f)[-1]) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_mutants.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def maybe_mutate():
    global mutate
    if not mutate:
        return
    if random.random() < 0.5:
        return

    if random.random() < 0.5:
        target, keys = dict1, dict1keys
    else:
        target, keys = dict2, dict2keys

    if random.random() < 0.2:
        # Insert a new key.
        mutate = 0   # disable mutation until key inserted
        while 1:
            newkey = Horrid(random.randrange(100))
            if newkey not in target:
                break
        target[newkey] = Horrid(random.randrange(100))
        keys.append(newkey)
        mutate = 1

    elif keys:
        # Delete a key at random.
        mutate = 0   # disable mutation until key deleted
        i = random.randrange(len(keys))
        key = keys[i]
        del target[key]
        del keys[i]
        mutate = 1

# A horrid class that triggers random mutations of dict1 and dict2 when
# instances are compared. 
Example 28
Project: pyblish-win   Author: pyblish   File: test_mutants.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test(n):
    for i in xrange(n):
        test_one(random.randrange(1, 100))

# See last comment block for clues about good values for n. 
Example 29
Project: pyblish-win   Author: pyblish   File: test_sort.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_stability(self):
        data = [(random.randrange(100), i) for i in xrange(200)]
        copy = data[:]
        data.sort(key=lambda x: x[0])   # sort on the random first field
        copy.sort()                     # sort using both fields
        self.assertEqual(data, copy)    # should get the same result 
Example 30
Project: pyblish-win   Author: pyblish   File: test_sort.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_reverse_stability(self):
        data = [(random.randrange(100), i) for i in xrange(200)]
        copy1 = data[:]
        copy2 = data[:]
        data.sort(cmp=lambda x,y: cmp(x[0],y[0]), reverse=True)
        copy1.sort(cmp=lambda x,y: cmp(y[0],x[0]))
        self.assertEqual(data, copy1)
        copy2.sort(key=lambda x: x[0], reverse=True)
        self.assertEqual(data, copy2)

#============================================================================== 
Example 31
Project: pyblish-win   Author: pyblish   File: test_strtod.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_underflow_boundary(self):
        # test values close to 2**-1075, the underflow boundary; similar
        # to boundary_tests, except that the random error doesn't scale
        # with n
        for exponent in xrange(-400, -320):
            base = 10**-exponent // 2**1075
            for j in xrange(TEST_SIZE):
                digits = base + random.randrange(-1000, 1000)
                s = '{}e{}'.format(digits, exponent)
                self.check_strtod(s) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_strtod.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bigcomp(self):
        for ndigs in 5, 10, 14, 15, 16, 17, 18, 19, 20, 40, 41, 50:
            dig10 = 10**ndigs
            for i in xrange(10 * TEST_SIZE):
                digits = random.randrange(dig10)
                exponent = random.randrange(-400, 400)
                s = '{}e{}'.format(digits, exponent)
                self.check_strtod(s) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_set.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_hash(self):
        self.assertEqual(hash(self.thetype('abcdeb')),
                         hash(self.thetype('ebecda')))

        # make sure that all permutations give the same hash value
        n = 100
        seq = [randrange(n) for i in xrange(n)]
        results = set()
        for i in xrange(200):
            shuffle(seq)
            results.add(hash(self.thetype(seq)))
        self.assertEqual(len(results), 1) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_heapq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_naive_nbest(self):
        data = [random.randrange(2000) for i in range(1000)]
        heap = []
        for item in data:
            self.module.heappush(heap, item)
            if len(heap) > 10:
                self.module.heappop(heap)
        heap.sort()
        self.assertEqual(heap, sorted(data)[-10:]) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_heapq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_nbest_with_pushpop(self):
        data = [random.randrange(2000) for i in range(1000)]
        heap = data[:10]
        self.module.heapify(heap)
        for item in data[10:]:
            self.module.heappushpop(heap, item)
        self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
        self.assertEqual(self.module.heappushpop([], 'x'), 'x') 
Example 36
Project: pyblish-win   Author: pyblish   File: test_heapq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_heapsort(self):
        # Exercise everything with repeated heapsort checks
        for trial in xrange(100):
            size = random.randrange(50)
            data = [random.randrange(25) for i in range(size)]
            if trial & 1:     # Half of the time, use heapify
                heap = data[:]
                self.module.heapify(heap)
            else:             # The rest of the time, use heappush
                heap = []
                for item in data:
                    self.module.heappush(heap, item)
            heap_sorted = [self.module.heappop(heap) for i in range(size)]
            self.assertEqual(heap_sorted, sorted(data)) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_heapq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_merge_stability(self):
        class Int(int):
            pass
        inputs = [[], [], [], []]
        for i in range(20000):
            stream = random.randrange(4)
            x = random.randrange(500)
            obj = Int(x)
            obj.pair = (x, stream)
            inputs[stream].append(obj)
        for stream in inputs:
            stream.sort()
        result = [i.pair for i in self.module.merge(*inputs)]
        self.assertEqual(result, sorted(result)) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_heapq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_nsmallest(self):
        data = [(random.randrange(2000), i) for i in range(1000)]
        for f in (None, lambda x:  x[0] * 547 % 2000):
            for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
                self.assertEqual(self.module.nsmallest(n, data), sorted(data)[:n])
                self.assertEqual(self.module.nsmallest(n, data, key=f),
                                 sorted(data, key=f)[:n]) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_heapq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_nlargest(self):
        data = [(random.randrange(2000), i) for i in range(1000)]
        for f in (None, lambda x:  x[0] * 547 % 2000):
            for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
                self.assertEqual(self.module.nlargest(n, data),
                                 sorted(data, reverse=True)[:n])
                self.assertEqual(self.module.nlargest(n, data, key=f),
                                 sorted(data, key=f, reverse=True)[:n]) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_deque.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_delitem(self):
        n = 500         # O(n**2) test, don't make this too big
        d = deque(xrange(n))
        self.assertRaises(IndexError, d.__delitem__, -n-1)
        self.assertRaises(IndexError, d.__delitem__, n)
        for i in xrange(n):
            self.assertEqual(len(d), n-i)
            j = random.randrange(-len(d), len(d))
            val = d[j]
            self.assertIn(val, d)
            del d[j]
            self.assertNotIn(val, d)
        self.assertEqual(len(d), 0) 
Example 41
Project: pyblish-win   Author: pyblish   File: uuid.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _random_getnode():
    """Get a random node ID, with eighth bit set as suggested by RFC 4122."""
    import random
    return random.randrange(0, 1<<48L) | 0x010000000000L 
Example 42
Project: pyblish-win   Author: pyblish   File: uuid.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def uuid1(node=None, clock_seq=None):
    """Generate a UUID from a host ID, sequence number, and the current time.
    If 'node' is not given, getnode() is used to obtain the hardware
    address.  If 'clock_seq' is given, it is used as the sequence number;
    otherwise a random 14-bit sequence number is chosen."""

    # When the system provides a version-1 UUID generator, use it (but don't
    # use UuidCreate here because its UUIDs don't conform to RFC 4122).
    if _uuid_generate_time and node is clock_seq is None:
        _buffer = ctypes.create_string_buffer(16)
        _uuid_generate_time(_buffer)
        return UUID(bytes=_buffer.raw)

    global _last_timestamp
    import time
    nanoseconds = int(time.time() * 1e9)
    # 0x01b21dd213814000 is the number of 100-ns intervals between the
    # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
    timestamp = int(nanoseconds//100) + 0x01b21dd213814000L
    if _last_timestamp is not None and timestamp <= _last_timestamp:
        timestamp = _last_timestamp + 1
    _last_timestamp = timestamp
    if clock_seq is None:
        import random
        clock_seq = random.randrange(1<<14L) # instead of stable storage
    time_low = timestamp & 0xffffffffL
    time_mid = (timestamp >> 32L) & 0xffffL
    time_hi_version = (timestamp >> 48L) & 0x0fffL
    clock_seq_low = clock_seq & 0xffL
    clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
    if node is None:
        node = getnode()
    return UUID(fields=(time_low, time_mid, time_hi_version,
                        clock_seq_hi_variant, clock_seq_low, node), version=1) 
Example 43
Project: python-samples   Author: dek-odoo   File: dek_program081.py    Apache License 2.0 5 votes vote down vote up
def main(startLimit, endLimit):
    print random.randrange(startLimit, endLimit + 1) 
Example 44
Project: earlgrey   Author: icon-project   File: test_multiprocess.py    Apache License 2.0 5 votes vote down vote up
def test_credential_failure(self):
        random_length = random.randrange(5, 10)
        random_string = "".join(random.choice(string.ascii_letters) for _ in range(random_length))

        print(f"username : {random_string}")
        print(f"password : {random_string}")

        server = multiprocessing.Process(target=self._run_server, args=(random_string, random_string))
        server.daemon = True
        server.start()

        client = multiprocessing.Process(target=self._run_client, args=(random_string, random_string))
        client.daemon = True
        client.start()

        server.join()
        client.join()

        self.assertEqual(server.exitcode, 1)
        self.assertEqual(client.exitcode, 1) 
Example 45
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def updateAccessCode(sessionName, paceLevel, dueDate, accessCode):
    if sessionName in Global.accessCodes:
        if not accessCode or dueDate:
            del Global.accessCodes[sessionName]
    else:
        if accessCode and not dueDate:
            Global.accessCodes[sessionName] = random.randrange(1+10**(accessCode-1), 10**accessCode) 
Example 46
Project: python-shamir-mnemonic   Author: trezor   File: generate_vectors.py    MIT License 5 votes vote down vote up
def random_bytes(n):
    return bytes(random.randrange(256) for _ in range(n)) 
Example 47
Project: flappybird-qlearning-bot   Author: chncyhn   File: flappy.py    MIT License 5 votes vote down vote up
def getRandomPipe():
    """returns a randomly generated pipe"""
    # y of gap between upper and lower pipe
    gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE))
    gapY += int(BASEY * 0.2)
    pipeHeight = IMAGES["pipe"][0].get_height()
    pipeX = SCREENWIDTH + 10

    return [
        {"x": pipeX, "y": gapY - pipeHeight},  # upper pipe
        {"x": pipeX, "y": gapY + PIPEGAPSIZE},  # lower pipe
    ] 
Example 48
Project: flappybird-qlearning-bot   Author: chncyhn   File: learn.py    MIT License 5 votes vote down vote up
def getRandomPipe():
    """returns a randomly generated pipe"""
    # y of gap between upper and lower pipe
    gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE))
    gapY += int(BASEY * 0.2)
    pipeHeight = PIPE[IM_HEIGTH]
    pipeX = SCREENWIDTH + 10

    return [
        {"x": pipeX, "y": gapY - pipeHeight},  # upper pipe
        {"x": pipeX, "y": gapY + PIPEGAPSIZE},  # lower pipe
    ] 
Example 49
Project: MusicDownloader   Author: wwwpf   File: qq.py    GNU General Public License v3.0 5 votes vote down vote up
def get_guid():
    return random.randrange(0, 1e10) 
Example 50
Project: deep-learning-note   Author: wdxtub   File: 7_candy.py    MIT License 5 votes vote down vote up
def producer(loops):
    for i in range(loops):
        refill()
        sleep(randrange(3)) 
Example 51
Project: deep-learning-note   Author: wdxtub   File: 7_candy.py    MIT License 5 votes vote down vote up
def consumer(loops):
    for i in range(loops):
        buy()
        sleep(randrange(3)) 
Example 52
Project: deep-learning-note   Author: wdxtub   File: 7_candy.py    MIT License 5 votes vote down vote up
def _main():
    print("starging at:", ctime())
    nloops = randrange(2, 6)
    print("THE CANDY MACHINE (full with %d bars)!" % MAX)
    Thread(
        target=consumer, args=(randrange(nloops, nloops + MAX + 2),)
    ).start()  # buyer
    Thread(target=producer, args=(nloops,)).start()  # vndr 
Example 53
Project: myhoard   Author: aiven   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def generate_rows(self, cursor, table):
        row_count = random.randrange(50, 200)
        for _ in range(row_count):
            character = random.choice("abcdefghijklmnopqrstuvwxyz")
            character_count = random.randrange(10, 10000)
            self.row_infos.append((character, character_count))
            self.row_count += 1
            self.estimated_bytes += character_count + 10
            data = character * character_count
            cursor.execute(f"INSERT INTO {table} (id, data) VALUES (%s, %s)", (self.row_count + self.index_offset, data))
        return row_count 
Example 54
Project: FarWest1789   Author: ginoingras   File: FW1789_threat.py    GNU General Public License v3.0 5 votes vote down vote up
def move(self):
		"""move jump from point to new position point"""
		self.counter += 1
		if self.counter >= self.time:
			self.rect.x = random.randrange(30,760)
			self.rect.y = random.randrange(30,540)
			self.counter = 0
			
		fenetre.blit(self.image,self.rect)
		#fenetre.blit(self.image, self.rect)
		#instead: threat.draw(fenetre) in main loop 
Example 55
Project: FarWest1789   Author: ginoingras   File: FW1789_caravan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, image, speed):
		pygame.sprite.Sprite.__init__(self)
		self.time = speed #90
		self.life = 10
		self.image = pygame.image.load("Images/%s" %image)
		self.rect = self.image.get_rect()
		self.rect.x = random.randrange(30,760) #random initial position
		self.rect.y = 500 # initial position
		self.newrect = self.image.get_rect()
		self.newrect.x = random.randrange(30,760) #random final position
		self.newrect.y = 500 # final position
		self.movx = (self.newrect.x - self.rect.x)/self.time
		#self.movy = (self.newrect.y - self.rect.y)/self.time
		self.movy = 0
		self.counter = int(self.time) 
Example 56
Project: radius-1xtest   Author: shanghai-edu   File: packet.py    Apache License 2.0 5 votes vote down vote up
def CreateAuthenticator():
        """Create a packet autenticator. All RADIUS packets contain a sixteen
        byte authenticator which is used to authenticate replies from the
        RADIUS server and in the password hiding algorithm. This function
        returns a suitable random string that can be used as an authenticator.

        :return: valid packet authenticator
        :rtype: string
        """

        data=""
        for i in range(16):
            data+=chr(random.randrange(0,256))

        return data 
Example 57
Project: radius-1xtest   Author: shanghai-edu   File: packet.py    Apache License 2.0 5 votes vote down vote up
def CreateID(self):
        """Create a packet ID.  All RADIUS requests have a ID which is used to
        identify a request. This is used to detect retries and replay attacks.
        This function returns a suitable random number that can be used as ID.

        :return: ID number
        :rtype:  integer

        """
        return random.randrange(0,256) 
Example 58
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: fake.py    Apache License 2.0 5 votes vote down vote up
def _VM_reboot(self, session, vm_ref):
        db_ref = _db_content['VM'][vm_ref]
        if db_ref['power_state'] != 'Running':
            raise Failure(['VM_BAD_POWER_STATE',
                'fake-opaque-ref', db_ref['power_state'].lower(), 'halted'])
        db_ref['power_state'] = 'Running'
        db_ref['domid'] = random.randrange(1, 1 << 16) 
Example 59
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: stubs.py    Apache License 2.0 5 votes vote down vote up
def VM_start(self, _1, ref, _2, _3):
        vm = fake.get_record('VM', ref)
        if vm['power_state'] != 'Halted':
            raise fake.Failure(['VM_BAD_POWER_STATE', ref, 'Halted',
                                vm['power_state']])
        vm['power_state'] = 'Running'
        vm['is_a_template'] = False
        vm['is_control_domain'] = False
        vm['domid'] = random.randrange(1, 1 << 16)
        return vm 
Example 60
Project: procgen   Author: juancroldan   File: white.py    Apache License 2.0 5 votes vote down vote up
def white2D_functional():
	print("Testing correlation for 2D white noise")
	N = 100
	x1 = randrange(-1000, 1000, 1)
	y1 = randrange(-1000, 1000, 1)
	x2 = x1 + randrange(-1000, 1000, 1)
	y2 = y1 + randrange(-1000, 1000, 1)
	values1 = [[combined(white, x / N, y / N) for x in range(x1, x1 + N)] for y in range(y1, y1 + N)]
	values2 = [[combined(white, x / N, y / N) for x in range(x2, x2 + N)] for y in range(y2, y2 + N)]
	rho = spearmanr(values1, values2, axis=None)
	assert abs(rho[0]) < 0.5
	print("rho = %s" % rho[0])
	print("\tNot signifying correlation found") 
Example 61
Project: procgen   Author: juancroldan   File: white.py    Apache License 2.0 5 votes vote down vote up
def white3D_functional():
	print("Testing correlation for 3D white noise")
	N = 100
	x1 = randrange(-1000, 1000, 1)
	y1 = randrange(-1000, 1000, 1)
	z1 = randrange(-1000, 1000, 1)
	x2 = x1 + randrange(-1000, 1000, 1)
	y2 = y1 + randrange(-1000, 1000, 1)
	z2 = z1 + randrange(-1000, 1000, 1)
	values1 = [[[combined(white, x / N, y / N) for x in range(x1, x1 + N)] for y in range(y1, y1 + N)] for z in range(z1, z1 + N)]
	values2 = [[[combined(white, x / N, y / N) for x in range(x2, x2 + N)] for y in range(y2, y2 + N)] for z in range(z2, z2 + N)]
	rho = spearmanr(values1, values2, axis=None)
	assert abs(rho[0]) < 0.5
	print("rho = %s" % rho[0])
	print("\tNot signifying correlation found") 
Example 62
Project: daqnet   Author: adamgreig   File: utils.py    MIT License 5 votes vote down vote up
def test_pipelined_adder():
    from nmigen.back import pysim
    import random

    n = 64
    m = 4
    adder = PipelinedAdder(n, m)

    def testbench():
        for _ in range(100):
            a = random.randrange(2**n)
            b = random.randrange(2**n)
            yield
            yield adder.a.eq(a)
            yield adder.b.eq(b)
            for _ in range(m+1):
                yield
            assert (yield adder.c) == (a+b) % (2**n)

        yield adder.a.eq(2**n-1)
        yield adder.b.eq(1)
        for _ in range(m+1):
            yield
        assert (yield adder.c) == 0

    vcdf = open("adder.vcd", "w")
    with pysim.Simulator(adder, vcd_file=vcdf) as sim:
        sim.add_clock(1e-6)
        sim.add_sync_process(testbench())
        sim.run() 
Example 63
Project: bigquerylayers   Author: smandaric   File: _upload.py    GNU General Public License v3.0 5 votes vote down vote up
def get_boundary():
    """Get a random boundary for a multipart request.

    Returns:
        bytes: The boundary used to separate parts of a multipart request.
    """
    random_int = random.randrange(sys.maxsize)
    boundary = _BOUNDARY_FORMAT.format(random_int)
    # NOTE: Neither % formatting nor .format() are available for byte strings
    #       in Python 3.4, so we must use unicode strings as templates.
    return boundary.encode(u"utf-8") 
Example 64
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def interpolation_dict(self):
        subs = html4css1.Writer.interpolation_dict(self)
        settings = self.document.settings
        pyhome = settings.python_home
        subs['pyhome'] = pyhome
        subs['pephome'] = settings.pep_home
        if pyhome == '..':
            subs['pepindex'] = '.'
        else:
            subs['pepindex'] = pyhome + '/dev/peps'
        index = self.document.first_child_matching_class(nodes.field_list)
        header = self.document[index]
        self.pepnum = header[0][1].astext()
        subs['pep'] = self.pepnum
        if settings.no_random:
            subs['banner'] = 0
        else:
            import random
            subs['banner'] = random.randrange(64)
        try:
            subs['pepnum'] = '%04i' % int(self.pepnum)
        except ValueError:
            subs['pepnum'] = self.pepnum
        self.title = header[1][1].astext()
        subs['title'] = self.title
        subs['body'] = ''.join(
            self.body_pre_docinfo + self.docinfo + self.body)
        return subs 
Example 65
Project: pyblish-win   Author: pyblish   File: test_builtin.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_min(self):
        self.assertEqual(min('123123'), '1')
        self.assertEqual(min(1, 2, 3), 1)
        self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
        self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)

        self.assertEqual(min(1, 2L, 3.0), 1)
        self.assertEqual(min(1L, 2.0, 3), 1L)
        self.assertEqual(min(1.0, 2, 3L), 1.0)

        self.assertRaises(TypeError, min)
        self.assertRaises(TypeError, min, 42)
        self.assertRaises(ValueError, min, ())
        class BadSeq:
            def __getitem__(self, index):
                raise ValueError
        self.assertRaises(ValueError, min, BadSeq())
        class BadNumber:
            def __cmp__(self, other):
                raise ValueError
        self.assertRaises(ValueError, min, (42, BadNumber()))

        for stmt in (
            "min(key=int)",                 # no args
            "min(1, key=int)",              # single arg not iterable
            "min(1, 2, keystone=int)",      # wrong keyword
            "min(1, 2, key=int, abc=int)",  # two many keywords
            "min(1, 2, key=1)",             # keyfunc is not callable
            ):
            try:
                exec(stmt) in globals()
            except TypeError:
                pass
            else:
                self.fail(stmt)

        self.assertEqual(min((1,), key=neg), 1)     # one elem iterable
        self.assertEqual(min((1,2), key=neg), 2)    # two elem iterable
        self.assertEqual(min(1, 2, key=neg), 2)     # two elems

        data = [random.randrange(200) for i in range(100)]
        keys = dict((elem, random.randrange(50)) for elem in data)
        f = keys.__getitem__
        self.assertEqual(min(data, key=f),
                         sorted(data, key=f)[0]) 
Example 66
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_tz_aware_arithmetic(self):
        import random

        now = self.theclass.now()
        tz55 = FixedOffset(-330, "west 5:30")
        timeaware = now.time().replace(tzinfo=tz55)
        nowaware = self.theclass.combine(now.date(), timeaware)
        self.assertIs(nowaware.tzinfo, tz55)
        self.assertEqual(nowaware.timetz(), timeaware)

        # Can't mix aware and non-aware.
        self.assertRaises(TypeError, lambda: now - nowaware)
        self.assertRaises(TypeError, lambda: nowaware - now)

        # And adding datetime's doesn't make sense, aware or not.
        self.assertRaises(TypeError, lambda: now + nowaware)
        self.assertRaises(TypeError, lambda: nowaware + now)
        self.assertRaises(TypeError, lambda: nowaware + nowaware)

        # Subtracting should yield 0.
        self.assertEqual(now - now, timedelta(0))
        self.assertEqual(nowaware - nowaware, timedelta(0))

        # Adding a delta should preserve tzinfo.
        delta = timedelta(weeks=1, minutes=12, microseconds=5678)
        nowawareplus = nowaware + delta
        self.assertIs(nowaware.tzinfo, tz55)
        nowawareplus2 = delta + nowaware
        self.assertIs(nowawareplus2.tzinfo, tz55)
        self.assertEqual(nowawareplus, nowawareplus2)

        # that - delta should be what we started with, and that - what we
        # started with should be delta.
        diff = nowawareplus - delta
        self.assertIs(diff.tzinfo, tz55)
        self.assertEqual(nowaware, diff)
        self.assertRaises(TypeError, lambda: delta - nowawareplus)
        self.assertEqual(nowawareplus - nowaware, delta)

        # Make up a random timezone.
        tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
        # Attach it to nowawareplus.
        nowawareplus = nowawareplus.replace(tzinfo=tzr)
        self.assertIs(nowawareplus.tzinfo, tzr)
        # Make sure the difference takes the timezone adjustments into account.
        got = nowaware - nowawareplus
        # Expected:  (nowaware base - nowaware offset) -
        #            (nowawareplus base - nowawareplus offset) =
        #            (nowaware base - nowawareplus base) +
        #            (nowawareplus offset - nowaware offset) =
        #            -delta + nowawareplus offset - nowaware offset
        expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
        self.assertEqual(got, expected)

        # Try max possible difference.
        min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
        max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
                            tzinfo=FixedOffset(-1439, "max"))
        maxdiff = max - min
        self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
                                  timedelta(minutes=2*1439)) 
Example 67
Project: pyblish-win   Author: pyblish   File: test_collections.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_multiset_operations(self):
        # Verify that adding a zero counter will strip zeros and negatives
        c = Counter(a=10, b=-2, c=0) + Counter()
        self.assertEqual(dict(c), dict(a=10))

        elements = 'abcd'
        for i in range(1000):
            # test random pairs of multisets
            p = Counter(dict((elem, randrange(-2,4)) for elem in elements))
            p.update(e=1, f=-1, g=0)
            q = Counter(dict((elem, randrange(-2,4)) for elem in elements))
            q.update(h=1, i=-1, j=0)
            for counterop, numberop in [
                (Counter.__add__, lambda x, y: max(0, x+y)),
                (Counter.__sub__, lambda x, y: max(0, x-y)),
                (Counter.__or__, lambda x, y: max(0,x,y)),
                (Counter.__and__, lambda x, y: max(0, min(x,y))),
            ]:
                result = counterop(p, q)
                for x in elements:
                    self.assertEqual(numberop(p[x], q[x]), result[x],
                                     (counterop, x, p, q))
                # verify that results exclude non-positive counts
                self.assertTrue(x>0 for x in result.values())

        elements = 'abcdef'
        for i in range(100):
            # verify that random multisets with no repeats are exactly like sets
            p = Counter(dict((elem, randrange(0, 2)) for elem in elements))
            q = Counter(dict((elem, randrange(0, 2)) for elem in elements))
            for counterop, setop in [
                (Counter.__sub__, set.__sub__),
                (Counter.__or__, set.__or__),
                (Counter.__and__, set.__and__),
            ]:
                counter_result = counterop(p, q)
                set_result = setop(set(p.elements()), set(q.elements()))
                self.assertEqual(counter_result, dict.fromkeys(set_result, 1)) 
Example 68
Project: pyblish-win   Author: pyblish   File: test_strtod.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_short_halfway_cases(self):
        # exact halfway cases with a small number of significant digits
        for k in 0, 5, 10, 15, 20:
            # upper = smallest integer >= 2**54/5**k
            upper = -(-2**54//5**k)
            # lower = smallest odd number >= 2**53/5**k
            lower = -(-2**53//5**k)
            if lower % 2 == 0:
                lower += 1
            for i in xrange(TEST_SIZE):
                # Select a random odd n in [2**53/5**k,
                # 2**54/5**k). Then n * 10**k gives a halfway case
                # with small number of significant digits.
                n, e = random.randrange(lower, upper, 2), k

                # Remove any additional powers of 5.
                while n % 5 == 0:
                    n, e = n // 5, e + 1
                assert n % 10 in (1, 3, 7, 9)

                # Try numbers of the form n * 2**p2 * 10**e, p2 >= 0,
                # until n * 2**p2 has more than 20 significant digits.
                digits, exponent = n, e
                while digits < 10**20:
                    s = '{}e{}'.format(digits, exponent)
                    self.check_strtod(s)
                    # Same again, but with extra trailing zeros.
                    s = '{}e{}'.format(digits * 10**40, exponent - 40)
                    self.check_strtod(s)
                    digits *= 2

                # Try numbers of the form n * 5**p2 * 10**(e - p5), p5
                # >= 0, with n * 5**p5 < 10**20.
                digits, exponent = n, e
                while digits < 10**20:
                    s = '{}e{}'.format(digits, exponent)
                    self.check_strtod(s)
                    # Same again, but with extra trailing zeros.
                    s = '{}e{}'.format(digits * 10**40, exponent - 40)
                    self.check_strtod(s)
                    digits *= 5
                    exponent -= 1 
Example 69
Project: pyblish-win   Author: pyblish   File: test_itertools.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_product(self):
        for args, result in [
            ([], [()]),                     # zero iterables
            (['ab'], [('a',), ('b',)]),     # one iterable
            ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]),     # two iterables
            ([range(0), range(2), range(3)], []),           # first iterable with zero length
            ([range(2), range(0), range(3)], []),           # middle iterable with zero length
            ([range(2), range(3), range(0)], []),           # last iterable with zero length
            ]:
            self.assertEqual(list(product(*args)), result)
            for r in range(4):
                self.assertEqual(list(product(*(args*r))),
                                 list(product(*args, **dict(repeat=r))))
        self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
        self.assertRaises(TypeError, product, range(6), None)

        def product1(*args, **kwds):
            pools = map(tuple, args) * kwds.get('repeat', 1)
            n = len(pools)
            if n == 0:
                yield ()
                return
            if any(len(pool) == 0 for pool in pools):
                return
            indices = [0] * n
            yield tuple(pool[i] for pool, i in zip(pools, indices))
            while 1:
                for i in reversed(range(n)):  # right to left
                    if indices[i] == len(pools[i]) - 1:
                        continue
                    indices[i] += 1
                    for j in range(i+1, n):
                        indices[j] = 0
                    yield tuple(pool[i] for pool, i in zip(pools, indices))
                    break
                else:
                    return

        def product2(*args, **kwds):
            'Pure python version used in docs'
            pools = map(tuple, args) * kwds.get('repeat', 1)
            result = [[]]
            for pool in pools:
                result = [x+[y] for x in result for y in pool]
            for prod in result:
                yield tuple(prod)

        argtypes = ['', 'abc', '', xrange(0), xrange(4), dict(a=1, b=2, c=3),
                    set('abcdefg'), range(11), tuple(range(13))]
        for i in range(100):
            args = [random.choice(argtypes) for j in range(random.randrange(5))]
            expected_len = prod(map(len, args))
            self.assertEqual(len(list(product(*args))), expected_len)
            self.assertEqual(list(product(*args)), list(product1(*args)))
            self.assertEqual(list(product(*args)), list(product2(*args)))
            args = map(iter, args)
            self.assertEqual(len(list(product(*args))), expected_len) 
Example 70
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 4 votes vote down vote up
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
    """Generate some lorem impsum for the template."""
    from jinja2.constants import LOREM_IPSUM_WORDS
    from random import choice, randrange
    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ','
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += '.'
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p = u' '.join(p)
        if p.endswith(','):
            p = p[:-1] + '.'
        elif not p.endswith('.'):
            p += '.'
        result.append(p)

    if not html:
        return u'\n\n'.join(result)
    return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) 
Example 71
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: utils.py    Apache License 2.0 4 votes vote down vote up
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
    """Generate some lorem impsum for the template."""
    from jinja2.constants import LOREM_IPSUM_WORDS
    from random import choice, randrange
    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ','
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += '.'
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p = u' '.join(p)
        if p.endswith(','):
            p = p[:-1] + '.'
        elif not p.endswith('.'):
            p += '.'
        result.append(p)

    if not html:
        return u'\n\n'.join(result)
    return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) 
Example 72
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 4 votes vote down vote up
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
    """Generate some lorem ipsum for the template."""
    from jinja2.constants import LOREM_IPSUM_WORDS
    from random import choice, randrange
    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ','
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += '.'
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p = u' '.join(p)
        if p.endswith(','):
            p = p[:-1] + '.'
        elif not p.endswith('.'):
            p += '.'
        result.append(p)

    if not html:
        return u'\n\n'.join(result)
    return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) 
Example 73
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: azure_rm_virtualmachine.py    MIT License 4 votes vote down vote up
def create_default_storage_account(self):
        '''
        Create a default storage account <vm name>XXXX, where XXXX is a random number. If <vm name>XXXX exists, use it.
        Otherwise, create one.

        :return: storage account object
        '''
        account = None
        valid_name = False

        # Attempt to find a valid storage account name
        storage_account_name_base = re.sub('[^a-zA-Z0-9]', '', self.name[:20].lower())
        for i in range(0, 5):
            rand = random.randrange(1000, 9999)
            storage_account_name = storage_account_name_base + str(rand)
            if self.check_storage_account_name(storage_account_name):
                valid_name = True
                break

        if not valid_name:
            self.fail("Failed to create a unique storage account name for {0}. Try using a different VM name."
                      .format(self.name))

        try:
            account = self.storage_client.storage_accounts.get_properties(self.resource_group, storage_account_name)
        except CloudError:
            pass

        if account:
            self.log("Storage account {0} found.".format(storage_account_name))
            self.check_provisioning_state(account)
            return account
        sku = self.storage_models.Sku(self.storage_models.SkuName.standard_lrs)
        sku.tier = self.storage_models.SkuTier.standard
        kind = self.storage_models.Kind.storage
        parameters = self.storage_models.StorageAccountCreateParameters(sku, kind, self.location)
        self.log("Creating storage account {0} in location {1}".format(storage_account_name, self.location))
        self.results['actions'].append("Created storage account {0}".format(storage_account_name))
        try:
            poller = self.storage_client.storage_accounts.create(self.resource_group, storage_account_name, parameters)
            self.get_poller_result(poller)
        except Exception as exc:
            self.fail("Failed to create storage account: {0} - {1}".format(storage_account_name, str(exc)))
        return self.get_storage_account(storage_account_name) 
Example 74
Project: flasky   Author: RoseOu   File: utils.py    MIT License 4 votes vote down vote up
def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
    """Generate some lorem impsum for the template."""
    from jinja2.constants import LOREM_IPSUM_WORDS
    from random import choice, randrange
    words = LOREM_IPSUM_WORDS.split()
    result = []

    for _ in range(n):
        next_capitalized = True
        last_comma = last_fullstop = 0
        word = None
        last = None
        p = []

        # each paragraph contains out of 20 to 100 words.
        for idx, _ in enumerate(range(randrange(min, max))):
            while True:
                word = choice(words)
                if word != last:
                    last = word
                    break
            if next_capitalized:
                word = word.capitalize()
                next_capitalized = False
            # add commas
            if idx - randrange(3, 8) > last_comma:
                last_comma = idx
                last_fullstop += 2
                word += ','
            # add end of sentences
            if idx - randrange(10, 20) > last_fullstop:
                last_comma = last_fullstop = idx
                word += '.'
                next_capitalized = True
            p.append(word)

        # ensure that the paragraph ends with a dot.
        p = u' '.join(p)
        if p.endswith(','):
            p = p[:-1] + '.'
        elif not p.endswith('.'):
            p += '.'
        result.append(p)

    if not html:
        return u'\n\n'.join(result)
    return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result)) 
Example 75
Project: core   Author: lifemapper   File: swap.py    GNU General Public License v3.0 4 votes vote down vote up
def swapRandomize(matrix, num_swaps, max_tries=MAX_TRIES_WITHOUT_SWAP):
    """Randomize a PAM matrix using the Gotelli swap method

    Args:
        matrix (:obj: Matrix): A Lifemapper matrix object with binary elements
        num_swaps (:obj: int): The number of swaps to perform
        max_tries (:obj: int): The maximum number of attempts to swap before
            failing

    Todo:
        Allow num_swaps to be specified as a percentage of the matrix fill
    """
    mtx_headers = matrix.getHeaders()
    swapped_mtx = matrix.data.copy().astype(int)
    counter = 0
    num_tries = 0
    row_len, col_len = matrix.data.shape

    #num_tries is a safety to kill the loop if nothing is ever found
    while counter < num_swaps and num_tries < max_tries:
        num_tries += 1
        column1 = randrange(0, col_len)
        column2 = randrange(0, col_len)
        row1 = randrange(0, row_len)
        while column2 == column1:
            column2 = randrange(0, col_len)
        first_corner = swapped_mtx[row1][column1]
        if first_corner ^ swapped_mtx[row1][column2]:
            row2 = randrange(0, row_len)
            while row2 == row1:
                    row2 = randrange(0, row_len)
            if ((first_corner ^ swapped_mtx[row2][column1]) and
                 (not(first_corner) ^ swapped_mtx[row2][column2])):
                    swapped_mtx[row1][column2] = first_corner
                    swapped_mtx[row2][column1] = first_corner
                    swapped_mtx[row2][column2] = not(first_corner)
                    swapped_mtx[row1][column1] = not(first_corner)
                    counter += 1
                    num_tries = 0
    if num_tries >= max_tries:
        raise Exception(
            'Reached maximum number of tries without finding suitable swap')

    return Matrix(swapped_mtx, headers=mtx_headers) 
Example 76
Project: plugin.program.steam.streaming   Author: Drakulix   File: service.py    MIT License 4 votes vote down vote up
def launch_client(self, ip, port, auth, app_id, instance):
        print "launching"

        path = xbmcaddon.Addon().getSetting("prescript")
        if xbmcaddon.Addon().getSetting("use_scripts") == "true" and path != None and path != "":
            import subprocess
            subprocess.call("\""+path+"\" \""+str(app_id)+"\"", shell=True)

        def do_the_rest(ip, port, auth, app_id):
            from stream_api import streaming_client

            import xbmcaddon
            command_args = []
            if xbmcaddon.Addon().getSetting("hwaccel") == "false":
                command_args.append("--nohwaccel")
            if xbmcaddon.Addon().getSetting("vsync") == "false":
                command_args.append("--novsync")
                command_args.append("--framerate")
                command_args.append(xbmcaddon.Addon().getSetting("framerate"))
            if xbmcaddon.Addon().getSetting("fullscreen") == "false":
                command_args.append("--windowed")
            command_args.append("--quality")
            command_args.append(str(int(xbmcaddon.Addon().getSetting("quality"))+1))
            if xbmcaddon.Addon().getSetting("autobitrate") == "false":
                command_args.append("--bitrate")
                command_args.append(xbmcaddon.Addon().getSetting("bitrate"))
            if xbmcaddon.Addon().getSetting("debug") == "true":
                command_args.append("--showdebugoverlay")

            streaming_client.run_client(ip, port, auth, command_args)

            path2 = xbmcaddon.Addon().getSetting("postscript")
            if xbmcaddon.Addon().getSetting("use_scripts") == "true" and path2 != None and path2 != "":
                import subprocess
                subprocess.call("\""+path2+"\" \""+str(app_id)+"\"", shell=True)

        t = threading.Thread(target=do_the_rest, args=(ip, port, auth, app_id))
        t.daemon = True
        t.start()

        xbmc.sleep(1000)
        #reconnect to workaround some wired issues. (One fail to start a game results in additional failures and seems to be only fixable by a reconnect)
        #self.client_id = random.randrange(0, sys.maxint) #new random id, yey^2
        #self.connected_steam_instances[instance].reconnect(self.client_id) #force reconnect
        #while not self.connected_steam_instances[instance].authenticated:
        #    xbmc.sleep(1000)
        return None 
Example 77
Project: FarWest1789   Author: ginoingras   File: FW1789_V001.py    GNU General Public License v3.0 4 votes vote down vote up
def loadStageSprites(StageNumber):
	groupBandits = pygame.sprite.Group()
	for idx in range(StagesBandits[StageNumber][0]):
		varRand = random.randrange(0, 3)
		if varRand == 0:
			bandit1 = threat("Dalton-Williamb.png", StagesBandits[StageNumber][1], StagesBandits[StageNumber][2])
		elif varRand == 1:
			bandit1 = threat("bandit2b.png", StagesBandits[StageNumber][1], StagesBandits[StageNumber][2])
		elif varRand >= 2:
			bandit1 = threat("bandit4b.png", StagesBandits[StageNumber][1], StagesBandits[StageNumber][2])
		groupBandits.add(bandit1)

	groupFarmers = pygame.sprite.Group()
	for idx in range(StagesFarmers[StageNumber][0]):
		varRand = random.randrange(0, 2)
		if varRand == 0:
			farmer1 = threat("farmerb.png", StagesFarmers[StageNumber][1], 1) #image, speed, life
		elif varRand >= 1:
			farmer1 = threat("Dalton-Ma-b.png", StagesFarmers[StageNumber][1], 1) #image, speed, life
		groupFarmers.add(farmer1)

	listCaravans = []
	groupCaravans =  pygame.sprite.Group()
	for idx in range(StagesDiligences[StageNumber][0]):
		varRand = random.randrange(0, 4)
		if varRand == 0:
			caravan1 = caravan("caravan4a.png", 90)
		elif varRand == 1:
			caravan1 = caravan("caravan2b.png", 90)
		elif varRand == 2:
			caravan1 = caravan("caravan1c.png", 90)
		elif varRand >= 3:
			caravan1 = caravan("caravan3b.png", StagesDiligences[StageNumber][1]) #image, speed
		
		listCaravans.append(caravan1)
		groupCaravans.add(caravan1)

	# add grenades bonus for diligences to hit
	groupBonusGrenades = pygame.sprite.Group()
	for idx in range(StagesGrenades[StageNumber][0]):
		bonus1 = threat("Grenade-6b.png", StagesGrenades[StageNumber][1], 1) #image, speed, life
		groupBonusGrenades.add(bonus1)

	# add as bullets bonus 
	groupBonusBullets = pygame.sprite.Group()
	for idx in range(StagesBullets[StageNumber][0]):
		#bonus1 = threat("bullets-2b.png", StagesBullets[StageNumber][1], 1) #image, speed, life
		bonus1 = threat("bullets-b.png", StagesBullets[StageNumber][1], 1) #image, speed, life
		groupBonusBullets.add(bonus1)
		
	return groupBandits, groupFarmers, listCaravans, groupCaravans, groupBonusGrenades, groupBonusBullets

################################################# 
Example 78
Project: SunshineCTF-2019-Public   Author: HackUCF   File: app.py    MIT License 4 votes vote down vote up
def generate_exam():
    solutions = []
    # start html ordered list
    exam = '<ol type="1">\n'

    # Generate 20 questions
    for n in range(20):
        # generate individual quesiton string
        prob = "{} {} {}".format(random.randrange(1,200), 
                                 random.choice(["+","-","*","/"]), 
                                 random.randrange(1,200)) 
        # add problem to ordered list in html
        exam += "<li>{}</li>\n".format(prob)

        # choose what the answer for the problem will be (A-D = 0 - 3)
        # keep track of all answers in solutions array
        answer = random.randrange(4)
        solutions.append(answer)

        # Add ordered list for all multiple choice options
        exam += '<ol type="A">\n'
        # generate multiple choice options
        for i in range(4):
            # right answer
            if i == answer:
                a = eval(prob.replace("/","//"))
            # random wrong answers
            else:
                a = random.randrange(20000)
            # place choice in html
            exam += '<li>{}</li>\n'.format(a)
        # ened options list
        exam += '</ol>\n'

    # end quesitons list
    exam += "</ol>\n"
    # add form to submit filled out scantron
    exam += '''
   <h1>Upload Solution</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''
    return (exam, solutions) 
Example 79
Project: CapsAttnNet   Author: rstager   File: gen_images.py    MIT License 4 votes vote down vote up
def generator(width_height=(28, 28), object_scale=0.5,
              width_shift_range=0.25, height_shift_range=0.25,
              scale_range=1, rotate_range=0,
              count=1,
              objects = default_objects):
    """Generate images and labels in a keras data generator style. Image contains simple objects
    in a random pose.

    Args:
        width_height (tuple(width,height)     : The size of the generated images.
        object_scale (float)        : The size objects contained in the images as fraction of image width
        width_shift_range(float)    : The range of random shift in object x position as fraction of image width
        height_shift_range(float)   : The range of random shift in object y position as fraction of image height
        scale_range(float)          : The range of scales of the objects. Objects are scaled (from x to 1)
        rotate_range(float)         : The range of rotation in degrees
        objects (list)              : A description of objects that can be contained in the images.

    Returns:
        generator                   :  The keras data generator. Firt argument is the image. Second is
                                       the pose (class,x offset,y offset, scale, rotation)
    """
    viewer = Viewer(*width_height)
    while 1:
        viewer.geoms=[]
        y_truth=[]
        for i in range(count):
            cls=random.randrange(len(objects))
            obj=[]
            for g,x,y,s,r in objects[cls][2]:
                r*=(np.pi/180)
                if g in 'B':
                    geom = FilledPolygon([(-0.5,-0.5), (0.5,-0.5), (0.5,0.5), (-0.5,0.5)])
                elif g in 'T':
                    geom = FilledPolygon(([(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5)]))
                elif g in 'C':
                    geom=make_circle(radius=1, res=30)
                geom.add_attr(Transform(translation=(x, y), rotation=r, scale=s))
                geom.add_attr(Transform(scale=(objects[cls][1],objects[cls][1])))
                geom.set_color(.8,.6,.4)
                obj.append(geom)

            x= random.uniform(-width_shift_range,width_shift_range)
            y= random.uniform(-height_shift_range,height_shift_range)
            s= random.uniform(scale_range,1)
            r=random.uniform(-rotate_range,rotate_range)*(np.pi/180)
            ss=s*object_scale * width_height[0]

            geom= Compound(obj)
            geom.add_attr(Transform(translation=((x + 0.5)*width_height[0], (y+0.5)*width_height[1]),
                                    rotation=r,scale=(ss,ss)))
            viewer.add_geom(geom)
            y_truth.append((cls,x,y,s,r))

        img=viewer.render(return_rgb_array = True)
        yield (img, np.array(y_truth)) 
Example 80
Project: python-lifx-sdk   Author: smarthall   File: client.py    MIT License 4 votes vote down vote up
def __init__(self, broadcast='255.255.255.255', address='0.0.0.0', discoverpoll=60, devicepoll=5):
        """
        The Client object is responsible for discovering lights and managing
        incoming and outgoing packets. This is the class most people will use to
        interact with the lights.

        :param broadcast: The address to broadcast to when discovering devices.
        :param address: The address to receive packet on.
        :param discoverpoll: The time in second between attempts to discover new bulbs.
        :param devicepoll: The time is seconds between polls to check if devices still respond.
        """

        # Get Transport
        self._transport = network.NetworkTransport(address=address, broadcast=broadcast)

        # Arguments
        self._discoverpolltime = discoverpoll
        self._devicepolltime = devicepoll

        # Generate Random Client ID
        self._source = random.randrange(1, pow(2, 32) - 1)

        # Start packet sequence at zero
        self._sequence = 0

        # Storage for devices
        self._devices = {}
        self._groups = {}
        self._locations = {}

        # Install our service packet handler
        pktfilter = lambda p:p.protocol_header.pkt_type == protocol.TYPE_STATESERVICE
        self._transport.register_packet_handler(self._servicepacket, pktfilter)

        # Install the group packet handler
        pktfilter = lambda p:p.protocol_header.pkt_type == protocol.TYPE_STATEGROUP
        self._transport.register_packet_handler(self._grouppacket, pktfilter)

        # Install the location packet handler
        pktfilter = lambda p:p.protocol_header.pkt_type == protocol.TYPE_STATELOCATION
        self._transport.register_packet_handler(self._locationpacket, pktfilter)

        # Send initial discovery packet
        self.discover()

        # Start polling threads
        self._discoverpoll = util.RepeatTimer(discoverpoll, self.discover)
        self._discoverpoll.daemon = True
        self._discoverpoll.start()
        self._devicepoll = util.RepeatTimer(devicepoll, self.poll_devices)
        self._devicepoll.daemon = True
        self._devicepoll.start()