Tuesday, December 20, 2011

How to put a style on input file type using CSS and jQuery

I came to this development where in I need to put a style on input file element. This is actually a challenge for me, but was able to find a way to do it. The button and inputbox is normally display in one call of an element. However, in CSS we can't style it the way we do with a normal input box, text area, etc.. and the only way for us to style it is to use jQuery/Javascript with a simple cheat using CSS.

First, we need to have a style for our inputbox and button.., that is actually for you to decide on how you want it to be.

Second, setup the HTML with the input file type element together with a styled inputbox and button. Please see below on how it will look like and take note of the id attribute I put in to be use for jQuery.

<input type="text" id="inputbox" name="inputbox" class="myinputbox"/>
<input type="button" id="button" name="button" class="mybutton"/>
<input type="file" id="inputfile" name="inputfile"/>


Once you've setup your HTML, we need to use the jQuery to trigger the #inputfile whenever we click on #inputbox or #button. Please see below.

$('#inputbox, #button').click(function() {
    $('#inputfile').trigger('click');
});


We also need to get the value of the #inputfile and change the value of the styled #inputbox as it changes. This is normally the filename of the file you selected on the open file dialog box.

$('#inputfile').change(function() {
    var data = $(this).val();
    var file = data.length ? data.split('\\').pop() : '';
    $('#inputbox').val(file);
});


Now, whenever you click on #inputbox and #button, the open file dialog box should appear and any change of value on #inputfile should reflect on #inputbox.

Lastly, we need to hide the #inputfile and retain the styled #inputbox and #button with a functional input file type element.

We can't use style="display:none" coz in some browsers JS will not work if the element is HIDE. So, the best way to do it is to set the opacity to "0" zero. This is a simple cheat to hide the elements without disabling them.

You will also have to consider other browsers, so the style should support all browsers. Please see below.

-moz-opacity:0;
filter:alpha(opacity:0);
opacity:0;


In summary, your HTML script should be like this.

<html>
<head>
<title>How to put a style on input file type using CSS and jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <input type="text" id="inputbox" name="inputbox" class="myinputbox"/>
    <input type="button" id="button" name="button" class="mybutton"/>
    <input type="file" id="inputfile" name="inputfile" style="opacity:0"/>
</body>
<html>
<script type="text/javascript">
$(document).ready(function() {
    $('#inputbox, #button').click(function() {
        $('#inputfile').trigger('click');
    });

    $('#inputfile').change(function() {
        var data = $(this).val();
        var file = data.length ? data.split('\\').pop() : '';
        $('#inputbox').val(file);
    });
});
</script>


Hope this helps a lot of developers.
Please see also my new post "File upload with style using jQuery and CSS".

Sunday, December 4, 2011

How to validate email address in PHP and jQuery.

PHP has a built in function where you can validate email address, but please take note that it only validates the format of the email address and not to check whether it is real or not.

To check whether the email address is real, you just have to put verification process to your application. Usually, verification process goes with registration process where user have to input their email address and other credentials. The application should send a confirmation link to the email address upon registration. The confirmation link must then be clicked by user to verify their registration or email address.

Anyway, for pre-validation, it's still better to put format validation of email address. This is for the application not to waste time of sending emails. Please see below for the quick and easy way in PHP.

<?php
$email = 'paul123@wideumbrella';

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "valid";
} else {
        echo "invalid";
}

?>


You can also validate the email address using jQuery. Please see custom function and implementation I did for jQuery.

<html>
<head>
<title>Validate Email</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
        $.fn.validateEmail = function() {
                var email = $(this).val();
                var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);

                return pattern.test(email);
        }

        $(document).ready(function() {
                $('.btnValidate').click(function() {
                        alert($('#email').validateEmail());
                });
        });
</script>
</head>
<body>
        <input type="text" value="" id="email"><a class="btnValidate" title="Validate" href="#">Validate</a>
</body>
</html>


Quote for the day: Perseverance is needed to release most of life's rewards. It's the last step in the race that counts the most. That is where the winner is determined. That is where the rewards come. If you run every step of the race well except the last one and you stop before the finish line, then the end result will be the the same if you never ran a step.

Monday, November 28, 2011

Hotshots in PhilSTAR.com - New dawn for high-tech mobile ticketing from Smart

MANILA, Philippines - Who knew that the day would come when a simple swipe of the hand could yield cinema tickets and movie treats? Smart Rewards together with SM Cinema made history when they launched the revolutionary bCode technology, the country’s first cutting-edge platform that allows subscribers to redeem free blockbuster rewards conveniently through their cell phones.

Offering the latest in mobile commerce, the breakthrough bCode technology allows loyal users of Smart Gold, Smart Buddy and Smart Bro users to claim big rewards, from free tickets, popcorn and drinks, to a P100 discount on movie tickets in as easy as a single tap on the terminal screen.

Driven with the commitment to innovation, Smart Reward pioneers the use of bCode technology for mobile ticketing in the country. To develop the technology, WolfPac Mobile, Inc., Smart’s mobile service solutions provider and application developer, spearheaded the integration of the Smart Rewards loyalty program to the new redemption platform.

According to Paul Gonzaga, WolfPac’s Web and MIS development manager, a crucial part of the implementation was developing the software that would allow subscribers to use their loyalty points in redeeming reward items via bCode. With a team of MIS experts, the development of the system took only one month in time for its launch recently.

Smart Rewards’ loyalty platform linked to the bCode platform offers a hassle-free mobile-ticketing service since it doesn’t require users to download any mobile application. Subscribers need only to text the item code of the reward to 9800, and a unique bCode SMS consisting of alphanumeric characters will be sent to their mobile phone. To receive the reward coupon, subscribers must simply scan the bCode in terminals designed to securely read the encrypted codes. SMART Bro users can also redeem free items via WebConnect and print out the given code to be scanned at the bCode machines located in SM cinemas nationwide.

The new redemption network is also compatible with all mobile phones in the market, making the complete movie experience accessible to all Smart subscribers. An instant hit among movie-lovers, the new bCode platform has gained an increasing following. Today, thousands of tickets and treats are being redeemed every month using the new technology.

“Through the innovative technology of bCode, Smart Rewards and WolfPac continue to provide more dynamic ways for subscribers to enjoy their rewards. Movie tickets and treats are just the start. Subscribers can expect to delight in even more rewards as we look forward to expanding the roster of redeemable items via bCode,” says Gonzaga.

Text REWARDS to 9800 for free to start redeeming exclusive treats only from Smart Rewards. Or visit smart.com.ph/rewards for many more exciting freebies.

Reference: http://www.philstar.com/Article.aspx?publicationSubCategoryId=449&articleId=750160

Wednesday, November 23, 2011

Computing the distance between zip codes longitude / latitude

I have created a function that will compute for the distance between zip codes (longitude / latitude).

The function will actually go a series of conversion from degrees to radians, radians to degrees, degrees to miles, then miles to any unit of measurement you want.

For the benefit of this post, we will have the distance in kilometers.

Given that, we need the multipliers below.

my $pi = atan2(1,1) * 4; # pi: 3.14159265358979
my $deg2radmul = $pi / 180; # degrees to radians multiplier: 0.0174532925199433
my $rad2degmul = 180 / $pi; # radians to degrees multiplier: 57.2957795130823
my $deg2milmul = 69.09; # degrees to miles multiplier
my $mil2kilmul = 1.609344; # miles to kilometers multiplier


First, we have to get the distance between longitude1 and longitude2 by subtracting the two points.

my $dlon = $lon1 - $lon2;


Next, get the distance by getting the radians value of each points and use sin and cos function in perl.

my $dist = sin($lat1 * $deg2radmul) * sin($lat2 * $deg2radmul) + cos($lat1 * $deg2radmul) * cos($lat2 * $deg2radmul) * cos($dlon * $deg2radmul);


