Feby Artandi

ROR Application for solved MARS ROVER PROBLEM

Posted by: febyartandi on: November 30, 2011

Download the app here:
https://github.com/febyartandi/mars-rover-ruby-with-webview

MARS HOVER PROBLEM
===================================

A squad of robotic rovers are to be landed by NASA on a plateau on Mars. This plateau, which is curiously rectangular, must be navigated by the rovers so that their on-board cameras can get a complete view of the surrounding terrain to send back to Earth.

A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.

In order to control a rover, NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.

Assume that the square directly North from (x, y) is (x, y+1).

INPUT:
The first line of input is the upper-right coordinates of the plateau, the lower-left coordinates are assumed to be 0,0.

The rest of the input is information pertaining to the rovers that have been deployed. Each rover has two lines of input. The first line gives the rover’s position, and the second line is a series of instructions telling the rover how to explore the plateau.

The position is made up of two integers and a letter separated by spaces, corresponding to the x and y co-ordinates and the rover’s orientation.

Each rover will be finished sequentially, which means that the second rover won’t start to move until the first one has finished moving.

OUTPUT
The output for each rover should be its final co-ordinates and heading.

INPUT AND OUTPUT

Test Input:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM

Expected Output:
1 3 N
5 1 E

Hi,

Today I am found some interesting case in twitter api search using geocode params.
When I call:

http://search.twitter.com/search.atom?geocode=40.757929%2C-73.985506%2C200km

it’s returned
….
Sorry, your query is too complex. Please reduce complexity and try again.
….

Strange,.because This call working some days ago.
And I spend some minutes and found that we can’t request more than 160km
This the working call:

http://search.twitter.com/search.atom?geocode=40.757929%2C-73.985506%2C160km

Delete all .svn files in one directory

Posted by: febyartandi on: February 10, 2010

Hi,

This is linux command to delete/clean .svn files from one directory. This usually used if you have one folder in old project and want to copy-paste into new project or new svn repository.

This the command in terminal:

find . -name “.svn” -exec rm -rf {} \;

Hope this help :-)

Hi,

If you need a sample rails application or maybe you’re starting a new fresh project, you doesnt need create it from a zero. You can use and edit my scratch application. This application includes
- signup
- login
- activation ( via email )
- forgot password ( send to email )
- edit profile
- create member area
- simple layout for front end and member ( include basic css )
- script to feeds table countries

To run application, Please Follow this steps:

Checkout app

git clone git@github.com:febyartandi/rails_2_scratch_app.git

or

svn co http://railsusersystem.unfuddle.com/svn/railsusersystem_rus
Username: guest
password: N2hJQN

Change configuration

- change configuration for database myql in config/database.yml with yours

- change google account for sending email in config/application.yml
smtp_user_name: yourgmailaccount
smtp_password: yourgmailpassword

- rake db:create && rake db:migrate
- rake migration:populate
- ruby script/server

Hope this help people !!

How to use linkedin api – invite people by email in ruby on rails

Posted by: febyartandi on: January 24, 2010

Hi guys,

This is quick tutorial about linkedin api – invitation by people email to join your linkedin network.

We will use linkedinapi rails plugin ( Created by Dimas Priyanto and Me base on oauth rails plugin )

  • checkout plugin
    svn co http://linkedinapi.unfuddle.com/svn/linkedinapi_linkedinapi/ and copy to vendor/plugins
    username: guest, password: password
  • run ruby script/console
  • initialize your linkedin api key and secret key
>> linkedin_api_key = ” YOUR LINKEDIN API KEY”

>> secret_key = “YOUR LINKEDIN API SECRET”

  • setting your callback
>> callback_url = ‘http://localhost:3000/linkedin_callback’
  • create oauth object
>> oauth = LinkedIn::Oauth.new(linkedin_api_key, linkedin_secret)
  • request authorize url
>> oauth.request_token.authorize_url

=> “https://api.linkedin.com/uas/oauth/authorize?oauth_token=53bc5779-75fb-4a82-915c-a33dba1dddf2″

Open the link in your browser  as redirection url for user to do authorization process,
if user authorize it we will get params[:oauth_verifier] in our “callback_url”,
use it to authorize from request

for example:

http://localhost:3000/linkedin_callback?oauth_token=94145e28-2d4d-4d55-856d-c5e791334e09&oauth_verifier=00883

>> oauth_verifier = “00883″

  • authorize using oauth verifier and token
