Example #1
1
    def test_get_slab(self):
        s = self.get_structure("LiFePO4")
        gen = SlabGenerator(s, [0, 0, 1], 10, 10)
        s = gen.get_slab(0.25)
        self.assertAlmostEqual(s.lattice.abc[2], 20.820740000000001)

        fcc = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3), ["Fe"], [[0, 0, 0]])
        gen = SlabGenerator(fcc, [1, 1, 1], 10, 10)
        slab = gen.get_slab()
        gen = SlabGenerator(fcc, [1, 1, 1], 10, 10, primitive=False)
        slab_non_prim = gen.get_slab()
        self.assertEqual(len(slab), 6)
        self.assertEqual(len(slab_non_prim), len(slab) * 4)

        # Some randomized testing of cell vectors
        for i in range(1, 231):
            i = random.randint(1, 230)
            sg = SpaceGroup.from_int_number(i)
            if sg.crystal_system == "hexagonal" or (sg.crystal_system == "trigonal" and sg.symbol.endswith("H")):
                latt = Lattice.hexagonal(5, 10)
            else:
                # Cubic lattice is compatible with all other space groups.
                latt = Lattice.cubic(5)
            s = Structure.from_spacegroup(i, latt, ["H"], [[0, 0, 0]])
            miller = (0, 0, 0)
            while miller == (0, 0, 0):
                miller = (random.randint(0, 6), random.randint(0, 6), random.randint(0, 6))
            gen = SlabGenerator(s, miller, 10, 10)
            a, b, c = gen.oriented_unit_cell.lattice.matrix
            self.assertAlmostEqual(np.dot(a, gen._normal), 0)
            self.assertAlmostEqual(np.dot(b, gen._normal), 0)
Example #2
1
def scrape_keyword_result(keyword, useragent_list, start_url, result_dir):
    br = start_browser(useragent_list)
    br.get(start_url)
    all_result_list = []
    if "sorry/IndexRedirect" in br.current_url or "400" in br.title:
        br.quit()
        return None
    else:
        result_list = scrape_the_page(br)
        all_result_list.extend(result_list)
        time.sleep(random.randint(5, 10))
        while True:
            try:
                br.find_element_by_id("pnnext")
            # Google's next page button have id 'pnnext'
            # if we can not find it. we should have get all the pages
            except NoSuchElementException:
                break
            else:
                br.find_element_by_id("pnnext").click()
                result_list = scrape_the_page(br)
                all_result_list.extend(result_list)
                time.sleep(random.randint(5, 10))
        save_result_to_file(keyword, all_result_list, result_dir)
        br.quit()
        return True
Example #3
1
def computer_turn():
    print("\n\n===============\nCOMPUTER'S TURN\n===============")
    valid = False
    while valid == False:
        row = random.randint(0, 7)
        column = random.randint(0, 7)
        cell = pgrid[row][column]
        if cell == "X":
            continue
        valid = True
    pgrid[row][column] = "X"
    print("Computer targets row {0}, column {1}.".format(row, column))
    p(pgrid)
    if cell != 0:
        print("Hit! (ship {0})".format(cell))
        pshipcount[cell] -= 1
        if pshipcount[cell] == 0:
            print("The computer sunk your ship {0}.\n".format(cell))
            pshipcount[cell] == "X"
        pshipcount[0] -= 1
    else:
        print("Miss.")
    if pshipcount[0] == 0:
        print("\n******You have lost.******")
    else:
        input("Press <Enter> to continue.")
