Python random.randint() Examples

The following are code examples for showing how to use random.randint(). 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: simulated-annealing-tsp   Author: chncyhn   File: anneal.py    MIT License 6 votes vote down vote up
def anneal(self):
        """
        Execute simulated annealing algorithm.
        """
        # Initialize with the greedy solution.
        self.cur_solution, self.cur_fitness = self.initial_solution()

        print("Starting annealing.")
        while self.T >= self.stopping_temperature and self.iteration < self.stopping_iter:
            candidate = list(self.cur_solution)
            l = random.randint(2, self.N - 1)
            i = random.randint(0, self.N - l)
            candidate[i : (i + l)] = reversed(candidate[i : (i + l)])
            self.accept(candidate)
            self.T *= self.alpha
            self.iteration += 1

            self.fitness_list.append(self.cur_fitness)

        print("Best fitness obtained: ", self.best_fitness)
        improvement = 100 * (self.fitness_list[0] - self.best_fitness) / (self.fitness_list[0])
        print(f"Improvement over greedy heuristic: {improvement : .2f}%") 
Example 2
Project: kicker-module   Author: EvanTheB   File: backend.py    GNU General Public License v3.0 6 votes vote down vote up
def test_concurrent():
    # run this in multiple processes,
    # the idea is that collisions will crash, but not munge data
    import random
    import time
    if not os.path.exists("tmp_test_con.log"):
        init_data_file("tmp_test_con.log")

    k = LadderData("tmp_test_con.log")
    # test concurrent log writes
    thread = str(random.randint(0, 100))
    print thread
    for x in range(100):
        time.sleep(0.01)
        k.add_player(thread + '_' + str(x))

    p, g = k.get_players_games()
    print len(p) 
Example 3
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 6 votes vote down vote up
def _capture2dImage(self, cameraId):
        # Capture Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture2DImage_{}".format(random.randint(1,10000000000))

        clientRGB = self.video_service.subscribeCamera(strName, cameraId, AL_kVGA, 11, 10)
        imageRGB = self.video_service.getImageRemote(clientRGB)

        imageWidth   = imageRGB[0]
        imageHeight  = imageRGB[1]
        array        = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image.
        image_name_2d = "images/img2d-" + str(self.imageNo2d) + ".png"
        im.save(image_name_2d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo2d += 1
        im.show()

        return 
Example 4
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    MIT License 6 votes vote down vote up
def _capture3dImage(self):
        # Depth Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture3dImage_{}".format(random.randint(1,10000000000))


        clientRGB = self.video_service.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 10)
        imageRGB = self.video_service.getImageRemote(clientRGB)

        imageWidth  = imageRGB[0]
        imageHeight = imageRGB[1]
        array       = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)
        # Save the image.
        image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png"
        im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo3d += 1
        im.show()

        return 
Example 5
Project: pepper-robot-programming   Author: maverickjoy   File: remote_voice.py    MIT License 6 votes vote down vote up
def _capture2dImage(self, cameraId):
        # Capture Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture2DImage_{}".format(random.randint(1,10000000000))


        clientRGB = self.video.subscribeCamera(strName, cameraId, AL_kVGA, 11, 10)
        imageRGB = self.video.getImageRemote(clientRGB)

        imageWidth = imageRGB[0]
        imageHeight = imageRGB[1]
        array = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image inside the images foler in pwd.
        image_name_2d = "images/img2d-" + str(self.imageNo2d) + ".png"
        im.save(image_name_2d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo2d += 1
        im.show()

        return 
Example 6
Project: pepper-robot-programming   Author: maverickjoy   File: remote_voice.py    MIT License 6 votes vote down vote up
def _capture3dImage(self):
        # Depth Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture3dImage_{}".format(random.randint(1,10000000000))

        clientRGB = self.video.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 15)
        imageRGB = self.video.getImageRemote(clientRGB)

        imageWidth = imageRGB[0]
        imageHeight = imageRGB[1]
        array = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image inside the images foler in pwd.
        image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png"
        im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo3d += 1
        im.show()

        return 