>> oauth.authorize_from_request(oauth.request_token.token, oauth.request_token.secret, oauth_verifier)
  • create linkedin api object
>> linkedin = LinkedIn::Base.new(oauth)
  • show your linkedin profile
>> linkedin.profile
“<?xml version=\”1.0\” encoding=\”UTF-8\” standalone=\”yes\”?>\n<person>\n  <first-name>Feby</first-name>\n  <last-name>Artandi</last-name>\n  <headline>Ruby on rails programmer</headline>\n  <site-standard-profile-request>\n    <url>http://www.linkedin.com/profile?viewProfile=&amp;key=30011332&amp;authToken=nM0a&amp;authType=name&amp;trk=api*a101208*</url>\n  </site-standard-profile-request>\n</person>\n”
“AAAAAA”
=> “<?xml version=\”1.0\” encoding=\”UTF-8\” standalone=\”yes\”?>\n<person>\n  <first-name>Feby</first-name>\n  <last-name>Artandi</last-name>\n  <headline>Ruby on rails programmer</headline>\n  <site-standard-profile-request>\n    <url>http://www.linkedin.com/profile?viewProfile=&amp;key=30011332&amp;authToken=nM0a&amp;authType=name&amp;trk=api*a101208*</url>\n  </site-standard-profile-request>\n</person>\n”
  • invite people by email, first name and last name
linkedin.invite_by_email(“feby@kiranatama.com”, “Feby”, “Artandi”)

That’s it, enjoy ! :)

Simple code to test twitter oauth with ruby on rails via web browser

Posted by: febyartandi on: January 14, 2010

Hi,

This is tutorial about implement twitter oauth in Ruby on Rails application using twitter_oauth gem.

You can see installation from http://github.com/moomerman/twitter_oauth/. The gem author show how to implement the oauth call in command prompt.

Now I’ll show you how to use the gem via web browser and save access key into database.

1. Create rails application ( if it’s your 1st rails project you should google about ruby on rails app )