def randomqueries():
    insertData()
    queries = [
        "SELECT DISTINCT Issue from consumer_complaint;",
        "SELECT DISTINCT State from consumer_complaint;",
        'SELECT Complaint from consumer_complaint WHERE state="TX";',
        "SELECT COUNT(*) from consumer_complaint;",
    ]
    reader = downloadData()
    db = MySQLdb.connect(host="ENDPOINT ADDRESS", port=3306, db="DATABASE", user="USERNAME", passwd="PASSWORD")
    cursor = db.cursor()
    start_time = time.time()
    for x in range(999):
        random = randint(0, 3)
        cursor.execute(queries[random])
    print "Time taken to complete 1000 queries is"
    print (time.time() - start_time)

    start_time2 = time.time()
    for x in range(4999):
        random = randint(0, 3)
        cursor.execute(queries[random])
    print "Time taken to complete 5000 queries is"
    print (time.time() - start_time2)

    start_time3 = time.time()
    for x in range(19999):
        random = randint(0, 3)
        cursor.execute(queries[random])
    print "Time taken to complete 20000 queries is"
    print (time.time() - start_time3)
    cursor.execute("DROP TABLE consumer_complaint;")
    db.commit()
    db.close()
Example #5
1
    def test_success(self):
        settings_str = (
            """
[kittyconfig]
auth = tests.gittests.test_utils.AllAuth
[kittygit]
repo_dir = %s 
        """.strip()
            % self.test_dir
        )
        test_settings = fake_settings(settings_str)

        user = "user-%d" % random.randint(0, 100)
        repo_name = "repo-%d" % random.randint(0, 100)
        repo = "%s/%s.git" % (user, repo_name)
        with open("/dev/null", "w") as out_stream:
            with open("/dev/null", "w") as err_stream:
                streams = (sys.stdin, out_stream, err_stream)
                random_root_patterns = random.randint(1, 100)
                request = Request(user, "kitty-git create-repo 'repo'", test_settings, streams, random_root_patterns)
                settings = handlers.get_settings(request)
                full_repo_dir = utils.get_full_repo_dir(settings, user, repo_name)

                result = handlers.create_repo(request, repo_name)
        self.assertTrue(user in result.content["message"])
        self.assertTrue(repo_name in result.content["message"])
        self.assertTrue(os.path.isdir(full_repo_dir))
Example #6
1
def getNumberSets():
    """
    Author: AlexKasapis
    Create the 3x9 array filled with the number sets that will be used to fill
    the sudoku table. These will be 3 sets of 3 numbers, in 3 unique combinations.
    Final example can be:
    1 5 3 | 8 2 9 | 7 6 4
    5 3 1 | 2 9 8 | 6 4 7
    3 1 5 | 9 8 2 | 4 7 6
    """
    # Initialize the array, and fill the first row with 1-9
    numberSets = [[0 for i in range(9)] for i in range(3)]
    for i in range(9):
        numberSets[0][i] = i + 1
    # Shuffle the numbers of the first row
    for i in range(20):
        index1 = random.randint(0, 8)
        index2 = random.randint(0, 8)
        tempCell = numberSets[0][index1]
        numberSets[0][index1] = numberSets[0][index2]
        numberSets[0][index2] = tempCell
    # Create the combinations of the sets
    for i in range(2):  # Which row
        for j in range(3):  # Which combination
            tempSet = shuffleSet(numberSets, j)
            validSet = False
            while validSet == False:
                validSet = checkValidation(numberSets, tempSet, i + 1, j)
                if validSet == False:
                    tempSet = shuffleSet(numberSets, j)
            numberSets[i + 1][0 + 3 * j] = tempSet[0]
            numberSets[i + 1][1 + 3 * j] = tempSet[1]
            numberSets[i + 1][2 + 3 * j] = tempSet[2]
    return numberSets
Example #7
1
    def test_transfer_credit_with_credit(self):
        original_credit_balance = random.randint(5, 10)
        CreditLine.add_credit(
            original_credit_balance, account=self.subscription.account, subscription=self.subscription
        )
        original_balance = self.invoice.balance
        adjustment_amount = random.randint(1, 5)

        adjust_balance_form = AdjustBalanceForm(
            self.invoice,
            {
                "adjustment_type": "credit",
                "custom_amount": adjustment_amount,
                "method": CreditAdjustmentReason.TRANSFER,
                "note": "some text",
                "invoice_id": self.invoice.id,
            },
        )
        self.assertTrue(adjust_balance_form.is_valid())

        adjust_balance_form.adjust_balance()
        self.assertEqual(original_balance - adjustment_amount, self.invoice.balance)
        self.assertEqual(
            original_credit_balance - adjustment_amount,
            sum(credit_line.balance for credit_line in CreditLine.get_credits_for_invoice(self.invoice)),
        )
