Sunday 25 December 2011

using libcurl in c/c++ program

  Using libcurl in c/c++ program on window machine.



1) Download libcurl:
      Go to curl.haxx.ex website and download the most appropriate package as per your system.
For this tutorial i've downloaded libcurl msvc build without ssl support.

When finish download , fire up your miscrosoft visual studio version 6 or higher( recommended).

Create new project:
   Win32>>Win32 Console Application

  

Press "OK" and "NEXT"

Now, in the Application Setting do uncheck "Precompiled headers" and then pess "Finish".



Now, before we begin writing any code, it's time to configure our visual studio to know libcurl whereabouts.

Configure Environment:
Go to Tools >> Options
           In the dialogue box so opened expand "Projects and Solutions" and choose "VC++ directories".




Add path to libcurl`s "include" folder in there. Do make sure that when you add library path select "library files" from 'show directories for:' drop down list and "include files" before adding libcurl`s include folder path.

When you're done, it's time to write our program.


2) Open curlTry2.cpp file and write a simple curl program. To ease this, you can copy a simple curl program from the curl examples given inside download libcurl files. (docs/examples)
Copy simple.c and paste it in curlTry.cpp program.

3) Run the program
             If you try to build your project now, it'll not build.
You'll see some linking error as follow:

1>------ Build started: Project: curlTry2, Configuration: Debug Win32 ------
1>Compiling...
1>curlTry2.cpp
1>stdafx.cpp
1>Generating Code...
1>Linking...
1>curlTry2.obj : error LNK2019: unresolved external symbol __imp__curl_easy_cleanup referenced in function _main
1>curlTry2.obj : error LNK2019: unresolved external symbol __imp__curl_easy_perform referenced in function _main
1>curlTry2.obj : error LNK2019: unresolved external symbol __imp__curl_easy_setopt referenced in function _main
1>curlTry2.obj : error LNK2019: unresolved external symbol __imp__curl_easy_init referenced in function _main
1>C:\Users\skm08030\Documents\Visual Studio 2008\Projects\curlTry2\Debug\curlTry2.exe : fatal error LNK1120: 4 unresolved externals
1>Build log was saved at "file://c:\Users\skm08030\Documents\Visual Studio 2008\Projects\curlTry2\curlTry2\Debug\BuildLog.htm"
1>curlTry2 - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


Correcting linking error:
             Error comes because you haven't specified the libcurl.lib files to it.
To do so, just right click on the project and select properties.



If it again throw the same linking error, then your lib and include dir path given under "VC++ directory" is not properly set.Please verify them. 

Try running your program again, this time it may demand for zlib1.dll file.

Download and copy dll file in project folder where curlTry2.cpp file is located. If you've already downloaded zlib1.dll files but it's giving you this error:
       ordinal 55 coun't not be located in dynamic link library zlib1.dll
then try downloading and adding zlib1.dll file from this link. 
Now, run your program. If everything goes right then it should work.



Reference:
http://curl.haxx.se/libcurl/c/

Windows developers using Microsoft Visual Studio, might enjoy:
             -> Rosso Salmanzadeh's Using libcurl in Visual Studio [PDF] guide.
             -> Andrei Jakab's Using libcurl with SSH support in Visual Studio 2008 [PDF]

Friday 2 December 2011

Thursday 1 December 2011

wget: proxy setting and wgetrc file

If your internet connection is set to use proxy network then you have to specify the same to wget as well.
otherwise wget will throw "connection refused.." error.

To specify http proxy address to wget you can do either of them.

->By providing in the command line argument

Wget: beyond DEFAULT*

wget is great command line downloading utility. It can be used to download any file from http or ftp uri.
So, here are some step to setup wget and get it working to download some stuff over internet.

Download wget:
for window: 
http://gnuwin32.sourceforge.net/packages/wget.htm


Install/Extract wget to any directory of your choice.
I've install it inside my 'C:" dir  such that my path to wget is as follow:
" C:\Program Files (x86)\GnuWin32"

