CategoryResources

Things You Need

Sieve of Eratosthenes Visualized in Real Time with Python

Spoiler Alert! This article reveals the answer to Project Euler problem #10.


Try it!

A few months ago I worked through the first 10 problems of Project Euler. I did OK up to problem #10. The question involved finding all the prime numbers up to 2,000,001. There were earlier questions that involved finding primes, and I cobbled together some javascript with the help of underscore.js that got the job done – albiet very slowly. My homespun solution was just too durn slow for problem #10. I turned to the internet, and it provided me a blazing fast solution. See below.

var ten = function sieve(max) {
    var D = [],
        primes = [],
        sum = 0;
    for (var q=2; q < max; q++) {
    if (D[q]) {
      for (var i=0; i < D[q].length; i++) {
        var p = D[q][i];
               
        if (D[p+q])
           D[p+q].push(p);
        else
           D[p+q]=[p];
      }
      delete D[q];
    } else {
            sum += q;
      primes.push(q);
      if (q*q<max)
         D[q*q]=[q];
    }
  }
  return sum;
 }(2000001);

So yeah, I cheated. At the time, I had no idea how this code worked, I just knew that it did. Since then, I’ve occasionally revisited this code to take another shot at figuring out what this mysterious D array is doing with its Ps and Qs. However, trace after trace and many breakpoints later I was still scratching my head.

But just yesterday I stumbled across Python Tutor. This site is simply amazing. These geniuses have developed an interactive online code editor that spits out pictures based on what your code is doing. You even get little playhead controls to step through each line! This wizardry finally allowed me to scratch the itch that’s been bugging me for a while.

I returned to the site where I ‘borrowed’ the JavaScript algorithm for the Sieve of E., and found the Python equivalent. The syntax is a bit different, but it essentially doing the same thing. The code looks like this:

def eratosthenes(maxnum):
   D = {}  # map composite integers to primes witnessing their compositeness
   q = 2   # first integer to test for primality
   while q <= maxnum:
       if q not in D:
           yield q       # not marked composite, must be prime
           D[q*q] = [q]  # first multiple of q not already marked
       else:
           for p in D[q]:  # move each witness to its next multiple
               D.setdefault(p+q,[]).append(p)
           del D[q]        # no longer need D[q], free memory
       q += 1

for p in eratosthenes(19): print p

The comments were helpful in determining that it was doing the same thing as the JS algorithm, but when I plugged this code into Python Tutor, WHAMMO! It hit me like a ton of bricks. D is a dictionary!!! D is where non-prime numbers are stored and created from prime factors.

So we iterate over all the numbers from 1 to whatever, with q as the iterator index. For each value of q, check the dictionary (D). If that value does not exist in D, then the number is prime. For each prime number, find the square and store it in the dictionary for later. So when q = 2, the first entry in D is 4. Then when q = 3, stick 9 in the dictionary. Also, for each dictionary entry created by squaring a prime, attach that prime as a child object.

When q is not prime, examine the dictionary entry. Take the child, add it to the dictionary value, and create a new entry in the dictionary for the sum. So when q = 4, its child value is 2. Take 2 + 4 and get 6. Create a dictionary entry for 6, and store the original prime factor (2) as its child. Then delete the previous dictionary entry (4). Keep this up until q is larger than your target value (2000001).

This part took me the longest to figure out, and it makes a lot more sense by skipping the deletion part. In the Python Tutor example, comment out the line del D[q]. When running the visualizer, the dictionary keeps growing and it is much easier to see how each entry is created, and why each entry is composite rather than prime. For each square value, its root is added over and over again until q reaches its limit. Deleting dictionary entries is not absolutely necessary with low values of q. It’s a memory saver that keeps D from getting out of hand (and crashing Chrome when trying this in JavaScript).

I know I did a sub-par job of explaining this, but seriously, that’s what Python Tutor is for. Try it, you’ll like it.

Install Yeoman and all its dependencies in Ubuntu Linux

Yeoman is awesome, but holy jeez are there a lot of requirements to get it fired up for the first time. Listed below are all the commands I typed in to get every last Yeoman dependency installed. I did this on 64-bit Ubuntu. For 32-bit, you’ll need to download a different version of PhantomJS, but otherwise I’m pretty sure everything else works the same.

CURL

sudo apt-get update
sudo apt-get install curl

GIT

reference: http://evgeny-goldin.com/blog/3-ways-install-git-linux-ubuntu/