Example 7
Project: pepper-robot-programming   Author: maverickjoy   File: remote_terminal.py    MIT License 6 votes vote down vote up
def _capture3dImage(self):
        # Depth Image in RGB

        # WARNING : The same Name could be used only six time.
        strName = "capture3dImage_{}".format(random.randint(1,10000000000))

        clientRGB = self.video.subscribeCamera(strName, AL_kDepthCamera, AL_kQVGA, 11, 15)
        imageRGB = self.video.getImageRemote(clientRGB)

        imageWidth = imageRGB[0]
        imageHeight = imageRGB[1]
        array = imageRGB[6]
        image_string = str(bytearray(array))

        # Create a PIL Image from our pixel array.
        im = Image.frombytes("RGB", (imageWidth, imageHeight), image_string)

        # Save the image inside the images foler in pwd.
        image_name_3d = "images/img3d-" + str(self.imageNo3d) + ".png"
        im.save(image_name_3d, "PNG") # Stored in images folder in the pwd, if not present then create one
        self.imageNo3d += 1
        im.show()

        return 
Example 8
Project: pyblish-win   Author: pyblish   File: dbtables.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __new_rowid(self, table, txn) :
        """Create a new unique row identifier"""
        unique = 0
        while not unique:
            # Generate a random 64-bit row ID string
            # (note: might have <64 bits of true randomness
            # but it's plenty for our database id needs!)
            blist = []
            for x in xrange(_rowid_str_len):
                blist.append(random.randint(0,255))
            newid = struct.pack('B'*_rowid_str_len, *blist)

            if sys.version_info[0] >= 3 :
                newid = newid.decode("iso8859-1")  # 8 bits

            # Guarantee uniqueness by adding this key to the database
            try:
                self.db.put(_rowid_key(table, newid), None, txn=txn,
                            flags=db.DB_NOOVERWRITE)
            except db.DBKeyExistError:
                pass
            else:
                unique = 1

        return newid 
Example 9
Project: WebTeam   Author: shashankrnr32   File: Encryption.py    MIT License 6 votes vote down vote up
def writeConfig(username,password):
    colorama.init(autoreset=True)
    Ukey = random.randint(10,50)
    Pkey = random.randint(10,50)
    username = username.encode()
    password = password.encode()
    Ukey,Pkey,username,password = encrypt(Ukey,Pkey,username,password)
    storage = open('config.txt','w')
    storage.write(str(base64.b64encode(str(Ukey).encode()),'UTF-8'))
    storage.write('\n')
    storage.write(str(base64.b64encode(str(Pkey).encode()),'UTF-8'))
    storage.write('\n')
    storage.write(str(username,'UTF-8'))
    storage.write('\n')
    storage.write(str(password,'UTF-8'))
    storage.close()
    print(colorama.Fore.GREEN+'[SUCCESS] Credentials Saved') 
Example 10
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: posixemulation.py    Apache License 2.0 6 votes vote down vote up
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
Example 11
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: posixemulation.py    Apache License 2.0 6 votes vote down vote up
def rename(src, dst):
        # Try atomic or pseudo-atomic rename
        if _rename(src, dst):
            return
        # Fall back to "move away and replace"
        try:
            os.rename(src, dst)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
            old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
            os.rename(dst, old)
            os.rename(src, dst)
            try:
                os.unlink(old)
            except Exception:
                pass 
Example 12
Project: ieml   Author: IEMLdev   File: tools.py    GNU General Public License v3.0 6 votes vote down vote up
def _build_graph_object(self, primitive, mode, max_nodes=6):
        nodes = {primitive()}
        modes = set()

        if max_nodes < 2:
            raise ValueError('Max nodes >= 2.')

        result = set()

        for i in range(random.randint(2, max_nodes)):
            while True:
                s, a, m = random.sample(nodes, 1)[0], primitive(), mode()
                if a in nodes or m in nodes or a in modes:
                    continue

                nodes.add(a)
                modes.add(m)

                result.add((s, a, m))
                break
        return result 
