Video Game Artifacts

Isn’t it beautiful? There is something hypnotic about that watching that video game – Robotron 2084. The levels are all fundamentally the same, and the action always takes place in an open arena.

But later, the enemies start getting silly. Glowing circles, rainbow-color-changing enemies, and, my personal favorite, the number “2084” shooting stuff at you.

Some of these enemies actually take advantage of graphical artifacts from that era of computing, such as indirect color registers, which store color information outside of the screen buffer. By changing a single register, you change the color of every pixel on the screen. By running through a loop and changing this register, you create flashing and color change effects.

I like this aspect of graphics : Playing with registers to create a cool graphical effect.

Fun stuff.

How to Code

I love this programming article by Terri Burns on Rookie Magazine! I could probably just retweet/share/like it, but I wanted to add my own $0.03 worth (up from $0.02 because I’m more opinionated than most…)

A step-by-step process:

1 Consider your Interests.

What I really want you to do here is to pick a platform. Do you want to write a game? What will people use to play it? Will they play your game in their web browser? On an iPhone? An Android? Or would you rather write a game within Minecraft that people play on a Minecraft server?

A web game will require you to learn JavaScript, and probably a game engine like EaselJS or Phaser. You will also need minimal HTML5 and CSS3 skills.

An iPhone game requires you to learn Objective-C or the Swift language. Android and Minecraft both require Java skills. There are loads of books targeted at Language and Platform, and you want to start with materials that apply to both. Don’t just pick up a generic HOWTO Java book when there are so many materials specialized to your needs.

2 Pick a Language

If you’ve done your job in step 1, then you may skip this step. But if you have a choice here one way or another, consider this: Many starting developers want to learn a language that’s hot, and a language that’s new.

And that’s exactly what you SHOULD do!!!

Github has an index showing language popularity in its open-source projects.  These languages are constantly changing by improving and adding new features for programmers to utilize. There is a reason for this : These new features help developers do more powerful things with less headache.

When it comes to programming languages, modern is better. Popular is better. Don’t learn an obscure language just because your programmer buddy tells you how Elite it is.

3 Learn It!

If you want to code, you must do two things: read code and write code.

Get a book with lots of examples, and watch YouTube videos. Pause the videos and type in the exact code the tutors are demonstrating. You really will learn by doing this! Follow your curiosity and try things. You can’t break it. Get a StackOverflow account and ask questions. Don’t worry if the moderators mark it as duplicate or ask you for more details. You are learning and that is the point!

4 Consider your Resources

YouTube videos, Safari Books Online, the library (often with free online resources!)… The list goes on. The less structure, the better! Don’t sign up for a course unless you really want the fundamental theory and mathematics. You don’t need university courses unless you’ve decided to make this your career. Programming can be a hobby just like sewing or landscaping!

5 Join Communities

Join Meetup.com or check around your local universities for groups with similar interests – Not just programming, but programming on the platform using the language you’ve picked.

Once you start working with other developers, you will be bombarded with a torrent of cases and tricks and techniques you never dreamed existed. You’ll start to get the feeling that you really didn’t know anything in the first place. That’s OK! Programming is a deep field that takes years to master. Learn, build, and don’t worry about it.

6 Build Something

It takes reading and writing to learn coding, but it you have to try to build something unique to really test the limits of your knowledge. Expect to spend a lot of time debugging and trying to figure out why things don’t work.

This is where tools are important. A good Integrated Development Environment (IDE) is important here (the books you picked in step will tell you which IDE to use). Take the time to learn the features of the IDE, especially the debugger and code refactoring. And I highly recommend you learn git or some other Version Control System (VCS). It gives you a backup for all of your work and allows you to track changes. You’ll be happy you learned it the first time you break a working program and need to revert to a working version.

Don’t worry if it’s not perfect! It’s yours! It works! You made something, and that is really cool!

7 Keep it Up!

If you want to be a software developer, develop software. It is its own field. Programming is unlike any other discipline. It is not science, it is not engineering, it is not business, it is not art.

We design, gathering and assembling the pieces we will need to realize our vision.

