From f41e8d22cb7584535d8dcd4c53e55d5e8e56bc2f Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Wed, 29 May 2024 15:01:15 +0530 Subject: [PATCH 01/11] Update work_connect.py --- work_connect.py | 153 ++++++++++++++++++++++++++++++------------------ 1 file changed, 96 insertions(+), 57 deletions(-) diff --git a/work_connect.py b/work_connect.py index bf3d4f9ed5a..dccb42d738d 100644 --- a/work_connect.py +++ b/work_connect.py @@ -1,65 +1,104 @@ -# Script Name : work_connect.py -# Author : Craig Richards -# Created : 11th May 2012 -# Last Modified : 31st October 2012 -# Version : 1.1 +import os +import subprocess +import sys +import time +import platform +import getpass +import logging -# Modifications : 1.1 - CR - Added some extra code, to check an argument is passed to the script first of all, then check it's a valid input +# Set up logging +logging.basicConfig(filename='script.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') -# Description : This simple script loads everything I need to connect to work etc +# Help text to display if no or invalid arguments are provided +help_text = """You need to pass an argument: + -c to connect to the remote desktop + -d to disconnect from the remote session + -cal to open Calculator + -paint to open MS Paint + -rdp to open Remote Desktop""" -import os # Load the Library Module -import subprocess # Load the Library Module -import sys # Load the Library Module -import time # Load the Library Module +# Check if at least one argument is passed to the script +if len(sys.argv) < 2: + print(help_text) + sys.exit(1) -dropbox = os.getenv( - "dropbox" -) # Set the variable dropbox, by getting the values of the environment setting for dropbox -rdpfile = "remote\\workpc.rdp" # Set the variable logfile, using the arguments passed to create the logfile -conffilename = os.path.join( - dropbox, rdpfile -) # Set the variable conffilename by joining confdir and conffile together -remote = ( - r"c:\windows\system32\mstsc.exe " # Set the variable remote with the path to mstsc -) +# Function to connect +def connect(): + try: + # Placeholder for connecting to remote desktop + logging.info("Connecting to remote desktop...") + print("Connecting to remote desktop...") + # Example: subprocess.Popen(["your_command_here"]) + except Exception as e: + logging.error(f"Failed to connect: {e}") + print(f"Failed to connect: {e}") + sys.exit(1) -text = """You need to pass an argument - -c Followed by login password to connect - -d to disconnect""" # Text to display if there is no argument passed or it's an invalid option - 1.2 +# Function to disconnect +def disconnect(): + try: + # Placeholder for disconnecting from remote session + logging.info("Disconnecting from remote session...") + print("Disconnecting from remote session...") + # Example: subprocess.Popen(["your_command_here"]) + except Exception as e: + logging.error(f"Failed to disconnect: {e}") + print(f"Failed to disconnect: {e}") + sys.exit(1) -if len(sys.argv) < 2: # Check there is at least one option passed to the script - 1.2 - print(text) # If not print the text above - 1.2 - sys.exit() # Exit the program - 1.2 +# Function to open Calculator +def open_calculator(): + try: + subprocess.Popen(["calc.exe"]) + except Exception as e: + logging.error(f"Failed to open Calculator: {e}") + print(f"Failed to open Calculator: {e}") + sys.exit(1) -if ( - "-h" in sys.argv or "--h" in sys.argv or "-help" in sys.argv or "--help" in sys.argv -): # Help Menu if called - print(text) # Print the text, stored in the text variable - 1.2 - sys.exit(0) # Exit the program +# Function to open MS Paint +def open_paint(): + try: + subprocess.Popen(["mspaint.exe"]) + except Exception as e: + logging.error(f"Failed to open MS Paint: {e}") + print(f"Failed to open MS Paint: {e}") + sys.exit(1) + +# Function to open Remote Desktop +def open_rdp(): + try: + subprocess.Popen(["mstsc.exe"]) + except Exception as e: + logging.error(f"Failed to open Remote Desktop: {e}") + print(f"Failed to open Remote Desktop: {e}") + sys.exit(1) + +# Function to get user confirmation +def get_confirmation(): + try: + confirmation = input("Are you sure you want to continue? (y/n): ").strip().lower() + if confirmation != 'y': + logging.info("Operation cancelled by user.") + print("Operation cancelled by user.") + sys.exit(0) + except KeyboardInterrupt: + logging.info("Operation cancelled by user.") + print("\nOperation cancelled by user.") + sys.exit(0) + +# Process the command line arguments +if sys.argv[1].lower() == "-c": + get_confirmation() + connect() +elif sys.argv[1].lower() == "-d": + get_confirmation() + disconnect() +elif sys.argv[1].lower() == "-cal": + open_calculator() +elif sys.argv[1].lower() == "-paint": + open_paint() +elif sys.argv[1].lower() == "-rdp": + open_rdp() else: - if sys.argv[1].lower().startswith("-c"): # If the first argument is -c then - passwd = sys.argv[ - 2 - ] # Set the variable passwd as the second argument passed, in this case my login password - subprocess.Popen( - ( - r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p " - + passwd - ) - ) - subprocess.Popen((r"c:\geektools\puttycm.exe")) - time.sleep( - 15 - ) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc - subprocess.Popen([remote, conffilename]) - elif ( - sys.argv[1].lower().startswith("-d") - ): # If the first argument is -d then disconnect my checkpoint session. - subprocess.Popen( - (r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect ") - ) - else: - print( - "Unknown option - " + text - ) # If any other option is passed, then print Unknown option and the text from above - 1.2 + print(f"Unknown option - {help_text}") + sys.exit(1) From 3c3ad5a2320a8d30d95f04acf631dd08d6459889 Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Wed, 5 Jun 2024 13:15:23 +0530 Subject: [PATCH 02/11] Create MiniSearchEngine.py --- Sorting Algorithms/MiniSearchEngine.py | 59 ++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Sorting Algorithms/MiniSearchEngine.py diff --git a/Sorting Algorithms/MiniSearchEngine.py b/Sorting Algorithms/MiniSearchEngine.py new file mode 100644 index 00000000000..a4efbfdd421 --- /dev/null +++ b/Sorting Algorithms/MiniSearchEngine.py @@ -0,0 +1,59 @@ +from collections import defaultdict + +documents = [ + "the quick brown fox jumps over the lazy dog", + "never jump over the lazy dog quickly", + "a fast brown fox leaps over a lazy dog", + "the fox", + "the dog", + "the lazy dog", + "quickly" +] + +def create_index(docs): + index = defaultdict(list) + for i, doc in enumerate(docs): + words = doc.split() + for word in words: + index[word].append(i) + return index + +def search(query, index): + query_words = query.split() + if not query_words: + return [] + + doc_lists = [set(index[word]) for word in query_words if word in index] + + if not doc_lists: + return [] + + result_docs = set.intersection(*doc_lists) + return list(result_docs) + +def rank_results(query, results, docs): + query_words = query.split() + ranked_results = [] + + for doc_index in results: + doc = docs[doc_index] + word_count = sum(doc.split().count(word) for word in query_words) + ranked_results.append((word_count, doc_index)) + + ranked_results.sort(reverse=True, key=lambda x: x[0]) + return [doc_index for _, doc_index in ranked_results] + +def main(): + index = create_index(documents) + while True: + query = input("Enter search query (or 'exit' to quit): ").strip() + if query == 'exit': + break + results = search(query, index) + ranked_results = rank_results(query, results, documents) + print(f"Documents matching '{query}': {ranked_results}") + for idx in ranked_results: + print(documents[idx]) + +if __name__ == "__main__": + main() From 786854297a6b2452b974f97c02cab5f070854072 Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Thu, 6 Jun 2024 11:02:56 +0530 Subject: [PATCH 03/11] Create linked_list.py --- Sorting Algorithms/linked_list.py | 92 +++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Sorting Algorithms/linked_list.py diff --git a/Sorting Algorithms/linked_list.py b/Sorting Algorithms/linked_list.py new file mode 100644 index 00000000000..4ea1a45a8f9 --- /dev/null +++ b/Sorting Algorithms/linked_list.py @@ -0,0 +1,92 @@ +class Node: + def __init__(self, data): + self.data = data + self.next = None + +class LinkedList: + def __init__(self): + self.head = None + + def append(self, data): + """Append a node with the given data to the end of the list.""" + new_node = Node(data) + if not self.head: + self.head = new_node + return + last_node = self.head + while last_node.next: + last_node = last_node.next + last_node.next = new_node + + def prepend(self, data): + """Prepend a node with the given data to the start of the list.""" + new_node = Node(data) + new_node.next = self.head + self.head = new_node + + def delete_with_value(self, data): + """Delete the first node containing the given data.""" + if not self.head: + return + + if self.head.data == data: + self.head = self.head.next + return + + current_node = self.head + while current_node.next and current_node.next.data != data: + current_node = current_node.next + + if current_node.next: + current_node.next = current_node.next.next + + def print_list(self): + """Print all elements in the linked list.""" + current_node = self.head + while current_node: + print(current_node.data, end=" -> ") + current_node = current_node.next + print("None") + + def insert_after_node(self, prev_node, data): + """Insert a new node after the given node.""" + if not prev_node: + print("The given previous node must in LinkedList.") + return + + new_node = Node(data) + new_node.next = prev_node.next + prev_node.next = new_node + + def delete_at_position(self, position): + """Delete the node at a specific position.""" + if not self.head: + return + + temp = self.head + + if position == 0: + self.head = temp.next + temp = None + return + + for i in range(position - 1): + temp = temp.next + if temp is None: + break + + if temp is None or temp.next is None: + return + + next = temp.next.next + temp.next = None + temp.next = next + + def length(self): + """Return the length of the linked list.""" + count = 0 + current_node = self.head + while current_node: + count += 1 + current_node = current_node.next + return count From 8f453c28deb077aab64372e040c8adb6c278bbaf Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Thu, 20 Jun 2024 15:22:15 +0530 Subject: [PATCH 04/11] Create task_manager.py --- Sorting Algorithms/task_manager.py | 108 +++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Sorting Algorithms/task_manager.py diff --git a/Sorting Algorithms/task_manager.py b/Sorting Algorithms/task_manager.py new file mode 100644 index 00000000000..8d17876c0e3 --- /dev/null +++ b/Sorting Algorithms/task_manager.py @@ -0,0 +1,108 @@ +import argparse +import datetime +import json +import logging as log +import time + +# Initialize logging +log.basicConfig(filename='tasks.log', level=log.INFO, format='%(asctime)s - %(message)s') + +# Load tasks from JSON file +def load_tasks(): + try: + with open('tasks.json', 'r') as file: + tasks = json.load(file) + except FileNotFoundError: + tasks = [] + return tasks + +# Save tasks to JSON file +def save_tasks(tasks): + with open('tasks.json', 'w') as file: + json.dump(tasks, file, indent=4) + +# Add a new task +def add_task(title, description, due_date): + tasks = load_tasks() + tasks.append({ + 'title': title, + 'description': description, + 'due_date': due_date, + 'status': 'pending' + }) + save_tasks(tasks) + log.info(f"Task '{title}' added with due date {due_date}") + +# List all tasks +def list_tasks(): + tasks = load_tasks() + for index, task in enumerate(tasks, start=1): + print(f"Task {index}:") + print(f" Title: {task['title']}") + print(f" Description: {task['description']}") + print(f" Due Date: {task['due_date']}") + print(f" Status: {task['status']}") + print() + +# Complete a task +def complete_task(index): + tasks = load_tasks() + if 1 <= index <= len(tasks): + tasks[index - 1]['status'] = 'completed' + save_tasks(tasks) + log.info(f"Task '{tasks[index - 1]['title']}' marked as completed") + else: + print("Invalid task index") + +# Delete a task +def delete_task(index): + tasks = load_tasks() + if 1 <= index <= len(tasks): + deleted_task = tasks.pop(index - 1) + save_tasks(tasks) + log.info(f"Task '{deleted_task['title']}' deleted") + else: + print("Invalid task index") + +# CLI setup +parser = argparse.ArgumentParser(description='Task Manager') +parser.add_argument('command', choices=['add', 'list', 'complete', 'delete'], help='Command to execute') +parser.add_argument('--title', help='Task title') +parser.add_argument('--description', help='Task description') +parser.add_argument('--due-date', help='Task due date (YYYY-MM-DD)') +parser.add_argument('--index', type=int, help='Task index') + +args = parser.parse_args() + +# Execute commands +if args.command == 'add': + add_task(args.title, args.description, args.due_date) +elif args.command == 'list': + list_tasks() +elif args.command == 'complete': + complete_task(args.index) +elif args.command == 'delete': + delete_task(args.index) + +""" +Usage: +Adding a task: + +csharp +Copy code +python task_manager.py add --title "Complete project" --description "Finish project report" --due-date 2024-07-01 +Listing tasks: + +Copy code +python task_manager.py list +Completing a task: + +css +Copy code +python task_manager.py complete --index 1 +Deleting a task: + +perl +Copy code +python task_manager.py delete --index 1 +""" From a35b6bdb8e7ddb0b75f3ec09f178b4d2c1a9c1bb Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Thu, 20 Jun 2024 15:23:53 +0530 Subject: [PATCH 05/11] Update task_manager.py --- Sorting Algorithms/task_manager.py | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/Sorting Algorithms/task_manager.py b/Sorting Algorithms/task_manager.py index 8d17876c0e3..4cb2ca922af 100644 --- a/Sorting Algorithms/task_manager.py +++ b/Sorting Algorithms/task_manager.py @@ -87,22 +87,14 @@ def delete_task(index): """ Usage: Adding a task: - -csharp -Copy code python task_manager.py add --title "Complete project" --description "Finish project report" --due-date 2024-07-01 -Listing tasks: -Copy code +Listing tasks: python task_manager.py list -Completing a task: -css -Copy code +Completing a task: python task_manager.py complete --index 1 -Deleting a task: -perl -Copy code +Deleting a task: python task_manager.py delete --index 1 """ From 7cfec1d3fc60a5826cf6417c573955c2527cd626 Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Thu, 20 Jun 2024 17:20:15 +0530 Subject: [PATCH 06/11] Update rotatelist.py --- rotatelist.py | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/rotatelist.py b/rotatelist.py index 9603b0434a1..e029d210bb0 100644 --- a/rotatelist.py +++ b/rotatelist.py @@ -1,20 +1,27 @@ -N = int(input("Enter The Size Of Array")) -list = [] -for i in range(0, N): - temp = int(input("Enter The Intger Numbers")) - list.append(temp) +def get_integer_input(prompt): + """ Helper function to get integer input from the user """ + while True: + try: + return int(input(prompt)) + except ValueError: + print("Please enter a valid integer.") +# Get the size of the array +N = get_integer_input("Enter the size of the array: ") -# Rotating Arrays Using Best Way: -# Left Rotation Of The List. -# Let's say we want to print list after its d number of rotations. +# Get the elements of the array +array = [] +for i in range(N): + array.append(get_integer_input(f"Enter integer number {i + 1}: ")) -finalList = [] -d = int(input("Enter The Number Of Times You Want To Rotate The Array")) +# Get the number of rotations +d = get_integer_input("Enter the number of times you want to rotate the array: ") -for i in range(0, N): - finalList.append(list[(i + d) % N]) +# Normalize d to be within the range of 0 to N-1 +d = d % N -print(finalList) +# Rotate the array to the left by d positions +rotated_array = array[d:] + array[:d] -# This Method holds the timeComplexity of O(N) and Space Complexity of O(N) +# Print the result +print("Rotated Array:", rotated_array) From f593e9f720299db82191a9faf8bda54befc1222d Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Thu, 20 Jun 2024 17:20:38 +0530 Subject: [PATCH 07/11] Update rotatelist.py --- rotatelist.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/rotatelist.py b/rotatelist.py index e029d210bb0..aa98ddbaedf 100644 --- a/rotatelist.py +++ b/rotatelist.py @@ -25,3 +25,18 @@ def get_integer_input(prompt): # Print the result print("Rotated Array:", rotated_array) + + +### +Usage Example: +text +Copy code +Enter the size of the array: 5 +Enter integer number 1: 10 +Enter integer number 2: 20 +Enter integer number 3: 30 +Enter integer number 4: 40 +Enter integer number 5: 50 +Enter the number of times you want to rotate the array: 2 +Rotated Array: [30, 40, 50, 10, 20] +### From 3af29cb6bd8adb6d41f603d77331664932abdfdb Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Thu, 20 Jun 2024 17:21:08 +0530 Subject: [PATCH 08/11] Update rotatelist.py --- rotatelist.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rotatelist.py b/rotatelist.py index aa98ddbaedf..101cb509659 100644 --- a/rotatelist.py +++ b/rotatelist.py @@ -27,7 +27,7 @@ def get_integer_input(prompt): print("Rotated Array:", rotated_array) -### +""" Usage Example: text Copy code @@ -39,4 +39,4 @@ def get_integer_input(prompt): Enter integer number 5: 50 Enter the number of times you want to rotate the array: 2 Rotated Array: [30, 40, 50, 10, 20] -### +""" From c75f726a81ec62cd0f1538e7359af4cd136b4286 Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Fri, 21 Jun 2024 11:59:02 +0530 Subject: [PATCH 09/11] Delete Sorting Algorithms/task_manager.py --- Sorting Algorithms/task_manager.py | 100 ----------------------------- 1 file changed, 100 deletions(-) delete mode 100644 Sorting Algorithms/task_manager.py diff --git a/Sorting Algorithms/task_manager.py b/Sorting Algorithms/task_manager.py deleted file mode 100644 index 4cb2ca922af..00000000000 --- a/Sorting Algorithms/task_manager.py +++ /dev/null @@ -1,100 +0,0 @@ -import argparse -import datetime -import json -import logging as log -import time - -# Initialize logging -log.basicConfig(filename='tasks.log', level=log.INFO, format='%(asctime)s - %(message)s') - -# Load tasks from JSON file -def load_tasks(): - try: - with open('tasks.json', 'r') as file: - tasks = json.load(file) - except FileNotFoundError: - tasks = [] - return tasks - -# Save tasks to JSON file -def save_tasks(tasks): - with open('tasks.json', 'w') as file: - json.dump(tasks, file, indent=4) - -# Add a new task -def add_task(title, description, due_date): - tasks = load_tasks() - tasks.append({ - 'title': title, - 'description': description, - 'due_date': due_date, - 'status': 'pending' - }) - save_tasks(tasks) - log.info(f"Task '{title}' added with due date {due_date}") - -# List all tasks -def list_tasks(): - tasks = load_tasks() - for index, task in enumerate(tasks, start=1): - print(f"Task {index}:") - print(f" Title: {task['title']}") - print(f" Description: {task['description']}") - print(f" Due Date: {task['due_date']}") - print(f" Status: {task['status']}") - print() - -# Complete a task -def complete_task(index): - tasks = load_tasks() - if 1 <= index <= len(tasks): - tasks[index - 1]['status'] = 'completed' - save_tasks(tasks) - log.info(f"Task '{tasks[index - 1]['title']}' marked as completed") - else: - print("Invalid task index") - -# Delete a task -def delete_task(index): - tasks = load_tasks() - if 1 <= index <= len(tasks): - deleted_task = tasks.pop(index - 1) - save_tasks(tasks) - log.info(f"Task '{deleted_task['title']}' deleted") - else: - print("Invalid task index") - -# CLI setup -parser = argparse.ArgumentParser(description='Task Manager') -parser.add_argument('command', choices=['add', 'list', 'complete', 'delete'], help='Command to execute') -parser.add_argument('--title', help='Task title') -parser.add_argument('--description', help='Task description') -parser.add_argument('--due-date', help='Task due date (YYYY-MM-DD)') -parser.add_argument('--index', type=int, help='Task index') - -args = parser.parse_args() - -# Execute commands -if args.command == 'add': - add_task(args.title, args.description, args.due_date) -elif args.command == 'list': - list_tasks() -elif args.command == 'complete': - complete_task(args.index) -elif args.command == 'delete': - delete_task(args.index) - -""" -Usage: -Adding a task: -python task_manager.py add --title "Complete project" --description "Finish project report" --due-date 2024-07-01 - -Listing tasks: -python task_manager.py list - -Completing a task: -python task_manager.py complete --index 1 - -Deleting a task: -python task_manager.py delete --index 1 -""" From 2ef2e1e68bd8ba9088c4f136032dac258fc43392 Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Fri, 21 Jun 2024 11:59:50 +0530 Subject: [PATCH 10/11] Create task_manager.py --- task_manager.py | 100 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 task_manager.py diff --git a/task_manager.py b/task_manager.py new file mode 100644 index 00000000000..4cb2ca922af --- /dev/null +++ b/task_manager.py @@ -0,0 +1,100 @@ +import argparse +import datetime +import json +import logging as log +import time + +# Initialize logging +log.basicConfig(filename='tasks.log', level=log.INFO, format='%(asctime)s - %(message)s') + +# Load tasks from JSON file +def load_tasks(): + try: + with open('tasks.json', 'r') as file: + tasks = json.load(file) + except FileNotFoundError: + tasks = [] + return tasks + +# Save tasks to JSON file +def save_tasks(tasks): + with open('tasks.json', 'w') as file: + json.dump(tasks, file, indent=4) + +# Add a new task +def add_task(title, description, due_date): + tasks = load_tasks() + tasks.append({ + 'title': title, + 'description': description, + 'due_date': due_date, + 'status': 'pending' + }) + save_tasks(tasks) + log.info(f"Task '{title}' added with due date {due_date}") + +# List all tasks +def list_tasks(): + tasks = load_tasks() + for index, task in enumerate(tasks, start=1): + print(f"Task {index}:") + print(f" Title: {task['title']}") + print(f" Description: {task['description']}") + print(f" Due Date: {task['due_date']}") + print(f" Status: {task['status']}") + print() + +# Complete a task +def complete_task(index): + tasks = load_tasks() + if 1 <= index <= len(tasks): + tasks[index - 1]['status'] = 'completed' + save_tasks(tasks) + log.info(f"Task '{tasks[index - 1]['title']}' marked as completed") + else: + print("Invalid task index") + +# Delete a task +def delete_task(index): + tasks = load_tasks() + if 1 <= index <= len(tasks): + deleted_task = tasks.pop(index - 1) + save_tasks(tasks) + log.info(f"Task '{deleted_task['title']}' deleted") + else: + print("Invalid task index") + +# CLI setup +parser = argparse.ArgumentParser(description='Task Manager') +parser.add_argument('command', choices=['add', 'list', 'complete', 'delete'], help='Command to execute') +parser.add_argument('--title', help='Task title') +parser.add_argument('--description', help='Task description') +parser.add_argument('--due-date', help='Task due date (YYYY-MM-DD)') +parser.add_argument('--index', type=int, help='Task index') + +args = parser.parse_args() + +# Execute commands +if args.command == 'add': + add_task(args.title, args.description, args.due_date) +elif args.command == 'list': + list_tasks() +elif args.command == 'complete': + complete_task(args.index) +elif args.command == 'delete': + delete_task(args.index) + +""" +Usage: +Adding a task: +python task_manager.py add --title "Complete project" --description "Finish project report" --due-date 2024-07-01 + +Listing tasks: +python task_manager.py list + +Completing a task: +python task_manager.py complete --index 1 + +Deleting a task: +python task_manager.py delete --index 1 +""" From d801337bc99c9ef33995faa75805f86d5e374075 Mon Sep 17 00:00:00 2001 From: Mani <69618775+devops-mani@users.noreply.github.com> Date: Wed, 26 Jun 2024 13:25:05 +0530 Subject: [PATCH 11/11] Create news_toi.py --- news_toi.py | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 news_toi.py diff --git a/news_toi.py b/news_toi.py new file mode 100644 index 00000000000..0f38399b855 --- /dev/null +++ b/news_toi.py @@ -0,0 +1,78 @@ +# Fetch news from Times Of India based on location +import requests +from bs4 import BeautifulSoup +import webbrowser +import time + + +def fetch_news_times_of_india(topic, headers): + """ + Fetch news from Times of India based on the given topic. + """ + base_url = "https://timesofindia.indiatimes.com/india/" + search_url = f"{base_url}{topic}" + + response = requests.get(search_url, headers=headers) + soup = BeautifulSoup(response.content, "html.parser") + news_items = soup.find_all(class_="w_tle") + + if not news_items: + return [] + + news_list = [] + for item in news_items: + title = item.find("a").get_text() + link = base_url + item.find("a")["href"] + news_list.append((title, link)) + + return news_list + + +def display_news(news_list): + """ + Display the list of news and prompt the user to open links. + """ + bold_start = "\033[1m" + bold_end = "\033[0m" + + if not news_list: + print("Sorry, no news available.") + return + + print("\nNews available: 😊") + for idx, (title, link) in enumerate(news_list, 1): + print(f"{bold_start}\033[1;32;40m \nNEWS {idx}:{bold_end} {bold_start}{title}{bold_end}") + open_link = input("For more details -> (y/n): ").strip().lower() + if open_link == 'y': + webbrowser.open(link) + elif open_link == 'n': + break + + +def main(): + """ + Main function to run the news fetching program. + """ + bold_start = "\033[1m" + bold_end = "\033[0m" + + print("\033[5;31;40m") + print(f"{bold_start} HERE YOU WILL GET ALL THE NEWS JUST IN ONE SEARCH {bold_end}\n") + print(f"{bold_start}{time.asctime(time.localtime(time.time()))}{bold_end}") + + user_agent = { + "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0" + } + + topic = input(f"{bold_start}\n\033[1;35;40m Search any news (state, city, country, etc.): {bold_end} ").strip() + + news = fetch_news_times_of_india(topic, user_agent) + display_news(news) + if not news: + print("Sorry, no news available.") + + print("\nThank you! 😊") + + +if __name__ == "__main__": + main()