Example #8
1
def creerVirus(corps):
    global i
    x, y = 0, 0
    FENETRE = data.get_fenetre()

    if i == -1:
        x = random.randint(FENETRE[0][0], FENETRE[0][1] - 2 * data.get_objet("virus", "rayon"))
        y = random.randint(FENETRE[1][0], FENETRE[1][1] - 2 * data.get_objet("virus", "rayon"))

        game.creerObjet(
            corps,
            "virus0",
            x,
            y,
            data.get_objet("virus", "rayon"),
            data.get_objet("virus", "vitesse"),
            data.get_objet("virus", "angle"),
            data.get_objet("virus", "pushUp"),
            data.get_objet("virus", "pushDown"),
            data.get_objet("virus", "pushLeft"),
            data.get_objet("virus", "pushRight"),
            data.get_objet("virus", "limiteVitesse"),
            data.get_objet("virus", "acceleration"),
            math.pi / data.get_objet("virus", "anglePlus"),
            data.get_objet("virus", "mitoseTime"),
            None,
            [0, 0, 0],
            0,
            None,
        )
        i = 0
    return True
Example #9
0
File: pyre.py Project: Regaerd/Pyre
    def update(self):
        try:  # needed to draw last character, which will ERR
            for i in range(int(self.width / 9)):
                self.buffer[int((random.random() * self.width) + self.width * (self.height - 1))] = self.intensity

            for i in range(self.size):
                result = int(
                    (
                        self.buffer[i]
                        + self.buffer[i + 1]
                        + self.buffer[i + self.width]
                        + self.buffer[i + self.width + 1]
                    )
                    / 4
                )
                self.buffer[i] = result
                self.render(i, result)
        except:
            pass

        if self.random_change and not random.randint(0, 100):
            self.update_color(random.randint(0, self.kCOLOR_RANGE))

        if self.fluctuate_intensity:
            self.intensity = clamp(
                self.min_intensity, self.intensity + (1 if random.randint(0, 1) else -1), self.max_intensity
            )

        if self.verbose:
            self.stdscr.clrtoeol()
            self.stdscr.addstr(
                0, 0, "colors:{}, intensity:{}, height:{}".format(self.colors, self.intensity, self.height)
            )

        self.stdscr.refresh()
Example #10
0
def colorShuffle(array):
    rm4 = random.randint(0, len(array) - 1)
    rm7 = random.randint(0, 2)
    array[rm4][0] = random.randint(0, 255)
    array[rm4][1] = random.randint(0, 255)
    array[rm4][2] = random.randint(0, 255)
    array[rm4][3] = random.random()
Example #11
0
    def checkAdddd(self, img):
        colorList = [[[0 for k in xrange(16)] for j in xrange(16)] for i in xrange(16)]
        # img = cv2.imread('test3.png')
        n = 0
        imgInfo = img.shape
        # print 'imgInfo', imgInfo
        for i in xrange((imgInfo[0] * imgInfo[1]) / 100):
            n += 1
            x = random.randint(0, imgInfo[0] - 1)
            y = random.randint(0, imgInfo[1] - 1)
            color = img[x, y].tolist()
            colorList[color[0] / 16][color[1] / 16][color[2] / 16] += 1
        # print color, int(color[0])/16, color[1]/16, color[2]/16

        N = 0
        for i in xrange(16):
            for j in xrange(16):
                for k in xrange(16):
                    if colorList[i][j][k] > 0:
                        N += 1
        # print N
        if N >= 85:
            boolAd = True
        else:
            boolAd = False
        return boolAd
