├── Ai-Analyze-Tweets.py ├── CSV-2FileCombineAndOutputMatches.py ├── CSV-Row-Shuffle.py ├── CSV-To-JSON.py ├── Check-and-Add-to-List.py ├── Colorful-Print.py ├── Commatize-Numbers.py ├── Copy-To-Clipboard.py ├── Count-And-Break.py ├── Datetime-Today-Midnight.py ├── Dictionary-Compare.py ├── Dictionary-Update.py ├── Discord-Avatar-Mod.py ├── Discord-Request-Post-Webhook.py ├── Discord-Send-Embeds.py ├── Discord-Send-Webhook.py ├── Download-Image-Resize-Upload-To-FTP.py ├── Find-In-Webpage.py ├── FizzBuzz.py ├── For-Loop-No-Unused-Variable-Warning.py ├── Gen-Random-From-List-Copy-To-Clipboard.py ├── Get-Cookies.py ├── Get-Date-And-Weekday.py ├── Get-Every-Combination.py ├── Get-Host-IP.py ├── Get-Unread-Email.py ├── Get-Weather.py ├── HTML-Unescape-URL-Fixer.py ├── If-And-Or.py ├── If-Request-Ok.py ├── JSON-Get-Nested-Keys.py ├── JSON-If-Key.py ├── JSON-Import-Print.py ├── Join-List.py ├── Leading-Zeros-On-Number.py ├── Math-On-Cuda.py ├── Module-Example ├── Module-Example.py ├── README.md └── Scripts │ ├── module1.py │ └── module2.py ├── Multi-Threading.py ├── PIL-3D-Text-FX.py ├── PIL-AA-Font.py ├── PIL-ColormindAI-Palettes.py ├── PIL-ColormindAI-Squares.py ├── PIL-Download-Edit.py ├── PIL-Draw-Text.py ├── PIL-Get-Pixel-Color.py ├── PIL-Layer-Img.py ├── PIL-RNG-Colorful-Squares.py ├── PIL-Radial-Copy-Text-FX.py ├── PIL-Request-Img.py ├── PIL-SquareGen-Maths.py ├── PNG-To-PBM.py ├── Pos-VS-Neg-Keyword.py ├── Print-Dict-Items.py ├── Print-OR.py ├── PyQt5-Interactive-Window.py ├── PyQt5-Interactive-Window.ui ├── README.md ├── Random-Wait.py ├── Re-Split.py ├── Round-Dollars-to-Int.py ├── Selenium-Change-Window-Position.py ├── Send-Bash-Cmds.py ├── String-To-Time-And-Compare.py ├── Text-File-Maniuplation.py ├── Trailing-Average-Layered.py ├── Trailing-Average.py ├── Translate-And-Analyze-Tweets.py ├── Translate-Goslate.py ├── Translate-TextBlob.py ├── Twitter-API-Get-Tweet.py ├── URL-Unshortener.py ├── Validate-BTC-Address.py ├── Wait-One-Week.py ├── Websockets-Get-XLM-Coin-Data.py ├── Write-HTML-Upload-FTP.py └── testData.json /Ai-Analyze-Tweets.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import urllib.parse 4 | from textblob import TextBlob 5 | 6 | searchTerm = "Cats and Dogs!" 7 | searchTerm = urllib.parse.quote(searchTerm) 8 | 9 | getInfo = requests.get('https://api.twitter.com/1.1/search/tweets.json?q='+ searchTerm +'&result_type=recent&count=50', headers={"Authorization": "Bearer AAAAAAAAAAAAAAAAAAAAA"}) 10 | parsedInfo = json.loads(getInfo.text)['statuses'] 11 | 12 | pubTweets = [] 13 | for x in range(len(parsedInfo)): 14 | pubTweets.append(parsedInfo[x]['text']) 15 | 16 | def clean_tweets(tweet): 17 | tweet_words = str(tweet).split(' ') 18 | clean_words = [word for word in tweet_words if not word.startswith('#')] 19 | return ' '.join(clean_words) 20 | 21 | def analyze(Topic): 22 | positive_tweets, negative_tweets = [], [] 23 | 24 | for tweet in range(len(pubTweets)): 25 | cleanedTweet = clean_tweets(pubTweets[tweet]) 26 | tweet_polarity = TextBlob(cleanedTweet).sentiment.polarity 27 | if tweet_polarity<0: 28 | negative_tweets.append(cleanedTweet) 29 | continue 30 | positive_tweets.append(cleanedTweet) 31 | return positive_tweets, negative_tweets 32 | positive, negative = analyze('Magufuli') 33 | print(positive , '\n\n', negative) 34 | print('Positive:',len(positive), ' VS ', 'Negative:',len(negative)) 35 | -------------------------------------------------------------------------------- /CSV-2FileCombineAndOutputMatches.py: -------------------------------------------------------------------------------- 1 | import csv 2 | 3 | def compare_and_merge_csv(file1, file1_column, file2, file2_column, output_file): 4 | with open(file1, mode='r', newline='', encoding='utf-8-sig') as f1: 5 | reader1 = csv.DictReader(f1) 6 | print("Columns in file 1:", reader1.fieldnames) # Debug print 7 | data1 = [row for row in reader1] 8 | 9 | with open(file2, mode='r', newline='', encoding='utf-8-sig') as f2: 10 | reader2 = csv.DictReader(f2) 11 | print("Columns in file 2:", reader2.fieldnames) 12 | data2 = [row for row in reader2] 13 | 14 | matches = [] 15 | for row1 in data1: 16 | for row2 in data2: 17 | if row1.get(file1_column, '').strip() == row2.get(file2_column, '').strip(): 18 | # Combine the matching rows into one dictionary 19 | combined_row = {**row1, **row2} 20 | matches.append(combined_row) 21 | 22 | combined_columns = reader1.fieldnames + [col for col in reader2.fieldnames if col not in reader1.fieldnames] 23 | 24 | with open(output_file, mode='w', newline='') as f_out: 25 | writer = csv.DictWriter(f_out, fieldnames=combined_columns) 26 | writer.writeheader() 27 | writer.writerows(matches) 28 | 29 | file1_path = 'file1.csv' # Update this to your first CSV file path 30 | file2_path = 'file2.csv' # Update this to your second CSV file path 31 | output_file_path = 'output.csv' # Update this to your desired output CSV file path 32 | file1_column_name = 'CName' # Update this to the column name in your first CSV file to compare 33 | file2_column_name = 'CName' # Update this to the column name in your second CSV file to compare 34 | 35 | compare_and_merge_csv(file1_path, file1_column_name, file2_path, file2_column_name, output_file_path) 36 | 37 | print("Merging completed. Check the output file:", output_file_path) 38 | -------------------------------------------------------------------------------- /CSV-Row-Shuffle.py: -------------------------------------------------------------------------------- 1 | # Opens CSV, shuffles rows, outputs to new CSV. 2 | 3 | import csv 4 | import random 5 | 6 | def shuffleCSV(csvInFilePath, csvOutFilePath): 7 | data = [] 8 | 9 | with open(csvInFilePath, encoding='utf-8') as csvf: 10 | csvReader = csv.reader(csvf) 11 | for rows in csvReader: 12 | data.append(rows) 13 | 14 | random.shuffle(data) 15 | 16 | with open(csvOutFilePath, 'w', newline='') as csvf: 17 | csvwriter = csv.writer(csvf) 18 | csvwriter.writerows(data) 19 | 20 | 21 | csvInFilePath = r'in.csv' 22 | csvOutFilePath = r'out.csv' 23 | 24 | shuffleCSV(csvInFilePath, csvOutFilePath) 25 | -------------------------------------------------------------------------------- /CSV-To-JSON.py: -------------------------------------------------------------------------------- 1 | 2 | import csv 3 | import json 4 | 5 | def make_json(csvFilePath, jsonFilePath): 6 | data = {'objects': []} 7 | 8 | with open(csvFilePath, encoding='utf-8') as csvf: 9 | csvReader = csv.DictReader(csvf) 10 | 11 | for rows in csvReader: 12 | data['objects'].append(rows) 13 | 14 | with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 15 | jsonf.write(json.dumps(data, indent=4)) 16 | 17 | 18 | csvFilePath = r'oldFile.csv' 19 | jsonFilePath = r'newFile.json' 20 | 21 | make_json(csvFilePath, jsonFilePath) 22 | -------------------------------------------------------------------------------- /Check-and-Add-to-List.py: -------------------------------------------------------------------------------- 1 | alist = ['aaa',['bbb','222'],'ccc'] 2 | 3 | blist = ['aaa','bbb','ccc','ddd','eee'] 4 | 5 | if ((blist[3] and blist[3]) in alist) == False: 6 | print(alist) 7 | print("nah") 8 | alist.insert(3,blist[3]) 9 | alist.insert(4,blist[4]) 10 | 11 | if ((blist[3] and blist[4]) in alist) == True: 12 | print(alist) 13 | print("yey") 14 | -------------------------------------------------------------------------------- /Colorful-Print.py: -------------------------------------------------------------------------------- 1 | class colors: 2 | reset='\033[0m' 3 | bold='\033[01m' 4 | disable='\033[02m' 5 | underline='\033[04m' 6 | reverse='\033[07m' 7 | strikethrough='\033[09m' 8 | invisible='\033[08m' 9 | class fg: 10 | black='\033[30m' 11 | red='\033[31m' 12 | green='\033[32m' 13 | orange='\033[33m' 14 | blue='\033[34m' 15 | purple='\033[35m' 16 | cyan='\033[36m' 17 | lightgrey='\033[37m' 18 | darkgrey='\033[90m' 19 | lightred='\033[91m' 20 | lightgreen='\033[92m' 21 | yellow='\033[93m' 22 | lightblue='\033[94m' 23 | pink='\033[95m' 24 | lightcyan='\033[96m' 25 | class bg: 26 | black='\033[40m' 27 | red='\033[41m' 28 | green='\033[42m' 29 | orange='\033[43m' 30 | blue='\033[44m' 31 | purple='\033[45m' 32 | cyan='\033[46m' 33 | lightgrey='\033[47m' 34 | 35 | print(colors.fg.lightred, colors.reverse, "Build a class of colors : Create a class to allot background and foreground colors and call them.", colors.reset) 36 | -------------------------------------------------------------------------------- /Commatize-Numbers.py: -------------------------------------------------------------------------------- 1 | print("{:,}".format(1000000)) 2 | -------------------------------------------------------------------------------- /Copy-To-Clipboard.py: -------------------------------------------------------------------------------- 1 | #pip install pyperclip 2 | import pyperclip as pc 3 | a1 = "This is now in your clipboard!" 4 | pc.copy(a1) 5 | 6 | a2 = pc.paste() 7 | print(a2) 8 | -------------------------------------------------------------------------------- /Count-And-Break.py: -------------------------------------------------------------------------------- 1 | x = 0 2 | while True: 3 | if x < 10: 4 | x = x + 1 5 | print(x) 6 | else: 7 | break 8 | 9 | print("Done") 10 | -------------------------------------------------------------------------------- /Datetime-Today-Midnight.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | todayDate = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) 4 | 5 | print(todayDate) 6 | -------------------------------------------------------------------------------- /Dictionary-Compare.py: -------------------------------------------------------------------------------- 1 | dict1 = {"a":"aaa","b":["bbb",["222"]],"c":"ccc"} 2 | 3 | dict2 = {"a":"aaa","b":["bbb",["222","333"],"bbb"],"c":"ccc","d":"ddd"} 4 | 5 | d1b = dict1.get("b") 6 | 7 | d2b = dict2.get("b") 8 | 9 | d1d = dict1.get("d") 10 | 11 | d2d = dict2.get("d") 12 | 13 | if len(d2b[1]) > len(d1b[1]): 14 | print("yey") 15 | 16 | if d2d != d1d: 17 | print("hey") 18 | -------------------------------------------------------------------------------- /Dictionary-Update.py: -------------------------------------------------------------------------------- 1 | dict1 = {"a":"aaa","b":["bbb","222"],"c":"ccc"} 2 | 3 | print(dict1["b"]) 4 | 5 | dict2 = {"b":["222","bbb"]} 6 | 7 | dict1.update(dict2) 8 | 9 | print(dict1["b"]) 10 | -------------------------------------------------------------------------------- /Discord-Avatar-Mod.py: -------------------------------------------------------------------------------- 1 | from dhooks import Webhook, Embed 2 | import requests 3 | 4 | #Offline 5 | with open('avatar.png', 'rb') as f: 6 | image1 = f.read() # bytes 7 | 8 | #Online 9 | url = 'https://url.com/avatar.png' 10 | getImage2 = requests.get(url) 11 | image2 = getImage2.content # bytes 12 | 13 | 14 | hook = Webhook('https://discordapp.com/api/webhooks/hook') 15 | 16 | hook.modify(name='Bob', avatar=image1) 17 | hook.send("Hello there! I'm a webhook :open_mouth:") 18 | 19 | hook.modify(name='Bob', avatar=image2) 20 | hook.send("Hello there! I'm a webhook :open_mouth:") 21 | -------------------------------------------------------------------------------- /Discord-Request-Post-Webhook.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | WEBHOOK_URL = 'https://discord.com/api/webhooks/token/token' 4 | requests.post(WEBHOOK_URL, { "content": "test" }) 5 | -------------------------------------------------------------------------------- /Discord-Send-Embeds.py: -------------------------------------------------------------------------------- 1 | from dhooks import Webhook, Embed 2 | 3 | hook = Webhook('https://discordapp.com/api/webhooks/token/token') 4 | image = ('https://picsum.photos/400/400') 5 | 6 | embed = Embed(description=name, timestamp='now', color=0x11b668) 7 | embed.set_author(name="Discord Test", icon_url=image) 8 | embed.add_field(name='Inline', value='True') 9 | embed.add_field(name='Inline', value='True') 10 | embed.add_field(name='Inline', value='False', inline=False) 11 | embed.set_footer(text='Test', icon_url=image) 12 | embed.set_thumbnail(image) 13 | 14 | hook.send(embed=embed) 15 | -------------------------------------------------------------------------------- /Discord-Send-Webhook.py: -------------------------------------------------------------------------------- 1 | from dhooks import Webhook 2 | 3 | hook = Webhook('https://discordapp.com/api/webhooks/token/token') 4 | 5 | hook.send("Hello! :open_mouth:") 6 | -------------------------------------------------------------------------------- /Download-Image-Resize-Upload-To-FTP.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from PIL import ImageFont 3 | from PIL import ImageDraw 4 | from io import BytesIO 5 | from datetime import datetime 6 | import requests 7 | import ftplib 8 | 9 | # Configure connection 10 | session = ftplib.FTP('FTPServer','USER','PASS') 11 | 12 | # Set Image to download 13 | rUrl = "https://www.python.org/static/img/python-logo.png" 14 | 15 | # Create canvas 16 | bg = Image.new("RGBA", (350, 350), (255, 255, 255, 255)) 17 | 18 | # Download Image and resize to canvas with Anti-Aliasing 19 | response = requests.get(rUrl) 20 | fg = Image.open(BytesIO(response.content)) 21 | fgSize = 350, 350 22 | fg.thumbnail(fgSize, Image.ANTIALIAS) 23 | 24 | # Paste resized Image to center of canvas. 25 | img_w, img_h = fg.size 26 | bg_w, bg_h = bg.size 27 | offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2) 28 | bg.paste(fg, offset,mask=fg) 29 | 30 | # Set file name with today's date 31 | ftpStr = str(datetime.today().strftime('%Y-%m-%d')+"-test.png") 32 | 33 | # Prep byte data for Upload 34 | bg.seek(0) 35 | temp = BytesIO() 36 | bg.save(temp, format='PNG') 37 | temp.seek(0) 38 | 39 | # Upload Image to FTP 40 | session.storbinary('STOR '+ftpStr, temp) 41 | session.quit() 42 | -------------------------------------------------------------------------------- /Find-In-Webpage.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import re 3 | 4 | url = 'https://www.python.org/' 5 | 6 | headers = { 7 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36" 8 | } 9 | 10 | getPage = requests.get(url, headers=headers, timeout=(60)) 11 | 12 | def NameOut(): 13 | getName = getPage.text.find('') 14 | nameParse = (getPage.text[(getName+7) : (getName+100)]) 15 | nameFixed = re.split("<|\|", nameParse) 16 | return nameFixed[0] 17 | 18 | print(NameOut()) 19 | -------------------------------------------------------------------------------- /FizzBuzz.py: -------------------------------------------------------------------------------- 1 | for i in range(1,101): 2 | if i % 3 == 0 and i % 5 == 0: 3 | print("FizzBuzz") 4 | elif i % 3 == 0: 5 | print("Fizz") 6 | elif i % 5 == 0: 7 | print("Buzz") 8 | else: 9 | print(i) 10 | -------------------------------------------------------------------------------- /For-Loop-No-Unused-Variable-Warning.py: -------------------------------------------------------------------------------- 1 | for _ in " "*5: 2 | print("a") 3 | -------------------------------------------------------------------------------- /Gen-Random-From-List-Copy-To-Clipboard.py: -------------------------------------------------------------------------------- 1 | #pip install pyperclip 2 | import pyperclip as pc 3 | import random 4 | 5 | tagCount = 4 #Set to number of tags you want. Must be within range of how many tags exist in tagList 6 | 7 | tagList = """ 8 | #test1 9 | #test2 10 | #test3 11 | #test4 12 | """ 13 | 14 | tags = tagList.splitlines() 15 | tags = tags[1:] 16 | random.shuffle(tags) 17 | tagOut = ' '.join(tags[:tagCount]) 18 | 19 | pc.copy(tagOut) 20 | print(pc.paste()) 21 | -------------------------------------------------------------------------------- /Get-Cookies.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | cookisession = requests.Session() 4 | cookiresponse = cookisession.get('https://github.com/vincentwimmer/') 5 | 6 | print(cookisession.cookies.get_dict()) 7 | print(cookiresponse.cookies.get_dict()) 8 | -------------------------------------------------------------------------------- /Get-Date-And-Weekday.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | #Print today's date and time 4 | print(datetime.datetime.today()) 5 | 6 | #Print enumerated Day of Week (Monday = 0) 7 | print(datetime.datetime.today().weekday()) 8 | -------------------------------------------------------------------------------- /Get-Every-Combination.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | a1 = ["apple","banana","orange"] 4 | a2 = ["red", "green", "blue"] 5 | a3 = ["one", "two", "three"] 6 | 7 | a = [a1,a2,a3] 8 | 9 | print(list(itertools.product(*a))) 10 | -------------------------------------------------------------------------------- /Get-Host-IP.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | host = socket.gethostname() 4 | ip = socket.gethostbyname(host) 5 | fqdn = socket.getfqdn() 6 | 7 | print("Host:",host) 8 | print("IP:",ip) 9 | print("FQDN:", fqdn) 10 | -------------------------------------------------------------------------------- /Get-Unread-Email.py: -------------------------------------------------------------------------------- 1 | # Note: This will mark mail as read after executing. 2 | 3 | mailUser = "email@website.com" 4 | mailPass = "password" 5 | imapHost = "website.com" 6 | 7 | mailConn = imaplib.IMAP4_SSL(imapHost, 993) 8 | mailConn.login(mailUser, mailPass) 9 | mailConn.select() 10 | result, data = mailConn.search(None, '(UNSEEN)') 11 | if result == 'OK': 12 | for num in data[0].split(): 13 | result, data = mailConn.fetch(num,'(RFC822)') 14 | if result == 'OK': 15 | email_message = email.message_from_bytes(data[0][1]) 16 | print('From:' + email_message['From']) 17 | print('To:' + email_message['To']) 18 | print('Date:' + email_message['Date']) 19 | print('Subject:' + str(email_message['Subject'])) 20 | print('Content:' + str(email_message.get_payload()[0])) 21 | mailConn.close() 22 | mailConn.logout() 23 | -------------------------------------------------------------------------------- /Get-Weather.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | weather = requests.get("https://wttr.in") 4 | 5 | print(weather.text) 6 | -------------------------------------------------------------------------------- /HTML-Unescape-URL-Fixer.py: -------------------------------------------------------------------------------- 1 | import html 2 | 3 | string = "https://b01.ugwdevice.net/ugw/agentif&c=E&" 4 | 5 | print(html.unescape(string)) 6 | -------------------------------------------------------------------------------- /If-And-Or.py: -------------------------------------------------------------------------------- 1 | a = True 2 | b = False 3 | c = True 4 | 5 | if a and (b or c): 6 | print("yey") 7 | -------------------------------------------------------------------------------- /If-Request-Ok.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | url = "http://google.com/" 4 | 5 | req = requests.get(url) 6 | 7 | if req.ok: 8 | print(req) 9 | -------------------------------------------------------------------------------- /JSON-Get-Nested-Keys.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | getJsonFile = 'testData.json' 4 | with open(getJsonFile) as jsonF: 5 | jsonObjects = json.load(jsonF) 6 | 7 | jsonNames = jsonObjects['objects'] 8 | 9 | for item in jsonNames : 10 | if item['Status'] == "Active": 11 | print(item['Name']) 12 | tags = '\n '.join(item['Tags']) 13 | print("Tags:", '\n' , tags, '\n', '--------') 14 | -------------------------------------------------------------------------------- /JSON-If-Key.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | getJsonFile = 'testData.json' 4 | with open(getJsonFile) as jsonF: 5 | jsonObjects = json.load(jsonF) 6 | 7 | jsonNames = jsonObjects['objects'] 8 | 9 | for item in jsonNames : 10 | if item['Status'] == "Active": 11 | print(item['Name']) 12 | -------------------------------------------------------------------------------- /JSON-Import-Print.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | getJsonFile = 'testData.json' 4 | with open(getJsonFile) as jsonF: 5 | jsonObjects = json.load(jsonF) 6 | 7 | jsonNames = jsonObjects['objects'] 8 | 9 | for item in jsonNames : 10 | print(item['Name']) 11 | -------------------------------------------------------------------------------- /Join-List.py: -------------------------------------------------------------------------------- 1 | list1 = ['a','b','c'] 2 | 3 | listStack = '\n'.join(list1) 4 | 5 | print(listStack) 6 | -------------------------------------------------------------------------------- /Leading-Zeros-On-Number.py: -------------------------------------------------------------------------------- 1 | #Prints 001 2 | print(str(1).zfill(3)) 3 | 4 | #Prints 010 5 | print(str(10).zfill(3)) 6 | 7 | #Prints 100 8 | print(str(100).zfill(3)) 9 | -------------------------------------------------------------------------------- /Math-On-Cuda.py: -------------------------------------------------------------------------------- 1 | from numba import jit, cuda 2 | import numpy as np 3 | from timeit import default_timer as timer 4 | 5 | # Run on CPU 6 | def func(a): 7 | for i in range(10000000): 8 | a[i]+= 1 9 | 10 | # Run on GPU 11 | @jit(target ="cuda") 12 | def func2(a): 13 | for i in range(10000000): 14 | a[i]+= 1 15 | 16 | if __name__=="__main__": 17 | n = 10000000 18 | a = np.ones(n, dtype = np.float64) 19 | 20 | start = timer() 21 | func(a) 22 | print("CPU:", timer()-start) 23 | 24 | start = timer() 25 | func2(a) 26 | print("GPU:", timer()-start) 27 | -------------------------------------------------------------------------------- /Module-Example/Module-Example.py: -------------------------------------------------------------------------------- 1 | import sys 2 | # Set path to script folder. 3 | sys.path.append('/Scripts/') 4 | 5 | # Import the whole script. 6 | import module1 7 | 8 | # Or import single function to maintain lean code. 9 | from module2 import main 10 | 11 | print(module1.main(1,3)) 12 | print(main(3,3)) 13 | -------------------------------------------------------------------------------- /Module-Example/README.md: -------------------------------------------------------------------------------- 1 | # Custom Modules 2 | 3 | - Set a folder and import your scripts from it to utilize them in your code as you would any other module. 4 | -------------------------------------------------------------------------------- /Module-Example/Scripts/module1.py: -------------------------------------------------------------------------------- 1 | def main(args1,args2): 2 | listA = [] 3 | multiplyArgs = (args1*args2) 4 | for x in range(multiplyArgs): 5 | listA.append("Apple") 6 | return(listA) 7 | -------------------------------------------------------------------------------- /Module-Example/Scripts/module2.py: -------------------------------------------------------------------------------- 1 | def main(args1,args2): 2 | listA = [] 3 | multiplyArgs = (args1*args2) 4 | for x in range(multiplyArgs): 5 | listA.append("Apple") 6 | return(listA) 7 | -------------------------------------------------------------------------------- /Multi-Threading.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | def Main(thread): 4 | print("Starting on Thread", thread) 5 | x = 0 6 | while True: 7 | if x < 50: 8 | x = x + 1 9 | print("Thread", thread, "Prints:", x) 10 | else: 11 | break 12 | 13 | for thread in range(10): 14 | threading.Thread(target=Main,args=(thread,)).start() 15 | -------------------------------------------------------------------------------- /PIL-3D-Text-FX.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from PIL import ImageFont 3 | from PIL import ImageDraw 4 | 5 | img = Image.new("RGB", (300, 300), (80, 80, 80)) 6 | inputText = "//&&||$$123ABC@@" 7 | 8 | # Set it up with Anti-Aliasing like in "PIL-AA-Font.py" - 3x everything's size. 9 | img2 = Image.new("RGBA", (900, 900), (255, 255, 255, 0)) 10 | draw = ImageDraw.Draw(img2) 11 | font = ImageFont.truetype("arial.ttf", 72) 12 | 13 | # Draw Text in loop while moving the draw position for each iteration. Also add increasing color values for gradient effect. 14 | for x in range(20): 15 | draw.text(((50 + (x/2)), (50 - (x*2))), inputText, (0,(10 * x),(8 * x)), font=font) 16 | 17 | # Draw Text on top of where the loop stopped with a slightly different shade of color for clarity/styling. 18 | draw.text((60, 10), inputText, (130,255,190), font=font) 19 | 20 | # Resize and apply AA. 21 | size = 300, 300 22 | img2.thumbnail(img.size, Image.ANTIALIAS) 23 | 24 | # Paste created transparent text layer onto BG. 25 | offset = (20, 20) 26 | img.paste(img2, offset,mask=img2) 27 | 28 | img.show() 29 | -------------------------------------------------------------------------------- /PIL-AA-Font.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from PIL import ImageFont 3 | from PIL import ImageDraw 4 | 5 | img = Image.new("RGB", (300, 300), (255, 255, 255)) 6 | 7 | # Create transparent image/layer at 3x scale of base image 8 | img2 = Image.new("RGBA", (900, 900), (255, 255, 255, 0)) 9 | draw = ImageDraw.Draw(img2) 10 | font = ImageFont.truetype("Roboto-Medium.ttf", 72) # 72 divided by 3 = 24. 11 | draw.text((0, 0), "//&&||$$123ABC@@", (0,0,0), font=font) 12 | 13 | # Resize to base image width/height and Anti-Alias 14 | img2.thumbnail(img.size, Image.ANTIALIAS) 15 | 16 | # Paste image as layer with an offset. 17 | offset = (20, 20) 18 | img.paste(img2, offset,mask=img2) 19 | 20 | img.show() 21 | -------------------------------------------------------------------------------- /PIL-ColormindAI-Palettes.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import random 3 | import requests 4 | import re 5 | import json 6 | 7 | url = 'http://colormind.io/api/' 8 | headers = { 9 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36" 10 | } 11 | data1 = {'model': 'makoto_shinkai'} 12 | data2 = {'model': 'city_photography'} 13 | data3 = {'model': 'default'} 14 | 15 | def drawImage(): 16 | # Get colors and split them 17 | rng = random.randrange(1,4) 18 | if rng == 1: 19 | data = data1 20 | if rng == 2: 21 | data = data2 22 | if rng == 3: 23 | data = data3 24 | 25 | getPage = requests.get(url, data=json.dumps(data), headers=headers, timeout=(60)) 26 | colorData = json.loads(getPage.content) 27 | colorData = colorData['result'] 28 | 29 | color1 = re.split("\[|,|]", str(colorData[0])) 30 | color1List = [color1[1],color1[2],color1[3]] 31 | 32 | color2 = re.split("\[|,|]", str(colorData[1])) 33 | color2List = [color2[1],color2[2],color2[3]] 34 | 35 | color3 = re.split("\[|,|]", str(colorData[2])) 36 | color3List = [color3[1],color3[2],color3[3]] 37 | 38 | color4 = re.split("\[|,|]", str(colorData[3])) 39 | color4List = [color4[1],color4[2],color4[3]] 40 | 41 | color5 = re.split("\[|,|]", str(colorData[4])) 42 | color5List = [color5[1],color5[2],color5[3]] 43 | 44 | # Create Image 45 | bottomGen = Image.new("RGB", (2500,2500), (int(color1List[0]),int(color1List[1]),int(color1List[2]))) 46 | topGen = Image.new("RGBA", (2000,2000), (255,255,255,0)) 47 | pixel = topGen.load() 48 | rng = 2 49 | for latx in range(2): 50 | latx = latx * 1000 51 | for lony in range(2): 52 | lony = lony * 1000 53 | 54 | 55 | 56 | if rng == 1: 57 | red = int(color1List[0]) 58 | green = int(color1List[1]) 59 | blue = int(color1List[2]) 60 | if rng == 2: 61 | red = int(color2List[0]) 62 | green = int(color2List[1]) 63 | blue = int(color2List[2]) 64 | if rng == 3: 65 | red = int(color3List[0]) 66 | green = int(color3List[1]) 67 | blue = int(color3List[2]) 68 | if rng == 4: 69 | red = int(color4List[0]) 70 | green = int(color4List[1]) 71 | blue = int(color4List[2]) 72 | if rng == 5: 73 | red = int(color5List[0]) 74 | green = int(color5List[1]) 75 | blue = int(color5List[2]) 76 | 77 | for x in range(1000): 78 | for y in range(1000): 79 | pixel[x+latx,y+lony]=(red,green,blue) 80 | 81 | rng = rng + 1 82 | 83 | print(data) 84 | bottomGen.paste(topGen,box=(250,250),mask=topGen) 85 | 86 | return bottomGen 87 | 88 | #finalImage = drawImage() 89 | ##finalImage.show() 90 | #finalImage.save('C:/Users/vwimmer/Desktop/test.png') 91 | 92 | for xnum in range(5): 93 | finalImage = drawImage() 94 | finalImage.save('C:/Users/vwimmer/Desktop/Out/'+str(xnum).zfill(3)+'.png') 95 | -------------------------------------------------------------------------------- /PIL-ColormindAI-Squares.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import random 3 | import requests 4 | import re 5 | import json 6 | 7 | #Perams - ResX/Y must be divisible by SquareSize for best results. 8 | ResX = 900 9 | ResY = 900 10 | SquareSize = 5 11 | 12 | # Connect and get color 13 | url = 'http://colormind.io/api/' 14 | headers = { 15 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36" 16 | } 17 | data1 = {'model': 'ui'} 18 | data2 = {'model': 'communist'} 19 | data3 = {'model': 'default'} 20 | 21 | def drawImage(): 22 | # Get colors and split them 23 | rng = random.randrange(1,4) 24 | if rng == 1: 25 | data = data1 26 | if rng == 2: 27 | data = data2 28 | if rng == 3: 29 | data = data3 30 | 31 | getPage = requests.get(url, data=json.dumps(data), headers=headers, timeout=(60)) 32 | colorData = json.loads(getPage.content) 33 | colorData = colorData['result'] 34 | 35 | color1 = re.split("\[|,|]", str(colorData[0])) 36 | color1List = [color1[1],color1[2],color1[3]] 37 | 38 | color2 = re.split("\[|,|]", str(colorData[1])) 39 | color2List = [color2[1],color2[2],color2[3]] 40 | 41 | color3 = re.split("\[|,|]", str(colorData[2])) 42 | color3List = [color3[1],color3[2],color3[3]] 43 | 44 | color4 = re.split("\[|,|]", str(colorData[3])) 45 | color4List = [color4[1],color4[2],color4[3]] 46 | 47 | color5 = re.split("\[|,|]", str(colorData[4])) 48 | color5List = [color5[1],color5[2],color5[3]] 49 | 50 | # Resolution Standards 51 | # 7680 × 4320 8k 52 | # 15360 x 8640 16k 53 | # 30720 x 17280 32k 54 | # 61440 x 34560 64k 55 | # 122880 x 69120 128k 56 | # 245760 x 138240 256k 57 | 58 | # Create Image 59 | testImage = Image.new("RGB", (ResX,ResY), (255,255,255)) 60 | pixel = testImage.load() 61 | 62 | for latx in range((ResX//SquareSize)): 63 | latx = latx * SquareSize 64 | for lony in range((ResY//SquareSize)): 65 | lony = (lony * SquareSize) - SquareSize 66 | 67 | rng = random.randrange(1,6) 68 | 69 | if rng == 1: 70 | red = int(color1List[0]) 71 | green = int(color1List[1]) 72 | blue = int(color1List[2]) 73 | if rng == 2: 74 | red = int(color2List[0]) 75 | green = int(color2List[1]) 76 | blue = int(color2List[2]) 77 | if rng == 3: 78 | red = int(color3List[0]) 79 | green = int(color3List[1]) 80 | blue = int(color3List[2]) 81 | if rng == 4: 82 | red = int(color4List[0]) 83 | green = int(color4List[1]) 84 | blue = int(color4List[2]) 85 | if rng == 5: 86 | red = int(color5List[0]) 87 | green = int(color5List[1]) 88 | blue = int(color5List[2]) 89 | 90 | for x in range(SquareSize): 91 | for y in range(SquareSize): 92 | pixel[x+latx,y+lony]=(red,green,blue) 93 | 94 | return testImage 95 | 96 | finalImage = drawImage() 97 | #finalImage.show() 98 | 99 | finalImage.save('C:/test.png') 100 | -------------------------------------------------------------------------------- /PIL-Download-Edit.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from PIL import ImageFont 3 | from PIL import ImageDraw 4 | import requests 5 | from io import BytesIO 6 | 7 | # Download and resize image. 8 | response = requests.get('https://avatars1.githubusercontent.com/u/9145304?s=460&u=1126a26b2ffac6187f655816e5eb0ffcb55c429b&v=4') 9 | bg = Image.open(BytesIO(response.content)) 10 | bg_resized = bg.resize((200,200)) 11 | 12 | # Open local image. 13 | fg = Image.open('overlay.png').convert('RGBA') 14 | 15 | # Setup Drawing. 16 | draw = ImageDraw.Draw(bg_resized, "RGBA") 17 | # Draw Rectangle. 18 | draw.rectangle((20, 20, 100, 70), outline=(33,255,33,255), fill=(33,33,33,150)) 19 | # Set font and write characters. 20 | font = ImageFont.truetype("Roboto-Medium.ttf", 24) 21 | draw.text((38, 30),"YEY",(33,255,33),font=font) 22 | 23 | # Bring everything together. 24 | bg_resized.paste(fg,box=(0,0),mask=fg) 25 | 26 | bg_resized.show() 27 | #bg_resized.save('result.png') 28 | -------------------------------------------------------------------------------- /PIL-Draw-Text.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from PIL import ImageFont 3 | from PIL import ImageDraw 4 | import requests 5 | from io import BytesIO 6 | 7 | response = requests.get('https://avatars1.githubusercontent.com/u/9145304?s=460&u=1126a26b2ffac6187f655816e5eb0ffcb55c429b&v=4') 8 | 9 | img = Image.open(BytesIO(response.content)) 10 | draw = ImageDraw.Draw(img, "RGBA") 11 | draw.rectangle((20, 20, 100, 70), outline=(33,255,33,255), fill=(33,33,33,150)) 12 | font = ImageFont.truetype("./Roboto-Medium.ttf", 24) 13 | draw.text((38, 30),"YEY",(33,255,33),font=font) 14 | 15 | img.show() 16 | -------------------------------------------------------------------------------- /PIL-Get-Pixel-Color.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | 3 | # Open 24px x 24px image 4 | im = Image.open(r"C:/Out/001.png") 5 | px = im.load() 6 | print (px[1, 1]) 7 | print (px[4, 4]) 8 | print (px[15, 4]) 9 | print (px[4, 15]) 10 | print (px[15, 15]) 11 | -------------------------------------------------------------------------------- /PIL-Layer-Img.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | 3 | # Open background and foreground and ensure they are RGB (not palette) 4 | bg = Image.open('background.png').convert('RGB') 5 | fg = Image.open('overlay.png').convert('RGBA') 6 | 7 | # Resize foreground down from 500x500 to 200x200 8 | fg_resized = fg.resize((200,200)) 9 | 10 | # Overlay foreground onto background at top right corner, using transparency of foreground as mask 11 | bg.paste(fg_resized,box=(0,0),mask=fg_resized) 12 | 13 | # Save result 14 | bg.show() 15 | #bg.save('result.png') 16 | -------------------------------------------------------------------------------- /PIL-RNG-Colorful-Squares.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import random 3 | 4 | def drawImage(): 5 | testImage = Image.new("RGB", (600,600), (255,255,255)) 6 | pixel = testImage.load() 7 | 8 | for latx in range(60): 9 | latx = latx * 10 10 | for lony in range(60): 11 | lony = lony * 10 12 | 13 | red = random.randrange(80,120) 14 | blue = random.randrange(80,230) 15 | green = random.randrange(80,200) 16 | for x in range(10): 17 | for y in range(10): 18 | pixel[x+latx,y+lony]=(red,green,blue) 19 | 20 | return testImage 21 | 22 | def main(): 23 | finalImage = drawImage() 24 | finalImage.show() 25 | 26 | if __name__ == "__main__": 27 | main() 28 | -------------------------------------------------------------------------------- /PIL-Radial-Copy-Text-FX.py: -------------------------------------------------------------------------------- 1 | # Warning - This will take a while to render on most computers because I added the "3x Anti-Aliasing" to the code. I made a non-AA version and attached it to the bottom of this file if interested. 2 | 3 | from PIL import Image 4 | from PIL import ImageFont 5 | from PIL import ImageDraw 6 | 7 | img = Image.new("RGB", (400, 400), (0, 0, 0)) 8 | inputText = "//&&||$$123ABC@" 9 | 10 | font = ImageFont.truetype("Roboto-Medium.ttf", 72) 11 | 12 | for x in range(360): 13 | txt = Image.new("RGBA", (1200, 1200), (255, 255, 255, 0)) 14 | draw = ImageDraw.Draw(txt) 15 | draw.text((20, 580), inputText, (int((9*(x/20))),int((9*(x/20))),int((9*(x/20)))), font=font) 16 | w = txt.rotate(-1 - (x*1)) 17 | size = 400, 400 18 | w.thumbnail(img.size, Image.ANTIALIAS) 19 | 20 | offset = (0,0) 21 | img.paste(w, offset,mask=w) 22 | 23 | 24 | txt = Image.new("RGBA", (1200, 1200), (255, 255, 255, 0)) 25 | draw = ImageDraw.Draw(txt) 26 | draw.text((20, 580), inputText, (255,255,255), font=font) 27 | size = 400, 400 28 | txt.thumbnail(img.size, Image.ANTIALIAS) 29 | offset = (0,0) 30 | img.paste(txt, offset,mask=txt) 31 | 32 | 33 | img.show() 34 | 35 | # --- No AA version below --- 36 | 37 | #from PIL import Image 38 | #from PIL import ImageFont 39 | #from PIL import ImageDraw 40 | # 41 | #img = Image.new("RGB", (400, 400), (0, 0, 0)) 42 | #inputText = "//&&||$$123ABC@" 43 | # 44 | #font = ImageFont.truetype("Roboto-Medium.ttf", 24) 45 | # 46 | #for x in range(360): 47 | # txt = Image.new("RGBA", (400, 400), (255, 255, 255, 0)) 48 | # draw = ImageDraw.Draw(txt) 49 | # draw.text((5, 190), inputText, (int((9*(x/20))),int((9*(x/20))),int((9*(x/20)))), font=font) 50 | # w = txt.rotate(-1 - (x*1)) 51 | # 52 | # offset = (0,0) 53 | # img.paste(w, offset,mask=w) 54 | # 55 | # 56 | #txt = Image.new("RGBA", (400, 400), (255, 255, 255, 0)) 57 | #draw = ImageDraw.Draw(txt) 58 | #draw.text((5, 190), inputText, (255,255,255), font=font) 59 | #offset = (0,0) 60 | #img.paste(txt, offset,mask=txt) 61 | # 62 | # 63 | #img.show() 64 | -------------------------------------------------------------------------------- /PIL-Request-Img.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import requests 3 | from io import BytesIO 4 | 5 | # Grab my GitHub profile picture 6 | response = requests.get('https://avatars1.githubusercontent.com/u/9145304?s=460&u=1126a26b2ffac6187f655816e5eb0ffcb55c429b&v=4') 7 | 8 | # Convert to PIL 9 | img = Image.open(BytesIO(response.content)) 10 | 11 | img.show() 12 | -------------------------------------------------------------------------------- /PIL-SquareGen-Maths.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | import random 3 | 4 | def drawImage(): 5 | wi = 2000 6 | hi = 2000 7 | 8 | testImage = Image.new("RGB", (wi,hi), (255,255,255)) 9 | pixel = testImage.load() 10 | 11 | size = 10 12 | for latx in range(int(wi/size)): 13 | latx = latx * size 14 | for lony in range(int(hi/size)): 15 | lony = lony * size 16 | 17 | #red = random.randrange(50,200) 18 | #blue = random.randrange(50,200) 19 | #green = random.randrange(50,200) 20 | 21 | red = int(latx / 8) 22 | blue = int(lony / 8) 23 | green = int((int(lony / 8) + int(latx / 8)) / 2) 24 | 25 | for x in range(size): 26 | for y in range(size): 27 | pixel[x+latx,y+lony]=(red,green,blue) 28 | 29 | return testImage 30 | 31 | def main(): 32 | finalImage = drawImage() 33 | finalImage.show() 34 | 35 | if __name__ == "__main__": 36 | main() 37 | -------------------------------------------------------------------------------- /PNG-To-PBM.py: -------------------------------------------------------------------------------- 1 | #Easily convert images to portable bitmaps and do things like displaying them on a Pi Pico OLED screen. 2 | from PIL import Image 3 | 4 | im = Image.open("file.png") 5 | #im = im.convert('L') # Convert to dithered black and white 6 | im = im.convert('1') 7 | im.save("file.pbm") 8 | -------------------------------------------------------------------------------- /Pos-VS-Neg-Keyword.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | #Get Name 4 | name = "Jack cat -red Game Royal Tiger apple" 5 | nameparse = re.split(" |-|/", name.lower()) 6 | 7 | #Set Keywords 8 | poskeywords = {"red", "Royal", "Cat"} 9 | negkeywords = {"Dog", "Green", "Play"} 10 | 11 | if poskeywords & set(nameparse): 12 | if negkeywords & set(nameparse): 13 | pass 14 | else: 15 | poskeywordsList = str(poskeywords & set(nameparse)) 16 | poskeywordsSplit = re.sub('[}{\']', '', poskeywordsList) 17 | print('Positive Keywords are:', poskeywordsSplit) 18 | -------------------------------------------------------------------------------- /Print-Dict-Items.py: -------------------------------------------------------------------------------- 1 | dict1 = {"a":"aaa","b":"bbb","c":"ccc"} 2 | 3 | str1 = "The dict: \n" 4 | 5 | for k,v in dict1.items(): 6 | vals = k + " : " + v 7 | str1 = str1 + str(vals) + "\n" 8 | 9 | print(str1) 10 | -------------------------------------------------------------------------------- /Print-OR.py: -------------------------------------------------------------------------------- 1 | a = False and "nah" 2 | b = None and "nope" 3 | c = True and "yey" 4 | 5 | d = (a or b or c) 6 | 7 | print(d) 8 | -------------------------------------------------------------------------------- /PyQt5-Interactive-Window.py: -------------------------------------------------------------------------------- 1 | from PyQt5 import QtWidgets, uic 2 | import sys 3 | import time 4 | import uuid 5 | import random 6 | import threading 7 | 8 | class Ui(QtWidgets.QMainWindow): 9 | def __init__(self): 10 | super(Ui, self).__init__() 11 | uic.loadUi('PyQt5-Interactive-Window.ui', self) 12 | 13 | self.printbutton = self.findChild(QtWidgets.QPushButton, 'printButton') # Find the button 14 | self.printbutton.clicked.connect(self.printButtonPressed) # Remember to pass the definition/method, not the return value! 15 | self.printbutton.setEnabled(False) 16 | 17 | self.clearbutton = self.findChild(QtWidgets.QPushButton, 'clearButton') 18 | self.clearbutton.clicked.connect(self.clearButtonPressed) 19 | 20 | self.updatebutton = self.findChild(QtWidgets.QPushButton, 'updateButton') 21 | self.updatebutton.clicked.connect(self.updateButtonPressed) 22 | 23 | self.progressbar = self.findChild(QtWidgets.QProgressBar, 'updateProgress') 24 | self.progressbar.setValue(0) 25 | 26 | self.input = self.findChild(QtWidgets.QLineEdit, 'textInput') 27 | 28 | self.show() 29 | 30 | def printButtonPressed(self): 31 | # This is executed when the button is pressed 32 | if (self.input.text()) != "": 33 | print(self.input.text()) 34 | 35 | def clearButtonPressed(self): 36 | self.progressbar.setValue(0) 37 | self.printbutton.setEnabled(False) 38 | self.input.clear() 39 | 40 | def updateButtonPressed(self): 41 | for x in range(101): 42 | self.progressbar.setValue(x) 43 | time.sleep(0.001) 44 | self.input.setText(my_random_string(50)) 45 | self.printbutton.setEnabled(True) 46 | 47 | def my_random_string(string_length=50): 48 | random = str(uuid.uuid4()) 49 | random = random.upper() # Make all characters uppercase. 50 | random = random.replace("-","") # Remove the UUID '-'. 51 | return random[0:string_length] # Return the random string. 52 | 53 | app = QtWidgets.QApplication(sys.argv) 54 | window = Ui() 55 | app.exec_() 56 | -------------------------------------------------------------------------------- /PyQt5-Interactive-Window.ui: -------------------------------------------------------------------------------- 1 | <?xml version="1.0" encoding="UTF-8"?> 2 | <ui version="4.0"> 3 | <class>MainWindow</class> 4 | <widget class="QMainWindow" name="MainWindow"> 5 | <property name="geometry"> 6 | <rect> 7 | <x>0</x> 8 | <y>0</y> 9 | <width>500</width> 10 | <height>200</height> 11 | </rect> 12 | </property> 13 | <property name="minimumSize"> 14 | <size> 15 | <width>500</width> 16 | <height>200</height> 17 | </size> 18 | </property> 19 | <property name="maximumSize"> 20 | <size> 21 | <width>500</width> 22 | <height>200</height> 23 | </size> 24 | </property> 25 | <property name="windowTitle"> 26 | <string>Big Test</string> 27 | </property> 28 | <property name="windowOpacity"> 29 | <double>1.000000000000000</double> 30 | </property> 31 | <property name="styleSheet"> 32 | <string notr="true">background-color: #444; border: none;</string> 33 | </property> 34 | <widget class="QWidget" name="centralwidget"> 35 | <widget class="QLineEdit" name="textInput"> 36 | <property name="geometry"> 37 | <rect> 38 | <x>40</x> 39 | <y>20</y> 40 | <width>421</width> 41 | <height>41</height> 42 | </rect> 43 | </property> 44 | <property name="styleSheet"> 45 | <string notr="true">background-color: #222; color: #66FF66; padding: 8px;</string> 46 | </property> 47 | </widget> 48 | <widget class="QProgressBar" name="updateProgress"> 49 | <property name="geometry"> 50 | <rect> 51 | <x>40</x> 52 | <y>80</y> 53 | <width>421</width> 54 | <height>31</height> 55 | </rect> 56 | </property> 57 | <property name="styleSheet"> 58 | <string notr="true">QProgressBar { 59 | text-align: center; 60 | background-color: #222; 61 | } 62 | 63 | QProgressBar::chunk { 64 | background-color: #66FF66; 65 | width: 20px; 66 | }</string> 67 | </property> 68 | <property name="value"> 69 | <number>50</number> 70 | </property> 71 | <property name="textVisible"> 72 | <bool>false</bool> 73 | </property> 74 | </widget> 75 | <widget class="QPushButton" name="printButton"> 76 | <property name="geometry"> 77 | <rect> 78 | <x>324</x> 79 | <y>130</y> 80 | <width>137</width> 81 | <height>41</height> 82 | </rect> 83 | </property> 84 | <property name="font"> 85 | <font> 86 | <family>Calibri Light</family> 87 | <pointsize>14</pointsize> 88 | </font> 89 | </property> 90 | <property name="styleSheet"> 91 | <string notr="true">#printButton { 92 | background-color: #999; 93 | 94 | } 95 | #printButton:pressed { 96 | background-color: #888; 97 | border-style: inset; 98 | }</string> 99 | </property> 100 | <property name="text"> 101 | <string>Print</string> 102 | </property> 103 | </widget> 104 | <widget class="QPushButton" name="updateButton"> 105 | <property name="geometry"> 106 | <rect> 107 | <x>40</x> 108 | <y>130</y> 109 | <width>137</width> 110 | <height>41</height> 111 | </rect> 112 | </property> 113 | <property name="font"> 114 | <font> 115 | <family>Calibri Light</family> 116 | <pointsize>14</pointsize> 117 | <weight>50</weight> 118 | <bold>false</bold> 119 | </font> 120 | </property> 121 | <property name="styleSheet"> 122 | <string notr="true">#updateButton { 123 | background-color: #999; 124 | 125 | } 126 | #updateButton:pressed { 127 | background-color: #888; 128 | border-style: inset; 129 | }</string> 130 | </property> 131 | <property name="text"> 132 | <string>Update</string> 133 | </property> 134 | </widget> 135 | <widget class="QPushButton" name="clearButton"> 136 | <property name="geometry"> 137 | <rect> 138 | <x>182</x> 139 | <y>130</y> 140 | <width>137</width> 141 | <height>41</height> 142 | </rect> 143 | </property> 144 | <property name="font"> 145 | <font> 146 | <family>Calibri Light</family> 147 | <pointsize>14</pointsize> 148 | </font> 149 | </property> 150 | <property name="styleSheet"> 151 | <string notr="true">#clearButton { 152 | background-color: #999; 153 | 154 | } 155 | #clearButton:pressed { 156 | background-color: #888; 157 | border-style: inset; 158 | }</string> 159 | </property> 160 | <property name="text"> 161 | <string>Clear</string> 162 | </property> 163 | </widget> 164 | </widget> 165 | </widget> 166 | <resources/> 167 | <connections/> 168 | </ui> 169 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Bits-and-Bytes 2 | 3 | Here's my collection of sketches that I create while testing chunks of code for my bigger projects. Feel free to refrence or take what you want and learn from it! 4 | -------------------------------------------------------------------------------- /Random-Wait.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | 4 | def rwait(): 5 | x = 0 6 | y = 0 7 | while y != 3: 8 | y = random.randint(0, (10)) 9 | x = (x + 1) 10 | return x 11 | 12 | while True: 13 | print("Waiting", rwait(), "seconds.") 14 | time.sleep(rwait()) 15 | -------------------------------------------------------------------------------- /Re-Split.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | string = "Python,Bits_and-Byt!es" 4 | 5 | res = re.split(',|_|-|!', string) 6 | 7 | print(str(res)) 8 | -------------------------------------------------------------------------------- /Round-Dollars-to-Int.py: -------------------------------------------------------------------------------- 1 | a = "19.95" 2 | a = round(float(a)) 3 | 4 | print(int(a)) 5 | -------------------------------------------------------------------------------- /Selenium-Change-Window-Position.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | from selenium import webdriver 3 | from selenium.webdriver.chrome.options import Options 4 | import chromedriver_binary 5 | 6 | my_url = "https://google.com/" 7 | 8 | chrome_options = Options() 9 | 10 | # You can change the initial window postion by adding this option. 11 | chrome_options.add_argument('--window-position=-10000,0') 12 | 13 | # This disables console logs 14 | chrome_options.add_experimental_option("excludeSwitches", ["enable-logging"]) 15 | 16 | driver = webdriver.Chrome(options = chrome_options) 17 | 18 | driver.get(my_url) 19 | 20 | sleep(3) 21 | 22 | # This line will set the window position at any given moment. 23 | driver.set_window_position(0,0) 24 | -------------------------------------------------------------------------------- /Send-Bash-Cmds.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | 4 | while True: 5 | os.system('echo "hello"') 6 | time.sleep(900) 7 | -------------------------------------------------------------------------------- /String-To-Time-And-Compare.py: -------------------------------------------------------------------------------- 1 | import re 2 | from datetime import datetime 3 | from datetime import timedelta 4 | 5 | a = "2020-07-24T10:59:00-06:00" 6 | productTime = datetime.fromisoformat(a) 7 | 8 | nowTime = datetime.now().astimezone().replace(microsecond=0) 9 | 10 | print(productTime) 11 | print(nowTime) 12 | 13 | if productTime > nowTime: 14 | print("yey") 15 | -------------------------------------------------------------------------------- /Text-File-Maniuplation.py: -------------------------------------------------------------------------------- 1 | filePath = "C:/Path/To/textFile.txt" 2 | 3 | # Write over entire document. 4 | input_file = open(filePath, "w") 5 | input_file.write("Content Overwritten") 6 | input_file.close() 7 | 8 | # Append to document. 9 | input_file = open(filePath, "a") 10 | input_file.write("\nContent Appended") 11 | input_file.close() 12 | 13 | # Open document and assign to variable. 14 | input_file = open(filePath, "r") 15 | textContent = input_file.read() 16 | print(textContent) 17 | 18 | # Print and convert document to manageable array. 19 | items = textContent.splitlines() 20 | for x in range(len(items)): 21 | print(items[x]) 22 | -------------------------------------------------------------------------------- /Trailing-Average-Layered.py: -------------------------------------------------------------------------------- 1 | import random 2 | import threading 3 | import time 4 | 5 | def averageData(): 6 | global avOutter 7 | global avInner 8 | avOutter = [0] * 20 9 | avInner = [0] * 20 10 | while True: 11 | for y in range(len(avOutter)): 12 | for z in range(len(avInner)): 13 | avInner[z] = random.randint(0,9) 14 | #print(avInner) 15 | time.sleep(0.05) 16 | avOutter[y] = round(sum(avInner) / len(avInner)) 17 | print(avOutter) 18 | 19 | def main(): 20 | while True: 21 | print(round(sum(avOutter) / len(avOutter))) 22 | time.sleep(2) 23 | 24 | avdata_thread = threading.Thread(target=averageData) 25 | avdata_thread.start() 26 | 27 | main_thread = threading.Thread(target=main) 28 | main_thread.start() 29 | -------------------------------------------------------------------------------- /Trailing-Average.py: -------------------------------------------------------------------------------- 1 | import random 2 | import threading 3 | import time 4 | 5 | def averageData(): 6 | global avList 7 | avList = [0] * 20 8 | while True: 9 | for x in range(len(avList)): 10 | avList[x] = random.randint(0,9) 11 | print(avList) 12 | time.sleep(0.15) 13 | 14 | def main(): 15 | while True: 16 | print(round(sum(avList) / len(avList))) 17 | time.sleep(2) 18 | 19 | avdata_thread = threading.Thread(target=averageData) 20 | avdata_thread.start() 21 | 22 | main_thread = threading.Thread(target=main) 23 | main_thread.start() 24 | -------------------------------------------------------------------------------- /Translate-And-Analyze-Tweets.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import urllib.parse 4 | from textblob import TextBlob 5 | 6 | searchTerm = "Cats and Dogs!" 7 | searchTerm = urllib.parse.quote(searchTerm) 8 | 9 | getInfo = requests.get('https://api.twitter.com/1.1/search/tweets.json?q='+ searchTerm +'&result_type=recent&count=100', headers={"Authorization": "Bearer AAAAAAAAAAAAAAAAAAAAA"}) 10 | parsedInfo = json.loads(getInfo.text)['statuses'] 11 | 12 | pubTweets = [] 13 | for x in range(len(parsedInfo)): 14 | pubTweets.append(parsedInfo[x]['text']) 15 | 16 | def clean_tweets(tweet): 17 | tweet_words = str(tweet).split(' ') 18 | clean_words = [word for word in tweet_words if not word.startswith('#')] 19 | return ' '.join(clean_words) 20 | 21 | def translateText(inputText): 22 | TText = TextBlob(inputText) 23 | TText = TText.translate(to='en') 24 | return TText 25 | 26 | def analyze(Topic): 27 | positive_tweets, negative_tweets = [], [] 28 | 29 | for tweet in range(len(pubTweets)): 30 | cleanedTweet = clean_tweets(pubTweets[tweet]) 31 | try: 32 | cleanedTweet = str(translateText(cleanedTweet)) 33 | except: 34 | pass 35 | tweet_polarity = TextBlob(cleanedTweet).sentiment.polarity 36 | if tweet_polarity<0: 37 | negative_tweets.append(cleanedTweet) 38 | continue 39 | positive_tweets.append(cleanedTweet) 40 | return positive_tweets, negative_tweets 41 | positive, negative = analyze('Magufuli') 42 | print(positive , '\n\n', negative) 43 | print('Positive:',len(positive), ' VS ', 'Negative:',len(negative)) 44 | -------------------------------------------------------------------------------- /Translate-Goslate.py: -------------------------------------------------------------------------------- 1 | import goslate 2 | 3 | toTranslate = "How's it going?" 4 | 5 | def translateText(inputText): 6 | gs = goslate.Goslate() 7 | TText = gs.translate(inputText, 'fr') 8 | return TText 9 | 10 | print(translateText(toTranslate)) 11 | -------------------------------------------------------------------------------- /Translate-TextBlob.py: -------------------------------------------------------------------------------- 1 | from textblob import TextBlob 2 | 3 | toTranslate = "How's it going?" 4 | 5 | def translateText(inputText): 6 | TText = TextBlob(inputText) 7 | TText = TText.translate(to='fr') 8 | return TText 9 | 10 | try: 11 | print(translateText(toTranslate)) 12 | except: 13 | print("Couldn't translate:",toTranslate) 14 | -------------------------------------------------------------------------------- /Twitter-API-Get-Tweet.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | import re 4 | import html 5 | 6 | getInfo = requests.get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=USERNAME&count=1', headers={"Authorization": "Bearer AAAAAA"}) 7 | parsedInfo = json.loads(getInfo.text)[0] 8 | 9 | print("") 10 | print("---------------------------------------------") 11 | print("@" + str(parsedInfo['user']['screen_name'])) 12 | print(str(parsedInfo['user']['profile_image_url'])) 13 | print(str(parsedInfo['user']['name'])) 14 | print(str(parsedInfo['user']['description'])) 15 | print("") 16 | print(str(parsedInfo['created_at'])) 17 | msgText = html.unescape(str(parsedInfo['text'])) 18 | print(msgText) 19 | print("") 20 | print("---------------------------------------------") 21 | for y in parsedInfo['entities']['urls']: 22 | print ("Expanded Link:", y.get('expanded_url')) 23 | print("---------------------------------------------") 24 | -------------------------------------------------------------------------------- /URL-Unshortener.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import urllib.parse 3 | 4 | url = "https://bit.ly/35RF3kn" 5 | 6 | session = requests.Session() 7 | resp = session.head(url, allow_redirects=True) 8 | 9 | print(resp.url) 10 | -------------------------------------------------------------------------------- /Validate-BTC-Address.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import base58 3 | import binascii 4 | 5 | def convertByteToHex(inp): 6 | return ''.join(["%02x" % x for x in inp]) 7 | 8 | bitcoinAddress = "1nBJUwDQm6sBd8ye8YxMd7DhS8EXKE2cp" 9 | base58Decoder = base58.b58decode(bitcoinAddress).hex() 10 | prefixAndHash = base58Decoder[:len(base58Decoder)-8] 11 | checksum = base58Decoder[len(base58Decoder)-8:] 12 | hash = prefixAndHash 13 | for x in range(1,3): 14 | hash = hashlib.sha256(binascii.unhexlify(hash)).hexdigest() 15 | if(checksum == hash[:8]): 16 | print("Checksum is valid!") 17 | else: 18 | print("Checksum is NOT valid!") 19 | -------------------------------------------------------------------------------- /Wait-One-Week.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | waitWeek = datetime.datetime.today() 4 | 5 | while True: 6 | todayDate = datetime.datetime.today() 7 | currentWeekday = datetime.datetime.today().weekday() 8 | 9 | if todayDate > waitWeek and currentWeekday == 2: 10 | print("yey it's wednesday!") 11 | 12 | waitWeek = datetime.datetime.today() + datetime.timedelta(days=1) 13 | 14 | print(waitWeek) 15 | -------------------------------------------------------------------------------- /Websockets-Get-XLM-Coin-Data.py: -------------------------------------------------------------------------------- 1 | from websocket import create_connection 2 | import json 3 | 4 | # Header 5 | headers = json.dumps({ 6 | "Accept-Encoding" : "gzip, deflate, br", 7 | "Accept-Language" : "en-US,en;q=0.9", 8 | "Cache-Control" : "no-cache", 9 | "Connection" : "Upgrade", 10 | "Host" : "prod-pusher.backend-capital.com", 11 | "Origin" : "https://capital.com", 12 | "Pragma" : "no-cache", 13 | "Sec-WebSocket-Extensions" : "permessage-deflate; client_max_window_bits", 14 | "Sec-WebSocket-Key" : "0gTLZSs2ALEjQfop9zPNCA==", 15 | "Sec-WebSocket-Version" : "13", 16 | "Upgrade" : "websocket", 17 | "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36" 18 | }) 19 | 20 | # Create Connection 21 | ws = create_connection('wss://prod-pusher.backend-capital.com/app/MvtsstCbm?protocol=7&client=js&version=4.2.2&flash=false',headers=headers) 22 | 23 | # Handshake 24 | ws.send('{"event":"pusher:subscribe","data":{"channel":"27236401963685060"}}') 25 | 26 | 27 | # Print Received Info 28 | while True: 29 | try: 30 | result = ws.recv() 31 | try: 32 | b = json.loads(result) 33 | b = json.loads(b['data']) 34 | print("XLM - [ Bid:",b['bid'], "] - [ Ask:",b['ask'],"]") 35 | except: 36 | print(result) 37 | 38 | except Exception as e: 39 | print(e) 40 | break 41 | -------------------------------------------------------------------------------- /Write-HTML-Upload-FTP.py: -------------------------------------------------------------------------------- 1 | import ftplib 2 | import io 3 | 4 | session = ftplib.FTP('host','user','pass') 5 | 6 | imageUrl = 'https://avatars1.githubusercontent.com/u/9145304?s=460&u=1126a26b2ffac6187f655816e5eb0ffcb55c429b&v=4' 7 | 8 | image = '<img src="' + imageUrl + '"/>' 9 | 10 | HTMLPart1 = """<!DOCTYPE html> 11 | <html> 12 | <head> 13 | <title>test 14 | 15 | 16 | """ 17 | 18 | HTMLPart2 = """ 19 | 20 | """ 21 | 22 | HTMLFinal = bytes((HTMLPart1 + image + HTMLPart2), encoding= 'utf-8') 23 | HTMLFinal = io.BytesIO(HTMLFinal) 24 | session.storbinary('STOR test.php', HTMLFinal) 25 | -------------------------------------------------------------------------------- /testData.json: -------------------------------------------------------------------------------- 1 | { 2 | "objects": [ 3 | { 4 | "Status": "Active", 5 | "ID": "46888", 6 | "Name": "Apple", 7 | "Tags": [ 8 | "Fruit", 9 | "Red" 10 | ] 11 | }, 12 | { 13 | "Status": "Inactive", 14 | "ID": "99997", 15 | "Name": "Banana", 16 | "Tags": [ 17 | "Fruit", 18 | "Yellow" 19 | ] 20 | }, 21 | { 22 | "Status": "Active", 23 | "ID": "88445", 24 | "Name": "Carrot", 25 | "Tags": [ 26 | "Vegetable", 27 | "Orange" 28 | ] 29 | } 30 | ] 31 | } 32 | --------------------------------------------------------------------------------