We write, carefully considering the expressiveness of what we write. The future of the project often rests on the quality of the code.

We solve problems, using math and technology to light the way.

It’s a fun hobby.

It’s an awesome career.

Functional JavaScript

Fun Fun Function is a wonderful video series for learning JavaScript and functional programming. I decided to try my own Map/Reduce filter in JS and uploaded it to my toybox. Some random notes of things I learned along the way:

  • JavaScript has four different variable scoping modifiers: letvarconst, and default (no modifier). let scopes to a block (like a loop), const also scopes to a block and prevents reassignment (though referenced objects may still be mutable), var scopes to a function, and the absence of modifiers indicates a global variable. As always, beware of hoisting which allows a variable to be scoped after it has already been used in code. Not all of these are available in all versions of JavaScript.
  • Running his examples using babel as an ES2015 transpiler is not trivial. To get it to run, I had to do:
    • npm install –save-dev babel-cli
    • npm install –save-dev babel-preset-es2015
    • export PATH=”./node_modules/.bin:$PATH”
    • babel –presets=es2015 medalOTM.js | node
  • JS map takes one parameter and returns one result. This is what you would expect of a mapping or relation.
  • JS reduce is more complex. It reduces the entire pipeline to a single object. This function takes a single callback function parameter and an optional initial value.
    • The initial value can be thought of as the starting point for an object to be built up by the reduce callback over many iterations of the pipeline. Our value is just {}, an empty object.
    • The callback builds up the object. It takes the object to be built up as the first parameter, and it returns a new value for that same object. The second parameter consists of the current pipeline element.
    • The general idea is to use each pipeline element to build up the object.

Functional is fun! And JavaScript is deep!

Thanks to  Kos on StackOverflow for helping me with my basic command-line syntax issues.

Too Many Dependency Managers

Package managers and dependency managers are essentially the same thing : They both install software you need. If you want to load an application onto your computer, you need a package manager. If you are developing software and want to import some libraries, you need a dependency manager. Both do mostly the same thing. They install software for you, automatically find and download dependencies, update to the latest version with an easy command, and generally make managing software installation much easier.

I now have enough of these managers on my development machine that I am starting to become bewildered : bower, brew, npm, maven, gem, cocoapods, pkgutil, and maybe some that I have missed. Each of these differ in scope, purpose, and behavior. I run them all on the Mac OSX command line.

pkgutil is the built-in package manager for Mac OSX, and is responsible for installing the very operating system itself. If you happen to have a .pkg file (somewhat rare), you can use this utility to install it. You’re more likely to use this tool on the command line to see what Apple put on your computer. pkutil --pkgs will give you the complete list of packages installed on your computer by Apple through your OS or applications from the App Store. Pick a package name like Essentials and you can see what files were installed using pkgutil --files com.apple.pkg.Essentials. An even more power feature is the ability to tell which package a particular file belongs to. Try it with pkgutil --file-info /bin/ls.

Sidequest! Let’s see if I can figure out which package manager I used to install NodeJS on my computer! pkgutil --file-info /usr/local/bin/node tells me… it was not installed using pkgutil. Well, the prefix /usr/local should have been a clue. Homebrew puts its installations there, as do other package managers.

Homebrew and MacPorts are package managers backed by a central database containing thousands of apps. Homebrew has a sexier web page, so I use it. I heard that it is implemented on top of git, and git rocks my world. Putting an application like NodeJS on your system with Homebrew is as simple as typing brew install node. You can upgrade all of your applications using brew upgrade, or view a list of all installed apps using brew list. You could also see them in /usr/local/Cellar. Brew uses beer puns like that. To a fault.

Homebrew can be installed using ruby, which, like gem, is installed on Mac OSX in the package Essentials.  Speaking of gem: gem is used to install ruby programs. You can use gem list to see a list of all installed packages, or gem list --remote to see a list of all available packages.

And it seems like neither gem, brew, nor pkgutil were used to install my local version of node. Hmm…

When using the package manager npm, it is important to distinguish between global and local installations. A global installation acts like a package manager for system commands, while a local installation acts like a dependency manager for development projects. Several other dependency managers have this split between global and local mode, including bower.