sudo apt-get install libcurl4-gnutls-dev libexpat1-dev gettext libz-dev libssl-dev
wget --no-check-certificate https://github.com/git/git/tarball/v1.7.12.2
tar -xvf v1.7.12.2
cd git-git-04043f4/
make prefix=/usr/local all
sudo make prefix=/usr/local install
git --version
rm -rRf git-git-04043f4
rm v1.7.12.2

NodeJS

reference: https://github.com/joyent/node/wiki/Installation

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs npm

RVM + Ruby 1.9.3

reference: http://ryanbigg.com/2010/12/ubuntu-ruby-rvm-rails-and-you/
You might want to grab a coffee. This is a long one.

sudo apt-get install build-essential
curl -L get.rvm.io | bash -s stable
echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"' >> ~/.bashrc
. ~/.bashrc
sudo apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion
rvm install 1.9.3
rvm use 1.9.3
rvm --default use 1.9.3-p194
ruby -v

Compass

reference: http://compass-style.org/install/

gem update --system
gem install compass

PhantomJS

Using apt-get will get you v. 1.4.0. The method below gets the latest version. For 32-bit, just remove ‘_64’ from each command.
reference: http://devblog.hedtek.com/2012/04/phantomjs-on-ubuntu.html

cd ~/
wget http://phantomjs.googlecode.com/files/phantomjs-1.7.0-linux-x86_64.tar.bz2
tar -xvf
cd /usr/local/share
sudo tar xvf ~/phantomjs-1.7.0-linux-x86_64.tar.bz2
sudo ln -s /usr/local/share/phantomjs-1.7.0-linux-x86_64/ /usr/local/share/phantomjs
sudo ln -s /usr/local/share/phantomjs/bin/phantomjs /usr/local/bin/phantomjs
phantomjs --version
rm ~/phantomjs-1.7.0-linux-x86_64.tar.bz2

JPEGTRAN / OptiPNG

sudo apt-get install libjpeg-turbo-progs
sudo apt-get install optipng

YEOMAN!!!

(finally!)

sudo npm install -g yo grunt-cli bower

And we’re done.

Angular Cats! An AngularJS Adventure Anthology

Over the past couple weeks I’ve been teaching myself about the AngularJS javascript framework. It’s gone pretty well so far, and I think I have a pretty decent handle on the basics. I’ve been able to use the tools provided to put together a small application that uses the Petfinder.com API as a backend. It is a remake of an old Flex application I built in 2009 for the House of Mews pet shelter in Memphis, TN. The application allows the user to browse pictures and information on all the adoptable cats currently at the shelter. See the application in context at www.houseofmews.com (and please excuse the background music). You can also view the app by itself here.

In addition to remaking the old app, I took the remodeling a few steps further in order to try out a few more AngularJS features. The newer version of application stands on its own and has a few added features – most notably, deep linking.

While working on this, I created a series of blog posts to chronicle my progress (and show off). There are five posts in total, with the first three focused on the ‘remake’ app, and the last two posts detailing parts of the ‘remodeled’ app. If you are interested in learning AngularJS for yourself, definitely pay attention to the latter posts. The first three posts are choc full of newbie mistakes and bad practices. They are a great example of how not to build an Angular application.

All of the code is available on GitHub. I’ve already tweaked the code a bit, so it may not match 1:1 with the code pasted into the blog posts, but everything is commented and should be relatively easy to follow. Anyway, thanks for paying attention! Enjoy!

Parts 1 – 3: House of Mews redux (source: ngCatsHOM)

Parts 4 & 5: Angular Cats! (source: ngCats)

AngularJS: ng-repeat, ng-hover, ng-click

So I’ve been diving into AngularJS lately, and am finding that it’s pretty awesome.  It feels more comfortable than backbone.js – most likely due to my Flex background.  I like the way ‘directives’ act similarly to Flex components, and two-way binding just works automagically.  Anyway, I’m converting my House of Mews Petfinder widget from Flex to Angular, and will post lots of code from that later.  But for now, here’s a tiny demo I threw together in jsFiddle. You can hover and click on list items, and stuff happens! (OK, so my real motivation for posting this was to test jsFiddle embedding. It works, and it’s sweet.)

profile for eterps at Stack Overflow, Q&A for professional and enthusiast programmersI’m a big fan of Stack Overflow and use it on nearly a daily basis for reference.  Once in a while I’ll post or answer a question. Recently, an answer of mine regarding responsive design in the context of Twitter Bootstrap has gotten a lot of attention.   Just for kicks, I’m cleaning up the conversation and posting the meat and potatoes here.