Then finally, convert the distance in radians, radians to degrees, degrees to miles, and miles to kilometers.

$dist = atan2(sqrt(1 - $dist**2), $dist);
$dist = $dist * $rad2degmul; # radians to degrees
$dist = $dist * $deg2milmul; # degrees to miles
$dist = $dist * $mil2kilmul; # miles to kilometers


To get the complete implementation and example that I created, please see below. Happy Coding!

#!/usr/bin/perl

my $lat1 = '14.559943';
my $lon1 = '121.015198';
my $lat2 = '14.56255';
my $lon2 = '121.017151';

my $dist = &distance($lat1, $lon1, $lat2, $lon2);
print "distance in km: $dist\n";

#!/usr/bin/perl

my $lat1 = '14.559943';
my $lon1 = '121.015198';
my $lat2 = '14.56255';
my $lon2 = '121.017151';

my $dist = &distance($lat1, $lon1, $lat2, $lon2);
print "distance in km: $dist\n";

sub distance
{
  my ($lat1, $lon1, $lat2, $lon2) = @_;
  my ($pi, $deg2radmul, $rad2degmul, $deg2milmul, $mil2kilmul, $dlon, $dist);

  $pi = atan2(1,1) * 4; # pi: 3.14159265358979
  $deg2radmul = $pi / 180; # degrees to radians multiplier: 0.0174532925199433
  $rad2degmul = 180 / $pi; # radians to degrees multiplier: 57.2957795130823
  $deg2milmul = 69.09; # degrees to miles multiplier
  $mil2kilmul = 1.609344; # miles to kilometers multiplier

  $dlon = $lon1 - $lon2;
  $dist = sin($lat1 * $deg2radmul) * sin($lat2 * $deg2radmul) + cos($lat1 * $deg2radmul) * cos($lat2 * $deg2radmul) * cos($dlon * $deg2radmul);

  $dist = atan2(sqrt(1 - $dist**2), $dist);
  $dist = $dist * $rad2degmul; # radians to degrees
  $dist = $dist * $deg2milmul; # degrees to miles
  $dist = $dist * $mil2kilmul; # miles to kilometers

  return ($dist);
}




1;


Some men succeed by what they know; some by what they do; and a few by what they are.

Friday, November 18, 2011

How to disable resize functionality on textarea

Textarea by default is resizable by dragging the bottom right corner of the element. Having that functionality will causes the layout to crash if we implemented styles in our textarea, such as having a background image instead of shadow style. That is because the background image doesn't follow the size of the textarea when resized.

We can disable the resize functionality by setting the resize to none. Please see below for the implementation.

<html>
<head>
<title>Disable Resize in Textarea</title>
</head>
<body>
<textarea style="resize:none" rows="5" cols="5"></textarea>
</body>
</html>

Thursday, November 17, 2011

How to show a running date and time clock in your website.

Using Ajax, I created a simple script that will show a running date and time clock in the website. Basically, the function will get the actual date and time of the server, then set a time out that loop in every second.

To get the date and time, you can initialize it by Date() object.

var today = new Date();


From there, you can get the date and time, please see below for the object methods that you can call.

var cmonth = today.getMonth(); // this will return the index of the month[0-11]
var cyear = today.getFullYear(); // this will return the year in 4 digits
var cday = today.getDate();
var chour = today.getHours();
var cmin = today.getMinutes();
var csec = today.getSeconds();


As for the complete implementation, please see below.

<html>
<head>
        <title>Hotel Aide</title>
        <script type="text/javascript">
        function updateTime() {
                var today = new Date();
                var month = new Array(12);
                month[0]="Jan";
                month[1]="Feb";
                month[2]="Mar";
                month[3]="Apr";
                month[4]="May";
                month[5]="Jun";
                month[6]="Jul";
                month[7]="Aug";
                month[8]="Sep";
                month[9]="Oct";
                month[10]="Nov";
                month[11]="Dec";

                var cmonth = month[today.getMonth()];
                var cyear = today.getFullYear();
                var cday = today.getDate();
                var chour=today.getHours();
                var cmin=today.getMinutes();
                var csec=today.getSeconds();

                if (chour<10) chour = "0"+chour;
                if (cmin<10) cmin = "0"+cmin;
                if (csec<10) csec = "0"+csec;

                document.getElementById('datetime').innerHTML= cmonth+' '+cday+', '+cyear+' '+chour+':'+cmin+':'+csec;
                window.setTimeout('updateTime();',1000);
        }
        </script>
</head>
<body onLoad="updateTime();">
        <span id="datetime"></span>
</body>
</html>


Hope this is helpful! Thanks!

Tuesday, November 15, 2011

Eclipse 101: Debug Certificate expired on x/xx/xx xx:xx AM/PM

I'm new to eclipse IDE and when I tested my newly created app for android, I encountered an error "Debug Certificate expired on 6/1/11 10:51 AM".

Developers might encounter this error when using eclipse and what we need to do here is to remove the debug certificate file for eclipse to create a new one.

To do this in linux or mac os, go to your terminal then execute the command below. Make sure you have the proper access to remove the file.

rm ~/.android/debug.keystore


Hope this helps a lot of developers which are new to eclipse IDE. Thank you for reading.

Monday, November 14, 2011

Eclipse 101: ERROR: Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml, reason: Unknown Host http://xxx.xxx.xxx.x

While doing an update on my Eclipse SDK for Android development, I came to a problem that I can't able to update SDK due to proxy problem which I didn't remember setting it up.

Problem is that I encountered this error "ERROR: Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml, reason: Unknown Host http://192.168.101.5".

I tried disabling the proxy settings of Eclipse Network Connections in all active provider: Direct, Manual, and Native but nothing works for me and error still persist.

It took me half a day to figure out the problem is, and then I found the config file on Android for the proxy settings.

You just have to go to this path: ~/.android/androidtool.cfg.. and you will see the settings like on this below.

### Settings for Android Tool
#Tue Jun 22 09:08:34 PHT 2010
http.proxyPort=80
sdkman.monitor.density=72
http.proxyHost=http\://192.168.101.5
sdkman.show.update.only=false
sdkman.ask.adb.restart=false
sdkman.force.http=false


Then update it to remove the proxy port, proxy host, and set the force http to true. The settings should be like this.

### Settings for Android Tool
#Tue Jun 22 09:08:34 PHT 2010
http.proxyPort=
sdkman.monitor.density=72
http.proxyHost=
sdkman.show.update.only=false
sdkman.ask.adb.restart=false
sdkman.force.http=true


Thank you for reading this post. Hope it helps!

Sunday, October 23, 2011

Net::UCP::Client SMSC Protocol in PERL

This post will teach you how to create an SMSC UCP client in Perl.

1. First, you will need Perl libraries that needs to be installed in your server. Libraries are as follows:
  • POSIX
  • Time::HiRes
  • File::Copy
  • Encode
  • Net::UCP
  • Data::Dumper
2. Initialize the script by creating SMSC object passing the smsc ip, smsc port, and smsc profile.

my $emi = Net::UCP->new (
        SMSC_HOST   => $smsc_ip,
        SMSC_PORT   => $smsc_port,
        SENDER_TEXT => $profile,
        SRC_HOST    => $source_ip,            # optional
        SRC_PORT    => $source_port,          # optional
        WARN        => 1,

        FAKE        => 0
) or die("Failed to create SMSC object");

$emi->open_link() or die($!);

3. Login to SMSC by supplying smsc id, smsc password, and smsc access code.

my ($acknowledge, $error_number, $error_text) = $emi->login(
        SMSC_ID    => $smsc_id,
        SMSC_PW    => $smsc_pw,
        SHORT_CODE => $smsc_ac,
        OTON       => $ton,       # optional
        ONPI       => '5',        # optional
        VERS       => '0100',     # optional
);