A local npm installation starts with npm init, which creates the package.json file used to track dependencies between frameworks. npm install fontawesome -save will create a node_modules folder containing fontawesome and all dependencies and update the package.json file. Additionally, npm will save the raw package files in your home folder under .npm as a kind of local cache to speed retrieval if you decide to use the same library for another project. This tutorial shows how to install the build tool Gulp using this method.

Global npm installations are intended for system commands, and they are really very different from dependency frameworks. Most npm commands can be followed with -g to make them global installations. npm install bower -g will install bower in /usr/local using subfolders and soft links. In more detail :

?? cd /usr/local/lib/node_modules/bower/

?? ls

CHANGELOG.md README.md lib

LICENSE bin package.json

?? cd /usr/local/bin

?? ls -l bower

bower -> ../lib/node_modules/bower/bin/bower

Bower is a package manager aimed at web development. It is actually built on top of node and npm, so we need those before installing bower. It seems redundant in purpose to npm, but it adds features. Look at a typical bower installation command :

?  ? bower install jquery
bower not-cached    https://github.com/jquery/jquery-dist.git#*
bower resolve       https://github.com/jquery/jquery-dist.git#*
bower checkout      jquery#3.1.0
bower resolved      https://github.com/jquery/jquery-dist.git#3.1.0
bower install       jquery#3.1.0

jquery#3.1.0 bower_components/jquery

Notice how verbose and clear everything is? However, bower does not handle nested dependencies (frameworks that require other frameworks), so that is something that must be handled by manually by the developer.

OK, I have no idea where my /usr/local/bin/node came from, but it’s time to update! brew install node followed by brew link --overwrite node brings node under my management umbrella, and now everything is up to date. Yay!

I’m going to save CocoaPods for another post.

 

Deep or Wide (Job Interview Preparation)

I had the pleasure of a going through a couple of job interviews in the past month. I was pleased with my performance on both. They were pleased with my performance on at least one.

Both companies are cool tech firms, but the interviews were very different.


Wide Company

Wide Company wanted to know if I was a real, modern software developer. This means that they wanted to know about my knowledge of tools and techniques, and my understanding of the principles of modern software architecture. They belted out a series of short-answer questions that sounded something like this:

  • What is a design pattern? (A well-structured solution to a common software problem. Most of the time means creating an interface where you weren’t planning to use one.)
  • Can you name a design pattern? (Sure – me laughing – Singleton)
  • OK, what’s a Singleton? (OK, here is where I expressed regret at not naming Decorator or Composite, since those are more interesting. But a Singleton is a pattern – or antipattern if you don’t like it – that only allows one instance through a factory method. It accurately models resources such as the operating system in some instances.)
  • How familiar are you with JavaScript? (Pretty good. I know what variable hoisting is.)
  • How familiar are you with Java? (Pretty darned good. I can solve problems using Java in job interviews.)
  • Have you ever used git? (I deploy my web sites using git and use it extensively at work, independent of our official VCS.)
  • Do you know about AngularJS? (Well, I know it is an app framework, something resembling MVC. I don’t really know it right now.)
  • Have you ever deployed anything to the cloud? (Well, not really.)
  • What is a Lambda expression? (Roughly an anonymous function that may or may not capture some lexical scope. If it does capture variable values in this way, it can be called a closure.)
  • What is dependency injection? (Also called inversion of dependency, it’s when you decouple a class from a class it uses by having the latter conform to an interface and having the object specified at run time rather than instantiating it directly. The Spring framework automates this pattern.)

There were more, but I have forgotten them. Or perhaps blocked out the painful memories…


Deep Company

Deep Company wanted to know how I solve problems using algorithms, data structures, and software.

They sent me a shared document and asked me to type solutions that they reviewed live during the interview. They gave me programming problems, and I chose to solve the problems in Java. In this interview, the questions resembled exam problems from a university course, and they asked me not to reveal any questions outside of the interview. So I won’t! Instead, I’ll make up problems of similar difficulty :

  • Suppose you have two circular linked lists. Write a method that tells me if the two lists are equal. The signature might look like this :

