Basic scripts

A shared folder with AI prompts and code snippets

From workspace: Python

Team: Main

Total snippets: 74

Python

Basic scripts

74 snippets

Email_scheduler

import smtplib from datetime import datetime import time # asking for credentials email_user = input("Enter your email") email_pass = input("Enter your password") email_to = input("Enter reciver's email") email_time = input("Enter time in...

email-sender

import smtplib to = input("Enter the Email of recipent:\n") content = input("Enter the Content for E-Mail:\n") def sendEmail(to, content): server = smtplib.SMTP('smtp.gmail.com', '587') server.ehlo() server.starttls() ...

email_verification

from dns import resolver import smtplib import socket import re # FIRST CHECK def check_syntax(email): regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' if (re.search(regex, email)): print("Check 1 (Syntax) Passed") ...

DotConnect

from tkinter import * from tkinter import font # Constants TOLERANCE = 8 CELL_SIZE = 40 OFFSET = 10 CIRCLE_RADIUS = 5 DOT_OFFSET = OFFSET + CIRCLE_RADIUS GAME_HEIGHT = 400 GAME_WIDTH = 400 # Player Class class Player: def __init__(self,...

Domain_name

import requests import decouple req_headers = {} def godaddy_credentials(): """ This functions reads your credentials from .env file """ global req_headers print("\n\t::: Reading Godaddy Credentials :::") ...

Word_detection

''' output : word detection on document (Simple OCR type of application) ''' import cv2 import numpy as np import imutils # frame read frame = cv2.imread('test.jpeg') # resize frame = cv2.resize(frame, (600, 600)) # grayscale gray =...

DND Verifier

# DNS VERIFIER import json import sys from collections import OrderedDict import dns.resolver def checker(dns_val=None) -> OrderedDict: ip_values = None avail = False if dns_val is None: raise ValueError("Sorry DNS not...

distance_conversion

import tkinter as tk from tkinter import * from tkinter import messagebox # main window root = tk.Tk() # window size (width x height) root.geometry("600x350") # title of window root.title("Distance Unit Converter") # disabling resizing...

DiskSpaceAnalyzer

import os def get_size(path): total_size = 0 if os.path.isfile(path): return os.path.getsize(path) elif os.path.isdir(path): for dirpath, dirnames, filenames in os.walk(path): for f in filenames: ...

Discord bot

import random import discord from discord.ext import commands # Your token here, inside the "" TOKEN = "" # Channel to send welcome messages to WELCOME_CHANNEL = "welcome" # All the nicknames for the random_nickname command NICKS = ["example1",...

Browser

# importing required libraries from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtWebEngineWidgets import * from PyQt5.QtPrintSupport import * import os import sys # creating main window class class...

Brick Breaker game

