Code Samples
Samples of code I've written, in a variety of languages, with annotations and comments.
PHP
This is a class from my secureids plugin for CakePHP. When a new entity is saved to the database, this class generates a unique Base-64 and UUID for use as primary keys for the entity. This has a variety of uses, from security to scalability. For more info, check out Tom Scott's video on the subject on YouTube.
// file: /downloads/code_samples/php/IdentifiableBehavior.php class IdentifiableBehavior extends Behavior { /** * Generates a pseudo-random 13-character base 64 ID. */ public function generateBase64Id() { // Get random base 10 number between 0 and mt_getrandmax() $base10 = mt_rand() * mt_rand(); // Convert random base 10 number to base 16 $base16 = base_convert($base10, 10, 16); // Base 64 encode base 16 number $base64 = base64_encode(pack('H*', $base16)); // Replace unsafe URL characters (/ and +) $base64 = str_replace('/', '_', $base64); $base64 = str_replace('+', '-', $base64); // Remove trailing double-equals sign $base64 = rtrim($base64, '='); // Return Base 64 ID return $base64; } /** * Generates a pseudo-random RFC4211-compliant version 4 (non-name based) UUID. */ public function generateUuid() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" mt_rand(0, 0xffff), mt_rand(0, 0xffff), // 16 bits for "time_mid" mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } /** * Generates IDs for an entity before it is saved to the database. * * @param Event $event Instance of save event * @param EntityInterface $entity Entity being saved */ public function beforeSave(Event $event, EntityInterface $entity) { // Check if entity is being created in database // If so, update appropriate ID fields if present if ($entity->isNew()) { $entity->set($this->config('base64.field'), $this->generateBase64Id()); $entity->set($this->config('uuid.field'), $this->generateUuid()); } } }Repo Download
Javascript
I joined a society at one point that had an online portal that allowed all of its members to get in touch with one another in case of an emergency. Trouble was, there was no easy way to import the contacts to my phone, so I built a bridge: a Javascript userscript that would add a button to the portal and allow me to download the contacts as vCards which import in a snap on Android.
// file: /downloads/code_samples/js/vcard_creator.js (function() { 'use strict'; console.log('vCard Creator loaded'); // Build HTML elements var button = $('').attr('id', 'vcard').addClass('btn btn-success').text('Download vCard'); // Scrape data from page var head = $('#mainhead'); var data = $('h2:contains("Contact Info")').parent(); var names = $('#mainhead').text().trim().replace('Member - ', '').replace(/35[0-9]{4}/, '').trim().split(' '); var data_fname = names[0]; names.shift(); var data_lname = names.join(' '); var data_company = $('font#station_title').text().trim(); var data_title = $(data.children('p:contains("Position:")')[0]).text().trim().replace('Position: ', '').replace('none', 'Member'); var data_email = $(data.children('p')[0]).text().trim(); var data_address = $(data.children('p')[1]).text().trim(); var data_hphone = $(data.children('p')[2]).text().trim().replace(/h: ?/, ''); var data_cphone = $(data.children('p')[3]).text().trim().replace(/c: ?/, ''); // Generate data URL var mimetype = 'text/x-vcard'; var fname = encodeURIComponent(data_fname); var lname = encodeURIComponent(data_lname); var company = encodeURIComponent(data_company); var title = encodeURIComponent(data_title); var email = encodeURIComponent(data_email); //var wphone = encodeURIComponent('123-456-7890'); var hphone = encodeURIComponent(data_hphone); var cphone = encodeURIComponent(data_cphone); var address = encodeURIComponent(data_address); var page = encodeURIComponent(window.location.href); var newline = '%0D%0A'; var link = 'data:' + mimetype + ',BEGIN%3AVCARD%0D%0AVERSION%3A3.0' + newline + 'N%3A' + lname + '%3B' + fname + '%3B%3B%3B' + newline + 'FN%3A' + fname + '%20' + lname + newline + 'ORG%3A' + company + '%3B' + newline + 'TITLE%3A' + title + newline + 'EMAIL%3Btype%3DINTERNET%3Btype%3DWORK%3Btype%3Dpref%3A' + email + newline + //'TEL%3Btype%3DWORK%3Btype%3Dpref%3A' + wphone + newline + 'TEL%3Btype%3DHOME%3A' + hphone + newline + 'TEL%3Btype%3DCELL%3A' + cphone + newline + 'item1.ADR%3Btype%3DHOME%3A%3B%3B' + address + newline + 'item3.URL%3Btype%3Dpref%3A' + page + newline + 'END%3AVCARD%0D%0A'; button.attr('href', link).attr('download', (data_fname + ' ' + data_lname).replace(/ /g, '_').toLowerCase()); // Add button to page var all = outer.append(inner.append(button)); all.insertAfter('#mainhead'); })();Repo Download
Python
A git commit hook for ensuring I write good commit messages with time and ticket annotations. Commits like these make Jira and managers verrrry happy.
// file: /downloads/code_samples/python/ensure_time_and_ticket.hook import sys import re # Grab commit message f = open(sys.argv[1], 'r') msg = f.read().replace('\n', '') # Preprocess regex r1 = re.compile('#time \d+(m(in)?s*|h(r)?s*|d(ay)?s*)') r2 = re.compile('^XYZ-\d+') if not r1.search(msg): print("WARNING: organizational constraint failure: missing #time annotation") if not re.match(r2, msg): print("WARNING: organizational constraint failure: missing ticket number")Repo Download
C/C++
This was a devilishly difficult class I wrote for Bitcamp 2015. I was attempting to make a voice interface for git...it turned out that speech processing is a much more difficult concept than I was expecting! Not to mention this was done in an auditorium packed-full of college kids all jabbering at once 😺
(Wanna know the cool part? This code totally worked on a computer-generated speech sample file, I just couldn't get it functional in the loud auditorium.)
// file: /downloads/code_samples/cpp/Listener.cpp Listener::Listener() { std::cout << "Listener invoked" << std::endl; // Test pocketsphinx ps_decoder_t *ps; cmd_ln_t *config; FILE *fh; char const *hyp, *uttid; int16 buf[512]; int rv; int32 score; config = cmd_ln_init(NULL, ps_args(), TRUE, "-hmm", "/usr/local/share/pocketsphinx/model/en-us/en-us", "-lm", "/usr/local/share/pocketsphinx/model/en-us/en-us.lm.dmp", "-dict", "/usr/local/share/pocketsphinx/model/en-us/cmudict-en-us.dict", NULL); ps = ps_init(config); if (ps == NULL) std::cout << "Error: ps was null" << std::endl; // fh = fopen("lib/pocketsphinx/test/data/goforward.raw", "rb"); fh = fopen("etc/buffalo.wav", "rb"); if (fh == NULL) std::cout << "Error: file handle was null" << std::endl; rv = ps_start_utt(ps); if (rv < 0) std::cout << "Error: rv < 0" << std::endl; while (!feof(fh)) { size_t nsamp; nsamp = fread(buf, 2, 512, fh); rv = ps_process_raw(ps, buf, nsamp, FALSE, FALSE); } rv = ps_end_utt(ps); if (rv < 0) std::cout << "Error: rv < 0" << std::endl; hyp = ps_get_hyp(ps, &score); if (hyp == NULL) std::cout << "Error: Hyp was null" << std::endl; printf("Recognized: %s\n", hyp); fclose(fh); ps_free(ps); cmd_ln_free_r(config); } Listener::~Listener() { std::cout << "Listener destroyed" << std::endl; }Repo Download
C#
This is a component that I wrote to communicate with an API that pulled organizational volunteer data down into a desktop application that made organizing and dispatching volunteers easier. This was a CRAPPY API, guys, ok? I might be a little proud of my REST calls here.
// file: /downloads/code_samples/csharp/survivo_component.cs public class SurvivoComponent { /// < summary> /// Loads API connection parameters and prepares component for use. /// < /summary> public SurvivoComponent() { // Capture API connection parameters from the config file. orgId = ConfigurationManager.AppSettings["SurvivoApiOrgId"]; apiUrl = ConfigurationManager.AppSettings["SurvivoApiUrl"]; apiUsername = ConfigurationManager.AppSettings["SurvivoApiUsername"]; apiPassword = ConfigurationManager.AppSettings["SurvivoApiPassword"]; } /// < summary> /// Checks if the component can connect to Survivo. /// < /summary> /// < returns>Returns true if connection is successful, false otherwise.< /returns> public bool CanConnectToSurvivo() { bool canConnect = false; // First check if the app can connect to the Internet // If it can't, it can't connect to Survivo either, so return false. if (NetHelper.CanConnectToInternet()) { // Submit basic request to Survivo API // API should respond with code 200 (OK) using (WebClient client = new WebClient()) { byte[] response = client.UploadValues(apiUrl, new System.Collections.Specialized.NameValueCollection() { { "org_id", orgId }, { "login_email", apiUsername }, { "login_pw", apiPassword }, { "lookup_type", "vol" }, { "lookup_method", "id" }, { "result_type", "id" }, { "action", "select" } }); // Parse response from byte array into XML // Then get status code node value from XML via xpath lastResponse = System.Text.Encoding.UTF8.GetString(response); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(lastResponse); var status = xmlDoc.SelectSingleNode("/response/status/code").InnerText; // If the status code is 200, connection was successful. // Otherwise, read the error message from the response and log it. if (status.Equals("200")) { canConnect = true; } else { var message = xmlDoc.SelectSingleNode("/response/status/message"); log.Error("Unable to connect to Survivo: " + message.InnerText); } } } else { canConnect = false; } return canConnect; } /// < summary> /// Looks up a volunteer in the Survivo database by email address. /// < /summary> /// < param name="email">Email of volunteer to look up< /param> /// < returns>Volunteer object if volunteer email found< /returns> public Volunteer GetVolunteerFromEmail(string email) { Volunteer vol = null; if (CanConnectToSurvivo()) { // Submit lookup request to Survivo API using (WebClient client = new WebClient()) { byte[] response = client.UploadValues(apiUrl, new System.Collections.Specialized.NameValueCollection() { { "org_id", orgId }, { "login_email", apiUsername }, { "login_pw", apiPassword }, { "lookup_type", "vol" }, { "lookup_method", "email" }, { "result_type", "full" }, { "action", "select" }, { "lookup_vol_email", email } }); // Parse response from byte array into XML // Then get status code node value from XML via xpath lastResponse = System.Text.Encoding.UTF8.GetString(response); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(lastResponse); int responseCode = 0; int numRecords = 0; if (xmlDoc.HasChildNodes) { responseCode = int.Parse(xmlDoc.SelectSingleNode("//response/status/code").InnerText); numRecords = int.Parse(xmlDoc.SelectSingleNode("//response/status/records").InnerText); } // Check if Survivo API returned exactly one record // If so, create and populate the volunteer object...otherwise, vol is null. if (responseCode == 200 && numRecords == 1) { // Set volunteer properties from XML data // One property (email) is pulled from the method parameters. vol = new Volunteer() { Id = int.Parse(xmlDoc.SelectSingleNode("//volunteer/cervis_vol_id").InnerText), FirstName = xmlDoc.SelectSingleNode("//volunteer/fname").InnerText, LastName = xmlDoc.SelectSingleNode("//volunteer/lname").InnerText, Email = email, PrimaryPhone = xmlDoc.SelectSingleNode("//volunteer/priphone").InnerText, AlternatePhone = xmlDoc.SelectSingleNode("//volunteer/altphone").InnerText, StreetAddress1 = xmlDoc.SelectSingleNode("//volunteer/address").InnerText, StreetAddress2 = xmlDoc.SelectSingleNode("//volunteer/address_line_2").InnerText, City = xmlDoc.SelectSingleNode("//volunteer/city").InnerText, State = xmlDoc.SelectSingleNode("//volunteer/state").InnerText, ZipCode = int.Parse(xmlDoc.SelectSingleNode("//volunteer/zip").InnerText), AccountType = xmlDoc.SelectSingleNode("//volunteer/acct_permission").InnerText, AccountStatus = xmlDoc.SelectSingleNode("//volunteer/acct_status").InnerText, CreationDate = DateTime.ParseExact(xmlDoc.SelectSingleNode("//volunteer/cervis_start_date").InnerText, "yyyy-MM-dd", CultureInfo.InvariantCulture), LastActive = DateTime.ParseExact(xmlDoc.SelectSingleNode("//volunteer/last_activity").InnerText, "yyyy-MM-dd", CultureInfo.InvariantCulture) }; } else { log.Error("Survivo volunteer lookup failed for " + email); } } } return vol; } }Repo Download
Java
This is a realllly simple Java app that I wrote to help me solve the hacking minigames in Fallout 4 back when I was a new player. I solve them in my head now, but it took some getting used to! (not familiar with Fallout? Check out an online version of the minigame here - click the red button to begin!)
// file: /downloads/code_samples/java/Cracker.java public class Hacker { /** * Returns a random guess from the password list * * @return Random guess */ public String getGuess() { guess = passwords.get(0); return guess; } /** * Returns an educated guess from the password list * * @param similarity Similarity of previous guess and correct answer * @return Educated guess */ public String getGuess(int similarity) { // Remove old guess from passwords list if (passwords.contains(guess)) { passwords.remove(guess); } for (int i = 0; i < passwords.size(); i++) { // Compare old guess to each password String password = passwords.get(i); int matches = 0; for (int j = 0; j < password.length(); j++) { if (password.charAt(j) == guess.charAt(j)) { matches++; } } // Check if password and guess are similar if (matches != similarity) { // Remove password from passwords list passwords.remove(password); } } // Get new guess from passwords list guess = passwords.get(0); // Return new guess return guess; } }Repo Download
Shell
For this sample I dug up some of my old dotfiles that I wrote. I'm a command-line junkie, so I love customizing dotfiles. Custom functions, aliases, commands, you name it. If it makes my dev box go faster I'm all ears.
// file: /downloads/code_samples/shell/funcs.sh ## # Checks if the system is currently needs a reboot ## function is_reboot_pending { if [ -f /var/run/reboot-required ]; then return true else return false fi } ## # Reloads an Apache Vhost and restarts Apache to apply configuration changes ## function reload_apache_vhost { if [ ! -z $1 ]; then echo "INFO: Reloading Apache Vhost $1..." a2dissite $1 a2ensite $1 service apache2 reload else echo "ERROR: Must specify name of virtual host name to reload" fi } ## # Displays information on the system's battery (charge state, time to full, etc.) ## function display_battery_info { if hash upower 2>/dev/null; then upower -i $(upower -e | grep 'BAT') | grep -E "state|time\ to\ full|percentage" else echo "ERROR: upower is required to run this command" fi } ## # Sets the appropriate permissions on /tmp and /logs for a CakePHP application ## function fix_cakephp_permissions { HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1` setfacl -R -m u:${HTTPDUSER}:rwx tmp setfacl -R -d -m u:${HTTPDUSER}:rwx tmp setfacl -R -m u:${HTTPDUSER}:rwx logs setfacl -R -d -m u:${HTTPDUSER}:rwx logs } ## # Generates a random security key for a CakePHP application ## function generate_cakephp_security_key { cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1 } ## # Sets the permissions of the user's SSH files to the right values ## function fix_ssh_permissions { chmod 700 ~/.ssh chmod 644 ~/.ssh/id_rsa.pub chmod 600 ~/.ssh/id_rsa } ## # Colorizes man page output ## man() { env \ LESS_TERMCAP_mb=$(printf "\e[1;31m") \ LESS_TERMCAP_md=$(printf "\e[1;31m") \ LESS_TERMCAP_me=$(printf "\e[0m") \ LESS_TERMCAP_se=$(printf "\e[0m") \ LESS_TERMCAP_so=$(printf "\e[1;44;33m") \ LESS_TERMCAP_ue=$(printf "\e[0m") \ LESS_TERMCAP_us=$(printf "\e[1;32m") \ man "$@" } export FUNCTIONS_CREATED=trueRepo Download
Wanna see more?
Check out my Codepen! Puzzles, scriptlets, & other treasures.