Category Archives: Programación

Fix python path: eggs before PYTHONPATH environment variable

Easy install has a very awful feature, whenever you install something as an egg it will prepend that path to your sys.path on runtime so your PYTHONPATH variable will be after all those eggs (which normally or at least for my way to work is completely fuck up).

To fix this locate the easy-install.pth file of your python installation ($ sudo locate easy-install.pth, in my case it was /usr/local/lib/python2.7/dist-packages/easy-install.pth) and remove all lines with import sys. And there you go, fixed.

error on super() method, TypeError: must be type, not classobj

If you have an error like:

    ...
    super(NuclearMissileHandler, self).__init__()
TypeError: must be type, not classobj

That means you have forgotten to inherit from object in the superclass/es.

Mental note: write something interesting in the fraking blog yo.

Create ruby/jruby bindings of C++/C with ffi

Let’s start with the basic. What are bindings? It’s a way to call low level libraries (normally in C or C++) from another language (high level one, like ruby, java or whatever). This simple step requires two important things: 1) first, to know how we should call the method itself and 2) second, how to map the type from the high level language to C primitives types. To accomplish this, we have what is called foreign function interface which trivialize this task.

In ruby/jruby world we are gonna need ffi gem (jruby also has a compatible ffi gem), besides that the most important part is to have a clear interface in C. You can do bindings for a C++ library if you create a C interface first (because the bindings between C++ and C are free, the compiler knows how to do it by itself). So let’s cut the crap and write some code

First our C++ library which can be this few lines or thousands:

class awesome_object {
  public:
    awesome_object(int a, int b) : a_(a), b_(b) {}
 
    int awesome_method() {
      return a_ + b_;
    }
 
  protected:
    int a_, b_;
}

Now the C bindings which will be our façade for our c++ library:

extern "C" {
  typedef awesome_object_p void *;
 
  awesome_object_p create_awesome_object(int a, int b) {
    return static_cast<void *>(new awesome_object(a, b));
  }
 
  void delete_pointer_to_awesome_object(awesome_object_p p) {
    delete static_cast<awesome_object *>(p);
  }
 
  int awesome_method(awesome_object_p p) {
    awesome_object o = *static_cast<awesome_object *>(p);
    return o.awesome_method();
  }
}

Now ruby code that use ffi gem to be able to call the methods defined in C:

require 'ffi'
 
module AwesomeObject
  include FFI
  extend FFI::Library
  ffi_lib "libawesome.so" # .dll if you are in windows, it doesn't matter the OS
  attach_function "delete_pointer_to_awesome_object", "delete_pointer_to_awesome_object", [:pointer], :void
  attach_function "awesome_method", "awesome_method", [:pointer], :int
  attach_function "create_awesome_object", "create_awesome_object", [:int, :int], :pointer
end

With this you can use your C++ library from ruby code (I’d recommend package everything as a gem) just like this:

class MyTest
  include AwesomeObject
  def test!
    object = create_awesome_object(11, 31)
    awesome_method object
    delete_pointer_to_awesome_object object
  end
end
MyTest.new.test!

So, if you have read until now, probably you just want something working, say no more. Download this tar.gz, and see all this by yourself. In the tar you have the code split into c/h cpp/hpp files as it should be, in the post I’ve put all together to simplify things. Just execute make test and if you have ruby, ffi gem and g++ installed on your system, you’ll see something like:

$ make test
g++ -g -Wall -fPIC -c awesome_object.cpp
g++ -g -Wall -fPIC -c awesome.c
g++ -g -Wall -fPIC -shared -o libawesome.so awesome.o awesome_object.o
ruby test.rb
42

Code Monkey like Fritos

Until now I’ve never heard about this song, about a code monkey, funny and nice at the same time. The same songwriter, Jonathan Coulton, has a lot more of similar (geek) songs. Awesome.

Code Monkey get up get coffee
Code Monkey go to job
Code Monkey have boring meeting with boring manager Rob
Rob say Code Monkey very diligent
but his output stink
his code not functional or elegant
what do Code Monkey think
Code Monkey think maybe manager want to write goddamn login page himself
Code Monkey not say it out loud
Code Monkey not crazy just proud

Code Monkey like Fritos
Code Monkey like Tab and Mountain Dew
Code Monkey very simple man
with big warm fuzzy secret heart
Code Monkey like you
Code Monkey like you

