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 8b6d120cbf7..2316f5442ef 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 @@ -20,7 +20,6 @@ student_record = os.getenv("STUDENTS_RECORD_FILE") import pickle -import logging # Define logger with info # import polar 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 a6529e15240..3e7729cf377 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,7 +1,6 @@ # binary file to search a given record import pickle -from dotenv import load_dotenv def search(): 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 65c7b4462bc..5f712e6fbe7 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 @@ -9,7 +9,11 @@ ) as F: 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 + 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") diff --git a/Armstrong_number b/Armstrong_number index 7dd1b267ea0..3e73a7528bc 100644 --- a/Armstrong_number +++ b/Armstrong_number @@ -6,8 +6,9 @@ def is_armstrong_number(number): temp = 0 while num != 0: rem = num % 10 - num //= 10 - temp += rem ** length + num //= 10 + temp += rem**length return temp == number - + + is_armstrong_number(5) diff --git a/Automated Scheduled Call Reminders/caller.py b/Automated Scheduled Call Reminders/caller.py index f069da7df88..81471699385 100644 --- a/Automated Scheduled Call Reminders/caller.py +++ b/Automated Scheduled Call Reminders/caller.py @@ -40,7 +40,7 @@ def search(): for doc in list_of_docs: if doc["from"][0:5] == five_minutes_prior: phone_number = doc["phone"] - call = client.calls.create( + client.calls.create( to=phone_number, from_="add your twilio number", url="http://demo.twilio.com/docs/voice.xml", diff --git a/Automated Scheduled Call Reminders/requirements.txt b/Automated Scheduled Call Reminders/requirements.txt index f5635170c24..61824b3fac1 100644 --- a/Automated Scheduled Call Reminders/requirements.txt +++ b/Automated Scheduled Call Reminders/requirements.txt @@ -11,4 +11,4 @@ timedelta credentials firestore initialize_app -Twilio \ No newline at end of file +Twilio diff --git a/Binary_to_Decimal.py b/Binary_to_Decimal.py index ed477d502a6..43c39f63aa9 100644 --- a/Binary_to_Decimal.py +++ b/Binary_to_Decimal.py @@ -10,7 +10,7 @@ def binaryToDecimal(binary): >>> binaryToDecimal(101011) 43 """ - decimal, i, n = 0, 0, 0 + decimal, i, _n = 0, 0, 0 while binary != 0: dec = binary % 10 decimal = decimal + dec * pow(2, i) diff --git a/BoardGame-CLI/snakeLadder.py b/BoardGame-CLI/snakeLadder.py index fd06dd64527..84878ce8bda 100644 --- a/BoardGame-CLI/snakeLadder.py +++ b/BoardGame-CLI/snakeLadder.py @@ -59,7 +59,7 @@ def play(): print(f"you got {temp1}") print("") - if isReady[i] == False and temp1 == 6: + if not isReady[i] and temp1 == 6: isReady[i] = True if isReady[i]: @@ -90,7 +90,6 @@ def play(): elif n == 2: players = {} # stores player ans their locations isReady = {} - current_loc = 1 # reset starting location to 1 player_input() elif n == 3: diff --git a/CRC/crc.py b/CRC/crc.py index d3d302244b7..44e9f7bb0cf 100644 --- a/CRC/crc.py +++ b/CRC/crc.py @@ -1,6 +1,5 @@ def crc_check(data, div): l = len(div) - ct = 0 data = [int(i) for i in data] div = [int(i) for i in div] zero = [0 for i in range(l)] diff --git a/Checker_game_by_dz/first.py b/Checker_game_by_dz/first.py index 0b6825590f8..0ba81d67762 100644 --- a/Checker_game_by_dz/first.py +++ b/Checker_game_by_dz/first.py @@ -41,7 +41,7 @@ def get_row_col_mouse(pos): while run: clock.tick(fps) - if board.winner() != None: + if board.winner() is not None: print(board.winner()) # check if any events is running or not diff --git a/CliYoutubeDownloader/requirements.txt b/CliYoutubeDownloader/requirements.txt index 30257302458..cd5e770101f 100644 --- a/CliYoutubeDownloader/requirements.txt +++ b/CliYoutubeDownloader/requirements.txt @@ -1 +1 @@ -pytube \ No newline at end of file +pytube diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py index f6fa4d56507..373448813e9 100644 --- a/Colors/pixel_sort.py +++ b/Colors/pixel_sort.py @@ -135,19 +135,19 @@ def main(): ) # 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: + if np.all(np.asarray(color)): 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: + if not np.all(np.asarray(color)): 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: + if np.any(np.asarray(i)) and sum(i) < thresh: color_n.append(i) color_n.sort(key=lambda bgr: step(bgr, 8)) # step sorting diff --git a/Day_of_week.py b/Day_of_week.py index c9c36bfada2..f0f9fd6f3b5 100644 --- a/Day_of_week.py +++ b/Day_of_week.py @@ -12,9 +12,9 @@ def process_date(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 + 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 diff --git a/Downloaded Files Organizer/obs.py b/Downloaded Files Organizer/obs.py index 1489f257041..1c6d1b8609d 100644 --- a/Downloaded Files Organizer/obs.py +++ b/Downloaded Files Organizer/obs.py @@ -9,7 +9,7 @@ def watcher(path): class Handler(FileSystemEventHandler): def on_created(self, event): if event.event_type == "created": - file_name = os.path.basename(event.src_path) + 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) diff --git a/Emoji Dictionary/QT_GUI.py b/Emoji Dictionary/QT_GUI.py index ef3f6f0cf40..71af4da2413 100644 --- a/Emoji Dictionary/QT_GUI.py +++ b/Emoji Dictionary/QT_GUI.py @@ -131,7 +131,8 @@ def clear_text(): button = QPushButton(emoji) button.setFixedSize(40, 40) button.setFont(QFont("Arial", 20)) - button.setStyleSheet(""" + button.setStyleSheet( + """ QPushButton { background-color: #ffffff; border: 1px solid #e0e0e0; @@ -140,7 +141,8 @@ def clear_text(): QPushButton:hover { background-color: #f0f0f0; } - """) + """ + ) button.clicked.connect(lambda checked, e=emoji: add_input_emoji(e)) self.emoji_layout.addWidget(button, row_idx, col_idx) self.emoji_buttons.append(button) diff --git a/EncryptionTool.py b/EncryptionTool.py index f6600752fa6..34e365189ae 100644 --- a/EncryptionTool.py +++ b/EncryptionTool.py @@ -48,11 +48,10 @@ def decrypt(enc_text): def readAndDecrypt(filename): file = open(filename, "r") data = file.read() - datalistint = [] actualdata = [] datalist = data.split(" ") datalist.remove("") - datalistint = [float(data) for data in datalist] + [float(data) for data in datalist] for data in datalist: current1 = int(decryptChar(data)) current1 = chr(current1) @@ -66,7 +65,6 @@ def readAndEncrypt(filename): data = file.read() datalist = list(data) encrypted_list = list() - encrypted_list_str = list() for data in datalist: current = ord(data) current = encryptChar(current) diff --git a/Extract-Table-from-pdf-txt-docx/main.py b/Extract-Table-from-pdf-txt-docx/main.py index d74649cd054..07e71ad90a2 100644 --- a/Extract-Table-from-pdf-txt-docx/main.py +++ b/Extract-Table-from-pdf-txt-docx/main.py @@ -6,16 +6,16 @@ # %% -if os.path.isdir("Parent") == True: +if os.path.isdir("Parent"): os.chdir("Parent") # FOR CHILD1 DIRECTORY -if os.path.isdir("Child1") == True: +if os.path.isdir("Child1"): os.chdir("Child1") # PDF FILE READING -if os.path.isfile("Pdf1_Child1.pdf") == True: +if os.path.isfile("Pdf1_Child1.pdf"): df_pdf_child1 = tabula.read_pdf("Pdf1_Child1.pdf", pages="all") # DOCUMENT READING -if os.path.isfile("Document_Child1.docx") == True: +if os.path.isfile("Document_Child1.docx"): document = Document("Document_Child1.docx") table = document.tables[0] data = [] @@ -30,7 +30,7 @@ data.append(row_data) df_document_child1 = pd.DataFrame(data) # TEXT READING -if os.path.isfile("Text_Child1.txt") == True: +if os.path.isfile("Text_Child1.txt"): df_text_child1 = pd.read_csv("Text_Child1.txt") # %% @@ -39,16 +39,16 @@ # %% os.chdir("../") -if os.path.isdir("Parent") == True: +if os.path.isdir("Parent"): os.chdir("Parent") # FOR CHILD2 DIRECTORY -if os.path.isdir("Child2") == True: +if os.path.isdir("Child2"): os.chdir("Child2") # PDF FILE READING -if os.path.isfile("Pdf1_Child2.pdf") == True: +if os.path.isfile("Pdf1_Child2.pdf"): df_pdf_child2 = tabula.read_pdf("Pdf1_Child2.pdf", pages="all") # DOCUMENT READING -if os.path.isfile("Document_Child2.docx") == True: +if os.path.isfile("Document_Child2.docx"): document = Document("Document_Child2.docx") table = document.tables[0] data = [] @@ -63,7 +63,7 @@ data.append(row_data) df_document_child2 = pd.DataFrame(data) # TEXT READING -if os.path.isfile("Text_Child2.txt") == True: +if os.path.isfile("Text_Child2.txt"): df_text_child2 = pd.read_csv("Text_Child2.txt") # %% @@ -71,16 +71,16 @@ # %% os.chdir("../") -if os.path.isdir("Parent") == True: +if os.path.isdir("Parent"): os.chdir("Parent") # FOR CHILD3 DIRECTORY -if os.path.isdir("Child3") == True: +if os.path.isdir("Child3"): os.chdir("Child3") # PDF FILE READING -if os.path.isfile("Pdf1_Child3.pdf") == True: +if os.path.isfile("Pdf1_Child3.pdf"): df_pdf_child3 = tabula.read_pdf("Pdf1_Child3.pdf", pages="all") # DOCUMENT READING -if os.path.isfile("Document_Child3.docx") == True: +if os.path.isfile("Document_Child3.docx"): document = Document("Document_Child3.docx") table = document.tables[0] data = [] @@ -95,7 +95,7 @@ data.append(row_data) df_document_child3 = pd.DataFrame(data) # TEXT READING -if os.path.isfile("Text_Child3.txt") == True: +if os.path.isfile("Text_Child3.txt"): df_text_child3 = pd.read_csv("Text_Child3.txt") # %% diff --git a/FibonacciNumbersWithGenerators.py b/FibonacciNumbersWithGenerators.py index 15771630222..49d35aae1e5 100644 --- a/FibonacciNumbersWithGenerators.py +++ b/FibonacciNumbersWithGenerators.py @@ -8,7 +8,7 @@ def fibonacci_generator(n=None): """ f0, f1 = 0, 1 yield f1 - while n == None or n > 1: + while n is None or n > 1: fn = f0 + f1 yield fn f0, f1 = f1, fn diff --git a/Google_Image_Downloader/image_grapper.py b/Google_Image_Downloader/image_grapper.py index d42f4a3ac86..a50bc3b49e6 100644 --- a/Google_Image_Downloader/image_grapper.py +++ b/Google_Image_Downloader/image_grapper.py @@ -58,7 +58,7 @@ def search_for_image(): 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: diff --git a/Grocery calculator.py b/Grocery calculator.py index 42adbb7cd74..7505d958c06 100644 --- a/Grocery calculator.py +++ b/Grocery calculator.py @@ -11,7 +11,7 @@ # Methods = addToList, Total, Subtotal, returnList class GroceryList(dict): def __init__(self): - self = {} + pass def addToList(self, item, price): self.update({item: price}) diff --git a/Industrial_developed_hangman/src/hangman/main.py b/Industrial_developed_hangman/src/hangman/main.py index 3839d9222f1..7ef112c94f5 100644 --- a/Industrial_developed_hangman/src/hangman/main.py +++ b/Industrial_developed_hangman/src/hangman/main.py @@ -126,7 +126,9 @@ def user_lose(self) -> None: def user_win(self) -> None: """Print text for end of game and exits.""" - print_wrong(f"{self._word_string_to_show} YOU WON", self._print_function) # noqa:WPS305 + print_wrong( + f"{self._word_string_to_show} YOU WON", self._print_function + ) # noqa:WPS305 def game_process(self, user_character: str) -> bool: # noqa: DAR201 diff --git a/Infix_to_Postfix.py b/Infix_to_Postfix.py index 597cd35cef3..541bac2c995 100644 --- a/Infix_to_Postfix.py +++ b/Infix_to_Postfix.py @@ -1,5 +1,6 @@ # Python program to convert infix expression to postfix + # Class to convert the expression class Conversion: # Constructor to initialize the class variables diff --git a/JARVIS/JARVIS_2.0.py b/JARVIS/JARVIS_2.0.py index 676c6b833ce..c57b3044834 100644 --- a/JARVIS/JARVIS_2.0.py +++ b/JARVIS/JARVIS_2.0.py @@ -258,7 +258,7 @@ def get_app(Q): webbrowser.open("https://github.com/") elif Q == "search for": que = Q.lstrip("search for") - answer = ask_gpt3(que) + ask_gpt3(que) elif ( Q == "email to other" @@ -269,7 +269,7 @@ def get_app(Q): with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 - audio = r.listen(source) + r.listen(source) to = "abc@gmail.com" content = input("Enter content") sendEmail(to, content) @@ -307,11 +307,11 @@ def get_app(Q): elif Q == "take a break": exit() else: - answer = ask_gpt3(Q) + ask_gpt3(Q) # master - apps = { + { "time": datetime.datetime.now(), "notepad": "Notepad.exe", "calculator": "calc.exe", diff --git a/JARVIS/requirements.txt b/JARVIS/requirements.txt index ca6bbccddbd..8c113ef6596 100644 --- a/JARVIS/requirements.txt +++ b/JARVIS/requirements.txt @@ -10,4 +10,4 @@ key playsound pyttsx3 SpeechRecognition -openai \ No newline at end of file +openai diff --git a/Key_Binding/requirement.txt b/Key_Binding/requirement.txt index 51d89fc61fc..9848dc29115 100644 --- a/Key_Binding/requirement.txt +++ b/Key_Binding/requirement.txt @@ -1 +1 @@ -quo>=2022.4 +quo >= 2022.4 diff --git a/Letter_Counter.py b/Letter_Counter.py index b900c72b4dc..77b7530e926 100644 --- a/Letter_Counter.py +++ b/Letter_Counter.py @@ -16,7 +16,7 @@ def printt(): # 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) + 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( diff --git a/LinkedLists all Types/doubly_linked_list.py b/LinkedLists all Types/doubly_linked_list.py index ed451dc58cd..715005f6003 100644 --- a/LinkedLists all Types/doubly_linked_list.py +++ b/LinkedLists all Types/doubly_linked_list.py @@ -23,7 +23,7 @@ def __init__(self): def insert_front(self, data): node = Node(data, self.head) - if self.head == None: + if self.head is None: self.tail = node node.prev = self.head self.head = node @@ -31,7 +31,7 @@ def insert_front(self, data): def insert_back(self, data): node = Node(data, None, self.tail) - if self.head == None: + if self.head is None: self.tail = self.head = node self.length += 1 else: @@ -72,7 +72,7 @@ def print(self): temp = self.head print("NULL <-", end=" ") while temp: - if temp.next == None: + if temp.next is None: print(f"{temp.data} ->", end=" ") break print(f"{temp.data} <=>", end=" ") @@ -158,7 +158,7 @@ def remove_by_value(self, idx_data): temp.next.prev = temp.prev self.length -= 1 return - if temp != None: + if temp is not None: temp = temp.next print("The Element is not the List!") @@ -195,7 +195,7 @@ def reverse(self): return prev = c_next = None curr = self.head - while curr != None: + while curr is not None: c_next = curr.next curr.next = prev prev = curr @@ -209,7 +209,7 @@ def mid_element(self): return slow = self.head.next fast = self.head.next.next - while fast != None and fast.next != None: + while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow.data diff --git a/LinkedLists all Types/singly_linked_list.py b/LinkedLists all Types/singly_linked_list.py index f1242b29cf8..eeeec94b2ce 100644 --- a/LinkedLists all Types/singly_linked_list.py +++ b/LinkedLists all Types/singly_linked_list.py @@ -22,14 +22,14 @@ def __init__(self): def insert_front(self, data): node = Node(data, self.head) - if self.head == None: + if self.head is None: self.tail = node self.head = node self.length += 1 def insert_back(self, data): node = Node(data) - if self.head == None: + if self.head is None: self.tail = self.head = node self.length += 1 else: @@ -142,7 +142,7 @@ def remove_by_value(self, idx_data): self.length -= 1 temp.next = None return - while temp.next != None: + while temp.next is not None: if temp.next.data == idx_data: temp.next = temp.next.next self.length -= 1 @@ -184,7 +184,7 @@ def reverse(self): return prev = c_next = None curr = self.head - while curr != None: + while curr is not None: c_next = curr.next curr.next = prev prev = curr @@ -198,7 +198,7 @@ def mid_element(self): return slow = self.head.next fast = self.head.next.next - while fast != None and fast.next != None: + while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next return slow.data diff --git a/Merge_linked_list.py b/Merge_linked_list.py index b5b38a7a132..667148ee0e3 100644 --- a/Merge_linked_list.py +++ b/Merge_linked_list.py @@ -1,6 +1,7 @@ # Python3 program merge two sorted linked # in third linked list using recursive. + # Node class class Node: def __init__(self, data): diff --git a/MySQL_Databses.py b/MySQL_Databses.py index 226a20e742c..4e1a795d72d 100644 --- a/MySQL_Databses.py +++ b/MySQL_Databses.py @@ -1,4 +1,5 @@ import mysql.connector + # MySQl databses details host = input("Enter MySQL host: ") username = input("Enter MySQL username: ") diff --git a/News_App/patterns.py b/News_App/patterns.py index 7d1074c65d3..c576512469f 100644 --- a/News_App/patterns.py +++ b/News_App/patterns.py @@ -98,7 +98,6 @@ "KOTAK MAHINDRA BANK ": "KOTAKBANK.NS", "LARSEN AND TOUBRO ": "LT.NS", "MAHINDRA AND MAHINDRA ": "M&M.NS", - "MARUTI SUZUKI INDIA ": "MARUTI.NS", "NTPC ": "NTPC.NS", "NESTLE INDIA ": "NESTLEIND.NS", "OIL AND NATURAL GAS CORPORATION ": "ONGC.NS", diff --git a/PONG_GAME.py b/PONG_GAME.py index 59b6e566c3d..8ddec6661de 100644 --- a/PONG_GAME.py +++ b/PONG_GAME.py @@ -45,14 +45,7 @@ def new_game(): def draw(canvas): - global \ - paddle1_pos, \ - paddle2_pos, \ - ball_pos, \ - ball_vel, \ - paddle1_vel, \ - paddle2_vel, \ - BALL_RADIUS + global paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel, BALL_RADIUS global score1, score2 canvas.draw_line([WIDTH / 2, 0], [WIDTH / 2, HEIGHT], 1, "White") diff --git a/PORT SCANNER.PY b/PORT SCANNER.PY index 594ea3eb16f..56093829e32 100644 --- a/PORT SCANNER.PY +++ b/PORT SCANNER.PY @@ -75,7 +75,9 @@ from time import time import platform # Clear the screen -subprocess.call('clear' if platform.platform() in ("Linux", "Darwin") else "cls", shell=True) +subprocess.call( + "clear" if platform.platform() in ("Linux", "Darwin") else "cls", shell=True +) # Ask for input remoteServer = input("Enter a remote host to scan: ") @@ -106,7 +108,7 @@ except KeyboardInterrupt: sys.exit(2) except socket.gaierror: - print('Hostname could not be resolved. Exiting') + print("Hostname could not be resolved. Exiting") sys.exit(1) except socket.error: @@ -120,4 +122,4 @@ t2 = time() total = t2 - t1 # Printing the information to screen -print('Scanning Completed in about {total} seconds', total) +print("Scanning Completed in about {total} seconds", total) diff --git a/Password Manager Using Tkinter/PGV.py b/Password Manager Using Tkinter/PGV.py index 045625ea650..9e107c802d8 100644 --- a/Password Manager Using Tkinter/PGV.py +++ b/Password Manager Using Tkinter/PGV.py @@ -1,11 +1,8 @@ import json new_data = { - website_input.get():{ - "email": email_input.get(), - "password": passw_input.get() - } - } + website_input.get(): {"email": email_input.get(), "password": passw_input.get()} +} try: with open("data.json", "r") as data_file: @@ -15,4 +12,4 @@ pass else: with open("data.json", "w") as data_file: - json.dump(new_data, data_file, indent = 4) \ No newline at end of file + json.dump(new_data, data_file, indent=4) diff --git a/Password Manager Using Tkinter/data.json b/Password Manager Using Tkinter/data.json index 399ea997575..64d473ed71b 100644 --- a/Password Manager Using Tkinter/data.json +++ b/Password Manager Using Tkinter/data.json @@ -1,14 +1,14 @@ { "Amazon": { "email": "prashant123Amazon@gmail.com", - "password": "1mD%#Z555rF$&2aRpI" + "password": "1mD%#Z555rF$&2aRpI", }, "Facebook": { "email": "prashant123Facebook@gmail.com", - "password": "qQ6#H7o&)i8S!3sO)c4" + "password": "qQ6#H7o&)i8S!3sO)c4", }, "Flipkart": { "email": "prashant123Flipkart@gmail.com", - "password": "1!+7NqmUZbN18K(3A+" - } -} \ No newline at end of file + "password": "1!+7NqmUZbN18K(3A+", + }, +} diff --git a/Password Manager Using Tkinter/main.py b/Password Manager Using Tkinter/main.py index 15d6fdc1d13..c66072bea99 100644 --- a/Password Manager Using Tkinter/main.py +++ b/Password Manager Using Tkinter/main.py @@ -12,12 +12,66 @@ # in a real application, this should be changed and stored securely (e.g., hashed and salted). MASTER_PASSWORD = "password123" + # ---------------------------- PASSWORD GENERATOR ------------------------------- # def generate_password(): """generates a random strong password and copies it to clipboard.""" - letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] - numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] - symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] + letters = [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + ] + numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] + symbols = ["!", "#", "$", "%", "&", "(", ")", "*", "+"] password_letters = [choice(letters) for _ in range(randint(8, 10))] password_symbols = [choice(symbols) for _ in range(randint(2, 4))] @@ -30,7 +84,10 @@ def generate_password(): password_entry.delete(0, tk.END) password_entry.insert(0, password) pyperclip.copy(password) - messagebox.showinfo(title="Password Generated", message="Password copied to clipboard!") + messagebox.showinfo( + title="Password Generated", message="Password copied to clipboard!" + ) + # ---------------------------- SAVE PASSWORD ------------------------------- # def save(): @@ -46,18 +103,23 @@ def save(): } if not website or not password: - messagebox.showerror(title="Oops", message="Please don't leave any fields empty!") + messagebox.showerror( + title="Oops", message="Please don't leave any fields empty!" + ) return - is_ok = messagebox.askokcancel(title=website, message=f"These are the details entered: \nEmail: {email} " - f"\nPassword: {password} \nIs it ok to save?") + is_ok = messagebox.askokcancel( + title=website, + message=f"These are the details entered: \nEmail: {email} " + f"\nPassword: {password} \nIs it ok to save?", + ) if is_ok: try: with open("data.json", "r") as data_file: data = json.load(data_file) except (FileNotFoundError, json.JSONDecodeError): data = {} - + data.update(new_data) with open("data.json", "w") as data_file: @@ -66,6 +128,7 @@ def save(): website_entry.delete(0, tk.END) password_entry.delete(0, tk.END) + # ---------------------------- FIND PASSWORD ------------------------------- # def find_password(): """finds and displays password for a given website.""" @@ -76,91 +139,123 @@ def find_password(): except (FileNotFoundError, json.JSONDecodeError): messagebox.showerror(title="Error", message="No Data File Found.") return - + if website in data: email = data[website]["email"] password = data[website]["password"] - messagebox.showinfo(title=website, message=f"Email: {email}\nPassword: {password}") + messagebox.showinfo( + title=website, message=f"Email: {email}\nPassword: {password}" + ) pyperclip.copy(password) - messagebox.showinfo(title="Copied", message="Password for {} copied to clipboard.".format(website)) + messagebox.showinfo( + title="Copied", + message="Password for {} copied to clipboard.".format(website), + ) else: messagebox.showerror(title="Error", message=f"No details for {website} exists.") + # ---------------------------- VIEW ALL PASSWORDS ------------------------------- # def view_all_passwords(): """prompts for master password and displays all saved passwords if correct.""" - password = simpledialog.askstring("Master Password", "Please enter the master password:", show='*') - + password = simpledialog.askstring( + "Master Password", "Please enter the master password:", show="*" + ) + if password == MASTER_PASSWORD: show_passwords_window() - elif password is not None: # avoids error message if user clicks cancel - messagebox.showerror("Incorrect Password", "The master password you entered is incorrect.") + elif password is not None: # avoids error message if user clicks cancel + messagebox.showerror( + "Incorrect Password", "The master password you entered is incorrect." + ) + def show_passwords_window(): """creates a new window to display all passwords in a table.""" all_passwords_window = tk.Toplevel(window) all_passwords_window.title("All Saved Passwords") all_passwords_window.config(padx=20, pady=20) - + # a frame for the treeview and scrollbar tree_frame = ttk.Frame(all_passwords_window) - tree_frame.grid(row=0, column=0, columnspan=2, sticky='nsew') - + tree_frame.grid(row=0, column=0, columnspan=2, sticky="nsew") + # a Treeview (table) - cols = ('Website', 'Email', 'Password') - tree = ttk.Treeview(tree_frame, columns=cols, show='headings') - + cols = ("Website", "Email", "Password") + tree = ttk.Treeview(tree_frame, columns=cols, show="headings") + # column headings and widths - tree.heading('Website', text='Website') - tree.column('Website', width=150) - tree.heading('Email', text='Email/Username') - tree.column('Email', width=200) - tree.heading('Password', text='Password') - tree.column('Password', width=200) - - tree.grid(row=0, column=0, sticky='nsew') + tree.heading("Website", text="Website") + tree.column("Website", width=150) + tree.heading("Email", text="Email/Username") + tree.column("Email", width=200) + tree.heading("Password", text="Password") + tree.column("Password", width=200) + + tree.grid(row=0, column=0, sticky="nsew") # a scrollbar scrollbar = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=tree.yview) tree.configure(yscroll=scrollbar.set) - scrollbar.grid(row=0, column=1, sticky='ns') + scrollbar.grid(row=0, column=1, sticky="ns") # load data from JSON file try: with open("data.json", "r") as data_file: data = json.load(data_file) - + # insert data into the treeview for website, details in data.items(): - tree.insert("", "end", values=(website, details['email'], details['password'])) - + tree.insert( + "", "end", values=(website, details["email"], details["password"]) + ) + except (FileNotFoundError, json.JSONDecodeError): # if file not found or empty, it will just show an empty table pass - + def copy_selected_info(column_index, info_type): """copies the email or password of the selected row.""" selected_item = tree.focus() if not selected_item: - messagebox.showwarning("No Selection", "Please select a row from the table first.", parent=all_passwords_window) + messagebox.showwarning( + "No Selection", + "Please select a row from the table first.", + parent=all_passwords_window, + ) return - - item_values = tree.item(selected_item, 'values') + + item_values = tree.item(selected_item, "values") info_to_copy = item_values[column_index] pyperclip.copy(info_to_copy) - messagebox.showinfo("Copied!", f"The {info_type.lower()} for '{item_values[0]}' has been copied to your clipboard.", parent=all_passwords_window) + messagebox.showinfo( + "Copied!", + f"The {info_type.lower()} for '{item_values[0]}' has been copied to your clipboard.", + parent=all_passwords_window, + ) # a frame for the buttons button_frame = ttk.Frame(all_passwords_window) - button_frame.grid(row=1, column=0, columnspan=2, pady=(10,0)) + button_frame.grid(row=1, column=0, columnspan=2, pady=(10, 0)) - copy_email_button = ttk.Button(button_frame, text="Copy Email", style="success.TButton", command=lambda: copy_selected_info(1, "Email")) + copy_email_button = ttk.Button( + button_frame, + text="Copy Email", + style="success.TButton", + command=lambda: copy_selected_info(1, "Email"), + ) copy_email_button.pack(side=tk.LEFT, padx=5) - copy_password_button = ttk.Button(button_frame, text="Copy Password", style="success.TButton", command=lambda: copy_selected_info(2, "Password")) + copy_password_button = ttk.Button( + button_frame, + text="Copy Password", + style="success.TButton", + command=lambda: copy_selected_info(2, "Password"), + ) copy_password_button.pack(side=tk.LEFT, padx=5) - all_passwords_window.grab_set() # makes window modal + all_passwords_window.grab_set() # makes window modal + # ---------------------------- UI SETUP ------------------------------- # window = ttk.Window(themename="superhero") @@ -192,16 +287,21 @@ def copy_selected_info(column_index, info_type): password_entry.grid(row=3, column=1, pady=5, sticky="EW") # buttons -search_button = ttk.Button(text="Search", width=14, command=find_password, style="info.TButton") -search_button.grid(row=1, column=2, sticky="EW", padx=(5,0)) -generate_password_button = ttk.Button(text="Generate Password", command=generate_password, style="success.TButton") -generate_password_button.grid(row=3, column=2, sticky="EW", padx=(5,0)) +search_button = ttk.Button( + text="Search", width=14, command=find_password, style="info.TButton" +) +search_button.grid(row=1, column=2, sticky="EW", padx=(5, 0)) +generate_password_button = ttk.Button( + text="Generate Password", command=generate_password, style="success.TButton" +) +generate_password_button.grid(row=3, column=2, sticky="EW", padx=(5, 0)) add_button = ttk.Button(text="Add", width=43, command=save, style="primary.TButton") -add_button.grid(row=4, column=1, columnspan=2, pady=(10,0), sticky="EW") +add_button.grid(row=4, column=1, columnspan=2, pady=(10, 0), sticky="EW") -view_all_button = ttk.Button(text="View All Passwords", command=view_all_passwords, style="secondary.TButton") -view_all_button.grid(row=5, column=1, columnspan=2, pady=(10,0), sticky="EW") +view_all_button = ttk.Button( + text="View All Passwords", command=view_all_passwords, style="secondary.TButton" +) +view_all_button.grid(row=5, column=1, columnspan=2, pady=(10, 0), sticky="EW") window.mainloop() - diff --git a/Password Manager Using Tkinter/requirements.txt b/Password Manager Using Tkinter/requirements.txt index 60ffacab8a4..b49506e51c07 100644 --- a/Password Manager Using Tkinter/requirements.txt +++ b/Password Manager Using Tkinter/requirements.txt @@ -1 +1 @@ -ttkbootstrap \ No newline at end of file +ttkbootstrap diff --git a/Python Programs/Python Program to Reverse a linked list.py b/Python Programs/Python Program to Reverse a linked list.py index e636a0df632..53ae08df10e 100644 --- a/Python Programs/Python Program to Reverse a linked list.py +++ b/Python Programs/Python Program to Reverse a linked list.py @@ -2,6 +2,7 @@ # Time Complexity : O(n) # Space Complexity : O(1) + # Node class class Node: # Constructor to initialize the node object diff --git a/Python_chatting_application/client.py b/Python_chatting_application/client.py index 447e7b6c448..1bddaa54ceb 100644 --- a/Python_chatting_application/client.py +++ b/Python_chatting_application/client.py @@ -20,7 +20,6 @@ def recieve(): except Exception as error: print(f"An Erro occured {error}") s.close() - flag = 1 break @@ -32,7 +31,6 @@ def Write(): except Exception as error: print(f"An Error Occured while sending message !!!\n error : {error}") s.close() - flag = 1 break diff --git a/Python_swapping.py b/Python_swapping.py index 1822f2f1bc3..a740662acf0 100644 --- a/Python_swapping.py +++ b/Python_swapping.py @@ -1,6 +1,7 @@ # Python3 program to swap first # and last element of a list + # Swap function def swapList(newList): size = len(newList) diff --git a/QR_code_generator/qrcode.py b/QR_code_generator/qrcode.py index 51a48b692b9..4965d331cdb 100755 --- a/QR_code_generator/qrcode.py +++ b/QR_code_generator/qrcode.py @@ -1,4 +1,5 @@ import pyqrcode + # from pyqrcode import QRCode # no need to import same library again and again diff --git a/QuestionAnswerVirtualAssistant/backend.py b/QuestionAnswerVirtualAssistant/backend.py index 3746a93cb69..7a7c5f2a257 100644 --- a/QuestionAnswerVirtualAssistant/backend.py +++ b/QuestionAnswerVirtualAssistant/backend.py @@ -74,7 +74,7 @@ def index_question_answer(self, question, answer): reverse_idx[word].append(row_id) reverse_idx = json.dumps(reverse_idx) cur = self.conn.cursor() - result = cur.execute( + cur.execute( "UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,) ) return "index successful" diff --git a/QuestionAnswerVirtualAssistant/requirements.txt b/QuestionAnswerVirtualAssistant/requirements.txt index fb4d28890ad..ff3211e9a15 100644 --- a/QuestionAnswerVirtualAssistant/requirements.txt +++ b/QuestionAnswerVirtualAssistant/requirements.txt @@ -1,2 +1,2 @@ pandas -scikit-learn \ No newline at end of file +scikit - learn diff --git a/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py b/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py index df3e705cbc0..b34c85937b1 100644 --- a/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py +++ b/Quizzler Using Tkinter and Trivia DB API/data_dynamic.py @@ -1,20 +1,17 @@ - -''' +""" This file is responsible for fetching quiz questions from the Open Trivia Database API. -''' +""" import requests -parameters = { - "amount": 10, - "type": "multiple", - "category": 18 -} +parameters = {"amount": 10, "type": "multiple", "category": 18} error_message = "" try: - response = requests.get(url="https://opentdb.com/api.php", params=parameters, timeout=10) + response = requests.get( + url="https://opentdb.com/api.php", params=parameters, timeout=10 + ) response.raise_for_status() # Raise an exception for HTTP errors question_data = response.json()["results"] print("Questions loaded successfully from the API.") diff --git a/Quizzler Using Tkinter and Trivia DB API/data_static.py b/Quizzler Using Tkinter and Trivia DB API/data_static.py index 081bc3982a2..5ea00107aca 100644 --- a/Quizzler Using Tkinter and Trivia DB API/data_static.py +++ b/Quizzler Using Tkinter and Trivia DB API/data_static.py @@ -5,8 +5,8 @@ "incorrect_answers": [ "Increase in hardware prices", "Decrease in computational power", - "Less complex problems for software engineers" - ] + "Less complex problems for software engineers", + ], }, { "question": "How have software engineers coped with the challenges of increasing computational capabilities?", @@ -14,8 +14,8 @@ "incorrect_answers": [ "By reducing programming efforts", "By simplifying programming languages", - "By avoiding large and complex problems" - ] + "By avoiding large and complex problems", + ], }, { "question": "Which of the following is a definition of software engineering according to IEEE?", @@ -23,8 +23,8 @@ "incorrect_answers": [ "The art of writing computer programs", "An engineering approach to developing software", - "A collection of unorganized programming techniques" - ] + "A collection of unorganized programming techniques", + ], }, { "question": "Why is software engineering similar to other engineering disciplines?", @@ -32,8 +32,8 @@ "incorrect_answers": [ "It makes use of subjective judgement and ill understood principles", "It often avoids conflicting goals", - "It relies solely on qualitative attributes" - ] + "It relies solely on qualitative attributes", + ], }, { "question": "Which statement supports the idea that software engineering is not just an art?", @@ -41,8 +41,8 @@ "incorrect_answers": [ "It makes subjective judgement based on qualitative attributes", "It avoids systematic and disciplined approaches", - "It does not require tradeoffs in problem solving" - ] + "It does not require tradeoffs in problem solving", + ], }, { "question": "How have software engineering principles evolved over the last sixty years?", @@ -50,17 +50,13 @@ "incorrect_answers": [ "From a science to an art form", "From a craft to an art form", - "From an engineering discipline to a craft" - ] + "From an engineering discipline to a craft", + ], }, { "question": "Which programming style is characterized by quickly developing a program without any specification, plan, or design?", "correct_answer": "Build and fix", - "incorrect_answers": [ - "Exploratory", - "Code and fix", - "Ad hoc" - ] + "incorrect_answers": ["Exploratory", "Code and fix", "Ad hoc"], }, { "question": "According to the text, what has been a symptom of the present software crisis?", @@ -68,8 +64,8 @@ "incorrect_answers": [ "Decrease in software development costs", "Software products becoming easier to alter and debug", - "Software products being delivered on time" - ] + "Software products being delivered on time", + ], }, { "question": "What is one of the main benefits of adopting software engineering techniques according to the text?", @@ -77,8 +73,8 @@ "incorrect_answers": [ "Increasing hardware costs", "Avoiding the use of scientific principles", - "Making software development more subjective" - ] + "Making software development more subjective", + ], }, { "question": "What is a key characteristic of toy software?", @@ -86,9 +82,9 @@ "incorrect_answers": [ "Developed by a team of professionals", "Large in size and highly complex", - "Thoroughly tested and maintained" - ] - } + "Thoroughly tested and maintained", + ], + }, # { # "question": "What differentiates professional software from toy software?", # "correct_answer": "Professional software is systematically designed, carefully implemented, and thoroughly tested", @@ -188,4 +184,4 @@ # "Data flow-oriented design" # ] # } -] \ No newline at end of file +] diff --git a/Quizzler Using Tkinter and Trivia DB API/main.py b/Quizzler Using Tkinter and Trivia DB API/main.py index 37a038c5d60..c6823ac1964 100644 --- a/Quizzler Using Tkinter and Trivia DB API/main.py +++ b/Quizzler Using Tkinter and Trivia DB API/main.py @@ -1,4 +1,3 @@ - """This file processes the fetched questions and prepares them for use in the quiz.""" from question_model import Question @@ -18,7 +17,7 @@ Question( question["question"], question["correct_answer"], - question["incorrect_answers"] + [question["correct_answer"]] + question["incorrect_answers"] + [question["correct_answer"]], ) for question in question_data ] diff --git a/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py b/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py index 53bcf178931..95212861a79 100644 --- a/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py +++ b/Quizzler Using Tkinter and Trivia DB API/quiz_brain.py @@ -1,8 +1,8 @@ - """This file contains the logic that drives the quiz game, including managing the current question, checking answers, and tracking the score.""" import html + class QuizBrain: def __init__(self, q_list): self.question_number = 0 diff --git a/Quizzler Using Tkinter and Trivia DB API/ui.py b/Quizzler Using Tkinter and Trivia DB API/ui.py index 42102c20fac..28cd558ff55 100644 --- a/Quizzler Using Tkinter and Trivia DB API/ui.py +++ b/Quizzler Using Tkinter and Trivia DB API/ui.py @@ -1,4 +1,3 @@ - """This file manages the graphical user interface of the quiz, using Tkinter to display questions, answer options, and the score to the user.""" from tkinter import * @@ -22,20 +21,29 @@ FONT = ("Lucida sans", 20) -class QuizInterface: +class QuizInterface: def __init__(self, quiz_brain: QuizBrain): self.quiz = quiz_brain self.window = Tk() self.window.title("Quizzler") self.window.config(padx=20, pady=20, bg=BACKGROUND) - self.score_label = Label(text="Score: 0", fg="white", bg=BACKGROUND, font=("Lucida sans", 15, "bold")) + self.score_label = Label( + text="Score: 0", fg="white", bg=BACKGROUND, font=("Lucida sans", 15, "bold") + ) self.score_label.grid(row=0, column=1) self.canvas = Canvas(width=1000, height=550, bg=CANVAS) self.question_text = self.canvas.create_text( - 500, 100, width=800, text="Some question text", fill=TEXT, font=FONT, anchor="center", justify="center" + 500, + 100, + width=800, + text="Some question text", + fill=TEXT, + font=FONT, + anchor="center", + justify="center", ) self.canvas.grid(row=1, column=0, columnspan=2, pady=50) @@ -59,8 +67,16 @@ def create_radio_buttons(self): y_position = 230 for i in range(4): radio_button = Radiobutton( - self.canvas, text="", variable=self.opt_selected, value=i + 1, font=FONT, bg=CANVAS, anchor="w", - justify="left", fg=TEXT, wraplength=900 + self.canvas, + text="", + variable=self.opt_selected, + value=i + 1, + font=FONT, + bg=CANVAS, + anchor="w", + justify="left", + fg=TEXT, + wraplength=900, ) radio_buttons.append(radio_button) self.canvas.create_window(50, y_position, window=radio_button, anchor="w") diff --git a/Search_Engine/backend.py b/Search_Engine/backend.py index 2c4f730b914..35332a49f58 100644 --- a/Search_Engine/backend.py +++ b/Search_Engine/backend.py @@ -69,7 +69,7 @@ def index_document(self, document): reverse_idx[word].append(row_id) reverse_idx = json.dumps(reverse_idx) cur = self.conn.cursor() - result = cur.execute( + cur.execute( "UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,) ) return "index successful" diff --git a/Snake Game Using Turtle/colors.py b/Snake Game Using Turtle/colors.py index 05fac02e5a2..9b4d6ab1db2 100644 --- a/Snake Game Using Turtle/colors.py +++ b/Snake Game Using Turtle/colors.py @@ -2,27 +2,27 @@ This file contains the color palette for the game, now including colors for the new interactive buttons. """ + # A fresh and vibrant color theme # --> food.py FOOD_COLOR = "#C70039" # A bright, contrasting red # --> main.py -BG_COLOR = '#F0F8FF' # AliceBlue, a very light and clean background +BG_COLOR = "#F0F8FF" # AliceBlue, a very light and clean background # --> scoreboard.py -GAME_OVER_COLOR = '#D21312' # Strong red for game over message -SCORE_COLOR = '#27374D' # Dark blue for high-contrast text -MESSAGE_COLOR = '#27374D' # Consistent dark blue for other messages +GAME_OVER_COLOR = "#D21312" # Strong red for game over message +SCORE_COLOR = "#27374D" # Dark blue for high-contrast text +MESSAGE_COLOR = "#27374D" # Consistent dark blue for other messages # --> snake.py -FIRST_SEGMENT_COLOR = '#006400' # DarkGreen for the snake's head -BODY_COLOR = '#2E8B57' # SeaGreen for the snake's body +FIRST_SEGMENT_COLOR = "#006400" # DarkGreen for the snake's head +BODY_COLOR = "#2E8B57" # SeaGreen for the snake's body # --> wall.py -WALL_COLOR = '#27374D' # Dark blue for a solid, visible border +WALL_COLOR = "#27374D" # Dark blue for a solid, visible border # --> UI Controls (Buttons) BUTTON_BG_COLOR = "#526D82" BUTTON_TEXT_COLOR = "#F0F8FF" BUTTON_BORDER_COLOR = "#27374D" - diff --git a/Snake Game Using Turtle/food.py b/Snake Game Using Turtle/food.py index 59dcd5eb740..72a141aea94 100644 --- a/Snake Game Using Turtle/food.py +++ b/Snake Game Using Turtle/food.py @@ -7,8 +7,10 @@ import random import colors + class Food(Turtle): - """ This class generates food for the snake to eat. """ + """This class generates food for the snake to eat.""" + def __init__(self): super().__init__() self.shape("circle") @@ -24,4 +26,3 @@ def refresh(self, left_wall, right_wall, bottom_wall, top_wall): random_x = random.randint(int(left_wall) + margin, int(right_wall) - margin) random_y = random.randint(int(bottom_wall) + margin, int(top_wall) - margin) self.goto(random_x, random_y) - diff --git a/Snake Game Using Turtle/highscore.txt b/Snake Game Using Turtle/highscore.txt index 62f9457511f..1e8b3149621 100644 --- a/Snake Game Using Turtle/highscore.txt +++ b/Snake Game Using Turtle/highscore.txt @@ -1 +1 @@ -6 \ No newline at end of file +6 diff --git a/Snake Game Using Turtle/main.py b/Snake Game Using Turtle/main.py index 9b874f1a3df..7656b574656 100644 --- a/Snake Game Using Turtle/main.py +++ b/Snake Game Using Turtle/main.py @@ -3,6 +3,7 @@ It handles screen setup, dynamic boundaries, UI controls (buttons), game state management, and the main game loop. """ + from turtle import Screen, Turtle from snake import Snake from food import Food @@ -43,17 +44,18 @@ # --- UI CONTROLS (BUTTONS) --- buttons = {} # Dictionary to hold button turtles and their properties + def create_button(name, x, y, width=120, height=40): """Creates a turtle-based button with a label.""" - if name in buttons and buttons[name]['turtle'] is not None: - buttons[name]['turtle'].clear() + if name in buttons and buttons[name]["turtle"] is not None: + buttons[name]["turtle"].clear() button_turtle = Turtle() button_turtle.hideturtle() button_turtle.penup() button_turtle.speed("fastest") - button_turtle.goto(x - width/2, y - height/2) + button_turtle.goto(x - width / 2, y - height / 2) button_turtle.color(colors.BUTTON_BORDER_COLOR, colors.BUTTON_BG_COLOR) button_turtle.begin_fill() for _ in range(2): @@ -67,13 +69,22 @@ def create_button(name, x, y, width=120, height=40): button_turtle.color(colors.BUTTON_TEXT_COLOR) button_turtle.write(name, align="center", font=("Lucida Sans", 14, "bold")) - buttons[name] = {'turtle': button_turtle, 'x': x, 'y': y, 'w': width, 'h': height, 'visible': True} + buttons[name] = { + "turtle": button_turtle, + "x": x, + "y": y, + "w": width, + "h": height, + "visible": True, + } + def hide_button(name): """Hides a button by clearing its turtle.""" - if name in buttons and buttons[name]['visible']: - buttons[name]['turtle'].clear() - buttons[name]['visible'] = False + if name in buttons and buttons[name]["visible"]: + buttons[name]["turtle"].clear() + buttons[name]["visible"] = False + def manage_buttons(): """Shows or hides buttons based on the current game state.""" @@ -93,6 +104,7 @@ def manage_buttons(): elif game_state == "game_over": create_button("Restart", btn_x, btn_y) + # --- GAME LOGIC & STATE TRANSITIONS --- def start_game(): global game_state @@ -100,6 +112,7 @@ def start_game(): game_state = "playing" scoreboard.update_scoreboard() + def toggle_pause_resume(): global game_state if game_state == "playing": @@ -109,6 +122,7 @@ def toggle_pause_resume(): game_state = "playing" scoreboard.update_scoreboard() + def restart_game(): global game_state if game_state == "game_over": @@ -117,14 +131,18 @@ def restart_game(): food.refresh(LEFT_WALL, RIGHT_WALL, BOTTOM_WALL, TOP_WALL) scoreboard.reset() + def is_click_on_button(name, x, y): """Checks if a click (x, y) is within the bounds of a visible button.""" - if name in buttons and buttons[name]['visible']: + if name in buttons and buttons[name]["visible"]: btn = buttons[name] - return (btn['x'] - btn['w']/2 < x < btn['x'] + btn['w']/2 and - btn['y'] - btn['h']/2 < y < btn['y'] + btn['h']/2) + return ( + btn["x"] - btn["w"] / 2 < x < btn["x"] + btn["w"] / 2 + and btn["y"] - btn["h"] / 2 < y < btn["y"] + btn["h"] / 2 + ) return False + def handle_click(x, y): """Main click handler to delegate actions based on button clicks.""" if game_state == "start" and is_click_on_button("Play", x, y): @@ -136,24 +154,32 @@ def handle_click(x, y): elif game_state == "game_over" and is_click_on_button("Restart", x, y): restart_game() + # --- KEYBOARD HANDLERS --- def handle_snake_up(): if game_state in ["start", "playing"]: start_game() snake.up() + + def handle_snake_down(): if game_state in ["start", "playing"]: start_game() snake.down() + + def handle_snake_left(): if game_state in ["start", "playing"]: start_game() snake.left() + + def handle_snake_right(): if game_state in ["start", "playing"]: start_game() snake.right() + # --- KEY & MOUSE BINDINGS --- screen.listen() screen.onkey(handle_snake_up, "Up") @@ -165,6 +191,7 @@ def handle_snake_right(): screen.onkey(restart_game, "R") screen.onclick(handle_click) + # --- MAIN GAME LOOP --- def game_loop(): global game_state @@ -176,7 +203,10 @@ def game_loop(): snake.extend() scoreboard.increase_score() # Collision with wall - if not (LEFT_WALL < snake.head.xcor() < RIGHT_WALL and BOTTOM_WALL < snake.head.ycor() < TOP_WALL): + if not ( + LEFT_WALL < snake.head.xcor() < RIGHT_WALL + and BOTTOM_WALL < snake.head.ycor() < TOP_WALL + ): game_state = "game_over" scoreboard.game_over() # Collision with tail @@ -188,8 +218,8 @@ def game_loop(): screen.update() screen.ontimer(game_loop, MOVE_DELAY_MS) + # --- INITIALIZE GAME --- scoreboard.display_start_message() game_loop() screen.exitonclick() - diff --git a/Snake Game Using Turtle/scoreboard.py b/Snake Game Using Turtle/scoreboard.py index 4ca9265071c..840b2e7038e 100644 --- a/Snake Game Using Turtle/scoreboard.py +++ b/Snake Game Using Turtle/scoreboard.py @@ -2,6 +2,7 @@ This file manages the display of the score, high score, and game messages. It now positions the score dynamically in the top-left corner. """ + from turtle import Turtle, Screen import colors @@ -11,8 +12,10 @@ MESSAGE_FONT = ("Courier", 40, "bold") INSTRUCTION_FONT = ("Lucida Sans", 16, "normal") + class Scoreboard(Turtle): - """ This class maintains the scoreboard, high score, and game messages. """ + """This class maintains the scoreboard, high score, and game messages.""" + def __init__(self): super().__init__() self.screen = Screen() # Get access to the screen object @@ -38,7 +41,11 @@ def update_scoreboard(self): x_pos = -self.screen.window_width() / 2 + 30 y_pos = self.screen.window_height() / 2 - 60 self.goto(x_pos, y_pos) - self.write(f"Score: {self.score} | High Score: {self.high_score}", align=ALIGNMENT, font=SCORE_FONT) + self.write( + f"Score: {self.score} | High Score: {self.high_score}", + align=ALIGNMENT, + font=SCORE_FONT, + ) def increase_score(self): """Increases score and updates the display.""" @@ -60,7 +67,9 @@ def game_over(self): self.color(colors.GAME_OVER_COLOR) self.write("GAME OVER", align="center", font=MESSAGE_FONT) self.goto(0, -40) - self.write("Click 'Restart' or Press 'R'", align="center", font=INSTRUCTION_FONT) + self.write( + "Click 'Restart' or Press 'R'", align="center", font=INSTRUCTION_FONT + ) def display_pause(self): """Displays the PAUSED message.""" @@ -68,13 +77,18 @@ def display_pause(self): self.color(colors.MESSAGE_COLOR) self.write("PAUSED", align="center", font=MESSAGE_FONT) self.goto(0, -40) - self.write("Click 'Resume' or Press 'Space'", align="center", font=INSTRUCTION_FONT) - + self.write( + "Click 'Resume' or Press 'Space'", align="center", font=INSTRUCTION_FONT + ) + def display_start_message(self): """Displays the welcome message and starting instructions.""" self.goto(0, 40) self.color(colors.MESSAGE_COLOR) self.write("SNAKE GAME", align="center", font=MESSAGE_FONT) self.goto(0, -40) - self.write("Click 'Play' or an Arrow Key to Start", align="center", font=INSTRUCTION_FONT) - + self.write( + "Click 'Play' or an Arrow Key to Start", + align="center", + font=INSTRUCTION_FONT, + ) diff --git a/Snake Game Using Turtle/snake.py b/Snake Game Using Turtle/snake.py index e9fb153c317..70e7b02200d 100644 --- a/Snake Game Using Turtle/snake.py +++ b/Snake Game Using Turtle/snake.py @@ -2,6 +2,7 @@ This file is responsible for creating the snake and managing its movement, extension, and reset functionality. """ + from turtle import Turtle import colors @@ -9,21 +10,23 @@ MOVE_DISTANCE = 20 UP, DOWN, LEFT, RIGHT = 90, 270, 180, 0 + class Snake: - """ This class creates a snake body and contains methods for movement and extension. """ + """This class creates a snake body and contains methods for movement and extension.""" + def __init__(self): self.segments = [] self.create_snake() self.head = self.segments[0] def create_snake(self): - """ Creates the initial snake body. """ + """Creates the initial snake body.""" for position in STARTING_POSITIONS: self.add_segment(position) self.segments[0].color(colors.FIRST_SEGMENT_COLOR) def add_segment(self, position): - """ Adds a new segment to the snake. """ + """Adds a new segment to the snake.""" new_segment = Turtle(shape="square") new_segment.penup() new_segment.goto(position) @@ -31,12 +34,12 @@ def add_segment(self, position): self.segments.append(new_segment) def extend(self): - """ Adds a new segment to the snake's tail. """ + """Adds a new segment to the snake's tail.""" self.add_segment(self.segments[-1].position()) self.segments[0].color(colors.FIRST_SEGMENT_COLOR) def move(self): - """ Moves the snake forward by moving each segment to the position of the one in front.""" + """Moves the snake forward by moving each segment to the position of the one in front.""" for i in range(len(self.segments) - 1, 0, -1): x = self.segments[i - 1].xcor() y = self.segments[i - 1].ycor() @@ -70,4 +73,3 @@ def right(self): """Turns the snake's head to the right, preventing it from reversing.""" if self.head.heading() != LEFT: self.head.setheading(RIGHT) - diff --git a/Snake Game Using Turtle/wall.py b/Snake Game Using Turtle/wall.py index dc47848961b..b99d9704782 100644 --- a/Snake Game Using Turtle/wall.py +++ b/Snake Game Using Turtle/wall.py @@ -3,8 +3,10 @@ from turtle import Turtle, Screen import colors + class Wall: - """ This class creates a wall around the game screen that adjusts to its dimensions. """ + """This class creates a wall around the game screen that adjusts to its dimensions.""" + def __init__(self): self.screen = Screen() self.create_wall() @@ -43,4 +45,3 @@ def create_wall(self): wall.goto(right - 10, top - 70) self.screen.update() - diff --git a/Snake_water_gun/main.py b/Snake_water_gun/main.py index 3928079b997..94c927feb0b 100644 --- a/Snake_water_gun/main.py +++ b/Snake_water_gun/main.py @@ -81,7 +81,7 @@ class bcolors: i += 1 print(f"{10 - i} matches left") -if run == True: +if run: print(f"Your score is {score} and the final result is...") time.sleep(3) if score > 5: diff --git a/Sorting Algorithims/mergesort_linkedlist.py b/Sorting Algorithims/mergesort_linkedlist.py index 4e833dc2e29..8e2a4831509 100644 --- a/Sorting Algorithims/mergesort_linkedlist.py +++ b/Sorting Algorithims/mergesort_linkedlist.py @@ -18,7 +18,7 @@ def insert(self, new_data: int) -> None: def printLL(self) -> None: temp = self.head - if temp == None: + if temp is None: return "Linked List is empty" while temp.next: print(temp.data, "->", end="") diff --git a/Sorting Algorithims/quicksort_linkedlist.py b/Sorting Algorithims/quicksort_linkedlist.py index 70804343a98..0e82636b651 100644 --- a/Sorting Algorithims/quicksort_linkedlist.py +++ b/Sorting Algorithims/quicksort_linkedlist.py @@ -26,7 +26,7 @@ def insert(self, new_data: int) -> None: # method to print the linkedlist def printLL(self) -> None: temp = self.head - if temp == None: + if temp is None: return "Linked List is empty" while temp.next: print(temp.data, "->", end="") @@ -39,7 +39,7 @@ def printLL(self) -> None: def partition(start, end): - if start == None or start.next == None: + if start is None or start.next is None: return start prev, curr = start, start.next pivot = prev.data diff --git a/Sorting Algorithms/Heap sort.py b/Sorting Algorithms/Heap sort.py index 6e5a80c3aff..2719cfa8875 100644 --- a/Sorting Algorithms/Heap sort.py +++ b/Sorting Algorithms/Heap sort.py @@ -1,5 +1,6 @@ # Python program for implementation of heap Sort + # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): diff --git a/Sorting Algorithms/Iterative Merge Sort.py b/Sorting Algorithms/Iterative Merge Sort.py index 734cf1954c0..4ec479dc7d1 100644 --- a/Sorting Algorithms/Iterative Merge Sort.py +++ b/Sorting Algorithms/Iterative Merge Sort.py @@ -1,5 +1,6 @@ # Iterative Merge sort (Bottom Up) + # Iterative mergesort function to # sort arr[0...n-1] def mergeSort(a): diff --git a/Sorting Algorithms/brickSort.py b/Sorting Algorithms/brickSort.py index 08308d05a5a..a81f690288b 100644 --- a/Sorting Algorithms/brickSort.py +++ b/Sorting Algorithms/brickSort.py @@ -7,7 +7,6 @@ def oddEvenSort(arr, n): 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] diff --git a/Street_Fighter/src/fighter.py b/Street_Fighter/src/fighter.py index 94fc68abd16..b41c828b80a 100644 --- a/Street_Fighter/src/fighter.py +++ b/Street_Fighter/src/fighter.py @@ -55,7 +55,7 @@ def move(self, screen_width, screen_height, target, round_over): key = pygame.key.get_pressed() # can only perform other actions if not currently attacking - if self.attacking == False and self.alive == True and round_over == False: + if not self.attacking and self.alive and not round_over: # check player 1 controls if self.player == 1: # movement @@ -66,7 +66,7 @@ def move(self, screen_width, screen_height, target, round_over): dx = SPEED self.running = True # jump - if key[pygame.K_w] and self.jump == False: + if key[pygame.K_w] and not self.jump: self.vel_y = -30 self.jump = True # attack @@ -88,7 +88,7 @@ def move(self, screen_width, screen_height, target, round_over): dx = SPEED self.running = True # jump - if key[pygame.K_UP] and self.jump == False: + if key[pygame.K_UP] and not self.jump: self.vel_y = -30 self.jump = True # attack diff --git a/Trending youtube videos b/Trending youtube videos index a14535e4ddc..e74f15e75f3 100644 --- a/Trending youtube videos +++ b/Trending youtube videos @@ -1,43 +1,45 @@ -''' - Python program that uses the YouTube Data API to fetch the top 10 trending YouTube videos. +""" + Python program that uses the YouTube Data API to fetch the top 10 trending YouTube videos. You’ll need to have an API key from Google Cloud Platform to use the YouTube Data API. -First, install the google-api-python-client library if you haven’t already: +First, install the google-api-python-client library if you haven’t already: pip install google-api-python-client -Replace 'YOUR_API_KEY' with your actual API key. This script will fetch and print the titles, -channels, and view counts of the top 10 trending YouTube videos in India. +Replace 'YOUR_API_KEY' with your actual API key. This script will fetch and print the titles, +channels, and view counts of the top 10 trending YouTube videos in India. You can change the regionCode to any other country code if needed. Then, you can use the following code: -''' +""" from googleapiclient.discovery import build # Replace with your own API key -API_KEY = 'YOUR_API_KEY' -YOUTUBE_API_SERVICE_NAME = 'youtube' -YOUTUBE_API_VERSION = 'v3' +API_KEY = "YOUR_API_KEY" +YOUTUBE_API_SERVICE_NAME = "youtube" +YOUTUBE_API_VERSION = "v3" + def get_trending_videos(): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY) - + # Call the API to get the top 10 trending videos request = youtube.videos().list( - part='snippet,statistics', - chart='mostPopular', - regionCode='IN', # Change this to your region code - maxResults=10 + part="snippet,statistics", + chart="mostPopular", + regionCode="IN", # Change this to your region code + maxResults=10, ) response = request.execute() - + # Print the video details - for item in response['items']: - title = item['snippet']['title'] - channel = item['snippet']['channelTitle'] - views = item['statistics']['viewCount'] - print(f'Title: {title}\nChannel: {channel}\nViews: {views}\n') + for item in response["items"]: + title = item["snippet"]["title"] + channel = item["snippet"]["channelTitle"] + views = item["statistics"]["viewCount"] + print(f"Title: {title}\nChannel: {channel}\nViews: {views}\n") + -if __name__ == '__main__': +if __name__ == "__main__": get_trending_videos() 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 f88c6538a15..69699577df5 100644 --- a/Triplets with zero sum/find_Triplets_with_zero_sum.py +++ b/Triplets with zero sum/find_Triplets_with_zero_sum.py @@ -50,7 +50,7 @@ def find_Triplets_with_zero_sum(arr, num): else: right -= 1 - if found == False: + if not found: print(" No Triplet Found") diff --git a/VoiceAssistant/Project_Basic_struct/TextTospeech.py b/VoiceAssistant/Project_Basic_struct/TextTospeech.py index 2bcc7f29b39..4755c96bec2 100644 --- a/VoiceAssistant/Project_Basic_struct/TextTospeech.py +++ b/VoiceAssistant/Project_Basic_struct/TextTospeech.py @@ -2,9 +2,7 @@ def tts(): - audio = "speech.mp3" - language = "en" sentence = input("Enter the text to be spoken :- ") speaker = win32com.client.Dispatch("SAPI.SpVoice") - sp = speaker.Speak(sentence) + speaker.Speak(sentence) diff --git a/VoiceAssistant/Project_Basic_struct/textRead.py b/VoiceAssistant/Project_Basic_struct/textRead.py index bd0d147121b..0a9fc41069f 100644 --- a/VoiceAssistant/Project_Basic_struct/textRead.py +++ b/VoiceAssistant/Project_Basic_struct/textRead.py @@ -43,7 +43,9 @@ def pdf_read(): path = doubleslash(location) pdf = fitz.open(path) - details = pdf.metadata # Stores the meta-data which generally includes Author name and Title of book/document. + details = ( + pdf.metadata + ) # Stores the meta-data which generally includes Author name and Title of book/document. total_pages = pdf.pageCount # Stores the total number of pages except Exception as exp: @@ -54,10 +56,10 @@ def pdf_read(): ) return "None" try: - """ 1. Author - 2. Creator - 3. Producer - 4. Title """ + """1. Author + 2. Creator + 3. Producer + 4. Title""" author = details["author"] # print("Author : ",author) @@ -181,7 +183,7 @@ def pdf_read(): try: key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) - if start_pg_no != None and end_pg_no != None: + if start_pg_no is not None and end_pg_no is not None: start_pg_no, end_pg_no = map( int, search_in_toc(toc, key, total_pages) ) @@ -199,7 +201,7 @@ def pdf_read(): start_pg_no, end_pg_no = map( int, search_in_toc(toc, key, total_pages) ) - if start_pg_no != None and end_pg_no != None: + if start_pg_no is not None and end_pg_no is not None: for i in range(start_pg_no - 1, end_pg_no): page = pdf.load_page(i) text = page.get_text("text") @@ -212,7 +214,7 @@ def pdf_read(): speak("Lesson name") key = input("Lesson name - ") start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages) - if start_pg_no != None and end_pg_no != None: + if start_pg_no is not None and end_pg_no is not None: start_pg_no, end_pg_no = map( int, search_in_toc(toc, key, total_pages) ) diff --git a/WeatherGUI.py b/WeatherGUI.py index 62a2fef6bf8..799f714f79a 100644 --- a/WeatherGUI.py +++ b/WeatherGUI.py @@ -1,10 +1,13 @@ import tkinter as tk import requests from bs4 import BeautifulSoup + url = "https://weather.com/en-IN/weather/today/l/32355ced66b7ce3ab7ccafb0a4f45f12e7c915bcf8454f712efa57474ba8d6c8" root = tk.Tk() root.title("Weather") root.config(bg="white") + + def getWeather(): page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") diff --git a/Web Socket.py b/Web Socket.py index 9c3c91beafa..8da7e224c00 100644 --- a/Web Socket.py +++ b/Web Socket.py @@ -1,5 +1,6 @@ # Program to print a data & it's Metadata of online uploaded file using "socket". import socket + skt_c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) skt_c.connect(("data.pr4e.org", 80)) link = "GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n".encode() diff --git a/XML/HTML parsing b/XML/HTML parsing index 8d8c2825e02..82876490f78 100644 --- a/XML/HTML parsing +++ b/XML/HTML parsing @@ -1,21 +1,22 @@ -dinner_recipe = ''' +dinner_recipe = """
-
amtunititem
24slicesbaguette
2+tbspolive oil
1cuptomatoes
1jarpesto
''' +""" # From http://effbot.org/zone/element-index.htm import xml.etree.ElementTree as etree + tree = etree.fromstring(dinner_recipe) # For invalid HTML use http://effbot.org/zone/element-soup.htm # import ElementSoup, StringIO # tree = ElementSoup.parse(StringIO.StringIO(dinner_recipe)) -pantry = set(['olive oil', 'pesto']) -for ingredient in tree.getiterator('tr'): +pantry = set(["olive oil", "pesto"]) +for ingredient in tree.getiterator("tr"): amt, unit, item = ingredient if item.tag == "td" and item.text not in pantry: - print ("%s: %s %s" % (item.text, amt.text, unit.text)) + print("%s: %s %s" % (item.text, amt.text, unit.text)) diff --git a/Youtube Downloader With GUI/main.py b/Youtube Downloader With GUI/main.py index b21e4495a99..d8efdb685f3 100644 --- a/Youtube Downloader With GUI/main.py +++ b/Youtube Downloader With GUI/main.py @@ -33,7 +33,7 @@ def startDownload(): return ob = YouTube(URL, on_progress_callback=progress) strm = ob.streams[0] - x = ob.description.split("|") + ob.description.split("|") file_size = strm.filesize dfile_size = file_size dfile_size /= 1000000 diff --git a/area_of_square_app.py b/area_of_square_app.py index d9e4a303005..5795c07f457 100644 --- a/area_of_square_app.py +++ b/area_of_square_app.py @@ -60,7 +60,7 @@ def ask_side(self): # I will have to learn inheritance and polymorphism. condition = 3 # condition = True - if condition == True and isinstance(condition, bool): + if condition and isinstance(condition, bool): while condition: n = input("Enter the side of the square: ") self.side = float(n) diff --git a/bank_managment_system/QTFrontend.py b/bank_managment_system/QTFrontend.py index 2f67009e322..ed442a43ab0 100644 --- a/bank_managment_system/QTFrontend.py +++ b/bank_managment_system/QTFrontend.py @@ -65,7 +65,8 @@ def create_styled_button(parent, text, min_size=None): button = QtWidgets.QPushButton(parent) if min_size: button.setMinimumSize(QtCore.QSize(*min_size)) - button.setStyleSheet(""" + button.setStyleSheet( + """ QPushButton { background-color: #3498db; color: white; @@ -82,7 +83,8 @@ def create_styled_button(parent, text, min_size=None): QPushButton:pressed { background-color: #1c6ea4; } - """) + """ + ) button.setText(text) return button @@ -172,7 +174,8 @@ def show_popup_message( else: button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) - button_box.setStyleSheet(""" + button_box.setStyleSheet( + """ QPushButton { background-color: #3498db; color: white; @@ -186,7 +189,8 @@ def show_popup_message( QPushButton:pressed { background-color: #1c6ea4; } - """) + """ + ) layout.addWidget(button_box) # Connect buttons @@ -423,7 +427,8 @@ def create_home_page(parent, on_admin_clicked, on_employee_clicked, on_exit_clic admin_button = create_styled_button(button_container, "Admin") employee_button = create_styled_button(button_container, "Employee") exit_button = create_styled_button(button_container, "Exit") - exit_button.setStyleSheet(""" + exit_button.setStyleSheet( + """ QPushButton { background-color: #e74c3c; color: white; @@ -440,7 +445,8 @@ def create_home_page(parent, on_admin_clicked, on_employee_clicked, on_exit_clic QPushButton:pressed { background-color: #992d22; } - """) + """ + ) button_container_layout.addWidget(admin_button) button_container_layout.addWidget(employee_button) @@ -556,7 +562,8 @@ def create_add_employee_page( ) main_layout.addWidget(content_frame) back_btn = QtWidgets.QPushButton("Back", content_frame) - back_btn.setStyleSheet(""" + back_btn.setStyleSheet( + """ QPushButton { background-color: #6c757d; color: white; @@ -568,7 +575,8 @@ def create_add_employee_page( QPushButton:hover { background-color: #5a6268; } - """) + """ + ) back_btn.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE)) main_layout.addWidget(back_btn, 0, alignment=QtCore.Qt.AlignLeft) if update_btn: @@ -666,7 +674,8 @@ def show_employee_list_page(parent, title): # Back button back_button = QtWidgets.QPushButton("Back", content_frame) - back_button.setStyleSheet(""" + back_button.setStyleSheet( + """ QPushButton { background-color: #6c757d; color: white; @@ -678,7 +687,8 @@ def show_employee_list_page(parent, title): QPushButton:hover { background-color: #5a6268; } - """) + """ + ) back_button.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE)) content_layout.addWidget(table_frame) @@ -706,7 +716,8 @@ def show_total_money(parent, title): content_layout.addWidget(total_money_label, alignment=QtCore.Qt.AlignCenter) # Back button back_button = QtWidgets.QPushButton("Back", content_frame) - back_button.setStyleSheet(""" + back_button.setStyleSheet( + """ QPushButton { background-color: #6c757d; color: white; @@ -718,7 +729,8 @@ def show_total_money(parent, title): QPushButton:hover { background-color: #5a6268; } - """) + """ + ) back_button.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE)) content_layout.addWidget(back_button, alignment=QtCore.Qt.AlignCenter) main_layout.addWidget(content_frame) @@ -816,7 +828,8 @@ def create_account_page(parent, title, update_btn=False): form_layout.addWidget(account_type_label) account_type_dropdown = QtWidgets.QComboBox(form_frame) account_type_dropdown.addItems(["Savings", "Current", "Fixed Deposit"]) - account_type_dropdown.setStyleSheet(""" + account_type_dropdown.setStyleSheet( + """ QComboBox { padding: 5px; border: 1px solid #ccc; @@ -842,7 +855,8 @@ def create_account_page(parent, title, update_btn=False): selection-background-color: #0078d4; selection-color: white; } - """) + """ + ) form_layout.addWidget(account_type_dropdown) # Submit button @@ -861,7 +875,8 @@ def create_account_page(parent, title, update_btn=False): ) main_layout.addWidget(content_frame) back_btn = QtWidgets.QPushButton("Back", content_frame) - back_btn.setStyleSheet(""" + back_btn.setStyleSheet( + """ QPushButton { background-color: #6c757d; color: white; @@ -873,7 +888,8 @@ def create_account_page(parent, title, update_btn=False): QPushButton:hover { background-color: #5a6268; } - """) + """ + ) back_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE)) main_layout.addWidget(back_btn, 0, alignment=QtCore.Qt.AlignLeft) @@ -972,7 +988,8 @@ def create_show_details_page2(parent, title): account_type_field = input_field exite_btn = create_styled_button(form_frame, "Exit", min_size=(100, 50)) - exite_btn.setStyleSheet(""" + exite_btn.setStyleSheet( + """ QPushButton { background-color: #6c757d; color: white; @@ -984,7 +1001,8 @@ def create_show_details_page2(parent, title): QPushButton:hover { background-color: #5a6268; } - """) + """ + ) exite_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE)) content_layout.addWidget( form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter @@ -1064,7 +1082,8 @@ def update_user(parent, title, input_fields_label, input_fielf: bool = True): ) main_layout.addWidget(content_frame) back_btn = create_styled_button(content_frame, "Back", min_size=(100, 50)) - back_btn.setStyleSheet(""" + back_btn.setStyleSheet( + """ QPushButton { background-color: #6c757d; color: white; @@ -1076,7 +1095,8 @@ def update_user(parent, title, input_fields_label, input_fielf: bool = True): QPushButton:hover { background-color: #5a6268; } - """) + """ + ) back_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE)) backend if input_fielf: diff --git a/bank_managment_system/backend.py b/bank_managment_system/backend.py index 081d4d3d551..3c824d776b0 100644 --- a/bank_managment_system/backend.py +++ b/bank_managment_system/backend.py @@ -11,7 +11,8 @@ def __init__(self, db_name="bankmanaging.db"): self.acc_no = self._get_last_acc_no() + 1 def _setup_tables(self): - self.cur.execute(""" + self.cur.execute( + """ CREATE TABLE IF NOT EXISTS bank ( acc_no INTEGER PRIMARY KEY, name TEXT, @@ -21,15 +22,18 @@ def _setup_tables(self): account_type TEXT, mobile_number TEXT ) - """) - self.cur.execute(""" + """ + ) + self.cur.execute( + """ CREATE TABLE IF NOT EXISTS staff ( name TEXT, pass TEXT, salary INTEGER, position TEXT ) - """) + """ + ) self.cur.execute("CREATE TABLE IF NOT EXISTS admin (name TEXT, pass TEXT)") self.cur.execute("SELECT COUNT(*) FROM admin") if self.cur.fetchone()[0] == 0: diff --git a/bank_managment_system/frontend.py b/bank_managment_system/frontend.py index f84903f3036..c53c9470415 100644 --- a/bank_managment_system/frontend.py +++ b/bank_managment_system/frontend.py @@ -129,7 +129,7 @@ def back_page2(): r = check_string_in_account_no(acc_no) if len(acc_no) != 0 and r: details = backend.get_details(acc_no) - if details != False: + if details: search_frame.grid_forget() global show_frame show_frame = Frame(tk) @@ -452,7 +452,7 @@ def update_name(): # def a function eho updates name in database def update_name_in_database(): new_name = entry_name.get() - r = check_string_in_account_no(new_name) + check_string_in_account_no(new_name) if len(new_name) != 0: # function in backend that updates name in table backend.update_name_in_bank_table(new_name, acc_no) diff --git a/billing.py b/billing.py index 451135cc91c..f8fb9868f1d 100644 --- a/billing.py +++ b/billing.py @@ -1,14 +1,15 @@ - items = {"apple": 5, "soap": 4, "soda": 6, "pie": 7, "cake": 20} total_price = 0 try: - print(""" + print( + """ Press 1 for apple Press 2 for soap Press 3 for soda Press 4 for pie Press 5 for cake -Press 6 for bill""") +Press 6 for bill""" + ) while True: choice = int(input("enter your choice here..")) if choice == 1: @@ -28,10 +29,12 @@ print("cake added to the cart") total_price += items["cake"] elif choice == 6: - print(f""" + print( + f""" Total amount :{total_price} -""") +""" + ) break else: print("Please enter the digits within the range 1-6..") diff --git a/binary_search_tree.py b/binary_search_tree.py index 327c45c722d..7ff22c8f1c9 100755 --- a/binary_search_tree.py +++ b/binary_search_tree.py @@ -234,7 +234,7 @@ def inorder_itr(node): stack = [] current = node while True: - if current != None: + if current is not None: stack.append(current) # L current = current.left elif stack != []: diff --git a/blackJackGUI.py b/blackJackGUI.py index a67e6e06717..68e90a3ce04 100644 --- a/blackJackGUI.py +++ b/blackJackGUI.py @@ -133,22 +133,22 @@ def deal(): def stand(): - if in_play == True: + if in_play: while dealer_card.get_value() < 17: dealer_card.add_card(deck.deal_card()) if dealer_card.get_value() > 21: - outcome = "you won!!" + pass elif player_card.get_value() <= dealer_card.get_value(): - outcome = "you lose" + pass else: - outcome = "you won!!" - score1 = str(player_card.get_value()) - score2 = str(dealer_card.get_value()) + pass + str(player_card.get_value()) + str(dealer_card.get_value()) def hit(): global outcome, in_play, score1, score2, player_card, dealer_card, deck - if in_play == True: + if in_play: player_card.add_card(deck.deal_card()) if player_card.get_value() > 21: diff --git a/bookstore_manangement_system.py b/bookstore_manangement_system.py index 9ef2809337b..3815709e4e8 100644 --- a/bookstore_manangement_system.py +++ b/bookstore_manangement_system.py @@ -230,7 +230,7 @@ def CNB2(): a = True -while a == True: +while a: # PROGRAM STARTED print(" *TO VIEW ALL ENTER 1") @@ -286,7 +286,7 @@ def CNB2(): mycur.execute(display) data2 = mycur.fetchone() - if data2 != None: + if data2 is not None: print("BOOK IS AVAILABLE") # BUY OR NOT @@ -613,7 +613,7 @@ def CNB2(): mycur.execute(display10) data20 = mycur.fetchone() - if data20 != None: + if data20 is not None: print("This ISBN Already Exists") os._exit(0) @@ -657,7 +657,7 @@ def CNB2(): mycur.execute(display) data2 = mycur.fetchone() - if data2 != None: + if data2 is not None: SNo1 = int(input("ENTER NEW SNo OF BOOK -- ")) name1 = input("ENTER NEW NAME OF BOOK --- ") author1 = input("ENTER NEW NAME OF AUTHOR -- ") @@ -724,7 +724,7 @@ def CNB2(): mycur.execute(display) data2 = mycur.fetchone() - if data2 != None: + if data2 is not None: separator() choice5 = input("ARE YOU SURE TO DELETE THIS BOOK ENTER Y/N -- ") diff --git a/brickout-game/brickout-game.py b/brickout-game/brickout-game.py index 40aa05f001d..024eff7e5aa 100644 --- a/brickout-game/brickout-game.py +++ b/brickout-game/brickout-game.py @@ -196,8 +196,8 @@ def collide(self, ball): brickH = self._height ballX = ball._xLoc ballY = ball._yLoc - ballXVel = ball.getXVel() - ballYVel = ball.getYVel() + ball.getXVel() + ball.getYVel() if ( (ballX + ball._radius) >= brickX @@ -252,7 +252,7 @@ def draw(self): draws all bricks onto screen. """ for brick in self._bricks: - if brick != None: + if brick is not None: brick.draw() def update(self, ball): @@ -260,7 +260,7 @@ def update(self, ball): 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] is not None) and self._bricks[i].collide(ball): self._bricks[i] = None # removes the None-elements from the brick list. diff --git a/calc_area.py b/calc_area.py index 29fb370cd4a..12ce26ffdcf 100644 --- a/calc_area.py +++ b/calc_area.py @@ -1,6 +1,8 @@ # Author: PrajaktaSathe # Program to calculate the area of - square, rectangle, circle, and triangle - import math as m + + def main(): shape = int( input( diff --git a/calculator.py b/calculator.py index ff456112afa..b9feb8c6f97 100644 --- a/calculator.py +++ b/calculator.py @@ -23,12 +23,8 @@ absolute value : aval(n) """ -import sys - ## Imported math library to run sin(), cos(), tan() and other such functions in the calculator -from fileinfo import raw_input - def calc(term): """ @@ -76,15 +72,12 @@ def calc(term): # here goes to the error cases. except ZeroDivisionError: print("Can't divide by 0. Please try again.") - except NameError: print("Invalid input. Please try again") - except AttributeError: print("Please check usage method and try again.") except TypeError: - print("please enter inputs of correct datatype ") - + print("Please only enter integers") return term @@ -110,20 +103,13 @@ def main(): + "- 12mod3\n\nEnter quit to exit" ) - if sys.version_info.major >= 3: - while True: - k = input("\nWhat is ") - if k == "quit": - break - result(k) - - else: - while True: - k = raw_input("\nWhat is ") - if k == "quit": - break - result(k) - -if __name__ == "__main__": +k = input("\nWhat is ") +if k == "quit" or "q": + result(k) +elif k is None: + print("Couldn't read input. Please try again.") +elif q is None: + print("Couldn't read input. Please try again.") +else: main() diff --git a/check if a number positive , negative or zero b/check if a number positive , negative or zero index c47cda8ae78..48deaebeafa 100644 --- a/check if a number positive , negative or zero +++ b/check if a number positive , negative or zero @@ -1,16 +1,15 @@ num = float(input("Enter a number: ")) if num > 0: - print("Positive number") + print("Positive number") elif num == 0: - print("Zero") + print("Zero") else: - print("Negative number") - num = float(input("Enter a number: ")) + print("Negative number") + num = float(input("Enter a number: ")) if num >= 0: - if num == 0: - print("Zero") - else: - print("Positive number") + if num == 0: + print("Zero") + else: + print("Positive number") else: - print("Negative number") - + print("Negative number") diff --git a/classicIndianCardMatch.py b/classicIndianCardMatch.py index 6c859fb8f4d..86483ebc3c7 100644 --- a/classicIndianCardMatch.py +++ b/classicIndianCardMatch.py @@ -93,7 +93,7 @@ def __str__(self): 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: + while switchPlayer: for card in range(len(player1)): input("Enter any key to place a card!!!\n") currentPlayer1Card = player1[card].rank @@ -107,7 +107,7 @@ def __str__(self): "The human got a match and takes all the cards from center pile.." ) break - while switchPlayer == False: + while not switchPlayer: for card in range(len(player2)): currentPlayer2Card = player2[card].rank print("Computer's current card's rank: {}".format(currentPlayer2Card)) diff --git a/days_from_date.py b/days_from_date.py index 61f09cc81fe..e4e138072bb 100644 --- a/days_from_date.py +++ b/days_from_date.py @@ -15,9 +15,9 @@ def process_date(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 + 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 @@ -30,9 +30,7 @@ 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 - ) + 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( diff --git a/dialogs/requirements.txt b/dialogs/requirements.txt index 51d89fc61fc..9848dc29115 100644 --- a/dialogs/requirements.txt +++ b/dialogs/requirements.txt @@ -1 +1 @@ -quo>=2022.4 +quo >= 2022.4 diff --git a/fF b/fF index 2edac5d9f5d..97e2ac3b3d2 100644 --- a/fF +++ b/fF @@ -9,6 +9,7 @@ import os import sys + def get_folder_size(directory): """Calculate the total size of a directory and its subdirectories.""" total_size = 0 @@ -17,6 +18,7 @@ def get_folder_size(directory): total_size += os.path.getsize(os.path.join(root, file)) return total_size + def format_size(size): """Format the size into human-readable units.""" units = ["Bytes", "KB", "MB", "GB", "TB"] @@ -25,19 +27,21 @@ def format_size(size): return f"{size:.2f} {unit}" size /= 1024 + def main(): if len(sys.argv) < 2: print("Usage: python folder_size.py ") sys.exit(1) directory = sys.argv[1] - + if not os.path.exists(directory): print(f"Error: The directory '{directory}' does not exist.") sys.exit(1) - + folder_size = get_folder_size(directory) print(f"Folder Size: {format_size(folder_size)}") + if __name__ == "__main__": main() diff --git a/fibonacci_SIMPLIFIED b/fibonacci_SIMPLIFIED index 77f6854050f..ce3d71a6a86 100644 --- a/fibonacci_SIMPLIFIED +++ b/fibonacci_SIMPLIFIED @@ -1,10 +1,10 @@ - -#printing fibonnaci series till nth element - simplified version for begginers +# printing fibonnaci series till nth element - simplified version for begginers def print_fibonacci(n): current_no = 1 prev_no = 0 for i in range(n): - print(current_no, end = " ") - prev_no,current_no = current_no, current_no + prev_no + print(current_no, end=" ") + prev_no, current_no = current_no, current_no + prev_no + print_fibonacci(10) diff --git a/file_ext_changer.py b/file_ext_changer.py index 407e46f991c..f951ba2ae31 100644 --- a/file_ext_changer.py +++ b/file_ext_changer.py @@ -97,7 +97,7 @@ def chxten_(files, xten): # Validation for file in files: check = p(file).exists() - if check == False: + if not check: print(f"{file} is not found. Paste this file in the directory of {file}") files.remove(file) # Ended validation @@ -122,7 +122,7 @@ def chxten_(files, xten): # Validation for file in files: check = p(file).exists() - if check == False: + if not check: print( f"{file} is not found. Paste this file in the directory of {file}" ) diff --git a/file_handle/File handle binary/question 1 (elegible for remedial, top marks).py b/file_handle/File handle binary/question 1 (elegible for remedial, top marks).py index 27a29f887dc..e2128e2db42 100644 --- a/file_handle/File handle binary/question 1 (elegible for remedial, top marks).py +++ b/file_handle/File handle binary/question 1 (elegible for remedial, top marks).py @@ -20,7 +20,6 @@ student_record = os.getenv("STUDENTS_RECORD_FILE") import pickle -import logging # Define logger with info # import polar diff --git a/file_handle/File handle binary/search record in binary file.py b/file_handle/File handle binary/search record in binary file.py index a3b89e69c87..61c1a4b3ee7 100644 --- a/file_handle/File handle binary/search record in binary file.py +++ b/file_handle/File handle binary/search record in binary file.py @@ -1,7 +1,6 @@ # binary file to search a given record import pickle -from dotenv import load_dotenv def search(): diff --git a/file_handle/File handle text/counter.py b/file_handle/File handle text/counter.py index 0cf3d03819a..42d3b25f20d 100644 --- a/file_handle/File handle text/counter.py +++ b/file_handle/File handle text/counter.py @@ -14,7 +14,6 @@ # ! Based on requirements of it - ## ! The questions are nothing but test-cases ## ! Make a test thing and handle it. # does it count only alphabets or numerics too? diff --git a/file_handle/File handle text/input,output and error streams.py b/file_handle/File handle text/input,output and error streams.py index a83319f8b5a..1633c2b2740 100644 --- a/file_handle/File handle text/input,output and error streams.py +++ b/file_handle/File handle text/input,output and error streams.py @@ -9,7 +9,11 @@ ) as F: 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 + 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") diff --git a/findlargestno.md b/findlargestno.md index a4fb15c1231..d636d48e307 100644 --- a/findlargestno.md +++ b/findlargestno.md @@ -7,15 +7,15 @@ num2 = 14 num3 = 12 # uncomment following lines to take three numbers from user -#num1 = float(input("Enter first number: ")) -#num2 = float(input("Enter second number: ")) -#num3 = float(input("Enter third number: ")) +# num1 = float(input("Enter first number: ")) +# num2 = float(input("Enter second number: ")) +# num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): - largest = num1 + largest = num1 elif (num2 >= num1) and (num2 >= num3): - largest = num2 + largest = num2 else: - largest = num3 + largest = num3 print("The largest number is", largest) diff --git a/get_youtube_view.py b/get_youtube_view.py index 77f1b1a29b8..118f0f7c37f 100644 --- a/get_youtube_view.py +++ b/get_youtube_view.py @@ -2,6 +2,7 @@ Created on Thu Apr 27 16:28:36 2017 @author: barnabysandeford """ + # Currently works for Safari, but just change to whichever # browser you're using. diff --git a/gui_calculator.py b/gui_calculator.py index e0fa630e427..b651ca183ea 100644 --- a/gui_calculator.py +++ b/gui_calculator.py @@ -98,7 +98,7 @@ def subtract(): def get(): - b = txt1.get() + txt1.get() def equals(): diff --git a/happy_num.py b/happy_num.py index d2d30dde99a..4e0d395f96a 100644 --- a/happy_num.py +++ b/happy_num.py @@ -1,5 +1,6 @@ # Way2 1: + # isHappyNumber() will determine whether a number is happy or not def isHappyNumber(num): rem = sum = 0 diff --git a/inheritance_YahV1729.py b/inheritance_YahV1729.py index 7b59954fe61..4ef8c724ab2 100644 --- a/inheritance_YahV1729.py +++ b/inheritance_YahV1729.py @@ -1,5 +1,6 @@ # A Python program to demonstrate inheritance + # Base or Super class. Note object in bracket. # (Generally, object is made ancestor of all classes) # In Python 3.x "class Person" is diff --git a/insta_monitering/insta_datafetcher.py b/insta_monitering/insta_datafetcher.py index 04b58df4052..924980c7962 100644 --- a/insta_monitering/insta_datafetcher.py +++ b/insta_monitering/insta_datafetcher.py @@ -95,7 +95,7 @@ async def request_pull(url): return data data = await request_pull(url) - if data != None: + if data is not None: break data = await dataprocess(htmldata=data) # here processing of data has to occur @@ -217,11 +217,11 @@ def reqest_pull(url): return data data = reqest_pull(self._url) - if data != None: + if data is not None: break datadict = ujson.loads(data) userdata, media_post, top_post = self._dataProcessing(datadict) - finallydata = self._lastProcess( + self._lastProcess( userdata=userdata, media_post=media_post, top_post=top_post ) # print(ujson.dumps(finallydata)) @@ -312,7 +312,7 @@ def startprocess(self, user, tags, type, productId): hashtags(user=user, tags=tags, type=type, productId=productId) check = self._dbProcessReader(user=user, tags=tags, productId=productId) print(check) - if check == False: + if not check: break time.sleep(300) # therad.join() @@ -388,7 +388,7 @@ def DBFetcherGreater(self, limit, date): postval = {} try: postval["posts"] = None - if limit.isdigit() == False and date.isdigit() == False: + if not limit.isdigit() and not date.isdigit(): raise Exception limit = int(limit) date = int(date) @@ -419,7 +419,7 @@ def DBFetcherLess(self, limit, date): postval = {} try: postval["posts"] = None - if limit.isdigit() == False and date.isdigit() == False: + if not limit.isdigit() and not date.isdigit(): raise Exception limit = int(limit) date = int(date) diff --git a/linear-algebra-python/src/tests.py b/linear-algebra-python/src/tests.py index 38e4a627c2d..e9885c1e37f 100644 --- a/linear-algebra-python/src/tests.py +++ b/linear-algebra-python/src/tests.py @@ -23,7 +23,7 @@ def test_component(self): self.assertEqual(x.component(0), 1) self.assertEqual(x.component(2), 3) try: - y = Vector() + Vector() self.assertTrue(False) except: self.assertTrue(True) diff --git a/magic8ball.py b/magic8ball.py index 816705b8e21..b76e3a547e1 100644 --- a/magic8ball.py +++ b/magic8ball.py @@ -39,7 +39,7 @@ def display_greeting(name): def magic_8_ball(): - question = inquirer.text(message="What's your question?").execute() + inquirer.text(message="What's your question?").execute() answer = random.choice(responses) print(Fore.BLUE + Style.BRIGHT + answer + Style.RESET_ALL) try_again() diff --git a/magic_8_ball.py b/magic_8_ball.py index 816705b8e21..b76e3a547e1 100644 --- a/magic_8_ball.py +++ b/magic_8_ball.py @@ -39,7 +39,7 @@ def display_greeting(name): def magic_8_ball(): - question = inquirer.text(message="What's your question?").execute() + inquirer.text(message="What's your question?").execute() answer = random.choice(responses) print(Fore.BLUE + Style.BRIGHT + answer + Style.RESET_ALL) try_again() diff --git a/mapit.py b/mapit.py index 27fb71a92fc..73d8666d7b7 100644 --- a/mapit.py +++ b/mapit.py @@ -1,6 +1,7 @@ import sys import webbrowser import pyperclip + if len(sys.argv) > 1: address = " ".join(sys.argv[1:]) diff --git a/new.py b/new.py index c5058551ec7..f7cf60e14f9 100644 --- a/new.py +++ b/new.py @@ -1,3 +1 @@ - print("Hello, world!") - diff --git a/news_articles__scraper.py b/news_articles__scraper.py index a9266ad0a58..70dcdbbf0ed 100644 --- a/news_articles__scraper.py +++ b/news_articles__scraper.py @@ -142,7 +142,9 @@ """**Scraping news from Times of India**""" -TOIarticle_links = [] # Creating an empty list of all the urls of news from Times of India site +TOIarticle_links = ( + [] +) # Creating an empty list of all the urls of news from Times of India site # Extracting links for all the pages (2 to 125) of boomlive fake news section for i in range(2, 126): diff --git a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py index 6eddf2d6b85..adecaee98c8 100644 --- a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py +++ b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py @@ -18,7 +18,7 @@ def start_reloader(): """Adding a live server for tkinter test GUI, which reloads the GUI when the code is changed.""" - reloader = hupper.start_reloader("p1.main") + hupper.start_reloader("p1.main") # Function to update expression diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py b/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py index ded1c86bcd3..24d7231244e 100644 --- a/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py +++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py @@ -258,7 +258,7 @@ def get_app(Q): webbrowser.open("https://github.com/") elif Q == "search for": que = Q.lstrip("search for") - answer = ask_gpt3(que) + ask_gpt3(que) elif ( Q == "email to other" @@ -269,7 +269,7 @@ def get_app(Q): with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 - audio = r.listen(source) + r.listen(source) to = "abc@gmail.com" content = input("Enter content") sendEmail(to, content) @@ -307,11 +307,11 @@ def get_app(Q): elif Q == "take a break": exit() else: - answer = ask_gpt3(Q) + ask_gpt3(Q) # master - apps = { + { "time": datetime.datetime.now(), "notepad": "Notepad.exe", "calculator": "calc.exe", diff --git a/nmap_scan.py b/nmap_scan.py index 72f4b078e96..767d1e0b7a3 100644 --- a/nmap_scan.py +++ b/nmap_scan.py @@ -31,7 +31,7 @@ def main(): # Main Program tgtHost = options.tgtHost tgtPorts = str(options.tgtPort).split(",") - if (tgtHost == None) | (tgtPorts[0] == None): + if (tgtHost is None) | (tgtPorts[0] is None): print(parser.usage) exit(0) diff --git a/other_pepole/get_ip_gui b/other_pepole/get_ip_gui index 5728697ac5b..5339ac1599c 100755 --- a/other_pepole/get_ip_gui +++ b/other_pepole/get_ip_gui @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- import socket + # **************** Modules Require *****************# from tkinter import * from urllib.request import urlopen @@ -12,19 +13,19 @@ from urllib.request import urlopen def get_wan_ip(): try: # get ip from http://ipecho.net/plain as text - wan_ip = urlopen('http://ipecho.net/plain').read().decode('utf-8') - res.configure(text='Wan IP is : ' + wan_ip, fg='#600') + wan_ip = urlopen("http://ipecho.net/plain").read().decode("utf-8") + res.configure(text="Wan IP is : " + wan_ip, fg="#600") except: - res.configure(text='Problem in source : http://ipecho.net/plain', fg='red') + res.configure(text="Problem in source : http://ipecho.net/plain", fg="red") # get local ip def get_local_ip(): try: - lan_ip = (socket.gethostbyname(socket.gethostname())) - res.configure(text='Local IP is : ' + lan_ip, fg='#600') + lan_ip = socket.gethostbyname(socket.gethostname()) + res.configure(text="Local IP is : " + lan_ip, fg="#600") except: - res.configure(text='Unkown Error', fg='#red') + res.configure(text="Unkown Error", fg="#red") # **************** about control button *****************# @@ -32,15 +33,19 @@ def get_local_ip(): def about(): global close_app, frame, info about_app.destroy() - frame = Frame(root, width=350, height=2, bg='blue') + frame = Frame(root, width=350, height=2, bg="blue") frame.grid(row=2, column=0, columnspan=4) - info = Label(root, text=""" + info = Label( + root, + text=""" Practice Python Take idea from here : https://github.com/geekcomputers/Python/blob/master/myip.py - """, fg='#02F') + """, + fg="#02F", + ) info.grid(row=3, column=0, columnspan=4, padx=5) - close_app = Button(root, text='Close', command=close_about, bg='#55F') + close_app = Button(root, text="Close", command=close_about, bg="#55F") close_app.grid(row=4, column=0, columnspan=4, pady=5) @@ -50,19 +55,19 @@ def close_about(): info.destroy() frame.destroy() close_app.destroy() - about_app = Button(root, text='about', command=about) + about_app = Button(root, text="about", command=about) about_app.grid(row=1, column=2, padx=5, pady=5, sticky=W) # **************** Tkinter GUI *****************# root = Tk() -root.title('Khaled programing practice') +root.title("Khaled programing practice") # all buttons -res = Label(root, text='00.00.00.00', font=25) -res_wan_ip = Button(root, text='Get Wan IP', command=get_wan_ip) -res_local_ip = Button(root, text='Get Local IP', command=get_local_ip) -about_app = Button(root, text='about', command=about) -quit_app = Button(root, text='quit', command=quit, bg='#f40') +res = Label(root, text="00.00.00.00", font=25) +res_wan_ip = Button(root, text="Get Wan IP", command=get_wan_ip) +res_local_ip = Button(root, text="Get Local IP", command=get_local_ip) +about_app = Button(root, text="about", command=about) +quit_app = Button(root, text="quit", command=quit, bg="#f40") # method grid to install the button in window res.grid(row=0, column=0, columnspan=4, sticky=N, padx=10, pady=5) res_wan_ip.grid(row=1, column=0, padx=5, pady=5, sticky=W) diff --git a/passwordGen.py b/passwordGen.py index 56ab3b462a1..9c0aadc2597 100644 --- a/passwordGen.py +++ b/passwordGen.py @@ -1,4 +1,5 @@ import random + lChars = "abcdefghijklmnopqrstuvwxyz" uChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" digits = "1234567890" @@ -20,4 +21,4 @@ for _ in range(2): myPass += random.choice(uChars) -print(myPass) +print(myPass) diff --git a/portscanner.py b/portscanner.py index 78fcde14a26..7e7e028719a 100644 --- a/portscanner.py +++ b/portscanner.py @@ -61,7 +61,7 @@ def main(): (options, args) = parser.parse_args() tgtHost = options.tgtHost tgtPorts = str(options.tgtPort).split(",") - if (tgtHost == None) | (tgtPorts[0] == None): + if (tgtHost is None) | (tgtPorts[0] is None): print(parser.usage) exit(0) portScan(tgtHost, tgtPorts) diff --git a/powerup_checks.py b/powerup_checks.py index b29cd43ba61..81f51165e89 100644 --- a/powerup_checks.py +++ b/powerup_checks.py @@ -87,7 +87,7 @@ def get_servers(query): # Function to get the servers from the database print("\nDisplaying Servers for : " + query + "\n") while True: # While there are results row = cursor.fetchone() # Return the results - if row == None: + if row is None: break f = open(serverfile, "a") # Open the serverfile f.write("%s\n" % str(row[0])) # Write the server out to the file diff --git a/primelib/Prime.txt b/primelib/Prime.txt index 801324b3c35..a5b17f32d44 100644 --- a/primelib/Prime.txt +++ b/primelib/Prime.txt @@ -3,20 +3,20 @@ num = 407 # To take input from the user -#num = int(input("Enter a number: ")) +# num = int(input("Enter a number: ")) # prime numbers are greater than 1 if num > 1: - # check for factors - for i in range(2,num): - if (num % i) == 0: - print(num,"is not a prime number") - print(i,"times",num//i,"is",num) - break - else: - print(num,"is a prime number") - + # check for factors + for i in range(2, num): + if (num % i) == 0: + print(num, "is not a prime number") + print(i, "times", num // i, "is", num) + break + else: + print(num, "is a prime number") + # if input number is less than # or equal to 1, it is not prime else: - print(num,"is not a prime number") + print(num, "is not a prime number") diff --git a/primelib/primelib.py b/primelib/primelib.py index e43f267c7d2..0027523770a 100644 --- a/primelib/primelib.py +++ b/primelib/primelib.py @@ -68,9 +68,9 @@ def isPrime(number): """ # 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. if number <= 3: @@ -198,9 +198,9 @@ def greatestPrimeFactor(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 @@ -225,9 +225,9 @@ def smallestPrimeFactor(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 @@ -285,9 +285,9 @@ def goldbach(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 @@ -353,9 +353,9 @@ 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 @@ -425,9 +425,9 @@ 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 @@ -459,9 +459,9 @@ def getPrime(n): 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 @@ -478,9 +478,9 @@ def getPrimesBetween(pNumber1, pNumber2): """ # 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 @@ -543,9 +543,9 @@ def isPerfectNumber(number): """ # 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) diff --git a/python_sms.py b/python_sms.py index 99cf8f943dc..42c6c275394 100644 --- a/python_sms.py +++ b/python_sms.py @@ -30,7 +30,7 @@ cursor.execute(loc_stmt) while True: row = cursor.fetchone() - if row == None: + if row is None: break sname = row[0] snumber = row[1] diff --git a/requirements.txt b/requirements.txt index bf51bb07640..6c59986c55d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -20,7 +20,7 @@ win10toast Counter Flask selenium -firebase-admin +firebase - admin ujson requests quo @@ -30,10 +30,10 @@ twilio tabula nltk Pillow -SocksiPy-branch +SocksiPy - branch xlrd fpdf -mysql-connector-repackaged +mysql - connector - repackaged word2number tornado obs @@ -43,7 +43,7 @@ keras pymongo playsound pyttsx3 -auto-mix-prep +auto - mix - prep lib pywifi patterns @@ -52,11 +52,11 @@ background pydantic openpyxl pytesseract -requests-mock +requests - mock pyglet urllib3 thirdai -google-api-python-client +google - api - python - client sound xlwt pygame @@ -68,7 +68,7 @@ yfinance tweepy tkcalendar pytube -xor-cipher +xor - cipher bird mechanize translate @@ -92,7 +92,7 @@ PyQRCode freegames pyperclip newspaper -opencv-python +opencv - python tensorflow pandas pytest @@ -106,6 +106,6 @@ httplib2 protobuf colorama plyer -Flask-Ask +Flask - Ask emoji PyAutoGUI diff --git a/requirements_with_versions.txt b/requirements_with_versions.txt index cd9b7538c8f..9fdd04fdc82 100644 --- a/requirements_with_versions.txt +++ b/requirements_with_versions.txt @@ -54,6 +54,9 @@ background==0.2.1 pydantic==2.12.3 openpyxl==3.1.2 pytesseract==0.3.13 +pydantic==2.7.3 +openpyxl==3.1.5 +pytesseract==0.3.10 requests-mock==1.12.1 pyglet==2.1.9 urllib3==2.5.0 diff --git a/russian_roulette.py b/russian_roulette.py index 82374186515..b1220766f03 100644 --- a/russian_roulette.py +++ b/russian_roulette.py @@ -44,7 +44,7 @@ def main(): turn = "pc" # game starts - while numOfRounds != 0 and (pc == False and player == False): + while numOfRounds != 0 and (not pc and not player): print(f"\nRound number {numOfRounds}/6") time.sleep(1) print("the gun is being loaded") diff --git a/scientific_cal.py b/scientific_cal.py index 11fccc450d5..6f0827f508f 100644 --- a/scientific_cal.py +++ b/scientific_cal.py @@ -1,16 +1,19 @@ import math while True: - print(""" + print( + """ Press 1 for basic calculator - Press 2 for scientifc calculator""") + Press 2 for scientifc calculator""" + ) try: cho = int(input("enter your choice here.. ")) if cho == 1: print(eval(input("enter the numbers with operator "))) elif cho == 2: user = int( - input(""" + input( + """ Press 1 for pi calculation press 2 for sin calculation press 3 for exponent calculation @@ -18,7 +21,8 @@ press 5 for square root calculation press 6 round calculation press 7 for absoulte value - press any other number to exit the loop. """) + press any other number to exit the loop. """ + ) ) a = float(input("enter your value here.. ")) diff --git a/sendemail.py b/sendemail.py index 070968157be..c586b9a0bb0 100644 --- a/sendemail.py +++ b/sendemail.py @@ -16,6 +16,8 @@ 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") diff --git a/sensors_information.py b/sensors_information.py index 257b41e5a4b..2b089ef13a6 100644 --- a/sensors_information.py +++ b/sensors_information.py @@ -2,8 +2,12 @@ import sys import socket import psutil + + def python_version(): return sys.version_info + + def ip_addresses(): hostname = socket.gethostname() addresses = socket.getaddrinfo(hostname, None) @@ -40,7 +44,7 @@ def command_line(argv): description="Display the values of the sensors", add_help=True, ) - arguments = parser.parse_args() + parser.parse_args() show_sensors() diff --git a/simulate_memory_cpu.py b/simulate_memory_cpu.py index 1a8ab142071..b8bad4677d8 100644 --- a/simulate_memory_cpu.py +++ b/simulate_memory_cpu.py @@ -28,9 +28,9 @@ def mem(): num = int(match.group(1)) unit = match.group(2) if unit == "MB": - s = " " * (num * 1024 * 1024) + " " * (num * 1024 * 1024) else: - s = " " * (num * 1024 * 1024 * 1024) + " " * (num * 1024 * 1024 * 1024) time.sleep(24 * 3600) else: print("bad args.....") diff --git a/singly_linked_list.py b/singly_linked_list.py index 8eca38598fe..927bf8e6056 100644 --- a/singly_linked_list.py +++ b/singly_linked_list.py @@ -11,7 +11,7 @@ def __init__(self): def length(self): curr = self.head count = 0 - while curr.next != None: + while curr.next is not None: count += 1 curr = curr.next return count @@ -22,7 +22,7 @@ def add_node(self, data): self.head = new_node else: curr = self.head - while curr.next != None: + while curr.next is not None: curr = curr.next curr.next = new_node @@ -64,7 +64,7 @@ def delete_end(self): curr = self.head prev = None while True: - if curr.next == None: + if curr.next is None: prev.next = None del curr break @@ -98,7 +98,7 @@ def display(self): print("List is empty") rev = [] curr = self.head - while curr != None: + while curr is not None: print(f"{curr.data} --> ", end="") rev.append(curr.data) curr = curr.next diff --git a/sorting_algos.py b/sorting_algos.py index cd9d6bcab90..f03402a0e5c 100644 --- a/sorting_algos.py +++ b/sorting_algos.py @@ -135,7 +135,7 @@ def counting_sort(arr: list) -> list: TC : O(n) SC : O(n)""" - n = len(arr) + len(arr) maxx = max(arr) counts = [0] * (maxx + 1) for x in arr: @@ -151,17 +151,8 @@ def counting_sort(arr: list) -> list: def main(): - algos = { - "selection_sort": ["TC : O(n^2)", "SC : O(1)"], - "bubble_sort": ["TC : O(n^2)", "SC : O(1)"], - "insertion_sort": ["TC : O(n^2)", "SC : O(1)"], - "merge_sort": ["TC : O(n^2)", "SC : O(1)"], - "quick_sort": ["TC : O(n^2)", "SC : O(1)"], - "counting_sort": ["TC : O(n^2)", "SC : O(1)"], - } - inp = [1, 2, 7, -8, 34, 2, 80, 790, 6] - arr = counting_sort(inp) + counting_sort(inp) print("U are amazing, Keep up") diff --git a/sqlite_check.py b/sqlite_check.py index 27e35ace641..c87944a3b68 100644 --- a/sqlite_check.py +++ b/sqlite_check.py @@ -44,6 +44,6 @@ cur.execute("SELECT name FROM sqlite_master WHERE type='table'") while True: row = cur.fetchone() - if row == None: + if row is None: break print(row[0]) diff --git a/stack.py b/stack.py index d90048ccf62..c6f4ef523d6 100644 --- a/stack.py +++ b/stack.py @@ -1,5 +1,6 @@ # Python program to reverse a string using stack + # Function to create an empty stack. # It initializes size of stack as 0 def createStack(): diff --git a/testlines.py b/testlines.py index 5de3766038e..c05b218e18e 100644 --- a/testlines.py +++ b/testlines.py @@ -11,7 +11,7 @@ def write_to_file(filename, txt): with open(filename, "w") as file_object: - s = file_object.write(txt) + file_object.write(txt) if __name__ == "__main__": diff --git a/tf_idf_generator.py b/tf_idf_generator.py index f31f0137b31..1cc31f1be2c 100644 --- a/tf_idf_generator.py +++ b/tf_idf_generator.py @@ -88,7 +88,9 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): """ 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) + 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) @@ -133,17 +135,21 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None): TAG, "Total number of unique words in corpus", len(idf), - "( " + paint("++" + str(len(idf) - prev_doc_count), "g") + " )" - if prev_file_path - else "", + ( + "( " + 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 "", + ( + "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )" + if prev_file_path + else "" + ), ) # dump if a dir-path is given diff --git a/time_delta.py b/time_delta.py index dc9d479303d..0f4a712a7ee 100644 --- a/time_delta.py +++ b/time_delta.py @@ -4,6 +4,7 @@ This module provides functionality to calculate the absolute difference in seconds between two timestamps in the format: Day dd Mon yyyy hh:mm:ss +xxxx """ + # ----------------------------------------------------------------------------- # You are givent two timestams in the format: Day dd Mon yyyy hh:mm:ss +xxxx # where +xxxx represents the timezone. diff --git a/ultimate-phone-book/contacts.py b/ultimate-phone-book/contacts.py index c1d70e9bcac..a8026874aaa 100644 --- a/ultimate-phone-book/contacts.py +++ b/ultimate-phone-book/contacts.py @@ -130,7 +130,7 @@ # if option 4 is selected elif a == 4: - if keyacess == True: + if keyacess: sortcounter = 1 while sortcounter != 0: # reset counter diff --git a/vowel remover function.py b/vowel remover function.py index 5af2ff5f01e..8d6467b57dc 100644 --- a/vowel remover function.py +++ b/vowel remover function.py @@ -4,4 +4,6 @@ def vowel_remover(text): if l.lower() not in "aeiou": string += l return string + + print(vowel_remover("hello world!")) diff --git a/webcam.py b/webcam.py index 30a89df27f4..eb3b63d6f0c 100644 --- a/webcam.py +++ b/webcam.py @@ -24,7 +24,7 @@ # Capture frame-by-frame ret, frame = cap.read() - if ret == True: + if ret: # Write frame to recording.avi out.write(frame) diff --git a/wiki/wiki.py b/wiki/wiki.py index dd2de43df4b..d4c3314b95a 100644 --- a/wiki/wiki.py +++ b/wiki/wiki.py @@ -15,6 +15,7 @@ WORD, END, ) + # import PIL as ImageTK diff --git a/wikipedia.py b/wikipedia.py index 7235894b66c..dd7a5f05321 100644 --- a/wikipedia.py +++ b/wikipedia.py @@ -1,14 +1,19 @@ import wikipedia from tkinter import * from tkinter.messagebox import showinfo + win = Tk() # objek win.title("WIKIPEDIA") win.geometry("200x70") # function + + # function def search_wiki(): search = entry.get() Hasil = wikipedia.summary(search) showinfo("Hasil Pencarian", Hasil) + + label = Label(win, text="Wikipedia Search :") label.grid(row=0, column=0) diff --git a/youtubedownloader.py b/youtubedownloader.py index b5667950a27..15fe2de2589 100644 --- a/youtubedownloader.py +++ b/youtubedownloader.py @@ -1,10 +1,14 @@ from tkinter import Button, Entry, Label, Tk, filedialog, messagebox from threading import Thread from pytube import YouTube + + def threading(): # Call work function t1 = Thread(target=download) t1.start() + + def download(): try: url = YouTube(str(url_box.get()))