die ("Login to SMSC failed. Error nbr: $error_number, Error txt: $error_text\n") unless($acknowledge);

4. Loop in to fetch SMSC messages. Please take note that we need to have a call-back function to call whenever it reaches timeout. All messages can be parsed by using parse_message() function that will return hash data.

$message = $emi->wait_in_loop(
        timeout => $timeout,
        clear => 1,
        action => \&timedout
);

if (defined($message)) {
        print "wait_in_loop: $message\n";
        $hshmsg = $emi->parse_message($message);

        $chksum = $hshmsg->{checksum};
        $rpid = $hshmsg->{rpid};
        $dcs = $hshmsg->{dcs};
        $type = $hshmsg->{type};
        $len = $hshmsg->{len};
        $xser = $hshmsg->{xser};
        $mt = $hshmsg->{mt};
        $trn = $hshmsg->{trn};
        $ot = $hshmsg->{ot};
        $srcmin = $hshmsg->{oadc};
        $dstmin = $hshmsg->{adc};
        $smsmsg = $hshmsg->{amsg};
        $tstamp = $hshmsg->{scts};
}

sub timedout {
        print "timeout reached...";
        exit 0;
}

5. Lastly, you need to acknowledge the receipt of messages by transmitting back the transaction id from the message you received.

$ucp_string = $emi->make_52(
        result => 1,
        trn => $trn,
        ack => 'A'
);

if ( defined($ucp_string) ) {
        ($acknowledge, $error_number, $error_text) = $emi->transmit_msg( $ucp_string, 10, 0 );
        print "transmit_msg: $error_text\n";
}


Please see below for the complete code with log and dump feature. Hope you like it.

#!/usr/bin/perl

use POSIX qw(strftime);
use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
use File::Copy;

use Encode;
use Net::UCP;
use Data::Dumper;

my ($message, $tstamp, $srcmin, $dstmin, $type, $xser, $mt, $trn, $ot, $smsmsg, $hshmsg, $ucp_string, $rpid, $chksum, $dcs, $len);

my $timeout = 120; # set timeout when fetching messages in secs

my $ton = 6; # set your TON from the SMSC server.
print "ton: $ton\n";

my $smsc_id = 'xxxx'; # set your SMSC ID
print "smsc id: $smsc_id\n";

my $smsc_pw = 'xxxxxxx'; # set your SMSC Password
print "smsc pw: $smsc_pw\n";

my $smsc_ac = 'xxxx'; # set your SMSC Access Code
print "smsc ac: $smsc_ac\n";

my $smsc_ip = 'xxx.xxx.xxx.xx'; # set the SMSC Destination IP
print "smsc ip: $smsc_ip\n";

my $smsc_port = 'xxxx'; # set the SMSC Destination Port
print "smsc port: $smsc_port\n";

my $source_ip = 'xxx.xxx.xxx.xx'; # set your SMSC Source IP
print "source ip: $source_ip\n";

my $source_port = 'xxxx'; # set your SMSC Source Port
print "source port: $source_port\n";

my $profile = 'xxxx'; # set your profile for logging
print "profile: $profile\n";

my $dumpdir = '/home/your/smsc/ucp/dump/directory'; # set your incoming dump directory
system "mkdir -p $dumpdir" if (!-e $dumpdir);
print "dump dir: $dumpdir\n";

my $logdir = '/home/your/smsc/ucp/log/directory'; # set your incoming log directory
system "mkdir -p $logdir" if (!-e $logdir);
print "log dir: $logdir\n";


# initialization... creating smsc object...
my $emi = Net::UCP->new (
  SMSC_HOST   => $smsc_ip,
  SMSC_PORT   => $smsc_port,
  SENDER_TEXT => $profile,
  SRC_HOST    => $source_ip,            # optional
  SRC_PORT    => $source_port,          # optional
  WARN        => 1,
  FAKE        => 0
) or die("Failed to create SMSC object");

$emi->open_link() or die($!);

# login to smsc...
my ($acknowledge, $error_number, $error_text) = $emi->login(
  SMSC_ID    => $smsc_id,
  SMSC_PW    => $smsc_pw,
  SHORT_CODE => $smsc_ac,
  OTON       => $ton,        # optional
  ONPI       => '5',        # optional
  VERS       => '0100',     # optional
);

die ("Login to SMSC failed. Error nbr: $error_number, Error txt: $error_text\n") unless($acknowledge);


while (1)
{
  # start fetching here..
  $message = $emi->wait_in_loop(
        timeout => $timeout,
        clear   => 1,
        action  => \&timedout
  );

  if (defined($message)) {
        &logme_raw($message);

        print "wait_in_loop: $message\n";
        $hshmsg = $emi->parse_message($message);

        $chksum = $hshmsg->{checksum};
        $rpid   = $hshmsg->{rpid};
        $dcs    = $hshmsg->{dcs};
        $type   = $hshmsg->{type};
        $len    = $hshmsg->{len};
        $xser   = $hshmsg->{xser};
        $mt     = $hshmsg->{mt};
        $trn    = $hshmsg->{trn};
        $ot     = $hshmsg->{ot};
        $srcmin = $hshmsg->{oadc};
        $dstmin = $hshmsg->{adc};
        $smsmsg = $hshmsg->{amsg};
        $tstamp = $hshmsg->{scts};

        &dumpme($profile, $srcmin, $dstmin, $type, $tstamp, $mt, $trn, $ot, $smsmsg);

        $ucp_string = $emi->make_52(
                  result => 1,
                  trn    => $trn,
                  ack    => 'A'
                  );

        if ( defined($ucp_string) ) {
                &logme_raw($ucp_string);

                ($acknowledge, $error_number, $error_text) = $emi->transmit_msg( $ucp_string, 10, 0 );
                print "transmit_msg: $error_text\n";
        }
  }
  else
  {
        print "no message from smsc\n";
  }
}

sub timedout {
  print "timeout reached...";

  exit 0;
}

sub logme
{
  my ($logdata) = @_;
  my ($logdate, $logtime);

  $logdate = strftime "%Y%m%d", localtime();
  $logtime = strftime "%H%M%S", localtime();

  open FLOG, ">> $logdir/$logdate-$profile.log";
  print FLOG "$logdate-$logtime -- $logdata\n";
  close FLOG;

  return 1;
}

sub logme_raw
{
  my ($logdata) = @_;
  my ($logdate, $logtime);

  $logdate = strftime "%Y%m%d", localtime();
  $logtime = strftime "%H%M%S", localtime();

  open FLOG, ">> $logdir/$logdate-$profile.raw";
  print FLOG "$logdate-$logtime -- $logdata\n";
  close FLOG;

  return 1;
}

sub dumpme
{
  my ($profile, $srcmin, $dstmin, $type, $tstamp, $mt, $trn, $ot, $smsmsg) = @_;
  my ($date, $time, $fname, $data);

  $date = strftime "%Y%m%d", localtime();
  $time = strftime "%H%M%S", localtime();

  $fname = "$date.$time.$tstamp";
  $data = "$profile|$srcmin|$dstmin|$type|$xser|$mt|$trn|$ot|$smsmsg";

  print "$data\n";
  &logme($data);

  open FILE, ">> $dumpdir/.$fname";
  print FILE "$data\n";
  close FILE;

  move("$dumpdir/.$fname","$dumpdir/$fname");
  return 1;
}

$emi->close_link();
print "done!";



1;


- Great leaders see the need, seize the opportunity, and serve without expecting anything in return. follow me on twitter @paulgonzaga

Sunday, October 16, 2011

JSP 101: How to make a POST and GET method request in JSP

