I don't know how but I'm writing!

Showcase: Some programs I wrote

Programs I have written

I was doing some further cleanup of my hard drive and I found some humorous snippets, so I thought I'd post them.

passman.py

Creation Date: 01 November 2013, time unknown

#!/usr/bin/python
#
# passman.py
# @author Drew Malzahn
# @version 2013.11.01
#
# Just a tiny password managing script I'm playing around with
# Possible features coming soon:
# - GUI
# - Crypto / other security
#
# WARNING:
# USING THIS TO ACTUALLY STORE PASSWORDS 
# IN ITS CURRENT ITERATION WOULD BE STUPID.
# DON'T DO IT.
# this is just a project I'm screwing around
# with, so don't use it as a serious tool.
#
import json, os, sys

# Def main functions
def get_ans(prompt):
    print(prompt)
    while True:
        x = raw_input("[Y/N] ")
        if x in ("yes", "YES", "y", "Y"):       return True
        elif x in ("no", "NO", "n", "N"):       return False
        else:                                   print("Please type 'yes' or 'no'. ")

def add(name, un, pw, com):
    j[name] = {"UNAME":un, "PASS":pw, "COM":com}

def mod(name, un, pw, com):
    try:
        x = j[name]
        j[name] = {"UNAME":un, "PASS":pw, "COM":com}
    except KeyError:
        print("The service you wish to modify doesn't exist.") 
    
def get(name):
    try:
        print("Service name: " + name)
        print("Username: " + j[name]["UNAME"])
        print("Password: " + j[name]["PASS"])
        print("Comment: " + j[name]["COM"])

    except KeyError:
        print("The service you wish to get info about doesn't exist.")
    
def rem(name):
    try:
        del j[name]
    except KeyError:
        print("The service you wish to delete doesn't exist.")

def dispall():
    for x in j:
        print("Service name: " + x)
        print("Username: " + j[x]["UNAME"])
        print("Password: " + j[x]["PASS"])
        print("Comment: " + j[x]["COM"])
        print

def passgen():
    import hashlib
    if os.name != 'posix':
        print "Sorry, this feature is only available on UNIX."
        return 0
    with open('/dev/random', 'rb') as fobj: rand = fobj.read(10)
    rand = hashlib.md5().update(rand).digest()
    print("Your new password: " + rand)

## Open the password file for reading
while True:
    try:
        with open("pass.txt", 'r') as fobj:
            jsn = fobj.read()
        break
    except IOError:
        i = get_ans("No password file found, would you like to create one?")
        if i:
            os.system("touch pass.txt")
            os.system("echo {} > pass.txt")
        else:
            print("Okay, exiting...")
            sys.exit(1)

try:
    j = json.loads(jsn)
except ValueError:
    print("Your password file is formatted wrong!")
    sys.exit(1)

## main loop
print("Welcome to Password Manager")
print("What would you like to do?") 
while True:
    #... just in case
    name= ""
    un = ""
    pw = ""
    com = ""
    print("1. Add an account")
    print("2. Modify an account")
    print("3. Retrieve an account")
    print("4. Remove an account")
    print("5. Display all accounts")
    print("6. Generate a sample password ")
    print("7. Exit")
    a = raw_input("> ")
    if a in ("yes", "YES", "y", "Y", "n", "N", "NO", "n"):
        print("Nice try.")
        break
    elif a == "1":
        name = raw_input("Name of Service: ").rstrip().lstrip()
        un = raw_input("Username or Email: ").rstrip().lstrip()
        pw = raw_input("Password: ")
        com = raw_input("Comment?: ").rstrip().lstrip()
        add(name, un, pw, com)
    elif a == "2":
        name = raw_input("Please enter the name of the service you would like to edit: ").rstrip().lstrip()
        un = raw_input("New Username or Email: ").rstrip().lstrip()
        pw = raw_input("New password: ")
        com = raw_input("New comment?: ").rstrip().lstrip()
        mod(name, un, pw, com)
    elif a == "3": get(raw_input("Name of Service: ").rstrip().lstrip())
    elif a == "4": rem(raw_input("Name of Service: ").rstrip().lstrip())
    elif a == "5": dispall()
    elif a == "6": passgen()
    elif a == "7": break
    else: print("Sorry, your input wasn't understood. Try again.")

# Cleanup
outdata = json.dumps(j)
with open('pass.txt', 'w') as fobj: fobj.write(outdata)
print("All done!")

This file is interesting and amusing in a few ways. For one, the comments in it are very self-serious: as if I really had to warn anyone about the safety of a Python program made for storing passwords in plain text written by a 17-year-old. ("Nice try." made me giggle.) The indentation struck me as being very un-Pythonic and looking very unlike a program I would write today. The use of a number menu instead of a subcommand-like interface is quaint, almost innocent.

