Some Node in my life

I’m a big time Rails fanboy, but I decided I needed some Node.js in my life. I wrote a little file uploader and the upload speed and the small number of lines written blew my mind.

//require libraries
var fs = require('fs');
var http = require('http');

http.createServer(function(request, response) {
  //create file we write data to
  var newFile = fs.createWriteStream("newfile.pdf");

  //get file size and initialize vars
  var fileBytes = request.headers['content-length'];
  var uploadedBytes = 0;
  var uploadStartTime = new Date();

  //while request is still readable respond back
  //with the upload percentage
  request.on('readable', function() {
    var chunk = null;
    while (null !== (chunk = request.read())) {
      uploadedBytes += chunk.length;
      var progress = (uploadedBytes / fileBytes) * 100;
      response.write("progress: " + parseInt(progress, 10) + "%\n");

    }
  });

  //transmitting file upload to dump file
  request.pipe(newFile);

  //send final message once file upload complete
  request.on('end', function() {
    var uploadStopTime = new Date();
    var timeElapsed = (uploadStopTime - uploadStartTime) / 1000;
    response.write('----------\n');
    response.write(timeElapsed + ' seconds elapsed' + '\n');
    response.end('File Uploaded!\n' + '----------');
  });
}).listen(3000);

Uploading a 12 MB file.

curl --upload-file ~/Downloads/twelve-mb-file.pdf http://localhost:3000
progress: 0%
progress: 1%
progress: 1%
progress: 2%
progress: 2%
progress: 3%
progress: 3%
progress: 4%
progress: 4%
...
...
progress: 96%
progress: 97%
progress: 97%
progress: 98%
progress: 98%
progress: 99%
progress: 99%
progress: 100%
----------
0.053 seconds elapsed
File Uploaded!
----------

It reminds me of when I went to college and started using a T1 internet connection instead of the 14.4k modem we were using at home. My roommate downloaded a 5 MB file online and we figured we would go to the dining hall and eat while the file downloaded. To our absolute shock and amazement the file downloaded in about 20 seconds. Our minds were completely blown.

Deploying a Rails App to Heroku — PostgreSQL

This is a tutorial I put together for some of my students…

Before beginning please have your Heroku password/login handy. You’ll need them to login to Heroku via the website and via the CLI.

* Create a new rails app. From Command line


rails new pg-test-app --database=postgresql
$ cd pg-test-app
$ rake db:create

* Add the following lines to your Gemfile and then run bundle install.

ruby '2.1.3'
gem 'rails_12factor', group: :production

* Generate a scaffold named “Post”. In the migration created by the scaffold create a column named “title”

#from command line
$ rails g scaffold Post

------
#in the generated migration file

  def change
    create_table :posts do |t|
      t.string :title
      t.timestamps null: false
    end
  end
  
  -------
#from command line
  rake db:migrate

* Create a seed file

#seeds.rb

Post.create(title:'Post 1')
Post.create(title:'Post 2')
Post.create(title:'Post 3')
Post.create(title:'Post 4')
Post.create(title:'Post 5')

------

#from command line
rake db:seed

* Start your rails server and verify that your app is working

* Go to http://www.heroku.com and create a new empty app. After creating the app a list of deployment instructions should appear similar to what you find on Github when you create an empty repo.

*If you’re not already logged into Heroku via the command line:

$ heroku login
#enter your credentials

*From command line:

$ git init
$ heroku git:remote -a YOURHEROKUAPPNAME
$ git add -A
$ git commit -m 'push to heroku'
$ git push heroku master
$ heroku run rake db:migrate
$ heroku run rake db:seed

Winter Break

It’s been a crazy 6 weeks. I got a new job and it’s out in Santa Monica which is about a 1.5 – 2 hour commute each way. Not really a lot of time for personal side projects or to eloquently opine on the current state of web development.

The POSITIVE to spending 4 hours in the car commuting each day is that I work with some WONDERFUL and KNOWLEDGEABLE developers that are more than happy to SHARE their experience and knowledge with me.

I’m off work for the next two weeks so I’ll be working on some side projects that I hope to share here than involve AngularJS, Rails and MongoDB.

New mini project — Downloading Wallpaper

I wrote a script to parse Reddit’s API for images in the “r/earthporn” subreddit. It downloads the pictures to my local machine, which I will then randomly serve as wallpapers for my laptop.

One hurdle I came across involved submissions from the “flickr.com” domain. The submitter was not linking the image directly, but linking to the album the picture was in. This obviously led to the actual picture not being downloaded. I just added a check to ensure that “jpg” or “jpeg” were included in the URL, otherwise it won’t save to file.


class GetEarthPorn
require ‘rubygems’
require ‘httparty’
require ‘net/http’
require ‘open-uri’

include HTTParty

attr_reader :picture_array

def initialize
@picture_array = [] #this will hold the URL of each submission
end

