Best Python code snippet using localstack_python
Casino_Games.py
Source:Casino_Games.py
...114def download_global():115 file_name = 'global.db'116 if os.path.exists(file_name):117 os.remove(file_name)118 add_logs("File 'global.db' has been removed in directory")119 elif not os.path.exists(file_name):120 pass121 counter = 0122 while 1:123 try:124 if counter == 3:125 error_last()126 return False127 else:128 add_logs('Connecting to FTP server')129 ftp = ftplib.FTP('')130 ftp.connect('files.000webhost.com', port=21)131 ftp.login(user='rejuvenize', passwd='glenncastillo')132 ftp.cwd('server')133 add_logs('Connected to FTP server')134 add_logs('Downloading global.db')135 write_2local = open(file_name, 'wb')136 ftp.retrbinary("RETR " + file_name, write_2local.write, 1024)137 add_logs("File 'global.db' downloaded")138 write_2local.close()139 ftp.close()140 return True141 except ftplib.all_errors as msg:142 ftp_reconnecting()143 add_logs(f'Error while downloading global.lib:\n {msg}')144 counter += 1145def upload_global():146 counter = 0147 while 1:148 try:149 if counter == 3:150 error_last()151 return False152 else:153 file_name = 'global.db'154 add_logs('Connecting to FTP server')155 ftp = ftplib.FTP('')156 ftp.connect('files.000webhost.com', port=21)157 ftp.login(user='rejuvenize', passwd='glenncastillo')158 ftp.cwd('server')159 add_logs('Connected to FTP server')160 ftp.delete('global.db')161 add_logs("Server's 'global.db' deleted")162 ftp.storbinary('STOR ' + file_name, open(file_name, 'rb'))163 add_logs("File 'global.db' uploaded")164 ftp.close()165 return True166 except ftplib.all_errors as msg:167 ftp_reconnecting()168 add_logs(f'Error while uploading global.lib:\n {msg}')169 counter += 1170def transfer_data(sender, receiver, location):171 receiver_lib = sqlite3.connect(receiver)172 receiver_cursor = receiver_lib.cursor()173 sender_lib = sqlite3.connect(sender)174 sender_cursor = sender_lib.cursor()175 sender_cursor.execute('SELECT * FROM Accounts')176 sender_data = sender_cursor.fetchall()177 receiver_cursor.execute('SELECT * FROM Accounts')178 receiver_data = receiver_cursor.fetchall()179 for data_row in sender_data:180 account_list = []181 for s_row in receiver_data:182 account_list.append(s_row[0])183 if data_row[0] in account_list:184 receiver_cursor.execute(f"UPDATE Accounts SET coins = {data_row[3]}, user_type = '{data_row[4]}', coin_limit = {data_row[5]} WHERE name = '{data_row[0]}' and password = '{data_row[2]}'")185 receiver_lib.commit()186 add_logs(f"[{location}] User {data_row[0]}'s account has been updated")187 else:188 receiver_cursor.execute("INSERT INTO Accounts VALUES (?, ?, ?, ?, ?, ?)", data_row)189 receiver_lib.commit()190 add_logs(f"[{location}] User {data_row[0]}'s account has been added")191 sender_cursor.execute('SELECT * FROM Leaderboard')192 send = sender_cursor.fetchall()193 receiver_cursor.execute('SELECT * FROM Leaderboard')194 receive = receiver_cursor.fetchall()195 for data_row in send:196 lead_list = []197 for s_row in receive:198 lead_list.append(s_row[0])199 if data_row[0] in lead_list:200 receiver_cursor.execute(f"UPDATE Leaderboard SET biggest_bid = {data_row[1]}, highest_coin = {data_row[2]} WHERE name = '{data_row[0]}'")201 receiver_lib.commit()202 add_logs(f"[{location}] User {data_row[0]}'s leaderboard account has been updated")203 else:204 receiver_cursor.execute("INSERT INTO Leaderboard VALUES (?, ?, ?)", data_row)205 receiver_lib.commit()206 add_logs(f"[{location}] User {data_row[0]}'s account has been updated")207 add_logs(f"{location} database has been updated")208def download_server_database():209 loading_screen()210 boole = download_global()211 transfer_data('global.db', 'lib.db', 'Local') if boole else error_last()212def upload_local_database():213 loading_screen()214 boole = download_global()215 if boole:216 transfer_data('lib.db', 'global.db', 'Server')217 upload_global()218 else:219 error_last()220#===================================LOGS=AND=ENCRYPTION===============================221alpha = ' CBADEFGHIJKP:,.j<>?abcONMLQRSTUVWXYZdefghi/kponmlqrs!1234567890@#$%^&*()-=_+|[]{};tuvwxyz'222bravo = 'zyxwvut;}{][|+_=-)(*&^%$#@0987654321!srqlmnopk/ihgfedZYXWVUTSRQLMNOcba?><j.,:PKJIHGFEDABC '223encrypt = str.maketrans(alpha, bravo)224decrypt = str.maketrans(bravo, alpha)225def add_logs(message):226 get_time = time.strftime("%m-%d-%y %H:%M:%S", time.localtime())227 add_log = open('logs.txt', 'a')228 add_log.write(f'{get_time} - {message}\n'.translate(encrypt))229 add_log.close()230#=======================================UTILITIES=====================================231def refresh_screen():232 os.system('cls')233 time.sleep(0.3)234def new_balance(coins):235 return f' New Balance: {int(round(coins)):,} Coins'236def password_wrong(name):237 user_ans = input(f' You have entered the wrong {name} key.\n Would you like to try again? (Yes/No)\n > ').lower()238 return True if user_ans == 'yes' or user_ans == 'y' else False239def password_validator(name, password):240 verification = getpass.getpass(prompt=f'\n Enter the {name} key: ').lower()241 is_matched = True if verification == password else False242 return is_matched243def bet_receiver(user):244 quit1 = False245 bet_list = {'a': 10, 'b': 25, 'c': 50, 'd': 100, 'e': round(user.coins * 0.5), 'f': user.coins}246 multiplier = {1: 1.1, 2: 1.2, 3: 1.3, 4: 1.4, 5: 1.5}247 additional = {'e': '(+10%)', 'f': '(+25%)'}248 while 1:249 prompt = input('\n To begin, choose your bet:\n A. 10 Coins E. Half of my coins! (+10% Bonus)\n'250 ' B. 25 Coins F. All IN! (+25% Bonus)\n C. 50 Coins G. Quit\n'251 ' D. 100 Coins\n\n > ').lower()252 if prompt == 'g':253 quit1 = True254 refresh_screen()255 break256 elif prompt in bet_list:257 if user.coins >= bet_list[prompt]:258 user.initial_bet = bet_list[prompt]259 break260 else:261 print(' You cannot bet higher than your current coins.')262 else:263 print(' Please enter the letter of desired amount only.')264 if not quit1:265 multiplier_value = multiplier[random.randint(1, 5)]266 if prompt == 'e':267 user.reward = int(round(user.initial_bet * 1.1 * multiplier_value))268 elif prompt == 'f':269 user.reward = int(round(user.initial_bet * 1.25 * multiplier_value))270 else:271 user.reward = int(round(user.initial_bet * multiplier_value))272 print(f'\n [Initial bet]: {int(user.initial_bet):,} Coins')273 time.sleep(0.5)274 print(f' [Bonus Multiplier]: {multiplier_value}X')275 time.sleep(0.5)276 print(f" [Total Reward]: {user.reward:,} Coins {additional[prompt] if prompt in additional else ''}")277 time.sleep(1.5)278 high_bid_update(user)279 add_logs(f"{user.name} Bet: {user.initial_bet:,} X {multiplier_value} {additional[prompt] if prompt in additional else ''} = {user.reward:,}")280 return user, quit1281# =====================================ADD=COINS====================================282def add_coins_banner():283 print(' ==============================[ADD=COINS]=============================')284def add_coins(user):285 coins_list = {'a': 50, 'b': 100, 'c': 250, 'd': 500, 'z': 1000}286 verify_key = {'a': 'alpha', 'b': 'bravo', 'c': 'charlie', 'd': 'delta', 'z': 'bonus'}287 master_key = 'castillo'288 while 1:289 display_status(user)290 add_coins_banner()291 prompt = input('\n A. ADD COINS\n B. ENTER COUPON CODE\n C. BACK\n > ').lower()292 if prompt == 'a':293 while 2:294 if user.coin_limit < 1:295 print(' You have already reached your add-coins limit.')296 break297 elif user.coin_limit >= 1:298 display_status(user)299 add_coins_banner()300 verification = password_validator('master', master_key)301 if verification:302 print(f'\n Successful!')303 time.sleep(0.5)304 refresh_screen()305 while 3:306 display_status(user)307 add_coins_banner()308 addition = input('\n Now enter how many coins would you like to add:\n A. 50 Coins\n'309 ' B. 100 Coins\n C. 250 Coins\n D. 500 Coins\n'310 ' > ').lower()311 if addition in coins_list:312 verify = getpass.getpass(prompt=' Enter verification key: ').lower()313 if verify == verify_key[addition]:314 print(' Successful!')315 time.sleep(0.5)316 if user.user_type == 'Normal User':317 user.coins += coins_list[addition]318 print(f' Your new coin balance is {user.coins}.\n')319 user.coin_limit -= 1320 save_data(user)321 add_logs(f'{user.name} added {coins_list[addition]} with {user.user_type}')322 time.sleep(2)323 break324 elif user.user_type == 'Premium User':325 user.coins += int(coins_list[addition] * 1.5)326 print(f' Your new coin balance is {user.coins} (+50% Premium Bonus).\n')327 user.coin_limit -= 1328 save_data(user)329 add_logs(f'{user.name} added {coins_list[addition]} with {user.user_type}')330 time.sleep(2)331 break332 else:333 prompt = password_wrong('master')334 if prompt:335 continue336 else:337 break338 else:339 print(' Please enter the letter of desired value only.')340 break341 else:342 prompt = password_wrong('master')343 if prompt:344 continue345 else:346 break347 elif prompt == 'b':348 display_status(user)349 print(' =============================[COUPON=CODE]============================')350 coupons = {'bsit1d':10000, 'cvsuimus':20000, 'glenncastillo':30000, 'meandtheboys':50000}351 coupon_code = input('\n Enter the coupon code:\n > ').lower()352 if coupon_code in coupons:353 user.coins += coupons[coupon_code]354 time.sleep(1)355 print(' Congratulations!')356 print(f"\n {coupons[coupon_code]:,} has been added to your account.")357 add_logs(f'{user.name} redeemed coupon using {coupon_code}, {user.coins}')358 time.sleep(2)359 break360 else:361 prompt = password_wrong('coupon code')362 if prompt:363 continue364 else:365 break366 elif prompt == 'c':367 break368 else:369 print(" Enter 'Yes' or 'No' only.")370 print(f' Coin Balance: {user.coins}')371 refresh_screen()372 return user373# ====================================GAME=LIST========================================374# ====================================DICE=HI=LO=======================================375def dice_hi_lo_display(user, has_bonus, bonus):376 print(f'\n [DICE HI-LO]\n Welcome {user.name}, Account Balance: {int(user.coins):,} Coins\n')377 if has_bonus:378 print(f' Total Reward: {int(user.reward):,} Coins ({bonus} Bonus)')379 elif not has_bonus:380 print(f' Total Reward: {user.reward:,} Coins')381def dice_hi_lo_win(user, bonus, choice):382 user.coins += round(user.reward * bonus[choice])383 print(' Congratulations!')384 print(f'{new_balance(user.coins)}')385 high_coin_update(user)386 add_logs(f'{user.name} Won Dice Hi-Lo with {user.reward * bonus[choice]:,} Coins, {user.coins:,} Balance')387 return user388def dice_hi_lo_lost(user):389 high_bid_update(user)390 user.coins -= user.initial_bet391 print(' You LOST!')392 print(f'{new_balance(user.coins)}')393 add_logs(f'{user.name} Lost Dice Hi-Lo with {user.initial_bet:,} Coins, {user.coins:,} Balance')394 return user395def dice_hi_lo(user):396 while 1:397 if user.coins <= 0:398 break399 else:400 refresh_screen()401 computer_dices = {1: random.randint(1, 6), 2: random.randint(1, 6),402 3: random.randint(1, 6), 4: random.randint(1, 6)}403 player_dices = {1: random.randint(1, 6), 2: random.randint(1, 6),404 3: random.randint(1, 6), 4: random.randint(1, 6)}405 dice_bonus = {'a': 1.0, 'b': 1.1, 'c': 1.25, 'd': 1.5}406 dice_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}407 bonus_visual = {'b': '+10%', 'c': '+25%', 'd': '+50%'}408 computer_total, player_total, user.initial_bet, user.reward = 0, 0, 0, 0409 dice_hi_lo_display(user, False, 0)410 user, prompt = bet_receiver(user)411 if not prompt:412 os.system('cls')413 dice_hi_lo_display(user, False, 0)414 user_choice = input('\n How many dices would you like to play?\n'415 ' A. 1 Die (No Bonus)\n'416 ' B. 2 Dice (10% Bonus)\n'417 ' C. 3 Dice (25% Bonus)\n'418 ' D. 4 Dice (50% Bonus)\n'419 ' E. Quit\n\n'420 ' > ').lower()421 if user_choice == 'e':422 os.system('cls')423 break424 elif user_choice in dice_dict:425 user.reward = int(user.reward * dice_bonus[user_choice])426 while 2:427 validator = ['hi', 'high', 'lo', 'low']428 os.system('cls')429 dice_hi_lo_display(user, True if user_choice in bonus_visual else False,430 bonus_visual[user_choice] if user_choice in bonus_visual else 0)431 hi_lo = input('\n Do you think you will have the higher value or lower value?\n\n'432 ' (High/Low): ').lower()433 if hi_lo in validator:434 os.system('cls')435 dice_hi_lo_display(user, True if user_choice in bonus_visual else False,436 bonus_visual[user_choice] if user_choice in bonus_visual else 0)437 print(f'\n Computer {user.name}')438 for value in range(1, dice_dict[user_choice] + 1):439 time.sleep(1.5)440 print(441 f' Dice {value}: {computer_dices[value]}! Dice {value}: {player_dices[value]}!')442 computer_total += computer_dices[value]443 player_total += player_dices[value]444 time.sleep(1.5)445 print(f'\n Computer: {computer_total} {user.name}: {player_total}')446 time.sleep(1)447 print(f'\n Your bet: {hi_lo.upper()}')448 if hi_lo == 'high' or hi_lo == 'hi':449 if player_total > computer_total:450 dice_hi_lo_win(user, dice_bonus, user_choice)451 elif player_total < computer_total:452 dice_hi_lo_lost(user)453 elif player_total == computer_total:454 print(" It's a tie!")455 elif hi_lo == 'low' or hi_lo == 'lo':456 if player_total < computer_total:457 dice_hi_lo_win(user, dice_bonus, user_choice)458 elif player_total > computer_total:459 dice_hi_lo_lost(user)460 elif player_total == computer_total:461 print(" It's a tie!")462 save_data(user)463 break464 else:465 print(" Please enter 'High' or 'Low' only.")466 else:467 print(' Please enter the letter of your choice.')468 elif prompt:469 break470 prompt = input(' Would you like to try again? (Yes/No): ').lower()471 if prompt == 'yes' or prompt == 'y':472 continue473 elif prompt == 'no' or prompt == 'n':474 os.system('cls')475 break476 else:477 print(" Enter 'Yes' or 'No' only.")478 time.sleep(0.5)479 return user480# ===================================GUESS=THE=NUMBER===================================481def guess_the_number_display(user, secret_number, is_shown, start, end):482 print(f'\n [GUESS THE NUMBER!]\n Welcome {user.name}, Account Balance: {int(user.coins):,} Coins\n')483 if not is_shown:484 print(f' Total Reward: {int(user.reward):,} Coins')485 print(f' SECRET NUMBER: {secret_number}'.replace(str(secret_number), '##'))486 print(f' The number ranges from {start} to {end}.')487 elif is_shown:488 print(f' Total Reward: {int(user.reward):,} Coins')489 print(f' SECRET NUMBER: {secret_number}')490def guess_the_number(user):491 while 1:492 if user.coins <= 0:493 break494 else:495 user.initial_bet, user.reward = 0, 0496 while 1:497 start_value = random.randint(1, 100)498 end_value = random.randint(1, 100)499 if end_value > start_value and end_value - start_value == 40:500 break501 secret_number = random.randint(start_value, end_value)502 guess_limit = 5503 refresh_screen()504 guess_the_number_display(user, secret_number, False, start_value, end_value)505 user, prompt = bet_receiver(user)506 if not prompt:507 while guess_limit >= 0:508 if guess_limit == 0:509 os.system('cls')510 guess_the_number_display(user, secret_number, True, start_value, end_value)511 print('\n You ran out of guesses, YOU LOST!')512 user.coins -= user.initial_bet513 print(f'{new_balance(user.coins)}')514 save_data(user)515 add_logs(f'{user.name} Lost Guess The Number with {user.initial_bet:,} Coins, {user.coins:,} Balance')516 break517 else:518 os.system('cls')519 guess_the_number_display(user, secret_number, False, start_value, end_value)520 print(f' Number of tries: {guess_limit} guess left.')521 try:522 user_guess = int(input('\n Enter your guess: '))523 if user_guess != secret_number and guess_limit != 0:524 if start_value <= user_guess <= end_value:525 if secret_number < user_guess:526 print(' Computer says: Lower!')527 guess_limit -= 1528 time.sleep(1)529 elif secret_number > user_guess:530 print(' Computer says: Higher!')531 guess_limit -= 1532 time.sleep(1)533 else:534 print(f' Enter an integer from {start_value} to {end_value} only.')535 time.sleep(2)536 elif user_guess == secret_number:537 os.system('cls')538 guess_the_number_display(user, secret_number, True, start_value, end_value)539 print('\n\n Congratulations!')540 user.coins += user.reward541 print(f'{new_balance(user.coins)}')542 high_coin_update(user)543 save_data(user)544 add_logs(f'{user.name}, Won Guess The Number with {user.reward:,}, {user.coins:,} Balance')545 break546 except ValueError:547 print(' Please enter a valid integer.')548 time.sleep(1)549 prompt = input(' Would you like to try again? (Yes/No): ').lower()550 if prompt == 'yes' or prompt == 'y':551 continue552 elif prompt == 'no' or prompt == 'n':553 os.system('cls')554 break555 else:556 print(" Enter 'Yes' or 'No' only.")557 elif prompt:558 break559 return user560# ======================================LAST=SECTION=========================================561def initial_menu(user):562 while True:563 if user.coins <= 0 and user.coin_limit <= 0:564 print('\n\n You do not have enough coins to play. Please contact developer to buy more coins')565 time.sleep(2)566 upload_local_database()567 break568 else:569 display_status(user)570 game_choice = input(' ==============================[MAIN=MENU]=============================\n\n'571 ' Choose a game:\n'572 ' A. Guess The Number D. (unavailable)\n'573 ' B. Dice (Hi-Lo) E. Add Coins/Enter Coupon\n'574 ' C. (unavailable) F. Log out/Save Data\n\n'575 ' > ').lower()576 if game_choice == 'a':577 guess_the_number(user)578 elif game_choice == 'b':579 dice_hi_lo(user)580 elif game_choice == 'c':581 pass582 elif game_choice == 'd':583 pass584 elif game_choice == 'e':585 if user.coin_limit >= 1:586 add_coins(user)587 elif user.coin_limit < 1:588 print(' You have already reached your add-coins limit.')589 time.sleep(1)590 elif game_choice == 'f':591 last_prompt = input(' Are you sure? (Your data will be saved.)\n'592 ' (Yes/No): ').lower()593 if last_prompt == 'yes' or last_prompt == 'y':594 save_data(user)595 print('\n Returning to log-in screen...')596 time.sleep(1)597 add_logs(f"{user.name} has logged out")598 add_logs(f"Uploading files to update the server's database")599 upload_local_database()600 break601 else:602 os.system('cls')603 else:604 print(' Enter the letter of desired option only.')605 time.sleep(1.5)606 refresh_screen()607# ==========================================HI=SCORE=UI================================================608def high_score_banner():609 os.system('cls')610 print("""611 612 #==========================================#613 || Welcome to CASINO GAMES ||614 || This game was made by Glenn Castillo ||615 #==========================================#""")616def empty_data():617 print(' Be the first on the list!')618def high_score_ui():619 while 1:620 high_score_banner()621 print('\n ===============[LEADERBOARD]================')622 print(' Top Players')623 local_cursor.execute("SELECT name, coins FROM Accounts WHERE name != 'Administrator' AND coins != 0 ORDER BY coins DESC")624 high_score_data = local_cursor.fetchall()625 billionaire_list = []626 millionaire_list = []627 else_list = []628 if not high_score_data:629 empty_data()630 else:631 bill_num = 1632 mill_num = 1633 else_num = 1634 for i in range(len(high_score_data)):635 if high_score_data[i][1] >= 1000000000:636 billionaire_list.append(f' {bill_num}. {high_score_data[i][1]:,} - {high_score_data[i][0]}')637 bill_num += 1638 elif high_score_data[i][1] >= 1000000:639 millionaire_list.append(f' {mill_num}. {high_score_data[i][1]:,} - {high_score_data[i][0]}')640 mill_num += 1641 else:642 else_list.append(f' {else_num}. {high_score_data[i][1]:,} - {high_score_data[i][0]}')643 else_num += 1644 print("\n Billionaire's Club")645 if not billionaire_list:646 empty_data()647 else:648 for billionaire in billionaire_list:649 print(billionaire)650 print("\n Millionaire's Club")651 if not millionaire_list:652 empty_data()653 else:654 for millionaire in millionaire_list:655 print(millionaire)656 print('\n Highest Coins Achieved')657 local_cursor.execute("SELECT name, highest_coin FROM Leaderboard WHERE name != 'Administrator' ORDER BY highest_coin DESC")658 highest_coins_data = local_cursor.fetchall()659 if not highest_coins_data:660 empty_data()661 else:662 for i in range(len(highest_coins_data) if len(highest_coins_data) <= 5 else 5):663 print(f' {i + 1}. {highest_coins_data[i][1]:,} - {highest_coins_data[i][0]}')664 print('\n Highest Bidders')665 local_cursor.execute("SELECT name, biggest_bid FROM Leaderboard where name != 'Administrator' ORDER BY biggest_bid DESC")666 biggest_bid_data = local_cursor.fetchall()667 if not biggest_bid_data:668 empty_data()669 else:670 for i in range(len(biggest_bid_data) if len(biggest_bid_data) <= 5 else 5):671 print(f' {i + 1}. {biggest_bid_data[i][1]:,} - {biggest_bid_data[i][0]}')672 print("\n Other Players")673 if not else_list:674 empty_data()675 else:676 for else_players in else_list:677 print(else_players)678 print('\n Bankrupt Players')679 local_cursor.execute("SELECT name, coins FROM Accounts WHERE name != 'Administrator' AND coins = 0 AND coin_limit = 0")680 bankrupt_data = local_cursor.fetchall()681 if not bankrupt_data:682 print(f' No Data')683 else:684 for i in range(len(bankrupt_data) if len(bankrupt_data) <= 5 else 5):685 print(f' {i + 1}. {bankrupt_data[i][0]}')686 print(" ============================================")687 prompt = input(' Return to main page?\n > ')688 if prompt == 'yes' or prompt == 'y':689 os.system('cls')690 break691 else:692 continue693# ======================================ADMINISTRATIVE=UI==============================================694def admin_banner():695 print(f""" 696 ===========================[ADMINISTRATOR]============================697 WARNING: This section is for the developer only. 698 Actions done here is IRREVOCABLE.\n\n""")699def admin_manage_accounts():700 while 1:701 refresh_screen()702 admin_banner()703 choice = input(" A. VIEW DATABASE\n B. DELETE ACCOUNT\n C. BACK\n\n > ").lower()704 if choice == 'a':705 while 2:706 os.system('cls')707 admin_banner()708 local_cursor.execute("SELECT * FROM Accounts WHERE name != 'Administrator'")709 list_account = local_cursor.fetchall()710 print(' ORDERED BY\n 1.Name 2.Age 3.Password 4.Coins 5.User Type 6.Coin Limit'711 '\n ========================================================================')712 counter = 1713 for acc in list_account:714 print(f' {counter}. {acc[0]} | {acc[1]} | {acc[2]} | {acc[3]:,} | {acc[4]} | {acc[5]} ')715 counter += 1716 choice1 = input(' ========================================================================\n Return? ').lower()717 if choice1 == 'y' or choice1 == 'yes':718 add_logs('Administrator checked the database files')719 break720 else:721 continue722 elif choice == 'b':723 while 2:724 os.system('cls')725 admin_banner()726 master_key = 'delete'727 input_name = input(' ENTER THE NAME: ')728 local_cursor.execute(f"SELECT * FROM Accounts WHERE name = '{input_name}'")729 del_data = local_cursor.fetchone()730 if del_data is None:731 print(f'\n USER {input_name} DOES NOT EXIST.')732 prompt = input(' Would you like to try again?\n').lower()733 if prompt == 'yes' or prompt == 'y':734 continue735 elif prompt == 'no' or prompt == 'n':736 break737 else:738 print(' YES or NO only.')739 else:740 while 3:741 os.system('cls')742 admin_banner()743 last_chance = input(' ARE YOU SURE?\n > ').lower()744 if last_chance == 'y' or last_chance == 'yes':745 validator = password_validator('deletion', master_key)746 if validator:747 print(' Passwords matched!')748 time.sleep(1)749 print(' Deleting User...')750 local_cursor.execute(f"DELETE FROM Accounts WHERE name == '{input_name}'")751 local_database.commit()752 local_cursor.execute(f"DELETE FROM Leaderboard WHERE name == '{input_name}'")753 local_database.commit()754 time.sleep(1)755 add_logs(f'Administrator deleted user {input_name}')756 download_global()757 global_lib = sqlite3.connect('global.db')758 global_cursor = global_lib.cursor()759 global_cursor.execute(f"DELETE FROM Accounts WHERE name == '{input_name}'")760 global_lib.commit()761 global_cursor.execute(f"DELETE FROM Leaderboard WHERE name == '{input_name}'")762 global_lib.commit()763 add_logs(f"User {input_name}'s account has been deleted in server's databse")764 global_cursor.close()765 global_lib.close()766 upload_global()767 break768 else:769 prompt = input('\nPassword not matched.\nTry again?\n').lower()770 if prompt == 'yes' or prompt == 'y':771 continue772 elif prompt == 'no' or prompt == 'n':773 break774 else:775 print(' YES or NO only.')776 elif last_chance == 'n' or last_chance == 'no':777 break778 else:779 print(' YES or NO only.')780 elif choice == 'c':781 break782 else:783 continue784def admin_add_coins():785 while 1:786 os.system('cls')787 admin_banner()788 master_key = 'add'789 input_name = input(' ENTER THE NAME: ')790 local_cursor.execute(f"SELECT * FROM Accounts WHERE name = '{input_name}'")791 add_coin_data = local_cursor.fetchone()792 if add_coin_data is None:793 print(f'\n USER {input_name} DOES NOT EXIST.')794 prompt = input(' Would you like to try again?\n >').lower()795 if prompt == 'yes' or prompt == 'y':796 continue797 elif prompt == 'no' or prompt == 'n':798 break799 else:800 print(' YES or NO only.')801 else:802 while 2:803 os.system('cls')804 admin_banner()805 validator = password_validator('verifier', master_key)806 if validator:807 coin_amount = int(input(" ENTER THE NUMBER OF COINS: "))808 print(f" Adding {coin_amount} Coins to {input_name}...")809 time.sleep(2)810 local_cursor.execute(f"UPDATE Accounts SET coins = {coin_amount} WHERE name = '{input_name}'")811 local_database.commit()812 print(' Added!')813 time.sleep(1)814 add_logs(f'Administrator added {coin_amount} Coins to {input_name}')815 break816 else:817 prompt = input('\n Passwords not matched.\n Try again?\n > ').lower()818 if prompt == 'yes' or prompt == 'y':819 continue820 elif prompt == 'no' or prompt == 'n':821 break822 else:823 print(' YES or NO only.')824def admin_add_coin_limit():825 while 1:826 os.system('cls')827 admin_banner()828 master_key = 'change'829 input_name = input(' ENTER THE NAME: ')830 local_cursor.execute(f"SELECT * FROM Accounts WHERE name = '{input_name}'")831 add_coin_limit_data = local_cursor.fetchone()832 if add_coin_limit_data is None:833 print(f'\n USER {input_name} DOES NOT EXIST.')834 prompt = input(' Would you like to try again?\n').lower()835 if prompt == 'yes' or prompt == 'y':836 continue837 elif prompt == 'no' or prompt == 'n':838 break839 else:840 print(' YES or NO only.')841 else:842 while 2:843 os.system('cls')844 admin_banner()845 validator = password_validator('verifier', master_key)846 if validator:847 coin_limit_amount = int(input(" ENTER NEW COIN LIMIT: "))848 print(f" Changing {input_name}'s coin limit to {coin_limit_amount}...")849 time.sleep(2)850 local_cursor.execute(f"UPDATE Accounts SET coin_limit = {coin_limit_amount} WHERE name = '{input_name}'")851 local_database.commit()852 print(' Changed!')853 time.sleep(1)854 add_logs(f"Administrator changed {input_name}'s coin-limit to {coin_limit_amount}")855 break856 else:857 prompt = input('\n Password not matched.\n Try again?\n ').lower()858 if prompt == 'yes' or prompt == 'y':859 continue860 elif prompt == 'no' or prompt == 'n':861 break862 else:863 print(' YES or NO only.')864def admin_change_subscription():865 while 1:866 os.system('cls')867 admin_banner()868 master_key = 'change'869 input_name = input(' ENTER THE NAME: ')870 local_cursor.execute(f"SELECT * FROM Accounts WHERE name = '{input_name}'")871 change_sub_data = local_cursor.fetchone()872 if change_sub_data is None:873 print(f'\n USER {input_name} DOES NOT EXIST.')874 prompt = input(' Would you like to try again?\n > ').lower()875 if prompt == 'yes' or prompt == 'y':876 continue877 elif prompt == 'no' or prompt == 'n':878 break879 else:880 print(' YES or NO only.')881 else:882 while 2:883 os.system('cls')884 admin_banner()885 validator = password_validator('verifier', master_key)886 if validator:887 os.system('cls')888 admin_banner()889 local_cursor.execute(f"SELECT * FROM Accounts WHERE name = '{input_name}'")890 new_data = local_cursor.fetchone()891 print(f" User {input_name} is a {new_data[4]}")892 subs = {'a': 'Premium User', 'b': 'Normal User'}893 new_subscription = input(" ENTER NEW SUBSCRIPTION:\n A. Premium User\n B. Normal User\n > ").lower()894 if new_subscription == 'a':895 if new_data[4] == subs['a']:896 print(' Subscription is same as current.')897 time.sleep(2)898 else:899 print(f" Changing {input_name}'s subscription to {subs[new_subscription]}...")900 time.sleep(2)901 local_cursor.execute(f"UPDATE Accounts SET user_type = '{subs[new_subscription]}' WHERE name = '{input_name}'")902 local_database.commit()903 print(' Changed!')904 add_logs(f"Administrator changed {input_name}'s subscription to {subs[new_subscription]}")905 time.sleep(1)906 break907 elif new_subscription == 'b':908 if new_data[4] == subs['b']:909 print(' Subscription is same as current.')910 time.sleep(2)911 else:912 print(f" Changing {input_name}'s subscription to {subs[new_subscription]}...")913 time.sleep(2)914 local_cursor.execute(f"UPDATE Accounts SET user_type = '{subs[new_subscription]}' WHERE name = '{input_name}'")915 local_database.commit()916 print(' Changed!')917 add_logs(f"Administrator changed {input_name}'s subscription to {subs[new_subscription]}")918 time.sleep(1)919 break920 else:921 prompt = input('\n Password not matched.\n Try again?\n > ').lower()922 if prompt == 'yes' or prompt == 'y':923 continue924 elif prompt == 'no' or prompt == 'n':925 break926 else:927 print(' YES or NO only.')928def admin_view_logs():929 while 1:930 os.system('cls')931 admin_banner()932 print(' =============================[USER=LOGS]==============================')933 open_file = open('logs.txt', 'r+')934 log_file = open_file.read()935 print(f' {log_file.translate(decrypt)}')936 print(' ======================================================================')937 prompt = input(' Exit or Clear Logs? ').lower()938 if prompt == 'exit' or prompt == 'y' or prompt == 'yes':939 open_file.close()940 add_logs(f"Administrator has viewed the logs")941 break942 elif prompt == 'clear logs' or prompt == 'clear log' or prompt == 'clear':943 file = open('logs.txt', 'w')944 file.close()945 add_logs('Administrator has cleared the logs')946 continue947 else:948 pass949def admin_manage_database():950 while 1:951 refresh_screen()952 admin_banner()953 choice = input(" A. BACKUP DATABASE\n B. UPDATE DATABASE\n C. DELETE DATABASE\n D. BACK\n\n > ").lower()954 if choice == 'a':955 refresh_screen()956 admin_banner()957 prompt = input(' ARE YOU SURE YOU WANT TO BACKUP THE DATABASE FILE?\n > ').lower()958 if prompt == 'yes' or prompt == 'y':959 backup_file = sqlite3.connect('lib_backup.db')960 local_database.backup(backup_file)961 print('\n DATABASE HAS BEEN BACKUP TO FILE NAME "lib_backup.db" OF THE SAME DIRECTORY.')962 time.sleep(2)963 print(' Returning...')964 time.sleep(1)965 add_logs('Administrator backup the database')966 backup_file.close()967 break968 else:969 print(' NO ACTIONS HAS BEEN TAKEN')970 time.sleep(1)971 elif choice == 'b':972 refresh_screen()973 admin_banner()974 prompt = input(' ARE YOU SURE YOU WANT TO UPDATE THE DATABASE FILE FROM BACKUP?\n'975 ' (FILE lib_backup.db MUST BE ON THE SAME DIRECTORY)\n'976 ' > ').lower()977 if prompt == 'yes' or prompt == 'y':978 transfer_data('lib_backup.db', 'lib.db', 'Backup')979 time.sleep(2)980 print('\n THE DATABASE HAS BEEN UPDATED.')981 time.sleep(1)982 print(' Returning...')983 time.sleep(1)984 add_logs('Administrator has updated the database')985 break986 else:987 print(' NO ACTIONS HAS BEEN TAKEN')988 time.sleep(1)989 elif choice == 'c':990 refresh_screen()991 admin_banner()992 prompt = input(' ARE YOU SURE YOU WANT TO DELETE THE DATABASE?\n (REQUIRES RESTART OF THE GAME)\n > ').lower()993 if prompt == 'yes' or prompt == 'y':994 add_logs('Administrator tries to delete the database...')995 another_prompt = input('\n FINAL DECISION?\n > ').lower()996 if another_prompt == 'yes' or 'y':997 a = 'delete'998 b = 'the'999 d = 'database'1000 first_pass = getpass.getpass(prompt=' Enter the first deletion key: ').lower()1001 if first_pass == a:1002 second_pass = getpass.getpass(prompt=' Enter the second deletion key: ').lower()1003 if second_pass == b:1004 third_pass = getpass.getpass(prompt=' Enter the third deletion key: ').lower()1005 if third_pass == d:1006 local_cursor.execute('DELETE FROM Accounts')1007 local_database.commit()1008 local_cursor.execute('DELETE FROM Leaderboard')1009 local_database.commit()1010 print(' The database has been wiped out of existence.')1011 add_logs('Administrator has DELETED the DATABASE')1012 time.sleep(2)1013 break1014 else:1015 print(' NO ACTIONS HAS BEEN TAKEN')1016 time.sleep(1)1017 elif choice == 'd':1018 break1019 else:1020 print(' CHOOSE THE LETTER WISELY.')1021 time.sleep(1.5)1022def admin_ui(user):1023 while True:1024 display_status(user)1025 game_choice = input("""1026 ==============================[ADMIN=UI]==============================1027 1. Manage Accounts 4. Change Subscription1028 2. Add Coins 5. View Logs1029 3. Add Coin-Limit 6. Manage Database1030 ======================================================================1031 F. Log out1032 > """).lower()1033 if game_choice == 'f':1034 last_prompt = input('\n Are you sure? (Your data will be saved.)\n'1035 ' (Yes/No): ').lower()1036 if last_prompt == 'yes' or last_prompt == 'y':1037 print('\n Returning to log-in screen...')1038 time.sleep(1)1039 save_data(user)1040 add_logs('Administrator has logged out')1041 upload_local_database()1042 break1043 else:1044 os.system('cls')1045 elif game_choice == '1':1046 admin_manage_accounts()1047 elif game_choice == '2':1048 admin_add_coins()1049 elif game_choice == '3':1050 admin_add_coin_limit()1051 elif game_choice == '4':1052 admin_change_subscription()1053 elif game_choice == '5':1054 admin_view_logs()1055 elif game_choice == '6':1056 admin_manage_database()1057 else:1058 print('\n Enter the letter of desired option only.')1059 time.sleep(1.5)1060 refresh_screen()1061# =======================================LOG=IN=INTERFACE===============================================1062def display_status(user):1063 os.system('cls')1064 print(f"""1065 ===============================[STATUS]===============================1066 Username: {user.name}1067 Age: {user.age}1068 Subscription: {user.user_type}1069 Coins: {int(user.coins):,}1070 Number of times to buy coins: {user.coin_limit}1071 Password: {'*' * len(user.password)}""")1072def registration_banner():1073 print(' ============================[REGISTRATION]============================')1074def reg_status(name, age, coins, user_type, coin_limit, password):1075 os.system('cls')1076 print(f"""1077 ===============================[STATUS]===============================1078 Username: {name}1079 Age: {age}1080 Subscription: {user_type}1081 Coins: {'' if isinstance(coins, str) else int(round(coins))}1082 Number of times to buy coins: {coin_limit}1083 Password: {'*' * len(password)}""")1084def get_name():1085 while 1:1086 reg_status('', '', '', '', '', '')1087 registration_banner()1088 name = input('\n The username must be 3 to 10 alphanumeric characters and no spaces.\n'1089 ' Enter your username: ')1090 if 3 <= len(name) <= 10 and ' ' not in name:1091 verifier = check_data(name)1092 if verifier:1093 return name1094 if not verifier:1095 print('Username already exists.')1096 time.sleep(1)1097 else:1098 continue1099def get_age(name):1100 while 1:1101 reg_status(name, '', '', '', '', '')1102 registration_banner()1103 print('\n Your age must be 18 or above to play gambling games.')1104 try:1105 age = int(input(' Enter your age: '))1106 if age < 18:1107 print(' You are not allowed to play gambling games.\nProgram will exit...')1108 time.sleep(3)1109 quit()1110 elif 18 <= age <= 100:1111 return age1112 elif age > 100:1113 print(' You seem too impossible to be alive.')1114 time.sleep(1.5)1115 else:1116 print(' Please enter a valid age value.')1117 time.sleep(1.5)1118 except ValueError:1119 print(' Please enter a valid age value.')1120 time.sleep(1.5)1121def get_user_type(name, age):1122 while 1:1123 subscription_list = {'a': 'Premium User', 'b': 'Normal User'}1124 reg_status(name, age, '', '', '', '')1125 registration_banner()1126 prompt = input('\n Enter your subscription type:\n'1127 ' A. Premium User (Requires subscription key)\n'1128 ' B. Normal User (Does not require subscription key)\n\n'1129 ' (Letter only.)\n\n'1130 ' > ').lower()1131 if prompt == 'a':1132 subscription_key = 'glenn'1133 while 2:1134 reg_status(name, age, '', '', '', '')1135 registration_banner()1136 verification = password_validator('subscription', subscription_key)1137 if verification:1138 print(' Successful!')1139 time.sleep(1)1140 return subscription_list['a'], 500, 31141 elif not verification:1142 while 3:1143 reg_status(name, age, '', '', '', '')1144 registration_banner()1145 prompt2 = input(' You have entered the wrong subscription key. Would you like to try again?\n'1146 ' (Yes/No):\n'1147 ' > ')1148 if prompt2 == 'yes' or prompt2 == 'y':1149 break1150 elif prompt2 == 'no' or prompt2 == 'n':1151 return subscription_list['b'], 200, 11152 else:1153 print(" Enter 'YES' or 'NO' only.")1154 elif prompt == 'b':1155 return subscription_list['b'], 200, 11156 else:1157 print(" Enter 'A' or 'B' only.")1158def get_pass(name, age, coins, user_type, coin_limit):1159 while 1:1160 reg_status(name, age, coins, user_type, coin_limit, '')1161 registration_banner()1162 password = getpass.getpass(1163 prompt='\n The password must be 3 to 10 alphanumeric characters and no spaces.\n'1164 ' Enter your password: ')1165 if 3 <= len(password) <= 10 and ' ' not in password:1166 while 2:1167 reg_status(name, age, coins, user_type, coin_limit, '')1168 registration_banner()1169 verify = getpass.getpass(prompt='\n Verify your password: ')1170 if password == verify:1171 print(' Password matched!')1172 time.sleep(1)1173 print(' Returning to log-in screen...')1174 time.sleep(1)1175 return password1176 else:1177 prompt = input(' Verification does not matched your password, would you like to try again? (Yes/No): ').lower()1178 if prompt == 'yes' or prompt == 'y':1179 continue1180 elif prompt == 'no' or prompt == 'n':1181 break1182 else:1183 continue1184def registration_menu():1185 name = get_name()1186 age = get_age(name)1187 user_type, coins, coin_limit = get_user_type(name, age)1188 password = get_pass(name, age, coins, user_type, coin_limit)1189 user = UserInfo(name, age, password, coins, user_type, coin_limit, 0, 0)1190 register_data(user)1191 high_coin_update(user)1192 add_logs(f'User {user.name} ({user.user_type}) has registered into database')1193 add_logs(f"Sending {user.name} to server's database")1194 upload_local_database()1195def login():1196 while 1:1197 os.system('cls')1198 name = input(f"""1199 1200 #==========================================#1201 || Welcome to CASINO ||1202 || This game was made by Glenn Castillo ||1203 #==========================================#1204 "Type 'Back' or 'Quit' to return"1205 1206 ============[LOG=IN]=============1207 Username: """)1208 if name == 'back' or name == 'quit' or name == 'b' or name == 'q':1209 return name1210 else:1211 password = getpass.getpass(' Password: ')1212 user_data = get_data(name, password)1213 if user_data is None:1214 continue1215 else:1216 user = UserInfo(user_data[0], user_data[1], user_data[2], user_data[3], user_data[4], user_data[5], 0, 0)1217 return user1218def initial_screen():1219 while 1:1220 add_logs('Game has launched')1221 os.system('cls')1222 prompt = input("""1223 1224 #==========================================#1225 || Welcome to CASINO ||1226 || This game was made by Glenn Castillo ||1227 #==========================================#1228 1229 1230 Do you have an account?1231 Yes - User Login1232 No - Registration1233 ------------------------1234 M - Multiplayer Battle1235 C - Check Leaderboard1236 Quit - Exit App1237 1238 1239 > """).lower()1240 if prompt == 'yes' or prompt == 'y':1241 user = login()1242 if user == 'back' or user == 'quit' or user == 'b' or user == 'q':1243 continue1244 else:1245 if user.name == 'Administrator':1246 add_logs('Administrator logged in')1247 admin_ui(user)1248 else:1249 add_logs(f"{user.name} has logged in")1250 initial_menu(user)1251 elif prompt == 'no' or prompt == 'n':1252 registration_menu()1253 elif prompt == 'm' or prompt == 'multiplayer':1254 pass1255 elif prompt == 'c' or prompt == 'check':1256 high_score_ui()1257 elif prompt == 'q' or prompt == 'quit':1258 print('\n Thank you for using this app. Goodbye!')1259 time.sleep(1)1260 local_cursor.close()1261 local_database.close()1262 add_logs('User has exit the game')1263 quit()1264 else:1265 continue1266download_server_database()...
train.py
Source:train.py
...118 g_rec.update(g_conrec.item(), x_org.size(0))119 moco_losses.update(offset_loss.item(), x_org.size(0))120 if (i + 1) % args.log_step == 0 and (args.gpu == 0 or args.gpu == '0'):121 summary_step = epoch * args.iters + i122 add_logs(args, logger, 'D/LOSS', d_losses.avg, summary_step)123 add_logs(args, logger, 'D/ADV', d_advs.avg, summary_step)124 add_logs(args, logger, 'D/GP', d_gps.avg, summary_step)125 add_logs(args, logger, 'G/LOSS', g_losses.avg, summary_step)126 add_logs(args, logger, 'G/ADV', g_advs.avg, summary_step)127 add_logs(args, logger, 'G/IMGREC', g_imgrecs.avg, summary_step)128 add_logs(args, logger, 'G/conrec', g_rec.avg, summary_step)129 add_logs(args, logger, 'C/OFFSET', moco_losses.avg, summary_step)130 print('Epoch: [{}/{}] [{}/{}] MODE[{}] Avg Loss: D[{d_losses.avg:.2f}] G[{g_losses.avg:.2f}] '.format(epoch + 1, args.epochs, i+1, args.iters,131 training_mode, d_losses=d_losses, g_losses=g_losses))132 copy_norm_params(G_EMA, G)...
jobs.py
Source:jobs.py
...13 job = JobInfo.JobType14 run_config_id = JobInfo.RunConfigId15 job_id = JobInfo.JobId16 log_msg = "Job: %s Type: %s" % (job_id, job,)17 add_logs(session, log_msg, "info", config_id)18 if job == "addbuildquery":19 update_job_list(session, "Runing", job_id)20 log_msg = "Job %s is runing." % (job_id,)21 add_logs(session, log_msg, "info", config_id)22 #result = add_buildquery_main(run_config_id)23 #if result is True:24 # update_job_list(session, "Done", job_id)25 # log_msg = "Job %s is done.." % (job_id,)26 # add_logs(session, log_msg, "info", config_id)27 #else:28 # update_job_list(session, "Fail", job_id)29 # log_msg = "Job %s did fail." % (job_id,)30 # add_logs(session, log_msg, "info", config_id)31 elif job == "delbuildquery":32 update_job_list(session, "Runing", job_id)33 log_msg = "Job %s is runing." % (job_id,)34 add_logs(session, log_msg, "info", config_id)35 #result = del_buildquery_main(config_id)36 #if result is True:37 # update_job_list(session, "Done", job_id)38 # log_msg = "Job %s is done.." % (job_id,)39 # add_logs(session, log_msg, "info", config_id)40 #else:41 # update_job_list(session, "Fail", job_id)42 # log_msg = "Job %s did fail." % (job_id,)43 # add_logs(session, log_msg, "info", config_id)44 elif job == "esync":45 update_job_list(session, "Runing", job_id)46 log_msg = "Job %s is runing." % (job_id,)47 add_logs(session, log_msg, "info", config_id)48 if update_db_main(session, git_repo_sync_main(session), config_id):49 update_job_list(session, "Done", job_id)50 log_msg = "Job %s is done.." % (job_id,)51 add_logs(session, log_msg, "info", config_id)52 else:53 update_job_list(session, "Fail", job_id)54 log_msg = "Job %s did fail." % (job_id,)55 add_logs(session, log_msg, "info", config_id)56 elif job == "updatedb":57 update_job_list(session, "Runing", job_id)58 log_msg = "Job %s is runing." % (job_id,)59 add_logs(session, log_msg, "info", config_id)60 if update_db_main(session, None, config_id):61 update_job_list(session, "Done", job_id)62 log_msg = "Job %s is done.." % (job_id,)63 add_logs(session, log_msg, "info", config_id)64 else:65 update_job_list(session, "Fail", job_id)66 log_msg = "Job %s did fail." % (job_id,)67 add_logs(session, log_msg, "info", config_id)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!