Wednesday 16 November 2011

get year and month out of a string using javascript

Create an array to store months names.


arrMonths= new Array()
arrMonths[0]='January'
arrMonths[1]='February'
arrMonths[2]='March'
arrMonths[3]='April'
arrMonths[4]='May'
arrMonths[5]='June'
arrMonths[6]='July'
arrMonths[7]='August'
arrMonths[8]='September'
arrMonths[9]='October'
arrMonths[10]='November'
arrMonths[11]='December'

Friday 4 November 2011

How to install libcurl binding for ruby?


How to install libcurl binding for ruby?

You can bring power of libcurl in your ruby installation via CURB. It does provide libcurl binding for your ruby program.
Steps to install

1)Make sure you've ruby and development kit installed on your system
2) Download libcurl development files.
2)Now, to install curb run the gem install command with extra options.

Friday 9 September 2011

How to install Ruby and RoR on Window Platform?

RUBY Installation on Window
Files required:
1) ruby installer for window : Ruby 1.9.2-p290
2) development kit : DevKit-tdm-32-4.5.2-20110712-1620-sfx.exe

Download and proceed installing Ruby as you normally do with any insaller... :P.
I've installed ruby inside my 'c:/'  dir. So, it's path is "C:\Ruby192"

I've put develpment kit insde this folder underneath  'devkit' folder.

For development kit:
Extract the dev-kit folder anywhere. I've extracted it inside  'C:\Ruby192' folder .

Goto the root folder where you extracted DevKit, which in my case is 'C:/Ruby192/devkit/ ' and execute undersign commands
ruby dk.rb init
ruby dk.rb install
Second Step:   Tell window about ruby and devkit
Once you done installing ruby and devkit, you need to add their path in window envrionment variables i.e PATH.
so... right click on "My computer" from anywhere ( start menu or through window explorer) then click properties and then  look for advanced setting tab and there look for "environment variables" under 'advanced' tab.
We have to edit one "system variable" :  PATH.
so , find and edit.
append the path to your  bin directory of ruby and path to bin directory of devkit in path variables , so that your final path variable look like this. Don't forget to separate them by semi-colon(;);

C:\pik\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Bazaar;C:\Program Files\cloudControl;C:\wamp\bin\php\php5.2.8;D:\git\bin;C:\Program Files\Java\jdk1.7.0\bin;C:\Program Files\GnuWin32\bin;C:\Program Files\Notepad++;C:\Program Files\Android\android-sdk\tools;C:\Program Files\Android\android-sdk\platform-tools;C:\pik;C:\Ruby192\bin;C:\Ruby192\devkit\bin

