def generate_password(): """Returns a 23 character random string, with 3 special characters at the end""" if sys.version_info > (3, 6): import secrets # pylint: disable=import-error alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(20)) special = ''.join(secrets.choice(string.punctuation) for i in range(3)) return password + special else: raise ImportError("Generating passwords require python 3.6 or higher")
def main(): print('Welcome to Ascii-Me') print('Send me some letters and I will ascii them.') print('Please only send letters and spaces.') print('After the asciination, you need to de-asciinate what I send you and send the normal letters back.') s = sys.stdin.readline().rstrip() sys.stderr.write('{} received {}\n'.format(tag, s)) output_sentence(s) for i in range(loop_count): decode = ' '.join(secrets.choice(dictionary) for _ in range(sentence_len)).lower() sys.stderr.write('{} sending {} ({}/{})\n'.format(tag, decode, i+1, loop_count)) output_sentence(decode) print('De-asciinate those letters... ({}/{})'.format(i+1, loop_count)) s = sys.stdin.readline().rstrip() sys.stderr.write('{} received {} ({}/{})\n'.format(tag, s, i+1, loop_count)) if s.lower() == decode: print('Thanks for asciinating!') else: print('Nope, you are not asciinating...') break else: sys.stderr.write('{} sending flag!\n'.format(tag)) print(flag)
def generate_token(length=''): if not length: length = random.randint(3, 32) length = int(length) assert 3 <= length <= 32 letters = string.ascii_letters + string.digits return ''.join(choice(letters) for _ in range(length))
def activate(): ''' Activate user account - finish the sign up process now that the email is verified - get user's password, do checks on it, and insert user into database ''' #send user to form to set password if hash is good if request.method == 'GET': #first, pull user's email and username out of hash hash = request.args.get('code') serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) try: decoded = serializer.loads(hash, salt='sign_up', max_age=3600) except SignatureExpired: flash('Activation period expired. Please sign up again.') return redirect(url_for('main.index')) except: flash("Error activating your account. Please sign up again below.") return redirect(url_for('main.index')) return render_template('activate.html', username=decoded[0], email=decoded[1]) # get user's desired password, check, add account if request.method == 'POST': username = request.form['username'] email = request.form['email'] password = request.form['password'] confirm_password = request.form['confirm_password'] #checks - password if password != confirm_password: flash("Your passwords did not match. Please try again.") return render_template('activate.html', username=username, email=email) if len(password) < 5: flash("Your password is too short. Please try again.") return render_template('activate.html', username=username, email=email) #checks - if user already completed sign up, redirect if User.query.filter_by(username=username).count() > 0: flash("You've already activated your account.") return redirect(url_for('main.index')) # use passlib to encrypt password myctx = CryptContext(schemes=['pbkdf2_sha256']) hashed_password = myctx.encrypt(password) # create a salt alphabet = string.ascii_letters + string.digits salt = ''.join(secrets.choice(alphabet) for i in range(32)) #add user user = User(username, hashed_password, salt, email) db.session.add(user) db.session.commit() login_user(user) flash('Thank you. Your account has been activated.') return redirect(url_for('main.settings'))
def calculate_password(change): import string from secrets import choice length = change.new # Generate a list of random letters of the correct length. password = ''.join(choice(string.ascii_letters) for _ in range(length)) # Add a line below to set the value of the widget password_text password_text.value = password
def make_secret_char(): while True: secret = "".join(secrets.choice(string.ascii_letters + string.digits) for i in range(6)) # keep trying until there is a secret with 1 lowercase, 1 uppercase and 1 digit, then break if (any(c.islower() for c in secret) and any(c.isdigit() for c in secret) and any(c.isupper for c in secret)): break return secret
def rndstr(size=16): """ Returns a string of random ascii characters or digits :param size: The length of the string :return: string """ _basech = string.ascii_letters + string.digits return "".join([choice(_basech) for _ in range(size)])
def unreserved(size=64): """ Returns a string of random ascii characters, digits and unreserved characters for use as RFC 7636 code verifiers :param size: The length of the string :return: string """ return "".join([choice(BASECH) for _ in range(size)])
def generate_word(self, vowel_consonant_repeats=1, start_vowel=False, end_vowel=False): """Returns a random consonant-(vowel-consonant)*wc pseudo-word.""" if not start_vowel: letter_list = [self.initial_consonants] else: letter_list = [] for i in range(vowel_consonant_repeats): letter_list.extend([self.vowels, self.final_consonants]) if end_vowel: letter_list.pop() return ''.join(choice(s) for s in letter_list)
def rndcaps(n): """ Generates a string of random capital letters. Arguments: n: Length of the output string. Returns: A string of n random capital letters. """ return ''.join([choice(_CAPS) for c in range(n)])
def dicer(flavor, length): with open_text('resources.lists', flavor + '.txt') as f: words = f.read().splitlines() seq = [choice(words) for i in range(length)] phrases = { 'hy': '-'.join(seq), 'sp': ' '.join(seq), 'so': ''.join(seq) } response = jsonify(phrases) response.headers['Cache-Control'] = 'no-store, no-cache' return response
def generate_random(generated_len=GENERATED_LEN) -> str: """ Generate random string with at least: 1 uppercase letter 1 lowercase letter 1 digit """ characters = ascii_letters + digits while True: password = ''.join(choice(characters) for _ in range(generated_len)) if (any(c for c in password if (c.isalpha() and c.islower())) and any(c for c in password if (c.isalpha() and c.isupper())) and any(c.isnumeric() for c in password)): break return password
def makeBuildPlan(config): '''Returns the list of tool names in build order.''' before, after = getBeforeAfterDependencies(config) plan = [] while before: edge = [k for k, parents in before.items() if not parents] if not edge: raise ValueError('circular dependencies: ' + ', '.join(before.keys())) x = secrets.choice(edge) plan.append(x) del before[x] for child in after[x]: before[child].remove(x) del after[x] return plan
def create(self): org_id = self.args.org_id # create unique uuid if org_id haven't been specified manualy if (not org_id): alphabet = string.ascii_letters + string.digits org_id = ''.join(secrets.choice(alphabet) for i in range(32)) # Check if Organization already exists found = self._getorganizationbyid(org_id)[0] if found: raise Exception("\nOrganization with id={} already exists!\n".format(org_id)) members = self.get_members_from_args() params = [type_converter("bytes32")(org_id), self.args.org_name, members] self._printout("Creating transaction to create organization name={} id={}\n".format(self.args.org_name, org_id)) self.transact_contract_command("Registry", "createOrganization", params) self._printout("id:\n%s"%org_id)
def up(config): """ Run up migration. :param config: Object holding configuration details about Submitty :type config: migrator.config.Config """ if 'php_user' in config.submitty_users: secrets_path = Path(config.config_path, 'secrets_submitty_php.json') if not secrets_path.exists(): characters = string.ascii_letters + string.digits secret_dict = { 'session': ''.join(secrets.choice(characters) for _ in range(64)) } with secrets_path.open('w') as open_file: json.dump(secret_dict, open_file, indent=2) secrets_path.chmod(0o440) shutil.chown(str(secrets_path), 'root', config.submitty_users['php_user'])
def random_string(length=5, upper_chars=True, punctuation=False): """ Generate a random string with the size equal to the given length. The string is based on random choices from a sequence of ascii lower case characters and digits. If length is not informed the string size will be 5. """ chars = string.ascii_lowercase + string.digits if upper_chars: chars += string.ascii_uppercase if punctuation: chars += string.punctuation if sys.version_info < (3, 6): import random return ''.join( random.SystemRandom().choice(chars) for _ in range(length) ) else: import secrets return ''.join(secrets.choice(chars) for _ in range(length))
import string import time from copy import deepcopy # This is a standalone performance test of the algorithm used in gcylc to # sort namespaces into "definition order", i.e. the order in which they are # defined in the suite.rc file. # Number of namespaces. N = 10000 # N names of length 5-15 characters each (c.f. namespaces in "definition # order"). names = [] for i in range(0, N): names.append(''.join(secrets.choice(string.ascii_letters) for n in range(5 + secrets.randrange(10)))) # N lists with 2-7 names each (c.f. tree view paths of the inheritance # hierarchy). paths1 = [] for i in range(0, N): p = [] for j in range(0, 2 + secrets.randrange(6)): z = secrets.randrange(0, N) p.append(names[z]) paths1.append(p) paths2 = deepcopy(paths1) # Alphanumeric sort.
def test_collect_rewards_integration( click_runner, funded_blockchain, configuration_file_location, alice_blockchain_test_config, bob_blockchain_test_config, charlie_blockchain_test_config, random_policy_label, blockchain_ursulas, staking_participant): blockchain = staking_participant.blockchain # Alice creates a policy and grants Bob access alice = alice_blockchain_test_config.produce( blockchain=funded_blockchain, network_middleware=MockRestMiddleware(), known_nodes=blockchain_ursulas) bob = bob_blockchain_test_config.produce( blockchain=blockchain, network_middleware=MockRestMiddleware(), known_nodes=blockchain_ursulas) # # Back to the Ursulas... # half_stake_time = MIN_LOCKED_PERIODS // 2 # Test setup logger = staking_participant.log # Enter the Teacher's Logger, and current_period = 1 # State the initial period for incrementing miner = Miner(checksum_address=staking_participant.checksum_public_address, blockchain=blockchain, is_me=True) pre_stake_eth_balance = miner.eth_balance # Finish the passage of time... once and for all for _ in range(half_stake_time): current_period += 1 logger.debug(f"period {current_period}") blockchain.time_travel(periods=1) miner.confirm_activity() M, N = 1, 1 expiration = maya.now() + datetime.timedelta(days=3) blockchain_policy = alice.grant(bob=bob, label=random_policy_label, m=M, n=1, value=POLICY_VALUE, expiration=expiration, handpicked_ursulas={staking_participant}) # Bob joins the policy bob.join_policy(random_policy_label, bytes(alice.stamp)) # Enrico Encrypts (of course) enrico = Enrico(policy_encrypting_key=blockchain_policy.public_key, network_middleware=MockRestMiddleware()) for index, _period in enumerate(range(half_stake_time - 5)): logger.debug(f"period {current_period}") alphabet = string.ascii_letters + string.digits # Random Request Periods if not random.choice((True, False)): continue # maybe re-encrypt max_reencryptions_per_period = 5 quantity = random.choice(range(max_reencryptions_per_period + 1)) quantity *= index # factorial or 0 verifying_key = UmbralPublicKey.from_bytes(bytes(alice.stamp)) # Random Re-encryptions for _i in range(quantity): # Encrypt random_data = ''.join( secrets.choice(alphabet) for i in range(secrets.choice(range(20, 100)))) ciphertext, signature = enrico.encrypt_message( message=bytes(random_data, encoding='utf-8')) # Retrieve payload = dict(message_kit=ciphertext, data_source=enrico, alice_verifying_key=verifying_key, label=random_policy_label) _cleartext = bob.retrieve(**payload) # Ursula Staying online and the clock advancing blockchain.time_travel(periods=1) miner.confirm_activity() current_period += 1 # Finish the passage of time... once and for all for _ in range(5): current_period += 1 logger.debug(f"period {current_period}") blockchain.time_travel(periods=1) miner.confirm_activity() # # WHERES THE MONEY URSULA?? - Collecting Rewards # # The address the client wants Ursula to send rewards to burner_wallet = blockchain.interface.w3.eth.account.create( INSECURE_DEVELOPMENT_PASSWORD) assert blockchain.interface.w3.eth.getBalance(burner_wallet.address) == 0 # Snag a random teacher from the fleet random_teacher = list(blockchain_ursulas).pop() collection_args = ('--mock-networking', 'ursula', 'collect-reward', '--teacher-uri', random_teacher.rest_interface, '--config-file', configuration_file_location, '--withdraw-address', burner_wallet.address, '--poa', '--force') result = click_runner.invoke(nucypher_cli, collection_args, input=INSECURE_DEVELOPMENT_PASSWORD, catch_exceptions=False) assert result.exit_code == 0 collected_reward = blockchain.interface.w3.eth.getBalance( burner_wallet.address) assert collected_reward != 0 expected_reward = Web3.toWei(21, 'gwei') * 30 * M assert collected_reward == expected_reward assert miner.eth_balance == pre_stake_eth_balance
def test_choice(self): # Test choice. items = [1, 2, 4, 8, 16, 32, 64] for i in range(10): self.assertTrue(secrets.choice(items) in items)
def easy_password(length): password = ''.join(secrets.choice(Difficulty.EASY) for i in range(length)) return password
def create_password_(len_pass): text = ''.join([ choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(len_pass) ]) return text
def run(ceph_cluster, **kw): """ CEPH-83574027 - Ensure creation of Subvolgroups, subvolumes works on NFS exports and run IO from nfs clients Pre-requisites: 1. Create cephfs volume creats fs volume create <vol_name> 2. Create nfs cluster ceph nfs cluster create <nfs_name> <nfs_server> Test operation: 1. Create cephfs nfs export ceph nfs export create cephfs <fs_name> <nfs_name> <nfs_export_name> path=<export_path> 2. Crete 2 cephfs subvolume group 3. Create cephfs subvolume in cephfs subvolume group 4. Create cephfs subvolume in deafault cephfs subvolume group 5. Mount nfs mount with cephfs export "mount -t nfs -o port=2049 <nfs_server>:<nfs_export> <nfs_mounting_dir> 7. Verify subvolume groups & subvolumes are created 6. Run IOs on both cephfs subvolumegroups & subvolumes Clean-up: 1. Remove all the data in Cephfs file system 2. Remove all the cephfs mounts 3. Delete cephfs nfs export """ try: tc = "CEPH-83574027" log.info(f"Running cephfs {tc} test case") config = kw["config"] build = config.get("build", config.get("rhbuild")) fs_util = FsUtils(ceph_cluster) clients = ceph_cluster.get_ceph_objects("client") client1 = clients[0] fs_util.prepare_clients(clients, build) fs_util.auth_list(clients) mon_node_ip = fs_util.get_mon_node_ips() mon_node_ip = ",".join(mon_node_ip) rhbuild = config.get("rhbuild") nfs_servers = ceph_cluster.get_ceph_objects("nfs") nfs_server = nfs_servers[0].node.hostname nfs_name = "cephfs-nfs" nfs_export_name = "/export_" + "".join( secrets.choice(string.digits) for i in range(3)) export_path = "/" fs_name = "cephfs" nfs_mounting_dir = "/mnt/nfs_" + "".join( secrets.choice(string.ascii_uppercase + string.digits) for i in range(5)) if "5.0" in rhbuild: client1.exec_command( sudo=True, cmd=f"ceph nfs export create cephfs {fs_name} {nfs_name} " f"{nfs_export_name} path={export_path}", ) else: client1.exec_command( sudo=True, cmd=f"ceph nfs export create cephfs {nfs_name} " f"{nfs_export_name} {fs_name} path={export_path}", ) subvolumegroup_list = [ { "vol_name": fs_name, "group_name": "subvolgroup_1", }, { "vol_name": fs_name, "group_name": "subvolgroup_2", }, ] for subvolumegroup in subvolumegroup_list: fs_util.create_subvolumegroup(clients[0], **subvolumegroup) subvolume_list = [ { "vol_name": fs_name, "subvol_name": "subvol_1", "group_name": "subvolgroup_1", "size": "5368706371", }, { "vol_name": fs_name, "subvol_name": "subvol_2", "size": "5368706371", }, ] for subvolume in subvolume_list: fs_util.create_subvolume(clients[0], **subvolume) commands = [ f"mkdir -p {nfs_mounting_dir}", f"mount -t nfs -o port=2049 {nfs_server}:{nfs_export_name} {nfs_mounting_dir}", ] for command in commands: client1.exec_command(sudo=True, cmd=command) out, rc = client1.exec_command(sudo=True, cmd=f"ls {nfs_mounting_dir}/volumes/") if "subvolgroup_1" not in out: raise CommandFailed("Subvolume group 1 creation failed") if "subvolgroup_2" not in out: raise CommandFailed("Subvolume group 2 creation failed") out, rc = client1.exec_command( sudo=True, cmd=f"ls {nfs_mounting_dir}/volumes/subvolgroup_1") if "subvol_1" not in out: raise CommandFailed("Subvolume creation in subvolume group failed") out, rc = client1.exec_command( sudo=True, cmd=f"ls {nfs_mounting_dir}/volumes/_nogroup") if "subvol_2" not in out: raise CommandFailed( "Subvolume creation in default subvolume group failed") commands = [ f"python3 /home/cephuser/smallfile/smallfile_cli.py --operation create --threads 10 --file-size 4 --files" f" 1000 --files-per-dir 10 --dirs-per-dir 2 --top {nfs_mounting_dir}/volumes/subvolgroup_1/subvol_1", f"python3 /home/cephuser/smallfile/smallfile_cli.py --operation read --threads 10 --file-size 4 --files" f" 1000 --files-per-dir 10 --dirs-per-dir 2 --top {nfs_mounting_dir}/volumes/subvolgroup_1/subvol_1", f"python3 /home/cephuser/smallfile/smallfile_cli.py --operation create --threads 10 --file-size 8 " f"--files 2000 --files-per-dir 5 --dirs-per-dir 5 --top {nfs_mounting_dir}/volumes/_nogroup/subvol_2/", f"python3 /home/cephuser/smallfile/smallfile_cli.py --operation read --threads 10 --file-size 8 " f"--files 2000 --files-per-dir 5 --dirs-per-dir 5 --top {nfs_mounting_dir}/volumes/_nogroup/subvol_2/", f"python3 /home/cephuser/smallfile/smallfile_cli.py --operation create --threads 5 --file-size 16 " f"--files 4000 --files-per-dir 20 --dirs-per-dir 4 --top {nfs_mounting_dir}/volumes/subvolgroup_2", f"python3 /home/cephuser/smallfile/smallfile_cli.py --operation read --threads 5 --file-size 16 " f"--files 4000 --files-per-dir 20 --dirs-per-dir 4 --top {nfs_mounting_dir}/volumes/subvolgroup_2", ] for command in commands: client1.exec_command(sudo=True, cmd=command, long_running=True) log.info("Test completed successfully") return 0 except Exception as e: log.info(e) log.info(traceback.format_exc()) return 1 finally: log.info("Cleaning up") client1.exec_command(sudo=True, cmd=f"rm -rf {nfs_mounting_dir}/*") client1.exec_command(sudo=True, cmd=f"umount {nfs_mounting_dir}") client1.exec_command( sudo=True, cmd=f"ceph nfs export delete {nfs_name} {nfs_export_name}", check_ec=False, )
def generate_short_id(): """Generate securely random 8 characters long alphanumeric ID.""" return "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(8))
async def sequencegame(cmd, pld): """ :param cmd: The command object referenced in the command. :type cmd: sigma.core.mechanics.command.SigmaCommand :param pld: The payload with execution data and details. :type pld: sigma.core.mechanics.payload.CommandPayload """ if Ongoing.is_ongoing(cmd.name, pld.msg.author.id): ongoing_error = GenericResponse( 'There is already one ongoing.').error() await pld.msg.channel.send(embed=ongoing_error) return try: Ongoing.set_ongoing(cmd.name, pld.msg.author.id) chosen = [secrets.choice(first_symbols) for _ in range(4)] title = f'🎯 {pld.msg.author.display_name}, you have 90 seconds for each attempt.' desc = f'Symbols you can use: {"".join(first_symbols)}' start_embed = discord.Embed(color=0xf9f9f9) start_embed.add_field(name=title, value=desc) await pld.msg.channel.send(embed=start_embed) def answer_check(msg): """ :type msg: discord.Message :rtype: bool """ if pld.msg.author.id != msg.author.id: return if pld.msg.channel.id != msg.channel.id: return message_args = [ char for char in msg.content if char in all_symbols ] if len(message_args) != 4: return for arg in message_args: if arg in all_symbols: return True finished = False victory = False timeout = False tries = 0 while not finished and tries < 6: try: answer = await cmd.bot.wait_for('message', check=answer_check, timeout=90) correct, results = check_answer(answer.content, chosen) tries += 1 if correct: finished = True victory = True currency = cmd.bot.cfg.pref.currency await cmd.db.add_resource(answer.author.id, 'currency', 50, cmd.name, pld.msg) win_title = f'🎉 Correct, {answer.author.display_name}. You won 50 {currency}!' win_embed = discord.Embed(color=0x77B255, title=win_title) await pld.msg.channel.send(embed=win_embed) else: attempt_title = f'💣 {answer.author.display_name} {tries}/6: {"".join(results)}' attempt_embed = discord.Embed(color=0x262626, title=attempt_title) await pld.msg.channel.send(embed=attempt_embed) except asyncio.TimeoutError: finished = True victory = False timeout = True timeout_title = f'🕙 Time\'s up {pld.msg.author.display_name}! It was {"".join(chosen)}' timeout_embed = discord.Embed(color=0x696969, title=timeout_title) await pld.msg.channel.send(embed=timeout_embed) if not victory and not timeout: lose_title = f'💥 Ooh, sorry {pld.msg.author.display_name}, it was {"".join(chosen)}' final_embed = discord.Embed(color=0xff3300, title=lose_title) await pld.msg.channel.send(embed=final_embed) Ongoing.del_ongoing(cmd.name, pld.msg.author.id) except Exception: if Ongoing.is_ongoing(cmd.name, pld.msg.author.id): Ongoing.del_ongoing(cmd.name, pld.msg.author.id) raise
def generate_secure_random_string(N=30): return ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(N))
def create_secret_key(length): key = "" characters = string.ascii_letters + string.digits + string.punctuation for i in range(length): key += secrets.choice(characters) return key
config['supervisor_user'] = SUPERVISOR_USER with open(SUBMITTY_USERS_JSON, 'w') as json_file: json.dump(config, json_file, indent=2) shutil.chown(SUBMITTY_USERS_JSON, 'root', DAEMON_GROUP if args.worker else DAEMONPHP_GROUP) os.chmod(SUBMITTY_USERS_JSON, 0o440) ############################################################################## # Write secrets_submitty_php json if not args.worker: config = OrderedDict() characters = string.ascii_letters + string.digits config['session'] = ''.join(secrets.choice(characters) for _ in range(64)) with open(SECRETS_PHP_JSON, 'w') as json_file: json.dump(config, json_file, indent=2) shutil.chown(SECRETS_PHP_JSON, 'root', PHP_GROUP) os.chmod(SECRETS_PHP_JSON, 0o440) ############################################################################## # Write submitty_admin json if not args.worker: config = OrderedDict() config['submitty_admin_username'] = SUBMITTY_ADMIN_USERNAME config['submitty_admin_password'] = SUBMITTY_ADMIN_PASSWORD with open(SUBMITTY_ADMIN_JSON, 'w') as json_file: json.dump(config, json_file, indent=2)
# time is only used for debugging and performance testing #import time import secrets import string # start_time is only used for debugging and performance testing #start_time = time.time() alphabet = string.ascii_letters + string.digits print("\nGenerating key file.") print("Please note that this could take up to 1 minute.\n") OTP_Key = ''.join(secrets.choice(alphabet) for i in range(10000000)) Key_File = open("key.txt", "w") Key_File.write(OTP_Key) Key_File.close() print("\nYour key has been generated. It is in the directory of this program") print("and is named key.txt\n") # This print function is only used for debugging and performance testing #print("--- %s seconds ---" % (time.time() - start_time))
def random_ascii_uppercase(): return secrets.choice(string.ascii_uppercase)
def gamePanel(): #initialize necessary variables clickCnt = 0 check = 0 startCheck = 0 endGame = 0 inputScore = 0 fail = 0 #create game panel graphics window with light grey background win = GraphWin("Game Panel", 300, 200) win.setBackground(color_rgb(211, 211, 211)) #draw title border line b = Rectangle(Point(0, 0), Point(300, 40)) b.setOutline("black") b.setFill("white") b.draw(win) #draw Title t = Text(b.getCenter(), "Pete-A-Maze") t.setSize(24) t.draw(win) #draw top scores panel ts = Rectangle(Point(50, 50), Point(250, 160)) ts.setOutline("black") ts.setFill("white") ts.draw(win) #display title of top scores titleTopScore = Text(Point(150, 60), "TOP SCORES") divider = Text(Point(150, 75), "**********") divider.setSize(18) titleTopScore.draw(win) divider.draw(win) #draw exit button e = Rectangle(Point(265, 170), Point(300, 200)) e.setOutline("black") e.setFill(color_rgb(255, 0, 0)) e.draw(win) et = Text(e.getCenter(), 'EXIT') et.setSize(14) et.draw(win) #draw new player button r = Rectangle(Point(100, 170), Point(200, 200)) r.setOutline("black") r.setFill(color_rgb(0, 255, 0)) r.draw(win) rt = Text(r.getCenter(), 'NEW PLAYER') rt.setSize(14) rt.draw(win) # draw the chance button c = Rectangle(Point(230, 60), Point(300, 100)) c.setOutline("black") c.setFill("green") ct = Text(c.getCenter(), 'CHANCE') ct.setSize(10) #display the top 4 scores spaceFromTitle = 12 name = scoresIn() name1 = name[0].replace(",", "\t") name2 = name[1].replace(",", "\t") name3 = name[2].replace(",", "\t") name4 = name[3].replace(",", "\t") score1 = Text(Point(150, 80 + spaceFromTitle), name1) score2 = Text(Point(150, 92 + spaceFromTitle), name2) score3 = Text(Point(150, 104 + spaceFromTitle), name3) score4 = Text(Point(150, 116 + spaceFromTitle), name4) score1.setSize(12) score2.setSize(12) score3.setSize(12) score4.setSize(12) score1.draw(win) score2.draw(win) score3.draw(win) score4.draw(win) #check for exit button while (check != 1): #get clicked point clickPoint = win.getMouse() x = clickPoint.x y = clickPoint.y #check if exit button clicked and close window if ((x >= 250) and (x <= 300)): if ((y >= 170) and (y <= 200)): clickCnt += 1 x = clickPoint.x y = clickPoint.y check = 1 #check if new player button clicked and close window if ((x >= 100) and (x <= 200)): if ((y >= 170) and (y <= 200)): clickCnt += 1 x = clickPoint.x y = clickPoint.y check = 0 #check if new player button was pressed if (startCheck != 1): #rewrite new player button to say start #set check var to start button state rt.undraw() rt = Text(r.getCenter(), 'START!') rt.setSize(14) rt.draw(win) startCheck = 1 #erase the title, score panel, title score panel, #divider, and all 4 top scores ts.undraw() titleTopScore.undraw() divider.undraw() score1.undraw() score2.undraw() score3.undraw() score4.undraw() #display label for entry box playerName = Text(Point(80, 60), "Player Name:") playerName.draw(win) #draw entry box for user input nameEntry = Entry(Point(180, 60), 15) nameEntry.setFill("white") nameEntry.draw(win) #otherwise start button is pressed else: #get the text from the entry box inputName = nameEntry.getText() #check if user entered information in entry box if (inputName != ""): #draw the reset button on the game panel rb = Rectangle(Point(0, 170), Point(50, 200)) rb.setOutline("black") rb.setFill(color_rgb(255, 255, 0)) rb.draw(win) rbt = Text(rb.getCenter(), 'RESET') rbt.setSize(14) rbt.draw(win) #erase the entry box nameEntry.undraw() #display the name the user entered savedName = Text(Point(150, 60), inputName) savedName.draw(win) c.draw(win) ct.draw(win) #display the score score = Text(Point(98, 100), "Score:") score.draw(win) savedScore = Text(Point(130, 100), inputScore) savedScore.draw(win) #create the field window and return #its objects gameWin, pete, gridList, bummer, circ1, circ2, startTime = field( ) #create and display the sensors in the #field window and return their locations sensorList = sensors(gridList, gameWin) #initialize variables to move Pete object colsIndex = 0 rowsIndex = 0 #loop while the field game has not ended while (endGame != 1): #animate pete and return necessary objects colsIndex, rowsIndex, peteLocList, inputScore, savedScore, fail = animatePete( circ1, circ2, colsIndex, rowsIndex, win, gameWin, pete, gridList, bummer, sensorList, inputScore, savedScore, win, fail) #update score savedScore.undraw() savedScore = Text(Point(130, 100), inputScore) savedScore.draw(win) #get pete objects x and y coords peteX1 = pete.getP1().getX() peteX2 = pete.getP2().getX() peteY1 = pete.getP1().getY() peteY2 = pete.getP2().getY() #get the coords of the red rectangle at the end #of the maze lastRectX1 = gridList[-1].getP1().getX() lastRectX2 = gridList[-1].getP2().getX() lastRectY1 = gridList[-1].getP1().getY() lastRectY2 = gridList[-1].getP2().getY() #check if pete is at the red rectangle if ((peteX1 > lastRectX1) and (peteX2 < lastRectX2)): if ((peteY1 > lastRectY1) and (peteY2 < lastRectY2)): # undraw chance and text c.undraw() ct.undraw() # calculate the total amount of time to finish the game spend = time.time() - startTime # if it is within 20 sec if spend < 20: #set the var to exit field loop endGame = 1 #display final message on field window finalMsg = Text( Point(200, 200), "Finished, Click to Close") finalMsg.draw(gameWin) # generate a list of different fill colors colorList = [ "red", "blue", "yellow", "orange", "green", "pink", "purple" ] # define a while loop to set fill for celebration while True: # loop through the list to set fill for i in gridList: i.setFill( secrets.choice(colorList)) celebration = gameWin.checkMouse() # #wait for last mouse click if celebration != None: #update top_scores.txt file with new scores scoresOut( inputScore, inputName) #close field window gameWin.close() win.close() main() break # if the time is over 20 sec if spend > 20: # display text to ask user to player again ending = Text( Point(200, 200), "Sorry! You need to spend less than 20s to be recorded!" ) ending.draw(gameWin) timeSpent = Text( Point(200, 250), "Your have spent," + str(round(spend, 2))) timeSpent.draw(gameWin) # wait for 3 seconds sleep(3) # close the game and graph window gameWin.close() win.close() main() #check if reset button clicked and close window if ((x >= 0) and (x <= 50)): if ((y >= 170) and (y <= 200)): #reset the score inputScore = 0 #close game panel graphics window win.close()
def hard_password(length): password = ''.join(secrets.choice(Difficulty.HARD) for i in range(length)) return password
angka = (idxpesan - idxotp) % len(simbol) hasil += simbol[angka] else: hasil += i a += 1 return hasil trueotp = [] for l in range(len(pesan)): trueotp.append(' ') while True: otp = [] for i in range(len(pesan)): a = secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ') otp.append(a) if trueotp[i] in simbol: otp[i] = trueotp[i] hasil = decryptpesan(pesan,otp) for z in range(len(pesan)): if hasil[z] == pesan1[z] and pesan[z] in simbol: trueotp[z] = otp[z] if hasil == pesan1: print("One Time Pad Key:") print(''.join(trueotp).replace(' ','')) break
def animatePete(circ1, circ2, colsIndex, rowsIndex, windowName, gameWin, pete, gridList, bummersList, sensorList, inputScore, savedScore, win, failIndex): #initialize necessary variables upperAlpha = string.ascii_uppercase lowerAlpha = string.ascii_lowercase cols = [] rows = [] peteLocList = "" checkForSensor = 0 possibility = [ "No attendence today!", "Partner is ill!", "Mom is calling!" ] i = 0 #create list of uppercase alphanumeric vals for i in upperAlpha: for j in range(10): cols.append(i + str(j)) #create list of lowercase alphanumeric vals for k in lowerAlpha: for l in range(10): rows.append(k + str(l)) #wait for mouse click in the field and get the #x and y coords of the click and pete mouseClick = gameWin.getMouse() mouseX = mouseClick.getX() mouseY = mouseClick.getY() peteX1 = pete.getP1().getX() peteX2 = pete.getP2().getX() peteY1 = pete.getP1().getY() peteY2 = pete.getP2().getY() #check if click is in the same column if ((peteX1 <= mouseX) and (peteX2 >= mouseX)): #loop through the difference between the click and #pete in increments of 40 (size of rects) for i in range(0, int(mouseY) - int(peteY2), 40): #get x and y coords of pete peteX1 = pete.getP1().getX() peteX2 = pete.getP2().getX() peteY1 = pete.getP1().getY() peteY2 = pete.getP2().getY() #check if click is below pete and move pete down if (peteY2 < mouseY): #erase pete and redraw pete by increments of 40 pete.undraw() pete.move(0, 40) pete.draw(gameWin) center = pete.getCenter() #create list of the columns that pete crosses colsIndex += 1 rowsIndex += 10 crossCols = cols[colsIndex] crossRows = rows[rowsIndex] peteLocList = crossCols #check if pete crossed a sensor and update score #accordingly and set check var for sensor if (peteLocList in sensorList): inputScore += 3 checkForSensor = 1 #check if sensor is not crossed and update score #accordingly if (checkForSensor != 1): inputScore += 1 #otherwise reset check var else: checkForSensor = 0 #check if pete moves into a Hoosier Bummer if str(center) in bummersList: failIndex += 1 # if it is the first time if failIndex == 1: # add 20 points to the total score inputScore += 20 # display the first alert text alert = Text(Point(200, 200), "You’ve hit a Hidden Hoosier Bummer!") alert.draw(gameWin) # after 3 seconds, undraw the alert sleep(3) alert.undraw() # if it is the second time if failIndex == 2: # display the alert for two seconds alert = Text(Point(200, 200), "That’s two Hoosier Bummers. Game Over") alert.draw(gameWin) sleep(2) # close the win and field window gameWin.close() win.close() #delay for 250ms sleep(.25) #loop through the difference between the click and #pete in increments of 40 (size of rects) for j in range(0, int(peteY1) - int(mouseY), 40): #check if click is below pete and move pete up if (peteY1 > mouseY): #erase pete and redraw pete by increments of -40 pete.undraw() pete.move(0, -40) pete.draw(gameWin) center = pete.getCenter() #create list of the columns that pete crosses rowsIndex -= 10 crossCols = cols[colsIndex] crossRows = rows[rowsIndex] colsIndex -= 1 peteLocList = crossCols #check if pete crossed a sensor and update score #accordingly and set check var for sensor if (peteLocList in sensorList): inputScore += 3 checkForSensor = 1 #check if sensor is not crossed and update score #accordingly if (checkForSensor != 1): inputScore += 1 #otherwise reset check var else: checkForSensor = 0 #check if pete moves into a Hoosier Bummer if str(center) in bummersList: failIndex += 1 # if it is the first time if failIndex == 1: # add 20 points to the total score inputScore += 20 # display the first alert text alert = Text(Point(200, 200), "You’ve hit a Hidden Hoosier Bummer!") alert.draw(gameWin) # after 3 seconds, undraw the alert sleep(3) alert.undraw() # if it is the second time if failIndex == 2: # display the alert for two seconds alert = Text(Point(200, 200), "That’s two Hoosier Bummers. Game Over") alert.draw(gameWin) sleep(2) # close the win and field window gameWin.close() win.close() #delay for 250ms sleep(.25) #check if click is in the same row elif ((peteY1 <= mouseY) and (peteY2 >= mouseY)): #loop through the difference between the click and #pete in increments of 40 (size of rects) for i in range(0, int(mouseX) - int(peteX2), 40): #get x and y coords of pete peteX1 = pete.getP1().getX() peteX2 = pete.getP2().getX() peteY1 = pete.getP1().getY() peteY2 = pete.getP2().getY() #check if click is to the right of pete and move pete right if (peteX2 < mouseX): #erase pete and redraw pete by increments of 40 pete.undraw() pete.move(40, 0) pete.draw(gameWin) center = pete.getCenter() #create list of the columns that pete crosses colsIndex += 10 rowsIndex += 1 crossCols = cols[colsIndex] crossRows = rows[rowsIndex] peteLocList = crossRows #check if pete crossed a sensor and update score #accordingly and set check var for sensor if (peteLocList in sensorList): inputScore += 3 checkForSensor = 1 #check if sensor is not crossed and update score #accordingly if (checkForSensor != 1): inputScore += 1 #otherwise reset check var else: checkForSensor = 0 #check if pete moves into a Hoosier Bummer if str(center) in bummersList: failIndex += 1 # if it is the first time if failIndex == 1: # add 20 points to the total score inputScore += 20 # display the first alert text alert = Text(Point(200, 200), "You’ve hit a Hidden Hoosier Bummer!") alert.draw(gameWin) # after 3 seconds, undraw the alert sleep(3) alert.undraw() # if it is the second time if failIndex == 2: # display the alert for two seconds alert = Text(Point(200, 200), "That’s two Hoosier Bummers. Game Over") alert.draw(gameWin) sleep(2) # close the win and field window gameWin.close() win.close() #delay for 250ms sleep(.25) #loop through the difference between the click and #pete in increments of 40 (size of rects) for j in range(0, int(peteX1) - int(mouseX), 40): #check if click is to the left of pete and move pete left if (peteX1 > mouseX): #erase pete and redraw pete by increments of 40 pete.undraw() pete.move(-40, 0) pete.draw(gameWin) center = pete.getCenter() #create list of the columns that pete crosses colsIndex -= 10 rowsIndex -= 1 crossCols = cols[colsIndex] crossRows = rows[rowsIndex] peteLocList = crossRows #check if pete crossed a sensor and update score #accordingly and set check var for sensor if (peteLocList in sensorList): inputScore += 3 checkForSensor = 1 #check if sensor is not crossed and update score #accordingly if (checkForSensor != 1): inputScore += 1 #otherwise reset check var else: checkForSensor = 0 #check if pete moves into a Hoosier Bummer if str(center) in bummersList: failIndex += 1 # if it is the first time if failIndex == 1: # add 20 points to the total score inputScore += 20 # display the first alert text alert = Text(Point(200, 200), "You’ve hit a Hidden Hoosier Bummer!") alert.draw(gameWin) # after 3 seconds, undraw the alert sleep(3) alert.undraw() # if it is the second time if failIndex == 2: # display the alert for two seconds alert = Text(Point(200, 200), "That’s two Hoosier Bummers. Game Over") alert.draw(gameWin) sleep(2) # close the win and field window gameWin.close() win.close() #check if the click is up and to the right elif ((peteX2 <= mouseX) and (peteY2 >= mouseY)): #initialize variables dy = -40 dx = 40 colsIndex += 11 rowsIndex -= 11 #move diagonal colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore = diagonal( dx, dy, pete, mouseX, mouseY, gameWin, colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore, bummersList, failIndex) #check if the click is up and to the left elif ((peteX1 >= mouseX) and (peteY1 >= mouseY)): #initialize variables dy = -40 dx = -40 colsIndex -= 11 rowsIndex -= 11 #move diagonal colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore = diagonal( dx, dy, pete, mouseX, mouseY, gameWin, colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore, bummersList, failIndex) #check if the click is down and to the right elif ((peteX2 <= mouseX) and (peteY1 <= mouseY)): #initialize variables dy = 40 dx = 40 colsIndex += 11 rowsIndex += 11 #move diagonal colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore = diagonal( dx, dy, pete, mouseX, mouseY, gameWin, colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore, bummersList, failIndex) #check if the click is down and to the left elif ((peteX1 >= mouseX) and (peteY1 <= mouseY)): #initialize variables dy = 40 dx = -40 colsIndex -= 11 rowsIndex += 11 #move diagonal colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore = diagonal( dx, dy, pete, mouseX, mouseY, gameWin, colsIndex, rowsIndex, cols, rows, checkForSensor, sensorList, peteLocList, inputScore, bummersList, failIndex) #get center point coords for pete and warp circles px = pete.getCenter().getX() py = pete.getCenter().getY() c1x = circ1.getCenter().getX() c1y = circ1.getCenter().getY() c2x = circ2.getCenter().getX() c2y = circ2.getCenter().getY() #check if pete is on the first warp circle if (px == c1x and py == c1y): #continuously loop while True: #get pete and cricle1 and circle2 center coords px = pete.getCenter().getX() py = pete.getCenter().getY() c1x = circ1.getCenter().getX() c1y = circ1.getCenter().getY() c2x = circ2.getCenter().getX() c2y = circ2.getCenter().getY() #check if pete is to the left and move left if (px > c2x): dx = -40 dy = 0 colsIndex -= 10 rowsIndex -= 1 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is to the right and move right if (px < c2x): dx = 40 dy = 0 colsIndex += 10 rowsIndex += 1 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is to the up and move up if (py > c2y): dx = 0 dy = -40 rowsIndex -= 10 colsIndex -= 1 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is to the down and move down if (py < c2y): dx = 0 dy = 40 colsIndex += 1 rowsIndex += 10 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is at the other circle and draw pete and exit loop if (px == c2x and py == c2y): pete.draw(gameWin) break #check if pete is on the second warp circle elif (px == c2x and py == c2y): #continuously loop while True: #get pete and cricle1 and circle2 center coords px = pete.getCenter().getX() py = pete.getCenter().getY() c1x = circ1.getCenter().getX() c1y = circ1.getCenter().getY() c2x = circ2.getCenter().getX() c2y = circ2.getCenter().getY() #check if pete is to the left and move left if (px > c1x): dx = -40 dy = 0 colsIndex -= 10 rowsIndex -= 1 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is to the right and move right if (px < c1x): dx = 40 dy = 0 colsIndex += 10 rowsIndex += 1 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is to the up and move up if (py > c1y): dx = 0 dy = -40 rowsIndex -= 10 colsIndex -= 1 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is to the down and move down if (py < c1y): dx = 0 dy = 40 colsIndex += 1 rowsIndex += 10 gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList = movePete( gameWin, dx, dy, cols, rows, pete, colsIndex, rowsIndex, peteLocList) #check if pete is at the other circle and draw pete and exit loop if (px == c1x and py == c1y): pete.draw(gameWin) break # check if there is a click in the game panel panelClick = windowName.checkMouse() if panelClick != None: xPanel = panelClick.getX() yPanel = panelClick.getY() # if reset button is clicked if xPanel < 50 and yPanel > 160: # move pete back to its starting position pete.undraw() pete = Rectangle(Point(2, 2), Point(38, 38)) pete.setFill("yellow") pete.draw(gameWin) # clear the score inputScore = 0 # if exit button is clicked if xPanel > 250 and yPanel > 160: # close the game panel gameWin.close() # close the field panel windowName.close() # if chance button is clicked if (xPanel > 230 and 60 < yPanel < 100): # randomly select a situation text = secrets.choice(possibility) # if chosing the first outcome if text == possibility[0]: for i in range(1, 99): gridList[i].setFill("yellow") condition1 = Text(pete.getCenter(), text) condition1.draw(gameWin) # sleep for 2 sec sleep(2) condition1.undraw() for i in range(1, 99): gridList[i].setFill("white") # reduce 10 points inputScore = inputScore - 10 # if choosing the second outcome if text == possibility[1]: for i in range(1, 99): gridList[i].setFill("blue") condition2 = Text(pete.getCenter(), text) condition2.draw(gameWin) # sleep for 2 sec sleep(2) condition2.undraw() for i in range(1, 99): gridList[i].setFill("white") # plus 3 points inputScore = inputScore + 3 # if choosing the third outcome if text == possibility[2]: for i in range(1, 99): gridList[i].setFill("red") condition3 = Text(pete.getCenter(), text) condition3.draw(gameWin) # sleep for 2 sec sleep(2) condition3.undraw() for i in range(1, 99): gridList[i].setFill("white") # plus 5 points inputScore += 5 # check pete position again peteX1 = pete.getP1().getX() peteX2 = pete.getP2().getX() peteY1 = pete.getP1().getY() peteY2 = pete.getP2().getY() #return pete location and score return colsIndex, rowsIndex, peteLocList, inputScore, savedScore, failIndex
def generate_random_string(count=10): return "".join((secrets.choice(string.ascii_letters) for i in range(count)))
def bypass_hcaptcha(url): """ :param url: url to page which gives hcaptcha :return: Returns Response object (cookies stored for future use) """ host = urlparse(url).netloc bypassed = False session = requests.session() headers = { 'User-Agent': choice(( 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko)', 'Mozilla/5.0 (iPad; CPU OS 9_3_5 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13G36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36' )) } logger.info("Bypassing captcha...") # Retry until success while not bypassed: site_key = str(uuid4()) response = session.post('https://hcaptcha.com/getcaptcha', headers=headers, data={ 'sitekey': site_key, 'host': host }).json() try: key = response['key'] tasks = [row['task_key'] for row in response['tasklist']] job = response['request_type'] timestamp = round(time()) + choice(range(30, 120)) answers = dict( zip(tasks, [choice(['true', 'false']) for index in range(len(tasks))])) mouse_movements = [] last_movement = timestamp for index in range(choice(range(1000, 10000))): last_movement += choice(range(10)) mouse_movements.append( [choice(range(500)), choice(range(500)), last_movement]) json = { 'job_mode': job, 'answers': answers, 'serverdomain': host, 'sitekey': site_key, 'motionData': { 'st': timestamp, 'dct': timestamp, 'mm': mouse_movements } } response = session.post(f'https://hcaptcha.com/checkcaptcha/{key}', json=json) response = response.json() bypassed = response['pass'] except (TypeError, KeyError): pass if bypassed: token = response['generated_pass_UUID'] resp = helpers.soupify(session.get(url)) bypass_url = f'https://{host}{resp.form.get("action")}' data = dict((x.get('name'), x.get('value')) for x in resp.select('form > input')) data.update({ 'id': resp.strong.text, 'g-recaptcha-response': token, 'h-captcha-response': token }) resp = session.post(bypass_url, data=data) if resp.status_code == 200: pickle.dump(resp.cookies, open(f'{tempfile.gettempdir()}/{host}', 'wb')) logger.info("Succesfully bypassed captcha!") return resp else: bypassed = False
import secrets with open('./google-10000-english-usa.txt') as f: def process_word(word): word = word.strip() return word[0].upper() + word[1:].lower() words = [process_word(word) for word in f.read().strip().split()] secret_word = lambda: secrets.choice(words) size = 8 pass_words = [secret_word() for i in range(size)] print(''.join(pass_words))
def iota_seed_generator(seed_length=iota_seed_length): population = "ABCDEFGHIJKLMNOPQRSTUVWXYZ9" out_string = "" for x in range(seed_length): out_string = out_string + secrets.choice(population) return out_string
import secrets import string length = int(input("Enter length of Passcode: ")) alphabet = string.ascii_letters + string.digits while True: password = ''.join(secrets.choice(alphabet) for i in range(length - 2)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): print('!' + password + '!') break
#import random import secrets #min = 1 #max = 6 foo = ['1', '2', '3', '4', '5', '6'] roll_again = "yes" while roll_again == "yes" or roll_again == "y": print("Rolling the dices...") print("The values are....") # print (random.randint(min, max)) # print (random.randint(min, max)) print(secrets.choice(foo)) roll_again = input("Roll the dices again?")
def random_chars(size, chars=string.ascii_letters): selection = iter(lambda: secrets.choice(chars), object()) while True: yield ''.join(islice(selection, size))
def get_random_quote(): return secrets.choice(QUOTE_APIS).get_random_quote()
def build_key_part(num_of_chars): alphabet = string.ascii_uppercase + string.digits password = "".join(secrets.choice(alphabet) for i in range(num_of_chars)) return password
def gen_pw(l): alphabet = string.ascii_letters + string.digits + string.punctuation alphabet = list(filter(lambda x: x not in "\"'\\", alphabet)) return ''.join(secrets.choice(alphabet) for _ in range(l))
def create(self, request, *args, **kwargs): get_order_id = Orders.objects.get(buyer=request.user.id) get_total_from_cart = get_order_id.get_total_from_cart alphabet = string.ascii_letters + string.digits salt = ''.join(secrets.choice(alphabet) for i in range(16)) param1 = ''.join(secrets.choice(alphabet) for i in range(16)) description = '' for i in request.data.get('items_ordered'): items_cart = Research.objects.get(id=i) instances = Cart.objects.filter(user_cart__buyer=request.user.id, ordered_item=items_cart, user_cart=get_order_id.id) get_name = list(instances.values( 'ordered_item__name'))[0]['ordered_item__name'] description += ' ID: {},'.format(i) description += ' Название исследования: {}.'.format(get_name) str2hash = "payment.php;{};USD;{};ru;534270;{};{};{};{};vwc90Vew0ZJVxUfa".format( get_total_from_cart, description, get_order_id.id, param1, salt, request.user.email) result = hashlib.md5(str2hash.encode()) md5result = result.hexdigest() # zeo = [] # search_id = 'ID:, 2020, Название, исследования:, 230, name.' # for i in search_id.split(): # try: # s = i.replace(',', '') # zeo.append(int(s)) # except: # pass # email_body = \ # 'Доброго времени суток, пользователь. ' + \ # 'Вам были отправлены файлы исследования. \n' + \ # 'Спасибо за покупку,\n' + \ # 'С уважением, команда Qliento' # # send_files = Mail( # from_email='*****@*****.**', # to_emails=['*****@*****.**'], # subject='Файлы исследования', # html_content=email_body, # ) # # data_file = ResearchFiles.objects.get(research=230) # # with open('static/files/{}'.format(str(data_file)), 'rb') as f: # data = f.read() # f.close() # # encoded_file = base64.b64encode(data).decode() # # attachedFile = Attachment( # FileContent(encoded_file), # FileName(str(data_file)) # ) # # send_files.attachment = attachedFile # sg = SendGridAPIClient(settings.api_key) # sg.send(send_files) get_order_id.pg_sig = param1 get_order_id.save() return Response( 'https://api.paybox.money/payment.php?pg_merchant_id=534270&pg_amount={}&pg_currency=USD&pg_description={}&' 'pg_language=ru&pg_order_id={}&pg_param1={}&pg_salt={}&pg_user_contact_email={}' '&pg_sig={}'.format(get_total_from_cart, description, get_order_id.id, param1, salt, request.user.email, md5result))
def random_string(n=10): return ''.join( secrets.choice(string.ascii_uppercase + string.digits) for i in range(n))
#!/usr/bin/env python3 # Needs to be put into a class # Needs a module to import dictionary values of the dieware list directly # rather than creating the dict here. # Clean up the horrible syntax of the functions. # Write some meaningful comments lol # put an argparser in here import secrets die = [1, 2, 3, 4, 5, 6] d = dict() die_roll = secrets.choice(die) def generate_dictionary(txt_file) -> dict: with open(txt_file) as f: for line in f: (key, val) = line.split() d[int(key)] = val def generate_word_number() -> int: w = [0] * 5 return int("".join(map(str, [secrets.choice(die) for i in w]))) def generate_die_words(num_words=10) -> list: return [generate_word_number() for _ in range(num_words)]
#!/usr/local/bin/python3 import secrets, string length = 16 chars = string.ascii_letters + string.digits + '!@#$%^&*()' print(''.join(secrets.choice(chars) for i in range(length)))
def generate_word_number() -> int: w = [0] * 5 return int("".join(map(str, [secrets.choice(die) for i in w])))
def medium_password(length): password = ''.join(secrets.choice(Difficulty.MEDIUM) for i in range(length)) return password
import secrets import string import pyperclip al = string.ascii_letters + string.digits def inputHandler(): while True: try: n = input('How many characters? ') if int(n) > 0: return int(n) else: raise ValueError except ValueError: print('Please only enter positive integers.') pyperclip.copy(''.join(secrets.choice(al) for i in range(inputHandler()))) print('Password has been copied to your clipboard!')
def generate_random_plan(): return secrets.choice(list(plan_choices.keys()))
def field(): #initialize necessary variables gridList = [] randomNums = [] start = time.time() bummerList = [] #create field graphics window with white background gameWin = GraphWin("The Field", 400, 400) gameWin.setBackground("white") #constantly loop to create black circles while (True): #create a list of random numbers from 20 to 400 #in increments of 40 for i in range(20, 380, 40): randomNums.append(i) #save a random number from the random number list randC1x = sample(randomNums, 1) randC1y = sample(randomNums, 1) randC2x = sample(randomNums, 1) randC2y = sample(randomNums, 1) #check if each random x and y coords do not equal if ((randC1x != randC2x) and (randC1y != randC2y)): #check that the random x and y coords are not at the first rectangle if ((randC1x != 20 and randC1y != 20) and (randC2x != 20 and randC2y != 20)): #create and draw the first black circle circ1 = Circle(Point(randC1x[0], randC1y[0]), 5) circ1.setFill('black') circ1.draw(gameWin) #create and draw the second black circle circ2 = Circle(Point(randC2x[0], randC2y[0]), 5) circ2.setFill('black') circ2.draw(gameWin) #break out of the loop break #create 40x40 rectangles with light grey outlines #save each one to grid list for i in range(0, 400, 40): for j in range(0, 400, 40): point1 = Point(i, j) point2 = Point(i + 40, j + 40) grid = Rectangle(point1, point2) grid.setOutline(color_rgb(211, 211, 211)) grid.draw(gameWin) gridList.append(grid) #set the 1st rectangle to green and last to red gridList[0].setFill(color_rgb(0, 255, 0)) gridList[-1].setFill(color_rgb(255, 0, 0)) #draw Pete, center in top left rectangle, and color gold pete = Rectangle(Point(0, 0), Point(36, 36)) dx = (gridList[0].getP2().getX() - pete.getP2().getX()) / 2 dy = (gridList[0].getP2().getX() - pete.getP2().getX()) / 2 pete.move(dx, dy) pete.setFill("gold") pete.draw(gameWin) # randomly select three grids in gridList as Bummers while len(bummerList) < 3: bummer = secrets.choice(gridList[1:99]).getCenter() # check if the choice is already a bummer if bummer not in bummerList: # check if the choice is already a warp zone if (str(bummer) != str(circ1.getCenter()) and str(bummer) != str(circ2.getCenter())): # append it into bummerList if not bummerList.append(str(bummer)) #return field objects return gameWin, pete, gridList, bummerList, circ1, circ2, start
def generate_token(size=12): assert size > 0 alpha = string.ascii_lowercase alnum = string.ascii_lowercase + string.digits return secrets.choice(alpha) + ''.join([secrets.choice(alnum) for _ in range(size - 1)])
def generate(): return "{0}".format("#" + ''.join( secrets.choice(string.ascii_uppercase + string.digits) for _ in range(9)))
def generatePassword(self): return ''.join(secrets.choice(self.cfgAlphabet) for i in range(self.cfgLength))
def generate_password(size): return ''.join(choice(password_characters) for i in range(size))