import pygame from pygame.locals import * pygame.init() ''' Defining gaming window size and font ''' Window_width = 500 Window_height = 500 window = pygame.display.set_mode((Window_width,...

Brain Teaser Game

import random # Define a list of brain teasers as tuples (question, answer) brain_teasers = [ ("I speak without a mouth and hear without ears. I have no body, but I come alive with the wind. What am I?", "an echo"), ("What comes once in a...

BMI_Calculator

from tkinter import * root = Tk() root.geometry("1350x650+0+0") root.resizable(0, 0) root.title("BMI CALCULATOR") def BMI_Cal(): Bheight = float(var2.get()) Bweight = float(var1.get()) BMI = str('%.2f' % (Bweight / (Bheight *...

BlurImage

# from re import X from tkinter.filedialog import * import tkinter as tk import cv2 window = tk.Tk() window.title("Image Blur") window.geometry('350x200') label = tk.Label(window, text="Choose an option").grid(row=0, column=1) def blur1(): ...

BlobDetection

import cv2 from tkinter.filedialog import * # we will find number of blobs with pixel value 255 in the following image # finding binary image print("\nImage should preferably be white (lighter) blobs on black (darker) background ") photo =...

blackjack

# IMPORT MODULES AND DEFINE VARIABLES import random playing = True # CLASSES class Card: # Creates all the cards def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return...

Bitcoin price tracker

import requests from bs4 import BeautifulSoup import time # create a function to get price of cryptocurrency def get_latest_crypto_price(coin): url = 'https://www.google.com/search?q=' + (coin) + 'price' # make a request to the website ...

Bitcoin Mining

# INPUT : Transactions = '''Neeraj->Zara->50,Nandu->Allu->5''' , difficulty=2 , # Previous_hash = a7sdxa036944e29568d0cff17edbe038f81208fecf9a66be9a2b8321c6ec7 # OUTPUT : Successfully mined bitcoins with nonce value:336 end mining....

Binary Calculator GUI

from tkinter import * window = Tk() window.title("Standard Binary Calculator") window.resizable(0, 0) # Function to clear the entry field def f1(): s = e1_val.get() e1.delete(first=0, last=len(s)) # Function to add "1" to the entry...

beatBoard

from tkinter import * from playsound import playsound from threading import Thread class padSound: def __init__(self, soundLocation): self.soundLocation = soundLocation def given_sound(self): ...

Battery Notification

import psutil from plyer import notification import time # From psutil we import sensors battery class which gives us battery percentage threshold = int(input('Enter the threshold: ')) battery = psutil.sensors_battery() percent =...

Bandwidth Monitor

# Contributed via : https://github.com/adarshkushwah/Network-Usage-Tracker import os import sys import time import threading import subprocess import tkinter import tkinter.messagebox def monitor(limit, unit): check = "vnstat" proc =...

Bag of words model

from sklearn.feature_extraction.text import CountVectorizer import nltk import pandas as pd # pandas is a library where your data can be stored, analyzed and processed in row and column representation from openpyxl import Workbook sentences =...

Backup generator

import os import shutil import datetime def backup_files(source_dir, destination_dir): """ Backup files from the source directory to the destination directory. :param source_dir: The directory containing the files to be...

Autonomous Taxi Agent

# -*- coding: utf-8 -*- """ Created on Fri Jun 4 18:02:01 2021 @author: Ayush """ import time import random import gym import numpy as np from IPython.display import clear_output env = gym.make('Taxi-v3') episodes = 10 for episode in range(1,...

Automatic Spelling Checker Corrector

# imports import sys from spellchecker import SpellChecker from nltk import word_tokenize # create an instance of the spellchecker spell = SpellChecker() # tokens --> stores the tokenized words tokens = [] def...

Automatic Certificate Generator

# importing packages & modules from PIL import Image, ImageDraw, ImageFont import pandas as pd import os # Implementation to generate certificate df = pd.read_csv('list.csv') font = ImageFont.truetype('arial.ttf', 60) for index, j in...

Automated Data Reporting

import pandas as pd def generate_data_report(data_file_path, report_file_path): df = pd.read_csv(data_file_path) summary_statistics = df.describe() column_means = df.mean() column_max_values = df.max() column_min_values =...

Automated scraper

import sys import requests from bs4 import BeautifulSoup import time def display_content(url, selector): try: # Send a GET request to the URL response = requests.get(url) # Check if the request was successful ...

Automated Script

import os import shutil def automated_backup(source_dir, destination_dir): try: # Check if the source directory exists if not os.path.exists(source_dir): print(f"Source directory '{source_dir}' does not exist.") ...

Automated GoogleSearch using Python

from googlesearch import search import sys class googlesearch: def __init__(self): self.search_count = None self.keyword_to_search = None self.search_results = None def set_search_count(self): # Set the...

Automated Game Testing Framework

import unittest class Game: def __init__(self): self.is_running = False self.score = 0 def start(self): self.is_running = True return "Game started." def play(self, action): if...

Automate Facebook bot

import pyautogui import time import webbrowser from selenium import webdriver from time import sleep from webdriver_manager.chrome import ChromeDriverManager from getpass import getpass LOGIN_URL = 'https://www.facebook.com/login.php' num =...

Auto LinkedIn

from selenium import webdriver # connect python with webbrowser-chrome from selenium.webdriver.common.keys import Keys import pyautogui as pag def main(): url = "http://linkedin.com/" # url of LinkedIn network_url =...

Auto Fill Google Forms

import csv import time from selenium import webdriver from selenium.webdriver.common.keys import Keys inputName = '/html/body/div/div[2]/form/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input' inputEmailID =...

Auto Backup

""" Simple backup script which just creates the root structure in an other folder and syncs everything which recursively lies within one of the source folders. For files bigger than a threshold they are first gziped.""" import argparse import...

Auto B'Day Wisher

# Pandas library is used for importing and reading the data import pandas as pd # datetime module is used for fetching the dates import datetime import smtplib # smtp library used for sending mail import os current_path =...

Audio to spectrogram

import librosa import matplotlib.pyplot as plt audio = 'path/to/your/audio/file' #replace this with the path to your file x, sr = librosa.load(audio) X = librosa.stft(x) Xdb = librosa.amplitude_to_db(abs(X)) plt.figure(figsize = (10,...

Audio to Text Convertor

import speech_recognition as sr def convert_audio_to_text(): # Initialize the recognizer r = sr.Recognizer() # Open the microphone and start recording with sr.Microphone() as source: print("Speak something...") ...

Audio split

from pydub import AudioSegment from pydub.silence import split_on_silence import os import collections import contextlib import sys import wave import os import webrtcvad def read_wave(path): with contextlib.closing(wave.open(path, 'rb'))...

Attachment Downloader

import ezgmail def attachmentdownload(resulthreads): # Two Objects used in code are GmailThread and GmailMessage # 1. GmailThread - Represents conversation threads # 2. GmailMessage - Represents individual emails within Threads ...

AskUbuntu Scraper

from bs4 import BeautifulSoup import requests import json class AskUbuntu: """ Create an instance of `AskUbuntu` class. ```python questions = AskUbuntu("topic") ``` """ def __init__(self, topic): self.topic...

Arbitary quotes generator

import random import quote def generate_quotes(): print("1. Inspirational") print("2. Motivational") print("3. Funny") print("4. Love") print("5. Life") choice = int(input("Enter your choice: ")) if choice == 1: ...

Applying Bitwise operations

import cv2 import argparse def perform_bitwise_operations(image1_path, image2_path): src1 = cv2.imread(image1_path) src2 = cv2.imread(image2_path) # Resizing the images to have the same dimensions src2 = cv2.resize(src2,...

Anime tracker

try: import sys import requests from bs4 import BeautifulSoup import urllib.parse as parse import re import argparse except ImportError as e: print('Terminal Error! ') print(f'System module import error: {e}') ...

AnagramFinder(GUI)

import tkinter as tk from itertools import permutations def find_anagrams(): a = entry.get().strip().lower() if a: b = a.split() c = [] for d in b: e = ["".join(f) for f in...

Anagram finder

from nltk.corpus import words import nltk nltk.download('words') def find_anagrams(search_words, word_list): # Function to sort letters in a word and return it as a string def sort_word(word): return ''.join(sorted(word)) #...

Amazon-Price-Alert

# Developed and maintained by https://github.com/sarthak1905 from bs4 import BeautifulSoup from requests_html import HTMLSession import os import time import smtplib import ssl class Scraper: # Initializes the scraper C3PO def...

Amazon product scraper

import requests from bs4 import BeautifulSoup class Product: def __init__(self, product_name: str): self.product_name = product_name def get_product(self): try: product_name = self.product_name ...

Amazon Wishlist Notifier

import requests from bs4 import BeautifulSoup import time import smtplib from email.mime.text import MIMEText # Replace with your own email and password SENDER_EMAIL = 'your_sender_email@gmail.com' SENDER_PASSWORD =...

Amazon Price Tracker

import requests from bs4 import BeautifulSoup import time import smtplib from email.mime.text import MIMEText def get_amazon_product_price(product_url): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...

Amazon Best Sellers Scraper

import requests from bs4 import BeautifulSoup def scrape_amazon_bestsellers(category_url): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110...

Convertors

from tkinter import * import urllib.request import webbrowser from functools import partial from tkinter import Tk, StringVar , ttk ################################################################### root = Tk() root.title('ALL IN ONE...

Algorithmic trading simulation

import pandas as pd import numpy as np import matplotlib.pyplot as plt # Simulated historical price data (more data points) data = { 'Date': pd.date_range(start='2010-01-01', periods=1000), 'Open': np.random.uniform(100, 200, 1000), ...

Air object

import cv2 from InitCaffe import * # Open video # cap = cv2.VideoCapture('NASA_video1.mp4') # video with airplane. # patch_size = 15 # Size of image patch to extract around featuns points patch_size = 25 # Size of image patch to extract around...

Recipe generator

import nltk import random from nltk.corpus import stopwords from nltk.tokenize import word_tokenize # Sample database of recipes recipes = { "Spaghetti Carbonara": { "ingredients": "pasta, eggs, bacon, parmesan cheese, black pepper", ...

Tron

import pygame import sys # Define the game window size WINDOW_WIDTH = 800 WINDOW_HEIGHT = 600 # Define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) # Define tile size and number of...

Reversi

import copy # Reversi Board Size BOARD_SIZE = 8 # Define player colors EMPTY = 0 BLACK = 1 WHITE = 2 # Define directions to explore in the board DIRECTIONS = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1,...

Flappy bird

# AI-driven AI Flappy Bird import pygame import neat import os import random # Game window size WINDOW_WIDTH = 500 WINDOW_HEIGHT = 800 # Bird images BIRD_IMAGES = [ pygame.transform.scale2x(pygame.image.load( os.path.join("images",...

Chatbot

import spacy # Load the spaCy English language model nlp = spacy.load("en_core_web_sm") # Function to get the response from the chatbot def get_response(query): # Process the user query doc = nlp(query) # Extract important...

Maze

import heapq import random class MazeSolver: def __init__(self, maze): self.maze = maze self.rows = len(maze) self.cols = len(maze[0]) self.start = (0, 0) self.goal = (self.rows - 1, self.cols - 1) ...

Language learning assistant

import random import speech_recognition as sr vocabulary = { 'apple': 'a fruit', 'dog': 'an animal that barks', 'cat': 'a small domesticated carnivorous mammal', 'book': 'a written or printed work consisting of pages glued or sewn...

AI storytelling game

import random class StoryNode: def __init__(self, text, options=None, effects=None): self.text = text self.options = options or [] self.effects = effects or {} class Character: def __init__(self, name): ...

AI code reviewer

import ast import pycodestyle class CodeReviewer: def __init__(self): self.feedback = [] def analyze_python_code(self, code): try: # Parse the Python code into an Abstract Syntax Tree (AST) tree =...

AI Chatbot

import requests import pyfiglet import itertools import threading import time import sys url = "https://simple-chatgpt-api.p.rapidapi.com/ask" headers = { "content-type": "application/json", "X-RapidAPI-Key": "OUR API KEY", ...

AI Calculator

from chatterbot import ChatBot import os # naming the ChatBot calculator # using mathematical evaluation logic # the calculator AI will not learn with the user input Bot = ChatBot(name='Calculator', read_only=True, ...

Music composer

import os import magenta.music as mm from magenta.models.melody_rnn import melody_rnn_sequence_generator # Set the directory to save the generated MIDI files output_dir = 'generated_music' os.makedirs(output_dir, exist_ok=True) # Initialize the...

Age calc gui

# import libraries import tkinter as tk from datetime import date # GUI App class class App: def __init__(self): # initialized window self.master = tk.Tk() self.master.geometry('280x300') ...

Advice

# Importing libraries import requests import tkinter as tk from tkinter import messagebox # Fetching advice from the advice api def advice(): try: res = requests.get("https://api.adviceslip.com/advice").json() ...

Adjective Comparative and Superlative Generator using NLP

from nltk.corpus import wordnet import nltk nltk.download('wordnet') def get_comp_sup(adjs): comp_sup = [] for adj in adjs: synsets = wordnet.synsets(adj) if synsets: syn = synsets[0] ...

addressbook

''' importing all the required libraries ''' import sqlite3 from sqlite3 import Error from tkinter import * import tkinter.messagebox root = Tk() root.geometry('600x370') list_of_names = [] root.title('AddressBook') Name = StringVar() Number =...

9 Types of Hash Cracker

#!/usr/bin/env python3 import hashlib import itertools import multiprocessing import os import string import threading import time class Cracker(object): ALPHA_LOWER = (string.ascii_lowercase,) ALPHA_UPPER = (string.ascii_uppercase,) ...

Age Calculator

from datetime import date def calculate_age(birthday): today = date.today() # Check if the birthdate is in the future if today < birthday: return "Invalid birthdate. Please enter a valid date." day_check =...