def genRandDestination():
    users = cm.user.objects.all()
    if users:
        randomUser = randomChoice(users)
        randomPretendAccountType = randomChoice(pretendAccountTypes)
        randomUser.addRecievingAccount(randomPretendAccountType)
        print("{} - destination added".format(randomUser.destination_set.last()))
Example #2
0
    def replace(self, value):
        if isinstance(value, list):
            for index in range(0, len(value)):
                if isinstance(value[index], str):
                    while -1 != value[index].find("*"):
                        value[index] = value[index].replace(
                            "*", randomChoice(self.passData), 1)
                    while -1 != value[index].find("$"):
                        value[index] = value[index].replace(
                            "$", randomChoice(self.passData_num), 1)
                elif isinstance(value[index], dict):
                    self.radom_replace(value[index])
                else:
                    pass

        elif isinstance(value, (int, float)):
            pass
            return value
        elif value is None:
            pass
            return value
        elif isinstance(value, dict):
            self.radom_replace(value)
        else:
            while -1 != value.find("*"):
                value = value.replace("*", randomChoice(self.passData), 1)
            while -1 != value.find("$"):
                value = value.replace("$", randomChoice(self.passData_num), 1)
        return value
def genRandSource():
    users = cm.user.objects.all()
    if users:
        randomUser = randomChoice(users)
        randomPretendAccountType = randomChoice(pretendAccountTypes)
        randomUser.addGivingAccount(randomPretendAccountType)
        print("{} - source added".format(randomUser.source_set.last()))
Example #4
0
def plot_random_faces(dataSetPath, jsonLabelsPath, numberToDisplay):
    fig = plt.figure(figsize=(20, 20))
    rows = floor(numberToDisplay / 5) + 1
    colums = 4

    with open(jsonLabelsPath) as jsonLabelFile:
        jsonData = jsonLoad(jsonLabelFile)

    dirs = [
        dir for dir in listdir(dataSetPath)
        if path.isdir(path.join(dataSetPath, dir))
    ]
    for i in range(numberToDisplay):
        # getting random dir for dictionary
        randomDir = randomChoice(dirs)
        dirPath = path.join(dataSetPath, randomDir)

        # getting files from randomed dir, then getting random file
        files = [
            file for file in listdir(dirPath)
            if path.isfile(path.join(dirPath, file)) and file.endswith(".jpg")
        ]
        randomFile = randomChoice(files)

        img = plt.imread(path.join(dirPath, randomFile))
        fig.add_subplot(rows, colums, i + 1).axis("Off")
        plt.imshow(img)

        # getting correct label for randomed file
        fx = jsonData[randomDir][randomFile]["x"]
        fy = jsonData[randomDir][randomFile]["y"]

        plt.scatter(x=[fx], y=[fy], c="r", s=5)

    plt.show()
 def handle(self, *args, **kwargs):
     ## These are functions below that modify the
     ## network in some way. Hopefully self explanitory.
     doables = [genRandUser,
                genRandChannel,
                genRandDestination,
                genRandSource,
                ]
     for i in range(0,kwargs['iterations']):
         print(i)
         randomChoice(doables)()
Example #6
0
def getpwd(len):
    password = []
    for i in range(0,int(len)):
        password.append(randomChoice(passData))
        password.append(randomChoice(passData1))
        password.append(randomChoice(passData2))
        password.append(randomChoice(passData3))
    x = 0
    p = ''
    while x != int(len):
        p = p + str(password[x])
        x += 1
    return p
Example #7
0
    def radom_replace_sum(self, json_params):
        if isinstance(json_params, dict):
            self.json_params = self.radom_replace(json_params)
        else:
            while -1 != json_params.find("*"):
                json_params = json_params.replace("*",
                                                  randomChoice(self.passData),
                                                  1)
            while -1 != json_params.find("$"):
                json_params = json_params.replace(
                    "$", randomChoice(self.passData_num), 1)
            self.json_params = json_params

        return self.json_params
