Skip to main content

Posts

Showing posts from 2008

Script to generate an RSS feed from RenWeb's announcements

The following ruby (jruby) and sql code will get the Announcements from RenWeb and create an RSS feed file from them. The scripts needs the JDBC ActiveRecord gem. If you have any questions on how to run this script, please write a comment below. Both files are released under the MIT license . main.rb: require 'rss/maker' require 'cgi' require 'rubygems' gem 'activerecord-jdbc-adapter' require 'jdbc_adapter' class AnnouncementsDistrict :jdbc, :username => "YOUR ODBC USERNAME", :password => "YOUR ODBC PASSWORD", :driver => "com.microsoft.sqlserver.jdbc.SQLServerDriver", :url => "jdbc:sqlserver://THE URL TO CONNECT;DatabaseName=YOUR DATABASE NAME") set_table_name("AnnouncementsDistrict") #Gets an sql query from a file def self.get_sql_query_from_file(filename, params_hash_for_sql_query = nil) fi = File.open(filename) sql_query = fi.read if pa...

How to create a yahoo datatable in rails

To create a Yahoo Ajax Datatable (with local datasource) from a rails view, I had to do the following. First I had to add this helper method to the Application controller: module ApplicationHelper #Outputs the javascript code necesary to create a yahoo datable # from a plain datasource # column_array: and array of 2-item arrays in the form: # ["name_wihout_spaces", "Text to show in the column header"] # data_rows: an array or rows. Each row is an array that has the values in the # order specified in the column_array. def to_yahoo_array_data_source(column_array, data_rows, custom_div_id = "myContainer", custom_col_var_name = "data_cols", custom_datasource_var_name = "data_source") column_items = [] column_array.each do |column| column_items Next I added the required javascript libraries to the application layout: <html> <head> <title>Email De...

Strange behavior with the up,left,space bar key combo

I was checking if the up and left arrow and the space bar was pressed in my game code to allow the player to move and turn and shoot at the same time. Turns out that in GameMaker 7, if the user holds up+left+space bar keys at the same time, either the up or the left arrow key event will be ignored. I had to change the shoot key to the key to go around this weird behavior.

Math game for Areas and Volumes

I just uploaded an educational game to YoYoGames called Math Areas and Volumes . The game was made using GameMaker and the original purpose for it was to help my eight grade student to improve their skills of finding the area and volume of objects. If you have ever taught children about areas and volumes, you probably will notice that some of them confused the two concepts. The game uses plain graphics to help students distinguish the difference between the area and volume concepts. A 2D square with little squares filling it, represent a square unit. A 3D cube with little cubes on it represents the cubic units. You would need to play it to completely get the idea of what I was trying to do to help the students. Something else worth noting is that I used some of the excellent graphics that came with my Multimedia Fusion. I already asked in the forum, and the official response was that I could use the graphics as long as distributed the game only as an “.exe”. Thank you Clickteam!

Warbler uses gem files from cache folder instead of gems folder

