Tuesday, October 21, 2008

6 Simple steps to add reCaptcha (Human detector / pod stopper) to your rails application or Radiant

During development of my company's website www.espace.com.eg and after the launch of our all new technology Neverblock our blogs received loads of comments and ofcourse..loads of spam!

I found a marvelous rock-solid solution using reCaptcha plugin (thanks to guys at ambethia and to the modification that my friend & colleague humanzz has done.). Using the recaptcha plugin is so trivial and simple, it is explained in humanzz's & ambethia's pages, but the trick is in installing it in radiant applications.

Just follow the steps and you'll do great, just like the integration in the blogs of www.espace.com.eg.

Step 1: Register in the reCaptcha site, provide your website URL and get the public and private reCaptcha keys.

Step 2: Open your radiant project and add these three lines in the config.after_initialize block to be as follows:

config.after_initialize do
Ambethia::ReCaptcha.enabled = true
Ambethia::ReCaptcha.public_key = 'abcdefghij.....'
Ambethia::ReCaptcha.private_key = '12345.........'
end

and put the keys you got respectively.

Step 3: Download the reCaptcha plugin modified from humanzz's account at gitHub and copy-paste it in the /vendor/plugins folder in your radiant applicationand name the folder "recaptcha or whatver".

Step 4: In your /extensions/comments/app/comments_controller.rb file (or whatever applicable to your case in radiant project) add the check for the validity of the reCaptcha to verify that the poster is a human not a pod

def create
----- bla bla bla
----- bla bla bla
----- bla bla bla

if verify_recaptcha(comment)
comment.save!
else
----- Some more bla bla bla but raising error!
end


Step 5: Now you need to display the recaptcha box, and as you know (one who use radiant often!) that we can't put ruby code in the radiant admin pages, we use tags instead; so we will create our own reCaptcha tag.
Open the tag file (comment_tags.rb in this extension or case) and create a small class in the CommentTags module

module CommentTags
class Recaptcha_Generator
include Ambethia::ReCaptcha::Helper
end


Now you can create the tag by adding this to the same file:

tag "recaptcha" do |recaptcha|
if Ambethia::ReCaptcha.enabled
Recaptcha_Generator.new.recaptcha_tags()
end
end



Step 6: In your radiant admin in the comment form now add this line to submit with the comment parameters,

<r:recaptcha/>


you'll find the recaptcha box appearing now before your eyes!

Bonus Step:
If an error appeared stating you have problems with session error,open the recaptcha.rb file in the plugin in the lib folder and modify

error = options[:error] ||= session[:recaptcha_error]


to be:

error = "You are not human!" #options[:error] ||= session[:recaptcha_error]


Any questions don't hesitate to ask!

Monday, September 29, 2008

6 Simple steps to create a smooth light image rotator in Javascript

While building the new version of the website of the company am working in -eSpace technologies-
I came to a need to create an image rotator in javascript to rotate the images of us working in the company (you can check it for your self in the footer of www.espace.com.eg).

I simply used the scriptaculous library to add the fade-in fade-out effect on the pictures.But I had some major problems where the pictures enters in an infinite loop of continuous loading which seriously kills the website especially if the size of the pics is large.

So I came up with a solution in 6 simple steps to overcome those shortcomings as follows:

Step1:
Assemble all your photos you wanna rotate in a folder and number them from 1 to n (where n is total number of photos, in our example let it be 5) and name the folder any name ex."rotating_photos".

Step2
include the 2 files "prototype.js" and "scriptaculous.js" in your folder, and include their names in your HTML.
You can download them from http://script.aculo.us/downloads as a whole package.

Step3
In your HTML code replace:

<body>


by:

<body onload="photoGallery();">


The use of this line is to call the javascript function of rotating to initiate the rotating sequence.

Step4
Add this javascript lines to your HTML file or you can put it in a separate file and include it to your HTML file as you regularly do.
var turn = 0 ;
var r=2;