once you done adding path to of devkit and ruby you're ready to install RoR :ruby web framework.
Now,  update your gems by running undersign gem`s update command:
>>gem update --system
Hug yourself,  you've just finish installing Ruby all by yourself. :D
Next step is to install RoR:ruby on rails.

RoR: Installation on Windows
To install Rails which is just like another gem in reign of ruby, i assume you have already successfully installed ruby and development kit.
open the command  prompt and type
>>gem install rails --include-dependencies
Now, you're done installing Rails as well. 
TEST IT:
>> rails new  myNewApp

reference:
devkit: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit

Errors that you may face:    
>>gem install rails

DevKit is needed because rails requires the json gem. Without installing DevKit you would get the error:
ERROR: Error installing cucumber:
The 'json' native gem requires installed build tools.
Please update your PATH to include build tools or download the DevKit
from 'http://rubyinstaller.org/downloads' and follow the instructions
at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
This is likely to happen if you've installed devkit.So, again check if you've installed devkit and if yes, then make sure that you've added right path in window Environment variable(PATH) i.e you've appended path to devkit's /bin directory in  PATH variable.

Wednesday 24 August 2011

How to make XML parsing compatible with IE

Internet Explorer is annoying as usual about this and you need to make exceptions for it.  Here's what you can do:

type: 'GET',
                        url: 'photos.xml',
                        dataType: ($.browser.msie) ? "text" : "xml", //if Browser is internet explorer, the datatype is text, otherwise xml.
                        success: getXML,
                        complete:


And then in my "success" function, add this:

if ($.browser.msie) {
    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.loadXML(xml);
    xml = xmlDoc;
}

Thursday 18 August 2011

How to preload images??

Every find need to pre-load images to add some grace in the way your site load or to make some bon-bon effects? I bet you do.  So, let see how one can achieve it using javascript orjquery. :)


Some variables to be used to preload image
imgSrc: /path/to/chantu.jpg
 #imgBox : element where to load

Javascript Way:
//create a new image element
var imgPreload = new Image();
//attach image
imgPreload.src = imgSrc;
//now load it and when image loads, bring it inside the DOM and place it inside the #imgBox ;)
imgPreload.onload= function(){
    //place it inside the DOM
$("#imgBox").append("imgPreload");
}

Monday 20 June 2011

Some handly Rails snippets

To get url along with query string

$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];

To extract 'year' or 'month' or 'day' from a unix timestamp
strtotime to convert date to unix timestamp as date() accept unix timestamp not just any simple string.
date('Y',strtotime('2011-12-2') );

To get Month name:
      Date::MONTHNAMES[Date.today.month]
or

I18n.t("date.month_names") # [nil, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
I18n.t("date.abbr_month_names") # [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
I18n.t("date.month_names")[Date.today.month] # "December"
I18n.t("date.abbr_month_names")[Date.today.month] # "Dec"

Thursday 16 June 2011

How to extract Body and Subject From piped mail

To extract Subject and Mail from piped mail

Raw Email format:

Received: from gijs ([192.168.55.2])
 by debian with smtp (Exim 3.12 #1 (Debian))
 id 17AYXZ-0002BE-00
 for ; Wed, 22 May 2002 18:00:41 +0200
From: "Gijs van Tulder" 
To: 
Subject: Test
Date: Wed, 22 May 2002 18:00:41 +0200
Message-ID: <KNEOKJCOCHEDPIMPAIMIOEOJCJAA.gijs@debian>
MIME-Version: 1.0
Content-Type: text/plain;
 charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
X-Priority: 3 (Normal)
X-MSMail-Priority: Normal
X-Mailer: Microsoft Outlook IMO, Build 9.0.2416 (9.0.2910.0)
Importance: Normal
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2600.0000

This is my message.

Thank you.

Saturday 11 June 2011

email forwarding: pipe to a program

Ever tried to read your mail outside of your mail client?
Then here's your chance to try to read or play with your incoming mails.

go to your cpanel , look for email forwarding option.
Add a new email forwarder and from the drop down list choose "pipe to a program".
In the text box enter a pipe sign `|` followed by a path to your script file.
eg.
|/home/mysite/public_html/test.php


Set it permission to 0755 and put a hash bang as the very first line of your code


In your test.php (or another) structure your code as this:


#!usr/local/bin/php -q


   --- your php code goes here---
//To read mail use this : 
$fd = fopen("php://stdin", "r"); 



#end

Friday 27 May 2011

Resolving Dependencies

Nokogiri:
  
libxml and libxslt

sudo apt-get install libxslt-dev libxml2-dev


Thursday 26 May 2011

Custom helpers in Rails

Ever thought of organizing your code in more than one files , rather writing all in one place.
Sometime, you want a method accessible to all your controller. Solutions to this is:
1) ApplicationController
2)Copy the same methods in each controller specific helper file i.e REPEAT YOURSELF, which go against the rails philosophy of DRY( Do Not Repeat Yourself)
3) Custom Helpers

Wednesday 18 May 2011

Run your script on system startup

Sometime you want to auto mount your window partitions on your linux machine or sometime you find need to clean clear or purge your database/inbox or sometime you might want to run your own custom script. Reasons are many and so are the solutions.

1) use cron jobs
2) use linux run level file

Sunday 15 May 2011

Learn three linux command a day

aah, here's a nice trick that'll randomly gives you three command for you to explore.

Trick make use of  linux `shuf' and `ls' command.