I was having the following error when running warbler war on my rails application folder: Cannot load gem at [/home/juanito/jruby-1.1.4/lib/ruby/gems/1.8/cache/activerecord-jdbc-adapter-0.8.2.gem] in /home/juanito/bulletonrails/svn_copy/bullet_gui /home/juanito/jruby-1.1.4/lib/ruby/site_ruby/1.8/rubygems/format.rb:41:in `from_file_by_path' I looked around the gems/1.8/cache folder and sure enough, the gem file for activerecord-jdbc-adapter was missing. I had deleted that file and other gem files from that folder a while ago because I thought I would not need them and they was taking space. Well, it turns out that Warbler uses the gem files from the rubygem's cache folder to unpack the gems into the WEB-INF folder. As a consequence, by basically using the original gem files, it bypasses any modification you make to your local gems. So if your newly deployed jruby WAR application is missing custom behavior that you added to your local gems, you may want to convert the gem...

Make your rails app launch the web browser when starting

In jruby, if you ever want to start the browser pointing to your application's base index page after rails finishes initialzing your application, you can take advantage of java.awt.Desktop::desktop.browse. java.awt.Desktop::desktop.browse will open the default OS's browser and point it to an URL you pass to it (tested on Windows, failed in Ubuntu+Firefox, don't know if it works on MacOSX or Solaris). Add these lines at the end of environment.rb to launch the browser: include Java java.awt.Desktop::desktop.browse( java.net.URI.new('http://localhost:3000'))

How to make Net::SSH work with Jruby on Windows

Net::SFTP works like a charm in Jruby on Linux. However, when I tested my application in Windows, I ran into a fail "to load -- dl/import ssh" error and then into "IOError (The system cannot find the path specified)". To work around the errors, I had to make some changes to the Net::SSH code to make it work. There are 2 files you need to change gems\net-ssh-2.0.4\lib\net\ssh\known_hosts.rb and gems\net-ssh-2.0.4\lib\net\ssh\authentication\pageant.rb. For known_hosts.rb change the add(host, key) method located at the end of file to read like this: # Tries to append an entry to the current source file for the given host # and key. If it is unable to (because the file is not writable, for # instance), an exception will be raised. def add(host, key) begin #jpt File.open(source, "a") do |file| blob = [Net::SSH::Buffer.from(:key, key).to_s].pack("m*").gsub(/\s/, "") file.puts "#{host} #...

Java-jruby program to turn on computers remotely

Using wakeonlan.rb from Kevin R. Bullock, I was able to creat a small jruby swing-gui program for turning on remote computers using Wake On LAN. The program displays in an array buttons corresponding to the computers listed in a text file. When you click the button, the program sends a WOL packet to the computer to turn it on. The code is the following (note that you need wakeonlan.rb in the same folder): # Copyright (c) 2008 Juan Pablo Tarquino # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in al...

New Avery 5160 template for Jasper Reports

I had to create an Avery 5160 (address labels 3x10) template for jasper for work. If you would like to use that production-ready template you can download it from here . The template has been used in a production environment, however, as always, make sure it works for you before printing too many labels :).

Ruby script to get a batch of MARC records

At work we bought a lot of new books for our new library. Our libraries use aprogram called LibraryPro which can import MARC records to add books to the catalog. To save ourselves some time, I look on the web for a script to get MARC records from the Internet and found this excellent script from William Denton. Because I needed to get batches of records and modify the records gotten to follow our custom dewey decimal number (number/category/author), I modified his script to accomplish that and this is how it looks now: #!/usr/local/bin/ruby -w # Script to get a batch of MARC records # #original code taken from http://www.miskatonic.org/library/zmarc.html # original programmer # William Denton wtd@pobox.com # April 2007 # modifications made by Juan Pablo Tarquino http://jptarqu.blogspot.com # Released under the MIT License. # Copyright (c) 2007 William Denton # Copyright (c) 2008 Juan Pablo Tarquino # # Permission is hereby granted, free of charge, to any person # obtaining a cop...

Update on Tomcat on SSL

At work, I set up Tomcat 6.0.16 to use SSL using the instructions from http://techtracer.com/2007/09/12/setting-up-ssl-on-tomcat-in-3-easy-steps/ . However, I had to modify some of the steps to make it work on mys system: When generating the Keystore file, make sure you tell keytool that you wnat RSA: keytool -genkey -alias techtracer -keypass yourpassword -keystore techtracer.bin -storepass yourpassword -keyalg RSA Also, in tomcat's sever.xml, use the code snippet from the official documentation (http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html) instead of his snippet, e.g.: < connector port="8443" minsparethreads="5" maxsparethreads="75" enablelookups="true" disableuploadtimeout="true" acceptcount="100" maxthreads="200" scheme="https" secure="true" sslenabled="true" keystorefile="/home/yourself/apache/webapps/techtracer.bin" keystorepass="yourpassword...

Deployed a JRails application using warbler in Apache

I was able to deploy a JRails application using warbler in Apache. The latest warbler gem is very nice and stable. I just needed to make sure warbler and jar were in my PATH variable. I also had to tell warbler to generate the files outside my truecrypt drive because somehow, truecrypt was not allowing WEB-INF folder to be uppercase. I still can't figure out how to change the Rails environment from Production to Development, it seems that warbler forces you to use Production which is very understandable considering that you usually deploy to production servers. Futhermore, thanks to the excellent Setting Up SSL on Tomcat In 3 Easy Steps article by nitinpai, i was able to set up apache and the rails application to run under SSL. Very, very nice and it was incredible easy, however, to make the certificate work with firefox 3 you need to tell keytool to use RSA. The is another article on the web about that, you can google it.

New Label templates for JasperReports

I had to create jasper templates for Avery 5390 and 5388 at work, so I decided to share the templates with those of you who are looking to print labels from iReport and/or JasperServer. You can download the templates here (includes 5390, 5388 and 5960) . The templates have a square where you should be able to safely put your content. I came up with the squares' dimensions by trial and error so please do some trial printings to see if it works for you. Also, groovy is the default language in my iReport so for all my templates had the language attribute set to groovy; if you run into problems with jasperserver you can do either one of the following: Place the groovy jars in JasperServer's webapp's lib folder. OR Edit the templates to disable groovy (remove the language="groovy" attribut from jasperReport node). Many thanks to André for pointing that out! The templates are released under the MIT license.

How to create customized, windows installers of Tomcat server

To create customized, windows installers of Tomcat server (including an option to allow the user to install it as a windows service) you can modify the ".nsi" installation script provided in the " res " folder. You can find the res folder when you download Tomcat's source code. For more information on nsi scripts please visit http://nsis.sourceforge.net/Main_Page .

Securely erase files and folders recursively in Linux

This ruby script will securely erase files and folders recursively in Linux. You may want to add a action to run this script to the context menu of Nautilus using nautilus-actions . # # Shreds files and folders recursively. Code released under MIT license. NUMBER_OF_PASSES = 20 def shred_files_and_folders(path) if File.directory?(path) files = Dir.entries(path) files.delete_if {|x| x == "." or x == ".." } files.each do |f| if File.directory?(path + '/' + f) shred_files_and_folders(path + '/' + f) else puts ` shred -v -z -u -n#{NUMBER_OF_PASSES} #{path + '/' + f}` end end Dir.rmdir(path) else puts ` shred -v -z -u -n#{NUMBER_OF_PASSES} #{path}` end end ARGV.each do |path| shred_files_and_folders(path) end

