Showing posts with label J. Show all posts
Showing posts with label J. Show all posts

Monday, September 29, 2008

TinyMCE: enforce maxlength

TinyMce doesn't have support for maxlength, and putting maxlength in the textfield tag won't do anything either.

If you try to google for a solution, you might come across this site

Don't waste your time on it, because the solution is built with the old tinymce api, it wouldn't work. Instead, use the solution from this post.


J

RoR: attr_accessible with attachment_fu

If you try to use attr_accessible on any model with attachment_fu plugin,
you'll get an error.

This article explains why


J

Tuesday, September 23, 2008

Stack and Queue Implementation

Array in Ruby already has built in push and pop function you can use, but if you want to make it more strict and idiot proof, here's how you can implement it.

class Stack

def initialize
@stack = []
end

def push(x)
@stack.push(x)
end

def pop
@stack.pop unless is_empty?
end

def peek
@stack.last
end

def is_empty?
@stack.empty?
end

end

class Queue

def initialize
@queue = []
end

def enqueue(x)
@queue << x
end

def dequeue(x)
@queue.shift
end

def peek
@queue.first
end

def is_empty?
@queue.empty?
end

end


J

Fun with String

This is why Ruby is amazing :D

1. converting strings to numbers

"123".to_i => 123
Duh, everyone knows that

but how bout
"123stfu".to_i => 123

or

" 123stfu ".to_i => 123

you can even indicate the base of your conversion

"111".to_i(2) => 7 # treat it as a binary number
"111".to_i(8) => 73 # treat it as an octal

split a string and convert it to an interger

"123 456 789".split.map {|m| m.to_i} => [123, 456, 789]

2. Replacing text

we can implement the lame rot13 encryption scheme in one line :)

class String; def rot13; self.tr("A-Ma-mN-Zn-z", "N-Zn-zA-Ma-m");end;end

"Please hide this line".rot13 => "Cyrnfr uvqr guvf yvar"

3. Counting Characters

s1 = "abcabcabcde"
s1.count("c") => 3
s1.count("abc") => 9
s1.count(s1) => 11

count can handle negation

s1.count("^abc") => 2
s1.count("^a") => 8

and range of chars

s1.count("a-c") => 9
s1.count("^a-z") => 0

4. Reversing a String

Microsoft loves to ask interviewee to reverse the word order of a String during an interview, it takes around 15 - 20 lines to implement the function in Java or C++, but we can do it in one :)

phrase = "This is a joke"
phrase.split.reverse.join(" ") => "joke a is This"

so next time you goto an interview, asks if they'll let you do it in Ruby ;)

5. Removing Duplicate Characters

string = "aaaaaaaaaaaaaaaaaaa".squeeze => "a"
string = "aaaaaaaaaaaaaaaaaaB".squeeze => "aB"
string = "hehe....".squeeze(".") => "hehe."


J

List of reflective methods

I find the following commands very useful from time to time, but I kept forgetting their names. So I'm creating this post to help remind myself.

a.class
# returns the class of an object a

a.superclass
# returns the superclass of an object a

a.instance_of? A
# determines if a.class == A

a.is_a? A
#determines whether a is an instance of c, or of any of its subclass, or of any modules.

a.respond_to? :something
#determines if a has a public or protected method with the specified name.


J

Monday, September 22, 2008

Duck Typing and Type Checking

Consider the following example:

class A
attr_accessor :x

def initialize
@x = 0
end

def +(other)
a = A.new
a.x = @x + other.x
return a
end
end

class B
attr_accessor :x

def initialize
@x = 0
end
end

a = A.new
a.x = 10
b = B.new
b.x = 5
puts (a+b).x # this will return 15

Ruby is a very dynamic language, the addition function doesn't care if the argument passed in is of type A, as long as it looks and behaves like A. This is called duck typing, name after the phase "if it walks like a duck and quacks like a duck, it must be a duck!"

if you want to ensure the object passed into the + function has to have an x accessor, you can add this to def +(other)

raise "error" unless other.respond_to? :x

or if you want to ensure object passed into the + function has to be of class A, you can add this instead:

raise "error" unless other.is_a? A


J

Instance Variable

Java and C++ programmers are used to declaring their variables in a class, and they think they should do the same in Ruby. WRONG!

For example:

class Animal
@age = 0
@name = ""

def initialize(age, name)
@age = age
@name = name
end
end

In this example, two sets of @age, @name are created. When the initialize method is called, self holds an instance of the Animal class. But the code outside of that function are executed as part of the definition of the Animal class. When @age and @name are executed, it refers to the Animal class, not the object instance. Hence @age, @name inside the initialize function are different from the @age, @name on the outside.


J

Sunday, September 21, 2008

Variable Parameters

Sometimes we want a method that can take any number of parameters.
One way to do it is to pass in a hash, but this can be annoying. Another method is to put an * before the method's parameter. Within the body of the method, list will be treated as an array with 0 or more elements.