2. Implement the restful authentication plugin ( see http://github.com/technoweenie/restful-authentication ) until you have user system.

3. Install the twitter_oauth gem http://github.com/moomerman/twitter_oauth/

4. Create migration

class CreateTwitterAccounts < ActiveRecord::Migration

  def self.up
    create_table :twitter_accounts do |t|
      t.integer :user_id
      t.string :token
      t.string :secret
      t.timestamps
    end
  end

  def self.down
    drop_table :twitter_accounts
  end
end

5. Edit user model, add this line

  has_one  :twitter_account, :dependent => :destroy

  def has_twitter_oauth?
    self.twitter_account and self.twitter_account.token and self.twitter_account.secret
  end

  def create_or_update_twitter_account_with_oauth_token(token, secret)
    twitter_account = self.twitter_account ? self.twitter_account : TwitterAccount.new(:user_id => self.id)
    twitter_account.token = token
    twitter_account.secret = secret
    twitter_account.save!
  end

6. Create and edit Model twitter_account ( ruby script/generate model twitter_account )
   Add this line: 

   belongs_to :user

7. Create try controller ( ruby script/generate controller try )
8 Edit try controller and copy-paste this:

   # require the gem twitter_oauth
   require 'twitter_oauth'
   # need user logged in
   before_filter :login_required

   #initialize your twitter key and secret ( you can get from here http://apiwiki.twitter.com/ )
   TWITTER_KEY = '83evR5lsb0E1gmvn0FXacQ'
   TWIITER_SECRET = 'REuY5OAS6EFXrC4KYCKYLX68qVBmx4lJshTZehIfI2M'

   # The url to back when user has authorize your app
   TWITTER_CALLBACK_URL = 'http://localhost:3000/try/callback'

    #index method
    # this method check if user has authorize your app
    # if no it'll show they link to authorize your app in their twitter account
    def index
      if !current_user.has_twitter_oauth?
        @T_OAUTH = TwitterOAuth::Client.new( :consumer_key => TWITTER_KEY, :consumer_secret => TWIITER_SECRET )
        @T_REQUEST_TOKEN = @T_OAUTH.request_token :o auth_callback => TWITTER_CALLBACK_URL
        @T_TOKEN = @T_REQUEST_TOKEN.token
        @T_SECRET = @T_REQUEST_TOKEN.secret
        @link = @T_REQUEST_TOKEN.authorize_url
        session['token' ] = @T_TOKEN
        session['secret'] = @T_SECRET
     end
  end

  # Method callback
  # this method will call after user authorize your app in twitter website
  # this method will authorize oauth token and verifier send from twitter and if success key and secret will stored in database
  def callback
    @T_OAUTH = TwitterOAuth::Client.new(:consumer_key => TWITTER_KEY, :consumer_secret => TWIITER_SECRET )
    @oauth_verifier = params[:oauth_verifier]
    access_token = @T_OAUTH.authorize(session['token'], session['secret'], :o auth_verifier => @oauth_verifier)
    if (@result = @T_OAUTH.authorized?)
      current_user.create_or_update_twitter_account_with_oauth_token(access_token.token, access_token.secret)
      session['token'] = nil
      session['secret'] = nil
      flash[:notice] = "Authorize complete"
    else
      flash[:notice] = "Authorize failed"
    end

    rescue
      flash[:notice] = "Authorize failed"
  end

  # method update status
  # this method is for sent tweet to your twitter
  def update_status
    if current_user.has_twitter_oauth?
      @T_OAUTH = TwitterOAuth::Client.new( :consumer_key => TWITTER_KEY,
      :consumer_secret => TWIITER_SECRET, :token => current_user.twitter_account.token,
      :secret => current_user.twitter_account.secret )

      if @T_OAUTH.authorized? and @T_OAUTH.update(params[:status])
        flash[:notice] = "Your tweet has been sent"
      else
        flash[:notice] = "Sorry ! Your tweet failed to sent, try later !"
      end
    else
      flash[:notice] = "You dont have twitter account with oauth token, please authorize myapp in your twitter !"
    end

   redirect_to :action => 'index' 

 end
9. Add file index.html.erb in app/views/try
    Copy - paste

    Test Twitter API

     <% if @link %>
        You have not authorize my app into your twitter 

       <%= link_to "Click here to authorize myapp.me", @link %>
     <% else %>
        Try to update your status 

        <% form_tag "/try/update_status", :method => "post" do %>
          <%= text_field_tag "status" %>
          <%= submit_tag "Update" %>
        <% end %>
      <% end %>

10. Add file callback.html.erb in app/views/try
   copy - paste

   <%= flash[:notice] %>

   <%= link_to "Click here", "/try" %> to back

That’s it, hope it can help you..
Please let me know if you find any error or problem when implement the codes.

Give comments to one paragraph / block in ruby

Posted by: febyartandi on: August 18, 2009

=begin -- comment begin ( make sure this is in the most left row /  indentation = 0 )

  def hallo
    render :text => "hello word"
  end

=end -- comment end ( make sure this is in the most left row /  indentation = 0 )

I’ve this problem when run my “old” rails application.

After some minutes trace, I found the problem is “name” for application controller file.

In my old application, the name is “application.rb“,

and when I renamed it with “application_controller.rb“,  it’s working !!

Hope this help peoples.

Ajax pagination – RoR and will paginate

Posted by: febyartandi on: May 11, 2009

Some peoples talked about ajax pagination in RoR and give solutions with jquery, override class RemoteLinkRenderer etc. All solutions is “to high class” for me, I need a “stupid” solution with only will-paginate and prototype :-) .

After some hours experiments, I’ve made the solution for create ajax pagination with only will-paginate and rjs.

See demo : http://ajax-pagination.herokugarden.com/users

The codes:

- Run ruby script/generate scaffold users first_name:string last_name:string address:string phone:string

modify:

- users_controller.rb

def index
find_users
end

def list_called_by_ajaxs
if request.xhr?
find_users
respond_to do |format|
format.js do
render :update do |page|
page.replace_html(‘list’, :partial => ‘users/list’)
end
end
end
end
end

private

def find_users
@users_per_page = 5
@users = User.all.paginate(:per_page => @users_per_page, :page => params[:page])
end

- modify users/index.html.erb<%= javascript_include_tag :defaults %>
<h1>Listing users</h1>

<%= render :partial => ‘list’%>
<div id=”loader-bottom” style=”display:none;s”><p>Loading..<br /></div>

- add users/_list.html.erb

<div id=”list”>
<%= render :partial => ‘pagination’ %>
<table border=”2″>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Address</th>
<th>Phone</th>
</tr>

<% @users.each do |user| %>
<tr>
<td><%=h user.first_name %></td>
<td><%=h user.last_name %></td>
<td><%=h user.address %></td>
<td><%=h user.phone %></td>
<td><%= link_to ‘Show’, user %></td>
<td><%= link_to ‘Edit’, edit_user_path(user) %></td>
<td><%= link_to ‘Destroy’, user, :confirm => ‘Are you sure?’, :method => :delete %></td>
</tr>
<% end %>
</table>

