Python random.randint() Examples

The following are 30 code examples of random.randint(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module random , or try the search function .
Example #1
Source File: hiv.py    From indras_net with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, name, infected, infection_length, initiative,
                 coupling_tendency, condom_use, test_frequency, commitment,
                 coupled=False, coupled_length=0, known=False, partner=None):
        init_state = random.randint(0, 3)
        super().__init__(name, "wandering around", NSTATES, init_state)
        self.coupled = coupled
        self.couple_length = coupled_length
        self.partner = partner
        self.initiative = initiative
        self.infected = infected
        self.known = known
        self.infection_length = infection_length
        self.coupling_tendency = coupling_tendency
        self.condom_use = condom_use
        self.test_frequency = test_frequency
        self.commitment = commitment
        self.state = init_state
        self.update_ntype() 
Example #2
Source File: asthama_search.py    From pepper-robot-programming with 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 #3
Source File: remote_voice.py    From pepper-robot-programming with 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 #4
Source File: test_basic.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, methodName, prop_file="models/basic_for_test.props"):
    
        super().__init__(methodName=methodName)
    
        pa = props.read_props(MODEL_NM, prop_file)
        # if result:
        #     pa.overwrite_props_from_dict(result.props)
        # else:
        #     print("Oh-oh, no props to read in!")
        #     exit(1)
    
        # Now we create a minimal environment for our agents to act within:
        self.env = bm.BasicEnv(model_nm=MODEL_NM, props=pa)
    
        # Now we loop creating multiple agents
        #  with numbered names based on the loop variable:
        for i in range(pa.props.get("num_agents").val):
            self.env.add_agent(bm.BasicAgent(name="agent" + str(i),
                                        goal="acting up!"))
        self.env.add_agent(bm.BasicAgent(name="agent for tracking",
                                         goal="acting up!"))

        # self.env.n_steps(random.randint(10, 20)) 
Example #5
Source File: test_agent_pop.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def test_get_pop_data(self):
        report = True
        check_list = []
        for var in self.dic_for_reference:
            random_pop_data = random.randint(1,10)
            check_list.append(random_pop_data)
            for a in self.dic_for_reference[var][AGENTS]:
                self.agentpop.append(a)
            self.agentpop.vars[var][POP_DATA] = random_pop_data
        index = 0
        for var in self.agentpop.vars:
            result = self.agentpop.get_pop_data(var)
            if result != check_list[index]:
                report = False
                break
            index += 1

        self.assertEqual(report, True) 
Example #6
Source File: test_agent_pop.py    From indras_net with GNU General Public License v3.0 6 votes vote down vote up
def test_get_my_pop(self):
        report = True
        for var in self.dic_for_reference:
            for a in self.dic_for_reference[var][AGENTS]:
                self.agentpop.append(a)
        var = str(random.randint(0, 2))
        dummy_node = node.Node("dummy node")
        dummy_node.ntype = var
        self.agentpop.append(dummy_node)
        self.dic_for_reference[var][AGENTS].append(dummy_node)
        result = self.agentpop.get_my_pop(dummy_node)
        correct_pop = len(self.dic_for_reference[var][AGENTS])
        if result != correct_pop:
            report = False

        self.assertEqual(report, True) 
Example #7
Source File: remote_voice.py    From pepper-robot-programming with 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
Source File: anneal.py    From simulated-annealing-tsp with 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 #9
Source File: remote_terminal.py    From pepper-robot-programming with 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 #10
Source File: __init__.py    From EDeN with MIT License 6 votes vote down vote up
def random_optimize(GA, GB, n_iter=20):
    best_c = None
    best_order = None
    best_depth = None
    best_quality = -1
    for it in range(n_iter):
        c = random.randint(1, 7)
        order = random.randint(1, 10)
        depth = random.randint(1, 20)
        pairings = match(GA, GB, complexity=c, order=order, max_depth=depth)
        quality = compute_quality(GA, GB, pairings)
        if quality > best_quality:
            best_quality = quality
            best_c = c
            best_order = order
            best_depth = depth
    logging.debug('[random search] quality:%.2f c:%d o:%d d:%d' % (best_quality, best_c, best_order, best_depth))
    return best_quality, best_c, best_order, best_depth 
