Ruby to Python Primer

If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It’s not Ruby 😀 , but it can get the job done. Here is a quick list of similarities between the two languages. I hope it helps… don’t forget to this list in the comments section 😉

#-----find object methods-----
s="hello, I am a string"

puts s.methods

print dir(s)

#find out more about a method using python

#-----view object's class-----


#------Iterate hashes-------

h.each{|key,value| puts "#{key}, #{value}"}

for key,value in h.iteritems():
print key, value

#---ternary operators

condition ? var = x : var = y

#python.. not exactly an operator, but you get the meaning
#---- var = y if condition is false
var = x if condition else y

s="hello, I am a string"
puts "Length of string is #{s.length} or #{s.size}"

puts "Length of hash is same as string, #{h.length} or #{h.size} "

print("This is the length of a string %s" % len("string"))
print("number of key/value pair= %d" % len({'one':1,'two':2}))

#---slicing lists/arrays

l[1..3] #=>[2,3]

l[1:3] #=>[2,3]

#--print string multiple times-----

4.times{print "hello"} #=> hellohellohellohello

print("hello" * 4) #=> hellohellohellohello


So for my own geeky pleasure, I decided to try writing cgi scripts with Ruby, Python, PHP, and Perl.  All had readily accessible documentation on how to POST to a https URL but ruby. My first thought was to look at the Net:HTTP documentation found HERE.

The one example I wanted was not listed. I did some searching around and pieced together the following code. I hope this is as big a help to you as it was to me. Looking at it, It seems pretty intuitive….but if your like me, sometimes you need it spelled out 😀

As a side note, setting path to path = ‘/../’ is my work-around for a script that is mapped to rather than ‘/some_POST_handling_script.rb’

#Juan Vazquez ->
require 'net/http'
require 'net/https'
http ='', 443)
http.use_ssl = true
#path(a.k.a) ->'
path = '/some_POST_handling_script.rb'
data = 'badguy=Gargamel'

headers = {'Content-Type'=> 'application/x-www-form-urlencoded'}

resp, data =, data, headers)

puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data

Recursive Directory Search with Ruby and Groovy

A while back I was bored and decided I need to brush up on my Ruby chops. I had been wanting to play with threads for quite some time and couldn’t think of anything that would be a fun project to do…until this crazy idea hit me.  Wouldn’t it be cool if could generate multiple threads to search different servers for any file of my choosing?” The code I wrote doesn’t directly do this, but with some minor tweaks it could be done.

I took that idea and ran with it using Ruby. After I finished coding, I thought I would try writing it from scratch using my second favorite language, Groovy (Ruby is my first).  I have to admit, writing the Groovy code was more intuitive because of the baked in file/directory iterators. I refactored my Ruby code a few times and ended up using the find module to maximize performance. Below is the code, and as always, I am open to suggestions on other ways of doing it 😀

Ruby code