Example #12
0
    def next(self):
        keys = PentatonicKeyboard().notes
        stretch_length = random.randint(2, 5)
        left_low = random.randint(40, 70)
        left_range = random.randint(1, 2)
        left = HSeq(list(keys).__getslice__(left_low, left_low + left_range))
        right = HSeq(list(keys).__getslice__(20, 50))

        note1 = Wandering(keys)
        duration1 = Wandering(range(2, 8))
        velocity1 = Randomized(range(20, 127))

        note2 = Wandering(left)
        duration2 = Randomized(range(0, len(left)))
        velocity2 = Wandering(range(70, 90))

        note3 = note2.echo()
        duration3 = Randomized(range(2, 12))
        velocity3 = Wandering(range(20, 127))

        finger1 = Finger(length=1160, note=note1, duration=duration1, velocity=velocity1)
        self.hand = [finger1]
        x = 160
        # player.play([loop([finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x),finger1.next(x)])])
        try:
            player.play([output])
        except Exception as e:
            print e
Example #13
0
    def test_fail(self):
        settings_str = (
            """
[kittyconfig]
auth = tests.gittests.test_utils.AllAuth
[kittygit]
repo_dir = %s 
        """.strip()
            % self.test_dir
        )
        test_settings = fake_settings(settings_str)

        user = "user-%d" % random.randint(0, 100)
        repo_name = "repo-%d" % random.randint(0, 100)
        repo = "%s/%s.git" % (user, repo_name)
        streams = (sys.stdin, sys.stdout, sys.stderr)
        random_root_patterns = random.randint(1, 100)
        request = Request(user, "kitty-git create-repo 'repo'", test_settings, streams, random_root_patterns)
        settings = handlers.get_settings(request)
        full_repo_dir = utils.get_full_repo_dir(settings, user, repo_name)

        self.mox.StubOutWithMock(subprocess, "call")
        subprocess.call(
            args=["git", "--git-dir=.", "init", "--bare"], cwd=full_repo_dir, stdout=sys.stderr, close_fds=True
        ).AndReturn(random.randint(1, 100))

        self.assertRaises(NappingCatException, handlers.create_repo, request, repo_name)
def formCycle(v0):
    global count_us, count_e
    cycle = []
    cycle.append(v0)
    r = randint(0, len(smegnosty[v0]) - 1)
    v1 = smegnosty[v0][r]
    while v1 in used[v0]:
        r = randint(0, len(smegnosty[v0]) - 1)
        v1 = smegnosty[v0][r]
    used[v0].append(v1)

    count_us += 1
    if v1 == v0:
        return cycle
    else:
        cycle.append(v1)
    while True:
        r = randint(0, len(smegnosty[v1]) - 1)
        while smegnosty[v1][r] in used[v1]:
            r = randint(0, len(smegnosty[v1]) - 1)
        v0 = v1
        v1 = smegnosty[v1][r]
        used[v0].append(v1)
        count_us = count_us + 1
        if v1 == cycle[0]:
            return cycle
        else:
            cycle.append(v1)
Example #15
0
 def test_count_instance_attributes(self):
     cLen = random.randint(3, 10)
     listInst = [dtree.Instance([0] * cLen)] * random.randint(5, 10)
     cLenObserved = dtree.count_instance_attributes(listInst)
     self.assertEqual(cLen, cLenObserved)
     listInstJag = build_jagged_instances()
     self.assertTrue(dtree.count_instance_attributes(listInstJag) is None)
Example #16
0
def test_string_range(m, name, key, count):
    # test range
    for i in xrange(0, 1000):
        v1, v2 = random.randint(0, 1000), random.randint(0, 1000)
        if v1 == v2:
            continue
        vmin = min(v1, v2)
        vmax = max(v1, v2)
        vminstr = "%010d" % vmin
        vmaxstr = "%010d" % vmax
        ret, result = m.sortlist_range(name, key, MEMLINK_VALUE_ALL, vminstr, vmaxstr)
        if ret != MEMLINK_OK:
            print "sortlist range:", vmin, vmax
            print "sortlist range error:", ret, vmin, vmax
            return -1
        if result.count != vmax - vmin:
            print "sortlist range:", vmin, vmax
            print "sortlist range count error:", result.count, vmax - vmin
            return -1
        item = result.items
        i = vmin
        while item:
            if item.value != "%010d" % i:
                print "sortlist range value error:", item.value, i
                return -1
            item = item.next
            i += 1