sahilsk@dragonaider:~$ ls /usr/bin/  | shuf -n 3
pgmnoise
evolution-settings
infokey

Libraries i like most

Here's is a list of my favourite libraries i use in most of my projects
#cURL family
                         :libcURL/curlcpp/php-curl
#ImageMagick              
                         :  :php imagick, ror:rmagick,cpp:imageMagick

auto mount ntfs drives

To mount ntfs partition on your linux operating evertime your OS boot up:
#automount.sh

#!/bin/bash




#Mount HDD
#create associative array  NOTE:SUPPORTED BY BASH >4.1 .
declare -A disks
disks=(["sda2"]="driveOne" ["sda5"]="driveTwo" ["sda6"]="driveThree")

Stopping Daemons

On my ubuntu server, i've many daemons and server running in the background and everytime i boot my desktop, they bootstrap on there own and start consuming cpu resources.
So, i wrote a script to stop all those server on system boot.


Permission denied error while executing c/c++ code compiled with gcc

Out of many reasons here are those which i faced

Not enough permission
solution:
$ chmod +x yourFileName
or
$chmod 777 yourFileName


little on bash scripting

Linux Bash Scripting


Simple Array
_________________________________________
$ name=("chantu"  "bhantu"  "santa"  Bhanta)
OR
$ name=(chantu bhantu santa bhanta)
_________________________________________

Iterating over an Simple Array

Friday 29 April 2011

Replacing RoR default prototype library with Jquery Via Jquery-Rails Gem

RoR is shipped with Prototype javascript library, it's pretty rich in feature and when its combine with scriptaculous it brings awesome javascript effects to your rails app.
Having use both prototype and jquery, i find jquery little less verbose.
After all, write less and do more should be given more preference.

Here are steps to replace prototype with jquery using a gem christened 'jquery-rails' .

In your  GemFile  add this one more gem


gem 'jquery-rails'

Rails partials ,layout and helpers

partials:
We can think of Rails partial templates (partials for short) as a kind of method
for views. A partial is simply a chunk of a view in its own separate file. You can
invoke (render) a partial from another template or from a controller, and the
partial will render itself and return the results of that rendering. And, just as
with methods, you can pass parameters to a partial, so the same partial can
render different results.


render(:partial => "partialFile")

html_escape in RoR

You can escape html entities from your code using Rails html_escape() method.

<%= html_escape ("<p> will remain as it is.")  %>
OR
<%=h  "<p>will remain as it is." %>

h() is a short tag for html_escape.
BUT IN RAILS 3 html_escape is used by default. 

Thursday 28 April 2011

How to create a checksum of a file in ruby?

Ruby Digest class does support many hashing algorithm. For example  sha1, sha2,sha256, md5 etc etc.
Md5 is most commonly used and it's known to be less secure than sha1.
Recently sha1 has been decoded by someone.
so, i prefer to use SHA2. :D

Sunday 24 April 2011

Gvim: best editor for linux workstations

I'm a big fan of TextMate text editor on Mac machine and on window i prefer Notepad to every other ide including eclipse. But nowadays i'm on linux and so i couldn't use textmate anymore and same goes for notepad++. I tried running it via wine, but most of its function didn't works well.
I google and found vim is one of the best editor for linux workstations. After trying a while, i found vim easy to use and rich in features.

First thing first, get yourself a copy of vim editor.  Vim comes in two variant : command line and Gui. I prefer Gui over command line one, reason being easier to edit and maintain while working on large project.

Saturday 23 April 2011

Upcoming Articles

*configuring and installing Full Text Seach Engine on Ruby on Rails, on Chantu sorry, Ubuntu. :P
*Top 10 rarely used  Mysql commands.
*