#  Juan Vazquez
require 'find'
class DirectoryWizard
  attr_accessor :root_dir,:exts, :thread_cnt, :thread_tracker, :count
  #initialize with a root , and file extensions
  def initialize(root, t_count,*extensions)
    @root_dir, @exts, @thread_cnt , @thread_tracker, @count = root, extensions, t_count, [], 0

  def start_looking
      puts Dir.entries(@root_dir).select{|dir_item| is_in_ext(dir_item) }
      list_dirs(@root_dir).each do|di|
        @thread_tracker <<{|directory| 
                                             recursive_file_search(directory) }
        wait_for_running_threads  if(@thread_tracker.size > @thread_cnt)
    rescue Exception => e; puts e;
  def recursive_file_search(directory)
       puts dir_item

    #return array of immediate subdirectories excluding . and ..
  def list_dirs(directory)
   Dir.entries(directory).select{|fh|(!is_p_c_directory?(fh) && 

  #return an array of all file/directories excluding '.' and '..'
  def list_contents(directory)
    Dir.entries(directory).delete_if{|x| is_p_c_directory?(x)}

  #is Parent or Current Directory
  def is_p_c_directory?(filename);(filename =="." || filename == "..");end
#return an array of files that match ext
  def is_in_ext(dir_item); @exts.detect{|ext| dir_item.match(ext)}; end
 def wait_for_running_threads
end #end class



puts "Done with Program count is #{t.count}"

Groovy Code

import java.util.regex.*;
class DirWiz{
   def root_dir, exts, thread_max_cnt, thread_tracker, count

   public DirWiz(String basedir, int t_count, List extensions){
        this.root_dir = basedir
        this.exts = compile_regex(extensions)
        this.thread_max_cnt = t_count
        this.thread_tracker = []
    def start_looking(){
          def dir = new File(this.root_dir)
          //recursively search directories
           dir.eachDir{ subDir->
            //thread it off
           if(this.thread_tracker.size() > this.thread_max_cnt){
           this.thread_tracker << Thread.start{
                 subDir.eachFileRecurse{ fh -> 
      }catch(Exception e){
        println("error ${e}")
   def print_if_match(String file){this.exts.each{ext->
   def check_using_compiled_regex(String file){
	def var = this.exts.find{it.matcher(file).matches()}
    }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   def check_for_files(String dir){
      try{ new File(dir).eachFile{ file ->
      }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   def compile_regex(List list){
    List ret_list=[]
    list.each{ ret_list <<    Pattern.compile(it,Pattern.CASE_INSENSITIVE)}
    return ret_list

def t = new DirWiz('c:\\',16,[".*\\.jpg.*"])//look for jpegs
//def t = new DirWiz('\\\\server\\dir\\',16,["filname"])

println("Done with the program total number of files is ${t.count}")



Proxy/ReverseProxy and Apache2

I recently configured Apache2 to be a ReverseProxy/Proxy and thought I would share my experiences while it was still fresh. Having never configured any kind of proxy, I found this webpage very informative. The scenario I would like to use for my example is that I have three internal web servers called

Site Local IP Remote IP Port 80 80 80

Alright…pretty straight forward right? If you are in a situation that I was when I started, you haven’t done much more than install apache from source and added a few modules here and there occasionally. The way I solved the problem was to create name-based virtual host for each of the servers.
our example would look like

#you can listen on specific ports for requests if you like
#I use the below statement to listen on 80 for all requests
Listen *:80
#Because we have multiple names mapped to same ip

<VirtualHost >
ProxyRequests Off
ProxyPass /
ProxyReverse /
ProxyPreserveHost On
ErrorLog reallycoolsite_error_log
CustomLog reallycoolsite_access_logs
</VirtualHost >

<VirtualHost >
ProxyRequests Off
ProxyPass /
ProxyReverse /
ProxyPreserveHost On
ErrorLog justcoolsite_error_log
CustomLog justcoolsite_access_logs
</VirtualHost >

<VirtualHost >
ProxyRequests Off
ProxyPass /
ProxyReverse /
ProxyPreserveHost On
ErrorLog reallylamesite_error_log
CustomLog reallylamesite_access_logs
</VirtualHost >

If you receive errors during the communication of your proxy and your server, it may be a good idea to investigate if you have an http protocol error discussed at the bottom of this page
The following two lines are pulled from the reference and fixed a problem I had with one of my IIS servers using SSL(for more info about the issue, go here

SetEnv force-proxy-request-1.0 1
SetEnv proxy-nokeepalive 1

My apache configuration file(httpd.conf) was the file I used to edit my settings.. Your file may be different depending on how new your apache version is. I found that some implementations called the configuration file apache.conf…. I hope this blog entry is helpful you, Happy Configuring!

Rotating Java Images

I am working on a swing flickr app and thought I would share some code to help those that are new to java gui programming( like me) and get them on their way to making their killer application.

I’ll start off with my first problem,  “How do I show an Image?” After looking through Java forums and going through my Java books, I settled on using Image Icons in JLabels. The next thing I wanted to do was rotate the image 90 degrees. I used Java’s Graphics class to accomplish this. The following groovy code loads 100 JLabels containing a JPEG of Pixar’s Wall-e that I had in the same directory rotated 90 degrees.

import java.awt.image.BufferedImage
import javax.swing.*
import java.awt.*;
import java.util.*;
import java.awt.image.AffineTransformOp
import java.awt.geom.AffineTransform

class ImageButton extends JLabel{
	ImageIcon picture

public ImageButton(ImageIcon icon){
	this.setPreferredSize(new Dimension(120,100))

public void rotateImage( int angle) {
	int w = this.picture.getImage().getWidth()
	int h = this.picture.getImage().getHeight()
	BufferedImage bi = new BufferedImage(w,h,
	Graphics bg = bi.createGraphics();
	bg.rotate(Math.toRadians(angle), w/2, h/2);
	bg.drawImage(this.picture.getImage(),0,0,w, h,
			0,0,w, h, null);

	bg.dispose()//cleans up resources
	this.setIcon(new ImageIcon(bi))
	this.setPreferredSize(new Dimension(this.picture.getIconHeight(),

JFrame f= new JFrame()
JPanel panel=new JPanel();
def img= new ImageIcon("walle.jpg")
	def btn=new ImageButton(new ImageIcon(img.getImage()
	btn.rotateImage(90)//rotate the image now
	println i




My first few attempts at the code gave me out of memory Heap errors. I unknowingly had BufferedImage references hanging around.  Once I realized this, I cleaned up my code and remembered to call dispose() on the graphics bg object and everything came together quite nicely.

BarCamp Omaha

I have just been informed/invited to Omaha’s BarCamp! According to the site, this is a “unconference born from the desire for people to share and learn in an open environment.”

The list of topics that have been submitted thus far are already enough to get any developer’s inner geek super-charged. At this point I am not sure what I will talk about, but here are a few ideas.

  1. uploading/updating multiple models in one form (ROR)
  2. Groovy and flickr
  3. Action Script 3 concepts
  4. Linux Administration
  5. Setting up Twiki

Any suggestions or votes on what I could bring to the BarCamp would be awesome. If you can make it, I suggest checking this event out! After all, you don’t want to be sitting there listening to you fellow IT buddies raving about the great time they had learning at BarCamp…right?

File I/O Part 1

I love to learn and try new languages. Not only is learning a new language fun, many times it teaches me something new about a language that I am already familiar with. The only problem that I have with learning so many languages, is keeping them straight. I decided that I would take a few of the dynamic languages I use most often and compile a list of how to handle File I/O with each of them. If you have a Dynamic language(part 2 of this post will be on static languages) not represented below or have another method of File I/O with the represented languages, please add to the list with its respective File I/O code:D
Without further ado…

//Groovy open file for writing
def target ="filename"
File wf= new File(target)
wf.write( "I am in your file eating your space" )

//Groovy one liner
new File('filename.txt').text = 'First line of text!'

//Groovy open file for appending
def target ="filename"
File af= new File(target)
af.append("I have all of your base")

//Groovy read each line in file
new File("filename").eachLine{line-> println line}

//Groovy read whole document and put into List

List lines = new File("filename").readLines()
//lines contains two lines that we need
println "first line  $lines[0]"
println "second line $lines[1]"

//Groovy reading one line
File rf= new File("filename") //open for reading
//read first line, trim, assign to tmp
rf.withReader { line ->tmp = line.readLine().trim()}

//Groovy test if file exists
File src = new File(srcFile)
if (src.exists() ){ println "I exist"}
else{println "I don't exist"}

#Ruby openfile for reading
fh =, "r")  # open file "path" for reading only

#Ruby open file for writing
fout   =, "w")  # open file "path" for writing only
fout.puts "Up, Up, Down, Down, Left, Right, Left, Right, B, A, Select, Start"

#Ruby open file for apending
fa.puts "I am at the end of file"

#Ruby read eachline in a file"file").each { |line| p line}

#Ruby read entire file to string
fh =
str =

#Ruby read entire file into array(each line is an element in the array)
fh =
str = fh.readlines

#Python Write a file
fout = open("DeletMe.txt", "w")
fout.write("Writing to fout\nCheck it out!")

#Python Read an entire file
fin = open("ReadingTest.txt", "r")
fin_text =
print fin_text

#Python read entire file into list
fin = open("ReadingTest.txt", "r")
txt= fin.readlines()
print txt[0]

#Python append to a file
fh= open ( 'DeleteMe.txt', 'a' )
fh.write ( '\n\n\nBottom line.' )

#Perl reading a file
open(FILE,  '<', $file) or die "Can't read $file: $!\n";
print ;

#Perl append to a file
open(FILE, '>>', $file) or    die "Can't append to $file: $!\n";
print FILE "text";

#Perl read and write to a file
#+< allows reading and writing, and keeps the data that was
#already in the file.  open() will fail if file doesn't exist.
open(FILE, "+<$file" ) or die ("Can't  read|write: $file\n");

#Perl read and write to a file
#+>allows writing and reading, but replaces/overwrites the
#data in the file if the file exists. Creates it if it doesn't exist.
open(FILE, "+>$file" ) or die ("Can't write or read:$file \n");


PHP code doesn’t display properly within WordPress, so here is an image of the code

PHP File I/O

Handling Ruby’s String.each_char Iterator

Ahh the joys of iterators. I can’t say enough about how much they make my life easier. They are just so darn handy. Life was good in my Ruby world until I needed to iterate through the characters in a string. Thinking to myself, “there has got to be a method that does this,” I looked up Ruby’s String class and saw just what the doctor ordered… each_char.

Feeling pretty proud that my favorite language had this baked right in, I was only to happy to inject it into my code and test it out. That is until I recieved the dreaded NoMethodError: undefined method `each_char’ . Eeek, what did I do wrong? Did I mispell the method…..Nope, did I call it correctly…..Yep. Well, what the heck is going on?

After multiple attempts to find the answer on Google, I finally posted my problem to the ruby-talk group. I was told that the Ruby 1.8 String implementation that I was using only understood bytes and that I could use require ‘jcode’ to get the iterator to work the way I wanted. I did some looking around and I am not sure this is a great solution, after all, I could have easily used the each_byte{|f| f.chr} to iterate through and convert accordingly. I don’t understand why something that is documented as part of the class, does not work.

It would really help if there was an easy to search area on the net dedicated to language quirks for people trying to get a better grasp of their programming language of choice. Maybe that will be my next ROR project.

As it turns out, my Ruby 1.8.7 installation on my Fedora core 9 works as advertised.

su vs. “su -” The Mystery Revealed

Inquiring minds want to know, what is this su - and why is it different than su? Well, if you are like me, you didn’t even know that su - existed. I ran into this problem when I was trying to add a new user to a new Linux machine. Remote root login was disabled(for obvious reasons:D) and I was logged in with my regular non-privileged user account. Well, normally the story goes like this…

  1. su
  2. Authenticate
  3. useradd account
  4. set password
  5. log out of privileged account
  6. Take coffee break from all the hard work and call it a day

No so today:( . When I attempted to run step three(useradd), I received a command not found error. “That’s weird” I thought. How could a machine not have this basic command. I looked in the bin directory to see if it was some kind of path error I was having. Thinking that this was the case, I was shocked to see that none of the user commands(adduser, usermod, deluser) where there.

After a few minutes of scratching my head, I asked someone more versed in Linux than I what they thought. After walking through each of the steps I had taken, my mistake was easily spotted. I hadn’t added the ‘-‘ to the su command. Thinking that the explanation was weird, I checked with google for the su - command. Sure enough, the link to Wikipedia had this to say about it,

Optionally, you can use a hyphen with su to invoke a login shell and assume the target user’s complete user environment:

I am glad I had someone to point this out to me… It could have been a longer and very frustrating ordeal. It was also a lesson for me to refer more to the man pages(it had the answer there too). I hope this blog entry helps someone else who is confronted with this situation.

Adding Functionality to Ruby Strings

Ok, here is the scoop. I was working on a project using Ruby and needed to grab three characters from a string skipping one character in between.

ex –>  “123456789”    would become 234 and 567

I thought this would be a great opportunity to try out blocks in Ruby and test open classes

class String
   def blocker(sizeOfGroup,offset)
        break if val.to_s.length < 1
        yield  self.slice!(0..(sizeOfGroup.abs-1))

here is the code I used to test with

string = "12345678910" 
string.blocker(3,-1){|v| ary.push(v)}
ary.each{|i|puts i}
puts "her is ary "+ary.inspect 

And this is the result.

>>> test.rb

her is ary ["234", "678", "10"]

This was definitely a fun experiment and I can't wait to try out more stuff. If you haven't played around with blocks, give it a just might like it.