Example #8
0
def stringKeyGenerator(length=16, use_alpha=False):
  key_set = '0123456789'

  if use_alpha:
    key_set = '0123456789ABCDEF'

  return ''.join(randomChoice(key_set) for x in range (length))
Example #9
0
def genpwd():
    password = []
    number = 2
    count = 0
    while count != number:
        password.append(randomChoice(passData))
        password.append(randomChoice(passData1))
        password.append(randomChoice(passData2))
        password.append(randomChoice(passData3))
        count += 1
    x = 0
    p = ''
    while x != len(password):
        p = p + str(password[x])
        x += 1
        #print(p)
    return p
Example #10
0
def chooseAction(epsilone, curr_state_idx, queue_model, Q):
    possible_jobs = queue_model.states_dict[curr_state_idx].jobs
    tmp = Q[curr_state_idx, possible_jobs]
    best_action = possible_jobs[np.argmin(Q[curr_state_idx, possible_jobs])]
    chosen_action = randomChoice(
        possible_jobs) if random() < epsilone else best_action

    return chosen_action, best_action
Example #11
0
 def __init__(self, language="english", max_wrong=5):
     self.max_wrong = max_wrong
     self.language = language.lower().strip()
     with open("./dictionaries/{}.txt".format(self.language)) as f:
         wordList = f.readlines()
     self.answer = randomChoice(wordList).upper().strip()
     self.blanks = ''.join(["_ "] * len(self.answer)).strip()
     self.guesses = set()
     self.wrong = frozenset(list(validLetters)).difference(list(
         self.answer))
Example #12
0
def genpwd():
    if get_management_configuration():
        pwdlengt = get_management_configuration()['lengthpwd']
    else:
        pwdlengt = 4
    password = []
    password.append(randomChoice(passData))
    password.append(randomChoice(passData1))
    password.append(randomChoice(passData2))
    password.append(randomChoice(passData3))
    for i in range(int(pwdlengt) - 4):
        password.append(randomChoice(seed))
    salt = ''.join(password)
    # x = 0
    # p = ''
    # while x != len(password):
    #     p = p + str(password[x])
    #     x += 1
    return salt
def generate(number):
    """Generate a random password, with the characters from characterlist """
    password = []
    number = int(number)
    count = 0
    while count != number:
        password.append(randomChoice(characters))
        count += 1
    #Turn password list into string and return
    return ''.join(password)
Example #14
0
def createRandomString(amount, chars, string=""):
    # Function to create a random string
    # Inputs:
    #   amount = integer | Defines the target length of the random string
    #   chars = string   | Defines the useable characters for the random string

    for i in range(charAmount):
        string += randomChoice(useableChars)

    return string
Example #15
0
def generate_answer(text):
    # NLU
    intent = get_intent(text)
    if intent is not None:
        return randomChoice(BOT_CONFIG['intents'][intent]['responses'])

    # Generative model
    get_random_answer = generate_random_answer(text)
    if get_random_answer is not None:
        return get_random_answer

    # Return failure phrase
    return get_failure_phrase()
Example #16
0
File: Siga.py Project: MWMAA/3x3
def compumoved(Board,currentPMark,otherPMark):

	moveOrigins = []
	moveDests = []

	for square in Board:
		if Board[square] == ' ':
			moveDests.append(square)
		elif Board[square] == currentPMark:
			moveOrigins.append(square)
		else:
			pass

	corners1 = {1,9}
	corners2 = {3,7}

	while True:
	
		moveOrigin = randomChoice(moveOrigins)
		moveDest = randomChoice(moveDests)
		moveSpace = moveDest - moveOrigin

		cornerJumps = {moveOrigin,moveDest} == corners1 or {moveOrigin,moveDest} == corners2
		normalJumps = (abs(moveSpace) == 6 or abs(moveSpace) == 2) and moveOrigin != 5
		ambitious = abs(moveSpace) == 7 or abs(moveSpace) == 5

		if ambitious:
			continue

		elif (normalJumps or cornerJumps) and Board[(moveDest + moveOrigin)/2] == otherPMark:
			continue

		else:
			Board[moveDest] = currentPMark
			Board[moveOrigin] = " "
			break

	del(corners1,corners2)
	return moveOrigin