Here are some jsFiddles to demonstrate the difference between fluid only and fluid + responsive.

Fluid-only: http://jsfiddle.net/5JECu/

Fluid-responsive: http://jsfiddle.net/ZnEEa/

Fixed-only: http://jsfiddle.net/eterpstra/ZR4zz/3/

Fixed-responsive: http://jsfiddle.net/eterpstra/rdvaG/12/

In the fixed width layout, the columns change when the browser window reaches a width defined in a media query. So when you have your window greater than 960px wide, it will stay at it’s maximum width. Then when you shrink your browser to 959px, it will snap to a new layout based on a media query that has a maximum width of 768px. So because you are viewing a fixed-width layout, the columns will not change when your browser width is between 768 and 960. Wen you are viewing a fluid-width layout, the column sizes will always change to match your browser’s width. The layout itself will also change in accordance to the media queries, as with a fixed-width layout.

When you decide between fixed width and fluid width you need to think in terms of your ENTIRE page. Generally, you want to pick one or the other, but not both.  In other words, the Scoaffolding page is using a fixed-width layout. The  and  on the Scaffolding page are not meant to be examples, but rather the documentation for implementing fixed and fluid width layouts.  The proper fixed width example is . The proper fluid width example is .

When observing Twitter’s , you should not see the content changing sizes when your browser is greater than 960px wide. This is the maximum (fixed) width of the page. Media queries in a fixed-width design will designate the minimum widths for particular styles. You will see this in action when you shrink your browser window and see the layout snap to a different size. Conversely, the fluid-width layout will always stretch to fit your browser window, no matter how wide it gets. The media queries indicate when the styles change, but the width of containers are always a percentage of your browser window (rather than a fixed number of pixels).

The ‘responsive’ media queries are all ready to go. You just need to decide if you want to use a fixed width or fluid width layout for your page.

When creating rows, be sure to use 

row

 with a fixed width layout, and 

row-fluid

 with a fluid width. Do not mix and match (unless you have a very good reason to do this).

I can’t tell what the difference is between twitter bootstrap fluid responsive vs non-responsive though… (asked by original poster)

Open the fluid example and maximize your window. Observe how the navigation menu is a horizontal list. Now slowly reduce the width of your browser. At some point, the navigation bar will change so that a button appears, and when the button is clicked, the menu appears as vertical. So with fluid, the only thing that changes is the width of the elements. With a responsive design, you can change any css rule based on the width of the browser. See my edited answer for some jsFiddle examples.

 

Two koans and an Euler walk into a (foo) bar…

In order to suck less at Javascript, I went searching for some more practice problems in the same vein as the js-assessment project I completed a couple months ago.  Luckily, there is no shortage of instructional material on Javascript these days, and two enterprising individuals have taken it upon themselves to construct sets of Javascript koans.

The koan projects are set up as a series of failing unit tests – much like the js-assessment project.  The object of the activity is to open the test file, then fill in the blanks so all the tests pass.   I couldn’t decide which set of koans would be most beneficial, so I did both.  Practice makes perfect, right?

Javascript Koans Complete 2I tackled the set from mrdavidlaing first.  There are fewer test files, and it seemed to me at the time that the concepts were a bit more advanced.  I was right. The koans got right into fun ideas such as protypal inheritance, functional scope, and advanced array functions like map and reduce.  The inspiration for these koans are from Douglas Crockford‘s, Javscript: The Good Parts.  These koans are a nice set of exercises to complete if you are  coming to javascript from another programming language, or are a beginning javascript developer, but already know the basic programming concepts.

The koans by liammclennan were more numerous, but covered roughly the same topics as the other set, plus a few more of the basics.  This is definitely the way to go to brush up on javascript, or try out javascript as a beginner.  I didn’t get as tripped up with these exercises as I did with Mr. Laing’s, but perhaps it was because I did them second that I felt they were easier.  Either way, they were nice exercises and very worthwhile.

Finally, I really decided to test my mettle by signing into Project Euler and make an attempt at the first few problems in the ever-expanding set.  I’d heard a lot about this site, but never really looked into it until now. I thought it would be a nice, fun set of exercises intended to help beginners learn about programming concepts.

Nope!