For example:

def average(*list)
x = 0
list.each {|l| x+= l}
l/list.size
end

irb>average 1,2,3,4,5,6,7,8,9
=> 5

J

Copying Objects

When you use =, clone, or dup to copy an object, only the object reference is copied,
not the referenced object itself (Shallow Copy).

In order to do a deep object copy, we can use the marshaling trick by dumping and
loading the object.

For example:

def deepcopy(something)
Marshal.load(Marshal.dump(something))
end

irb>b = "abcd"
=> "abcd"
irb>a = b
=> "abcd"
irb>a.upcase!
=>"ABCD"
irb>b
=>"ABCD" # see how b changes too
irb>b = deepcopy(a)
=>"ABCD"
irb>b.downcase!
=>"abcd"
irb>a
=>"ABCD" # a stayed the same this time

J

Saturday, September 20, 2008

More on enumerable

In ruby, I use .each alot to visit every elements in the array.
Did you know there's a .step(x) function that allows you to visit
every x th element in the array?

For example:

r = 0..3
r.each {|l| prints l.to_s + ' ' } # Prints 0 1 2 3

r.step(2) {|l| prints l.to_s + ' '} # Prints 0 2


J

Thousands Seperator

In ruby, underscore can be inserted into integer literals as thousands separator.

For example:

1_000 will be interpreted as 1000
1_000 + 1_000 will equal 2000
1_000_000_000 will be interpreted as 1 billion

the same technique works for float number as well

For example:

1_000.1 will be interpreted as 1000.1


J

Saturday, July 12, 2008

Uploading large file to nginx server

If you upload a file over 1M in size to a nginx server, you might get a "Request Entity Too Large" (413) error.
We can overcome this problem by specifying the client_max_body_size in nginx.conf

nano /etc/nginx/nginx.conf

under "server {"
add the following line

client_max_body_size 5M

this will change the max file size to 5M, you can change that number to whatever you like.


J

Thursday, May 22, 2008

Remote Host Identification has Changed

I just reinstalled our main server. When I try to ssh into it I got an error:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.

Please contact your system administrator.
Add correct host key in /home/user/.ssh/known_hosts to get rid of this message.
Offending key in /home/user/.ssh/known_hosts:1
RSA host key for ras.mydomain.com has changed and you have requested strict checking.
Host key verification failed.

-----------------------------------------------------------

The reason behind this is because your local computer still has the old RSA host key stored in /home/your_account/.ssh/known_hosts.

The easiest way to solve this problem is simply delete that file or you can delete the host entry in the file.


Joseph

Friday, May 2, 2008

VMware on Hardy

There is currently no vmware package for hardy (DAMNIT!!). So we gotta do it the hard way.

1. apt-get the following

sudo apt-get install build-essential linux-headers-`uname -r`
sudo apt-get install xinetd

2. download the vmware tarball

just goto the website, it's constantly changing so I wouldn't bother posting it.

3. Get your FREE registration number (this used to cost a fortune, lucky us)

http://register.vmware.com/content/registration.html

4. Extract the tarball somewhere and run it by doing

tar -zxvf xxx.tar.gz
go into the directory
sudo ./vmware-install.pl

5. Now it'll ask you bunch of questions, just keep pressing enter. After awhile, it'll start compiling and fail :)

6. This has something to do with hardy's kernel, but don't worry, there's a patch for it.

wget http://uruz.org/files/vmware-any-any-update-116.tgz
tar -xvzf vmware-any-any-update116.tgz
cd vmware-any-any-update116
sudo ./runme.pl

7. VMware should start compiling and asks you more questions after (just keep pressing enter)

8. Once you've configured your vmware server, you need to link up some libraries

sudo ln -sf /lib/libgcc_s.so.1 /usr/lib/vmware/lib/libgcc_s.so.1/libgcc_s.so.1
sudo ln -sf /usr/lib/libpng12.so.0 /usr/lib/vmware/lib/libpng12.so.0/libpng12.so.0

9. And that's it, you can launch it by typing vmware on your console


J

Monday, April 28, 2008

Hardy Heron Connection Problem

Just upgraded to Hardy two days ago. Is it nice? Yes. Is there any problems with it? Yes.

Installation was fast as usual, took around 20 mins. Video settings, sound card, network card ... are all setup and ready to go after the system rebooted itself. Firefox 3 looks better than ever, however, I can't seem to get a connection?!?

What's more weird is that I can actually goto google.com, but everything else will time out on me!
After hours of searching, some dude suggested that I should decrease the MTU (maximum transmission unit) from 1500 (standard for ethernet) to 1492 by typing the following command

sudo ifconfig eth0 mtu 1492

amazingly, my connection is back to normal! (if anyone know why that is, can you please educate me on this issue? I really like to know the reason behind this!)


J

Thursday, April 17, 2008

Responds_to_parent loc error

If the rjs inside your responds_to_parent block ended up removing the iframe from your html page, the loc variable will no longer be defined.