Example #17
0
def createPlay(playdata):
    print "TODO"
    # get a cast of characters
    charbotsN = []
    print playdata.numChars
    print playdata.charVars
    charnum = playdata.numChars + random.randint(0, playdata.charVars / 2)
    print "Cast " + str(charnum)

    for i in range(0, charnum):
        j = random.randint(0, len(playdata.charList) - 1)
        if j not in charbotsN:
            charbotsN.append(j)
        else:
            i = i - 1
    print charbotsN
    charBots = []
    characters = []
    indexi = {}
    for j in charbotsN:
        charBots.append(makeBot(playdata.playName, playdata.charList[j].name))
        characters.append(playdata.charList[j])
    pos = 0
    script = ""
    # make scenes until done
    while pos < 1:
        scene = createScene(playdata, characters, pos, charBots, playdata.charList)
        script = script + scene["text"] + "\n"
        pos = pos + scene["scene"].length

    script = script + "\n\n\t\t\t END"

    return script
Example #18
0
    def test_operation_failed(self):
        test_dir = self.test_dir
        settings_str = (
            """
[kittyconfig]
auth = tests.gittests.test_utils.AllAuth
[kittygit]
repo_dir = %s 
        """.strip()
            % test_dir
        )
        test_settings = fake_settings(settings_str)

        repo_name = "something-%d" % random.randint(0, 100)
        full_repo_name = "random-user-%d/%s" % (random.randint(0, 100), repo_name)
        directory = "%s/%s.git" % (test_dir, full_repo_name)
        other_user = "random-user-%d" % random.randint(0, 100)
        with open("/dev/null", "w") as out_stream:
            with open("/dev/null", "w") as err_stream:
                streams = (sys.stdin, out_stream, err_stream)
                random_root_patterns = random.randint(1, 100)
                request = Request(other_user, "kitty-git fork", test_settings, streams, random_root_patterns)
                expected_dir = os.path.expanduser("%s/%s/%s.git" % (test_dir, other_user, repo_name))

                self.assertRaises(NappingCatException, handlers.fork_repo, request, full_repo_name)
                self.assertFalse(os.path.isdir(directory))
                self.assertFalse(os.path.isdir(expected_dir))
Example #19
0
    def test_operation_successful(self):
        test_dir = self.test_dir
        settings_str = (
            """
[kittyconfig]
auth = tests.gittests.test_utils.AllAuth
[kittygit]
repo_dir = %s 
        """.strip()
            % test_dir
        )
        test_settings = fake_settings(settings_str)

        repo_name = "something-%d" % random.randint(0, 100)
        full_repo_name = "random-user-%d/%s" % (random.randint(0, 100), repo_name)

        directory = "%s/%s.git" % (test_dir, full_repo_name)
        with open("/dev/null", "w") as output:
            operations.create_repository("git", output, output, output, directory)

        other_user = "random-user-%d" % random.randint(0, 100)
        with open("/dev/null", "w") as out_stream:
            with open("/dev/null", "w") as err_stream:
                streams = (sys.stdin, out_stream, err_stream)
                random_root_patterns = random.randint(1, 100)
                request = Request(other_user, "kitty-git fork", test_settings, streams, random_root_patterns)
                expected_dir = os.path.expanduser("%s/%s/%s.git" % (test_dir, other_user, repo_name))
                result = handlers.fork_repo(request, full_repo_name)

        self.assertTrue(isinstance(result, Response))
        self.assertTrue(repo_name in result.content["message"])
        self.assertTrue(os.path.isdir(directory))
        self.assertTrue(os.path.isdir(expected_dir))
