diff --git a/.github/workflows/datadog-synthetics.yml b/.github/workflows/datadog-synthetics.yml
new file mode 100644
index 00000000000..ae3a26706d9
--- /dev/null
+++ b/.github/workflows/datadog-synthetics.yml
@@ -0,0 +1,38 @@
+# This workflow will trigger Datadog Synthetic tests within your Datadog organisation
+# For more information on running Synthetic tests within your GitHub workflows see: https://docs.datadoghq.com/synthetics/cicd_integrations/github_actions/
+
+# This workflow uses actions that are not certified by GitHub.
+# They are provided by a third-party and are governed by
+# separate terms of service, privacy policy, and support
+# documentation.
+
+# To get started:
+
+# 1. Add your Datadog API (DD_API_KEY) and Application Key (DD_APP_KEY) as secrets to your GitHub repository. For more information, see: https://docs.datadoghq.com/account_management/api-app-keys/.
+# 2. Start using the action within your workflow
+
+name: Run Datadog Synthetic tests
+
+on:
+ push:
+ branches: [ "master" ]
+ pull_request:
+ branches: [ "master" ]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ # Run Synthetic tests within your GitHub workflow.
+ # For additional configuration options visit the action within the marketplace: https://github.com/marketplace/actions/datadog-synthetics-ci
+ - name: Run Datadog Synthetic tests
+ uses: DataDog/synthetics-ci-github-action@87b505388a22005bb8013481e3f73a367b9a53eb # v1.4.0
+ with:
+ api_key: ${{secrets.DD_API_KEY}}
+ app_key: ${{secrets.DD_APP_KEY}}
+ test_search_query: 'tag:e2e-tests' #Modify this tag to suit your tagging strategy
+
+
diff --git a/.github/workflows/lint_python.yml b/.github/workflows/lint_python.yml
index 4fbba44f38d..b90bd664f4a 100644
--- a/.github/workflows/lint_python.yml
+++ b/.github/workflows/lint_python.yml
@@ -1,4 +1,4 @@
-name: lint_python
+name: python
on: [pull_request, push]
jobs:
lint_python:
diff --git a/.gitignore b/.gitignore
index e2cee02848f..0f3717818e6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,7 @@ for i in string:
odd+=i
print(lower+upper+odd+even)
+.venv
# operating system-related files
# file properties cache/storage on macOS
@@ -23,3 +24,4 @@ print(lower+upper+odd+even)
# thumbnail cache on Windows
Thumbs.db
+bankmanaging.db
\ No newline at end of file
diff --git a/1 File handle/File handle binary/Deleting record in a binary file.py b/1 File handle/File handle binary/Deleting record in a binary file.py
index dca55c2d140..d3922a5afc4 100644
--- a/1 File handle/File handle binary/Deleting record in a binary file.py
+++ b/1 File handle/File handle binary/Deleting record in a binary file.py
@@ -3,18 +3,14 @@
def bdelete():
# Opening a file & loading it
- with open("studrec.dat") as F:
+ with open("studrec.dat","rb") as F:
stud = pickle.load(F)
print(stud)
# Deleting the Roll no. entered by user
rno = int(input("Enter the Roll no. to be deleted: "))
- with open("studrec.dat") as F:
- rec = []
- for i in stud:
- if i[0] == rno:
- continue
- rec.append(i)
+ with open("studrec.dat","wb") as F:
+ rec = [i for i in stud if i[0] != rno]
pickle.dump(rec, F)
diff --git a/1 File handle/File handle binary/File handle binary read (record in non list form).py b/1 File handle/File handle binary/File handle binary read (record in non list form).py
index f37d97f0bff..bb9f127ea0b 100644
--- a/1 File handle/File handle binary/File handle binary read (record in non list form).py
+++ b/1 File handle/File handle binary/File handle binary read (record in non list form).py
@@ -2,7 +2,7 @@
def binary_read():
- with open("studrec.dat") as b:
+ with open("studrec.dat","rb") as b:
stud = pickle.load(b)
print(stud)
diff --git a/1 File handle/File handle binary/Update a binary file.py b/1 File handle/File handle binary/Update a binary file.py
index 19f16b955da..b72154345ae 100644
--- a/1 File handle/File handle binary/Update a binary file.py
+++ b/1 File handle/File handle binary/Update a binary file.py
@@ -4,30 +4,27 @@
def update():
- F = open("class.dat", "rb+")
- S = pickle.load(F)
- found = 0
- rno = int(input("enter the roll number you want to update"))
- for i in S:
- if rno == i[0]:
- print("the currrent name is", i[1])
- i[1] = input("enter the new name")
- found = 1
- break
+ with open("class.dat", "rb+") as F:
+ S = pickle.load(F)
+ found = False
+ rno = int(input("enter the roll number you want to update"))
- if found == 0:
- print("Record not found")
+ for i in S:
+ if rno == i[0]:
+ print(f"the currrent name is {i[1]}")
+ i[1] = input("enter the new name")
+ found = True
+ break
- else:
- F.seek(0)
- pickle.dump(S, F)
+ if found:
+ print("Record not found")
- F.close()
+ else:
+ F.seek(0)
+ pickle.dump(S, F)
update()
-F = open("class.dat", "rb")
-val = pickle.load(F)
-print(val)
-F.close()
+with open("class.dat", "rb") as F:
+ print(pickle.load(F))
diff --git a/1 File handle/File handle binary/Update a binary file2.py b/1 File handle/File handle binary/Update a binary file2.py
index 38925dc6332..88adeef443f 100644
--- a/1 File handle/File handle binary/Update a binary file2.py
+++ b/1 File handle/File handle binary/Update a binary file2.py
@@ -1,31 +1,30 @@
-# updating records in a bnary file
+# updating records in a binary file
import pickle
def update():
- File = open("studrec.dat", "rb+")
- value = pickle.load(File)
- found = 0
- roll = int(input("Enter the roll number of the record"))
- for i in value:
- if roll == i[0]:
- print("current name", i[1])
- print("current marks", i[2])
- i[1] = input("Enter the new name")
- i[2] = int(input("Enter the new marks"))
- found = 1
-
- if found == 0:
- print("Record not found")
-
- else:
- pickle.dump(value, File)
- File.seek(0)
- newval = pickle.load(File)
- print(newval)
-
- File.close()
+
+ with open("studrec.dat", "rb+") as File:
+ value = pickle.load(File)
+ found = False
+ roll = int(input("Enter the roll number of the record"))
+
+ for i in value:
+ if roll == i[0]:
+ print(f"current name {i[1]}")
+ print(f"current marks {i[2]}")
+ i[1] = input("Enter the new name")
+ i[2] = int(input("Enter the new marks"))
+ found = True
+
+ if not found:
+ print("Record not found")
+
+ else:
+ pickle.dump(value, File)
+ File.seek(0)
+ print(pickle.load(File))
update()
diff --git a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py
index 08ac16f3e32..bf84e9824ec 100644
--- a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py
+++ b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py
@@ -12,7 +12,6 @@
import pickle
-F = open("class.dat", "ab")
list = [
[1, "Ramya", 30],
[2, "vaishnavi", 60],
@@ -24,54 +23,46 @@
[8, "sandhya", 65],
]
-
-pickle.dump(list, F)
-F.close()
+with open("class.dat", "ab") as F:
+ pickle.dump(list, F)
+ F.close()
def remcount():
- F = open("class.dat", "rb")
- val = pickle.load(F)
- count = 0
+ with open("class.dat", "rb") as F:
+ val = pickle.load(F)
+ count = 0
- for i in val:
- if i[2] <= 40:
- print(i, "eligible for remedial")
- count += 1
- print("the total number of students are", count)
- F.close()
+ for i in val:
+ if i[2] <= 40:
+ print(f"{i} eligible for remedial")
+ count += 1
+ print(f"the total number of students are {count}")
remcount()
def firstmark():
- F = open("class.dat", "rb")
- val = pickle.load(F)
- main = []
- count = 0
-
- for i in val:
- data = i[2]
- main.append(data)
+ with open("class.dat", "rb") as F:
+ val = pickle.load(F)
+ count = 0
+ main = [i[2] for i in val]
- top = max(main)
- print(top, "is the first mark")
+ top = max(main)
+ print(top, "is the first mark")
- F.seek(0)
- for i in val:
- if top == i[2]:
- print(i)
- print("congrats")
- count += 1
+ F.seek(0)
+ for i in val:
+ if top == i[2]:
+ print(f"{i}\ncongrats")
+ count += 1
- print("the total number of students who secured top marks are", count)
- F.close()
+ print("the total number of students who secured top marks are", count)
firstmark()
-F = open("class.dat", "rb")
-val = pickle.load(F)
-print(val)
-F.close()
+with open("class.dat", "rb") as F:
+ val = pickle.load(F)
+ print(val)
diff --git a/1 File handle/File handle binary/search record in binary file.py b/1 File handle/File handle binary/search record in binary file.py
index fd58d246bb9..80d2071134e 100644
--- a/1 File handle/File handle binary/search record in binary file.py
+++ b/1 File handle/File handle binary/search record in binary file.py
@@ -4,21 +4,18 @@
def binary_search():
- F = open("studrec.dat", "rb")
- # your file path will be different
- value = pickle.load(F)
- search = 0
- rno = int(input("Enter the roll number of the student"))
+ with open("studrec.dat", "rb") as F:
+ # your file path will be different
+ search = 0
+ rno = int(input("Enter the roll number of the student"))
- for i in value:
- if i[0] == rno:
- print("Record found successfully")
- print(i)
- search = 1
+ for i in pickle.load(F):
+ if i[0] == rno:
+ print(f"Record found successfully\n{i}")
+ search = 1
- if search == 0:
- print("Sorry! record not found")
- F.close()
+ if search == 0:
+ print("Sorry! record not found")
binary_search()
diff --git a/1 File handle/File handle text/counter.py b/1 File handle/File handle text/counter.py
new file mode 100644
index 00000000000..1019eeacae8
--- /dev/null
+++ b/1 File handle/File handle text/counter.py
@@ -0,0 +1,35 @@
+"""
+ Class resposible for counting words for different files:
+ - Reduce redundant code
+ - Easier code management/debugging
+ - Code readability
+"""
+
+class Counter:
+
+ def __init__(self, text:str) -> None:
+ self.text = text
+
+ # Define the initial count of the lower and upper case.
+ self.count_lower = 0
+ self.count_upper = 0
+ self.count()
+
+ def count(self) -> None:
+
+ for char in self.text:
+ if char.lower():
+ self.count_lower += 1
+ elif char.upper():
+ self.count_upper += 1
+
+ return (self.count_lower, self.count_upper)
+
+ def get_total_lower(self) -> int:
+ return self.count_lower
+
+ def get_total_upper(self) -> int:
+ return self.count_upper
+
+ def get_total(self) -> int:
+ return self.count_lower + self.count_upper
\ No newline at end of file
diff --git a/1 File handle/File handle text/file handle 12 length of line in text file.py b/1 File handle/File handle text/file handle 12 length of line in text file.py
index 7666668310d..d14ef16a4ea 100644
--- a/1 File handle/File handle text/file handle 12 length of line in text file.py
+++ b/1 File handle/File handle text/file handle 12 length of line in text file.py
@@ -9,28 +9,28 @@ def write_to_file(file_name):
if os.path.exists(file_name):
print(f"Error: {file_name} already exists.")
+ return
- else:
- with open(file_name, "a") as F:
- while True:
- text = input("enter any text to add in the file:- ")
- F.write(
- text + "\n"
- ) # write function takes exactly 1 arguement so concatenation
- choice = input("Do you want to enter more, y/n")
- if choice == "n":
- break
-
+ with open(file_name, "a") as F:
+
+ while True:
+ text = input("enter any text to add in the file:- ")
+ F.write( f"{text}\n" )
+ choice = input("Do you want to enter more, y/n").lower()
+ if choice == "n":
+ break
+
def longlines():
+
with open(file_name, encoding='utf-8') as F:
lines = F.readlines()
+ lines_less_than_50 = list( filter(lambda line: len(line) < 50, lines ) )
- for i in lines:
- if len(i) < 50:
+ if not lines_less_than_50:
+ print("There is no line which is less than 50")
+ else:
+ for i in lines_less_than_50:
print(i, end="\t")
- else:
- print("There is no line which is less than 50 ")
-
if __name__ == "__main__":
write_to_file(file_name)
diff --git a/1 File handle/File handle text/question 2.py b/1 File handle/File handle text/question 2.py
index c5f49454b2e..cbb84fcd13f 100644
--- a/1 File handle/File handle text/question 2.py
+++ b/1 File handle/File handle text/question 2.py
@@ -8,17 +8,15 @@
def display_words(file_path):
-
try:
- with open(file_path, 'r') as F:
- lines = F.read()
- words = lines.split()
- count = 0
- for word in words:
- if (len(word) < 4):
- print(word)
- count += 1
- return "The total number of the word's count which has less than 4 characters", (count)
+ with open(file_path) as F:
+ words = F.read().split()
+ words_less_than_40 = list( filter(lambda word: len(word) < 4, words) )
+
+ for word in words_less_than_40:
+ print(word)
+
+ return "The total number of the word's count which has less than 4 characters", (len(words_less_than_40))
except FileNotFoundError:
print("File not found")
diff --git a/1 File handle/File handle text/question 5.py b/1 File handle/File handle text/question 5.py
index 795433266aa..864520df4cd 100644
--- a/1 File handle/File handle text/question 5.py
+++ b/1 File handle/File handle text/question 5.py
@@ -1,8 +1,8 @@
"""Write a function in python to count the number of lowercase
alphabets present in a text file “happy.txt"""
-import time
-import os
+import time, os
+from counter import Counter
print("You will see the count of lowercase, uppercase and total count of alphabets in provided file..")
@@ -16,30 +16,15 @@
def lowercase(file_path):
try:
- with open(file_path, 'r') as F:
- # Define the initial count of the lower and upper case.
- lowercase_count = 0
- uppercase_count = 0
-
- value = F.read()
-
- for i in value:
- if i.islower():
- # It will increase the count.
- lowercase_count += 1
- elif i.isupper():
- uppercase_count += 1
-
-
-
- total_count = lowercase_count+uppercase_count
+ with open(file_path) as F:
+ word_counter = Counter(F.read())
- print("The total number of lower case letters are", lowercase_count)
- time.sleep(1)
- print("The total number of upper case letters are", uppercase_count)
- time.sleep(1)
- print("The total number of letters are", total_count)
- time.sleep(1)
+ print(f"The total number of lower case letters are {word_counter.get_total_lower()}")
+ time.sleep(0.5)
+ print(f"The total number of upper case letters are {word_counter.get_total_upper()}")
+ time.sleep(0.5)
+ print(f"The total number of letters are {word_counter.get_total()}")
+ time.sleep(0.5)
except FileNotFoundError:
print("File is not exist.. Please check AGAIN")
diff --git a/1 File handle/File handle text/question 6.py b/1 File handle/File handle text/question 6.py
index b41373135cf..467ea401995 100644
--- a/1 File handle/File handle text/question 6.py
+++ b/1 File handle/File handle text/question 6.py
@@ -1,20 +1,16 @@
"""Write a function in python to count the number of lowercase
-alphabets present in a text file “happy.txt"""
+alphabets present in a text file “happy.txt”"""
+from counter import Counter
def lowercase():
+
with open("happy.txt") as F:
- count_lower = 0
- count_upper = 0
- value = F.read()
- for i in value:
- if i.islower():
- count_lower += 1
- elif i.isupper():
- count_upper += 1
- print("The total number of lower case letters are", count_lower)
- print("The total number of upper case letters are", count_upper)
- print("The total number of letters are", count_lower + count_upper)
+ word_counter = Counter(F.read())
+
+ print(f"The total number of lower case letters are {word_counter.get_total_lower()}")
+ print(f"The total number of upper case letters are {word_counter.get_total_upper()}")
+ print(f"The total number of letters are {word_counter.get_total()}")
if __name__ == "__main__":
lowercase()
diff --git a/1 File handle/File handle text/question3.py b/1 File handle/File handle text/question3.py
index 713dc7f917a..bc05c22561d 100644
--- a/1 File handle/File handle text/question3.py
+++ b/1 File handle/File handle text/question3.py
@@ -18,28 +18,26 @@ def write_to_file(file_name):
else:
with open(file_name, "a") as F:
+
while True:
text = input("enter any text")
- F.write(
- text + "\n"
- ) # write function takes exactly 1 arguement so concatenation
- choice = input("do you want to enter more, y/n")
- if choice == "n":
+ F.write(f"{text}\n")
+
+ if input("do you want to enter more, y/n").lower() == "n":
break
-# write_to_file()
-
# step2:
def check_first_letter():
with open(file_name) as F:
- value = F.read()
- count = 0
- line = value.split()
- for i in line:
- if i[0] in ["m", "M", "i", "I"]:
- count += 1
- print(i)
- print("The total number of sentences starting with I or M are", count)
+ lines = F.read().split()
+
+ # store all starting letters from each line in one string after converting to lower case
+ first_letters = "".join([line[0].lower() for line in lines])
+
+ count_i = first_letters.count("i")
+ count_m = first_letters.count("m")
+
+ print(f"The total number of sentences starting with I or M are {count_i + count_m}")
if __name__ == "__main__":
diff --git a/1 File handle/File handle text/special symbol after word.py b/1 File handle/File handle text/special symbol after word.py
index 353a98cca87..1e23af6bddb 100644
--- a/1 File handle/File handle text/special symbol after word.py
+++ b/1 File handle/File handle text/special symbol after word.py
@@ -1,16 +1,11 @@
-F = open("happy.txt", "r")
-# method 1
-val = F.read()
-val = val.split()
-for i in val:
- print(i, "*", end="")
-print("\n")
+with open("happy.txt", "r") as F:
+ # method 1
+ for i in F.read().split():
+ print(i, "*", end="")
+ print("\n")
-
-# method 2
-F.seek(0)
-value = F.readlines()
-for line in value:
- for word in line.split():
- print(word, "*", end="")
-F.close()
+ # method 2
+ F.seek(0)
+ for line in F.readlines():
+ for word in line.split():
+ print(word, "*", end="")
diff --git a/12.py b/12.py
deleted file mode 100644
index 4d84bb24359..00000000000
--- a/12.py
+++ /dev/null
@@ -1,5 +0,0 @@
-import turtle
-t = turtle.Turtle()
-t.circle(20)
-t1=turtle.Turtle()
-t1.circle(25)
diff --git a/56 b/56
deleted file mode 100644
index 2f93feb9918..00000000000
--- a/56
+++ /dev/null
@@ -1,3 +0,0 @@
-import turtle
-t = turtle.Turtle()
-t.circle(50)
diff --git a/8_puzzle.py b/8_puzzle.py
new file mode 100644
index 00000000000..630cc12dd21
--- /dev/null
+++ b/8_puzzle.py
@@ -0,0 +1,92 @@
+from queue import PriorityQueue
+
+class PuzzleState:
+ def __init__(self, board, goal, moves=0, previous=None):
+ self.board = board
+ self.goal = goal
+ self.moves = moves
+ self.previous = previous
+
+ def __lt__(self, other):
+ return self.priority() < other.priority()
+
+ def priority(self):
+ return self.moves + self.manhattan()
+
+ def manhattan(self):
+ distance = 0
+ for i in range(3):
+ for j in range(3):
+ if self.board[i][j] != 0:
+ x, y = divmod(self.board[i][j] - 1, 3)
+ distance += abs(x - i) + abs(y - j)
+ return distance
+
+ def is_goal(self):
+ return self.board == self.goal
+
+ def neighbors(self):
+ neighbors = []
+ x, y = next((i, j) for i in range(3) for j in range(3) if self.board[i][j] == 0)
+ directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
+
+ for dx, dy in directions:
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < 3 and 0 <= ny < 3:
+ new_board = [row[:] for row in self.board]
+ new_board[x][y], new_board[nx][ny] = new_board[nx][ny], new_board[x][y]
+ neighbors.append(PuzzleState(new_board, self.goal, self.moves + 1, self))
+
+ return neighbors
+
+def solve_puzzle(initial_board, goal_board):
+ initial_state = PuzzleState(initial_board, goal_board)
+ frontier = PriorityQueue()
+ frontier.put(initial_state)
+ explored = set()
+
+ while not frontier.empty():
+ current_state = frontier.get()
+
+ if current_state.is_goal():
+ return current_state
+
+ explored.add(tuple(map(tuple, current_state.board)))
+
+ for neighbor in current_state.neighbors():
+ if tuple(map(tuple, neighbor.board)) not in explored:
+ frontier.put(neighbor)
+
+ return None
+
+def print_solution(solution):
+ steps = []
+ while solution:
+ steps.append(solution.board)
+ solution = solution.previous
+ steps.reverse()
+
+ for step in steps:
+ for row in step:
+ print(' '.join(map(str, row)))
+ print()
+
+# Example usage
+initial_board = [
+ [1, 2, 3],
+ [4, 0, 5],
+ [7, 8, 6]
+]
+
+goal_board = [
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 0]
+]
+
+solution = solve_puzzle(initial_board, goal_board)
+if solution:
+ print("Solution found:")
+ print_solution(solution)
+else:
+ print("No solution found.")
diff --git a/AI Game/Tic-Tac-Toe-AI/tic tac b/AI Game/Tic-Tac-Toe-AI/tic tac
new file mode 100644
index 00000000000..47a950ff8bf
--- /dev/null
+++ b/AI Game/Tic-Tac-Toe-AI/tic tac
@@ -0,0 +1 @@
+hii
diff --git a/AI Game/Tic-Tac-Toe-AI/tictactoe.py b/AI Game/Tic-Tac-Toe-AI/tictactoe.py
new file mode 100644
index 00000000000..0cd5bd0dc36
--- /dev/null
+++ b/AI Game/Tic-Tac-Toe-AI/tictactoe.py
@@ -0,0 +1,104 @@
+from tkinter import messagebox #provides a different set of dialogues that are used to display message boxes
+import customtkinter as ctk
+import customtkinter as messagebox
+def check_winner(board, player):
+ # Check rows, columns, and diagonals for a win
+ for i in range(3):
+ if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
+ return True
+ if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
+ return True
+ return False
+
+def is_board_full(board):
+ return all(all(cell != ' ' for cell in row) for row in board)
+
+def minimax(board, depth, is_maximizing):
+ if check_winner(board, 'X'):
+ return -1
+ if check_winner(board, 'O'):
+ return 1
+ if is_board_full(board):
+ return 0
+
+ if is_maximizing: #recursive approach that fills board with Os
+ max_eval = float('-inf')
+ for i in range(3):
+ for j in range(3):
+ if board[i][j] == ' ':
+ board[i][j] = 'O'
+ eval = minimax(board, depth + 1, False) #recursion
+ board[i][j] = ' '
+ max_eval = max(max_eval, eval)
+ return max_eval
+ else: #recursive approach that fills board with Xs
+ min_eval = float('inf')
+ for i in range(3):
+ for j in range(3):
+ if board[i][j] == ' ':
+ board[i][j] = 'X'
+ eval = minimax(board, depth + 1, True) #recursion
+ board[i][j] = ' '
+ min_eval = min(min_eval, eval)
+ return min_eval
+
+#determines the best move for the current player and returns a tuple representing the position
+def best_move(board):
+ best_val = float('-inf')
+ best_move = None
+
+ for i in range(3):
+ for j in range(3):
+ if board[i][j] == ' ':
+ board[i][j] = 'O'
+ move_val = minimax(board, 0, False)
+ board[i][j] = ' '
+ if move_val > best_val:
+ best_val = move_val
+ best_move = (i, j)
+
+ return best_move
+
+def make_move(row, col):
+ if board[row][col] == ' ':
+ board[row][col] = 'X'
+ # in tk we use the config but in customtkinter we use configure for
+ buttons[row][col].configure(text='X')
+ if check_winner(board, 'X'):
+ messagebox.showinfo("Tic-Tac-Toe", "You win!")
+ root.quit()
+ elif is_board_full(board):
+ messagebox.showinfo("Tic-Tac-Toe", "It's a draw!")
+ root.quit()
+ else:
+ ai_move()
+ else:
+ messagebox.showerror("Error", "Invalid move")
+
+#AI's turn to play
+def ai_move():
+ row, col = best_move(board)
+ board[row][col] = 'O'
+ buttons[row][col].configure(text='O')
+ if check_winner(board, 'O'):
+ messagebox.showinfo("Tic-Tac-Toe", "AI wins!")
+ root.quit()
+ elif is_board_full(board):
+ messagebox.showinfo("Tic-Tac-Toe", "It's a draw!")
+ root.quit()
+# change old UI code to customtkinter UI
+root = ctk.CTk()
+root.title("Tic-Tac-Toe")
+
+board = [[' ' for _ in range(3)] for _ in range(3)]
+buttons = []
+
+for i in range(3):
+ row_buttons = []
+ for j in range(3):
+ button = ctk.CTkButton(root, text=' ', font=('normal', 30), width=100, height=100, command=lambda row=i, col=j: make_move(row, col))
+ button.grid(row=i, column=j, padx=2, pady=2)
+ row_buttons.append(button)
+ buttons.append(row_buttons)
+
+root.mainloop()
diff --git a/Add two numbers.py b/Add two numbers.py
deleted file mode 100644
index 5a95f11e3bc..00000000000
--- a/Add two numbers.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# User pick two numbers to sum
-
-num1 = float(input("Number 1:"))
-num2 = float(input("Number 2:"))
-
-# Add two numbers
-sum = num1 + num2
-
-# Display the sum
-print("The sum of"num1,'and'num2,'is',sum)
diff --git a/Addtion of two numbers.py b/Addtion of two numbers.py
deleted file mode 100644
index ffe570b7002..00000000000
--- a/Addtion of two numbers.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# Python3 program to add two numbers
-
-number1 = input("First number: ")
-number2 = input("\nSecond number: ")
-
-# Adding two numbers
-# User might also enter float numbers
-sum = float(number1) + float(number2)
-
-# Display the sum
-# will print value in float
-print("The sum of {0} and {1} is {2}".format(number1, number2, sum))
diff --git a/Anonymous_TextApp.py b/Anonymous_TextApp.py
new file mode 100644
index 00000000000..9b3f5052e88
--- /dev/null
+++ b/Anonymous_TextApp.py
@@ -0,0 +1,83 @@
+import tkinter as tk
+from PIL import Image, ImageTk
+from twilio.rest import Client
+
+window = tk.Tk()
+window.title("Anonymous_Text_App")
+window.geometry("800x750")
+
+# Define global variables
+body = ""
+to = ""
+
+def message():
+ global body, to
+ account_sid = 'Your_account_sid' # Your account sid
+ auth_token = 'Your_auth_token' # Your auth token
+ client = Client(account_sid, auth_token)
+ msg = client.messages.create(
+ from_='Twilio_number', # Twilio number
+ body=body,
+ to=to
+ )
+ print(msg.sid)
+ confirmation_label.config(text="Message Sent!")
+
+
+
+try:
+ # Load the background image
+ bg_img = Image.open(r"D:\Downloads\img2.png")
+
+ #Canvas widget
+ canvas = tk.Canvas(window, width=800, height=750)
+ canvas.pack(fill="both", expand=True)
+
+ # background image to the Canvas
+ bg_photo = ImageTk.PhotoImage(bg_img)
+ bg_image_id = canvas.create_image(0, 0, image=bg_photo, anchor="nw")
+ bg_image_id = canvas.create_image(550, 250, image=bg_photo, anchor="center")
+ bg_image_id = canvas.create_image(1100, 250, image=bg_photo, anchor="center")
+ bg_image_id = canvas.create_image(1250, 250, image=bg_photo, anchor="center")
+ bg_image_id = canvas.create_image(250, 750, image=bg_photo, anchor="center")
+ bg_image_id = canvas.create_image(850, 750, image=bg_photo, anchor="center")
+ bg_image_id = canvas.create_image(1300, 750, image=bg_photo, anchor="center")
+
+
+
+ # Foreground Image
+ img = Image.open(r"D:\Downloads\output-onlinepngtools.png")
+ photo = ImageTk.PhotoImage(img)
+ img_label = tk.Label(window, image=photo, anchor="w")
+ img_label.image = photo
+ img_label.place(x=10, y=20)
+
+ # Text for number input
+ canvas.create_text(1050, 300, text="Enter the number starting with +[country code]", font=("Poppins", 18, "bold"), fill="black", anchor="n")
+ text_field_number = tk.Entry(canvas, width=17, font=("Poppins", 25, "bold"), bg="#404040", fg="white", show="*")
+ canvas.create_window(1100, 350, window=text_field_number, anchor="n")
+
+ # Text for message input
+ canvas.create_text(1050, 450, text="Enter the Message", font=("Poppins", 18, "bold"), fill="black", anchor="n")
+ text_field_text = tk.Entry(canvas, width=17, font=("Poppins", 25, "bold"), bg="#404040", fg="white")
+ canvas.create_window(1100, 500, window=text_field_text, anchor="n")
+
+ # label for confirmation message
+ confirmation_label = tk.Label(window, text="", font=("Poppins", 16), fg="green")
+ canvas.create_window(1100, 600, window=confirmation_label, anchor="n")
+
+except Exception as e:
+ print(f"Error loading image: {e}")
+
+# Function to save input and send message
+def save_and_send():
+ global body, to
+ to = str(text_field_number.get())
+ body = str(text_field_text.get())
+ message()
+
+# Button to save input and send message
+save_button = tk.Button(window, text="Save and Send", command=save_and_send)
+canvas.create_window(1200, 550, window=save_button, anchor='n')
+
+window.mainloop()
\ No newline at end of file
diff --git a/Armstrong_number.py b/Armstrong_number.py
index be923c0bf35..59732994f81 100644
--- a/Armstrong_number.py
+++ b/Armstrong_number.py
@@ -1,21 +1,24 @@
-def is_armstrong_number(number):
- total = 0
+"""
+In number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong) or a plus perfect number),
+in a given number base b, is a number that is the total of its own digits each raised to the power of the number of digits.
+Source: https://en.wikipedia.org/wiki/Narcissistic_number
+NOTE:
+this scripts only works for number in base 10
+"""
- # find the sum of the cube of each digit
- temp = number
- while temp > 0:
- digit = temp % 10
- total += digit ** 3
- temp //= 10
+def is_armstrong_number(number:str):
+ total:int = 0
+ exp:int = len(number) #get the number of digits, this will determinate the exponent
+
+ digits:list[int] = []
+ for digit in number: digits.append(int(digit)) #get the single digits
+ for x in digits: total += x ** exp #get the power of each digit and sum it to the total
- # return the result
- if number == total:
- return True
+ # display the result
+ if int(number) == total:
+ print(number,"is an Armstrong number")
else:
- return False
+ print(number,"is not an Armstrong number")
-number = int(input("Enter the number: "))
-if is_armstrong_number(number):
- print(number,"is an Armstrong number")
-else:
- print(number,"is not an Armstrong number")
+number = input("Enter the number : ")
+is_armstrong_number(number)
diff --git a/Assembler/GUIDE.txt b/Assembler/GUIDE.txt
index ccb59b84cf7..fbf1b3822be 100644
--- a/Assembler/GUIDE.txt
+++ b/Assembler/GUIDE.txt
@@ -27,10 +27,10 @@ int 0x80
```
-* The first line move the number 56 into register ecx.
-* The second line subtract 10 from the ecx register.
+* The first line move the number 56 into register ecx.
+* The second line subtracts 10 from the ecx register.
* The third line move the number 4 into the eax register. This is for the print-function.
-* The fourt line call interrupt 0x80, thus the result will print onto console.
+* The fourth line call interrupt 0x80, thus the result will print onto console.
* The fifth line is a new line. This is important.
**Important: close each line with a newline!**
@@ -67,7 +67,7 @@ int 0x80
```
-**Important: The arithmetic commands (add, sub) works only with registers or constans.
+**Important: The arithmetic commands (add, sub) work only with registers or constants.
Therefore we must use the register ebx as a placeholder, above.**
@@ -79,12 +79,12 @@ Result of code, above.
### Comments available
-Comments begin with ; and ends with a newline.
-We noticed a comment, above.
+Comments begin with ; and end with a newline.
+We noticed a comment above.
### Push and Pop
-Sometimes we must save the content of a register, against losing of data.
+Sometimes we must save the content of a register, against losing data.
Therefor we use the push and pop command.
```
@@ -92,7 +92,7 @@ push eax
```
-This line will push the content of register eax onto the stack.
+This line will push the contents of register eax onto the stack.
```
pop ecx
@@ -109,7 +109,7 @@ pop [register]
### Jumps
-With the command **cmp** we can compare two register.
+With the command **cmp** we can compare two registers.
```
cmp r0, r1
@@ -119,7 +119,7 @@ jmp l2
```
Are the two register equal? The the command **je** is actively and jumps to label **l1**
-Otherwise the command **jmp** is actively and jumps to label **l2**
+Otherwise, the command **jmp** is actively and jumps to label **l2**
#### Labels
diff --git a/Assembler/README.md b/Assembler/README.md
index 25cbcafff5d..bb3f26d0f8f 100644
--- a/Assembler/README.md
+++ b/Assembler/README.md
@@ -1,3 +1,4 @@
+# hy your name
# Python-Assembler
# WE need A FREE T-SHIRT
This program is a simple assembler-like (intel-syntax) interpreter language. The program is written in python 3.
diff --git a/Assembler/assembler.py b/Assembler/assembler.py
index 24a6840c1d4..0acd48b1535 100644
--- a/Assembler/assembler.py
+++ b/Assembler/assembler.py
@@ -996,10 +996,13 @@ def parser():
if token.token in variables:
token.token = variables[token.token]
else:
- print("Error: undefine variable! --> " + token.token)
+ print(f"Error: Undefined variable {token.token}")
return
+
elif token.t == "string":
- pass
+
+ token.token = str(token.token)
+
elif isinstance(token.token, float):
pass
elif token.token.isdigit():
@@ -1161,7 +1164,7 @@ def parser():
zeroFlag = False
elif tmpToken.token == "ebx":
ebx -= token.token
-
+
# update zero flag
if ebx == 0:
zeroFlag = True
@@ -1249,6 +1252,9 @@ def parser():
# pop register from stack
match token.token:
case "eax":
+ if len(stack) == 0:
+ print("Error: Stack Underflow")
+ return
eax = stack.pop()
case "ebx":
ebx = stack.pop()
@@ -1454,6 +1460,9 @@ def parser():
eax /= eax
case "ebx":
+ if ebx == 0:
+ print("Error: Division by Zero")
+ return
eax /= ebx
case "ecx":
diff --git a/Assembler/examples/klmn b/Assembler/examples/klmn
new file mode 100644
index 00000000000..9c16fab3022
--- /dev/null
+++ b/Assembler/examples/klmn
@@ -0,0 +1,2 @@
+Assembler/examples/code2.txt
+hello world
diff --git a/AutoComplete_App/backend.py b/AutoComplete_App/backend.py
new file mode 100644
index 00000000000..47e1c7906d6
--- /dev/null
+++ b/AutoComplete_App/backend.py
@@ -0,0 +1,126 @@
+import sqlite3
+import json
+
+class AutoComplete:
+ """
+ It works by building a `WordMap` that stores words to word-follower-count
+ ----------------------------
+ e.g. To train the following statement:
+
+ It is not enough to just know how tools work and what they worth,
+ we have got to learn how to use them and to use them well.
+ And with all these new weapons in your arsenal, we would better
+ get those profits fired up
+
+ we create the following:
+ { It: {is:1}
+ is: {not:1}
+ not: {enough:1}
+ enough: {to:1}
+ to: {just:1, learn:1, use:2}
+ just: {know:1}
+ .
+ .
+ profits: {fired:1}
+ fired: {up:1}
+ }
+ so the word completion for "to" will be "use".
+ For optimization, we use another store `WordPrediction` to save the
+ predictions for each word
+ """
+
+ def __init__(self):
+ """
+ Returns - None
+ Input - None
+ ----------
+ - Initialize database. we use sqlite3
+ - Check if the tables exist, if not create them
+ - maintain a class level access to the database
+ connection object
+ """
+ self.conn = sqlite3.connect("autocompleteDB.sqlite3", autocommit=True)
+ cur = self.conn.cursor()
+ res = cur.execute("SELECT name FROM sqlite_master WHERE name='WordMap'")
+ tables_exist = res.fetchone()
+
+ if not tables_exist:
+ self.conn.execute("CREATE TABLE WordMap(name TEXT, value TEXT)")
+ self.conn.execute('CREATE TABLE WordPrediction (name TEXT, value TEXT)')
+ cur.execute("INSERT INTO WordMap VALUES (?, ?)", ("wordsmap", "{}",))
+ cur.execute("INSERT INTO WordPrediction VALUES (?, ?)", ("predictions", "{}",))
+
+ def train(self, sentence):
+ """
+ Returns - string
+ Input - str: a string of words called sentence
+ ----------
+ Trains the sentence. It does this by creating a map of
+ current words to next words and their counts for each
+ time the next word appears after the current word
+ - takes in the sentence and splits it into a list of words
+ - retrieves the word map and predictions map
+ - creates the word map and predictions map together
+ - saves word map and predictions map to the database
+ """
+ cur = self.conn.cursor()
+ words_list = sentence.split(" ")
+
+ words_map = cur.execute("SELECT value FROM WordMap WHERE name='wordsmap'").fetchone()[0]
+ words_map = json.loads(words_map)
+
+ predictions = cur.execute("SELECT value FROM WordPrediction WHERE name='predictions'").fetchone()[0]
+ predictions = json.loads(predictions)
+
+ for idx in range(len(words_list)-1):
+ curr_word, next_word = words_list[idx], words_list[idx+1]
+ if curr_word not in words_map:
+ words_map[curr_word] = {}
+ if next_word not in words_map[curr_word]:
+ words_map[curr_word][next_word] = 1
+ else:
+ words_map[curr_word][next_word] += 1
+
+ # checking the completion word against the next word
+ if curr_word not in predictions:
+ predictions[curr_word] = {
+ 'completion_word': next_word,
+ 'completion_count': 1
+ }
+ else:
+ if words_map[curr_word][next_word] > predictions[curr_word]['completion_count']:
+ predictions[curr_word]['completion_word'] = next_word
+ predictions[curr_word]['completion_count'] = words_map[curr_word][next_word]
+
+ words_map = json.dumps(words_map)
+ predictions = json.dumps(predictions)
+
+ cur.execute("UPDATE WordMap SET value = (?) WHERE name='wordsmap'", (words_map,))
+ cur.execute("UPDATE WordPrediction SET value = (?) WHERE name='predictions'", (predictions,))
+ return("training complete")
+
+ def predict(self, word):
+ """
+ Returns - string
+ Input - string
+ ----------
+ Returns the completion word of the input word
+ - takes in a word
+ - retrieves the predictions map
+ - returns the completion word of the input word
+ """
+ cur = self.conn.cursor()
+ predictions = cur.execute("SELECT value FROM WordPrediction WHERE name='predictions'").fetchone()[0]
+ predictions = json.loads(predictions)
+ completion_word = predictions[word.lower()]['completion_word']
+ return completion_word
+
+
+
+if __name__ == "__main__":
+ input_ = "It is not enough to just know how tools work and what they worth,\
+ we have got to learn how to use them and to use them well. And with\
+ all these new weapons in your arsenal, we would better get those profits fired up"
+ ac = AutoComplete()
+ ac.train(input_)
+ print(ac.predict("to"))
\ No newline at end of file
diff --git a/AutoComplete_App/frontend.py b/AutoComplete_App/frontend.py
new file mode 100644
index 00000000000..90e576e849e
--- /dev/null
+++ b/AutoComplete_App/frontend.py
@@ -0,0 +1,37 @@
+from tkinter import *
+from tkinter import messagebox
+import backend
+
+
+def train():
+ sentence = train_entry.get()
+ ac = backend.AutoComplete()
+ ac.train(sentence)
+
+def predict_word():
+ word = predict_word_entry.get()
+ ac = backend.AutoComplete()
+ print(ac.predict(word))
+
+if __name__ == "__main__":
+ root = Tk()
+ root.title("Input note")
+ root.geometry('300x300')
+
+ train_label = Label(root, text="Train")
+ train_label.pack()
+ train_entry = Entry(root)
+ train_entry.pack()
+
+ train_button = Button(root, text="train", command=train)
+ train_button.pack()
+
+ predict_word_label = Label(root, text="Input term to predict")
+ predict_word_label.pack()
+ predict_word_entry = Entry(root)
+ predict_word_entry.pack()
+
+ predict_button = Button(root, text="predict", command=predict_word)
+ predict_button.pack()
+
+ root.mainloop()
\ No newline at end of file
diff --git a/BlackJack_game/blackjack.py b/BlackJack_game/blackjack.py
index c1bc919e01c..275b0d7368d 100644
--- a/BlackJack_game/blackjack.py
+++ b/BlackJack_game/blackjack.py
@@ -1,7 +1,7 @@
# master
# master
# BLACK JACK - CASINO A GAME OF FORTUNE!!!
-from time import *
+from time import sleep
# BLACK JACK - CASINO
# PYTHON CODE BASE
@@ -118,4 +118,4 @@ def dealer_choice():
else:
dealer_choice()
- break
+ break
\ No newline at end of file
diff --git a/BrowserHistory/backend.py b/BrowserHistory/backend.py
new file mode 100644
index 00000000000..89df7a0da8b
--- /dev/null
+++ b/BrowserHistory/backend.py
@@ -0,0 +1,102 @@
+class DLL:
+ """
+ a doubly linked list that holds the current page,
+ next page, and previous page.
+ Used to enforce order in operations.
+ """
+ def __init__(self, val: str =None):
+ self.val = val
+ self.nxt = None
+ self.prev = None
+
+
+class BrowserHistory:
+ """
+ This class designs the operations of a browser history
+
+ It works by using a doubly linked list to hold the urls with optimized
+ navigation using step counters and memory management
+ """
+
+ def __init__(self, homepage: str):
+ """
+ Returns - None
+ Input - str
+ ----------
+ - Initialize doubly linked list which will serve as the
+ browser history and sets the current page
+ - Initialize navigation counters
+ """
+ self._head = DLL(homepage)
+ self._curr = self._head
+ self._back_count = 0
+ self._forward_count = 0
+
+ def visit(self, url: str) -> None:
+ """
+ Returns - None
+ Input - str
+ ----------
+ - Adds the current url to the DLL
+ - Sets both the next and previous values
+ - Cleans up forward history to prevent memory leaks
+ - Resets forward count and increments back count
+ """
+ # Clear forward history to prevent memory leaks
+ self._curr.nxt = None
+ self._forward_count = 0
+
+ # Create and link new node
+ url_node = DLL(url)
+ self._curr.nxt = url_node
+ url_node.prev = self._curr
+
+ # Update current node and counts
+ self._curr = url_node
+ self._back_count += 1
+
+ def back(self, steps: int) -> str:
+ """
+ Returns - str
+ Input - int
+ ----------
+ - Moves backwards through history up to available steps
+ - Updates navigation counters
+ - Returns current page URL
+ """
+ # Only traverse available nodes
+ steps = min(steps, self._back_count)
+ while steps > 0:
+ self._curr = self._curr.prev
+ steps -= 1
+ self._back_count -= 1
+ self._forward_count += 1
+ return self._curr.val
+
+ def forward(self, steps: int) -> str:
+ """
+ Returns - str
+ Input - int
+ ----------
+ - Moves forward through history up to available steps
+ - Updates navigation counters
+ - Returns current page URL
+ """
+ # Only traverse available nodes
+ steps = min(steps, self._forward_count)
+ while steps > 0:
+ self._curr = self._curr.nxt
+ steps -= 1
+ self._forward_count -= 1
+ self._back_count += 1
+ return self._curr.val
+
+
+if __name__ == "__main__":
+ obj = BrowserHistory("google.com")
+ obj.visit("twitter.com")
+ param_2 = obj.back(1)
+ param_3 = obj.forward(1)
+
+ print(param_2)
+ print(param_3)
diff --git a/BrowserHistory/tests/test_browser_history.py b/BrowserHistory/tests/test_browser_history.py
new file mode 100644
index 00000000000..829f326c238
--- /dev/null
+++ b/BrowserHistory/tests/test_browser_history.py
@@ -0,0 +1,91 @@
+import unittest
+import sys
+import os
+
+# Add parent directory to path to import backend
+sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+from backend import BrowserHistory
+
+class TestBrowserHistory(unittest.TestCase):
+ def setUp(self):
+ """Set up test cases"""
+ self.browser = BrowserHistory("homepage.com")
+
+ def test_initialization(self):
+ """Test proper initialization of BrowserHistory"""
+ self.assertEqual(self.browser._curr.val, "homepage.com")
+ self.assertEqual(self.browser._back_count, 0)
+ self.assertEqual(self.browser._forward_count, 0)
+ self.assertIsNone(self.browser._curr.nxt)
+ self.assertIsNone(self.browser._curr.prev)
+
+ def test_visit(self):
+ """Test visit functionality and forward history cleanup"""
+ self.browser.visit("page1.com")
+ self.assertEqual(self.browser._curr.val, "page1.com")
+ self.assertEqual(self.browser._back_count, 1)
+ self.assertEqual(self.browser._forward_count, 0)
+
+ # Test forward history cleanup
+ self.browser.visit("page2.com")
+ self.browser.back(1)
+ self.browser.visit("page3.com") # Should clear forward history
+ self.assertIsNone(self.browser._curr.nxt)
+ self.assertEqual(self.browser._forward_count, 0)
+
+ def test_back_navigation(self):
+ """Test back navigation with counter validation"""
+ # Setup history
+ self.browser.visit("page1.com")
+ self.browser.visit("page2.com")
+
+ # Test normal back navigation
+ result = self.browser.back(1)
+ self.assertEqual(result, "page1.com")
+ self.assertEqual(self.browser._back_count, 1)
+ self.assertEqual(self.browser._forward_count, 1)
+
+ # Test back with more steps than available
+ result = self.browser.back(5) # Should only go back 1 step
+ self.assertEqual(result, "homepage.com")
+ self.assertEqual(self.browser._back_count, 0)
+ self.assertEqual(self.browser._forward_count, 2)
+
+ def test_forward_navigation(self):
+ """Test forward navigation with counter validation"""
+ # Setup history and position
+ self.browser.visit("page1.com")
+ self.browser.visit("page2.com")
+ self.browser.back(2) # Go back to homepage
+
+ # Test normal forward navigation
+ result = self.browser.forward(1)
+ self.assertEqual(result, "page1.com")
+ self.assertEqual(self.browser._forward_count, 1)
+ self.assertEqual(self.browser._back_count, 1)
+
+ # Test forward with more steps than available
+ result = self.browser.forward(5) # Should only go forward remaining 1 step
+ self.assertEqual(result, "page2.com")
+ self.assertEqual(self.browser._forward_count, 0)
+ self.assertEqual(self.browser._back_count, 2)
+
+ def test_complex_navigation(self):
+ """Test complex navigation patterns"""
+ self.browser.visit("page1.com")
+ self.browser.visit("page2.com")
+ self.browser.visit("page3.com")
+
+ # Back navigation
+ self.assertEqual(self.browser.back(2), "page1.com")
+
+ # New visit should clear forward history
+ self.browser.visit("page4.com")
+ self.assertEqual(self.browser._forward_count, 0)
+ self.assertIsNone(self.browser._curr.nxt)
+
+ # Verify we can't go forward to cleared history
+ self.assertEqual(self.browser.forward(1), "page4.com")
+
+if __name__ == '__main__':
+ unittest.main()
\ No newline at end of file
diff --git a/BruteForce.py b/BruteForce.py
index 0df67e43dff..46b17844e26 100644
--- a/BruteForce.py
+++ b/BruteForce.py
@@ -4,8 +4,8 @@
def findPassword(chars, function, show=50, format_="%s"):
password = None
- attempts = 00
- size = 01
+ attempts = 0
+ size = 1
stop = False
while not stop:
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index fdb17afd1db..1ce6863533c 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -1,4 +1,4 @@
-# Contributor Covenant Code of Conduct
+# Contributor Covenant Code of Conduct Easy to understand
## Our Pledge
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9f1ab7baf14..24cde27bebc 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,4 +1,4 @@
-# Contributing
+# Contributing Notepad Sorting
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
diff --git a/CSV_file.py b/CSV_file.py
new file mode 100644
index 00000000000..d67e23064c4
--- /dev/null
+++ b/CSV_file.py
@@ -0,0 +1,14 @@
+import pandas as pd
+
+# loading the dataset
+
+df= pd.read_csv(r"c:\PROJECT\Drug_Recommendation_System\drug_recommendation_system\Drugs_Review_Datasets.csv")
+
+print(df) #prints Dataset
+# funtions
+print(df.tail())
+print(df.head())
+print(df.info())
+print(df.describe())
+print(df.column)
+print(df.shape())
\ No newline at end of file
diff --git a/Caesar Cipher Encoder & Decoder.py b/Caesar Cipher Encoder & Decoder.py
index 7bd078e2849..63097b39e17 100644
--- a/Caesar Cipher Encoder & Decoder.py
+++ b/Caesar Cipher Encoder & Decoder.py
@@ -1,85 +1,67 @@
-#PROJECT1
-#CAESAR CIPHER DECODER
+# PROJECT1
+# CAESAR CIPHER ENCODER/DECODER
-#Author: InTruder
-#Cloned from: https://github.com/InTruder-Sec/caesar-cipher
+# Author: InTruder
+# Cloned from: https://github.com/InTruder-Sec/caesar-cipher
+# Improved by: OfficialAhmed (https://github.com/OfficialAhmed)
+
+def get_int() -> int:
+ """
+ Get integer, otherwise redo
+ """
+
+ try:
+ key = int(input("Enter number of characters you want to shift: "))
+ except:
+ print("Enter an integer")
+ key = get_int()
+
+ return key
def main():
+
print("[>] CAESAR CIPHER DECODER!!! \n")
print("[1] Encrypt\n[2] Decrypt")
- try:
- func = int(input("Choose one of the above(example for encode enter 1): "))
- except:
- print("\n[>] Invalid input")
- exit()
- if func == 2:
- decode()
- else:
- if func == 1:
+ match input("Choose one of the above(example for encode enter 1): "):
+
+ case "1":
encode()
- else:
- print("\n[>] Invalid input")
- exit()
+
+ case "2":
+ decode()
+
+ case _:
+ print("\n[>] Invalid input. Choose 1 or 2")
+ main()
+
def encode():
- text = input("Enter text to encode: ")
- key = input("Enter number of characters you want to shift: ")
+
encoded_cipher = ""
- try:
- key = int(key)
- except:
- print("Only intigers between 0 to 25 are allowed. Try again :)")
- exit()
- if key > 25:
- print("Only intigers between 0 to 25 are allowed. Try again :)")
- exit()
- else:
- key = key
- text = text.upper()
+ text = input("Enter text to encode: ")
+ key = get_int()
+
for char in text:
- ascii = ord(char)
- if ascii > 90:
- new_ascii = ascii
- else:
- if ascii < 65:
- new_ascii = ascii
- else:
- new_ascii = ascii + key
- if new_ascii > 90:
- new_ascii = new_ascii - 26
- else:
- new_ascii = new_ascii
- encoded = chr(new_ascii)
- encoded_cipher = encoded_cipher + encoded
- print("Encoded text: " + encoded_cipher)
+
+ ascii = ord(char) + key
+ encoded_cipher += chr(ascii)
+ print(f"Encoded text: {encoded_cipher}")
def decode():
+
+ decoded_cipher = ""
cipher = input("\n[>] Enter your cipher text: ")
- print("Posiblities of cipher text are: \n")
- cipher = cipher.lower()
- for i in range(1, 26):
- decoded = ""
- decoded_cipher = ""
- for char in cipher:
- ascii = ord(char)
- if ascii < 97:
- new_ascii = ascii
- else:
- if ascii > 122:
- new_ascii = ascii
- else:
- new_ascii = ascii - int(i)
- if new_ascii < 97:
- new_ascii = new_ascii + 26
- else:
- new_ascii = new_ascii
- decoded = chr(new_ascii)
- decoded_cipher = decoded_cipher + decoded
- print("\n" + decoded_cipher)
+ key = get_int()
+
+ for character in cipher:
+ ascii = ord(character) - key
+ decoded_cipher += chr(ascii)
+
+ print(decoded_cipher)
if __name__ == '__main__':
diff --git a/Calculate resistance.py b/Calculate resistance.py
index 10c7a5ad3e2..ee6f10319a1 100644
--- a/Calculate resistance.py
+++ b/Calculate resistance.py
@@ -1,12 +1,16 @@
-def res(R1, R2):
- sum = R1 + R2
- if (option =="series"):
- return sum
- else:
- return (R1 * R2)/(R1 + R2)
-Resistance1 = int(input("Enter R1 : "))
-Resistance2 = int(input("Enter R2 : "))
-option = str(input("Enter series or parallel :"))
-print("\n")
-R = res(Resistance1,Resistance2 )
-print("The total resistance is", R)
+def res(R1, R2):
+ sum = R1 + R2
+ if option =="series":
+ return sum
+ elif option =="parallel" :
+ return (R1 * R2)/sum
+ return 0
+Resistance1 = int(input("Enter R1 : "))
+Resistance2 = int(input("Enter R2 : "))
+option = input("Enter series or parallel :")
+print("\n")
+R = res(Resistance1,Resistance2 )
+if R==0:
+ print('Wrong Input!!' )
+else:
+ print("The total resistance is", R)
diff --git a/Calculator with simple ui.py b/Calculator with simple ui.py
index eb0a5b727a2..122156a3cfd 100644
--- a/Calculator with simple ui.py
+++ b/Calculator with simple ui.py
@@ -1,23 +1,73 @@
# Program make a simple calculator
-# This function adds two numbers
-def add(x, y):
- return x + y
-# This function subtracts two numbers
-def subtract(x, y):
- return x - y
+class Calculator:
+ def __init__(self):
+ pass
-# This function multiplies two numbers
-def multiply(x, y):
- return x * y
+ def add(self, num1, num2):
+ """
+ This function adds two numbers.
-# This function divides two numbers
-def divide(x, y):
- return x / y
+ Examples:
+ >>> add(2, 3)
+ 5
+ >>> add(5, 9)
+ 14
+ >>> add(-1, 2)
+ 1
+ """
+ return num1 + num2
+
+ def subtract(self, num1, num2):
+ """
+ This function subtracts two numbers.
+
+ Examples:
+ >>> subtract(5, 3)
+ 2
+ >>> subtract(9, 5)
+ 4
+ >>> subtract(4, 9)
+ -5
+ """
+ return num1 - num2
+
+ def multiply(self, num1, num2):
+ """
+ This function multiplies two numbers.
+
+ Examples:
+ >>> multiply(4, 2)
+ 8
+ >>> multiply(3, 3)
+ 9
+ >>> multiply(9, 9)
+ 81
+ """
+ return num1 * num2
+
+ def divide(self, num1, num2):
+ """
+ This function divides two numbers.
+
+ Examples:
+ >>> divide(4, 4)
+ 1
+ >>> divide(6, 3)
+ 2
+ >>> divide(9, 1)
+ 9
+ """
+ if num2 == 0:
+ print("Cannot divide by zero")
+ else:
+ return num1 / num2
+
+
+calculator = Calculator()
-print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
@@ -28,22 +78,21 @@ def divide(x, y):
choice = input("Enter choice(1/2/3/4): ")
# Check if choice is one of the four options
- if choice in ('1', '2', '3', '4'):
+ if choice in ("1", "2", "3", "4"):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
- if choice == '1':
- print(num1, "+", num2, "=", add(num1, num2))
+ if choice == "1":
+ print(calculator.add(num1, num2))
- elif choice == '2':
- print(num1, "-", num2, "=", subtract(num1, num2))
+ elif choice == "2":
+ print(calculator.subtract(num1, num2))
- elif choice == '3':
- print(num1, "*", num2, "=", multiply(num1, num2))
+ elif choice == "3":
+ print(calculator.multiply(num1, num2))
- elif choice == '4':
- print(num1, "/", num2, "=", divide(num1, num2))
+ elif choice == "4":
+ print(calculator.divide(num1, num2))
break
else:
print("Invalid Input")
-
diff --git a/Calendar (GUI) b/Calendar (GUI).py
similarity index 100%
rename from Calendar (GUI)
rename to Calendar (GUI).py
diff --git a/CliYoutubeDownloader/CliYoutubeDownloader.py b/CliYoutubeDownloader/CliYoutubeDownloader.py
index 81c35a81ad8..2af607ad5ae 100644
--- a/CliYoutubeDownloader/CliYoutubeDownloader.py
+++ b/CliYoutubeDownloader/CliYoutubeDownloader.py
@@ -1,12 +1,12 @@
# libraraies
-import pytube
+import pytubefix
import sys
class YouTubeDownloder:
def __init__(self):
- self.url = str(input("Enter the url of video : "))
+ self.url = str(input("Enter the URL of video : "))
self.youtube = pytube.YouTube(
self.url, on_progress_callback=YouTubeDownloder.onProgress
)
@@ -28,14 +28,14 @@ def showStreams(self):
self.chooseStream()
def chooseStream(self):
- self.choose = int(input("please select one : "))
+ self.choose = int(input("Please select one : "))
self.validateChooseValue()
def validateChooseValue(self):
if self.choose in range(1, self.streamNo):
self.getStream()
else:
- print("please enter a correct option on the list.")
+ print("Please enter a correct option on the list.")
self.chooseStream()
def getStream(self):
@@ -49,7 +49,7 @@ def getFileSize(self):
def getPermisionToContinue(self):
print(
- "\n title : {0} \n author : {1} \n size : {2:.2f}MB \n resolution : {3} \n fps : {4} \n ".format(
+ "\n Title : {0} \n Author : {1} \n Size : {2:.2f}MB \n Resolution : {3} \n FPS : {4} \n ".format(
self.youtube.title,
self.youtube.author,
file_size,
@@ -57,7 +57,7 @@ def getPermisionToContinue(self):
self.stream.fps,
)
)
- if input("do you want it ?(defualt = (y)es) or (n)o ") == "n":
+ if input("Do you want it ?(default = (y)es) or (n)o ") == "n":
self.showStreams()
else:
self.main()
@@ -69,7 +69,7 @@ def download(self):
def onProgress(stream=None, chunk=None, remaining=None):
file_downloaded = file_size - (remaining / 1000000)
print(
- f"downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]",
+ f"Downloading ... {file_downloaded/file_size*100:0.2f} % [{file_downloaded:.1f}MB of {file_size:.1f}MB]",
end="\r",
)
diff --git a/CliYoutubeDownloader/requirements.txt b/CliYoutubeDownloader/requirements.txt
index cd5e770101f..9a9d50658dc 100644
--- a/CliYoutubeDownloader/requirements.txt
+++ b/CliYoutubeDownloader/requirements.txt
@@ -1 +1 @@
-pytube
+pytubefix
diff --git a/Colors/multicoloredline.py b/Colors/multicoloredline.py
index 312e419289f..fdbe1c45881 100644
--- a/Colors/multicoloredline.py
+++ b/Colors/multicoloredline.py
@@ -1,8 +1,54 @@
-## This script prints a multicolored line
-# quo can be installed using pip
-
-from quo.console import Console
+from rich.console import Console
+from rich.syntax import Syntax
+from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn
+from rich.table import Table
+import time
+import json
console = Console()
-console.rule(multiclored=true)
+# Fancy separator
+console.rule("[bold]Welcome to Rich Terminal[/bold]", style="rainbow")
+
+# Define some JSON data
+json_data = {
+ "message": "Hello, World!",
+ "status": "success",
+ "code": 200
+}
+
+# Print JSON with syntax highlighting
+syntax = Syntax(json.dumps(json_data, indent=4), "json", theme="monokai", line_numbers=True)
+console.print(syntax)
+
+# Simulating a progress bar
+console.print("\n[bold cyan]Processing data...[/bold cyan]\n")
+
+with Progress(
+ SpinnerColumn(),
+ TextColumn("[progress.description]{task.description}"),
+ BarColumn(),
+ TextColumn("{task.percentage:>3.0f}%"),
+ console=console,
+) as progress:
+ task = progress.add_task("[cyan]Loading...", total=100)
+ for _ in range(100):
+ time.sleep(0.02)
+ progress.update(task, advance=1)
+
+# Create a rich table
+console.print("\n[bold magenta]Results Summary:[/bold magenta]\n")
+
+table = Table(title="System Report", show_header=True, header_style="bold cyan")
+table.add_column("Metric", style="bold yellow")
+table.add_column("Value", justify="right", style="bold green")
+
+table.add_row("CPU Usage", "12.5%")
+table.add_row("Memory Usage", "68.3%")
+table.add_row("Disk Space", "45.7% free")
+
+console.print(table)
+
+# Success message
+console.print("\n[bold green]🎉 Process completed successfully![/bold green]\n")
+console.rule(style="rainbow")
diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py
index 3c3c06ea616..920e034817f 100644
--- a/Colors/pixel_sort.py
+++ b/Colors/pixel_sort.py
@@ -43,7 +43,7 @@ def createDataSet(val=0, data=[]):
# Generating colors for each row of the frame
def generateColors(c_sorted, frame, row):
global df, img_list
- height = 25
+ height = 15
img = np.zeros((height, len(c_sorted), 3), np.uint8)
for x in range(0, len(c_sorted)):
r, g, b = c_sorted[x][0] * 255, c_sorted[x][1] * 255, c_sorted[x][2] * 255
diff --git a/Colors/print_colors.py b/Colors/print_colors.py
index edf78440a22..6aacaa9d4b4 100644
--- a/Colors/print_colors.py
+++ b/Colors/print_colors.py
@@ -1,6 +1,4 @@
import sys
-
-
class colors:
CYAN = "\033[36m"
GREEN = "\033[32m"
@@ -8,13 +6,8 @@ class colors:
BLUE = "\033[34m"
RED = "\033[31m"
ENDC = "\033[0m"
-
-
def printc(color, message):
print(color + message + colors.ENDC)
-
-
-# color which we print or import
printc(colors.CYAN, sys.argv[1])
printc(colors.GREEN, sys.argv[1])
printc(colors.YELLOW, sys.argv[1])
diff --git a/Count the Number of Each Vowel b/Count the Number of Each Vowel
deleted file mode 100644
index eaca619f7a4..00000000000
--- a/Count the Number of Each Vowel
+++ /dev/null
@@ -1,9 +0,0 @@
-vowels = 'aeiou'
-ip_str = 'Hello, have you tried our tutorial section yet?'
-count = 0
-
-for char in ip_str:
- if char in vowels:
- count += 1
-
-print(count)
diff --git a/Crack_password.py b/Crack_password.py
index b32af07afd6..6941b6236e5 100644
--- a/Crack_password.py
+++ b/Crack_password.py
@@ -1,11 +1,11 @@
from random import *
user_pass = input("Enter your password: ")
-password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v','w', 'x', 'y', 'z',]
+password = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't','u','v','w', 'x', 'y', 'z',"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
guess = ""
while (guess != user_pass):
guess = ""
for letter in range(len(user_pass)):
- guess_letter = password[randint(0, 25)]
+ guess_letter = password[randint(0, 51)]
guess = str(guess_letter) + str(guess)
print(guess)
print("Your password is",guess)
diff --git a/Eight_Puzzle_Solver/eight_puzzle.py b/Eight_Puzzle_Solver/eight_puzzle.py
deleted file mode 100644
index 703df00b3e6..00000000000
--- a/Eight_Puzzle_Solver/eight_puzzle.py
+++ /dev/null
@@ -1,457 +0,0 @@
-# import sys
-from collections import deque
-from copy import deepcopy
-from queue import PriorityQueue
-
-# import time
-# from collections import Counter
-
-
-class Node:
- def __init__(self, state, depth=0, moves=None, optimizer=0):
- """
- Parameters:
- state: State of Puzzle
- depth: Depth of State in Space Search Tree
- moves: Moves List to reach this state from initial state
- optimizer: Used for UCS Only
- 0 - Manhattan Distance
- 1 - Hamming Distance
- 2 - Combination of 0 and 1
-
- Returns: Node Object
- """
- self.state = state
- self.size = len(state)
- self.depth = depth
- self.optimizer = optimizer
- if moves is None:
- self.moves = list()
- else:
- self.moves = moves
-
- def getAvailableActions(self):
- """
- Parameters: Current State
- Returns: Available Actions for Current State
- 0 - Left 1 - Right 2 - Top 3 - Bottom
- Restrictions: state is self.size x self.size Array
- """
- action = list()
- for i in range(self.size):
- for j in range(self.size):
- if self.state[i][j] == 0:
- if i > 0:
- action.append(2)
- if j > 0:
- action.append(0)
- if i < self.size - 1:
- action.append(3)
- if j < self.size - 1:
- action.append(1)
- return action
- return action
-
- def getResultFromAction(self, action):
- """
- Parameters: Current State , Action
- Returns: Node with New State
- Restrictions: Action will always be valid and state is self.size x self.size Array
- """
- newstate = deepcopy(self.state)
- newMoves = deepcopy(self.moves)
- for i in range(self.size):
- for j in range(self.size):
- if newstate[i][j] == 0:
- if action == 2:
- newstate[i][j], newstate[i - 1][j] = (
- newstate[i - 1][j],
- newstate[i][j],
- )
- newMoves.append(2)
- return Node(
- newstate,
- depth=self.depth + 1,
- moves=newMoves,
- optimizer=self.optimizer,
- )
- if action == 3:
- newstate[i][j], newstate[i + 1][j] = (
- newstate[i + 1][j],
- newstate[i][j],
- )
- newMoves.append(3)
- return Node(
- newstate,
- depth=self.depth + 1,
- moves=newMoves,
- optimizer=self.optimizer,
- )
- if action == 0:
- newstate[i][j], newstate[i][j - 1] = (
- newstate[i][j - 1],
- newstate[i][j],
- )
- newMoves.append(0)
- return Node(
- newstate,
- depth=self.depth + 1,
- moves=newMoves,
- optimizer=self.optimizer,
- )
- if action == 1:
- newstate[i][j], newstate[i][j + 1] = (
- newstate[i][j + 1],
- newstate[i][j],
- )
- newMoves.append(1)
- return Node(
- newstate,
- depth=self.depth + 1,
- moves=newMoves,
- optimizer=self.optimizer,
- )
- return None
-
- def isGoalState(self):
- """
- Parameters: State
- Returns: True if Goal State, otherwise False
- Restrictions: State is self.size x self.size Array
- """
- for i in range(self.size):
- for j in range(self.size):
- if i == j and j == self.size - 1:
- continue
- if self.state[i][j] != (i) * self.size + (j + 1):
- return False
- return True
-
- def getManhattanDistance(self):
- """
- Parameters: State
- Returns: Manhattan Distance between Current State and Goal State
- Restrictions: State must be a self.size x self.size Array
- """
- ans = 0
- for i in range(self.size):
- for j in range(self.size):
- if self.state[i][j] != 0:
- ans = (
- ans
- + abs((self.state[i][j] - 1) % self.size - j)
- + abs((self.state[i][j] - 1) // self.size - i)
- )
-
- return ans
-
- def getHammingDistance(self):
- ans = 0
- for i in range(self.size):
- for j in range(self.size):
- if self.state[i][j] != 0 and self.state[i][j] != i * 3 + (j + 1):
- ans = ans + 1
- return ans
-
- def __hash__(self):
- flatState = [j for sub in self.state for j in sub]
- flatState = tuple(flatState)
- return hash(flatState)
-
- def __gt__(self, other):
- if self.optimizer == 0:
- if self.getManhattanDistance() > other.getManhattanDistance():
- return True
- else:
- return False
- elif self.optimizer == 1:
- if self.getHammingDistance() > other.getHammingDistance():
- return True
- else:
- return False
- elif self.optimizer == 2:
- if (
- self.getHammingDistance() + self.getManhattanDistance()
- > other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
- return True
-
- def __ge__(self, other):
- if self.optimizer == 0:
- if self.getManhattanDistance() >= other.getManhattanDistance():
- return True
- else:
- return False
- elif self.optimizer == 1:
- if self.getHammingDistance() >= other.getHammingDistance():
- return True
- else:
- return False
- elif self.optimizer == 2:
- if (
- self.getHammingDistance() + self.getManhattanDistance()
- >= other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
- return True
-
- def __lt__(self, other):
- if self.optimizer == 0:
- if self.getManhattanDistance() < other.getManhattanDistance():
- return True
- else:
- return False
- elif self.optimizer == 1:
- if self.getHammingDistance() < other.getHammingDistance():
- return True
- else:
- return False
- elif self.optimizer == 2:
- if (
- self.getHammingDistance() + self.getManhattanDistance()
- < other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
- return True
-
- def __le__(self, other):
- if self.optimizer == 0:
- if self.getManhattanDistance() <= other.getManhattanDistance():
- return True
- else:
- return False
- elif self.optimizer == 1:
- if self.getHammingDistance() <= other.getHammingDistance():
- return True
- else:
- return False
- elif self.optimizer == 2:
- if (
- self.getHammingDistance() + self.getManhattanDistance()
- <= other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
- return True
-
- def __eq__(self, other):
- if self.optimizer == 0:
- if self.getManhattanDistance() == other.getManhattanDistance():
- return True
- else:
- return False
- elif self.optimizer == 1:
- if self.getHammingDistance() == other.getHammingDistance():
- return True
- else:
- return False
- elif self.optimizer == 2:
- if (
- self.getHammingDistance() + self.getManhattanDistance()
- == other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
- return True
-
-
-class Solver:
- def __init__(self, state):
- self.state = state
-
- def isSolvable(self):
- """
- Parameters: State
- Returns: True if state is solvable, otherwise False
- """
- flatState = [j for sub in self.state for j in sub]
- inversions = 0
- for i in range(len(flatState) - 1):
- for j in range(i + 1, len(flatState)):
- if (
- flatState[i] != 0
- and flatState[j] != 0
- and flatState[i] > flatState[j]
- ):
- inversions = inversions + 1
- return inversions % 2 == 0
-
- def breadth_first_search(self):
- """
- Parameters: State
- Returns: List of Moves to solve the state, otherwise None if unsolvable
- """
- if self.isSolvable() == False:
- return (None, None)
-
- closed = list()
- q = deque()
- q.append(Node(state=self.state, depth=0))
- while q:
- node = q.popleft()
-
- if node.isGoalState():
- return (node.moves, len(closed))
- if node.state not in closed:
- closed.append(node.state)
- for action in node.getAvailableActions():
- q.append(node.getResultFromAction(action))
-
- return (None, None)
-
- def depth_first_search(self):
- """
- Parameters: State
- Returns: List of Moves to solve the state, otherwise None if unsolvable
- """
- if self.isSolvable() == False:
- return (None, None)
- closed = list()
- q = list()
- q.append(Node(state=self.state, depth=0))
- while q:
- node = q.pop()
- if node.isGoalState():
- return (node.moves, len(closed))
- if node.state not in closed:
- closed.append(node.state)
- for action in node.getAvailableActions():
- q.append(node.getResultFromAction(action))
-
- return (None, None)
-
- def uniform_cost_search(self, optimizer=0):
- """
- Parameters: State, Optimizer
- Returns: List of Moves to solve the state, otherwise None if unsolvable
- """
- if self.isSolvable() == False:
- return (None, None)
- closed = list()
- q = PriorityQueue()
- q.put(Node(state=self.state, depth=0, optimizer=optimizer))
- while q:
- node = q.get()
- if node.isGoalState():
- return (node.moves, len(closed))
- if node.state not in closed:
- closed.append(node.state)
- for action in node.getAvailableActions():
- q.put(node.getResultFromAction(action))
-
- return (None, None)
-
- def a_star(self):
- """
- Parameters: State, Optimizer
- Returns: List of Moves to solve the state, otherwise None if unsolvable
- """
- if self.isSolvable() == False:
- return (None, None)
- closed = dict()
- q = PriorityQueue()
- node = Node(state=self.state, depth=0)
- q.put((node.getManhattanDistance(), node))
- while q:
- dist, node = q.get()
- closed[node] = dist
- if node.isGoalState():
- return (node.moves, len(closed))
- for action in node.getAvailableActions():
- nextNode = node.getResultFromAction(action)
- nextDist = nextNode.getManhattanDistance()
- if (
- nextNode not in closed
- or nextNode.depth + nextDist < closed[nextNode]
- ):
- q.put((nextNode.depth + nextDist, nextNode))
- return (None, None)
-
-
-def toWord(action):
- """
- Parameters: List of moves
- Returns: Returns List of moves in Word
- """
- if action == 0:
- return "Left"
- if action == 1:
- return "Right"
- if action == 2:
- return "Top"
- if action == 3:
- return "Bottom"
-
-
-# initialState = [[1,8,4],[3,6,0],[2,7,5]]
-# # [[1,2,3],[4,5,6],[0,7,8]]
-# # [[6,8,5],[2,3,4],[1,0,7]]
-# # [[13,11,10,7],[6,0,15,2],[14,1,8,12],[5,3,4,9]]
-# # [[8,2,3],[4,6,5],[7,8,0]]
-# solver = Solver(initialState)
-# print("Initial State:- {}".format(initialState))
-# n = Node(state=initialState,depth=0)
-
-# print('-------------------------A Star--------------------------------')
-# startTime = time.time()
-# moves,nodesGenerated = solver.a_star()
-# endTime = time.time()
-# if moves is None:
-# print("Given State is Unsolvable!")
-# else:
-# wordMoves = list(map(toWord,moves))
-# print("Nodes Generated:- {}".format(nodesGenerated))
-# print("No. of moves:- {}".format(len(moves)))
-# print("Required Moves:- {}".format(wordMoves))
-# print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000))
-
-
-# print('-------------------------UCS--------------------------------')
-# startTime = time.time()
-# moves,nodesGenerated = solver.uniform_cost_search()
-# endTime = time.time()
-# if moves is None:
-# print("Given State is Unsolvable!")
-# else:
-# wordMoves = list(map(toWord,moves))
-# print("Nodes Generated:- {}".format(nodesGenerated))
-# print("No. of moves:- {}".format(len(moves)))
-# print("Required Moves:- {}".format(wordMoves))
-# print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000))
-
-
-# print('-------------------------BFS--------------------------------')
-# startTime = time.time()
-# moves,nodesGenerated = (solver.breadth_first_search())
-# endTime = time.time()
-# if moves is None:
-# print("Given State is Unsolvable!")
-# else:
-# wordMoves = list(map(toWord,moves))
-# print("Nodes Generated:- {}".format(nodesGenerated))
-# print("No. of moves:- {}".format(len(moves)))
-# print("Required Moves:- {}".format(wordMoves))
-# print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000))
-
-
-# print('-------------------------DFS--------------------------------')
-# startTime = time.time()
-# moves,nodesGenerated = (solver.depth_first_search())
-# endTime = time.time()
-# if moves is None:
-# print("Given State is Unsolvable!")
-# else:
-# wordMoves = list(map(toWord,moves))
-# print("Nodes Generated:- {}".format(nodesGenerated))
-# print("No. of moves:- {}".format(len(moves)))
-# print("Required Moves:- {}".format(wordMoves))
-# print("Execution Time:- {:.2f} ms".format((endTime-startTime)*1000))
diff --git a/Emoji Dictionary/QT_GUI.py b/Emoji Dictionary/QT_GUI.py
new file mode 100644
index 00000000000..a4dd819ccb8
--- /dev/null
+++ b/Emoji Dictionary/QT_GUI.py
@@ -0,0 +1,82 @@
+
+# -*- coding: utf-8 -*-
+
+import sys
+from PyQt5.QtCore import *
+from PyQt5.QtGui import *
+from PyQt5.QtWidgets import *
+from PyQt5 import uic
+from emoji import demojize
+import os
+
+class MainWindow(QMainWindow):
+ def __init__(self):
+ super(MainWindow, self).__init__()
+
+ # Load the UI file
+ uic.loadUi(os.path.join(os.path.dirname(__file__),'QT_GUI.ui'),self)
+ self.pushButton_4.clicked.connect(self.close)
+ self.pushButton_2.clicked.connect(lambda:search_emoji())
+ self.pushButton_3.clicked.connect(lambda:clear_text())
+ cells = [
+
+ ["🐒", "🐕", "🐎", "🐪", "🐁", "🐘", "🦘", "🦈", "🐓", "🐝", "👀", "🦴", "👩🏿", "🤝", "🧑", "🏾", "👱🏽", "♀", "🎞", "🎨", "⚽"],
+ ["🍕", "🍗", "🍜", "☕", "🍴", "🍉", "🍓", "🌴", "🌵", "🛺", "🚲", "🛴", "🚉", "🚀", "✈", "🛰", "🚦", "🏳", "🌈", "🌎", "🧭"],
+ ["🔥", "❄", "🌟", "🌞", "🌛", "🌝", "🌧", "🧺", "🧷", "🪒", "⛲", "🗼", "🕌", "👁", "🗨", "💬", "™", "💯", "🔕", "💥", "❤"],
+ ["😀", "🥰", "😴", "🤓", "🤮", "🤬", "😨", "🤑", "😫", "😎"],
+ ]
+ def emoji_wight_btn():
+ if self.emoji_widget.isVisible():
+ self.emoji_widget.hide()
+ else:
+ self.emoji_widget.show()
+
+ def search_emoji():
+ word = self.lineEdit.text()
+ print(f"Field Text: {word}")
+ if word == "":
+ self.textEdit.setText("You have entered no emoji.")
+ else:
+ means = demojize(word)
+ self.textEdit.setText("Meaning of Emoji : " + str(word) + "\n\n" + means.replace("::", ":\n: "))
+
+ def add_input_emoji(emoji):
+ self.lineEdit.setText(self.lineEdit.text() + emoji)
+
+ def clear_text():
+ self.lineEdit.setText("")
+ self.textEdit.setText("")
+
+ self.emoji_buttons = []
+ self.emoji_layout = QGridLayout()
+ self.emoji_widget = QWidget()
+ self.emoji_widget.setLayout(self.emoji_layout)
+ self.frame_2.layout().addWidget(self.emoji_widget)
+ self.emoji_widget.hide()
+ self.pushButton.clicked.connect(lambda:emoji_wight_btn())
+
+
+ for row_idx, row in enumerate(cells):
+ for col_idx, emoji in enumerate(row):
+ button = QPushButton(emoji)
+ button.setFixedSize(40, 40)
+ button.setFont(QFont("Arial", 20))
+ button.setStyleSheet("""
+ QPushButton {
+ background-color: #ffffff;
+ border: 1px solid #e0e0e0;
+ border-radius: 5px;
+ }
+ QPushButton:hover {
+ background-color: #f0f0f0;
+ }
+ """)
+ button.clicked.connect(lambda checked, e=emoji: add_input_emoji(e))
+ self.emoji_layout.addWidget(button, row_idx, col_idx)
+ self.emoji_buttons.append(button)
+
+if __name__ == '__main__':
+ app = QApplication(sys.argv)
+ window = MainWindow()
+ window.show()
+ sys.exit(app.exec_())
diff --git a/Emoji Dictionary/QT_GUI.ui b/Emoji Dictionary/QT_GUI.ui
new file mode 100644
index 00000000000..49267698e80
--- /dev/null
+++ b/Emoji Dictionary/QT_GUI.ui
@@ -0,0 +1,411 @@
+
+
+ MainWindow
+
+
+
+ 0
+ 0
+ 944
+ 638
+
+
+
+ MainWindow
+
+
+ background-color: #f0f2f5;
+
+
+
+ background-color: transparent;
+
+
+
+ 8
+
+
+ 10
+
+
+ 10
+
+
+ 10
+
+
+ 10
+
+ -
+
+
+ background-color: #ffffff;
+ border-radius: 10px;
+ padding: 15px;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 30
+
+
+
+ color: #1a73e8;
+ padding: 10px;
+
+
+ EMOJI DICTIONARY
+
+
+ Qt::AlignCenter
+
+
+
+
+
+
+ -
+
+
+
+ 0
+ 0
+
+
+
+
+ 0
+ 0
+
+
+
+ background-color: transparent;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 20
+
+
+
+ color: #333333;
+ padding: 10px;
+
+
+ Enter any Emoji you want to search...
+
+
+
+ -
+
+
+ background-color: #ffffff;
+ border-radius: 8px;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 14
+ 50
+ false
+
+
+
+ QLineEdit {
+ border: 1px solid #dcdcdc;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ background-color: #fafafa;
+ }
+ QLineEdit:focus {
+ border-color: #1a73e8;
+ background-color: #ffffff;
+ }
+
+
+
+
+
+
+ -
+
+
+ true
+
+
+
+ 14
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #1a73e8;
+ color: white;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #1557b0;
+ }
+ QPushButton:pressed {
+ background-color: #104080;
+ }
+
+
+ Emoji Board
+
+
+
+
+
+
+ -
+
+
+ background-color: transparent;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 14
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #34c759;
+ color: white;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #2ea44f;
+ }
+ QPushButton:pressed {
+ background-color: #26833b;
+ }
+
+
+ 🔍 Search
+
+
+
+ -
+
+
+
+ 14
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #ff3b30;
+ color: white;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #cc2f27;
+ }
+ QPushButton:pressed {
+ background-color: #99231f;
+ }
+
+
+ 🧹 Clear
+
+
+
+
+
+
+
+
+
+ -
+
+
+
+ 0
+ 0
+
+
+
+ background-color: #ffffff;
+ border-radius: 10px;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 16
+ 50
+ false
+
+
+
+ color: #333333;
+ padding-bottom: 10px;
+
+
+ Meaning...
+
+
+
+ -
+
+
+
+ 14
+
+
+
+
+
+QTextEdit {
+ border: 1px solid #dcdcdc;
+ border-radius: 5px;
+ padding: 10px;
+ font-size: 14px;
+ background-color: #fafafa;
+ }
+ QTextEdit:focus {
+ border-color: #1a73e8;
+ background-color: #ffffff;
+ }
+
+
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
+<html><head><meta name="qrichtext" content="1" /><style type="text/css">
+p, li { white-space: pre-wrap; }
+</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:14px; font-weight:400; font-style:normal;">
+<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:7.8pt;"><br /></p></body></html>
+
+
+
+ -
+
+
+
+ 140
+ 40
+
+
+
+
+ 14
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #ff9500;
+ color: white;
+ border-radius: 5px;
+ padding: 10px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #cc7700;
+ }
+ QPushButton:pressed {
+ background-color: #995900;
+ }
+
+
+ EXIT
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Emoji Dictionary/README.md b/Emoji Dictionary/README.md
index bfeee397ad6..ef821174fce 100644
--- a/Emoji Dictionary/README.md
+++ b/Emoji Dictionary/README.md
@@ -10,6 +10,8 @@
- tkinter module
- from tkinter messagebox module
- emoji
+- opencv
+
### How this Script works :
- User just need to download the file and run the emoji_dictionary.py on their local system.
diff --git a/Emoji Dictionary/untitled.ui b/Emoji Dictionary/untitled.ui
new file mode 100644
index 00000000000..a6753b7dd19
--- /dev/null
+++ b/Emoji Dictionary/untitled.ui
@@ -0,0 +1,406 @@
+
+
+ MainWindow
+
+
+
+ 0
+ 0
+ 948
+ 527
+
+
+
+ MainWindow
+
+
+ background-color: #f0f2f5;
+
+
+
+ background-color: transparent;
+
+
+
+ 8
+
+
+ 10
+
+
+ 10
+
+
+ 10
+
+
+ 10
+
+ -
+
+
+ background-color: #ffffff;
+ border-radius: 10px;
+ padding: 15px;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 30
+
+
+
+ color: #1a73e8;
+ padding: 10px;
+
+
+ EMOJI DICTIONARY
+
+
+ Qt::AlignCenter
+
+
+
+
+
+
+ -
+
+
+
+ 0
+ 0
+
+
+
+
+ 0
+ 0
+
+
+
+ background-color: transparent;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 20
+
+
+
+ color: #333333;
+ padding: 10px;
+
+
+ Enter any Emoji you want to search...
+
+
+
+ -
+
+
+ background-color: #ffffff;
+border-radius: 8px;
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ -1
+
+
+
+ QLineEdit {
+ border: 1px solid #dcdcdc;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ background-color: #fafafa;
+ }
+ QLineEdit:focus {
+ border-color: #1a73e8;
+ background-color: #ffffff;
+ }
+
+
+
+ -
+
+
+ true
+
+
+
+ -1
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #1a73e8;
+ color: white;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #1557b0;
+ }
+ QPushButton:pressed {
+ background-color: #104080;
+ }
+
+
+ Emoji Board
+
+
+
+
+
+
+ -
+
+
+ background-color: transparent;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ -1
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #34c759;
+ color: white;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #2ea44f;
+ }
+ QPushButton:pressed {
+ background-color: #26833b;
+ }
+
+
+ 🔍 Search
+
+
+
+ -
+
+
+
+ -1
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #ff3b30;
+ color: white;
+ border-radius: 5px;
+ padding: 8px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #cc2f27;
+ }
+ QPushButton:pressed {
+ background-color: #99231f;
+ }
+
+
+ 🧹 Clear
+
+
+
+
+
+
+
+
+
+ -
+
+
+
+ 0
+ 0
+
+
+
+ background-color: #ffffff;
+ border-radius: 10px;
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 16
+ 50
+ false
+
+
+
+ color: #333333;
+padding-bottom: 10px;
+
+
+ Meaning...
+
+
+
+ -
+
+
+
+ -1
+
+
+
+ QTextEdit {
+ border: 1px solid #dcdcdc;
+ border-radius: 5px;
+ padding: 10px;
+ font-size: 14px;
+ background-color: #fafafa;
+ }
+ QTextEdit:focus {
+ border-color: #1a73e8;
+ background-color: #ffffff;
+ }
+
+
+ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
+<html><head><meta name="qrichtext" content="1" /><style type="text/css">
+p, li { white-space: pre-wrap; }
+</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:14px; font-weight:400; font-style:normal;">
+<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:20pt;"><br /></p></body></html>
+
+
+
+ -
+
+
+
+ 140
+ 40
+
+
+
+
+ -1
+ 62
+ true
+
+
+
+ QPushButton {
+ background-color: #ff9500;
+ color: white;
+ border-radius: 5px;
+ padding: 10px;
+ font-size: 14px;
+ font-weight: 500;
+ }
+ QPushButton:hover {
+ background-color: #cc7700;
+ }
+ QPushButton:pressed {
+ background-color: #995900;
+ }
+
+
+ EXIT
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/ExtractThumbnailFromVideo/README.md b/ExtractThumbnailFromVideo/README.md
new file mode 100644
index 00000000000..2726afa84dd
--- /dev/null
+++ b/ExtractThumbnailFromVideo/README.md
@@ -0,0 +1,49 @@
+# Thumbnail Extractor
+
+This Python function extracts a thumbnail frame from a video and saves it as an image file. It utilizes the OpenCV library to perform these operations. This README provides an overview of the function, its usage, and the required packages.
+
+## Table of Contents
+- [Function Description](#function-description)
+- [Usage](#usage)
+- [Required Packages](#required-packages)
+
+## Function Description
+
+The `extract_thumbnail` function takes two parameters:
+
+- `video_path` (str): The path to the input video file.
+- `frame_size` (tuple): A tuple containing the desired dimensions (width, height) for the thumbnail frame.
+
+The function will raise an `Exception` if it fails to extract a frame from the video.
+
+### Function Logic
+
+1. The function opens the specified video file using OpenCV.
+2. It seeks to the middle frame by calculating the middle frame index.
+3. The frame is resized to the specified dimensions.
+4. The resized frame is saved as an image file with a filename derived from the video's base name.
+
+## Usage
+
+Here's an example of how to use the function:
+
+```python
+from thumbnail_extractor import extract_thumbnail
+
+# Extract a thumbnail from 'my_video.mp4' with dimensions (320, 240)
+extract_thumbnail('my_video.mp4', (320, 240))
+# Replace 'my_video.mp4' with the path to your own video file and (320, 240) with your desired thumbnail dimensions.
+
+## Required Packages
+```
+To use this function, you need the following package:
+
+- **OpenCV (cv2)**: You can install it using `pip`:
+
+ ```shell
+ pip install opencv-python
+ ```
+
+This function is useful for generating thumbnail images from videos. It simplifies the process of creating video thumbnails for various applications.
+
+
diff --git a/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py b/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py
new file mode 100644
index 00000000000..76ca3b43eb7
--- /dev/null
+++ b/ExtractThumbnailFromVideo/extract_thumbnail_from_video.py
@@ -0,0 +1,39 @@
+import cv2
+import os
+
+def extract_thumbnail(video_path, frame_size):
+ """
+ Extracts a thumbnail frame from a video and saves it as an image file.
+
+ Args:
+ video_path (str): The path to the input video file.
+ frame_size (tuple): A tuple containing the desired dimensions (width, height) for the thumbnail frame.
+
+ Raises:
+ Exception: If the function fails to extract a frame from the video.
+
+ The function opens the specified video file, seeks to the middle frame,
+ resizes the frame to the specified dimensions, and saves it as an image
+ file with a filename derived from the video's base name.
+
+ Example:
+ extract_thumbnail('my_video.mp4', (320, 240))
+
+ Required Packages:
+ cv2 (pip install cv2)
+
+ This function is useful for generating thumbnail images from videos.
+ """
+ video_capture = cv2.VideoCapture(video_path) # Open the video file for reading
+ total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) # Get the total number of frames in the video
+ middle_frame_index = total_frames // 2 # Calculate the index of the middle frame
+ video_capture.set(cv2.CAP_PROP_POS_FRAMES, middle_frame_index) # Seek to the middle frame
+ success, frame = video_capture.read() # Read the middle frame
+ video_capture.release() # Release the video capture object
+
+ if success:
+ frame = cv2.resize(frame, frame_size) # Resize the frame to the specified dimensions
+ thumbnail_filename = f"{os.path.basename(video_path)}_thumbnail.jpg" # Create a filename for the thumbnail
+ cv2.imwrite(thumbnail_filename, frame) # Save the thumbnail frame as an image
+ else:
+ raise Exception("Could not extract frame") # Raise an exception if frame extraction fails
diff --git a/FIND FACTORIAL OF A NUMBER.py b/FIND FACTORIAL OF A NUMBER.py
index 1ab661e93be..37bc7cd8c01 100644
--- a/FIND FACTORIAL OF A NUMBER.py
+++ b/FIND FACTORIAL OF A NUMBER.py
@@ -1,13 +1,13 @@
# Python program to find the factorial of a number provided by the user.
def factorial(n):
- if n < 0:
- return("Oops!Factorial Not Possible")
- elif n = 0:
- return 1
- else:
- return n*factorial(n-1)
-
-n = int(input())
-print(factorial(n))
+ if n < 0: # factorial of number less than 0 is not possible
+ return "Oops!Factorial Not Possible"
+ elif n == 0: # 0! = 1; when n=0 it returns 1 to the function which is calling it previously.
+ return 1
+ else:
+ return n*factorial(n-1)
+#Recursive function. At every iteration "n" is getting reduced by 1 until the "n" is equal to 0.
+n = int(input("Enter a number: ")) # asks the user for input
+print(factorial(n)) # function call
diff --git a/Face and eye Recognition/face_recofnation_first.py b/Face and eye Recognition/face_recofnation_first.py
index 8c61c3b0f07..c60faba84db 100644
--- a/Face and eye Recognition/face_recofnation_first.py
+++ b/Face and eye Recognition/face_recofnation_first.py
@@ -1,37 +1,52 @@
-## Name - Soumyajit Chakraborty
-## place - kolkata
-## date - 10 / 08 / 2020
-
import cv2 as cv
-face_cascade = cv.CascadeClassifier("..\libs\haarcascade_frontalface_default.xml")
-face_cascade_eye = cv.CascadeClassifier("..\libs\haarcascade_eye.xml")
-# face_glass = cv.CascadeClassifier('..\libs\haarcascade_eye_tree_eyeglasses.xml')
-
-cap = cv.VideoCapture(0)
-while cap.isOpened():
-
- falg, img = cap.read() # start reading the camera output i mean frames
- # cap.read() returning a bool value and a frame onject type value
-
- gray = cv.cvtColor(
- img, cv.COLOR_BGR2GRAY
- ) # converting to grayscale image to perform smoother
- faces = face_cascade.detectMultiScale(
- img, 1.1, 7
- ) # we use detectMultiscale library function to detect the predefined structures of a face
- eyes = face_cascade_eye.detectMultiScale(img, 1.1, 7)
- # using for loops we are trying to read each and every frame and map
- for (x, y, w, h) in faces:
- cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
-
- for (a, b, c, d) in eyes:
- cv.rectangle(img, (a, b), (a + c, b + d), (255, 0, 0), 1)
-
- cv.imshow("img", img)
- c = cv.waitKey(1)
- if c == ord("q"):
- break
-
-cv.release()
-cv.destroyAllWindows()
+
+def detect_faces_and_eyes():
+ """
+ Detects faces and eyes in real-time using the webcam.
+
+ Press 'q' to exit the program.
+ """
+ # Load the pre-trained classifiers for face and eye detection
+ face_cascade = cv.CascadeClassifier(r"..\libs\haarcascade_frontalface_default.xml")
+ eye_cascade = cv.CascadeClassifier(r"..\libs\haarcascade_eye.xml")
+
+ # Open the webcam
+ cap = cv.VideoCapture(0)
+
+ while cap.isOpened():
+ # Read a frame from the webcam
+ flag, img = cap.read()
+
+ # Convert the frame to grayscale for better performance
+ gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
+
+ # Detect faces in the frame
+ faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=7)
+
+ # Detect eyes in the frame
+ eyes = eye_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=7)
+
+ # Draw rectangles around faces and eyes
+ for x, y, w, h in faces:
+ cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
+
+ for a, b, c, d in eyes:
+ cv.rectangle(img, (a, b), (a + c, b + d), (255, 0, 0), 1)
+
+ # Display the resulting frame
+ cv.imshow("Face and Eye Detection", img)
+
+ # Check for the 'q' key to exit the program
+ key = cv.waitKey(1)
+ if key == ord("q"):
+ break
+
+ # Release the webcam and close all windows
+ cap.release()
+ cv.destroyAllWindows()
+
+
+if __name__ == "__main__":
+ # Call the main function
+ detect_faces_and_eyes()
\ No newline at end of file
diff --git a/Face and eye Recognition/gesture_control.py b/Face and eye Recognition/gesture_control.py
index db15e1849f1..8afd63af13f 100644
--- a/Face and eye Recognition/gesture_control.py
+++ b/Face and eye Recognition/gesture_control.py
@@ -1,18 +1,27 @@
import cv2 as cv
-# import numpy as np
+# Read the image in grayscale
+img = cv.imread(r"..\img\hand1.jpg", cv.IMREAD_GRAYSCALE)
-img = cv.imread("..\img\hand1.jpg", 0)
-flag, frame = cv.threshold(img, 70, 255, cv.THRESH_BINARY)
+# Apply thresholding to create a binary image
+_, thresholded = cv.threshold(img, 70, 255, cv.THRESH_BINARY)
-contor, _ = cv.findContours(frame.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
+# Find contours in the binary image
+contours, _ = cv.findContours(thresholded.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
-hull = [cv.convexHull(c) for c in contor]
+# Convex Hull for each contour
+convex_hulls = [cv.convexHull(contour) for contour in contours]
-final = cv.drawContours(img, hull, -1, (0, 0, 0))
-cv.imshow("original_image", img)
-cv.imshow("thres", frame)
-cv.imshow("final_hsv", final)
+# Draw contours and convex hulls on the original image
+original_with_contours = cv.drawContours(img.copy(), contours, -1, (0, 0, 0), 2)
+original_with_convex_hulls = cv.drawContours(img.copy(), convex_hulls, -1, (0, 0, 0), 2)
+# Display the images
+cv.imshow("Original Image", img)
+cv.imshow("Thresholded Image", thresholded)
+cv.imshow("Contours", original_with_contours)
+cv.imshow("Convex Hulls", original_with_convex_hulls)
+
+# Wait for a key press and close windows
cv.waitKey(0)
cv.destroyAllWindows()
diff --git a/FibonacciNumbersWithGenerators.py b/FibonacciNumbersWithGenerators.py
index 6227d3b48e0..5d090a0a7ea 100644
--- a/FibonacciNumbersWithGenerators.py
+++ b/FibonacciNumbersWithGenerators.py
@@ -14,5 +14,5 @@ def fibonacci_generator(n = None):
f0, f1 = f1, fn
n -= 1
-for n_fibo in fibonacci(7):
+for n_fibo in fibonacci_generator(7):
print(n_fibo)
diff --git a/Flappy Bird - created with tkinter/Flappy Bird.py b/Flappy Bird - created with tkinter/Flappy Bird.py
index 308a7c6ea70..7dfe9564dfb 100644
--- a/Flappy Bird - created with tkinter/Flappy Bird.py
+++ b/Flappy Bird - created with tkinter/Flappy Bird.py
@@ -1,419 +1,85 @@
-__author__ = "Jean Loui Bernard Silva de Jesus"
-__version__ = "1.0"
+import pygame
+import random
-import os.path
-from datetime import timedelta
-from time import time
-from tkinter import Tk, Button
+# Initialize Pygame
+pygame.init()
-from Background import Background
-from Bird import Bird
-from Settings import Settings
-from Tubes import Tubes
+# Set up display
+screen_width = 500
+screen_height = 700
+screen = pygame.display.set_mode((screen_width, screen_height))
+pygame.display.set_caption("Flappy Bird")
+# Load images
+bird_image = pygame.image.load("bird.png").convert_alpha()
+pipe_image = pygame.image.load("pipe.png").convert_alpha()
+background_image = pygame.image.load("background.png").convert_alpha()
-class App(Tk, Settings):
- """
- Classe principal do jogo onde tudo será executado
- """
-
- # Variáveis privadas e ajustes internos
- __background_animation_speed = 720
- __bestScore = 0
- __bird_descend_speed = 38.4
- __buttons = []
- __playing = False
- __score = 0
- __time = "%H:%M:%S"
-
+# Bird class
+class Bird:
def __init__(self):
+ self.image = bird_image
+ self.x = 50
+ self.y = screen_height // 2
+ self.vel = 0
+ self.gravity = 1
- Tk.__init__(self)
- self.setOptions()
-
- # Se o tamanho da largura e altura da janela forem definidos, eles serão usados no jogo.
- # Caso eles tenham o valor None, o tamanho da janela será o tamanho do monitor do usuário.
-
- if all([self.window_width, self.window_height]):
- self.__width = self.window_width
- self.__height = self.window_height
- else:
- self.__width = self.winfo_screenwidth()
- self.__height = self.winfo_screenheight()
-
- # Configura a janela do programa
- self.title(self.window_name)
- self.geometry("{}x{}".format(self.__width, self.__height))
- self.resizable(*self.window_rz)
- self.attributes("-fullscreen", self.window_fullscreen)
- self["bg"] = "black"
-
- # Verifica se existem as imagens do jogo
- for file in self.images_fp:
- if not os.path.exists(file):
- raise FileNotFoundError(
- "The following file was not found:\n{}".format(file)
- )
-
- # Carrega a imagem do botão para começar o jogo
- self.__startButton_image = Background.getPhotoImage(
- image_path=self.startButton_fp,
- width=(self.__width // 100) * self.button_width,
- height=(self.__height // 100) * self.button_height,
- closeAfter=True,
- )[0]
-
- # Carrega a imagem do botão para sair do jogo
- self.__exitButton_image = Background.getPhotoImage(
- image_path=self.exitButton_fp,
- width=(self.__width // 100) * self.button_width,
- height=(self.__height // 100) * self.button_height,
- closeAfter=True,
- )[0]
-
- # Carrega a imagem do título do jogo
- self.__title_image = Background.getPhotoImage(
- image_path=self.title_fp,
- width=(self.__width // 100) * self.title_width,
- height=(self.__height // 100) * self.title_height,
- closeAfter=True,
- )[0]
-
- # Carrega a imagem do placar do jogo
- self.__scoreboard_image = Background.getPhotoImage(
- image_path=self.scoreboard_fp,
- width=(self.__width // 100) * self.scoreboard_width,
- height=(self.__height // 100) * self.scoreboard_height,
- closeAfter=True,
- )[0]
-
- # Define a velocidade da animação do background com base na largura da janela
- self.__background_animation_speed //= self.__width / 100
- self.__background_animation_speed = int(self.__background_animation_speed)
-
- # Define a velocidade de descida do pássaro com base na altura da janela
- self.__bird_descend_speed //= self.__height / 100
- self.__bird_descend_speed = int(self.__bird_descend_speed)
-
- def changeFullscreenOption(self, event=None):
- """
- Método para colocar o jogo no modo "fullscreen" ou "window"
- """
-
- self.window_fullscreen = not self.window_fullscreen
- self.attributes("-fullscreen", self.window_fullscreen)
-
- def close(self, event=None):
- """
- Método para fechar o jogo
- """
-
- # Salva a melhor pontuação do jogador antes de sair do jogo
- self.saveScore()
-
- # Tenta interromper os processos
- try:
- self.__background.stop()
- self.__bird.kill()
- self.__tubes.stop()
- finally:
- quit()
-
- def createMenuButtons(self):
- """
- Método para criar os botões de menu
- """
-
- # Define o tamanho do botão em porcentagem com base no tamanho da janela
- width = (self.__width // 100) * self.button_width
- height = (self.__height // 100) * self.button_height
-
- # Cria um botão para começar o jogo
- startButton = Button(
- self,
- image=self.__startButton_image,
- bd=0,
- command=self.start,
- cursor=self.button_cursor,
- bg=self.button_bg,
- activebackground=self.button_activebackground,
- )
- # Coloca o botão dentro do background ( Canvas )
- self.__buttons.append(
- self.__background.create_window(
- (self.__width // 2) - width // 1.5,
- int(self.__height / 100 * self.button_position_y),
- window=startButton,
- )
- )
-
- # Cria um botão para sair do jogo
- exitButton = Button(
- self,
- image=self.__exitButton_image,
- bd=0,
- command=self.close,
- cursor=self.button_cursor,
- bg=self.button_bg,
- activebackground=self.button_activebackground,
- )
-
- # Coloca o botão dentro do background ( Canvas )
- self.__buttons.append(
- self.__background.create_window(
- (self.__width // 2) + width // 1.5,
- int(self.__height / 100 * self.button_position_y),
- window=exitButton,
- )
- )
-
- def createScoreBoard(self):
- """
- Método para criar a imagem do placar do jogo no background
- junto com as informações do jogador.
- """
-
- # Define a posição X e Y
- x = self.__width // 2
- y = (self.__height // 100) * self.scoreboard_position_y
-
- # Calcula o tamanho da imagem do placar
- scoreboard_w = (self.__width // 100) * self.scoreboard_width
- scoreboard_h = (self.__width // 100) * self.scoreboard_height
-
- # Calcula a posição X e Y do texto da pontuação do último jogo
- score_x = x - scoreboard_w / 100 * 60 / 2
- score_y = y + scoreboard_h / 100 * 10 / 2
-
- # Calcula a posição X e Y do texto da melhor pontuação do jogador
- bestScore_x = x + scoreboard_w / 100 * 35 / 2
- bestScore_y = y + scoreboard_h / 100 * 10 / 2
-
- # Calcula a posição X e Y do texto do tempo de jogo
- time_x = x
- time_y = y + scoreboard_h / 100 * 35 / 2
-
- # Define a fonte dos textos
- font = (self.text_font, int(0.02196 * self.__width + 0.5))
-
- # Cria a imagem do placar no background
- self.__background.create_image(x, y, image=self.__scoreboard_image)
-
- # Cria texto para mostrar o score do último jogo
- self.__background.create_text(
- score_x,
- score_y,
- text="Score: %s" % self.__score,
- fill=self.text_fill,
- font=font,
- )
-
- # Cria texto para mostrar a melhor pontuação do jogador
- self.__background.create_text(
- bestScore_x,
- bestScore_y,
- text="Best Score: %s" % self.__bestScore,
- fill=self.text_fill,
- font=font,
- )
-
- # Cria texto para mostrar o tempo de jogo
- self.__background.create_text(
- time_x,
- time_y,
- text="Time: %s" % self.__time,
- fill=self.text_fill,
- font=font,
- )
-
- def createTitleImage(self):
- """
- Método para criar a imagem do título do jogo no background
- """
-
- self.__background.create_image(
- self.__width // 2,
- (self.__height // 100) * self.title_position_y,
- image=self.__title_image,
- )
+ def update(self):
+ self.vel += self.gravity
+ self.y += self.vel
- def deleteMenuButtons(self):
- """
- Método para deletar os botões de menu
- """
+ def flap(self):
+ self.vel = -10
- # Deleta cada botão criado dentro do background
- for item in self.__buttons:
- self.__background.delete(item)
-
- # Limpa a lista de botões
- self.__buttons.clear()
-
- def gameOver(self):
- """
- Método de fim de jogo
- """
-
- # Calcula o tempo jogado em segundos e depois o formata
- self.__time = int(time() - self.__time)
- self.__time = str(timedelta(seconds=self.__time))
-
- # Interrompe a animação do plano de fundo e a animação dos tubos
- self.__background.stop()
- self.__tubes.stop()
-
- # Declara que o jogo não está mais em execução
- self.__playing = False
-
- # Cria os botões inciais
- self.createMenuButtons()
-
- # Cria image do título do jogo
- self.createTitleImage()
-
- # Cria imagem do placar e mostra as informações do jogo passado
- self.createScoreBoard()
-
- def increaseScore(self):
- """
- Método para aumentar a pontuação do jogo atual do jogador
- """
-
- self.__score += 1
- if self.__score > self.__bestScore:
- self.__bestScore = self.__score
-
- def init(self):
- """
- Método para iniciar o programa em si, criando toda a parte gráfica inicial do jogo
- """
-
- # self.createMenuButtons()
- self.loadScore()
-
- # Cria o plano de fundo do jogo
- self.__background = Background(
- self,
- self.__width,
- self.__height,
- fp=self.background_fp,
- animation_speed=self.__background_animation_speed,
- )
-
- # Foca o plano de fundo para que seja possível definir os eventos
- self.__background.focus_force()
- # Define evento para trocar o modo de janela para "fullscreen" ou "window"
- self.__background.bind(
- self.window_fullscreen_event, self.changeFullscreenOption
- )
- # Define evento para começar o jogo
- self.__background.bind(self.window_start_event, self.start)
- # Define evento para sair do jogo
- self.__background.bind(self.window_exit_event, self.close)
-
- # Define um método caso o usuário feche a janela do jogo
- self.protocol("WM_DELETE_WINDOW", self.close)
-
- # Empacota o objeto background
- self.__background.pack()
-
- # Cria os botões do menu do jogo
- self.createMenuButtons()
-
- # Cria imagem do título do jogo
- self.createTitleImage()
-
- # Cria um pássaro inicial no jogo
- self.__bird = Bird(
- self.__background,
- self.gameOver,
- self.__width,
- self.__height,
- fp=self.bird_fp,
- event=self.bird_event,
- descend_speed=self.__bird_descend_speed,
- )
-
- def loadScore(self):
- """
- Método para carregar a pontuação do jogador
- """
-
- # Tenta carregar o placar do usuário
- try:
- file = open(self.score_fp)
- self.__bestScore = int(file.read(), 2)
- file.close()
-
- # Se não for possível, será criado um arquivo para guardar o placar
- except BaseException:
- file = open(self.score_fp, "w")
- file.write(bin(self.__bestScore))
- file.close()
-
- def saveScore(self):
- """
- Método para salvar a pontuação do jogador
- """
-
- with open(self.score_fp, "w") as file:
- file.write(bin(self.__bestScore))
-
- def start(self, event=None):
- """
- Método para inicializar o jogo
- """
-
- # Este método é executado somente se o jogador não estiver já jogando
- if self.__playing:
- return
-
- # Reinicia o placar
- self.__score = 0
- self.__time = time()
-
- # Remove os botões de menu
- self.deleteMenuButtons()
-
- # Reinicia o background
- self.__background.reset()
-
- # Inicializa a animação do background se True
- if self.background_animation:
- self.__background.run()
-
- # Cria um pássaro no jogo
- self.__bird = Bird(
- self.__background,
- self.gameOver,
- self.__width,
- self.__height,
- fp=self.bird_fp,
- event=self.bird_event,
- descend_speed=self.__bird_descend_speed,
- )
-
- # Cria tubos no jogo
- self.__tubes = Tubes(
- self.__background,
- self.__bird,
- self.increaseScore,
- self.__width,
- self.__height,
- fp=self.tube_fp,
- animation_speed=self.__background_animation_speed,
- )
-
- # Inicializa a animação do pássaro e dos tubos
- self.__bird.start()
- self.__tubes.start()
+ def draw(self, screen):
+ screen.blit(self.image, (self.x, self.y))
+# Pipe class
+class Pipe:
+ def __init__(self):
+ self.image = pipe_image
+ self.x = screen_width
+ self.y = random.randint(150, screen_height - 150)
+ self.vel = 5
+
+ def update(self):
+ self.x -= self.vel
+
+ def draw(self, screen):
+ screen.blit(self.image, (self.x, self.y))
+ screen.blit(pygame.transform.flip(self.image, False, True), (self.x, self.y - screen_height))
+
+def main():
+ clock = pygame.time.Clock()
+ bird = Bird()
+ pipes = [Pipe()]
+ score = 0
+
+ running = True
+ while running:
+ for event in pygame.event.get():
+ if event.type == pygame.QUIT:
+ running = False
+ if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
+ bird.flap()
+
+ bird.update()
+ for pipe in pipes:
+ pipe.update()
+ if pipe.x + pipe.image.get_width() < 0:
+ pipes.remove(pipe)
+ pipes.append(Pipe())
+ score += 1
+
+ screen.blit(background_image, (0, 0))
+ bird.draw(screen)
+ for pipe in pipes:
+ pipe.draw(screen)
+
+ pygame.display.update()
+ clock.tick(30)
+
+ pygame.quit()
if __name__ == "__main__":
- try:
- app = App()
- app.init()
- app.mainloop()
-
- except FileNotFoundError as error:
- print(error)
+ main()
diff --git a/Grocery calculator.py b/Grocery calculator.py
index b2e9a9949b3..eedb5c7ea15 100644
--- a/Grocery calculator.py
+++ b/Grocery calculator.py
@@ -8,28 +8,28 @@
#Object = GroceryList
#Methods = addToList, Total, Subtotal, returnList
-
class GroceryList(dict):
- def __init__(self):
- self = {}
+ def __init__(self):
+ self = {}
- def addToList(self, item, price):
- self.update({item:price})
+ def addToList(self, item, price):
+
+ self.update({item:price})
- def Total(self):
+ def Total(self):
total = 0
for items in self:
total += (self[items])*.07 + (self[items])
return total
- def Subtotal(self):
+ def Subtotal(self):
subtotal = 0
for items in self:
subtotal += self[items]
return subtotal
- def returnList(self):
+ def returnList(self):
return self
'''Test list should return:
@@ -44,12 +44,12 @@ def returnList(self):
List1.addToList("kombucha", 3)
-print List1.Total()
-print List1.Subtotal()
-print List1.returnList()
+print(List1.Total())
+print(List1.Subtotal())
+print(List1.returnList())
#*****************************************************
-print
+print()
#*****************************************************
@@ -59,6 +59,6 @@ def returnList(self):
List2.addToList('wine', 25.36)
List2.addToList('steak', 17.64)
-print List2.Total()
-print List2.Subtotal()
-print List2.returnList()
+print(List2.Total())
+print(List2.Subtotal())
+print(List2.returnList())
diff --git a/HTML_to_PDF/index.html b/HTML_to_PDF/index.html
new file mode 100644
index 00000000000..6b39d63cb2d
--- /dev/null
+++ b/HTML_to_PDF/index.html
@@ -0,0 +1,221 @@
+
+
+
+
+
+ HTML to PDF Test Page
+
+
+
+
+
+
+ 📄 This page is created for testing HTML to PDF conversion!
+
+
+
+
+
HTML to PDF Test
+
+
+
+
+
+
+ Welcome!
+ This is a test page designed to check HTML to PDF conversion.
+
+ ⚡ This section highlights that we are testing the ability to convert HTML pages into PDF format.
+
+
+
+
+ About This Test
+ This page includes various HTML elements to check how they appear in the converted PDF.
+
+
+
+ Elements to Test
+
+ - Headings & Paragraphs
+ - Navigation & Links
+ - Lists & Bullet Points
+ - Background Colors & Styling
+ - Margins & Spacing
+
+
+
+
+
+
+
+
+
+
diff --git a/HTML_to_PDF/main.py b/HTML_to_PDF/main.py
new file mode 100644
index 00000000000..67954b0a2a9
--- /dev/null
+++ b/HTML_to_PDF/main.py
@@ -0,0 +1,28 @@
+import pdfkit
+import os
+
+# Download wkhtmltopdf from https://wkhtmltopdf.org/downloads.html
+# Set the path to the wkhtmltopdf executable
+
+wkhtmltopdf_path = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
+
+# Configure pdfkit to use wkhtmltopdf
+config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path)
+
+# Path of HTML and PDF files
+path=os.getcwd()
+htmlFile = f'{path}\\index.html'
+pdfFile = f'{path}\\output.pdf'
+
+# Check if the HTML file exists before proceeding
+if not os.path.exists(htmlFile):
+ print(f"HTML file does not exist at: {htmlFile}")
+else:
+ try:
+ # Convert HTML to PDF
+ pdfkit.from_file(htmlFile, pdfFile, configuration=config)
+ print(f"Successfully converted HTML to PDF: {pdfFile}")
+ except Exception as e:
+ print(f"An error occurred: {e}")
+
+
diff --git a/HTML_to_PDF/output.pdf b/HTML_to_PDF/output.pdf
new file mode 100644
index 00000000000..8d8f56439f2
Binary files /dev/null and b/HTML_to_PDF/output.pdf differ
diff --git a/Hand-Motion-Detection/hand_motion_recognizer.py b/Hand-Motion-Detection/hand_motion_recognizer.py
index 9e9db13ce9e..59efb53c8ef 100644
--- a/Hand-Motion-Detection/hand_motion_recognizer.py
+++ b/Hand-Motion-Detection/hand_motion_recognizer.py
@@ -1,8 +1,5 @@
import mediapipe as mp
import cv2
-import numpy as np
-import uuid
-import os
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
diff --git a/Hand-Motion-Detection/requirements.txt b/Hand-Motion-Detection/requirements.txt
index 422ece87c09..e851a4195fe 100644
--- a/Hand-Motion-Detection/requirements.txt
+++ b/Hand-Motion-Detection/requirements.txt
@@ -1,3 +1,3 @@
-numpy==1.25.1
-opencv_python==4.8.0.74
-mediapipe==0.10.2
+numpy==2.2.3
+opencv_python==4.11.0.86
+mediapipe==0.10.21
diff --git a/Hotel-Management.py b/Hotel-Management.py
index b8e4cfcbfeb..edfdec0934a 100644
--- a/Hotel-Management.py
+++ b/Hotel-Management.py
@@ -1,72 +1,74 @@
-def menu():
- print("")
- print("")
- print(" Welcome to Hotel Database Management Software")
- print("")
- print("")
-
- print("1-Add new customer details")
- print("2-Modify already existing customer details")
- print("3-Search customer details")
- print("4-View all customer details")
- print("5-Delete customer details")
- print("6-Exit the program")
- print("")
-
- user_input = int(input("Enter your choice(1-6): "))
-
- if user_input == 1:
- add()
- elif user_input == 2:
- modify()
+def menu():
- elif user_input == 3:
- search()
+ options = {
+ 1 : {
+ "title" : "Add new customer details",
+ "method": lambda : add()
+ },
+
+ 2 : {
+ "title" : "Modify already existing customer details",
+ "method": lambda : modify()
+ },
+
+ 3 : {
+ "title" : "Search customer details",
+ "method": lambda : search()
+ },
+
+ 4 : {
+ "title" : "View all customer details",
+ "method": lambda : view()
+ },
+
+ 5 : {
+ "title" : "Delete customer details",
+ "method": lambda : remove()
+ },
+
+ 6 : {
+ "title" : "Exit the program",
+ "method": lambda : exit()
+ }
+ }
- elif user_input == 4:
- view()
+ print(f"\n\n{' '*25}Welcome to Hotel Database Management Software\n\n")
- elif user_input == 5:
- remove()
+ for num, option in options.items():
+ print(f"{num}: {option.get('title')}")
+ print()
- elif user_input == 6:
- exit()
+ options.get( int(input("Enter your choice(1-6): ")) ).get("method")()
def add():
- print("")
- Name1 = input("Enter your first name: ")
- print("")
-
- Name2 = input("Enter your last name: ")
- print("")
-
- Phone_Num = input("Enter your phone number(without +91): ")
- print("")
+ Name1 = input("\nEnter your first name: \n")
+ Name2 = input("\nEnter your last name: \n")
+ Phone_Num = input("\nEnter your phone number(without +91): \n")
print("These are the rooms that are currently available")
print("1-Normal (500/Day)")
print("2-Deluxe (1000/Day)")
print("3-Super Deluxe (1500/Day)")
print("4-Premium Deluxe (2000/Day)")
- print("")
- Room_Type = int(input("Which type you want(1-4): "))
- print("")
- if Room_Type == 1:
- x = 500
- Room_Type = "Normal"
- elif Room_Type == 2:
- x = 1000
- Room_Type = "Deluxe"
- elif Room_Type == 3:
- x = 1500
- Room_Type = "Super Deluxe"
- elif Room_Type == 4:
- x = 2000
- Room_Type = "Premium"
+ Room_Type = int(input("\nWhich type you want(1-4): \n"))
+
+ match Room_Type:
+ case 1:
+ x = 500
+ Room_Type = "Normal"
+ case 2:
+ x = 1000
+ Room_Type = "Deluxe"
+ case 3:
+ x = 1500
+ Room_Type = "Super Deluxe"
+ case 4:
+ x = 2000
+ Room_Type = "Premium"
Days = int(input("How many days you will stay: "))
Money = x * Days
@@ -85,11 +87,10 @@ def add():
print("Online payment")
print("")
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
+ with open("Management.txt", "r") as File:
+ string = File.read()
+ string = string.replace("'", '"')
+ dictionary = json.loads(string)
if len(dictionary.get("Room")) == 0:
Room_num = "501"
@@ -114,12 +115,10 @@ def add():
dictionary["Price"].append(Money)
dictionary["Room"].append(Room_num)
- File = open("Management.txt", "w", encoding="utf-8")
- File.write(str(dictionary))
- File.close()
+ with open("Management.txt", "w", encoding="utf-8") as File:
+ File.write(str(dictionary))
- print("")
- print("Your data has been successfully added to our database.")
+ print("\nYour data has been successfully added to our database.")
exit_menu()
@@ -128,109 +127,83 @@ def add():
import json
filecheck = os.path.isfile("Management.txt")
-if filecheck == False:
- File = open("Management.txt", "a", encoding="utf-8")
- temp1 = {
- "First_Name": [],
- "Last_Name": [],
- "Phone_num": [],
- "Room_Type": [],
- "Days": [],
- "Price": [],
- "Room": [],
- }
- File.write(str(temp1))
- File.close()
+if not filecheck:
+ with open("Management.txt", "a", encoding="utf-8") as File:
+ temp1 = {
+ "First_Name": [],
+ "Last_Name": [],
+ "Phone_num": [],
+ "Room_Type": [],
+ "Days": [],
+ "Price": [],
+ "Room": [],
+ }
+ File.write(str(temp1))
def modify():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
+ with open("Management.txt", "r") as File:
+ string = File.read()
+ string = string.replace("'", '"')
+ dictionary = json.loads(string)
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
if dict_len == 0:
- print("")
- print("There is no data in our database")
- print("")
+ print("\nThere is no data in our database\n")
menu()
else:
- print("")
- Room = input("Enter your Room Number: ")
+ Room = input("\nEnter your Room Number: ")
listt = dictionary["Room"]
index = int(listt.index(Room))
- print("")
- print("1-Change your first name")
+ print("\n1-Change your first name")
print("2-Change your last name")
print("3-Change your phone number")
- print("")
- choice = input("Enter your choice: ")
- print("")
-
- File = open("Management.txt", "w", encoding="utf-8")
-
- if choice == str(1):
- user_input = input("Enter New First Name: ")
- listt1 = dictionary["First_Name"]
+ choice = int(input("\nEnter your choice: "))
+ print()
+
+ with open("Management.txt", "w", encoding="utf-8") as File:
+
+ match choice:
+ case 1:
+ category = "First_Name"
+ case 2:
+ category = "Last_Name"
+ case 3:
+ category = "Phone_num"
+
+ user_input = input(f"Enter New {category.replace('_', ' ')}")
+ listt1 = dictionary[category]
listt1[index] = user_input
- dictionary["First_Name"] = None
- dictionary["First_Name"] = listt1
- File.write(str(dictionary))
- File.close()
+ dictionary[category] = None
+ dictionary[category] = listt1
- elif choice == str(2):
- user_input = input("Enter New Last Name: ")
- listt1 = dictionary["Last_Name"]
- listt1[index] = user_input
- dictionary["Last_Name"] = None
- dictionary["Last_Name"] = listt1
File.write(str(dictionary))
- File.close()
-
- elif choice == str(3):
- user_input = input("Enter New Phone Number: ")
- listt1 = dictionary["Phone_num"]
- listt1[index] = user_input
- dictionary["Phone_num"] = None
- dictionary["Phone_num"] = listt1
- File.write(str(dictionary))
- File.close()
-
- print("")
- print("Your data has been successfully updated")
+ print("\nYour data has been successfully updated")
exit_menu()
def search():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
+ with open("Management.txt") as File:
+ dictionary = json.loads(File.read().replace("'", '"'))
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
+
if dict_len == 0:
- print("")
- print("There is no data in our database")
- print("")
+ print("\nThere is no data in our database\n")
menu()
else:
- print("")
- Room = input("Enter your Room Number: ")
- print("")
+ Room = input("\nEnter your Room Number: ")
- listt = dictionary["Room"]
- index = int(listt.index(Room))
+ listt_num = dictionary.get("Room")
+ index = int(listt_num.index(Room))
listt_fname = dictionary.get("First_Name")
listt_lname = dictionary.get("Last_Name")
@@ -238,38 +211,29 @@ def search():
listt_type = dictionary.get("Room_Type")
listt_days = dictionary.get("Days")
listt_price = dictionary.get("Price")
- listt_num = dictionary.get("Room")
- print("")
- print("First Name:", listt_fname[index])
- print("Last Name:", listt_lname[index])
- print("Phone number:", listt_phone[index])
- print("Room Type:", listt_type[index])
- print("Days staying:", listt_days[index])
- print("Money paid:", listt_price[index])
- print("Room Number:", listt_num[index])
+ print(f"\nFirst Name: {listt_fname[index]}")
+ print(f"Last Name: {listt_lname[index]}")
+ print(f"Phone number: {listt_phone[index]}")
+ print(f"Room Type: {listt_type[index]}")
+ print(f"Days staying: {listt_days[index]}")
+ print(f"Money paid: {listt_price[index]}")
+ print(f"Room Number: {listt_num[index]}")
exit_menu()
def remove():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
+ with open("Management.txt") as File:
+ dictionary = json.loads(File.read().replace("'", '"'))
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
if dict_len == 0:
- print("")
- print("There is no data in our database")
- print("")
+ print("\nThere is no data in our database\n")
menu()
else:
- print("")
- Room = input("Enter your Room Number: ")
- print("")
+ Room = input("\nEnter your Room Number: ")
listt = dictionary["Room"]
index = int(listt.index(Room))
@@ -311,9 +275,8 @@ def remove():
dictionary["Room"] = None
dictionary["Room"] = listt_num
- file1 = open("Management.txt", "w", encoding="utf-8")
- file1.write(str(dictionary))
- file1.close()
+ with open("Management.txt", "w", encoding="utf-8") as file1:
+ file1.write(str(dictionary))
print("Details has been removed successfully")
@@ -322,18 +285,13 @@ def remove():
def view():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
+ with open("Management.txt") as File:
+ dictionary = json.loads(File.read().replace("'", '"'))
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
if dict_len == 0:
- print("")
- print("There is no data in our database")
- print("")
+ print("\nThere is no data in our database\n")
menu()
else:
diff --git a/Image-watermarker/README.md b/Image-watermarker/README.md
new file mode 100644
index 00000000000..55755407495
--- /dev/null
+++ b/Image-watermarker/README.md
@@ -0,0 +1,98 @@
+# Watermarking Application
+
+A Python-based watermarking application built using `CustomTkinter` and `PIL` that allows users to add text and logo watermarks to images. The application supports the customization of text, font, size, color, and the ability to drag and position the watermark on the image.
+
+## Features
+
+- **Text Watermark**: Add customizable text to your images.
+ - Select font style, size, and color.
+ - Drag and position the text watermark on the image.
+- **Logo Watermark**: Add a logo or image as a watermark.
+ - Resize and position the logo watermark.
+ - Supports various image formats (JPG, PNG, BMP).
+- **Mutual Exclusivity**: The application ensures that users can either add text or a logo as a watermark, not both simultaneously.
+- **Image Saving**: Save the watermarked image in PNG format with an option to choose the file name and location.
+
+## Installation
+
+### Prerequisites
+
+- Python 3.6 or higher
+- `PIL` (Pillow)
+- `CustomTkinter`
+
+### Installation Steps
+
+1. **Clone the repository:**
+
+ ```bash
+ git clone https://github.com/jinku-06/Image-Watermarking-Desktop-app.git
+ cd watermarking-app
+ ```
+
+2. **Install the required packages:**
+
+ ```bash
+ pip install -r requirements.txt
+ ```
+
+3. **Run the application:**
+
+ ```bash
+ python app.py
+ ```
+
+## Usage
+
+1. **Load an Image**: Start by loading an image onto the canvas.
+2. **Add Text Watermark**:
+ - Input your desired text.
+ - Customize the font style, size, and color.
+ - Drag and position the text on the image.
+ - Note: Adding a text watermark disables the option to add a logo.
+3. **Add Logo Watermark**:
+ - Select and upload a logo or image to use as a watermark.
+ - Resize and position the logo on the image.
+ - Note: Adding a logo watermark disables the option to add text.
+4. **Save the Image**: Once satisfied with the watermark, save the image to your desired location.
+
+## Project Structure
+
+```bash
+watermarking-app/
+│
+├── fonts/ # Custom fonts directory
+├── app.py # Main application file
+├── watermark.py # Watermark functionality class
+├── requirements.txt # Required Python packages
+└── README.md # Project documentation
+```
+
+## Sample and look
+
+Below are some sample images showcasing the application work:
+
+UI:
+
+
+
+Text Watermark :
+
+
+
+Logo Watermark:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Image-watermarker/app.py b/Image-watermarker/app.py
new file mode 100644
index 00000000000..3a388d3b98a
--- /dev/null
+++ b/Image-watermarker/app.py
@@ -0,0 +1,332 @@
+import customtkinter as ctk
+from customtkinter import filedialog
+from CTkMessagebox import CTkMessagebox
+from PIL import Image, ImageTk
+from watermark import Watermark
+import pyglet
+from tkinter import colorchooser
+
+
+# ------------------- Create Window -----------------
+pyglet.font.add_directory("fonts")
+
+
+window = ctk.CTk()
+window.geometry("810x525")
+window.title("Grenze")
+
+text_label = None
+loaded_image = False
+logo = None
+img = None
+user_text = None
+logo_path = None
+color_code = "white"
+font_values = ["Decorative", "MartianMono", "DancingScript", "AkayaKanadaka"]
+
+
+# -------------------------- LOAD IMAGE AND CHECK FILE TYPE ON IMAGE CANVAS (use Frame) --------------
+def load_image():
+ global img, loaded_image, image_canvas
+
+ file_path = filedialog.askopenfilename(
+ filetypes=[("Image files", "*.jpg *.jpeg *.png *.bmp")]
+ )
+ if not file_path:
+ return
+
+ img = Image.open(file_path)
+ max_width, max_height = 800, 600
+ if img.width > max_width or img.height > max_height:
+ ratio = min(max_width / img.width, max_height / img.height)
+ resize_img = img.resize(
+ (int(img.width * ratio), int(img.height * ratio)), Image.Resampling.LANCZOS
+ )
+ loaded_image = ImageTk.PhotoImage(resize_img)
+
+ window.geometry(f"{resize_img.width + 300+30}x{resize_img.height + 50}")
+ image_canvas.config(width=resize_img.width, height=resize_img.height)
+ image_canvas.grid(row=0, column=1, padx=20, pady=20, columnspan=2)
+ image_canvas.create_image(0, 0, anchor="nw", image=loaded_image)
+ else:
+ loaded_image = ImageTk.PhotoImage(img)
+ window.geometry(f"{img.width + 300}x{img.height + 50}")
+ image_canvas.config(width=img.width, height=img.height)
+ image_canvas.grid(row=0, column=1, padx=20, pady=20, columnspan=2)
+ image_canvas.create_image(0, 0, anchor="nw", image=loaded_image)
+
+
+# ------------------------------------- DRAG AND DROP FEATURE --------
+
+start_x = 0
+start_y = 0
+
+new_x = 0
+new_y = 0
+
+
+def move_logo(e):
+ global logo, new_x, new_y
+ canvas_width = image_canvas.winfo_width()
+ canvas_height = image_canvas.winfo_height()
+ label_width = image_canvas.bbox(logo)[2] - image_canvas.bbox(logo)[0]
+ label_height = image_canvas.bbox(logo)[3] - image_canvas.bbox(logo)[1]
+
+ new_x = e.x
+ new_y = e.y
+
+ if new_x < 0:
+ new_x = 0
+ elif new_x + label_width > canvas_width:
+ new_x = canvas_width - label_width
+
+ if new_y < 0:
+ new_y = 0
+ elif new_y + label_height > canvas_height:
+ new_y = canvas_height - label_height
+ image_canvas.coords(logo, new_x, new_y)
+
+
+def move_text(e):
+ global text_label, new_x, new_y
+ canvas_width = image_canvas.winfo_width()
+ canvas_height = image_canvas.winfo_height()
+ label_width = image_canvas.bbox(text_label)[2] - image_canvas.bbox(text_label)[0]
+ label_height = image_canvas.bbox(text_label)[3] - image_canvas.bbox(text_label)[1]
+
+ new_x = e.x
+ new_y = e.y
+
+ if new_x < 0:
+ new_x = 0
+ elif new_x + label_width > canvas_width:
+ new_x = canvas_width - label_width
+
+ if new_y < 0:
+ new_y = 0
+ elif new_y + label_height > canvas_height:
+ new_y = canvas_height - label_height
+ image_canvas.coords(text_label, new_x, new_y)
+
+
+def choose_color():
+ global color_code
+ choose_color = colorchooser.askcolor(title="Choose Color")
+ color_code = choose_color[1]
+
+
+# ----------------- ADD TEXT ON CANVAS-----------------
+
+
+def add_text_on_canvas():
+ global text_label, loaded_image, user_text, img, font_values
+ user_text = text.get()
+ font_key = font_style.get()
+ if font_key not in font_values:
+ CTkMessagebox(
+ title="Font Not Available",
+ message=f"{font_key} FileNotFoundError.",
+ )
+ return
+
+ if logo is not None:
+ CTkMessagebox(title="Logo Use", message="Logo is in use.")
+ return
+
+ if text_label is not None:
+ image_canvas.delete(text_label) # Delete previous text_label
+
+ if loaded_image:
+ if user_text:
+ selected_size = int(font_size.get())
+ pyglet.font.add_file(f"fonts/{font_key}.ttf")
+ text_label = image_canvas.create_text(
+ 10,
+ 10,
+ text=user_text,
+ font=(font_key, selected_size),
+ fill=color_code,
+ anchor="nw",
+ )
+
+ image_canvas.tag_bind(text_label, "", move_text)
+ else:
+ CTkMessagebox(title="Error", message="Text Filed Empty.", icon="cancel")
+ else:
+ CTkMessagebox(title="Error", message="Image Not Found. Upload Image.")
+
+
+# ----------------------TODO UPLOAD LOGO -----------
+
+
+def upload_logo():
+ global loaded_image, logo, logo_path, text_label
+
+ if text_label is not None:
+ CTkMessagebox(
+ title="Text In Use", message="You are using text. Can't use logo."
+ )
+ return
+
+ if logo is not None:
+ image_canvas.delete(logo)
+ if loaded_image:
+ logo_path = filedialog.askopenfilename(
+ filetypes=[("Image files", "*.jpg *.jpeg *.png *.bmp")],
+ )
+ if logo_path:
+ logo_image = Image.open(logo_path).convert("RGBA")
+ resize = logo_image.resize((160, 150))
+ logo_photo = ImageTk.PhotoImage(resize)
+ logo = image_canvas.create_image(0, 0, anchor="nw", image=logo_photo)
+ image_canvas.tag_bind(logo, "", move_logo)
+
+ image_canvas.logo_photo = logo_photo
+
+ else:
+ CTkMessagebox(
+ title="Image Field Empty",
+ message="Image field empty. Click on the open image button to add the image to the canvas.",
+ icon="cancel",
+ )
+
+
+# ---------------------------- TODO SAVE FUNCTION ---------------
+watermark = Watermark()
+
+
+def save_image():
+ global text_label, loaded_image, file_path, user_text, img, new_x, new_y, logo
+ if loaded_image and text_label:
+ width, height = img.size
+ canvas_width = image_canvas.winfo_width()
+ canvas_height = image_canvas.winfo_height()
+
+ scale_x = width / canvas_width
+ scale_y = height / canvas_height
+
+ image_x = int(new_x * scale_x) - 10
+ image_y = int(new_y * scale_y) - 10
+
+ adjusted_font_size = int(int(font_size.get()) * min(scale_x, scale_y)) + 6
+ watermarked_image = watermark.add_text_watermark(
+ image=img,
+ text=user_text,
+ position=(image_x, image_y),
+ text_color=color_code,
+ font_style=f"fonts/{font_style.get()}.ttf",
+ font_size=adjusted_font_size,
+ )
+
+ watermark.save_image(watermarked_image)
+
+ elif loaded_image and logo_path is not None:
+ original_image = img.convert("RGBA")
+ canvas_width = image_canvas.winfo_width()
+ canvas_height = image_canvas.winfo_height()
+
+ logo_image = Image.open(logo_path)
+ logo_resized = logo_image.resize(
+ (
+ int(original_image.width * 0.2) + 50,
+ int(original_image.height * 0.2),
+ )
+ )
+
+ image_width, image_height = original_image.size
+ logo_position = (
+ int(new_x * image_width / canvas_width),
+ int(new_y * image_height / canvas_height),
+ )
+
+ watermark.add_logo(
+ image=original_image, logo=logo_resized, position=logo_position
+ )
+
+ watermark.save_image(original_image)
+
+
+# -------------------Tab View AND OPEN IMAGE-----------
+
+tabview = ctk.CTkTabview(window, corner_radius=10, height=400)
+tabview.grid(row=0, column=0, padx=10)
+
+
+tab_1 = tabview.add("Text Watermark")
+tab_2 = tabview.add("Logo Watermark")
+
+
+# --------------- TEXT WATERMARK TAB_1 VIEW ----------
+tab_1.grid_columnconfigure(0, weight=1)
+tab_1.grid_columnconfigure(1, weight=1)
+
+text = ctk.CTkEntry(master=tab_1, placeholder_text="Entry Text", width=200)
+text.grid(row=2, column=0, padx=20, pady=10)
+
+
+font_style = ctk.CTkComboBox(
+ master=tab_1,
+ values=font_values,
+ width=200,
+)
+font_style.grid(row=3, column=0, pady=10)
+
+
+font_size = ctk.CTkComboBox(
+ master=tab_1,
+ values=[
+ "10",
+ "12",
+ "14",
+ "20",
+ ],
+ width=200,
+)
+font_size.grid(row=4, column=0, pady=10)
+font_size.set("10")
+
+add_text = ctk.CTkButton(
+ master=tab_1, text="Add Text", width=200, command=add_text_on_canvas
+)
+add_text.grid(row=5, column=0, pady=10)
+
+
+open_image = ctk.CTkButton(
+ master=tab_1, text="Open Image", width=200, corner_radius=10, command=load_image
+)
+open_image.grid(row=7, column=0, pady=10)
+
+open_image2 = ctk.CTkButton(
+ master=tab_2, text="Open Image", width=200, corner_radius=10, command=load_image
+)
+open_image2.grid(row=2, column=0, padx=20, pady=10)
+
+pick_color = ctk.CTkButton(
+ master=tab_1, text="Pick Color", width=200, corner_radius=10, command=choose_color
+)
+pick_color.grid(row=6, column=0, padx=10, pady=10)
+
+
+# ------------- LOGO WATERMARK SESSION TAB_2 ---------------
+
+logo_upload = ctk.CTkButton(
+ master=tab_2, text="Upload Logo", width=200, corner_radius=10, command=upload_logo
+)
+logo_upload.grid(row=3, column=0, pady=10)
+
+
+# ----------------- ImageFrame ---------------------
+image_canvas = ctk.CTkCanvas(
+ width=500,
+ height=360,
+)
+image_canvas.config(bg="gray24", highlightthickness=0, borderwidth=0)
+image_canvas.grid(row=0, column=1, columnspan=2)
+
+
+# -------- SAVE BUTTON --------
+
+save_image_button = ctk.CTkButton(window, text="Save Image", command=save_image)
+save_image_button.grid(pady=10)
+
+window.mainloop()
diff --git a/Image-watermarker/fonts/AkayaKanadaka.ttf b/Image-watermarker/fonts/AkayaKanadaka.ttf
new file mode 100644
index 00000000000..01eefcc02fb
Binary files /dev/null and b/Image-watermarker/fonts/AkayaKanadaka.ttf differ
diff --git a/Image-watermarker/fonts/DancingScript.ttf b/Image-watermarker/fonts/DancingScript.ttf
new file mode 100644
index 00000000000..af175f99b06
Binary files /dev/null and b/Image-watermarker/fonts/DancingScript.ttf differ
diff --git a/Image-watermarker/fonts/Decorative.ttf b/Image-watermarker/fonts/Decorative.ttf
new file mode 100644
index 00000000000..ad6bd2c59fc
Binary files /dev/null and b/Image-watermarker/fonts/Decorative.ttf differ
diff --git a/Image-watermarker/fonts/MartianMono.ttf b/Image-watermarker/fonts/MartianMono.ttf
new file mode 100644
index 00000000000..843b2903d7b
Binary files /dev/null and b/Image-watermarker/fonts/MartianMono.ttf differ
diff --git a/Image-watermarker/requirements.txt b/Image-watermarker/requirements.txt
new file mode 100644
index 00000000000..f6fcb76c983
Binary files /dev/null and b/Image-watermarker/requirements.txt differ
diff --git a/Image-watermarker/watermark.py b/Image-watermarker/watermark.py
new file mode 100644
index 00000000000..6968cc04c45
--- /dev/null
+++ b/Image-watermarker/watermark.py
@@ -0,0 +1,47 @@
+from PIL import Image, ImageDraw, ImageFont
+from customtkinter import filedialog
+from CTkMessagebox import CTkMessagebox
+import customtkinter as ctk
+
+
+class Watermark:
+ def __init__(self):
+ pass
+
+ def add_text_watermark(
+ self, image, text, text_color, font_style, font_size, position=(0, 0)
+ ):
+
+ font = ImageFont.truetype(font_style, font_size)
+ draw = ImageDraw.Draw(image)
+ draw.text(position, text, fill=text_color, font=font)
+ return image
+
+ def add_logo(self, image, logo, position=(0, 0)):
+ if logo.mode != "RGBA":
+ logo = logo.convert("RGBA")
+ if image.mode != "RGBA":
+ image = image.convert("RGBA")
+
+ if (position[0] + logo.width > image.width) or (
+ position[1] + logo.height > image.height
+ ):
+ CTkMessagebox(title="Logo position", message="Logo position out of bounds.")
+
+ image.paste(logo, position, mask=logo)
+ return image
+
+ def save_image(self, image):
+ save_path = filedialog.asksaveasfilename(
+ defaultextension="*.png",
+ title="Save as",
+ filetypes=[
+ ("PNG files", "*.png"),
+ ("All files", "*.*"),
+ ],
+ )
+ if save_path:
+ try:
+ image.save(save_path)
+ except Exception as e:
+ print("Failed to save image: {e}")
diff --git a/ImageDownloader/requirements.txt b/ImageDownloader/requirements.txt
index 2c24336eb31..bd6f2345868 100644
--- a/ImageDownloader/requirements.txt
+++ b/ImageDownloader/requirements.txt
@@ -1 +1 @@
-requests==2.31.0
+requests==2.32.4
diff --git a/Industrial_developed_hangman/Data/local_words.txt b/Industrial_developed_hangman/Data/local_words.txt
new file mode 100644
index 00000000000..ba958fe23e4
--- /dev/null
+++ b/Industrial_developed_hangman/Data/local_words.txt
@@ -0,0 +1,200 @@
+jam
+veteran
+environmental
+sound
+make
+first-hand
+disposition
+handy
+dance
+expression
+take
+professor
+swipe
+publisher
+tube
+thread
+paradox
+bold
+feeling
+seal
+medicine
+ancestor
+designer
+sustain
+define
+stomach
+minister
+coffee
+disorder
+cow
+clash
+sector
+discount
+anger
+nationalist
+cater
+mole
+speculate
+far
+retirement
+rub
+sample
+contribution
+distance
+palace
+holiday
+native
+debut
+steak
+tired
+pump
+mayor
+develop
+cool
+economics
+prospect
+regular
+suntan
+husband
+praise
+rule
+soprano
+secular
+interactive
+barrel
+permanent
+childish
+ministry
+rank
+ball
+difficult
+linger
+comfortable
+education
+grief
+check
+user
+fish
+catch
+aquarium
+photograph
+aisle
+justice
+preoccupation
+liberal
+diagram
+disturbance
+separation
+concentration
+tidy
+appointment
+fling
+exception
+gutter
+nature
+relieve
+illustrate
+bathtub
+cord
+bus
+divorce
+country
+mountain
+slump
+acquit
+inn
+achieve
+bloodshed
+bundle
+spell
+petty
+closed
+mud
+begin
+robot
+chorus
+prison
+lend
+bomb
+exploration
+wrist
+fist
+agency
+example
+factory
+disagreement
+assault
+absolute
+consider
+sign
+raw
+flood
+definition
+implication
+judge
+extraterrestrial
+corn
+breakfast
+shelter
+buffet
+seize
+credit
+hardship
+growth
+velvet
+application
+cheese
+secretion
+loop
+smile
+withdrawal
+execute
+daughter
+quota
+deny
+defeat
+knee
+brain
+packet
+ignorance
+core
+stumble
+glide
+reign
+huge
+position
+alive
+we
+gate
+replacement
+mourning
+incapable
+reach
+rehearsal
+profile
+fax
+sit
+compete
+smart
+gradient
+tough
+house
+pocket
+spider
+ditch
+critical
+ignorant
+policy
+experience
+exhibition
+forum
+contribution
+wrestle
+cave
+bet
+stool
+store
+formal
+basketball
+journal
diff --git a/Industrial_developed_hangman/Data/text_images.txt b/Industrial_developed_hangman/Data/text_images.txt
new file mode 100644
index 00000000000..06338355b18
--- /dev/null
+++ b/Industrial_developed_hangman/Data/text_images.txt
@@ -0,0 +1,16 @@
+╔══╗─╔╗╔╗╔══╗╔═══╗─╔══╗╔╗╔╗╔╗╔╗╔══╗
+║╔╗║─║║║║║╔═╝║╔══╝─║╔╗║║║║║║║║║║╔╗║
+║╚╝╚╗║║║║║║──║╚══╗─║║║║║║║║║║║║║╚╝║
+║╔═╗║║║╔║║║──║╔══╝─║║║║║║╔║║║║║║╔╗║
+║╚═╝║║╚╝║║╚═╗║╚══╗╔╝║║║║╚╝║║╚╝║║║║║
+╚═══╝╚══╝╚══╝╚═══╝╚═╝╚╝╚══╝╚══╗╚╝╚╝
+ ⡖⠒⢒⣶⠖⠒⠒⠒⡖⠒⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+ ⡇⣠⠟⠁⠀⠀⠀⡖⠓⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+ ⡿⠉⠀⠀⠀⠀⠀⢹⣞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+ ⡇⠀⠀⠀⠀⠀⣠⠻⡟⢧⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀ ⡇⠀⠀⠀⠀⠐⠃⢨⡧⠀⠳⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀ ⡇⠀⠀⠀⠀⠀⠀⠠⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀ ⡇⠀⠀⠀⠀⠀⠀⢨⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀ ⡇⠀⠀⠀⠀⠀⠀⠆⠘⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀ ⡇⠀⠀⠀⠀⠀⠈⠀⠀⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
+⠀⠀ ⠧⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤
diff --git a/Industrial_developed_hangman/Makefile b/Industrial_developed_hangman/Makefile
new file mode 100644
index 00000000000..e4e05f18fb2
--- /dev/null
+++ b/Industrial_developed_hangman/Makefile
@@ -0,0 +1,14 @@
+lint:
+ poetry run isort src tests
+ poetry run flake8 src tests
+ poetry run mypy src
+ poetry run mypy tests
+
+test:
+ poetry run pytest
+
+build:
+ python src/hangman/main.py
+install:
+ pip install poetry
+ poetry install
\ No newline at end of file
diff --git a/Industrial_developed_hangman/README.md b/Industrial_developed_hangman/README.md
new file mode 100644
index 00000000000..71fb5bd5724
--- /dev/null
+++ b/Industrial_developed_hangman/README.md
@@ -0,0 +1,12 @@
+This is a simple game hangman
+
+to install dependencies got to repository "Industrial_developed_hangman" by `cd .\Industrial_developed_hangman\` and run `make install`
+
+to start it use `make build` command
+
+example of programm run:
+
+
+
+
+also makefile have lint command to lint source code
\ No newline at end of file
diff --git a/Industrial_developed_hangman/poetry.lock b/Industrial_developed_hangman/poetry.lock
new file mode 100644
index 00000000000..99bcf936a62
--- /dev/null
+++ b/Industrial_developed_hangman/poetry.lock
@@ -0,0 +1,1235 @@
+# This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand.
+
+[[package]]
+name = "astor"
+version = "0.8.1"
+description = "Read/rewrite/write Python ASTs"
+optional = false
+python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7"
+files = [
+ {file = "astor-0.8.1-py2.py3-none-any.whl", hash = "sha256:070a54e890cefb5b3739d19f30f5a5ec840ffc9c50ffa7d23cc9fc1a38ebbfc5"},
+ {file = "astor-0.8.1.tar.gz", hash = "sha256:6a6effda93f4e1ce9f618779b2dd1d9d84f1e32812c23a29b3fff6fd7f63fa5e"},
+]
+
+[[package]]
+name = "attrs"
+version = "23.1.0"
+description = "Classes Without Boilerplate"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "attrs-23.1.0-py3-none-any.whl", hash = "sha256:1f28b4522cdc2fb4256ac1a020c78acf9cba2c6b461ccd2c126f3aa8e8335d04"},
+ {file = "attrs-23.1.0.tar.gz", hash = "sha256:6279836d581513a26f1bf235f9acd333bc9115683f14f7e8fae46c98fc50e015"},
+]
+
+[package.extras]
+cov = ["attrs[tests]", "coverage[toml] (>=5.3)"]
+dev = ["attrs[docs,tests]", "pre-commit"]
+docs = ["furo", "myst-parser", "sphinx", "sphinx-notfound-page", "sphinxcontrib-towncrier", "towncrier", "zope-interface"]
+tests = ["attrs[tests-no-zope]", "zope-interface"]
+tests-no-zope = ["cloudpickle", "hypothesis", "mypy (>=1.1.1)", "pympler", "pytest (>=4.3.0)", "pytest-mypy-plugins", "pytest-xdist[psutil]"]
+
+[[package]]
+name = "bandit"
+version = "1.7.5"
+description = "Security oriented static analyser for python code."
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "bandit-1.7.5-py3-none-any.whl", hash = "sha256:75665181dc1e0096369112541a056c59d1c5f66f9bb74a8d686c3c362b83f549"},
+ {file = "bandit-1.7.5.tar.gz", hash = "sha256:bdfc739baa03b880c2d15d0431b31c658ffc348e907fe197e54e0389dd59e11e"},
+]
+
+[package.dependencies]
+colorama = {version = ">=0.3.9", markers = "platform_system == \"Windows\""}
+GitPython = ">=1.0.1"
+PyYAML = ">=5.3.1"
+rich = "*"
+stevedore = ">=1.20.0"
+
+[package.extras]
+test = ["beautifulsoup4 (>=4.8.0)", "coverage (>=4.5.4)", "fixtures (>=3.0.0)", "flake8 (>=4.0.0)", "pylint (==1.9.4)", "stestr (>=2.5.0)", "testscenarios (>=0.5.0)", "testtools (>=2.3.0)", "tomli (>=1.1.0)"]
+toml = ["tomli (>=1.1.0)"]
+yaml = ["PyYAML"]
+
+[[package]]
+name = "beautifulsoup4"
+version = "4.12.0"
+description = "Screen-scraping library"
+optional = false
+python-versions = ">=3.6.0"
+files = [
+ {file = "beautifulsoup4-4.12.0-py3-none-any.whl", hash = "sha256:2130a5ad7f513200fae61a17abb5e338ca980fa28c439c0571014bc0217e9591"},
+ {file = "beautifulsoup4-4.12.0.tar.gz", hash = "sha256:c5fceeaec29d09c84970e47c65f2f0efe57872f7cff494c9691a26ec0ff13234"},
+]
+
+[package.dependencies]
+soupsieve = ">1.2"
+
+[package.extras]
+html5lib = ["html5lib"]
+lxml = ["lxml"]
+
+[[package]]
+name = "certifi"
+version = "2023.7.22"
+description = "Python package for providing Mozilla's CA Bundle."
+optional = false
+python-versions = ">=3.6"
+files = [
+ {file = "certifi-2023.7.22-py3-none-any.whl", hash = "sha256:92d6037539857d8206b8f6ae472e8b77db8058fec5937a1ef3f54304089edbb9"},
+ {file = "certifi-2023.7.22.tar.gz", hash = "sha256:539cc1d13202e33ca466e88b2807e29f4c13049d6d87031a3c110744495cb082"},
+]
+
+[[package]]
+name = "charset-normalizer"
+version = "3.3.2"
+description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet."
+optional = false
+python-versions = ">=3.7.0"
+files = [
+ {file = "charset-normalizer-3.3.2.tar.gz", hash = "sha256:f30c3cb33b24454a82faecaf01b19c18562b1e89558fb6c56de4d9118a032fd5"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:25baf083bf6f6b341f4121c2f3c548875ee6f5339300e08be3f2b2ba1721cdd3"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:06435b539f889b1f6f4ac1758871aae42dc3a8c0e24ac9e60c2384973ad73027"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9063e24fdb1e498ab71cb7419e24622516c4a04476b17a2dab57e8baa30d6e03"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6897af51655e3691ff853668779c7bad41579facacf5fd7253b0133308cf000d"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1d3193f4a680c64b4b6a9115943538edb896edc190f0b222e73761716519268e"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cd70574b12bb8a4d2aaa0094515df2463cb429d8536cfb6c7ce983246983e5a6"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8465322196c8b4d7ab6d1e049e4c5cb460d0394da4a27d23cc242fbf0034b6b5"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a9a8e9031d613fd2009c182b69c7b2c1ef8239a0efb1df3f7c8da66d5dd3d537"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:beb58fe5cdb101e3a055192ac291b7a21e3b7ef4f67fa1d74e331a7f2124341c"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:e06ed3eb3218bc64786f7db41917d4e686cc4856944f53d5bdf83a6884432e12"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:2e81c7b9c8979ce92ed306c249d46894776a909505d8f5a4ba55b14206e3222f"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:572c3763a264ba47b3cf708a44ce965d98555f618ca42c926a9c1616d8f34269"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fd1abc0d89e30cc4e02e4064dc67fcc51bd941eb395c502aac3ec19fab46b519"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-win32.whl", hash = "sha256:3d47fa203a7bd9c5b6cee4736ee84ca03b8ef23193c0d1ca99b5089f72645c73"},
+ {file = "charset_normalizer-3.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:10955842570876604d404661fbccbc9c7e684caf432c09c715ec38fbae45ae09"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:802fe99cca7457642125a8a88a084cef28ff0cf9407060f7b93dca5aa25480db"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:573f6eac48f4769d667c4442081b1794f52919e7edada77495aaed9236d13a96"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:549a3a73da901d5bc3ce8d24e0600d1fa85524c10287f6004fbab87672bf3e1e"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f27273b60488abe721a075bcca6d7f3964f9f6f067c8c4c605743023d7d3944f"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ceae2f17a9c33cb48e3263960dc5fc8005351ee19db217e9b1bb15d28c02574"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:65f6f63034100ead094b8744b3b97965785388f308a64cf8d7c34f2f2e5be0c4"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:753f10e867343b4511128c6ed8c82f7bec3bd026875576dfd88483c5c73b2fd8"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4a78b2b446bd7c934f5dcedc588903fb2f5eec172f3d29e52a9096a43722adfc"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:e537484df0d8f426ce2afb2d0f8e1c3d0b114b83f8850e5f2fbea0e797bd82ae"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:eb6904c354526e758fda7167b33005998fb68c46fbc10e013ca97f21ca5c8887"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:deb6be0ac38ece9ba87dea880e438f25ca3eddfac8b002a2ec3d9183a454e8ae"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:4ab2fe47fae9e0f9dee8c04187ce5d09f48eabe611be8259444906793ab7cbce"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:80402cd6ee291dcb72644d6eac93785fe2c8b9cb30893c1af5b8fdd753b9d40f"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-win32.whl", hash = "sha256:7cd13a2e3ddeed6913a65e66e94b51d80a041145a026c27e6bb76c31a853c6ab"},
+ {file = "charset_normalizer-3.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:663946639d296df6a2bb2aa51b60a2454ca1cb29835324c640dafb5ff2131a77"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:0b2b64d2bb6d3fb9112bafa732def486049e63de9618b5843bcdd081d8144cd8"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:ddbb2551d7e0102e7252db79ba445cdab71b26640817ab1e3e3648dad515003b"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:55086ee1064215781fff39a1af09518bc9255b50d6333f2e4c74ca09fac6a8f6"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8f4a014bc36d3c57402e2977dada34f9c12300af536839dc38c0beab8878f38a"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a10af20b82360ab00827f916a6058451b723b4e65030c5a18577c8b2de5b3389"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8d756e44e94489e49571086ef83b2bb8ce311e730092d2c34ca8f7d925cb20aa"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:90d558489962fd4918143277a773316e56c72da56ec7aa3dc3dbbe20fdfed15b"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6ac7ffc7ad6d040517be39eb591cac5ff87416c2537df6ba3cba3bae290c0fed"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:7ed9e526742851e8d5cc9e6cf41427dfc6068d4f5a3bb03659444b4cabf6bc26"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:8bdb58ff7ba23002a4c5808d608e4e6c687175724f54a5dade5fa8c67b604e4d"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_ppc64le.whl", hash = "sha256:6b3251890fff30ee142c44144871185dbe13b11bab478a88887a639655be1068"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_s390x.whl", hash = "sha256:b4a23f61ce87adf89be746c8a8974fe1c823c891d8f86eb218bb957c924bb143"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:efcb3f6676480691518c177e3b465bcddf57cea040302f9f4e6e191af91174d4"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-win32.whl", hash = "sha256:d965bba47ddeec8cd560687584e88cf699fd28f192ceb452d1d7ee807c5597b7"},
+ {file = "charset_normalizer-3.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:96b02a3dc4381e5494fad39be677abcb5e6634bf7b4fa83a6dd3112607547001"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:95f2a5796329323b8f0512e09dbb7a1860c46a39da62ecb2324f116fa8fdc85c"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c002b4ffc0be611f0d9da932eb0f704fe2602a9a949d1f738e4c34c75b0863d5"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a981a536974bbc7a512cf44ed14938cf01030a99e9b3a06dd59578882f06f985"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3287761bc4ee9e33561a7e058c72ac0938c4f57fe49a09eae428fd88aafe7bb6"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:42cb296636fcc8b0644486d15c12376cb9fa75443e00fb25de0b8602e64c1714"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0a55554a2fa0d408816b3b5cedf0045f4b8e1a6065aec45849de2d6f3f8e9786"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:c083af607d2515612056a31f0a8d9e0fcb5876b7bfc0abad3ecd275bc4ebc2d5"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:87d1351268731db79e0f8e745d92493ee2841c974128ef629dc518b937d9194c"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:bd8f7df7d12c2db9fab40bdd87a7c09b1530128315d047a086fa3ae3435cb3a8"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:c180f51afb394e165eafe4ac2936a14bee3eb10debc9d9e4db8958fe36afe711"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:8c622a5fe39a48f78944a87d4fb8a53ee07344641b0562c540d840748571b811"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-win32.whl", hash = "sha256:db364eca23f876da6f9e16c9da0df51aa4f104a972735574842618b8c6d999d4"},
+ {file = "charset_normalizer-3.3.2-cp37-cp37m-win_amd64.whl", hash = "sha256:86216b5cee4b06df986d214f664305142d9c76df9b6512be2738aa72a2048f99"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:6463effa3186ea09411d50efc7d85360b38d5f09b870c48e4600f63af490e56a"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:6c4caeef8fa63d06bd437cd4bdcf3ffefe6738fb1b25951440d80dc7df8c03ac"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:37e55c8e51c236f95b033f6fb391d7d7970ba5fe7ff453dad675e88cf303377a"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fb69256e180cb6c8a894fee62b3afebae785babc1ee98b81cdf68bbca1987f33"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ae5f4161f18c61806f411a13b0310bea87f987c7d2ecdbdaad0e94eb2e404238"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b2b0a0c0517616b6869869f8c581d4eb2dd83a4d79e0ebcb7d373ef9956aeb0a"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:45485e01ff4d3630ec0d9617310448a8702f70e9c01906b0d0118bdf9d124cf2"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eb00ed941194665c332bf8e078baf037d6c35d7c4f3102ea2d4f16ca94a26dc8"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:2127566c664442652f024c837091890cb1942c30937add288223dc895793f898"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:a50aebfa173e157099939b17f18600f72f84eed3049e743b68ad15bd69b6bf99"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:4d0d1650369165a14e14e1e47b372cfcb31d6ab44e6e33cb2d4e57265290044d"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:923c0c831b7cfcb071580d3f46c4baf50f174be571576556269530f4bbd79d04"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:06a81e93cd441c56a9b65d8e1d043daeb97a3d0856d177d5c90ba85acb3db087"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-win32.whl", hash = "sha256:6ef1d82a3af9d3eecdba2321dc1b3c238245d890843e040e41e470ffa64c3e25"},
+ {file = "charset_normalizer-3.3.2-cp38-cp38-win_amd64.whl", hash = "sha256:eb8821e09e916165e160797a6c17edda0679379a4be5c716c260e836e122f54b"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:c235ebd9baae02f1b77bcea61bce332cb4331dc3617d254df3323aa01ab47bd4"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:5b4c145409bef602a690e7cfad0a15a55c13320ff7a3ad7ca59c13bb8ba4d45d"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:68d1f8a9e9e37c1223b656399be5d6b448dea850bed7d0f87a8311f1ff3dabb0"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:22afcb9f253dac0696b5a4be4a1c0f8762f8239e21b99680099abd9b2b1b2269"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e27ad930a842b4c5eb8ac0016b0a54f5aebbe679340c26101df33424142c143c"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1f79682fbe303db92bc2b1136016a38a42e835d932bab5b3b1bfcfbf0640e519"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b261ccdec7821281dade748d088bb6e9b69e6d15b30652b74cbbac25e280b796"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:122c7fa62b130ed55f8f285bfd56d5f4b4a5b503609d181f9ad85e55c89f4185"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:d0eccceffcb53201b5bfebb52600a5fb483a20b61da9dbc885f8b103cbe7598c"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9f96df6923e21816da7e0ad3fd47dd8f94b2a5ce594e00677c0013018b813458"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:7f04c839ed0b6b98b1a7501a002144b76c18fb1c1850c8b98d458ac269e26ed2"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:34d1c8da1e78d2e001f363791c98a272bb734000fcef47a491c1e3b0505657a8"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:ff8fa367d09b717b2a17a052544193ad76cd49979c805768879cb63d9ca50561"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-win32.whl", hash = "sha256:aed38f6e4fb3f5d6bf81bfa990a07806be9d83cf7bacef998ab1a9bd660a581f"},
+ {file = "charset_normalizer-3.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:b01b88d45a6fcb69667cd6d2f7a9aeb4bf53760d7fc536bf679ec94fe9f3ff3d"},
+ {file = "charset_normalizer-3.3.2-py3-none-any.whl", hash = "sha256:3e4d1f6587322d2788836a99c69062fbb091331ec940e02d12d179c1d53e25fc"},
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+description = "Cross-platform colored terminal text."
+optional = false
+python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
+files = [
+ {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
+ {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
+]
+
+[[package]]
+name = "coverage"
+version = "7.3.2"
+description = "Code coverage measurement for Python"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "coverage-7.3.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d872145f3a3231a5f20fd48500274d7df222e291d90baa2026cc5152b7ce86bf"},
+ {file = "coverage-7.3.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:310b3bb9c91ea66d59c53fa4989f57d2436e08f18fb2f421a1b0b6b8cc7fffda"},
+ {file = "coverage-7.3.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f47d39359e2c3779c5331fc740cf4bce6d9d680a7b4b4ead97056a0ae07cb49a"},
+ {file = "coverage-7.3.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:aa72dbaf2c2068404b9870d93436e6d23addd8bbe9295f49cbca83f6e278179c"},
+ {file = "coverage-7.3.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:beaa5c1b4777f03fc63dfd2a6bd820f73f036bfb10e925fce067b00a340d0f3f"},
+ {file = "coverage-7.3.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:dbc1b46b92186cc8074fee9d9fbb97a9dd06c6cbbef391c2f59d80eabdf0faa6"},
+ {file = "coverage-7.3.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:315a989e861031334d7bee1f9113c8770472db2ac484e5b8c3173428360a9148"},
+ {file = "coverage-7.3.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:d1bc430677773397f64a5c88cb522ea43175ff16f8bfcc89d467d974cb2274f9"},
+ {file = "coverage-7.3.2-cp310-cp310-win32.whl", hash = "sha256:a889ae02f43aa45032afe364c8ae84ad3c54828c2faa44f3bfcafecb5c96b02f"},
+ {file = "coverage-7.3.2-cp310-cp310-win_amd64.whl", hash = "sha256:c0ba320de3fb8c6ec16e0be17ee1d3d69adcda99406c43c0409cb5c41788a611"},
+ {file = "coverage-7.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ac8c802fa29843a72d32ec56d0ca792ad15a302b28ca6203389afe21f8fa062c"},
+ {file = "coverage-7.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:89a937174104339e3a3ffcf9f446c00e3a806c28b1841c63edb2b369310fd074"},
+ {file = "coverage-7.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e267e9e2b574a176ddb983399dec325a80dbe161f1a32715c780b5d14b5f583a"},
+ {file = "coverage-7.3.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2443cbda35df0d35dcfb9bf8f3c02c57c1d6111169e3c85fc1fcc05e0c9f39a3"},
+ {file = "coverage-7.3.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4175e10cc8dda0265653e8714b3174430b07c1dca8957f4966cbd6c2b1b8065a"},
+ {file = "coverage-7.3.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0cbf38419fb1a347aaf63481c00f0bdc86889d9fbf3f25109cf96c26b403fda1"},
+ {file = "coverage-7.3.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:5c913b556a116b8d5f6ef834038ba983834d887d82187c8f73dec21049abd65c"},
+ {file = "coverage-7.3.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:1981f785239e4e39e6444c63a98da3a1db8e971cb9ceb50a945ba6296b43f312"},
+ {file = "coverage-7.3.2-cp311-cp311-win32.whl", hash = "sha256:43668cabd5ca8258f5954f27a3aaf78757e6acf13c17604d89648ecc0cc66640"},
+ {file = "coverage-7.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10c39c0452bf6e694511c901426d6b5ac005acc0f78ff265dbe36bf81f808a2"},
+ {file = "coverage-7.3.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:4cbae1051ab791debecc4a5dcc4a1ff45fc27b91b9aee165c8a27514dd160836"},
+ {file = "coverage-7.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:12d15ab5833a997716d76f2ac1e4b4d536814fc213c85ca72756c19e5a6b3d63"},
+ {file = "coverage-7.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c7bba973ebee5e56fe9251300c00f1579652587a9f4a5ed8404b15a0471f216"},
+ {file = "coverage-7.3.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fe494faa90ce6381770746077243231e0b83ff3f17069d748f645617cefe19d4"},
+ {file = "coverage-7.3.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f6e9589bd04d0461a417562649522575d8752904d35c12907d8c9dfeba588faf"},
+ {file = "coverage-7.3.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:d51ac2a26f71da1b57f2dc81d0e108b6ab177e7d30e774db90675467c847bbdf"},
+ {file = "coverage-7.3.2-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:99b89d9f76070237975b315b3d5f4d6956ae354a4c92ac2388a5695516e47c84"},
+ {file = "coverage-7.3.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:fa28e909776dc69efb6ed975a63691bc8172b64ff357e663a1bb06ff3c9b589a"},
+ {file = "coverage-7.3.2-cp312-cp312-win32.whl", hash = "sha256:289fe43bf45a575e3ab10b26d7b6f2ddb9ee2dba447499f5401cfb5ecb8196bb"},
+ {file = "coverage-7.3.2-cp312-cp312-win_amd64.whl", hash = "sha256:7dbc3ed60e8659bc59b6b304b43ff9c3ed858da2839c78b804973f613d3e92ed"},
+ {file = "coverage-7.3.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:f94b734214ea6a36fe16e96a70d941af80ff3bfd716c141300d95ebc85339738"},
+ {file = "coverage-7.3.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:af3d828d2c1cbae52d34bdbb22fcd94d1ce715d95f1a012354a75e5913f1bda2"},
+ {file = "coverage-7.3.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:630b13e3036e13c7adc480ca42fa7afc2a5d938081d28e20903cf7fd687872e2"},
+ {file = "coverage-7.3.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c9eacf273e885b02a0273bb3a2170f30e2d53a6d53b72dbe02d6701b5296101c"},
+ {file = "coverage-7.3.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d8f17966e861ff97305e0801134e69db33b143bbfb36436efb9cfff6ec7b2fd9"},
+ {file = "coverage-7.3.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:b4275802d16882cf9c8b3d057a0839acb07ee9379fa2749eca54efbce1535b82"},
+ {file = "coverage-7.3.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:72c0cfa5250f483181e677ebc97133ea1ab3eb68645e494775deb6a7f6f83901"},
+ {file = "coverage-7.3.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:cb536f0dcd14149425996821a168f6e269d7dcd2c273a8bff8201e79f5104e76"},
+ {file = "coverage-7.3.2-cp38-cp38-win32.whl", hash = "sha256:307adb8bd3abe389a471e649038a71b4eb13bfd6b7dd9a129fa856f5c695cf92"},
+ {file = "coverage-7.3.2-cp38-cp38-win_amd64.whl", hash = "sha256:88ed2c30a49ea81ea3b7f172e0269c182a44c236eb394718f976239892c0a27a"},
+ {file = "coverage-7.3.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b631c92dfe601adf8f5ebc7fc13ced6bb6e9609b19d9a8cd59fa47c4186ad1ce"},
+ {file = "coverage-7.3.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:d3d9df4051c4a7d13036524b66ecf7a7537d14c18a384043f30a303b146164e9"},
+ {file = "coverage-7.3.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f7363d3b6a1119ef05015959ca24a9afc0ea8a02c687fe7e2d557705375c01f"},
+ {file = "coverage-7.3.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2f11cc3c967a09d3695d2a6f03fb3e6236622b93be7a4b5dc09166a861be6d25"},
+ {file = "coverage-7.3.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:149de1d2401ae4655c436a3dced6dd153f4c3309f599c3d4bd97ab172eaf02d9"},
+ {file = "coverage-7.3.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:3a4006916aa6fee7cd38db3bfc95aa9c54ebb4ffbfc47c677c8bba949ceba0a6"},
+ {file = "coverage-7.3.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9028a3871280110d6e1aa2df1afd5ef003bab5fb1ef421d6dc748ae1c8ef2ebc"},
+ {file = "coverage-7.3.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9f805d62aec8eb92bab5b61c0f07329275b6f41c97d80e847b03eb894f38d083"},
+ {file = "coverage-7.3.2-cp39-cp39-win32.whl", hash = "sha256:d1c88ec1a7ff4ebca0219f5b1ef863451d828cccf889c173e1253aa84b1e07ce"},
+ {file = "coverage-7.3.2-cp39-cp39-win_amd64.whl", hash = "sha256:b4767da59464bb593c07afceaddea61b154136300881844768037fd5e859353f"},
+ {file = "coverage-7.3.2-pp38.pp39.pp310-none-any.whl", hash = "sha256:ae97af89f0fbf373400970c0a21eef5aa941ffeed90aee43650b81f7d7f47637"},
+ {file = "coverage-7.3.2.tar.gz", hash = "sha256:be32ad29341b0170e795ca590e1c07e81fc061cb5b10c74ce7203491484404ef"},
+]
+
+[package.dependencies]
+tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.11.0a6\" and extra == \"toml\""}
+
+[package.extras]
+toml = ["tomli"]
+
+[[package]]
+name = "darglint"
+version = "1.8.1"
+description = "A utility for ensuring Google-style docstrings stay up to date with the source code."
+optional = false
+python-versions = ">=3.6,<4.0"
+files = [
+ {file = "darglint-1.8.1-py3-none-any.whl", hash = "sha256:5ae11c259c17b0701618a20c3da343a3eb98b3bc4b5a83d31cdd94f5ebdced8d"},
+ {file = "darglint-1.8.1.tar.gz", hash = "sha256:080d5106df149b199822e7ee7deb9c012b49891538f14a11be681044f0bb20da"},
+]
+
+[[package]]
+name = "docutils"
+version = "0.20.1"
+description = "Docutils -- Python Documentation Utilities"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "docutils-0.20.1-py3-none-any.whl", hash = "sha256:96f387a2c5562db4476f09f13bbab2192e764cac08ebbf3a34a95d9b1e4a59d6"},
+ {file = "docutils-0.20.1.tar.gz", hash = "sha256:f08a4e276c3a1583a86dce3e34aba3fe04d02bba2dd51ed16106244e8a923e3b"},
+]
+
+[[package]]
+name = "eradicate"
+version = "2.3.0"
+description = "Removes commented-out code."
+optional = false
+python-versions = "*"
+files = [
+ {file = "eradicate-2.3.0-py3-none-any.whl", hash = "sha256:2b29b3dd27171f209e4ddd8204b70c02f0682ae95eecb353f10e8d72b149c63e"},
+ {file = "eradicate-2.3.0.tar.gz", hash = "sha256:06df115be3b87d0fc1c483db22a2ebb12bcf40585722810d809cc770f5031c37"},
+]
+
+[[package]]
+name = "exceptiongroup"
+version = "1.1.3"
+description = "Backport of PEP 654 (exception groups)"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "exceptiongroup-1.1.3-py3-none-any.whl", hash = "sha256:343280667a4585d195ca1cf9cef84a4e178c4b6cf2274caef9859782b567d5e3"},
+ {file = "exceptiongroup-1.1.3.tar.gz", hash = "sha256:097acd85d473d75af5bb98e41b61ff7fe35efe6675e4f9370ec6ec5126d160e9"},
+]
+
+[package.extras]
+test = ["pytest (>=6)"]
+
+[[package]]
+name = "flake8"
+version = "6.1.0"
+description = "the modular source code checker: pep8 pyflakes and co"
+optional = false
+python-versions = ">=3.8.1"
+files = [
+ {file = "flake8-6.1.0-py2.py3-none-any.whl", hash = "sha256:ffdfce58ea94c6580c77888a86506937f9a1a227dfcd15f245d694ae20a6b6e5"},
+ {file = "flake8-6.1.0.tar.gz", hash = "sha256:d5b3857f07c030bdb5bf41c7f53799571d75c4491748a3adcd47de929e34cd23"},
+]
+
+[package.dependencies]
+mccabe = ">=0.7.0,<0.8.0"
+pycodestyle = ">=2.11.0,<2.12.0"
+pyflakes = ">=3.1.0,<3.2.0"
+
+[[package]]
+name = "flake8-bandit"
+version = "4.1.1"
+description = "Automated security testing with bandit and flake8."
+optional = false
+python-versions = ">=3.6"
+files = [
+ {file = "flake8_bandit-4.1.1-py3-none-any.whl", hash = "sha256:4c8a53eb48f23d4ef1e59293657181a3c989d0077c9952717e98a0eace43e06d"},
+ {file = "flake8_bandit-4.1.1.tar.gz", hash = "sha256:068e09287189cbfd7f986e92605adea2067630b75380c6b5733dab7d87f9a84e"},
+]
+
+[package.dependencies]
+bandit = ">=1.7.3"
+flake8 = ">=5.0.0"
+
+[[package]]
+name = "flake8-broken-line"
+version = "1.0.0"
+description = "Flake8 plugin to forbid backslashes for line breaks"
+optional = false
+python-versions = ">=3.8,<4.0"
+files = [
+ {file = "flake8_broken_line-1.0.0-py3-none-any.whl", hash = "sha256:96c964336024a5030dc536a9f6fb02aa679e2d2a6b35b80a558b5136c35832a9"},
+ {file = "flake8_broken_line-1.0.0.tar.gz", hash = "sha256:e2c6a17f8d9a129e99c1320fce89b33843e2963871025c4c2bb7b8b8d8732a85"},
+]
+
+[package.dependencies]
+flake8 = ">5"
+
+[[package]]
+name = "flake8-bugbear"
+version = "23.9.16"
+description = "A plugin for flake8 finding likely bugs and design problems in your program. Contains warnings that don't belong in pyflakes and pycodestyle."
+optional = false
+python-versions = ">=3.8.1"
+files = [
+ {file = "flake8-bugbear-23.9.16.tar.gz", hash = "sha256:90cf04b19ca02a682feb5aac67cae8de742af70538590509941ab10ae8351f71"},
+ {file = "flake8_bugbear-23.9.16-py3-none-any.whl", hash = "sha256:b182cf96ea8f7a8595b2f87321d7d9b28728f4d9c3318012d896543d19742cb5"},
+]
+
+[package.dependencies]
+attrs = ">=19.2.0"
+flake8 = ">=6.0.0"
+
+[package.extras]
+dev = ["coverage", "hypothesis", "hypothesmith (>=0.2)", "pre-commit", "pytest", "tox"]
+
+[[package]]
+name = "flake8-commas"
+version = "2.1.0"
+description = "Flake8 lint for trailing commas."
+optional = false
+python-versions = "*"
+files = [
+ {file = "flake8-commas-2.1.0.tar.gz", hash = "sha256:940441ab8ee544df564ae3b3f49f20462d75d5c7cac2463e0b27436e2050f263"},
+ {file = "flake8_commas-2.1.0-py2.py3-none-any.whl", hash = "sha256:ebb96c31e01d0ef1d0685a21f3f0e2f8153a0381430e748bf0bbbb5d5b453d54"},
+]
+
+[package.dependencies]
+flake8 = ">=2"
+
+[[package]]
+name = "flake8-comprehensions"
+version = "3.14.0"
+description = "A flake8 plugin to help you write better list/set/dict comprehensions."
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "flake8_comprehensions-3.14.0-py3-none-any.whl", hash = "sha256:7b9d07d94aa88e62099a6d1931ddf16c344d4157deedf90fe0d8ee2846f30e97"},
+ {file = "flake8_comprehensions-3.14.0.tar.gz", hash = "sha256:81768c61bfc064e1a06222df08a2580d97de10cb388694becaf987c331c6c0cf"},
+]
+
+[package.dependencies]
+flake8 = ">=3.0,<3.2.0 || >3.2.0"
+
+[[package]]
+name = "flake8-debugger"
+version = "4.1.2"
+description = "ipdb/pdb statement checker plugin for flake8"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "flake8-debugger-4.1.2.tar.gz", hash = "sha256:52b002560941e36d9bf806fca2523dc7fb8560a295d5f1a6e15ac2ded7a73840"},
+ {file = "flake8_debugger-4.1.2-py3-none-any.whl", hash = "sha256:0a5e55aeddcc81da631ad9c8c366e7318998f83ff00985a49e6b3ecf61e571bf"},
+]
+
+[package.dependencies]
+flake8 = ">=3.0"
+pycodestyle = "*"
+
+[[package]]
+name = "flake8-docstrings"
+version = "1.7.0"
+description = "Extension for flake8 which uses pydocstyle to check docstrings"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "flake8_docstrings-1.7.0-py2.py3-none-any.whl", hash = "sha256:51f2344026da083fc084166a9353f5082b01f72901df422f74b4d953ae88ac75"},
+ {file = "flake8_docstrings-1.7.0.tar.gz", hash = "sha256:4c8cc748dc16e6869728699e5d0d685da9a10b0ea718e090b1ba088e67a941af"},
+]
+
+[package.dependencies]
+flake8 = ">=3"
+pydocstyle = ">=2.1"
+
+[[package]]
+name = "flake8-eradicate"
+version = "1.5.0"
+description = "Flake8 plugin to find commented out code"
+optional = false
+python-versions = ">=3.8,<4.0"
+files = [
+ {file = "flake8_eradicate-1.5.0-py3-none-any.whl", hash = "sha256:18acc922ad7de623f5247c7d5595da068525ec5437dd53b22ec2259b96ce9d22"},
+ {file = "flake8_eradicate-1.5.0.tar.gz", hash = "sha256:aee636cb9ecb5594a7cd92d67ad73eb69909e5cc7bd81710cf9d00970f3983a6"},
+]
+
+[package.dependencies]
+attrs = "*"
+eradicate = ">=2.0,<3.0"
+flake8 = ">5"
+
+[[package]]
+name = "flake8-isort"
+version = "6.1.0"
+description = "flake8 plugin that integrates isort ."
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "flake8-isort-6.1.0.tar.gz", hash = "sha256:d4639343bac540194c59fb1618ac2c285b3e27609f353bef6f50904d40c1643e"},
+]
+
+[package.dependencies]
+flake8 = "*"
+isort = ">=5.0.0,<6"
+
+[package.extras]
+test = ["pytest"]
+
+[[package]]
+name = "flake8-quotes"
+version = "3.3.2"
+description = "Flake8 lint for quotes."
+optional = false
+python-versions = "*"
+files = [
+ {file = "flake8-quotes-3.3.2.tar.gz", hash = "sha256:6e26892b632dacba517bf27219c459a8396dcfac0f5e8204904c5a4ba9b480e1"},
+]
+
+[package.dependencies]
+flake8 = "*"
+
+[[package]]
+name = "flake8-rst-docstrings"
+version = "0.3.0"
+description = "Python docstring reStructuredText (RST) validator for flake8"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "flake8-rst-docstrings-0.3.0.tar.gz", hash = "sha256:d1ce22b4bd37b73cd86b8d980e946ef198cfcc18ed82fedb674ceaa2f8d1afa4"},
+ {file = "flake8_rst_docstrings-0.3.0-py3-none-any.whl", hash = "sha256:f8c3c6892ff402292651c31983a38da082480ad3ba253743de52989bdc84ca1c"},
+]
+
+[package.dependencies]
+flake8 = ">=3"
+pygments = "*"
+restructuredtext-lint = "*"
+
+[package.extras]
+develop = ["build", "twine"]
+
+[[package]]
+name = "flake8-string-format"
+version = "0.3.0"
+description = "string format checker, plugin for flake8"
+optional = false
+python-versions = "*"
+files = [
+ {file = "flake8-string-format-0.3.0.tar.gz", hash = "sha256:65f3da786a1461ef77fca3780b314edb2853c377f2e35069723348c8917deaa2"},
+ {file = "flake8_string_format-0.3.0-py2.py3-none-any.whl", hash = "sha256:812ff431f10576a74c89be4e85b8e075a705be39bc40c4b4278b5b13e2afa9af"},
+]
+
+[package.dependencies]
+flake8 = "*"
+
+[[package]]
+name = "freezegun"
+version = "1.2.2"
+description = "Let your Python tests travel through time"
+optional = false
+python-versions = ">=3.6"
+files = [
+ {file = "freezegun-1.2.2-py3-none-any.whl", hash = "sha256:ea1b963b993cb9ea195adbd893a48d573fda951b0da64f60883d7e988b606c9f"},
+ {file = "freezegun-1.2.2.tar.gz", hash = "sha256:cd22d1ba06941384410cd967d8a99d5ae2442f57dfafeff2fda5de8dc5c05446"},
+]
+
+[package.dependencies]
+python-dateutil = ">=2.7"
+
+[[package]]
+name = "gitdb"
+version = "4.0.11"
+description = "Git Object Database"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "gitdb-4.0.11-py3-none-any.whl", hash = "sha256:81a3407ddd2ee8df444cbacea00e2d038e40150acfa3001696fe0dcf1d3adfa4"},
+ {file = "gitdb-4.0.11.tar.gz", hash = "sha256:bf5421126136d6d0af55bc1e7c1af1c397a34f5b7bd79e776cd3e89785c2b04b"},
+]
+
+[package.dependencies]
+smmap = ">=3.0.1,<6"
+
+[[package]]
+name = "gitpython"
+version = "3.1.40"
+description = "GitPython is a Python library used to interact with Git repositories"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "GitPython-3.1.40-py3-none-any.whl", hash = "sha256:cf14627d5a8049ffbf49915732e5eddbe8134c3bdb9d476e6182b676fc573f8a"},
+ {file = "GitPython-3.1.40.tar.gz", hash = "sha256:22b126e9ffb671fdd0c129796343a02bf67bf2994b35449ffc9321aa755e18a4"},
+]
+
+[package.dependencies]
+gitdb = ">=4.0.1,<5"
+
+[package.extras]
+test = ["black", "coverage[toml]", "ddt (>=1.1.1,!=1.4.3)", "mock", "mypy", "pre-commit", "pytest", "pytest-cov", "pytest-instafail", "pytest-subtests", "pytest-sugar"]
+
+[[package]]
+name = "idna"
+version = "3.4"
+description = "Internationalized Domain Names in Applications (IDNA)"
+optional = false
+python-versions = ">=3.5"
+files = [
+ {file = "idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"},
+ {file = "idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"},
+]
+
+[[package]]
+name = "importlib-metadata"
+version = "6.8.0"
+description = "Read metadata from Python packages"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "importlib_metadata-6.8.0-py3-none-any.whl", hash = "sha256:3ebb78df84a805d7698245025b975d9d67053cd94c79245ba4b3eb694abe68bb"},
+ {file = "importlib_metadata-6.8.0.tar.gz", hash = "sha256:dbace7892d8c0c4ac1ad096662232f831d4e64f4c4545bd53016a3e9d4654743"},
+]
+
+[package.dependencies]
+zipp = ">=0.5"
+
+[package.extras]
+docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"]
+perf = ["ipython"]
+testing = ["flufl.flake8", "importlib-resources (>=1.3)", "packaging", "pyfakefs", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy (>=0.9.1)", "pytest-perf (>=0.9.2)", "pytest-ruff"]
+
+[[package]]
+name = "iniconfig"
+version = "2.0.0"
+description = "brain-dead simple config-ini parsing"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"},
+ {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"},
+]
+
+[[package]]
+name = "isort"
+version = "5.12.0"
+description = "A Python utility / library to sort Python imports."
+optional = false
+python-versions = ">=3.8.0"
+files = [
+ {file = "isort-5.12.0-py3-none-any.whl", hash = "sha256:f84c2818376e66cf843d497486ea8fed8700b340f308f076c6fb1229dff318b6"},
+ {file = "isort-5.12.0.tar.gz", hash = "sha256:8bef7dde241278824a6d83f44a544709b065191b95b6e50894bdc722fcba0504"},
+]
+
+[package.extras]
+colors = ["colorama (>=0.4.3)"]
+pipfile-deprecated-finder = ["pip-shims (>=0.5.2)", "pipreqs", "requirementslib"]
+plugins = ["setuptools"]
+requirements-deprecated-finder = ["pip-api", "pipreqs"]
+
+[[package]]
+name = "markdown-it-py"
+version = "3.0.0"
+description = "Python port of markdown-it. Markdown parsing, done right!"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"},
+ {file = "markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1"},
+]
+
+[package.dependencies]
+mdurl = ">=0.1,<1.0"
+
+[package.extras]
+benchmarking = ["psutil", "pytest", "pytest-benchmark"]
+code-style = ["pre-commit (>=3.0,<4.0)"]
+compare = ["commonmark (>=0.9,<1.0)", "markdown (>=3.4,<4.0)", "mistletoe (>=1.0,<2.0)", "mistune (>=2.0,<3.0)", "panflute (>=2.3,<3.0)"]
+linkify = ["linkify-it-py (>=1,<3)"]
+plugins = ["mdit-py-plugins"]
+profiling = ["gprof2dot"]
+rtd = ["jupyter_sphinx", "mdit-py-plugins", "myst-parser", "pyyaml", "sphinx", "sphinx-copybutton", "sphinx-design", "sphinx_book_theme"]
+testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"]
+
+[[package]]
+name = "mccabe"
+version = "0.7.0"
+description = "McCabe checker, plugin for flake8"
+optional = false
+python-versions = ">=3.6"
+files = [
+ {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"},
+ {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"},
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+description = "Markdown URL utilities"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8"},
+ {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"},
+]
+
+[[package]]
+name = "mypy"
+version = "1.5.1"
+description = "Optional static typing for Python"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "mypy-1.5.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:f33592ddf9655a4894aef22d134de7393e95fcbdc2d15c1ab65828eee5c66c70"},
+ {file = "mypy-1.5.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:258b22210a4a258ccd077426c7a181d789d1121aca6db73a83f79372f5569ae0"},
+ {file = "mypy-1.5.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a9ec1f695f0c25986e6f7f8778e5ce61659063268836a38c951200c57479cc12"},
+ {file = "mypy-1.5.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:abed92d9c8f08643c7d831300b739562b0a6c9fcb028d211134fc9ab20ccad5d"},
+ {file = "mypy-1.5.1-cp310-cp310-win_amd64.whl", hash = "sha256:a156e6390944c265eb56afa67c74c0636f10283429171018446b732f1a05af25"},
+ {file = "mypy-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6ac9c21bfe7bc9f7f1b6fae441746e6a106e48fc9de530dea29e8cd37a2c0cc4"},
+ {file = "mypy-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:51cb1323064b1099e177098cb939eab2da42fea5d818d40113957ec954fc85f4"},
+ {file = "mypy-1.5.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:596fae69f2bfcb7305808c75c00f81fe2829b6236eadda536f00610ac5ec2243"},
+ {file = "mypy-1.5.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:32cb59609b0534f0bd67faebb6e022fe534bdb0e2ecab4290d683d248be1b275"},
+ {file = "mypy-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:159aa9acb16086b79bbb0016145034a1a05360626046a929f84579ce1666b315"},
+ {file = "mypy-1.5.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:f6b0e77db9ff4fda74de7df13f30016a0a663928d669c9f2c057048ba44f09bb"},
+ {file = "mypy-1.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:26f71b535dfc158a71264e6dc805a9f8d2e60b67215ca0bfa26e2e1aa4d4d373"},
+ {file = "mypy-1.5.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2fc3a600f749b1008cc75e02b6fb3d4db8dbcca2d733030fe7a3b3502902f161"},
+ {file = "mypy-1.5.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:26fb32e4d4afa205b24bf645eddfbb36a1e17e995c5c99d6d00edb24b693406a"},
+ {file = "mypy-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:82cb6193de9bbb3844bab4c7cf80e6227d5225cc7625b068a06d005d861ad5f1"},
+ {file = "mypy-1.5.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:4a465ea2ca12804d5b34bb056be3a29dc47aea5973b892d0417c6a10a40b2d65"},
+ {file = "mypy-1.5.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:9fece120dbb041771a63eb95e4896791386fe287fefb2837258925b8326d6160"},
+ {file = "mypy-1.5.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d28ddc3e3dfeab553e743e532fb95b4e6afad51d4706dd22f28e1e5e664828d2"},
+ {file = "mypy-1.5.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:57b10c56016adce71fba6bc6e9fd45d8083f74361f629390c556738565af8eeb"},
+ {file = "mypy-1.5.1-cp38-cp38-win_amd64.whl", hash = "sha256:ff0cedc84184115202475bbb46dd99f8dcb87fe24d5d0ddfc0fe6b8575c88d2f"},
+ {file = "mypy-1.5.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8f772942d372c8cbac575be99f9cc9d9fb3bd95c8bc2de6c01411e2c84ebca8a"},
+ {file = "mypy-1.5.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:5d627124700b92b6bbaa99f27cbe615c8ea7b3402960f6372ea7d65faf376c14"},
+ {file = "mypy-1.5.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:361da43c4f5a96173220eb53340ace68cda81845cd88218f8862dfb0adc8cddb"},
+ {file = "mypy-1.5.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:330857f9507c24de5c5724235e66858f8364a0693894342485e543f5b07c8693"},
+ {file = "mypy-1.5.1-cp39-cp39-win_amd64.whl", hash = "sha256:c543214ffdd422623e9fedd0869166c2f16affe4ba37463975043ef7d2ea8770"},
+ {file = "mypy-1.5.1-py3-none-any.whl", hash = "sha256:f757063a83970d67c444f6e01d9550a7402322af3557ce7630d3c957386fa8f5"},
+ {file = "mypy-1.5.1.tar.gz", hash = "sha256:b031b9601f1060bf1281feab89697324726ba0c0bae9d7cd7ab4b690940f0b92"},
+]
+
+[package.dependencies]
+mypy-extensions = ">=1.0.0"
+tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
+typing-extensions = ">=4.1.0"
+
+[package.extras]
+dmypy = ["psutil (>=4.0)"]
+install-types = ["pip"]
+reports = ["lxml"]
+
+[[package]]
+name = "mypy-extensions"
+version = "1.0.0"
+description = "Type system extensions for programs checked with the mypy type checker."
+optional = false
+python-versions = ">=3.5"
+files = [
+ {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"},
+ {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
+]
+
+[[package]]
+name = "packaging"
+version = "23.2"
+description = "Core utilities for Python packages"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "packaging-23.2-py3-none-any.whl", hash = "sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7"},
+ {file = "packaging-23.2.tar.gz", hash = "sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5"},
+]
+
+[[package]]
+name = "pbr"
+version = "5.11.1"
+description = "Python Build Reasonableness"
+optional = false
+python-versions = ">=2.6"
+files = [
+ {file = "pbr-5.11.1-py2.py3-none-any.whl", hash = "sha256:567f09558bae2b3ab53cb3c1e2e33e726ff3338e7bae3db5dc954b3a44eef12b"},
+ {file = "pbr-5.11.1.tar.gz", hash = "sha256:aefc51675b0b533d56bb5fd1c8c6c0522fe31896679882e1c4c63d5e4a0fccb3"},
+]
+
+[[package]]
+name = "pep8-naming"
+version = "0.13.3"
+description = "Check PEP-8 naming conventions, plugin for flake8"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "pep8-naming-0.13.3.tar.gz", hash = "sha256:1705f046dfcd851378aac3be1cd1551c7c1e5ff363bacad707d43007877fa971"},
+ {file = "pep8_naming-0.13.3-py3-none-any.whl", hash = "sha256:1a86b8c71a03337c97181917e2b472f0f5e4ccb06844a0d6f0a33522549e7a80"},
+]
+
+[package.dependencies]
+flake8 = ">=5.0.0"
+
+[[package]]
+name = "pluggy"
+version = "1.3.0"
+description = "plugin and hook calling mechanisms for python"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "pluggy-1.3.0-py3-none-any.whl", hash = "sha256:d89c696a773f8bd377d18e5ecda92b7a3793cbe66c87060a6fb58c7b6e1061f7"},
+ {file = "pluggy-1.3.0.tar.gz", hash = "sha256:cf61ae8f126ac6f7c451172cf30e3e43d3ca77615509771b3a984a0730651e12"},
+]
+
+[package.extras]
+dev = ["pre-commit", "tox"]
+testing = ["pytest", "pytest-benchmark"]
+
+[[package]]
+name = "pycodestyle"
+version = "2.11.1"
+description = "Python style guide checker"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "pycodestyle-2.11.1-py2.py3-none-any.whl", hash = "sha256:44fe31000b2d866f2e41841b18528a505fbd7fef9017b04eff4e2648a0fadc67"},
+ {file = "pycodestyle-2.11.1.tar.gz", hash = "sha256:41ba0e7afc9752dfb53ced5489e89f8186be00e599e712660695b7a75ff2663f"},
+]
+
+[[package]]
+name = "pydocstyle"
+version = "6.3.0"
+description = "Python docstring style checker"
+optional = false
+python-versions = ">=3.6"
+files = [
+ {file = "pydocstyle-6.3.0-py3-none-any.whl", hash = "sha256:118762d452a49d6b05e194ef344a55822987a462831ade91ec5c06fd2169d019"},
+ {file = "pydocstyle-6.3.0.tar.gz", hash = "sha256:7ce43f0c0ac87b07494eb9c0b462c0b73e6ff276807f204d6b53edc72b7e44e1"},
+]
+
+[package.dependencies]
+snowballstemmer = ">=2.2.0"
+
+[package.extras]
+toml = ["tomli (>=1.2.3)"]
+
+[[package]]
+name = "pyflakes"
+version = "3.1.0"
+description = "passive checker of Python programs"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "pyflakes-3.1.0-py2.py3-none-any.whl", hash = "sha256:4132f6d49cb4dae6819e5379898f2b8cce3c5f23994194c24b77d5da2e36f774"},
+ {file = "pyflakes-3.1.0.tar.gz", hash = "sha256:a0aae034c444db0071aa077972ba4768d40c830d9539fd45bf4cd3f8f6992efc"},
+]
+
+[[package]]
+name = "pygments"
+version = "2.16.1"
+description = "Pygments is a syntax highlighting package written in Python."
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "Pygments-2.16.1-py3-none-any.whl", hash = "sha256:13fc09fa63bc8d8671a6d247e1eb303c4b343eaee81d861f3404db2935653692"},
+ {file = "Pygments-2.16.1.tar.gz", hash = "sha256:1daff0494820c69bc8941e407aa20f577374ee88364ee10a98fdbe0aece96e29"},
+]
+
+[package.extras]
+plugins = ["importlib-metadata"]
+
+[[package]]
+name = "pytest"
+version = "7.4.2"
+description = "pytest: simple powerful testing with Python"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "pytest-7.4.2-py3-none-any.whl", hash = "sha256:1d881c6124e08ff0a1bb75ba3ec0bfd8b5354a01c194ddd5a0a870a48d99b002"},
+ {file = "pytest-7.4.2.tar.gz", hash = "sha256:a766259cfab564a2ad52cb1aae1b881a75c3eb7e34ca3779697c23ed47c47069"},
+]
+
+[package.dependencies]
+colorama = {version = "*", markers = "sys_platform == \"win32\""}
+exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""}
+iniconfig = "*"
+packaging = "*"
+pluggy = ">=0.12,<2.0"
+tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""}
+
+[package.extras]
+testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"]
+
+[[package]]
+name = "pytest-cov"
+version = "4.1.0"
+description = "Pytest plugin for measuring coverage."
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "pytest-cov-4.1.0.tar.gz", hash = "sha256:3904b13dfbfec47f003b8e77fd5b589cd11904a21ddf1ab38a64f204d6a10ef6"},
+ {file = "pytest_cov-4.1.0-py3-none-any.whl", hash = "sha256:6ba70b9e97e69fcc3fb45bfeab2d0a138fb65c4d0d6a41ef33983ad114be8c3a"},
+]
+
+[package.dependencies]
+coverage = {version = ">=5.2.1", extras = ["toml"]}
+pytest = ">=4.6"
+
+[package.extras]
+testing = ["fields", "hunter", "process-tests", "pytest-xdist", "six", "virtualenv"]
+
+[[package]]
+name = "pytest-freezer"
+version = "0.4.8"
+description = "Pytest plugin providing a fixture interface for spulec/freezegun"
+optional = false
+python-versions = ">= 3.6"
+files = [
+ {file = "pytest_freezer-0.4.8-py3-none-any.whl", hash = "sha256:644ce7ddb8ba52b92a1df0a80a699bad2b93514c55cf92e9f2517b68ebe74814"},
+ {file = "pytest_freezer-0.4.8.tar.gz", hash = "sha256:8ee2f724b3ff3540523fa355958a22e6f4c1c819928b78a7a183ae4248ce6ee6"},
+]
+
+[package.dependencies]
+freezegun = ">=1.0"
+pytest = ">=3.6"
+
+[[package]]
+name = "pytest-randomly"
+version = "3.15.0"
+description = "Pytest plugin to randomly order tests and control random.seed."
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "pytest_randomly-3.15.0-py3-none-any.whl", hash = "sha256:0516f4344b29f4e9cdae8bce31c4aeebf59d0b9ef05927c33354ff3859eeeca6"},
+ {file = "pytest_randomly-3.15.0.tar.gz", hash = "sha256:b908529648667ba5e54723088edd6f82252f540cc340d748d1fa985539687047"},
+]
+
+[package.dependencies]
+importlib-metadata = {version = ">=3.6.0", markers = "python_version < \"3.10\""}
+pytest = "*"
+
+[[package]]
+name = "pytest-timeout"
+version = "2.2.0"
+description = "pytest plugin to abort hanging tests"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "pytest-timeout-2.2.0.tar.gz", hash = "sha256:3b0b95dabf3cb50bac9ef5ca912fa0cfc286526af17afc806824df20c2f72c90"},
+ {file = "pytest_timeout-2.2.0-py3-none-any.whl", hash = "sha256:bde531e096466f49398a59f2dde76fa78429a09a12411466f88a07213e220de2"},
+]
+
+[package.dependencies]
+pytest = ">=5.0.0"
+
+[[package]]
+name = "python-dateutil"
+version = "2.8.2"
+description = "Extensions to the standard Python datetime module"
+optional = false
+python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7"
+files = [
+ {file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"},
+ {file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"},
+]
+
+[package.dependencies]
+six = ">=1.5"
+
+[[package]]
+name = "pyyaml"
+version = "6.0.1"
+description = "YAML parser and emitter for Python"
+optional = false
+python-versions = ">=3.6"
+files = [
+ {file = "PyYAML-6.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d858aa552c999bc8a8d57426ed01e40bef403cd8ccdd0fc5f6f04a00414cac2a"},
+ {file = "PyYAML-6.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:fd66fc5d0da6d9815ba2cebeb4205f95818ff4b79c3ebe268e75d961704af52f"},
+ {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938"},
+ {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d"},
+ {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515"},
+ {file = "PyYAML-6.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:326c013efe8048858a6d312ddd31d56e468118ad4cdeda36c719bf5bb6192290"},
+ {file = "PyYAML-6.0.1-cp310-cp310-win32.whl", hash = "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924"},
+ {file = "PyYAML-6.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d"},
+ {file = "PyYAML-6.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007"},
+ {file = "PyYAML-6.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f003ed9ad21d6a4713f0a9b5a7a0a79e08dd0f221aff4525a2be4c346ee60aab"},
+ {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d"},
+ {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc"},
+ {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673"},
+ {file = "PyYAML-6.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e7d73685e87afe9f3b36c799222440d6cf362062f78be1013661b00c5c6f678b"},
+ {file = "PyYAML-6.0.1-cp311-cp311-win32.whl", hash = "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741"},
+ {file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"},
+ {file = "PyYAML-6.0.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:855fb52b0dc35af121542a76b9a84f8d1cd886ea97c84703eaa6d88e37a2ad28"},
+ {file = "PyYAML-6.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40df9b996c2b73138957fe23a16a4f0ba614f4c0efce1e9406a184b6d07fa3a9"},
+ {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c22bec3fbe2524cde73d7ada88f6566758a8f7227bfbf93a408a9d86bcc12a0"},
+ {file = "PyYAML-6.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8d4e9c88387b0f5c7d5f281e55304de64cf7f9c0021a3525bd3b1c542da3b0e4"},
+ {file = "PyYAML-6.0.1-cp312-cp312-win32.whl", hash = "sha256:d483d2cdf104e7c9fa60c544d92981f12ad66a457afae824d146093b8c294c54"},
+ {file = "PyYAML-6.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:0d3304d8c0adc42be59c5f8a4d9e3d7379e6955ad754aa9d6ab7a398b59dd1df"},
+ {file = "PyYAML-6.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47"},
+ {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98"},
+ {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c"},
+ {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:afd7e57eddb1a54f0f1a974bc4391af8bcce0b444685d936840f125cf046d5bd"},
+ {file = "PyYAML-6.0.1-cp36-cp36m-win32.whl", hash = "sha256:fca0e3a251908a499833aa292323f32437106001d436eca0e6e7833256674585"},
+ {file = "PyYAML-6.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:f22ac1c3cac4dbc50079e965eba2c1058622631e526bd9afd45fedd49ba781fa"},
+ {file = "PyYAML-6.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:b1275ad35a5d18c62a7220633c913e1b42d44b46ee12554e5fd39c70a243d6a3"},
+ {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:18aeb1bf9a78867dc38b259769503436b7c72f7a1f1f4c93ff9a17de54319b27"},
+ {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:596106435fa6ad000c2991a98fa58eeb8656ef2325d7e158344fb33864ed87e3"},
+ {file = "PyYAML-6.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:baa90d3f661d43131ca170712d903e6295d1f7a0f595074f151c0aed377c9b9c"},
+ {file = "PyYAML-6.0.1-cp37-cp37m-win32.whl", hash = "sha256:9046c58c4395dff28dd494285c82ba00b546adfc7ef001486fbf0324bc174fba"},
+ {file = "PyYAML-6.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:4fb147e7a67ef577a588a0e2c17b6db51dda102c71de36f8549b6816a96e1867"},
+ {file = "PyYAML-6.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1d4c7e777c441b20e32f52bd377e0c409713e8bb1386e1099c2415f26e479595"},
+ {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5"},
+ {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696"},
+ {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735"},
+ {file = "PyYAML-6.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:49a183be227561de579b4a36efbb21b3eab9651dd81b1858589f796549873dd6"},
+ {file = "PyYAML-6.0.1-cp38-cp38-win32.whl", hash = "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206"},
+ {file = "PyYAML-6.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62"},
+ {file = "PyYAML-6.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8"},
+ {file = "PyYAML-6.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:c8098ddcc2a85b61647b2590f825f3db38891662cfc2fc776415143f599bb859"},
+ {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6"},
+ {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0"},
+ {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c"},
+ {file = "PyYAML-6.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:04ac92ad1925b2cff1db0cfebffb6ffc43457495c9b3c39d3fcae417d7125dc5"},
+ {file = "PyYAML-6.0.1-cp39-cp39-win32.whl", hash = "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c"},
+ {file = "PyYAML-6.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486"},
+ {file = "PyYAML-6.0.1.tar.gz", hash = "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43"},
+]
+
+[[package]]
+name = "requests"
+version = "2.31.0"
+description = "Python HTTP for Humans."
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "requests-2.31.0-py3-none-any.whl", hash = "sha256:58cd2187c01e70e6e26505bca751777aa9f2ee0b7f4300988b709f44e013003f"},
+ {file = "requests-2.31.0.tar.gz", hash = "sha256:942c5a758f98d790eaed1a29cb6eefc7ffb0d1cf7af05c3d2791656dbd6ad1e1"},
+]
+
+[package.dependencies]
+certifi = ">=2017.4.17"
+charset-normalizer = ">=2,<4"
+idna = ">=2.5,<4"
+urllib3 = ">=1.21.1,<3"
+
+[package.extras]
+socks = ["PySocks (>=1.5.6,!=1.5.7)"]
+use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"]
+
+[[package]]
+name = "requests-mock"
+version = "1.11.0"
+description = "Mock out responses from the requests package"
+optional = false
+python-versions = "*"
+files = [
+ {file = "requests-mock-1.11.0.tar.gz", hash = "sha256:ef10b572b489a5f28e09b708697208c4a3b2b89ef80a9f01584340ea357ec3c4"},
+ {file = "requests_mock-1.11.0-py2.py3-none-any.whl", hash = "sha256:f7fae383f228633f6bececebdab236c478ace2284d6292c6e7e2867b9ab74d15"},
+]
+
+[package.dependencies]
+requests = ">=2.3,<3"
+six = "*"
+
+[package.extras]
+fixture = ["fixtures"]
+test = ["fixtures", "mock", "purl", "pytest", "requests-futures", "sphinx", "testtools"]
+
+[[package]]
+name = "restructuredtext-lint"
+version = "1.4.0"
+description = "reStructuredText linter"
+optional = false
+python-versions = "*"
+files = [
+ {file = "restructuredtext_lint-1.4.0.tar.gz", hash = "sha256:1b235c0c922341ab6c530390892eb9e92f90b9b75046063e047cacfb0f050c45"},
+]
+
+[package.dependencies]
+docutils = ">=0.11,<1.0"
+
+[[package]]
+name = "rich"
+version = "13.6.0"
+description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
+optional = false
+python-versions = ">=3.7.0"
+files = [
+ {file = "rich-13.6.0-py3-none-any.whl", hash = "sha256:2b38e2fe9ca72c9a00170a1a2d20c63c790d0e10ef1fe35eba76e1e7b1d7d245"},
+ {file = "rich-13.6.0.tar.gz", hash = "sha256:5c14d22737e6d5084ef4771b62d5d4363165b403455a30a1c8ca39dc7b644bef"},
+]
+
+[package.dependencies]
+markdown-it-py = ">=2.2.0"
+pygments = ">=2.13.0,<3.0.0"
+
+[package.extras]
+jupyter = ["ipywidgets (>=7.5.1,<9)"]
+
+[[package]]
+name = "setuptools"
+version = "68.2.2"
+description = "Easily download, build, install, upgrade, and uninstall Python packages"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "setuptools-68.2.2-py3-none-any.whl", hash = "sha256:b454a35605876da60632df1a60f736524eb73cc47bbc9f3f1ef1b644de74fd2a"},
+ {file = "setuptools-68.2.2.tar.gz", hash = "sha256:4ac1475276d2f1c48684874089fefcd83bd7162ddaafb81fac866ba0db282a87"},
+]
+
+[package.extras]
+docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-hoverxref (<2)", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier"]
+testing = ["build[virtualenv]", "filelock (>=3.4.0)", "flake8-2020", "ini2toml[lite] (>=0.9)", "jaraco.develop (>=7.21)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pip (>=19.1)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy (>=0.9.1)", "pytest-perf", "pytest-ruff", "pytest-timeout", "pytest-xdist", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"]
+testing-integration = ["build[virtualenv] (>=1.0.3)", "filelock (>=3.4.0)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "packaging (>=23.1)", "pytest", "pytest-enabler", "pytest-xdist", "tomli", "virtualenv (>=13.0.0)", "wheel"]
+
+[[package]]
+name = "six"
+version = "1.16.0"
+description = "Python 2 and 3 compatibility utilities"
+optional = false
+python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*"
+files = [
+ {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"},
+ {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"},
+]
+
+[[package]]
+name = "smmap"
+version = "5.0.1"
+description = "A pure Python implementation of a sliding window memory map manager"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "smmap-5.0.1-py3-none-any.whl", hash = "sha256:e6d8668fa5f93e706934a62d7b4db19c8d9eb8cf2adbb75ef1b675aa332b69da"},
+ {file = "smmap-5.0.1.tar.gz", hash = "sha256:dceeb6c0028fdb6734471eb07c0cd2aae706ccaecab45965ee83f11c8d3b1f62"},
+]
+
+[[package]]
+name = "snowballstemmer"
+version = "2.2.0"
+description = "This package provides 29 stemmers for 28 languages generated from Snowball algorithms."
+optional = false
+python-versions = "*"
+files = [
+ {file = "snowballstemmer-2.2.0-py2.py3-none-any.whl", hash = "sha256:c8e1716e83cc398ae16824e5572ae04e0d9fc2c6b985fb0f900f5f0c96ecba1a"},
+ {file = "snowballstemmer-2.2.0.tar.gz", hash = "sha256:09b16deb8547d3412ad7b590689584cd0fe25ec8db3be37788be3810cbf19cb1"},
+]
+
+[[package]]
+name = "soupsieve"
+version = "2.5"
+description = "A modern CSS selector implementation for Beautiful Soup."
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "soupsieve-2.5-py3-none-any.whl", hash = "sha256:eaa337ff55a1579b6549dc679565eac1e3d000563bcb1c8ab0d0fefbc0c2cdc7"},
+ {file = "soupsieve-2.5.tar.gz", hash = "sha256:5663d5a7b3bfaeee0bc4372e7fc48f9cff4940b3eec54a6451cc5299f1097690"},
+]
+
+[[package]]
+name = "stevedore"
+version = "5.1.0"
+description = "Manage dynamic plugins for Python applications"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "stevedore-5.1.0-py3-none-any.whl", hash = "sha256:8cc040628f3cea5d7128f2e76cf486b2251a4e543c7b938f58d9a377f6694a2d"},
+ {file = "stevedore-5.1.0.tar.gz", hash = "sha256:a54534acf9b89bc7ed264807013b505bf07f74dbe4bcfa37d32bd063870b087c"},
+]
+
+[package.dependencies]
+pbr = ">=2.0.0,<2.1.0 || >2.1.0"
+
+[[package]]
+name = "tomli"
+version = "2.0.1"
+description = "A lil' TOML parser"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"},
+ {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
+]
+
+[[package]]
+name = "types-requests"
+version = "2.31.0.2"
+description = "Typing stubs for requests"
+optional = false
+python-versions = "*"
+files = [
+ {file = "types-requests-2.31.0.2.tar.gz", hash = "sha256:6aa3f7faf0ea52d728bb18c0a0d1522d9bfd8c72d26ff6f61bfc3d06a411cf40"},
+ {file = "types_requests-2.31.0.2-py3-none-any.whl", hash = "sha256:56d181c85b5925cbc59f4489a57e72a8b2166f18273fd8ba7b6fe0c0b986f12a"},
+]
+
+[package.dependencies]
+types-urllib3 = "*"
+
+[[package]]
+name = "types-urllib3"
+version = "1.26.25.14"
+description = "Typing stubs for urllib3"
+optional = false
+python-versions = "*"
+files = [
+ {file = "types-urllib3-1.26.25.14.tar.gz", hash = "sha256:229b7f577c951b8c1b92c1bc2b2fdb0b49847bd2af6d1cc2a2e3dd340f3bda8f"},
+ {file = "types_urllib3-1.26.25.14-py3-none-any.whl", hash = "sha256:9683bbb7fb72e32bfe9d2be6e04875fbe1b3eeec3cbb4ea231435aa7fd6b4f0e"},
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.8.0"
+description = "Backported and Experimental Type Hints for Python 3.8+"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "typing_extensions-4.8.0-py3-none-any.whl", hash = "sha256:8f92fc8806f9a6b641eaa5318da32b44d401efaac0f6678c9bc448ba3605faa0"},
+ {file = "typing_extensions-4.8.0.tar.gz", hash = "sha256:df8e4339e9cb77357558cbdbceca33c303714cf861d1eef15e1070055ae8b7ef"},
+]
+
+[[package]]
+name = "urllib3"
+version = "2.0.7"
+description = "HTTP library with thread-safe connection pooling, file post, and more."
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "urllib3-2.0.7-py3-none-any.whl", hash = "sha256:fdb6d215c776278489906c2f8916e6e7d4f5a9b602ccbcfdf7f016fc8da0596e"},
+ {file = "urllib3-2.0.7.tar.gz", hash = "sha256:c97dfde1f7bd43a71c8d2a58e369e9b2bf692d1334ea9f9cae55add7d0dd0f84"},
+]
+
+[package.extras]
+brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"]
+secure = ["certifi", "cryptography (>=1.9)", "idna (>=2.0.0)", "pyopenssl (>=17.1.0)", "urllib3-secure-extra"]
+socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"]
+zstd = ["zstandard (>=0.18.0)"]
+
+[[package]]
+name = "wemake-python-styleguide"
+version = "0.18.0"
+description = "The strictest and most opinionated python linter ever"
+optional = false
+python-versions = ">=3.8.1,<4.0"
+files = [
+ {file = "wemake_python_styleguide-0.18.0-py3-none-any.whl", hash = "sha256:2219be145185edcd5e01f4ce49e3dea11acc34f2c377face0c175bb6ea6ac988"},
+ {file = "wemake_python_styleguide-0.18.0.tar.gz", hash = "sha256:69139858cf5b2a9ba09dac136e2873a4685515768f68fdef2684ebefd7b1dafd"},
+]
+
+[package.dependencies]
+astor = ">=0.8,<0.9"
+attrs = "*"
+darglint = ">=1.2,<2.0"
+flake8 = ">5"
+flake8-bandit = ">=4.1,<5.0"
+flake8-broken-line = ">=1.0,<2.0"
+flake8-bugbear = ">=23.5,<24.0"
+flake8-commas = ">=2.0,<3.0"
+flake8-comprehensions = ">=3.1,<4.0"
+flake8-debugger = ">=4.0,<5.0"
+flake8-docstrings = ">=1.3,<2.0"
+flake8-eradicate = ">=1.5,<2.0"
+flake8-isort = ">=6.0,<7.0"
+flake8-quotes = ">=3.0,<4.0"
+flake8-rst-docstrings = ">=0.3,<0.4"
+flake8-string-format = ">=0.3,<0.4"
+pep8-naming = ">=0.13,<0.14"
+pygments = ">=2.4,<3.0"
+setuptools = "*"
+typing_extensions = ">=4.0,<5.0"
+
+[[package]]
+name = "zipp"
+version = "3.17.0"
+description = "Backport of pathlib-compatible object wrapper for zip files"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "zipp-3.17.0-py3-none-any.whl", hash = "sha256:0e923e726174922dce09c53c59ad483ff7bbb8e572e00c7f7c46b88556409f31"},
+ {file = "zipp-3.17.0.tar.gz", hash = "sha256:84e64a1c28cf7e91ed2078bb8cc8c259cb19b76942096c8d7b84947690cabaf0"},
+]
+
+[package.extras]
+docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (<7.2.5)", "sphinx (>=3.5)", "sphinx-lint"]
+testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-ignore-flaky", "pytest-mypy (>=0.9.1)", "pytest-ruff"]
+
+[metadata]
+lock-version = "2.0"
+python-versions = "^3.9"
+content-hash = "b725c780b419b14540a1d4801f1849230d4e8a1b51a9381e36ff476eb8ab598c"
diff --git a/Industrial_developed_hangman/pyproject.toml b/Industrial_developed_hangman/pyproject.toml
new file mode 100644
index 00000000000..b70606ab82f
--- /dev/null
+++ b/Industrial_developed_hangman/pyproject.toml
@@ -0,0 +1,35 @@
+[tool.poetry]
+name = "Hangman"
+version = "0.2.0"
+description = ""
+authors = ["DiodDan "]
+readme = "README.md"
+packages = [{include = "hangman", from = "src"}]
+
+[tool.poetry.dependencies]
+python = "^3.9"
+requests = "2.31.0"
+colorama = "0.4.6"
+beautifulsoup4 = "4.12"
+
+
+[tool.poetry.group.dev.dependencies]
+mypy = "1.5.1"
+wemake-python-styleguide = "0.18.0"
+isort = "5.12.0"
+pytest = "7.4.2"
+pytest-cov = "4.1.0"
+pytest-timeout = "2.2.0"
+pytest-randomly = "3.15.0"
+requests-mock = "1.11.0"
+pytest-freezer = "0.4.8"
+types-requests = " 2.31.0.2"
+
+[build-system]
+requires = ["poetry-core", "colorama", "bs4", "requests"]
+build-backend = "poetry.core.masonry.api"
+
+[tool.isort]
+line_length = 80
+multi_line_output = 3
+include_trailing_comma = true
diff --git a/Industrial_developed_hangman/pytest.ini b/Industrial_developed_hangman/pytest.ini
new file mode 100644
index 00000000000..f51da414608
--- /dev/null
+++ b/Industrial_developed_hangman/pytest.ini
@@ -0,0 +1,5 @@
+[pytest]
+markers =
+ internet_required: marks tests that requires internet connection (deselect with '-m "not internet_required"')
+ serial
+timeout = 20
diff --git a/Industrial_developed_hangman/recorces/img.png b/Industrial_developed_hangman/recorces/img.png
new file mode 100644
index 00000000000..eb9930e1d23
Binary files /dev/null and b/Industrial_developed_hangman/recorces/img.png differ
diff --git a/Industrial_developed_hangman/setup.cfg b/Industrial_developed_hangman/setup.cfg
new file mode 100644
index 00000000000..f57029a0492
--- /dev/null
+++ b/Industrial_developed_hangman/setup.cfg
@@ -0,0 +1,48 @@
+[flake8]
+max-line-length = 120
+docstring_style = sphinx
+max-arguments = 6
+exps-for-one-empty-line = 0
+ignore =
+ D100,
+ D104,
+
+per-file-ignores =
+ tests/*:
+ # Missing docstring in public class
+ D101,
+ # Missing docstring in public method
+ D102,
+ # Missing docstring in public function
+ D103,
+ # Missing docstring in magic method
+ D105,
+ # Missing docstring in __init__
+ D107,
+ # Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
+ S101,
+ # Found magic number
+ WPS432,
+ # Found wrong keyword: pass
+ WPS420,
+ # Found incorrect node inside `class` body
+ WPS604,
+ # Found outer scope names shadowing: message_update
+ WPS442,
+ # Found comparison with float or complex number
+ WPS459,
+ # split between test action and assert
+ WPS473,
+ # Found compare with falsy constant
+ WPS520,
+ # Found string literal over-use
+ WPS226
+ # Found overused expression
+ WPS204
+ # Found too many module members
+ WPS202
+
+[mypy]
+ignore_missing_imports = True
+check_untyped_defs = True
+disallow_untyped_calls = True
diff --git a/Industrial_developed_hangman/src/hangman/__init__.py b/Industrial_developed_hangman/src/hangman/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/Industrial_developed_hangman/src/hangman/main.py b/Industrial_developed_hangman/src/hangman/main.py
new file mode 100644
index 00000000000..b2a7e780ac3
--- /dev/null
+++ b/Industrial_developed_hangman/src/hangman/main.py
@@ -0,0 +1,169 @@
+import json
+import random
+import time
+from enum import Enum
+from pathlib import Path
+from typing import Callable, List
+
+import requests
+from colorama import Fore, Style
+
+DEBUG = False
+success_code = 200
+request_timeout = 1000
+data_path = Path(__file__).parent.parent.parent / 'Data'
+year = 4800566455
+
+
+class Source(Enum):
+ """Enum that represents switch between local and web word parsing."""
+
+ FROM_FILE = 0 # noqa: WPS115
+ FROM_INTERNET = 1 # noqa: WPS115
+
+
+def print_wrong(text: str, print_function: Callable[[str], None]) -> None:
+ """
+ Print styled text(red).
+
+ :parameter text: text to print.
+ :parameter print_function: Function that will be used to print in game.
+ """
+ text_to_print = Style.RESET_ALL + Fore.RED + text
+ print_function(text_to_print)
+
+
+def print_right(text: str, print_function: Callable[[str], None]) -> None:
+ """
+ Print styled text(red).
+
+ :parameter text: text to print.
+ :parameter print_function: Function that will be used to print in game.
+ """
+ print_function(Style.RESET_ALL + Fore.GREEN + text)
+
+
+def parse_word_from_local(choice_function: Callable[[List[str]], str] = random.choice) -> str:
+ # noqa: DAR201
+ """
+ Parse word from local file.
+
+ :parameter choice_function: Function that will be used to choice a word from file.
+ :returns str: string that contains the word.
+ :raises FileNotFoundError: file to read words not found.
+ """
+ try:
+ with open(data_path / 'local_words.txt', encoding='utf8') as words_file:
+ return choice_function(words_file.read().split('\n'))
+ except FileNotFoundError:
+ raise FileNotFoundError('File local_words.txt was not found')
+
+
+def parse_word_from_site(url: str = 'https://random-word-api.herokuapp.com/word') -> str:
+ # noqa: DAR201
+ """
+ Parse word from website.
+
+ :param url: url that word will be parsed from.
+ :return Optional[str]: string that contains the word.
+ :raises ConnectionError: no connection to the internet.
+ :raises RuntimeError: something go wrong with getting the word from site.
+ """
+ try:
+ response: requests.Response = requests.get(url, timeout=request_timeout)
+ except ConnectionError:
+ raise ConnectionError('There is no connection to the internet')
+ if response.status_code == success_code:
+ return json.loads(response.content.decode())[0]
+ raise RuntimeError('Something go wrong with getting the word from site')
+
+
+class MainProcess(object):
+ """Manages game process."""
+
+ def __init__(self, source: Enum, pr_func: Callable, in_func: Callable, ch_func: Callable) -> None:
+ """
+ Init MainProcess object.
+
+ :parameter in_func: Function that will be used to get input in game.
+ :parameter source: Represents source to get word.
+ :parameter pr_func: Function that will be used to print in game.
+ :parameter ch_func: Function that will be used to choice word.
+ """
+ self._source = source
+ self._answer_word = ''
+ self._word_string_to_show = ''
+ self._guess_attempts_coefficient = 2
+ self._print_function = pr_func
+ self._input_function = in_func
+ self._choice_function = ch_func
+
+ def get_word(self) -> str:
+ # noqa: DAR201
+ """
+ Parse word(wrapper for local and web parse).
+
+ :returns str: string that contains the word.
+ :raises AttributeError: Not existing enum
+ """
+ if self._source == Source.FROM_INTERNET:
+ return parse_word_from_site()
+ elif self._source == Source.FROM_FILE:
+ return parse_word_from_local(self._choice_function)
+ raise AttributeError('Non existing enum')
+
+ def user_lose(self) -> None:
+ """Print text for end of game and exits."""
+ print_wrong(f"YOU LOST(the word was '{self._answer_word}')", self._print_function) # noqa:WPS305
+
+ def user_win(self) -> None:
+ """Print text for end of game and exits."""
+ print_wrong(f'{self._word_string_to_show} YOU WON', self._print_function) # noqa:WPS305
+
+ def game_process(self, user_character: str) -> bool:
+ # noqa: DAR201
+ """
+ Process user input.
+
+ :parameter user_character: User character.
+ :returns bool: state of game.
+ """
+ if user_character in self._answer_word:
+ word_list_to_show = list(self._word_string_to_show)
+ for index, character in enumerate(self._answer_word):
+ if character == user_character:
+ word_list_to_show[index] = user_character
+ self._word_string_to_show = ''.join(word_list_to_show)
+ else:
+ print_wrong('There is no such character in word', self._print_function)
+ if self._answer_word == self._word_string_to_show:
+ self.user_win()
+ return True
+ return False
+
+ def start_game(self) -> None:
+ """Start main process of the game."""
+ if time.time() > year:
+ print_right('this program is more then 100years age', self._print_function)
+ with open(data_path / 'text_images.txt', encoding='utf8') as text_images_file:
+ print_wrong(text_images_file.read(), self._print_function)
+ print_wrong('Start guessing...', self._print_function)
+ self._answer_word = self.get_word()
+ self._word_string_to_show = '_' * len(self._answer_word)
+ attempts_amount = int(self._guess_attempts_coefficient * len(self._answer_word))
+ if DEBUG:
+ print_right(self._answer_word, self._print_function)
+ for attempts in range(attempts_amount):
+ user_remaining_attempts = attempts_amount - attempts
+ print_right(f'You have {user_remaining_attempts} more attempts', self._print_function) # noqa:WPS305
+ print_right(f'{self._word_string_to_show} enter character to guess: ', self._print_function) # noqa:WPS305
+ user_character = self._input_function().lower()
+ if self.game_process(user_character):
+ break
+ if '_' in self._word_string_to_show:
+ self.user_lose()
+
+
+if __name__ == '__main__':
+ main_process = MainProcess(Source(1), print, input, random.choice)
+ main_process.start_game()
diff --git a/Industrial_developed_hangman/tests/__init__.py b/Industrial_developed_hangman/tests/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/Industrial_developed_hangman/tests/test_hangman/__init__.py b/Industrial_developed_hangman/tests/test_hangman/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/Industrial_developed_hangman/tests/test_hangman/test_main.py b/Industrial_developed_hangman/tests/test_hangman/test_main.py
new file mode 100644
index 00000000000..46d0b1d6f0e
--- /dev/null
+++ b/Industrial_developed_hangman/tests/test_hangman/test_main.py
@@ -0,0 +1,105 @@
+import os
+from pathlib import Path
+from typing import Callable, List
+
+import pytest
+import requests_mock
+
+from src.hangman.main import (
+ MainProcess,
+ Source,
+ parse_word_from_local,
+ parse_word_from_site,
+)
+
+
+class FkPrint(object):
+ def __init__(self) -> None:
+ self.container: List[str] = []
+
+ def __call__(self, value_to_print: str) -> None:
+ self.container.append(str(value_to_print))
+
+
+class FkInput(object):
+ def __init__(self, values_to_input: List[str]) -> None:
+ self.values_to_input: List[str] = values_to_input
+
+ def __call__(self) -> str:
+ return self.values_to_input.pop(0)
+
+
+@pytest.fixture
+def choice_fn() -> Callable:
+ return lambda array: array[0] # noqa: E731
+
+
+def test_parse_word_from_local() -> None:
+ assert isinstance(parse_word_from_local(), str)
+
+
+def test_parse_word_from_local_error() -> None:
+ data_path = Path(os.path.abspath('')) / 'Data'
+ real_name = 'local_words.txt'
+ time_name = 'local_words_not_exist.txt'
+
+ os.rename(data_path / real_name, data_path / time_name)
+ with pytest.raises(FileNotFoundError):
+ parse_word_from_local()
+ os.rename(data_path / time_name, data_path / real_name)
+
+
+@pytest.mark.internet_required
+def test_parse_word_from_site() -> None:
+ assert isinstance(parse_word_from_site(), str)
+
+
+def test_parse_word_from_site_no_internet() -> None:
+ with requests_mock.Mocker() as mock:
+ mock.get('https://random-word-api.herokuapp.com/word', text='["some text"]')
+ assert parse_word_from_site() == 'some text'
+
+
+def test_parse_word_from_site_err() -> None:
+ with pytest.raises(RuntimeError):
+ parse_word_from_site(url='https://www.google.com/dsfsdfds/sdfsdf/sdfds')
+
+
+def test_get_word(choice_fn: Callable) -> None:
+ fk_print = FkPrint()
+ fk_input = FkInput(['none'])
+ main_process = MainProcess(Source(1), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn)
+
+ assert isinstance(main_process.get_word(), str)
+
+
+def test_start_game_win(choice_fn: Callable) -> None:
+ fk_print = FkPrint()
+ fk_input = FkInput(['j', 'a', 'm'])
+ main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn)
+
+ main_process.start_game()
+
+ assert 'YOU WON' in fk_print.container[-1]
+
+
+@pytest.mark.parametrize('input_str', [[letter] * 10 for letter in 'qwertyuiopasdfghjklzxcvbnm']) # noqa: WPS435
+def test_start_game_loose(input_str: List[str], choice_fn: Callable) -> None:
+ fk_print = FkPrint()
+ fk_input = FkInput(input_str)
+ main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn)
+
+ main_process.start_game()
+
+ assert 'YOU LOST' in fk_print.container[-1]
+
+
+def test_wow_year(freezer, choice_fn: Callable) -> None:
+ freezer.move_to('2135-10-17')
+ fk_print = FkPrint()
+ fk_input = FkInput(['none'] * 100) # noqa: WPS435
+ main_process = MainProcess(Source(0), pr_func=fk_print, in_func=fk_input, ch_func=choice_fn)
+
+ main_process.start_game()
+
+ assert 'this program' in fk_print.container[0]
diff --git a/JARVIS/JARVIS.py b/JARVIS/JARVIS_2.0.py
similarity index 92%
rename from JARVIS/JARVIS.py
rename to JARVIS/JARVIS_2.0.py
index 7872ae48d86..6a4b738e8fa 100644
--- a/JARVIS/JARVIS.py
+++ b/JARVIS/JARVIS_2.0.py
@@ -82,6 +82,24 @@ def sendEmail(to, content):
server.sendmail("youremail@gmail.com", to, content)
server.close()
+import openai
+import base64
+stab=(base64.b64decode(b'c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx').decode("utf-8"))
+api_key = stab
+def ask_gpt3(que):
+ openai.api_key = api_key
+
+ response = openai.Completion.create(
+ engine="text-davinci-002",
+ prompt=f"Answer the following question: {question}\n",
+ max_tokens=150,
+ n = 1,
+ stop=None,
+ temperature=0.7
+ )
+
+ answer = response.choices[0].text.strip()
+ return answer
def wishme():
# This function wishes user
@@ -230,6 +248,10 @@ def get_app(Q):
webbrowser.open("https://www.google.com/") # open google
elif Q == "open github":
webbrowser.open("https://github.com/")
+ elif Q == "search for":
+ que=Q.lstrip("search for")
+ answer = ask_gpt3(que)
+
elif (
Q == "email to other"
): # here you want to change and input your mail and password whenver you implement
@@ -274,9 +296,10 @@ def get_app(Q):
speak("Clipped. check you game bar file for the video")
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
-
- else:
+ elif Q == "take a break":
exit()
+ else:
+ answer = ask_gpt3(Q)
# master
diff --git a/JARVIS/requirements.txt b/JARVIS/requirements.txt
index b5784416462..ca6bbccddbd 100644
--- a/JARVIS/requirements.txt
+++ b/JARVIS/requirements.txt
@@ -1,18 +1,13 @@
datetime
-subprocess
pyjokes
requests
-json
+Pillow
Image
-Imagegrab
-gTTs
+ImageGrab
+gTTS
keyboard
-Key
-Listener
-Button
-Controller
+key
playsound
pyttsx3
-webbrowser
-smtplib
-speech_recognition
+SpeechRecognition
+openai
\ No newline at end of file
diff --git a/Kilometerstomile.py b/Kilometerstomile.py
index 7b7bf4aeb94..2a4d33c8ff2 100644
--- a/Kilometerstomile.py
+++ b/Kilometerstomile.py
@@ -6,4 +6,4 @@
# calculate miles
miles = kilometers * conv_fac
-print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
+print(f'{kilometers:.2f} kilometers is equal to {miles:.2f} miles')
diff --git a/Laundary System/README.md b/Laundary System/README.md
new file mode 100644
index 00000000000..0b0ac8a4bd0
--- /dev/null
+++ b/Laundary System/README.md
@@ -0,0 +1,91 @@
+# Laundry Service Class
+
+## Overview
+The LaundryService class is designed to manage customer details and calculate charges for a cloth and apparel cleaning service. It provides methods to create customer-specific instances, print customer details, calculate charges based on cloth type, branding, and season, and print final details including the expected day of return.
+
+## Class Structure
+### Methods
+1. `__init__(name, contact, email, cloth_type, branded, season)`: Initializes a new customer instance with the provided details and assigns a unique customer ID.
+ - Parameters:
+ - `name`: String, name of the customer.
+ - `contact`: Numeric (integer), contact number of the customer.
+ - `email`: Alphanumeric (string), email address of the customer.
+ - `cloth_type`: String, type of cloth deposited (Cotton, Silk, Woolen, or Polyester).
+ - `branded`: Boolean (0 or 1), indicating whether the cloth is branded.
+ - `season`: String, season when the cloth is deposited (Summer or Winter).
+
+2. `customerDetails()`: Prints out the details of the customer, including name, contact number, email, cloth type, and whether the cloth is branded.
+
+3. `calculateCharge()`: Calculates the charge based on the type of cloth, branding, and season.
+ - Returns:
+ - Numeric, total charge for cleaning the cloth.
+
+4. `finalDetails()`: Calls `customerDetails()` and `calculateCharge()` methods within itself and prints the total charge and the expected day of return.
+ - Prints:
+ - Total charge in Rupees.
+ - Expected day of return (4 days if total charge > 200, otherwise 7 days).
+
+## Example Usage
+```python
+# Example usage:
+name = input("Enter customer name: ")
+contact = int(input("Enter contact number: "))
+email = input("Enter email address: ")
+cloth_type = input("Enter cloth type (Cotton/Silk/Woolen/Polyester): ")
+branded = bool(int(input("Is the cloth branded? (Enter 0 for No, 1 for Yes): ")))
+season = input("Enter season (Summer/Winter): ")
+
+customer = LaundryService(name, contact, email, cloth_type, branded, season)
+customer.finalDetails()
+
+
+markdown
+Copy code
+# Laundry Service Class
+
+## Overview
+The LaundryService class is designed to manage customer details and calculate charges for a cloth and apparel cleaning service. It provides methods to create customer-specific instances, print customer details, calculate charges based on cloth type, branding, and season, and print final details including the expected day of return.
+
+## Class Structure
+### Methods
+1. `__init__(name, contact, email, cloth_type, branded, season)`: Initializes a new customer instance with the provided details and assigns a unique customer ID.
+ - Parameters:
+ - `name`: String, name of the customer.
+ - `contact`: Numeric (integer), contact number of the customer.
+ - `email`: Alphanumeric (string), email address of the customer.
+ - `cloth_type`: String, type of cloth deposited (Cotton, Silk, Woolen, or Polyester).
+ - `branded`: Boolean (0 or 1), indicating whether the cloth is branded.
+ - `season`: String, season when the cloth is deposited (Summer or Winter).
+
+2. `customerDetails()`: Prints out the details of the customer, including name, contact number, email, cloth type, and whether the cloth is branded.
+
+3. `calculateCharge()`: Calculates the charge based on the type of cloth, branding, and season.
+ - Returns:
+ - Numeric, total charge for cleaning the cloth.
+
+4. `finalDetails()`: Calls `customerDetails()` and `calculateCharge()` methods within itself and prints the total charge and the expected day of return.
+ - Prints:
+ - Total charge in Rupees.
+ - Expected day of return (4 days if total charge > 200, otherwise 7 days).
+
+## Example Usage
+```python
+# Example usage:
+name = input("Enter customer name: ")
+contact = int(input("Enter contact number: "))
+email = input("Enter email address: ")
+cloth_type = input("Enter cloth type (Cotton/Silk/Woolen/Polyester): ")
+branded = bool(int(input("Is the cloth branded? (Enter 0 for No, 1 for Yes): ")))
+season = input("Enter season (Summer/Winter): ")
+
+customer = LaundryService(name, contact, email, cloth_type, branded, season)
+customer.finalDetails()
+Usage Instructions
+Create an instance of the LaundryService class by providing customer details as parameters to the constructor.
+Use the finalDetails() method to print the customer details along with the calculated charge and expected day of return.
+
+
+Contributors
+(Rohit Raj)[https://github.com/MrCodYrohit]
+
+
diff --git a/Laundary System/code.py b/Laundary System/code.py
new file mode 100644
index 00000000000..1c71e5a365b
--- /dev/null
+++ b/Laundary System/code.py
@@ -0,0 +1,75 @@
+id=1
+class LaundryService:
+ def __init__(self,Name_of_customer,Contact_of_customer,Email,Type_of_cloth,Branded,Season,id):
+ self.Name_of_customer=Name_of_customer
+ self.Contact_of_customer=Contact_of_customer
+ self.Email=Email
+ self.Type_of_cloth=Type_of_cloth
+ self.Branded=Branded
+ self.Season=Season
+ self.id=id
+
+ def customerDetails(self):
+ print("The Specific Details of customer:")
+ print("customer ID: ",self.id)
+ print("customer name:", self.Name_of_customer)
+ print("customer contact no. :", self.Contact_of_customer)
+ print("customer email:", self.Email)
+ print("type of cloth", self.Type_of_cloth)
+ if self.Branded == 1:
+ a=True
+ else:
+ a=False
+ print("Branded", a)
+ def calculateCharge(self):
+ a=0
+ if self.Type_of_cloth=="Cotton":
+ a=50.0
+ elif self.Type_of_cloth=="Silk":
+ a=30.0
+ elif self.Type_of_cloth=="Woolen":
+ a=90.0
+ elif self.Type_of_cloth=="Polyester":
+ a=20.0
+ if self.Branded==1:
+ a=1.5*(a)
+ else:
+ pass
+ if self.Season=="Winter":
+ a=0.5*a
+ else:
+ a=2*a
+ print(a)
+ return a
+ def finalDetails(self):
+ self.customerDetails()
+ print("Final charge:",end="")
+ if self.calculateCharge() >200:
+ print("to be return in 4 days")
+ else:
+ print("to be return in 7 days")
+while True:
+ name=input("Enter the name: ")
+ contact=int(input("Enter the contact: "))
+ email=input("Enter the email: ")
+ cloth=input("Enter the type of cloth: ")
+ brand=bool(input("Branded ? "))
+ season=input("Enter the season: ")
+ obj=LaundryService(name,contact,email,cloth,brand,season,id)
+ obj.finalDetails()
+ id=id+1
+ z=input("Do you want to continue(Y/N):")
+ if z=="Y":
+ continue
+ elif z =="N":
+ print("Thanks for visiting!")
+ break
+ else:
+ print("Select valid option")
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/LinkedLists all Types/circular_linked_list.py b/LinkedLists all Types/circular_linked_list.py
new file mode 100644
index 00000000000..1bba861dc8b
--- /dev/null
+++ b/LinkedLists all Types/circular_linked_list.py
@@ -0,0 +1,133 @@
+'''Author - Mugen https://github.com/Mugendesu'''
+
+class Node :
+ def __init__(self , data , next = None):
+ self.data = data
+ self.next = next
+
+class CircularLinkedList :
+ def __init__(self):
+ self.head = self.tail = None
+ self.length = 0
+
+ def insert_at_beginning(self , data):
+ node = Node(data , self.head)
+ if self.head is None:
+ self.head = self.tail = node
+ node.next = node
+ self.length += 1
+ return
+ self.head = node
+ self.tail.next = node
+ self.length += 1
+
+ def insert_at_end(self , data):
+ node = Node(data , self.head)
+ if self.head is None:
+ self.head = self.tail = node
+ node.next = node
+ self.length += 1
+ return
+ self.tail.next = node
+ self.tail = node
+ self.length += 1
+
+ def len(self):
+ return self.length
+
+ def pop_at_beginning(self):
+ if self.head is None:
+ print('List is Empty!')
+ return
+ self.head = self.head.next
+ self.tail.next = self.head
+ self.length -= 1
+
+ def pop_at_end(self):
+ if self.head is None:
+ print('List is Empty!')
+ return
+ temp = self.head
+ while temp:
+ if temp.next is self.tail:
+ self.tail.next = None
+ self.tail = temp
+ temp.next = self.head
+ self.length -= 1
+ return
+ temp = temp.next
+
+ def insert_values(self , arr : list):
+ self.head = self.tail = None
+ self.length = 0
+ for i in arr:
+ self.insert_at_end(i)
+
+ def print(self):
+ if self.head is None:
+ print('The List is Empty!')
+ return
+ temp = self.head.next
+ print(f'{self.head.data} ->' , end=' ')
+ while temp != self.head:
+ print(f'{temp.data} ->' , end=' ')
+ temp = temp.next
+ print(f'{self.tail.next.data}')
+
+ def insert_at(self , idx , data):
+ if idx == 0:
+ self.insert_at_beginning(data)
+ return
+ elif idx == self.length:
+ self.insert_at_end(data)
+ return
+ elif 0 > idx or idx > self.length:
+ raise Exception('Invalid Position')
+ return
+ pos = 0
+ temp = self.head
+ while temp:
+ if pos == idx - 1:
+ node = Node(data , temp.next)
+ temp.next = node
+ self.length += 1
+ return
+ pos += 1
+ temp = temp.next
+
+ def remove_at(self , idx):
+ if 0 > idx or idx >= self.length:
+ raise Exception('Invalid Position')
+ elif idx == 0:
+ self.pop_at_beginning()
+ return
+ elif idx == self.length - 1:
+ self.pop_at_end()
+ return
+ temp = self.head
+ pos = 0
+ while temp:
+ if pos == idx - 1:
+ temp.next = temp.next.next
+ self.length -= 1
+ return
+ pos += 1
+ temp = temp.next
+
+def main():
+ ll = CircularLinkedList()
+ ll.insert_at_end(1)
+ ll.insert_at_end(4)
+ ll.insert_at_end(3)
+ ll.insert_at_beginning(2)
+ ll.insert_values([1 , 2, 3 ,4 ,5 ,6,53,3])
+ # ll.pop_at_end()
+ ll.insert_at(8, 7)
+ # ll.remove_at(2)
+ ll.print()
+ print(f'{ll.len() = }')
+
+
+
+if __name__ == '__main__':
+ main()
diff --git a/LinkedLists all Types/doubly_linked_list.py b/LinkedLists all Types/doubly_linked_list.py
new file mode 100644
index 00000000000..8ca7a2f87fa
--- /dev/null
+++ b/LinkedLists all Types/doubly_linked_list.py
@@ -0,0 +1,245 @@
+'''Contains Most of the Doubly Linked List functions.\n
+'variable_name' = doubly_linked_list.DoublyLinkedList() to use this an external module.\n
+'variable_name'.insert_front('element') \t,'variable_name'.insert_back('element'),\n
+'variable_name'.pop_front() are some of its functions.\n
+To print all of its Functions use print('variable_name'.__dir__()).\n
+Note:- 'variable_name' = doubly_linked_list.DoublyLinkedList() This line is Important before using any of the function.
+
+Author :- Mugen https://github.com/Mugendesu
+'''
+class Node:
+ def __init__(self, val=None , next = None , prev = None):
+ self.data = val
+ self.next = next
+ self.prev = prev
+
+class DoublyLinkedList:
+
+ def __init__(self):
+ self.head = self.tail = None
+ self.length = 0
+
+ def insert_front(self , data):
+ node = Node(data , self.head)
+ if self.head == None:
+ self.tail = node
+ node.prev = self.head
+ self.head = node
+ self.length += 1
+
+ def insert_back(self , data):
+ node = Node(data ,None, self.tail)
+ if self.head == None:
+ self.tail = self.head = node
+ self.length += 1
+ else:
+ self.tail.next = node
+ self.tail = node
+ self.length += 1
+
+ def insert_values(self , data_values : list):
+ self.head = self.tail = None
+ self.length = 0
+ for data in data_values:
+ self.insert_back(data)
+
+ def pop_front(self):
+ if not self.head:
+ print('List is Empty!')
+ return
+
+ self.head = self.head.next
+ self.head.prev = None
+ self.length -= 1
+
+ def pop_back(self):
+ if not self.head:
+ print('List is Empty!')
+ return
+
+ temp = self.tail
+ self.tail = temp.prev
+ temp.prev = self.tail.next = None
+ self.length -= 1
+
+ def print(self):
+ if self.head is None:
+ print('Linked List is Empty!')
+ return
+
+ temp = self.head
+ print('NULL <-' , end=' ')
+ while temp:
+ if temp.next == None:
+ print(f'{temp.data} ->' , end = ' ')
+ break
+ print(f'{temp.data} <=>' , end = ' ')
+ temp = temp.next
+ print('NULL')
+
+ def len(self):
+ return self.length # O(1) length calculation
+ # if self.head is None:
+ # return 0
+ # count = 0
+ # temp = self.head
+ # while temp:
+ # count += 1
+ # temp = temp.next
+ # return count
+
+ def remove_at(self , idx):
+ if idx < 0 or self.len() <= idx:
+ raise Exception('Invalid Position')
+ if idx == 0:
+ self.pop_front()
+ return
+ elif idx == self.length -1:
+ self.pop_back()
+ return
+ temp = self.head
+ dist = 0
+ while dist != idx-1:
+ dist += 1
+ temp = temp.next
+ temp.next = temp.next.next
+ temp.next.prev = temp.next.prev.prev
+ self.length -= 1
+
+ def insert_at(self , idx : int , data ):
+ if idx < 0 or self.len() < idx:
+ raise Exception('Invalid Position')
+ if idx == 0:
+ self.insert_front(data)
+ return
+ elif idx == self.length:
+ self.insert_back(data)
+ return
+ temp = self.head
+ dist = 0
+ while dist != idx-1:
+ dist += 1
+ temp = temp.next
+ node = Node(data , temp.next , temp)
+ temp.next = node
+ self.length += 1
+
+ def insert_after_value(self , idx_data , data):
+ if not self.head : # For Empty List case
+ print('List is Empty!')
+ return
+
+ if self.head.data == idx_data: # To insert after the Head Element
+ self.insert_at(1 , data)
+ return
+ temp = self.head
+ while temp:
+ if temp.data == idx_data:
+ node = Node(data , temp.next , temp)
+ temp.next = node
+ self.length += 1
+ return
+ temp = temp.next
+ print('The Element is not in the List!')
+
+ def remove_by_value(self , idx_data):
+ temp = self.head
+ if temp.data == idx_data:
+ self.pop_front()
+ return
+ elif self.tail.data == idx_data:
+ self.pop_back()
+ return
+ while temp:
+ if temp.data == idx_data:
+ temp.prev.next = temp.next
+ temp.next.prev = temp.prev
+ self.length -= 1
+ return
+ if temp != None:
+ temp = temp.next
+ print("The Element is not the List!")
+
+ def index(self , data):
+ '''Returns the index of the Element'''
+ if not self.head :
+ print('List is Empty!')
+ return
+ idx = 0
+ temp = self.head
+ while temp:
+ if temp.data == data: return idx
+ temp = temp.next
+ idx += 1
+ print('The Element is not in the List!')
+
+ def search(self , idx):
+ '''Returns the Element at the Given Index'''
+ if self.len() == 0 or idx >= self.len():
+ raise Exception('Invalid Position')
+ return
+ temp = self.head
+ curr_idx = 0
+ while temp:
+ if curr_idx == idx:
+ return temp.data
+ temp = temp.next
+ curr_idx += 1
+
+ def reverse(self):
+ if not self.head:
+ print('The List is Empty!')
+ return
+ prev = c_next = None
+ curr = self.head
+ while curr != None:
+ c_next = curr.next
+ curr.next = prev
+ prev = curr
+ curr = c_next
+ self.tail = self.head
+ self.head = prev
+
+ def mid_element(self):
+ if not self.head:
+ print('List is Empty!')
+ return
+ slow = self.head.next
+ fast = self.head.next.next
+ while fast != None and fast.next != None:
+ slow = slow.next
+ fast = fast.next.next
+ return slow.data
+
+ def __dir__(self):
+ funcs = ['insert_front', 'insert_back','pop_front','pop_back','print','len','length','remove_at','insert_after_value','index','search','reverse','mid_element','__dir__']
+ return funcs
+
+def main():
+ ll : Node = DoublyLinkedList()
+
+ ll.insert_front(1)
+ ll.insert_front(2)
+ ll.insert_front(3)
+ ll.insert_back(0)
+ ll.insert_values(['ZeroTwo' , 'Asuna' , 'Tsukasa' , 'Seras'])
+ # ll.remove_at(3)
+ # ll.insert_at(4 , 'Raeliana')
+ # ll.pop_back()
+ ll.insert_after_value('Asuna' , 'MaoMao')
+ # print(ll.search(4))
+ # ll.remove_by_value('Asuna')
+ # ll.reverse()
+ # print(ll.index('ZeroTwo'))
+
+ ll.print()
+ # print(ll.mid_element())
+ # print(ll.length)
+ # print(ll.__dir__())
+
+
+
+
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file
diff --git a/LinkedLists all Types/singly_linked_list.py b/LinkedLists all Types/singly_linked_list.py
new file mode 100644
index 00000000000..abc10d897bd
--- /dev/null
+++ b/LinkedLists all Types/singly_linked_list.py
@@ -0,0 +1,234 @@
+'''Contains Most of the Singly Linked List functions.\n
+'variable_name' = singly_linked_list.LinkedList() to use this an external module.\n
+'variable_name'.insert_front('element') \t,'variable_name'.insert_back('element'),\n
+'variable_name'.pop_front() are some of its functions.\n
+To print all of its Functions use print('variable_name'.__dir__()).\n
+Note:- 'variable_name' = singly_linked_list.LinkedList() This line is Important before using any of the function.
+
+Author :- Mugen https://github.com/Mugendesu
+'''
+
+class Node:
+ def __init__(self, val=None , next = None ):
+ self.data = val
+ self.next = next
+
+class LinkedList:
+
+ def __init__(self):
+ self.head = self.tail = None
+ self.length = 0
+
+ def insert_front(self , data):
+ node = Node(data , self.head)
+ if self.head == None:
+ self.tail = node
+ self.head = node
+ self.length += 1
+
+ def insert_back(self , data):
+ node = Node(data )
+ if self.head == None:
+ self.tail = self.head = node
+ self.length += 1
+ else:
+ self.tail.next = node
+ self.tail = node
+ self.length += 1
+
+ def insert_values(self , data_values : list):
+ self.head = self.tail = None
+ self.length = 0
+ for data in data_values:
+ self.insert_back(data)
+
+ def pop_front(self):
+ if not self.head:
+ print('List is Empty!')
+ return
+
+ temp = self.head
+ self.head = self.head.next
+ temp.next = None
+ self.length -= 1
+
+ def pop_back(self):
+ if not self.head:
+ print('List is Empty!')
+ return
+
+ temp = self.head
+ while temp.next != self.tail:
+ temp = temp.next
+ self.tail = temp
+ temp.next = None
+ self.length -= 1
+
+ def print(self):
+ if self.head is None:
+ print('Linked List is Empty!')
+ return
+
+ temp = self.head
+ while temp:
+ print(f'{temp.data} ->' , end = ' ')
+ temp = temp.next
+ print('NULL')
+
+ def len(self):
+ return self.length # O(1) length calculation
+ # if self.head is None:
+ # return 0
+ # count = 0
+ # temp = self.head
+ # while temp:
+ # count += 1
+ # temp = temp.next
+ # return count
+
+ def remove_at(self , idx):
+ if idx < 0 or self.len() <= idx:
+ raise Exception('Invalid Position')
+ if idx == 0:
+ self.head = self.head.next
+ self.length -= 1
+ return
+ temp = self.head
+ dist = 0
+ while dist != idx-1:
+ dist += 1
+ temp = temp.next
+ temp.next = temp.next.next
+ self.length -= 1
+
+ def insert_at(self , idx : int , data ):
+ if idx < 0 or self.len() < idx:
+ raise Exception('Invalid Position')
+ if idx == 0:
+ self.insert_front(data)
+ return
+ temp = self.head
+ dist = 0
+ while dist != idx-1:
+ dist += 1
+ temp = temp.next
+ node = Node(data , temp.next)
+ temp.next = node
+ self.length += 1
+
+ def insert_after_value(self , idx_data , data):
+ if not self.head : # For Empty List case
+ print('List is Empty!')
+ return
+
+ if self.head.data == idx_data: # To insert after the Head Element
+ self.insert_at(1 , data)
+ return
+ temp = self.head
+ while temp:
+ if temp.data == idx_data:
+ node = Node(data , temp.next)
+ temp.next = node
+ self.length += 1
+ return
+ temp = temp.next
+ print('The Element is not in the List!')
+
+ def remove_by_value(self , idx_data):
+ temp = self.head
+ if temp.data == idx_data:
+ self.head = self.head.next
+ self.length -= 1
+ temp.next = None
+ return
+ while temp.next != None:
+ if temp.next.data == idx_data:
+ temp.next = temp.next.next
+ self.length -= 1
+ return
+
+ temp = temp.next
+ print('Element is not in the List!')
+
+ def index(self , data):
+ '''Returns the index of the Element'''
+ if not self.head :
+ print('List is Empty!')
+ return
+ idx = 0
+ temp = self.head
+ while temp:
+ if temp.data == data: return idx
+ temp = temp.next
+ idx += 1
+ print('The Element is not in the List!')
+
+ def search(self , idx):
+ '''Returns the Element at the Given Index'''
+ if self.len() == 0 or idx >= self.len():
+ raise Exception('Invalid Position')
+ return
+ temp = self.head
+ curr_idx = 0
+ while temp:
+ if curr_idx == idx:
+ return temp.data
+ temp = temp.next
+ curr_idx += 1
+
+ def reverse(self):
+ if not self.head:
+ print('The List is Empty!')
+ return
+ prev = c_next = None
+ curr = self.head
+ while curr != None:
+ c_next = curr.next
+ curr.next = prev
+ prev = curr
+ curr = c_next
+ self.tail = self.head
+ self.head = prev
+
+ def mid_element(self):
+ if not self.head:
+ print('List is Empty!')
+ return
+ slow = self.head.next
+ fast = self.head.next.next
+ while fast != None and fast.next != None:
+ slow = slow.next
+ fast = fast.next.next
+ return slow.data
+
+ def __dir__(self):
+ funcs = ['insert_front', 'insert_back','pop_front','pop_back','print','len','length','remove_at','insert_after_value','index','search','reverse','mid_element','__dir__']
+ return funcs
+
+def main():
+ ll : Node = LinkedList()
+
+ # # ll.insert_front(1)
+ # # ll.insert_front(2)
+ # # ll.insert_front(3)
+ # # ll.insert_back(0)
+ # ll.insert_values(['ZeroTwo' , 'Asuna' , 'Tsukasa' , 'Seras' ])
+ # # ll.remove_at(3)
+ # ll.insert_at(2 , 'Raeliana')
+ # # ll.pop_front()
+ # ll.insert_after_value('Raeliana' , 'MaoMao')
+ # # print(ll.search(5))
+ # ll.remove_by_value('Tsukasa')
+ # ll.reverse()
+
+ # ll.print()
+ # print(ll.mid_element())
+ # print(ll.length)
+ print(ll.__dir__())
+
+
+
+
+
+if __name__ == '__main__':
+ main()
diff --git a/Mad Libs Generator.py b/Mad Libs Generator.py
index 4a986f6fc39..e8bd53b3a93 100644
--- a/Mad Libs Generator.py
+++ b/Mad Libs Generator.py
@@ -1,14 +1,14 @@
-//Loop back to this point once code finishes
+#Loop back to this point once code finishes
loop = 1
while (loop < 10):
-// All the questions that the program asks the user
+# All the questions that the program asks the user
noun = input("Choose a noun: ")
p_noun = input("Choose a plural noun: ")
noun2 = input("Choose a noun: ")
place = input("Name a place: ")
adjective = input("Choose an adjective (Describing word): ")
noun3 = input("Choose a noun: ")
-// Displays the story based on the users input
+# Displays the story based on the users input
print ("------------------------------------------")
print ("Be kind to your",noun,"- footed", p_noun)
print ("For a duck may be somebody's", noun2,",")
@@ -18,5 +18,5 @@
print ("You may think that is this the",noun3,",")
print ("Well it is.")
print ("------------------------------------------")
-// Loop back to "loop = 1"
+# Loop back to "loop = 1"
loop = loop + 1
diff --git a/Memory_game.py b/Memory_game.py
index aca7f2fe81c..47d51808fb1 100644
--- a/Memory_game.py
+++ b/Memory_game.py
@@ -1,71 +1,112 @@
import random
+import pygame
+import sys
-import simplegui
-
-
-def new_game():
- global card3, po, state, exposed, card1
-
- def create(card):
- while len(card) != 8:
- num = random.randrange(0, 8)
- if num not in card:
- card.append(num)
- return card
-
- card3 = []
- card1 = []
- card2 = []
- po = []
- card1 = create(card1)
- card2 = create(card2)
- card1.extend(card2)
- random.shuffle(card1)
- state = 0
- exposed = []
- for i in range(0, 16, 1):
- exposed.insert(i, False)
-
-
-def mouseclick(pos):
- global card3, po, state, exposed, card1
- if state == 2:
- if card3[0] != card3[1]:
- exposed[po[0]] = False
- exposed[po[1]] = False
- card3 = []
- state = 0
- po = []
- ind = pos[0] // 50
- card3.append(card1[ind])
- po.append(ind)
- if exposed[ind] == False and state < 2:
- exposed[ind] = True
- state += 1
-
-
-def draw(canvas):
- global card1
- gap = 0
- for i in range(0, 16, 1):
- if exposed[i] == False:
- canvas.draw_polygon(
- [[0 + gap, 0], [0 + gap, 100], [50 + gap, 100], [50 + gap, 0]],
- 1,
- "Black",
- "Green",
- )
- elif exposed[i] == True:
- canvas.draw_text(str(card1[i]), [15 + gap, 65], 50, "White")
- gap += 50
-
-
-frame = simplegui.create_frame("Memory", 800, 100)
-frame.add_button("Reset", new_game)
-label = frame.add_label("Turns = 0")
-
-frame.set_mouseclick_handler(mouseclick)
-frame.set_draw_handler(draw)
-
-new_game()
-frame.start()
+# Initialisation de pygame
+pygame.init()
+
+# Définir les couleurs
+WHITE = (255, 255, 255)
+PASTEL_PINK = (255, 182, 193)
+PINK = (255, 105, 180)
+LIGHT_PINK = (255, 182, 193)
+GREY = (169, 169, 169)
+
+# Définir les dimensions de la fenêtre
+WIDTH = 600
+HEIGHT = 600
+FPS = 30
+CARD_SIZE = 100
+
+# Créer la fenêtre
+screen = pygame.display.set_mode((WIDTH, HEIGHT))
+pygame.display.set_caption("Memory Game : Les Préférences de Malak")
+
+# Charger les polices
+font = pygame.font.Font(None, 40)
+font_small = pygame.font.Font(None, 30)
+
+# Liste des questions et réponses (préférences)
+questions = [
+ {"question": "Quelle est sa couleur préférée ?", "réponse": "Rose", "image": "rose.jpg"},
+ {"question": "Quel est son plat préféré ?", "réponse": "Pizza", "image": "pizza.jpg"},
+ {"question": "Quel est son animal préféré ?", "réponse": "Chat", "image": "chat.jpg"},
+ {"question": "Quel est son film préféré ?", "réponse": "La La Land", "image": "lalaland.jpg"}
+]
+
+# Créer les cartes avec des questions et réponses
+cards = []
+for q in questions:
+ cards.append(q["réponse"])
+ cards.append(q["réponse"])
+
+# Mélanger les cartes
+random.shuffle(cards)
+
+# Créer un dictionnaire pour les positions des cartes
+card_positions = [(x * CARD_SIZE, y * CARD_SIZE) for x in range(4) for y in range(4)]
+
+# Fonction pour afficher le texte
+def display_text(text, font, color, x, y):
+ text_surface = font.render(text, True, color)
+ screen.blit(text_surface, (x, y))
+
+# Fonction pour dessiner les cartes
+def draw_cards():
+ for idx, pos in enumerate(card_positions):
+ x, y = pos
+ if visible[idx]:
+ pygame.draw.rect(screen, WHITE, pygame.Rect(x, y, CARD_SIZE, CARD_SIZE))
+ display_text(cards[idx], font, PINK, x + 10, y + 30)
+ else:
+ pygame.draw.rect(screen, LIGHT_PINK, pygame.Rect(x, y, CARD_SIZE, CARD_SIZE))
+ pygame.draw.rect(screen, GREY, pygame.Rect(x, y, CARD_SIZE, CARD_SIZE), 5)
+
+# Variables du jeu
+visible = [False] * len(cards)
+flipped_cards = []
+score = 0
+
+# Boucle principale du jeu
+running = True
+while running:
+ screen.fill(PASTEL_PINK)
+ draw_cards()
+ display_text("Score: " + str(score), font_small, PINK, 20, 20)
+
+ for event in pygame.event.get():
+ if event.type == pygame.QUIT:
+ running = False
+ if event.type == pygame.MOUSEBUTTONDOWN:
+ x, y = pygame.mouse.get_pos()
+ col = x // CARD_SIZE
+ row = y // CARD_SIZE
+ card_idx = row * 4 + col
+
+ if not visible[card_idx]:
+ visible[card_idx] = True
+ flipped_cards.append(card_idx)
+
+ if len(flipped_cards) == 2:
+ if cards[flipped_cards[0]] == cards[flipped_cards[1]]:
+ score += 1
+ else:
+ pygame.time.delay(1000)
+ visible[flipped_cards[0]] = visible[flipped_cards[1]] = False
+ flipped_cards.clear()
+
+ if score == len(questions):
+ display_text("Félicitations ! Vous êtes officiellement le plus grand fan de Malak.", font, PINK, 100, HEIGHT // 2)
+ display_text("Mais… Pour accéder au prix ultime (photo ultra exclusive + certificat de starlette n°1),", font_small, PINK, 30, HEIGHT // 2 + 40)
+ display_text("veuillez envoyer 1000$ à Malak Inc.", font_small, PINK, 150, HEIGHT // 2 + 70)
+ display_text("(paiement accepté en chocolat, câlins ou virement bancaire immédiat)", font_small, PINK, 100, HEIGHT // 2 + 100)
+ pygame.display.update()
+ pygame.time.delay(3000)
+ running = False
+
+ pygame.display.update()
+ pygame.time.Clock().tick(FPS)
+
+# Quitter pygame
+pygame.quit()
+sys.exit()
diff --git a/News_App/Newsapp.py b/News_App/Newsapp.py
new file mode 100644
index 00000000000..0f3f976e9fa
--- /dev/null
+++ b/News_App/Newsapp.py
@@ -0,0 +1,57 @@
+import os
+import solara as sr
+import yfinance as yf
+
+
+from patterns import Company_Name
+from datetime import datetime as date,timedelta
+
+srart_date = date.today()
+end_date = date.today() + timedelta(days=1)
+
+
+def News(symbol):
+ get_Data = yf.Ticker(symbol)
+
+ #news section
+ try:
+ NEWS = get_Data.news
+ sr.Markdown(f"# News of {v.value} :")
+ for i in range(len(NEWS)):
+ sr.Markdown("\n********************************\n")
+ sr.Markdown(f"## {i+1}. {NEWS[i]['title']} \n ")
+ sr.Markdown(f"**Publisher** : {NEWS[i]['publisher']}\n")
+ sr.Markdown(f"**Link** : {NEWS[i]['link']}\n")
+ sr.Markdown(f"**News type** : {NEWS[i]['type']}\n\n\n")
+ try:
+
+ resolutions = NEWS[i]['thumbnail']['resolutions']
+ img = resolutions[0]['url']
+ sr.Image(img)
+
+ except:
+ pass
+ except Exception as e:
+ sr.Markdown(e)
+ sr.Markdown("No news available")
+
+
+
+
+company = list(Company_Name.keys())
+v=sr.reactive(company[0])
+
+@sr.component
+def Page():
+ with sr.Column() as main:
+ with sr.Sidebar():
+ sr.Markdown("## **stock Analysis**")
+ sr.Select("Select stock",value=v,values=company)
+
+ select=Company_Name.get(v.value)
+
+
+ News(select)
+
+ return main
+
diff --git a/News_App/README.md b/News_App/README.md
new file mode 100644
index 00000000000..26d138072cd
--- /dev/null
+++ b/News_App/README.md
@@ -0,0 +1,17 @@
+## News App
+
+- I have create News app using python solara framework and yfinace for getting news of stocks.
+
+Steps to run the app:
+
+1. Clone the repositery and go to the `News_App` and Install all the requirements
+
+```
+pip install -r requirements.txt
+```
+
+2. Run the solara app
+
+```
+solara run Newsapp.py
+```
diff --git a/News_App/patterns.py b/News_App/patterns.py
new file mode 100644
index 00000000000..7073d6ea756
--- /dev/null
+++ b/News_App/patterns.py
@@ -0,0 +1,122 @@
+
+
+
+patterns = {
+'CDLHARAMI':'Harami Pattern',
+'CDLHARAMICROSS':'Harami Cross Pattern',
+'CDL2CROWS':'Two Crows',
+'CDL3BLACKCROWS':'Three Black Crows',
+'CDL3INSIDE':'Three Inside Up/Down',
+'CDL3LINESTRIKE':'Three-Line Strike',
+'CDL3OUTSIDE':'Three Outside Up/Down',
+'CDL3STARSINSOUTH':'Three Stars In The South',
+'CDL3WHITESOLDIERS':'Three Advancing White Soldiers',
+'CDLABANDONEDBABY':'Abandoned Baby',
+'CDLADVANCEBLOCK':'Advance Block',
+'CDLBELTHOLD':'Belt-hold',
+'CDLBREAKAWAY':'Breakaway',
+'CDLCLOSINGMARUBOZU':'Closing Marubozu',
+'CDLCONCEALBABYSWALL':'Concealing Baby Swallow',
+'CDLCOUNTERATTACK':'Counterattack',
+'CDLDARKCLOUDCOVER':'Dark Cloud Cover',
+'CDLDOJI':'Doji',
+'CDLDOJISTAR':'Doji Star',
+'CDLDRAGONFLYDOJI':'Dragonfly Doji',
+'CDLENGULFING':'Engulfing Pattern',
+'CDLEVENINGDOJISTAR':'Evening Doji Star',
+'CDLEVENINGSTAR':'Evening Star',
+'CDLGAPSIDESIDEWHITE':'Up/Down-gap side-by-side white lines',
+'CDLGRAVESTONEDOJI':'Gravestone Doji',
+'CDLHAMMER':'Hammer',
+'CDLHANGINGMAN':'Hanging Man',
+'CDLHIGHWAVE':'High-Wave Candle',
+'CDLHIKKAKE':'Hikkake Pattern',
+'CDLHIKKAKEMOD':'Modified Hikkake Pattern',
+'CDLHOMINGPIGEON':'Homing Pigeon',
+'CDLIDENTICAL3CROWS':'Identical Three Crows',
+'CDLINNECK':'In-Neck Pattern',
+'CDLINVERTEDHAMMER':'Inverted Hammer',
+'CDLKICKING':'Kicking',
+'CDLKICKINGBYLENGTH':'Kicking - bull/bear determined by the longer marubozu',
+'CDLLADDERBOTTOM':'Ladder Bottom',
+'CDLLONGLEGGEDDOJI':'Long Legged Doji',
+'CDLLONGLINE':'Long Line Candle',
+'CDLMARUBOZU':'Marubozu',
+'CDLMATCHINGLOW':'Matching Low',
+'CDLMATHOLD':'Mat Hold',
+'CDLMORNINGDOJISTAR':'Morning Doji Star',
+'CDLMORNINGSTAR':'Morning Star',
+'CDLONNECK':'On-Neck Pattern',
+'CDLPIERCING':'Piercing Pattern',
+'CDLRICKSHAWMAN':'Rickshaw Man',
+'CDLRISEFALL3METHODS':'Rising/Falling Three Methods',
+'CDLSEPARATINGLINES':'Separating Lines',
+'CDLSHOOTINGSTAR':'Shooting Star',
+'CDLSHORTLINE':'Short Line Candle',
+'CDLSPINNINGTOP':'Spinning Top',
+'CDLSTALLEDPATTERN':'Stalled Pattern',
+'CDLSTICKSANDWICH':'Stick Sandwich',
+'CDLTAKURI':'Takuri (Dragonfly Doji with very long lower shadow)',
+'CDLTASUKIGAP':'Tasuki Gap',
+'CDLTHRUSTING':'Thrusting Pattern',
+'CDLTRISTAR':'Tristar Pattern',
+'CDLUNIQUE3RIVER':'Unique 3 River',
+'CDLUPSIDEGAP2CROWS':'Upside Gap Two Crows',
+'CDLXSIDEGAP3METHODS':'Upside/Downside Gap Three Methods'
+}
+
+Company_Name ={
+"NIFTY 50" :"^NSEI",
+"NIFTY BANK" : "^NSEBANK",
+"INDIA VIX" : "^INDIAVIX",
+"ADANI ENTERPRISES ":"ADANIENT.NS",
+"ADANI PORTS AND SPECIAL ECONOMIC ZONE ":"ADANIPORTS.NS",
+"APOLLO HOSPITALS ENTERPRISE ":"APOLLOHOSP.NS",
+"ASIAN PAINTS ":"ASIANPAINT.NS",
+"Axis Bank ":"AXISBANK.NS",
+"MARUTI SUZUKI INDIA ":"MARUTI.NS",
+"BAJAJ FINANCE ":"BAJFINANCE.NS",
+"Bajaj Finserv ":"BAJAJFINSV.NS",
+"BHARAT PETROLEUM CORPORATION ":"BPCL.NS",
+"Bharti Airtel ":"BHARTIARTL.NS", # change
+"BRITANNIA INDUSTRIES LTD" :"BRITANNIA.NS",
+"CIPLA ":"CIPLA.NS",
+"COAL INDIA LTD " :"COALINDIA.NS",
+"DIVI'S LABORATORIES ":"DIVISLAB.NS",
+"DR.REDDY'S LABORATORIES LTD ":"DRREDDY.NS",
+"EICHER MOTORS ":"EICHERMOT.NS",
+"GRASIM INDUSTRIES LTD ":"GRASIM.NS",
+"HCL TECHNOLOGIES ":"HCLTECH.NS",
+"HDFC BANK ":"HDFCBANK.NS",
+"HDFC LIFE INSURANCE COMPANY ":"HDFCLIFE.NS",
+"Hero MotoCorp ":"HEROMOTOCO.NS",
+"HINDALCO INDUSTRIES ":"HINDALCO.NS",
+"HINDUSTAN UNILEVER ":"HINDUNILVR.NS",
+"HOUSING DEVELOPMENT FINANCE CORPORATION ":"HDFC.NS",
+"ICICI BANK ":"ICICIBANK.NS",
+"ITC ":"ITC.NS",
+"INDUSIND BANK LTD. ":"INDUSINDBK.NS",
+"INFOSYS ":"INFY.NS",
+"JSW Steel ":"JSWSTEEL.NS",
+"KOTAK MAHINDRA BANK ":"KOTAKBANK.NS",
+"LARSEN AND TOUBRO ":"LT.NS",
+"MAHINDRA AND MAHINDRA ":"M&M.NS",
+"MARUTI SUZUKI INDIA ":"MARUTI.NS",
+"NTPC ":"NTPC.NS",
+"NESTLE INDIA ":"NESTLEIND.NS",
+"OIL AND NATURAL GAS CORPORATION ":"ONGC.NS",
+"POWER GRID CORPORATION OF INDIA ":"POWERGRID.NS",
+"RELIANCE INDUSTRIES ":"RELIANCE.NS", #cahnged
+"SBI LIFE INSURANCE COMPANY ":"SBILIFE.NS",
+"SBI":"SBIN.NS",
+"SUN PHARMACEUTICAL INDUSTRIES ":"SUNPHARMA.NS",
+"TATA CONSULTANCY SERVICES ":"TCS.NS",
+"TATA CONSUMER PRODUCTS ":"TATACONSUM.NS",
+"TATA MOTORS ":"TATAMTRDVR.NS",
+"TATA STEEL ":"TATASTEEL.NS",
+"TECH MAHINDRA ":"TECHM.NS",
+"TITAN COMPANY ":"TITAN.NS",
+"UPL ":"UPL.NS",
+"ULTRATECH CEMENT ":"ULTRACEMCO.NS",
+"WIPRO ":"WIPRO.NS"
+}
diff --git a/News_App/requirements.txt b/News_App/requirements.txt
new file mode 100644
index 00000000000..bf511c5a6fa
--- /dev/null
+++ b/News_App/requirements.txt
@@ -0,0 +1,6 @@
+solara == 1.48.0
+Flask
+gunicorn ==23.0.0
+simple-websocket
+flask-sock
+yfinance
\ No newline at end of file
diff --git a/PDF/demerge_pdfs.py b/PDF/demerge_pdfs.py
new file mode 100644
index 00000000000..12fcf081428
--- /dev/null
+++ b/PDF/demerge_pdfs.py
@@ -0,0 +1,43 @@
+"""
+Python program to split large pdf(typically textbook) into small set of pdfs, maybe chapterwise
+to enhance the experience of reading and feasibility to study only specific parts from the large original textbook
+"""
+
+
+import PyPDF2
+path = input()
+merged_pdf = open(path, mode='rb')
+
+
+pdf = PyPDF2.PdfFileReader(merged_pdf)
+
+(u, ctr, x) = tuple([0]*3)
+for i in range(1, pdf.numPages+1):
+
+ if u >= pdf.numPages:
+ print("Successfully done!")
+ exit(0)
+ name = input("Enter the name of the pdf: ")
+ ctr = int(input(f"Enter the number of pages for {name}: "))
+ u += ctr
+ if u > pdf.numPages:
+ print('Limit exceeded! ')
+ break
+
+ base_path = '/Users/darpan/Desktop/{}.pdf'
+ path = base_path.format(name)
+ f = open(path, mode='wb')
+ pdf_writer = PyPDF2.PdfFileWriter()
+
+ for j in range(x, x+ctr):
+ page = pdf.getPage(j)
+ pdf_writer.addPage(page)
+
+ x += ctr
+
+ pdf_writer.write(f)
+ f.close()
+
+
+merged_pdf.close()
+print("Successfully done!")
diff --git a/PDF/requirements.txt b/PDF/requirements.txt
index b065c619ace..4a068119c0d 100644
--- a/PDF/requirements.txt
+++ b/PDF/requirements.txt
@@ -1,2 +1,2 @@
-Pillow==10.0.0
+Pillow==11.2.1
fpdf==1.7.2
\ No newline at end of file
diff --git a/Password Generator/requirements.txt b/Password Generator/requirements.txt
index a84a8a40727..8fb084425cf 100644
--- a/Password Generator/requirements.txt
+++ b/Password Generator/requirements.txt
@@ -1,3 +1,2 @@
-string
-secrets
-random
+colorama==0.4.6
+inquirer==3.4.0
\ No newline at end of file
diff --git a/Patterns/half triangle pattern.py b/Patterns/half triangle pattern.py
new file mode 100644
index 00000000000..4a87b93f7c4
--- /dev/null
+++ b/Patterns/half triangle pattern.py
@@ -0,0 +1,70 @@
+ # (upper half - repeat)
+ #1
+ #22
+ #333
+
+ # (upper half - incremental)
+ #1
+ #12
+ #123
+
+ # (lower half - incremental)
+ #123
+ #12
+ #1
+
+ # (lower half - repeat)
+ #333
+ #22
+ #1
+
+def main():
+ lines = int(input("Enter no.of lines: "))
+ pattern = input("i: increment or r:repeat pattern: ").lower()
+ part = input("u: upper part or l: lower part: ").lower()
+
+ match pattern:
+ case "i":
+ if part == "u":
+ upper_half_incremental_pattern(lines)
+ else:
+ lower_half_incremental_pattern(lines)
+
+ case "r":
+ if part == "u":
+ upper_half_repeat_pattern(lines)
+ else:
+ lower_half_repeat_pattern(lines)
+
+ case _:
+ print("Invalid input")
+ exit(0)
+
+def upper_half_repeat_pattern(lines=5):
+ for column in range(1, (lines +1)):
+ print(f"{str(column) * column}")
+
+
+def lower_half_repeat_pattern(lines=5):
+ for length in range(lines, 0, -1):
+ print(f"{str(length) * length}")
+
+
+def upper_half_incremental_pattern(lines=5):
+ const=""
+ for column in range(1, (lines +1)):
+ const+=str(column)
+ print(const)
+
+
+
+def lower_half_incremental_pattern(lines=5):
+ for row_length in range(lines, 0, -1):
+ for x in range(1,row_length+1):
+ print(x,end='')
+ print()
+
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Patterns/pattern1.py b/Patterns/pattern1.py
deleted file mode 100644
index ac3869e064e..00000000000
--- a/Patterns/pattern1.py
+++ /dev/null
@@ -1,27 +0,0 @@
-#pattern
-#1234567
-#123456
-#12345
-#1234
-#123
-#1
-
-def main():
- lines = int(input("Enter no.of lines: "))
- pattern(lines)
-
-def pattern(lines):
- m = lines + 1
- l = 1
- for i in reversed(range(lines+1)):
- t = ""
- k = 1
- for m in range(i):
- if k == 10:
- k = 0
- t = str(t) + str(k)
- k = k + 1
- print(t)
-
-if __name__ == "__main__":
- main()
diff --git a/Patterns/pattern2.py b/Patterns/pattern2.py
index 5e8650e3860..84093334cb0 100644
--- a/Patterns/pattern2.py
+++ b/Patterns/pattern2.py
@@ -13,14 +13,10 @@ def main():
pattern(lines)
def pattern(lines):
- for i in range(lines,0,-1):
- for j in range(lines-i):
- print(' ', end='')
-
- for j in range(2*i-1):
- print('$',end='')
- print()
-
+ flag=lines
+ for i in range(lines):
+ print(" "*(i),'$'*(2*flag-1))
+ flag-=1
if __name__ == "__main__":
main()
diff --git a/Patterns/pattern3.py b/Patterns/pattern3.py
deleted file mode 100644
index abaca7c41e0..00000000000
--- a/Patterns/pattern3.py
+++ /dev/null
@@ -1,24 +0,0 @@
-#Simple number triangle piramid
-#1
-#22
-#333
-#4444
-#55555
-#666666
-
-
-
-
-def main():
- lines = int(input("Enter no.of lines: "))
- pattern(lines)
-
-def pattern(lines):
- t = 1
- for i in range(1, (lines +1)):
- format = str(t)*i
- print(format)
- t = t + 1
-
-if __name__ == "__main__":
- main()
diff --git a/Patterns/pattern5.py b/Patterns/pattern5.py
index 58f75df847b..d0c20b8afb9 100644
--- a/Patterns/pattern5.py
+++ b/Patterns/pattern5.py
@@ -9,11 +9,11 @@ def main():
lines = int(input("Enter the number of lines: "))
pattern(lines)
-def pattern(rows):
- for i in range(1, rows+1):
- for j in range(i, 0, -1):
- print(j, end="")
- print()
+def pattern(rows):
+ const=''
+ for i in range(1, rows+1):
+ const=str(i)+const
+ print(const)
if __name__ == "__main__":
main()
diff --git a/Patterns/patterns.py b/Patterns/patterns.py
index a23b463df12..9aa70bd0883 100644
--- a/Patterns/patterns.py
+++ b/Patterns/patterns.py
@@ -19,21 +19,11 @@ def main():
pattern(lines)
def pattern(lines):
+ for i in range(1,lines+1):
+ print("* "*i)
+ print()
for i in range(lines):
- for j in range(i+1):
- print("* ", end="")
- print("")
- print(" ")
-
- for i in range(0,lines):
-
- for j in range(0, (2 * (i - 1)) + 1):
- print(" ", end="")
-
- for j in range(0, lines - i):
- print("*", end=" ")
-
- print("")
+ print(" "*i,"* "*(lines-i))
if __name__ == "__main__":
main()
diff --git a/Pc_information.py b/Pc_information.py
new file mode 100644
index 00000000000..3117d78bdfa
--- /dev/null
+++ b/Pc_information.py
@@ -0,0 +1,11 @@
+import platform # built in lib
+
+print(f"System : {platform.system()}") # Prints type of Operating System
+print(f"System name : {platform.node()}") # Prints System Name
+print(f"version : {platform.release()}") # Prints System Version
+# TO get the detailed version number
+print(f"detailed version number : {platform.version()}") # Prints detailed version number
+print(f"System architecture : {platform.machine()}") # Prints whether the system is 32-bit ot 64-bit
+print(f"System processor : {platform.processor()}") # Prints CPU model
+
+
diff --git a/Personal-Expense-Tracker/README.md b/Personal-Expense-Tracker/README.md
new file mode 100644
index 00000000000..8c54ea4d695
--- /dev/null
+++ b/Personal-Expense-Tracker/README.md
@@ -0,0 +1,50 @@
+# Personal Expense Tracker CLI
+
+This is a basic command-line interface (CLI) application built with Python to help you track your daily expenses. It allows you to easily add your expenditures, categorize them, and view your spending patterns over different time periods.
+
+## Features
+
+* **Add New Expense:** Record new expenses by providing the amount, category (e.g., food, travel, shopping, bills), date, and an optional note.
+* **View Expenses:** Display your expenses for a specific day, week, month, or all recorded expenses.
+* **Filter by Category:** View expenses belonging to a particular category.
+* **Data Persistence:** Your expense data is saved to a plain text file (`expenses.txt`) so it's retained between sessions.
+* **Simple Command-Line Interface:** Easy-to-use text-based menu for interacting with the application.
+
+## Technologies Used
+
+* **Python:** The core programming language used for the application logic.
+* **File Handling:** Used to store and retrieve expense data from a text file.
+* **`datetime` module:** For handling and managing date information for expenses.
+
+## How to Run
+
+1. Make sure you have Python installed on your system.
+2. Save the `expense_tracker.py` file to your local machine.
+3. Open your terminal or command prompt.
+4. Navigate to the directory where you saved the file using the `cd` command.
+5. Run the application by executing the command: `python expense_tracker.py`
+
+## Basic Usage
+
+1. Run the script. You will see a menu with different options.
+2. To add a new expense, choose option `1` and follow the prompts to enter the required information.
+3. To view expenses, choose option `2` and select the desired time period (day, week, month, or all).
+4. To filter expenses by category, choose option `3` and enter the category you want to view.
+5. To save any new expenses (though the application automatically saves on exit as well), choose option `4`.
+6. To exit the application, choose option `5`.
+
+## Potential Future Enhancements (Ideas for Expansion)
+
+* Implement a monthly budget feature with alerts.
+* Add a login system for multiple users.
+* Generate visual reports like pie charts for category-wise spending (using libraries like `matplotlib`).
+* Incorporate voice input for adding expenses (using `speech_recognition`).
+* Migrate data storage to a more structured database like SQLite.
+
+* Add functionality to export expense data to CSV files.
+
+---
+
+> This simple Personal Expense Tracker provides a basic yet functional way to manage your finances from the command line.
+
+#### Author: Dhrubaraj Pati
\ No newline at end of file
diff --git a/Personal-Expense-Tracker/expense_tracker.py b/Personal-Expense-Tracker/expense_tracker.py
new file mode 100644
index 00000000000..12d6b4a33c2
--- /dev/null
+++ b/Personal-Expense-Tracker/expense_tracker.py
@@ -0,0 +1,112 @@
+import datetime
+
+def add_expense(expenses):
+ amount = float(input("Enter the expense amount: "))
+ category = input("Category (food, travel, shopping, bills, etc.): ")
+ date_str = input("Date (YYYY-MM-DD): ")
+ try:
+ date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
+ except ValueError:
+ print("Incorrect date format. Please use YYYY-MM-DD format.")
+ return
+ note = input("(Optional) Note: ")
+ expenses.append({"amount": amount, "category": category, "date": date, "note": note})
+ print("Expense added!")
+
+def view_expenses(expenses, period="all", category_filter=None):
+ if not expenses:
+ print("No expenses recorded yet.")
+ return
+
+ filtered_expenses = expenses
+ if category_filter:
+ filtered_expenses = [e for e in filtered_expenses if e["category"] == category_filter]
+
+ if period == "day":
+ date_str = input("Enter the date to view expenses for (YYYY-MM-DD): ")
+ try:
+ date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
+ filtered_expenses = [e for e in filtered_expenses if e["date"] == date]
+ except ValueError:
+ print("Incorrect date format.")
+ return
+ elif period == "week":
+ date_str = input("Enter the start date of the week (YYYY-MM-DD - first day of the week): ")
+ try:
+ start_date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
+ end_date = start_date + datetime.timedelta(days=6)
+ filtered_expenses = [e for e in filtered_expenses if start_date <= e["date"] <= end_date]
+ except ValueError:
+ print("Incorrect date format.")
+ return
+ elif period == "month":
+ year = input("Enter the year for the month (YYYY): ")
+ month = input("Enter the month (MM): ")
+ try:
+ year = int(year)
+ month = int(month)
+ filtered_expenses = [e for e in filtered_expenses if e["date"].year == year and e["date"].month == month]
+ except ValueError:
+ print("Incorrect year or month format.")
+ return
+
+ if not filtered_expenses:
+ print("No expenses found for this period or category.")
+ return
+
+ print("\n--- Expenses ---")
+ total_spent = 0
+ for expense in filtered_expenses:
+ print(f"Amount: {expense['amount']}, Category: {expense['category']}, Date: {expense['date']}, Note: {expense['note']}")
+ total_spent += expense['amount']
+ print(f"\nTotal spent: {total_spent}")
+
+def save_expenses(expenses, filename="expenses.txt"):
+ with open(filename, "w") as f:
+ for expense in expenses:
+ f.write(f"{expense['amount']},{expense['category']},{expense['date']},{expense['note']}\n")
+ print("Expenses saved!")
+
+def load_expenses(filename="expenses.txt"):
+ expenses = []
+ try:
+ with open(filename, "r") as f:
+ for line in f:
+ amount, category, date_str, note = line.strip().split(',')
+ expenses.append({"amount": float(amount), "category": category, "date": datetime.datetime.strptime(date_str, "%Y-%m-%d").date(), "note": note})
+ except FileNotFoundError:
+ pass
+ return expenses
+
+def main():
+ expenses = load_expenses()
+
+ while True:
+ print("\n--- Personal Expense Tracker ---")
+ print("1. Add new expense")
+ print("2. View expenses")
+ print("3. Filter by category")
+ print("4. Save expenses")
+ print("5. Exit")
+
+ choice = input("Choose your option: ")
+
+ if choice == '1':
+ add_expense(expenses)
+ elif choice == '2':
+ period = input("View expenses by (day/week/month/all): ").lower()
+ view_expenses(expenses, period)
+ elif choice == '3':
+ category_filter = input("Enter the category to filter by: ")
+ view_expenses(expenses, category_filter=category_filter)
+ elif choice == '4':
+ save_expenses(expenses)
+ elif choice == '5':
+ save_expenses(expenses)
+ print("Thank you!")
+ break
+ else:
+ print("Invalid option. Please try again.")
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/PingPong/Ball.py b/PingPong/Ball.py
new file mode 100644
index 00000000000..73961fc07f2
--- /dev/null
+++ b/PingPong/Ball.py
@@ -0,0 +1,59 @@
+import pygame
+pygame.init()
+
+class Ball:
+
+ def __init__(self, pos, vel, win, rad, minCoord, maxCoord):
+
+ self.pos = pos
+ self.vel = vel
+ self.win = win
+ self.rad = rad
+ self.minCoord = minCoord
+ self.maxCoord = maxCoord
+
+
+ def drawBall(self):
+
+ pygame.draw.circle(self.win, (255,)*3, self.pos, self.rad, 0)
+
+
+ def doHorizontalFlip(self):
+
+ self.vel[0] *= -1
+ print("Github")
+
+
+ def doVerticalFlip(self):
+
+ self.vel[1] *= -1
+
+
+ def borderCollisionCheck(self):
+
+ if (self.pos[0] <= self.minCoord[0]) or (self.pos[0] >= self.maxCoord[0]):
+
+ self.doHorizontalFlip()
+
+ if (self.pos[1] <= self.minCoord[1]) or (self.pos[1] >= self.maxCoord[1]):
+
+ self.doVerticalFlip()
+
+
+ def updatePos(self):
+
+ self.pos = [self.pos[0]+self.vel[0], self.pos[1]+self.vel[1]]
+
+
+ def checkSlabCollision(self, slabPos): # slab pos = [xmin, ymin, xmax, ymax]
+ if (
+ self.pos[0] + self.rad > slabPos[0]
+ and self.pos[0] - self.rad < slabPos[2]
+ and self.pos[1] + self.rad > slabPos[1]
+ and self.pos[1] - self.rad < slabPos[3]
+ ):
+ # Handle collision here (e.g., reverse ball's direction)
+ if self.pos[0] < slabPos[0] or self.pos[0] > slabPos[2]:
+ self.vel[0] *= -1
+ if self.pos[1] < slabPos[1] or self.pos[1] > slabPos[3]:
+ self.vel[1] *= -1
diff --git a/PingPong/Slab.py b/PingPong/Slab.py
new file mode 100644
index 00000000000..c5fb5d70bec
--- /dev/null
+++ b/PingPong/Slab.py
@@ -0,0 +1,31 @@
+import pygame
+pygame.init()
+
+class Slab:
+ def __init__(self, win, size, pos, player, minPos, maxPos):
+ self.win = win
+ self.size = size
+ self.pos = pos
+ self.player = player #player = 1 or 2
+ self.minPos = minPos
+ self.maxPos = maxPos
+
+
+ def draw(self):
+ pygame.draw.rect(self.win, (255, 255, 255), (self.pos[0], self.pos[1], self.size[0], self.size[1]))
+
+ def getCoords(self):
+ return [self.pos[0], self.pos[1], self.pos[0] + self.size[0], self.pos[1] + self.size[1]]
+
+ def updatePos(self):
+ keys = pygame.key.get_pressed()
+ if self.player == 1:
+ if keys[pygame.K_UP] and self.getCoords()[1]> self.minPos[1]:
+ self.pos[1] -= 0.3
+ if keys[pygame.K_DOWN] and self.getCoords()[3]< self.maxPos[1]:
+ self.pos[1] += 0.3
+ else:
+ if keys[pygame.K_w] and self.getCoords()[1]> self.minPos[1]:
+ self.pos[1] -= 0.3
+ if keys[pygame.K_s] and self.getCoords()[3]< self.maxPos[1]:
+ self.pos[1] += 0.3
\ No newline at end of file
diff --git a/PingPong/main.py b/PingPong/main.py
new file mode 100644
index 00000000000..2892f8c9305
--- /dev/null
+++ b/PingPong/main.py
@@ -0,0 +1,40 @@
+from Ball import Ball
+from Slab import Slab
+import pygame
+
+WIDTH = 600
+HEIGHT = 600
+BLACK = (0,0,0)
+WHITE = (255,)*3
+pygame.init()
+
+win = pygame.display.set_mode((WIDTH, HEIGHT ))
+
+print("Controls: W&S for player 1 and arrow up and down for player 2")
+
+ball = Ball([300,300 ], [0.3,0.1], win, 10, (0,0), (600,600))
+slab = Slab(win, [10,100], [500, 300], 1, (0, 0), (600, 600))
+slab2 = Slab(win, [10,100], [100, 300], 2, (0, 0), (600, 600))
+run = True
+while run:
+ for event in pygame.event.get():
+ if event.type == pygame.QUIT:
+ run = False
+
+ keys = pygame.key.get_pressed()
+ win.fill(BLACK)
+
+ ball.borderCollisionCheck()
+ ball.checkSlabCollision(slab.getCoords())
+ ball.checkSlabCollision(slab2.getCoords())
+ ball.updatePos()
+ ball.drawBall()
+
+ slab.updatePos()
+ slab.draw()
+
+ slab2.updatePos()
+ slab2.draw()
+
+ pygame.display.update()
+pygame.quit()
\ No newline at end of file
diff --git a/Pomodoro (tkinter).py b/Pomodoro (tkinter).py
new file mode 100644
index 00000000000..964963c5894
--- /dev/null
+++ b/Pomodoro (tkinter).py
@@ -0,0 +1,208 @@
+from tkinter import *
+
+# ---------------------------- CONSTANTS & GLOBALS ------------------------------- #
+PINK = "#e2979c"
+GREEN = "#9bdeac"
+FONT_NAME = "Courier"
+DEFAULT_WORK_MIN = 25
+DEFAULT_BREAK_MIN = 5
+
+# Background color options
+bg_colors = {
+ "Pink": "#e2979c",
+ "Green": "#9bdeac",
+ "Blue": "#1f75fe",
+ "Yellow": "#ffcc00",
+ "Purple": "#b19cd9"
+}
+
+# Global variables
+ROUND = 1
+timer_mec = None
+total_time = 0 # Total seconds for the current session
+is_paused = False # Timer pause flag
+remaining_time = 0 # Remaining time (in seconds) when paused
+custom_work_min = DEFAULT_WORK_MIN
+custom_break_min = DEFAULT_BREAK_MIN
+
+# ---------------------------- BACKGROUND COLOR CHANGE FUNCTION ------------------------------- #
+def change_background(*args):
+ selected = bg_color_var.get()
+ new_color = bg_colors.get(selected, PINK)
+ window.config(bg=new_color)
+ canvas.config(bg=new_color)
+ label.config(bg=new_color)
+ tick_label.config(bg=new_color)
+ work_label.config(bg=new_color)
+ break_label.config(bg=new_color)
+
+# ---------------------------- NOTIFICATION FUNCTION ------------------------------- #
+def show_notification(message):
+ notif = Toplevel(window)
+ notif.overrideredirect(True)
+ notif.config(bg=PINK)
+
+ msg_label = Label(notif, text=message, font=(FONT_NAME, 12, "bold"),
+ bg=GREEN, fg="white", padx=10, pady=5)
+ msg_label.pack()
+
+ window.update_idletasks()
+ wx = window.winfo_rootx()
+ wy = window.winfo_rooty()
+ wwidth = window.winfo_width()
+ wheight = window.winfo_height()
+
+ notif.update_idletasks()
+ nwidth = notif.winfo_width()
+ nheight = notif.winfo_height()
+
+ x = wx + (wwidth - nwidth) // 2
+ y = wy + wheight - nheight - 10
+ notif.geometry(f"+{x}+{y}")
+
+ notif.after(3000, notif.destroy)
+
+# ---------------------------- TIMER FUNCTIONS ------------------------------- #
+def reset_timer():
+ global ROUND, timer_mec, total_time, is_paused, remaining_time
+ ROUND = 1
+ is_paused = False
+ remaining_time = 0
+ if timer_mec is not None:
+ window.after_cancel(timer_mec)
+ canvas.itemconfig(timer_text, text="00:00")
+ label.config(text="Timer")
+ tick_label.config(text="")
+ total_time = 0
+ canvas.itemconfig(progress_arc, extent=0)
+ start_button.config(state=NORMAL)
+ pause_button.config(state=DISABLED)
+ play_button.config(state=DISABLED)
+
+def start_timer():
+ global ROUND, total_time, is_paused
+ canvas.itemconfig(progress_arc, extent=0)
+
+ if ROUND % 2 == 1: # Work session
+ total_time = custom_work_min * 60
+ label.config(text="Work", fg=GREEN)
+ else: # Break session
+ total_time = custom_break_min * 60
+ label.config(text="Break", fg=PINK)
+
+ count_down(total_time)
+ start_button.config(state=DISABLED)
+ pause_button.config(state=NORMAL)
+ play_button.config(state=DISABLED)
+ is_paused = False
+
+def count_down(count):
+ global timer_mec, remaining_time
+ remaining_time = count
+ minutes = count // 60
+ seconds = count % 60
+ if seconds < 10:
+ seconds = f"0{seconds}"
+ canvas.itemconfig(timer_text, text=f"{minutes}:{seconds}")
+
+ if total_time > 0:
+ progress = (total_time - count) / total_time
+ canvas.itemconfig(progress_arc, extent=progress * 360)
+
+ if count > 0 and not is_paused:
+ timer_mec = window.after(1000, count_down, count - 1)
+ elif count == 0:
+ if ROUND % 2 == 1:
+ show_notification("Work session complete! Time for a break.")
+ else:
+ show_notification("Break over! Back to work.")
+ if ROUND % 2 == 0:
+ tick_label.config(text=tick_label.cget("text") + "#")
+ ROUND += 1
+ start_timer()
+
+def pause_timer():
+ global is_paused, timer_mec
+ if not is_paused:
+ is_paused = True
+ if timer_mec is not None:
+ window.after_cancel(timer_mec)
+ pause_button.config(state=DISABLED)
+ play_button.config(state=NORMAL)
+
+def resume_timer():
+ global is_paused
+ if is_paused:
+ is_paused = False
+ count_down(remaining_time)
+ play_button.config(state=DISABLED)
+ pause_button.config(state=NORMAL)
+
+def set_custom_durations():
+ global custom_work_min, custom_break_min
+ try:
+ work_val = int(entry_work.get())
+ break_val = int(entry_break.get())
+ custom_work_min = work_val
+ custom_break_min = break_val
+ canvas.itemconfig(left_custom, text=f"{custom_work_min}m")
+ canvas.itemconfig(right_custom, text=f"{custom_break_min}m")
+ except ValueError:
+ pass
+
+# ---------------------------- UI SETUP ------------------------------- #
+window = Tk()
+window.title("Pomodoro")
+window.config(padx=100, pady=50, bg=PINK)
+
+# Canvas setup with increased width for spacing
+canvas = Canvas(window, width=240, height=224, bg=PINK, highlightthickness=0)
+timer_text = canvas.create_text(120, 112, text="00:00", font=(FONT_NAME, 35, "bold"), fill="white")
+background_circle = canvas.create_arc(40, 32, 200, 192, start=0, extent=359.9,
+ style="arc", outline="white", width=5)
+progress_arc = canvas.create_arc(40, 32, 200, 192, start=270, extent=0,
+ style="arc", outline="green", width=5)
+# Updated positions for work and break time labels
+left_custom = canvas.create_text(20, 112, text=f"{custom_work_min}m", font=(FONT_NAME, 12, "bold"), fill="white")
+right_custom = canvas.create_text(220, 112, text=f"{custom_break_min}m", font=(FONT_NAME, 12, "bold"), fill="white")
+
+canvas.grid(column=1, row=1)
+
+label = Label(text="Timer", font=(FONT_NAME, 35, "bold"), bg=PINK, fg="green")
+label.grid(column=1, row=0)
+
+start_button = Button(text="Start", command=start_timer, highlightthickness=0)
+start_button.grid(column=0, row=2)
+
+reset_button = Button(text="Reset", command=reset_timer, highlightthickness=0)
+reset_button.grid(column=2, row=2)
+
+pause_button = Button(text="Pause", command=pause_timer, highlightthickness=0, state=DISABLED)
+pause_button.grid(column=0, row=3)
+
+play_button = Button(text="Play", command=resume_timer, highlightthickness=0, state=DISABLED)
+play_button.grid(column=2, row=3)
+
+tick_label = Label(text="", font=(FONT_NAME, 15, "bold"), bg=PINK, fg="green")
+tick_label.grid(column=1, row=4)
+
+# Custom durations (stacked vertically)
+work_label = Label(text="Work (min):", font=(FONT_NAME, 12, "bold"), bg=PINK, fg="white")
+work_label.grid(column=1, row=5, pady=(20, 0))
+entry_work = Entry(width=5, font=(FONT_NAME, 12))
+entry_work.grid(column=1, row=6, pady=(5, 10))
+break_label = Label(text="Break (min):", font=(FONT_NAME, 12, "bold"), bg=PINK, fg="white")
+break_label.grid(column=1, row=7, pady=(5, 0))
+entry_break = Entry(width=5, font=(FONT_NAME, 12))
+entry_break.grid(column=1, row=8, pady=(5, 10))
+set_button = Button(text="Set Durations", command=set_custom_durations, font=(FONT_NAME, 12))
+set_button.grid(column=1, row=9, pady=(10, 20))
+
+# OptionMenu for changing background color
+bg_color_var = StringVar(window)
+bg_color_var.set("Pink")
+bg_option = OptionMenu(window, bg_color_var, *bg_colors.keys(), command=change_background)
+bg_option.config(font=(FONT_NAME, 12))
+bg_option.grid(column=1, row=10, pady=(10, 20))
+
+window.mainloop()
diff --git a/PongPong_Game/requirements.txt b/PongPong_Game/requirements.txt
index 768581ded2c..71000361bd6 100644
--- a/PongPong_Game/requirements.txt
+++ b/PongPong_Game/requirements.txt
@@ -1 +1 @@
-pyglet==2.0.8
+pyglet==2.1.6
diff --git a/Prime_number.py b/Prime_number.py
index 1a345b5abe6..92800c63e83 100644
--- a/Prime_number.py
+++ b/Prime_number.py
@@ -23,7 +23,7 @@ def is_prime_b(n):
if n == 2:
return True
else:
- for i in range(2, n):
+ for i in range(2, int(n//2)+1):
if n % i == 0:
return False
return True
diff --git a/Print_List_of_Even_Numbers.py b/Print_List_of_Even_Numbers.py
deleted file mode 100644
index 5addb87407f..00000000000
--- a/Print_List_of_Even_Numbers.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# Very sort method to creat list of even number form a given list
-# Advance-Python
-list_number = list(map(int, input().split()))
-even_list = [i for i in list_number if i % 2 == 0]
-print(even_list)
-exit() # Another one
-n = int(input("Enter the required range : ")) # user input
-list = []
-
-if n < 0:
- print("Not a valid number, please enter a positive number!")
-else:
- for i in range(0, n + 1):
- if i % 2 == 0:
- list.append(
- i
- ) # appending items to the initialised list getting from the 'if' statement
-
-print(list)
diff --git a/Print_List_of_Odd_Numbers.py b/Print_List_of_Odd_Numbers.py
deleted file mode 100644
index f032e035dee..00000000000
--- a/Print_List_of_Odd_Numbers.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# master
-# Another best method to do this
-
-n = map(list(int, input().split()))
-odd_list = list(i for i in n if i % 2 != 0)
-print(odd_list)
-exit()
-
-# CALCULATE NUMBER OF ODD NUMBERS
-
-# CALCULATE NUMBER OF ODD NUMBERS WITHIN A GIVEN LIMIT
-# master
-
-n = int(input("Enter the limit : ")) # user input
-
-if n <= 0:
- print("Invalid number, please enter a number greater than zero!")
-else:
- odd_list = [i for i in range(1, n + 1, 2)] # creating string with number "i"
- print(odd_list) # in range from 1 till "n".
-
-
-# printing odd and even number in same program
-n = map(list(int, input().split()))
-even = []
-odd = []
-for i in range(n):
- if i % 2 == 0:
- even.append(i)
- else:
- odd.append(i)
diff --git a/Python Program for Tower of Hanoi.py b/Python Program for Tower of Hanoi.py
index f187ca0355d..7efb1b56363 100644
--- a/Python Program for Tower of Hanoi.py
+++ b/Python Program for Tower of Hanoi.py
@@ -1,10 +1,10 @@
# Recursive Python function to solve the tower of hanoi
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
- print "Move disk 1 from source",source,"to destination",destination
+ print("Move disk 1 from source ",source," to destination ",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
- print "Move disk",n,"from source",source,"to destination",destination
+ print("Move disk ",n," from source ",source," to destination ",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
n = 4
TowerOfHanoi(n,'A','B','C')
diff --git a/Python Program to Count the Number of Each Vowel.py b/Python Program to Count the Number of Each Vowel.py
index f5dbd864d17..297e2488590 100644
--- a/Python Program to Count the Number of Each Vowel.py
+++ b/Python Program to Count the Number of Each Vowel.py
@@ -16,4 +16,4 @@
if char in count:
count[char] += 1
-print(count)s
+print(count)
diff --git a/Python Program to Reverse a linked list.py b/Python Program to Reverse a linked list.py
index 212d4503dc3..c3eff50ebab 100644
--- a/Python Program to Reverse a linked list.py
+++ b/Python Program to Reverse a linked list.py
@@ -37,7 +37,7 @@ def push(self, new_data):
def printList(self):
temp = self.head
while(temp):
- print temp.data,
+ print(temp.data)
temp = temp.next
@@ -48,10 +48,10 @@ def printList(self):
llist.push(15)
llist.push(85)
-print "Given Linked List"
+print("Given Linked List")
llist.printList()
llist.reverse()
-print "\nReversed Linked List"
+print("\nReversed Linked List")
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
diff --git a/Python Program to Sort Words in Alphabetic Order.py b/Python Program to Sort Words in Alphabetic Order.py
index f4ebe04a29c..3e4bd3564e5 100644
--- a/Python Program to Sort Words in Alphabetic Order.py
+++ b/Python Program to Sort Words in Alphabetic Order.py
@@ -1,18 +1,42 @@
-# Program to sort alphabetically the words form a string provided by the user
+# Program to sort words alphabetically and put them in a dictionary with corresponding numbered keys
+# We are also removing punctuation to ensure the desired output, without importing a library for assistance.
-my_str = "Hello this Is an Example With cased letters"
+# Declare base variables
+word_Dict = {}
+count = 0
+my_str = "Hello this Is an Example With cased letters. Hello, this is a good string"
+#Initialize punctuation
+punctuations = '''!()-[]{};:'",<>./?@#$%^&*_~'''
# To take input from the user
#my_str = input("Enter a string: ")
+# remove punctuation from the string and use an empty variable to put the alphabetic characters into
+no_punct = ""
+for char in my_str:
+ if char not in punctuations:
+ no_punct = no_punct + char
+
+# Make all words in string lowercase. my_str now equals the original string without the punctuation
+my_str = no_punct.lower()
+
# breakdown the string into a list of words
words = my_str.split()
-# sort the list
+# sort the list and remove duplicate words
words.sort()
-# display the sorted words
-
-print("The sorted words are:")
+new_Word_List = []
for word in words:
- print(word)
+ if word not in new_Word_List:
+ new_Word_List.append(word)
+ else:
+ continue
+
+# insert sorted words into dictionary with key
+
+for word in new_Word_List:
+ count+=1
+ word_Dict[count] = word
+
+print(word_Dict)
diff --git a/Python Voice Generator.py b/Python Voice Generator.py
new file mode 100644
index 00000000000..9541ccfae51
--- /dev/null
+++ b/Python Voice Generator.py
@@ -0,0 +1,11 @@
+#install and import google text-to-speech library gtts
+from gtts import gTTS
+import os
+#provide user input text
+text=input('enter the text: ')
+#covert text into voice
+voice=gTTS(text=text, lang='en')
+#save the generated voice
+voice.save('output.mp3')
+#play the file in windows
+os.system('start output.mp3')
\ No newline at end of file
diff --git a/Python-Array-Equilibrium-Index.py b/Python-Array-Equilibrium-Index.py
index 81e42ea6092..0aac8fbf995 100644
--- a/Python-Array-Equilibrium-Index.py
+++ b/Python-Array-Equilibrium-Index.py
@@ -1,4 +1,4 @@
-Array Equilibrium Index
+"""Array Equilibrium Index
Send Feedback
Find and return the equilibrium index of an array. Equilibrium index of an array is an index i such that the sum of elements at indices less than i is equal to the sum of elements at indices greater than i.
Element at index i is not included in either part.
@@ -13,7 +13,7 @@
7
-7 1 5 2 -4 3 0
Sample Output :
-3
+3 """
def equilibrium(arr):
# finding the sum of whole array
diff --git a/QR_code_generator/qrcode.py b/QR_code_generator/qrcode.py
index 475f66e99fe..63a4b26684f 100755
--- a/QR_code_generator/qrcode.py
+++ b/QR_code_generator/qrcode.py
@@ -1,5 +1,6 @@
import pyqrcode, png
-from pyqrcode import QRCode
+# from pyqrcode import QRCode
+# no need to import same library again and again
# Creating QR code after given text "input"
url = pyqrcode.create(input("Enter text to convert: "))
diff --git a/QuestionAnswerVirtualAssistant/backend.py b/QuestionAnswerVirtualAssistant/backend.py
new file mode 100644
index 00000000000..3d21899a4fc
--- /dev/null
+++ b/QuestionAnswerVirtualAssistant/backend.py
@@ -0,0 +1,195 @@
+import sqlite3
+import json
+import pandas as pd
+import sklearn
+from sklearn.feature_extraction.text import TfidfVectorizer
+
+class QuestionAnswerVirtualAssistant:
+ """
+ Used for automatic question-answering
+
+ It works by building a reverse index store that maps
+ words to an id. To find the indexed questions that contain
+ a certain the words in the user question, we then take an
+ intersection of the ids, ranks the questions to pick the best fit,
+ then select the answer that maps to that question
+ """
+
+ def __init__(self):
+ """
+ Returns - None
+ Input - None
+ ----------
+ - Initialize database. we use sqlite3
+ - Check if the tables exist, if not create them
+ - maintain a class level access to the database
+ connection object
+ """
+ self.conn = sqlite3.connect("virtualassistant.sqlite3", autocommit=True)
+ cur = self.conn.cursor()
+ res = cur.execute("SELECT name FROM sqlite_master WHERE name='IdToQuesAns'")
+ tables_exist = res.fetchone()
+
+ if not tables_exist:
+ self.conn.execute("CREATE TABLE IdToQuesAns(id INTEGER PRIMARY KEY, question TEXT, answer TEXT)")
+ self.conn.execute('CREATE TABLE WordToId (name TEXT, value TEXT)')
+ cur.execute("INSERT INTO WordToId VALUES (?, ?)", ("index", "{}",))
+
+ def index_question_answer(self, question, answer):
+ """
+ Returns - string
+ Input - str: a string of words called question
+ ----------
+ Indexes the question and answer. It does this by performing two
+ operations - add the question and answer to the IdToQuesAns, then
+ adds the words in the question to WordToId
+ - takes in the question and answer (str)
+ - passes the question and answer to a method to add them
+ to IdToQuesAns
+ - retrieves the id of the inserted ques-answer
+ - uses the id to call the method that adds the words of
+ the question to the reverse index WordToId if the word has not
+ already been indexed
+ """
+ row_id = self._add_to_IdToQuesAns(question.lower(), answer.lower())
+ cur = self.conn.cursor()
+ reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0]
+ reverse_idx = json.loads(reverse_idx)
+ question = question.split()
+ for word in question:
+ if word not in reverse_idx:
+ reverse_idx[word] = [row_id]
+ else:
+ if row_id not in reverse_idx[word]:
+ reverse_idx[word].append(row_id)
+ reverse_idx = json.dumps(reverse_idx)
+ cur = self.conn.cursor()
+ result = cur.execute("UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,))
+ return("index successful")
+
+ def _add_to_IdToQuesAns(self, question, answer):
+ """
+ Returns - int: the id of the inserted document
+ Input - str: a string of words called `document`
+ ---------
+ - use the class-level connection object to insert the document
+ into the db
+ - retrieve and return the row id of the inserted document
+ """
+ cur = self.conn.cursor()
+ res = cur.execute("INSERT INTO IdToQuesAns (question, answer) VALUES (?, ?)", (question, answer,))
+ return res.lastrowid
+
+ def find_questions(self, user_input):
+ """
+ Returns - : the return value of the _find_questions_with_idx method
+ Input - str: a string of words called `user_input`, expected to be a question
+ ---------
+ - retrieve the reverse index
+ - use the words contained in the user input to find all the idxs
+ that contain the word
+ - use idxs to call the _find_questions_with_idx method
+ - return the result of the called method
+ """
+ cur = self.conn.cursor()
+ reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0]
+ reverse_idx = json.loads(reverse_idx)
+ user_input = user_input.split(" ")
+ all_docs_with_user_input = []
+ for term in user_input:
+ if term in reverse_idx:
+ all_docs_with_user_input.append(reverse_idx[term])
+
+ if not all_docs_with_user_input: # the user_input does not exist
+ return []
+
+ common_idx_of_docs = set(all_docs_with_user_input[0])
+ for idx in all_docs_with_user_input[1:]:
+ common_idx_of_docs.intersection_update(idx)
+
+ if not common_idx_of_docs: # the user_input does not exist
+ return []
+
+ return self._find_questions_with_idx(common_idx_of_docs)
+
+ def _find_questions_with_idx(self, idxs):
+ """
+ Returns - list[str]: the list of questions with the idxs
+ Input - list of idxs
+ ---------
+ - use the class-level connection object to retrieve the questions that
+ have the idx in the input list of idxs.
+ - retrieve and return these questions as a list
+ """
+ idxs = list(idxs)
+ cur = self.conn.cursor()
+ sql="SELECT id, question, answer FROM IdToQuesAns WHERE id in ({seq})".format(
+ seq=','.join(['?']*len(idxs))
+ )
+ result = cur.execute(sql, idxs).fetchall()
+ return(result)
+
+ def find_most_matched_question(self, user_input, corpus):
+ """
+ Returns - list[str]: the list of [(score, most_matching_question)]
+ Input - user_input, and list of matching questions called corpus
+ ---------
+ - use the tfidf score to rank the questions and pick the most matching
+ question
+ """
+ vectorizer = TfidfVectorizer()
+ tfidf_scores = vectorizer.fit_transform(corpus)
+ tfidf_array = pd.DataFrame(tfidf_scores.toarray(),columns=vectorizer.get_feature_names_out())
+ tfidf_dict = tfidf_array.to_dict()
+
+ user_input = user_input.split(" ")
+ result = []
+ for idx in range(len(corpus)):
+ result.append([0, corpus[idx]])
+
+ for term in user_input:
+ if term in tfidf_dict:
+ for idx in range(len(result)):
+ result[idx][0] += tfidf_dict[term][idx]
+ return result[0]
+
+ def provide_answer(self, user_input):
+ """
+ Returns - str: the answer to the user_input
+ Input - str: user_input
+ ---------
+ - use the user_input to get the list of matching questions
+ - create a corpus which is a list of all matching questions
+ - create a question_map that maps questions to their respective answers
+ - use the user_input and corpus to find the most matching question
+ - return the answer that matches that question from the question_map
+ """
+ matching_questions = self.find_questions(user_input)
+ corpus = [item[1] for item in matching_questions]
+ question_map = {question:answer for (id, question, answer) in matching_questions}
+ score, most_matching_question = self.find_most_matched_question(user_input, corpus)
+ return question_map[most_matching_question]
+
+
+if __name__ == "__main__":
+ va = QuestionAnswerVirtualAssistant()
+ va.index_question_answer(
+ "What are the different types of competitions available on Kaggle",
+ "Types of Competitions Kaggle Competitions are designed to provide challenges for competitors"
+ )
+ print(
+ va.index_question_answer(
+ "How to form, manage, and disband teams in a competition",
+ "Everyone that competes in a Competition does so as a team. A team is a group of one or more users"
+ )
+ )
+ va.index_question_answer(
+ "What is Data Leakage",
+ "Data Leakage is the presence of unexpected additional information in the training data"
+ )
+ va.index_question_answer(
+ "How does Kaggle handle cheating",
+ "Cheating is not taken lightly on Kaggle. We monitor our compliance account"
+ )
+ print(va.provide_answer("state Kaggle cheating policy"))
+ print(va.provide_answer("Tell me what is data leakage"))
\ No newline at end of file
diff --git a/QuestionAnswerVirtualAssistant/frontend.py b/QuestionAnswerVirtualAssistant/frontend.py
new file mode 100644
index 00000000000..bc99cfebd36
--- /dev/null
+++ b/QuestionAnswerVirtualAssistant/frontend.py
@@ -0,0 +1,41 @@
+from tkinter import *
+from tkinter import messagebox
+import backend
+
+
+def index_question_answer():
+ # for this, we are separating question and answer by "_"
+ question_answer = index_question_answer_entry.get()
+ question, answer = question_answer.split("_")
+ print(question)
+ print(answer)
+ va = backend.QuestionAnswerVirtualAssistant()
+ print(va.index_question_answer(question, answer))
+
+def provide_answer():
+ term = provide_answer_entry.get()
+ va = backend.QuestionAnswerVirtualAssistant()
+ print(va.provide_answer(term))
+
+if __name__ == "__main__":
+ root = Tk()
+ root.title("Knowledge base")
+ root.geometry('300x300')
+
+ index_question_answer_label = Label(root, text="Add question:")
+ index_question_answer_label.pack()
+ index_question_answer_entry = Entry(root)
+ index_question_answer_entry.pack()
+
+ index_question_answer_button = Button(root, text="add", command=index_question_answer)
+ index_question_answer_button.pack()
+
+ provide_answer_label = Label(root, text="User Input:")
+ provide_answer_label.pack()
+ provide_answer_entry = Entry(root)
+ provide_answer_entry.pack()
+
+ search_term_button = Button(root, text="ask", command=provide_answer)
+ search_term_button.pack()
+
+ root.mainloop()
\ No newline at end of file
diff --git a/QuestionAnswerVirtualAssistant/requirements.txt b/QuestionAnswerVirtualAssistant/requirements.txt
new file mode 100644
index 00000000000..fb4d28890ad
--- /dev/null
+++ b/QuestionAnswerVirtualAssistant/requirements.txt
@@ -0,0 +1,2 @@
+pandas
+scikit-learn
\ No newline at end of file
diff --git a/README.md b/README.md
index 97687e178a8..873ea61f1b9 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,4 @@
+#This is a new repo
# My Python Eggs 🐍 😄
@@ -52,7 +53,8 @@ Feel free to explore the scripts and use them for your learning and automation n
38. [Images Downloader](https://git.io/JvnJh) - Download images from webpages on Unix-based systems.
39. [space_invader.py.py](https://github.com/meezan-mallick/space_invader_game) - Classical 2D space invader game to recall your childhood memories.
40. [Test Case Generator](https://github.com/Tanmay-901/test-case-generator/blob/master/test_case.py) - Generate different types of test cases with a clean and friendly UI, used in competitive programming and software testing.
-
+41. [Extract Thumbnail From Video](https://github.com/geekcomputers/Python/tree/ExtractThumbnailFromVideo) - Extract Thumbnail from video files
+42. [How to begin the journey of open source (first contribution)](https://www.youtube.com/watch?v=v2X51AVgl3o) - First Contribution of open source
_**Note**: The content in this repository belongs to the respective authors and creators. I'm just providing a formatted README.md for better presentation._
diff --git a/Search_Engine/README.md b/Search_Engine/README.md
new file mode 100644
index 00000000000..36081b0aad8
--- /dev/null
+++ b/Search_Engine/README.md
@@ -0,0 +1,9 @@
+Python Program to search through various documents and return the documents containing the search term. Algorithm involves using a reverse index to store each word in each document where a document is defined by an index. To get the document that contains a search term, we simply find an intersect of all the words in the search term, and using the resulting indexes, retrieve the document(s) that contain these words
+
+To use directly, run
+
+```python3 backend.py```
+
+To use a gui, run
+
+```python3 frontend.py```
\ No newline at end of file
diff --git a/Search_Engine/backend.py b/Search_Engine/backend.py
new file mode 100644
index 00000000000..f716f5fa16d
--- /dev/null
+++ b/Search_Engine/backend.py
@@ -0,0 +1,135 @@
+import sqlite3
+import test_data
+import ast
+import json
+
+class SearchEngine:
+ """
+ It works by building a reverse index store that maps
+ words to an id. To find the document(s) that contain
+ a certain search term, we then take an intersection
+ of the ids
+ """
+
+ def __init__(self):
+ """
+ Returns - None
+ Input - None
+ ----------
+ - Initialize database. we use sqlite3
+ - Check if the tables exist, if not create them
+ - maintain a class level access to the database
+ connection object
+ """
+ self.conn = sqlite3.connect("searchengine.sqlite3", autocommit=True)
+ cur = self.conn.cursor()
+ res = cur.execute("SELECT name FROM sqlite_master WHERE name='IdToDoc'")
+ tables_exist = res.fetchone()
+
+ if not tables_exist:
+ self.conn.execute("CREATE TABLE IdToDoc(id INTEGER PRIMARY KEY, document TEXT)")
+ self.conn.execute('CREATE TABLE WordToId (name TEXT, value TEXT)')
+ cur.execute("INSERT INTO WordToId VALUES (?, ?)", ("index", "{}",))
+
+ def index_document(self, document):
+ """
+ Returns - string
+ Input - str: a string of words called document
+ ----------
+ Indexes the document. It does this by performing two
+ operations - add the document to the IdToDoc, then
+ adds the words in the document to WordToId
+ - takes in the document (str)
+ - passes the document to a method to add the document
+ to IdToDoc
+ - retrieves the id of the inserted document
+ - uses the id to call the method that adds the words of
+ the document to the reverse index WordToId if the word has not
+ already been indexed
+ """
+ row_id = self._add_to_IdToDoc(document)
+ cur = self.conn.cursor()
+ reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0]
+ reverse_idx = json.loads(reverse_idx)
+ document = document.split()
+ for word in document:
+ if word not in reverse_idx:
+ reverse_idx[word] = [row_id]
+ else:
+ if row_id not in reverse_idx[word]:
+ reverse_idx[word].append(row_id)
+ reverse_idx = json.dumps(reverse_idx)
+ cur = self.conn.cursor()
+ result = cur.execute("UPDATE WordToId SET value = (?) WHERE name='index'", (reverse_idx,))
+ return("index successful")
+
+ def _add_to_IdToDoc(self, document):
+ """
+ Returns - int: the id of the inserted document
+ Input - str: a string of words called `document`
+ ---------
+ - use the class-level connection object to insert the document
+ into the db
+ - retrieve and return the row id of the inserted document
+ """
+ cur = self.conn.cursor()
+ res = cur.execute("INSERT INTO IdToDoc (document) VALUES (?)", (document,))
+ return res.lastrowid
+
+ def find_documents(self, search_term):
+ """
+ Returns - : the return value of the _find_documents_with_idx method
+ Input - str: a string of words called `search_term`
+ ---------
+ - retrieve the reverse index
+ - use the words contained in the search term to find all the idxs
+ that contain the word
+ - use idxs to call the _find_documents_with_idx method
+ - return the result of the called method
+ """
+ cur = self.conn.cursor()
+ reverse_idx = cur.execute("SELECT value FROM WordToId WHERE name='index'").fetchone()[0]
+ reverse_idx = json.loads(reverse_idx)
+ search_term = search_term.split(" ")
+ all_docs_with_search_term = []
+ for term in search_term:
+ if term in reverse_idx:
+ all_docs_with_search_term.append(reverse_idx[term])
+
+ if not all_docs_with_search_term: # the search term does not exist
+ return []
+
+ common_idx_of_docs = set(all_docs_with_search_term[0])
+ for idx in all_docs_with_search_term[1:]:
+ common_idx_of_docs.intersection_update(idx)
+
+ if not common_idx_of_docs: # the search term does not exist
+ return []
+
+ return self._find_documents_with_idx(common_idx_of_docs)
+
+ def _find_documents_with_idx(self, idxs):
+ """
+ Returns - list[str]: the list of documents with the idxs
+ Input - list of idxs
+ ---------
+ - use the class-level connection object to retrieve the documents that
+ have the idx in the input list of idxs.
+ - retrieve and return these documents as a list
+ """
+ idxs = list(idxs)
+ cur = self.conn.cursor()
+ sql="SELECT document FROM IdToDoc WHERE id in ({seq})".format(
+ seq=','.join(['?']*len(idxs))
+ )
+ result = cur.execute(sql, idxs).fetchall()
+ return(result)
+
+
+if __name__ == "__main__":
+ se = SearchEngine()
+ se.index_document("we should all strive to be happy and happy again")
+ print(se.index_document("happiness is all you need"))
+ se.index_document("no way should we be sad")
+ se.index_document("a cheerful heart is a happy one even in Nigeria")
+ print(se.find_documents("happy"))
\ No newline at end of file
diff --git a/Search_Engine/frontend.py b/Search_Engine/frontend.py
new file mode 100644
index 00000000000..93dd7636f19
--- /dev/null
+++ b/Search_Engine/frontend.py
@@ -0,0 +1,37 @@
+from tkinter import *
+from tkinter import messagebox
+import backend
+
+
+def add_document():
+ document = add_documents_entry.get()
+ se = backend.SearchEngine()
+ print(se.index_document(document))
+
+def find_term():
+ term = find_term_entry.get()
+ se = backend.SearchEngine()
+ print(se.find_documents(term))
+
+if __name__ == "__main__":
+ root = Tk()
+ root.title("Registration Form")
+ root.geometry('300x300')
+
+ add_documents_label = Label(root, text="Add Document:")
+ add_documents_label.pack()
+ add_documents_entry = Entry(root)
+ add_documents_entry.pack()
+
+ add_document_button = Button(root, text="add", command=add_document)
+ add_document_button.pack()
+
+ find_term_label = Label(root, text="Input term to search:")
+ find_term_label.pack()
+ find_term_entry = Entry(root)
+ find_term_entry.pack()
+
+ search_term_button = Button(root, text="search", command=find_term)
+ search_term_button.pack()
+
+ root.mainloop()
\ No newline at end of file
diff --git a/Search_Engine/test_data.py b/Search_Engine/test_data.py
new file mode 100644
index 00000000000..d58f43e7d17
--- /dev/null
+++ b/Search_Engine/test_data.py
@@ -0,0 +1,8 @@
+documents = [
+ "we should all strive to be happy",
+ "happiness is all you need",
+ "a cheerful heart is a happy one",
+ "no way should we be sad"
+]
+
+search = "happy"
\ No newline at end of file
diff --git a/Shivaansh.py b/Shivaansh.py
deleted file mode 100644
index deec715f10f..00000000000
--- a/Shivaansh.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from __future__ import print_function
-
-x = input("Enter a number: ")
-for i in range(1, 11, 1):
- print(x, "x", i, "=", (x * i))
diff --git a/Simple calculator.py b/Simple calculator.py
deleted file mode 100644
index 497bdf7854b..00000000000
--- a/Simple calculator.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# Program to make a simple calculator
-
-# This function adds two numbers
-def add(x, y):
- return x + y
-
-# This function subtracts two numbers
-def subtract(x, y):
- return x - y
-
-# This function multiplies two numbers
-def multiply(x, y):
- return x * y
-
-# This function divides two numbers
-def divide(x, y):
- if(y==0):
- raise Exception("Divisor cannot be zero")
- return x / y
-
-
-print("Select operation.")
-print("1.Add")
-print("2.Subtract")
-print("3.Multiply")
-print("4.Divide")
-
-while True:
- # Take input from the user
- choice = input("Enter choice(1/2/3/4): ")
-
- # Check if choice is one of the four options
- if choice in ('1', '2', '3', '4'):
- num1 = float(input("Enter first number: "))
- num2 = float(input("Enter second number: "))
-
- if choice == '1':
- print(num1, "+", num2, "=", add(num1, num2))
-
- elif choice == '2':
- print(num1, "-", num2, "=", subtract(num1, num2))
-
- elif choice == '3':
- print(num1, "*", num2, "=", multiply(num1, num2))
-
- elif choice == '4':
- print(num1, "/", num2, "=", divide(num1, num2))
- break
- else:
- print("Invalid Input")
diff --git a/SimpleCalculator.py b/SimpleCalculator.py
deleted file mode 100644
index 294c972e545..00000000000
--- a/SimpleCalculator.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# Simple Calculator
-def add(a, b):
- return a + b
-
-
-def subtract(a, b):
- return a - b
-
-
-def multiply(a, b):
- return a * b
-
-
-def divide(a, b):
- try:
- return a / b
- except ZeroDivisionError:
- return "Zero Division Error"
-
-
-def power(a, b):
- return a ** b
-
-
-def main():
- print("Select Operation")
- print("1.Add")
- print("2.Subtract")
- print("3.Multiply")
- print("4.Divide")
- print("5.Power")
-
- choice = input("Enter Choice(+,-,*,/,^): ")
- num1 = int(input("Enter first number: "))
- num2 = int(input("Enter Second number:"))
-
- if choice == "+":
- print(num1, "+", num2, "=", add(num1, num2))
-
- elif choice == "-":
- print(num1, "-", num2, "=", subtract(num1, num2))
-
- elif choice == "*":
- print(num1, "*", num2, "=", multiply(num1, num2))
-
- elif choice == "/":
- print(num1, "/", num2, "=", divide(num1, num2))
- elif choice == "**":
- print(num1, "^", num2, "=", power(num1, num2))
- else:
- print("Invalid input")
- main()
-
-
-if __name__ == "__main__":
- main()
diff --git a/Simple_Calculator.py b/Simple_Calculator.py
deleted file mode 100644
index 0dc8e42b8f7..00000000000
--- a/Simple_Calculator.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# Program make a simple calculator
-
-# This function adds two numbers
-def add(x, y):
- return x + y
-
-# This function subtracts two numbers
-def subtract(x, y):
- return x - y
-
-# This function multiplies two numbers
-def multiply(x, y):
- return x * y
-
-# This function divides two numbers
-def divide(x, y):
- return x / y
-
-# This function gives the remainder of two numbers
-def mod(x,y):
- return x % y
-
-
-print("Select operation.")
-print("1.Add")
-print("2.Subtract")
-print("3.Multiply")
-print("4.Divide")
-print("5.Modulo division")
-
-while True:
- # Take input from the user
- choice = input("Enter choice(1/2/3/4/5): ")
-
- # Check if choice is one of the four options
- if choice in ('1', '2', '3', '4','5'):
- num1 = float(input("Enter first number: "))
- num2 = float(input("Enter second number: "))
-
- if choice == '1':
- print(num1, "+", num2, "=", add(num1, num2))
-
- elif choice == '2':
- print(num1, "-", num2, "=", subtract(num1, num2))
-
- elif choice == '3':
- print(num1, "*", num2, "=", multiply(num1, num2))
-
- elif choice == '4':
- print(num1, "/", num2, "=", divide(num1, num2))
-
- elif choice == '5':
- print(num1, "%", num2, "=", mod(num1, num2))
- break
- else:
- print("Invalid Input")
diff --git a/Snake_water_gun/main.py b/Snake_water_gun/main.py
index 5a8b1332894..23d8b51f5c3 100644
--- a/Snake_water_gun/main.py
+++ b/Snake_water_gun/main.py
@@ -22,21 +22,26 @@ class bcolors:
run = True
li = ["s", "w", "g"]
-system("clear")
-b = input(
- bcolors.OKBLUE
- + bcolors.BOLD
- + "Welcome to the game 'Snake-Water-Gun'.\nWanna play? Type Y or N: "
- + bcolors.ENDC
-).capitalize()
-
-if b == "N":
- run = False
- print("Ok bubyeee! See you later")
-elif b == "Y" or b == "y":
- print(
- "There will be 10 matches, and the one who wins more matches will win. Let's start."
- )
+while True:
+ system("clear")
+ b = input(
+ bcolors.OKBLUE
+ + bcolors.BOLD
+ + "Welcome to the game 'Snake-Water-Gun'.\nWanna play? Type Y or N: "
+ + bcolors.ENDC
+ ).capitalize()
+
+ if b == "N":
+ run = False
+ print("Ok bubyeee! See you later")
+ break
+ elif b == "Y" or b == "y":
+ print(
+ "There will be 10 matches, and the one who wins more matches will win. Let's start."
+ )
+ break
+ else:
+ continue
i = 0
score = 0
diff --git a/Sorting Algorithims/heapsort_linkedlist.py b/Sorting Algorithims/heapsort_linkedlist.py
new file mode 100644
index 00000000000..7e9584077e6
--- /dev/null
+++ b/Sorting Algorithims/heapsort_linkedlist.py
@@ -0,0 +1,82 @@
+class Node:
+ def __init__(self, data):
+ self.data = data
+ self.next = None
+
+class LinkedList:
+ def __init__(self):
+ self.head = None
+
+ def push(self, data):
+ new_node = Node(data)
+ new_node.next = self.head
+ self.head = new_node
+
+ def print_list(self):
+ current = self.head
+ while current:
+ print(current.data, end=" -> ")
+ current = current.next
+ print("None")
+
+ def heapify(self, n, i):
+ largest = i
+ left = 2 * i + 1
+ right = 2 * i + 2
+
+ current = self.head
+ for _ in range(i):
+ current = current.next
+
+ if left < n and current.data < current.next.data:
+ largest = left
+
+ if right < n and current.data < current.next.data:
+ largest = right
+
+ if largest != i:
+ self.swap(i, largest)
+ self.heapify(n, largest)
+
+ def swap(self, i, j):
+ current_i = self.head
+ current_j = self.head
+
+ for _ in range(i):
+ current_i = current_i.next
+
+ for _ in range(j):
+ current_j = current_j.next
+
+ current_i.data, current_j.data = current_j.data, current_i.data
+
+ def heap_sort(self):
+ n = 0
+ current = self.head
+ while current:
+ n += 1
+ current = current.next
+
+ for i in range(n // 2 - 1, -1, -1):
+ self.heapify(n, i)
+
+ for i in range(n - 1, 0, -1):
+ self.swap(0, i)
+ self.heapify(i, 0)
+
+# Example usage:
+linked_list = LinkedList()
+linked_list.push(12)
+linked_list.push(11)
+linked_list.push(13)
+linked_list.push(5)
+linked_list.push(6)
+linked_list.push(7)
+
+print("Original Linked List:")
+linked_list.print_list()
+
+linked_list.heap_sort()
+
+print("Sorted Linked List:")
+linked_list.print_list()
diff --git a/Sorting Algorithims/mergesort_linkedlist.py b/Sorting Algorithims/mergesort_linkedlist.py
new file mode 100644
index 00000000000..429684b6c0c
--- /dev/null
+++ b/Sorting Algorithims/mergesort_linkedlist.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+class Node:
+ def __init__(self, data: int) -> None:
+ self.data = data
+ self.next = None
+
+class LinkedList:
+ def __init__(self):
+ self.head = None
+
+ def insert(self, new_data: int) -> None:
+ new_node = Node(new_data)
+ new_node.next = self.head
+ self.head = new_node
+
+ def printLL(self) -> None:
+ temp = self.head
+ if temp == None:
+ return 'Linked List is empty'
+ while temp.next:
+ print(temp.data, '->', end='')
+ temp = temp.next
+ print(temp.data)
+ return
+
+# Merge two sorted linked lists
+def merge(left, right):
+ if not left:
+ return right
+ if not right:
+ return left
+
+ if left.data < right.data:
+ result = left
+ result.next = merge(left.next, right)
+ else:
+ result = right
+ result.next = merge(left, right.next)
+
+ return result
+
+# Merge sort for linked list
+def merge_sort(head):
+ if not head or not head.next:
+ return head
+
+ # Find the middle of the list
+ slow = head
+ fast = head.next
+ while fast and fast.next:
+ slow = slow.next
+ fast = fast.next.next
+
+ left = head
+ right = slow.next
+ slow.next = None
+
+ left = merge_sort(left)
+ right = merge_sort(right)
+
+ return merge(left, right)
+
+if __name__ == "__main__":
+ ll = LinkedList()
+ print("Enter the space-separated values of numbers to be inserted in the linked list prompted below:")
+ arr = list(map(int, input().split()))
+ for num in arr:
+ ll.insert(num)
+
+ print("Linked list before sorting:")
+ ll.printLL()
+
+ ll.head = merge_sort(ll.head)
+
+ print('Linked list after sorting:')
+ ll.printLL()
diff --git a/Sorting Algorithims/quicksort_linkedlist.py b/Sorting Algorithims/quicksort_linkedlist.py
new file mode 100644
index 00000000000..97de82e2bc2
--- /dev/null
+++ b/Sorting Algorithims/quicksort_linkedlist.py
@@ -0,0 +1,76 @@
+"""
+Given a linked list with head pointer,
+sort the linked list using quicksort technique without using any extra space
+Time complexity: O(NlogN), Space complexity: O(1)
+"""
+from __future__ import annotations
+
+
+class Node:
+ def __init__(self, data: int) -> None:
+ self.data = data
+ self.next = None
+
+
+class LinkedList:
+ def __init__(self):
+ self.head = None
+
+ # method to insert nodes at the start of linkedlist
+ def insert(self, new_data: int) -> None:
+ new_node = Node(new_data)
+ new_node.next = self.head
+ self.head = new_node
+
+ # method to print the linkedlist
+ def printLL(self) -> None:
+ temp = self.head
+ if temp == None:
+ return 'Linked List is empty'
+ while temp.next:
+ print(temp.data, '->', end='')
+ temp = temp.next
+ print(temp.data)
+ return
+
+# Partition algorithm with pivot as first element
+
+
+def partition(start, end):
+ if start == None or start.next == None:
+ return start
+ prev, curr = start, start.next
+ pivot = prev.data
+ while curr != end:
+ if curr.data < pivot:
+ prev = prev.next
+ temp = prev.data
+ prev.data = curr.data
+ curr.data = temp
+ curr = curr.next
+ temp = prev.data
+ prev.data = start.data
+ start.data = temp
+ return prev
+
+
+# recursive quicksort for function calls
+def quicksort_LL(start, end):
+ if start != end:
+ pos = partition(start, end)
+ quicksort_LL(start, pos)
+ quicksort_LL(pos.next, end)
+ return
+
+
+if __name__ == "__main__":
+ ll = LinkedList()
+ print("Enter the space seperated values of numbers to be inserted in linkedlist prompted below:")
+ arr = list(map(int, input().split()))
+ for num in arr:
+ ll.insert(num)
+ print("Linkedlist before sorting:")
+ ll.printLL()
+ quicksort_LL(ll.head, None)
+ print('Linkedlist after sorting: ')
+ ll.printLL()
diff --git a/Sorting Algorithms/dual_pivot_quicksort.py b/Sorting Algorithms/dual_pivot_quicksort.py
new file mode 100644
index 00000000000..ef625d2fb13
--- /dev/null
+++ b/Sorting Algorithms/dual_pivot_quicksort.py
@@ -0,0 +1,80 @@
+def dual_pivot_quicksort(arr, low, high):
+ """
+ Performs Dual-Pivot QuickSort on the input array.
+
+ Dual-Pivot QuickSort is an optimized version of QuickSort that uses
+ two pivot elements to partition the array into three segments in each
+ recursive call. This improves performance by reducing the number of
+ recursive calls, making it faster on average than the single-pivot
+ QuickSort.
+
+ Parameters:
+ arr (list): The list to be sorted.
+ low (int): The starting index of the segment to sort.
+ high (int): The ending index of the segment to sort.
+
+ Returns:
+ None: Sorts the array in place.
+ """
+ if low < high:
+ # Partition the array and get the two pivot indices
+ lp, rp = partition(arr, low, high)
+ # Recursively sort elements less than pivot1
+ dual_pivot_quicksort(arr, low, lp - 1)
+ # Recursively sort elements between pivot1 and pivot2
+ dual_pivot_quicksort(arr, lp + 1, rp - 1)
+ # Recursively sort elements greater than pivot2
+ dual_pivot_quicksort(arr, rp + 1, high)
+
+def partition(arr, low, high):
+ """
+ Partitions the array segment defined by low and high using two pivots.
+
+ This function arranges elements into three sections:
+ - Elements less than pivot1
+ - Elements between pivot1 and pivot2
+ - Elements greater than pivot2
+
+ Parameters:
+ arr (list): The list to partition.
+ low (int): The starting index of the segment to partition.
+ high (int): The ending index of the segment to partition.
+
+ Returns:
+ tuple: Indices of the two pivots in sorted positions (lp, rp).
+ """
+ # Ensure the left pivot is less than or equal to the right pivot
+ if arr[low] > arr[high]:
+ arr[low], arr[high] = arr[high], arr[low]
+ pivot1 = arr[low] # left pivot
+ pivot2 = arr[high] # right pivot
+
+ # Initialize pointers
+ i = low + 1 # Pointer to traverse the array
+ lt = low + 1 # Boundary for elements less than pivot1
+ gt = high - 1 # Boundary for elements greater than pivot2
+
+ # Traverse and partition the array based on the two pivots
+ while i <= gt:
+ if arr[i] < pivot1:
+ arr[i], arr[lt] = arr[lt], arr[i] # Swap to move smaller elements to the left
+ lt += 1
+ elif arr[i] > pivot2:
+ arr[i], arr[gt] = arr[gt], arr[i] # Swap to move larger elements to the right
+ gt -= 1
+ i -= 1 # Decrement i to re-evaluate the swapped element
+ i += 1
+
+ # Place the pivots in their correct sorted positions
+ lt -= 1
+ gt += 1
+ arr[low], arr[lt] = arr[lt], arr[low] # Place pivot1 at its correct position
+ arr[high], arr[gt] = arr[gt], arr[high] # Place pivot2 at its correct position
+
+ return lt, gt # Return the indices of the two pivots
+
+# Example usage
+# Sample Test Case
+arr = [24, 8, 42, 75, 29, 77, 38, 57]
+dual_pivot_quicksort(arr, 0, len(arr) - 1)
+print("Sorted array:", arr)
diff --git a/SpeechToText.py b/SpeechToText.py
new file mode 100644
index 00000000000..12ee402667a
--- /dev/null
+++ b/SpeechToText.py
@@ -0,0 +1,14 @@
+import pyttsx3
+
+engine = pyttsx3.init()
+
+voices = engine.getProperty("voices")
+for voice in voices:
+ print(voice.id)
+ print(voice.name)
+
+id ="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0"
+engine.setProperty("voices",id )
+engine.setProperty("rate",165)
+engine.say("jarivs") # Replace string with our own text
+engine.runAndWait()
\ No newline at end of file
diff --git a/String_Palindrome.py b/String_Palindrome.py
index 6b8302b6477..ab4103fd863 100644
--- a/String_Palindrome.py
+++ b/String_Palindrome.py
@@ -1,15 +1,15 @@
# Program to check if a string is palindrome or not
-my_str = 'aIbohPhoBiA'
+my_str = input().strip()
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
-rev_str = reversed(my_str)
+rev_str = my_str[::-1]
# check if the string is equal to its reverse
-if list(my_str) == list(rev_str):
+if my_str == rev_str:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
diff --git a/Sum of digits of a number.py b/Sum of digits of a number.py
index ebc8f00b514..c000547c7bc 100644
--- a/Sum of digits of a number.py
+++ b/Sum of digits of a number.py
@@ -1,7 +1,33 @@
-q=0
-n=int(input("Enter Number: "))
-while(n>0):
- r=n%10
- q=q+r
- n=n//10
-print("Sum of digits is: "+str(q))
+# Python code to calculate the sum of digits of a number, by taking number input from user.
+
+import sys
+
+def get_integer():
+ for i in range(3,0,-1): # executes the loop 3 times. Giving 3 chances to the user.
+ num = input("enter a number:")
+ if num.isnumeric(): # checks if entered input is an integer string or not.
+ num = int(num) # converting integer string to integer. And returns it to where function is called.
+ return num
+ else:
+ print("enter integer only")
+ print(f'{i-1} chances are left' if (i-1)>1 else f'{i-1} chance is left') # prints if user entered wrong input and chances left.
+ continue
+
+
+def addition(num):
+ Sum=0
+ if type(num) is type(None): # Checks if number type is none or not. If type is none program exits.
+ print("Try again!")
+ sys.exit()
+ while num > 0: # Addition- adding the digits in the number.
+ digit = int(num % 10)
+ Sum += digit
+ num /= 10
+ return Sum # Returns sum to where the function is called.
+
+
+
+if __name__ == '__main__': # this is used to overcome the problems while importing this file.
+ number = get_integer()
+ Sum = addition(number)
+ print(f'Sum of digits of {number} is {Sum}') # Prints the sum
diff --git a/Swap numbers.py b/Swap numbers.py
deleted file mode 100644
index 15fe20efc2e..00000000000
--- a/Swap numbers.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# Python program to swap two variables
-
-x = 5
-y = 10
-
-# To take inputs from the user
-#x = input('Enter value of x: ')
-#y = input('Enter value of y: ')
-
-# create a temporary variable and swap the values
-temp = x
-x = y
-y = temp
-
-# in python we can swap without using a third variablex
-
-x,y = y,x
-print(x,y)
-# output is 10,5
-
-print('The value of x after swapping: {}'.format(x))
-print('The value of y after swapping: {}'.format(y))
diff --git a/TIC_TAC_TOE/index.py b/TIC_TAC_TOE/index.py
new file mode 100644
index 00000000000..95245d34fe5
--- /dev/null
+++ b/TIC_TAC_TOE/index.py
@@ -0,0 +1,60 @@
+def print_board(board):
+ for row in board:
+ print(" | ".join(row))
+ print("-" * 9)
+
+def check_winner(board, player):
+ for i in range(3):
+ # Check rows and columns
+ if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)):
+ return True
+ # Check diagonals
+ if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)):
+ return True
+ return False
+
+def is_full(board):
+ return all(cell != " " for row in board for cell in row)
+# A function that validates user input
+def get_valid_input(prompt):
+ while True:
+ try:
+ value = int(input(prompt))
+ if 0 <= value < 3: # Check if the value is within the valid range
+ return value
+ else:
+ print("Invalid input: Enter a number between 0 and 2.")
+ except ValueError:
+ print("Invalid input: Please enter an integer.")
+
+def main():
+ board = [[" " for _ in range(3)] for _ in range(3)]
+ player = "X"
+
+ while True:
+ print_board(board)
+ print(f"Player {player}'s turn:")
+
+ # Get validated inputs
+ row = get_valid_input("Enter the row (0, 1, 2): ")
+ col = get_valid_input("Enter the column (0, 1, 2): ")
+
+ if board[row][col] == " ":
+ board[row][col] = player
+
+ if check_winner(board, player):
+ print_board(board)
+ print(f"Player {player} wins!")
+ break
+
+ if is_full(board):
+ print_board(board)
+ print("It's a draw!")
+ break
+
+ player = "O" if player == "X" else "X"
+ else:
+ print("Invalid move: That spot is already taken. Try again.")
+
+if __name__ == "__main__":
+ main()
diff --git a/Task1.2.txt b/Task1.2.txt
new file mode 100644
index 00000000000..e100a2ca4ab
--- /dev/null
+++ b/Task1.2.txt
@@ -0,0 +1 @@
+Task 1.2
diff --git a/TaskManager.py b/TaskManager.py
new file mode 100644
index 00000000000..250eb05323b
--- /dev/null
+++ b/TaskManager.py
@@ -0,0 +1,31 @@
+import datetime
+import csv
+
+def load_tasks(filename='tasks.csv'):
+ tasks = []
+ with open(filename, 'r', newline='') as file:
+ reader = csv.reader(file)
+ for row in reader:
+ tasks.append({'task': row[0], 'deadline': row[1], 'completed': row[2]})
+ return tasks
+
+def save_tasks(tasks, filename='tasks.csv'):
+ with open(filename, 'w', newline='') as file:
+ writer = csv.writer(file)
+ for task in tasks:
+ writer.writerow([task['task'], task['deadline'], task['completed']])
+
+def add_task(task, deadline):
+ tasks = load_tasks()
+ tasks.append({'task': task, 'deadline': deadline, 'completed': 'No'})
+ save_tasks(tasks)
+ print("Task added successfully!")
+
+def show_tasks():
+ tasks = load_tasks()
+ for task in tasks:
+ print(f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}")
+
+# Example usage
+add_task('Write daily report', '2024-04-20')
+show_tasks()
diff --git a/TaskPlanner.py b/TaskPlanner.py
new file mode 100644
index 00000000000..250eb05323b
--- /dev/null
+++ b/TaskPlanner.py
@@ -0,0 +1,31 @@
+import datetime
+import csv
+
+def load_tasks(filename='tasks.csv'):
+ tasks = []
+ with open(filename, 'r', newline='') as file:
+ reader = csv.reader(file)
+ for row in reader:
+ tasks.append({'task': row[0], 'deadline': row[1], 'completed': row[2]})
+ return tasks
+
+def save_tasks(tasks, filename='tasks.csv'):
+ with open(filename, 'w', newline='') as file:
+ writer = csv.writer(file)
+ for task in tasks:
+ writer.writerow([task['task'], task['deadline'], task['completed']])
+
+def add_task(task, deadline):
+ tasks = load_tasks()
+ tasks.append({'task': task, 'deadline': deadline, 'completed': 'No'})
+ save_tasks(tasks)
+ print("Task added successfully!")
+
+def show_tasks():
+ tasks = load_tasks()
+ for task in tasks:
+ print(f"Task: {task['task']}, Deadline: {task['deadline']}, Completed: {task['completed']}")
+
+# Example usage
+add_task('Write daily report', '2024-04-20')
+show_tasks()
diff --git a/ThirdAI/Terms and Conditions/Readme.md b/ThirdAI/Terms and Conditions/Readme.md
new file mode 100644
index 00000000000..da9378a8dcb
--- /dev/null
+++ b/ThirdAI/Terms and Conditions/Readme.md
@@ -0,0 +1,81 @@
+# ThirdAIApp and NeuralDBClient
+
+This repository contains two components: `ThirdAIApp` and `NeuralDBClient`. `ThirdAIApp` is a graphical user interface (GUI) application for interacting with the ThirdAI neural database client. It allows you to perform training with PDF files and query the database. `NeuralDBClient` is a Python class that serves as a client for interacting with the ThirdAI neural database. It allows you to train the database with PDF files and perform queries to retrieve information.
+
+## ThirdAIApp
+
+### Features
+
+- Insert PDF files for training.
+- Train the neural database client.
+- Enter queries to retrieve information from the database.
+- Display the output in a new window.
+
+### Installation
+
+To run `ThirdAIApp`, you need to have Python and Tkinter installed. You also need the `ThirdAI` library, which you can install using pip:
+
+```bash
+pip install ThirdAI
+```
+
+### Usage
+
+1. Run the `ThirdAIApp.py` script.
+2. The main window will appear.
+3. Click the "Insert File!" button to select a PDF file for training.
+4. Click the "Training" button to train the neural database client with the selected file.
+5. Enter your query in the "Query" field.
+6. Click the "Processing" button to process the query and display the output in a new window.
+7. You can click the "Clear" button to clear the query and file selections.
+
+### Dependencies
+
+- Python 3.x
+- Tkinter
+- ThirdAI
+
+## NeuralDBClient
+
+### Features
+
+- Train the neural database with PDF files.
+- Perform queries on the neural database.
+
+### Installation
+
+To use `NeuralDBClient`, you need to have the `thirdai` library installed, and you'll need an API key from ThirdAI.
+
+You can install the `thirdai` library using pip:
+
+```bash
+pip install thirdai
+```
+
+### Usage
+
+1. Import the `NeuralDBClient` class from `neural_db_client.py`.
+2. Create an instance of the `NeuralDBClient` class, providing your ThirdAI API key as an argument.
+
+ ```python
+ from neural_db_client import NeuralDBClient
+
+ client = NeuralDBClient(api_key="YOUR_API_KEY")
+ ```
+
+3. Train the neural database with PDF files using the `train` method. Provide a list of file paths to the PDF files you want to use for training.
+
+ ```python
+ client.train(file_paths=["file1.pdf", "file2.pdf"])
+ ```
+
+4. Perform queries on the neural database using the `query` method. Provide your query as a string, and the method will return the query results as a string.
+
+ ```python
+ result = client.query(question="What is the capital of France?")
+ ```
+
+### Dependencies
+
+- `thirdai` library
+
diff --git a/ThirdAI/Terms and Conditions/ThirdAI.py b/ThirdAI/Terms and Conditions/ThirdAI.py
new file mode 100644
index 00000000000..67d3928ec4b
--- /dev/null
+++ b/ThirdAI/Terms and Conditions/ThirdAI.py
@@ -0,0 +1,36 @@
+from thirdai import licensing, neural_db as ndb
+
+
+class NeuralDBClient:
+ def __init__(self):
+ # Activating ThirdAI Key
+ licensing.activate("ADD-YOUR-THIRDAI-ACTIVATION-KEY")
+
+ # Creating NeuralBD variable to access Neural Database
+ self.db = ndb.NeuralDB(user_id="my_user")
+
+ def train(self, file_paths):
+ # Retrieving path of file
+ insertable_docs = []
+ pdf_files = file_paths
+
+ # Appending PDF file to the Database stack
+ pdf_doc = ndb.PDF(pdf_files)
+ insertable_docs.append(pdf_doc)
+
+ # Inserting/Uploading PDF file to Neural database for training
+ self.db.insert(insertable_docs, train=True)
+
+ def query(self, question):
+ # Searching of required query in neural database
+ search_results = self.db.search(
+ query=question,
+ top_k=2,
+ on_error=lambda error_msg: print(f"Error! {error_msg}"))
+
+ output = ""
+ for result in search_results:
+ output += result.text + "\n\n"
+
+ return output
+
diff --git a/ThirdAI/Terms and Conditions/TkinterUI.py b/ThirdAI/Terms and Conditions/TkinterUI.py
new file mode 100644
index 00000000000..47317636a23
--- /dev/null
+++ b/ThirdAI/Terms and Conditions/TkinterUI.py
@@ -0,0 +1,144 @@
+import tkinter as tk
+from tkinter.font import Font
+from tkinter import messagebox
+from tkinter import filedialog
+from ThirdAI import NeuralDBClient as Ndb
+
+
+class ThirdAIApp:
+ """
+ A GUI application for using the ThirdAI neural database client to train and query data.
+ """
+ def __init__(self, root):
+ """
+ Initialize the user interface window.
+
+ Args:
+ root (tk.Tk): The main Tkinter window.
+ """
+ # Initialize the main window
+ self.root = root
+ self.root.geometry("600x500")
+ self.root.title('ThirdAI - T&C')
+
+ # Initialize variables
+ self.path = []
+ self.client = Ndb()
+
+ # GUI elements
+
+ # Labels and buttons
+ self.menu = tk.Label(self.root, text="Terms & Conditions", font=self.custom_font(30), fg='black',
+ highlightthickness=2, highlightbackground="red")
+ self.menu.place(x=125, y=10)
+
+ self.insert_button = tk.Button(self.root, text="Insert File!", font=self.custom_font(15), fg='black', bg="grey",
+ width=10, command=self.file_input)
+ self.insert_button.place(x=245, y=100)
+
+ self.text_box = tk.Text(self.root, wrap=tk.WORD, width=30, height=1)
+ self.text_box.place(x=165, y=150)
+
+ self.training_button = tk.Button(self.root, text="Training", font=self.custom_font(15), fg='black', bg="grey",
+ width=10, command=self.training)
+ self.training_button.place(x=245, y=195)
+
+ self.query_label = tk.Label(self.root, text="Query", font=self.custom_font(20), fg='black')
+ self.query_label.place(x=255, y=255)
+
+ self.query_entry = tk.Entry(self.root, font=self.custom_font(20), width=30)
+ self.query_entry.place(x=70, y=300)
+
+ self.processing_button = tk.Button(self.root, text="Processing", font=self.custom_font(15), fg='black',
+ bg="grey", width=10, command=self.processing)
+ self.processing_button.place(x=245, y=355)
+
+ self.clear_button = tk.Button(self.root, text="Clear", font=15, fg='black', bg="grey", width=10,
+ command=self.clear_all)
+ self.clear_button.place(x=245, y=405)
+
+ @staticmethod
+ def custom_font(size):
+ """
+ Create a custom font with the specified size.
+
+ Args:
+ size (int): The font size.
+
+ Returns:
+ Font: The custom Font object.
+ """
+ return Font(size=size)
+
+ def file_input(self):
+ """
+ Open a file dialog to select a PDF file and display its name in the text box.
+ """
+ file_type = dict(defaultextension=".pdf", filetypes=[("pdf file", "*.pdf")])
+ file_path = filedialog.askopenfilename(**file_type)
+
+ if file_path:
+ self.path.append(file_path)
+ file_name = file_path.split("/")[-1]
+ self.text_box.delete(1.0, tk.END)
+ self.text_box.insert(tk.INSERT, file_name)
+
+ def clear_all(self):
+ """
+ Clear the query entry, text box, and reset the path.
+ """
+ self.query_entry.delete(0, tk.END)
+ self.text_box.delete(1.0, tk.END)
+ self.path.clear()
+
+ def training(self):
+ """
+ Train the neural database client with the selected PDF file.
+ """
+ if not self.path:
+ messagebox.showwarning("No File Selected", "Please select a PDF file before training.")
+ return
+
+ self.client.train(self.path[0])
+
+ messagebox.showinfo("Training Complete", "Training is done!")
+
+ def processing(self):
+ """
+ Process a user query and display the output in a new window.
+ """
+ question = self.query_entry.get()
+
+ # When there is no query submitted by the user
+ if not question:
+ messagebox.showwarning("No Query", "Please enter a query.")
+ return
+
+ output = self.client.query(question)
+ self.display_output(output)
+
+ def display_output(self, output_data):
+ """
+ Display the output data in a new window.
+
+ Args:
+ output_data (str): The output text to be displayed.
+ """
+ output_window = tk.Toplevel(self.root)
+ output_window.title("Output Data")
+ output_window.geometry("500x500")
+
+ output_text = tk.Text(output_window, wrap=tk.WORD, width=50, height=50)
+ output_text.pack(padx=10, pady=10)
+ output_text.insert(tk.END, output_data)
+
+
+if __name__ == "__main__":
+ """
+ Initializing the main application window
+ """
+
+ # Calling the main application window
+ win = tk.Tk()
+ app = ThirdAIApp(win)
+ win.mainloop()
diff --git a/ThirdAI/Terms and Conditions/XYZ product.pdf b/ThirdAI/Terms and Conditions/XYZ product.pdf
new file mode 100644
index 00000000000..8a7484070df
Binary files /dev/null and b/ThirdAI/Terms and Conditions/XYZ product.pdf differ
diff --git a/To find the largest number between 3 numbers.py b/To find the largest number between 3 numbers.py
index 061e1e3aff4..5e7e1575292 100644
--- a/To find the largest number between 3 numbers.py
+++ b/To find the largest number between 3 numbers.py
@@ -2,6 +2,6 @@
a=[]
for i in range(3):
- a.append(int(input())
+ a.append(int(input()))
print("The largest among three numbers is:",max(a))
diff --git a/Todo_GUi.py b/Todo_GUi.py
new file mode 100644
index 00000000000..21dafef44e3
--- /dev/null
+++ b/Todo_GUi.py
@@ -0,0 +1,48 @@
+from tkinter import messagebox
+import tkinter as tk
+
+# Function to be called when button is clicked
+def add_Button():
+ task=Input.get()
+ if task:
+ List.insert(tk.END,task)
+ Input.delete(0,tk.END)
+
+
+
+def del_Button():
+ try:
+ task=List.curselection()[0]
+ List.delete(task)
+ except IndexError:
+ messagebox.showwarning("Selection Error", "Please select a task to delete.")
+
+
+
+# Create the main window
+window = tk.Tk()
+window.title("Task Manager")
+window.geometry("500x500")
+window.resizable(False,False)
+window.config(bg="light grey")
+
+# text filed
+Input=tk.Entry(window,width=50)
+Input.grid(row=0,column=0,padx=20,pady=60)
+Input.focus()
+
+# Create the button
+add =tk.Button(window, text="ADD TASK", height=2, width=9, command=add_Button)
+add.grid(row=0, column=1, padx=20, pady=0)
+
+delete=tk.Button(window,text="DELETE TASK", height=2,width=10,command=del_Button)
+delete.grid(row=1,column=1)
+
+# creating list box
+List=tk.Listbox(window,width=50,height=20)
+List.grid(row=1,column=0)
+
+
+
+
+window.mainloop()
\ No newline at end of file
diff --git a/Trending youtube videos b/Trending youtube videos
new file mode 100644
index 00000000000..a14535e4ddc
--- /dev/null
+++ b/Trending youtube videos
@@ -0,0 +1,43 @@
+'''
+ Python program that uses the YouTube Data API to fetch the top 10 trending YouTube videos.
+You’ll need to have an API key from Google Cloud Platform to use the YouTube Data API.
+
+First, install the google-api-python-client library if you haven’t already:
+pip install google-api-python-client
+
+Replace 'YOUR_API_KEY' with your actual API key. This script will fetch and print the titles,
+channels, and view counts of the top 10 trending YouTube videos in India.
+You can change the regionCode to any other country code if needed.
+
+Then, you can use the following code:
+
+'''
+
+from googleapiclient.discovery import build
+
+# Replace with your own API key
+API_KEY = 'YOUR_API_KEY'
+YOUTUBE_API_SERVICE_NAME = 'youtube'
+YOUTUBE_API_VERSION = 'v3'
+
+def get_trending_videos():
+ youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY)
+
+ # Call the API to get the top 10 trending videos
+ request = youtube.videos().list(
+ part='snippet,statistics',
+ chart='mostPopular',
+ regionCode='IN', # Change this to your region code
+ maxResults=10
+ )
+ response = request.execute()
+
+ # Print the video details
+ for item in response['items']:
+ title = item['snippet']['title']
+ channel = item['snippet']['channelTitle']
+ views = item['statistics']['viewCount']
+ print(f'Title: {title}\nChannel: {channel}\nViews: {views}\n')
+
+if __name__ == '__main__':
+ get_trending_videos()
diff --git a/Wikipdedia/flask_rendering.py b/Wikipdedia/flask_rendering.py
new file mode 100644
index 00000000000..05c6d7494bf
--- /dev/null
+++ b/Wikipdedia/flask_rendering.py
@@ -0,0 +1,27 @@
+from flask import Flask, render_template, request
+import practice_beautifulsoap as data
+
+app = Flask(__name__, template_folder='template')
+
+
+@app.route('/', methods=["GET", "POST"])
+def index():
+ languages = data.lang()
+ return render_template('index.html', languages=languages)
+
+
+@app.route("/display", methods=["POST"])
+def output():
+ if request.method == "POST":
+ entered_topic = request.form.get("topic")
+ selected_language = request.form.get("language")
+
+ soup_data = data.data(entered_topic, selected_language)
+ soup_image = data.get_image_urls(entered_topic)
+
+ return render_template('output.html', heading=entered_topic.upper(), data=soup_data,
+ url=soup_image, language=selected_language)
+
+
+if __name__ == "__main__":
+ app.run(debug=True)
diff --git a/Wikipdedia/main.py b/Wikipdedia/main.py
new file mode 100644
index 00000000000..5596b44786f
--- /dev/null
+++ b/Wikipdedia/main.py
@@ -0,0 +1,16 @@
+# This is a sample Python script.
+
+# Press Shift+F10 to execute it or replace it with your code.
+# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
+
+
+def print_hi(name):
+ # Use a breakpoint in the code line below to debug your script.
+ print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
+
+
+# Press the green button in the gutter to run the script.
+if __name__ == '__main__':
+ print_hi('PyCharm')
+
+# See PyCharm help at https://www.jetbrains.com/help/pycharm/
diff --git a/Wikipdedia/practice_beautifulsoap.py b/Wikipdedia/practice_beautifulsoap.py
new file mode 100644
index 00000000000..00beb87fc44
--- /dev/null
+++ b/Wikipdedia/practice_beautifulsoap.py
@@ -0,0 +1,69 @@
+from bs4 import BeautifulSoup
+import requests
+
+language_symbols = {}
+
+
+def lang():
+ try:
+ response = requests.get("https://www.wikipedia.org/")
+ response.raise_for_status()
+ soup = BeautifulSoup(response.content, 'html.parser')
+
+ for option in soup.find_all('option'):
+ language = option.text
+ symbol = option['lang']
+ language_symbols[language] = symbol
+
+ return list(language_symbols.keys())
+
+ except requests.exceptions.RequestException as e:
+ print("Error fetching language data:", e)
+ return []
+
+
+def data(selected_topic, selected_language):
+ symbol = language_symbols.get(selected_language)
+
+ try:
+ url = f"https://{symbol}.wikipedia.org/wiki/%7Bselected_topic%7D"
+ data_response = requests.get(url)
+ data_response.raise_for_status()
+ data_soup = BeautifulSoup(data_response.content, 'html.parser')
+
+ main_content = data_soup.find('div', {'id': 'mw-content-text'})
+ filtered_content = ""
+
+ if main_content:
+ for element in main_content.descendants:
+ if element.name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']:
+ filtered_content += "\n" + element.get_text(strip=True).upper() + "\n"
+
+ elif element.name == 'p':
+ filtered_content += element.get_text(strip=True) + "\n"
+
+ return filtered_content
+
+ except requests.exceptions.RequestException as e:
+ print("Error fetching Wikipedia content:", e)
+ return "Error fetching data."
+
+
+def get_image_urls(query):
+ try:
+ search_url = f"https://www.google.com/search?q={query}&tbm=isch"
+ image_response = requests.get(search_url)
+ image_response.raise_for_status()
+ image_soup = BeautifulSoup(image_response.content, 'html.parser')
+
+ image_urls = []
+ for img in image_soup.find_all('img'):
+ image_url = img.get('src')
+ if image_url and image_url.startswith("http"):
+ image_urls.append(image_url)
+
+ return image_urls[0]
+
+ except requests.exceptions.RequestException as e:
+ print("Error fetching image URLs:", e)
+ return None
diff --git a/Wikipdedia/static/js/output.js b/Wikipdedia/static/js/output.js
new file mode 100644
index 00000000000..5c360de488e
--- /dev/null
+++ b/Wikipdedia/static/js/output.js
@@ -0,0 +1,9 @@
+function validateForm() {
+ var language = document.getElementById("language").value;
+
+ if (language === "Select") {
+ alert("Please select a language.");
+ return false;
+ }
+}
+
diff --git a/Wikipdedia/template/index.html b/Wikipdedia/template/index.html
new file mode 100644
index 00000000000..7a2bdb712ab
--- /dev/null
+++ b/Wikipdedia/template/index.html
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+ Input Web Page
+
+
+
+
+
+
+

+
Wikipedia
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Wikipdedia/template/output.html b/Wikipdedia/template/output.html
new file mode 100644
index 00000000000..ee2d3b0b240
--- /dev/null
+++ b/Wikipdedia/template/output.html
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+ Output Web Page
+
+
+
+
+
+
+

+
{{ heading }}
+
in {{ language }} language
+
+
+
+
+
+
+
+
+
diff --git a/Word_Dictionary/dictionary.py b/Word_Dictionary/dictionary.py
new file mode 100644
index 00000000000..39f15eb47ec
--- /dev/null
+++ b/Word_Dictionary/dictionary.py
@@ -0,0 +1,62 @@
+from typing import Dict, List
+
+
+class Dictionary:
+
+ def __init__(self):
+ self.node = {}
+
+ def add_word(self, word: str) -> None:
+ node = self.node
+ for ltr in word:
+ if ltr not in node:
+ node[ltr] = {}
+ node = node[ltr]
+ node["is_word"] = True
+
+ def word_exists(self, word: str) -> bool:
+ node = self.node
+ for ltr in word:
+ if ltr not in node:
+ return False
+ node = node[ltr]
+ return "is_word" in node
+
+ def list_words_from_node(self, node: Dict, spelling: str) -> None:
+ if "is_word" in node:
+ self.words_list.append(spelling)
+ return
+ for ltr in node:
+ self.list_words_from_node(node[ltr], spelling+ltr)
+
+ def print_all_words_in_dictionary(self) -> List[str]:
+ node = self.node
+ self.words_list = []
+ self.list_words_from_node(node, "")
+ return self.words_list
+
+ def suggest_words_starting_with(self, prefix: str) -> List[str]:
+ node = self.node
+ for ltr in prefix:
+ if ltr not in node:
+ return False
+ node = node[ltr]
+ self.words_list = []
+ self.list_words_from_node(node, prefix)
+ return self.words_list
+
+
+
+
+# Your Dictionary object will be instantiated and called as such:
+obj = Dictionary()
+obj.add_word("word")
+obj.add_word("woke")
+obj.add_word("happy")
+
+param_2 = obj.word_exists("word")
+param_3 = obj.suggest_words_starting_with("wo")
+
+print(param_2)
+print(param_3)
+print(obj.print_all_words_in_dictionary())
\ No newline at end of file
diff --git a/add 2 number.py b/add 2 number.py
deleted file mode 100644
index e10b54423d5..00000000000
--- a/add 2 number.py
+++ /dev/null
@@ -1,3 +0,0 @@
-num1=int(input("Enter the First Number : "))
-num2=int(input("Enter the Second Number : "))
-print("Sum:",num1 + num2)
diff --git a/add 2 numbers.py b/add 2 numbers.py
deleted file mode 100644
index cf300757152..00000000000
--- a/add 2 numbers.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# This program adds two numbers
-# Works with Python 3.6 version and above.
-
-# Set the values.
-num1 = 1.5
-num2 = 6.3
-
-# Display the sum.
-print(f'The sum of {num1} and {num2} is {num1 + num2}.')
diff --git a/add two no.py b/add two no.py
deleted file mode 100644
index d1b6fd9e455..00000000000
--- a/add two no.py
+++ /dev/null
@@ -1,7 +0,0 @@
-num1 = 1.5
-num2 = 6.3
-
-
-sum = num1 + num2
-
-print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
diff --git a/add two number.py b/add two number.py
deleted file mode 100644
index 8fbba127e70..00000000000
--- a/add two number.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# This program adds two numbers
-
-num1 = 1.5
-num2 = 6.3
-
-# Add two numbers
-sum = num1 + num2
-
-# Display the sum
-print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
diff --git a/add_2_nums.py b/add_2_nums.py
deleted file mode 100644
index 0b7bf5b84db..00000000000
--- a/add_2_nums.py
+++ /dev/null
@@ -1,5 +0,0 @@
-# for item in # this python program asks uses for 2 number and returns their sum:
-
-a = int(input("enter first Number: "))
-b = int(input("enter second Number: "))
-print("sum is:", a+b)
diff --git a/add_two_number.py b/add_two_number.py
new file mode 100644
index 00000000000..2824d2c1872
--- /dev/null
+++ b/add_two_number.py
@@ -0,0 +1,17 @@
+user_input = (input("type type 'start' to run program:")).lower()
+
+if user_input == 'start':
+ is_game_running = True
+else:
+ is_game_running = False
+
+
+while (is_game_running):
+ num1 = int(input("enter number 1:"))
+ num2 = int(input("enter number 2:"))
+ num3 = num1+num2
+ print(f"sum of {num1} and {num2} is {num3}")
+ user_input = (input("if you want to discontinue type 'stop':")).lower()
+ if user_input == "stop":
+ is_game_running = False
+
diff --git a/add_two_nums.py b/add_two_nums.py
new file mode 100644
index 00000000000..f68631f2ea1
--- /dev/null
+++ b/add_two_nums.py
@@ -0,0 +1,24 @@
+__author__ = "Nitkarsh Chourasia"
+__version__ = "1.0"
+def addition(
+ num1: typing.Union[int, float],
+ num2: typing.Union[int, float]
+) -> str:
+ """A function to add two given numbers."""
+
+ # Checking if the given parameters are numerical or not.
+ if not isinstance(num1, (int, float)):
+ return "Please input numerical values only for num1."
+ if not isinstance(num2, (int, float)):
+ return "Please input numerical values only for num2."
+
+ # Adding the given parameters.
+ sum_result = num1 + num2
+
+ # returning the result.
+ return f"The sum of {num1} and {num2} is: {sum_result}"
+)
+
+print(addition(5, 10)) # This will use the provided parameters
+print(addition(2, 2))
+print(addition(-3, -5))
diff --git a/addition.py b/addition.py
deleted file mode 100644
index 2a90bae31fb..00000000000
--- a/addition.py
+++ /dev/null
@@ -1,35 +0,0 @@
-print()
-print()
-
-a = True
-
-while a == True:
-
- number1 = int(input("enter first number:"))
- number2 = int(input("enter second number:"))
- number3 = int(input("enter third number:"))
- sum = number1 + number2 + number3
-
- print()
- print("\t\t======================================")
- print()
-
- print("Addition of three numbers is", " :-- ", sum)
-
- print()
- print("\t\t======================================")
- print()
-
- d = input("Do tou want to do it again ?? Y / N -- ").lower()
-
- if d == "y":
-
- print()
- print("\t\t======================================")
- print()
-
- continue
-
- else:
-
- exit()
diff --git a/addtwonumber.py b/addtwonumber.py
deleted file mode 100644
index 1c7f167328e..00000000000
--- a/addtwonumber.py
+++ /dev/null
@@ -1,7 +0,0 @@
-//Python Program to Add Two Numbers
-a = int(input("enter first number: "))
-b = int(input("enter second number: "))
-
-sum = a + b
-
-print("sum:", sum)
diff --git a/advanced_calculator.py b/advanced_calculator.py
new file mode 100644
index 00000000000..82ff80d8970
--- /dev/null
+++ b/advanced_calculator.py
@@ -0,0 +1,391 @@
+# This is like making a package.lock file for npm package.
+# Yes, I should be making it.
+__author__ = "Nitkarsh Chourasia"
+__version__ = "0.0.0" # SemVer # Understand more about it
+__license__ = "MIT" # Understand more about it
+# Want to make it open source but how to do it?
+# Program to make a simple calculator
+# Will have to extensively work on Jarvis and local_document and MongoDb and Redis and JavaScript and CSS and DOM manipulation to understand it.
+# Will have to study maths to understand it more better.
+# How can I market gtts? Like showing used google's api? This is how can I market it?
+# Project description? What will be the project description?
+
+from numbers import Number
+from sys import exit
+import colorama as color
+import inquirer
+from gtts import gTTS
+from pygame import mixer, time
+from io import BytesIO
+from pprint import pprint
+import art
+import date
+
+
+# Find the best of best extensions for the auto generation of the documentation parts.
+# For your favourite languages like JavaScript, Python ,etc,...
+# Should be able to print date and time too.
+# Should use voice assistant for specially abled people.
+# A fully personalised calculator.
+# voice_assistant on/off , setting bool value to true or false
+
+# Is the operations valid?
+
+
+# Validation checker
+class Calculator:
+ def __init__(self):
+ self.take_inputs()
+
+ def add(self):
+ """summary: Get the sum of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1 + self.num2
+
+ def sub(self):
+ """_summary_: Get the difference of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1 - self.num2
+
+ def multi(self):
+ """_summary_: Get the product of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1 * self.num2
+
+ def div(self):
+ """_summary_: Get the quotient of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ # What do we mean by quotient?
+ return self.num1 / self.num2
+
+ def power(self):
+ """_summary_: Get the power of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1**self.num2
+
+ def root(self):
+ """_summary_: Get the root of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1 ** (1 / self.num2)
+
+ def remainer(self):
+ """_summary_: Get the remainder of numbers
+
+ Returns:
+ _type_: _description_
+ """
+
+ # Do I have to use the '.' period or full_stop in the numbers?
+ return self.num1 % self.num2
+
+ def cube_root(self):
+ """_summary_: Get the cube root of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1 ** (1 / 3)
+
+ def cube_exponent(self):
+ """_summary_: Get the cube exponent of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1**3
+
+ def square_root(self):
+ """_summary_: Get the square root of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1 ** (1 / 2)
+
+ def square_exponent(self):
+ """_summary_: Get the square exponent of numbers
+
+ Returns:
+ _type_: _description_
+ """
+ return self.num1**2
+
+ def factorial(self):
+ """_summary_: Get the factorial of numbers"""
+ pass
+
+ def list_factors(self):
+ """_summary_: Get the list of factors of numbers"""
+ pass
+
+ def factorial(self):
+ for i in range(1, self.num + 1):
+ self.factorial = self.factorial * i # is this right?
+
+ def LCM(self):
+ """_summary_: Get the LCM of numbers"""
+ pass
+
+ def HCF(self):
+ """_summary_: Get the HCF of numbers"""
+ pass
+
+ # class time: # Working with days calculator
+ def age_calculator(self):
+ """_summary_: Get the age of the user"""
+ # This is be very accurate and precise it should include proper leap year and last birthday till now every detail.
+ # Should show the preciseness in seconds when called.
+ pass
+
+ def days_calculator(self):
+ """_summary_: Get the days between two dates"""
+ pass
+
+ def leap_year(self):
+ """_summary_: Get the leap year of the user"""
+ pass
+
+ def perimeter(self):
+ """_summary_: Get the perimeter of the user"""
+ pass
+
+ class Trigonometry:
+ """_summary_: Class enriched with all the methods to solve basic trignometric problems"""
+
+ def pythagorean_theorem(self):
+ """_summary_: Get the pythagorean theorem of the user"""
+ pass
+
+ def find_hypotenuse(self):
+ """_summary_: Get the hypotenuse of the user"""
+ pass
+
+ def find_base(self):
+ """_summary_: Get the base of the user"""
+ pass
+
+ def find_perpendicular(self):
+ """_summary_: Get the perpendicular of the user"""
+ pass
+
+ # class Logarithms:
+ # Learn more about Maths in general
+
+ def quadratic_equation(self):
+ """_summary_: Get the quadratic equation of the user"""
+ pass
+
+ def open_system_calculator(self):
+ """_summary_: Open the calculator present on the machine of the user"""
+ # first identify the os
+ # track the calculator
+ # add a debugging feature like error handling
+ # for linux and mac
+ # if no such found then print a message to the user that sorry dear it wasn't possible to so
+ # then open it
+
+ def take_inputs(self):
+ """_summary_: Take the inputs from the user in proper sucession"""
+ while True:
+ while True:
+ try:
+ # self.num1 = float(input("Enter The First Number: "))
+ # self.num2 = float(input("Enter The Second Number: "))
+ pprint("Enter your number")
+ # validation check must be done
+ break
+ except ValueError:
+ pprint("Please Enter A Valid Number")
+ continue
+ # To let the user to know it is time to exit.
+ pprint("Press 'q' to exit")
+ # if self.num1 == "q" or self.num2 == "q":
+ # exit() # Some how I need to exit it
+
+ def greeting(self):
+ """_summary_: Greet the user with using Audio"""
+ text_to_audio = "Welcome To The Calculator"
+ self.gtts_object = gTTS(text=text_to_audio, lang="en", tld="co.in", slow=False)
+ tts = self.gtts_object
+ fp = BytesIO()
+ tts.write_to_fp(fp)
+ fp.seek(0) # Reset the BytesIO object to the beginning
+ mixer.init()
+ mixer.music.load(fp)
+ mixer.music.play()
+ while mixer.music.get_busy():
+ time.Clock().tick(10)
+
+ # Here OOP is not followed.
+ def user_name(self):
+ """_summary_: Get the name of the user and have an option to greet him/her"""
+ self.name = input("Please enter your good name: ")
+ # Making validation checks here
+ text_to_audio = "{self.name}"
+ self.gtts_object = gTTS(text=text_to_audio, lang="en", tld="co.in", slow=False)
+ tts = self.gtts_object
+ fp = BytesIO()
+ tts.write_to_fp(fp)
+ fp.seek(0) # Reset the BytesIO object to the beginning
+ mixer.init()
+ mixer.music.load(fp)
+ mixer.music.play()
+ while mixer.music.get_busy():
+ time.Clock().tick(10)
+
+ def user_name_art(self):
+ """_summary_: Get the name of the user and have an option to show him his user name in art"""
+ # Default is to show = True, else False if user tries to disable it.
+
+ # Tell him to show the time and date
+ # print(art.text2art(self.name))
+ # print(date and time of now)
+ # Remove whitespaces from beginning and end
+ # Remove middle name and last name
+ # Remove special characters
+ # Remove numbers
+ f_name = self.name.split(" ")[0]
+ f_name = f_name.strip()
+ # Remove every number present in it
+ # Will have to practice not logic
+ f_name = "".join([i for i in f_name if not i.isdigit()])
+
+ # perform string operations on it for the art to be displayed.
+ # Remove white spaces
+ # Remove middle name and last name
+ # Remove special characters
+ # Remove numbers
+ # Remove everything
+
+ class unitConversion:
+ """_summary_: Class enriched with all the methods to convert units"""
+
+ # Do we full-stops in generating documentations?
+
+ def __init__(self):
+ """_summary_: Initialise the class with the required attributes"""
+ self.take_inputs()
+
+ def length(self):
+ """_summary_: Convert length units"""
+ # It should have a meter to unit and unit to meter converter
+ # Othe lengths units it should also have.
+ # Like cm to pico meter and what not
+ pass
+
+ def area(self):
+ # This will to have multiple shapes and polygons to it to improve it's area.
+ # This will to have multiple shapes and polygons to it to improve it's area.
+ # I will try to use the best of the formula to do it like the n number of polygons to be solved.
+
+ pass
+
+ def volume(self):
+ # Different shapes and polygons to it to improve it's volume.
+ pass
+
+ def mass(self):
+ pass
+
+ def time(self):
+ pass
+
+ def speed(self):
+ pass
+
+ def temperature(self):
+ pass
+
+ def data(self):
+ pass
+
+ def pressure(self):
+ pass
+
+ def energy(self):
+ pass
+
+ def power(self):
+ pass
+
+ def angle(self):
+ pass
+
+ def force(self):
+ pass
+
+ def frequency(self):
+ pass
+
+ def take_inputs(self):
+ pass
+
+ class CurrencyConverter:
+ def __init__(self):
+ self.take_inputs()
+
+ def take_inputs(self):
+ pass
+
+ def convert(self):
+ pass
+
+ class Commands:
+ def __init__(self):
+ self.take_inputs()
+
+ def previous_number(self):
+ pass
+
+ def previous_operation(self):
+ pass
+
+ def previous_result(self):
+ pass
+
+ def clear_screen(self):
+ # Do I need a clear screen?
+ # os.system("cls" if os.name == "nt" else "clear")
+ # os.system("cls")
+ # os.system("clear")
+ pass
+
+
+if __name__ == "__main__":
+ operation_1 = Calculator(10, 5)
+
+ # Operations
+ # User interaction
+ # Study them properly and try to understand them.
+ # Study them properly and try to understand them in very detailed length. Please.
+ # Add a function to continually ask for input until the user enters a valid input.
+
+
+# Let's explore colorma
+# Also user log ins, and it saves user data and preferences.
+# A feature of the least priority right now.
+
+# List of features priority should be planned.
+
+
+# Documentations are good to read and understand.
+# A one stop solution is to stop and read the document.
+# It is much better and easier to understand.
diff --git a/agecalculator.py b/agecalculator.py
new file mode 100644
index 00000000000..094aa88ca46
--- /dev/null
+++ b/agecalculator.py
@@ -0,0 +1,69 @@
+from _datetime import datetime
+import tkinter as tk
+from tkinter import ttk
+from _datetime import *
+
+win = tk.Tk()
+win.title('Age Calculate')
+win.geometry('310x400')
+# win.iconbitmap('pic.png') this is use extention ico then show pic
+
+############################################ Frame ############################################
+pic = tk.PhotoImage(file=r"E:\Python Practice\Age_calculate\pic.png")
+win.tk.call('wm','iconphoto',win._w,pic)
+
+
+canvas=tk.Canvas(win,width=310,height=190)
+canvas.grid()
+image = tk.PhotoImage(file=r"E:\Python Practice\Age_calculate\pic.png")
+canvas.create_image(0,0,anchor='nw',image=image)
+
+frame = ttk.Frame(win)
+frame.place(x=40,y=220)
+
+
+
+############################################ Label on Frame ############################################
+
+name = ttk.Label(frame,text = 'Name : ',font = ('',12,'bold'))
+name.grid(row=0,column=0,sticky = tk.W)
+
+year = ttk.Label(frame,text = 'Year : ',font = ('',12,'bold'))
+year.grid(row=1,column=0,sticky = tk.W)
+
+month = ttk.Label(frame,text = 'Month : ',font = ('',12,'bold'))
+month.grid(row=2,column=0,sticky = tk.W)
+
+date = ttk.Label(frame,text = 'Date : ',font = ('',12,'bold'))
+date.grid(row=3,column=0,sticky = tk.W)
+
+############################################ Entry Box ############################################
+name_entry = ttk.Entry(frame,width=25)
+name_entry.grid(row=0,column=1)
+name_entry.focus()
+
+year_entry = ttk.Entry(frame,width=25)
+year_entry.grid(row=1,column=1,pady=5)
+
+month_entry = ttk.Entry(frame,width=25)
+month_entry.grid(row=2,column=1)
+
+date_entry = ttk.Entry(frame,width=25)
+date_entry.grid(row=3,column=1,pady=5)
+
+
+def age_cal():
+ name_entry.get()
+ year_entry.get()
+ month_entry.get()
+ date_entry.get()
+ cal = datetime.today()-(int(year_entry))
+ print(cal)
+
+
+btn = ttk.Button(frame,text='Age calculate',command=age_cal)
+btn.grid(row=4,column=1)
+
+
+
+win.mainloop()
diff --git a/area_of_square.py b/area_of_square.py
deleted file mode 100644
index 471e7c1cdb6..00000000000
--- a/area_of_square.py
+++ /dev/null
@@ -1,5 +0,0 @@
-# Returns the area of the square with given sides
-n = input("Enter the side of the square: ") # Side length should be given in input
-side = float(n)
-area = side * side # calculate area
-print("Area of the given square is ", area)
diff --git a/area_of_square_app.py b/area_of_square_app.py
new file mode 100644
index 00000000000..d9e4a303005
--- /dev/null
+++ b/area_of_square_app.py
@@ -0,0 +1,130 @@
+__author__ = "Nitkarsh Chourasia"
+__author_GitHub_profile__ = "https://github.com/NitkarshChourasia"
+__author_email_address__ = "playnitkarsh@gmal.com"
+__created_on__ = "10/10/2021"
+__last_updated__ = "10/10/2021"
+
+from word2number import w2n
+
+
+def convert_words_to_number(word_str):
+ """
+ Convert a string containing number words to an integer.
+
+ Args:
+ - word_str (str): Input string with number words.
+
+ Returns:
+ - int: Numeric equivalent of the input string.
+ """
+ numeric_result = w2n.word_to_num(word_str)
+ return numeric_result
+
+
+# Example usage:
+number_str = "two hundred fifteen"
+result = convert_words_to_number(number_str)
+print(result) # Output: 215
+
+
+class Square:
+ def __init__(self, side=None):
+ if side is None:
+ self.ask_side()
+ # else:
+ # self.side = float(side)
+ else:
+ if not isinstance(side, (int, float)):
+ try:
+ side = float(side)
+ except ValueError:
+ # return "Invalid input for side."
+ raise ValueError("Invalid input for side.")
+ else:
+ self.side = float(side)
+ # Check if the result is a float and remove unnecessary zeros
+
+ self.calculate_square()
+ self.truncate_decimals()
+
+ # If ask side or input directly into the square.
+ # That can be done?
+ def calculate_square(self):
+ self.area = self.side * self.side
+ return self.area
+
+ # Want to add a while loop asking for the input.
+ # Also have an option to ask the user in true mode or in repeat mode.
+ def ask_side(self):
+ # if true bool then while if int or float then for loop.
+ # I will have to learn inheritance and polymorphism.
+ condition = 3
+ # condition = True
+ if condition == True and isinstance(condition, bool):
+ while condition:
+ n = input("Enter the side of the square: ")
+ self.side = float(n)
+ elif isinstance(condition, (int, float)):
+ for i in range(_=condition):
+ n = input("Enter the side of the square: ")
+ self.side = float(n)
+ # n = input("Enter the side of the square: ")
+ # self.side = float(n)
+ # return
+
+ def truncate_decimals(self):
+ return (
+ f"{self.area:.10f}".rstrip("0").rstrip(".")
+ if "." in str(self.area)
+ else self.area
+ )
+
+ # Prettifying the output.
+
+ def calculate_perimeter(self):
+ return 4 * self.side
+
+ def calculate_perimeter_prettify(self):
+ return f"The perimeter of the square is {self.calculate_perimeter()}."
+
+ def calculate_area_prettify(self):
+ return f"The area of the square is {self.area}."
+
+ def truncate_decimals_prettify(self):
+ return f"The area of the square is {self.truncate_decimals()}."
+
+
+if __name__ == "__main__":
+ output_one = Square()
+ truncated_area = output_one.truncate_decimals()
+ # print(output_one.truncate_decimals())
+ print(truncated_area)
+
+
+# add a while loop to keep asking for the user input.
+# also make sure to add a about menu to input a while loop in tkinter app.
+
+# It can use a beautiful GUI also.
+# Even validation is left.
+# What if string is provided in number? Then?
+# What if chars are provided. Then?
+# What if a negative number is provided? Then?
+# What if a number is provided in alphabets characters? Then?
+# Can it a single method have more object in it?
+
+# Also need to perform testing on it.
+# EXTREME FORM OF TESTING NEED TO BE PERFORMED ON IT.
+# Documentation is also needed.
+# Comments are also needed.
+# TYPE hints are also needed.
+
+# README.md file is also needed.
+## Which will explain the whole project.
+### Like how to use the application.
+### List down the features in explicit detail.
+### How to use different methods and classes.
+### It will also a image of the project in working state.
+### It will also have a video to the project in working state.
+
+# It should also have .exe and linux executable file.
+# It should also be installable into Windows(x86) system and if possible into Linux system also.
diff --git a/async_downloader/requirements.txt b/async_downloader/requirements.txt
index 8af244589bf..d7fb9f5f95b 100644
--- a/async_downloader/requirements.txt
+++ b/async_downloader/requirements.txt
@@ -1 +1 @@
-aiohttp==3.8.5
+aiohttp==3.12.12
diff --git a/bank_managment_system/QTFrontend.py b/bank_managment_system/QTFrontend.py
new file mode 100644
index 00000000000..9a1a54106f1
--- /dev/null
+++ b/bank_managment_system/QTFrontend.py
@@ -0,0 +1,1218 @@
+
+from PyQt5 import QtCore, QtGui, QtWidgets
+import sys
+import backend
+backend.connect_database()
+
+employee_data = None
+# Page Constants (for reference)
+HOME_PAGE = 0
+ADMIN_PAGE = 1
+EMPLOYEE_PAGE = 2
+ADMIN_MENU_PAGE = 3
+ADD_EMPLOYEE_PAGE = 4
+UPDATE_EMPLOYEE_PAGE1 = 5
+UPDATE_EMPLOYEE_PAGE2 = 6
+EMPLOYEE_LIST_PAGE = 7
+ADMIN_TOTAL_MONEY = 8
+EMPLOYEE_MENU_PAGE = 9
+EMPLOYEE_CREATE_ACCOUNT_PAGE = 10
+EMPLOYEE_SHOW_DETAILS_PAGE1 = 11
+EMPLOYEE_SHOW_DETAILS_PAGE2 = 12
+EMPLOYEE_ADD_BALANCE_SEARCH = 13
+EMPLOYEE_ADD_BALANCE_PAGE = 14
+EMPLOYEE_WITHDRAW_MONEY_SEARCH = 15
+EMPLOYEE_WITHDRAW_MONEY_PAGE = 16
+
+FONT_SIZE = QtGui.QFont("Segoe UI", 12)
+# -------------------------------------------------------------------------------------------------------------
+# === Reusable UI Component Functions ===
+# -------------------------------------------------------------------------------------------------------------
+
+def create_styled_frame(parent, min_size=None, style=""):
+ """Create a styled QFrame with optional minimum size and custom style."""
+ frame = QtWidgets.QFrame(parent)
+ frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
+ frame.setFrameShadow(QtWidgets.QFrame.Raised)
+ if min_size:
+ frame.setMinimumSize(QtCore.QSize(*min_size))
+ frame.setStyleSheet(style)
+ return frame
+
+def create_styled_label(parent, text, font_size=12, bold=False, style="color: #2c3e50; padding: 10px;"):
+ """Create a styled QLabel with customizable font size and boldness."""
+ label = QtWidgets.QLabel(parent)
+ font = QtGui.QFont("Segoe UI", font_size)
+ if bold:
+ font.setBold(True)
+ font.setWeight(75)
+ label.setFont(font)
+ label.setStyleSheet(style)
+ label.setText(text)
+ return label
+
+def create_styled_button(parent, text, min_size=None):
+ """Create a styled QPushButton with hover and pressed effects."""
+ button = QtWidgets.QPushButton(parent)
+ if min_size:
+ button.setMinimumSize(QtCore.QSize(*min_size))
+ button.setStyleSheet("""
+ QPushButton {
+ background-color: #3498db;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+ """)
+ button.setText(text)
+ return button
+
+def create_input_field(parent, label_text, min_label_size=(120, 0)):
+ """Create a horizontal layout with a label and a QLineEdit."""
+ frame = create_styled_frame(parent, style="padding: 7px;")
+ layout = QtWidgets.QHBoxLayout(frame)
+ layout.setContentsMargins(0, 0, 0, 0)
+ layout.setSpacing(0)
+
+ label = create_styled_label(frame, label_text, font_size=12, bold=True, style="color: #2c3e50;")
+ if min_label_size:
+ label.setMinimumSize(QtCore.QSize(*min_label_size))
+
+ line_edit = QtWidgets.QLineEdit(frame)
+ line_edit.setFont(FONT_SIZE)
+ line_edit.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;")
+
+ layout.addWidget(label)
+ layout.addWidget(line_edit)
+ return frame, line_edit
+
+def create_input_field_V(parent, label_text, min_label_size=(120, 0)):
+ """Create a horizontal layout with a label and a QLineEdit."""
+ frame = create_styled_frame(parent, style="padding: 7px;")
+ layout = QtWidgets.QVBoxLayout(frame)
+ layout.setContentsMargins(0, 0, 0, 0)
+ layout.setSpacing(0)
+
+ label = create_styled_label(frame, label_text, font_size=12, bold=True, style="color: #2c3e50;")
+ if min_label_size:
+ label.setMinimumSize(QtCore.QSize(*min_label_size))
+
+ line_edit = QtWidgets.QLineEdit(frame)
+ line_edit.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;")
+ line_edit.setFont(FONT_SIZE)
+
+ layout.addWidget(label)
+ layout.addWidget(line_edit)
+ return frame, line_edit
+
+def show_popup_message(parent, message: str, page: int = None, show_cancel: bool = False,cancel_page: int = HOME_PAGE):
+ """Reusable popup message box.
+
+ Args:
+ parent: The parent widget.
+ message (str): The message to display.
+ page (int, optional): Page index to switch to after dialog closes.
+ show_cancel (bool): Whether to show the Cancel button.
+ """
+ dialog = QtWidgets.QDialog(parent)
+ dialog.setWindowTitle("Message")
+ dialog.setFixedSize(350, 100)
+ dialog.setStyleSheet("background-color: #f0f0f0;")
+
+ layout = QtWidgets.QVBoxLayout(dialog)
+ layout.setSpacing(10)
+ layout.setContentsMargins(15, 15, 15, 15)
+
+ label = QtWidgets.QLabel(message)
+ label.setStyleSheet("font-size: 12px; color: #2c3e50;")
+ label.setWordWrap(True)
+ layout.addWidget(label)
+
+ # Decide which buttons to show
+ if show_cancel:
+ button_box = QtWidgets.QDialogButtonBox(
+ QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel
+ )
+ else:
+ button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok)
+
+ button_box.setStyleSheet("""
+ QPushButton {
+ background-color: #3498db;
+ color: white;
+ border-radius: 4px;
+ padding: 6px 12px;
+ min-width: 80px;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+ """)
+ layout.addWidget(button_box)
+
+ # Connect buttons
+ def on_accept():
+ if page is not None:
+ parent.setCurrentIndex(page)
+ dialog.accept()
+
+ def on_reject():
+ if page is not None:
+ parent.setCurrentIndex(cancel_page)
+ dialog.reject()
+
+ button_box.accepted.connect(on_accept)
+ button_box.rejected.connect(on_reject)
+
+ dialog.exec_()
+
+def search_result(parent, title,label_text):
+ page, main_layout = create_page_with_header(parent, title)
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+ content_layout.alignment
+
+ form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+ form_layout.setSpacing(3)
+ # Define input fields
+ user = create_input_field(form_frame, label_text, min_label_size=(180, 0))
+ form_layout.addWidget(user[0])
+ user_account_number= user[1]
+ user_account_number.setFont(FONT_SIZE)
+ submit_button = create_styled_button(form_frame, "Submit", min_size=(100, 50))
+ form_layout.addWidget(submit_button)
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+
+ return page,(user_account_number,submit_button)
+# -------------------------------------------------------------------------------------------------------------
+# === Page Creation Functions ==
+# -------------------------------------------------------------------------------------------------------------
+def create_page_with_header(parent, title_text):
+ """Create a page with a styled header and return the page + main layout."""
+ page = QtWidgets.QWidget(parent)
+ main_layout = QtWidgets.QVBoxLayout(page)
+ main_layout.setContentsMargins(20, 20, 20, 20)
+ main_layout.setSpacing(20)
+
+ header_frame = create_styled_frame(page, style="background-color: #ffffff; border-radius: 10px; padding: 10px;")
+ header_layout = QtWidgets.QVBoxLayout(header_frame)
+ title_label = create_styled_label(header_frame, title_text, font_size=30)
+ header_layout.addWidget(title_label, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop)
+
+ main_layout.addWidget(header_frame, 0, QtCore.Qt.AlignTop)
+ return page, main_layout
+def get_employee_name(parent, name_field_text="Enter Employee Name"):
+ page, main_layout = create_page_with_header(parent, "Employee Data Update")
+
+ # Content frame
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+
+ # Form frame
+ form_frame = create_styled_frame(content_frame, min_size=(340, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+
+ # Form fields
+ name_label, name_field = create_input_field(form_frame, name_field_text)
+ search_button = create_styled_button(form_frame, "Search", min_size=(100, 30))
+ form_layout.addWidget(name_label)
+ form_layout.addWidget(search_button)
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+
+ def on_search_button_clicked():
+ global employee_data
+ entered_name = name_field.text().strip()
+ print(f"Entered Name: {entered_name}")
+ if not entered_name:
+ QtWidgets.QMessageBox.warning(parent, "Input Error", "Please enter an employee name.")
+ return
+
+ try:
+ employee_check = backend.check_name_in_staff(entered_name)
+ print(f"Employee Check: {type(employee_check)},{employee_check}")
+ if employee_check:
+ cur = backend.cur
+ cur.execute("SELECT * FROM staff WHERE name = ?", (entered_name,))
+ employee_data = cur.fetchone()
+ print(f"Employee Data: {employee_data}")
+ parent.setCurrentIndex(UPDATE_EMPLOYEE_PAGE2)
+
+ # if employee_data:
+ # QtWidgets.QMessageBox.information(parent, "Employee Found",
+ # f"Employee data:\nID: {fetch[0]}\nName: {fetch[1]}\nDept: {fetch[2]}\nRole: {fetch[3]}")
+
+
+ else:
+ QtWidgets.QMessageBox.information(parent, "Not Found", "Employee not found.")
+ except Exception as e:
+ QtWidgets.QMessageBox.critical(parent, "Error", f"An error occurred: {str(e)}")
+
+ search_button.clicked.connect(on_search_button_clicked)
+
+ return page
+
+
+ #backend.check_name_in_staff()
+
+def create_login_page(parent ,title, name_field_text="Name :", password_field_text="Password :", submit_text="Submit",):
+ """Create a login page with a title, name and password fields, and a submit button."""
+ page, main_layout = create_page_with_header(parent, title)
+
+ # Content frame
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+
+ # Form frame
+ form_frame = create_styled_frame(content_frame, min_size=(340, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+ form_layout.setSpacing(20)
+
+ # Input fields
+ name_frame, name_edit = create_input_field(form_frame, name_field_text)
+ password_frame, password_edit = create_input_field(form_frame, password_field_text)
+
+ # Submit button
+ button_frame = create_styled_frame(form_frame, style="padding: 7px;")
+ button_layout = QtWidgets.QVBoxLayout(button_frame)
+ button_layout.setSpacing(60)
+ submit_button = create_styled_button(button_frame, submit_text, min_size=(150, 0))
+ button_layout.addWidget(submit_button, 0, QtCore.Qt.AlignHCenter)
+
+ form_layout.addWidget(name_frame)
+ form_layout.addWidget(password_frame)
+ form_layout.addWidget(button_frame)
+
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+
+
+
+ return page, name_edit, password_edit, submit_button
+
+def on_login_button_clicked(parent, name_field, password_field):
+ name = name_field.text().strip()
+ password = password_field.text().strip()
+
+ if not name or not password:
+ show_popup_message(parent, "Please enter your name and password.",HOME_PAGE)
+ else:
+ try:
+ # Ideally, here you'd call a backend authentication check
+ success = backend.check_admin(name, password)
+ if success:
+ QtWidgets.QMessageBox.information(parent, "Login Successful", f"Welcome, {name}!")
+ else:
+ QtWidgets.QMessageBox.warning(parent, "Login Failed", "Incorrect name or password.")
+ except Exception as e:
+ QtWidgets.QMessageBox.critical(parent, "Error", f"An error occurred during login: {str(e)}")
+
+def create_home_page(parent, on_admin_clicked, on_employee_clicked, on_exit_clicked):
+ """Create the home page with Admin, Employee, and Exit buttons."""
+ page, main_layout = create_page_with_header(parent, "Admin Menu")
+
+ # Button frame
+ button_frame = create_styled_frame(page)
+ button_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ button_layout = QtWidgets.QVBoxLayout(button_frame)
+
+ # Button container
+ button_container = create_styled_frame(button_frame, min_size=(300, 0), style="background-color: #ffffff; border-radius: 15px; padding: 20px;")
+ button_container_layout = QtWidgets.QVBoxLayout(button_container)
+ button_container_layout.setSpacing(15)
+
+ # Buttons
+ admin_button = create_styled_button(button_container, "Admin")
+ employee_button = create_styled_button(button_container, "Employee")
+ exit_button = create_styled_button(button_container, "Exit")
+ exit_button.setStyleSheet("""
+ QPushButton {
+ background-color: #e74c3c;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #c0392b;
+ }
+ QPushButton:pressed {
+ background-color: #992d22;
+ }
+ """)
+
+ button_container_layout.addWidget(admin_button)
+ button_container_layout.addWidget(employee_button)
+ button_container_layout.addWidget(exit_button)
+
+ button_layout.addWidget(button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(button_frame)
+
+ # Connect button signals
+ admin_button.clicked.connect(on_admin_clicked)
+ employee_button.clicked.connect(on_employee_clicked)
+ exit_button.clicked.connect(on_exit_clicked)
+
+ return page
+
+def create_admin_menu_page(parent):
+ page, main_layout = create_page_with_header(parent, "Admin Menu")
+
+ button_frame = create_styled_frame(page)
+ button_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ button_layout = QtWidgets.QVBoxLayout(button_frame)
+
+ button_container = create_styled_frame(button_frame, min_size=(300, 0), style="background-color: #ffffff; border-radius: 15px; padding: 20px;")
+ button_container_layout = QtWidgets.QVBoxLayout(button_container)
+ button_container_layout.setSpacing(15)
+
+ # Define button labels
+ button_labels = ["Add Employee", "Update Employee", "Employee List", "Total Money", "Back"]
+ buttons = []
+
+ for label in button_labels:
+ btn = create_styled_button(button_container, label)
+ button_container_layout.addWidget(btn)
+ buttons.append(btn)
+
+ button_layout.addWidget(button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(button_frame)
+
+ return page, *buttons # Unpack as add_button, update_employee, etc.
+
+def create_add_employee_page(parent, title, submit_text="Submit",update_btn:bool=False):
+ page, main_layout = create_page_with_header(parent, title)
+
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+
+ form_frame = create_styled_frame(content_frame, min_size=(340, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+ form_layout.setSpacing(10)
+
+ # Define input fields
+ fields = ["Name :", "Password :", "Salary :", "Position :"]
+ name_edit = None
+ password_edit = None
+ salary_edit = None
+ position_edit = None
+ edits = []
+
+ for i, field in enumerate(fields):
+ field_frame, field_edit = create_input_field(form_frame, field)
+ form_layout.addWidget(field_frame)
+ if i == 0:
+ name_edit = field_edit
+ elif i == 1:
+ password_edit = field_edit
+ elif i == 2:
+ salary_edit = field_edit
+ elif i == 3:
+ position_edit = field_edit
+ edits.append(field_edit)
+ # Submit button
+ button_frame = create_styled_frame(form_frame, style="padding: 7px;")
+ button_layout = QtWidgets.QVBoxLayout(button_frame)
+ if update_btn:
+ update_button = create_styled_button(button_frame, "Update", min_size=(100, 50))
+ button_layout.addWidget(update_button, 0, QtCore.Qt.AlignHCenter)
+ else:
+ submit_button = create_styled_button(button_frame, submit_text, min_size=(100, 50))
+ button_layout.addWidget(submit_button, 0, QtCore.Qt.AlignHCenter)
+
+
+ form_layout.addWidget(button_frame)
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+ back_btn = QtWidgets.QPushButton("Back", content_frame)
+ back_btn.setStyleSheet("""
+ QPushButton {
+ background-color: #6c757d;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ padding: 8px 16px;
+ font-size: 14px;
+ }
+ QPushButton:hover {
+ background-color: #5a6268;
+ }
+ """)
+ back_btn.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE))
+ main_layout.addWidget(back_btn, 0,alignment=QtCore.Qt.AlignLeft)
+ if update_btn:
+ return page, name_edit, password_edit, salary_edit, position_edit, update_button
+ else:
+ return page, name_edit, password_edit, salary_edit, position_edit, submit_button # Unpack as name_edit, password_edit, etc.
+
+def show_employee_list_page(parent, title):
+ page, main_layout = create_page_with_header(parent, title)
+
+ content_frame = create_styled_frame(page, style="background-color: #f9f9f9; border-radius: 10px; padding: 15px;")
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+
+ # Table frame
+ table_frame = create_styled_frame(content_frame, style="background-color: #ffffff; border-radius: 8px; padding: 10px;")
+ table_layout = QtWidgets.QVBoxLayout(table_frame)
+ table_layout.setSpacing(0)
+
+ # Header row
+ header_frame = create_styled_frame(table_frame, style="background-color: #f5f5f5; ; border-radius: 8px 8px 0 0; padding: 10px;")
+ header_layout = QtWidgets.QHBoxLayout(header_frame)
+ header_layout.setContentsMargins(10, 5, 10, 5)
+ headers = ["Name", "Position", "Salary"]
+ for i, header in enumerate(headers):
+ header_label = QtWidgets.QLabel(header, header_frame)
+ header_label.setStyleSheet("font-weight: bold; font-size: 14px; color: #333333; padding: 0px; margin: 0px;")
+ if i == 2: # Right-align salary header
+ header_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
+ else:
+ header_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
+ header_layout.addWidget(header_label, 1 if i < 2 else 0) # Stretch name and position, not salary
+ table_layout.addWidget(header_frame)
+
+ # Employee rows
+ employees = backend.show_employees_for_update()
+ for row, employee in enumerate(employees):
+ row_frame = create_styled_frame(table_frame, style=f"background-color: {'#fafafa' if row % 2 else '#ffffff'}; padding: 8px;")
+ row_layout = QtWidgets.QHBoxLayout(row_frame)
+ row_layout.setContentsMargins(10, 5, 10, 5)
+
+ # Name
+ name_label = QtWidgets.QLabel(employee[0], row_frame)
+ name_label.setStyleSheet("font-size: 14px; color: #333333; padding: 0px; margin: 0px;")
+ name_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
+ row_layout.addWidget(name_label, 1)
+
+ # Position
+ position_label = QtWidgets.QLabel(employee[3], row_frame)
+ position_label.setStyleSheet("font-size: 14px; color: #333333; padding: 0px; margin: 0px;")
+ position_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
+ row_layout.addWidget(position_label, 1)
+
+ # Salary (formatted as currency)
+ salary_label = QtWidgets.QLabel(f"${float(employee[2]):,.2f}", row_frame)
+ salary_label.setStyleSheet("font-size: 14px; color: #333333; padding: 0px; margin: 0px;")
+ salary_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
+ row_layout.addWidget(salary_label, 0)
+
+ table_layout.addWidget(row_frame)
+
+ # Add stretch to prevent rows from expanding vertically
+ table_layout.addStretch()
+
+ # Back button
+ back_button = QtWidgets.QPushButton("Back", content_frame)
+ back_button.setStyleSheet("""
+ QPushButton {
+ background-color: #6c757d;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ padding: 8px 16px;
+ font-size: 14px;
+ }
+ QPushButton:hover {
+ background-color: #5a6268;
+ }
+ """)
+ back_button.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE))
+
+ content_layout.addWidget(table_frame)
+ main_layout.addWidget(back_button, alignment=QtCore.Qt.AlignLeft)
+ main_layout.addWidget(content_frame)
+
+ return page
+def show_total_money(parent, title):
+ page, main_layout = create_page_with_header(parent, title)
+
+ content_frame = create_styled_frame(page, style="background-color: #f9f9f9; border-radius: 10px; padding: 15px;")
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+ content_layout.setProperty("spacing", 10)
+ all = backend.all_money()
+
+ # Total money label
+ total_money_label = QtWidgets.QLabel(f"Total Money: ${all}", content_frame)
+ total_money_label.setStyleSheet("font-size: 24px; font-weight: bold; color: #333333;")
+ content_layout.addWidget(total_money_label, alignment=QtCore.Qt.AlignCenter)
+ # Back button
+ back_button = QtWidgets.QPushButton("Back", content_frame)
+ back_button.setStyleSheet("""
+ QPushButton {
+ background-color: #6c757d;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ padding: 8px 16px;
+ font-size: 14px;
+ }
+ QPushButton:hover {
+ background-color: #5a6268;
+ }
+ """)
+ back_button.clicked.connect(lambda: parent.setCurrentIndex(ADMIN_MENU_PAGE))
+ content_layout.addWidget(back_button, alignment=QtCore.Qt.AlignCenter)
+ main_layout.addWidget(content_frame)
+ return page
+
+#-----------employees menu pages-----------
+def create_employee_menu_page(parent, title):
+ page, main_layout = create_page_with_header(parent, title)
+
+ button_frame = create_styled_frame(page)
+ button_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ button_layout = QtWidgets.QVBoxLayout(button_frame)
+
+ button_container = create_styled_frame(button_frame, min_size=(300, 0), style="background-color: #ffffff; border-radius: 15px; padding: 20px;")
+ button_container_layout = QtWidgets.QVBoxLayout(button_container)
+ button_container_layout.setSpacing(15)
+
+ # Define button labels
+ button_labels = ["Create Account ", "Show Details", "Add Balance", "Withdraw Money", "Chack Balanace", "Update Account", "list of all Members", "Delete Account", "Back"]
+ buttons = []
+
+ for label in button_labels:
+ btn:QtWidgets.QPushButton = create_styled_button(button_container, label)
+ button_container_layout.addWidget(btn)
+ buttons.append(btn)
+
+ button_layout.addWidget(button_container, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(button_frame)
+
+ return page, *buttons # Unpack as add_button, update_employee, etc.
+
+def create_account_page(parent, title):
+ page, main_layout = create_page_with_header(parent, title)
+
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+
+ form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+ form_layout.setSpacing(3)
+
+ # Define input fields
+ fields = ["Name :", "Age :", "Address","Balance :", "Mobile number :"]
+ edits = []
+
+ for i, field in enumerate(fields):
+ field_frame, field_edit = create_input_field(form_frame, field,min_label_size=(160, 0))
+ form_layout.addWidget(field_frame)
+ field_edit.setFont(QtGui.QFont("Arial", 12))
+ if i == 0:
+ name_edit = field_edit
+ elif i == 1:
+ Age_edit = field_edit
+ elif i == 2:
+ Address_edit = field_edit
+ elif i == 3:
+ Balance_edit = field_edit
+ elif i == 4:
+ Mobile_number_edit = field_edit
+ edits.append(field_edit)
+ # Dropdown for account type
+ account_type_label = QtWidgets.QLabel("Account Type :", form_frame)
+ account_type_label.setStyleSheet("font-size: 14px; font-weight: bold; color: #333333;")
+ form_layout.addWidget(account_type_label)
+ account_type_dropdown = QtWidgets.QComboBox(form_frame)
+ account_type_dropdown.addItems(["Savings", "Current", "Fixed Deposit"])
+ account_type_dropdown.setStyleSheet("""
+ QComboBox {
+ padding: 5px;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+ background-color: white;
+ min-width: 200px;
+ font-size: 14px;
+ }
+ QComboBox:hover {
+ border: 1px solid #999;
+ }
+ QComboBox::drop-down {
+ border: none;
+ width: 25px;
+ }
+ QComboBox::down-arrow {
+ width: 12px;
+ height: 12px;
+ }
+ QComboBox QAbstractItemView {
+ border: 1px solid #ccc;
+ background-color: white;
+ selection-background-color: #0078d4;
+ selection-color: white;
+ }
+ """)
+ form_layout.addWidget(account_type_dropdown)
+
+ # Submit button
+ button_frame = create_styled_frame(form_frame, style="padding: 7px;")
+ button_layout = QtWidgets.QVBoxLayout(button_frame)
+
+
+ submit_button = create_styled_button(button_frame, "Submit", min_size=(100, 50))
+ button_layout.addWidget(submit_button, 0, QtCore.Qt.AlignHCenter)
+
+
+ form_layout.addWidget(button_frame)
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+ back_btn = QtWidgets.QPushButton("Back", content_frame)
+ back_btn.setStyleSheet("""
+ QPushButton {
+ background-color: #6c757d;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ padding: 8px 16px;
+ font-size: 14px;
+ }
+ QPushButton:hover {
+ background-color: #5a6268;
+ }
+ """)
+ back_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE))
+ main_layout.addWidget(back_btn, 0,alignment=QtCore.Qt.AlignLeft)
+
+ return page,( name_edit, Age_edit,Address_edit,Balance_edit,Mobile_number_edit, account_type_dropdown ,submit_button)
+
+def create_show_details_page1(parent, title):
+ page, main_layout = create_page_with_header(parent, title)
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+
+ form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+ form_layout.setSpacing(3)
+ # Define input fields
+ bannk_user = create_input_field(form_frame, "Enter Bank account Number :", min_label_size=(180, 0))
+ form_layout.addWidget(bannk_user[0])
+ user_account_number= bannk_user[1]
+ submit_button = create_styled_button(form_frame, "Submit", min_size=(100, 50))
+ form_layout.addWidget(submit_button)
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+
+ return page,(user_account_number,submit_button)
+
+def create_show_details_page2(parent, title):
+ page, main_layout = create_page_with_header(parent, title)
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+
+ form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+ form_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ form_layout.setSpacing(3)
+
+ # Define input fields
+
+ labeles = ["Account No: ","Name: ", "Age:", "Address: ", "Balance: ", "Mobile Number: ", "Account Type: "]
+ for i in range(len(labeles)):
+ label_frame, input_field = create_input_field(form_frame, labeles[i], min_label_size=(180, 30))
+ form_layout.addWidget(label_frame)
+ input_field.setReadOnly(True)
+ input_field.setFont(QtGui.QFont("Arial", 12))
+ if i == 0:
+ account_no_field = input_field
+ elif i == 1:
+ name_field = input_field
+ elif i == 2:
+ age_field = input_field
+ elif i == 3:
+ address_field = input_field
+ elif i == 4:
+ balance_field = input_field
+ elif i == 5:
+ mobile_number_field = input_field
+ elif i == 6:
+ account_type_field = input_field
+
+ exite_btn = create_styled_button(form_frame, "Exit", min_size=(100, 50))
+ exite_btn.setStyleSheet("""
+ QPushButton {
+ background-color: #6c757d;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ padding: 8px 16px;
+ font-size: 14px;
+ }
+ QPushButton:hover {
+ background-color: #5a6268;
+ }
+ """)
+ exite_btn.clicked.connect(lambda: parent.setCurrentIndex(EMPLOYEE_MENU_PAGE))
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+ main_layout.addWidget(exite_btn)
+
+ return page,(account_no_field,name_field,age_field,address_field,balance_field,mobile_number_field,account_type_field,exite_btn)
+
+def update_user(parent, title,input_fields_label):
+ page, main_layout = create_page_with_header(parent, title)
+ content_frame = create_styled_frame(page)
+ content_frame.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ content_layout = QtWidgets.QVBoxLayout(content_frame)
+ content_layout.alignment
+
+ form_frame = create_styled_frame(content_frame, min_size=(400, 200), style="background-color: #ffffff; border-radius: 15px; padding: 10px;")
+ form_layout = QtWidgets.QVBoxLayout(form_frame)
+ form_layout.setSpacing(3)
+ # Define input fields
+ user = create_input_field(form_frame, "User Name: ", min_label_size=(180, 0))
+ user_balance = create_input_field(form_frame, "Balance: ", min_label_size=(180, 0))
+ user_update_balance = create_input_field_V(form_frame, input_fields_label, min_label_size=(180, 0))
+
+ # Add input fields to the form layout
+ form_layout.addWidget(user[0])
+ form_layout.addWidget(user_balance[0])
+ form_layout.addWidget(user_update_balance[0])
+
+ # Store the input fields in variables
+ user_account_name= user[1]
+ user_account_name.setReadOnly(True)
+ user_account_name.setStyleSheet("background-color: #8a8a8a; border: 1px solid #ccc; border-radius: 4px; padding: 8px;")
+ user_balance_field = user_balance[1]
+ user_balance_field.setReadOnly(True)
+ user_balance_field.setStyleSheet("background-color: #8a8a8a; border: 1px solid #ccc; border-radius: 4px; padding: 8px;")
+ user_update_balance_field = user_update_balance[1]
+ user_update_balance_field.setStyleSheet("background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 4px; padding: 8px;")
+
+
+ # Set the font size for the input fields
+ user_account_name.setFont(FONT_SIZE)
+ user_balance_field.setFont(FONT_SIZE)
+ user_update_balance_field.setFont(FONT_SIZE)
+
+ # Add a submit button
+ submit_button = create_styled_button(form_frame, "Submit", min_size=(100, 50))
+ form_layout.addWidget(submit_button)
+ content_layout.addWidget(form_frame, 0, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
+ main_layout.addWidget(content_frame)
+
+ return page,(user_account_name,user_balance_field,user_update_balance_field,submit_button)
+
+# -------------------------------------------------------------------------------------------------------------
+# === Main Window Setup ===
+# -------------------------------------------------------------------------------------------------------------
+
+def setup_main_window(main_window: QtWidgets.QMainWindow):
+ """Set up the main window with a stacked widget containing home, admin, and employee pages."""
+ main_window.setObjectName("MainWindow")
+ main_window.resize(800, 600)
+ main_window.setStyleSheet("background-color: #f0f2f5;")
+
+ central_widget = QtWidgets.QWidget(main_window)
+ main_layout = QtWidgets.QHBoxLayout(central_widget)
+
+ stacked_widget = QtWidgets.QStackedWidget(central_widget)
+
+ # Create pages
+ def switch_to_admin():
+ stacked_widget.setCurrentIndex(ADMIN_PAGE)
+
+ def switch_to_employee():
+ stacked_widget.setCurrentIndex(EMPLOYEE_PAGE)
+
+ def exit_app():
+ QtWidgets.QApplication.quit()
+
+ def admin_login_menu_page(name, password):
+ try:
+ # Ideally, here you'd call a backend authentication check
+ success = backend.check_admin(name, password)
+ if success:
+ QtWidgets.QMessageBox.information(stacked_widget, "Login Successful", f"Welcome, {name}!")
+ stacked_widget.setCurrentIndex(ADMIN_MENU_PAGE)
+ else:
+ QtWidgets.QMessageBox.warning(stacked_widget, "Login Failed", "Incorrect name or password.")
+ except Exception as e:
+ QtWidgets.QMessageBox.critical(stacked_widget, "Error", f"An error occurred during login: {str(e)}")
+ # show_popup_message(stacked_widget,"Invalid admin credentials",0)
+
+ def add_employee_form_submit(name, password, salary, position):
+ if (
+ len(name) != 0
+ and len(password) != 0
+ and len(salary) != 0
+ and len(position) != 0
+ ):
+ backend.create_employee(name, password, salary, position)
+ show_popup_message(stacked_widget,"Employee added successfully",ADMIN_MENU_PAGE)
+
+ else:
+ print("Please fill in all fields")
+ show_popup_message(stacked_widget,"Please fill in all fields",ADD_EMPLOYEE_PAGE)
+ def update_employee_data(name, password, salary, position, name_to_update):
+ try:
+ cur = backend.cur
+ if name_to_update:
+ cur.execute("UPDATE staff SET Name = ? WHERE name = ?", (name, name_to_update))
+
+ cur.execute("UPDATE staff SET Name = ? WHERE name = ?", (password, name))
+ cur.execute("UPDATE staff SET password = ? WHERE name = ?", (password, name))
+ cur.execute("UPDATE staff SET salary = ? WHERE name = ?", (salary, name))
+ cur.execute("UPDATE staff SET position = ? WHERE name = ?", (position, name))
+ backend.conn.commit()
+ show_popup_message(stacked_widget,"Employee Upadate successfully",UPDATE_EMPLOYEE_PAGE2)
+
+ except:
+ show_popup_message(stacked_widget,"Please fill in all fields",UPDATE_EMPLOYEE_PAGE2)
+
+
+
+ # Create Home Page
+ home_page = create_home_page(
+ stacked_widget,
+ switch_to_admin,
+ switch_to_employee,
+ exit_app
+ )
+ # ------------------------------------------------------------------------------------------------
+ # -------------------------------------Admin panel page ---------------------------------------
+ # ------------------------------------------------------------------------------------------------
+ # Create Admin Login Page
+ admin_page, admin_name, admin_password, admin_submit = create_login_page(
+ stacked_widget,
+ title="Admin Login"
+ )
+ admin_password.setEchoMode(QtWidgets.QLineEdit.Password)
+ admin_name.setFont(QtGui.QFont("Arial", 10))
+ admin_password.setFont(QtGui.QFont("Arial", 10))
+ admin_name.setPlaceholderText("Enter your name")
+ admin_password.setPlaceholderText("Enter your password")
+
+ admin_submit.clicked.connect(
+ lambda: admin_login_menu_page(
+ admin_name.text(),
+ admin_password.text()
+ )
+ )
+
+ # Create Admin Menu Page
+ admin_menu_page, add_button, update_button, list_button, money_button, back_button = create_admin_menu_page(
+ stacked_widget
+ )
+
+ add_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(ADD_EMPLOYEE_PAGE))
+ update_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(UPDATE_EMPLOYEE_PAGE1))
+ list_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_LIST_PAGE))
+ back_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(HOME_PAGE))
+ money_button.clicked.connect(lambda: stacked_widget.setCurrentIndex(ADMIN_TOTAL_MONEY))
+ # Create Add Employee Page
+ add_employee_page, emp_name, emp_password, emp_salary, emp_position, emp_submit = create_add_employee_page(
+ stacked_widget,
+ title="Add Employee"
+ )
+
+ # Update Employee Page
+ u_employee_page1 = get_employee_name(stacked_widget)
+ # apply the update_employee_data function to the submit button
+
+ u_employee_page2 ,u_employee_name, u_employee_password, u_employee_salary, u_employee_position,u_employee_update = create_add_employee_page(stacked_widget,"Update Employee Details",update_btn=True)
+ def populate_employee_data():
+ global employee_data
+ if employee_data:
+ print("employee_data is not None")
+ u_employee_name.setText(str(employee_data[0])) # Name
+ u_employee_password.setText(str(employee_data[1])) # Password
+ u_employee_salary.setText(str(employee_data[2])) # Salary
+ u_employee_position.setText(str(employee_data[3])) # Position
+ else:
+ # Clear fields if no employee data is available
+ print("employee_data is None")
+ u_employee_name.clear()
+ u_employee_password.clear()
+ u_employee_salary.clear()
+ u_employee_position.clear()
+ QtWidgets.QMessageBox.warning(stacked_widget, "No Data", "No employee data available to display.")
+ def on_page_changed(index):
+ if index == 6: # update_employee_page2 is at index 6
+ populate_employee_data()
+
+ # Connect the currentChanged signal to the on_page_changed function
+ stacked_widget.currentChanged.connect(on_page_changed)
+ def update_employee_data(name, password, salary, position, name_to_update):
+ try:
+ if not name_to_update:
+ show_popup_message(stacked_widget, "Original employee name is missing.", UPDATE_EMPLOYEE_PAGE2)
+ return
+ if not (name or password or salary or position):
+ show_popup_message(stacked_widget, "Please fill at least one field to update.", UPDATE_EMPLOYEE_PAGE2)
+ return
+ if name:
+ backend.update_employee_name(name, name_to_update)
+ if password:
+ backend.update_employee_password(password, name_to_update)
+ if salary:
+ try:
+ salary = int(salary)
+ backend.update_employee_salary(salary, name_to_update)
+ except ValueError:
+ show_popup_message(stacked_widget, "Salary must be a valid number.", 5)
+ return
+ if position:
+ backend.update_employee_position(position, name_to_update)
+ show_popup_message(stacked_widget, "Employee updated successfully.", ADMIN_MENU_PAGE)
+ except Exception as e:
+ show_popup_message(stacked_widget, f"Error updating employee: {str(e)}",UPDATE_EMPLOYEE_PAGE2,show_cancel=True,cancel_page=ADMIN_MENU_PAGE)
+ u_employee_update.clicked.connect(
+ lambda: update_employee_data(
+ u_employee_name.text().strip(),
+ u_employee_password.text().strip(),
+ u_employee_salary.text().strip(),
+ u_employee_position.text().strip(),
+ employee_data[0] if employee_data else ""
+ )
+ )
+
+
+ emp_submit.clicked.connect(
+ lambda: add_employee_form_submit(
+ emp_name.text(),
+ emp_password.text(),
+ emp_salary.text(),
+ emp_position.text()
+ )
+ )
+ # show employee list page
+ employee_list_page = show_employee_list_page(stacked_widget,"Employee List")
+ admin_total_money = show_total_money(stacked_widget,"Total Money")
+ # ------------------------------------------------------------------------------------------------
+ # -------------------------------------Employee panel page ---------------------------------------
+ # ------------------------------------------------------------------------------------------------
+
+ # Create Employee Login Page
+ employee_page, employee_name, employee_password, employee_submit = create_login_page(
+ stacked_widget,
+ title="Employee Login"
+ )
+ employee_submit.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_MENU_PAGE))
+ employee_menu_page, E_Create_Account, E_Show_Details, E_add_Balance, E_Withdraw_Money, E_Chack_Balanace, E_Update_Account, E_list_of_all_Members, E_Delete_Account, E_Back= create_employee_menu_page(stacked_widget,"Employee Menu")
+ # List of all page
+ E_Create_Account.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_CREATE_ACCOUNT_PAGE))
+ E_Show_Details.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_SHOW_DETAILS_PAGE1))
+ E_add_Balance.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_ADD_BALANCE_SEARCH))
+ E_Withdraw_Money.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_WITHDRAW_MONEY_SEARCH))
+ # E_Chack_Balanace.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_CHECK_BALANCE_PAGE))
+ # E_Update_Account.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_UPDATE_ACCOUNT_PAGE))
+ # E_list_of_all_Members.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_LIST_OF_ALL_MEMBERS_PAGE))
+ # E_Delete_Account.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_DELETE_ACCOUNT_PAGE))
+ # E_Back.clicked.connect(lambda: stacked_widget.setCurrentIndex(EMPLOYEE_MENU_PAGE))
+
+ employee_create_account_page,all_employee_menu_btn = create_account_page(stacked_widget, "Create Account")
+ all_employee_menu_btn[6].clicked.connect(lambda: add_account_form_submit(
+ all_employee_menu_btn[0].text().strip(),
+ all_employee_menu_btn[1].text().strip(),
+ all_employee_menu_btn[2].text().strip(),
+ all_employee_menu_btn[3].text().strip(),
+ all_employee_menu_btn[5].currentText(),
+ all_employee_menu_btn[4].text().strip()
+ ))
+
+ def add_account_form_submit(name, age, address, balance, account_type, mobile):
+ if (
+ len(name) != 0
+ and len(age) != 0
+ and len(address) != 0
+ and len(balance) != 0
+ and len(account_type) != 0
+ and len(mobile) != 0
+ ):
+ try:
+ balance = int(balance)
+ except ValueError:
+ show_popup_message(stacked_widget, "Balance must be a valid number", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if balance < 0:
+ show_popup_message(stacked_widget, "Balance cannot be negative",EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if account_type not in ["Savings", "Current","Fixed Deposit"]:
+ show_popup_message(stacked_widget, "Invalid account type", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if len(mobile) != 10:
+ show_popup_message(stacked_widget, "Mobile number must be 10 digits", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if not mobile.isdigit():
+ show_popup_message(stacked_widget, "Mobile number must contain only digits", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if not name.isalpha():
+ show_popup_message(stacked_widget, "Name must contain only alphabets", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if not age.isdigit():
+ show_popup_message(stacked_widget, "Age must contain only digits", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if int(age) < 18:
+ show_popup_message(stacked_widget, "Age must be greater than 18", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ if len(address) < 10:
+ show_popup_message(stacked_widget, "Address must be at least 10 characters long", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ return
+ backend.create_customer(name, age, address, balance, account_type, mobile)
+ all_employee_menu_btn[0].setText("")
+ all_employee_menu_btn[1].setText("")
+ all_employee_menu_btn[2].setText("")
+ all_employee_menu_btn[3].setText("")
+ all_employee_menu_btn[4].setText("")
+ all_employee_menu_btn[5].currentText(),
+ show_popup_message(stacked_widget, "Account created successfully", EMPLOYEE_MENU_PAGE, False)
+ else:
+ show_popup_message(stacked_widget, "Please fill in all fields", EMPLOYEE_CREATE_ACCOUNT_PAGE)
+ # Add pages to stacked widget
+
+ show_bank_user_data_page1,show_bank_user_other1 = create_show_details_page1(stacked_widget, "Show Details")
+ show_bank_user_data_page2,show_bank_user_other2 = create_show_details_page2(stacked_widget, "Show Details")
+
+ show_bank_user_other1[1].clicked.connect(lambda: show_bank_user_data_page1_submit_btn(int(show_bank_user_other1[0].text().strip())))
+ def show_bank_user_data_page1_submit_btn(name:int):
+ account_data = backend.get_details(name)
+ if account_data:
+ show_bank_user_other1[0].setText("")
+ show_bank_user_other2[0].setText(str(account_data[0]))
+ show_bank_user_other2[1].setText(str(account_data[1]))
+ show_bank_user_other2[2].setText(str(account_data[2]))
+ show_bank_user_other2[3].setText(str(account_data[3]))
+ show_bank_user_other2[4].setText(str(account_data[4]))
+ show_bank_user_other2[5].setText(str(account_data[5]))
+ show_bank_user_other2[6].setText(str(account_data[6]))
+ stacked_widget.setCurrentIndex(EMPLOYEE_SHOW_DETAILS_PAGE2)
+ else:
+ show_popup_message(stacked_widget, "Account not found", EMPLOYEE_SHOW_DETAILS_PAGE1)
+
+ # Add balance page
+ add_balance_search_page,add_balance_search_other = search_result(stacked_widget, "Add Balance","Enter Account Number: ")
+ add_balance_search_other[1].clicked.connect(lambda: add_balance_page_submit_btn(int(add_balance_search_other[0].text().strip())))
+
+
+ add_balance_page,add_balance_other =update_user(stacked_widget, "Add Balance User Account","Enter Ammount: ")
+ add_balance_other[3].clicked.connect(lambda:update_user_account_balance(add_balance_other[2].text().strip()))
+
+
+ def add_balance_page_submit_btn(account_number:int):
+ check = backend.check_acc_no(account_number)
+ if check:
+ account_data = backend.get_details(account_number)
+ add_balance_other[0].setText(str(account_data[1]))
+ add_balance_other[1].setText(str(account_data[4]))
+ stacked_widget.setCurrentIndex(14)
+ return account_data
+ else:
+ show_popup_message(stacked_widget, "Account not found", EMPLOYEE_ADD_BALANCE_SEARCH,show_cancel=True,cancel_page=EMPLOYEE_MENU_PAGE)
+
+ def update_user_account_balance(add_money:int):
+ account_number=int(add_balance_search_other[0].text().strip())
+ backend.update_balance(add_money,account_number)
+ add_balance_other[0].setText("")
+ add_balance_other[1].setText("")
+ show_popup_message(stacked_widget, "Balance updated successfully", EMPLOYEE_MENU_PAGE)
+ add_balance_search_other[0].setText("")
+
+ # Withdraw money page
+ withdraw_money_search_page,withdraw_money_search_other = search_result(stacked_widget, "Withdraw Money","Enter Account Number: ")
+ withdraw_money_search_other[1].clicked.connect(lambda: withdraw_money_page_submit_btn(int(withdraw_money_search_other[0].text().strip())))
+
+
+ withdraw_money_page,withdraw_money_other =update_user(stacked_widget, "Withdraw Money From User Account","Withdraw Amount: ")
+ withdraw_money_other[3].clicked.connect(lambda:update_user_account_withdraw(withdraw_money_other[2].text().strip()))
+
+ def withdraw_money_page_submit_btn(account_number:int):
+ print(account_number)
+ check = backend.check_acc_no(account_number)
+ print(check)
+ if check:
+ account_data = backend.get_details(account_number)
+ withdraw_money_other[0].setText(str(account_data[1]))
+ withdraw_money_other[1].setText(str(account_data[4]))
+ stacked_widget.setCurrentIndex(16)
+ return account_data
+ else:
+ show_popup_message(stacked_widget, "Account not found", EMPLOYEE_WITHDRAW_MONEY_SEARCH,show_cancel=True,cancel_page=EMPLOYEE_MENU_PAGE)
+
+ def update_user_account_withdraw(withdraw_money:int):
+ account_number=int(withdraw_money_search_other[0].text().strip())
+ backend.deduct_balance(int(withdraw_money),int(account_number))
+ withdraw_money_other[0].setText("")
+ withdraw_money_other[1].setText("")
+ show_popup_message(stacked_widget, "Balance updated successfully", EMPLOYEE_MENU_PAGE)
+ withdraw_money_search_other[0].setText("")
+
+ stacked_widget.addWidget(home_page)#0
+ stacked_widget.addWidget(admin_page)#1
+ stacked_widget.addWidget(employee_page)#2
+ stacked_widget.addWidget(admin_menu_page)#3
+ stacked_widget.addWidget(add_employee_page)#4
+ stacked_widget.addWidget(u_employee_page1)#5
+ stacked_widget.addWidget(u_employee_page2)#6
+ stacked_widget.addWidget(employee_list_page)#7
+ stacked_widget.addWidget(admin_total_money)#8
+ stacked_widget.addWidget(employee_menu_page)#9
+ stacked_widget.addWidget(employee_create_account_page)#10
+ stacked_widget.addWidget(show_bank_user_data_page1)#11
+ stacked_widget.addWidget(show_bank_user_data_page2)#12
+ stacked_widget.addWidget(add_balance_search_page)#13
+ stacked_widget.addWidget(add_balance_page)#14
+ stacked_widget.addWidget(withdraw_money_search_page)#15
+ stacked_widget.addWidget(withdraw_money_page)#16
+
+
+
+ main_layout.addWidget(stacked_widget)
+ main_window.setCentralWidget(central_widget)
+
+ # Set initial page
+ stacked_widget.setCurrentIndex(9)
+
+ return stacked_widget, {
+ "admin_name": admin_name,
+ "admin_password": admin_password,
+ "admin_submit": admin_submit,
+ "employee_name": employee_name,
+ "employee_password": employee_password,
+ "employee_submit": employee_submit
+ }
+
+def main():
+ """Main function to launch the application."""
+ app = QtWidgets.QApplication(sys.argv)
+ main_window = QtWidgets.QMainWindow()
+ stacked_widget, widgets = setup_main_window(main_window)
+
+ # Example: Connect submit buttons to print input values
+
+
+ main_window.show()
+ sys.exit(app.exec_())
+# -------------------------------------------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ main()
+# TO-DO:
+# 1.refese the employee list page after add or delete or update employee
+
diff --git a/bank_managment_system/backend.py b/bank_managment_system/backend.py
index e54027cf0a6..7ea679863b5 100644
--- a/bank_managment_system/backend.py
+++ b/bank_managment_system/backend.py
@@ -1,248 +1,169 @@
import sqlite3
-
-
-# making connection with database
+import os
+# Making connection with database
def connect_database():
global conn
global cur
- conn = sqlite3.connect("bankmanaging.db")
-
+ conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), "bankmanaging.db"))
cur = conn.cursor()
-
cur.execute(
- "create table if not exists bank (acc_no int, name text, age int, address text, balance int, account_type text, mobile_number int)"
+ """
+ CREATE TABLE IF NOT EXISTS bank (
+ acc_no INTEGER PRIMARY KEY,
+ name TEXT,
+ age INTEGER,
+ address TEXT,
+ balance INTEGER,
+ account_type TEXT,
+ mobile_number TEXT
+ )
+ """
)
cur.execute(
- "create table if not exists staff (name text, pass text,salary int, position text)"
+ """
+ CREATE TABLE IF NOT EXISTS staff (
+ name TEXT,
+ pass TEXT,
+ salary INTEGER,
+ position TEXT
+ )
+ """
)
- cur.execute("create table if not exists admin (name text, pass text)")
- cur.execute("insert into admin values('arpit','123')")
+ cur.execute("CREATE TABLE IF NOT EXISTS admin (name TEXT, pass TEXT)")
+
+ # Only insert admin if not exists
+ cur.execute("SELECT COUNT(*) FROM admin")
+ if cur.fetchone()[0] == 0:
+ cur.execute("INSERT INTO admin VALUES (?, ?)", ('admin', 'admin123'))
+
conn.commit()
- cur.execute("select acc_no from bank")
- acc = cur.fetchall()
- global acc_no
- if len(acc) == 0:
- acc_no = 1
- else:
- acc_no = int(acc[-1][0]) + 1
+ # Fetch last account number to avoid duplicate or incorrect numbering
+ cur.execute("SELECT acc_no FROM bank ORDER BY acc_no DESC LIMIT 1")
+ acc = cur.fetchone()
+ global acc_no
+ acc_no = 1 if acc is None else acc[0] + 1
-# check admin dtails in database
+# Check admin details in database
def check_admin(name, password):
- cur.execute("select * from admin")
- data = cur.fetchall()
-
- if data[0][0] == name and data[0][1] == password:
- return True
- return
-
+ cur.execute("SELECT * FROM admin WHERE name = ? AND pass = ?", (name, password))
+ return cur.fetchone() is not None
-# create employee in database
-def create_employee(name, password, salary, positon):
- print(password)
- cur.execute("insert into staff values(?,?,?,?)", (name, password, salary, positon))
+# Create employee in database
+def create_employee(name, password, salary, position):
+ cur.execute("INSERT INTO staff VALUES (?, ?, ?, ?)", (name, password, salary, position))
conn.commit()
-
-# check employee details in dabase for employee login
+# Check employee login details
def check_employee(name, password):
- print(password)
- print(name)
- cur.execute("select name,pass from staff")
- data = cur.fetchall()
- print(data)
- if len(data) == 0:
- return False
- for i in range(len(data)):
- if data[i][0] == name and data[i][1] == password:
- return True
+ cur.execute("SELECT 1 FROM staff WHERE name = ? AND pass = ?", (name, password))
+ return cur.fetchone() is not None
- return False
-
-
-# create customer details in database
+# Create customer in database
def create_customer(name, age, address, balance, acc_type, mobile_number):
global acc_no
cur.execute(
- "insert into bank values(?,?,?,?,?,?,?)",
- (acc_no, name, age, address, balance, acc_type, mobile_number),
+ "INSERT INTO bank VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (acc_no, name, age, address, balance, acc_type, mobile_number)
)
conn.commit()
- acc_no = acc_no + 1
+ acc_no += 1
return acc_no - 1
-
-# check account in database
+# Check if account number exists
def check_acc_no(acc_no):
- cur.execute("select acc_no from bank")
- list_acc_no = cur.fetchall()
-
- for i in range(len(list_acc_no)):
- if list_acc_no[i][0] == int(acc_no):
- return True
- return False
+ cur.execute("SELECT 1 FROM bank WHERE acc_no = ?", (acc_no,))
+ return cur.fetchone() is not None
-
-# get all details of a particular customer from database
+# Get customer details
def get_details(acc_no):
- cur.execute("select * from bank where acc_no=?", (acc_no))
- global detail
- detail = cur.fetchall()
- print(detail)
- if len(detail) == 0:
- return False
- else:
- return (
- detail[0][0],
- detail[0][1],
- detail[0][2],
- detail[0][3],
- detail[0][4],
- detail[0][5],
- detail[0][6],
- )
-
+ cur.execute("SELECT * FROM bank WHERE acc_no = ?", (acc_no,))
+ detail = cur.fetchone()
+ return detail if detail else False
-# add new balance of customer in bank database
+# Update customer balance
def update_balance(new_money, acc_no):
- cur.execute("select balance from bank where acc_no=?", (acc_no,))
- bal = cur.fetchall()
- bal = bal[0][0]
- new_bal = bal + int(new_money)
-
- cur.execute("update bank set balance=? where acc_no=?", (new_bal, acc_no))
+ cur.execute("UPDATE bank SET balance = balance + ? WHERE acc_no = ?", (new_money, acc_no))
conn.commit()
-
-# deduct balance from customer bank database
+# Deduct balance
def deduct_balance(new_money, acc_no):
- cur.execute("select balance from bank where acc_no=?", (acc_no,))
- bal = cur.fetchall()
- bal = bal[0][0]
- if bal < int(new_money):
- return False
- else:
- new_bal = bal - int(new_money)
-
- cur.execute("update bank set balance=? where acc_no=?", (new_bal, acc_no))
+ cur.execute("SELECT balance FROM bank WHERE acc_no = ?", (acc_no,))
+ bal = cur.fetchone()
+ if bal and bal[0] >= new_money:
+ cur.execute("UPDATE bank SET balance = balance - ? WHERE acc_no = ?", (new_money, acc_no))
conn.commit()
return True
+ return False
-
-# gave balance of a particular account number from database
+# Get account balance
def check_balance(acc_no):
- cur.execute("select balance from bank where acc_no=?", (acc_no))
- bal = cur.fetchall()
- return bal[0][0]
-
+ cur.execute("SELECT balance FROM bank WHERE acc_no = ?", (acc_no,))
+ bal = cur.fetchone()
+ return bal[0] if bal else 0
-# update_name_in_bank_table
+# Update customer details
def update_name_in_bank_table(new_name, acc_no):
- print(new_name)
- conn.execute("update bank set name='{}' where acc_no={}".format(new_name, acc_no))
+ cur.execute("UPDATE bank SET name = ? WHERE acc_no = ?", (new_name, acc_no))
conn.commit()
-
-# update_age_in_bank_table
-def update_age_in_bank_table(new_name, acc_no):
- print(new_name)
- conn.execute("update bank set age={} where acc_no={}".format(new_name, acc_no))
+def update_age_in_bank_table(new_age, acc_no):
+ cur.execute("UPDATE bank SET age = ? WHERE acc_no = ?", (new_age, acc_no))
conn.commit()
-
-# update_address_in_bank_table
-def update_address_in_bank_table(new_name, acc_no):
- print(new_name)
- conn.execute(
- "update bank set address='{}' where acc_no={}".format(new_name, acc_no)
- )
+def update_address_in_bank_table(new_address, acc_no):
+ cur.execute("UPDATE bank SET address = ? WHERE acc_no = ?", (new_address, acc_no))
conn.commit()
-
-# list of all customers in bank
+# List all customers
def list_all_customers():
- cur.execute("select * from bank")
- deatil = cur.fetchall()
+ cur.execute("SELECT * FROM bank")
+ return cur.fetchall()
- return deatil
-
-
-# delete account from database
+# Delete account
def delete_acc(acc_no):
- cur.execute("delete from bank where acc_no=?", (acc_no))
+ cur.execute("DELETE FROM bank WHERE acc_no = ?", (acc_no,))
conn.commit()
-
-# show employees detail from staff table
+# Show employees
def show_employees():
- cur.execute("select name, salary, position,pass from staff")
- detail = cur.fetchall()
- return detail
+ cur.execute("SELECT name, salary, position FROM staff")
+ return cur.fetchall()
-
-# return all money in bank
+# Get total money in bank
def all_money():
- cur.execute("select balance from bank")
- bal = cur.fetchall()
- print(bal)
- if len(bal) == 0:
- return False
- else:
- total = 0
- for i in bal:
- total = total + i[0]
- return total
-
-
-# return a list of all employees name
-def show_employees_for_update():
- cur.execute("select * from staff")
- detail = cur.fetchall()
- return detail
+ cur.execute("SELECT SUM(balance) FROM bank")
+ total = cur.fetchone()[0]
+ return total if total else 0
+# Get employee details
+def show_employees_for_update():
+ cur.execute("SELECT * FROM staff")
+ return cur.fetchall()
-# update employee name from data base
+# Update employee details
def update_employee_name(new_name, old_name):
- print(new_name, old_name)
- cur.execute("update staff set name='{}' where name='{}'".format(new_name, old_name))
+ cur.execute("UPDATE staff SET name = ? WHERE name = ?", (new_name, old_name))
conn.commit()
-
def update_employee_password(new_pass, old_name):
- print(new_pass, old_name)
- cur.execute("update staff set pass='{}' where name='{}'".format(new_pass, old_name))
+ cur.execute("UPDATE staff SET pass = ? WHERE name = ?", (new_pass, old_name))
conn.commit()
-
def update_employee_salary(new_salary, old_name):
- print(new_salary, old_name)
- cur.execute(
- "update staff set salary={} where name='{}'".format(new_salary, old_name)
- )
+ cur.execute("UPDATE staff SET salary = ? WHERE name = ?", (new_salary, old_name))
conn.commit()
-
def update_employee_position(new_pos, old_name):
- print(new_pos, old_name)
- cur.execute(
- "update staff set position='{}' where name='{}'".format(new_pos, old_name)
- )
+ cur.execute("UPDATE staff SET position = ? WHERE name = ?", (new_pos, old_name))
conn.commit()
-
-# get name and balance from bank of a particular account number
+# Get customer name and balance
def get_detail(acc_no):
- cur.execute("select name, balance from bank where acc_no=?", (acc_no))
- details = cur.fetchall()
- return details
-
+ cur.execute("SELECT name, balance FROM bank WHERE acc_no = ?", (acc_no,))
+ return cur.fetchone()
+# Check if employee exists
def check_name_in_staff(name):
- cur = conn.cursor()
- cur.execute("select name from staff")
- details = cur.fetchall()
-
- for i in details:
- if i[0] == name:
- return True
- return False
+ cur.execute("SELECT 1 FROM staff WHERE name = ?", (name,))
+ return cur.fetchone() is not None
\ No newline at end of file
diff --git a/bank_managment_system/untitled.ui b/bank_managment_system/untitled.ui
new file mode 100644
index 00000000000..12c130fb4e7
--- /dev/null
+++ b/bank_managment_system/untitled.ui
@@ -0,0 +1,862 @@
+
+
+ MainWindow
+
+
+
+ 0
+ 0
+ 800
+ 600
+
+
+
+ MainWindow
+
+
+
+ background-color: #f0f2f5;
+QPushButton {
+ background-color: #3498db;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+
+
+
+ -
+
+
+ 2
+
+
+
+
-
+
+
+
+ background-color: #ffffff;
+ border-radius: 10px;
+ padding: 10px;
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 30
+
+
+
+
+ color: #2c3e50;
+ padding: 10px;
+
+
+
+ Bank Management system
+
+
+
+
+
+
+ -
+
+
+
+ 0
+ 0
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 300
+ 0
+
+
+
+
+ 16
+
+
+
+
+
+ background-color: #ffffff;
+ border-radius: 15px;
+ padding: 20px;
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+ QPushButton {
+ background-color: #3498db;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+
+
+ Admin
+
+
+
+ -
+
+
+ QPushButton {
+ background-color: #3498db;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+
+
+ Employee
+
+
+
+ -
+
+
+ QPushButton {
+ background-color: #3498db;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+
+
+ Exit
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ -
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+
+ 340
+ 210
+ 261
+ 231
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+
+ 20
+ 20
+ 75
+ 23
+
+
+
+ PushButton
+
+
+
+
+
+
+
+
+
+ -
+
+
+
+ background-color: #ffffff;
+ border-radius: 10px;
+ padding: 10px;
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 30
+
+
+
+
+ color: #2c3e50;
+ padding: 10px;
+
+
+
+ Employee Login
+
+
+
+
+
+
+ -
+
+
+
+ 0
+ 0
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 340
+ 200
+
+
+
+
+ 16
+
+
+
+
+
+ background-color: #ffffff;
+ border-radius: 15px;
+ padding: 10px;
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+ padding:7
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 120
+ 0
+
+
+
+
+ 12
+ 75
+ true
+
+
+
+
+ color: #2c3e50;
+
+
+
+ Name :
+
+
+
+ -
+
+
+ background-color: rgb(168, 168, 168);
+
+
+
+
+
+
+
+
+
+ -
+
+
+ padding:7
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 120
+ 0
+
+
+
+
+ 12
+ 75
+ true
+
+
+
+
+ color: #2c3e50;
+
+
+
+ Password :
+
+
+
+ -
+
+
+ background-color: rgb(168, 168, 168);
+
+
+
+
+
+
+
+
+
+ -
+
+
+ padding:7
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 60
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 150
+ 0
+
+
+
+ QPushButton {
+ background-color: #3498db;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+
+
+ Submit
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ -
+
+
+
+ background-color: #ffffff;
+ border-radius: 10px;
+ padding: 10px;
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 30
+
+
+
+
+ color: #2c3e50;
+ padding: 10px;
+
+
+
+ Admin Login
+
+
+
+
+
+
+ -
+
+
+
+ 0
+ 0
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
-
+
+
+
+ 340
+ 200
+
+
+
+
+ 16
+
+
+
+
+
+ background-color: #ffffff;
+ border-radius: 15px;
+ padding: 10px;
+
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+ padding:7
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 120
+ 0
+
+
+
+
+ 12
+ 75
+ true
+
+
+
+
+ color: #2c3e50;
+
+
+
+ Name :
+
+
+
+ -
+
+
+ background-color: rgb(168, 168, 168);
+
+
+
+
+
+
+
+
+
+ -
+
+
+ padding:7
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 120
+ 0
+
+
+
+
+ 12
+ 75
+ true
+
+
+
+
+ color: #2c3e50;
+
+
+
+ Password :
+
+
+
+ -
+
+
+ background-color: rgb(168, 168, 168);
+
+
+
+
+
+
+
+
+
+ -
+
+
+ padding:7
+
+
+ QFrame::StyledPanel
+
+
+ QFrame::Raised
+
+
+
+ 60
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
+ 0
+
+
-
+
+
+
+ 150
+ 0
+
+
+
+ QPushButton {
+ background-color: #3498db;
+ color: white;
+ font-family: 'Segoe UI';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 8px;
+ padding: 12px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #2980b9;
+ }
+ QPushButton:pressed {
+ background-color: #1c6ea4;
+ }
+
+
+ Submit
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/basic example b/basic example
deleted file mode 100644
index 9da92d6f5b8..00000000000
--- a/basic example
+++ /dev/null
@@ -1,11 +0,0 @@
-## Example: Kilometers to Miles
-
-# Taking kilometers input from the user
-kilometers = float(input("Enter value in kilometers: "))
-
-# conversion factor
-conv_fac = 0.621371
-
-# calculate miles
-miles = kilometers * conv_fac
-print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
diff --git a/basic_cal.py b/basic_cal.py
new file mode 100644
index 00000000000..6629ad178db
--- /dev/null
+++ b/basic_cal.py
@@ -0,0 +1,8 @@
+while True:
+ try:
+ print(eval(input("enter digits with operator (e.g. 5+5)\n")))
+ except:
+ print("Invalid Input, try again..")
+
+# Simple Calculator using eval() in Python
+# This calculator takes user input like "5+5" or "10/2" and shows the result.
\ No newline at end of file
diff --git a/billing.py b/billing.py
new file mode 100644
index 00000000000..f6fb387101c
--- /dev/null
+++ b/billing.py
@@ -0,0 +1,70 @@
+updated_billing
+items= {"apple":5,"soap":4,"soda":6,"pie":7,"cake":20}
+total_price=0
+try :
+ print("""
+Press 1 for apple
+Press 2 for soap
+Press 3 for soda
+Press 4 for pie
+Press 5 for cake
+Press 6 for bill""")
+ while True:
+ choice = int(input("enter your choice here..\n"))
+ if choice ==1:
+ print("Apple added to the cart")
+ total_price+=items["apple"]
+
+ elif choice== 2:
+ print("soap added to the cart")
+ total_price+= items["soap"]
+ elif choice ==3:
+ print("soda added to the cart")
+ total_price+=items["soda"]
+ elif choice ==4:
+ print("pie added to the cart")
+ total_price+=items["pie"]
+ elif choice ==5:
+ print("cake added to the cart")
+ total_price+=items["cake"]
+ elif choice == 6:
+ print(f"""
+
+Total amount :{total_price}
+""")
+ break
+ else:
+ print("Please enter the digits within the range 1-6..")
+except:
+ print("enter only digits")
+
+"""
+Code Explanation:
+A dictionary named items is created to store product names and their corresponding prices.
+Example: "apple": 5 means apple costs 5 units.
+
+one variable is initialized:
+
+total_price to keep track of the overall bill.
+
+
+A menu is printed that shows the user what number to press for each item or to generate the final bill.
+
+A while True loop is started, meaning it will keep running until the user explicitly chooses to stop (by selecting "6" for the bill).
+
+Inside the loop:
+
+The user is asked to enter a number (1–6).
+
+Depending on their input:
+
+If they enter 1–5, the corresponding item is "added to the cart" and its price is added to the total_price.
+
+If they enter 6, the total price is printed and the loop breaks (ends).
+
+If they enter something outside 1–6, a warning message is shown.
+
+The try-except block is used to catch errors if the user enters something that's not a number (like a letter or symbol).
+In that case, it simply shows: "enter only digits".
+"""
+
diff --git a/binary_search_trees/delete_a_node_in_bst.py b/binary_search_trees/delete_a_node_in_bst.py
new file mode 100644
index 00000000000..bfb6a0708ac
--- /dev/null
+++ b/binary_search_trees/delete_a_node_in_bst.py
@@ -0,0 +1,35 @@
+from inorder_successor import inorder_successor
+# The above line imports the inorder_successor function from the inorder_successor.py file
+def delete_node(root,val):
+ """ This function deletes a node with value val from the BST"""
+
+ # search in the left subtree
+ if root.data < val:
+ root.right = delete_node(root.right,val)
+
+ # search in the right subtree
+ elif root.data>val:
+ root.left=delete_node(root.left,val)
+
+ # node to be deleted is found
+ else:
+ # case 1: no child leaf node
+ if root.left is None and root.right is None:
+ return None
+
+ # case 2: one child
+ if root.left is None:
+ return root.right
+
+ # case 2: one child
+ elif root.right is None:
+ return root.left
+
+ # case 3: two children
+
+ # find the inorder successor
+ IS=inorder_successor(root.right)
+ root.data=IS.data
+ root.right=delete_node(root.right,IS.data)
+ return root
+
\ No newline at end of file
diff --git a/binary_search_trees/inorder_successor.py b/binary_search_trees/inorder_successor.py
new file mode 100644
index 00000000000..b9b15666eea
--- /dev/null
+++ b/binary_search_trees/inorder_successor.py
@@ -0,0 +1,10 @@
+def inorder_successor(root):
+ # This function returns the inorder successor of a node in a BST
+
+ # The inorder successor of a node is the node with the smallest value greater than the value of the node
+ current=root
+
+ # The inorder successor is the leftmost node in the right subtree
+ while current.left is not None:
+ current=current.left
+ return current
\ No newline at end of file
diff --git a/binary_search_trees/inorder_traversal.py b/binary_search_trees/inorder_traversal.py
new file mode 100644
index 00000000000..3bb4c4101ed
--- /dev/null
+++ b/binary_search_trees/inorder_traversal.py
@@ -0,0 +1,15 @@
+def inorder(root):
+ """ This function performs an inorder traversal of a BST"""
+
+ # The inorder traversal of a BST is the nodes in increasing order
+ if root is None:
+ return
+
+ # Traverse the left subtree
+ inorder(root.left)
+
+ # Print the root node
+ print(root.data)
+
+ # Traverse the right subtree
+ inorder(root.right)
\ No newline at end of file
diff --git a/binary_search_trees/insert_in_bst.py b/binary_search_trees/insert_in_bst.py
new file mode 100644
index 00000000000..dd726d06596
--- /dev/null
+++ b/binary_search_trees/insert_in_bst.py
@@ -0,0 +1,17 @@
+from tree_node import Node
+def insert(root,val):
+
+ """ This function inserts a node with value val into the BST"""
+
+ # If the tree is empty, create a new node
+ if root is None:
+ return Node(val)
+
+ # If the value to be inserted is less than the root value, insert in the left subtree
+ if val < root.data:
+ root.left = insert(root.left,val)
+
+ # If the value to be inserted is greater than the root value, insert in the right subtree
+ else:
+ root.right = insert(root.right,val)
+ return root
\ No newline at end of file
diff --git a/binary_search_trees/main.py b/binary_search_trees/main.py
new file mode 100644
index 00000000000..96ebb6ae8eb
--- /dev/null
+++ b/binary_search_trees/main.py
@@ -0,0 +1,85 @@
+from tree_node import Node
+from insert_in_bst import insert
+from delete_a_node_in_bst import delete_node
+from search_in_bst import search
+from inorder_successor import inorder_successor
+from mirror_a_bst import create_mirror_bst
+from print_in_range import print_in_range
+from root_to_leaf_paths import print_root_to_leaf_paths
+from validate_bst import is_valid_bst
+
+
+def main():
+
+ # Create a BST
+ root = None
+ root = insert(root, 50)
+ root = insert(root, 30)
+ root = insert(root, 20)
+ root = insert(root, 40)
+ root = insert(root, 70)
+ root = insert(root, 60)
+ root = insert(root, 80)
+
+ # Print the inorder traversal of the BST
+ print("Inorder traversal of the original BST:")
+ print_in_range(root, 10, 90)
+
+ # Print the root to leaf paths
+ print("Root to leaf paths:")
+ print_root_to_leaf_paths(root, [])
+
+ # Check if the tree is a BST
+ print("Is the tree a BST:", is_valid_bst(root,None,None))
+
+
+ # Delete nodes from the BST
+ print("Deleting 20 from the BST:")
+ root = delete_node(root, 20)
+
+ # Print the inorder traversal of the BST
+ print("Inorder traversal of the BST after deleting 20:")
+ print_in_range(root, 10, 90)
+
+ # Check if the tree is a BST
+ print("Is the tree a BST:", is_valid_bst(root,None,None))
+
+
+ # Delete nodes from the BST
+ print("Deleting 30 from the BST:")
+ root = delete_node(root, 30)
+
+ # Print the inorder traversal of the BST after deleting 30
+ print("Inorder traversal of the BST after deleting 30:")
+ print_in_range(root, 10, 90)
+
+ # Check if the tree is a BST
+ print("Is the tree a BST:", is_valid_bst(root,None,None))
+
+ # Delete nodes from the BST
+ print("Deleting 50 from the BST:")
+ root = delete_node(root, 50)
+
+ # Print the inorder traversal of the BST after deleting 50
+ print("Inorder traversal of the BST after deleting 50:")
+ print_in_range(root, 10, 90)
+
+ # Check if the tree is a BST
+ print("Is the tree a BST:", is_valid_bst(root,None,None))
+
+
+ print("Searching for 70 in the BST:", search(root, 70))
+ print("Searching for 100 in the BST:", search(root, 100))
+ print("Inorder traversal of the BST:")
+ print_in_range(root, 10, 90)
+ print("Creating a mirror of the BST:")
+ mirror_root = create_mirror_bst(root)
+ print("Inorder traversal of the mirror BST:")
+ print_in_range(mirror_root, 10, 90)
+
+if __name__ == "__main__":
+ main()
+
+
+
+
diff --git a/binary_search_trees/mirror_a_bst.py b/binary_search_trees/mirror_a_bst.py
new file mode 100644
index 00000000000..73f080f85c2
--- /dev/null
+++ b/binary_search_trees/mirror_a_bst.py
@@ -0,0 +1,16 @@
+from tree_node import Node
+def create_mirror_bst(root):
+ """ Function to create a mirror of a binary search tree"""
+
+ # If the tree is empty, return None
+ if root is None:
+ return None
+
+ # Create a new node with the root value
+
+ # Recursively create the mirror of the left and right subtrees
+ left_mirror = create_mirror_bst(root.left)
+ right_mirror = create_mirror_bst(root.right)
+ root.left = right_mirror
+ root.right = left_mirror
+ return root
\ No newline at end of file
diff --git a/binary_search_trees/print_in_range.py b/binary_search_trees/print_in_range.py
new file mode 100644
index 00000000000..fecca23ba24
--- /dev/null
+++ b/binary_search_trees/print_in_range.py
@@ -0,0 +1,21 @@
+def print_in_range(root,k1,k2):
+
+ """ This function prints the nodes in a BST that are in the range k1 to k2 inclusive"""
+
+ # If the tree is empty, return
+ if root is None:
+ return
+
+ # If the root value is in the range, print the root value
+ if root.data >= k1 and root.data <= k2:
+ print_in_range(root.left,k1,k2)
+ print(root.data)
+ print_in_range(root.right,k1,k2)
+
+ # If the root value is less than k1, the nodes in the range will be in the right subtree
+ elif root.data < k1:
+ print_in_range(root.left,k1,k2)
+
+ # If the root value is greater than k2, the nodes in the range will be in the left subtree
+ else:
+ print_in_range(root.right,k1,k2)
\ No newline at end of file
diff --git a/binary_search_trees/root_to_leaf_paths.py b/binary_search_trees/root_to_leaf_paths.py
new file mode 100644
index 00000000000..22867a713ec
--- /dev/null
+++ b/binary_search_trees/root_to_leaf_paths.py
@@ -0,0 +1,17 @@
+def print_root_to_leaf_paths(root, path):
+ """ This function prints all the root to leaf paths in a BST"""
+
+ # If the tree is empty, return
+ if root is None:
+ return
+
+ # Add the root value to the path
+ path.append(root.data)
+ if root.left is None and root.right is None:
+ print(path)
+
+ # Recursively print the root to leaf paths in the left and right subtrees
+ else:
+ print_root_to_leaf_paths(root.left, path)
+ print_root_to_leaf_paths(root.right, path)
+ path.pop()
\ No newline at end of file
diff --git a/binary_search_trees/search_in_bst.py b/binary_search_trees/search_in_bst.py
new file mode 100644
index 00000000000..4a95780e43a
--- /dev/null
+++ b/binary_search_trees/search_in_bst.py
@@ -0,0 +1,15 @@
+def search(root, val):
+ """ This function searches for a node with value val in the BST and returns True if found, False otherwise"""
+
+ # If the tree is empty, return False
+ if root == None:
+ return False
+
+ # If the root value is equal to the value to be searched, return True
+ if root.data == val:
+ return True
+
+ # If the value to be searched is less than the root value, search in the left subtree
+ if root.data > val:
+ return search(root.left, val)
+ return search(root.right, val)
\ No newline at end of file
diff --git a/binary_search_trees/tree_node.py b/binary_search_trees/tree_node.py
new file mode 100644
index 00000000000..1d35656da08
--- /dev/null
+++ b/binary_search_trees/tree_node.py
@@ -0,0 +1,8 @@
+
+# Node class for binary tree
+
+class Node:
+ def __init__(self, data):
+ self.data = data
+ self.left = None
+ self.right = None
diff --git a/binary_search_trees/validate_bst.py b/binary_search_trees/validate_bst.py
new file mode 100644
index 00000000000..3569c833005
--- /dev/null
+++ b/binary_search_trees/validate_bst.py
@@ -0,0 +1,17 @@
+def is_valid_bst(root,min,max):
+ """ Function to check if a binary tree is a binary search tree"""
+
+ # If the tree is empty, return True
+ if root is None:
+ return True
+
+ # If the root value is less than the minimum value or greater than the maximum value, return False
+ if min is not None and root.data <= min.data:
+ return False
+
+ # If the root value is greater than the maximum value or less than the minimum value, return False
+ elif max is not None and root.data >= max.data:
+ return False
+
+ # Recursively check if the left and right subtrees are BSTs
+ return is_valid_bst(root.left,min,root) and is_valid_bst(root.right,root,max)
\ No newline at end of file
diff --git a/bodymass.py b/bodymass.py
new file mode 100644
index 00000000000..be37d0db0ef
--- /dev/null
+++ b/bodymass.py
@@ -0,0 +1,19 @@
+kilo = float (input("kilonuzu giriniz(örnek: 84.9): "))
+boy = float (input("Boyunuzu m cinsinden giriniz: "))
+
+vki = (kilo / (boy**2))
+
+if vki < 18.5:
+ print(f"vucut kitle indeksiniz: {vki} zayıfsınız.")
+elif vki < 25:
+ print (f"vucut kitle indeksiniz: {vki} normalsiniz.")
+elif vki < 30:
+ print (f"vucut kitle indeksiniz: {vki} fazla kilolusunuz.")
+elif vki < 35:
+ print (f"vucut kitle indeksiniz: {vki} 1. derece obezsiniz")
+elif vki < 40:
+ print (f"vucut kitle indeksiniz: {vki} 2.derece obezsiniz.")
+elif vki >40:
+ print (f"vucut kitle indeksiniz: {vki} 3.derece obezsiniz.")
+else:
+ print("Yanlış değer girdiniz.")
diff --git a/calculator.py b/calculator.py
index b12986aa7e6..b0ef5dca8dd 100644
--- a/calculator.py
+++ b/calculator.py
@@ -37,6 +37,9 @@ def calc(term):
purpose: This function is the actual calculator and the heart of the application
"""
+ # This part is for reading and converting function expressions.
+ term = term.lower()
+
# This part is for reading and converting arithmetic terms.
term = term.replace(" ", "")
term = term.replace("^", "**")
@@ -61,9 +64,6 @@ def calc(term):
"e",
]
- # This part is for reading and converting function expressions.
- term = term.lower()
-
for func in functions:
if func in term:
withmath = "math." + func
diff --git a/calculatorproject.py b/calculatorproject.py
deleted file mode 100644
index 9e335d38c95..00000000000
--- a/calculatorproject.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# Program make a simple calculator
-def add(x, y):
- return x + y
-def subtract(x, y):
- return x - y
-def multiply(x, y):
- return x * y
-
-def divide(x, y):
- return x / y
-
-
-print("Select operation.")
-print("1.Add")
-print("2.Subtract")
-print("3.Multiply")
-print("4.Divide")
-
-while True:
- # Take input from the user
- choice = input("Enter choice(1/2/3/4): ")
-
- # Check if choice is one of the four options
- if choice in ('1', '2', '3', '4'):
- num1 = float(input("Enter first number: "))
- num2 = float(input("Enter second number: "))
-
- if choice == '1':
- print(num1, "+", num2, "=", add(num1, num2))
-
- elif choice == '2':
- print(num1, "-", num2, "=", subtract(num1, num2))
-
- elif choice == '3':
- print(num1, "*", num2, "=", multiply(num1, num2))
-
- elif choice == '4':
- print(num1, "/", num2, "=", divide(num1, num2))
- break
- else:
- print("Invalid Input")
diff --git a/check whether the string is Symmetrical or Palindrome b/check whether the string is Symmetrical or Palindrome.py
similarity index 100%
rename from check whether the string is Symmetrical or Palindrome
rename to check whether the string is Symmetrical or Palindrome.py
diff --git a/cicd b/cicd
new file mode 100644
index 00000000000..8b137891791
--- /dev/null
+++ b/cicd
@@ -0,0 +1 @@
+
diff --git a/cli_master/cli_master.py b/cli_master/cli_master.py
new file mode 100644
index 00000000000..f57a3b192bb
--- /dev/null
+++ b/cli_master/cli_master.py
@@ -0,0 +1,136 @@
+import os
+import sys
+from pprint import pprint
+
+import sys
+
+sys.path.append(os.path.realpath("."))
+import inquirer # noqa
+
+# Take authentication input from the user
+questions = [
+ inquirer.List(
+ "authentication", # This is the key
+ message="Choose an option",
+ choices=["Login", "Sign up", "Exit"],
+ ),
+]
+answers = inquirer.prompt(questions)
+
+
+# Just making pipelines
+class Validation:
+ def phone_validation():
+ # Think over how to make a validation for phone number?
+ pass
+
+ def email_validation():
+ pass
+
+ def password_validation():
+ pass
+
+ def username_validation():
+ pass
+
+ def country_validation():
+ # All the countries in the world???
+ # JSON can be used.
+ # Download the file
+
+ def state_validation():
+ # All the states in the world??
+ # The state of the selected country only.
+ pass
+
+ def city_validation():
+ # All the cities in the world??
+ # JSON can be used.
+ pass
+
+
+# Have an option to go back.
+# How can I do it?
+if answers["authentication"] == "Login":
+ print("Login")
+ questions = [
+ inquirer.Text(
+ "username",
+ message="What's your username?",
+ validate=Validation.login_username,
+ ),
+ inquirer.Text(
+ "password",
+ message="What's your password?",
+ validate=Validation.login_password,
+ ),
+ ]
+
+
+elif answers["authentication"] == "Sign up":
+ print("Sign up")
+
+ questions = [
+ inquirer.Text(
+ "name",
+ message="What's your first name?",
+ validate=Validation.fname_validation,
+ ),
+ inquirer.Text(
+ "surname",
+ message="What's your last name(surname)?, validate=Validation.lname), {name}?",
+ ),
+ inquirer.Text(
+ "phone",
+ message="What's your phone number",
+ validate=Validation.phone_validation,
+ ),
+ inquirer.Text(
+ "email",
+ message="What's your email",
+ validate=Validation.email_validation,
+ ),
+ inquirer.Text(
+ "password",
+ message="What's your password",
+ validate=Validation.password_validation,
+ ),
+ inquirer.Text(
+ "password",
+ message="Confirm your password",
+ validate=Validation.password_confirmation,
+ ),
+ inquirer.Text(
+ "username",
+ message="What's your username",
+ validate=Validation.username_validation,
+ ),
+ inquirer.Text(
+ "country",
+ message="What's your country",
+ validate=Validation.country_validation,
+ ),
+ inquirer.Text(
+ "state",
+ message="What's your state",
+ validate=Validation.state_validation,
+ ),
+ inquirer.Text(
+ "city",
+ message="What's your city",
+ validate=Validation.city_validation,
+ ),
+ inquirer.Text(
+ "address",
+ message="What's your address",
+ validate=Validation.address_validation,
+ ),
+ ]
+# Also add optional in the above thing.
+# Have string manipulation for the above thing.
+# How to add authentication of google to command line?
+elif answers["authentication"] == "Exit":
+ print("Exit")
+ sys.exit()
+
+pprint(answers)
diff --git a/cli_master/database_import_countries.py b/cli_master/database_import_countries.py
new file mode 100644
index 00000000000..27255834e9e
--- /dev/null
+++ b/cli_master/database_import_countries.py
@@ -0,0 +1,9 @@
+import requests
+
+url = "https://api.countrystatecity.in/v1/countries"
+
+headers = {"X-CSCAPI-KEY": "API_KEY"}
+
+response = requests.request("GET", url, headers=headers)
+
+print(response.text)
diff --git a/cli_master/validation_page.py b/cli_master/validation_page.py
new file mode 100644
index 00000000000..8852781d4b7
--- /dev/null
+++ b/cli_master/validation_page.py
@@ -0,0 +1,62 @@
+import re
+
+def phone_validation(phone_number):
+ # Match a typical US phone number format (xxx) xxx-xxxx
+ pattern = re.compile(r'^\(\d{3}\) \d{3}-\d{4}$')
+ return bool(pattern.match(phone_number))
+
+# Example usage:
+phone_number_input = input("Enter phone number: ")
+if phone_validation(phone_number_input):
+ print("Phone number is valid.")
+else:
+ print("Invalid phone number.")
+
+def email_validation(email):
+ # Basic email format validation
+ pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
+ return bool(pattern.match(email))
+
+# Example usage:
+email_input = input("Enter email address: ")
+if email_validation(email_input):
+ print("Email address is valid.")
+else:
+ print("Invalid email address.")
+
+
+def password_validation(password):
+ # Password must be at least 8 characters long and contain at least one digit
+ return len(password) >= 8 and any(char.isdigit() for char in password)
+
+# Example usage:
+password_input = input("Enter password: ")
+if password_validation(password_input):
+ print("Password is valid.")
+else:
+ print("Invalid password.")
+
+
+def username_validation(username):
+ # Allow only alphanumeric characters and underscores
+ return bool(re.match('^[a-zA-Z0-9_]+$', username))
+
+# Example usage:
+username_input = input("Enter username: ")
+if username_validation(username_input):
+ print("Username is valid.")
+else:
+ print("Invalid username.")
+
+
+def country_validation(country):
+ # Example: Allow only alphabetical characters and spaces
+ return bool(re.match('^[a-zA-Z ]+$', country))
+
+# Example usage:
+country_input = input("Enter country name: ")
+if country_validation(country_input):
+ print("Country name is valid.")
+else:
+ print("Invalid country name.")
+
diff --git a/colorma_as_color.py b/colorma_as_color.py
new file mode 100644
index 00000000000..9bf2338ebbb
--- /dev/null
+++ b/colorma_as_color.py
@@ -0,0 +1,22 @@
+import colorama as color
+
+
+from colorama import Fore, Back, Style
+
+print(Fore.RED + "some red text")
+print(Back.GREEN + "and with a green background")
+print("So any text will be in green background?")
+
+print("So is it a wrapper of some sort?")
+print("dark_angel wasn't using it in her code.")
+print("she was just being using direct ANSI codes.")
+print(Style.RESET_ALL)
+print(Fore.BRIGHT_RED + "some bright red text")
+print(Back.WHITE + "and with a white background")
+print("Will need to study about what is ANSI codes.")
+print(Style.DIM + "and in dim text")
+print(Style.RESET_ALL)
+print("back to normal now")
+
+
+# …or, Colorama can be used in conjunction with existing ANSI libraries such as the venerable Termcolor the fabulous Blessings, or the incredible _Rich.
\ No newline at end of file
diff --git a/compass_code.py b/compass_code.py
new file mode 100644
index 00000000000..ec0ac377ba6
--- /dev/null
+++ b/compass_code.py
@@ -0,0 +1,8 @@
+def degree_to_direction(deg):
+ directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
+
+ deg = deg% 360
+ deg = int(deg//45)
+ print(directions[deg])
+
+degree_to_direction(45)
\ No newline at end of file
diff --git a/contribution.txt b/contribution.txt
new file mode 100644
index 00000000000..181a276c94d
--- /dev/null
+++ b/contribution.txt
@@ -0,0 +1 @@
+Add a dark mode toggle for better UX
diff --git a/conversion.py b/conversion.py
deleted file mode 100644
index 022035234f5..00000000000
--- a/conversion.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# Python program to convert a list
-# of character
-
-def convert(s):
-
- # initialization of string to ""
- new = ""
-
- # traverse in the string
- for x in s:
- new += x
-
- # return string
- return new
-
-
-# driver code
-s = ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's']
-print(convert(s))
diff --git a/convert_wind_direction_to_degrees.py b/convert_wind_direction_to_degrees.py
new file mode 100644
index 00000000000..cbac637f332
--- /dev/null
+++ b/convert_wind_direction_to_degrees.py
@@ -0,0 +1,19 @@
+def degrees_to_compass(degrees):
+ directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
+ index = round(degrees / 45) % 8
+ return directions[index]
+
+# Taking input from the user
+while True:
+ try:
+ degrees = float(input("Enter the wind direction in degrees (0-359): "))
+ if degrees < 0 or degrees >= 360:
+ raise ValueError("Degrees must be between 0 and 359")
+ break
+ except ValueError as ve:
+ print(f"Error: {ve}")
+ continue
+
+
+compass_direction = degrees_to_compass(degrees)
+print(f"{degrees} degrees is {compass_direction}")
diff --git a/count_vowels.py b/count_vowels.py
deleted file mode 100644
index 852566b3550..00000000000
--- a/count_vowels.py
+++ /dev/null
@@ -1,17 +0,0 @@
-vowels = "aeiou"
-
-ip_str = "Hello, have you tried our tutorial section yet?"
-
-
-# count the vowels
-vowel_count = 0
-consonant_count = 0
-
-for char in ip_str:
- if char in vowels:
- vowel_count += 1
- else:
- consonant_count += 1
-
-print("Total Vowels: ", vowel_count)
-print("Total consonants: ", consonant_count)
diff --git a/currency converter/gui.ui b/currency converter/gui.ui
index 6c8e578fc95..a2b39c9e6a4 100644
--- a/currency converter/gui.ui
+++ b/currency converter/gui.ui
@@ -6,13 +6,101 @@
0
0
- 794
- 365
+ 785
+ 362
MainWindow
+
+ QMainWindow {
+ background-color: #2C2F33;
+ }
+ QLabel#label {
+ color: #FFFFFF;
+ font-family: 'Arial';
+ font-size: 28px;
+ font-weight: bold;
+ background-color: transparent;
+ padding: 10px;
+ }
+ QLabel#label_2, QLabel#label_3 {
+ color: #7289DA;
+ font-family: 'Arial';
+ font-size: 20px;
+ font-weight: normal;
+ background-color: transparent;
+ }
+ QComboBox {
+ background-color: #23272A;
+ color: #FFFFFF;
+ font-family: 'Arial';
+ font-size: 16px;
+ border-radius: 10px;
+ padding: 10px;
+ border: 1px solid #7289DA;
+ }
+ QComboBox:hover {
+ border: 1px solid #677BC4;
+ }
+ QComboBox::drop-down {
+ border: none;
+ width: 20px;
+ }
+ QComboBox::down-arrow {
+ image: url(http://github.com/:/icons/down_arrow.png);
+ width: 12px;
+ height: 12px;
+ }
+ QComboBox QAbstractItemView {
+ background-color: #23272A;
+ color: #FFFFFF;
+ selection-background-color: #7289DA;
+ selection-color: #FFFFFF;
+ border: 1px solid #7289DA;
+ border-radius: 5px;
+ }
+ QLineEdit {
+ background-color: #23272A;
+ color: #FFFFFF;
+ font-family: 'Arial';
+ font-size: 20px;
+ border-radius: 10px;
+ padding: 10px;
+ border: 1px solid #7289DA;
+ }
+ QLineEdit:hover, QLineEdit:focus {
+ border: 1px solid #677BC4;
+ }
+ QPushButton {
+ background-color: #7289DA;
+ color: #FFFFFF;
+ font-family: 'Arial';
+ font-size: 16px;
+ font-weight: bold;
+ border-radius: 10px;
+ padding: 10px;
+ border: none;
+ }
+ QPushButton:hover {
+ background-color: #677BC4;
+ }
+ QPushButton:pressed {
+ background-color: #5B6EAE;
+ }
+ QLCDNumber {
+ background-color: #23272A;
+ color: #43B581;
+ border-radius: 10px;
+ border: 1px solid #7289DA;
+ padding: 10px;
+ }
+ QStatusBar {
+ background-color: #23272A;
+ color: #FFFFFF;
+ }
+
@@ -25,8 +113,8 @@
- Segoe Script
- 24
+ Arial
+ -1
75
true
@@ -61,7 +149,7 @@
- 110
+ 100
260
571
41
@@ -92,9 +180,11 @@
- Monotype Corsiva
- 20
+ Arial
+ -1
+ 50
true
+ false
@@ -112,9 +202,11 @@
- Monotype Corsiva
- 20
+ Arial
+ -1
+ 50
true
+ false
@@ -132,7 +224,6 @@
-
diff --git a/decimal to binary b/decimal to binary.py
similarity index 100%
rename from decimal to binary
rename to decimal to binary.py
diff --git a/coronacases.py b/depreciated_programs/corona_cases.py
similarity index 98%
rename from coronacases.py
rename to depreciated_programs/corona_cases.py
index b06d15ca97f..e93e7cd99f9 100644
--- a/coronacases.py
+++ b/depreciated_programs/corona_cases.py
@@ -43,7 +43,7 @@ def world():
print(world)
-def indiac():
+def india():
cases = f"""
██╗███╗░░██╗██████╗░██╗░█████╗░
██║████╗░██║██╔══██╗██║██╔══██╗
@@ -53,7 +53,7 @@ def indiac():
╚═╝╚═╝░░╚══╝╚═════╝░╚═╝╚═╝░░╚═╝
Country Name :- {name}
-New Confirmed Cases :- {indiaconfirmed}
+New Confirmed Cases :- {indiaonfirmed}
Total Confirmed Cases :- {indiatotal}
New Deaths :- {indiaDeaths}
Total Deaths :- {deathstotal}
@@ -86,7 +86,7 @@ def choices():
sleep(1)
choices()
elif choice == "2":
- indiac()
+ india()
sleep(1)
choices()
else:
diff --git a/encrypter-decrypter-gui.py b/encrypter-decrypter-gui.py
index ea46ea95bb9..75d10d37839 100644
--- a/encrypter-decrypter-gui.py
+++ b/encrypter-decrypter-gui.py
@@ -34,6 +34,32 @@ def __init__(self, parent):
self.parent = parent
# ========== Data Key ==========
self.data_dic = {
+ "A": "Q",
+ "B": "W",
+ "C": "E",
+ "D": "R",
+ "E": "T",
+ "F": "Y",
+ "G": "U",
+ "H": "I",
+ "I": "O",
+ "J": "P",
+ "K": "A",
+ "L": "S",
+ "M": "D",
+ "N": "F",
+ "O": "G",
+ "P": "H",
+ "Q": "J",
+ "R": "K",
+ "S": "L",
+ "T": "Z",
+ "U": "X",
+ "V": "C",
+ "W": "V",
+ "X": "B",
+ "Y": "N",
+ "Z": "M",
"a": "q",
"b": "w",
"c": "e",
@@ -199,7 +225,7 @@ def backend_work(self, todo, text_coming):
try:
text_coming = str(
text_coming
- ).lower() # <----- Lowering the letters as dic in lower letter
+ ) # <----- Lowering the letters as dic in lower letter
for word in text_coming:
for key, value in self.data_dic.items():
if word == key:
@@ -212,7 +238,7 @@ def backend_work(self, todo, text_coming):
return text_to_return
elif todo == "Decrypt":
try:
- text_coming = str(text_coming).lower()
+ text_coming = str(text_coming)
for word in text_coming:
for key, value in self.data_dic.items():
if word == value:
diff --git a/encrypter_decrypter_gui.py b/encrypter_decrypter_gui.py
new file mode 100644
index 00000000000..75d10d37839
--- /dev/null
+++ b/encrypter_decrypter_gui.py
@@ -0,0 +1,263 @@
+# ==================== Importing Libraries ====================
+# =============================================================
+import tkinter as tk
+from tkinter import ttk
+from tkinter.messagebox import showerror
+from tkinter.scrolledtext import ScrolledText
+
+# =============================================================
+
+
+class Main(tk.Tk):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.title("Alphacrypter")
+ # ----- Setting Geometry -----
+ self.geometry_settings()
+
+ def geometry_settings(self):
+ _com_scr_w = self.winfo_screenwidth()
+ _com_scr_h = self.winfo_screenheight()
+ _my_w = 300
+ _my_h = 450
+ # ----- Now Getting X and Y Coordinates
+ _x = int(_com_scr_w / 2 - _my_w / 2)
+ _y = int(_com_scr_h / 2 - _my_h / 2)
+ _geo_string = str(_my_w) + "x" + str(_my_h) + "+" + str(_x) + "+" + str(_y)
+ self.geometry(_geo_string)
+ # ----- Geometry Setting Completed Now Disabling Resize Screen Button -----
+ self.resizable(width=False, height=False)
+
+
+class Notebook:
+ def __init__(self, parent):
+ self.parent = parent
+ # ========== Data Key ==========
+ self.data_dic = {
+ "A": "Q",
+ "B": "W",
+ "C": "E",
+ "D": "R",
+ "E": "T",
+ "F": "Y",
+ "G": "U",
+ "H": "I",
+ "I": "O",
+ "J": "P",
+ "K": "A",
+ "L": "S",
+ "M": "D",
+ "N": "F",
+ "O": "G",
+ "P": "H",
+ "Q": "J",
+ "R": "K",
+ "S": "L",
+ "T": "Z",
+ "U": "X",
+ "V": "C",
+ "W": "V",
+ "X": "B",
+ "Y": "N",
+ "Z": "M",
+ "a": "q",
+ "b": "w",
+ "c": "e",
+ "d": "r",
+ "e": "t",
+ "f": "y",
+ "g": "u",
+ "h": "i",
+ "i": "o",
+ "j": "p",
+ "k": "a",
+ "l": "s",
+ "m": "d",
+ "n": "f",
+ "o": "g",
+ "p": "h",
+ "q": "j",
+ "r": "k",
+ "s": "l",
+ "t": "z",
+ "u": "x",
+ "v": "c",
+ "w": "v",
+ "x": "b",
+ "y": "n",
+ "z": "m",
+ "1": "_",
+ "2": "-",
+ "3": "|",
+ "4": "?",
+ "5": "*",
+ "6": "!",
+ "7": "@",
+ "8": "#",
+ "9": "$",
+ "0": "~",
+ ".": "/",
+ ",": "+",
+ " ": "&",
+ }
+ # ==============================
+ # ----- Notebook With Two Pages -----
+ self.nb = ttk.Notebook(self.parent)
+ self.page1 = ttk.Frame(self.nb)
+ self.page2 = ttk.Frame(self.nb)
+ self.nb.add(self.page1, text="Encrypt The Words")
+ self.nb.add(self.page2, text="Decrypt The Words")
+ self.nb.pack(expand=True, fill="both")
+ # ----- LabelFrames -----
+ self.page1_main_label = ttk.LabelFrame(
+ self.page1, text="Encrypt Any Text"
+ ) # <----- Page1 LabelFrame1
+ self.page1_main_label.grid(row=0, column=0, pady=20, padx=2, ipadx=20)
+ self.page1_output_label = ttk.LabelFrame(self.page1, text="Decrypted Text")
+ self.page1_output_label.grid(row=1, column=0, pady=10, padx=2)
+
+ self.page2_main_label = ttk.LabelFrame(
+ self.page2, text="Decrypt Any Text"
+ ) # <----- Page1 LabelFrame1
+ self.page2_main_label.grid(row=0, column=0, pady=20, padx=2, ipadx=20)
+ self.page2_output_label = ttk.LabelFrame(self.page2, text="Real Text")
+ self.page2_output_label.grid(row=1, column=0, pady=10, padx=2)
+ # <---Scrolled Text Global
+ self.decrypted_text_box = ScrolledText(
+ self.page1_output_label, width=30, height=5, state="normal"
+ )
+ self.decrypted_text_box.grid(row=1, column=0, padx=2, pady=10)
+
+ self.text_box = ScrolledText(
+ self.page2_output_label, width=30, height=5, state="normal"
+ )
+ self.text_box.grid(row=1, column=0, padx=2, pady=10)
+ # ----- Variables -----
+ self.user_text = tk.StringVar()
+ self.decrypted_user_text = tk.StringVar()
+
+ self.user_text2 = tk.StringVar()
+ self.real_text = tk.StringVar()
+ # ----- Getting Inside Page1 -----
+ self.page1_inside()
+ self.page2_inside()
+
+ def page1_inside(self):
+ style = ttk.Style()
+ user_text_label = ttk.Label(
+ self.page1_main_label, text="Enter Your Text Here : ", font=("", 14)
+ )
+ user_text_label.grid(row=0, column=0, pady=10)
+ user_entry_box = ttk.Entry(
+ self.page1_main_label, width=35, textvariable=self.user_text
+ )
+ user_entry_box.grid(row=1, column=0)
+ style.configure(
+ "TButton",
+ foreground="black",
+ background="white",
+ relief="groove",
+ font=("", 12),
+ )
+ encrypt_btn = ttk.Button(
+ self.page1_main_label,
+ text="Encrypt Text",
+ style="TButton",
+ command=self.encrypt_now,
+ )
+ encrypt_btn.grid(row=2, column=0, pady=15)
+
+ # ---------- Page1 Button Binding Function ----------
+
+ def encrypt_now(self):
+ user_text = self.user_text.get()
+ if user_text == "":
+ showerror(
+ "Nothing Found", "Please Enter Something In Entry Box To Encrypt...!"
+ )
+ return
+ else:
+ self.decrypted_user_text = self.backend_work("Encrypt", user_text)
+ self.decrypted_text_box.insert(tk.INSERT, self.decrypted_user_text, tk.END)
+
+ # --------------------------------------------------Binding Functions of Page1 End Here
+ # Page2 ------------------>
+ def page2_inside(self):
+ style = ttk.Style()
+ user_text_label = ttk.Label(
+ self.page2_main_label, text="Enter Decrypted Text Here : ", font=("", 14)
+ )
+ user_text_label.grid(row=0, column=0, pady=10)
+ user_entry_box = ttk.Entry(
+ self.page2_main_label, width=35, textvariable=self.user_text2
+ )
+ user_entry_box.grid(row=1, column=0)
+ style.configure(
+ "TButton",
+ foreground="black",
+ background="white",
+ relief="groove",
+ font=("", 12),
+ )
+ encrypt_btn = ttk.Button(
+ self.page2_main_label,
+ text="Decrypt Text",
+ style="TButton",
+ command=self.decrypt_now,
+ )
+ encrypt_btn.grid(row=2, column=0, pady=15)
+ # ---------- Page1 Button Binding Function ----------
+
+ def decrypt_now(self):
+ user_text = self.user_text2.get()
+ if user_text == "":
+ showerror(
+ "Nothing Found", "Please Enter Something In Entry Box To Encrypt...!"
+ )
+ return
+ else:
+ self.real_text = self.backend_work("Decrypt", user_text)
+ self.text_box.insert(tk.INSERT, self.real_text, tk.END)
+
+ def backend_work(self, todo, text_coming):
+ text_to_return = ""
+ if todo == "Encrypt":
+ try:
+ text_coming = str(
+ text_coming
+ ) # <----- Lowering the letters as dic in lower letter
+ for word in text_coming:
+ for key, value in self.data_dic.items():
+ if word == key:
+ # print(word, " : ", key)
+ text_to_return += value
+
+ except ValueError:
+ showerror("Unknown", "Something Went Wrong, Please Restart Application")
+
+ return text_to_return
+ elif todo == "Decrypt":
+ try:
+ text_coming = str(text_coming)
+ for word in text_coming:
+ for key, value in self.data_dic.items():
+ if word == value:
+ text_to_return += key
+
+ except ValueError:
+ showerror("Unknown", "Something Went Wrong, Please Restart Application")
+
+ return text_to_return
+
+ else:
+ showerror("No Function", "Function Could not get what to do...!")
+
+
+# =============================================================
+# ==================== Classes End Here ... ! =================
+
+
+if __name__ == "__main__":
+ run = Main()
+ Notebook(run)
+ run.mainloop()
diff --git a/environment.yml b/environment.yml
new file mode 100644
index 00000000000..a290a698a55
Binary files /dev/null and b/environment.yml differ
diff --git a/even and odd.py b/even and odd.py
deleted file mode 100644
index 7ac6bae114b..00000000000
--- a/even and odd.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Python program to check if the input number is odd or even.
-# A number is even if division by 2 gives a remainder of 0.
-# If the remainder is 1, it is an odd number.
-
-num = int(input("Enter a number: "))
-if (num % 2) == 0:
- print("{0} is Even".format(num))
-else:
- print("{0} is Odd".format(num))
diff --git a/even.py b/even.py
deleted file mode 100644
index 2faafbc3818..00000000000
--- a/even.py
+++ /dev/null
@@ -1,5 +0,0 @@
-num = int(input("Enter a number: "))
-if (num % 2) == 0:
- print("{0} is Even".format(num))
-else:
- print("{0} is Odd".format(num))
diff --git a/example.txt b/example.txt
new file mode 100644
index 00000000000..cb511a2b55e
--- /dev/null
+++ b/example.txt
@@ -0,0 +1 @@
+Change from feature-branch
diff --git a/fF b/fF
new file mode 100644
index 00000000000..2edac5d9f5d
--- /dev/null
+++ b/fF
@@ -0,0 +1,43 @@
+# Script Name : folder_size.py
+# Author : Craig Richards (Simplified by Assistant)
+# Created : 19th July 2012
+# Last Modified : 19th December 2024
+# Version : 2.0.0
+
+# Description : Scans a directory and subdirectories to display the total size.
+
+import os
+import sys
+
+def get_folder_size(directory):
+ """Calculate the total size of a directory and its subdirectories."""
+ total_size = 0
+ for root, _, files in os.walk(directory):
+ for file in files:
+ total_size += os.path.getsize(os.path.join(root, file))
+ return total_size
+
+def format_size(size):
+ """Format the size into human-readable units."""
+ units = ["Bytes", "KB", "MB", "GB", "TB"]
+ for unit in units:
+ if size < 1024 or unit == units[-1]:
+ return f"{size:.2f} {unit}"
+ size /= 1024
+
+def main():
+ if len(sys.argv) < 2:
+ print("Usage: python folder_size.py ")
+ sys.exit(1)
+
+ directory = sys.argv[1]
+
+ if not os.path.exists(directory):
+ print(f"Error: The directory '{directory}' does not exist.")
+ sys.exit(1)
+
+ folder_size = get_folder_size(directory)
+ print(f"Folder Size: {format_size(folder_size)}")
+
+if __name__ == "__main__":
+ main()
diff --git a/factor.py b/factor.py
deleted file mode 100644
index 2e17bec367f..00000000000
--- a/factor.py
+++ /dev/null
@@ -1,9 +0,0 @@
-def factorial(n):
- if n == 0:
- return 1
- else:
- return n * factorial(n - 1)
-
-
-n = int(input("Input a number to compute the factiorial : "))
-print(factorial(n))
diff --git a/fibonacci_SIMPLIFIED b/fibonacci_SIMPLIFIED
new file mode 100644
index 00000000000..77f6854050f
--- /dev/null
+++ b/fibonacci_SIMPLIFIED
@@ -0,0 +1,10 @@
+
+#printing fibonnaci series till nth element - simplified version for begginers
+def print_fibonacci(n):
+ current_no = 1
+ prev_no = 0
+ for i in range(n):
+ print(current_no, end = " ")
+ prev_no,current_no = current_no, current_no + prev_no
+
+print_fibonacci(10)
diff --git a/file_ext_changer.py b/file_ext_changer.py
new file mode 100644
index 00000000000..4d80261b052
--- /dev/null
+++ b/file_ext_changer.py
@@ -0,0 +1,129 @@
+'''' Multiple extension changer'''
+import time
+from pathlib import Path as p
+import random as rand
+import hashlib
+
+
+def chxten_(files, xten):
+ chfile = []
+ for file in files:
+ ch_file = file.split('.')
+ ch_file = ch_file[0]
+ chfile.append(ch_file)
+ if len(xten) == len(chfile):
+ chxten = []
+ for i in range(len(chfile)):
+ ch_xten = chfile[i] + xten[i]
+ chxten.append(ch_xten)
+ elif len(xten) < len(chfile) and len(xten) != 1:
+ chxten = []
+ for i in range(len(xten)):
+ ch_xten = chfile[i] + xten[i]
+ chxten.append(ch_xten)
+ for i in range(1, (len(chfile) + 1) - len(xten)):
+ ch_xten = chfile[- + i] + xten[-1]
+ chxten.append(ch_xten)
+ elif len(xten) == 1:
+ chxten = []
+ for i in range(len(chfile)):
+ ch_xten = chfile[i] + xten[0]
+ chxten.append(ch_xten)
+ elif len(xten) > len(chfile):
+ chxten = []
+ for i in range(1, (len(xten) + 1) - len(chfile)):
+ f = p(files[-i])
+ p.touch(chfile[-i] + xten[-1])
+ new = f.read_bytes()
+ p(chfile[-i] + xten[-1]).write_bytes(new)
+ for i in range(len(chfile)):
+ ch_xten = chfile[i] + xten[i]
+ chxten.append(ch_xten)
+ else:
+ return 'an error occured'
+ return chxten
+
+
+# End of function definitions
+# Beggining of execution of code
+#password
+password = input('Enter password:')
+
+password = password.encode()
+
+password = hashlib.sha512(password).hexdigest()
+if password == 'c99d3d8f321ff63c2f4aaec6f96f8df740efa2dc5f98fccdbbb503627fd69a9084073574ee4df2b888f9fe2ed90e29002c318be476bb62dabf8386a607db06c4':
+ pass
+else:
+ print('wrong password!')
+ time.sleep(0.3)
+ exit(404)
+files = input('Enter file names and thier extensions (seperated by commas):')
+xten = input('Enter Xtensions to change with (seperated by commas):')
+
+if files == '*':
+ pw = p.cwd()
+ files = ''
+ for i in pw.iterdir():
+ if not p.is_dir(i):
+ i = str(i)
+ if not i.endswith('.py'):
+ # if not i.endswith('exe'):
+ if not i.endswith('.log'):
+ files = files + i + ','
+if files == 'r':
+ pw = p.cwd()
+ files = ''
+ filer = []
+ for i in pw.iterdir():
+ if p.is_file(i):
+ i = str(i)
+ if not i.endswith('.py'):
+ if not i.endswith('.exe'):
+ if not i.endswith('.log'):
+ filer.append(i)
+ for i in range(5):
+ pos = rand.randint(0,len(filer))
+ files = files + filer[pos] + ','
+
+ print(files)
+files = files.split(',')
+xten = xten.split(',')
+
+# Validation
+for file in files:
+ check = p(file).exists()
+ if check == False:
+ print(f'{file} is not found. Paste this file in the directory of {file}')
+ files.remove(file)
+# Ended validation
+
+count = len(files)
+chxten = chxten_(files, xten)
+
+# Error Handlings
+if chxten == 'an error occured':
+ print('Check your inputs correctly')
+ time.sleep(1)
+ exit(404)
+else:
+ try:
+ for i in range(len(files)):
+ f = p(files[i])
+ f.rename(chxten[i])
+ print('All files has been changed')
+ except PermissionError:
+ pass
+ except FileNotFoundError:
+ # Validation
+ for file in files:
+ check = p(file).exists()
+ if check == False:
+ print(f'{file} is not found. Paste this file in the directory of {file}')
+ files.remove(file)
+ # except Exception:
+ # print('An Error Has Occured in exception')
+ # time.sleep(1)
+ # exit(404)
+
+# last modified 3:25PM 12/12/2023 (DD/MM/YYYY)
diff --git a/find_cube_root.py b/find_cube_root.py
index cf315708a25..667f7fa0f2d 100644
--- a/find_cube_root.py
+++ b/find_cube_root.py
@@ -19,12 +19,12 @@ def cubeRoot():
cubeRoot()
-cont = str(input("Would you like to continue: "))
-while cont == "yes":
+cont = input("Would you like to continue: ")
+while cont == "yes" or "y":
cubeRoot()
- cont = str(input("Would you like to continue: "))
- if cont == "no":
+ cont = input("Would you like to continue: ")
+ if cont == "no" or "n":
exit()
else:
print("Enter a correct answer(yes or no)")
- cont = str(input("Would you like to continue: "))
+ cont = input("Would you like to continue: ")
diff --git a/gcd.py b/gcd.py
index 0f10da082d7..b496dca1d20 100644
--- a/gcd.py
+++ b/gcd.py
@@ -6,6 +6,7 @@
b = int(input("Enter number 2 (b): "))
i = 1
+gcd=-1
while i <= a and i <= b:
if a % i == 0 and b % i == 0:
gcd = i
diff --git a/gstin_scraper.py b/gstin_scraper.py
new file mode 100644
index 00000000000..4f55ca6de30
--- /dev/null
+++ b/gstin_scraper.py
@@ -0,0 +1,76 @@
+from bs4 import BeautifulSoup
+import requests
+import time
+
+# Script Name : gstin_scraper.py
+# Author : Purshotam
+# Created : Sep 6, 2021 7:59 PM
+# Last Modified : Oct 3, 2023 6:28 PM
+# Version : 1.0
+# Modifications :
+""" Description :
+GSTIN, short for Goods and Services Tax Identification Number,
+is a unique 15 digit identification number assigned to every taxpayer
+(primarily dealer or supplier or any business entity) registered under the GST regime.
+This script is able to fetch GSTIN numbers for any company registered in the
+Mumbai / Banglore region.
+"""
+
+
+# Using a demo list in case of testing the script.
+# This list will be used in case user skips "company input" dialogue by pressing enter.
+demo_companies = ["Bank of Baroda", "Trident Limited", "Reliance Limited", "The Yummy Treat", "Yes Bank", "Mumbai Mineral Trading Corporation"]
+
+def get_company_list():
+ company_list = []
+
+ while True:
+ company = input("Enter a company name (or press Enter to finish): ")
+ if not company:
+ break
+ company_list.append(company)
+
+ return company_list
+
+def fetch_gstins(company_name, csrf_token):
+ third_party_gstin_site = "https://www.knowyourgst.com/gst-number-search/by-name-pan/"
+ payload = {'gstnum': company_name, 'csrfmiddlewaretoken': csrf_token}
+
+ # Getting the HTML content and extracting the GSTIN content using BeautifulSoup.
+ html_content = requests.post(third_party_gstin_site, data=payload)
+ soup = BeautifulSoup(html_content.text, 'html.parser')
+ site_results = soup.find_all(id="searchresult")
+
+ # Extracting GSTIN specific values from child elements.
+ gstins = [result.strong.next_sibling.next_sibling.string for result in site_results]
+
+ return gstins
+
+def main():
+ temp = get_company_list()
+ companies = temp if temp else demo_companies
+
+ all_gstin_data = ""
+ third_party_gstin_site = "https://www.knowyourgst.com/gst-number-search/by-name-pan/"
+
+ # Getting the CSRF value for further RESTful calls.
+ page_with_csrf = requests.get(third_party_gstin_site)
+ soup = BeautifulSoup(page_with_csrf.text, 'html.parser')
+ csrf_token = soup.find('input', {"name": "csrfmiddlewaretoken"})['value']
+
+ for company in companies:
+ gstins = fetch_gstins(company, csrf_token)
+
+ # Only include GSTINs for Bengaluru and Mumbai-based companies
+ comma_separated_gstins = ', '.join([g for g in gstins if g.startswith(('27', '29'))])
+
+ all_gstin_data += f"{company} = {comma_separated_gstins}\n\n"
+
+ # Delaying for false DDOS alerts on the third-party site
+ time.sleep(0.5)
+
+ # Printing the data
+ print(all_gstin_data)
+
+if __name__ == "__main__":
+ main()
diff --git a/hamming-numbers b/hamming-numbers
new file mode 100644
index 00000000000..c9f81deb7f6
--- /dev/null
+++ b/hamming-numbers
@@ -0,0 +1,51 @@
+"""
+A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some
+non-negative integers i, j, and k. They are often referred to as regular numbers.
+The first 20 Hamming numbers are: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, and 36
+"""
+
+
+def hamming(n_element: int) -> list:
+ """
+ This function creates an ordered list of n length as requested, and afterwards
+ returns the last value of the list. It must be given a positive integer.
+
+ :param n_element: The number of elements on the list
+ :return: The nth element of the list
+
+ >>> hamming(5)
+ [1, 2, 3, 4, 5]
+ >>> hamming(10)
+ [1, 2, 3, 4, 5, 6, 8, 9, 10, 12]
+ >>> hamming(15)
+ [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
+ """
+ n_element = int(n_element)
+ if n_element < 1:
+ my_error = ValueError("a should be a positive number")
+ raise my_error
+
+ hamming_list = [1]
+ i, j, k = (0, 0, 0)
+ index = 1
+ while index < n_element:
+ while hamming_list[i] * 2 <= hamming_list[-1]:
+ i += 1
+ while hamming_list[j] * 3 <= hamming_list[-1]:
+ j += 1
+ while hamming_list[k] * 5 <= hamming_list[-1]:
+ k += 1
+ hamming_list.append(
+ min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5)
+ )
+ index += 1
+ return hamming_list
+
+
+if __name__ == "__main__":
+ n = input("Enter the last number (nth term) of the Hamming Number Series: ")
+ print("Formula of Hamming Number Series => 2^i * 3^j * 5^k")
+ hamming_numbers = hamming(int(n))
+ print("-----------------------------------------------------")
+ print(f"The list with nth numbers is: {hamming_numbers}")
+ print("-----------------------------------------------------")
diff --git a/index.html b/index.html
new file mode 100644
index 00000000000..8b137891791
--- /dev/null
+++ b/index.html
@@ -0,0 +1 @@
+
diff --git a/index.py b/index.py
new file mode 100644
index 00000000000..b89d747b62d
--- /dev/null
+++ b/index.py
@@ -0,0 +1,16 @@
+num = 11
+#Negative numbers, 0 and 1 are not primes
+if num > 1:
+
+ # Iterate from 2 to n // 2
+ for i in range(2, (num//2)+1):
+
+ # If num is divisible by any number between
+ #2 and n / 2, it is not prime
+ if (num % i) == 0:
+ print(num, "is not a prime number")
+ break
+ else:
+ print(num, "is a prime number")
+else:
+ print(num, "is not a prime number")
diff --git a/is_number.py b/is_number.py
new file mode 100644
index 00000000000..5dcd98f9eb1
--- /dev/null
+++ b/is_number.py
@@ -0,0 +1,33 @@
+# importing the module to check for all kinds of numbers truthiness in python.
+import numbers
+from math import pow
+from typing import Any
+
+# Assign values to author and version.
+__author__ = "Nitkarsh Chourasia"
+__version__ = "1.0.0"
+__date__ = "2023-08-24"
+
+
+def check_number(input_value: Any) -> str:
+ """Check if input is a number of any kind or not."""
+
+ if isinstance(input_value, numbers.Number):
+ return f"{input_value} is a number."
+ else:
+ return f"{input_value} is not a number."
+
+
+if __name__ == "__main__":
+ print(f"Author: {__author__}")
+ print(f"Version: {__version__}")
+ print(f"Function Documentation: {check_number.__doc__}")
+ print(f"Date: {__date__}")
+
+ print() # Just inserting a new blank line.
+
+ print(check_number(100))
+ print(check_number(0))
+ print(check_number(pow(10, 20)))
+ print(check_number("Hello"))
+ print(check_number(1 + 2j))
diff --git a/kilo_to_miles.py b/kilo_to_miles.py
new file mode 100644
index 00000000000..ff33cd208c5
--- /dev/null
+++ b/kilo_to_miles.py
@@ -0,0 +1,4 @@
+user= float(input("enter kilometers here.. "))
+miles= user*0.621371
+print(f"{user} kilometers equals to {miles:.2f} miles")
+
diff --git a/large_files_reading.py b/large_files_reading.py
new file mode 100644
index 00000000000..a5ce0936f8a
--- /dev/null
+++ b/large_files_reading.py
@@ -0,0 +1,4 @@
+with open("new_project.txt", "r" , encoding="utf-8") as file: # replace "largefile.text" with your actual file name or with absoulte path
+# encoding = "utf-8" is especially used when the file contains special characters....
+ for f in file:
+ print(f.strip())
diff --git a/linear_search.py b/linear_search.py
index d8776a12c09..a4cb39f9cdb 100644
--- a/linear_search.py
+++ b/linear_search.py
@@ -1,17 +1,11 @@
-list = []
num = int(input("Enter size of list: \t"))
-for n in range(num):
- numbers = int(input("Enter any number: \t"))
- list.append(numbers)
+list = [int(input("Enter any number: \t")) for _ in range(num)]
x = int(input("\nEnter number to search: \t"))
-found = False
-
-for i in range(len(list)):
- if list[i] == x:
- found = True
- print("\n%d found at position %d" % (x, i))
- break
-if not found:
- print("\n%d is not in list" % x)
+for position, number in enumerate(list):
+ if number == x:
+ print(f"\n{x} found at position {position}")
+else:
+ print(f"list: {list}")
+ print(f"{x} is not in list")
\ No newline at end of file
diff --git a/login.py b/login.py
index 791c1d94247..8095f4f4e54 100644
--- a/login.py
+++ b/login.py
@@ -20,7 +20,7 @@ def logo():
print("\033[1;36;49m")
-# This is Login Funtion
+# This is Login Function
def login():
# for clear the screen
os.system("clear")
diff --git a/loops.py b/loops.py
new file mode 100644
index 00000000000..50d4ac6ef7b
--- /dev/null
+++ b/loops.py
@@ -0,0 +1,40 @@
+# 2 loops
+
+# for loop:
+
+"""
+Syntax..
+-> "range" : starts with 0.
+-> The space after the space is called as identiation, python generally identifies the block of code with the help of indentation,
+indentation is generally 4 spaces / 1 tab space..
+
+
+for in range():
+ statements you want to execute
+
+for in :
+ print()
+To print the list / or any iterator items
+
+"""
+
+# 1. for with range...
+for i in range(3):
+ print("Hello... with range")
+ # prints Hello 3 times..
+
+# 2.for with list
+
+l1=[1,2,3,78,98,56,52]
+for i in l1:
+ print("list items",i)
+ # prints list items one by one....
+
+for i in "ABC":
+ print(i)
+
+# while loop:
+i=0
+while i<=5:
+ print("hello.. with while")
+ i+=1
\ No newline at end of file
diff --git a/love_turtle.py b/love_turtle.py
index 82e0217205b..238b3eebf80 100644
--- a/love_turtle.py
+++ b/love_turtle.py
@@ -1,20 +1,28 @@
import turtle
-t = turtle.Turtle()
-turtle.title("I Love You")
-screen = turtle.Screen()
-screen.bgcolor("white")
-t.color("red")
-t.begin_fill()
-t.fillcolor("black")
-
-t.left(140)
-t.forward(180)
-t.circle(-90, 200)
-
-t.setheading(60) # t.left
-t.circle(-90, 200)
-t.forward(180)
-
-t.end_fill()
-t.hideturtle()
+
+def heart_red():
+ t = turtle.Turtle()
+ turtle.title("I Love You")
+ screen = turtle.Screen()
+ screen.bgcolor("white")
+ t.color("red")
+ t.begin_fill()
+ t.fillcolor("red")
+
+ t.left(140)
+ t.forward(180)
+ t.circle(-90, 200)
+
+ t.setheading(60) # t.left
+ t.circle(-90, 200)
+ t.forward(180)
+
+ t.end_fill()
+ t.hideturtle()
+
+ turtle.done()
+
+
+if __name__ == "__main__":
+ heart_red()
diff --git a/luhn_algorithm_for_credit_card_validation.py b/luhn_algorithm_for_credit_card_validation.py
new file mode 100644
index 00000000000..7eac88701f8
--- /dev/null
+++ b/luhn_algorithm_for_credit_card_validation.py
@@ -0,0 +1,41 @@
+"""
+The Luhn Algorithm is widely used for error-checking in various applications, such as verifying credit card numbers.
+
+By building this project, you'll gain experience working with numerical computations and string manipulation.
+
+"""
+
+# TODO: To make it much more better and succint
+
+
+def verify_card_number(card_number):
+ sum_of_odd_digits = 0
+ card_number_reversed = card_number[::-1]
+ odd_digits = card_number_reversed[::2]
+
+ for digit in odd_digits:
+ sum_of_odd_digits += int(digit)
+
+ sum_of_even_digits = 0
+ even_digits = card_number_reversed[1::2]
+ for digit in even_digits:
+ number = int(digit) * 2
+ if number >= 10:
+ number = (number // 10) + (number % 10)
+ sum_of_even_digits += number
+ total = sum_of_odd_digits + sum_of_even_digits
+ return total % 10 == 0
+
+
+def main():
+ card_number = "4111-1111-4555-1142"
+ card_translation = str.maketrans({"-": "", " ": ""})
+ translated_card_number = card_number.translate(card_translation)
+
+ if verify_card_number(translated_card_number):
+ print("VALID!")
+ else:
+ print("INVALID!")
+
+
+main()
diff --git a/magic8ball.py b/magic8ball.py
index 1ce9dc39a69..816705b8e21 100644
--- a/magic8ball.py
+++ b/magic8ball.py
@@ -1,49 +1,63 @@
import random
+from colorama import Fore, Style
+import inquirer
responses = [
"It is certain",
"It is decidedly so",
"Without a doubt",
- "Yes definitely ",
+ "Yes definitely",
"You may rely on it",
"As I see it, yes",
- "Most likely ",
+ "Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Do not count on it",
"My reply is no",
- " My sources say no",
- " Outlook not so good",
+ "My sources say no",
+ "Outlook not so good",
"Very doubtful",
"Reply hazy try again",
"Ask again later",
- "Better not tell you now ",
- "Cannot predict now ",
+ "Better not tell you now",
+ "Cannot predict now",
"Concentrate and ask again",
]
-print("Hi! I am the magic 8 ball, what's your name?")
-name = input()
-print("Hello!" + name)
-
-
-def magic8Ball():
- print("Whay's your question? ")
- question = input()
- answer = responses[random.randint(0, len(responses) - 1)]
- print(answer)
- tryAgain()
-
-
-def tryAgain():
- print(
- "Do you wanna ask any more questions? press Y for yes and any other key to exit "
- )
- x = input()
- if x in ["Y", "y"]:
- magic8Ball()
+
+
+# Will use a class on it.
+# Will try to make it much more better.
+def get_user_name():
+ return inquirer.text(
+ message="Hi! I am the magic 8 ball, what's your name?"
+ ).execute()
+
+
+def display_greeting(name):
+ print(f"Hello, {name}!")
+
+
+def magic_8_ball():
+ question = inquirer.text(message="What's your question?").execute()
+ answer = random.choice(responses)
+ print(Fore.BLUE + Style.BRIGHT + answer + Style.RESET_ALL)
+ try_again()
+
+
+def try_again():
+ response = inquirer.list_input(
+ message="Do you want to ask more questions?",
+ choices=["Yes", "No"],
+ ).execute()
+
+ if response.lower() == "yes":
+ magic_8_ball()
else:
exit()
-magic8Ball()
+if __name__ == "__main__":
+ user_name = get_user_name()
+ display_greeting(user_name)
+ magic_8_ball()
diff --git a/magic_8_ball.py b/magic_8_ball.py
new file mode 100644
index 00000000000..816705b8e21
--- /dev/null
+++ b/magic_8_ball.py
@@ -0,0 +1,63 @@
+import random
+from colorama import Fore, Style
+import inquirer
+
+responses = [
+ "It is certain",
+ "It is decidedly so",
+ "Without a doubt",
+ "Yes definitely",
+ "You may rely on it",
+ "As I see it, yes",
+ "Most likely",
+ "Outlook good",
+ "Yes",
+ "Signs point to yes",
+ "Do not count on it",
+ "My reply is no",
+ "My sources say no",
+ "Outlook not so good",
+ "Very doubtful",
+ "Reply hazy try again",
+ "Ask again later",
+ "Better not tell you now",
+ "Cannot predict now",
+ "Concentrate and ask again",
+]
+
+
+# Will use a class on it.
+# Will try to make it much more better.
+def get_user_name():
+ return inquirer.text(
+ message="Hi! I am the magic 8 ball, what's your name?"
+ ).execute()
+
+
+def display_greeting(name):
+ print(f"Hello, {name}!")
+
+
+def magic_8_ball():
+ question = inquirer.text(message="What's your question?").execute()
+ answer = random.choice(responses)
+ print(Fore.BLUE + Style.BRIGHT + answer + Style.RESET_ALL)
+ try_again()
+
+
+def try_again():
+ response = inquirer.list_input(
+ message="Do you want to ask more questions?",
+ choices=["Yes", "No"],
+ ).execute()
+
+ if response.lower() == "yes":
+ magic_8_ball()
+ else:
+ exit()
+
+
+if __name__ == "__main__":
+ user_name = get_user_name()
+ display_greeting(user_name)
+ magic_8_ball()
diff --git a/main.py b/main.py
deleted file mode 100644
index 7eeb1845114..00000000000
--- a/main.py
+++ /dev/null
@@ -1,17 +0,0 @@
-""" patient_name = "john smith"
-age = 20
-is_patient_name = True
-print(patient_name) """
-
-""" word = input("Why are you unemployed")
-print("Due to lack of " +word) """
-
-"""a = input("Enter 1st Number:")
-b = input("Enter 2nd Number:")
-sum = float (a) + int (b)
-print(sum)
-"""
-student = "ANKITASDFAHBVGASDNDSDNBFCZCXCNIGL"
-print(student.lower())
-
-print(student.find("ASDF"))
diff --git a/multiple_comditions.py b/multiple_comditions.py
new file mode 100644
index 00000000000..68ebd1f94e5
--- /dev/null
+++ b/multiple_comditions.py
@@ -0,0 +1,22 @@
+while True:
+ try:
+ user = int(input("enter any number b/w 1-3\n"))
+ if user == 1:
+ print("in first if")
+ elif user == 2:
+ print("in second if")
+ elif user ==3:
+ print("in third if")
+ else:
+ print("Enter numbers b/w the range of 1-3")
+ except:
+ print("enter only digits")
+
+
+"""
+## Why we are using elif instead of nested if ?
+When you have multiple conditions to check, using nested if means that if the first condition is true, the program still checks the second
+if condition, even though it's already decided that the first condition worked. This makes the program do more work than necessary.
+On the other hand, when you use elif, if one condition is satisfied, the program exits the rest of the conditions and doesn't continue checking.
+It’s more efficient and clean, as it immediately moves to the correct option without unnecessary steps.
+"""
\ No newline at end of file
diff --git a/new.py b/new.py
index 9df00e5faaa..5a5f623242c 100644
--- a/new.py
+++ b/new.py
@@ -1,137 +1,9 @@
-"""
-a simple terminal program to find new about certain topic by web scraping site.
-site used :
-1. Times of India,
- link : https://timesofindia.indiatimes.com/india/
-2. India's Today,
- link : https://www.indiatoday.in/topic/
-"""
-
-import requests
-from bs4 import BeautifulSoup
-import webbrowser
-import time
-
-
-def Times_of_India(userInput, ua):
- bold_start = "\033[1m"
- bold_end = "\033[0m"
-
- url = "https://timesofindia.indiatimes.com/india/"
- url += userInput
-
- res = requests.post(url, headers=ua)
- soup = BeautifulSoup(res.content, "html.parser")
- data = soup.find_all(class_="w_tle")
-
- if len(data) > 0:
- print("News available :", "\N{slightly smiling face}")
- if len(data) == 0:
- return 0
-
- for item in range(len(data)):
- print(bold_start, "\033[1;32;40m \nNEWS : ", item + 1, bold_end, end=" ")
- data1 = data[item].find("a")
- print(bold_start, data1.get_text(), bold_end)
-
- bol = input("For more details ->(y) (y/n) :: ")
- if bol == "y":
- url += data1.get("href")
- print("%s" % url)
-
- webbrowser.open(url)
-
- return len(data)
-
-
-def india_today(userInput, ua):
- bold_start = "\033[1m"
- bold_end = "\033[0m"
-
- url = "https://www.indiatoday.in/topic/"
- url += userInput
-
- res = requests.get(url, headers=ua)
- soup = BeautifulSoup(res.content, "html.parser")
- data = soup.find_all(class_="field-content")
-
- if len(data) > 0:
- print("\nNews available : ", "\N{slightly smiling face}")
- k = 0
- for i in range(len(data)):
- data1 = data[i].find_all("a")
- for j in range(len(data1)):
- print(bold_start, "\033[1;32;40m\nNEWS ", k + 1, bold_end, end=" : ")
- k += 1
- print(bold_start, data1[j].get_text(), bold_end)
- bol = input("\nFor more details ->(y) (y/n) :: ")
- if bol == "y" or bol == "Y":
- data2 = data[i].find("a")
- url = data2.get("href")
- webbrowser.open(url)
-
- return len(data)
+def hello_world():
+ """
+ Prints a greeting message.
+ """
+ print("Hello, world!")
if __name__ == "__main__":
- import doctest
-
- doctest.testmod()
- bold_start = "\033[1m"
- bold_end = "\033[0m"
- print("\033[5;31;40m")
- print(
- bold_start,
- " HERE YOU WILL GET ALL THE NEWS JUST IN ONE SEARCH ",
- bold_end,
- )
- print("\n")
- localtime = time.asctime(time.localtime(time.time()))
- print(bold_start, localtime, bold_end)
-
- ua = {
- "UserAgent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0"
- }
- print(
- bold_start,
- "\n\033[1;35;40m Search any news (state , city ,Country , AnyThings etc) : ",
- bold_end,
- end=" ",
- )
-
- userInput = input()
-
- print(bold_start, "\033[1;33;40m \n")
- print("Which news channel data would you prefer")
- print("1. Times of india")
- print("2. India's Today", bold_end)
-
- say = int(input())
-
- if say == 1:
- length = Times_of_India(userInput, ua)
- if length == 0:
- print("Sorry Here No News Available", "\N{expressionless face}")
- print("\n")
- print(
- "Would you like to go for India's Today (y/n):: ",
- "\N{thinking face}",
- end=" ",
- )
- speak = input()
- if speak == "y":
- length = india_today(userInput, ua)
- if length == 0:
- print("Sorry No news", "\N{expressionless face}")
- else:
- print("\nThank you", "\U0001f600")
-
- elif say == 2:
- length = india_today(userInput, ua)
-
- if length == 0:
- print("Sorry No news")
- else:
- print("\nThank you", "\U0001f600")
- else:
- print("Sorry", "\N{expressionless face}")
+ hello_world()
diff --git a/new_pattern.py b/new_pattern.py
index e9ebc1c257c..6c5120eb586 100644
--- a/new_pattern.py
+++ b/new_pattern.py
@@ -12,14 +12,14 @@ def main():
lines = int(input("Enter no.of lines: "))
pattern(lines)
-def pattern(lines):
- t = 1
- for i in reversed(range(lines)):
- nxt_pattern = "$"*t
- pattern = "@"*(i+1)
- final_pattern = pattern + " n " + nxt_pattern
- print(final_pattern)
- t = t +1
+def pattern(lines):
+ t = 1
+ for i in range(lines,0,-1):
+ nxt_pattern = "$"*t
+ pattern = "@"*(i)
+ final_pattern = pattern + " " + nxt_pattern
+ print(final_pattern)
+ t = t +1
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/counter_app/counter_app.py b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/counter_app/counter_app.py
new file mode 100644
index 00000000000..df070d92a4e
--- /dev/null
+++ b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/counter_app/counter_app.py
@@ -0,0 +1,69 @@
+# Author: Nitkarsh Chourasia
+# Date created: 28/12/2023
+
+# Import the required libraries
+import tkinter as tk
+from tkinter import ttk
+
+
+class MyApplication:
+ """A class to create a counter app."""
+
+ def __init__(self, master):
+ # Initialize the master window
+ self.master = master
+ # Set the title and geometry of the master window
+ self.master.title("Counter App")
+ self.master.geometry("300x300")
+
+ # Create the widgets
+ self.create_widgets()
+
+ # Create the widgets
+ def create_widgets(self):
+ # Create a frame to hold the widgets
+ frame = ttk.Frame(self.master)
+ # Pack the frame to the master window
+ frame.pack(padx=20, pady=20)
+
+ # Create a label to display the counter
+ self.label = ttk.Label(frame, text="0", font=("Arial Bold", 70))
+ # Grid the label to the frame
+ self.label.grid(row=0, column=0, padx=20, pady=20)
+
+ # Add a button for interaction to increase the counter
+ add_button = ttk.Button(frame, text="Add", command=self.on_add_click)
+ # Grid the button to the frame
+ add_button.grid(row=1, column=0, pady=10)
+
+ # Add a button for interaction to decrease the counter
+ remove_button = ttk.Button(frame, text="Remove", command=self.on_remove_click)
+ # Grid the button to the frame
+ remove_button.grid(row=2, column=0, pady=10)
+
+ # Add a click event handler
+ def on_add_click(self):
+ # Get the current text of the label
+ current_text = self.label.cget("text")
+ # Convert the text to an integer and add 1
+ new_text = int(current_text) + 1
+ # Set the new text to the label
+ self.label.config(text=new_text)
+
+ # Add a click event handler
+ def on_remove_click(self):
+ # Get the current text of the label
+ current_text = self.label.cget("text")
+ # Convert the text to an integer and subtract 1
+ new_text = int(current_text) - 1
+ # Set the new text to the label
+ self.label.config(text=new_text)
+
+
+if __name__ == "__main__":
+ # Create the root window
+ root = tk.Tk()
+ # Create an instance of the application
+ app = MyApplication(root)
+ # Run the app
+ root.mainloop()
diff --git a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/hello_world_excla_increment_app/hello_world_incre_decre_(!).py b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/hello_world_excla_increment_app/hello_world_incre_decre_(!).py
new file mode 100644
index 00000000000..acdd66f44c7
--- /dev/null
+++ b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/hello_world_excla_increment_app/hello_world_incre_decre_(!).py
@@ -0,0 +1,50 @@
+import tkinter as tk
+from tkinter import ttk
+
+
+class MyApplication:
+ def __init__(self, master):
+ self.master = master
+ # Want to understand why .master.title was used?
+ self.master.title("Hello World")
+
+ self.create_widgets()
+
+ def create_widgets(self):
+ frame = ttk.Frame(self.master)
+ frame.pack(padx=20, pady=20)
+ # grid and pack are different geometry managers.
+ self.label = ttk.Label(frame, text="Hello World!", font=("Arial Bold", 50))
+ self.label.grid(row=0, column=0, padx=20, pady=20)
+
+ # Add a button for interaction
+ concat_button = ttk.Button(
+ frame, text="Click Me!", command=self.on_button_click
+ )
+ concat_button.grid(row=1, column=0, pady=10)
+
+ remove_button = ttk.Button(
+ frame, text="Remove '!'", command=self.on_remove_click
+ )
+ remove_button.grid(row=2, column=0, pady=10)
+
+ def on_button_click(self):
+ current_text = self.label.cget("text")
+ # current_text = self.label["text"]
+ #! Solve this.
+ new_text = current_text + "!"
+ self.label.config(text=new_text)
+
+ def on_remove_click(self):
+ # current_text = self.label.cget("text")
+ current_text = self.label["text"]
+ #! Solve this.
+ new_text = current_text[:-1]
+ self.label.config(text=new_text)
+ # TODO: Can make a char matching function, to remove the last char, if it is a '!'.
+
+
+if __name__ == "__main__":
+ root = tk.Tk()
+ app = MyApplication(root)
+ root.mainloop()
diff --git a/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py
new file mode 100644
index 00000000000..6eddf2d6b85
--- /dev/null
+++ b/nitkarshchourasia/to_sort/GUI_apps/tkinter_apps/simple_calc_GUI/simple_calculator_GUI.py
@@ -0,0 +1,431 @@
+from tkinter import *
+
+# To install hupper, use: "pip install hupper"
+# On CMD, or Terminal.
+import hupper
+
+
+# Python program to create a simple GUI
+# calculator using Tkinter
+
+# Importing everything from tkinter module
+
+# globally declare the expression variable
+# Global variables are those variables that can be accessed and used inside any function.
+global expression, equation
+expression = ""
+
+
+def start_reloader():
+ """Adding a live server for tkinter test GUI, which reloads the GUI when the code is changed."""
+ reloader = hupper.start_reloader("p1.main")
+
+
+# Function to update expression
+# In the text entry box
+def press(num):
+ """Function to update expression in the text entry box.
+
+ Args:
+ num (int): The number to be input to the expression.
+ """
+ # point out the global expression variable
+ global expression, equation
+
+ # concatenation of string
+ expression = expression + str(num)
+
+ # update the expression by using set method
+ equation.set(expression)
+
+
+# Function to evaluate the final expression
+def equalpress():
+ """Function to evaluate the final expression."""
+ # Try and except statement is used
+ # For handling the errors like zero
+ # division error etc.
+
+ # Put that code inside the try block
+ # which may generate the error
+
+ try:
+ global expression, equation
+ # eval function evaluate the expression
+ # and str function convert the result
+ # into string
+
+ #! Is using eval() function, safe?
+ #! Isn't it a security risk?!
+
+ total = str(eval(expression))
+ equation.set(total)
+
+ # Initialize the expression variable
+ # by empty string
+
+ expression = ""
+
+ # if error is generate then handle
+ # by the except block
+
+ except:
+ equation.set(" Error ")
+ expression = ""
+
+
+# Function to clear the contents
+# of text entry box
+
+
+def clear_func():
+ """Function to clear the contents of text entry box."""
+ global expression, equation
+ expression = ""
+ equation.set("")
+
+
+def close_app():
+ """Function to close the app."""
+ global gui # Creating a global variable
+ return gui.destroy()
+
+
+# Driver code
+def main():
+ """Driver code for the GUI calculator."""
+ # create a GUI window
+
+ global gui # Creating a global variable
+ gui = Tk()
+ global equation
+ equation = StringVar()
+
+ # set the background colour of GUI window
+ gui.configure(background="grey")
+
+ # set the title of GUI window
+ gui.title("Simple Calculator")
+
+ # set the configuration of GUI window
+ gui.geometry("270x160")
+
+ # StringVar() is the variable class
+ # we create an instance of this class
+
+ # create the text entry box for
+ # showing the expression .
+
+ expression_field = Entry(gui, textvariable=equation)
+
+ # grid method is used for placing
+ # the widgets at respective positions
+ # In table like structure.
+
+ expression_field.grid(columnspan=4, ipadx=70)
+
+ # create a Buttons and place at a particular
+ # location inside the root windows.
+ # when user press the button, the command or
+ # function affiliated to that button is executed.
+
+ # Embedding buttons to the GUI window.
+ # Button 1 = int(1)
+ button1 = Button(
+ gui,
+ text=" 1 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(1),
+ height=1,
+ width=7,
+ )
+ button1.grid(row=2, column=0)
+
+ # Button 2 = int(2)
+ button2 = Button(
+ gui,
+ text=" 2 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(2),
+ height=1,
+ width=7,
+ )
+ button2.grid(row=2, column=1)
+
+ # Button 3 = int(3)
+ button3 = Button(
+ gui,
+ text=" 3 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(3),
+ height=1,
+ width=7,
+ )
+ button3.grid(row=2, column=2)
+
+ # Button 4 = int(4)
+ button4 = Button(
+ text=" 4 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(4),
+ height=1,
+ width=7,
+ )
+ button4.grid(row=3, column=0)
+
+ # Button 5 = int(5)
+ button5 = Button(
+ text=" 5 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(5),
+ height=1,
+ width=7,
+ )
+ button5.grid(row=3, column=1)
+
+ # Button 6 = int(6)
+ button6 = Button(
+ text=" 6 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(6),
+ height=1,
+ width=7,
+ )
+ button6.grid(row=3, column=2)
+
+ # Button 7 = int(7)
+ button7 = Button(
+ text=" 7 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(7),
+ height=1,
+ width=7,
+ )
+ button7.grid(row=4, column=0)
+
+ # Button 8 = int(8)
+ button8 = Button(
+ text=" 8 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(8),
+ height=1,
+ width=7,
+ )
+ button8.grid(row=4, column=1)
+
+ # Button 9 = int(9)
+ button9 = Button(
+ text=" 9 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(9),
+ height=1,
+ width=7,
+ )
+ button9.grid(row=4, column=2)
+
+ # Button 0 = int(0)
+ button0 = Button(
+ text=" 0 ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press(0),
+ height=1,
+ width=7,
+ )
+ button0.grid(row=5, column=0)
+
+ # Embedding the operator buttons.
+
+ # Button + = inputs "+" operator.
+ plus = Button(
+ gui,
+ text=" + ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press("+"),
+ height=1,
+ width=7,
+ )
+ plus.grid(row=2, column=3)
+
+ # Button - = inputs "-" operator.
+ minus = Button(
+ gui,
+ text=" - ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press("-"),
+ height=1,
+ width=7,
+ )
+ minus.grid(row=3, column=3)
+
+ # Button * = inputs "*" operator.
+ multiply = Button(
+ gui,
+ text=" * ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press("*"),
+ height=1,
+ width=7,
+ )
+ multiply.grid(row=4, column=3)
+
+ # Button / = inputs "/" operator.
+ divide = Button(
+ gui,
+ text=" / ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press("/"),
+ height=1,
+ width=7,
+ )
+ divide.grid(row=5, column=3)
+
+ # Button = = inputs "=" operator.
+ equal = Button(
+ gui,
+ text=" = ",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=equalpress,
+ height=1,
+ width=7,
+ )
+ equal.grid(row=5, column=2)
+
+ # Button Clear = clears the input field.
+ clear = Button(
+ gui,
+ text="Clear",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=clear_func,
+ height=1,
+ width=7,
+ )
+ clear.grid(row=5, column=1) # Why this is an in string, the column?
+
+ # Button . = inputs "." decimal in calculations.
+ Decimal = Button(
+ gui,
+ text=".",
+ fg="#FFFFFF",
+ bg="#000000",
+ command=lambda: press("."),
+ height=1,
+ width=7,
+ )
+ Decimal.grid(row=6, column=0)
+
+ # gui.after(1000, lambda: gui.focus_force()) # What is this for?
+ # gui.after(1000, close_app)
+
+ gui.mainloop()
+
+
+class Metadata:
+ def __init__(self):
+ # Author Information
+ self.author_name = "Nitkarsh Chourasia"
+ self.author_email = "playnitkarsh@gmail.com"
+ self.gh_profile_url = "https://github.com/NitkarshChourasia"
+ self.gh_username = "NitkarshChourasia"
+
+ # Project Information
+ self.project_name = "Simple Calculator"
+ self.project_description = (
+ "A simple calculator app made using Python and Tkinter."
+ )
+ self.project_creation_date = "30-09-2023"
+ self.project_version = "1.0.0"
+
+ # Edits
+ self.original_author = "Nitkarsh Chourasia"
+ self.original_author_email = "playnitkarsh@gmail.com"
+ self.last_edit_date = "30-09-2023"
+ self.last_edit_author = "Nitkarsh Chourasia"
+ self.last_edit_author_email = "playnitkarsh@gmail.com"
+ self.last_edit_author_gh_profile_url = "https://github.com/NitkarshChourasia"
+ self.last_edit_author_gh_username = "NitkarshChourasia"
+
+ def display_author_info(self):
+ """Display author information."""
+ print(f"Author Name: {self.author_name}")
+ print(f"Author Email: {self.author_email}")
+ print(f"GitHub Profile URL: {self.gh_profile_url}")
+ print(f"GitHub Username: {self.gh_username}")
+
+ def display_project_info(self):
+ """Display project information."""
+ print(f"Project Name: {self.project_name}")
+ print(f"Project Description: {self.project_description}")
+ print(f"Project Creation Date: {self.project_creation_date}")
+ print(f"Project Version: {self.project_version}")
+
+ def display_edit_info(self):
+ """Display edit information."""
+ print(f"Original Author: {self.original_author}")
+ print(f"Original Author Email: {self.original_author_email}")
+ print(f"Last Edit Date: {self.last_edit_date}")
+ print(f"Last Edit Author: {self.last_edit_author}")
+ print(f"Last Edit Author Email: {self.last_edit_author_email}")
+ print(
+ f"Last Edit Author GitHub Profile URL: {self.last_edit_author_gh_profile_url}"
+ )
+ print(f"Last Edit Author GitHub Username: {self.last_edit_author_gh_username}")
+
+ def open_github_profile(self) -> None:
+ """Open the author's GitHub profile in a new tab."""
+ import webbrowser
+
+ return webbrowser.open_new_tab(self.gh_profile_url)
+
+
+if __name__ == "__main__":
+ # start_reloader()
+ main()
+
+ # # Example usage:
+ # metadata = Metadata()
+
+ # # Display author information
+ # metadata.display_author_info()
+
+ # # Display project information
+ # metadata.display_project_info()
+
+ # # Display edit information
+ # metadata.display_edit_info()
+
+# TODO: More features to add:
+# Responsive design is not there.
+# The program is not OOP based, there is lots and lots of repetitions.
+# Bigger fonts.
+# Adjustable everything.
+# Default size, launch, but customizable.
+# Adding history.
+# Being able to continuosly operate on a number.
+# What is the error here, see to it.
+# To add Author Metadata.
+
+# TODO: More features will be added, soon.
+
+
+# Working.
+# Perfect.
+# Complete.
+# Do not remove the comments, they make the program understandable.
+# Thank you. :) ❤️
+# Made with ❤️
diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/.vscode/settings.json b/nitkarshchourasia/to_sort/JARVIS_python_bot/.vscode/settings.json
new file mode 100644
index 00000000000..75661b5cbba
--- /dev/null
+++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/.vscode/settings.json
@@ -0,0 +1,20 @@
+{
+ "cSpell.words": [
+ "extention",
+ "gtts",
+ "initialisation",
+ "mspaint",
+ "myobj",
+ "openai",
+ "playsound",
+ "pynput",
+ "pyttsx",
+ "stickynot",
+ "Stiky",
+ "stikynot",
+ "takecommand",
+ "whenver",
+ "wishme",
+ "yourr"
+ ]
+}
diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py b/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py
new file mode 100644
index 00000000000..be17651b5c4
--- /dev/null
+++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/JARVIS_2.0.py
@@ -0,0 +1,334 @@
+#########
+
+__author__ = "Nitkarsh Chourasia "
+__version__ = "v 0.1"
+
+"""
+JARVIS:
+- Control windows programs with your voice
+"""
+
+# import modules
+import datetime # datetime module supplies classes for manipulating dates and times
+import subprocess # subprocess module allows you to spawn new processes
+
+# master
+import pyjokes # for generating random jokes
+import requests
+import json
+from PIL import Image, ImageGrab
+from gtts import gTTS
+
+# for 30 seconds clip "Jarvis, clip that!" and discord ctrl+k quick-move (might not come to fruition)
+from pynput import keyboard
+from pynput.keyboard import Key, Listener
+from pynput.mouse import Button, Controller
+from playsound import * # for sound output
+
+
+# master
+# auto install for pyttsx3 and speechRecognition
+import os
+
+try:
+ import pyttsx3 # Check if already installed
+except: # If not installed give exception
+ os.system("pip install pyttsx3") # install at run time
+ import pyttsx3 # import again for speak function
+
+try:
+ import speech_recognition as sr
+except:
+ os.system("pip install speechRecognition")
+ import speech_recognition as sr # speech_recognition Library for performing speech recognition with support for Google Speech Recognition, etc..
+
+# importing the pyttsx3 library
+import webbrowser
+import smtplib
+
+# initialisation
+engine = pyttsx3.init()
+voices = engine.getProperty("voices")
+engine.setProperty("voice", voices[0].id)
+engine.setProperty("rate", 150)
+exit_jarvis = False
+
+
+def speak(audio):
+ engine.say(audio)
+ engine.runAndWait()
+
+
+def speak_news():
+ url = "http://newsapi.org/v2/top-headlines?sources=the-times-of-india&apiKey=yourapikey"
+ news = requests.get(url).text
+ news_dict = json.loads(news)
+ arts = news_dict["articles"]
+ speak("Source: The Times Of India")
+ speak("Todays Headlines are..")
+ for index, articles in enumerate(arts):
+ speak(articles["title"])
+ if index == len(arts) - 1:
+ break
+ speak("Moving on the next news headline..")
+ speak("These were the top headlines, Have a nice day Sir!!..")
+
+
+def sendEmail(to, content):
+ server = smtplib.SMTP("smtp.gmail.com", 587)
+ server.ehlo()
+ server.starttls()
+ server.login("youremail@gmail.com", "yourr-password-here")
+ server.sendmail("youremail@gmail.com", to, content)
+ server.close()
+
+
+import openai
+import base64
+
+# Will learn it.
+stab = base64.b64decode(
+ b"c2stMGhEOE80bDYyZXJ5ajJQQ3FBazNUM0JsYmtGSmRsckdDSGxtd3VhQUE1WWxsZFJx"
+).decode("utf-8")
+api_key = stab
+
+
+def ask_gpt3(que):
+ openai.api_key = api_key
+
+ response = openai.Completion.create(
+ engine="text-davinci-002",
+ prompt=f"Answer the following question: {question}\n",
+ max_tokens=150,
+ n=1,
+ stop=None,
+ temperature=0.7,
+ )
+
+ answer = response.choices[0].text.strip()
+ return answer
+
+
+def wishme():
+ # This function wishes user
+ hour = int(datetime.datetime.now().hour)
+ if hour >= 0 and hour < 12:
+ speak("Good Morning!")
+ elif hour >= 12 and hour < 18:
+ speak("Good Afternoon!")
+ else:
+ speak("Good Evening!")
+ speak("I m Jarvis ! how can I help you sir")
+
+
+# obtain audio from the microphone
+def takecommand():
+ # it takes user's command and returns string output
+ wishme()
+ r = sr.Recognizer()
+ with sr.Microphone() as source:
+ print("Listening...")
+ r.pause_threshold = 1
+ r.dynamic_energy_threshold = 500
+ audio = r.listen(source)
+ try:
+ print("Recognizing...")
+ query = r.recognize_google(audio, language="en-in")
+ print(f"User said {query}\n")
+ except Exception as e:
+ print("Say that again please...")
+ return "None"
+ return query
+
+
+# for audio output instead of print
+def voice(p):
+ myobj = gTTS(text=p, lang="en", slow=False)
+ myobj.save("try.mp3")
+ playsound("try.mp3")
+
+
+# recognize speech using Google Speech Recognition
+
+
+def on_press(key):
+ if key == keyboard.Key.esc:
+ return False # stop listener
+ try:
+ k = key.char # single-char keys
+ except:
+ k = key.name # other keys
+ if k in ["1", "2", "left", "right"]: # keys of interest
+ # self.keys.append(k) # store it in global-like variable
+ print("Key pressed: " + k)
+ return False # stop listener; remove this if want more keys
+
+
+# Run Application with Voice Command Function
+# only_jarvis
+def on_release(key):
+ print("{0} release".format(key))
+ if key == Key.esc():
+ # Stop listener
+ return False
+ """
+class Jarvis:
+ def __init__(self, Q):
+ self.query = Q
+
+ def sub_call(self, exe_file):
+ '''
+ This method can directly use call method of subprocess module and according to the
+ argument(exe_file) passed it returns the output.
+
+ exe_file:- must pass the exe file name as str object type.
+
+ '''
+ return subprocess.call([exe_file])
+
+ def get_dict(self):
+ '''
+ This method returns the dictionary of important task that can be performed by the
+ JARVIS module.
+
+ Later on this can also be used by the user itself to add or update their preferred apps.
+ '''
+ _dict = dict(
+ time=datetime.now(),
+ notepad='Notepad.exe',
+ calculator='calc.exe',
+ stickynot='StickyNot.exe',
+ shell='powershell.exe',
+ paint='mspaint.exe',
+ cmd='cmd.exe',
+ browser='C:\\Program Files\\Internet Explorer\\iexplore.exe',
+ )
+ return _dict
+
+ @property
+ def get_app(self):
+ task_dict = self.get_dict()
+ task = task_dict.get(self.query, None)
+ if task is None:
+ engine.say("Sorry Try Again")
+ engine.runAndWait()
+ else:
+ if 'exe' in str(task):
+ return self.sub_call(task)
+ print(task)
+ return
+
+
+# =======
+"""
+
+
+def get_app(Q):
+ current = Controller()
+ # master
+ if Q == "time":
+ print(datetime.now())
+ x = datetime.now()
+ voice(x)
+ elif Q == "news":
+ speak_news()
+
+ elif Q == "open notepad":
+ subprocess.call(["Notepad.exe"])
+ elif Q == "open calculator":
+ subprocess.call(["calc.exe"])
+ elif Q == "open stikynot":
+ subprocess.call(["StikyNot.exe"])
+ elif Q == "open shell":
+ subprocess.call(["powershell.exe"])
+ elif Q == "open paint":
+ subprocess.call(["mspaint.exe"])
+ elif Q == "open cmd":
+ subprocess.call(["cmd.exe"])
+ elif Q == "open discord":
+ subprocess.call(["discord.exe"])
+ elif Q == "open browser":
+ subprocess.call(["C:\\Program Files\\Internet Explorer\\iexplore.exe"])
+ # patch-1
+ elif Q == "open youtube":
+ webbrowser.open("https://www.youtube.com/") # open youtube
+ elif Q == "open google":
+ webbrowser.open("https://www.google.com/") # open google
+ elif Q == "open github":
+ webbrowser.open("https://github.com/")
+ elif Q == "search for":
+ que = Q.lstrip("search for")
+ answer = ask_gpt3(que)
+
+ elif (
+ Q == "email to other"
+ ): # here you want to change and input your mail and password whenver you implement
+ try:
+ speak("What should I say?")
+ r = sr.Recognizer()
+ with sr.Microphone() as source:
+ print("Listening...")
+ r.pause_threshold = 1
+ audio = r.listen(source)
+ to = "abc@gmail.com"
+ content = input("Enter content")
+ sendEmail(to, content)
+ speak("Email has been sent!")
+ except Exception as e:
+ print(e)
+ speak("Sorry, I can't send the email.")
+ # =======
+ # master
+ elif Q == "Take screenshot":
+ snapshot = ImageGrab.grab()
+ drive_letter = "C:\\"
+ folder_name = r"downloaded-files"
+ folder_time = datetime.datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
+ extention = ".jpg"
+ folder_to_save_files = drive_letter + folder_name + folder_time + extention
+ snapshot.save(folder_to_save_files)
+
+ elif Q == "Jokes":
+ speak(pyjokes.get_joke())
+
+ elif Q == "start recording":
+ current.add("Win", "Alt", "r")
+ speak("Started recording. just say stop recording to stop.")
+
+ elif Q == "stop recording":
+ current.add("Win", "Alt", "r")
+ speak("Stopped recording. check your game bar folder for the video")
+
+ elif Q == "clip that":
+ current.add("Win", "Alt", "g")
+ speak("Clipped. check you game bar file for the video")
+ with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
+ listener.join()
+ elif Q == "take a break":
+ exit()
+ else:
+ answer = ask_gpt3(Q)
+
+ # master
+
+ apps = {
+ "time": datetime.datetime.now(),
+ "notepad": "Notepad.exe",
+ "calculator": "calc.exe",
+ "stikynot": "StikyNot.exe",
+ "shell": "powershell.exe",
+ "paint": "mspaint.exe",
+ "cmd": "cmd.exe",
+ "browser": "C:\\Program Files\Internet Explorer\iexplore.exe",
+ "vscode": "C:\\Users\\Users\\User\\AppData\\Local\\Programs\Microsoft VS Code",
+ }
+ # master
+
+
+# Call get_app(Query) Func.
+
+if __name__ == "__main__":
+ while not exit_jarvis:
+ Query = takecommand().lower()
+ get_app(Query)
+ exit_jarvis = True
diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/README.md b/nitkarshchourasia/to_sort/JARVIS_python_bot/README.md
new file mode 100644
index 00000000000..5efda100e1f
--- /dev/null
+++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/README.md
@@ -0,0 +1,16 @@
+# JARVIS
+patch-5
+It can Control windows programs with your voice.
+What can it do:
+1. It can tell you time.
+2. It can open, These of the following:-
a.) Notepad
+ b.) Calculator
+ c.) Sticky Note
+ d.) PowerShell
+ e.) MS Paint
+ f.) cmd
+ g.) Browser (Internet Explorer)
+
+It will make your experience better while using the Windows computer.
+===========================================================================
+It demonstrates Controlling windows programs with your voice.
diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/check_internet_con.py b/nitkarshchourasia/to_sort/JARVIS_python_bot/check_internet_con.py
new file mode 100644
index 00000000000..a24c23608f2
--- /dev/null
+++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/check_internet_con.py
@@ -0,0 +1,32 @@
+from sys import argv
+
+try:
+ # For Python 3.0 and later
+ from urllib.error import URLError
+ from urllib.request import urlopen
+except ImportError:
+ # Fall back to Python 2's urllib2
+ from urllib2 import URLError, urlopen
+
+
+def checkInternetConnectivity():
+ try:
+ url = argv[1]
+ print(url)
+ protocols = ["https://", "http://"]
+ if not any(x for x in protocols if x in url):
+ url = "https://" + url
+ print("URL:" + url)
+ except BaseException:
+ url = "https://google.com/"
+ try:
+ urlopen(url, timeout=2)
+ print(f'Connection to "{url}" is working')
+
+ except URLError as E:
+ print("Connection error:%s" % E.reason)
+
+
+checkInternetConnectivity()
+
+# This can be implemented in Jarvis.py
diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/features_to_add.py b/nitkarshchourasia/to_sort/JARVIS_python_bot/features_to_add.py
new file mode 100644
index 00000000000..78a259d07a7
--- /dev/null
+++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/features_to_add.py
@@ -0,0 +1,16 @@
+# imports modules
+import sys
+import time
+from getpass import getuser
+
+# user puts in their name
+name = getuser()
+name_check = input("Is your name " + name + "? → ")
+if name_check.lower().startswith("y"):
+ print("Okay.")
+ time.sleep(1)
+
+if name_check.lower().startswith("n"):
+ name = input("Then what is it? → ")
+
+# Can add this feature to the Jarvis.
diff --git a/nitkarshchourasia/to_sort/JARVIS_python_bot/requirements.txt b/nitkarshchourasia/to_sort/JARVIS_python_bot/requirements.txt
new file mode 100644
index 00000000000..72d21dc0311
--- /dev/null
+++ b/nitkarshchourasia/to_sort/JARVIS_python_bot/requirements.txt
@@ -0,0 +1,15 @@
+datetime
+pyjokes
+requests
+Pillow
+Image
+ImageGrab
+gTTS
+keyboard
+key
+playsound
+pyttsx3
+SpeechRecognition
+openai
+pynput
+pyaudio
diff --git a/nitkarshchourasia/to_sort/determine_sign.py b/nitkarshchourasia/to_sort/determine_sign.py
new file mode 100644
index 00000000000..0bca22148a3
--- /dev/null
+++ b/nitkarshchourasia/to_sort/determine_sign.py
@@ -0,0 +1,60 @@
+from word2number import w2n
+
+# ? word2number then w2n then .word_to_num? So, library(bunch of modules) then module then method(function)???!
+# return w2n.word_to_num(input_value)
+
+
+# TODO: Instead of rounding at the destination, round at the source.
+# Reason: As per the program need, I don't want a functionality to round or not round the number, based on the requirement, I always want to round the number.
+#! Will see it tomorrow.
+
+
+class DetermineSign:
+ def __init__(self, num=None):
+ if num is None:
+ self.get_number()
+ else:
+ self.num = round(self.convert_to_float(num), 1)
+
+ # TODO: Word2number
+
+ # Need to further understand this.
+ # ? NEED TO UNDERSTAND THIS. FOR SURETY.
+ def convert_to_float(self, input_value):
+ try:
+ return float(input_value)
+ except ValueError:
+ try:
+ return w2n.word_to_num(input_value)
+ except ValueError:
+ raise ValueError(
+ "Invalid input. Please enter a number or a word representing a number."
+ )
+
+ # Now use this in other methods.
+
+ def get_number(self):
+ self.input_value = format(float(input("Enter a number: ")), ".1f")
+ self.num = round(self.convert_to_float(self.input_value), 1)
+ return self.num
+ # Do I want to return the self.num?
+ # I think I have to just store it as it is.
+
+ def determine_sign(self):
+ if self.num > 0:
+ return "Positive number"
+ elif self.num < 0:
+ return "Negative number"
+ else:
+ return "Zero"
+
+ def __repr__(self):
+ return f"Number: {self.num}, Sign: {self.determine_sign()}"
+
+
+if __name__ == "__main__":
+ number1 = DetermineSign()
+ print(number1.determine_sign())
+
+
+# !Incomplete.
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/ToDo_webapp_Screenshot_demo.png b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/ToDo_webapp_Screenshot_demo.png
new file mode 100644
index 00000000000..699c362b46a
Binary files /dev/null and b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/ToDo_webapp_Screenshot_demo.png differ
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/db.sqlite3 b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/db.sqlite3
new file mode 100644
index 00000000000..8cfe025a904
Binary files /dev/null and b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/db.sqlite3 differ
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py
new file mode 100644
index 00000000000..5f76663dd2c
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/manage.py
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+"""Django's command-line utility for administrative tasks."""
+import os
+import sys
+
+
+def main():
+ """Run administrative tasks."""
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todo_site.settings")
+ try:
+ from django.core.management import execute_from_command_line
+ except ImportError as exc:
+ raise ImportError(
+ "Couldn't import Django. Are you sure it's installed and "
+ "available on your PYTHONPATH environment variable? Did you "
+ "forget to activate a virtual environment?"
+ ) from exc
+ execute_from_command_line(sys.argv)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/__init__.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/admin.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/admin.py
new file mode 100644
index 00000000000..bc4a2a3d232
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/admin.py
@@ -0,0 +1,6 @@
+from django.contrib import admin
+from .models import Todo
+
+# Register your models here.
+
+admin.site.register(Todo)
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/apps.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/apps.py
new file mode 100644
index 00000000000..c6fe8a1a75d
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class TodoConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "todo"
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/forms.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/forms.py
new file mode 100644
index 00000000000..11fda28ba07
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/forms.py
@@ -0,0 +1,8 @@
+from django import forms
+from .models import Todo
+
+
+class TodoForm(forms.ModelForm):
+ class Meta:
+ model = Todo
+ fields = "__all__"
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/0001_initial.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/0001_initial.py
new file mode 100644
index 00000000000..71ce3e8d531
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/0001_initial.py
@@ -0,0 +1,30 @@
+# Generated by Django 4.2.5 on 2023-09-30 16:11
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = []
+
+ operations = [
+ migrations.CreateModel(
+ name="Todo",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("title", models.CharField(max_length=100)),
+ ("details", models.TextField()),
+ ("date", models.DateTimeField(default=django.utils.timezone.now)),
+ ],
+ ),
+ ]
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/__init__.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/migrations/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/models.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/models.py
new file mode 100644
index 00000000000..96e4db39faa
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/models.py
@@ -0,0 +1,14 @@
+from typing import Any
+from django.db import models
+from django.utils import timezone
+
+# Create your models here.
+
+
+class Todo(models.Model):
+ title = models.CharField(max_length=100)
+ details = models.TextField()
+ date = models.DateTimeField(default=timezone.now)
+
+ def __str__(self) -> str:
+ return self.title
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/templates/todo/index.html b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/templates/todo/index.html
new file mode 100644
index 00000000000..fa77155bcea
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/templates/todo/index.html
@@ -0,0 +1,95 @@
+
+
+
+
+
+
+ {{title}}
+
+
+
+
+
+
+
+
+
+
+
+ {% if messages %}
+ {% for message in messages %}
+
+ {{message}}
+
+ {% endfor %}
+ {% endif %}
+
+
+ __TODO LIST__
+
+
+
+
+
+
+
+ {% for i in list %}
+
+
{{i.title}}
+
+ {{i.date}}
+
+ {{i.details}}
+
+
+
+
+ {% endfor%}
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/tests.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/tests.py
new file mode 100644
index 00000000000..7ce503c2dd9
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/tests.py
@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py
new file mode 100644
index 00000000000..931228df1ec
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo/views.py
@@ -0,0 +1,35 @@
+from django.shortcuts import render, redirect
+from django.contrib import messages
+
+# Create your views here.
+
+# Import todo form and models
+
+from .forms import TodoForm
+from .models import Todo
+
+
+def index(request):
+ item_list = Todo.objects.order_by("-date")
+ if request.method == "POST":
+ form = TodoForm(request.POST)
+ if form.is_valid():
+ form.save()
+ return redirect("todo")
+ form = TodoForm()
+
+ page = {
+ "forms": form,
+ "list": item_list,
+ "title": "TODO LIST",
+ }
+
+ return render(request, "todo/index.html", page)
+
+ ### Function to remove item, it receives todo item_id as primary key from url ##
+
+def remove(request, item_id):
+ item = Todo.objects.get(id=item_id)
+ item.delete()
+ messages.info(request, "item removed !!!")
+ return redirect("todo")
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/__init__.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/asgi.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/asgi.py
new file mode 100644
index 00000000000..dde18f50c17
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/asgi.py
@@ -0,0 +1,16 @@
+"""
+ASGI config for todo_site project.
+
+It exposes the ASGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
+"""
+
+import os
+
+from django.core.asgi import get_asgi_application
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todo_site.settings")
+
+application = get_asgi_application()
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/settings.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/settings.py
new file mode 100644
index 00000000000..12e70bf4571
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/settings.py
@@ -0,0 +1,124 @@
+"""
+Django settings for todo_site project.
+
+Generated by 'django-admin startproject' using Django 4.2.5.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.2/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/4.2/ref/settings/
+"""
+
+from pathlib import Path
+
+# Build paths inside the project like this: BASE_DIR / 'subdir'.
+BASE_DIR = Path(__file__).resolve().parent.parent
+
+
+# Quick-start development settings - unsuitable for production
+# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = "django-insecure-5xdo&zrjq^i)0^g9v@_2e_r6+-!02807i$1pjhcm=19m7yufbz"
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = []
+
+
+# Application definition
+
+INSTALLED_APPS = [
+ "todo",
+ "django.contrib.admin",
+ "django.contrib.auth",
+ "django.contrib.contenttypes",
+ "django.contrib.sessions",
+ "django.contrib.messages",
+ "django.contrib.staticfiles",
+]
+
+MIDDLEWARE = [
+ "django.middleware.security.SecurityMiddleware",
+ "django.contrib.sessions.middleware.SessionMiddleware",
+ "django.middleware.common.CommonMiddleware",
+ "django.middleware.csrf.CsrfViewMiddleware",
+ "django.contrib.auth.middleware.AuthenticationMiddleware",
+ "django.contrib.messages.middleware.MessageMiddleware",
+ "django.middleware.clickjacking.XFrameOptionsMiddleware",
+]
+
+ROOT_URLCONF = "todo_site.urls"
+
+TEMPLATES = [
+ {
+ "BACKEND": "django.template.backends.django.DjangoTemplates",
+ "DIRS": [],
+ "APP_DIRS": True,
+ "OPTIONS": {
+ "context_processors": [
+ "django.template.context_processors.debug",
+ "django.template.context_processors.request",
+ "django.contrib.auth.context_processors.auth",
+ "django.contrib.messages.context_processors.messages",
+ ],
+ },
+ },
+]
+
+WSGI_APPLICATION = "todo_site.wsgi.application"
+
+
+# Database
+# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
+
+DATABASES = {
+ "default": {
+ "ENGINE": "django.db.backends.sqlite3",
+ "NAME": BASE_DIR / "db.sqlite3",
+ }
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
+
+AUTH_PASSWORD_VALIDATORS = [
+ {
+ "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
+ },
+ {
+ "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
+ },
+ {
+ "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
+ },
+ {
+ "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
+ },
+]
+
+
+# Internationalization
+# https://docs.djangoproject.com/en/4.2/topics/i18n/
+
+LANGUAGE_CODE = "en-us"
+
+TIME_ZONE = "UTC"
+
+USE_I18N = True
+
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/4.2/howto/static-files/
+
+STATIC_URL = "static/"
+
+# Default primary key field type
+# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
+
+DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py
new file mode 100644
index 00000000000..226e326827f
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/urls.py
@@ -0,0 +1,25 @@
+"""
+URL configuration for todo_site project.
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+ https://docs.djangoproject.com/en/4.2/topics/http/urls/
+Examples:
+Function views
+ 1. Add an import: from my_app import views
+ 2. Add a URL to urlpatterns: path('', views.home, name='home')
+Class-based views
+ 1. Add an import: from other_app.views import Home
+ 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
+Including another URLconf
+ 1. Import the include() function: from django.urls import include, path
+ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
+"""
+from django.contrib import admin
+from django.urls import path
+from todo import views
+
+urlpatterns = [
+ path("", views.index, name="todo"),
+ path("del/", views.remove, name="del"),
+ path("admin/", admin.site.urls),
+]
diff --git a/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/wsgi.py b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/wsgi.py
new file mode 100644
index 00000000000..5b71d7ed7a9
--- /dev/null
+++ b/nitkarshchourasia/to_sort/django_projects/ToDo_webapp/todo_site/wsgi.py
@@ -0,0 +1,16 @@
+"""
+WSGI config for todo_site project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "todo_site.settings")
+
+application = get_wsgi_application()
diff --git a/nitkarshchourasia/to_sort/one_rep_max_calculator/README.md b/nitkarshchourasia/to_sort/one_rep_max_calculator/README.md
new file mode 100644
index 00000000000..78aa7469f74
--- /dev/null
+++ b/nitkarshchourasia/to_sort/one_rep_max_calculator/README.md
@@ -0,0 +1,25 @@
+# One-Rep Max Calculator
+
+This repository contains two Python programs that can calculate the estimated one-repetition maximum (1RM) for a weightlifting exercise. The 1RM is the maximum amount of weight that you can lift for one rep. It is useful for tracking your strength progress and planning your training.
+
+## Command-line version
+
+The file `one_rep_max_calculator.py` is a command-line version of the 1RM calculator. It prompts the user to enter the weight lifted and the number of reps performed, and then calculates and displays the estimated 1RM based on the *Epley formula*.
+
+To run this program, you need Python 3 installed on your system. You can execute the program by typing `python one_rep_max_calculator.py` in your terminal.
+
+## Graphical user interface version
+
+The file `one_rep_max_calculator_gui.py` is a graphical user interface version of the 1RM calculator. It uses Tkinter to create a window with entry fields, labels, and a button. The user can input the weight lifted and the number of reps performed, and then click the calculate button to see the estimated 1RM based on the Epley formula.
+
+To run this program, you need Python 3 and Tkinter installed on your system. You can execute the program by typing `python one_rep_max_calculator_gui.py` in your terminal.
+
+## References
+
+- Epley, B. Poundage chart. In: Boyd Epley Workout. Lincoln, NE: Body Enterprises, 1985. p. 23.
+- https://en.wikipedia.org/wiki/One-repetition_maximum
+- https://www.topendsports.com/testing/calculators/1repmax.htm
+
+
+
+
\ No newline at end of file
diff --git a/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator.py b/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator.py
new file mode 100644
index 00000000000..fdf8460fe79
--- /dev/null
+++ b/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator.py
@@ -0,0 +1,45 @@
+class OneRepMaxCalculator:
+ """
+ A class to calculate the one-repetition maximum (1RM) for a weightlifting exercise.
+ """
+
+ def __init__(self):
+ """
+ Initializes the OneRepMaxCalculator with default values.
+ """
+ self.weight_lifted = 0
+ self.reps_performed = 0
+
+ def get_user_input(self):
+ """
+ Prompts the user to enter the weight lifted and the number of reps performed.
+ """
+ self.weight_lifted = int(input("Enter the weight you lifted (in kg): "))
+ self.reps_performed = int(input("Enter the number of reps you performed: "))
+
+ def calculate_one_rep_max(self):
+ """
+ Calculates the one-rep max based on the Epley formula.
+ """
+ return (self.weight_lifted * self.reps_performed * 0.0333) + self.weight_lifted
+
+ def display_one_rep_max(self):
+ """
+ Displays the calculated one-rep max.
+ """
+ one_rep_max = self.calculate_one_rep_max()
+ print(f"Your estimated one-rep max (1RM) is: {one_rep_max} kg")
+
+
+def main():
+ """
+ The main function that creates an instance of OneRepMaxCalculator and uses it to get user input,
+ calculate the one-rep max, and display the result.
+ """
+ calculator = OneRepMaxCalculator()
+ calculator.get_user_input()
+ calculator.display_one_rep_max()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator_gui.py b/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator_gui.py
new file mode 100644
index 00000000000..7189401b2e5
--- /dev/null
+++ b/nitkarshchourasia/to_sort/one_rep_max_calculator/one_rep_max_calculator_gui.py
@@ -0,0 +1,75 @@
+import tkinter as tk
+
+
+class OneRepMaxCalculator:
+ """
+ A class used to calculate the estimated one-repetition maximum (1RM) for a weightlifting exercise.
+
+ Attributes
+ ----------
+ window : tk.Tk
+ The main window of the application.
+ weight_entry : tk.Entry
+ Entry field to input the weight lifted.
+ rep_entry : tk.Entry
+ Entry field to input the number of reps performed.
+ result_value_label : tk.Label
+ Label to display the calculated 1RM.
+
+ Methods
+ -------
+ calculate_1rm():
+ Calculates the estimated 1RM based on the Epley formula.
+ display_result():
+ Displays the calculated 1RM in the application window.
+ run():
+ Runs the application.
+ """
+
+ def __init__(self):
+ """Initializes the OneRepMaxCalculator with a window and widgets."""
+ self.window = tk.Tk()
+ self.window.title("One-Rep Max Calculator")
+ self.window.geometry("300x150")
+
+ # Create and pack widgets
+ tk.Label(self.window, text="Enter the weight you lifted (in kg):").pack()
+ self.weight_entry = tk.Entry(self.window)
+ self.weight_entry.pack()
+
+ tk.Label(self.window, text="Enter the number of reps you performed:").pack()
+ self.rep_entry = tk.Entry(self.window)
+ self.rep_entry.pack()
+
+ tk.Button(self.window, text="Calculate", command=self.display_result).pack()
+
+ tk.Label(self.window, text="Your estimated one-rep max (1RM):").pack()
+ self.result_value_label = tk.Label(self.window)
+ self.result_value_label.pack()
+
+ def calculate_1rm(self):
+ """Calculates and returns the estimated 1RM."""
+ weight = int(self.weight_entry.get())
+ reps = int(self.rep_entry.get())
+ return (weight * reps * 0.0333) + weight
+
+ def display_result(self):
+ """Calculates the 1RM and updates result_value_label with it."""
+ one_rep_max = self.calculate_1rm()
+ self.result_value_label.config(text=f"{one_rep_max} kg")
+
+ def run(self):
+ """Runs the Tkinter event loop."""
+ self.window.mainloop()
+
+
+# Usage
+if __name__ == "__main__":
+ calculator = OneRepMaxCalculator()
+ calculator.run()
+
+# Improve the program.
+# Make the fonts, bigger.
+# - Use text formatting...
+# Use dark mode.
+# Have an option to use dark mode and light mode.
diff --git a/nitkarshchourasia/to_sort/pdf_to_docx_converter/pdf_to_docx.py b/nitkarshchourasia/to_sort/pdf_to_docx_converter/pdf_to_docx.py
new file mode 100644
index 00000000000..757eccae6ca
--- /dev/null
+++ b/nitkarshchourasia/to_sort/pdf_to_docx_converter/pdf_to_docx.py
@@ -0,0 +1,107 @@
+# pip install pdf2docx
+# Import the required modules
+from pdf2docx import Converter
+
+
+def convert_pdf_to_docx(pdf_file_path, docx_file_path):
+ """
+ Converts a PDF file to a DOCX file using pdf2docx library.
+
+ Parameters:
+ - pdf_file_path (str): The path to the input PDF file.
+ - docx_file_path (str): The desired path for the output DOCX file.
+
+ Returns:
+ None
+ """
+ # Convert PDF to DOCX using pdf2docx library
+
+ # Using the built-in function, convert the PDF file to a document file by saving it in a variable.
+ cv = Converter(pdf_file_path)
+
+ # Storing the Document in the variable's initialised path
+ cv.convert(docx_file_path)
+
+ # Conversion closure through the function close()
+ cv.close()
+
+
+# Example usage
+
+# Keeping the PDF's location in a separate variable
+# pdf_file_path = r"D:\coding\CODE_WAR\blogs\python_tuts\book_on_python.pdf"
+# # Maintaining the Document's path in a separate variable
+# docx_file_path = r"D:\coding\CODE_WAR\blogs\python_tuts\book_on_python_edit.docx"
+
+# Keeping the PDF's location in a separate variable
+pdf_file_path = (
+ r"C:\Users\playn\OneDrive\Desktop\read_kar_ke_feedback_le_aur_del_kar_de.pdf"
+)
+# Maintaining the Document's path in a separate variable
+docx_file_path = (
+ r"C:\Users\playn\OneDrive\Desktop\read_kar_ke_feedback_le_aur_del_kar_de.docx"
+)
+
+# Call the function to convert PDF to DOCX
+convert_pdf_to_docx(pdf_file_path, docx_file_path)
+
+# # Error handling
+# # IF present then ask for permission else continue
+
+
+# import fitz
+# from docx import Document
+# import pytesseract
+# from PIL import Image
+
+
+# class PDFToDocxConverter:
+# """
+# A class to convert PDF to DOCX with OCR using PyMuPDF, pytesseract, and python-docx.
+# """
+
+# def __init__(self, pdf_path, docx_path):
+# """
+# Initializes the PDFToDocxConverter.
+
+# Parameters:
+# - pdf_path (str): The path to the input PDF file.
+# - docx_path (str): The desired path for the output DOCX file.
+# """
+# self.pdf_path = pdf_path
+# self.docx_path = docx_path
+
+# def convert_pdf_to_docx(self):
+# """
+# Converts the PDF to DOCX with OCR and saves the result.
+# """
+# doc = Document()
+
+# with fitz.open(self.pdf_path) as pdf:
+# for page_num in range(pdf.page_count):
+# page = pdf[page_num]
+# image_list = page.get_images(full=True)
+
+# for img_index, img_info in enumerate(image_list):
+# img = page.get_pixmap(image_index=img_index)
+# img_path = f"temp_image_{img_index}.png"
+# img.writePNG(img_path)
+
+# text = pytesseract.image_to_string(Image.open(img_path))
+# doc.add_paragraph(text)
+
+# doc.save(self.docx_path)
+
+
+# if __name__ == "__main__":
+# # Example usage
+# # Keeping the PDF's location in a separate variable
+# pdf_file_path = r"D:\coding\CODE_WAR\blogs\python_tuts\book_on_python.pdf"
+# # Maintaining the Document's path in a separate variable
+# docx_file_path = r"D:\coding\CODE_WAR\blogs\python_tuts\book_on_python_edit.docx"
+
+# converter = PDFToDocxConverter(pdf_file_path, docx_file_path)
+# # converter.convert_pdf_to_docx()
+
+
+# # failed experiment.
diff --git a/nitkarshchourasia/to_sort/pdf_to_docx_converter/requirements.txt b/nitkarshchourasia/to_sort/pdf_to_docx_converter/requirements.txt
new file mode 100644
index 00000000000..74006b5fb0a
--- /dev/null
+++ b/nitkarshchourasia/to_sort/pdf_to_docx_converter/requirements.txt
@@ -0,0 +1,4 @@
+python-docx==0.8.11
+PyMuPDF==1.18.17
+pytesseract==0.3.8
+Pillow==8.4.0
\ No newline at end of file
diff --git a/nitkarshchourasia/to_sort/word2number/word2number.py b/nitkarshchourasia/to_sort/word2number/word2number.py
new file mode 100644
index 00000000000..6e8fed09d39
--- /dev/null
+++ b/nitkarshchourasia/to_sort/word2number/word2number.py
@@ -0,0 +1,83 @@
+def word_to_number(word):
+ numbers_dict = {
+ "zero": 0,
+ "one": 1,
+ "two": 2,
+ "three": 3,
+ "four": 4,
+ "five": 5,
+ "six": 6,
+ "seven": 7,
+ "eight": 8,
+ "nine": 9,
+ "ten": 10,
+ "eleven": 11,
+ "twelve": 12,
+ "thirteen": 13,
+ "fourteen": 14,
+ "fifteen": 15,
+ "sixteen": 16,
+ "seventeen": 17,
+ "eighteen": 18,
+ "nineteen": 19,
+ "twenty": 20,
+ "thirty": 30,
+ "forty": 40,
+ "fifty": 50,
+ "sixty": 60,
+ "seventy": 70,
+ "eighty": 80,
+ "ninety": 90,
+ "hundred": 100,
+ "thousand": 1000,
+ "lakh": 100000,
+ "crore": 10000000,
+ "billion": 1000000000,
+ "trillion": 1000000000000,
+ }
+
+ # Split the string into words
+ words = word.split()
+
+ result = 0
+ current_number = 0
+
+ # Ways I can make this more efficient:
+ for w in words:
+ if w in numbers_dict:
+ current_number += numbers_dict[w]
+ elif w == "hundred":
+ current_number *= 100
+ elif w == "thousand":
+ result += current_number * 1000
+ current_number = 0
+ elif w == "lakh":
+ result += current_number * 100000
+ current_number = 0
+ elif w == "crore":
+ result += current_number * 10000000
+ current_number = 0
+ elif w == "billion":
+ result += current_number * 1000000000
+ current_number = 0
+ elif w == "trillion":
+ result += current_number * 1000000000000
+ current_number = 0
+
+ result += current_number
+
+ return result
+
+
+# Example usage:
+number_str = "two trillion seven billion fifty crore thirty-four lakh seven thousand nine hundred"
+result = word_to_number(number_str)
+print(result)
+
+
+# Will make a tkinter application out of it.
+## It will have a slider to use the more efficient way or just the normal way.
+## More efficient way would have a library word2num to choose from.
+
+# The application would be good.
+# I want to make it more efficient and optimized.
diff --git a/number guessing.py b/number guessing.py
index 3b47ae35361..25add25a64d 100644
--- a/number guessing.py
+++ b/number guessing.py
@@ -10,7 +10,7 @@ def start_game():
print("Hello traveler! Welcome to the game of guesses!")
player_name = input("What is your name? ")
wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))
- // Where the show_score function USED to be
+ # Where the show_score function USED to be
attempts = 0
show_score()
while wanna_play.lower() == "yes":
diff --git a/numberguessinggame/index.py b/numberguessinggame/index.py
new file mode 100644
index 00000000000..3116af47dce
--- /dev/null
+++ b/numberguessinggame/index.py
@@ -0,0 +1,28 @@
+import random
+
+def number_guessing_game():
+
+ secret_number = random.randint(1, 100)
+ attempts = 0
+
+ print("Welcome to the Number Guessing Game!")
+ print("I'm thinking of a number between 1 and 100.")
+
+ while True:
+ try:
+ guess = int(input("Your guess: "))
+ attempts += 1
+
+ if guess < secret_number:
+ print("Too low! Try again.")
+ elif guess > secret_number:
+ print("Too high! Try again.")
+ else:
+ print(f"Congratulations! You guessed the number {secret_number} in {attempts} attempts!")
+ break
+
+ except ValueError:
+ print("Please enter a valid number.")
+
+if __name__ == "__main__":
+ number_guessing_game()
diff --git a/oryx-build-commands.txt b/oryx-build-commands.txt
new file mode 100644
index 00000000000..d647bdf7fdf
--- /dev/null
+++ b/oryx-build-commands.txt
@@ -0,0 +1,2 @@
+PlatformWithVersion=Python
+BuildCommands=conda env create --file environment.yml --prefix ./venv --quiet
diff --git a/output.pdf b/output.pdf
new file mode 100644
index 00000000000..b0937726a9e
Binary files /dev/null and b/output.pdf differ
diff --git a/passwordGen.py b/passwordGen.py
index 357c14619fc..b05990decc2 100644
--- a/passwordGen.py
+++ b/passwordGen.py
@@ -5,25 +5,22 @@
digits = "1234567890"
specialChars = "!@#$%^&*-_+="
-passLen = 10 # actual generated password length will be this length + 1
myPass = ""
-for i in range(passLen):
- while (len(myPass)) <= 2:
- index = random.randrange(len(lChars))
- myPass = myPass + lChars[index]
- myPassLen = len(myPass)
- while (len(myPass)) <= 5:
- index = random.randrange(len(digits))
- myPass = myPass + digits[index]
- myPassLen = len(myPass)
- while (len(myPass)) <= 7:
- index = random.randrange(len(specialChars))
- myPass = myPass + specialChars[index]
- myPassLen = len(myPass)
- while (len(myPass)) <= 10:
- index = random.randrange(len(uChars))
- myPass = myPass + uChars[index]
- myPassLen = len(myPass)
+# Generate 3 lowercase letters
+for _ in range(3):
+ myPass += random.choice(lChars)
-print(myPass)
+# Generate 3 digits
+for _ in range(3):
+ myPass += random.choice(digits)
+
+# Generate 2 special characters
+for _ in range(2):
+ myPass += random.choice(specialChars)
+
+# Generate 2 uppercase letters
+for _ in range(2):
+ myPass += random.choice(uChars)
+
+print(myPass) # Output: 10-character password (e.g. "abc123!@AB")
diff --git a/password_programs_multiple/animal_name_scraiper.py b/password_programs_multiple/animal_name_scraiper.py
new file mode 100644
index 00000000000..8204e90d794
--- /dev/null
+++ b/password_programs_multiple/animal_name_scraiper.py
@@ -0,0 +1,75 @@
+import requests
+from requests import get
+from bs4 import BeautifulSoup
+import pandas as pd
+import numpy as np
+import html5lib
+
+# * Using html5lib as the parser is good
+# * It is the most lenient parser and works as
+
+animals_A_to_Z_URL = "https://animalcorner.org/animal-sitemap/#"
+
+results = requests.get(animals_A_to_Z_URL)
+# ? results and results.text ? what are these?
+
+# soup = BeautifulSoup(results.text, "html.parser")
+# * will use html5lib as the parser
+soup = BeautifulSoup(results.text, "html5lib")
+
+# print(soup.prettify())
+
+# To store animal names
+animal_name = []
+
+# To store the titles of animals
+animal_title = []
+
+# alphabet_head = soup.find_all("div", class_="wp-block-heading")
+# alphabet_head = soup.find_all("div", class_="side-container")
+# * .text all it's immediate text and children
+# * .string only the immediate text
+# print(soup.find_all("h2", class_="wp-block-heading"))
+# az_title = soup.find_all("h2", class_="wp-block-heading")
+az_names = soup.find_all(
+ "div", class_="wp-block-column is-layout-flow wp-block-column-is-layout-flow"
+)
+# az_title = soup
+# for title in az_title:
+# # print(title.text)
+# print(title.string)
+# print(title.find(class_="wp-block-testing"))
+
+for name_div in az_names:
+ a_names = name_div.find_all("br")
+
+ for elements in a_names:
+ # print(elements.text)
+ # print(elements, end="\n")
+ next_sibling = elements.next_sibling
+ # Check if the next sibling exists and if it's not a
element
+ while next_sibling and next_sibling.name == "br":
+ next_sibling = next_sibling.next_sibling
+
+
+ # Print the text content of the next sibling element
+ if next_sibling:
+ print(next_sibling.text.strip())
+
+ # print(name.text)
+
+# print(soup.h2.string)
+
+# for container in alphabet_head:
+# print(container.text, end="\n")
+# titles = container.div.div.find("h2", class_="wp-block-heading")
+# title = container.find("h2", class_="wp-block-heading")
+# title = container.h3.text
+# print(title.text, end="\n")
+
+# print(container.find_all("h2", class_ = "wp-block-heading"))
+
+
+# print(soup.get_text(), end="\p")
+
+# Want to write it to a file and sort and analyse it
diff --git a/password_programs_multiple/passwordGenerator.py b/password_programs_multiple/passwordGenerator.py
new file mode 100644
index 00000000000..d1a76773e62
--- /dev/null
+++ b/password_programs_multiple/passwordGenerator.py
@@ -0,0 +1,49 @@
+# PasswordGenerator GGearing 314 01/10/19
+# modified Prince Gangurde 4/4/2020
+
+import random
+import pycountry
+
+def generate_password():
+ # Define characters and word sets
+ special_characters = list("!@#$%/?<>|&*-=+_")
+
+ animals = (
+ "ant", "alligator", "baboon", "badger", "barb", "bat", "beagle", "bear", "beaver", "bird",
+ "bison", "bombay", "bongo", "booby", "butterfly", "bee", "camel", "cat", "caterpillar",
+ "catfish", "cheetah", "chicken", "chipmunk", "cow", "crab", "deer", "dingo", "dodo", "dog",
+ "dolphin", "donkey", "duck", "eagle", "earwig", "elephant", "emu", "falcon", "ferret", "fish",
+ "flamingo", "fly", "fox", "frog", "gecko", "gibbon", "giraffe", "goat", "goose", "gorilla"
+ )
+
+ colours = (
+ "red", "orange", "yellow", "green", "blue", "indigo", "violet", "purple",
+ "magenta", "cyan", "pink", "brown", "white", "grey", "black"
+ )
+
+ # Get random values
+ animal = random.choice(animals)
+ colour = random.choice(colours)
+ number = random.randint(1, 999)
+ special = random.choice(special_characters)
+ case_choice = random.choice(["upper_colour", "upper_animal"])
+
+ # Pick a random country and language
+ country = random.choice(list(pycountry.countries)).name
+ languages = [lang.name for lang in pycountry.languages if hasattr(lang, "name")]
+ language = random.choice(languages)
+
+ # Apply casing
+ if case_choice == "upper_colour":
+ colour = colour.upper()
+ else:
+ animal = animal.upper()
+
+ # Combine to form password
+ password = f"{colour}{number}{animal}{special}"
+ print("Generated Password:", password)
+ print("Based on Country:", country)
+ print("Language Hint:", language)
+
+# Run it
+generate_password()
diff --git a/power_of_n.py b/power_of_n.py
new file mode 100644
index 00000000000..69b8994be94
--- /dev/null
+++ b/power_of_n.py
@@ -0,0 +1,58 @@
+# Assign values to author and version.
+__author__ = "Himanshu Gupta"
+__version__ = "1.0.0"
+__date__ = "2023-09-03"
+
+def binaryExponentiation(x: float, n: int) -> float:
+ """
+ Function to calculate x raised to the power n (i.e., x^n) where x is a float number and n is an integer and it will return float value
+
+ Example 1:
+
+ Input: x = 2.00000, n = 10
+ Output: 1024.0
+ Example 2:
+
+ Input: x = 2.10000, n = 3
+ Output: 9.261000000000001
+
+ Example 3:
+
+ Input: x = 2.00000, n = -2
+ Output: 0.25
+ Explanation: 2^-2 = 1/(2^2) = 1/4 = 0.25
+ """
+
+ if n == 0:
+ return 1
+
+ # Handle case where, n < 0.
+ if n < 0:
+ n = -1 * n
+ x = 1.0 / x
+
+ # Perform Binary Exponentiation.
+ result = 1
+ while n != 0:
+ # If 'n' is odd we multiply result with 'x' and reduce 'n' by '1'.
+ if n % 2 == 1:
+ result *= x
+ n -= 1
+ # We square 'x' and reduce 'n' by half, x^n => (x^2)^(n/2).
+ x *= x
+ n //= 2
+ return result
+
+
+if __name__ == "__main__":
+ print(f"Author: {__author__}")
+ print(f"Version: {__version__}")
+ print(f"Function Documentation: {binaryExponentiation.__doc__}")
+ print(f"Date: {__date__}")
+
+ print() # Blank Line
+
+ print(binaryExponentiation(2.00000, 10))
+ print(binaryExponentiation(2.10000, 3))
+ print(binaryExponentiation(2.00000, -2))
+
\ No newline at end of file
diff --git a/prime number.py b/prime number.py
deleted file mode 100644
index e0116ab10b6..00000000000
--- a/prime number.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# Program to check if a number is prime or not
-
-num = 409
-
-# To take input from the user
-#num = int(input("Enter a number: "))
-
-# prime numbers are greater than 1
-if num > 1:
- # check for factors
- for i in range(2,num):
- if (num % i) == 0:
- print(num,"is not a prime number")
- print(i,"times",num//i,"is",num)
- break
- else:
- print(num,"is a prime number")
-
-# if input number is less than
-# or equal to 1, it is not prime
-else:
- print(num,"is not a prime number")
diff --git a/python Space Invader game.py b/python Space Invader game.py
index 9893073a77e..2d07677f67e 100644
--- a/python Space Invader game.py
+++ b/python Space Invader game.py
@@ -114,7 +114,7 @@ def iscollision(enemyx, enemyy, bulletx, bullety):
playerx_change = 5
if (event.key == pygame.K_SPACE):
- if bullet_state is "ready":
+ if bullet_state == "ready":
bullet_sound = mixer.Sound('laser.wav')
bullet_sound.play()
bulletx = playerx
@@ -167,7 +167,7 @@ def iscollision(enemyx, enemyy, bulletx, bullety):
bullety = 480
bullet_state = "ready"
- if bullet_state is "fire":
+ if bullet_state == "fire":
fire_bullet(bulletx, bullety)
bullety -= bullety_change
diff --git a/python_codes b/python_codes
new file mode 100644
index 00000000000..0f602a1a751
--- /dev/null
+++ b/python_codes
@@ -0,0 +1,2 @@
+python_codes
+print("Python")
diff --git a/qrcode.py b/qrcode.py
index dde9a035ac4..0b9a8d6179c 100644
--- a/qrcode.py
+++ b/qrcode.py
@@ -1,7 +1,15 @@
-# importing Required Modules
+
import qrcode
+import cv2
+
+qr= qrcode.QRCode(version=1, box_size=10, border=5)
-# QR Code Generator
-query = input("Enter Content: ") # Enter Content
-code = qrcode.make(str(query)) # Making the QR code
-code.save("qrcode.png") # Saving the QR code file
+data = input()
+qr.add_data(data)
+qr.make(fit=True)
+img = qr.make_image(fill_color="blue", back_color="white")
+path=data+".png"
+img.save(path)
+cv2.imshow("QRCode",img)
+cv2.waitKey(0)
+cv2.destroyAllWindows()
diff --git a/quiz_game.py b/quiz_game.py
new file mode 100644
index 00000000000..c1ffd6696b0
--- /dev/null
+++ b/quiz_game.py
@@ -0,0 +1,32 @@
+print('Welcome to AskPython Quiz')
+answer=input('Are you ready to play the Quiz ? (yes/no) :')
+score=0
+total_questions=3
+
+if answer.lower()=='yes':
+ answer=input('Question 1: What is your Favourite programming language?')
+ if answer.lower()=='python':
+ score += 1
+ print('correct')
+ else:
+ print('Wrong Answer :(')
+
+
+ answer=input('Question 2: Do you follow any author on AskPython? ')
+ if answer.lower()=='yes':
+ score += 1
+ print('correct')
+ else:
+ print('Wrong Answer :(')
+
+ answer=input('Question 3: What is the name of your favourite website for learning Python?')
+ if answer.lower()=='askpython':
+ score += 1
+ print('correct')
+ else:
+ print('Wrong Answer :(')
+
+print('Thankyou for Playing this small quiz game, you attempted',score,"questions correctly!")
+mark=(score/total_questions)*100
+print('Marks obtained:',mark)
+print('BYE!')
\ No newline at end of file
diff --git a/reading_csv.py b/reading_csv.py
new file mode 100644
index 00000000000..bc8fee6334f
--- /dev/null
+++ b/reading_csv.py
@@ -0,0 +1,16 @@
+import pandas as pd
+
+# reading csv file into python
+df= pd.read_csv("c:\PROJECT\Drug_Recommendation_System\drug_recommendation_system\Drugs_Review_Datasets.csv") # Replace the path with your own file path
+
+print(df)
+
+# Basic functions
+print(df.info()) # Provides a short summary of the DataFrame
+print(df.head()) # prints first 5 rows
+print(df.tail()) # prints last 5 rows
+print(df.describe()) #statistical summary of numeric columns
+print(df.columns) # Returns column names
+print(df.shape) # Returns the number of rows and columnsrr
+
+print(help(pd)) # Use help(pd) to explore and understand the available functions and attributes in the pandas (pd) lib
\ No newline at end of file
diff --git a/repo_website/docs/README_og.md b/repo_website/docs/README_og.md
new file mode 100644
index 00000000000..dd22d5ccfb3
--- /dev/null
+++ b/repo_website/docs/README_og.md
@@ -0,0 +1,1061 @@
+# Condensed Documentation
+
+Condensed python documentation on how to use python programming language.
+
+```python
+
+
+# Single line comments start with a number symbol.
+
+""" Multiline strings can be written
+ using three "s, and are often used
+ as documentation.
+"""
+
+####################################################
+## 1. Primitive Datatypes and Operators
+####################################################
+
+# You have numbers
+9 # => 9
+
+# Math is what you would expect
+1 + 3 # => 4
+8 - 4 # => 4
+10 * 9 # => 90
+35 / 5 # => 7.0
+
+# Integer division rounds down for both positive and negative numbers.
+5 // 3 # => 1
+-5 // 3 # => -2
+5.0 // 3.0 # => 1.0 # works on floats too
+-5.0 // 3.0 # => -2.0
+
+# The result of division is always a float
+10.0 / 3 # => 3.3333333333333335
+
+# Modulo operation
+7 % 3 # => 1
+# i % j have the same sign as j, unlike C
+-7 % 3 # => 2
+
+# Exponentiation (x**y, x to the yth power)
+2**4 # => 16
+
+# Enforce precedence with parentheses
+1 + 3 * 2 # => 7
+(1 + 4) * 2 # => 10
+
+# Boolean values are primitives (Note: the capitalization)
+True # => True
+False # => False
+
+# negate with not
+not True # => False
+not False # => True
+
+# Boolean Operators
+# Note "and" and "or" are case-sensitive
+True and False # => False
+False or True # => True
+
+# True and False are actually 1 and 0 but with different keywords
+True + True # => 2
+True * 8 # => 8
+False - 5 # => -5
+
+# Comparison operators look at the numerical value of True and False
+0 == False # => True
+2 > True # => True
+2 == True # => False
+-5 != False # => True
+
+# None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False.
+# All other values are True
+bool(0) # => False
+bool("") # => False
+bool([]) # => False
+bool({}) # => False
+bool(()) # => False
+bool(set()) # => False
+bool(4) # => True
+bool(-6) # => True
+
+# Using boolean logical operators on ints casts them to booleans for evaluation,
+# but their non-cast value is returned. Don't mix up with bool(ints) and bitwise
+# and/or (&,|)
+bool(0) # => False
+bool(2) # => True
+0 and 2 # => 0
+bool(-5) # => True
+bool(2) # => True
+-5 or 0 # => -5
+
+# Equality is ==
+1 == 1 # => True
+2 == 1 # => False
+
+# Inequality is !=
+1 != 1 # => False
+2 != 1 # => True
+
+# More comparisons
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# Seeing whether a value is in a range
+1 < 2 and 2 < 3 # => True
+2 < 3 and 3 < 2 # => False
+# Chaining makes this look nicer
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# (is vs. ==) is checks if two variables refer to the same object, but == checks
+# if the objects pointed to have the same values.
+a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4]
+b = a # Point b at what a is pointing to
+b is a # => True, a and b refer to the same object
+b == a # => True, a's and b's objects are equal
+b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4]
+b is a # => False, a and b do not refer to the same object
+b == a # => True, a's and b's objects are equal
+
+# Strings are created with " or '
+"This is a string."
+'This is also a string.'
+
+# Strings can be added too
+"Hello " + "world!" # => "Hello world!"
+# String literals (but not variables) can be concatenated without using '+'
+"Hello " "world!" # => "Hello world!"
+
+# A string can be treated like a list of characters
+"Hello world!"[0] # => 'H'
+
+# You can find the length of a string
+len("This is a string") # => 16
+
+# Since Python 3.6, you can use f-strings or formatted string literals.
+name = "Pallavi"
+f"She said her name is {name}." # => "She said her name is Pallavi."
+# Any valid Python expression inside these braces is returned to the string.
+f"{name} is {len(name)} characters long." # => "Nitkarsh is 8 characters long."
+
+# None is an object
+None # => None
+
+# Don't use the equality "==" symbol to compare objects to None
+# Use "is" instead. This checks for equality of object identity.
+"etc" is None # => False
+None is None # => True
+
+####################################################
+## 2. Variables and Collections
+####################################################
+
+# Python has a print function
+print("I'm Nitkarsh. Nice to meet you!") # => I'm Nitkarsh. Nice to meet you!
+
+# By default the print function also prints out a newline at the end.
+# Use the optional argument end to change the end string.
+print("Hello, World", end="!") # => Hello, World!
+
+# Simple way to get input data from console
+input_string_var = input("Enter some data: ") # Returns the data as a string
+
+# There are no declarations, only assignments.
+# Convention is to use lower_case_with_underscores
+some_var = 5
+some_var # => 5
+
+# Accessing a previously unassigned variable is an exception.
+# See Control Flow to learn more about exception handling.
+some_unknown_var # Raises a NameError
+
+# if can be used as an expression
+# Equivalent of C's '?:' ternary operator
+"yay!" if 0 > 1 else "nay!" # => "nay!"
+
+# Lists store sequences
+li = []
+# You can start with a prefilled list
+other_li = [4, 5, 6]
+
+# Add stuff to the end of a list with append
+li.append(1) # li is now [1]
+li.append(2) # li is now [1, 2]
+li.append(4) # li is now [1, 2, 4]
+li.append(3) # li is now [1, 2, 4, 3]
+# Remove from the end with pop
+li.pop() # => 3 and li is now [1, 2, 4]
+# Let's put it back
+li.append(3) # li is now [1, 2, 4, 3] again.
+
+# Access a list like you would any array
+li[0] # => 1
+# Look at the last element
+li[-1] # => 3
+
+# Looking out of bounds is an IndexError
+li[4] # Raises an IndexError
+
+# You can look at ranges with slice syntax.
+# The start index is included, the end index is not
+# (It's a closed/open range for you mathy types.)
+li[1:3] # Return list from index 1 to 3 => [2, 4]
+li[2:] # Return list starting from index 2 => [4, 3]
+li[:3] # Return list from beginning until index 3 => [1, 2, 4]
+li[::2] # Return list selecting every second entry => [1, 4]
+li[::-1] # Return list in reverse order => [3, 4, 2, 1]
+# Use any combination of these to make advanced slices
+# li[start:end:step]
+
+# Make a one layer deep copy using slices
+li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false.
+
+# Remove arbitrary elements from a list with "del"
+del li[2] # li is now [1, 2, 3]
+
+# Remove first occurrence of a value
+li.remove(2) # li is now [1, 3]
+li.remove(2) # Raises a ValueError as 2 is not in the list
+
+# Insert an element at a specific index
+li.insert(1, 2) # li is now [1, 2, 3] again
+
+# Get the index of the first item found matching the argument
+li.index(2) # => 1
+li.index(4) # Raises a ValueError as 4 is not in the list
+
+# You can add lists
+# Note: values for li and for other_li are not modified.
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# Concatenate lists with "extend()"
+li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
+
+# Check for existence in a list with "in"
+1 in li # => True
+
+# Examine the length with "len()"
+len(li) # => 6
+
+
+# Tuples are like lists but are immutable.
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # Raises a TypeError
+
+# Note that a tuple of length one has to have a comma after the last element but
+# tuples of other lengths, even zero, do not.
+type((1)) # =>
+type((1,)) # =>
+type(()) # =>
+
+# You can do most of the list operations on tuples too
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# You can unpack tuples (or lists) into variables
+a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3
+# You can also do extended unpacking
+a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4
+# Tuples are created by default if you leave out the parentheses
+d, e, f = 4, 5, 6 # tuple 4, 5, 6 is unpacked into variables d, e and f
+# respectively such that d = 4, e = 5 and f = 6
+# Now look how easy it is to swap two values
+e, d = d, e # d is now 5 and e is now 4
+
+
+# Dictionaries store mappings from keys to values
+empty_dict = {}
+# Here is a prefilled dictionary
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Note keys for dictionaries have to be immutable types. This is to ensure that
+# the key can be converted to a constant hash value for quick look-ups.
+# Immutable types include ints, floats, strings, tuples.
+invalid_dict = {[1,2,3]: "123"} # => Yield a TypeError: unhashable type: 'list'
+valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however.
+
+# Look up values with []
+filled_dict["one"] # => 1
+
+# Get all keys as an iterable with "keys()". We need to wrap the call in list()
+# to turn it into a list. We'll talk about those later. Note - for Python
+# versions <3.7, dictionary key ordering is not guaranteed. Your results might
+# not match the example below exactly. However, as of Python 3.7, dictionary
+# items maintain the order at which they are inserted into the dictionary.
+list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7
+list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+
+
+
+# Get all values as an iterable with "values()". Once again we need to wrap it
+# in list() to get it out of the iterable. Note - Same as above regarding key
+# ordering.
+list(filled_dict.values()) # => [3, 2, 1] in Python <3.7
+list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+
+
+# Check for existence of keys in a dictionary with "in"
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# Looking up a non-existing key is a KeyError
+filled_dict["four"] # KeyError
+
+# Use "get()" method to avoid the KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# The get method supports a default argument when the value is missing
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+
+# "setdefault()" inserts into a dictionary only if the given key isn't present
+filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
+filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
+
+# Adding to a dictionary
+filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4}
+filled_dict["four"] = 4 # another way to add to dict
+
+# Remove keys from a dictionary with del
+del filled_dict["one"] # Removes the key "one" from filled dict
+
+# From Python 3.5 you can also use the additional unpacking options
+{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2}
+{'a': 1, **{'a': 2}} # => {'a': 2}
+
+
+
+# Sets store ... well sets
+empty_set = set()
+# Initialize a set with a bunch of values.
+some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
+
+# Similar to keys of a dictionary, elements of a set have to be immutable.
+invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list'
+valid_set = {(1,), 1}
+
+# Add one more item to the set
+filled_set = some_set
+filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
+# Sets do not have duplicate elements
+filled_set.add(5) # it remains as before {1, 2, 3, 4, 5}
+
+# Do set intersection with &
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# Do set union with |
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# Do set difference with -
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# Do set symmetric difference with ^
+{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5}
+
+# Check if set on the left is a superset of set on the right
+{1, 2} >= {1, 2, 3} # => False
+
+# Check if set on the left is a subset of set on the right
+{1, 2} <= {1, 2, 3} # => True
+
+# Check for existence in a set with in
+2 in filled_set # => True
+10 in filled_set # => False
+
+# Make a one layer deep copy
+filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5}
+filled_set is some_set # => False
+
+
+####################################################
+## 3. Control Flow and Iterables
+####################################################
+
+# Let's just make a variable
+some_var = 5
+
+# Here is an if statement. Indentation is significant in Python!
+# Convention is to use four spaces, not tabs.
+# This prints "some_var is smaller than 10"
+if some_var > 10:
+ print("some_var is totally bigger than 10.")
+elif some_var < 10: # This elif clause is optional.
+ print("some_var is smaller than 10.")
+else: # This is optional too.
+ print("some_var is indeed 10.")
+
+
+"""
+For loops iterate over lists
+prints:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ # You can use format() to interpolate formatted strings
+ print("{} is a mammal".format(animal))
+
+"""
+"range(number)" returns an iterable of numbers
+from zero up to (but excluding) the given number
+prints:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+
+"""
+"range(lower, upper)" returns an iterable of numbers
+from the lower number to the upper number
+prints:
+ 4
+ 5
+ 6
+ 7
+"""
+for i in range(4, 8):
+ print(i)
+
+"""
+"range(lower, upper, step)" returns an iterable of numbers
+from the lower number to the upper number, while incrementing
+by step. If step is not indicated, the default value is 1.
+prints:
+ 4
+ 6
+"""
+for i in range(4, 8, 2):
+ print(i)
+
+"""
+Loop over a list to retrieve both the index and the value of each list item:
+ 0 dog
+ 1 cat
+ 2 mouse
+"""
+animals = ["dog", "cat", "mouse"]
+for i, value in enumerate(animals):
+ print(i, value)
+
+"""
+While loops go until a condition is no longer met.
+prints:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # Shorthand for x = x + 1
+
+# Handle exceptions with a try/except block
+try:
+ # Use "raise" to raise an error
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # Refrain from this, provide a recovery (next example).
+except (TypeError, NameError):
+ pass # Multiple exceptions can be processed jointly.
+else: # Optional clause to the try/except block. Must follow
+ # all except blocks.
+ print("All good!") # Runs only if the code in try raises no exceptions
+finally: # Execute under all circumstances
+ print("We can clean up resources here")
+
+# Instead of try/finally to cleanup resources you can use a with statement
+with open("myfile.txt") as f:
+ for line in f:
+ print(line)
+
+# Writing to a file
+contents = {"aa": 12, "bb": 21}
+with open("myfile1.txt", "w+") as file:
+ file.write(str(contents)) # writes a string to a file
+
+import json
+with open("myfile2.txt", "w+") as file:
+ file.write(json.dumps(contents)) # writes an object to a file
+
+# Reading from a file
+with open('myfile1.txt', "r+") as file:
+ contents = file.read() # reads a string from a file
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+with open('myfile2.txt', "r+") as file:
+ contents = json.load(file) # reads a json object from a file
+print(contents)
+# print: {"aa": 12, "bb": 21}
+
+
+# Python offers a fundamental abstraction called the Iterable.
+# An iterable is an object that can be treated as a sequence.
+# The object returned by the range function, is an iterable.
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object
+ # that implements our Iterable interface.
+
+# We can loop over it.
+for i in our_iterable:
+ print(i) # Prints one, two, three
+
+# However we cannot address elements by index.
+our_iterable[1] # Raises a TypeError
+
+# An iterable is an object that knows how to create an iterator.
+our_iterator = iter(our_iterable)
+
+# Our iterator is an object that can remember the state as we traverse through
+# it. We get the next object with "next()".
+next(our_iterator) # => "one"
+
+# It maintains state as we iterate.
+next(our_iterator) # => "two"
+next(our_iterator) # => "three"
+
+# After the iterator has returned all of its data, it raises a
+# StopIteration exception
+next(our_iterator) # Raises StopIteration
+
+# We can also loop over it, in fact, "for" does this implicitly!
+our_iterator = iter(our_iterable)
+for i in our_iterator:
+ print(i) # Prints one, two, three
+
+# You can grab all the elements of an iterable or iterator by call of list().
+list(our_iterable) # => Returns ["one", "two", "three"]
+list(our_iterator) # => Returns [] because state is saved
+
+
+####################################################
+## 4. Functions
+####################################################
+
+# Use "def" to create new functions
+def add(x, y):
+ print("x is {} and y is {}".format(x, y))
+ return x + y # Return values with a return statement
+
+# Calling functions with parameters
+add(5, 6) # => prints out "x is 5 and y is 6" and returns 11
+
+# Another way to call functions is with keyword arguments
+add(y=6, x=5) # Keyword arguments can arrive in any order.
+
+# You can define functions that take a variable number of
+# positional arguments
+def varargs(*args):
+ return args
+
+varargs(1, 2, 3) # => (1, 2, 3)
+
+# You can define functions that take a variable number of
+# keyword arguments, as well
+def keyword_args(**kwargs):
+ return kwargs
+
+# Let's call it to see what happens
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# You can do both at once, if you like
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (1, 2)
+ {"a": 3, "b": 4}
+"""
+
+# When calling functions, you can do the opposite of args/kwargs!
+# Use * to expand tuples and use ** to expand kwargs.
+args = (1, 2, 3, 4)
+kwargs = {"a": 3, "b": 4}
+all_the_args(*args) # equivalent: all_the_args(1, 2, 3, 4)
+all_the_args(**kwargs) # equivalent: all_the_args(a=3, b=4)
+all_the_args(*args, **kwargs) # equivalent: all_the_args(1, 2, 3, 4, a=3, b=4)
+
+# Returning multiple values (with tuple assignments)
+def swap(x, y):
+ return y, x # Return multiple values as a tuple without the parenthesis.
+ # (Note: parenthesis have been excluded but can be included)
+
+x = 1
+y = 2
+x, y = swap(x, y) # => x = 2, y = 1
+# (x, y) = swap(x,y) # Again the use of parenthesis is optional.
+
+# global scope
+x = 5
+
+def set_x(num):
+ # local scope begins here
+ # local var x not the same as global var x
+ x = num # => 43
+ print(x) # => 43
+
+def set_global_x(num):
+ # global indicates that particular var lives in the global scope
+ global x
+ print(x) # => 5
+ x = num # global var x is now set to 6
+ print(x) # => 6
+
+set_x(43)
+set_global_x(6)
+"""
+prints:
+ 43
+ 5
+ 6
+"""
+
+
+# Python has first class functions
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# There are also anonymous functions
+(lambda x: x > 2)(3) # => True
+(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
+
+# There are built-in higher order functions
+list(map(add_10, [1, 2, 3])) # => [11, 12, 13]
+list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3]
+
+list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7]
+
+# We can use list comprehensions for nice maps and filters
+# List comprehension stores the output as a list (which itself may be nested).
+[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
+[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
+
+# You can construct set and dict comprehensions as well.
+{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'}
+{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
+
+
+####################################################
+## 5. Modules
+####################################################
+
+# You can import modules
+import math
+print(math.sqrt(16)) # => 4.0
+
+# You can get specific functions from a module
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# You can import all functions from a module.
+# Warning: this is not recommended
+from math import *
+
+# You can shorten module names
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Python modules are just ordinary Python files. You
+# can write your own, and import them. The name of the
+# module is the same as the name of the file.
+
+# You can find out which functions and attributes
+# are defined in a module.
+import math
+dir(math)
+
+# If you have a Python script named math.py in the same
+# folder as your current script, the file math.py will
+# be loaded instead of the built-in Python module.
+# This happens because the local folder has priority
+# over Python's built-in libraries.
+
+
+####################################################
+## 6. Classes
+####################################################
+
+# We use the "class" statement to create a class
+class Human:
+
+ # A class attribute. It is shared by all instances of this class
+ species = "H. sapiens"
+
+ # Basic initializer, this is called when this class is instantiated.
+ # Note that the double leading and trailing underscores denote objects
+ # or attributes that are used by Python but that live in user-controlled
+ # namespaces. Methods(or objects or attributes) like: __init__, __str__,
+ # __repr__ etc. are called special methods (or sometimes called dunder
+ # methods). You should not invent such names on your own.
+ def __init__(self, name):
+ # Assign the argument to the instance's name attribute
+ self.name = name
+
+ # Initialize property
+ self._age = 0
+
+ # An instance method. All methods take "self" as the first argument
+ def say(self, msg):
+ print("{name}: {message}".format(name=self.name, message=msg))
+
+ # Another instance method
+ def sing(self):
+ return 'yo... yo... microphone check... one two... one two...'
+
+ # A class method is shared among all instances
+ # They are called with the calling class as the first argument
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # A static method is called without a class or instance reference
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+ # A property is just like a getter.
+ # It turns the method age() into a read-only attribute of the same name.
+ # There's no need to write trivial getters and setters in Python, though.
+ @property
+ def age(self):
+ return self._age
+
+ # This allows the property to be set
+ @age.setter
+ def age(self, age):
+ self._age = age
+
+ # This allows the property to be deleted
+ @age.deleter
+ def age(self):
+ del self._age
+
+
+# When a Python interpreter reads a source file it executes all its code.
+# This __name__ check makes sure this code block is only executed when this
+# module is the main program.
+if __name__ == '__main__':
+ # Instantiate a class
+ i = Human(name="Ian")
+ i.say("hi") # "Ian: hi"
+ j = Human("Joel")
+ j.say("hello") # "Joel: hello"
+ # i and j are instances of type Human; i.e., they are Human objects.
+
+ # Call our class method
+ i.say(i.get_species()) # "Ian: H. sapiens"
+ # Change the shared attribute
+ Human.species = "H. neanderthalensis"
+ i.say(i.get_species()) # => "Ian: H. neanderthalensis"
+ j.say(j.get_species()) # => "Joel: H. neanderthalensis"
+
+ # Call the static method
+ print(Human.grunt()) # => "*grunt*"
+
+ # Static methods can be called by instances too
+ print(i.grunt()) # => "*grunt*"
+
+ # Update the property for this instance
+ i.age = 42
+ # Get the property
+ i.say(i.age) # => "Ian: 42"
+ j.say(j.age) # => "Joel: 0"
+ # Delete the property
+ del i.age
+ # i.age # => this would raise an AttributeError
+
+
+####################################################
+## 6.1 Inheritance
+####################################################
+
+# Inheritance allows new child classes to be defined that inherit methods and
+# variables from their parent class.
+
+# Using the Human class defined above as the base or parent class, we can
+# define a child class, Superhero, which inherits the class variables like
+# "species", "name", and "age", as well as methods, like "sing" and "grunt"
+# from the Human class, but can also have its own unique properties.
+
+# To take advantage of modularization by file you could place the classes above
+# in their own files, say, human.py
+
+# To import functions from other files use the following format
+# from "filename-without-extension" import "function-or-class"
+
+from human import Human
+
+
+# Specify the parent class(es) as parameters to the class definition
+class Superhero(Human):
+
+ # If the child class should inherit all of the parent's definitions without
+ # any modifications, you can just use the "pass" keyword (and nothing else)
+ # but in this case it is commented out to allow for a unique child class:
+ # pass
+
+ # Child classes can override their parents' attributes
+ species = 'Superhuman'
+
+ # Children automatically inherit their parent class's constructor including
+ # its arguments, but can also define additional arguments or definitions
+ # and override its methods such as the class constructor.
+ # This constructor inherits the "name" argument from the "Human" class and
+ # adds the "superpower" and "movie" arguments:
+ def __init__(self, name, movie=False,
+ superpowers=["super strength", "bulletproofing"]):
+
+ # add additional class attributes:
+ self.fictional = True
+ self.movie = movie
+ # be aware of mutable default values, since defaults are shared
+ self.superpowers = superpowers
+
+ # The "super" function lets you access the parent class's methods
+ # that are overridden by the child, in this case, the __init__ method.
+ # This calls the parent class constructor:
+ super().__init__(name)
+
+ # override the sing method
+ def sing(self):
+ return 'Dun, dun, DUN!'
+
+ # add an additional instance method
+ def boast(self):
+ for power in self.superpowers:
+ print("I wield the power of {pow}!".format(pow=power))
+
+
+if __name__ == '__main__':
+ sup = Superhero(name="Tick")
+
+ # Instance type checks
+ if isinstance(sup, Human):
+ print('I am human')
+ if type(sup) is Superhero:
+ print('I am a superhero')
+
+ # Get the Method Resolution search Order used by both getattr() and super()
+ # This attribute is dynamic and can be updated
+ print(Superhero.__mro__) # => (,
+ # => , )
+
+ # Calls parent method but uses its own class attribute
+ print(sup.get_species()) # => Superhuman
+
+ # Calls overridden method
+ print(sup.sing()) # => Dun, dun, DUN!
+
+ # Calls method from Human
+ sup.say('Spoon') # => Tick: Spoon
+
+ # Call method that exists only in Superhero
+ sup.boast() # => I wield the power of super strength!
+ # => I wield the power of bulletproofing!
+
+ # Inherited class attribute
+ sup.age = 31
+ print(sup.age) # => 31
+
+ # Attribute that only exists within Superhero
+ print('Am I Oscar eligible? ' + str(sup.movie))
+
+####################################################
+## 6.2 Multiple Inheritance
+####################################################
+
+# Another class definition
+# bat.py
+class Bat:
+
+ species = 'Baty'
+
+ def __init__(self, can_fly=True):
+ self.fly = can_fly
+
+ # This class also has a say method
+ def say(self, msg):
+ msg = '... ... ...'
+ return msg
+
+ # And its own method as well
+ def sonar(self):
+ return '))) ... ((('
+
+if __name__ == '__main__':
+ b = Bat()
+ print(b.say('hello'))
+ print(b.fly)
+
+
+# And yet another class definition that inherits from Superhero and Bat
+# superhero.py
+from superhero import Superhero
+from bat import Bat
+
+# Define Batman as a child that inherits from both Superhero and Bat
+class Batman(Superhero, Bat):
+
+ def __init__(self, *args, **kwargs):
+ # Typically to inherit attributes you have to call super:
+ # super(Batman, self).__init__(*args, **kwargs)
+ # However we are dealing with multiple inheritance here, and super()
+ # only works with the next base class in the MRO list.
+ # So instead we explicitly call __init__ for all ancestors.
+ # The use of *args and **kwargs allows for a clean way to pass
+ # arguments, with each parent "peeling a layer of the onion".
+ Superhero.__init__(self, 'anonymous', movie=True,
+ superpowers=['Wealthy'], *args, **kwargs)
+ Bat.__init__(self, *args, can_fly=False, **kwargs)
+ # override the value for the name attribute
+ self.name = 'Sad Affleck'
+
+ def sing(self):
+ return 'nan nan nan nan nan batman!'
+
+
+if __name__ == '__main__':
+ sup = Batman()
+
+ # Get the Method Resolution search Order used by both getattr() and super().
+ # This attribute is dynamic and can be updated
+ print(Batman.__mro__) # => (,
+ # => ,
+ # => ,
+ # => , )
+
+ # Calls parent method but uses its own class attribute
+ print(sup.get_species()) # => Superhuman
+
+ # Calls overridden method
+ print(sup.sing()) # => nan nan nan nan nan batman!
+
+ # Calls method from Human, because inheritance order matters
+ sup.say('I agree') # => Sad Affleck: I agree
+
+ # Call method that exists only in 2nd ancestor
+ print(sup.sonar()) # => ))) ... (((
+
+ # Inherited class attribute
+ sup.age = 100
+ print(sup.age) # => 100
+
+ # Inherited attribute from 2nd ancestor whose default value was overridden.
+ print('Can I fly? ' + str(sup.fly)) # => Can I fly? False
+
+
+
+####################################################
+## 7. Advanced
+####################################################
+
+# Generators help you make lazy code.
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Generators are memory-efficient because they only load the data needed to
+# process the next value in the iterable. This allows them to perform
+# operations on otherwise prohibitively large value ranges.
+# NOTE: `range` replaces `xrange` in Python 3.
+for i in double_numbers(range(1, 900000000)): # `range` is a generator.
+ print(i)
+ if i >= 30:
+ break
+
+# Just as you can create a list comprehension, you can create generator
+# comprehensions as well.
+values = (-x for x in [1,2,3,4,5])
+for x in values:
+ print(x) # prints -1 -2 -3 -4 -5 to console/terminal
+
+# You can also cast a generator comprehension directly to a list.
+values = (-x for x in [1,2,3,4,5])
+gen_to_list = list(values)
+print(gen_to_list) # => [-1, -2, -3, -4, -5]
+
+
+# Decorators
+# In this example `beg` wraps `say`. If say_please is True then it
+# will change the returned message.
+from functools import wraps
+
+
+def intro(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "My name is Nitkarsh Chourasia.")
+ return msg
+
+ return wrapper
+
+
+@intro
+def say(say_please=False):
+ msg = "I published this static site, here."
+ return msg, say_please
+
+
+print(say()) # I published this static site, here.
+print(say(say_please=True)) # I published this static site, here. My name is Nitkarsh Chourasia.
+
+
+
+
+
+
+####################################################
+## Author's Info
+####################################################
+
+import webbrowser
+
+class Author:
+ def __init__(self, name: str, github_profile_url: str) -> None:
+ """Initialize the Author class with name and GitHub profile URL."""
+ self.name = name
+ self.github_profile_url = github_profile_url
+ self.github_username = github_profile_url[19:]
+
+ def open_github_profile(self) -> None:
+ """Open the author's GitHub profile in a new tab."""
+ return webbrowser.open_new_tab(self.github_profile_url)
+
+# Create an instance of the Author class
+AUTHOR = Author("Nitkarsh Chourasia", "https://github.com/NitkarshChourasia")
+
+# Access the encapsulated data
+print(f"Author Name: {AUTHOR.name}")
+print(f"Github Profile Link: {AUTHOR.github_profile_url}")
+print(f"Github Username: {AUTHOR.github_username}")
+
+# Open the author's GitHub profile in a new tab
+AUTHOR.open_github_profile()
+
+####################################################
+
+```
diff --git a/repo_website/docs/img/favicon.ico b/repo_website/docs/img/favicon.ico
new file mode 100644
index 00000000000..bcc463b858b
Binary files /dev/null and b/repo_website/docs/img/favicon.ico differ
diff --git a/repo_website/mkdocs.yml b/repo_website/mkdocs.yml
new file mode 100644
index 00000000000..152bffd5931
--- /dev/null
+++ b/repo_website/mkdocs.yml
@@ -0,0 +1,77 @@
+site_name: Learn Python Programming Language
+# site_url: https://james-willett.github.io/mkdocs-material-youtube-tutorial/
+# site_url: https://example.com/
+site_url: https://github.com/NitkarshChourasia
+
+nav:
+ - Home: README.md
+ - Downloads: README.md
+ - Music: README.md
+ - Assets: README.md
+ - About: README.md
+
+theme:
+ name: material
+ features:
+ - navigation.tabs
+ - navigation.sections
+ - toc.integrate
+ - navigation.top
+ - search.suggest
+ - search.highlight
+ - content.tabs.link
+ - content.code.annotation
+ - content.code.copy
+ language: en
+ palette:
+ - scheme: default
+ toggle:
+ icon: material/toggle-switch-off-outline
+ name: Switch to dark mode
+ primary: teal
+ accent: purple
+ - scheme: slate
+ toggle:
+ icon: material/toggle-switch
+ name: Switch to light mode
+ primary: teal
+ accent: lime
+# This switch is not appearing, make it good.
+
+# plugins:
+# - social
+
+extra:
+ social:
+ - icon: fontawesome/brands/github-alt
+ link: https://github.com/NitkarshChourasia
+ - icon: fontawesome/brands/twitter
+ link: https://twitter.com/NitkarshC
+ - icon: fontawesome/brands/linkedin
+ link: https://www.linkedin.com/in/willettjames/ # Put mine. Here.
+ link: https://www.linkedin.com/in/nitkarshchourasia
+
+markdown_extensions:
+ - pymdownx.highlight:
+ anchor_linenums: true
+ - pymdownx.inlinehilite
+ - pymdownx.snippets
+ - admonition
+ - pymdownx.arithmatex:
+ generic: true
+ - footnotes
+ - pymdownx.details
+ - pymdownx.superfences
+ - pymdownx.mark
+ - attr_list
+ - pymdownx.emoji:
+ emoji_index: !!python/name:materialx.emoji.twemoji
+ emoji_generator: !!python/name:materialx.emoji.to_svg
+
+copyright: |
+
+ © 2023 Nitkarsh Chourasia
+
+# At the last ask bing how to improve it further.
+
+# Make it fully, and extra loaded.
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 00000000000..ba601b8c8ab
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,113 @@
+pafy
+aiohttp
+fuzzywuzzy
+hupper
+seaborn
+time
+simplegui
+utils
+Tubes
+modules
+pdf2docx
+pong
+beautifulsoup4
+dictator
+caller
+watchdog
+PyQt5
+numpy
+fileinfo
+backend
+win10toast
+Counter
+Flask
+selenium
+firebase-admin
+ujson
+requests
+quo
+PyPDF2
+pyserial
+twilio
+tabula
+nltk
+Pillow
+SocksiPy-branch
+xlrd
+fpdf
+mysql-connector-repackaged
+word2number
+tornado
+obs
+todo
+oauth2client
+keras
+pymongo
+playsound
+pyttsx3
+auto-mix-prep
+lib
+pywifi
+patterns
+openai
+background
+pydantic
+openpyxl
+pytesseract
+requests-mock
+pyglet
+urllib3
+thirdai
+google-api-python-client
+sound
+xlwt
+pygame
+speechtotext
+wikipedia
+tqdm
+Menu
+yfinance
+tweepy
+tkcalendar
+pytube
+xor-cipher
+bird
+mechanize
+translate
+solara
+pywhatkit
+mutagen
+Unidecode
+Ball
+pynput
+gTTS
+ccxt
+fitz
+fastapi
+Django
+docx
+matplotlib
+pyshorteners
+geocoder
+APScheduler
+PyQRCode
+freegames
+pyperclip
+newspaper
+opencv-python
+tensorflow
+pandas
+pytest
+qrcode
+googletrans
+slab
+psutil
+mediapipe
+rich
+httplib2
+protobuf
+colorama
+plyer
+Flask-Ask
+emoji
+PyAutoGUI
diff --git a/requirements_with_versions.txt b/requirements_with_versions.txt
new file mode 100644
index 00000000000..39189267917
--- /dev/null
+++ b/requirements_with_versions.txt
@@ -0,0 +1,113 @@
+pafy==0.5.5
+aiohttp==3.12.12
+fuzzywuzzy==0.18.0
+hupper==1.12.1
+seaborn==0.13.2
+time==1.0.0
+simplegui==0.1.1
+utils==1.0.2
+Tubes==0.2.1
+modules==1.0.0
+pdf2docx==0.5.8
+pong==1.5
+beautifulsoup4==4.13.4
+dictator==0.3.1
+caller==0.0.2
+watchdog==6.0.0
+PyQt5==5.15.11
+numpy==2.2.3
+fileinfo==0.3.3
+backend==0.2.4.1
+win10toast==0.9
+Counter==1.0.0
+Flask==3.1.1
+selenium==4.33.0
+firebase-admin==6.9.0
+ujson==5.10.0
+requests==2.32.4
+quo==2023.5.1
+PyPDF2==3.0.1
+pyserial==3.5
+twilio==9.6.2
+tabula==1.0.5
+nltk==3.9.1
+Pillow==11.2.1
+SocksiPy-branch==1.01
+xlrd==2.0.1
+fpdf==1.7.2
+mysql-connector-repackaged==0.3.1
+word2number==1.1
+tornado==6.5.1
+obs==0.0.0
+todo==0.1
+oauth2client==4.1.3
+keras==3.10.0
+pymongo==4.12.1
+playsound==1.3.0
+pyttsx3==2.98
+auto-mix-prep==0.2.0
+lib==4.0.0
+pywifi==1.1.12
+patterns==0.3
+openai==1.86.0
+background==0.2.1
+pydantic==2.11.6
+openpyxl==3.1.2
+pytesseract==0.3.13
+requests-mock==1.12.1
+pyglet==2.1.6
+urllib3==2.4.0
+thirdai==0.9.33
+google-api-python-client==2.172.0
+sound==0.1.0
+xlwt==1.3.0
+pygame==2.6.1
+speechtotext==0.0.3
+wikipedia==1.4.0
+tqdm==4.67.1
+Menu==3.2.2
+yfinance==0.2.62
+tweepy==4.15.0
+tkcalendar==1.6.1
+pytube==15.0.0
+xor-cipher==5.0.2
+bird==0.1.2
+mechanize==0.4.10
+translate==3.6.1
+solara==1.48.0
+pywhatkit==5.4
+mutagen==1.47.0
+Unidecode==1.4.0
+Ball==0.2.9
+pynput==1.8.1
+gTTS==2.5.4
+ccxt==4.4.86
+fitz==0.0.1.dev2
+fastapi==0.115.12
+Django==5.1.7
+docx==0.2.4
+matplotlib==3.10.0
+pyshorteners==1.0.1
+geocoder==1.38.1
+APScheduler==3.11.0
+PyQRCode==1.2.1
+freegames==2.5.3
+pyperclip==1.8.2
+newspaper==0.1.0.7
+opencv-python==4.11.0.86
+tensorflow==2.18.1
+pandas==2.2.3
+pytest==8.4.0
+qrcode==8.2
+googletrans==4.0.2
+slab==1.8.0
+psutil==7.0.0
+mediapipe==0.10.21
+rich==14.0.0
+httplib2==0.22.0
+protobuf==6.31.1
+colorama==0.4.6
+plyer==2.1.0
+Flask-Ask==0.9.8
+emoji==2.14.1
+PyAutoGUI==0.9.54
diff --git a/rock_paper_scissor_game.py b/rock_paper_scissor_game.py
index 21ab7c3ba50..1cc3c8dedd3 100644
--- a/rock_paper_scissor_game.py
+++ b/rock_paper_scissor_game.py
@@ -47,3 +47,6 @@ def game(player_choice):
print("draw")
elif diff == 2 or diff == 4:
print("you lose!!!")
+
+
+# Also improve it
diff --git a/sWAP_cASE.py b/sWAP_cASE.py
deleted file mode 100644
index f3c21d55ad9..00000000000
--- a/sWAP_cASE.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
-
-
-def swap_case(s):
- return s.swapcase()
-
-
-if __name__ == "__main__":
- s = input()
- result = swap_case(s)
- print(result)
diff --git a/saving_input_into_list.py b/saving_input_into_list.py
new file mode 100644
index 00000000000..03caac68016
--- /dev/null
+++ b/saving_input_into_list.py
@@ -0,0 +1,13 @@
+ran= int(input("Enter the range of elements you want to store / insert "))
+l1=[]
+for i in range(ran):
+ l1.append(input("Enter here "))
+
+print(l1)
+
+
+"""
+program first asks the user how many values they want to enter. Then, using a loop, it lets the user enter that many values one by one.
+Each entered value is saved into a list called l1. Once all the values are entered, the program prints the complete list, showing
+everything the user typed. It's a beginner-friendly way to learn how to collect multiple inputs and store them for later use.
+"""
\ No newline at end of file
diff --git a/scientific_cal.py b/scientific_cal.py
new file mode 100644
index 00000000000..9827ec8f44f
--- /dev/null
+++ b/scientific_cal.py
@@ -0,0 +1,45 @@
+import math
+while True:
+ print("""
+ Press 1 for basic calculator
+ Press 2 for scientifc calculator""")
+ try:
+ cho= int(input("enter your choice here.. "))
+ if cho == 1:
+ print(eval(input("enter the numbers with operator ")))
+ elif cho==2:
+ user = int(input("""
+ Press 1 for pi calculation
+ press 2 for sin calculation
+ press 3 for exponent calculation
+ press 4 for tangent calculation
+ press 5 for square root calculation
+ press 6 round calculation
+ press 7 for absoulte value
+ press any other number to exit the loop. """))
+
+ a= float(input("enter your value here.. "))
+ if user== 1:
+ print(f"entered value : {a} result :{math.pi*(a)}")
+ elif user ==2:
+ print(f"entered value : {a} result :{math.sin(math.radians(a))}")
+
+ elif user == 3:
+ power= float(input("enter the power"))
+ print(f"entered value : {a} result :{a**power}")
+ elif user ==4:
+ angle_in_radians = math.radians(a)
+ result = math.tan(angle_in_radians)
+ print(f"entered value : {a} result :{result}")
+ elif user ==5 :
+ print(f"entered value : {a} result :{math.sqrt(a)}")
+ elif user== 6:
+ print(f"entered value : {a} result :{round(a)}")
+ elif user ==7 :
+ print(f"entered value : {a} result :{abs(a)}")
+ else:
+ break
+ except ZeroDivisionError:
+ print("value cannot be divided by 0")
+ except:
+ print("Enter only digits ")
\ No newline at end of file
diff --git a/send_message_automation/README.md b/send_message_automation/README.md
new file mode 100644
index 00000000000..c38ad7bb52a
--- /dev/null
+++ b/send_message_automation/README.md
@@ -0,0 +1,8 @@
+# Send message automation
+
+
+sources used:
+
+
+Gif image creation credit goes to:
+- ezgif.com used to make gif images.
\ No newline at end of file
diff --git a/send_message_automation/author_name_NC.txt b/send_message_automation/author_name_NC.txt
new file mode 100644
index 00000000000..17822fa7961
--- /dev/null
+++ b/send_message_automation/author_name_NC.txt
@@ -0,0 +1,7 @@
+
+ __ _ _ _ _ ___ _ _
+ /\ \ \(_)| |_ | | __ __ _ _ __ ___ | |__ / __\| |__ ___ _ _ _ __ __ _ ___ (_) __ _
+ / \/ /| || __|| |/ / / _` || '__|/ __|| '_ \ / / | '_ \ / _ \ | | | || '__| / _` |/ __|| | / _` |
+/ /\ / | || |_ | < | (_| || | \__ \| | | | / /___ | | | || (_) || |_| || | | (_| |\__ \| || (_| |
+\_\ \/ |_| \__||_|\_\ \__,_||_| |___/|_| |_| \____/ |_| |_| \___/ \__,_||_| \__,_||___/|_| \__,_|
+
diff --git a/send_message_automation/automatic_send-message_demo_video.mp4 b/send_message_automation/automatic_send-message_demo_video.mp4
new file mode 100644
index 00000000000..f01908000bf
Binary files /dev/null and b/send_message_automation/automatic_send-message_demo_video.mp4 differ
diff --git a/send_message_automation/message_automation.py b/send_message_automation/message_automation.py
new file mode 100644
index 00000000000..5a797ece210
--- /dev/null
+++ b/send_message_automation/message_automation.py
@@ -0,0 +1,41 @@
+import pyautogui
+from time import sleep
+
+# Do you want to include the message counter?
+# make a class of it.
+
+# Can make a broswer session open and navigating to web.whatsapp
+# os dependencies and browser dependencies and default browser if none
+# also check for whatsapp on the system
+
+
+def send_message(message):
+ pyautogui.write(message)
+ pyautogui.press("enter")
+
+
+def send_repeatedly(message, repetitions, delay):
+ count = 1
+ try:
+ for _ in range(repetitions):
+ send_message(f"Message {count}: {message}")
+ sleep(delay)
+ count += 1
+ except KeyboardInterrupt:
+ print("\nProgram terminated by user.")
+
+
+if __name__ == "__main__":
+ try:
+ user_message = input("Enter the message you want to send: ")
+ repetitions = int(input("Enter the number of repetitions: "))
+ delay = float(input("Enter the delay between messages (in seconds): "))
+
+ sleep(5)
+ send_repeatedly(user_message, repetitions, delay)
+
+ except ValueError:
+ print("Invalid input. Please enter a valid number.")
+
+ except Exception as e:
+ print(f"An error occurred: {str(e)}")
diff --git a/send_message_automation/send_message_automation_demo_gif_image.gif b/send_message_automation/send_message_automation_demo_gif_image.gif
new file mode 100644
index 00000000000..f186167a965
Binary files /dev/null and b/send_message_automation/send_message_automation_demo_gif_image.gif differ
diff --git a/send_message_automation/send_message_automation_demo_video_2.mp4 b/send_message_automation/send_message_automation_demo_video_2.mp4
new file mode 100644
index 00000000000..db973e981e1
Binary files /dev/null and b/send_message_automation/send_message_automation_demo_video_2.mp4 differ
diff --git a/simple_calcu.py b/simple_calcu.py
new file mode 100644
index 00000000000..f31ca843ac8
--- /dev/null
+++ b/simple_calcu.py
@@ -0,0 +1,5 @@
+while True:
+ print(int(input("enter first number..")) + int(input("enter second number..")))
+ q= input("press q to quit or press anu key to continue").lower()
+ if q==" q":
+ break
\ No newline at end of file
diff --git a/simple_calculator/simple_calculator.py b/simple_calculator/simple_calculator.py
new file mode 100644
index 00000000000..b84588896c4
--- /dev/null
+++ b/simple_calculator/simple_calculator.py
@@ -0,0 +1,57 @@
+# Define functions for each operation
+def add(x, y):
+ return x + y
+
+def subtract(x, y):
+ return x - y
+
+def multiply(x, y):
+ return x * y
+
+def divide(x, y):
+ # Prevent division by zero
+ if y == 0:
+ return "Error: Division by zero is not allowed"
+ return x / y
+
+# Display the options to the user
+def display_menu():
+ print("\nSelect operation:")
+ print("1. Add")
+ print("2. Subtract")
+ print("3. Multiply")
+ print("4. Divide")
+
+# Main program loop
+while True:
+ display_menu()
+
+ # Take input from the user
+ choice = input("Enter choice (1/2/3/4): ")
+
+ # Check if the choice is valid
+ if choice in ('1', '2', '3', '4'):
+ try:
+ num1 = float(input("Enter first number: "))
+ num2 = float(input("Enter second number: "))
+ except ValueError:
+ print("Invalid input. Please enter numeric values.")
+ continue
+
+ # Perform the chosen operation
+ if choice == '1':
+ print(f"{num1} + {num2} = {add(num1, num2)}")
+ elif choice == '2':
+ print(f"{num1} - {num2} = {subtract(num1, num2)}")
+ elif choice == '3':
+ print(f"{num1} * {num2} = {multiply(num1, num2)}")
+ elif choice == '4':
+ print(f"{num1} / {num2} = {divide(num1, num2)}")
+
+ # Check if the user wants another calculation
+ next_calculation = input("Do you want to perform another calculation? (yes/no): ").lower()
+ if next_calculation != 'yes':
+ print("Exiting the calculator.")
+ break
+ else:
+ print("Invalid input. Please select a valid operation.")
diff --git a/sorting_algos.py b/sorting_algos.py
new file mode 100644
index 00000000000..d34169a5141
--- /dev/null
+++ b/sorting_algos.py
@@ -0,0 +1,121 @@
+'''Contains some of the Major Sorting Algorithm'''
+
+def selection_sort(arr : list) -> list:
+ '''TC : O(n^2)
+ SC : O(1)'''
+ n = len(arr)
+ for i in range( n):
+ for j in range(i+1 , n):
+ if arr[i] > arr[j]:
+ arr[i] , arr[j] = arr[j] , arr[i]
+ return arr
+
+def bubble_sort(arr : list) -> list:
+ '''TC : O(n^2)
+ SC : O(1)'''
+ n = len(arr)
+ flag = True
+ while flag:
+ flag = False
+ for i in range(1 , n):
+ if arr[i-1] > arr[i]:
+ flag = True
+ arr[i-1] , arr[i] = arr[i] , arr[i-1]
+ return arr
+
+def insertion_sort(arr : list) -> list:
+ '''TC : O(n^2)
+ SC : O(1)'''
+ n = len(arr)
+ for i in range(1, n):
+ for j in range(i , 0 , -1):
+ if arr[j-1] > arr[j]:
+ arr[j-1] , arr[j] = arr[j] , arr[j-1]
+ else :
+ break
+ return arr
+
+def merge_sort(arr : list) -> list:
+ '''TC : O(nlogn)
+ SC : O(n) for this version ... But SC can be reduced to O(1)'''
+ n = len(arr)
+ if n == 1: return arr
+
+ m = len(arr) // 2
+ L = arr[:m]
+ R = arr[m:]
+ L = merge_sort(L)
+ R = merge_sort(R)
+ l = r = 0
+
+ sorted_arr = [0] * n
+ i = 0
+
+ while l < len(L) and r < len(R):
+ if L[l] < R[r]:
+ sorted_arr[i] = L[l]
+ l += 1
+ else :
+ sorted_arr[i] = R[r]
+ r += 1
+ i += 1
+
+ while l < len(L):
+ sorted_arr[i] = L[l]
+ l += 1
+ i += 1
+
+ while r < len(R):
+ sorted_arr[i] = R[r]
+ r += 1
+ i += 1
+
+ return arr
+
+def quick_sort(arr : list) -> list:
+ '''TC : O(nlogn) (TC can be n^2 for SUUUper worst case i.e. If the Pivot is continuously bad)
+ SC : O(n) for this version ... But SC can be reduced to O(logn)'''
+
+ if len(arr) <= 1: return arr
+
+ piv = arr[-1]
+ L = [x for x in arr[:-1] if x <= piv]
+ R = [x for x in arr[:-1] if x > piv]
+
+ L , R = quick_sort(L) , quick_sort(L)
+
+ return L + [piv] + R
+
+def counting_sort(arr : list) -> list:
+ '''This Works only for Positive int's(+ve), but can be modified for Negative's also
+
+ TC : O(n)
+ SC : O(n)'''
+ n = len(arr)
+ maxx = max(arr)
+ counts = [0] * (maxx + 1)
+ for x in arr:
+ counts[x] += 1
+
+ i = 0
+ for c in range(maxx + 1):
+ while counts[c] > 0:
+ arr[i] = c
+ i += 1
+ counts[c] -= 1
+ return arr
+
+def main():
+ algos = {'selection_sort' : ['TC : O(n^2)','SC : O(1)'],
+ 'bubble_sort' : ['TC : O(n^2)','SC : O(1)'],
+ 'insertion_sort' : ['TC : O(n^2)','SC : O(1)'],
+ 'merge_sort' : ['TC : O(n^2)','SC : O(1)'],
+ 'quick_sort' : ['TC : O(n^2)','SC : O(1)'],
+ 'counting_sort' : ['TC : O(n^2)','SC : O(1)'],}
+
+ inp = [1 , 2 ,7 , -8 , 34 , 2 , 80 , 790 , 6]
+ arr = counting_sort(inp)
+ print('U are amazing, Keep up')
+
+if __name__ == '__main__':
+ main()
\ No newline at end of file
diff --git a/square_root.py b/square_root.py
new file mode 100644
index 00000000000..768340a9104
--- /dev/null
+++ b/square_root.py
@@ -0,0 +1,9 @@
+import math
+
+def square_root(number):
+ if number >=0:
+ print(f"Square root {math.sqrt(number)}")
+ else:
+ print("Cannot find square root for the negative numbers..")
+while True:
+ square_root(int(input("enter any number")))
\ No newline at end of file
diff --git a/string_palin.py b/string_palin.py
new file mode 100644
index 00000000000..1349f993c4c
--- /dev/null
+++ b/string_palin.py
@@ -0,0 +1,20 @@
+#
+
+# With slicing -> Reverses the string using string[::-1]
+
+
+string= input("enter a word to check.. ")
+copy=string[::-1]
+if string == copy:
+ print("Plaindrome")
+else:
+ print("!")
+
+# Without slicing –> Reverses the string manually using a loop
+reverse_string=""
+for i in string:
+ reverse_string=i+reverse_string
+if string == reverse_string:
+ print(reverse_string)
+else:
+ print("!")
\ No newline at end of file
diff --git a/sum_of_digits_of_a_number.py b/sum_of_digits_of_a_number.py
new file mode 100644
index 00000000000..06bb321441f
--- /dev/null
+++ b/sum_of_digits_of_a_number.py
@@ -0,0 +1,28 @@
+import sys
+
+def get_integer_input(prompt, attempts):
+ for i in range(attempts, 0, -1):
+ try:
+ n = int(input(prompt))
+ return n
+ except ValueError:
+ print("Enter an integer only")
+ print(f"{i-1} {'chance' if i-1 == 1 else 'chances'} left")
+ return None
+
+def sum_of_digits(n):
+ total = 0
+ while n > 0:
+ total += n % 10
+ n //= 10
+ return total
+
+chances = 3
+number = get_integer_input("Enter a number: ", chances)
+
+if number is None:
+ print("You've used all your chances.")
+ sys.exit()
+
+result = sum_of_digits(number)
+print(f"The sum of the digits of {number} is: {result}")
diff --git a/swap.py b/swap.py
index 9cff84bdca7..00971b94165 100644
--- a/swap.py
+++ b/swap.py
@@ -27,7 +27,7 @@ def __init__(self, x, y):
The second value to be swapped.
"""
- if not isinstance(x, int) or not isinstance(y, int):
+ if not isinstance(x, (int, float)) or not isinstance(y, (float, int)):
raise ValueError("Both x and y should be integers.")
self.x = x
diff --git a/text_to_audio/README.md b/text_to_audio/README.md
new file mode 100644
index 00000000000..4cca8f6131d
--- /dev/null
+++ b/text_to_audio/README.md
@@ -0,0 +1,12 @@
+Improvement: Nitkarsh Chourasia
+
+Improvement made:
+Used class
+implemented lazy loading
+optimised memory by selective importing of modules and it's methods
+uses effective exception handling
+tested on windows and linux
+gui is to be made
+Memory optimised
+PEP8 compliant
+linter friendly :
\ No newline at end of file
diff --git a/text_to_audio/author_name_NC.txt b/text_to_audio/author_name_NC.txt
new file mode 100644
index 00000000000..17822fa7961
--- /dev/null
+++ b/text_to_audio/author_name_NC.txt
@@ -0,0 +1,7 @@
+
+ __ _ _ _ _ ___ _ _
+ /\ \ \(_)| |_ | | __ __ _ _ __ ___ | |__ / __\| |__ ___ _ _ _ __ __ _ ___ (_) __ _
+ / \/ /| || __|| |/ / / _` || '__|/ __|| '_ \ / / | '_ \ / _ \ | | | || '__| / _` |/ __|| | / _` |
+/ /\ / | || |_ | < | (_| || | \__ \| | | | / /___ | | | || (_) || |_| || | | (_| |\__ \| || (_| |
+\_\ \/ |_| \__||_|\_\ \__,_||_| |___/|_| |_| \____/ |_| |_| \___/ \__,_||_| \__,_||___/|_| \__,_|
+
diff --git a/text_to_audio/main.py b/text_to_audio/main.py
new file mode 100644
index 00000000000..ff7a3e56e64
--- /dev/null
+++ b/text_to_audio/main.py
@@ -0,0 +1,205 @@
+# A exclusive CLI version can be made using inquirer library.
+from gtts import gTTS
+from io import BytesIO
+
+# only use when needed to avoid memory usage in program
+from pprint import pprint
+
+"""_summary_
+def some_function():
+ # Pygame module is only imported when this function is called
+ import pygame.mixer as mixer
+ mixer.init()
+
+# USE LAZY LOADING
+
+ Returns:
+ _type_: _description_
+ """
+
+"""
+# For example, if you are using pygame, you might do something like:
+# import pygame
+# audio_file.seek(0) # Reset the BytesIO object to the beginning
+# pygame.mixer.init()
+# pygame.mixer.music.load(audio_file)
+# pygame.mixer.music.play()
+
+# Note: The actual loading and playing of the MP3 data in an audio library are not provided in the code snippet.
+# The last comments indicate that it depends on the specific audio library you choose.
+
+"""
+# Should have
+
+# How to play a audio without saving it?
+# efficiently?
+# So I can also combine two languages?
+# Exception for network issues?
+
+# class userAudio:
+
+# print("\n")
+# print(dir(gTTS))
+
+# file_naming can be added too.
+
+
+class userAudio:
+ def __init__(
+ self,
+ text: str = None,
+ language: str = "en",
+ slow: bool = True,
+ accent: str = "com",
+ ): # Correct the syntax here.
+ self.lang = language
+ self.slow = slow
+ self.accent = accent
+
+ if text is None:
+ self.user_input()
+ else:
+ self.text_to_audio = text
+
+ self.gtts_object = gTTS(
+ text=self.text_to_audio, lang=self.lang, slow=self.slow, tld=self.accent
+ )
+
+ # ! Some error is here.
+ def user_input(self):
+ text = input("Enter the text you want to convert to audio: ")
+ self.text_to_audio = text
+ self.gtts_object = gTTS(
+ text=self.text_to_audio, lang=self.lang, slow=self.slow, tld=self.accent
+ ) # Just need to understand the class workings little better.
+ # Isn't this declaring this again?
+
+ def save_only(self, filename="default.mp3"):
+ # The class will take care of the playing and saving.
+ # The initialisation will take care of it.
+ self.gtts_object.save(filename)
+
+ def play_only(self):
+ from pygame import mixer, time
+
+ tts = self.gtts_object
+ fp = BytesIO()
+ tts.write_to_fp(fp)
+ fp.seek(0) # Reset the BytesIO object to the beginning
+ mixer.init()
+ mixer.music.load(fp)
+ mixer.music.play()
+ while mixer.music.get_busy():
+ time.Clock().tick(10)
+ # Consider using a different method for playing audio, Pygame might not be optimal
+
+ # Object initialisation please.
+ # def save_path(self):
+ # from pathlib import Path
+
+ # user_path = Path(input("Enter the path to save the audio: "))
+
+ # # .exists() is a method in Path class
+ # if user_path.exists:
+ # pprint(f"The provided path {user_path} exists.")
+ # # full_path = user_path + "/" + input("Enter the file name: ")
+ # full_path = user_path + "/" + "default.mp3"
+ # self.save(user_path)
+ # pprint("File saved successfully")
+ # else:
+ # # prompts the user again three times to do so.
+ # # if not then choose the default one asking user to choose the default one.
+ # # if he says no, then asks to input again.
+ # # then ask three times.
+ # # at max
+ # """dir testing has to be done seprately"""
+
+ # if user_path.is_dir:
+ # gTTS.save(user_path)
+
+ # def file_name(self):
+ # while True:
+ # file_path = input("Enter the file path: ")
+ # if file_path.exists:
+ # break
+ # else:
+ # # for wrong input type exceptions
+ # while True:
+ # continue_response = input("Are you sure you want to continue?(y/n):")
+ # continue_response = continue_response.strip().lower()
+ # if continue_response in ["y", "yes", "start"]:
+ # break
+ # elif continue_response in ["n", "no", "stop"]:
+ # break
+ # # file_path = user_path + "/" + input("Enter the file name: ")
+ # # file_path = user_path + "/" + "default.mp3"
+ # # Also work a best way to save good quality audio and what is best format to save it in.
+
+ # def save_and_play(self):
+ # self.save_only()
+ # self.play_only()
+ # self.save_path()
+ # self.file_name()
+
+ # def concatenate_audio(self):
+ # # logic to concatenate audio?
+ # # why, special feature about it?
+ # # this is not a logic concatenation application.
+ # pass
+
+
+# hello = userAudio("Hello, world!")
+# hello.play_only()
+
+with open("special_file.txt", "r") as f:
+ retrieved_text = f.read()
+retrieved_text = retrieved_text.replace("\n", "")
+
+# hello = userAudio("Hello, user how are you?", slow=False)
+hello = userAudio
+hello.play_only()
+
+
+class fun_secret_generator_string:
+ # Instructions on how to use it?
+ def __init__(self, string):
+ self.string = string
+
+ # text = "Input your text here."
+ # with open("special_file.txt", "w") as f:
+ # for char in text:
+ # f.write(char + "\n")
+ # f.close()
+ # print("File saved successfully")
+
+ # Reading from the file
+ with open("special_file.txt", "r") as f:
+ retrieved_text = f.read()
+ retrieved_text = retrieved_text.replace("\n", "")
+
+
+# Also have an option to play from a file, a text file.
+# Will later put other pdf and word2docx vectorisations.
+# from gtts import gTTS
+# import os
+
+# # Enter the name of your text file
+# mytextfile = "hello.txt"
+
+# # Specify the language in which you want your audio
+# language = "en"
+
+# # Get the contents of your file
+# with open(mytextfile, 'r') as f:
+# mytext = f.read()
+# f.close()
+
+# # Create an instance of gTTS class
+# myobj = gTTS(text=mytext, lang=language, slow=False)
+
+# # Method to create your audio file in mp3 format
+# myobj.save("hello.mp3")
+# print("Audio Saved")
+
+# # This will play your audio file
+# os.system("mpg321 hello.mp3")
diff --git a/text_to_audio/requirements.txt b/text_to_audio/requirements.txt
new file mode 100644
index 00000000000..01a5c752ec0
--- /dev/null
+++ b/text_to_audio/requirements.txt
@@ -0,0 +1,2 @@
+gTTS==2.5.4
+pygame==2.6.1
diff --git a/text_to_audio/special_file.txt b/text_to_audio/special_file.txt
new file mode 100644
index 00000000000..40148d26029
--- /dev/null
+++ b/text_to_audio/special_file.txt
@@ -0,0 +1,67 @@
+T
+e
+r
+i
+
+m
+a
+a
+
+k
+i
+
+c
+h
+u
+t
+,
+
+b
+h
+o
+s
+d
+i
+k
+e
+
+j
+a
+k
+a
+r
+
+g
+a
+a
+a
+n
+d
+
+m
+a
+a
+r
+a
+a
+n
+a
+a
+
+c
+h
+u
+t
+
+m
+a
+a
+a
+r
+a
+a
+n
+i
+
+k
+e
diff --git a/text_to_pig_latin.py b/text_to_pig_latin.py
new file mode 100644
index 00000000000..850b13913e8
--- /dev/null
+++ b/text_to_pig_latin.py
@@ -0,0 +1,38 @@
+"""
+This program converts English text to Pig-Latin. In Pig-Latin, we take the first letter of each word,
+move it to the end, and add 'ay'. If the first letter is a vowel, we simply add 'hay' to the end.
+The program preserves capitalization and title case.
+
+For example:
+- "Hello" becomes "Ellohay"
+- "Image" becomes "Imagehay"
+- "My name is John Smith" becomes "Ymay amenay ishay Ohnjay Mithsmay"
+"""
+
+
+def pig_latin_word(word):
+ vowels = "AEIOUaeiou"
+
+ if word[0] in vowels:
+ return word + "hay"
+ else:
+ return word[1:] + word[0] + "ay"
+
+def pig_latin_sentence(text):
+ words = text.split()
+ pig_latin_words = []
+
+ for word in words:
+ # Preserve capitalization
+ if word.isupper():
+ pig_latin_words.append(pig_latin_word(word).upper())
+ elif word.istitle():
+ pig_latin_words.append(pig_latin_word(word).title())
+ else:
+ pig_latin_words.append(pig_latin_word(word))
+
+ return ' '.join(pig_latin_words)
+
+user_input = input("Enter some English text: ")
+pig_latin_text = pig_latin_sentence(user_input)
+print("\nPig-Latin: " + pig_latin_text)
diff --git a/tower_of_hanoi.py b/tower_of_hanoi.py
deleted file mode 100644
index 0fbf061b96a..00000000000
--- a/tower_of_hanoi.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move
- the entire stack to another rod, obeying the following simple rules:
-1) Only one disk can be moved at a time.
-2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk
- can only be moved if it is the uppermost disk on a stack.
-3) No disk may be placed on top of a smaller disk.
-APPROACH:
-Take an example for 2 disks :
-Let rod 1 = 'SOURCE', rod 2 = 'TEMPORARY', rod 3 = 'DESTINATION'.
-
-Step 1 : Shift first disk from 'SOURCE' to 'TEMPORARY'.
-Step 2 : Shift second disk from 'SOURCE' to 'DESTINATION'.
-Step 3 : Shift first disk from 'TEMPORARY' to 'DESTINATION'.
-
-The pattern here is :
-Shift 'n-1' disks from 'SOURCE' to 'TEMPORARY'.
-Shift last disk from 'SOURCE' to 'DESTINATION'.
-Shift 'n-1' disks from 'TEMPORARY' to 'DESTINATION'.
-"""
-
-
-def toh(n, s, t, d):
- if n == 1:
- print(s, "-->", d)
- return
- toh(n - 1, s, d, t)
- print(s, "-->", d)
- toh(n - 1, t, s, d)
-
-
-if __name__ == "__main__":
- while 1:
-
- n = int(input("""Enter number of disks:"""))
-
- if n < 0:
- print("Try Again with a valid input")
- continue
- elif n == 0:
- break
- toh(n, "Source", "Temporary", "Destination")
-
- print("ENTER 0 TO EXIT")
diff --git a/turtle_shapes_made.py b/turtle_shapes_made.py
new file mode 100644
index 00000000000..e82ece728f4
--- /dev/null
+++ b/turtle_shapes_made.py
@@ -0,0 +1,49 @@
+import turtle
+
+class ShapeDrawer:
+ def __init__(self, color, pensize):
+ self.turtle = turtle.Turtle()
+ self.turtle.color(color)
+ self.turtle.pensize(pensize)
+
+ def draw_rectangle(self, width, height):
+ for _ in range(2):
+ self.turtle.forward(width)
+ self.turtle.left(90)
+ self.turtle.forward(height)
+ self.turtle.left(90)
+
+ def draw_triangle(self, length):
+ for _ in range(3):
+ self.turtle.forward(length)
+ self.turtle.left(120)
+
+def main():
+ scrn = turtle.Screen()
+ scrn.bgcolor("lavender")
+
+ # Draw Rectangle
+ rectangle_drawer = ShapeDrawer("blue", 3)
+ rectangle_drawer.draw_rectangle(180, 75)
+
+ # Draw Triangle
+ triangle_drawer = ShapeDrawer("hot pink", 4)
+ triangle_drawer.turtle.penup()
+ triangle_drawer.turtle.goto(-90, -75)
+ triangle_drawer.turtle.pendown()
+ triangle_drawer.draw_triangle(100)
+
+ # Add more drawings as needed
+ # ...
+
+ # Example: Draw a circle
+ circle_drawer = ShapeDrawer("green", 2)
+ circle_drawer.turtle.penup()
+ circle_drawer.turtle.goto(0, 0)
+ circle_drawer.turtle.pendown()
+ circle_drawer.turtle.circle(50)
+
+ scrn.exitonclick()
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/tweeter.py b/tweeter.py
index 73a7b3ce57a..1ae534f448e 100644
--- a/tweeter.py
+++ b/tweeter.py
@@ -1,24 +1,13 @@
-"""
-Author: Shreyas Daniel (shreydan)
-Install: tweepy - "pip install tweepy"
-API: Create a twitter app "apps.twitter.com" to get your OAuth requirements.
-Version: 1.0
-
-Tweet text and pics directly from the terminal.
-"""
from __future__ import print_function
-
import os
-
import tweepy
-try:
- input = raw_input
-except NameError:
- pass
+# TODO: Further improvements can be made to the program
+# TODO: Further feature improvements and Refactoring can be done to the program
+# TODO: Add a README.md file showcasing how adding it to the PATH variable can make the posting much easier
-def getStatus():
+def get_status():
lines = []
while True:
line = input()
@@ -26,57 +15,58 @@ def getStatus():
lines.append(line)
else:
break
- status = "\n".join(lines)
- return status
+ return "\n".join(lines)
-def tweetthis(type):
- if type == "text":
- print("Enter your tweet " + user.name)
- tweet = getStatus()
- try:
- api.update_status(tweet)
- except Exception as e:
- print(e)
- return
- elif type == "pic":
- print("Enter pic path " + user.name)
- pic = os.path.abspath(input())
- print("Enter status " + user.name)
- title = getStatus()
- try:
- api.update_with_media(pic, status=title)
- except Exception as e:
- print(e)
- return
+def tweet_text(api, user):
+ print(f"Enter your tweet, {user.name}:")
+ tweet = get_status()
+ try:
+ api.update_status(tweet)
+ print("\nTweet posted successfully!")
+ except tweepy.TweepError as e:
+ print(f"Error posting tweet: {e}")
- print("\n\nDONE!!")
+def tweet_picture(api, user):
+ print(f"Enter the picture path, {user.name}:")
+ pic = os.path.abspath(input())
+ print(f"Enter the status, {user.name}:")
+ title = get_status()
+ try:
+ api.update_with_media(pic, status=title)
+ print("\nTweet with picture posted successfully!")
+ except tweepy.TweepError as e:
+ print(f"Error posting tweet with picture: {e}")
-def initialize():
- global api, auth, user
- ck = "here" # consumer key
- cks = "here" # consumer key SECRET
- at = "here" # access token
- ats = "here" # access token SECRET
+
+def initialize_api():
+ ck = "your_consumer_key"
+ cks = "your_consumer_key_secret"
+ at = "your_access_token"
+ ats = "your_access_token_secret"
auth = tweepy.OAuthHandler(ck, cks)
auth.set_access_token(at, ats)
-
api = tweepy.API(auth)
user = api.me()
+ return api, user
def main():
- doit = int(input("\n1. text\n2. picture\n"))
- initialize()
- if doit == 1:
- tweetthis("text")
- elif doit == 2:
- tweetthis("pic")
- else:
- print("OK, Let's try again!")
- main()
+ try:
+ doit = int(input("\n1. Text\n2. Picture\nChoose option (1/2): "))
+ api, user = initialize_api()
+
+ if doit == 1:
+ tweet_text(api, user)
+ elif doit == 2:
+ tweet_picture(api, user)
+ else:
+ print("Invalid option. Please choose 1 or 2.")
+ except ValueError:
+ print("Invalid input. Please enter a valid number.")
-main()
+if __name__ == "__main__":
+ main()
diff --git a/two_num.py b/two_num.py
index 5780845217f..45719e1ebe4 100644
--- a/two_num.py
+++ b/two_num.py
@@ -1,26 +1,58 @@
-"""Author Anurag Kumar (mailto:anuragkumarak95@gmail.com)
+"""
+Author: Anurag Kumar (mailto:anuragkumarak95@gmail.com)
-Given an array of integers, return indices of the two numbers
-such that they add up to a specific target.
-You may assume that each input would have exactly one solution,
-and you may not use the same element twice.
+Description:
+ This function finds two numbers in a given list that add up to a specified target.
+ It returns the indices of those two numbers.
-Example:
-Given nums = [2, 7, 11, 15], target = 9,
-Because nums[0] + nums[1] = 2 + 7 = 9,
-return [0, 1].
+Constraints:
+ - Each input will have exactly one solution.
+ - The same element cannot be used twice.
+Example:
+ >>> two_sum([2, 7, 11, 15], 9)
+ [0, 1]
"""
+from typing import List, Optional
+
+def two_sum(nums: List[int], target: int) -> Optional[List[int]]:
+ """
+ Finds indices of two numbers in 'nums' that add up to 'target'.
+
+ Args:
+ nums (List[int]): List of integers.
+ target (int): Target sum.
+
+ Returns:
+ Optional[List[int]]: Indices of the two numbers that add up to the target,
+ or None if no such pair is found.
+ """
+ if len(nums) < 2:
+ raise ValueError("Input list must contain at least two numbers.")
+
+ if not all(isinstance(num, int) for num in nums):
+ raise TypeError("All elements in the list must be integers.")
+
+ # Dictionary to track seen values and their indices
+ seen_values = {}
+
+ for index, value in enumerate(nums):
+ complement = target - value
+ if complement in seen_values:
+ return [seen_values[complement], index]
+ seen_values[value] = index
+
+ return None
+
+# Example usage
+if __name__ == "__main__":
+ example_nums = [2, 7, 11, 15]
+ example_target = 9
+ result = two_sum(example_nums, example_target)
-def twoSum(nums, target):
- chk_map = {}
- for index, val in enumerate(nums):
- compl = target - val
- if compl in chk_map:
- indices = [chk_map[compl], index]
- print(indices)
- return [indices]
- else:
- chk_map[val] = index
- return False
+ if result:
+ num1, num2 = example_nums[result[0]], example_nums[result[1]]
+ print(f"Indices that add up to {example_target}: {result} (Values: {num1} + {num2})")
+ else:
+ print(f"No combination found that adds up to {example_target}.")
diff --git a/url_shortner.py b/url_shortner.py
new file mode 100644
index 00000000000..0631a4bdb60
--- /dev/null
+++ b/url_shortner.py
@@ -0,0 +1,14 @@
+# Importing the required libraries.
+import pyshorteners
+
+# Taking input from the user.
+url = input("Enter URL: ")
+
+# Creating an instance of the pyshorteners library.
+shortener = pyshorteners.Shortener()
+
+# Shortening the URL using TinyURL.
+shortened_URL = shortener.tinyurl.short(url)
+
+# Displaying the shortened URL.
+print(f"Shortened URL: {shortened_URL}")
diff --git a/usinglist.py b/usinglist.py
deleted file mode 100644
index d4644216c62..00000000000
--- a/usinglist.py
+++ /dev/null
@@ -1,2 +0,0 @@
-fruits = ['apple', 'kiwi', 'mango']
-fruits.append("kiwi")
diff --git a/very_easy/is_number.py b/very_easy/is_number.py
new file mode 100644
index 00000000000..5dcd98f9eb1
--- /dev/null
+++ b/very_easy/is_number.py
@@ -0,0 +1,33 @@
+# importing the module to check for all kinds of numbers truthiness in python.
+import numbers
+from math import pow
+from typing import Any
+
+# Assign values to author and version.
+__author__ = "Nitkarsh Chourasia"
+__version__ = "1.0.0"
+__date__ = "2023-08-24"
+
+
+def check_number(input_value: Any) -> str:
+ """Check if input is a number of any kind or not."""
+
+ if isinstance(input_value, numbers.Number):
+ return f"{input_value} is a number."
+ else:
+ return f"{input_value} is not a number."
+
+
+if __name__ == "__main__":
+ print(f"Author: {__author__}")
+ print(f"Version: {__version__}")
+ print(f"Function Documentation: {check_number.__doc__}")
+ print(f"Date: {__date__}")
+
+ print() # Just inserting a new blank line.
+
+ print(check_number(100))
+ print(check_number(0))
+ print(check_number(pow(10, 20)))
+ print(check_number("Hello"))
+ print(check_number(1 + 2j))
diff --git a/videodownloder.py b/videodownloder.py
index 489fd210130..6b91829e293 100644
--- a/videodownloder.py
+++ b/videodownloder.py
@@ -18,7 +18,7 @@
d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution)
try:
- d_video.download(__PATH)
+ d_video.download(PATH)
except:
print("Some Error!")
print('Task Completed!')
diff --git a/vigenere_cipher.py b/vigenere_cipher.py
new file mode 100644
index 00000000000..6cb73cef8ae
--- /dev/null
+++ b/vigenere_cipher.py
@@ -0,0 +1,39 @@
+text = "mrttaqrhknsw ih puggrur"
+custom_key = "happycoding"
+
+
+def vigenere(message, key, direction=1):
+ key_index = 0
+ alphabet = "abcdefghijklmnopqrstuvwxyz"
+ final_message = ""
+
+ for char in message.lower():
+ # Append any non-letter character to the message
+ if not char.isalpha():
+ final_message += char
+ else:
+ # Find the right key character to encode/decode
+ key_char = key[key_index % len(key)]
+ key_index += 1
+
+ # Define the offset and the encrypted/decrypted letter
+ offset = alphabet.index(key_char)
+ index = alphabet.find(char)
+ new_index = (index + offset * direction) % len(alphabet)
+ final_message += alphabet[new_index]
+
+ return final_message
+
+
+def encrypt(message, key):
+ return vigenere(message, key)
+
+
+def decrypt(message, key):
+ return vigenere(message, key, -1)
+
+
+print(f"\nEncrypted text: {text}")
+print(f"Key: {custom_key}")
+decryption = decrypt(text, custom_key)
+print(f"\nDecrypted text: {decryption}\n")
diff --git a/voice.py b/voice.py
new file mode 100644
index 00000000000..b8f2a3e23c8
--- /dev/null
+++ b/voice.py
@@ -0,0 +1,14 @@
+from gtts import gTTS
+import os
+
+# Define the text you want to convert to speech
+text = "Hello! This is a sample text to convert to speech."
+
+# Create a gTTS object
+tts = gTTS(text=text, lang='en')
+
+# Save the audio file
+tts.save("output.mp3")
+
+# Play the audio file
+os.system("start output.mp3")
diff --git a/vowels.py b/vowels.py
deleted file mode 100644
index c4cb540b286..00000000000
--- a/vowels.py
+++ /dev/null
@@ -1,19 +0,0 @@
-print("\n### Vowel counter ###\n")
-string = input("Enter a string: ").lower()
-vowels = ["a", "e", "i", "o", "u"]
-
-vowelscounter = 0
-
-
-def checkVowels(letter):
- for i in range(len(vowels)):
- if letter == vowels[i]:
- return True
- return False
-
-
-for i in range(len(string)):
- if checkVowels(string[i]):
- vowelscounter = vowelscounter + 1
-
-print(f"\n### {vowelscounter} vowel(s) were found in the string. ###")
diff --git a/webcam.py b/webcam.py
index 87125999309..30a89df27f4 100644
--- a/webcam.py
+++ b/webcam.py
@@ -1,9 +1,10 @@
# Requirements:
# pip install numpy
-# sudo apt-get install python-openCV
+# pip install opencv-python
# Program:
-# opens your webcam, and records.
+# Opens your webcam and records.
+# Improve this program and make it suitable for general module like use in another programs
import cv2
cap = cv2.VideoCapture(0)
@@ -13,7 +14,7 @@
frames_height = int(cap.get(4))
# Specify the video codec
-# FourCC is plateform dependent, however MJPG is a safe choice.
+# FourCC is platform dependent; however, MJPG is a safe choice.
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
# Create video writer object. Save file to recording.avi
@@ -24,7 +25,6 @@
ret, frame = cap.read()
if ret == True:
-
# Write frame to recording.avi
out.write(frame)
@@ -36,7 +36,7 @@
if cv2.waitKey(1) & 0xFF == ord("q"):
break
-# When everything done, release the capture and video writer
+# When everything is done, release the capture and video writer
cap.release()
out.release()
cv2.destroyAllWindows()
diff --git a/wifi hack by brutefore.py b/wifi hack by brutefore.py
index 50cee0e973c..efcbe2c9347 100644
--- a/wifi hack by brutefore.py
+++ b/wifi hack by brutefore.py
@@ -70,7 +70,7 @@ def getwifi(wifilist, wificount):
sorted(allwifilist, key=lambda st: st[1], reverse=True)
time.sleep(1)
n = 0
- if len(allwifilist) is not 0:
+ if len(allwifilist) != 0:
for item in allwifilist:
if (item[0] not in ssidlist) & (item[0] not in wifilist):
n = n + 1
diff --git a/youtubedownloader.py b/youtubedownloader.py
index 8343098aa0b..55b5bc85990 100644
--- a/youtubedownloader.py
+++ b/youtubedownloader.py
@@ -14,12 +14,16 @@ def download():
url = YouTube(str(url_box.get()))
video = url.streams.first()
filename = filedialog.asksaveasfilename(defaultextension=".mp4", filetypes=[("MP4 files", "*.mp4")])
- video.download(filename=filename)
- messagebox.showinfo('', 'Download completed!')
+ if filename: # Check if a filename is selected
+ video.download(filename=filename)
+ messagebox.showinfo('', 'Download completed!')
+ else:
+ messagebox.showwarning('', 'Download cancelled!')
except Exception as e:
messagebox.showerror("Error", "An error occurred while downloading the video.")
+
root = Tk()
root.title('YouTube Downloader')
root.geometry('780x500+200+200')