Example #11
Source File: asthama_search.py    From pepper-robot-programming with 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 #12
Source File: BinaryFuzz.py    From ALF with Apache License 2.0 5 votes vote down vote up
def _mutate_bytes(target_data, special=SPECIAL_BINFUZZ_VALUE):
    """
    This function applies :func:`~alf.fuzz._mutate_byte` to each byte in a given list
    :func:`~_mutate_bytes` returns a list of fuzzed bytes
    """
    return bytearray(_mutate_byte(b, random.randint(0, SINGLE_BYTE_OPS), special) for b in target_data)

################################################################################
# Classes
################################################################################ 
Example #13
Source File: BinaryFuzz.py    From ALF with Apache License 2.0 5 votes vote down vote up
def _select_active_fuzz_types(self):
        """
        This method is used to randomly disable different fuzz types on a per iteration basis.
        """
        type_count = len(self.fuzz_types)
        if type_count < 2:
            return
        self.active_fuzz_types = random.sample(self.fuzz_types, random.randint(1, type_count)) 
Example #14
Source File: PortChange_Generatr.py    From ChaoSlingr with 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 #15
Source File: BinaryFuzz.py    From ALF with Apache License 2.0 5 votes vote down vote up
def random_binfuzz_type():
    """
    This function will return a randomly chosen fuzz_type from ``BINFUZZ_*``.
    """
    return randint(0, BINFUZZ_N-1)


# takes an integer argument, returns an integer 
Example #16
Source File: ValueFuzz.py    From ALF with Apache License 2.0 5 votes vote down vote up
def random_intfuzz_type():
    """
    This function will return a randomly chosen fuzz_type from ``INTFUZZ_*``.
    """
    return randint(0, INTFUZZ_N-1)

################################################################################
# Classes
################################################################################ 
Example #17
Source File: PortChange_Generatr.py    From ChaoSlingr with 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 #18
Source File: test_models.py    From backtrader-cn with 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 #19
Source File: test_models.py    From backtrader-cn with 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 #20
Source File: tracking.py    From pedestrian-haar-based-detector with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, x, y, w, h, color=None, label=None):
		self.x = x
		self.y = y
		self.h = h
		self.myarray = []
		self.w = w
		if color is None:
			self.color = availablecolors[random.randint(0,len(availablecolors)-1)]
		else:
			self.color = color
		
		if label is None:
			self.label = availablenames[random.randint(0,len(availablenames)-1)]
		else:
			self.label = label 
Example #21
Source File: test_forestfire.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_n_step(self):
        announce('test_n_step')
        report = True
        period_before_run = self.env.period
        random_steps = random.randint(3,30)
        self.env.n_steps(random_steps)
        period_after_run = self.env.period
        if (period_before_run + random_steps) != period_after_run:
            report = False
        self.assertEqual(report, True) 
Example #22
Source File: ValueFuzz.py    From ALF with Apache License 2.0 5 votes vote down vote up
def random_strfuzz_type():
    """
    This function will return a randomly chosen fuzz_type from ``STRFUZZ_*``.
    """
    return randint(0, STRFUZZ_N-1) 