function hideAll(which)
{
if(which==1)
for(i=0 ;i<$('in_1').childNodes.length; i++)
$('in_1').childNodes[i].style.display = "none" ;
else
for(i=0 ;i<$('in_2').childNodes.length; i++)
$('in_2').childNodes[i].style.display = "none" ;
}
function photoGallery()
{
src = "rotating_photos/"+r+".jpg" ;
id = "pic_"+r ;

found=false;
for(i=0 ;i<$('in_2').childNodes.length; i++)
{
if($('in_2').childNodes[i].id==id)
{
found = true ;
break;
}
}
for(i=0 ;i<$('in_1').childNodes.length; i++)
{
if($('in_1').childNodes[i].id==id)
{
found = true ;
break;
}
}

if(turn==0){
if(found==false)
{
img = document.createElement("img");
img.src = src ;
img.id = id ;
$('in_2').appendChild(img);
hideAll(2) ;
$(id).show() ;
}
else{
hideAll(2) ;
$('in_2').appendChild( $(id) ) ;
$(id).show() ;
}
new Effect.Fade('in_1') ;
new Effect.Appear('in_2', { queue: 'end' }) ;
turn =1;
}
else{
if(found==false)
{
img = document.createElement("img");
img.src = src ;
img.id = id ;
$('in_1').appendChild(img);
hideAll(1) ;
$(id).show() ;
}
else{
hideAll(1) ;
$('in_1').appendChild( $(id) ) ;
$(id).show() ;
}
new Effect.Fade('in_2') ;
new Effect.Appear('in_1', { queue: 'end' }) ;
turn =0;
}

r+=1;
if(r>15) r=1;

var s=setTimeout("photoGallery()",3000);
}


Step5
<div id="photo-gallery">
<div id="in_1"><img src="rotating_photos/1.jpg" /></div>
<div id="in_2" style="display:none;"><img src="rotating_photos/2.jpg" /></div>
</div>


Step6
If you want to adjust the timing of rotating you can change the number 3000 in the last sentence in the function "photoGallery()" to be any number in milliseconds.

Sunday, July 20, 2008

10 Simple Steps to create taggable extensions in Radiant CMS under Rails 2.1

During my attempts to add a “vacancies” extension in Radiant 0.6.7 I faced several problems, as the tutorial on the website http://wiki.radiantcms.org/Creating_Radiant_Extensions is outdated and applicable not on rails 2.1, after solving those problems I decided to write a blog on how to deal with them step by step through an example creating a “vacancies” tutorial.

First, refer to the website mentioned above to do all the regular steps starting from installing rails till creating our first Radiant application. Next it is required to start generating an extension that enables the admin to easily add/remove/edit job vacancies through a wizard and to appear on the website itself dynamically.

Step 1: A new extension named vacancies will be created through the command

script/generate extension vacancies


Notice that the bold word could be replaced by the name of your new extension, but as for our case its name is vacancies. The following output should be seen:

create vendor/extensions/vacancies/app/controllers
create vendor/extensions/vacancies/app/helpers
create vendor/extensions/vacancies/app/models
create vendor/extensions/vacancies/app/views
create vendor/extensions/vacancies/db/migrate
create vendor/extensions/vacancies/lib/tasks
create vendor/extensions/vacancies/README
create vendor/extensions/vacancies/vacancies_extension.rb
create vendor/extensions/vacancies/lib/tasks/vacancies_extension_tasks.rake
create vendor/extensions/vacancies/spec/controllers
create vendor/extensions/vacancies/spec/models
create vendor/extensions/vacancies/spec/views
create vendor/extensions/vacancies/spec/helpers
create vendor/extensions/vacancies/Rakefile
create vendor/extensions/vacancies/spec/spec_helper.rb
create vendor/extensions/vacancies/spec/spec.opts


