diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..fa0d3b7c --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,15 @@ +# These are supported funding model platforms + +github: [DhanushNehru] +patreon: dhanushnehru +open_collective: # Replace with a single Open Collective username +ko_fi: dhanushnehru +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +polar: # Replace with a single Polar username +buy_me_a_coffee: dhanushnehru +thanks_dev: dhanushnehru +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/Arrange It/README.md b/Arrange It/README.md index 78013930..86e7f8eb 100644 --- a/Arrange It/README.md +++ b/Arrange It/README.md @@ -4,7 +4,7 @@ With the help of this script, files can be moved automatically to the folder tha ## New Feature: Custom Folder Configuration --Now, you can customize how files are arranged by defining your own folder structure and file extensions using a config.json file. This allows for more flexibility without needing to modify the Python code itself. +Now, you can customize how files are arranged by defining your own folder structure and file extensions using a config.json file. This allows for more flexibility without needing to modify the Python code itself. `python arrangeit.py` # How To Use the config.json File diff --git a/Auto WiFi Check/requirements.txt b/Auto WiFi Check/requirements.txt index 7a7d08a2..4d227ca1 100644 --- a/Auto WiFi Check/requirements.txt +++ b/Auto WiFi Check/requirements.txt @@ -1 +1 @@ -schedule==1.1.0 +schedule==1.2.2 diff --git a/Auto WiFi Check/wifi_checker.py b/Auto WiFi Check/wifi_checker.py index c2c3048c..e0c20b9b 100644 --- a/Auto WiFi Check/wifi_checker.py +++ b/Auto WiFi Check/wifi_checker.py @@ -2,44 +2,99 @@ import subprocess import sys import time -from datetime import datetime +import logging import schedule as sc +# Create the log file if it doesn't already exist +LOG_FILE = "wifi_status_log.txt" +PING_HOST = "www.google.com" + +try: + with open(LOG_FILE, 'x') as file: + file.write("Logs:\n") + print(f"File '{LOG_FILE}' created successfully.") +except FileExistsError: + print(f"File '{LOG_FILE}' already exists.") + +# Set up logging to log to a file with timestamps +logging.basicConfig(filename=LOG_FILE, + level=logging.INFO, + format='%(asctime)s - %(message)s', + filemode='a') # Append mode def enable(): - subprocess.call("netsh interface set interface Wi-Fi enabled") - print("Turning On the laptop WiFi") + try: + subprocess.call("netsh interface set interface Wi-Fi enabled", shell=True) + print("Turning On the laptop WiFi") + logging.info("WiFi enabled") + except Exception as e: + print(f"Failed to enable WiFi: {e}") + logging.error(f"Failed to enable WiFi: {e}") def disable(): - subprocess.call("netsh interface set interface Wi-Fi disabled") - print("Turning Off the laptop WiFi") - + try: + subprocess.call("netsh interface set interface Wi-Fi disabled", shell=True) + print("Turning Off the laptop WiFi") + logging.info("WiFi disabled") + except Exception as e: + print(f"Failed to disable WiFi: {e}") + logging.error(f"Failed to disable WiFi: {e}") - def job(): - if subprocess.call("netsh interface set interface Wi-Fi enabled") == 0: + try: + subprocess.call("netsh interface set interface Wi-Fi enabled", shell=True) print("WiFi is enabled and connected to internet") - hostname = "www.google.com" - response = subprocess.call("ping -n 1 " + hostname) + logging.info("WiFi is enabled and connected to the internet.") + + response = subprocess.call(f"ping -n 1 {PING_HOST}", shell=True) + if response == 1: print("Your Connection is not working") - disable() - time.sleep(1) - enable() + logging.warning("WiFi connection not working, ping failed.") + + attempt_counter = 0 + max_attempts = 3 + + while attempt_counter < max_attempts: + print(f"Attempt {attempt_counter + 1} to reconnect...") + logging.info(f"Attempt {attempt_counter + 1} to reconnect...") + + disable() + time.sleep(1) + enable() + + time.sleep(5) + + response = subprocess.call(f"ping -n 1 {PING_HOST}", shell=True) + if response == 0: + print("Reconnection successful!") + logging.info("Reconnection successful!") + break + else: + print(f"Reconnection attempt {attempt_counter + 1} failed.") + logging.warning(f"Reconnection attempt {attempt_counter + 1} failed.") + + attempt_counter += 1 + + if attempt_counter == max_attempts and response != 0: + print(f"Failed to reconnect after {max_attempts} attempts.") + logging.error(f"Failed to reconnect after {max_attempts} attempts.") + except Exception as e: + print(f"Error during WiFi check: {e}") + logging.error(f"Error during WiFi check: {e}") def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() - except: + except Exception as e: + logging.error(f"Admin check failed: {e}") return False if is_admin(): - # job() sc.every(50).seconds.do(job) else: ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1) - while True: sc.run_pending() - time.sleep(1) \ No newline at end of file + time.sleep(1) diff --git a/Auto WiFi Check/wifi_status_log.txt b/Auto WiFi Check/wifi_status_log.txt new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/Auto WiFi Check/wifi_status_log.txt @@ -0,0 +1 @@ + diff --git a/AutoCert/README.md b/AutoCert/README.md index c2600978..2a1e0709 100644 --- a/AutoCert/README.md +++ b/AutoCert/README.md @@ -12,10 +12,10 @@ A Python script to auto generate e-certificates in bulk. # Instruction to use
    -
  1. First install all the dependencies, present in the requirements.txt file
  2. -
  3. Put a certificate template with blank fields, in the project folder, with the name `certificateTemplate.png` .Make sure the template is in `png` format only
  4. +
  5. First install all the dependencies, present in the requirements.txt file.
  6. +
  7. Put a certificate template with blank fields, in the project folder, with the name `certificateTemplate.png`. Make sure the template is in `png` format only.
  8. Put the input `csv` file containing a list of the participant names by under a column name.
  9. -
  10. Once all this is done, run `python3 main.py` in your terminal
  11. +
  12. Once all this is done, run `python3 main.py` in your terminal.
  13. The generated certificates would be present under the *export* folder, with each certificate having the name of the participant.