I would like to share with you the GET and POST method request I created while doing some JSP coding.

The example below is a GET method request that will access a specific URL passing the parameters as query string. 


<%@ page language="java" session="false"
import="java.util.*"
import="java.io.*,java.net.*"
%>

<%
try {
        String strLine = "";
        String xmlReturn = "";
       
        URL url = new URL("http://www.example.com/yourscript.jsp?param1=testparam1¶m2=testparam2");

        // read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        while ((strLine = in.readLine()) != null) {
            xmlReturn += strLine;
        }

        // print out xml return by the server
        out.print(xmlReturn);
        in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

%>


The example below is a POST method request that will access a specific URL passing the parameters in a POST manner.


<%@ page language="java" session="false"
import="java.util.*"
import="java.io.*,java.net.*"
%>

<%
try {
        String strLine = "";
        String xmlReturn = "";

        URL url = new URL("http://www.example.com/yourscript.jsp");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
//      connection.setInstanceFollowRedirects(false);

        DataOutputStream xmlRequest = new DataOutputStream(connection.getOutputStream());
        xmlRequest.writeBytes("param1=testparam1&param2=testparam2");
        xmlRequest.flush();
        xmlRequest.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // server returned HTTP 200 and response okay.

                // read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                while ((strLine = in.readLine()) != null) {
                    xmlReturn += strLine;
                }


                // print out xml return by the server
                out.print(xmlReturn);
                in.close();
        } else {
                // server returned HTTP error code.
                out.print(connection.getResponseCode());
        }

} catch (MalformedURLException e) {
} catch (IOException e) {
}

%> 


Hope this helps you on your JSP endeavor. Happy coding!!

Quote for the day: The real heart of servanthood is security. Show me someone who thinks he is too important to serve, and I'll show you someone who is basically insecure. How we treat others is really a reflection of how we think of ourselves. - john m.

Saturday, October 15, 2011

How to align in center your modal page in jQuery

I have created a jQuery function that will align your modal page in center. The alignment will default to "0" if it encounters a negative value.

Please see below script.

$.fn.doCenter = function () {
    var topVal = (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop();
    var leftVal = (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft();

    if (topVal < 0) topVal = 0;
    if (leftVal < 0) leftVal = 0;

    this.css("position","absolute");
    this.css("top", topVal + "px");
    this.css("left", leftVal + "px");

    return this;
}


Sample usage:

$("#yourmodal").doCenter();


Give it a try, you will love it!!

Thursday, October 13, 2011

How to parse an XML return across browser and return an XML object via jQuery.

I came to across to a problem where I can't parse the XML return from the REST URL using jQuery on IE browser.

Since our best friend IE has another way of thinking, I come up with a function that cater all XML parsing (across browser).

The function below parseXMLToObj will accept parameter xmlData, which can either be an object or an XML string.

The function will return the converted XML object which you can use in doing some jQuery stuff.

You can download jQuery from here: http://code.jquery.com/jquery-latest.js


function parseXMLToObj(xmlData) {
        if ($.isXMLDoc(xmlData) || !$.browser.msie || ($.browser.msie && document.documentMode == 9)) {
                return $(xmlData);
        } else {
                var xmlDoc = $.parseXML(xmlData);
                return $(xmlDoc);
        }
}


Sample Usage:

var xmlData = "<results><data>1</data><data>2</data></results>";
parseXMLToObj(xmlData);


Goodluck! Happy coding!!

Tuesday, September 20, 2011

JS 101: How to get URL parameters from HTML page

Same with PHP or ASP page, HTML will be able to get the query string parameters but not that as easy compare to PHP and ASP.

We can get it by parsing the URL parameters via javascript, and to help you with, I created a script below that does it.

The script will parse and get the "spage" parameter of the HTML page and prompt it via alert dialog box. Sample URL will be.. index.htm?spage=1..

var spage = getUrlParam("spage");
alert(spage);

function getUrlParam(param)
{
    var hash = [];
    var value = '';
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    

    for(var i = 0; i < hashes.length; i++) { 
        hash = hashes[i].split('='); 
        if (hash[0] == param) value = hash[1]; 
    } 

    return value;
}

Hope you like it!!

Sunday, September 18, 2011

IE 101: Misalignment of element on IE browsers

In web development, most developers have issues on IE compatibility. One of the problem I encountered are the misalignment of the element in IE browser, specially the IE8.

This is due to the styling you made on alignment. We normally use vertical alignment in CSS to align our element vertically.

Problem here is that the value "text-top" is not working on IE8. Hence, you have to use "top" instead, which is the same behavior with "text-top".

In your CSS entries, instead of using this one:

vertical-align: text-top;

You have to use this one:

vertical-align: top;


Hope this helps.

I'll be posting more of IE issues to help other developers to get through with it. Follow IE 101 for more of IE posts.

Sunday, August 7, 2011

IE7 Error: Expected identifier, string or number

Most developers are suffering from IE7 compatibility issue. Most of the time, we encounters error when doing javascript. One of the error I encountered was "Expected identifier, string or number".

This error is due to IE expecting a data. For the sake of this post, I will use the jcarousel plugin passing the parameters we need.

<script type="text/javascript">
$(document).ready(function() {
    $(".carousel").jCarouselLite({
        visible: 3,
        btnPrev: 'a.prevbtnHome',
        btnNext: 'a.nextbtnHome',
    });
});
</script>

As you can see on the sample JS above, we are passing parameters ending all with comma ",". This approach will actually work on most browsers but not on IE7 and below.

To resolve this, you just need to remove the comma "," on the last parameter.

<script type="text/javascript">
$(document).ready(function() {
    $(".carousel").jCarouselLite({
        visible: 3,
        btnPrev: 'a.prevbtnHome',
        btnNext: 'a.nextbtnHome'
    });
});
</script>

Hope this post helps a lot!

Perl 101: Accessing HTTPS URL via LWP

LWP(Library for WWW in Perl) is a Perl library that you can use to access the URL via back-end. However, accessing the URL via HTTPS needs SSL verification which stops your script from running.

Basically, if you are to access the HTTPS URL via browser, it will prompt you to verify the certificate which you have to accept before you actually be able to access it successfully.

To do it via back-end, we will have to do the same but this time, no interface.

First, we need to do SSL verification on the actual server that you will be using to access the URL, and to do that, we will use LYNX command and save the certificate if prompted.

Please see sample syntax below.

lynx https://example.mydomain.com/myscript.php..

If you don't have LYNX, you can do the normal way by accessing it via the browser. All you need to do is to access the browser of the actual server and save the certificate from there.

To check if successful, try to access the URL again, and you should not be prompted to save the certificate again. Hence, saving certificate is not successful.

Once okay with the certificate, we are now good to use LWP library to access the URL.

Please take note that the libraries below should be installed in your server.
- LWP::UserAgent
- HTTP::Request
- Crypt::SSLeay

The script below will be able to access the HTTPS URL. Hope you like it!

#!/usr/bin/perl
use LWP;

my $url = 'https://example.mydomain.com/myscript.php';
my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 0 });
$ua->timeout(60000);

my $res = $ua->get($url);
print "result: $res\n";

1;

Saturday, June 18, 2011

Resolution: Codeigniter HTACCESS with GoDaddy NOT working.

I'm having problems with GoDaddy web hosting when I used Codeigniter as my framework in developing my site. All the pages I made are can't be found and it seems like that my .htaccess is NOT working and the page always echo the message "No input file specified."

As per Codeigniter documentation, by default, the index.php file will be included in your URLs:

example.com/index.php/news/article/my_article

And you can easily change the URL and do mod_rewrite using .htaccess. See below.

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Unfortunately, this is NOT working with GoDaddy, and to resolve this, instead having the above .htaccess, your entry should be like this.

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ index.php?$1 [L]