Now you can see that a folder named vacancies is created under vendor/extensions this folder contains all the details of such extension (as a separate rails application with its separate apps, model, controller, views...etc).

Step 2: If you are operating from UNIX environment you now have to change the mode of the folder to be enabled for altering, so go to the vendor/extensions directory through the shell and type in

chmod 777 vacancies -R



Step 3: Open the vacancies_extension.rb file in the vacancies folder and change its contents to be:

class VacanciesExtension < Radiant::Extension
version "1.0"
description "Allows you to add a job-vacancies facility to your Web site."
url "http://yourwebsite.com/vacancies"

define_routes do |map|
map.namespace :admin do |admin|
# Directs /admin/vacancies/* to Admin::VacanciesController (/admin/vacancies_controller.rb)
admin.resources :vacancies
end
end

def activate
admin.tabs.add "Vacancies", "/admin/vacancies", :before => "Layouts"
Page.send :include, VacanciesTags
end

def deactivate
admin.tabs.remove "Vacancies"
end
end


Step 4:
Now start the server by typing the command:

script/server -e development

Open the browser on the URL http://localhost:3000 something like that will appear when you choose the extensions link on the top right corner.

Step 5: Next, we will create the model to the extension by typing the command:

script/generate extension_model Vacancies admin/Vacancy

and the output would be
exists app/models/admin
exists spec/models/admin
create app/models/admin/vacancy.rb
create spec/models/admin/vacancy_spec.rb
exists db/migrate
create db/migrate/001_create_admin_vacancies.rb

If you look at the output of the command, you will notice that it generated:
the file for
  • The Vacancy model
  • The rspec test
  • The migration
  • The migration file would be like this:


class CreateVacancies < ActiveRecord::Migration
def self.up
create_table :vacancies do |t|
t.string :title
t.string :ref
t.text :description

t.timestamps
end
end

def self.down
drop_table :vacancies
end
end

Now run the migration by typing:

rake development db:migrate:extensions


Step 6: Now we will create the controller of the extension by the command:

script/generate extension_controller Vacancies admin/vacancies

The output would be like this:

create app/controllers/admin
create app/helpers/admin
create app/views/admin/vacancies
create spec/controllers/admin
create spec/helpers/admin
create spec/views/admin/vacancies
create spec/controllers/admin/vacancies_controller_spec.rb
create spec/helpers/admin/vacancies_helper_spec.rb
create app/controllers/admin/vacancies_controller.rb
create app/helpers/admin/vacancies_helper.rb
The reason behind admin/ part is that the vacancies is managed via the admin.
If you look at the output of the command, you will notice that it generated:
The Admin::LinksController
The functional test for the controller
The folder for the link controller views

Step 7: Now we will create the views,
create file index.html.erb in views/admin/vacancies folder and in it write:

<h1>Listing Vacancies</h1>
<table>
<tr>
<th>Title</th>
<th>Ref.</th>
<th>Description</th>
</tr>

<% for vacancy in @vacancies %>
<tr>
<td><%=h vacancy.title %></td>
<td><%=h vacancy.ref %></td>
<td><%=h vacancy.description %></td>
<td><%= link_to 'Show', admin_vacancy_path(vacancy.id) %></td>
<td><%= link_to 'Edit', edit_admin_vacancy_path(vacancy) %></td>
<td><%= link_to 'Destroy', admin_vacancy_path(vacancy.id), :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>

<br />

<%= link_to 'New Vacancy', new_admin_vacancy_path %>

create file new.html.erb in views/admin/vacancies folder and in it write:

<h1>New Vacancy</h1>

<%= error_messages_for :vacancy %>

<% form_for(@vacancy) do |f| %>
<p>
<b>Title</b><br />
<%= f.text_field :title %>
</p>

<p>
<b>Ref.</b><br />
<%= f.text_field :ref %>
</p>

<p>
<b>Description</b><br />
<%= f.text_area :description %>
</p>