Example #20
0
    def test_bad_repo_raises_bad_parameter(self):
        settings_str = (
            """
[kittyconfig]
auth = tests.gittests.test_utils.AllAuth
[kittygit]
repo_dir = %s 
        """.strip()
            % self.test_dir
        )
        test_settings = fake_settings(settings_str)
        repo = "blah/%d.git" % random.randint(0, 100)
        variants = (
            ("git-upload-pack '%s'", "-upload-pack "),
            ("git upload-pack '%s'", " upload-pack "),
            ("git-receive-pack '%s'", "-receive-pack "),
            ("git receive-pack '%s'", " receive-pack "),
        )

        streams = (sys.stdin, sys.stdout, sys.stderr)
        for cmd, action in variants:
            random_root_patterns = random.randint(1, 100)
            request = Request(
                "random-user-%d" % random.randint(0, 100), cmd % repo, test_settings, streams, random_root_patterns
            )
            self.assertRaises(KittyGitBadParameter, handlers.handle_git, request, action)
Example #21
0
def permutation_bulk(indiv, Optimizer):
    """Move function to perform Permutation of one atom based on atomlist
    Inputs:
        indiv = Individual class object to be altered
        Optimizer = Optimizer class object with needed parameters
    Outputs:
        indiv = Altered Individual class object
    """
    if "MU" in Optimizer.debug:
        debug = True
    else:
        debug = False
    if Optimizer.structure != "Defect":
        Optimizer.output.write(
            "WARNING: Crystal extended permutation attempted on non-Defect system. Skipping Mutation\n"
        )
    else:
        a1 = indiv.bulki[random.randint(0, indiv.bulki.get_number_of_atoms() - 1)]
        opts = [inds for inds in indiv.bulki if inds.symbol != a1.symbol]
        try:
            a2 = opts[random.randint(0, len(opts) - 1)]
        except ValueError:
            a2 = indiv.bulki[random.randint(0, indiv.bulki.get_number_of_atoms() - 1)]
            Optimizer.output.write("WARNING: Permutation Mutation attempted on single atom structure system\n")
        indiv.bulki[a1.index].symbol, indiv.bulki[a2.index].symbol = a2.symbol, a1.symbol
        Optimizer.output.write("Bulk Permutation Mutation performed on individuals bulk\n")
        Optimizer.output.write("Index = " + repr(indiv.index) + "\n")
        Optimizer.output.write(repr(a1.symbol) + " swapped with " + repr(a2.symbol) + "\n")
        Optimizer.output.write(repr(indiv.bulki) + "\n")
        muttype = "PB"
        if indiv.energy == 0:
            indiv.history_index = indiv.history_index + "m" + muttype
        else:
            indiv.history_index = repr(indiv.index) + "m" + muttype
    return indiv
Example #22
0
    def test_success_with_template_dir(self):
        settings_str = (
            """
[kittyconfig]
auth = tests.gittests.test_utils.AllAuth
[kittygit]
repo_dir = %s 
        """.strip()
            % self.test_dir
        )
        test_settings = fake_settings(settings_str)

        user = "user-%d" % random.randint(0, 100)
        repo_name = "repo-%d" % random.randint(0, 100)
        repo = "%s/%s.git" % (user, repo_name)
        with open("/dev/null", "w") as out_stream:
            with open("/dev/null", "w") as err_stream:
                streams = (sys.stdin, out_stream, err_stream)
                random_root_patterns = random.randint(1, 100)
                request = Request(user, "kitty-git create-repo 'repo'", test_settings, streams, random_root_patterns)
                settings = handlers.get_settings(request)
                full_repo_dir = utils.get_full_repo_dir(settings, user, repo_name)

                result = handlers.create_repo(request, repo_name, os.path.join(os.getcwd(), "tests/support"))
        self.assertTrue(user in result.content["message"])
        self.assertTrue(repo_name in result.content["message"])
        self.assertTrue(os.path.isdir(full_repo_dir))
        self.assertTrue(os.path.isfile("tests/support/hooks/post-commit"))
        import time

        time.sleep(1)  # pass the time for a bit for things to
        # flush to disk
        self.assertTrue(os.path.isfile("%s/hooks/post-commit" % full_repo_dir))