Hope this helps you as well.

Saturday, May 21, 2011

Tips & Tricks: Changing the site address using HTML FRAMES

To change the site address or do redirection using your own URL, you can use HTML FRAMES.

All you need to do is to supply the site address on source attribute of the FRAME and set the columns and rows to 100%.


<html>
<frameset cols="100%">
<frameset rows="100%">
<frame src="http://www.google.com/">
</frameset>
</frameset>
</html>


Hope this post helps you!

Sunday, May 15, 2011

How to make your background image as carousel using CSS and jQuery

This post will teach you how to set your background as carousel of images using CSS and jQuery.

To do this, just follow the 3 simple steps below.

1. First, you should have the list of images for your site's background.

2. Set an id for your <body> tag, let say id="body" as stated below.

<html>
<head>
</head>
<body id="body">
</body>
</html>

3. Create a javascript that changes the background-image property of the body tag using jquery and set it in a loop using setTimeout().

<script type="text/javascript">
        function carousel_bg(id) {
                var bgimgs = [ '1920x625_Sonata_homepage_image.jpg', '1920x625_Equus_homepage_image.jpg', '5_home_hero_1920x625_CF_background.jpg' ]; // add images here..
                var img = bgimgs[id];
                var cnt = 3; // change this number when adding images..

                $('#body').css("background-image", "url(http://www.pitstopmotors.com.ph/images/"+img+")");

                id = id + 1;
                if (id==cnt) id = 0;

                setTimeout("carousel_bg("+id+")", 10000);
        }

        $(document).ready(function() {
                carousel_bg(0);     
        });
</script>

You can still add images by adding the image filename on the array "bgimgs" and change the variable "cnt" to add images as part of the loop.. and that's it.

To get the complete code, please see below.

<html>
<head>
<title>Hotshots Carousel Background</title>

<script type="text/javascript" src="http://www.pitstopmotors.com.ph/js/jquery-1.4.2.js"></script>
<script type="text/javascript">
        function carousel_bg(id) {
                var bgimgs = [ '1920x625_Sonata_homepage_image.jpg', '1920x625_Equus_homepage_image.jpg', '5_home_hero_1920x625_CF_background.jpg' ]; // add images here..
                var img = bgimgs[id];
                var cnt = 3; // change this number when adding images..

                $('#body').css("background-image", "url(http://www.pitstopmotors.com.ph/images/"+img+")");

                id = id + 1;
                if (id==cnt) id = 0;

                setTimeout("carousel_bg("+id+")", 10000);
        }

        $(document).ready(function() {
                carousel_bg(0);     
        });
</script>
</head>
<body id="body">
</body>
</html>

Resolution to NuSOAP XML Parsing Error: XML or text declaration not at start of entity..

As I was doing a web service using NuSOAP in PHP, I encountered an XML Parsing Error saying "XML or text declaration not at start of entity.."

I re-checked my code multiple times but can't find any syntax problem.

I tried searching in google to find answers, but most of the forums are saying about the trailing spaces in the XML format which I believe I don't have.

Given that, I have NO CHOICE but to find it by myself..

After a long trial and error, doing some changes in the script.., removing some extra spaces.., replacing special characters.., removing some extra lines.., etc...

I was able to reach the end of the script and saw the new line after the PHP end tag "?>"..

Still in doubt, but I tried removing it.. and guess what?? it works!! That is a proof that patience and perseverance really works.. hehehe!!

Anyway, I can't believe that NuSOAP missed this.. Hope that their next version was able to resolve this..

Sunday, May 8, 2011

How to set your facebook page and apps username

First, not all pages and apps are eligible to have a username in facebook, you need at least 25 facebook users to like your page and apps.

To set your username, just follow the steps below.

1. Login to your facebook account.

2. Go to this link - http://www.facebook.com/username/

3. Choose a page or apps you want to set a username.

4. Facebook will check if it is eligible to have it.

5. If eligible, you will be prompt to set the username.

And that's it!! very simple hahh..

Saturday, May 7, 2011

How to sort playlist on youtube custom player

I see a lot of people having problems in sorting video playlist of their youtube custom player.

By default, without doing anything, youtube custom player will sort videos from oldest to latest but most of us wanted to sort videos from the latest to oldest.

Here is what I found to resolve this, and to do this is NOT through youtube custom player but on the video playlist.

Please see steps below.

1. Login to your youtube account.

2. Go to your video playlist - http://www.youtube.com/my_playlists

3. Change the order by changing the number of your videos by clicking the number of each videos and change it.

4. This should be done each time you added a new video, unless google was able to have this on custom player.

5. Changing the playlist order will changed custom player accordingly.

Monday, May 2, 2011

Handling HTML checkbox in AJAX

This post will teach you how to check and uncheck all the checkbox in a table using a toggle checkbox.

I have created 3 functions below.
  • check_toggle - this will toggle checkbox whether check all or uncheck all.
  • check_all - this will check all the checkbox in the form.
  • uncheck_all - this will uncheck all the checkbox in the form.
Please see implementation below.

<script type="text/javascript">

function check_toggle() {
        var obj = document.frmdata.checkbox_toggle;
        if (obj.checked==true) {
                check_all();
        } else {
                uncheck_all();
        }
}

function check_all() {
        var obj = document.frmdata.checkbox
        if (!obj.length) {
                obj.checked = true
        } else {
                var x = 0;
                for (x = 0; x <= obj.length; x++) {
                        obj[x].checked = true
                }
        }
}

function uncheck_all() {
        var obj = document.frmdata.checkbox
        if (!obj.length) {
                obj.checked = false
        } else {
                var x = 0;
                for (x = 0; x <= obj.length; x++) {
                        obj[x].checked = false
                }
        }
}

</script>

<form id="frmdata" name="frmdata">
<table>
        <tr>
                <td><input type="checkbox" name="checkbox_toggle" id="checkbox_toggle" onclick="check_toggle();"></input></td>
                <td>Description</td>
        </tr>
        <tr>
                <td><input type="checkbox" name="checkbox" id="checkbox"></input></td>
                <td>Row 1</td>
        </tr>
        <tr>
                <td><input type="checkbox" name="checkbox" id="checkbox"></input></td>
                <td>Row 2</td>
        </tr>
         <tr>
                <td><input type="checkbox" name="checkbox" id="checkbox"></input></td>
                <td>Row 3</td>
        </tr>
</form>

Wednesday, April 13, 2011

Generating random unique codes in PERL

This post will teach you how to generate random unique codes in PERL. Just follow the simple steps below. Enjoy!!

1. Create an array of character set combination. Below was set to 29 alphanumeric characters excluding other characters with similarities.

my @arrCharset = split //, "abcdefhjkmnpqrstuvwxyz2345678"; # 29 alphanumeric characters

2. Set the number of random codes you want to generate and set it into the loop.

$intCodes = 540000; # this will generate 540,000 random codes.
for ($i=1; $i<=$intCodes; $i++)
{
  ##.......... see step #3 ..........
  ##.......... see step #5 ..........
}

3. Inside the loop in step #2, set the number of characters you wanted on each code and create a loop to generate random code.

$intCharCnt = 6; # this will generate 6 characters per code.
for ($l=1; $l<=$intCharCnt; $l++)
{
  ##.......... see step #4 ..........
}

4. Inside the loop in step #3, pick a random character in the character set in step #1 and generate the code. 

$intRand = int(rand(scalar(@arrCharset)));
$strCode .= $arrCharset[$intRand];

5. Once the code was generated, check this with hashes of codes if exists. If exists deduct the counter of random codes we set in step #2, If not then write to hash. This will make the generation of codes unique.