Example #23
Source File: asciiarts.py    From wafw00f with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def randomArt():

    woof = '''
                   '''+W+'''______
                  '''+W+'''/      \\
                 '''+W+'''(  Woof! )
                  '''+W+r'''\  ____/                      '''+R+''')
                  '''+W+''',,                           '''+R+''') ('''+Y+'''_
             '''+Y+'''.-. '''+W+'''-    '''+G+'''_______                 '''+R+'''( '''+Y+'''|__|
            '''+Y+'''()``; '''+G+'''|==|_______)                '''+R+'''.)'''+Y+'''|__|
            '''+Y+'''/ ('        '''+G+'''/|\                  '''+R+'''(  '''+Y+'''|__|
        '''+Y+'''(  /  )       '''+G+''' / | \                  '''+R+'''. '''+Y+'''|__|
         '''+Y+r'''\(_)_))      '''+G+'''/  |  \                   '''+Y+'''|__|'''+E+'''

                    '''+C+'~ WAFW00F : '+B+'v'+__version__+''' ~'''+W+'''
    The Web Application Firewall Fingerprinting Toolkit
    '''+E

    w00f = '''
                '''+W+'''______
               '''+W+'''/      \\
              '''+W+'''(  W00f! )
               '''+W+'''\  ____/
               '''+W+''',,    '''+G+'''__            '''+Y+'''404 Hack Not Found
           '''+C+'''|`-.__   '''+G+'''/ /                     '''+R+''' __     __
           '''+C+'''/"  _/  '''+G+'''/_/                       '''+R+'''\ \   / /
          '''+B+'''*===*    '''+G+'''/                          '''+R+'''\ \_/ /  '''+Y+'''405 Not Allowed
         '''+C+'''/     )__//                           '''+R+'''\   /
    '''+C+'''/|  /     /---`                        '''+Y+'''403 Forbidden
    '''+C+r'''\\/`   \ |                                 '''+R+'''/ _ \\
    '''+C+r'''`\    /_\\_              '''+Y+'''502 Bad Gateway  '''+R+'''/ / \ \  '''+Y+'''500 Internal Error
      '''+C+'''`_____``-`                             '''+R+'''/_/   \_\\

                        '''+C+'~ WAFW00F : '+B+'v'+__version__+''' ~'''+W+'''
        The Web Application Firewall Fingerprinting Toolkit
    '''+E

    arts = [woof, w00f]
    return arts[randint(0,1)] 
Example #24
Source File: bigbox.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def create_consumer(name, i, props=None):
    """
    Create consumers
    """
    spending_power = random.randint(50, 70)
    consumer_books = {"spending power": spending_power,
                      "last util": 0.0,
                      "item needed": get_rand_good_type()}
    return Agent(name + str(i), attrs=consumer_books, action=consumer_action) 
Example #25
Source File: test_api_endpoints.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_put_props(self):
        """
        Test whether we are able to put props
        """
        model_id = random.randint(0, 10)
        with app.test_request_context():
            rv = self.props.put(model_id)
        self.assertEqual(type(rv), dict) 
Example #26
Source File: test_api_endpoints.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_get_props(self):
        """
        See if we can get props.
        """
        model_id = random.randint(0, 10)
        rv = self.props.get(model_id)

        test_model_file = indra_dir + MODEL_FILE
        with open(test_model_file) as file:
            test_models_db = json.loads(file.read())["models_database"]

        with open(indra_dir + "/" + test_models_db[model_id]["props"]) as file:
            test_props = json.loads(file.read())

        self.assertEqual(rv, test_props) 
Example #27
Source File: test_fashion.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_n_step(self):
        announce('test_n_step')
        report = True
        period_before_run = self.env.period
        random_steps = random.randint(3,30)
        self.env.n_steps(random_steps)
        period_after_run = self.env.period
        if (period_before_run + random_steps) != period_after_run:
            report = False
        self.assertEqual(report, True) 
Example #28
Source File: test_gridang.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_n_step(self):
        announce('test_n_step')
        report = True
        period_before_run = self.env.period
        random_steps = random.randint(3,30)
        self.env.n_steps(random_steps)
        period_after_run = self.env.period
        if (period_before_run + random_steps) != period_after_run:
            report = False
        self.assertEqual(report, True) 
Example #29
Source File: test_wolfsheep.py    From indras_net with GNU General Public License v3.0 5 votes vote down vote up
def test_n_step(self):
        announce('test_n_step')
        report = True
        period_before_run = self.env.period
        random_steps = random.randint(3,30)
        self.env.n_steps(random_steps)
        period_after_run = self.env.period
        if (period_before_run + random_steps) != period_after_run:
            report = False
        self.assertEqual(report, True) 
Example #30
Source File: GXSecure.py    From Gurux.DLMS.Python with 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