stego.py

Creation Date: 23 April 2014, 4:36 PM

#!/usr/bin/python
# stego.py
# Simple script to embed data inside image files.
import argparse, os, sys

ident = {
    "PK\x03\x04":".zip",
    "\x89PNG":".png",
    "\xff\xd8\xff\xe0\x00\x10JFIF":".jpg"
}

endbytes = {
    ".png":"IEND\xAE\x42\x60\x82",
    ".jpg":"\xFF\xD9"
}

def put_data(data, img):
    try:
        with open(img, 'a+b') as fobj:
            fobj.write(data)
        print("Data written!")
    except IOError:
        print("Something went wrong!")
        sys.exit(1)

def simple_extract(img):
    ext = img[-4:]
    with open(img, 'rb') as fobj: s = fobj.read()
    pos = s.find(endbytes[ext])
    if pos == -1:
        print("Something went really wrong!")
        sys.exit(1)
    snew = s[pos+len(endbytes[ext]):]
    if not snew:
        print("The file has no hidden data.")
        return 0
    uext = ".dmp"
    for t in ident:
        if t in snew:
            uext = ident[t]
    with open("hidden_data"+uext, 'w+b') as fobj: fobj.write(snew)

def put_jpg_data(data, jpg):
    pass

# Set up argparse
parser = argparse.ArgumentParser()
parser.add_argument("image", help=".png file you wish to run operations on.")
parser.add_argument("--data", help="Data you wish to store.")
args = parser.parse_args()

if not os.path.isfile(args.image):
    print("%s does not exist!" % args.image)
    sys.exit(1)

data = ""
try:
    with open(args.data, 'r') as fobj:
        data = fobj.read()
except:
    if args.data:
        print("%s cannot be opened. Exiting..." % args.data)
        sys.exit(1)

if data:
    put_data(data, args.image)
else:
    simple_extract(args.image)

print("All done! Exiting...")
sys.exit(0)

I definitely wrote this in high school, not only because of the date, but because it was part of a set of programs I wrote for my (now defunct) 'Programming Club' that I tried to start. It appears to use a simple and well-known steganography technique to hide data inside image files. I find it really hard to believe I came up with the idea by myself, but the code does actually seem to be written by me.

OliverHw2.java

Creation Date: 25 October 2014, 11:20 PM

//Turn Audio On == Lower Audio When On
// 10:32 objects move in pseudo sync
import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
 
int topLeftX, topLeftY;
int bottomRightX, bottomRightY;
int xSpeed, ySpeed;
int startTime;
int score;
int totalScore;
int lives;
int playerX, playerY, playerR;
int playerDeltaX, playerDeltaY;
boolean gameStart, collOff;
 
Minim minim;
AudioPlayer HeavensFall; //variable name
 
void setup()
{
  //rectangle
  size(800, 600);
  noStroke();
  topLeftX= width / 2 - 25;
  topLeftY= height / 2 - 50;
  bottomRightX = width / 2 + 120;
  bottomRightY = height / 2 + 150;
  xSpeed  = 4;
  ySpeed  = 5;
  textSize(20);
  startTime = 0;
  totalScore = 0;
  gameStart = false;
  collOff = false;
 
  /* Define variables for the player */
  playerR= 60;
  playerX = playerR;
  playerY = playerR;
  playerDeltaX = 3;
  playerDeltaY= 4;
 
  minim = new Minim(this);
  HeavensFall = minim.loadFile("08. aLIEz (Instrumental).mp3");
  HeavensFall.loop();
  // Music will need some debugging as its getting a JavaSound Minim Error -> ID3 code APIC error
}
void draw()
{
  background(0);
  //start rectangle
  fill(255, 0, 255 );
  rectMode(CORNERS);
  rect(topLeftX, topLeftY, bottomRightX, bottomRightY);
  //end retctangle
 
  moveBoss();
  drawPlayer();
  drawText();
  movePlayer();
}
 
void moveBoss()
{
  if (topLeftX <= 0 || bottomRightX > width)
    xSpeed = -xSpeed;
 
  if (topLeftY <= 0 || bottomRightY >= height)
    ySpeed = -ySpeed;
 
  // start moving Boss
  topLeftX += xSpeed;
  bottomRightX += xSpeed;
 
  topLeftY += ySpeed;
  bottomRightY += ySpeed;
  // stop moving Boss
}
 
void drawPlayer()
{
  fill(0, 255, 255);
  ellipse(playerX, playerY, playerR, playerR);
}
 
void mousePressed()
{
  startTime = millis();
  totalScore += (millis() - startTime) / 1000;
}

