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

How to subscribe to a subreddit using Snoo

This post piggybacks on my prior post where I wrote about the difficulty I was having interfacing with Reddit’s API. That problem has now been solved.

Relevant Links

The subscribe method in Snoo’s master repo is unfortunately outdated and will return in a 404 error.


def subscribe subreddit, action = "sub"
  logged_in?
  post('/api/subscribe', body: {action: action, sr: subreddit, uh: @modhash, api_type: 'json'})
end

The reason it returns a 404 error is because the API now requires you to pass the subreddit’s formatted id instead of it’s name. Where do you get this formatted id? Let’s use the r/nba subreddit for our example.

Navigate your browser to http://www.reddit.com/r/nba/about.json. Below is the relevant excerpt.

{

    "kind": "t5",
    "data": {
        "submit_text_html": null,
        "user_is_banned": false,
        "id": "2qo4s",
        "submit_text": "",
        "display_name": "nba",
...
...
}

Per the API docs the formatted id should be “kind” + _ + “id”, which would be “t5_2q04s”. This is what needs to be passed as the subreddit name, not “r/nba”.

Let’s start rewriting the method:


def subscribe(subreddit)
  subreddit_json = self.subreddit_info(subreddit)
  subreddit_id = subreddit_json['kind'] + "_" + subreddit_json['data']['id']
end

In Snoo there is a method named #subreddit_info located in subreddits.rb. It returns the json hash that you saw earlier when you visited http://www.reddit.com/r/nba/about.json. The subreddit_id variable builds the “t5_2q04s” formatted id.


def subscribe(subreddit)
  ...
  ...
  server_response = self.class.post('/api/subscribe.json',
    body:{uh:@modhash, action:'sub', sr: subreddit_id, api_type:'json'})
end

The server_response variable will contain the response from Reddit’s server after we send the request. The self.class.post method comes from the HTTParty gem that is bundled with Snoo. The first parameter is the URL we want to send the post request to. The second parameter is the body of our post request. For what exactly needs to be sent in the body you can see this specific entry in the API docs.

And finally let’s bring it all together with the final method:


def subscribe(subreddit)
  subreddit_json = self.subreddit_info(subreddit)
  subreddit_id = subreddit_json['kind'] + "_" + subreddit_json['data']['id']
  server_response = self.class.post('/api/subscribe.json',
    body:{uh:@modhash, action:'sub', sr: subreddit_id, api_type:'json'})
  return "Successfully subscribed to r/#{subreddit}" if server_response.code == 200
  return "Error code: #{server_response.code}" unless server_response == 200
end

You get notified either way if the request was successful or not. If the request was unsuccessful you are notified of the HTTP error code.

I hope this helps!

Trying to get a Reddit Bot up and running

I browse Reddit a lot and I thought it would be good programming practice to try and automate some of the more frequent tasks I do, namely searching for “Kobe Bryant” in the r/nba subreddit.

My first instinct was to write a bot from scratch, but writing a bot really isn’t my goal. My goal is to get a bot to do my searching for me. Writing an entire bot from scratch to accomplish one task seems like a case of “reinventing the wheel”, especially when there are tried-and-tested bots that exist.

I did some searching and found a stable bot framework called Snoo that is written in Ruby. It’s not as feature-rich as PRAW, which is written in Python, but it does the job and the code is easy to understand.

I can login fine. I can get my account settings fine. The problem comes when I try to add functionality. The problem isn’t with the bot itself, but with trying to interface with Reddit’s API.

My first task was to add a method to subscribe to a forum.

def subscribe(subreddit)
	logged_in?
	HTTParty.post('http://www.reddit.com/api/subscribe.json',body:{uh: @modhash, action:'sub', sr: subreddit, api_type: 'json'})
end

Instead of success I get this response back

pry(main)> reddit.subscribe('/r/nba')
=> {"json"=>{"errors"=>[["USER_REQUIRED", "please login to do that", nil]]}}

It was suggested that I try passing my session cookie or my user name and I’ve tried those and no success…YET. So until then I’ll keep on pushing…