Project Euler SolutionsProject Euler is for computer science and math geeks bent on stretching their brains to the limit.  The difficulty curve here is very nearly a vertical line placed millimeters from your nose.  Problem 1 is basically a fizzbuzz variant, and a warmup (tease, perhaps).  After that, you will be humbled.  What I thought would be a nice afternoon activity turned into a two week affair.  Basic concepts like looping and conditional statements just won’t cut it – unless you feel like waiting several hours for an answer to compute.  I had to turn to Google to learn more than I ever wanted to know about the Seive of Erastosthenes and Pathagorean triples.  But even if I didn’t figure out they mathy parts myself, I still managed to craft unique (to me) solutions in javascript based on the pseudocode or general algorithms discovered by others.  After reaching problem 10, though, I’m done. For now.

My GitHub Repos:

Fork of mrdavidliang’s koans

Fork of leammclennan’s koans

Project Euler answers (executed via Jasmine)

A simple example of the Javascript ‘Call’ function

I was asked about function.call() the other day during a discussion with a co-worker, and came up with this example off the top of my head.  There are many, many uses of call().  In addition to accepting an object as a parameter to replace the called function’s this, it also accepts an arbitrary number of arguments that will be passed into the called function.  Better examples can be found in the Mozilla Developer Network JavaScript Reference.

// A constructor function for a Dog
var Dog = function(name){
this.name = name;
};

Dog.prototype.bark = function bark(){console.log(this.name + " barks!");};

// Fred is a Dog.
// Fred can bark, because all Dogs can bark.
var fredDog = new Dog("Fred");
fredDog.bark(); // => "Fred barks!"

// A constructor function for a Cat
var Cat = function(name){ this.name = name; };

// Bill is a Cat
var billCat = new Cat("Bill");

// Normally, Cats cannot bark,
// but Bill is an exception and has learned how to bark like Fred
fredDog.bark.call(billCat); // => "Bill barks!"

When bark() is invoked with the call() function, billCat takes the place of this within the bark function of Dog, so this.name is a reference to billCat.name instead of fredDog.name.

Code HTML5 in the Cloud with StackMob, Cloud9 and GitHub

In my recent efforts to learn more about modern Javascript I’ve been looking around at different Backend-as-a-Service (BaaS) companies.  They presumably would provide a dead simple server option for whatever I’m working on so I can focus all my attention on the front-end.  I signed up for a number of different accounts to explore the feature set and documentation, and settled on StackMob due to the perceived ease of use, and the fact that their Javascript SDK is built on backbone.js (another current interest of mine).  After creating (and deleting) some dummy apps to get a feel for things, I eventually got a very simple, but usable, database put together.  What is interesting about StackMob is that they will host your front-end app, as well as provide the back-end.  Not only that, but you deploy to your front-end development server directly from GitHub.  It’s a pretty slick system.  And as soon as I realized that GitHub projects can be edited via the Cloud9 IDE, I had a nice little dev environment fully hosted in the cloud.

I’m not saying this combination is at all practical for serious use, but it could be useful in a pinch, or when monkeying around with some prototypes while using multiple computers.  Plus Cloud9 is just fun to look at, and this provided a good excuse to use it for real once in a while.  Oh, and it’s all free (as in beer).

To get started, sign up for a Stackmob account, and a GitHub account.  Both sites have amazing documentation for getting up-and-running on their respective services.  GitHub has very detailed instructions for setting up your account with a git client on Linux, OS X, and Windows.  If you haven’t already, follow those instructions, but do not yet create a repository.

Getting started in StackMob is just as easy.  Sign up for an account, then create an app.  Every app generated by StackMob starts with a Users table, which is enough for now.  Grab the Javascript SDK from the Get your SDK page, and follow the setup instructions in the Setup your JS SDK Dev Environment section.  Step 2 is optional if you just want to edit your app in the Cloud9 IDE.  Otherwise make sure you have Ruby installed and give it a try.  In Step 3, you will be instructed to create a GitHub repository. Do that.  While you are logged into GitHub, also set up automatic fetching, so your code will get deployed to your development server every time you push to GitHub.  The Hosting Your HTML5 App… page has all the necessary instructions. Make sure you have committed and pushed some files (likely the StackMob SDK) to your GitHub repository.

