Pythagorean Triplet Finder in Ruby

A Pythagorean Triplet is a set of three numbers, a, b, c that satisfy this condition.

a^2+b^2=c^2

For example, 3, 4, and 5 make up a Pythagorean Triplet.

Now the question is, can we create program that find all pairs of numbers that create Pythagorean Triplets with a given number?

Check out my solution here.

While the both method works fine, the second method utilizes Triangular inequality. This omits extra looping that's unnecessary and saves tons of run time.

When n was 10000, method 1 took 8.720612 seconds and method 2 took 5.516031 seconds. Method 2 is 58.1% faster than method 1.

Using Heroku Scheduler for Rails 3.1.3

Heroku recently launched Scheduler that is more advanced than the previously scheduled task runner, Cron. Unlike Cron, Schduler can run on hourly basis for "free", though Heroku charges for the amount of time you ran Schduler. Previously pricing model for Cron was rather ridiculous. Heroku was charging something like $3/month for simply installing Cron running on hourly basis. 

Installing Scheduler is super easy. Just follow the documentation on Heroku website. However, here are some odd quarks to keep in while you install Scheduler on your Rails app.

1. The name of the task on Heroku Scheduler page must equal the name declared in the scheduler.rake

2. undefined method `methodname' for #<memory location> Error
I was getting this error, when I was running something along the line of User.send_reminders in my scheduler. This was problematic because I did not have my method in User class of User model. Instead send_reminders method in my case was found in UsersController class. So here's what I did instead.

users_controller = UsersController.new
users_controller.send_reminders

GoodCount Shows a Breakdown of Presidential Candidate Coverage by Major News Websites

What does GoodCount do?

GoodCount keeps track of presidential candidate coverage done by major news websites such as cnn.com and foxnews.com. GoodCount counts the number of times candidates' names have been mentioned on daily basis.

Motivation behind GoodCount

Have you ever wondered how much coverage different presidential candidates get? I noticed that certain candidates get disproportionate amount of coverage by mainstream media than others. On the one hand, this should come as no surprise. No one expects say, Marxist-Leninist Party should get the same amount of coverage as Democratic Party. However, the question becomes more complicated when we are dealing with presidential candidates running for the party nomination.

Republican-candidates-nh-debate

Ron Paul supporters have been at the forefront of challenging mainstream media to give Ron Paul a fair share of news coverage since 2008 election. Now 2011 is ending and the same disgruntled attitude still remains relatively unchanged. I wanted to find out whether if this attitude was justified by evidence.

What GoodCount doesn't do?

  • GoodCount does not keep track of TV, paper and radio coverage of candidates.
  • Number of candidate coverages are not normalized. For example, one instance of Obama on NY Times is treated the same as one instance of Obama on LA Times even though NY Times has a larger readership than LA Times.
  • GoodCount cannot distinguish between negative and positive coverage of candidates. Remember when almost all media coverage on Obama was negative hit pieces on the topic of Jeromiah Wright and birth certificate during 2008 election? GoodCount is agnostic about the attitude of the coverage.

Some technical challenges GoodCount face

  • Some candidate names are mentione through Twitter feeds, but GoodCount can't detect them.
  • I would love to get GoodCount to perform even a rudimentary sentimental analysis of articles.

---

I have some exciting plans for this project. If you find the project interesting, please share it with others around you. Also let me know of features you'd like to see from the project. 

Deploying Ruby on Rails 3.1 Application to Heroku (dealing with some common errors)

Deploying Ruby on Rails 3.1 application to Heroku was not actually as straight forward as Heroku made it out to be. I had great experience with Heroku with Rails 2.x and Rails 3.0, but with Rails 3.1, I had to perform several extra steps in order to deploy successfully.

1. Using postgresql on Heroku production environment, while using sqlite or mysql in development environment

If my memory serves correctly, I'm pretty sure Heroku used to be able to perform rake db:migrate, even when the development database uses sqlite or mysql without extra configuration in Gemfile. This is not the case for Rails 3.1. Typically, deploying Heroku follows these steps.
$ heroku create
$ git push heroku master
$ heroku rake db:migrate

However, if you run the third step without Gemfile modification, you get this error.

$ heroku rake db:migrate
      rake aborted!
      Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.)

      Tasks: TOP => db:migrate => db:load_config
      (See full trace by running task with --trace)

Solution: Gem Install 'pg'

  1. Open your Gemfile
  2. Modify Gemfile this way
    group :production do
            gem 'pg'
          end
          group :development, :test do
            gem 'sqlite3' 
          end
  3. Install the bundle locally for your development environment.
    $ bundle install --without production

After performing these steps, you see that you can migrate now. Make sure after you edit your Gemfile, you push the changes to Heroku.

$ heroku rake db:migrate
    Migrating to CreatePosts (20111206055855)
    ==  CreatePosts: migrating ====================================================
    -- create_table(:posts)
       -> 0.0189s
    ==  CreatePosts: migrated (0.0199s) ===========================================

"We're sorry, but something went wrong."

So your application is now live online, but something is obvious wrong with this. To check out where it went wrong, perform this command.
$ heroku logs
The result will be something like the following.

2011-12-06T06:54:48+00:00 app[web.1]: Completed 500 Internal Server Error in 148ms
      2011-12-06T06:54:48+00:00 app[web.1]: 
      2011-12-06T06:54:48+00:00 app[web.1]: ActionView::Template::Error (application.css isn't precompiled):

This is caused by asset pipeline being disabled by default in Rails 3.1.

Solution: Enable asset pipeline compiling

  1. Open config/environments/production.rb
  2. Find this line: config.assets.compile = false
  3. Change the false to true. config.assets.compile = true

Something is still wrong with javascript runtime?

Solution: gem 'therubyracer'

  1. In Gemfile, put gem 'therubyracer' in the production group

Is there concept of "since" in any programming language?

We see this in programming all the time. if condition result end

On the other hand, I'm not sure if since statements are used in programming. since result some cause end

I understand that since a result can be written in if condition because since statements themselves are conditional statemetns. However, in dealing with problems, we sometimes do observe the end result without knowing why that result was caused.

For example, in politics, politicians know their approximate popularity, but calculating which issues affect how much of popularity is a different problem all together. Such an event could be programmed like this.
since approximate popularity politician popularity = economy * x + foreign policy * y + health care * z + ... end

These applications are countless in the world. In the past, computers were not powerful enough to calculate any problem of this magnitude. They first were not being able to find out about the result such as an approximate popularity of politicians accurately. This isn't the case at all today. Google Trends is a great way to find out popular topics of the day that involves massive computing of counting several hundred millions of queries per day

So couldn't there be a compiler that automatically understand since syntax?

Using build method in has_one and has_many associations for Ruby on Rails

I learned using build method the hard way yesterday. I did not know that there is a subtle difference in way you use build method for has_one association and has_many association in Ruby on Rails. Say we have two associations like these.

  1. Human has_one head
  2. Human has_many fingers

Say we already have belongs_to statement for both head and fingers. For the first case, human has_one head assoication, you instantiate a head by the following statement.
@human.build_head

For the second case with has_many association, you instantiate finders by doing this.
@human.fingers.build

This is also confirmed by A Guide to Active Record Associations.

When initializing a new has_one or belongs_to association you must use the build_ prefix to build the association, rather than the association.build method that would be used for has_many or has_and_belongs_to_many associations. To create one, use the create_ prefix.

Back up and Restore MySQL database for Wordpress

Whether you are switching your web host or changing a Wordpress theme, backing up your MySQL database regularly is always a good practise.

To back up Wordpress on localhost,
$ mysql -u username -p password -h localhost databasename > databasebackup.sql

To back up database at remote host, you need to make sure that you know ip address of the host, database username, password of your host database, ssh access. All these information should be provided by your host. If you can't find them, contact them directly. The command to back up database at remote host is,
mysql -u username -p password -h 123.123.456.456 databasename > databasebackup.sql

To restore your database using the backup file,
mysqldump -u username -p password databasename > databasebackup.sql


The above commands were tested on MySQL version:
Ver 14.14 Distrib 5.1.54, for debian-linux-gnu (i686)

References:
[1] Import MySQL dumpfile, SQL datafile into my database
[2] Backing Up and Restoring Your MySQL Database

Install Scala 2.9.1 on Ubuntu 11.04!

Scala_logo
I have been meaning to try out Scala for some time. I came across Scala when Wired reported that Twitter was replacing much of Ruby code in the server side with Scala, Scala is definately gaining more traction thanks to notable players such as Foursquare, LinkedIn and Novell announcing that they use Scala. First thing's first. We should install Scala on the computer.

As of November 3, 2011, the latest stable build is Scala 2.9.1. We will install this version of Scala.

wget http://www.scala-lang.org/downloads/distrib/files/scala-2.9.1.final-installer.jar
sudo java -jar scala-2.9.1.final-installer.jar

The default location of installation is /usr/local/scala, so after installaion, set PATH like this.

PATH="$PATH:/usr/local/scala/bin"

To permanently include Scala into your PATH, open .bashrc in your /home/yourname directory and add this line.

export PATH=/path/to/dir:$PATH

You are ready to use Scala commands!

scala -version
Scala code runner version 2.9.1.final -- Copyright 2002-2011, LAMP/EPFL

If you see that result, you have installed Scala on Ubuntu 11.04 successfully.

Running RSpec

RSpec is a Behaviour-Driven Development tool for Ruby programmers. BDD is an approach to software development that combines Test-Driven Development, Domain Driven Design, and Acceptance Test-Driven Planning. RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD. (RSpec Documentation)

When you create a new Rails app, put -T at the end of the command like this

>> rails new sample_app -T

Install rspec

>> gem install rspec-rails

Install bundle

>> bundle install

Install files needed by Rails to run rspec

>> rails generate rspec:install

To run the rspec

>> bundle exec rspec spec/

MVC action in Ruby on Rails

Ruby on Rails is a framework that conforms to Model-View-Controller (MVC) pattern.

Here is a scenario of what happens in Ruby on Rails application, when a user visits the user index page at /users explained by Michael Hartl in Ruby on Rails Tutorial: Learn Rails by Example.

Mvc_detailed-full

  1. The browser issues a request for the /users URL.
  2. Rails routes /users to the index action in the Users controller.
  3. The index action asks the User model to retrieve all users (User.all).
  4. The User model pulls all the users from the database.
  5. The User model returns the list of users to the controller.
  6. The controller captures the users in the @users variable, which is passed to the index view.
  7. The view uses Embedded Ruby to render the page as HTML.
  8. The controller passes the HTML back to the browser.