Code Monkey hang around at front desk
tell you sweater look nice
Code Monkey offer buy you soda
bring you cup bring you ice
you say no thank you for the soda cause
soda make you fat
anyway you busy with the telephone
no time for chat

Code Monkey have long walk back to cubicle
he sit down pretend to work
Code Monkey not thinking so straight
Code Monkey not feeling so great

Code Monkey like Fritos
Code Monkey like Tab and Mountain Dew
Code Monkey very simple man
with big warm fuzzy secret heart
Code Monkey like you
Code Monkey like you a lot

Code Monkey have every reason
to get out this place
Code Monkey just keep on working
to see your soft pretty face
Much rather wake up eat a coffee cake
Take bath, take nap
This job fulfilling in creative way
such a load of crap
Code Monkey think someday he have everything even pretty girl like you
Code Monkey just waiting for now
Code Monkey say someday, somehow

Code Monkey like Fritos
Code Monkey like Tab and Mountain Dew
Code Monkey very simple man
with big warm fuzzy secret heart
Code Monkey like you
Code Monkey like you

boost::asio, synchronous read with timeout

The boost::asio (which means asynchronous input/output) library, is quite powerful library for asynchronous i/o, but it could be a bit difficult at first to figure out how to do a normal synchronous read. So, as a reminder for my future-me, and for you, this snippet it’ll be very useful to accomplish that. Probably there will be another ways for doing that, but this is how I managed to do it:

using namespace boost::asio;
using namespace boost::system;
using boost::optional;
 
ip::tcp::socket _socket; // it could be another kind of socket, not only ip::tcp
 
/** 
 * Dumb function to be used as handler argument and save the error_code
 * into a pointer
 *
 * e.g.: boost::bind( &set_result, some_pointer, _1 )
 */
void set_result( optional<error_code>* a, error_code b ) 
{
  a->reset( b );
}
 
#define TIMEOUT 60
/**
 * it uses _socket 
 * if timeout happends throw a system_error exception
 */
template<typename MutableBufferSequence>
optional<error_code> read_with_timeout(
    const MutableBufferSequence& buffer
  ) throw( system_error )
{
  optional<error_code> timer_result;
  optional<error_code> read_result;
 
  deadline_timer timer( _socket.io_service() );
 
  timer.expires_from_now( seconds(TIMEOUT) );
  timer.async_wait( boost::bind(&set_result, &timer_result, _1) );
 
  boost::asio::async_read(
      _socket,
      buffer,
      boost::asio::transfer_at_least( buffer_size_helper(buffer) ),
      boost::bind( &set_result, &read_result, _1 )
    );
 
  _socket.io_service().reset();
 
  while ( _socket.io_service().run_one() )
  {
    if ( read_result )
    {
      timer.cancel();
    }
    else if ( timer_result )
    {
      _socket.cancel();
      throw system_error(
          error_code( errc::timed_out, get_generic_category() )            
        );
    }
  }
  return read_result;
}

I hope it will be useful, have fun.

How to know, in ruby, which methods have been added and by whom?

If you are not very careful, monkeypatching could be very harmful. One thing to remember is that you should never override a method to add funcionality, for those kind of thinks you must use alias chain method pattern, a safer way of doing that.

For the rest of the monkeypatching, i.e. add new methods, you could debug them really easy with something like this:

class Class
   def method_added(method_name)
      puts "#{method_name} added to #{self}, callstack:"
      puts caller.map{|line| "\t#{line}" }.join("\n")
   end
end

You can always add more code to filter by class or by method’s name. Let’s see an example:

$ more example.rb 
require 'date'
require 'time'
 
class Class
   def method_added(method_name)
      return if %w(method_added).include? method_name.to_s
      puts "#{method_name} added to #{self}, callstack:"
      puts caller.map{|line| "\t#{line}" }.join("\n")
   end
end
 
class Time
   def to_date
      Date.ordinal self.year, self.yday
   end
end
 
class Date
   def to_time
      Time.parse self.to_s
   end
end
 
raise "to_date not working" unless
   Time.now.to_date == Date.today
raise "to time not working" unless
   Time.now.to_date.to_time == Date.today.to_time

The output will be:

$ ruby example.rb 
to_date added to Time, callstack:
	example.rb:13
to_time added to Date, callstack:
	example.rb:19

Nice, isn’t it?. Remember to be carefull with your monkeypatching, with great power comes great responsibility, it’s just a tool, neither magic nor the panacea.