diff --git a/Black Hat Python/README.md b/Black Hat Python/README.md index cfb0ebf5..b2ac355f 100644 --- a/Black Hat Python/README.md +++ b/Black Hat Python/README.md @@ -9,8 +9,7 @@ Simply choose a directory (DIR) in which to clone the project using git clone https://github.com/DhanushNehru/Python-Scripts/Black Hat Python.git ``` -create a new virtual environment or `venv` for it (recommended -) and install the requirements using `pip install`. +create a new virtual environment or `venv` for it (recommended) and install the requirements using `pip install`. diff --git a/Cafe Management System/README.md b/Cafe Management System/README.md index b5cf86ab..9589c958 100644 --- a/Cafe Management System/README.md +++ b/Cafe Management System/README.md @@ -1,6 +1,6 @@ # Cafe Management System - This is a cafe Management System Coded by Python using `tkinter` library. -- You need to install `Pillow`by entering `pip install Pillow`. +- You need to install `Pillow` by entering `pip install Pillow`. \ No newline at end of file diff --git a/Chess Board/ChessBoard.py b/Chess Board/ChessBoard.py index 122080a2..2c64f25c 100644 --- a/Chess Board/ChessBoard.py +++ b/Chess Board/ChessBoard.py @@ -1,20 +1,63 @@ import matplotlib.pyplot as plt import numpy as np -from matplotlib.colors import LogNorm +from matplotlib.patches import Rectangle -dx, dy = 0.015, 0.05 -# numpy.arange returns evenly spaced values within a given interval -x = np.arange(-4.0, 4.0, dx) # Corrected -04.0 to -4.0 -y = np.arange(-4.0, 4.0, dy) # Corrected -04.0 to -4.0 -# returns coordinate matrices from coordinate vectors -X, Y = np.meshgrid(x, y) +# Chess symbols for pieces (Unicode) +chess_pieces = { + "rook_white": "\u2656", + "rook_black": "\u265C", + "pawn_white": "\u2659", + "pawn_black": "\u265F", +} -extent = np.min(x), np.max(x), np.min(y), np.max(y) +# Initial piece positions for demonstration +initial_pieces = [ + (0, 0, chess_pieces["rook_black"]), + (0, 7, chess_pieces["rook_black"]), + (7, 0, chess_pieces["rook_white"]), + (7, 7, chess_pieces["rook_white"]), + (1, 0, chess_pieces["pawn_black"]), + (1, 7, chess_pieces["pawn_black"]), + (6, 0, chess_pieces["pawn_white"]), + (6, 7, chess_pieces["pawn_white"]), +] -Z1 = np.add.outer(range(8), range(8)) % 2 +# Function to draw the chessboard +def draw_chessboard(highlight_squares=None): + board_size = 8 + chessboard = np.add.outer(range(board_size), range(board_size)) % 2 -plt.imshow(Z1, cmap="binary_r", interpolation="nearest", extent=extent, alpha=1) + fig, ax = plt.subplots(figsize=(8, 8)) + ax.imshow(chessboard, cmap="cividis", interpolation="nearest") -plt.title("Chess Board", fontweight="bold") + # Remove axes for a cleaner look + ax.set_xticks([]) + ax.set_yticks([]) -plt.show() + # Add grid lines to separate the squares + for i in range(board_size + 1): + ax.axhline(i - 0.5, color="black", linewidth=1, alpha=0.7) + ax.axvline(i - 0.5, color="black", linewidth=1, alpha=0.7) + + # Highlight specific squares + if highlight_squares: + for (row, col) in highlight_squares: + ax.add_patch(Rectangle((col - 0.5, row - 0.5), 1, 1, color="yellow", alpha=0.4)) + + # Add chess pieces + for row, col, piece in initial_pieces: + ax.text(col, row, piece, fontsize=28, ha="center", va="center", color="black" if (row + col) % 2 == 0 else "white") + + # Add coordinate labels + for i in range(board_size): + ax.text(-0.8, i, str(8 - i), fontsize=12, va="center") # Row labels + ax.text(i, 8 - 0.3, chr(65 + i), fontsize=12, ha="center") # Column labels + + # Title + ax.set_title("Chess Board", fontweight="bold", fontsize=16) + + plt.show() + +# Highlight squares (optional demo) +highlight = [(0, 0), (7, 7), (3, 3)] # Example of squares to highlight +draw_chessboard(highlight_squares=highlight) diff --git a/Chess Board/README.md b/Chess Board/README.md index 5b085375..b00c6b01 100644 --- a/Chess Board/README.md +++ b/Chess Board/README.md @@ -1,4 +1,4 @@ -This repository consists of a list of python scripts to automate few tasks. +This repository consists of a list of python scripts to automate a few tasks. You can contribute by adding more python scripts which can be used to automate things. Some of already done are listed below. Incase you have anything to be followed while executing the python script mention it as well diff --git a/Connect Four/README.md b/Connect Four/README.md new file mode 100644 index 00000000..622a49d8 --- /dev/null +++ b/Connect Four/README.md @@ -0,0 +1,37 @@ +# Connect Four +I have created the board game, "Connect Four", using the programming language Python. The entire project was created all on one file. This was a project I chose to develop during my spare time as this was not a common project constructed by other developers. The program follows all rules of the game, where players can win by either having 4 in a row horizontally, vertically, or diagonally. The dimensions for this particular game is a 6x7 board. In other words, the board is designed as 6 rows and 7 columns. Therefore, I initialized a nested list called board that contains the 7 columns as elements, and the 6 rows within each element. + +``` +board = [["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6] +``` + + +Determining the logic for a player to have 4 in a row diagonally proved to be the most challenging in my opinion. The best solution was to view this as positive and negative slopes since these diagonals were +either from the bottom left to top right, or the top left to bottom right. Afterwards, I created two separate boards to determine all possible coordinates that can be starting points to create 4 in a row as shown +in the table below: + +Note: The coordinate is [col, row] + +### Positive Slope Possible Starting Points +| | | | | | | | +|------------|------------|------------|------------|------------|------------|------------| +| 1.1 | 2.1 | 3.1 | 4.1 | 5.1 | 6.1 | 7.1 | +| 1.2 | 2.2 | 3.2 | 4.2 | 5.2 | 6.2 | 7.2 | +| 1.3 | 2.3 | 3.3 | 4.3 | 5.3 | 6.3 | 7.3 | +| 1.4 | 2.4 | 3.4 | 4.4 | 5.4 | 6.4 | 7.4 | +| 1.5 | 2.5 | 3.5 | 4.5 | 5.5 | 6.5 | 7.5 | +| 1.6 | 2.6 | 3.6 | 4.6 | 5.6 | 6.6 | 7.6 | + + +### Negative Slope Possible Starting Points +| | | | | | | | +|------------|------------|------------|------------|------------|------------|------------| +| 1.1 | 2.1 | 3.1 | 4.1 | 5.1 | 6.1 | 7.1 | +| 1.2 | 2.2 | 3.2 | 4.2 | 5.2 | 6.2 | 7.2 | +| 1.3 | 2.3 | 3.3 | 4.3 | 5.3 | 6.3 | 7.3 | +| 1.4 | 2.4 | 3.4 | 4.4 | 5.4 | 6.4 | 7.4 | +| 1.5 | 2.5 | 3.5 | 4.5 | 5.5 | 6.5 | 7.5 | +| 1.6 | 2.6 | 3.6 | 4.6 | 5.6 | 6.6 | 7.6 | + +What I noticed is the positive slope starting points are from rows 4-6 and columns 1-4, while the negatiive slope starting points are from rows 1-3 and columns 1-4. Therefore, each type of slope has its own +function and nested for loop that iterates through only the possible starting points. \ No newline at end of file diff --git a/Connect Four/connectfour.py b/Connect Four/connectfour.py new file mode 100644 index 00000000..c5fd146e --- /dev/null +++ b/Connect Four/connectfour.py @@ -0,0 +1,242 @@ +import random + +board = [["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6, ["-"] * 6] + + +def gamePlayTwoPlayers(p1, p2): + win = "" + while win == "": + column = int(input("{}'s turn. Enter which column you would like to drop your piece into: ".format(p1))) + connectFourBoard(column, "X") + + if check_vertical_win(p1, p2, column): + print() + print(check_vertical_win(p1, p2, column)) + break + if check_horizontal_win(p1, p2): + print() + print(check_horizontal_win(p1, p2)) + break + if check_positive_diagonal_win(p1, p2): + print() + print(check_positive_diagonal_win(p1, p2)) + break + if check_negative_diagonal_win(p1, p2): + print() + print(check_negative_diagonal_win(p1, p2)) + break + + column = int(input("{}'s turn. Enter which column you would like to drop your piece into: ".format(p2))) + connectFourBoard(column, "O") + + if check_vertical_win(p1, p2, column): + print() + print(check_vertical_win(p1, p2, column)) + break + if check_horizontal_win(p1, p2): + print() + print(check_horizontal_win("x", "O")) + break + if check_positive_diagonal_win(p1, p2): + print() + print(check_positive_diagonal_win(p1, p2)) + break + if check_negative_diagonal_win(p1, p2): + print() + print(check_negative_diagonal_win(p1, p2)) + break + + +def gamePlayOnePlayer(p1, p2): + win = "" + while win == "": + column = int(input("{}'s turn. Enter which column you would like to drop your piece into: ".format(p1))) + connectFourBoard(column, "X") + + if check_vertical_win(p1, p2, column): + print() + print(check_vertical_win(p1, p2, column)) + break + if check_horizontal_win(p1, p2): + print() + print(check_horizontal_win(p1, p2)) + break + if check_positive_diagonal_win(p1, p2): + print() + print(check_positive_diagonal_win(p1, p2)) + break + if check_negative_diagonal_win(p1, p2): + print() + print(check_negative_diagonal_win(p1, p2)) + break + + print() + + column = random.randint(1, 7) + connectFourBoard(column, "O") + + if check_vertical_win(p1, p2, column): + print() + print(check_vertical_win(p1, p2, column)) + break + if check_horizontal_win(p1, p2): + print() + print(check_horizontal_win(p1, p2)) + break + if check_positive_diagonal_win(p1, p2): + print() + print(check_positive_diagonal_win(p1, p2)) + break + if check_negative_diagonal_win(p1, p2): + print() + print(check_negative_diagonal_win(p1, p2)) + break + + +def connectFourBoard(col, playerIcon): + col -= 1 + coordinate = [] + + for row in range(len(board[col])-1, -1, -1): + if board[col][row] == "-": + board[col][row] = playerIcon + coordinate.append([row, col]) + break + for row in range(len(board)): + for col in range(len(board[row])): + print("|", board[row][col], "|", board[row+1][col], "|", board[row+2][col], "|", board[row+3][col], "|", + board[row+4][col], "|", board[row+5][col], "|", board[row+6][col], "|") + break + + +def check_vertical_win(p1, p2, col): + playerCount1 = 0 + playerCount2 = 0 + col -= 1 + + for row in range(len(board[col])-1, -1, -1): + if board[col][row] == "X": + playerCount1 += 1 + playerCount2 = 0 + elif board[col][row] == "O": + playerCount2 += 1 + playerCount1 = 0 + + if playerCount1 == 4: + return "{} Wins".format(p1) + elif playerCount2 == 4: + return "{} Wins".format(p2) + + +def check_horizontal_win(p1, p2): + for row in range(len(board[0])-1, -1, -1): + playerCount1 = 0 + playerCount2 = 0 + for col in range(len(board)): + if board[col][row] == "X": + playerCount1 += 1 + playerCount2 = 0 + elif board[col][row] == "O": + playerCount2 += 1 + playerCount1 = 0 + elif board[col][row] == "-": + playerCount1 = 0 + playerCount2 = 0 + + if playerCount1 == 4: + return "{} Wins".format(p1) + elif playerCount2 == 4: + return "{} Wins".format(p2) + + +def check_positive_diagonal_win(p1, p2): + playerCount1 = 0 + playerCount2 = 0 + + for row in range(len(board[0])-1, -1, -1): + for col in range(len(board)-3): + if board[col][row] == "X": + playerCount1 += 1 + while playerCount1 < 4: + col += 1 + row -= 1 + if board[col][row] == "X": + playerCount1 += 1 + else: + playerCount1 = 0 + break + elif board[col][row] == "O": + playerCount1 += 1 + while playerCount1 < 4: + col += 1 + row -= 1 + if board[col][row] == "O": + playerCount1 += 1 + else: + playerCount1 = 0 + break + + if playerCount1 == 4: + return "{} Wins".format(p1) + elif playerCount2 == 4: + return "{} Wins".format(p2) + else: + playerCount1 = 0 + playerCount2 = 0 + + +def check_negative_diagonal_win(p1, p2): + playerCount1 = 0 + playerCount2 = 0 + + for row in range(len(board[0])-3): + for col in range(len(board)-3): + if board[col][row] == "X": + playerCount1 += 1 + while playerCount1 < 4: + col += 1 + row -= 1 + if board[col][row] == "X": + playerCount1 += 1 + else: + playerCount1 = 0 + break + elif board[col][row] == "O": + playerCount1 += 1 + while playerCount1 < 4: + col += 1 + row += 1 + if board[col][row] == "O": + playerCount1 += 1 + else: + playerCount1 = 0 + break + + if playerCount1 == 4: + return "{} Wins".format(p1) + elif playerCount2 == 4: + return "{} Wins".format(p2) + else: + playerCount1 = 0 + playerCount2 = 0 + + +def main(): + print("Welcome to Connect Four! Connect 4 of your pieces in either horizontal, vertical, or diagonal to win.") + + numPlayers = int(input("Choose how many players: ")) + + while numPlayers not in [1,2]: + numPlayers = int(input("Sorry for the value you entered was invalid. Are you playing with 1 or 2 players: ")) + + if numPlayers == 1: + player1 = input("Player 1, please enter your name: ") + player2 = "CPU" + gamePlayTwoPlayers(player1, player2) + elif numPlayers == 2: + player1 = input("Player 1, please enter your name: ") + player2 = input("Player 2, please enter your name: ") + gamePlayTwoPlayers(player1, player2) + + +main() \ No newline at end of file diff --git a/Distance Calculator/README.md b/Distance Calculator/README.md new file mode 100644 index 00000000..4d00f8b1 --- /dev/null +++ b/Distance Calculator/README.md @@ -0,0 +1,14 @@ +# Program +This is a *distance calculator*, used to calculate the distance between two points on a 2D plane. + +# How to use + +## Use any of the following commands - +`python distance_calculator.py` + +`python3 distance_calculator.py` + +## Example +![image](https://github.com/user-attachments/assets/987537c2-236e-4560-9a06-3de4bbe98f5e) + +Made by Mathdallas_code(me) diff --git a/Distance Calculator/distance_calculator.py b/Distance Calculator/distance_calculator.py new file mode 100644 index 00000000..b5b393c8 --- /dev/null +++ b/Distance Calculator/distance_calculator.py @@ -0,0 +1,71 @@ +# Uses the pythagorean theorem to calculate the distance between two points on a 2D plane. +# The points are represented as tuples of two numbers. +# The function should return a float. + +# Sample :- startX = 0, startY = 0, endX = 3, endY = 4. +# So, according to pythagorean theorem, the distance between these two points is 5.0. + +# Hope this helps! + +# Importing module(s) +import math + +# Main loop +while True: + use_program=input("Do you want to calculate the distance between two points? (yes/no): ") + if use_program.lower() == "yes": + pass + elif use_program.lower() == "no": + print("Thank you for using the distance calculator!") + quit() + else: + print("Invalid input! Please enter 'yes' or 'no'.") + continue + + # Input validation for startX, startY, endX, endY + + # startX + while True: + startX = input("Enter starting x-coordinate: ") + if not startX.isnumeric(): + print("Error! Input has to be a number!") + continue + else: + break + + # startY + while True: + startY = input("Enter starting y-coordinate: ") + if not startY.isnumeric(): + print("Error! Input has to be a number!") + continue + else: + break + + # endX + while True: + endX = input("Enter ending x-coordinate: ") + if not endX.isnumeric(): + print("Error! Input has to be a number!") + continue + else: + break + + # endY + while True: + endY = input("Enter ending y-coordinate: ") + if not endY.isnumeric(): + print("Error! Input has to be a number!") + continue + else: + break + + # Converting the values to floats + startX = float(startX) + startY = float(startY) + endX = float(endX) + endY = float(endY) + + # The calculation + distance = math.sqrt(math.pow(startX - endX, 2) + math.pow(startY - endY, 2)) + print(f"The distance between ({startX}, {startY}) and ({endX}, {endY}) is {distance} units.") diff --git a/Expense Tracker/Expense Tracker.db b/Expense Tracker/Expense Tracker.db new file mode 100644 index 00000000..fe88adda Binary files /dev/null and b/Expense Tracker/Expense Tracker.db differ diff --git a/Expense Tracker/README.md b/Expense Tracker/README.md index 29d399b5..920b6aa7 100644 --- a/Expense Tracker/README.md +++ b/Expense Tracker/README.md @@ -7,6 +7,7 @@ Install the required dependencies using pip: ``` pip install -r requirements.txt ``` +or you can manually install single Library. Run the expense.py file to start the bot: diff --git a/Expense Tracker/expense.py b/Expense Tracker/expense.py index 56be5299..c6d21136 100644 --- a/Expense Tracker/expense.py +++ b/Expense Tracker/expense.py @@ -1,50 +1,294 @@ +import datetime +import sqlite3 +from tkcalendar import DateEntry +from tkinter import * +import tkinter.messagebox as tb +import tkinter.ttk as ttk + +# Functions +def list_all_expenses(): + global connector, table + + table.delete(*table.get_children()) + + all_data = connector.execute('SELECT * FROM ExpenseTracker') + data = all_data.fetchall() + + for values in data: + table.insert('', END, values=values) + +def clear_fields(): + global Desc, payee, amnt, MoP, date, table + + today_date = datetime.datetime.now().date() + + Desc.set('') ; payee.set('') ; amnt.set(0.0) ; MoP.set('Cash'), date.set_date(today_date) + table.selection_remove(*table.selection()) + +def remove_expense(): + if not table.selection(): + tb.showerror('No record selected!', 'Please select a record to delete!') + return + + current_selected_expense = table.item(table.focus()) + values_selected = current_selected_expense['values'] + + surety = tb.askyesno('Are you sure?', f'Are you sure that you want to delete the record of {values_selected[2]}') + + if surety: + connector.execute('DELETE FROM ExpenseTracker WHERE ID=%d' % values_selected[0]) + connector.commit() + + list_all_expenses() + tb.showinfo('Record deleted successfully!', 'The record you wanted to delete has been deleted successfully') + +def remove_all_expenses(): + surety = tb.askyesno('Are you sure?', 'Are you sure that you want to delete all the expense items from the database?', icon='warning') + + if surety: + table.delete(*table.get_children()) + + connector.execute('DELETE FROM ExpenseTracker') + connector.commit() + + clear_fields() + list_all_expenses() + tb.showinfo('All Expenses deleted', 'All the expenses were successfully deleted') + else: + tb.showinfo('Ok then', 'The task was aborted and no expense was deleted!') + +def search_expenses(search_term): + """ + Search and display expenses based on a search term in any column. + """ + global table + table.delete(*table.get_children()) + + query = f""" + SELECT * FROM ExpenseTracker WHERE + Date LIKE ? OR + Payee LIKE ? OR + Description LIKE ? OR + Amount LIKE ? OR + ModeOfPayment LIKE ?; + """ + search_param = f"%{search_term}%" + results = connector.execute(query, (search_param,) * 5) + + for data in results.fetchall(): + table.insert('', END, values=data) + + +def filter_expenses_by_date(date_from, date_to): + """ + Filter and display expenses based on a date range. + """ + global table + table.delete(*table.get_children()) + + query = """ + SELECT * FROM ExpenseTracker WHERE Date BETWEEN ? AND ?; + """ + results = connector.execute(query, (date_from, date_to)) + + for data in results.fetchall(): + table.insert('', END, values=data) + + +def sort_expenses(column, order): + """ + Sort expenses by a column in ascending or descending order. + """ + global table + table.delete(*table.get_children()) + + query = f"SELECT * FROM ExpenseTracker ORDER BY {column} {order};" + results = connector.execute(query) + + for data in results.fetchall(): + table.insert('', END, values=data) + + + +def add_another_expense(): + global date, payee, Desc, amnt, MoP + global connector + + if not date.get() or not payee.get() or not Desc.get() or not amnt.get() or not MoP.get(): + tb.showerror('Fields empty!', "Please fill all the missing fields before pressing the add button!") + else: + connector.execute( + 'INSERT INTO ExpenseTracker (Date, Payee, Description, Amount, ModeOfPayment) VALUES (?, ?, ?, ?, ?)', + (date.get_date(), payee.get(), Desc.get(), amnt.get(), MoP.get()) + ) + connector.commit() + + clear_fields() + list_all_expenses() + tb.showinfo('Expense added', 'The expense whose details you just entered has been added to the database') + +def expense_to_words_before_adding(): + global date, Desc, amnt, payee, MoP + + if not date or not Desc or not amnt or not payee or not MoP: + tb.showerror('Incomplete data', 'The data is incomplete, meaning fill all the fields first!') + + message = f'Your expense can be read like: \n"You paid {amnt.get()} to {payee.get()} for {Desc.get()} on {date.get_date()} via {MoP.get()}"' + + add_question = tb.askyesno('Read your record like: ', f'{message}\n\nShould I add it to the database?') + + if add_question: + add_another_expense() + else: + tb.showinfo('Ok', 'Please take your time to add this record') + +# Connecting to the Database +connector = sqlite3.connect("Expense Tracker.db") +cursor = connector.cursor() + +connector.execute( + 'CREATE TABLE IF NOT EXISTS ExpenseTracker (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Date DATETIME, Payee TEXT, Description TEXT, Amount FLOAT, ModeOfPayment TEXT)' +) +connector.commit() + +# Backgrounds and Fonts +dataentery_frame_bg = 'light blue' +buttons_frame_bg = 'tomato' +hlb_btn_bg = 'Indianred' + +lbl_font = ('Georgia', 13) +entry_font = 'Times 13 bold' +btn_font = ('Gill Sans MT', 13) + +# Initializing the GUI window +root = Tk() +root.title('DebEx') +root.geometry('1200x550') +root.resizable(0, 0) + +Label(root, text='DebEx', font=('white', 21, 'bold'), bg=hlb_btn_bg).pack(side=TOP, fill=X) + +# StringVar and DoubleVar variables +Desc = StringVar() +amnt = DoubleVar() +payee = StringVar() +MoP = StringVar(value='Cash') + +# Frames +data_entry_frame = Frame(root, bg=dataentery_frame_bg) +data_entry_frame.place(x=0, y=35, relheight=0.95, relwidth=0.25) + +buttons_frame = Frame(root, bg=buttons_frame_bg) +buttons_frame.place(relx=0.25, rely=0.063, relwidth=0.75, relheight=0.12) + +tree_frame = Frame(root) +tree_frame.place(relx=0.25, rely=0.18, relwidth=0.75, relheight=0.8) + +# Data Entry Frame +Label(data_entry_frame, text='Date (M/DD/YY) :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=50) +date = DateEntry(data_entry_frame, date=datetime.datetime.now().date(), font=entry_font) +date.place(x=160, y=50) + +Label(data_entry_frame, text='Payee\t :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=230) +Entry(data_entry_frame, font=entry_font, width=31, text=payee).place(x=10, y=260) + +Label(data_entry_frame, text='Description :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=100) +Entry(data_entry_frame, font=entry_font, width=31, text=Desc).place(x=10, y=130) + +Label(data_entry_frame, text='Amount\t :', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=180) +Entry(data_entry_frame, font=entry_font, width=14, text=amnt).place(x=160, y=180) + +Label(data_entry_frame, text='Mode of Payment:', font=lbl_font, bg=dataentery_frame_bg).place(x=10, y=310) +dd1 = OptionMenu(data_entry_frame, MoP, *['Cash', 'Cheque', 'Credit Card', 'Debit Card', 'Paytm', 'Google Pay', 'Razorpay']) +dd1.place(x=160, y=305) ; dd1.configure(width=10, font=entry_font) + +Button(data_entry_frame, text='Add expense', command=add_another_expense, font=btn_font, width=30, + bg=hlb_btn_bg).place(x=10, y=395) + +# Buttons' Frame +Button(buttons_frame, text='Delete Expense', font=btn_font, width=25, bg=hlb_btn_bg, command=remove_expense).place(x=30, y=5) + +Button(buttons_frame, text='Clear Fields in DataEntry Frame', font=btn_font, width=25, bg=hlb_btn_bg, + command=clear_fields).place(x=335, y=5) + +Button(buttons_frame, text='Delete All Expenses', font=btn_font, width=25, bg=hlb_btn_bg, command=remove_all_expenses).place(x=640, y=5) + import csv -import os +from tkinter.filedialog import asksaveasfilename + -CSV_FILE = "expenses.csv" +def export_to_csv(): + """ + Export the table data to a CSV file. + """ + data = connector.execute('SELECT * FROM ExpenseTracker').fetchall() + if not data: + tb.showerror("Export Failed", "No expenses to export!") + return -def initialize_csv(): - if not os.path.exists(CSV_FILE): - with open(CSV_FILE, "w", newline="") as file: + save_file_path = asksaveasfilename( + defaultextension=".csv", + filetypes=[("CSV files", "*.csv"), ("All files", "*.*")], + title="Save As" + ) + + if save_file_path: + with open(save_file_path, mode='w', newline='') as file: writer = csv.writer(file) - writer.writerow(["Date", "Description", "Amount"]) + # Write the header + writer.writerow(['ID', 'Date', 'Payee', 'Description', 'Amount', 'Mode of Payment']) + # Write the data + writer.writerows(data) + + tb.showinfo("Export Successful", f"Expenses exported to {save_file_path}") + + +filter_frame = Frame(root, bg="light gray") +filter_frame.place(x=10, y=500, width=1165, height=35) + +Label(filter_frame, text="Date From:", font=("Georgia", 10), bg="light gray").place(x=10, y=5) +date_from = DateEntry(filter_frame, date=datetime.datetime.now().date(), width=10) +date_from.place(x=90, y=5) + +Label(filter_frame, text="Date To:", font=("Georgia", 10), bg="light gray").place(x=200, y=5) +date_to = DateEntry(filter_frame, date=datetime.datetime.now().date(), width=10) +date_to.place(x=270, y=5) -def add_expense(date, description, amount): - with open(CSV_FILE, "a", newline="") as file: - writer = csv.writer(file) - writer.writerow([date, description, amount]) +Button(filter_frame, text="Filter", font=('Gill Sans MT', 10), width=10, bg=hlb_btn_bg, + command=lambda: filter_expenses_by_date(date_from.get_date(), date_to.get_date())).place(x=400, y=3) -def view_expenses(): - with open(CSV_FILE, "r") as file: - reader = csv.reader(file) - for row in reader: - print(", ".join(row)) +Button(filter_frame, text="Export to CSV", font=('Gill Sans MT', 10), width=15, bg=hlb_btn_bg, + command=export_to_csv).place(x=500, y=3) -if __name__ == "__main__": - initialize_csv() - while True: - print("\nExpense Tracker Menu:") - print("1. Add Expense") - print("2. View Expenses") - print("3. Exit") +# Treeview Frame +table = ttk.Treeview(tree_frame, selectmode=BROWSE, columns=('ID', 'Date', 'Payee', 'Description', 'Amount', 'Mode of Payment')) - choice = input("Enter your choice: ") +X_Scroller = Scrollbar(table, orient=HORIZONTAL, command=table.xview) +Y_Scroller = Scrollbar(table, orient=VERTICAL, command=table.yview) +X_Scroller.pack(side=BOTTOM, fill=X) +Y_Scroller.pack(side=RIGHT, fill=Y) - if choice == "1": - date = input("Enter the date (YYYY-MM-DD): ") - description = input("Enter the description: ") - amount = input("Enter the amount: ") +table.config(yscrollcommand=Y_Scroller.set, xscrollcommand=X_Scroller.set) - add_expense(date, description, amount) - print("Expense added successfully!") +table.heading('ID', text='S No.', anchor=CENTER) +table.heading('Date', text='Date', anchor=CENTER) +table.heading('Payee', text='Payee', anchor=CENTER) +table.heading('Description', text='Description', anchor=CENTER) +table.heading('Amount', text='Amount', anchor=CENTER) +table.heading('Mode of Payment', text='Mode of Payment', anchor=CENTER) - elif choice == "2": - print("Expenses:") - view_expenses() +table.column('#0', width=0, stretch=NO) +table.column('#1', width=50, stretch=NO) +table.column('#2', width=95, stretch=NO) # Date column +table.column('#3', width=150, stretch=NO) # Payee column +table.column('#4', width=325, stretch=NO) # Title column +table.column('#5', width=135, stretch=NO) # Amount column +table.column('#6', width=125, stretch=NO) # Mode of Payment column - elif choice == "3": - break +table.place(relx=0, y=0, relheight=1, relwidth=1) - else: - print("Invalid choice. Please try again.") +list_all_expenses() +# Finalizing the GUI window +root.update() +root.mainloop() diff --git a/Expense Tracker/requirements.txt b/Expense Tracker/requirements.txt index 8d34d431..324f637a 100644 --- a/Expense Tracker/requirements.txt +++ b/Expense Tracker/requirements.txt @@ -1,2 +1,4 @@ -csv -os +datetime +sqlite3 +tkcalendar +tkinter \ No newline at end of file diff --git a/Fake Profile/FakeProfile.py b/Fake Profile/FakeProfile.py index c3b81ded..aa15d01c 100644 --- a/Fake Profile/FakeProfile.py +++ b/Fake Profile/FakeProfile.py @@ -1,22 +1,101 @@ from faker import Faker +from typing import List +import json + +# Initialize Faker with multiple locales fake = Faker(['it_IT', 'en_US', 'ja_JP']) -print("### ALL faker Attribute") -print(dir(fake)) - -profile = """ -### Faker Profile ### -Name : {} -Email : {} -Social Security number (SSN) : {} -Address : {} -Location : {}, {} -URL : {} -""".format(fake.name(), - fake.email(), - fake.ssn(), - fake.address(), - fake.latitude(), fake.longitude(), - fake.url() - ) - -print(profile) + + +def generate_fake_profiles(num_profiles: int) -> List[dict]: + """ + Generate a list of fake profiles. + + Args: + num_profiles (int): Number of profiles to generate. + + Returns: + List[dict]: A list of dictionaries where each represents a profile. + """ + profiles = [] + for _ in range(num_profiles): + profile = { + "Locale": fake.locales, + "Name": fake.name(), + "Email": fake.email(), + "SSN": fake.ssn(), + "Address": fake.address(), + "Latitude": fake.latitude(), + "Longitude": fake.longitude(), + "URL": fake.url() + } + profiles.append(profile) + return profiles + + +def display_profiles(profiles: List[dict]): + """ + Display the generated profiles in a formatted way. + + Args: + profiles (List[dict]): A list of profiles to print. + """ + for index, profile in enumerate(profiles, start=1): + print(f"\n### Faker Profile {index} ###") + print(f"Locale : {', '.join(profile['Locale'])}") + print(f"Name : {profile['Name']}") + print(f"Email : {profile['Email']}") + print(f"Social Security number (SSN) : {profile['SSN']}") + print(f"Address : {profile['Address']}") + print(f"Location : ({profile['Latitude']}, {profile['Longitude']})") + print(f"URL : {profile['URL']}") + print("-" * 40) + + +def save_profiles_to_file(profiles: List[dict], filename: str) -> None: + """ + Save the list of profiles to a file in JSON format. + + Args: + profiles (List[dict]): The list of profiles to save. + filename (str): The name of the output file. + """ + try: + with open(filename, "w") as file: + json.dump(profiles, file, indent=4) + print(f"\nProfiles successfully saved to {filename}") + except Exception as e: + print(f"Error while saving profiles to file: {e}") + + +def main(): + """ + Main function to handle user interaction and workflow. + """ + print("\n### Faker Profile Generator ###") + try: + num_profiles = int(input("Enter the number of profiles to generate: ")) + if num_profiles < 1: + raise ValueError("Number of profiles must be greater than 0.") + + # Generate fake profiles + profiles = generate_fake_profiles(num_profiles) + + # Display profiles + display_profiles(profiles) + + # Save to file + save_option = input("Do you want to save the profiles to a file? (y/n): ").strip().lower() + if save_option == "y": + filename = input("Enter filename (e.g., profiles.json): ").strip() + save_profiles_to_file(profiles, filename) + + print("\nProcess completed successfully!") + except ValueError as ve: + print(f"Invalid input: {ve}") + except Exception as e: + print(f"An unexpected error occurred: {e}") + + +# Run the script +if __name__ == "__main__": + main() diff --git a/FileOrganizer/FileOrganizer.py b/FileOrganizer/FileOrganizer.py index 834db468..0ca91093 100644 --- a/FileOrganizer/FileOrganizer.py +++ b/FileOrganizer/FileOrganizer.py @@ -4,23 +4,40 @@ # Prompt the user for the directory path to organize files path = input("Enter path: ") -# List all files in the specified directory -files = os.listdir(path) +# Check if the directory exists +if not os.path.exists(path): + print("Error: The specified directory does not exist.") +else: + # List all items in the specified directory + files = os.listdir(path) # Iterate through each file in the directory -for file in files: - # Split the filename and extension - filename, extension = os.path.splitext(file) - - # Remove the leading dot from the extension for folder naming - extension = extension[1:] - - # Check if a directory for the file extension already exists - if os.path.exists(path + '/' + extension): - # Move the file to the corresponding extension folder - shutil.move(path + '/' + file, path + '/' + extension + '/' + file) - else: - # If the directory does not exist, create it - os.makedirs(path + '/' + extension) - # Move the file to the newly created extension folder - shutil.move(path + '/' + file, path + '/' + extension + '/' + file) + for file in files: + file_path = os.path.join(path, file) + + # Skip directories + if os.path.isdir(file_path): + continue + + # Split the filename and extension + filename, extension = os.path.splitext(file) + extension = extension[1:] if extension else "NoExtension" # Handle files without extensions + + # Destination folder for the extension + dest_folder = os.path.join(path, extension) + + # Create the directory if it does not exist + if not os.path.exists(dest_folder): + os.makedirs(dest_folder) + + # Handle duplicate files by renaming them + dest_file_path = os.path.join(dest_folder, file) + counter = 1 + while os.path.exists(dest_file_path): + newfilename = f"{filename}{counter}.{extension}" if extension != "NoExtension" else f"{filename}_{counter}" + dest_file_path = os.path.join(dest_folder, new_filename) + counter += 1 + + # Move the file + shutil.move(file_path, dest_file_path) + print(f"Moved: {file} → {dest_file_path}") \ No newline at end of file diff --git a/Images to WebP Converter/README.md b/Images to WebP Converter/README.md new file mode 100644 index 00000000..e7e9b947 --- /dev/null +++ b/Images to WebP Converter/README.md @@ -0,0 +1,58 @@ +# Image to WebP Converter + +This repository contains two Python scripts for converting images to WebP format. One script is for command-line usage, and the other provides a graphical user interface (GUI) for easier interaction. + +## Files + +1. `image_to_webp.py`: A command-line tool for converting images to WebP format. +2. `image_to_webp_gui.py`: A GUI tool for converting images to WebP format. + +## Requirements + +- Python 3.x +- Pillow library +- Tkinter library (for the GUI tool) + +You can install the required libraries using pip: + +```sh +pip install Pillow +``` + +Tkinter is included with standard Python installations. If you encounter issues, you may need to install it separately. + +## Usage + +### Command-Line Tool + +The `image_to_webp.py` script allows you to convert images to WebP format using the command line. + +#### Arguments + +- `files`: Paths to the image files to convert. +- `save_directory`: Directory to save the converted WebP images. +- `quality`: Quality of the output WebP images (1-100). + +#### Example + +```sh +python image_to_webp.py image1.jpg image2.png /path/to/save/directory 80 +``` + +### GUI Tool + +The `image_to_webp_gui.py` script provides a graphical user interface for converting images to WebP format. + +#### Steps + +1. Run the script: + + ```sh + python image_to_webp_gui.py + ``` + +2. A file dialog will appear to select multiple image files. +3. Another dialog will appear to select the directory to save the converted WebP images. +4. A dialog will prompt you to enter the quality of the output WebP images (1-100). +5. The images will be converted and saved to the specified directory. + diff --git a/Images to WebP Converter/image_to_webp.py b/Images to WebP Converter/image_to_webp.py new file mode 100644 index 00000000..1ce4b2d2 --- /dev/null +++ b/Images to WebP Converter/image_to_webp.py @@ -0,0 +1,29 @@ +import argparse +from PIL import Image +import os + +# Set up argument parser +parser = argparse.ArgumentParser(description="Convert images to WebP format.") +parser.add_argument("files", nargs='+', help="Paths to the image files to convert.") +parser.add_argument("save_directory", help="Directory to save the converted WebP images.") +parser.add_argument("quality", type=int, help="Quality of the output WebP images (1-100).") + +args = parser.parse_args() + +webp_paths = [] + +for path in args.files: + if path: + # Open the image file + im = Image.open(path) + base_name = os.path.basename(path) + name, ext = os.path.splitext(base_name) + # Define the save path for the WebP image + save_path = os.path.join(args.save_directory, f"{name}.webp") + # Save the image as WebP with the specified quality + im.save(save_path, 'webp', quality=args.quality) + webp_paths.append(save_path) + print(f"Image converted and saved to: {save_path}") + +# python image_to_webp.py +# python image_to_webp.py image1.jpg image2.png /path/to/save/directory 80 \ No newline at end of file diff --git a/Images to WebP Converter/image_to_webp_gui.py b/Images to WebP Converter/image_to_webp_gui.py new file mode 100644 index 00000000..589e76e1 --- /dev/null +++ b/Images to WebP Converter/image_to_webp_gui.py @@ -0,0 +1,35 @@ +from tkinter import Label, Tk, simpledialog +from PIL import Image, ImageTk +import tkinter.filedialog as tkFileDialog +import os + +# Initialize the Tkinter root window +root = Tk() +root.withdraw() # Hide the root window + +# Open file dialog to select multiple image files +paths = tkFileDialog.askopenfilenames(filetypes=[("Image Files", ('.jpg', '.jpeg', '.png', '.bmp', '.gif'))]) +webp_paths = [] + +if paths: + # Open directory dialog to select the save directory + save_directory = tkFileDialog.askdirectory() + if save_directory: + # Ask user for the quality of the output WebP images + quality = simpledialog.askinteger("Quality", "Enter quality (1-100):", minvalue=1, maxvalue=100) + if quality: + for path in paths: + if path: + # Open the image file + im = Image.open(path) + base_name = os.path.basename(path) + name, ext = os.path.splitext(base_name) + # Define the save path for the WebP image + save_path = os.path.join(save_directory, f"{name}.webp") + # Save the image as WebP with the specified quality + im.save(save_path, 'webp', quality=quality) + webp_paths.append(save_path) + print(f"Image converted and saved to: {save_path}") + +# Close the Tkinter window +root.destroy() # Close the Tkinter window \ No newline at end of file diff --git a/Mood based youtube song generator/README.md b/Mood based youtube song generator/README.md new file mode 100644 index 00000000..efadd890 --- /dev/null +++ b/Mood based youtube song generator/README.md @@ -0,0 +1,35 @@ +# Mood Based Youtube Song Generator +This Python script fetches a random song from YouTube based on your mood input and opens it in your default web browser. + +## Features +Accepts mood input (e.g., happy, sad, energetic) and finds related songs on YouTube. +Opens the YouTube song URL in your browser. + +## Setup + +### 1. Install dependencies: +```shell +pip install -r requirements.txt +``` + +### 2. Get your YouTube API key: +- Follow the instructions to get your YouTube Data API key. + +### 3. Set your API key: +Replace the api_key variable in the script with your own [YouTube Data API key](https://developers.google.com/youtube/v3/getting-started) +```python +api_key = "YOUR_YOUTUBE_API_KEY" +``` + +### 4. Run the script: +```shell +python random_song_generator.py +``` + +## Example +Input: +```bash +Enter your mood (e.g., happy, sad, energetic): happy +``` +The script will fetch a song and open it in your browser. + diff --git a/Mood based youtube song generator/random_song_generator.py b/Mood based youtube song generator/random_song_generator.py new file mode 100644 index 00000000..241b432c --- /dev/null +++ b/Mood based youtube song generator/random_song_generator.py @@ -0,0 +1,33 @@ +import random +import webbrowser +from googleapiclient.discovery import build + + +def fetch_youtube_songs(mood): + api_key = "your_youtube_api_key" + youtube = build("youtube", "v3", developerKey=api_key) + request = youtube.search().list( + q=f"{mood} song", part="snippet", type="video", maxResults=10 + ) + response = request.execute() + songs = [ + f"{item['snippet']['title']} - https://www.youtube.com/watch?v={item['id']['videoId']}" + for item in response['items'] + ] + return songs + + +def random_song_generator(): + mood = input("Enter your mood (e.g., happy, sad, energetic): ").lower() + try: + songs = fetch_youtube_songs(mood) + random_song = random.choice(songs) + song_title, song_url = random_song.split(" - ") + webbrowser.open(song_url) + print(f"Here's a song for your mood ({mood}):\n{random_song}") + except Exception as e: + print("Error fetching songs. Please check your API key and mood.") + + +if __name__ == "__main__": + random_song_generator() diff --git a/Mood based youtube song generator/requirements.txt b/Mood based youtube song generator/requirements.txt new file mode 100644 index 00000000..704bcd50 --- /dev/null +++ b/Mood based youtube song generator/requirements.txt @@ -0,0 +1 @@ +google-api-python-client \ No newline at end of file diff --git a/Password Generator/PasswordGenerator.py b/Password Generator/PasswordGenerator.py index c07c70fa..ec34ebec 100644 --- a/Password Generator/PasswordGenerator.py +++ b/Password Generator/PasswordGenerator.py @@ -1,96 +1,87 @@ import random as rr import string as ss - - -""" -ASCII -A -> Z : 65 -> 90 -a -> z : 97 -> 122 -""" - characters = ['@', '#', '$', '%', '&', '?'] -pass_len = int(input('How lengthy do you want your password to be : ')) +def generate_password(pass_len): + # Initialize counters + total_nums = 0 + total_symbols = 0 + total_cap = 0 + total_low = 0 -tempy, tempz = 0, 0 -tempx = rr.randint(2, pass_len-1) # alphabets + # Ensure at least one of each type + tempx = rr.randint(2, max(2, pass_len - 2)) # at least 2 letters + remaining = pass_len - tempx -if tempx != pass_len: - tempy = rr.randint(1, (pass_len - tempx - 1)) # numbers + tempy = rr.randint(1, max(1, remaining - 1)) # at least 1 number + remaining -= tempy total_nums = tempy -if (tempx + tempy) != pass_len: - tempz = rr.randint(1, (pass_len-(tempx+tempy))) # special characters + tempz = remaining # rest goes to special characters total_symbols = tempz -# password : empty string for now -pass_word = '' - -# adding alphabets - -while tempx: - x = tempx - num_cap = rr.randint(0, x) - num_low = x-num_cap + # Generate password + pass_word = '' + # Add alphabets + num_cap = rr.randint(1, tempx - 1) # at least 1 uppercase + num_low = tempx - num_cap # rest lowercase total_cap = num_cap total_low = num_low - # capitals in password : - while num_cap: - temp = chr(rr.randint(65, 90)) - pass_word = pass_word + str(temp) - num_cap -= 1 - - # lower-case in password : - while num_low: - temp = chr(rr.randint(97, 122)) - pass_word = pass_word + str(temp) - num_low -= 1 - - break - -# adding numbers to the password -while tempy: - temp = (rr.randint(0, 9)) - pass_word = pass_word + str(temp) - tempy -= 1 - -# adding special characters to the password -while tempz: - temp = rr.randint(0, len(characters)-1) - pass_word = pass_word + characters[temp] - tempz -= 1 - -#shuffles the string + # Add capitals + pass_word += ''.join(chr(rr.randint(65, 90)) for _ in range(num_cap)) + + # Add lowercase + pass_word += ''.join(chr(rr.randint(97, 122)) for _ in range(num_low)) + + # Add numbers + pass_word += ''.join(str(rr.randint(0, 9)) for _ in range(tempy)) + + # Add special characters + pass_word += ''.join(rr.choice(characters) for _ in range(tempz)) + + return pass_word, total_cap, total_low, total_nums, total_symbols + + def shuffle_(alpha): str_temp = list(alpha) rr.shuffle(str_temp) - alpha = ''.join(str_temp) - return alpha + return ''.join(str_temp) + -#adds colour to the text def colored(r, g, b, text): return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text) -final_pass =colored(200,200,50, (shuffle_(shuffle_(shuffle_(pass_word))))) +def main(): + pass_len = int(input('How lengthy do you want your password to be : ')) -# result & summary -result = """ -Generate Password Summary : + if pass_len < 4: + print("Password length must be at least 4 characters") + return -Charactor Uppercase : {0} -Charactor Lowercase : {1} + pass_word, total_cap, total_low, total_nums, total_symbols = generate_password(pass_len) + + # Shuffle multiple times + final_pass = colored(200, 200, 50, shuffle_(shuffle_(shuffle_(pass_word)))) + + result = """ +Generate Password Summary: + +Character Uppercase : {0} +Character Lowercase : {1} Numbers : {2} Symbols : {3} -Your computer generated password is : +Your computer generated password is: {4} """.format(total_cap, total_low, total_nums, total_symbols, final_pass) -print(result) + print(result) + -# print(f"\nYour computer generated password is : {final_pass}\n\n") +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Password Strength Checker/README.md b/Password Strength Checker/README.md index ea4db086..70cabe2e 100644 --- a/Password Strength Checker/README.md +++ b/Password Strength Checker/README.md @@ -11,16 +11,13 @@ A password strength checker that utilizes machine learning to classify the stren ```bash git clone https://github.com/DhanushNehru/Python-Scripts cd "Password Strength Checker" - 2. Create and activate a virtual environment: ```bash python3 -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate` - 3. Install the required packages: ```bash pip install -r requirements.txt - ## Usage To run the password strength checker: ```bash diff --git a/Pizza Order/PizzaTest.py b/Pizza Order/PizzaTest.py new file mode 100644 index 00000000..bc77171d --- /dev/null +++ b/Pizza Order/PizzaTest.py @@ -0,0 +1,112 @@ +import subprocess + + +def runTest (file, inText): + if file =="order": + res = subprocess.run("python " + file + ".py", input=inText, capture_output=True, text=True, shell=True) + return res.stdout + + if file == "pizzaReceipt": + res = subprocess.run("python -c \"from pizzaReceipt import *; generateReceipt([" +inText+ "])\"", capture_output=True, text=True, shell= True) + return res.stdout + + +def equalWithoutSpaces(expected, student): + expected = expected.replace(" ", "") + expected = expected.replace("\t", "") + student = student.replace(" ", "") + student = student.replace("\t", "") + return expected == student + + + +# --------------- Test 1 - No Order--------------- + +inputString = "" +studentOutput = runTest("pizzaReceipt", inputString) +expectedOutput = "You did not order anything\n" + +# Compare studentOutput to expectedOutput +if studentOutput == expectedOutput: + print("Test 1 Passed. (Receipt for empty order)") +else: + print("Test 1 Failed. (Receipt for empty order)") + +#print(studentOutput) + +# --------------- Test 2 - List of Orders--------------- + +inputString = "('L', ['HAM', 'BACON', 'ONION', 'TOMATO']), ('S', ['PEPPERONI', 'SAUSAGE', 'CHICKEN', 'HAM']), ('L', ['BROCCOLI', 'CHICKEN', 'ONION'])" +studentOutput = runTest("pizzaReceipt", inputString) +expectedOutput = "Your order: \nPizza 1: L 11.99\n- HAM\n- BACON\n- ONION\n- TOMATO\nExtra Topping (L) 1.00\n" +expectedOutput += "Pizza 2: S 7.99\n- PEPPERONI\n- SAUSAGE\n- CHICKEN\n- HAM\nExtra Topping (S) 0.50\n" +expectedOutput += "Pizza 3: L 11.99\n- BROCCOLI\n- CHICKEN\n- ONION\nTax: 4.35\nTotal: 37.82\n" + +# Compare studentOutput to expectedOutput +#if studentOutput == expectedOutput: +if equalWithoutSpaces(expectedOutput, studentOutput): + print("Test 2 Passed. (Receipt for empty order of 3 pizzas)") +else: + print("Test 2 Failed. (Receipt for empty order of 3 pizzas)") + + +# --------------- Test 3 - List of Orders--------------- + +inputString = "('XL', ['GREEN PEPPER', 'HOT PEPPER', 'MUSHROOM', 'ONION', 'SPINACH']), ('L', ['PEPPERONI', 'ONION', 'OLIVE', 'MUSHROOM']), ('L', ['PINEAPPLE', 'HAM']), ('M', ['GROUND BEEF', 'TOMATO', 'ONION', 'SPINACH'])" +studentOutput = runTest("pizzaReceipt", inputString) +expectedOutput = "Your order: \nPizza 1: XL 13.99\n- GREEN PEPPER\n- HOT PEPPER\n- MUSHROOM\n- ONION\n- SPINACH\nExtra Topping (XL) 1.25\n" +expectedOutput += "Extra Topping (XL) 1.25\nPizza 2: L 11.99\n- PEPPERONI\n- ONION\n- OLIVE\n- MUSHROOM\n" +expectedOutput += "Extra Topping (L) 1.00\nPizza 3: L 11.99\n- PINEAPPLE\n- HAM\nPizza 4: M 9.99\n" +expectedOutput += "- GROUND BEEF\n- TOMATO\n- ONION\n- SPINACH\nExtra Topping (M) 0.75\nTax: 6.79\nTotal: 59.00\n" + +# Compare studentOutput to expectedOutput +if equalWithoutSpaces(expectedOutput, studentOutput): + print("Test 3 Passed. (Receipt for empty order of 4 pizzas)") +else: + print("Test 3 Failed. (Receipt for empty order of 4 pizzas)") + +# --------------- Test 4 - Find Specific Values in Output --------------- + +studentOutput = runTest("order", "Yes\nL\nHAM\nX\nNo\n") + +if studentOutput.find("13.55") != -1: + print("Test 4 Passed. (Ordering system for order of 1 pizza)") +else: + print("Test 4 Failed. (Ordering system for order of 1 pizza)") + +#print(studentOutput) + +# --------------- Test 5 - Find Specific Values in Output--------------- + +studentOutput = runTest("order", "Yes\nmedium\nM\nLIST\npepperoni\nonion\nmushroom\nhot pepper\ntomato\nX\nq\n") + +if studentOutput.find("\"X\"\n('") != -1 and studentOutput.count("Choose a size:") == 2 and studentOutput.count("Type in one of our toppings") == 7 and studentOutput.find("1.49") != -1 and studentOutput.find("12.98") != -1: + print("Test 5 Passed. (Ordering system with typo and use of LIST)") +else: + + print("Test 5 Failed. (Ordering system with typo and use of LIST)") + +print() +print(studentOutput.find("\"X\"\n('") != -1) +print(studentOutput.count("Choose a size:") == 2) +print(studentOutput.count("Type in one of our toppings") == 7) +print(studentOutput.find("1.49") != -1) +print(studentOutput.find("12.98") != -1) +print() + +# --------------- Find Specific Values in Output --------------- + +studentOutput = runTest("order", "y\nm\nsausage\nbacon\nonion\nX\ny\nXl\nchicken\ntomato\nspinach\nmushroom\nx\ny\nm\nolive\nbroccoli\nhot pepper\ngreen pepper\nx\nno\n") + +if studentOutput.count("Type in one of our toppings") == 14 and studentOutput.find("4.68") != -1 and studentOutput.find("40.65") != -1: + print("Test 6 Passed. (Ordering system for order of 3 pizzas)") +else: + print("Test 6 Failed. (Ordering system for order of 3 pizzas)") + +# print(studentOutput) +# print(expectedOutput) +# -------------------------------- + + + + diff --git a/Pizza Order/README.md b/Pizza Order/README.md new file mode 100644 index 00000000..b859e05f --- /dev/null +++ b/Pizza Order/README.md @@ -0,0 +1,6 @@ +# OrderPizza + A program that I created in one of my computer science courses containing a frontend and backend. The frontend deals with asking the user for their order, while the backend focuses on storing the information in a receipt format along with its calculations by using functions, lists, and tuples. + + In the frontend, the user first asks if the customer would like to order. If they say no, the code exits completely and is terminated. If the user says yes, it will then ask for the size of pizza as each have a different price range. After, the user will ask for toppings. The maximum that they can enter is three. Afterwards, every topping will cost an additional price to its total. After they have completed asking toppings, the program creates the order in a tuple and is stored in a variable. If the user would like to continue to ordering, the program would loop once more using a while loop and repeat the same questions that were asked in the last instance Afterwards, the second order is incremented to the variable containing the tuple. Otherwise, the code exits and the pizza receipt file is called using the variable of the tuple containing the pizza order and will print a receipt detailing the order and the total. + + In the backend, once the customer has finished ordering, the function is called using the variable as a paramter containing the customers order and creates a receipt by first showing the first pizza, its size, toppings and the amount is placed on the right hand side. If there are more than three toppings, it will show its additional cost as well. If there are more pizzas included, it will repeat the process once more. Afterwards, it shows the total before tax, the additional 13% tax in dollar amount and the total with tax. diff --git a/Pizza Order/order.py b/Pizza Order/order.py new file mode 100644 index 00000000..3ece1594 --- /dev/null +++ b/Pizza Order/order.py @@ -0,0 +1,80 @@ +# purpose of order.py is the front end for users to submit their order +from pizzaReceipt import * # asks to import all functions found in the pizzaReceipt.py file + +# set all initial variables before beginning +size = "" +pizza_lst = [] +pizza_lst_current = [] +toppings_lst = [] # list to be a parameter for generateReceipt function +list_order_yes = ["Yes", "yes", "Y", "y", "YES"] +list_order_no = ["No", "no", "Q", "NO", "N", "n"] +TOPPINGS = ("ONION", "TOMATO", "GREEN PEPPER", "MUSHROOM", "OLIVE", "SPINACH", "BROCCOLI", "PINEAPPLE", + "HOT PEPPER", "PEPPERONI", "HAM", "BACON", "GROUND BEEF", "CHICKEN", "SAUSAGE") + +# ask user whether they want to order. +order = input("Do you want to order a pizza? ") + +# case for when an invalid input is submitted +while (order not in list_order_yes) and (order not in list_order_no): + order = input("Do you want to order a pizza? ") + +# ask for size +if order in list_order_yes: + size = input("Choose a size: ") + size.upper() + + # case for when a user inputs invalid size + while size.upper() not in ["S", "M", "L", "XL"]: + size = input("Choose a size: ") + +# entire loop to repeat if user wants to order more than one pizza +while order in list_order_yes: + # set empty toppings list as it will show empty each time loop is made + toppings_lst = [] + # ask user for topping, whether they want to see a list of the toppings, or to finish ordering toppings. + topping = input('Type in one of our toppings to add it to your pizza. To see the list of toppings, enter "LIST". ' + 'When you are done adding toppings, enter "X" ') + + # cae for when a user places an invalid input for this question + while (topping.upper() != "X") and (topping.upper() != "LIST") and (topping.upper() not in TOPPINGS): + topping = input('Type in one of our toppings to add it to your pizza. To see the list of toppings, enter "LIST". ' + 'When you are done adding toppings, enter "X" ') + + print() + # toppings while loop which ask for toppings selection or list view, multiple times until user enters X + while topping.upper() != "X": + TOPPINGS = ("ONION", "TOMATO", "GREEN PEPPER", "MUSHROOM", "OLIVE", "SPINACH", "BROCCOLI", "PINEAPPLE", + "HOT PEPPER", "PEPPERONI", "HAM", "BACON", "GROUND BEEF", "CHICKEN", "SAUSAGE") + if topping.upper() == "LIST": + print(topping.upper()) + print(TOPPINGS) + topping = input('Type in one of our toppings to add it to your pizza. To see the list of toppings, enter "LIST". ' + 'When you are done adding toppings, enter "X" \n \n') + elif topping.upper() in TOPPINGS: + print(topping.upper()) + print("Added", topping.upper(), "to your pizza") + toppings_lst.append(topping) + topping = input('Type in one of our toppings to add it to your pizza. To see the list of toppings, enter "LIST". ' + 'When you are done adding toppings, enter "X" \n \n') + + # add the size and toppings list as a tuple to pizza_lst + pizza_lst.append((size.upper(), toppings_lst)) + print(pizza_lst) + # ask whether they want to continue ordering + order = input("Do you want to continue ordering? ") + + # case for when user types invalid input + while (order not in list_order_yes) and (order not in list_order_no): + order = input("Do you want to order a pizza? ") + + # if they say no, break the loop and go through the last line of the code + if order in list_order_no: + break + elif order in list_order_yes: + size = input("Choose a size: ") # if they want to order again start by asking size + + # case for when user types invalid input + while size.upper() not in ["S", "M", "L", "XL"]: + size = input("Choose a size: ") + +generateReceipt(pizza_lst) # at the end of program, call function using pizza_lst as a parameter diff --git a/Pizza Order/pizzaReceipt.py b/Pizza Order/pizzaReceipt.py new file mode 100644 index 00000000..b7ff1d3d --- /dev/null +++ b/Pizza Order/pizzaReceipt.py @@ -0,0 +1,105 @@ +# purpose of pizzaReceipt.py is the back end where the developers create methods and functions to properly format the receipt and its total +def generateReceipt(pizzaOrder): + # parameter will be placed with pizza_lst = ("M", ["PEPPERONI", "OLIVE"], -----) + # set initial variables + size = "" + additional_price = 0 + price_before_tax = 0 + tax = 1.13 + counter = 1 # pizza number + size_price = 0 + additional_price_tag = float(0) + additional_price_tag_format = "" + + # if its an empty list, display this statement + if len(pizzaOrder) == 0: + print("You did not order anything") + exit() + + # beginning of the format of receipt + print("Your order: ") + + # a for loop which goes through all tuples in the list based on its indices + for pizza in range(len(pizzaOrder)): + # cases to determine the sizes selected and its price + if pizzaOrder[pizza][0] == "S": + size_price = 7.99 + size = "S" + elif pizzaOrder[pizza][0] == "M": + size_price = 9.99 + size = "M" + elif pizzaOrder[pizza][0] == "L": + size_price = 11.99 + size = "L" + elif pizzaOrder[pizza][0] == "XL": + size_price = 13.99 + size = "XL" + + # add the price of the size to the final price before tax + price_before_tax += size_price + + # formatting the pizza number and its size beside it and the price on the other side + if size == "XL": + print("Pizza", str(counter) + ":", str(size) + " \t\t\t " + str(size_price)) + elif size == "L": + print("Pizza", str(counter) + ":", str(size) + " \t\t\t " + str(size_price)) + elif size == "M": + print("Pizza", str(counter) + ":", str(size) + " \t\t\t " + str(size_price)) + elif size == "S": + print("Pizza", str(counter) + ":", str(size) + " \t\t\t " + str(size_price)) + + # increment counter variable by one for the pizza number + counter += 1 + + # format the toppings with a dash in front + for j in range(len(pizzaOrder[pizza][1])): + print("- " + str(pizzaOrder[pizza][1][j])) + + # if theres more than three toppings, calculate the total additional price and added to the total price before tax + if len(pizzaOrder[pizza][1]) > 3: + n = len(pizzaOrder[pizza][1]) - 3 + if size == "S": + additional_price_tag = 0.50 + additional_price_tag_format = "{:.2f}".format(additional_price_tag) + additional_price = 0.50 * n + price_before_tax += additional_price + elif size == "M": + additional_price_tag = 0.75 + additional_price = 0.75 * n + price_before_tax += additional_price + elif size == "L": + additional_price_tag = 1.00 + additional_price_tag_format = "{:.2f}".format(additional_price_tag) + additional_price = 1.00 * n + price_before_tax += additional_price + elif size == "XL": + additional_price_tag = 1.25 + additional_price = 1.25 * n + price_before_tax += additional_price + + # format the extra topping portion of the receipt with its size and price on the other side + float_additional_price = float(additional_price) + format_additional_price = "{:.2f}" .format(float_additional_price) + + for extra in range(len(pizzaOrder[pizza][1])): + if extra > 2: + if size == "XL": + print("Extra Topping", "(" + size + ")" + "\t\t " + str(additional_price_tag)) + elif size == "L": + print("Extra Topping", "(" + size + ")" + "\t\t " + str(additional_price_tag_format)) + elif size == "M": + print("Extra Topping", "(" + size + ")" + "\t\t " + str(additional_price_tag)) + elif size == "S": + print("Extra Topping", "(" + size + ")" + "\t\t " + str(additional_price_tag_format)) + # outside of loop begins, calculates the price before tax with the tax value set earlier + price_final = price_before_tax * tax + + # add the tax price to be added and set it to a float, as well as the final price with tax + float1 = float(price_before_tax * (13/100)) + float2 = float(price_final) + formatFloat1 = "{:.2f}" .format(float1) + formatFloat2 = "{:.2f}" .format(float2) + + # format the price of the tax, and the total with both values on the other side + print("Tax:" + "\t\t\t\t\t " + formatFloat1) + print("Total:" + "\t\t\t\t\t " + formatFloat2) diff --git a/Pizza Order/pyvenv.cfg b/Pizza Order/pyvenv.cfg new file mode 100644 index 00000000..b83f8fb7 --- /dev/null +++ b/Pizza Order/pyvenv.cfg @@ -0,0 +1,8 @@ +home = /Library/Frameworks/Python.framework/Versions/3.10 +implementation = CPython +version_info = 3.10.0.final.0 +virtualenv = 20.13.0 +include-system-site-packages = false +base-prefix = /Library/Frameworks/Python.framework/Versions/3.10 +base-exec-prefix = /Library/Frameworks/Python.framework/Versions/3.10 +base-executable = /usr/local/bin/python3.10 diff --git a/QR Code Generator/QRcode.py b/QR Code Generator/QRcode.py index adf4bcd0..bd1dffb5 100644 --- a/QR Code Generator/QRcode.py +++ b/QR Code Generator/QRcode.py @@ -1,8 +1,29 @@ import qrcode +from qrcode.constants import ERROR_CORRECT_L -qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L) -qr.add_data("INSERT YOUR LINK HERE") -qr.make(fit=True) +def generate_qrcode(data: str, file_path: str = "qrcode.png", fill_color: str = "black", back_color: str = "white"): + """ + Generates a QR code from the provided data and saves it as an image file. + + Parameters: + - data (str): The content the QR code should contain (URL, text, etc.). + - file_path (str): The path to save the QR code image file (default: "qrcode.png"). + - fill_color (str): Color of the QR code (default: "black"). + - back_color (str): Background color of the QR code (default: "white"). + """ + qr = qrcode.QRCode( + version=1, + error_correction=ERROR_CORRECT_L, + box_size=10, + border=4 + ) + qr.add_data(data) + qr.make(fit=True) + + # Generate the image with specified colors + img = qr.make_image(fill_color=fill_color, back_color=back_color) + img.save(file_path) + print(f"QR code saved as {file_path}") -img = qr.make_image(fill_color="black", back_color="white") -img.save("qrcode.png") +# Usage example +generate_qrcode("https://example.com", "my_qrcode.png") diff --git a/README.md b/README.md index cb63b7dd..0547119f 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,6 @@ - [Gitpod](#gitpod) - [Wall of Contributors](#wall-of-contributors) -
[![Join Our Discord](https://img.shields.io/badge/Discord-Join%20Server-blue?logo=discord&style=for-the-badge)](https://discord.com/invite/Yn9g6KuWyA) [![Subscribe on YouTube](https://img.shields.io/badge/YouTube-Subscribe-red?logo=youtube&style=for-the-badge)](https://www.youtube.com/@dhanushnehru?sub_confirmation=1) @@ -34,7 +33,7 @@ _**Note: Please follow the maintainer of the repository for quick approval of th **NOTE:** Remember to close your issues once your PR has been merged! They can be reopened if needed. -More information on contributing and the general code of conduct for discussion and feedback in this repo can be found here: [Contributions.md](https://github.com/DhanushNehru/Python-Scripts/blob/master/Contributions.md) +More information on contributing and the general code of conduct for discussion and feedback in this repo can be found here: [CONTRIBUTIONS.md](https://github.com/DhanushNehru/Python-Scripts/blob/master/CONTRIBUTIONS.md) ## List of Scripts in Repo @@ -49,13 +48,15 @@ More information on contributing and the general code of conduct for discussion | Blackjack | [Blackjack](https://github.com/DhanushNehru/Python-Scripts/tree/master/Blackjack) | A game of Blackjack - let's get a 21. | | Chessboard | [Chessboard](https://github.com/DhanushNehru/Python-Scripts/tree/master/Chess%20Board) | Creates a chessboard using matplotlib. | | Compound Interest Calculator | [Compound Interest Calculator](https://github.com/DhanushNehru/Python-Scripts/tree/master/Calculate%20Compound%20Interest) | A Python script to calculate compound interest. | -| Countdown Timer | [Countdown Timer](https://github.com/DhanushNehru/Python-Scripts/tree/master/Countdown%20Timer) | Displays a message when the Input time elapses. | | Convert Temperature | [Convert Temperature](https://github.com/DhanushNehru/Python-Scripts/tree/master/Convert%20Temperature) | A python script to convert temperature between Fahreheit, Celsius and Kelvin | +| Connect Four | [Connect Four](https://github.com/DhanushNehru/Python-Scripts/tree/master/Connect%20Four) | A Python script for the board game Connect Four, which can be played by 1-2 players | +| Countdown Timer | [Countdown Timer](https://github.com/DhanushNehru/Python-Scripts/tree/master/Countdown%20Timer) | Displays a message when the Input time elapses. | | Crop Images | [Crop Images](https://github.com/DhanushNehru/Python-Scripts/tree/master/Crop%20Images) | A Python script to crop a given image. | | CSV to Excel | [CSV to Excel](https://github.com/DhanushNehru/Python-Scripts/tree/master/CSV%20to%20Excel) | A Python script to convert a CSV to an Excel file. | | Currency Script | [Currency Script](https://github.com/DhanushNehru/Python-Scripts/tree/master/Currency%20Script) | A Python script to convert the currency of one country to that of another. | | Digital Clock | [Digital Clock](https://github.com/DhanushNehru/Python-Scripts/tree/master/Digital%20Clock) | A Python script to preview a digital clock in the terminal. | | Display Popup Window | [Display Popup Window](https://github.com/DhanushNehru/Python-Scripts/tree/master/Display%20Popup%20Window) | A Python script to preview a GUI interface to the user. | +| Distance Calculator | [Distance Calculator](https://github.com/Mathdallas-code/Python-Scripts/tree/master/Distance%20Calculator) | A Python script to calculate the distance between two points. | Duplicate Finder | [Duplicate Finder](https://github.com/DhanushNehru/Python-Scripts/tree/master/Duplicate%Fnder) | The script identifies duplicate files by MD5 hash and allows deletion or relocation. | | Emoji | [Emoji](https://github.com/DhanushNehru/Python-Scripts/tree/master/Emoji) | The script generates a PDF with an emoji using a custom TrueType font. | | Emoji to PDF | [Emoji to PDF](https://github.com/DhanushNehru/Python-Scripts/tree/master/Emoji%20To%20Pdf) | A Python Script to view Emoji in PDF. | @@ -83,6 +84,7 @@ More information on contributing and the general code of conduct for discussion | Image Watermarker | [Image Watermarker](https://github.com/DhanushNehru/Python-Scripts/tree/master/Image%20Watermarker) | Adds a watermark to an image. | | Image to ASCII | [Image to ASCII](https://github.com/DhanushNehru/Python-Scripts/tree/master/Image%20to%20ASCII) | Converts an image into ASCII art. | | Image to Gif | [Image to Gif](https://github.com/DhanushNehru/Python-Scripts/tree/master/Image%20to%20GIF) | Generate gif from images. | +| Images to WebP Converter | [Images to WebP Converter] (https://github.com/DhanushNehru/Python-Scripts/tree/master/Images%20to%20WebP%20Converter) | Converts images to WebP vie cmd or GUI | | Interactive Dictionary | [Interactive Dictionary](https://github.com/DhanushNehru/Python-Scripts/tree/master/Image%20InteractiveDictionary) | finding out meanings of words | | IP Geolocator | [IP Geolocator](https://github.com/DhanushNehru/Python-Scripts/tree/master/IP%20Geolocator) | Uses an IP address to geolocate a location on Earth. | | Jokes Generator | [Jokes generator](https://github.com/DhanushNehru/Python-Scripts/tree/master/Jokes%20Generator) | Generates jokes. | @@ -96,6 +98,7 @@ More information on contributing and the general code of conduct for discussion | Longitude & Latitude to conical coverter | [Longitude Latitude conical converter](master/Longitude%20Latitude%20conical%20converter) | Converts Longitude and Latitude to Lambert conformal conic projection. | | Mail Sender | [Mail Sender](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mail%20Sender) | Sends an email. | | Merge Two Images | [Merge Two Images](https://github.com/DhanushNehru/Python-Scripts/tree/master/Merge%20Two%20Images) | Merges two images horizontally or vertically. | +| Mood based youtube song generator | [Mood based youtube song generator](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mood%20based%20youtube%20song%20generator) | This Python script fetches a random song from YouTube based on your mood input and opens it in your default web browser. | | Mouse mover | [Mouse mover](https://github.com/DhanushNehru/Python-Scripts/tree/master/Mouse%20Mover) | Moves your mouse every 15 seconds. | | Morse Code | [Mose Code](https://github.com/DhanushNehru/Python-Scripts/tree/master/Morse%20Code) | Encodes and decodes Morse code. | | No Screensaver | [No Screensaver](https://github.com/DhanushNehru/Python-Scripts/tree/master/No%20Screensaver) | Prevents screensaver from turning on. | @@ -107,6 +110,7 @@ More information on contributing and the general code of conduct for discussion | PDF to Audio | [PDF to Audio](https://github.com/DhanushNehru/Python-Scripts/tree/master/PDF%20to%20Audio) | Converts PDF to audio. | | PDF to Text | [PDF to text](https://github.com/DhanushNehru/Python-Scripts/tree/master/PDF%20to%20text) | Converts PDF to text. | | PDF merger and splitter | [PDF Merger and Splitter](https://github.com/AbhijitMotekar99/Python-Scripts/blob/master/PDF%20Merger%20and%20Splitter/PDF%20Merger%20and%20Splitter.py) | Create a tool that can merge multiple PDF files into one or split a single PDF into separate pages. | +| Pizza Order | [Pizza Order](https://github.com/DhanushNehru/Python-Scripts/tree/master/Pizza%20Order) | An algorithm designed to handle pizza orders from customers with accurate receipts and calculations. | | Planet Simulation | [Planet Simulation](https://github.com/DhanushNehru/Python-Scripts/tree/master/Planet%20Simulation) | A simulation of several planets rotating around the sun. | | Playlist Exchange | [Playlist Exchange](https://github.com/DhanushNehru/Python-Scripts/tree/master/Playlist%20Exchange) | A Python script to exchange songs and playlists between Spotify and Python. | | Pigeonhole Sort | [Algorithm](https://github.com/DhanushNehru/Python-Scripts/tree/master/PigeonHole) | The pigeonhole sort algorithm to sort your arrays efficiently! | @@ -118,7 +122,7 @@ More information on contributing and the general code of conduct for discussion | QR Code with logo | [QR code with Logo](https://github.com/DhanushNehru/Python-Scripts/tree/master/QR%20with%20Logo) | QR Code Customization Feature | | Random Color Generator | [Random Color Generator](https://github.com/DhanushNehru/Python-Scripts/tree/master/Random%20Color%20Generator) | A random color generator that will show you the color and values! | | Remove Background | [Remove Background](https://github.com/DhanushNehru/Python-Scripts/tree/master/Remove%20Background) | Removes the background of images. | -| Road-Lane-Detection | [Road-Lane-Detection](https://github.com/NotIncorecc/Python-Scripts/tree/master/Road-Lane-Detection) | Detects the lanes of the road | +| Road-Lane-Detection | [Road-Lane-Detection](https://github.com/NotIncorecc/Python-Scripts/tree/master/Road-Lane-Detection) | Detects the lanes of the road | | Rock Paper Scissor 1 | [Rock Paper Scissor 1](https://github.com/DhanushNehru/Python-Scripts/tree/master/Rock%20Paper%20Scissor%201) | A game of Rock Paper Scissors. | | Rock Paper Scissor 2 | [Rock Paper Scissor 2](https://github.com/DhanushNehru/Python-Scripts/tree/master/Rock%20Paper%20Scissor%202) | A new version game of Rock Paper Scissors. | | Run Then Notify | [Run Then Notify](https://github.com/DhanushNehru/Python-Scripts/tree/master/Run%20Then%20Notify) | Runs a slow command and emails you when it completes execution. | @@ -126,6 +130,7 @@ More information on contributing and the general code of conduct for discussion | Simple DDOS | [Simple DDOS](https://github.com/VanshajR/Python-Scripts/tree/master/Simple%20DDOS) | The code allows you to send multiple HTTP requests concurrently for a specified duration. | | Simple TCP Chat Server | [Simple TCP Chat Server](https://github.com/DhanushNehru/Python-Scripts/tree/master/TCP%20Chat%20Server) | Creates a local server on your LAN for receiving and sending messages! | | Smart Attendance System | [Smart Attendance System](https://github.com/DhanushNehru/Python-Scripts/tree/master/Smart%20Attendance%20System) | This OpenCV framework is for Smart Attendance by actively decoding a student's QR Code. | +| Snake Game | [Snake Game](https://github.com/DhanushNehru/Python-Scripts/tree/master/Snake%20Game) | Classic snake game using python. | | Snake Water Gun | [Snake Water Gun](https://github.com/DhanushNehru/Python-Scripts/tree/master/Snake%20Water%20Gun) | A game similar to Rock Paper Scissors. | | Sorting | [Sorting](https://github.com/DhanushNehru/Python-Scripts/tree/master/Sorting) | Algorithm for bubble sorting. | | Star Pattern | [Star Pattern](https://github.com/DhanushNehru/Python-Scripts/tree/master/Star%20Pattern) | Creates a star pattern pyramid. | @@ -139,6 +144,7 @@ More information on contributing and the general code of conduct for discussion | Turtle Graphics | [Turtle Graphics](https://github.com/DhanushNehru/Python-Scripts/tree/master/Turtle%20Graphics) | Code using turtle graphics. | | Twitter Selenium Bot | [Twitter Selenium Bot](https://github.com/DhanushNehru/Python-Scripts/tree/master/Twitter%20Selenium%20Bot) | A bot that can interact with Twitter in a variety of ways. | | Umbrella Reminder | [Umbrella Reminder](https://github.com/DhanushNehru/Python-Scripts/tree/master/Umbrella%20Reminder) | A reminder for umbrellas. | +| University Rankings | [University Rankings](https://github.com/DhanushNehru/Python-Scripts/tree/master/University%20Rankings) | Ranks Universities across the globes using the Country, Continent, and Captial | | URL Shortener | [URL Shortener](https://github.com/DhanushNehru/Python-Scripts/tree/master/URL%20Shortener) | A URL shortener code compresses long URLs into shorter, more manageable links | | Video Downloader | [Video Downloader](https://github.com/DhanushNehru/Python-Scripts/tree/master/Video%20Downloader) | Download Videos from youtube to your local system. | | Video Watermarker | [Video Watermarker](https://github.com/DhanushNehru/Python-Scripts/tree/master/Video%20Watermarker) | Adds watermark to any video of your choice. | @@ -147,7 +153,7 @@ More information on contributing and the general code of conduct for discussion | Weather GUI | [Weather GUI](https://github.com/DhanushNehru/Python-Scripts/tree/master/Weather%20GUI) | Displays information on the weather. | | Website Blocker | [Website Blocker](https://github.com/DhanushNehru/Python-Scripts/tree/master/Website%20Blocker) | Downloads the website and loads it on your homepage in your local IP. | | Website Cloner | [Website Cloner](https://github.com/DhanushNehru/Python-Scripts/tree/master/Website%20Cloner) | Clones any website and opens the site in your local IP. | -| Web Scraper | [Web Scraper](https://github.com/Charul00/Python-Scripts/tree/main/Web%20Scraper) | A Python script that scrapes blog titles from Python.org and saves them to a file. | +| Web Scraper | [Web Scraper](https://github.com/DhanushNehru/Python-Scripts/tree/master/Web%20Scraper) | A Python script that scrapes blog titles from [Python.org](https://www.python.org/) and saves them to a file. | | Weight Converter | [Weight Converter](https://github.com/WatashiwaSid/Python-Scripts/tree/master/Weight%20Converter) | Simple GUI script to convert weight in different measurement units. | | Wikipedia Data Extractor | [Wikipedia Data Extractor](https://github.com/DhanushNehru/Python-Scripts/tree/master/Wikipedia%20Data%20Extractor) | A simple Wikipedia data extractor script to get output in your IDE. | | Word to PDF | [Word to PDF](https://github.com/DhanushNehru/Python-Scripts/tree/master/Word%20to%20PDF%20converter) | A Python script to convert an MS Word file to a PDF file. | diff --git a/Smart Attendance System/README_smart_attendance_system.md b/Smart Attendance System/README.md similarity index 100% rename from Smart Attendance System/README_smart_attendance_system.md rename to Smart Attendance System/README.md diff --git a/Snake Game/README.md b/Snake Game/README.md new file mode 100644 index 00000000..51592849 --- /dev/null +++ b/Snake Game/README.md @@ -0,0 +1,3 @@ +# Snake-Game + +![snake game demo](https://github.com/user-attachments/assets/a88cd856-a477-4f02-ac50-eb09a801cd8a) diff --git a/Snake Game/data.txt b/Snake Game/data.txt new file mode 100644 index 00000000..25bf17fc --- /dev/null +++ b/Snake Game/data.txt @@ -0,0 +1 @@ +18 \ No newline at end of file diff --git a/Snake Game/food.py b/Snake Game/food.py new file mode 100644 index 00000000..b014c00a --- /dev/null +++ b/Snake Game/food.py @@ -0,0 +1,18 @@ +from turtle import Turtle +import random + +class Food(Turtle): #It refers to dot as food + def __init__(self): + super().__init__() + self.shape("circle") + self.penup() + self.shapesize(stretch_len= 0.5, stretch_wid= 0.5) + self.color("blue") + self.speed("fastest") + self.refresh() + + def refresh(self): + random_x = random.randint(-280, 280) + random_y = random.randint(-280, 280) + self.goto(random_x, random_y) + diff --git a/Snake Game/main.py b/Snake Game/main.py new file mode 100644 index 00000000..5ad9c3cc --- /dev/null +++ b/Snake Game/main.py @@ -0,0 +1,46 @@ +from turtle import Screen + +from snake import Snake +from food import Food +from scoreboard import Scoreboard +import time + +screen = Screen() +screen.setup(width= 600, height= 600) +screen.bgcolor("black") +screen.title("Snake Game") +screen.tracer(0) + +snake = Snake() +food = Food() +scoreboard = Scoreboard() + +screen.listen() +screen.onkey(snake.up, "Up") +screen.onkey(snake.down,"Down") +screen.onkey(snake.left,"Left") +screen.onkey(snake.right,"Right") + +is_game_on = True +while is_game_on: + screen.update() + time.sleep(0.15) + snake.move() + #detect collision with the food + if snake.head.distance(food) < 15: + food.refresh() + snake.extend() + scoreboard.increase_score() + + #detect collision with the wall + if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: + scoreboard.reset() + snake.reset() + + #detect collision with the tail + for segment in snake.segments[1:]: + if snake.head.distance(segment) < 10: + scoreboard.reset() + snake.reset() + +screen.exitonclick() \ No newline at end of file diff --git a/Snake Game/scoreboard.py b/Snake Game/scoreboard.py new file mode 100644 index 00000000..074fe43f --- /dev/null +++ b/Snake Game/scoreboard.py @@ -0,0 +1,31 @@ +from turtle import Turtle +ALIGNMENT = "center" +FONT = ("Courier", 25, "normal") +class Scoreboard(Turtle): + def __init__(self): + super().__init__() + self.score = 0 + with open("data.txt") as data: + self.highscore = int(data.read()) + self.color("white") + self.penup() + self.goto(0, 260) + self.hideturtle() + self.update_score() + + def update_score(self): + self.clear() + self.write(f"Score: {self.score} HighScore: {self.highscore}", align= ALIGNMENT, font= FONT) + + def reset(self): + if self.score > self.highscore: + self.highscore = self.score + with open("data.txt", "w") as data: + data.write(f"{self.highscore}") + self.score = 0 + self.update_score() + + def increase_score(self): + self.score += 1 + self.update_score() + diff --git a/Snake Game/snake.py b/Snake Game/snake.py new file mode 100644 index 00000000..8286e363 --- /dev/null +++ b/Snake Game/snake.py @@ -0,0 +1,54 @@ +from turtle import Turtle +STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] +MOVE_DISTANCE = 20 +UP = 90 +DOWN = 270 +RIGHT = 0 +LEFT = 180 + +class Snake: + def __init__(self): + self.segments = [] + self.create_snake() + self.head = self.segments[0] + + def create_snake(self): + for position in STARTING_POSITIONS: + self.add_segment(position) + + def reset(self): + for seg in self.segments: + seg.goto(1000, 1000) + self.segments.clear() + self.create_snake() + self.head = self.segments[0] + + def add_segment(self, position): + new_segment = Turtle("square") + new_segment.penup() + new_segment.color("white") + new_segment.goto(position) + self.segments.append(new_segment) + + def extend(self): + self.add_segment(self.segments[-1].position()) + + def move(self): + for seg_num in range(len(self.segments) - 1, 0, -1): + new_x = self.segments[seg_num - 1].xcor() + new_y = self.segments[seg_num - 1].ycor() + self.segments[seg_num].goto(new_x, new_y) + self.segments[0].forward(MOVE_DISTANCE) + + def up(self): + if self.head.heading() != DOWN: + self.head.setheading(UP) + def down(self): + if self.head.heading() != UP: + self.head.setheading(DOWN) + def left(self): + if self.head.heading() != RIGHT: + self.head.setheading(LEFT) + def right(self): + if self.head.heading() != LEFT: + self.head.setheading(RIGHT) \ No newline at end of file diff --git a/University Rankings/README.md b/University Rankings/README.md new file mode 100644 index 00000000..d769243a --- /dev/null +++ b/University Rankings/README.md @@ -0,0 +1,10 @@ +# UniversityRankings + A program that I constructed for ranking universities based on two files provided by the user. One would contain the list of universities around the world ranked in order, and another file contains the various countries and its corresponding capital. In this instance, I used two files called capitals.csv and TopUni.csv. I chose to create this program by using one function, however, this program can be altered and constructed by using multiple functions. Since the files that we are using are comma separated values (csv), I chose to open them by importing and using pandas as pd. The output was displayed on an output.txt file to record my output in that file. Below are the following calculations that were made in the program. + + 1. The first part of the program details the total number of universities in the TopUni.csv file. + 2. The second part of the program displays all the available countries + 3. The third part of the program illustrates all the available continents + 4. The next part of the program identifies the international and national rankings that are associated with the selected country + 5. The following portion of the code calculates the average score, relative score, + 6. The next part determines the capital of the selected country + 7. The last part of the code outputs the universities name(s) that contain the capital diff --git a/University Rankings/output.txt b/University Rankings/output.txt new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/University Rankings/output.txt @@ -0,0 +1 @@ + diff --git a/University Rankings/pyvenv.cfg b/University Rankings/pyvenv.cfg new file mode 100644 index 00000000..b83f8fb7 --- /dev/null +++ b/University Rankings/pyvenv.cfg @@ -0,0 +1,8 @@ +home = /Library/Frameworks/Python.framework/Versions/3.10 +implementation = CPython +version_info = 3.10.0.final.0 +virtualenv = 20.13.0 +include-system-site-packages = false +base-prefix = /Library/Frameworks/Python.framework/Versions/3.10 +base-exec-prefix = /Library/Frameworks/Python.framework/Versions/3.10 +base-executable = /usr/local/bin/python3.10 diff --git a/University Rankings/univRanking.py b/University Rankings/univRanking.py new file mode 100644 index 00000000..0608261c --- /dev/null +++ b/University Rankings/univRanking.py @@ -0,0 +1,192 @@ +import pandas as pd + +def getInformation(selectedCountry, rankingFileName, capitalsFileName): + # add selected country + # Total number of universities + # show countries + # show continents + # calculate average score (sum of all uni scores within the selected country) / (number of universities within the selected country) + # display the average score + # calculate the relative score (average score) / (The highest score within the continent where the university is selected) + + available_countries = 0 + counter = 0 + countries = "" + continents = "" + countries_lst = [] + continents_lst = [] + TopUni = pd.read_csv(rankingFileName) + Capitals = pd.read_csv(capitalsFileName) + country_counter = 0 + country_counter_rank = 1 + + file = open("output.txt", "w") # open output.txt file where output is stored + + for line in range(len(TopUni)): + counter += 1 + + file.write("Total number of Universities => {}\n" .format(counter)) # PART 1 TOTAL NUMBER OF UNIVERSITIES + + # LISTING ALL AVAILABLE COUNTRIES WITHIN THE FILE + for country in Capitals["Country Name"]: + if country not in countries_lst: + countries_lst.append(country) + available_countries += 1 + + for country in countries_lst: + if countries == "": + countries = countries + country + else: + countries = countries + ", " + country + + file.write("Available countries => {}\n" .format(countries)) # PART 2 AVAILABLE COUNTRIES + + # FINDING ALL AVAILABLE CONTINENTS WITHIN THE FILE + for continent in Capitals["Continent"]: + if continent not in continents_lst: + continents_lst.append(continent) + + for continent in continents_lst: + if continents == "": + continents = continents + continent + else: + continents = continents + ", " + continent + + file.write("Available Continents => {}\n" .format(continents)) # PART 3 AVAILABLE CONTINENTS + + # FINDING THE INTERNATIONAL RANK OF COUNTRIES ASSOCIATED WITH THE SELECTED COUNTRY + for country in TopUni["Country"]: + if country == selectedCountry: + file.write("At international rank => {} the university name is => {}\n" .format(country_counter_rank, TopUni["Institution name"][country_counter])) # PART 4 INTERNATIONAL RANK + country_counter += 1 + country_counter_rank += 1 + + country_counter = 0 + country_national_counter_rank = 1 + + for country in TopUni["Country"]: + if country == selectedCountry: + file.write("At national rank => {} the university name is => {}\n" .format(country_national_counter_rank, TopUni["Institution name"][country_counter])) # PART 5 NATIONAL RANK + country_national_counter_rank += 1 + country_counter += 1 + + number_of_universities = 0 + university_score = 0 + TopUni = pd.read_csv(rankingFileName) + counter = 0 + + for country in TopUni["Country"]: + if selectedCountry == country: + university_score += TopUni["Score"][counter] + number_of_universities += 1 + counter += 1 + + # THE AVERAGE SCORE CALCULATIONS + averageScore = university_score / number_of_universities + file.write("The average score => {}%\n" .format(round(averageScore, 1))) # PART 6 AVERAGE SCORE # PART 6 + + number_of_universities = 0 + university_score = 0 + TopUni = pd.read_csv(rankingFileName) + Capitals = pd.read_csv(capitalsFileName) + highestScore1 = 0 + highestScore2 = 0 + highestScore3 = 0 + highestScore4 = 0 + highestScore5 = 0 + counter1 = 0 + counter2 = 0 + counter3 = 0 + continent = "" + + # CALCULATING THE RELATIVE SCORE + for country in TopUni["Country"]: + if selectedCountry == country: + university_score += TopUni["Score"][counter1] + number_of_universities += 1 + counter1 += 1 + + averageScore = university_score / number_of_universities + + for country in Capitals["Country Name"]: + if selectedCountry == country: + continent = Capitals["Continent"][counter2] + counter2 += 1 + + for continentScore in TopUni["Score"]: + if TopUni["Country"][counter3] in ["Jordan", "Palestine", "China", "Israel", "Japan", "Singapore", "South Korea", "Taiwan"]: + if continentScore > highestScore1: + highestScore1 = continentScore + elif TopUni["Country"][counter3] in "Australia": + if continentScore > highestScore2: + highestScore2 = continentScore + elif TopUni["Country"][counter3] in ["Canada", "USA"]: + if continentScore > highestScore3: + highestScore3 = continentScore + elif TopUni["Country"][counter3] in ["Denmark", "France", "Germany", "Netherlands", "Norway", "Sweden", "Switzerland", "United Kingdom"]: + if continentScore > highestScore4: + highestScore4 = continentScore + elif TopUni["Country"][counter3] in ["Egypt"]: + if continentScore > highestScore5: + highestScore5 = continentScore + + counter3 += 1 + + # PART 7 RELATIVE SCORE + if selectedCountry in ["Jordan", "Palestine", "China", "Israel", "Japan", "Singapore", "South Korea", "Taiwan"]: + relativeScore = (averageScore / highestScore1) * 100 + file.write("The relative score to the top university in {} is => ({} / {}) x 100% = {}%\n" .format(continent, averageScore, highestScore1, round(relativeScore, 1))) + elif selectedCountry in "Australia": + relativeScore = (averageScore / highestScore2) * 100 + file.write("The relative score to the top university in {} is => ({} / {}) x 100% = {}%\n" .format(continent, averageScore, highestScore2, round(relativeScore, 1))) + elif selectedCountry in ["Canada", "USA"]: + relativeScore = (averageScore / highestScore3) * 100 + file.write("The relative score to the top university in {} is => ({} / {}) x 100% = {}%\n" .format(continent, averageScore, highestScore3, round(relativeScore, 1))) + elif selectedCountry in ["Denmark", "France", "Germany", "Netherlands", "Norway", "Sweden", "Switzerland", "United Kingdom"]: + relativeScore = (averageScore / highestScore4) * 100 + file.write("The relative score to the top university in {} is => ({} / {}) x 100% = {}%\n" .format(continent, averageScore, highestScore4, round(relativeScore, 1))) + elif selectedCountry in ["Egypt"]: + relativeScore = (averageScore / highestScore5) * 100 + file.write("The relative score to the top university in {} is => ({} / {}) x 100% = {}%\n" .format(continent, averageScore, highestScore5, round(relativeScore, 1))) + + # FINDING THE CAPITAL OF THE SELECTED COUNTRY + Capitals = pd.read_csv(capitalsFileName) + capital = "" + counter = 0 + + for cap in Capitals["Country Name"]: + if cap == selectedCountry: + capital = Capitals["Capital"][counter] + counter += 1 + + file.write("The capital is => {}\n" .format(capital)) # PART 8 CAPITAL OF SELECTED COUNTRY + + # FINDING THE UNIVERSITIES THAT HAVE THE NAME OF THE CAPITAL WITHIN IT + TopUni = pd.read_csv(rankingFileName) + Capitals = pd.read_csv(capitalsFileName) + capital = "" + counter1 = 0 + counter2 = 0 + number_counter = 1 + for cap in Capitals["Country Name"]: + if cap == selectedCountry: + capital = Capitals["Capital"][counter1] + counter1 += 1 + + file.write("The universities that contain the capital name => \n") # PART 9 CAPITAL NAME IN UNIVERSITY NAME + + for uni in TopUni["Country"]: + if (selectedCountry == uni) and (capital in TopUni["Institution name"][counter2]): + file.write("#" + str(number_counter) + " " + TopUni["Institution name"][counter2] + "\n") + number_counter += 1 + counter2 += 1 + + +def __main__(): + country = input("input the country you want to look at: ") + file1 = "TopUni.csv" + file2 = "capitals.csv" + getInformation(country, file1, file2) + + +__main__() diff --git a/Website Cloner/index.html b/Website Cloner/index.html index 26c2f4ee..357d9e74 100644 --- a/Website Cloner/index.html +++ b/Website Cloner/index.html @@ -1,40 +1,32 @@ - PROXY SERVER - - - - + PROXY SERVER + + + + -
-
-
-
-
- - - - - -
- -
- -
-
-
-
-
- - +
+
+
+
+
+ + + + + +
+
+ +
+
+
+
+
diff --git a/Website Cloner/server.py b/Website Cloner/server.py index 3816e4ba..446f8bc6 100644 --- a/Website Cloner/server.py +++ b/Website Cloner/server.py @@ -8,31 +8,52 @@ class RequestHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): if self.path == "/": self.path = "index.html" - return http.server.SimpleHTTPRequestHandler.do_GET(self) + try: + return http.server.SimpleHTTPRequestHandler.do_GET(self) + except FileNotFoundError: + self.send_error(404, "File not found") + def do_POST(self): - form = cgi.FieldStorage( - fp=self.rfile, - headers=self.headers, - environ={ - 'REQUEST_METHOD': 'POST', - 'CONTENT_TYPE': self.headers['Content-Type'], - }) - url = form.getvalue('submitButton') - urlN = 'https://' + str(url) +'/' - isdir = os.path.isdir(url) - if not isdir: - kwargs = {'project_name': url} - save_webpage( - url=urlN, - project_folder='./', - **kwargs - ) - path = url + "/" + url + "/index.html" + content_length = int(self.headers.get('Content-Length', 0)) + post_data = self.rfile.read(content_length).decode("utf-8") + + # Parse the URL from the form submission + form = cgi.parse_qs(post_data) + url = form.get("submitButton", [""])[0] + + if not url: + self.send_error(400, "Bad Request: URL is missing") + return + + urlN = "https://" + url.strip("/") + project_folder = os.path.join('./cloned_sites', url.replace("https://", "").replace("http://", "")) + + if not os.path.isdir(project_folder): + os.makedirs(project_folder, exist_ok=True) + try: + save_webpage( + url=urlN, + project_folder=project_folder, + project_name=url.replace("https://", "").replace("http://", "") + ) + except Exception as e: + self.send_error(500, f"Error cloning website: {e}") + return + + path = os.path.join(project_folder, "index.html") + if not os.path.isfile(path): + self.send_error(404, "Cloned page not found") + return + self.send_response(301) - self.send_header('Location', path) + self.send_header("Location", "/" + path) self.end_headers() - return http.server.SimpleHTTPRequestHandler.do_GET(self) + PORT = 7000 -s = socketserver.TCPServer(("127.0.0.1", PORT), RequestHandler) -s.serve_forever() \ No newline at end of file +os.chdir(os.path.dirname(os.path.abspath(__file__))) + +with socketserver.TCPServer(("127.0.0.1", PORT), RequestHandler) as s: + s.allow_reuse_address = True + print(f"Server running on http://127.0.0.1:{PORT}") + s.serve_forever() diff --git a/import of music and video/Readme.md b/import of music and video/Readme.md index e528183b..fa87e429 100644 --- a/import of music and video/Readme.md +++ b/import of music and video/Readme.md @@ -12,8 +12,6 @@ Before you begin, ensure you have met the following requirements: ```bash pip install pygame - - ## Usage Clone or download this repository to your local machine. Open your terminal or command prompt and navigate to the project directory. @@ -50,7 +48,6 @@ Before you begin, ensure you have met the following requirements: ```bash pip install opencv-python - **Usage** Clone or download this repository to your local machine. Open your terminal or command prompt and navigate to the project directory.