The archive

Program & Design

Tips, tricks, tutorials, and tools on programming & web design.

66 posts

  1. How to optimize a website in 2018

    Let's start with caching. So many levels of caching. Before we even get to your website, there's DNS. What IP does your domain point to? Usually, your OS will cache this DNS lookup for you. Failing that, your DNS…

  2. How to generate a deployment key for Bitbucket

    SSH into your server Run ssh-keygen -t rsa to generate a public and private key pair It will ask you where you to save the files. I recommend /root/.ssh/bitbucket It will ask you to choose a passphrase. Since we're just…

  3. Installing node-canvas on Windows

    There's an article here that describes the process, but it's a bit vague in some areas and didn't work for me. If you're on 64-bit Windows, you will need the 64-bit version of GTK which comes bundled with Cairo if you…

  4. Selenium, PhantomJS, Node, Screenshots and Sizzle

    Without going into too much detail, I just wanted to post a snippet of how to get all these technologies playing nicely together: var webdriver = require ( 'selenium-webdriver' ); var fs = require ( 'fs' ); var driver =…

  5. Two-way implicit casting

    I'm presently writing a framework that wraps a C API using interop. Many of the classes/structs defined in the C library already exist in .NET, but I have to re-implement them anyway so that I can interface with the…

  6. Meteor, Blade + Windows 8

    Introductions Meteor is a hot new Node-based web development framework. Blade is a templating language based on Jade, which is a bit similar to Haml. Windows 8 is an operating system that no one but me likes.…

  7. Find devices on your network

    I have a NAS device on my network which has a web interface, but I didn't know it's IP. Running this simple command from cmd.exe gave me a handful of IPs to try which lead me to finding it very quickly: arp -a The…

  8. WAMP: Apache won't start/icon stays green

    I have a non-standard installation of WAMP . I've installed it to my Z:/wamp . Recently it stopped working. All the suggestions I found on the web told me to check port 80, or check the apache_error.log but that didn't…

  9. PHP: Generate a unique filename for a given directory

    This function will generate a filename unique to specified directory. If you're using it to create filenames for uploaded images, for example, you can give it a path to your upload folder an extension such as 'jpg'. It…

  10. High quality image resize (C#)

    You can use this class to resize images proportionally (maintaining aspect ratio), or to resize an image to an exact size and crop off excess (useful for making nice thumbnails): public static class ImageExt { public…

  11. Convert decimal numbers to any base (C#)

    You can use this little function to convert a decimal to any base. I use it for compacting large numbers. public static class BaseConverter { public static string Encode ( BigInteger value , int @base = 0 , string chars…

  12. Human Readable File Size in PHP

    public static function iec_file_size ($size, $digits = 4 , $unit = 0 ) { $units = array ( 'B' , 'KiB' , 'MiB' , 'GiB' , 'TiB' , 'PiB' , 'EiB' , 'ZiB' , 'YiB' ); while ($size >= 1024 ) { $size /= 1024 ; ++ $unit; }…

  13. Microphone Boost

    This post is a bit a different than my usual posts. I was on Skype, about to start a gaming session with my friend, when he notified me that my mic was really quiet compared to when he talked to his other friends. I…

  14. To split an image into tiles using ImageMagick

    If you've got ImageMagick installed, you can split an image into squares with a command like: convert -crop 256x256 terrain.png tiles/tile%03d.png I'm using this to break up a MineCraft texture I downloaded.

  15. Find where executable is installed to

    Often when writing a script, I want to put a hashbang (#!) at the top so that I can execute the file, but I can never remember where the binary for python or php is installed to. An easy way to find out is to use the…

  16. JSON Prettifier

    This is a simple class I wrote to nicely format a JSON string. Just call it with JsonFormatter.PrettyPrint(yourJsonString) public static class JsonFormatter { public static string Indent = " " ; public static void…

  17. Subtracting Sets

    A couple times now I've wanted to subtract one set ( HashSet<T> ) from another. HashSet has a method ExceptWith that does just this, except that it modifies the current set in place. What if you don't want that? You…

  18. String Slice

    Here's an extension method to slice strings in C#, similar to Python's slice notation. public static string Slice ( this string str , int ? start = null , int ? end = null , int step = 1 ) { if (step == 0 ) throw new…

  19. How to deep-copy/clone an object

    The easiest way to deep copy an object is to serialize and deserialize it. Here's an example from a project I'm working on: [ Serializable ()] public class Board : ICloneable , ISerializable { // ... object ICloneable .…

  20. Recursive get/set/has-attr

    def _getattr (obj, attr, default = None ): try : left, right = attr.split( '.' , 1 ) except : return getattr (obj, attr, default) return _getattr( getattr (obj, left), right, default) def _setattr (obj, attr, val): try…

  21. Thread-Safe Observable List for WPF

    I'm probably posting this too early; I haven't had a chance to extensively test it yet but I basically just locked every function down, and made any method that actually modifies the list run on the main thread so that…

  22. Thread-Safe Observable Priority Queue for WPF

    Building on my last post, I realized that you couldn't push elements onto the queue from a worker thread, making it pretty much useless. However, if we dispatch the pushes back to the UI thread, it should work, right?…

  23. Observable Priority Queue

    Just started playing around with WPF in VS 2010. They have this ObservableCollection class which you can bind to your DataGrid or ListControl and then when you add or remove items from it, the control is refreshed…

  24. Human-readable file size in C#

    static string ReadableFileSize ( double size , int unit = 0 ) { string [] units = { "B" , "KiB" , "MiB" , "GiB" , "TiB" , "PiB" , "EiB" , "ZiB" , "YiB" }; while (size >= 1024 ) { size /= 1024 ; ++ unit; } return String.…

  25. A Simple Priority Queue in C#

    using System ; using System . Collections . Generic ; using System . Linq ; using System . Text ; namespace QueueSpace { public class PriorityQueue < TValue > : PriorityQueue < TValue , int > { } public class…

  26. Django Send HTML Emails

    You can use this little function to load emails from a template and send them in both HTML and plaintext formats. from django.core.mail import EmailMultiAlternatives from django.template import loader, Context from…

  27. .NET Dock Panel

    Apparently .NET does not come with any dock widget, like the ones used for the Toolbox and Properties window in Visual Studio. However, there is a freely available one on sourceforge called DockPanel Suite .…

  28. C# Blocking Queue

    If you're writing a threaded application in C# and you need to wait until a resource becomes available, you can use this class. Very handy for producer/consumer scenarios. public class BlockingQueue < T > { Queue < T >…

  29. Django, Flatpages, Markdown, and Syntax Highlighting

    For what should have been an easy task, this turned out to be extraordinarily difficult. I assume you have Django already installed. If not, the tutorials on djangoproject.com aren't too terrible, provided you're not on…

  30. Qt + OpenGL Code Example

    This article is from August 2009; please see the updated and more detailed version here . I wanted to develop a game using OpenGL but I was having trouble deciding on a windowing library. Somebody suggested I try Qt, so…

  31. array_map_recursive

    Not much needs to be said here. function array_map_recursive ($callback, $arr) { $ret = array (); foreach ($arr as $key => $val) { if ( is_array ($val)) $ret[$key] = array_map_recursive ($callback, $val); else…

  32. All I want is a drag-and-drop CD burner

    I know I've mostly been posting code snippets here, but I originally started this site to post more in-depth tutorials. This isn't going to be one of those. I'm taking a spin and would like to say a few words on the…

  33. jQuery Select Table Column or Row

    Table rows are pretty easy to work as all the td elements are contained within one tr , but how would you grab all the td s in a single column? Why, by using these selectors of course! $.fn. row = function ( i ) {…

  34. SQL Injection Safe Queries Redux

    function mysql_safe_string ($value) { if ( is_numeric ($value)) return $value; elseif ( empty ($value)) return 'NULL' ; elseif ( is_string ($value)) return ' \' ' . mysql_real_escape_string ($value) . ' \' ' ; elseif (…

  35. Facebook PHP API: Get the names of all your friends

    If you didn't already know, Facebook has an API that exposes quite a darn bit information. You can easily query this data using their API, but each request takes a fair bit of time. Typically, to get the names of all…

  36. Get Domain & Subdomain from URL

    preg_match ( '/ ^ (?:www \. )?(?:(. + ) \. )?(. + \. . + ) $ /i' , $_SERVER[ 'HTTP_HOST' ], $matches); define ( 'PROTOCOL' , strtolower ( substr ($_SERVER[ 'SERVER_PROTOCOL' ], 0 , strpos ($_SERVER[ 'SERVER_PROTOCOL' ],…

  37. Insert into MySQL datetime column from PHP

    You can use this simple function to convert a unix timestamp (like the one obtained from time()) to MySQL datetime format: function mysql_datetime ($timestamp = null ) { if ( ! isset ($timestamp)) $timestamp = time ();…

  38. Human-readable file size in JavaScript

    "size" is in bytes, the rest you should be able to figure out. function readableFileSize ( size ) { var units = [ 'B' , 'KB' , 'MB' , 'GB' , 'TB' , 'PB' , 'EB' , 'ZB' , 'YB' ]; var i = 0 ; while (size >= 1024 ) { size…

  39. Flash Player 10 on Ubuntu 64-bit

    There's a wad of tutorials out there on how to to install this plugin, but I've found they either don't work, or over complicate things. If you haven't already found it, download the Flash Player 10 64-bit plugin for…

  40. Hash/unhash HTML

    Here's a little class I wrote that lets you hash HTML and other things so that you can do some processing on just the text, and then unhash the HTML again. class ht { static $hashes = array (); # hashes everything that…

  41. PHP string ends with

    There's a hundred ways to do this, but here's the one I came up with. It doesn't use regex's so it should be pretty quick. function ends_with ($str, $suffix) { return substr ($str, - strlen ($suffix)) == $suffix; }…

  42. Random String

    Just some functions for generating random strings in PHP. function randstr ($len = 8 , $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' ) { $i = 0 ; $str = '' ; $randmax = strlen ($chars) - 1 ;…

  43. Encode Array as String

    I wanted to store an array in a cookie, so I wrote these two functions: function encode_arr ($data) { return base64_encode ( serialize ($data)); } function decode_arr ($data) { return unserialize ( base64_decode…

  44. jQuery Select Text Range

    Here's a jQuery function I wrote which you can use to select a range of text in an input field. $.fn. selectRange = function ( start , end ) { return this . each ( function () { if ( this .setSelectionRange) { this .…

  45. Simple Rounded Corners with CSS

    I know there are umpteen billion tutorials on rounded corners out there, but here's an easy way that I like to do it. Requires only one image, and allows you to nudge your text as close to the corners are you like. If…

  46. Vertically center text with CSS

    Anyone who has used CSS for awhile knows that vertically aligning stuff isn't easy. Vertically aligning just text, however, is pretty simple. If your container is 30px tall, just set the line-height to 30px too and your…

  47. Draw an Unfilled Circle

    OpenGL doesn't seem to have any functions for drawing an unfilled circle, so you can use this code instead. It uses lines, so you can adjust the line thickness with glLineWidth and anti-alias it with…

  48. Base62 Encode

    If you have large integers and you want to shrink them down in size for whatever reason, you can use this code. Should be easy enough to extend if you want even higher bases (just add a few more chars and increase the…

  49. Easy Current Page Tab

    So, you have a bunch of links along the top of your page, and you want to highlight the current one when you click on it. Easy enough to do if you copy and paste the entire navbar onto every page and add some CSS to the…

  50. Human-readable file size in C

    I did a quick search on Google and couldn't find any code that did this in C/C++, so here's my contribution for the day. Just remember the allocate enough space in the buffer -- about 10 chars should be enough. char*…

  51. Extract (almost) any archive type

    After getting tired of trying to remember "tar xvzf", I wrote a little script for extracting almost any file type via the linux command-line. You can copy and paste this script into a text editor like gedit and save it…

  52. Draw IplImage

    OpenCV stores images in a data structure called IplImage. They provide methods for rendering it to the screen, but if you want to use OpenGL instead (which should be faster and gives you more flexibility), I wrote the…

  53. Get frame count from AVI

    Here's a little code snippet I wrote to get the number of frames in an AVI video file. int getFrameCount ( const char * filename ) { // only works on AVIs int frameCount; char size[ 4 ]; ifstream fin (filename, ios ::in…

  54. Templating with PHP

    There are two main ways to create templates with PHP. Header/Footer Files First, design a one-page static layout for your site. You should come up with something like this: <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0…

  55. Resize images using this PHP script

    Always bugs me when people stretch their images out of proportion, there's really no reason for it. Just use this simply function to nicely resize your images! If you want all your images the same size (like a square),…

  56. Use .htaccess to hide file extensions

    Create a file at the root of your web server called ".htaccess". Put the following code inside: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule .* $0.php This…

  57. cPanel Quick Config - Quick Tip

    Maybe I'm slow, but I just discovered "php.ini QuickConfig" in cPanel 11. It probably exists in prior versions too. It was hidden under "Software / Services". Most of the default settings should be fine, but you might…

  58. Mark's PHP Snippets

    These are just a few PHP snippets/functions I have written over the years and have found to be quite useful. mysql_connect ( 'localhost' , 'USERNAME' , 'PASSWORD' ); mysql_select_db ( 'DATABASE' ); This one really isn't…

  59. Create a Blog in 30 Minutes Without a Framework

    A lot of PHP frameworks like to boast "create a blog in 20 minutes". Well, I'm going to show you how to create a bare bones blog in about 30, but without the use of a framework. Our blog will include posts, and…

  60. XHTML 1.0 Strict Template

    Just a little template I like to use every time I create a new HTML page. The DOCTYPE does make a difference as to how the page is rendered. <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"…

  61. How To Create a Database and Install WordPress

    This tutorial isn't just about installing WordPress. It will cover how to set up a database using cPanel and, optionally, how to unzip files directly on your web server. WordPress also has installation documentation ,…