void drawText()
{
  //scoring etc
  if (gameStart && lives > 0)
  {
    int score = millis() - startTime / 50000;
    text(millis() / 1000, 25, 25);
    text("Round score: " + score, 25, 25);
    text("Total score: " + totalScore, 25, 75);
  } 
  else
  {
    text("Game over", 25, 25);
    text("Final score: " + totalScore, 25, 75);
    text("Lives: " + lives, 25, 125);
  }  // end scoring etc
}

void movePlayer()
{
  if (playerX < playerR || playerX > width - playerR)
  {
    playerDeltaX = -playerDeltaX;
  }
  if (playerY < playerR || playerY > height - playerR)
  {
    playerDeltaY = -playerDeltaY;
  }
  playerX += playerDeltaX;
  playerY += playerDeltaY;
}

int checkCollision()
{
  int[] topcorner = {playerX - playerR, playerY - playerR};
  int[] bottomcorner = {playerX + playerR, playerY + playerR};

  if (topcorner[0] >= topLeftX && topcorner[0] <= bottomRightX && topcorner[1] >= topLeftY && topcorner[1] <= bottomRightY)
  {
    collOff = true;
    return 1;
  }
  return 0;
}

This one is a doozy. Several comments:

  1. From the filename, I was clearly helping someone (probably Oliver) with their homework. I don't think I wrote this code, but there's no way to know.
  2. The file does not look like valid Java. I don't think this would compile.
  3. I don't really know what the file is doing but it appears to be some sort of game.
  4. The file 08. aLIEz (Instrumental).mp3 is a theme from an anime called Aldnoah.Zero, which was released in February of 2014 and I do actually remember watching.
  5. I really like the line AudioPlayer HeavensFall; //variable name. Thanks for letting me know!

tmp.rkt

Creation Date: 21 February 2016, 11:47 PM

#lang racket

(define (choose n r)
  (/ (factorial n) (* (factorial (- n r)) (factorial r))))

(define (factorial n)
  (if (eq? n 0)
      1
      (* n (factorial (- n 1)))))

(foldl + 0 (map (lambda (i) (* i (choose 6 i) (expt 0.10 i) (expt 0.90 (- 6 i)))) (range 6)))

(- 1 (* (choose 6 1) 0.10 (expt 0.90 5)) (expt 0.90 6))

The expression at the bottom can be written as:

1(61)(0.10)(0.905)(0.906)

I honestly have no idea what this could mean but it looks like it could be related to a Binomial Distribution. The foldl looks like I was trying to generate data for a plot? Probably no way to know as it's not associated with any other file or folder.

halp.py

Creation Date: 2 September 2016, 12:17 AM

import os
import csv

def grep_file(fname, regex):
    cmd = "\"C:\\Program Files\\Git\\bin\\ag.exe\" {0} '{1}'".format(regex, fname)
    os.system(cmd)

with open('halp.csv', 'r', encoding='utf-8') as csvfile:
    csvread = csv.reader(csvfile)
    for row in csvread:
        fn = os.path.join(row[1], row[0])
        print(fn)
        grep_file(fn, r"[A-Za-z0-9]{20}")

No idea what halp.csv is, or why I couldn't just use a shell script. Probably because I was on Windows.

stuff.py

Creation Date: 7 September 2016, 5:01 PM

def hello(hi):
    print(hi)

    hello

(Yes, I know what you're thinking - this program is a no-op.)

test.el

Creation Date: 13 October 2016, 1:55 AM

(message "Fuck")

test.erl

Creation Date: 15 November 2016, 4:40 PM

-module(test).
-compile(export_all).

start() ->
    Pid = func(),
    A = [{func(), 1}, {func(), 2}, {func(), 3}, {Pid, 4}],
    %% A = [func(), 1, func(), 2, func(), 3, Pid, 4],
    case lists:keyfind(Pid, 1, A) of
        {Pid, Val} -> Val;
        false -> exit("WHAT THE FUCK IS GOING OOOON")
    end.

func() ->
    spawn(fun () -> timer:sleep(2000) end).

collector/main.py

Creation Date: 7 July 2016, 9:24 PM

from argparse import ArgumentParser
from urllib.parse import urlparse

def main():
    _prog = os.path.basename(os.path.abspath(__file__))
    ap = ArgumentParser(
        prog=_prog,
        description="Simple CLI frontend for collector."
    )
    ap.add_argument("-s", "--status", )

if __name__ == "__main__":
    main()

... That's the entire file. No other files in the folder. Apparently this idea wasn't good enough to make it past the "copy a template from online" stage.

crypto_example.py

Creation Date: 19 September 2017, 5:02 PM

from Crypto.Cipher import AES

Now this is cryptography!

prank_ls.c

Creation Date: 15 August 2018, 10:59 PM

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv, char **env) {
    int fd;
    unsigned short rnd;
    if ((fd = open("/dev/urandom", O_RDONLY)) > -1) {
        if (read(fd, (char*)&rnd, 1) == 1) {
            if (rnd % 20 == 3) {
                return execvp("/bin/sl", argv);
            }
        }
    }
    execvp("/usr/local/share/ls.backup", argv);
    return -1;
}