Example #17
0
def transformText(text):
    new_text = ""
    # Prüfe jeden Buchstaben
    for letter in text:
        # Prüfe ob Buchstabe in Umwandlungstabelle vorhanden ist
        if letter in transformations.keys() and len(
                transformations[letter]) > 0:
            # Wähle eineen zufälliges Zeichen für den Buchstabem aus der Umwandlungstabelle
            new_text += randomChoice(transformations[letter])
        else:
            # Ist kein Zeichen für den Buchstaben vorhanden, lasse diesen stehen.
            new_text += letter
    return new_text
Example #18
0
 async def _launch(self):
     await channelSend("MATCH_INIT", self.__id, " ".join(self.playerPings))
     self.__accounts = AccountHander(self)
     self.__mapSelector = MapSelection(self)
     for i in range(len(self.__teams)):
         self.__teams[i] = Team(i, f"Team {i+1}", self)
         key = randomChoice(list(self.__players))
         self.__teams[i].addPlayer(TeamCaptain, self.__players.pop(key))
     self.__teams[0].captain.isTurn = True
     self.__status = MatchStatus.IS_PICKING
     await channelSend("MATCH_SHOW_PICKS",
                       self.__id,
                       self.__teams[0].captain.mention,
                       match=self)
Example #19
0
def gen(number):
    password = []
    number = int(number)
    count = 0
    print "\nGenerating password..."
    while count != number:
        password.append(randomChoice(passData))
        count += 1
    x = 0
    p = ''
    while x != len(password):
        p = p + str(password[x])
        x += 1    
    print "Password generated.",
    print "Here's your %s character password. Note that there may be spaces: %s" % (len(password), p)
def getNewName(length):
    picList = []
    choiceData = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2',
        '3', '4', '5', '6', '7', '8', '9', '0'
    ]

    count = 0
    while count != length:
        picList.append(randomChoice(choiceData))
        count += 1
    picNewName = string.join(picList).replace(" ", "")

    return picNewName
Example #21
0
def gen(number):
    password = []
    number = int(number)
    count = 0
    print "\nGenerating password..."
    while count != number:
        password.append(randomChoice(passData))
        count += 1
    x = 0
    p = ''
    while x != len(password):
        p = p + str(password[x])
        x += 1
    print "Password generated.",
    print "Here's your %s character password. Note that there may be spaces: %s" % (
        len(password), p)
Example #22
0
    def start(self):
        # Starts the Game
        self.clearScreen()
        print("""
█▀▀ █░░ █▀▀ █░░█ █▀▀ ░▀░ █▀▀   █▀▀ █░█ █▀▀█ █▀▀█ █▀▀ █▀▀ █▀▀
█▀▀ █░░ █▀▀ █░░█ ▀▀█ ▀█▀ ▀▀█   █▀▀ ▄▀▄ █░░█ █▄▄▀ █▀▀ ▀▀█ ▀▀█
▀▀▀ ▀▀▀ ▀▀▀ ░▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀   ▀▀▀ ▀░▀ █▀▀▀ ▀░▀▀ ▀▀▀ ▀▀▀ ▀▀▀
        """)
        print("©2018 Matt Fan")
        print(
            "\nThanks for playing my game! Eleusis is a game designed by Robert Abbott in 1956, where there's a secret rule, and players take turns placing cards onto a MAIN LINE that they think obey that rule."
        )
        print(
            "My implementation is a streamlined, multi-player version (based on Eleusis Express variant) where players take turns placing cards to match a rule that's procedurally generated at the beginning of the round."
        )
        print("More info in the README. Enjoy!\n")
        print(
            "First, let's figure out who's playing. One at a time, have each player type their name below."
        )
        players = []
        addingPlayers = True
        while addingPlayers:
            playerName = input("Name: ")
            if playerName not in players:
                players.append(playerName)
            else:
                print('Sorry, that name is already taken.')
            makingChoice = True
            while makingChoice:
                choice = input('Do you want to add another player? (y/n)')
                if choice == 'y' or choice == 'Y':
                    makingChoice = False
                elif choice == 'n' or choice == 'N':
                    makingChoice = False
                    addingPlayers = False
                else:
                    print("I didn't recognize that command.")
        print("Great! Let's get started!")

        self.players = Players(players)

        self.initializeRound(randomChoice(
            self.rules))  # recursively calls new rounds until players quit
        self.clearScreen()
        print('\nThanks for playing Eleusis!')  # exit program
        sleep(2)