Example #23
0
def create_ship(size):
    while True:
        try:
            orientation = random.randint(1, 2)
            if orientation == 1:
                x = 1
                y = 0
            elif orientation == 2:
                x = 0
                y = 1
            pos1 = random.randint(0, 7)
            pos2 = random.randint(0, 7)
            cells = []
            for i in range(size):
                cells.append(cgrid[pos1 + (i * y)][pos2 + (i * x)])
            celltotal = 0
            if all([c == 0 for c in cells]):
                break
        except IndexError:
            next
    for i in range(size):
        cgrid[pos1 + (i * y)][pos2 + (i * x)] = size
    global cshipcount
    cshipcount[size] = size
    cshipcount[0] += size
Example #24
0
    def test_random(self):
        array = []
        alphabet_num = 100
        n = 10000
        freq = [0] * alphabet_num

        for i in range(n):
            c = random.randint(0, alphabet_num - 1)
            array.append(c)
            freq[c] += 1

        wa = WatArray()
        wa.Init(array)

        self.assertEqual(wa.alphabet_num(), alphabet_num)
        self.assertEqual(wa.length(), n)
        for i in range(alphabet_num):
            self.assertEqual(wa.Freq(i), freq[i])

        counts = [0] * alphabet_num
        for i in range(len(array)):
            c = array[i]

            self.assertEqual(wa.Lookup(i), c)
            s = 0
            for j in range(alphabet_num):
                if random.randint(0, 100 - 1) == 0:
                    self.assertEqual(wa.Rank(j, i), counts[j])
                    self.assertEqual(wa.RankLessThan(j, i), s)
                    self.assertEqual(wa.RankMoreThan(j, i), i - s - counts[j])
                s += counts[j]
            counts[c] += 1

            self.assertEqual(wa.Select(c, counts[c]), i)
 def nextStep(self, newScene=False):
     if newScene == True:
         self.next_step = 0
     else:
         if self.current_scene["order"] == "random":
             step = randint(0, len(self.current_scene["steps"]) - 1)
             while step == self.next_step:
                 step = randint(0, len(self.current_scene["steps"]) - 1)
             self.next_step = step
         else:
             if self.next_step < (len(self.current_scene["steps"]) - 1):
                 self.next_step += 1
             elif self.current_scene["repeat"] == True:
                 self.next_step = 0
             else:
                 return
     self.scene_updated = False
     self.hold_frames = (
         int(round(self.current_scene["steps"][self.next_step]["hold"] / self.config["frame_duration"])) + 1
     )
     self.fade_frames = int(
         round(self.current_scene["steps"][self.next_step]["fade"] / self.config["frame_duration"])
     )
     print (
         "Playing scene: %-30s Step: %02d/%02d"
         % (self.current_scene["name"], self.next_step + 1, len(self.current_scene["steps"]))
     )
def test4(count):
    print "*** test4 ***"

    lenx = 7
    leny = 21
    canvas = Canvas(lenx, leny)
    global strip
    strip = canvas.strip2D.strip
    strip.clear([40, 40, 40])

    while count > 0:
        strip.clear([0, 0, 0])
        x = random.randint(0, 6)
        y = random.randint(0, 20)
        cr = random.randint(0, 255)
        cg = random.randint(0, 255)
        cb = random.randint(0, 255)
        for r in range(4):
            canvas.circle(x, y, r, [cr, cg, cb])
            strip.artnet.send(canvas.strip2D.strip)
            time.sleep(1.0)
            count -= 1
        # canvas.strip2D.rotl();
        # strip.artnet.send(canvas.strip2D.strip);

    strip.artnet.close()