<br />

<%= link_to ‘New user’, new_user_path %>

</div>

- add users/_pagination.html.erb

<%- if @users.total_entries <= @users_per_page-%>
<%- pages = 1 %>
<%- else -%>
<%- pages = (@users.total_entries / @users_per_page) + 1%>
<%- end -%>
<%- if pages > 1-%>
<div id =”pagination” class=”pagination” style=”margin:0 5px 0 5px;padding: 0″>
<%- current = params[:page].nil? ? 1 : params[:page].to_i -%>
<span class=”current”> Page: </span>
<%- for i in 1..pages -%>
<%- if (i == current ) -%>
<span class=”current”><%= i %></span>
<%- else -%>
<%= link_to_remote i, {
:url => (list_called_by_ajax_users_path(:page => i)),
:method => :get,
:loading => “$(‘list’).hide();$(‘loader-bottom’).show()”,
:complete =>  “$(‘list’).show();$(‘loader-bottom’).hide()”} %>
<%- end -%>
<%- end -%>
</div>

<%- end -%>

modify “config/routes.rb”

add this line: map.resources :users, :collection => {:list_called_by_ajax => :get}

Hope this stupid solutions help peoples :D

HTML Tutorial – Part 1

Posted by: febyartandi on: February 20, 2009

1.1 What is HTML ?

HTML, an initialism of HyperText Markup Language, is the    predominant markup language for Web pages.

See http://en.wikipedia.org/wiki/HTML for details.

1.2 How to create HTML file ?

  • Open your text editor ( notepad, gedit, textmate, editplus, etc )
  • Create new file
  • Save file with .html, for example : index.html ( don’t forget to to choose option “save as type” : “all files”
  • press save or ok

1.3 Basic format of html document

open your html file and type ( or just copy -paste ):

<HTML>
  <HEAD>
    <TITLE>This text will show as the bar title in browser </TITLE>
  </HEAD>
  <BODY>
    This is the body, put your text, picture, etc here.
  </BODY>
</HTML>

Save your file and run it in the browser ( double click in your html file or right click – open with – Firefox.

1.4 Change the background color

you can change your page color with modify the tag  <body>.

example:

<HTML>
  <HEAD>
    <TITLE>This text will show as the bar title in browser </TITLE>
  </HEAD>
  <BODY bgcolor="red" >
    This is the body, put your text, picture, etc here.
  </BODY>
</HTML>

1.5 Show picture

In HTML, images are defined with the <img> tag. To display an image on a page, you need to use the src attribute. Src stands for “source”. The value of the src attribute is the URL of the image you want to display on your page.

example ( put this command inside of html body ):

<img src= “my_image.jpg”>

note: Change “my_image.jpg” with your own image url.

1.6 Text Modification (1)

examples:

<HTML>
  <HEAD>
    <TITLE>This text will show as the bar title in browser </TITLE>
  </HEAD>
  <BODY bgcolor="red" >

    <b> Bold text </b>

    <i> italic text </i>

    <strong> strong text </strong>

    <small> small text </small>

    <big> big text </big>

    <sub> sub-script </sub>

    <sup> sper-script </sup>

    <del> Wrong Text </del>

</BODY>
</HTML>

1.7 Text Modification (2)

change the font size ( put this command inside html body ):

    <font size=”20″> Font size 20 </font>

    create marquee text

      <marquee> This is marquee text </marquee>

      1.8 Create A links

      Links are defined with <a href=”target_url”>
      example:
      <a href=”http://www.google.com”> Google.com</a>

      Link to open target utr in new window
      <a href=”http://www.google.com” target=”_blank”> Google.com</a>

      1.9 Create a List

      -Unordered list

      An unordered listis a list of items. It starts with the <ul> tag.
      Each list item starts with the <li> tag.
      example:
      <ul>
      <li> Jazz </li>
      <li> Rock </li>
      <li> Blues</li>

      </ul>

      -Ordered list
      An Ordered listis a list of sorted items. It starts with the <ol> tag.
      Each list item starts with the <li> tag.
      example:
      <ol type=”a” start=”1″>
      <li> Jazz </li>
      <li> Rock </li>
      <li> Blues</li>
      </ol>
      note: you can change type with “1″ for numeric and “i” for romanian.

      Follow

      Get every new post delivered to your Inbox.