By this point, you can edit files locally, push the files to GitHub, and see your changes reflected online.  To start editing online, go to c9.io and log in using your GitHub account.  When you reach your dashboard, you should see a big green button that says Create New Project in the left-hand sidebar, as well as a section in the sidebar labeled Projects on GitHub.  The URL for your dashboard is http://c9.io/yourgithubusername.  If you cannot see your GitHub project, click the refresh button in the far lower left corner of the screen.  Select your StackMob GitHub project from the sidebar menu, and click Clone to Edit.  In the modal window, select Shared Development Server and click Checkout. It will take a minute, but your project should be created and listed under My Projects. Select your project and click Start Editing.  You should be taken to the editor window where you can open and edit your project files.  Take a few minutes to admire the lovely UI and its many features, and edit a file or two.

To test out your edits, open the console window (Menu: Windows > Console ) and run your usual git commands – e.g. git commit -a -m “msg” and git push. The Cloud9 git client will push your changes to your GitHub master branch, and those changes will then propogate almost immediately to your hosted StackMob application.

This is creating a web application in the cloud.  Development-in-the-cloud is not quite cut out for daily use, but if you really need to try out some code or get in a quick change from any computer (or tablet, or phone), this is a nifty way to do it.

 

A Test-Driven JavaScript Assessment – I Passed!

Over the past few weeks (months?), I’ve been making a grand effort to learn as much as I can about javascript.  I’ve gotten my hands on a couple , read countless , and most recently, stumbled upon a very interesting blog post.  Rebecca Murphey (of yayQuery! fame) recently created a series of failing unit tests in javascript and made a nice node.js app from them (available on Github).  This provides a nice exercise for anyone wishing to assess their fundamental javascript skills.  Given the fact that I had no idea where I stood in terms of skill, I thought I’d give it a go.

I’m glad I did.  Not only was it a mild wake-up call, but a great introduction to some topics that I don’t see often in the real world – topics like partial functions & currying, closures, creating modules, and working with prototypes.  I’m not ashamed to say this took a better part of a Sunday afternoon, as it was quite rewarding to see that “100%” show up on the screen.  Some of the tests were ridiculously easy, some were challenging, and there were a few where I didn’t really know what I was supposed to do, but eventually got something working while sticking to the topic at hand.

I’ve uploaded a fork of the project to github with my completed answers.  More tests may be added into the future, so I’ll be able to simply pull them down and hack away.  It will also be nice for my future self to look back on this in a year or two and have a chuckle at the expense of my present self.

Count the occurrences of an item in a List or Array

So I came across a situation where I had a whole bunch of items in a collection, and I needed to know how many of each kind there were.  In other words, I needed to know the number of each unique element in an IList, Array, ArrayCollection, or what-have-you.  I looked for some help online, and fiddled around and got it working.  Then a few weeks later I had to do the same thing, and darn near forgot how I did this.  Here is the trick – SORT!

Sort the items in the array (alphabetically, numerically, chronologically, etc…) so that unique items are grouped together.  Then simply loop over the collection counting identical items, and when a new item occurs, make a note of how many you have of the first item, and start counting again.  Below is a quick example.  Click “Generate” to create a list of 50 items, where each item is going to be a fish, cat, dog or pony.  Then click “Count” to count the number of each one.  Also notice how the original list is now sorted so all the ‘dogs’ and ‘cats’ are together.

Sorry, either Adobe flash is not installed or you do not have it enabled

Here’s the meat of the code:

sortedList = new ();

//Sort Newlist Alphabetically
newList.sort();

/*  Create an object to keep track of each unique item in the array. For example
*   { Name: 'cat'
*     Value: 7  }
*/

var countObject:;

//Create a var to store the previously examined item in the list.
var previousItem:;

//Loop over all the items in the newArray
for each ( var currentItem: in newList )
{
//If the current item in the list is different from the previous item, then create a new countObject and start counting the new item.
if (previousItem == null || currentItem != previousItem)
{
//Create a new object
countObject = new ();

//Set the name to the current item in the loop
countObject.name = currentItem;

//Count this item
countObject.value = 1;

//Put the object in the sorted list so we can see it later
sortedList.push(countObject);

//Done. Set the current item to the previous item.
previousItem = currentItem;
}
else  //Otherwise, we haven't switched to a new item yet, so keep counting the current item.
{
/*  Find the last countObject in the sortedList, then add 1 to the value of that object.
*   For example, if we have looped over 3 cat items in a row, and the current item is also cat, then:
*   { Name: cat, Value: 3 + 1 }
*/

sortedList[sortedList.length - 1].value += 1;
}
}

and Full Source for the above example.

© 2017 Eric Terpstra

Theme by Anders NorénUp ↑