Example #27
0
def np_comparison_check(h2o_data, np_data, num_elements):
    """
    Check values achieved by h2o against values achieved by numpy

    :param h2o_data: an H2OFrame or H2OVec
    :param np_data: a numpy array
    :param num_elements: number of elements to compare
    :return: None
    """
    # Check for numpy
    try:
        imp.find_module("numpy")
    except ImportError:
        assert False, "failed comparison check because unable to import numpy"

    import numpy as np

    rows, cols = h2o_data.dim
    for i in range(num_elements):
        r = random.randint(0, rows - 1)
        c = random.randint(0, cols - 1)
        h2o_val = h2o_data[r, c]
        np_val = np_data[r, c] if len(np_data.shape) > 1 else np_data[r]
        if isinstance(np_val, np.bool_):
            np_val = bool(np_val)  # numpy haz special bool type :(
        assert (
            np.absolute(h2o_val - np_val) < 1e-5
        ), "failed comparison check! h2o computed {0} and numpy computed {1}".format(h2o_val, np_val)
Example #28
0
    def update(self):
        self.rect.x += self.change_x

        self.rect.y += self.change_y
        self.checkKeys()
        if self.rect.right > screen.get_width():
            self.rect.right = screen.get_width()
        elif self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.bottom > screen.get_height():
            self.rect.bottom = screen.get_height()
        elif self.rect.top < 0:
            self.rect.top = 0
        if pygame.sprite.groupcollide(enemySprites, playerSprites, 1, 0) and self.damaged == False:
            self.lives -= 1
            score.lives -= 1
            self.damaged = True
            enemySprites.add(EnemyShip(random.randint(0, screen.get_width())))
        elif pygame.sprite.groupcollide(enemyLasers, playerSprites, 1, 0) and self.damaged == False:
            self.lives -= 1
            score.lives -= 1
            self.damaged = True
            enemySprites.add(EnemyShip(random.randint(0, screen.get_width())))

        if self.damaged == True:
            self.damageTimer += 1
            if self.damageTimer == self.damageMax:
                self.damaged = False
                self.damageTimer = 0

        if self.lives == 0 and score.lives == 0:
            gameOver = True
Example #29
0
    def __generate_payouts(self, num_hills, hill_size):
        """ Compute several gaussians and build the payout map """
        hills = []
        for i in range(num_hills):
            cx = random.randint(0, self.width - 1)
            cy = random.randint(0, self.height - 1)
            sx = random.random() * hill_size + 1
            sy = random.random() * hill_size + 1
            theta = random.random() * math.pi
            hills.append(Gaussian2D((cx, cy), (sx, sy), theta))
            # Add a mirror image one too to make the map fair
            hills.append(Gaussian2D(self.__mirror(cx, cy), (sx, sy), theta + math.pi))

        # Sum all the hills
        money_payout_rates = [[0.0] * self.height for x in range(self.width)]
        for y in range(self.height):
            for x in range(self.width):
                money_payout_rates[x][y] = sum([h.value((x, y)) for h in hills])

        # Normalize the rates from 0->1
        max_payout = max([max(row) for row in money_payout_rates])
        min_payout = min([min(row) for row in money_payout_rates])
        for y in range(self.height):
            for x in range(self.width):
                offset = money_payout_rates[x][y] - min_payout
                money_payout_rates[x][y] = offset / (max_payout - min_payout)
                money_payout_rates[x][y] = int(1000 * money_payout_rates[x][y]) / 1000.0

        return money_payout_rates
Example #30
0
        def tbstim():
            yield reset.pulse(42)
            yield clock.posedge

            # only testing one peripheral, set the peripheral/slave
            # address to the first ...
            if isinstance(membus, Barebone):
                membus.per_addr.next = 1
                peraddr = 0
            else:
                peraddr = 0x10000

            yield clock.posedge

            for ii in range(args.num_loops):
                randaddr = randint(0, depth - 1) | peraddr
                randdata = randint(0, maxval - 1)
                testvals[randaddr] = randdata
                yield membus.writetrans(randaddr, randdata)
            yield clock.posedge

            for addr, data in testvals.items():
                yield membus.readtrans(addr)
                read_data = membus.get_read_data()
                assert read_data == data, "{:08X} != {:08X}".format(read_data, data)
            yield clock.posedge

            yield delay(100)
            raise StopSimulation