Example #23
0
    def _createWarpEffectEmitter(self) -> Emitter:
        """
        Random particle textures
        """
        texture0 = self._warpEffectTextures[0]
        texture2 = self._warpEffectTextures[2]

        e: Emitter = Emitter(
            center_xy=self._centerPosition,
            emit_controller=EmitterIntervalWithTime(DEFAULT_EMIT_INTERVAL, DEFAULT_EMIT_DURATION),
            particle_factory=lambda emitter: LifetimeParticle(
                filename_or_texture=randomChoice((texture0, texture2)),
                change_xy=rand_on_circle((0.0, 0.0), PARTICLE_SPEED_FAST),
                lifetime=DEFAULT_PARTICLE_LIFETIME,
                scale=DEFAULT_SCALE
            )
        )

        return e
Example #24
0
def compquick():
    # general loop for quick match game mode
    while True:

        # player one loop + error catching
        while True:
            player_one = input("Play rock, paper, or scissors: ").lower()
            if player_one == "leave":  # forcequit in quick match mode player one input
                print("The programme will finish now.")
                quit()
            elif player_one != "rock" and player_one != "scissors" and player_one != "paper":
                print("Oops! Try again!")
                continue
            else:
                break

        # computer loop + error catching
        player_two = randomChoice(["rock", "paper", "scissors"])
        print("Computer played", player_two, "!")

        # general loop victory conditions + messages
        if player_one == "rock" and player_two == "paper":
            print("Paper beats rock! Computer won.")
            break
        if player_one == "rock" and player_two == "scissors":
            print("Rock beats scissors! You won.")
            break
        if player_one == "paper" and player_two == "rock":
            print("Paper beats rock! You won.")
            break
        if player_one == "paper" and player_two == "scissors":
            print("Scissors beat paper! Computer won.")
            break
        if player_one == "scissors" and player_two == "rock":
            print("Rock beats scissors! Computer won.")
            break
        if player_one == "scissors" and player_two == "paper":
            print("Scissors beat paper! You won.")
            break
        if player_one == player_two:
            print("It's a draw!")
            break
Example #25
0
 def initializeRound(self, rule):
     self.roundActive = True
     self.winner = None
     self.rule = rule
     self.deck = Deck(
         int(len(self.players) * self.STARTING_HAND_SIZE / 40) +
         1)  # Determine how many decks to fold in to start
     self.line = Line()
     Rule.setLine(self.line)
     for player in self.players:
         player.hand = Hand()
         for n in range(0, self.STARTING_HAND_SIZE):
             player.hand.addCard(self.deck.deal())
     self.line.addToMain(self.deck.deal())
     while True:  # Keep cycling player turns until someone wins
         self.playTurn(self.players.nextPlayer())
         if self.roundActive == False:
             self.clearScreen()
             print(
                 f"\n{self.winner.name} has WON this round!\nThe rule was {self.rule.name}\n"
             )
             print('Cumulative scores for the entire game:')
             ranked = sorted(self.players.getPlayers(),
                             key=lambda k: k.score,
                             reverse=True)
             for player in ranked:
                 print(f"    {player.name}    :   {player.score}")
             print(
                 f"\n{ranked[0].name} is leading for the game, with {ranked[0].score} points\n"
             )
             makingChoice = True
             while makingChoice:
                 choice = input('Do you want to play another round? (y/n)')
                 if choice == 'y' or choice == 'Y':
                     self.initializeRound(randomChoice(
                         self.rules))  # Call a new round.
                     makingChoice = False  # Otherwise, exit.
                 elif choice == 'n' or choice == 'N':
                     return None
                 else:
                     print("I didn't recognize that command.")
             return None