Script to delete old backups files created with Cobian Backup

The following ruby code will delete from a folder old backups files created with Cobian Backup. The deletion is recursive, so all the folders within the folder will be cleaned. # # Deletes old backups made with Cobian Backup. This code is released under the MIT license. NUMBER_OF_FILES_TO_KEEP = 6 def delete_old_backups(path) files = Dir.entries(path) files.sort! {|x,y| y x } files.delete_if {|x| x == "." or x == ".." } name_of_file = " " new_name_of_file = "" file_cnt = 0 files.each do |f| puts f new_name_of_file = f.split(" ")[0] if new_name_of_file != name_of_file file_cnt = 0 name_of_file = new_name_of_file end if File.directory?(path + '/' + f) delete_old_backups(path + '/' + f) end file_cnt = file_cnt + 1 if file_cnt > NUMBER_OF_FILES_TO_KEEP puts "delete " + path + '/' + f File.delete(path + '/' + f) end en...

Jmaki, Jruby and Tomcat: stories from J Land

I was using the nice Dojo Table widget for a rails application because I needed to allow the user to sort the displayed table. I also needed to deploy the application on Tomcat. To make it work, I had to copy the resources folder created by Jmaki in the public folder to the root folder of Tomcat's webapps (the webapps folder). I also had to do some fixes to jmaki_core_celper.rb source. The modified parts (which adds more functionality such as allowing to pass field names to jmaki widgets) are the following: module JmakiCoreHelper # ---------- Global Constants ---------- JMAKI_RESOURCES = RAILS_ROOT + '/' + "public/resources/" #chg by JPT to allow Tomcat to find the the widget's files ... # ---------- Global jMaki Methods ---------- def jmaki_widget(name, options = {}, field_name ="jmaki_field", width = 100) # Set up variables we will need result = "" nameSlashed = name.tr('.', '/') widgetD...

Create objects for a has_one relationship in the Create form's has_one subform

I was having a problem using the active scaffold's subform when creating child objects in the create form. I had a class ClassSections that has_one Course. When I clicked "create new" in the AS scaffold I had the opportunity to enter a new Course in the Course subform that shows on the ClassSections's create form. However, when I saved it , it returned an error telling me that "Course can't be null". I was surpirsed since I could choose an existing Course but not create one from that form. After some time, I discovered that the culprit was that I had a validation in the ClassSections class to prevent the course_id to be null (validates_nullability_of :course) and in the RDBMS I had also a NOT NULL constraint in the foreign key. I disabled both constrains (in the class and in the RDBMS) and now it works. The lesson learned: In Active scaffold, if you want to be able to create objects for the has_one relationship in the Create form's has_one subform...

Mail labels and letter templates for jasperreports

The following are free (MIT license) mailing labels and letter templates for jasperreports that you can download and use in jasperserver and/or ireport: Update 3/15/2011 : I moved the Mail templates zip file here . Please consider making a small donation if the templates are of help to you, Thank you! If you need more information on how to use those templates please leave a comment in the blog.

Deployed a jruby on rails application on both Glassfish and Tomcat using Goldspike

