Archive for the ‘Ruby’ tag
Code Golf
CSLU did code golf today. I did 1 and a half tasks, which were:
- Output the first 100 prime numbers
- Output e to 100 decimal places
Prime numbers
I’m quite proud of this, I managed to do this in 55 characters initially but then after some collaboration with the rest of the club shrunk it down to 49 characters
2.upto(541){|a|i=2;i+=1 while a%i>0;p a if i==a}
e
I never got his fully working as I ended up getting caught up in list comprehensions. Ended up with:
1 + sum [1 / (product [m | m <- [1..n] ]) | n <- [1..300] ]
Which is the same as and shows how pretty Haskell is.
Ruby gem – json_serialisable
I was working on a ruby project and stumbed upon my first valid application of metaprogramming. I was creating json serialisation methods and realised they were all practically identical. So I looked at how attr_accessor worked and then wrote my own class method called attr_serialisable. This method generated serialisation methods automatically.
Example
Given a class A
class A
attr_accessor :a, :b, :c
attr_serialisable :a, :b, :c
def initialize(a, b, c)
@a, @b, @c = a, b, c
end
end
attr_serialisable would generate the following methods:
def to_json(*a)
{
"json_class" => self.class.name,
"a" => @a,
"b" => @b,
"c" => @c
}.to_json(*a)
end
def json_create(o)
new(*o["a"], *o["b"], *o["c"])
end
Which will allow the class to easily be used by the ‘json’ library.
Links
Fountain code challenge
For the second term of the 2011/2012 academic year I’ve made a small challenge for members of CSLU.
Details are found on the PDF.
Good luck.
P.S a bit of background reading can be found here.
Programming languages course
So I ran a talk on learning programming languages last week. It was the second time I had done that particular talk, and in this case the hardware setup went smoothly – as it was done by Stephen Wattam the CSLU VP.
We had a pretty good turn out, mostly of year year undergraduate students who so far had only played with a little C. I took pictures of everyone hard at work doing their task … well, ok. They were mostly on tryruby.org which was even better.
It showed that they had an interest in a new language which is fairly good at prototyping and will allow them to try out their ideas fast. I may have semi pushed them on to it in my talk, so I’m glad they were listening. No one tried learning Haskell though, but then I’ll drop in on everyone next term and see how they are doing. The slides and some info for my talk can be found at the CSLU site.
On a side note … My Instagram tshirt came! I’m not sure if I’ll ever wear it outside as it’s a bit long, but still!
Rain – Agent-based water
Well I’ve been wanting to do this for a while now, and on Sunday with a freshly installed (and therefore speedy) net book under my belt, I thought I’d have a crack at it.
Last year (maybe even 2 years now) ago, I made a weak plasmoid generator with the intention of using it for terrain generation. I’ve always wanted to use that library for some agent based programming, and a simple (rule wise) example of it would be water. You put some water agents on the map they move as low as they can go, then evaporate. This kind of does that, and definitely suffers from “proof of concept” syndrome. Water moves, but to do anything fancy will require redoing, which I’ll probably end up doing on my next free Sunday.
So, using a library called Gosu to handle the drawing and the event loop, and a library called TexPlay which allowed me to modify pixels, I got a render up and running which displayed a map of tiles (1 pixel tile
), and the colour was defined with a lambda that was passed to all of them.
As I’m learning Haskell at the moment, I thought I’d give some lambdas a go, and it made it really easy actually.
There are two types of agents in this program, Rain and Sources.
- Rain just flows to a low point.
- Sources make Rains.
Rains become sources if they hit a low point, which basically has the effect of stacking the Rains that have pooled there so they can make lakes. As Rains are destroyed when they stop, and Sources can only produce a finite amount of Rains based on how many are there when it is made, the system sort of stays constant. Initial sources are given enough Rains to cover the whole map 1 deep.
That is awkward to explain.
Most of the issues with this program was making the renderer fast enough to work on a net book, and as I’m not a graphics man, I made many rooky mistakes.
This is fairly mesmirizing to watch, and I’ll definitely improve it further, by:
- Making the map colouring sample from colour->height table
- Have water level as a tile attribute to make things cleaner
- Fix evaporation
- Make it so that tiles which have a constant flow of agents over them are distinguished from one-off “rain” paths
- Fix Rain
It’s a project, feel free to fork from git hub here at https://github.com/carl-ellis/Rain
Old school screen capture.
Video here: Rain – agent-based
Rails 3 and lighttpd
This was performed on Archlinux with lighttpd 1.4.28 and rails 3.0.3
Prerequisites
Required packages:
- lighttpd,
- fcgi,
- ruby,
- and their dependencies…
Ruby Setup
Required gems:
- fcgi,
- bundler
(if you are behind a proxy, the magic gem command is :
# gem install GEM -r -p "http://[PROXY_URL]:[PROXY_PORT]"
)
Once you have that you need to create a “dispatch.fcgi” script to do all the rails magic. I found an example one at http://stackoverflow.com/questions/3296206/rails-3-and-fcgi .
#!/usr/bin/ruby
require 'rubygems'require 'fcgi'
require_relative '../config/environment'
class Rack::PathInfoRewriter
def initialize(app)
@app = app
end
def call(env)
env.delete('SCRIPT_NAME')
parts = env['REQUEST_URI'].split('?')
env['PATH_INFO'] = parts[0]
env['QUERY_STRING'] = parts[1].to_s
@app.call(env)
end
end
Rack::Handler::FastCGI.run Rack::PathInfoRewriter.new(YOUR_APP_NAME::Application)
Running a “bundle install” from your app root will make sure all the necessary gems are available for local use. Follow these instructions and run “ruby public/dispatch.fcgi”, if you get no errors, voila!
Lighttpd Setup
Now, to set up lighttpd you need to merge this with your config:
server.modules += ( "mod_fastcgi", "mod_rewrite" )
$HTTP["host"] == "localhost" {
server.document-root = "/path/to/your/app/public/"
server.dir-listing = "disable"
server.error-handler-404 = "/dispatch.fcgi"
fastcgi.server = (
".fcgi" => (
"localhost" => (
"min-procs" => 1,
"max-procs" => 1,
"socket" => "/tmp/ruby-beholder.socket",
"bin-path" => "/path/to/your/app/public/dispatch.fcgi",
"bin-environment" => ( "RAILS_ENV" => "development" )
)
)
)
}
A quick “sudo /etc/rc.d/lighttpd restart” and a check of the error logs will tell you if it has worked
New Article on Jimhi
I’ve wrote a small article on my site, about the architecture and motivation behind my site.
More of a meta-article really.
It is pretty short, simple, and written at 2am.
http://jimhi.com/content/articles/jimhi/
C
Battery Monitor – rbatmon
I use a rather spartan windowing manager called awesome in all of my machines. This has been a fine setup until I used it on my netbook due to one small issue, battery monitors.
On my desktop machines and the laptop I use gkrellm to monitor cpu and memory and for the laptop it has a handy battery usage label. With the netbook however, screen real estate is quite valuable, so I opted for finding something to sit in the system tray.
After a quick look it seems there was nothing which was lightweight or simple or not requiring me to install the entirety of gnome.
In the end I made my own called rbatmon, then packaged it up for use in the AUR. If you have a substandard flavour of linux, not to worry, You can grab the script from my githib page here.
The most interesting challenge of this was building a package for the first time. There is a great package for Archlinux called abs (available on pacman) which fills /usr/share/pacman with some example PKGBUILDS for standard sources of gettings code from VCS’s.
Page on my site regarding this is here.
AUR page is here.
C
Article is actually … up!
Wow, it has been … 5 months since I said I would write that article? Well … here it is! A link to it anyway: http://www.jimhi.com/content/articles/ .
Will be writing a nice auto table of contents generator and folding javascript now, so it looks a bit nice and follows the site a bit more.
Probably wise to add a link back too !
Next article to be written will be on a java version of the Enigma machine I wrote. Then I shall write up a maze generator and solver which Stephen Wattam and myself built for the Computing Society.
Laters
Possibly the third attempt to start using this.
Yo.
Well, as everyone who has a blog is aware, its hard to actually find anything to put in it, never mind actually remembering to write it.
Ok, so personal stuff. Started my studentship at Lancaster University within the EIS(http://eis.comp.lancs.ac.uk) research group. Still unsure of an actual topic, although I will probably swing towards the algorithmic side of localisation in WSN.
Still, I rarely have time to do any personal code, yet some stuff happens. Recently wrote a basic heightmap generator in Ruby, currently porting to Lua, and it outputs some nice images using image tools like RMagick or just plain VT100 colour output.
Post to follow explaining the code.