Example #26
0
#!/bin/env python
from random import choice as randomChoice
from time import sleep
from subprocess import call

notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
noteMods = ['sharp', 'flat']

while True:
    note = randomChoice(notes)
    mod = randomChoice(noteMods)

    if randomChoice([True, False]):
        note = "%s-%s" % (note, mod)

    call(['say', note])
    sleep(3)
Example #27
0
    def compround():
        # general loop in normal game mode round
        rc = 1  # round counter
        plonesc = 0  # player one score
        pltwosc = 0  # player one score
        print(
            "If you want to finish and get results before completing all rounds, type 'get results'."
        )  # info about early results
        while True:
            # player one loop + error catching
            if rc > usr_round_nmb:
                break
            while True:
                while True:
                    print("Round", rc)  # print round number
                    player_one = input(
                        "Play rock, paper, or scissors: ").lower()
                    if player_one == "get results":  # break if early results requested
                        break
                    if player_one == "leave":  # forcequit in normal game mode player one input
                        print("The programme will finish now.")
                        quit()
                    if player_one != "rock" and player_one != "scissors" and player_one != "paper":
                        print("Oops! Try again!")
                        continue
                    else:
                        break

                # go straight to results, ignore computer
                if player_one == "get results":
                    break

                # computer loop + error catching
                player_two = randomChoice(["rock", "paper", "scissors"])
                print("Computer played", player_two, "!")

                # general loop scoring conditions + messages
                if rc > usr_round_nmb or player_one == "Get results" or player_one == "get results":
                    break
                if player_one == "rock" and player_two == "paper":
                    print("Paper beats rock! Computer scores.")
                    pltwosc += 1  # computer scores round
                    break
                if player_one == "rock" and player_two == "scissors":
                    print("Rock beats scissors! You score.")
                    plonesc += 1  # you score round
                    break
                if player_one == "paper" and player_two == "rock":
                    print("Paper beats rock! You score.")
                    plonesc += 1
                    break
                if player_one == "paper" and player_two == "scissors":
                    print("Scissors beat paper! Computer scores.")
                    pltwosc += 1
                    break
                if player_one == "scissors" and player_two == "rock":
                    print("Rock beats scissors! Computer scores.")
                    pltwosc += 1
                    break
                if player_one == "scissors" and player_two == "paper":
                    print("Scissors beat paper! You score.")
                    plonesc += 1
                    break
                if player_one == player_two:
                    print("It's a draw! Nobody scores.")
                    break
                return plonesc, pltwosc

            rc += 1  # increments round number

            # evaluate scores after all rounds
            if rc > usr_round_nmb or player_one == "Get results" or player_one == "get results":
                if plonesc > pltwosc:
                    print("Congratulations! You won", str(plonesc), "to",
                          str(pltwosc) + "!")
                elif pltwosc > plonesc:
                    print("Tough luck! Computer won", str(pltwosc), "to",
                          str(plonesc) + "!")
                else:
                    print("You're both equally skilled. Draw!")
                break
Example #28
0
for square in Board:
    if Board[square] == ' ':
        moveDests.append(square)
    elif Board[square] == currentPMark:
        moveOrigins.append(square)
    else:
        pass

corners1 = {1, 9}
corners2 = {3, 7}

print('thinking...')