if (exists($hshCodes{$strCode}))
{
    $i --;
}
else
{
    $hshCodes{$strCode} = 1;
    print "$strCode\n";
}

Please see below for the complete random unique code generator.

#!/usr/bin/perl

my @arrCharset = split //, "abcdefhjkmnpqrstuvwxyz2345678"; # 29 alphanumeric characters
my %hshCodes;
my ($i, $l, $strCode);

$intCodes = 540000; # this will generate 540,000 random codes.
$intCharCnt = 6; # this will generate 6 characters per code.

for ($i=1; $i<=$intCodes; $i++)
{
  $strCode = '';
  for ($l=1; $l<=$intCharCnt; $l++)
  {
    $intRand = int(rand(scalar(@arrCharset)));
    $strCode .= $arrCharset[$intRand];
  }

  if (exists($hshCodes{$strCode}))
  {
    $i --;
  }
  else
  {
    $hshCodes{$strCode} = 1;
    print "$strCode\n";
  }
}


1;

Saturday, April 9, 2011

GREP command in linux / unix

GREP command searches the file for a lines match to a string, words, or characters we pass on.
Syntax: grep [-option] 'search word' /path/to/file

Options are as follows:
  • -i : to ignore word case.
  • -r : recursively read files under each directory.
  • -w : to get the matching word only.
  • -c : to count number of lines that the search word matches.
  • -P : to use regex command within the grep command.
  • -l : to list the file names matching the search word.
  • -v : to get lines that doesn't match the search word.

Sample GREP commands:

- default grep command without using an option.
$ grep 'word' /path/to/file

- ignoring word cases and matches
$ grep -i 'word'/path/to/file

- using regex to get all the lines that matches
$ grep -P "word1|word2" /path/to/file
$ grep -P "^word3" /path/to/file

- matching the exact words in a line
$ grep -w "word" /path/to/file

- get the file names that matches the search word.
$ grep -l "init()" /path/to/file*

- invert matches to the line
$ grep -v "word" /path/to/file

- grep command combining options and uses pipe to execute next grep command.
$ grep -ivP "word1|word2" /path/to/file
$ grep -i "word" /path/to/file | grep -vP "word2"

IN_ARRAY sub function in PERL

IN_ARRAY is one of the common functionality in PHP that searches data in an array - http://php.net/in_array. This function takes 2 parameters: (1) the search key and (2) the array stack, it returns boolean whether found or not.

This functionality lacks in Perl and with this post, we can now have it in Perl.

The function below follows the same parameters we set in PHP: in_array(<search key>, <array>). This function map the array into hash in which Perl can do searches and returns 1 or 0.

Hope you like it!! Enjoy!

sub in_array
{
     my ($search_key, @arr) = @_;

     my %items = map {$_ => 1} @arr;
     return (exists($items{$search_key})) ? 1 : 0;
}


Usage:

#!/usr/bin/perl

my @arr = ('Paul','Raf','Tina','Mich');

sub in_array
{
     my ($search_key, @arr) = @_;

     my %items = map {$_ => 1} @arr;
     return (exists($items{$search_key})) ? 1 : 0;
}

if (&in_array('Paul', @arr))
{
     print "Got you Paul!!\n";
}
else
{
     print "Paul not found!!\n";
}


1;


Output:

paulgonzaga:Perl paulgonzaga$ perl in_array.pl
Got you Paul!!
paulgonzaga:Perl paulgonzaga$

Sunday, April 3, 2011

File handling in PERL

We have 2 ways on how to write to a file in PERL.

The script below will create and write to a file overwritten the data inside the file. The script will automatically creates a file if it doesn't exist. An error will return if there's a file permission denied or directory path doesn't exist.

open FHFILE, "> file1.txt" or die "file can't be created: $!";
print FHFILE "test data\n";
close FHFILE;

The script below will create and append to a file. Same with #1, it automatically creates a file and an error will return if there's a file permission denied or directory path doesn't exist.

open FHFILE, ">> file1.txt" or die "file can't be created: $!";
print FHFILE "test data\n";
close FHFILE;

The script below will read the file then pass the data into an array. An error will return if file is not readable.

open FHFILE, "< file1.txt" or die "error reading file: $!";
@arrData = <FHFILE>;
close FHFILE;

Sunday, March 27, 2011

How to retrieve your twitter feeds in PERL

Retrieving twitter feeds is very simple and easy, you only need an HTTP request that returns format such as JSON, XML, RSS, and ATOM. This method doesn't require authentication.

Just follow the simple steps below using PERL. Hope you like it!

1. Install LWP::UserAgent in your server.

2. Initialize libraries, header and user agent.

require LWP::UserAgent;

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://api.twitter.com/',
             'User-Agent' => $uagent);

3. Compose the HTTP request.

my $twuser = '<your twitter username>';
my $twurl = "http://api.twitter.com/1/statuses/user_timeline.<format>?screen_name=$twuser";

Supported Format:
  • JSON
  • XML
  • RSS
  • ATOM
URL Parameters:
  • user_id - The id of twitter account you want to retrieve.
  • screen_name - The username of twitter account you want to retrieve.
  • since_id - This will return the feeds after or more than the specified message id.
  • max_id - This will return the feeds before or less than the specified message id.
  • count - The number of tweets to be retrieve.
  • page - This will specify the page of the result to retrieve.
  • trim_user - When set to either true, t or 1, each tweet returned in a timeline will include a user object including only the status authors numerical id.
  • include_rts - When set to either true, t or 1, the timeline will contain native retweets (if they exist) in addition to the standard stream of tweets.
  • include_entities - When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future.
4. Execute HTTP GET request.

my $response = $lwpua->get($twurl, @header);
my $return = $response->content;


That's it!! Please see below for the complete code using JSON format.

#!/usr/bin/perl

require LWP::UserAgent;
use JSON;

my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'http://api.twitter.com/', 'User-Agent' => $uagent);

my $twuser = '<your twitter username>';
my $twurl = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$twuser";

my $response = $lwpua->get($twurl, @header);
my $return = $response->content;

my $json = JSON->new->allow_nonref;
my $json_text = $json->decode($return);

my @tweets = @{$json_text};

my $message;
foreach $tweet (@tweets)
{
  $message .= $tweet->{text}."\n";
}

print "$message";



1;

Resource: dev.twitter.com

Wednesday, March 23, 2011

How to set up an auto adjust width and height in CSS

Again, our best friend IE has it's own way of doing things. IE interprets width and height as min-width and min-height which is totally different from other browser. Given that, this can be a problem if we want our container to adjust accordingly to the content we want to display.

To resolve this, please see below.

#container {
        background-color:#FFFFFF;
        width:840px;
        height:450px;
}
html>body #container {
        height: auto;
        width: auto;
        min-height:450px;
        min-width:840px;
        overflow:hidden;
}

All browsers including our best friend IE will read through the first set of CSS rule #container and the second set will not be interpret by IE because it uses child selector 'html > body' in which interprets Non-IE browser.

Monday, March 21, 2011

How to get latitude and longtitude values from google maps

There are 2 ways on how to get the latitude and longtitude coordinates from google maps.

First option is to get it using javascript:

Just follow the simple steps below to do it.

1. Go to google maps website - http://maps.google.com

2. Click to the center of the site you want.

3. Once you are at the center, copy and paste the code below on your browser's address bar.

javascript:void(prompt('',gApplication.getMap().getCenter()));

4. A pop-up message will prompt with the latitude and longtitude values enclosing with parenthesis.

5. Check the returned values by putting it to google maps search bar and enter. An arrow will point to the map where the location is.

Problem here is that you have to be at the center of the Map to get the actual coordinates.

Resource: http://lifehacker.com


Second is to get it the easier way by enabling the options on your google maps account:

Just follow the simple steps below to activate.