Besides having an ugly error message on your firebug console, it can actually cause problems for the javascripts on that page as well.

In order the get around this problem, you'll need to do the following patches:

in parent_selector_assertion.rb and responds_to_parent.rb

replace all occurrence of
(3 in parent_selector_assertion, 1 in responds_to_parent)
loc.replace('about:blank');

with
if (window.loc) { loc.replace('about:blank'); }
and that's it!


J

Monday, March 31, 2008

Ruby Exception Hiearchy

For those who wants a better understand of the exception hiearchy, here it is!

Exception
Errno
NoMemoryError
ScriptError
LoadError
NotImplementedError
SyntaxError
SignalException
Interrupt
StandardError
ArgumentError
IOError
EOFError
IndexError
LocalJumpError
NameError
NoMethodError
RangeError
FloatDomainError
RegexpError
RuntimeError
SecurityError
SystemCallError
SystemStackError
ThreadError
TypeError
ZeroDivisionError
SystemExit
SystemStackError

Cheers,

Joseph

Monday, March 17, 2008

Bugzilla Installation on Ubuntu

the installation guide on bugzilla's website scares me, you can easily spend over a day in order to get it up and running. Fortunately, that's not the case for ubuntu.

with the help of apt-get, we can easily cut it down to 15 mins

1. apt-get install mysql-server (if it's not already there)
2. then follow on screen instructions
3. mysql -u - root -p (we need to create a new user called bugzilla)
4. GRANT ALL PRIVILEGES ON *.* TO 'bugzilla'@'localhost' IDENTIFIED BY 'password';
5. \q
6. apt-get install bugzilla (we are half way done already lol)
7. follow on screen instructions

and you are done! goto http://yourserver/bugzilla and start using it.

the package we just installed is version 2.2, for those who want the latest and greatest, please keep reading, I need another 15 minutes of your time.

1. goto /var/www/ and wget the latest tarball from bugzilla
2. tar -zxvf the_file_you_just_downloaded.tar.gz
3. log back into mysql and create a 'bugs' account (step 3 and 4 from previous section)
4. cd into the newly extracted bugzilla folder
5. cp -pr ../bugzilla/data .
6. sudo ./checksetup.pl
7. sudo chmod -R 755 .
8. sudo chomd -R 755 /var/lib/bugzilla/data
9. open /etc/apache2/httpd.conf

add the following line to the bottom (if it's not there)

<Directory /var/www/bugzilla>
AddHandler cgi-script .cgi
Options +Indexes +ExecCGI
DirectoryIndex index.cgi
AllowOverride Limit
</Directory>
10. restart the server : sudo /etc/init.d/apache2 restart
11. rename the newly extracted folder to bugzilla
12. enjoy


J

Saturday, March 15, 2008

Postgres + Rails + Ubuntu Troubleshooting

Problem 1 - forgotten password for postgres

Solution - TOUGH! you gotta re-install, that's what happened to me

Problem 2 - sudo apt-get remove postgresql did not remove any of the configuration files

Solution - use apt-get purge postgresql instead, this applies to all other packages

Problem 3 - sudo apt-get purge postgresql did not remove all the associated files

Solution - use sudo apt-get purge postgresql* instead or you can run apt-get autoclean after

Problem 4 - postgres refuses connection, but I swear I entered the password correctly!!!

Solution - postgres is very protective, the account you are logging in must match your current linux account .

Problem 5 - But what if I want postgres to manage its own account?

Solution - edit /etc/postgresql/8.1/main/pg_hba.conf, look near the bottom of the file, modify "Unix domain Socket" to local all all md5, "IPv4 local connections" to host all all 127.0.0.1/32 md5

and don't forget to restart the server by doing /etc/init.d/postgres-8.2 restart

Problem 6 - I installed postgres-pr but rails can't connect to postgres and I tried installing the
regular postgres gem but it failed!

Solution - in order to install the postgres gem, make sure you have the libpq-dev gem installed first. (gem install libpq-dev). Try installing the postgres gem again, it should work!

Problem 7 - I want postgres to run on some other port, what can I do?

Solution - first edit the /etc/postgresql/8.2/main/postgresql.conf, change the port number there first (don't forget to restart the server) then you have to goto your rails directly and edit config/database.yml, add ":port [portnumber]" to all your environments.


J

Sunday, March 2, 2008

Mcolumn reference "id" is ambiguous

Today I tried to improve the performance of my action by doing just one db call through eager loading. For those who have no idea what it is, please read our previous post

http://twoblinddevs.blogspot.com/search?q=eager+loading

This is what I wanted to do

Person.find(:first, :include=>[ :person_info, :messages], :conditions=>["id = :user_id", { :user_id => session[:id]}] )

when I refreshed the browser, it shows me this error message - Mcolumn reference "id" is ambiguous.

The reason rails complain is because all three tables have an id column. In order to work around this problem, you simply have to change id = :user_id to people.id = :user_id


J