<p>
<%= f.submit "Create" %>
</p>
<% end %>

<%= link_to 'Back', admin_vacancies_path %>

create file edit.html.erb in views/admin/vacancies folder and in it write:

<h1>Editing Vacancy</h1>

<%= error_messages_for :vacancy %>

<% form_for(@vacancy) do |f| %>
<p>
<b>Title</b><br />
<%= f.text_field :title %>
</p>

<p>
<b>Ref.</b><br />
<%= f.text_field :ref %>
</p>

<p>
<b>Description</b><br />
<%= f.text_area :description %>
</p>

<p>
<%= f.submit "Update" %>
</p>
<% end %>

<%= link_to 'Show', @vacancy %> |
<%= link_to 'Back', admin_vacancies_path %>

create file show.html.erb in views/admin/vacancies folder and in it write:

<p>
<b>Title:</b>
<%=h @vacancy.title %>
</p>

<p>
<b>Ref.:</b>
<%=h @vacancy.ref %>
</p>

<p>
<b>Description:</b>
<%=h @vacancy.description %>
</p>


<%= link_to 'Edit', edit_admin_vacancy_path(@vacancy) %> |
<%= link_to 'Back', admin_vacancies_path %>

Step 8: Modify the controller to display in view by putting:

# GET /vacancies
# GET /vacancies.xml
def index
@vacancies = Admin::Vacancy.find(:all)

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @vacancies }
end
end

# GET /vacancies/1
# GET /vacancies/1.xml
def show
@vacancy = Admin::Vacancy.find(params[:id])

respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @vacancy }
end
end

# GET /vacancies/new
# GET /vacancies/new.xml
def new
@vacancy = Admin::Vacancy.new

respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @vacancy }
end
end

# GET /vacancies/1/edit
def edit
@vacancy = Admin::Vacancy.find(params[:id])
end

# POST / vacancies
# POST /vacancies .xml
def create
@vacancy = Admin::Vacancy.new(params[:admin_vacancy])

respond_to do |format|
if @vacancy.save
flash[:notice] = 'Vacancy was successfully created.'
format.html { redirect_to(@vacancy) }
format.xml { render :xml => @vacancy, :status => :created, :location => @vacancy }
else
format.html { render :action => "new" }
format.xml { render :xml => @vacancy.errors, :status => :unprocessable_entity }
end
end
end

# PUT /vacancies/1
# PUT /vacancies/1.xml
def update
@vacancy = Admin::Vacancy.find(params[:id])

respond_to do |format|
if @vacancy .update_attributes(params[:admin_vacancy])
flash[:notice] = 'Vacancy was successfully updated.'
format.html { redirect_to(@vacancy) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @vacancy.errors, :status => :unprocessable_entity }
end
end
end

# DELETE /vacancies/1
# DELETE /vacancies/1.xml
def destroy
@vacancy = Admin::Vacancy.find(params[:id])
@vacancy.destroy

respond_to do |format|
format.html { redirect_to(admin_vacancies_url) }
format.xml { head :ok }
end
end


Step 9: Restart the server, add vacancies, edit, show and delete them by accessing admin and clicking on the vacancies tab.
Step 10: Now it's time to create custom tags, create a new file in the “app/models” directory of your extension called “vacancies_tags.rb” and add the following code:

module VacanciesTags
include Radiant::Taggable

tag 'vacancies' do |tag|
tag.expand
end

tag 'vacancies:each' do |tag|
result = []
Admin::Vacancy.find(:all, :order => 'title ASC').each do |vacancy|
tag.locals.vacancy = vacancy
result << tag.expand
end
result
end