1. Go to google maps website - http://maps.google.com/

2. Log-in to your google account.

3. On the upper right corner of the page, you will see the Options Icon tab.

4. Click the Options Icon tab and select "Maps Labs".

5. A lightbox page will pop-up displaying all the options available for google maps.

6. Set the "LatLng Tooltip" and "LatLng Marker" to ENABLE, then save changes.

7. Go to the map, zoom in until you get to the site you want, then click and hold the "Shift" key on your keyboard.

8. You will noticed that every time you move the cursor while holding shift button, latitude and longtitude changes accordingly.


Hope you like it!! Yeah men!!

Sunday, March 20, 2011

Setting up a style in table header and data records

Just sharing you the basic but a good look style for table display.

table tr td, table tr th {
        font-size: 9px;
        background-color: #ECEFF5;
        border: 1px dotted #0B3485;
        color: #0B3485;
        height: 25px;
        padding: 2px;
        vertical-align: middle;
}


Details are as follows:
  • font-size - The size of the font you want.
  • background-color - The background color of your table.
  • border - The border of your table, I set it to 1px dotted to be not so usual.
  • color - The color of your text.
  • height - The height of each table row.
  • padding - This is to setup a padding in displaying records.
  • vertical-align - To align the data vertically. I set it to middle to vertically align it in center.

Setting up a style in form input button

By default, input button and submit type is not really in a good look.. I recommend to style it with a simple CSS entry below. Hope you like it!!

input[type="button"], input[type="submit"] {
    background-color#1E6591;
    border2px solid #1E6591;
    color#FFFFFF;
    font-size11px;
    font-weightbolder;
}


Details are as follows:
  • background-color - This is the background color of your button.
  • border - The border of your button.
  • color - The color of the text in a button.
  • font-size - The font size of the text of the button.
  • font-weight - The font weight of the text of the button. This is either normal or bold. By default it's equal to normal.

Setting up a style in form input text and textarea

By default, input text and textarea in a form is not really in a good look.. I recommend to style it with a simple CSS entry below. Hope you like it!!

input[type="text"], textarea {
        background: #f9f9f9;
        border: 1px solid #ccc;
        box-shadow: inset 1px 1px 1px rgba(0,0,0,0.1);
        -moz-box-shadow: inset 1px 1px 1px rgba(0,0,0,0.1);
        -webkit-box-shadow: inset 1px 1px 1px rgba(0,0,0,0.1);
        padding: 2px;
        font-family: "lucida grande",verdana,tahoma,arial,sans-serif;
}


Details are as follows:
  • background - This will be the color of the box shadow
  • border - Color of the box border
  • box-shadow - This is the current standard in CSS shadow settings
  • -moz-box-shadow - This is used to support way too old version of Mozilla
  • -webkit-box-shadow - This is used to support other browser
  • padding - To implement padding between other elements.
  • font-family - To put a style in fonts for textarea and input text.

Hope this helps a lot. Happy coding!!

Wednesday, March 16, 2011

How to checkin to foursquare via backend using PERL and PHP

Checking in to foursquare is more likely the same as posting a shout out, tweet or status in social network like facebook and twitter.

Foursquare follows authentication via OAuth and this post will teach you how to do it via back-end using PERL and PHP.

I assume you already read my post on how to Login to foursquare via back-end in PERL. You should be able to understand it first to proceed with authentication and do the check-in in users behalf.

Just follow the simple steps for your implementation.

1. You must have a Client ID and the Callback URL. If you don't have yet, create one by going to foursquare developers link - http://developer.foursquare.com/

2. To register a new consumer, click the "Manage OAuthConsumers" link or go to OAuth page - https://foursquare.com/oauth/

3. Enter your Application Name, Application Website, and Callback URL. Please take note that your Callback URL will be your Redirect URI.

4. After successful registration, Client ID and Client Secret will be generated.

5. What we need from now is the Client ID and once we have it, we can now start the coding part.

6. First thing we have to do is to login to users account via back-end. Please see post - Login to foursquare via back-end in PERL

7. After successful login, next step is to authenticate your application. To authenticate your app, you should pass a Client ID and your Callback URL that was registered from Consumer Registration.

$client_id = '<your client id>';
$redirect_uri = '<your callback url>';

$response = $lwpua->get("https://foursquare.com/oauth2/authenticate?client_id=$client_id&response_type=code&display=touch&redirect_uri=$redirect_uri", @header);

$form_data = $response->content;
$form_data =~ s/\n//g;

8. If this is the first time you authenticate your app, return page will be asking users permission to "Allow" the application to access account details and transact in users behalf. We can do this in back-end by implementing REGEX to get the NAME parameter of the value="Allow", then passed it on to authentication URL - https://foursquare.com/oauth2/authenticate.

$form_data =~ /form method="post" action="(.*?)"(.*?)input value="Allow" type="submit" name="(.*?)" class="input_button"/ig;

$form_action = $1;
$form_allow = $3;

$response = $lwpua->get("https://foursquare.com/oauth2/authenticate?$form_allow=Allow", @header);
$form_data = $response->content;

9. After allowing the application, foursquare will redirect the user to redirect URI that we set on step #7. Your callback URL or redirect URI must capture the CODE parameter and exchange it with TOKEN. This can now be done via PHP.

10. Foursquare will pass the CODE parameter via GET method on our Callback URL. Our Callback URL should be able to capture it and use it in exchange of an access token. To get an access token, we should pass the CODE parameter, Client ID, Client Secret, Callback URL, and Grant Type to the access token URL - https://foursquare.com/oauth2/access_token. Client ID, Client Secret, and Callback URL are data from the consumer registration, and the Grant Type should be equal to "authorization_code". Please take note that this is now on PHP.

$client_id = '<your client id>';
$client_secret = '<your client secret>';
$redirect_uri = '<your callback url>';
$grant_type = 'authorization_code';

$code = $_GET['code'];      
$oauthurl = "https://foursquare.com/oauth2/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=$grant_type&redirect_uri=$redirect_uri&code=$code";

11. As per implementation below, I use the open stream to get the contents and convert it to JSON which will then return an object with an access token.

$url_handler = fopen("$oauthurl", 'r');
$json = json_decode(stream_get_contents($url_handler));
fclose($url_handler);

$token = $json->access_token;

13. Now that you have the Token, we are now ready to do the Foursquare Check-in. Going back to PERL, what we need to do here is to do a POST request to Foursquare API URL - https://api.foursquare.com/v2/checkins/add. venueId will be the place or location you want to check-in, shout is optional if you want your post to have a custom message, broadcast can be of public or private, and lastly the oauth_token which is the access token we get from step #12. Again, this is now in PERL.

$intVenueID = "<the venue id you want to check-in>";
$strShout = "<your shout message>";
$strToken = "<your access token>";

$response = $lwpua->post("https://api.foursquare.com/v2/checkins/add",
                      ['venueId' => $intVenueID,
                       'shout' => $strShout,
                       'oauth_token' => $strToken,
                       'broadcast' => 'public,faceboook,twitter'], @header);

print $response->content;

That's it!! Hope you were able to follow. In case you don't, you can refer to the scripts below. Good luck and enjoy!!

- Here's the PERL script, it composes of 2 sub functions: check_foursquare_login() and post_foursquare_checkin()


#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://foursquare.com',
             'User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = "<your foursquare username>";
my $strPass = "<your foursquare password>";
my $client_id = "15NGPG2GHI3S1UFMST01FOO0ABPXNFFTGJVTVSZS55W1UN4A";
my $redirect_uri = "http://localhost/foursquare/foursquare.php";
my $status = "testing foursquare status";

my $form_data = &check_foursquare_login($strUser, $strPass, $client_id, $redirect_uri);