Example 13
Project: ieml   Author: IEMLdev   File: tools.py    GNU General Public License v3.0 6 votes vote down vote up
def random_usl(dictionary, rank_type=None):
    global _ieml_object_generator
    if _ieml_object_generator is None:
        _ieml_object_generator = RandomPoolIEMLObjectGenerator(dictionary, level=Text, pool_size=100)

    if rank_type and not isinstance(rank_type, IEMLSyntaxType):
        raise ValueError('The wanted type for the generated usl object must be a IEMLType, here : '
                         '%s'%rank_type.__class__.__name__)

    if not rank_type:
        i = random.randint(0, 10)
        if i < 4:
            rank_type = _ieml_objects_types[i]
        else:
            rank_type = Text

    return usl(_ieml_object_generator.from_type(rank_type)) 
Example 14
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: diningPhilosophers.py    MIT License 6 votes vote down vote up
def run(self):
    print("{} has started thinking".format(threading.currentThread().getName()))
    while True:
      time.sleep(random.randint(1,5))
      print("{} has finished thinking".format(threading.currentThread().getName()))
      self.leftFork.acquire()
      time.sleep(random.randint(1,5))
      try:
        print("{} has acquired the left fork".format(threading.currentThread().getName()))

        self.rightFork.acquire()
        try:
          print("{} has attained both forks, currently eating".format(threading.currentThread().getName()))
        finally:
          self.rightFork.release()   
          print("{} has released the right fork".format(threading.currentThread().getName()))
      finally:
        self.leftFork.release()
        print("{} has released the left fork".format(threading.currentThread().getName())) 
Example 15
Project: iSDX   Author: sdn-ixp   File: tmgr.py    Apache License 2.0 6 votes vote down vote up
def send (args):
    if len(args) != 4:
        log.error('MM:00 SEND: ERROR usage: send source bind_addr dest_addr dest_port')
        return
    src = args[0]
    baddr = args[1]
    daddr = args[2]
    dport = args[3]
    if src not in hosts:
        log.error('MM:00 SEND: ERROR unknown src ' + src)
        return
    rand = str(random.randint(1000000000, 9999999999)) # must be 10 characters
    r = generic(src, 'TEST', 'test ' + rand + ' ' + baddr + ' ' + daddr + ' ' + str(dport) + '\n')
    if r is None:   # connection error
        return
    log.info('MM:' + src + ' SEND: ' + r.strip()) 