In retrospect, I don't know if this is 'funny' or just 'evil'...

mcbot.py

Creation Date: 3 July 2020, 1:22AM

import re
import sys
import time
import cv2
import pytesseract
import win32gui
import numpy as np
from PIL import Image, ImageGrab

pytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe' # TODO

def find_window(window_name_or_comparator):
    """
    This is gross.
    https://stackoverflow.com/questions/55547940/how-to-get-a-list-of-the-name-of-every-open-window
    """
    _wnoc = None
    _lst = []

    def win_enum_handler(window_handle, context):
        window_name = win32gui.GetWindowText(window_handle)
        if callable(_wnoc):
            try:
                if _wnoc(window_handle, context):
                    _lst.append((window_handle, context))
            except TypeError:
                pass
        elif isinstance(_wnoc, str) and _wnoc == window_name:
            _lst.append((window_handle, context))
        else:
            mobj = _wnoc.match(window_name)
            if mobj:
                _lst.append((window_handle, context))

    _wnoc = window_name_or_comparator
    win32gui.EnumWindows(win_enum_handler, None)
    return _lst

def process_img(image):
    original_image = image
    # convert to gray
    processed_img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    # edge detection
    # processed_img =  cv2.Canny(processed_img, threshold1=200, threshold2=300)
    (thresh, processed_img) = cv2.threshold(processed_img, 127, 255, cv2.THRESH_BINARY)
    return processed_img

def main():
    windows = find_window(re.compile(r"Minecraft 1.16.*"))
    if not windows:
        sys.exit("Cannot find an open instance of Minecraft; exiting")
    window_handle, window_context = windows[0]
    box = win32gui.GetWindowRect(window_handle)
    win_left, win_top, win_right, win_bot = box
    window_bound = (win_left, win_top, win_right, win_bot)

    # while True:
    #     screen = np.array(ImageGrab.grab(bbox=window_bound))
    #     new_screen = process_img(screen)
    #     cv2.imshow('window', new_screen)

    #     image = image[127:219, 508:722]
    #     #(thresh, image) = cv2.threshold(image, 128, 255, cv2.THRESH_BbINARY | cv2.THRESH_OTSU)
    #     cv2.imwrite('test.jpg', image)
    #     print('Text detected: {}'.format(pytesseract.image_to_string(Image.open('test.jpg'))))
    #     time.sleep(2)

    #     # TODO Why not just pytesseract.image_to_string(image) ???

    #     # TODO
    #     # if cv2.waitKey(25) & 0xFF == ord('q'):
    #     #     cv2.destroyAllWindows()
    #     #     break

    while True:
        screen = np.array(ImageGrab.grab(bbox=window_bound))
        screen = process_img(screen)
        screen = screen[32:132, 2:100]
        cv2.imshow('window', screen)
        cv2.imwrite('test.jpg', screen)
        # image = new_screen[win_left:win_top, win_right:win_bot]
        #(thresh, image) = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
        print('Text detected: {}'.format(pytesseract.image_to_string(Image.open('test.jpg'))))
        cv2.waitKey(20)
        # time.sleep(2)

import string
string.printable
main()

I remember this now, actually! Previously I had several RuneScape bots that worked doing basically the dumbest thing you can think of:

  1. Take a screenshot of the window
  2. Look for a target by checking a pre-defined list of color values
  3. Interact by clicking
  4. Look for additional pixels indicating the operation worked
  5. Repeat!

Doing this was surprisingly easy and effective and I had more than one bot that would buy and sell things on the Grand Exchange. Apparently in 2020 I tried to replicate this success in Minecraft but with a bit more complex of an algorithm that tried to detect text and edges of objects on the screen. Looking at the file, it doesn't look like my experiments worked. I don't think I ever got to the point where the game was running and the bot was actually reading the screen, it was just reading from a screenshot called test.jpg.

I've lightly edited the file to make it easier to fit embedded in the text, but you can kind of see that my coding style was well-formed at this point: lots of spaces and comments, preferring functions over class definitions, and a number of 'early-fail' checks (where instead of throwing a Python exception, we just quit out). I still write code that looks pretty much like this.

Disclaimer

If you're reading this and you're a recruiter or (God forbid) my employer or something, just know that this supposed to be funny and not actually representative of my programming skill. For more serious code you can check out my Github.