ProFTPD behind the NAT

Having installed proftpd on your system, let make it accessible to the world or atleast to your dear ones.

Edit your proftpd.conf file and uncomment or Append these lines

Port 21
PassivePorts 60000 65535
MasqueradeAddress YourSiteName.ath.cx
eg

ProFTPD(File Transfer Protocol) setup on Linux

Installation
$ sudo apt-get install proftpd

root@dragonaider:/home/sahilsk# sudo apt-get install proftpd
Reading package lists... Done
Building dependency tree       
Reading state information... Done .....


RoR heroku deployment

Heroku
Heroku is best known for Ruby On Rails hosting. It's world class service place it apart from others.

Best thing about Heroku is that it also provide a free hosting of 100mb diskspace and 5mb of Database.
Enough to get you started with ror project deployment.

since creating account on heroku is free you can also create create and deploy facebook on heroku for free.

Here are the step:

Network File System v4:setup

Quick setup of network file system on localhost:

Download following packages:

for server:
$ sudo apt-get install nfs-kernel-server

for client:
$ sudo apt-get install nfs-common

once done installing, configure your /etc/exports file. Here's mine:

Tuesday 19 April 2011

RMagick Installation And Usage

You might have heard of imagemagick libarary : the popular library that does almost all operation on image one can think of.
I'm a die hard fan of image magick library. and probably that's why no matter which language i choose to program i always opt imagemagick wrapper functions  for eg. Imagick for php, Magick++ for c++ and RMagick for Rails.

RMagick Installation :

$ gem install RMagck 2  # if Rails < 2 , install RMagick 1 else for Rails  3 install RMagick 2.x

confirm
$ gem list  # if you see RMagick in your list then it's installed in rubygems.


Rmagick installation on Windows

1) Go and download  rmagick for windows (win32)
Project page:
http://rubyforge.org/frs/?group_id=12&release_id=39888

Download here (RMagick-2.12.0-ImageMagick-6.5.6-8-Q8.zip)

2) Extract and CD to unzipped directory

3) Install it

gem update --system


You should see:
  • Successfully installed rmagick-2.12.0-x86-mswin32
If instead you get the message
  • Error installing gem rmagick[.gem]: buffer error
then you didn't update RubyGems. Do so now and re-run the gem install command.





downspout: download files over http and ftp protocols.

DownspoutA beautiful gem that let you download files from any website or any ftp site.
Here's quick example of downspout.

Installation :
$ gem install downspout
Once done, run the rails console
$ rails c



Operations on String :Ruby Way

I  want this post to filled with examples. But since i don't have much examples i urges you to please post some examples via your precious comments and help this post to grow more and more.

Well, more the merrier. 


To generate Timestamp like this :  20110419230024

some useful rails methods and links for sahilsk.

Rails Inflector: 
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html


if model name = "UserAccountHistory "  ,table name = "user_account_histories"
"user_History".tableize   # user_histories
"user_history".pluralize # user_Histories
"user_account_history".camelize # UserAccountHistory

Kaminari : beautiful pagination gem for Rails 3

Pagination on ActiveRecord


Pagination
In older times, i used to use Will_Paginate , a very nice pagination gem. But after using Kaminari i find will_paginate little more verbose.
Nowadays i uses  a beautiful gem christened Kaminari by amatsuda

How to setup kaminari to paginate your table ?

RoR : naming Conventions

controllers
name should be Plural eg.  users, items, teachers
multiwords name should be in  CamelCase,
eg.   UserItems,  UserSessions etc


model
name should be singular and database table name should be plural.
eg. table name : users  ; model name => user
table name :people ; model name => person


Got Lost? How to generate plural form for  table name?
ruby-1.9.2-p0 > "person".tableize
 => "people" 

learn more on text transformation a.k. Text Inflectors 


Table Relationships:
HINT: read it aloud

belongs_to :singularName
has_many :pluralNames
has_on :singularName