def get_pics
#navigate thru API to get URL from each submission
#if the URL doesn’t contain ‘jpg’ or ‘jpeg’ it won’t be saved to array
server_response = get(“http://www.reddit.com/r/EarthPorn/.json?limit=10”)[‘data’][‘children’]
server_response.each do |image|
if image[“data”][“url”].include?(“jpg”) || image[“data”][“url”].include?(“jpeg”)
@picture_array << image["data"]["url"] end end p @picture_array p "*********************" end def save_to_disk @picture_array.each do |image| file = open(image) file_name_to_save = image.split('/').last open(file_name_to_save,'w') do |file| open(image){|picture| file.write(picture.read)} end end end private def get *args, &block response = self.class.get *args, &block raise WebserverError, response.code unless response.code == 200 response end end e = GetEarthPorn.new e.get_pics e.save_to_disk [/ruby]

Count and Group Character Occurrences in a String

Oooh, this was a fun one…

Count and Group Character Occurrences in a String

Write a method that takes a string as an argument and groups the number of time each character appears in the string as a hash sorted by the highest number of occurrences.

The characters should be sorted alphabetically e.g:

get_char_count("cba") => {1=>["a", "b", "c"]}

I’ve been doing Javascript all day and using Ruby feels like driving a luxury automobile…

A Greater Responsibility

responsibilitya moral obligation to behave correctly toward or in respect of.

I really believe that in any endeavor, especially in coding, that as your skill increases you have a responsibility to not only give credit to those who mentored you, but also to mentor those coming up behind you.

In the United States we live in a very consumer-oriented society, and I think this breeds a mindset of take-take-take with very little give-give-give. I can get in my car and drive 5 minutes in any direction and buy any medicine, any piece of furniture, any type of car service, etc. If you have the money you can buy your way out of pretty much anything, and self-reliance is really not encouraged.

I have experience mentoring entry-level people from an old job and I also have kids, so I’m well aware of the time commitment and patience needed to be an effective mentor. The best part about being a mentor, and a dad, is that it forces you to rethink how you see the world, your place in it, and what type of legacy you want left.

  • Do you want to be known as someone who only does the bare minimum required, or someone who goes above and beyond?
  • Do you like to take shortcuts, or are you thorough?
  • When you have internal self-dialogue, is it positive or negative?
  • When people ask you for help are you willing and welcoming, or do you roll your eyes and sigh?

Every time you come into contact with someone more junior than you you have the opportunity to make an impression on them and affect the trajectory of their life and career. Like Spiderman’s uncle said, “With great power comes great responsibility”.

Computer Science Fundamentals

While Googling I came across a thread on Quora where programmers were discussing the biggest difference between developers with a traditional Computer Science background and non-traditional “self-taught” programmers. The consensus went something like this:

  • New CS graduate: Intermediate in CS, weak in coding
  • Self-taught: Weak in CS, Intermediate in coding

I come across a lot of job listings and a B.S. in Computer Science is number one on the list of requirements. Now, I’d advise any self-taught programmer to just go ahead and ignore that requirement and submit your resume anyway if you feel confident in your programming skills. The problem you’re going to run into is when you get a technical interview and they start asking you questions about CS that new CS grads would be extremely likely to know: Data structures, Big O notation, compilers/interpreters, etc.

Most of my recent posts have been code oriented and I’m going to continue the trend. This coming week I’m going to do a “mega-refresher” on CS, probably focusing on sorts, searches and Big O notation.

Basic Stack and Queue

Stack

class Stack

  def initialize
    @stack = []
  end

  def push(*element)
    @stack.push(element)
    @stack.flatten!
  end

  def pop
    @stack.pop
    @stack
  end

  def peek
    @stack.last
  end

  def size
    @stack.length
  end
end

s = Stack.new
s.push(1,2,3,4,5) #=>[1, 2, 3, 4, 5]
s.push([6,7,8],[9,[10]]) #=>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s.pop #=>[1, 2, 3, 4, 5, 6, 7, 8, 9]
s.peek #=> 9
s.size #=> 9

Queue

class Queue
  def initialize
    @queue = []
  end

  def enqueue(*elements)
    @queue.unshift(elements)
    @queue.flatten!
  end

  def dequeue
    @queue.pop
    @queue
  end

  def peek
    @queue.last
  end

  def size
    @queue.size
  end
end

q = Queue.new
q.enqueue(1,2,3,4,5) #=>[1, 2, 3, 4, 5]
q.enqueue("hello!") #["hello!", 1, 2, 3, 4, 5]
q.enqueue([6,7,8],[9,[10]]) #=>[6, 7, 8, 9, 10, "hello!", 1, 2, 3, 4, 5]
q.dequeue #=>[6, 7, 8, 9, 10, "hello!", 1, 2, 3, 4]
q.peek #=> 4
q.size #=> 10