while True:

    moveOrigin = randomChoice(moveOrigins)
    print('mvorig: ' + str(moveOrigin))
    moveDest = randomChoice(moveDests)
    print('mvDst: ' + str(moveDest))
    moveSpace = moveDest - moveOrigin

    cornerJumps = {moveOrigin, moveDest} == corners1 or {moveOrigin, moveDest
                                                         } == corners2
    print('cornerJumps: ' + str(cornerJumps))
    normalJumps = abs(moveSpace) == 6 or abs(moveSpace) == 2
    print('normalJumps: ' + str(normalJumps))
    ambitious = abs(moveSpace) == 7 or abs(moveSpace) == 5
    print('ambitious: ' + str(ambitious))

    if ambitious:
        print('can\'t move this far!')
Example #29
0
def get_failure_phrase():
    return randomChoice(BOT_CONFIG['failure_phrases'])
Example #30
0
def genId(length=7):
    return ''.join(randomChoice(ascii_lowercase) for _ in range(length))
Example #31
0
#!/bin/env python
from random import choice as randomChoice
from time import sleep
from subprocess import call

notes = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
noteMods = ['sharp', 'flat']

while True:
  note = randomChoice(notes)
  mod  = randomChoice(noteMods)

  if randomChoice([True, False]):
    note = "%s-%s" % (note, mod)

  call(['say', note])
  sleep(3)
Example #32
0
 def getCompMove(self):
     """Pseudo-randomly generates a computer move and stores it as _compMove"""
     if self._compMove is not None:
         raise GameSequenceError("Computer has already gone!")
     self._compMove = randomChoice([move for move in self.Moves])
    def __randomDirection_(self) -> Direction:
        """

        Returns:  A random direction
        """
        return randomChoice(list(Direction))
Example #34
0
    def generate(self) -> MazeProtocol:
        # start our maze generator in the top left of the maze
        start = XY(0, 0)

        # init positionsStack to a new empty stack of type int
        self.__positionsStack = Stack[int]()

        # Convert the `start` position to the same cell's index in the maze, and push to the positions stack
        self.__positionsStack.push(
            # get the index of the `start` posotion
            self.__maze.getIndexFromCoordinates(start))

        # set the starting cell as visited
        self.__visitedOrNotCells[self.__positionsStack.peek()] = True

        # while the positions stack is not empty, so we automatically exit the loop when visited all cells and back at start
        while not self.__positionsStack.isEmpty():
            randomCellChoice: Optional[int] = None
            # this loop tries to find a random cell to visit out of the unvisited neighbours of the current cell
            while randomCellChoice is None:
                # if we've ran out of positions to backtrack to, and therefore made the entire maze
                if self.__positionsStack.isEmpty():
                    break

                # get a list of unvisited adjacent cells
                neighbourCells = self.__maze.getNeighboursOfCell(
                    # get the current position by peeking the stack.
                    # don't pop because we want the item to remain on the stack,
                    # so we can backtrach through it.
                    self.__positionsStack.peek())

                # Filter the neighbourCells by whether they've been visited or not
                # create a lambda to return whether or not a cell at index has been visited, but return the inverse because we are _filtering_ the cells!
                checkIsVisited: Callable[
                    [int],
                    bool] = lambda cellIndex: not self.__visitedOrNotCells[
                        cellIndex]
                # …and filter the neighbourCells by this lambda, and put it into the list `unvisitedWalls`
                unvisitedWalls = list(filter(checkIsVisited, neighbourCells))

                # check that there are unvisited walls
                if len(unvisitedWalls) > 0:
                    # choose a random wall
                    randomCellChoice = randomChoice(unvisitedWalls)
                    # set the next cell to visited
                    self.__visitedOrNotCells[randomCellChoice] = True
                else:
                    # all the cells here have been visited
                    # so back up to the last cell, by popping the positionsStack
                    self.__positionsStack.pop()

            # if the cell hasn't been chosen, and therefore we've explored the whole maze
            if randomCellChoice is None:
                # break so we can return the completed maze
                break

            # carve a passage through to the adjacent cell
            self.__maze.removeWallBetween(
                cellAIndex=self.__positionsStack.peek(),
                cellBIndex=randomCellChoice,
            )
            # push the choice to the positionsStack so it is our next one
            self.__positionsStack.push(randomCellChoice)

        return self.__maze