A very wonderful  post on RoR naming conventions is posted on  iT signals

How to install Rails in ubuntu?


Once you done installing ruby, lets connect to the next link in the chain :RAILS Installation.
Ruby programs comes in small modules called gems, which are self-contained packages of Ruby Code.
Since gems with different version numbers may cause some conflict, it's preferable to separate gemsets, which are self-contained budles of gems or simply Repository of Ruby Extensions.

So, to create two different gem sets one for each rail version do the following:
 $ rvm --create 1.8.6@rails2 #  or $ rvm --create 1.8@chantu
 $ rvm --create use 1.9.2@rails3 # or $ rvm --create 1.9.2@bhantu

first command create the gemsets rails2 associated with Ruby 1.8.6 while the second command creates the gemsets rails3 associated with Ruby 1.9.2 and uses it at the same time.

To use Ruby 1.9.2 and Rails 3 by default :
$ rvm --default use 1.9.2@rails3 # This sets the default Ruby to 1.9.2 and default gemset to rails3

Got Lost?
$ rvm --help
$ rvm gemset --help


Insall RubyGems
RubyGems: Package Mannager for Ruby projects. You can access those tons of ruby/rails extension to further enhance the productivity of your rails app had you have this.
So, lets get it first.

wait....
since you've installed RVM , you already got it. Bingo...
confirm:
sahilsk@dragonaider:~/cronfarm$ which gem
/home/sahilsk/.rvm/rubies/ruby-1.9.2-p0/bin/gem

 If you don't have it, go and download RubyGems, extract it and then go to the rubygems directory and run the setup file
$ [sudo] ruby setup. rb  # here sudo tag is optional

update your repo : RubyGems
$ gem update --system


Finally the moment you all waited so long  . Yes, Installation of RAILS
$ gem install rails --version 3.0.0 # or simple || $ gem install rails  || # gem will get the latest version for you.
 Confirm:
$ rails v
Rails 3.0





How to install Ruby on Ubuntu powered systems

Here's the first step to teach your system how to interpret ruby's methods and classes.
slap1 =>Install Ruby Interpreter.

The best and easiest way to install ruby interpreter in your system is by using 'Ruby Version Manager" a.k.a RVM. So, go and install it right away
Once done installing, just run through this commands. :

$ rvm get head  # Make RVM to go and get the latest records
$ rvm reload     #once done fetching latest records, update local records. NOTE: installation not yet started.
$ rvm list known # List Ruby interpreters available or installation
$ rvm list #lit Ruby Interpreters you've already installed

# START INSTALLING RUBY
$ rvm install 1.8.7-p174 # One of the interreters selected from the  (rvm list known) list
$ rvm install 1.9.2  # I'll install 1.9 version too. Why?? bcoz i'm kew........l. Not necessary for you. Opt the verson you like most.

Now, out of various version i've installed which one should i make default?? 1.8 or 1.9 ?or should i use any ruby interpreter??
If answer to any of above question is TRUE(YES) proceed
$ rvm use 1.9.2  # user ruby 1.9.1 OR simply  "rvm 1.9.2"

confirm  your ruby version by running this command in shell.
$ ruby -v

Still need help
$ rvm --help

$rvm gemset --help 


System wide install is no longer exist.
Use this command in Ubuntu console to install rvm as root and be available for all users:

it'll install your rvm in /usr/local/rvm .

now, add  this line in your ~/.bashrc file



change the line that goes like  [-z "$PS1"] .. to this


if [[ -n "$PS1" ]]; then
..
.....
Now, in the last, append these lines


[[ -s "/usr/local/rvm/scripts/rvm" ]] && source "/usr/local/rvm/scripts/rvm"


fi 


last 'fi' to end the upper if block. :D



Hello World

=begin
A simple 'Hello World' Program in Ruby.
=end


ruby-1.9.2-p0 > def say_hello; puts "Hello World!"; end

ruby-1.9.2-p0 > say_hello
Hello World!