Update 4/19/08: make sure you have rake 7.x instead of the newer 8.x version! Update 6/7/08: It does work with the latest Rake! please make sure you don't have a file in your folder whose name has a parentheses or a space when creating the WAR file. It is possible to deploy a jruby on rails application on both Glassfish and Tomcat. Make sure you read the Goldspike wiki and follow all the directions. Also make sure that you create a project WIHTOUT support for war deployment and instead install the goldspike manually. Also make sure your application works in production mode in Mongrel before you try to deploy it, that will save you a lot of time chasing ghost errors (both Glassfish and Tomcat are not very good spewing rails related errors). Also make sure that all your files are being deployed and that if you refer to any file in your application folder you use the RAILS_ROOT constant to get the absolute path. I was opening a file using a relative path, the file was on the root ...

How to make your Jrails application run in Glassfish v2

Using Netbeans 6.0, Create a Rails application WITHOUT support for WAR deployment. Glassfish will use the "production" part of database.yml, so make sure you have a valid configuration there. Install the goldspike plugin (script/plugin install http://jruby-extras.rubyforge.org/svn/trunk/rails-integration/plugins/goldspike ) In Netbeans, refresh the rake tasks. Add your dependent gems in the war.rb file located in config folder (see http://wiki.jruby.org/wiki/Goldspike for more instructions on how to do that). Basically is something like: add_gem 'activerecord-jdbcpostgresql-adapter' add_gem 'fastercsv' run rake->war->standalone->create from the menu. copy and paste the generated war file (should be in the app's root folder) into the autodeploy folder of you glassfish domain's (domains/yourdomain) folder. start your glassfish server. Navigate to your application, e.g.: http://localhost:8080/finances/categories/list.

How to call rake from ruby code

The following is a method to execute rake tasks from ruby code : #arguments can be for example db:migrate def call_rake(arguments) if RUBY_PLATFORM =~ /mswin/ rake_cmd = "rake.bat" #very important because windows will break with just "rake" else rake_cmd = "rake" end puts "calling #{rake_cmd} " + arguments puts system("#{rake_cmd} " + arguments) puts $? end Check out my Bullet on Rails project at Rubyforge.net to see how to call script generate scripts from ruby code.

Overriding conditions_for_collection from a module

When using ActiveScaffold, I had problems overriding conditions_for_collection from a module. The problem was that even tho I was overriding the instance method conditions_for_collection in the FilterFormExtensions module, I was including (using "include FilterFormExtensions") the module before inserting the activescaffold into the controller (using the active_scaffold method). Any active scaffold method that you want override using a module, make sure you include the module after inserting the active scaffold. Of course if you declare the method as an instance method of your controller, the method will be overridden regardless of whether is before or after inserting the active scaffold.

Rails and ActiveScaffold problems

It appears that form_tag :action => 'show_results' is not the same as form_tag 'show_results' . Always use form_tag :action => 'show_results' . Also, when you get strange errors from RJS that ActiveScaffold hide method does not exists, you may need to download the latest version of ActiveScaffold and make sure that the Public folder (where the javascript files are stored) and the Vendor folder (where the plugin is stored) gets updated with that new version.

My first work with Gosu + Chipmunk

I modified the tutorial game to make the ship point to the mouse cursor. Kept the physics, resulting in an interesting game. Here is the source code: require 'rubygems' require 'gosu' require 'chipmunk' SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 # The number of steps to process every Gosu update # The Player ship can get going so fast as to "move through" a # star without triggering a collision; an increased number of # Chipmunk step calls per update will effectively avoid this issue SUBSTEPS = 6 # Convenience methods for converting between Gosu degrees, radians, and Vec2 vectors class Numeric def gosu_to_radians (self - 90) * Math::PI / 180.0 end def radians_to_gosu self * 180.0 / Math::PI + 90 end def radians_to_vec2 CP::Vec2.new(Math::cos(self), Math::sin(self)) end end # Layering of sprites module ZOrder Background, Stars, Player, UI, Cursor = *0..4 end class Cursor attr_reader :img, :visible, :imgObj, :p...

Gosu, Chipmunk in Ubuntu linux

To use the excellent ruby game framework Gosu and the 2D physics engine Chipmunk in Ubuntu, you need to copy the two .so files (chipmunk.so and gosu.so) in the /lib/ruby/1.8/i686-linux folder. You can download those files from  https://sites.google.com/site/jptarqu/downloads  (look for  gosu_and_chipmunk.tar.bz2) . I will explore the possibility of cross-platform, easy Game development using Gosu.