boolean areEqual (Node a, Node b)

Now this is the point where you are supposed to ask questions, which I did. But I tried to provide my own answers where I could.

  1. Can I assume Node has fields Node.next, and Node.value?
  2. Are the passed nodes “head”, “tail”, or neither? A: Neither. There is no head or tail, and elements do not have a position index. It does not follow the traditional list API.
  3. Are the lists considered equal if the contain the same values in any orientation, regardless of whether a and b point to the same location in those lists?
  4. Can the nodes be null? Are there any one-element lists?
  5. And so on…

If you take the restriction that the nodes passed are supposed to be equal, and every element value matches at every position going around the list, then this problem can be solved by iterating around the list and checking each value for a match, and stopping when you reach the first node again. I wrote my answer mostly ignoring null edge cases at first,

  • Now write the same method, but without the assumption that the passed node positions have to match. Now a and b represent any arbitrary node in the circular list, but I want equals to be true if either list matches the other where you are allowed to start at any position.

Here I actually wrote down sample data structure instances as an example, and asked if they would be considered equal or not.

            a        b
            |        |
            v        v
Apple -> Banana -> Cherry ---
  ^                         |
  |--------------------------

I hope that you understand my ASCII art. I may need to work on my posting skills. Please comment if you have a cool tool for drawing data structures in WordPress or HTML.

And, yes, those two structures are supposed to return true for equality.

Now the problem becomes harder, but is still doable. You can brute-force the solution with a two-level loop, one rotate the starting position until the starting elements match in value, another to check each position for equality after that.

  • Can you optimize your solution?

Optimization depends on the use cases. An optimization for one case makes other cases run slower.

Suppose the lists contain lots of repeat values. If that is true, then keeping a count of the number of occurrences of each value in a hash table would allow you to short-circuit the method and return false right away if the lists do not contain the same content counts. But if the counts match, you must continue and check their structure to make sure that matches as well.


So, to the future : I am preparing for more interviews. But which way? Deep or wide?

Do I write some sample codes in Spring, AngularJS, and EJB 3.0?

Or do I solve algorithm puzzles and then optimize them?

I’ll do a little of both.

Wish me luck!

How did my HEAD get detached?

I would not have started this blog if I was afraid to look stupid in public. Here is my latest attempt:

http://stackoverflow.com/questions/38437946/how-can-a-one-entry-git-repo-be-in-detached-head-status

OpenGL 16 Years Ago

A funny thing happened this morning. I found my Masters Thesis online! It was in the ProQuest Dissertations and Theses Global database. I have uploaded it to ResearchGate.net.

At the time, OpenGL was the cross-platform 3D platform of choice. That’s still true, although OpenGL has changed and evolved a great deal!

JavaScript Promise

I was mildly surprised to learn that the Promise class has been built-in to JavaScript. I was trying to fully grok the functional library Bacon when I ran into the JavaScript documentation for Promise. A Promise looks like this :

var p = new Promise( /* executor */ function(resolve, reject) { ... } );

A Promise can be in one of three states at all times : Pending, Fulfilled, or Rejected. This is actually not a new idea. Ever play with Java Scanner? Its hasNext() method returns a boolean indicating the presence of another token on the data stream. But one must understand that some streams, such as network packet streams, may postpone answering while waiting for a slow client. Thus, hasNext() returns true if another packet of data has been received, false if the client has disconnected, and simply blocks (does not return) if the network client is being quiet. This corresponds to Fulfilled, Rejected, and Pending. A Promise is much more explicit.

The Promise constructor calls function before anything else. function is expected to spawn asynchronous work but not call resolve or reject immediately. is created only after function has returned. Once the asynchronous work completes, function will call resolve or reject, which notifies the Promise object of the new state.

Here is an example that fetches tweets from twitter using a Promise to handle the asynchronous call.

var http = require('http')

url = 'http://maps.googleapis.com/maps/api/geocode/json?address=New York, NY, U.S.A' 

//url = 'http://maps.googleapis.com/maps/api/geocode/json?address=Mungalatoid'

