# A Simple Monte Carlo Experiment in R: More 𝜋

Monte Carlo simulations (or Monte Carlo methods) are a simple but useful technique to derive a solution to a problem by randomly guessing possible inputs. The definition is so broad that it’s likely you’ve used this technique without even realizing it.

The hello world problem for Monte Carlo applications is undoubtedly calculating approximations of 𝜋, albeit ineffeciently.

### It’s Always About Darts

Before we can write software to do this we need to think about how to restate the question in probablistic terms. 𝜋 is simply the ratio of a circle’s circumference to its diamater.

$\pi = \frac{C}{d}$

We also know the area of circle is:

$A_c = \pi r^2$

Suppose a circle was inscribed inside of a square.

We could then define the area of the square in terms of the circle’s diameter:

$A_s = lw = dd = d^2$

Or in terms of the circles radius:

$A_s = (2r)^2 = 4r^2$

Now, onto the darts. Imagine you’re throwing darts at the square. The universe is constrainted such that every dart lands randomly inside of the square.

The probability of a dart hitting the circle is the radio of the area of the circle over the square.

$\frac{A_c}{A_s} = \frac{\pi r^2}{4r^2}$

Which means:

$\pi = 4\frac{A_c}{A_s}$

Restated another way:

$\frac{\pi}{4} = \frac{A_c}{A_s}$

Now that we know a fourth of 𝜋, we can limit our trial to one quadrant because the ratio still holds true. This isn’t strictly nessecary but it simplies the program.

Here we have the make.pi function that creates an R data.frame that holds the trials containing the X & Y coordinates of the dart position.

This plot gives us a visualization of where each trial lands.

And finally we can check how well this solution scales with different size trials.

# Using New Relic With Clojure

At getaroom.com we’ve used New Relic extensively for many years to monitor our Rails applications. We’ve recently began moving our backend infastructure to Clojure, maintaing the visibility New Relic gave us for our Rails environment was a must.

New Relic’s product is great, but the ability to add custom instrumention to a Clojure application is less than ideal. The primary method of custom instrumentation using New Relic’s Java agent is via custom annotations. Sean Corfield wrote an excellent post on how to get this to work using deftype.

### Setup New Relic

Adding the New Relic API jar will permit custom metrics via the Java API. At getaroom we use it expose a number of metrics about our business of selling hotel rooms. These metrics can be displayed using custom dashboards along with many of the standard graphs available but they don’t provide the same insight that instrumentation of underlying function calls can provide.

Enabling New Relic requires launching the JVM using the -javaagent switch. The startup time of the agent leaves much to be desired. Given this, I’ve found it useful to conditionally enable New Relic via a leiningen profile.

### Instrumentation of AOT Compiled Code

Adding a custom annotation in Clojure isn’t always practical. Let’s consider the case where we wanted to instrument the custom JSON library cheshire. If we were calling parse-string we could create functions that call through a method containing the custom Trace annotation as Sean Corfield describes here. This works but involves extra stubs used only to satisfy New Relic’s use of annotations.

If you’re willing to trade the downsides of AOT compilation for better instrumentation we can use New Relic’s custom XML extensions. We acheive this by using an AOT compiled uberjar. Currently, this trade-off is worth for us but YMMV.

#### Instrumenting Clojure Functions with Custom XML Extensions

In many cases the AOT compiled function has a name that is very easy to find. An anonymous function is not one of these cases.

The following is the roughly what the generated class looks like for the function cheshire.core/parse-string.

Now that we know what the method signature looks like, we can add the custom extension XML.

Add the following XML to a file called cheshire.xml within the extensions folder of your New Relic install.

Once this is added and the application is restarted you should begin to see traces that include the generated class name for the cheshire.core/parse-string function. Additionally, using the excellent New Relic thread profiler you can easily find new functions that would benefit from visibility in New Relic traces.

# Apple Push Notifications Toolkit for Ruby

Lately I’ve been working on an iPhone application that utilizes Push Notifications extensively. While Apple provides great documentation there is still a fair amount of work left up to the developer to send push notification in ordinance to their usage policy.

Since I’m using Rails for the backend I needed a way to maintain a single open SSL connection to prevent setup and tear down for every notification sent. To accomplish this I created an Event Machine based server deamon that that proxies all requests send by Rails application over a local, non SSL socket.

The proxy queues and sends each notification to the Apple notification servers. Additionally I’ve created a command line script to send notifications for testing purposes. My project Apn Server is hosted on Github.

You can add it to your Rails application via

You can use either a direct connection to Apple or one through the apnserverd proxy included in the gem. To configure directly to Apple’s server (and also setting up and tearing down a new connection each time). Add the following to your environment.rb.

To use the non SSL apnserverd proxy simply drop the PEM configuration option

To send a notification from Ruby

You can also send notifications via the line with

# Remove Bevel and Gloss Effect From iPhone Icon

After search for this a bit, it is a simple property inside of your Info.plist. To remove the bevel and gloss effect set the following property:

For more properties check out the [Info.plist reference](http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationEnvironment/chapter_3_section_4.html#//apple_ref/doc/uid/TP40007072-CH7-SW15).

# Parsing CSS With ANTLR

For a project I"m working on, we’ve used CSS syntax to describe styling on application objects. To accomplish this we created a parser using Antlr. Here is our implementation of the CSS core syntax. Unicode support is left out as it was not needed for our use case, but it should be pretty easy to add in.

# Securing Data Wtih OpenSSL and Ruby: Part One

For the most part Ruby has fantastic APIs. While there is an occasional wart here and there (I"m speaking to you [DateTime](http://www.ruby-forum.com/topic/146117)). In general, it doesn’t suck. The OpenSSL bindings for Ruby are no exception.

1. Bob, meet Alice ##

To begin our cultural learnings of OpenSSL and Ruby, let’s take a look at source repository for the interpreter. In the [samples](http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/trunk/sample/openssl/) directory are some nice examples how the bindings work. It seems that some of the original code examples were never migrated from the RubyPKI project, but thats ok, you can still access [them](http://cvs.savannah.gnu.org/viewvc/rubypki/ossl2/examples/) here.

1. The OpenSSL Digest Class ##

One of the most common things you’ll most likely need is to create a digest of a string of data. We can do this using by instantiating a Digest class then invoking the hexdigest method.

Simple enough. But what is the deal with ‘digest’ versus ‘openssl/digest’? According to the ‘digest’ module is only used for backwards compatibility, so use the openssl version when possible.

1. Available Digest Algorithms ##

According to the source, the Digest algorithms available are dependent upon the version of OpenSSL compiled with Ruby.

# Compiling Erlang Applications With Rake

The irony of Rake is that Ruby really doesn’t need it. This is not to say it isn’t useful to Ruby projects, quite the contrary. Where Rake shines is in building software for applications that require byte code and object code, such as Java or C centric projects.

One such language requiring byte code compilation is Erlang. The design of the runtime environment used by Erlang should be familiar to most Java or C# developers. Erlang uses a byte code compiler (erlc) and various application meta-data files (.app, .rel, .config). For my development work I use Erlide, the Eclipse based Erlang IDE. The standard project layout for an application created in Erlide is:

+ project
– ebin
– include
– src

When creating a Rake file for Erlang projects, I ran into a few problems with compiling the source into the separate ebin directory. Namely, dependencies where not being constructed as desired yielding a full rebuild every time I ran the build script! In the following example I dynamically create the file rules so that the bytecode (.beam) files will only be recompiled if the source (.erl) file is changed.