Example 16
Project: Automated-Social-Annotation   Author: acadTags   File: SVM.py    MIT License 6 votes vote down vote up
def display_for_qualitative_evaluation(modelToEval, evalX_embedded, evalX,evalY,vocabulary_index2word,vocabulary_index2word_label):
    prediction_str=""
    #generate the doc indexes same as for the deep learning models.
    number_examples=len(evalY)
    rn_dict={}
    rn.seed(1) # set the seed to produce same documents for prediction
    batch_size=128
    for i in range(0,500):
        batch_chosen=rn.randint(0,number_examples//batch_size)
        x_chosen=rn.randint(0,batch_size)
        #rn_dict[(batch_chosen*batch_size,x_chosen)]=1
        rn_dict[batch_chosen*batch_size+x_chosen]=1
        
    y_pred = modelToEval.predict(evalX_embedded)
    y_true = np.asarray(evalY)    
    for i in range(len(y_pred)):
        label_predicted = np.where(y_pred[i]==1)[0]
        if rn_dict.get(i) == 1:
            doc = 'doc: ' + ' '.join(display_results(evalX[i],vocabulary_index2word))
            pred = 'prediction-svm: ' + ' '.join(display_results(label_predicted,vocabulary_index2word_label))
            get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
            label = 'labels: ' + ' '.join(display_results(get_indexes(1,evalY[i]),vocabulary_index2word_label))
            prediction_str = prediction_str + '\n' + doc + '\n' + pred + '\n' + label + '\n'
    
    return prediction_str 
Example 17
Project: unicorn-hat-hd   Author: pimoroni   File: snake.py    MIT License 5 votes vote down vote up
def reset(self):
        c_x, c_y = self.canvas.get_shape()
        c_y -= 3

        self.position = (random.randint(0, c_x - 1), random.randint(0, c_y - 1))

        self.score = random.randint(0, len(self.colours) - 1)

        self.eaten = False 
Example 18
Project: Gurux.DLMS.Python   Author: Gurux   File: GXSecure.py    GNU General Public License v2.0 5 votes vote down vote up
def generateChallenge(cls):
        #  Random challenge is 8 to 64 bytes.
        #  Texas Instruments accepts only 16 byte long challenge.
        #  For this reason challenge size is 16 bytes at the moment.
        len_ = 16
        result = [None] * len_
        pos = 0
        while pos != len_:
            result[pos] = random.randint(0, 255)
            pos += 1
        return result 
Example 19
Project: stream-finder   Author: kiwiholmberg   File: twitch.py    MIT License 5 votes vote down vote up
def get_live_stream(channel):
    client_id = get_client_id()
    token, sig = get_token_and_signature(channel, client_id)
    url = USHER_API.format(channel=channel, sig=sig, token=token, random=random.randint(0, 1E7))
    r = requests.get(url)
    m3u8_obj = m3u8.loads(r.text)
    return m3u8_obj 
Example 20
Project: fs_image   Author: facebookincubator   File: test_repo_sizer.py    MIT License 5 votes vote down vote up
def _set_expected_unions(self, *expected_unions: Iterable[Set[str]]):
        for union in expected_unions:
            size = randint(10**3, 10**6)
            self.final_size += size
            for chk in union:
                self.sizes[chk] = size

    # Helper to reason about tests - pass sets of strings (corresponding to
    # checksums) and it will make a sizer with those synonym sets. Also call
    # _set_expected_unions prior to this, to set what the final result of the
    # merge is expected to be 
Example 21
Project: Hasami   Author: Lokraan   File: output_generator.py    MIT License 5 votes vote down vote up
def get_color() -> hex:
	"""
	Generates  a random hexadecimal color and returns it


	Returns:
		hexadecimal color

	"""
	r = lambda: random.randint(0, 255)
	
	color = (r(), r(), r())
	color = (int("0x%02x%02x%02x" % color, 16))
	
	return color 
Example 22
Project: mycode   Author: gmraabe   File: first-oop.py    GNU General Public License v3.0 5 votes vote down vote up
def roll(self):
    self.dice = [] # clears current dice
    for i in range(3):
      self.dice.append(randint(1,6)) 
Example 23
Project: mycode   Author: gmraabe   File: cheatdice.py    GNU General Public License v3.0 5 votes vote down vote up
def roll(self):                     # rolls 3 dice that value between 1 and 6
    self.dice = []                    
    for i in range(3):               
      self.dice.append(randint(1,6)) 
Example 24
Project: book_parser   Author: colorblank   File: Exiaoshuo.py    MIT License 5 votes vote down vote up
def get_soup(any_url):
    # 传入链接
    # 返回BeautifulSoup对象
    result = requests.get(any_url, headers=header[random.randint(0, 4)])
    html_doc = result.content
    try:
        html_doc = html_doc.decode('utf-8')
    except UnicodeDecodeError:
        html_doc = html_doc.decode('gbk')
    soup = BeautifulSoup(html_doc, 'html.parser')
    return soup 
Example 25
Project: book_parser   Author: colorblank   File: template.py    MIT License 5 votes vote down vote up
def get_soup(any_url):
    # 传入链接
    # 返回BeautifulSoup对象
    result = requests.get(any_url, headers=header[random.randint(0, 4)])
    html_doc = result.content
    try:
        html_doc = html_doc.decode('utf-8')
    except UnicodeDecodeError:
        html_doc = html_doc.decode('gbk')
    soup = BeautifulSoup(html_doc, 'html.parser')
    return soup 
Example 26
Project: book_parser   Author: colorblank   File: Wenxuemi.py    MIT License 5 votes vote down vote up
def get_soup(any_url):
    # 传入链接
    # 返回BeautifulSoup对象
    result = requests.get(any_url, headers=header[random.randint(0, 4)])
    html_doc = result.content
    try:
        html_doc = html_doc.decode('utf-8')
    except UnicodeDecodeError:
        html_doc = html_doc.decode('gbk')
    soup = BeautifulSoup(html_doc, 'html.parser')
    return soup 
Example 27
Project: explirefit   Author: codogogo   File: data_helper.py    Apache License 2.0 5 votes vote down vote up
def create_corrupts(correct_train, correct_test, concept_dict, prev_dict, num_corrupt = 2, shuffle = True):
	concepts = list(concept_dict.values())
	train_corrupt = []
	test_corrupt = []
	current_dict = {}	

	merged = []
	merged.extend(correct_train)
	merged.extend(correct_test)

	for i in range(len(merged)):
		rel_str = merged[i][1] + "_" + merged[i][0]
		if rel_str not in prev_dict and rel_str not in current_dict:
			(train_corrupt if i < len(correct_train) else test_corrupt).append((merged[i][1], merged[i][0], "0"))
			current_dict[rel_str] = 1
		
		for j in range(num_corrupt - 1):
			c1 = concepts[random.randint(0, len(concepts) - 1)]
			c2 = concepts[random.randint(0, len(concepts) - 1)]
			rel_str = c1 + "_" + c2
			while(rel_str in prev_dict or rel_str in current_dict):
				c1 = concepts[random.randint(0, len(concepts) - 1)]
				c2 = concepts[random.randint(0, len(concepts) - 1)]
				rel_str = c1 + "_" + c2
			(train_corrupt if i < len(correct_train) else test_corrupt).append((c1, c2, "0"))
			current_dict[rel_str] = 1
			
	fdata_train = []
	fdata_train.extend(correct_train)
	fdata_train.extend(train_corrupt)
	
	fdata_test = []
	fdata_test.extend(correct_test)
	fdata_test.extend(test_corrupt)

	if shuffle:
		random.shuffle(fdata_train)
		random.shuffle(fdata_test)
	
	return (fdata_train, fdata_test) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_float.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_floatasratio(self):
        for f, ratio in [
                (0.875, (7, 8)),
                (-0.875, (-7, 8)),
                (0.0, (0, 1)),
                (11.5, (23, 2)),
            ]:
            self.assertEqual(f.as_integer_ratio(), ratio)

        for i in range(10000):
            f = random.random()
            f *= 10 ** random.randint(-100, 100)
            n, d = f.as_integer_ratio()
            self.assertEqual(float(n).__truediv__(d), f)

        R = fractions.Fraction
        self.assertEqual(R(0, 1),
                         R(*float(0.0).as_integer_ratio()))
        self.assertEqual(R(5, 2),
                         R(*float(2.5).as_integer_ratio()))
        self.assertEqual(R(1, 2),
                         R(*float(0.5).as_integer_ratio()))
        self.assertEqual(R(4728779608739021, 2251799813685248),
                         R(*float(2.1).as_integer_ratio()))
        self.assertEqual(R(-4728779608739021, 2251799813685248),
                         R(*float(-2.1).as_integer_ratio()))
        self.assertEqual(R(-2100, 1),
                         R(*float(-2100.0).as_integer_ratio()))

        self.assertRaises(OverflowError, float('inf').as_integer_ratio)
        self.assertRaises(OverflowError, float('-inf').as_integer_ratio)
        self.assertRaises(ValueError, float('nan').as_integer_ratio) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def zip_random_open_test(self, f, compression):
        self.make_test_archive(f, compression)

        # Read the ZIP archive
        with zipfile.ZipFile(f, "r", compression) as zipfp:
            zipdata1 = []
            with zipfp.open(TESTFN) as zipopen1:
                while True:
                    read_data = zipopen1.read(randint(1, 1024))
                    if not read_data:
                        break
                    zipdata1.append(read_data)

            self.assertEqual(''.join(zipdata1), self.data) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        datacount = randint(16, 64)*1024 + randint(1, 1024)
        self.data = ''.join(struct.pack('<f', random()*randint(-1000, 1000))
                            for i in xrange(datacount))

        # Make a source file with some lines
        with open(TESTFN, "wb") as fp:
            fp.write(self.data) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_long.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getran2(ndigits):
        answer = 0L
        for i in xrange(ndigits):
            answer = (answer << SHIFT) | random.randint(0, MASK)
        if random.random() < 0.5:
            answer = -answer
        return answer 
Example 32
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_race(self):
        # Issue #14632 refers.
        def remove_loop(fname, tries):
            for _ in range(tries):
                try:
                    os.unlink(fname)
                except OSError:
                    pass
                time.sleep(0.004 * random.randint(0, 4))

        del_count = 500
        log_count = 500

        for delay in (False, True):
            fd, fn = tempfile.mkstemp('.log', 'test_logging-3-')
            os.close(fd)
            remover = threading.Thread(target=remove_loop, args=(fn, del_count))
            remover.daemon = True
            remover.start()
            h = logging.handlers.WatchedFileHandler(fn, delay=delay)
            f = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s')
            h.setFormatter(f)
            try:
                for _ in range(log_count):
                    time.sleep(0.005)
                    r = logging.makeLogRecord({'msg': 'testing' })
                    h.handle(r)
            finally:
                remover.join()
                try:
                    h.close()
                except ValueError:
                    pass
                if os.path.exists(fn):
                    os.unlink(fn)


# Set the locale to the platform-dependent default.  I have no idea
# why the test does this, but in any case we save the current locale
# first and restore it at the end. 
Example 33
Project: backtrader-cn   Author: pandalibin   File: test_models.py    GNU General Public License v3.0 5 votes vote down vote up
def test_get_library_not_exist():
    lib_name = '{}{}'.format(RUN_TEST_LIBRARY, random.randint(1, 100))
    lib = models.get_library(lib_name)
    assert lib is None 
Example 34
Project: backtrader-cn   Author: pandalibin   File: test_models.py    GNU General Public License v3.0 5 votes vote down vote up
def test_get_or_create_library_not_exist():
    lib_name = '{}{}'.format(RUN_TEST_LIBRARY, random.randint(1, 100))
    lib = models.get_or_create_library(lib_name)
    assert isinstance(lib, arctic.store.version_store.VersionStore)

    models.drop_library(lib_name)
    assert models.get_library(lib_name) is None 
Example 35
Project: ChaoSlingr   Author: Optum   File: PortChange_Generatr.py    Apache License 2.0 5 votes vote down vote up
def addport(sgidnum):
    FromPort = randint(10000,65000)
    ToPort = FromPort + randint(0,5)
    Protocols = ["tcp", "udp"]
    Cidr = "0.0.0.0/0"
    PortPackage = {'IpProtocol': Protocols[randint(0,1)],
        'FromPort': FromPort,
        'ToPort': ToPort,
        'IpRanges': [{'CidrIp': Cidr}],
        'SecurityGroupId': sgidnum
    }
    return PortPackage

# get security group permissions 
Example 36
Project: ChaoSlingr   Author: Optum   File: PortChange_Generatr.py    Apache License 2.0 5 votes vote down vote up
def changeR(SGlist):
    sgid = randint(0,len(SGlist)-1)
    return SGlist[sgid]

# this function populates a list of security group id's that have the opt-in tag set to true 
Example 37
Project: yolov3-detector   Author: ccerhan   File: main.py    MIT License 5 votes vote down vote up
def load_labels(path):
    with open(path) as file:
        labels = [line.rstrip('\n') for line in file]
        colors = ['#{:06x}'.format(random.randint(0, 0xFFFFFF)) for i in range(len(labels))]
        return labels, colors 
Example 38
Project: wikilinks   Author: trovdimi   File: WikiBrowser.py    MIT License 5 votes vote down vote up
def __init__(self, html, resolution):

        QWebView.__init__(self)
        self.resolution = resolution
        self.finished = False
        self.out = "web2png.%i.png"%int(random.randint(0,1000))

        #self.web_view = QWebView()
        #self.css_file = QString('/home/ddimitrov/wikiwsd/data/wikipedia_css.css')
        #path = os.getcwd()

        #self.settings().setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True)
        #self.settings().setAttribute(QWebSettings.LocalContentCanAccessFileUrls, True)
        #self.web_view.settings().setUserStyleSheetUrl(QUrl.fromLocalFile("wikipedia_css.css"))

        #self.web_view.settings().setUserStyleSheetUrl(QUrl.fromLocalFile(QString('file:///home/ddimitrov/wikiwsd/wikipedia_css.css')))
        #print self.web_view.settings().userStyleSheetUrl()
        #self.web_view.settings().setAttribute(QWebSettings.AutoLoadImages, False)
        #self.web_view.settings().setAttribute(QWebSettings.JavascriptEnabled, False)
        #self.setCentralWidget(self.web_view)
        
        #self.resize(resolution[0], resolution[1])
        
        self.loadFinished.connect(self._load_finished)
        #self.loadProgress.connect(self._loadProgress)
        
        self.setHtml(html)
       
        #self.page_length = None
        #self.positions = None
        #self.out = "web2png.%i.png"%int(time.time()) 
Example 39
Project: automl-translation-tools   Author: GoogleCloudPlatform   File: autosplit.py    Apache License 2.0 5 votes vote down vote up
def _assign_ml_use(self):
    """Randomly assign a example type with current split ratio."""
    # Generate a random number between [0, total_size)
    example_index = random.randint(0, sum(self._example_counts.values()) - 1)
    int(random.random() * sum(self._example_counts.values()))

    for ml_use_value in _ML_USES:
      if example_index < self._example_counts[ml_use_value]:
        return ml_use_value
      example_index -= self._example_counts[ml_use_value]
    return MLUse.TRAIN 
Example 40
Project: slidoc   Author: mitotic   File: multiproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_random60(hex=False, integer=False):
    """Return "60-bit" randomness as 10 Base64URL characters (default) or 15 hex digits (or as an integer)
   Uses HMAC for safer randomness (using MD5 for speed)
    """
    randstr = struct.pack("Q", random.randint(0, (1 << 60)-1) )
    hmac_obj = hmac.new(str(get_random_hmac_key), randstr, digestmod=hashlib.md5)
    if integer:
        return struct.unpack("Q", hmac_obj.digest()[:8])[0]   # 64 bits of the MD5 HMAC
    elif hex:
        return hmac_obj.hexdigest()[:15]                   # 60 bits of the MD5 HMAC
    else:
        return b64url_encode(hmac_obj.digest()[:9])[:10]   # 60 bits of the MD5 HMAC 
Example 41
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_nonce(self, token, site_name='', userId=''):
        site_key = sliauth.gen_site_key(Options['root_auth_key'], site_name) if site_name else Options['root_auth_key']
        upload_key = sliauth.gen_hmac_token(site_key, 'upload:')
        if token != sliauth.gen_hmac_token(upload_key, 'nonce:'+userId):
            return None
        nonce = str(random.randint(10000001,99999999))
        self.user_nonces[site_name][userId] = nonce
        return nonce 
Example 42
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getSessionVersion(cls, sessionName, update=False):
        # TODO: Integrate this with separate session versioning in sessions_slidoc
        if not sessionName:
            return ''
        
        if not CommandOpts.session_versioning:
            return 'noversioning'

        if sessionName not in cls._sessionVersions:
            cls._sessionVersions[sessionName] = random.randint(100000,999999)*1000
        elif update:
            cls._sessionVersions[sessionName] += 1

        return str(cls._sessionVersions[sessionName]) 
Example 43
Project: slidoc   Author: mitotic   File: md2md.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_random_label(id_str=''):
    if id_str:
        return '%04d-%s' % (random.randint(0, 9999), id_str)
    else:
        return '%03d-%04d' % (random.randint(0, 999), random.randint(0, 9999)) 
Example 44
Project: slidoc   Author: mitotic   File: nb2md.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def rand_name():
    return '%03d-%04d' % (random.randint(0, 999), random.randint(0, 9999)) 
Example 45
Project: slidoc   Author: mitotic   File: sdproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def makeSeed(cls, val=None):
        return (val % cls.m) if val else random.randint(0,cls.m) 
Example 46
Project: slidoc   Author: mitotic   File: sdproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shuffleArray(array, randFunc=None):
    # Durstenfeld shuffle
    randFunc = randFunc or random.randint;
    for i in reversed(range(1,len(array))):
        j = randFunc(0, i)
        temp = array[i]
        array[i] = array[j]
        array[j] = temp
    return array 
Example 47
Project: slidoc   Author: mitotic   File: sdproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unsafeTriggerUpdates(sessionName, modCols, insertRows, startRow=3):
    # WARNING: Destructive testing of sheet updates. Use only on test sessions, NEVER on production sessions
    # Inserts random values in specified list of columns to trigger updates
    testSheet = getSheet(sessionName)
    headers = testSheet.getSheetValues(1, 1, 1, testSheet.getLastColumn())[0]
    nrows = testSheet.getLastRow() - startRow + 1
    retval = ''

    print("WARNING:unsafeTestUpdates: Destructive testing of sheet updates", sessionName, modCols, insertRows, file=sys.stderr)
    if modCols:
        randCols = []
        randVals = [[]]
        for m in range(nrows):
            randVals.append([])

        for j in range(len(modCols)):
            modCol = modCols[j]
            header = headers[modCol-1]
            randCols.append(header)
            randVals[0].append(header)
            for m in range(nrows):
                randValue = randomTime() if timeColumn(header) else random.randint(0,100)
                testSheet.getRange(startRow+m, modCol, 1, 1).setValue(randValue)
                randVals[m+1].append(randValue)

        f = io.BytesIO()
        pprint.pprint(randVals, stream=f)
        retval = f.getvalue()

    for j in range(len(insertRows)):
        randNum = random.randint(1111,9999)
        randId = 'I%d' % randNum
        if insertRows[j] > 3:
            randName = '%s%d' % (testSheet.getSheetValues(insertRows[j]-1, 1, 1, 1)[0][0], randNum)
        else:
            randName = '#name%d' % randNum
        testSheet.insertRowBefore(insertRows[j], randId);
        testSheet.getRange(insertRows[j], 1, 1, 2).setValues([[randName, randId]])

    return retval 
Example 48
Project: ieml   Author: IEMLdev   File: tools.py    GNU General Public License v3.0 5 votes vote down vote up
def text(self):
        return text(random.sample(self.propositions_pool, random.randint(1, 8))) 
Example 49
Project: ieml   Author: IEMLdev   File: test_ast.py    GNU General Public License v3.0 5 votes vote down vote up
def test_word_instanciation(self):
        w = word("U:")
        self.assertEqual(w, word('U:', literals=str(random.randint(0, 1000000000)))) 
Example 50
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: results.py    MIT License 5 votes vote down vote up
def multiplyByTwo(n):
  time.sleep(random.randint(1,2))
  return 2 * n