var p = new Promise((resolve, reject) => {
	console.log("Kicking off an HTTP request")
	// kicks off an asynchronous HTTP request
	http.get(url, (response) => {
		var data = ''
		console.log('HTTP response received')
		response.on('data', (buffer) => {data += buffer})
		response.on('end', () => {
			var twitterObject = JSON.parse(data)
			if (twitterObject.status == 'ZERO_RESULTS') {
				reject(data)
			} else {
				resolve(data) 
			}
		})
		response.on('error', () => {reject('HTTP Error')})
	})
	console.log("HTTP request has been made")
})

console.log("Evaluating Promise")
p.then(
	(resolvedValue) => {console.log("Promise resolved " + resolvedValue)}
).catch(
	(failureReason) => {console.log("Promise rejected " + failureReason)}
)

Try changing between the URLs to see what happens when Google cannot find a match for the place name. Notice that Evaluating Promise is printed before the http.get callback function is called.

Mind you, this whole thing is much simpler just using node’s fetch, which actually returns a promise given a URL.

Web deployment is a small part of a big picture

I was listening to an episode of PHP Rountable (Thumbs Up, guys!) and I learned a bit about web and app deployment.

The Wikipedia entry for DevOps lists several of the latest cool tools. I’ve been hearing a lot about these:

  • Docker (containerization) : Docker uses Linux isolation tools – similar idea to virtualization, but with a less-complete illusion of independent resources – to allow applications to run independently in a consistent environment. Essentially, you install Docker and use it to run the app that you really want to run. It is a kind of application wrapper. The goal is to deploy your application along with its environment so that it runs consistently everywhere. It is written in Go and is open source.
  • Jenkins (continuous integration) : Jenkins lets you run your applications in a servlet container on a traditional Apache web/app server. A servlet container manages the lifecycle of a servlet, while the servlet itself responds to web requests and maintains state and cookies and such. Jenkins ties into this ecosystem by reconfiguring or restarting server components and running test suites as commits are made to source code repositories. It is written in Java and is open source.
  • Puppet (infrastructure as code) : Puppet allows you to declaratively assemble configuration data about your server and code dependencies in a kind of object-oriented way. Tool installations, libraries, frameworks, and server instances can all be described by rules you created, and puppet will take care of assembling these within a Linux virtual server (VSP). Puppet actually works on several platforms, is written in Ruby, and is open source.
  • Vagrant (virtualization platform) : Vagrant is a wrapper for VirtualBox, VMWare, and for isolation tools such as Linux containers. It is similar to Docker in that it manages a configured server within a server. Vagrant is written in Ruby and is open source.

There are Docker MeetUps in southern Virginia.

I recently needed to update a web site on an already-established server, so I did not have my familiar dev loop set up. SSH was unavailable, so I made use of git-ftp. It works very smoothly; I recommend it if you can’t ssh to your web server!

Objective-C for fun and (some day) profit

It’s not much to look at, but I am in the process of moving all of my Objective-C, C, C++, Java, and JavaScript toy boxes over to Github. A toy box is what I call a workspace filled with unrelated, incoherent mini-programs that demonstrate language features. The goal here is to understand syntax, semantics, and language behavior.

One of my favorite features of Objective-C is that sending a message to nil (IE calling a method on a null reference in any other language) has the following effect:

It does nothing!

This allows for some elegant code. Algorithms look bloated when they check for null values and other edge cases. Consider binary tree traversal. The basic algorithm of an inorder search is :

Search : Tree
Search : Left Subtree if not null
Print Root Node Value
Search : Right Subtree if not null

Wouldn’t it be nice if we didn’t need to check for nil/null? In Objective-C, it is! Check this out :

@interface BT: NSObject {
        @public
        int val;
        BT *left;
        BT *right;
}
- (void) inOrder;

@end

@implementation BT
- (void) inOrder {
        [left inOrder];
        printf("%d\n",val);
        [right inOrder];
}
@end

Isn’t that cool??? The full code is available on Github.

Swift is up to version 3, but I still see Objective-C everywhere. I think Objective-C still a useful language to know.