tag 'vacancies:each:vacancy' do |tag|
vacancy = tag.locals.vacancy
%{#{vacancy.title}-#{vacancy.ref}}
end
end

To activate the tags add this line to the activate method in vacancies_extension.rb file

Page.send :include, VacanciesTags


In the page or snippet or layout add those tags:

<ul>
<r:vacancies:each>
<li><r:vacancy/></li>
</r:vacancies:each>
</ul>

Thursday, February 21, 2008

Computers A.I vs. Human Genetics - A philosophic overview

Computers A.I vs. Human Genetics

Are we playing God?!

For as long as we have known, there has been a persisting question:

How do we, Humans, work?!

There have been many attempts by scientists, philosophers, biologists and even mathematicians to understand the entity of a human being, its instincts and its soul.

In the last few decades, with the continuous breakthroughs in the study of the brain, the neurological system and the birth of a new branch of science called genetics, many scientists went even further in assuming that the human being is more like a well built machine with a very complex circuit of neurons monitored and managed by the code embedded in the human DNA strand, this code is composed of 4 symbols (G, C, U, A) and the entire set of genes –called the human genome- is composed at just under 3 billion base pairs and about 20,000–25,000 genes which are considered as the blue-print to all cells of the body, how they replicate, produce proteins, interact…etc.

This sophisticated code may be the main reason and explanation of cell characteristics, malfunctions or even diseases, but what about feelings, morals, thoughts, dreams? Are they just chemical reactions and electric pulses that occur inside our brains to shape our mind, conscious and judgment?

During the last 50 years we have built faster, more powerful with enormous memory machines. We wrote programs, techniques and smart algorithms and the development is increasing tremendously. Now, the question is, would we, one day, be able to build a machine with the same complexity and power of the "human circuit"?

Further more, would it start living actually?....start thinking, feeling, interacting and even dreaming?

There is a rule in replication, if you wanted to replicate a thing you must know all about its properties, characteristics, functionality, its points of weakness and strength. For example, if you wanted to replicate a car you must know for certain its dimensions, weight, material of manufacture, max speed and performance; so that when you make one that resembles it.

Given that, to replicate the human brain, we must know all about it and its performance in particular.

Well, we DON'T!! , it was stated and proved that the human being only uses 10% of his brain power, what about the other 90%?

Have you ever been in a dangerous situation and suddenly out of no where you started to act with super-human abilities? For example, if you faced a lion or a fire, you'll find adrenaline pumping through your veins making you run at a speed that exceeds the fastest runner ever known, even if you can hardly walk in normal conditions!

There has been a great struggle in the search for increasing the abilities of the human being, knowing that his brain can be much more powerful, may be able to use Telepathy, Telekinesis...etc, but if the brain can be, theoretically, increased in power, what would be the problem?

Unfortunately the human being is more like a computer with very powerful software (mind) and a very weak hardware (body). For example the case of epilepsy, where the brain sends spikes of electric signals where the body can't handle and starts malfunctioning, ironically epilepsy might be accompanied with high degrees of intelligence!

What about machine intelligence? Is it possible? In my opinion we must define the concept of intelligence we are aiming at, I think that we haven't and will not reach any degree of intelligence known to man, but we are striving in another kind of intelligence booked only for machines. Unfortunately the two concepts of intelligence (either human or machine intelligence) are confused with each other as the definition is misleading, so I guess before starting to study artificial intelligence we must have solid contentment that a machine will not have a human intelligence and a human will never have a machine intelligence, at least that what I think. The reason behind my believe is that for machines we have only increased its information database and multiplying the size of its rule book, as I think intelligence is an answer of multi-variable equation that many of humans can't solve!


There are still some unanswered questions, here they are:

  • If the gene code manages the properties of the human being and his cells, does it control the feelings, the thoughts, and the attitude of a man?
  • In our search for the brain have we found out what was the mind?
  • If the programs and algorithms manage the actions of computers, do they, one day, be able to provide the machines with feelings and thoughts?
  • The most important question: If God blessed us with the ability to sense, feel, think, and dream with our continuous development in genetics and machine's artificial intelligence.........Are we playing God?!


Hany SalahEldeen