if ($form_data =~ /^OK\|/)
{
  my ($strTag, $intUserID, $strToken) = split /\|/, $form_data, 3;
  &post_foursquare_checkin($intUserID, $strToken, '', $status);

  unlink($cookie_file);
  print "done!";
}
else
{
  $form_data =~ /form method="post" action="(.*?)"(.*?)input value="Allow" type="submit" name="(.*?)" class="input_button"/ig;

  my $form_action = $1;
  my $form_allow = $3;

  my $response = $lwpua->get("https://foursquare.com/oauth2/authenticate?$form_allow=Allow", @header);
  $form_data = $response->content;

  if ($form_data =~ /^OK\|/)
  {
    my ($strTag, $intUserID, $strToken) = split /\|/, $form_data, 3;
    &post_foursquare_checkin($intUserID, $strToken, '', $status);

    unlink($cookie_file);
    print "done!";
  }
  else
  {
    unlink($cookie_file);
    print "error authentication!";
  }
}

sub check_foursquare_login
{
  my ($strUser, $strPass, $client_id, $redirect_uri) = @_;

  # log-in to foursquare
  my $response = $lwpua->post('https://foursquare.com/mobile/login',
                      ['username' => $strUser,
                       'password' => $strPass], @header);
  $cookie_jar->extract_cookies( $response );
  $cookie_jar->save;

  $response = $lwpua->get("https://foursquare.com/oauth2/authenticate?client_id=$client_id&response_type=code&display=wap&redirect_uri=$redirect_uri", @header);

  $form_data = $response->content;
  $form_data =~ s/\n//g;

  return $form_data;
}

sub post_foursquare_checkin
{
  my ($strUserID, $strToken, $intVenueID, $strShout) = @_;
  my ($response);

  $response = $lwpua->post("https://api.foursquare.com/v2/checkins/add",
                      ['venueId' => $intVenueID,
                       'shout' => $strShout,
                       'oauth_token' => $strToken,
                       'broadcast' => 'public,faceboook,twitter'], @header);

  return $response->content;
}



1;


- Here's the PHP script. Save this in your web server and set this as your callback URL in consumer registration.


<?

$client_id = "15NGPG2GHI3S1UFMST01FOO0ABPXNFFTGJVTVSZS55W1UN4A"; // hotshots client id
$client_secret = "NEHCL3UL0KS1QJD22NLIQ5RMR4BL4IUZIJZW25VHSJ4JPZKB";
$grant_type = "authorization_code";
$redirect_uri = "http://localhost/foursquare/foursquare.php";

$code = $_GET['code'];

if ($code) {
        // get access token
        $oauthurl = "https://foursquare.com/oauth2/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=$grant_type&redirect_uri=$redirect_uri&code=$code";

        $url_handler = fopen("$oauthurl", 'r');
        $json = json_decode(stream_get_contents($url_handler));
        fclose($url_handler);

        $token = $json->access_token;
        if ($token) {
                $info_contents = `curl https://api.foursquare.com/v2/users/self?oauth_token=$token`;
                $json = json_decode($info_contents);
                $userid = $json->response->user->id;

                echo "OK|$userid|$token";
        }
}


?>

Monday, March 14, 2011

How to embed a custom youtube player in your website


For you to be able to embed a youtube player in your website, you should have a youtube account to access into.

If you have one already, just follow the simple steps below and you were able to create a custom player that you can put into your website.

1. Go to youtube website - http://youtube.com and enter your username and password.

2. Once logged-in, go to custom player page - http://www.youtube.com/custom_player.

3. On the custom player page, enter your desired player name and description.

4. Select the theme color that you like.

5. Select the layout for your player.

6. Choose the content that you want to be played. Contents are either your own videos, your favorite videos, or one of your playlist. Don't forget to click the "Select" button to confirm the contents that you want.

7. To finally generate the code, just click the "Generate Code" button and the embed code will be generated.

8. Copy the embed code and click the "Finish" button to go to your list of players.

9. To add the newly created player into your site, just paste the code you just copied and save it. You should be able to see the player you just created in your site.

10. To edit your players, go to this link - http://www.youtube.com/my_players then select the player you want to edit. The chosen layout will not be editable.

Hope you like it!! This is just a sample implementation. Thank you for reading this post.

Thursday, March 10, 2011

Converting numeric values to currency formatted numbers in PERL

While developing a particular report in Perl, I just noticed that my output for currency values are just numbers without commas and decimal points. So, I do some research to check for an existing function in Perl that simply do this conversion but didn't find anything.. No choice.. I have to create a sub function that converts numeric values to currency values, and I did and now sharing this to you..

Please see sample code and sub function that I just created. Hope you like it!!

#!/usr/bin/perl

$number = 4356789; # sample data
$currency = &convert_to_currency($number);

print "Here we go in Peso value: P$currency\n";

sub convert_to_currency
{
        my ($number) = @_;

        $number = sprintf("%.2f", $number);
        $number = "$1,$2$3" while ($number =~ /(.*\d)(\d\d\d)(.*)/i);
        return $number;
}



1;

Sunday, March 6, 2011

CSS class for transparency that all browsers support

Personally, one of my favorite in web designs are transparency. It gives life to your site as you will have layers of texts and images in one look.

It's great thing haa!! but did you know that having that in your site is a challenge for us programmers? That is because we have to consider all browsers to support transparency in one time setting.

Good thing..!! The class below will resolve the implementation of transparency for all browsers.

.transparency {
    opacity: 0.5;
    filter: alpha(opacity=50);
    -moz-opacity: 0.5;
    -khtml-opacity: 0.5;
}

Below are the CSS properties we used:
  • opacity: 0.5; - This is the current standard in CSS transparency settings. This will work in most versions of Firefox, Safari, and Opera.
  • filter: alpha(opacity=50); - This one is for our best friend IE.
  • -moz-opacity: 0.5; - This one you need for way too old version of Mozilla.
  • -khtml-opacity: 0.5; - This one you need for old Safari (1.x).
Resource: css-tricks.com

Thursday, March 3, 2011

How to create a directory watcher in PERL


Most of the time, we want to achieve a REAL-TIME processing. However, there are some limitations that we don't have control over, and one of the best example is without having a direct connection to the application you are processing into.

One way to achieve a REAL-TIME processing without a direct connection is to have a back-end processing that will watch and process transactions. This is what we called directory watcher.

With this post, it will help you create a directory watcher in PERL. Just follow the simple steps below to do that.

1. Set the look up directory where you want your script to look into.

2. Create a NON-ENDING loop using WHILE() syntax. To create a NON-ENDING loop, we just have to pass a variable or condition that will always results to TRUE. Example below pass a variable 1 that results to TRUE. And as best practice, a SLEEP function should be implemented every end of each loop, this is for the script not to eat too much of the memory.

while(1) {
  # this creates a non ending loop coz 1 is equal to true..

  sleep 1;
}

3. Inside your WHILE loop, you have to OPEN the look up directory by using OPENDIR() syntax. And as best practice, you need to close the directory every end of the loop.

opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";

4. Loop the files we read from a look up directory.

opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";
while ($file = readdir(DIR))
{
  # file names from a reading directory...
}
closedir DIR;


Hope you like it!! Please see the complete code below for your implementation.

#!/usr/bin/perl

$lookup_dir = "<directory to look into>";

while(1)
{
        print "lookup directory: $lookup_dir\n";

        opendir(DIR, $lookup_dir) || die "Cannot opendir $lookup_dir: $!";
        while ($file = readdir(DIR))
        {
                if (($file ne '.') && ($file ne '..') && ($file !~ /^\./))
                {
                        print "here file: $file\n";
                        # do what you want with the file...
                }
        }

        closedir DIR;
        sleep 1;
}




1;

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.