tag:blogger.com,1999:blog-37350254821168103462024-03-05T14:43:44.522+06:00টেকনোলজি ব্লগপ্রোগ্রামিং ও তথ্য প্রযুক্তির অন্যান্য বিষয়ে আর্টিকেল, টিপস এবং নিউজ!Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.comBlogger34125tag:blogger.com,1999:blog-3735025482116810346.post-14534521281232350522012-03-18T14:04:00.000+06:002012-03-18T14:04:25.982+06:00Problem with strtotime in PHPToday I found an interesting issue. Please try this following PHP code:<br />
<code>print strtotime("18/03/2012 06:08 am");</code><br />
I didn't see any output. Then I looked at the <a href="http://php.net/strtotime">documentation</a> and found the following line:<br />
<blockquote>Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.</blockquote><br />
So I had to replace "/" with "-" using str_replace and that worked!<br />
<code>print strtotime("18-03-2012 06:08 am");</code><br />
Output:<br />
<code>1332029280</code>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-56791794034576015472012-03-05T15:45:00.001+06:002012-03-05T15:46:44.990+06:00Phone Number Extractor in PHPHere is a function to parse the content of a web page and extract phone / fax numbers (USA only). Regular expression is used to parse phone numbers.<br />
<br />
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4wOGPOeCWTCUizh8-qojnb_hSQux3zsdqj2O-xYDNPbx8VIn6DV7bRnSJZWSeyw_gIsOrzLjZCdlHXxvUENjBz3W20AGo7oqLo-GNqMCXnDcYQbxTOcDkgnsbhPm7cI46HfA2WPbbfFcc/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> function extract_phone_numbers ($html_content)
{
$html_content = preg_replace("/[\s\+\-\(\)\.]/", "", $html_content);
$ara = array();
if (preg_match_all('/\D(\d{10})\D/', $html_content, $data)) {
$ara = array_unique($data[1]);
}
if (preg_match_all('/1(\d{10})\D/', $html_content, $data)) {
$ara = array_unique(array_merge($ara, $data[1]));
}
if (preg_match_all('/^(\d{10})$/', $html_content, $data)) {
$ara = array_unique(array_merge($ara, $data[1]));
}
return $ara;
}
</code></pre>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-53456324490231930652012-03-05T15:41:00.000+06:002012-03-05T15:41:07.455+06:00Email extractor in PHP using regexToday, I am sharing my PHP code that extracts email address from html source of an URL. It uses regular expression to parse email address.<br />
<br />
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4wOGPOeCWTCUizh8-qojnb_hSQux3zsdqj2O-xYDNPbx8VIn6DV7bRnSJZWSeyw_gIsOrzLjZCdlHXxvUENjBz3W20AGo7oqLo-GNqMCXnDcYQbxTOcDkgnsbhPm7cI46HfA2WPbbfFcc/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> function extract_email_addresses ($html_source)
{
$html_source = str_replace("(at)", "@", $html_source);
$html_source = str_replace("[at]", "@", $html_source);
$html_source = str_replace("(dot)", ".", $html_source);
$html_source = str_replace("[dot]", ".", $html_source);
$html_source = strtolower($html_source);
$ara = array();
if (preg_match_all('/([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3}))/', $html_source, $data)) {
$ara = array_unique($data[1]);
}
return $ara;
}
</code></pre>Please share your thoughts to improve the function.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-40351972009281298962012-03-03T16:16:00.000+06:002012-03-03T16:16:49.750+06:00A simple crawler in Java<div dir="ltr" style="text-align: left;" trbidi="on">So far I have written crawlers in many languages (PHP, Perl, Python, C#). Recently I wrote another one in Java. This is a simple spider / crawler, that gets the html source and extracts all the URLs from that source and then checks the HTTP response of those URLs. <br />
<br />
Steps:<br />
<br />
1. Get the URL from user (as command line input).<br />
<br />
2. Get the html source code of that URL (using the function getUrlContent(url)).<br />
<br />
3. Get all the hyper-links from the html source code (using the function getHyperlinks(content)).<br />
<br />
4. For each of the URLs extracted from html source, get the HTTP Response code (using the function getHTTPResponseCode(url)).<br />
<br />
Here is the full code:</div><br />
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4wOGPOeCWTCUizh8-qojnb_hSQux3zsdqj2O-xYDNPbx8VIn6DV7bRnSJZWSeyw_gIsOrzLjZCdlHXxvUENjBz3W20AGo7oqLo-GNqMCXnDcYQbxTOcDkgnsbhPm7cI46HfA2WPbbfFcc/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Checker {
public static void main(String args[]) throws Exception
{
String url = null;
if (args.length > 0) {
url = args[0];
System.out.println(url);
}
else {
System.out.println("Please enter the URL as a command line parameter.");
return;
}
String content = getUrlContent(url);
ArrayList<String> links = getHyperlinks(content);
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
int status;
for (int i = 0; i < links.size(); i++) {
url = (String) links.get(i);
System.out.println(url);
status = getHTTPResponseCode(url);
if (status != 200) {
if (status > 0) {
out.write(url + ", HTTP Response Code: " + status + "\n");
}
else {
out.write(url + ", Unknown Error\n");
}
}
}
out.close();
}
private static ArrayList<String> getHyperlinks(String html)
{
ArrayList<String> links = new ArrayList<String>();
Pattern p = Pattern.compile("<a [^<>]*?href=\"(http.*?)\"");
Matcher m = p.matcher(html);
while(m.find()) {
links.add(m.group(1));
}
p = Pattern.compile("<a [^<>]*?href='(http.*?)'");
m = p.matcher(html);
while(m.find()) {
links.add(m.group(1));
}
return links;
}
private static String getUrlContent(String targetUrl) throws Exception
{
HttpURLConnection connection = null;
BufferedReader br = null;
StringBuilder sb = null;
String line = null;
String content = null;
URL target = null;
try {
target = new URL(targetUrl);
connection = (HttpURLConnection)target.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(30 * 1000); // timeout 30 seconds
connection.connect();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
content = sb.toString();
} catch (SocketTimeoutException e) {
System.out.println("Timed Out!");
} catch (UnknownHostException e) {
System.out.println("Unknown Host");
} catch (Exception e) {
System.out.println("Unknown Error");
}
finally {
connection.disconnect();
br = null;
sb = null;
connection = null;
}
return content;
}
private static int getHTTPResponseCode(String targetUrl) throws Exception
{
HttpURLConnection connection = null;
int response;
URL target = null;
try {
target = new URL(targetUrl);
connection = (HttpURLConnection)target.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(10 * 1000); // timeout 10 seconds
connection.connect();
response = ((HttpURLConnection) connection).getResponseCode();
} catch (SocketTimeoutException e) {
response = -100;
} catch (UnknownHostException e) {
response = -101;
}catch (Exception e) {
response = -102;
}
finally {
connection.disconnect();
connection = null;
}
return response;
}
}
</code></pre>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-82065248335600276252011-08-22T07:12:00.001+06:002011-08-22T07:14:50.639+06:00AJAX Call Problem in Facebook application http / https issueToday I got report from one of my client (for whom I have developed a facebook app recently) that in some browsers the app is not working. Nothing happens when a button is clicked (a facebook share dialog should appear)! So, I investigated the problem. I found that when the button is clicked, the URL used for AJAX call starts with https and in some browsers (example: Chrome) it was giving a javascript error. This is because the application started with http there where in some other facebook account, it start with https. So I handled the issue with the following code in my jQuery function that is called when the button is clicked:<br />
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4wOGPOeCWTCUizh8-qojnb_hSQux3zsdqj2O-xYDNPbx8VIn6DV7bRnSJZWSeyw_gIsOrzLjZCdlHXxvUENjBz3W20AGo7oqLo-GNqMCXnDcYQbxTOcDkgnsbhPm7cI46HfA2WPbbfFcc/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> var protocol = $(location).attr("protocol");
var loadUrl = 'http://secure.example.com/server/serve.php';
if (protocol == 'https:') {
loadUrl = 'https://secure.example.com/server/serve.php';
}
</code></pre>And it solved the problem!Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-43307502981795348452011-07-28T00:20:00.000+06:002011-07-28T00:20:40.472+06:00I am backIt's been a while I am not writing in this blog. But I frequently get into problems and find solutions searching Google, so I think I should write down my problems and solutions, at least the link. Sometimes I also read interesting blog posts about programming or software development or something else that is not worth sharing in facebook, so I shall share those links also with my comments.<br />
<br />
Stay tuned. :)Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-37236748431398226852010-09-18T21:50:00.000+06:002010-09-18T22:10:19.065+06:00PHP Script to get Alexa rank using Alexa APIHere is an example PHP code that uses Alexa API to get Alexa rank. Note that for Alexa API, you need to purchase keys, as it's not free. Though it's not free cost is very low.<br /><br />define("ACCESS_KEY_ID", "put key here"); <br />define("SECRET_ACCESS_KEY", "put key here");<br />define("SERVICE_ENDPOINT", "http://awis.amazonaws.com?");<br /><br />define("ACTION", "UrlInfo");<br />define("RESPONSE_GROUP", "Rank, LinksInCount");<br /><br />$results = array();<br /><br />function get_alexa_rank($site_url)<br />{<br /> global $results;<br /> $results = array();<br /> <br /> $awis_url = generate_url($site_url);<br /><br /> $result = make_http_request($awis_url);<br /><br /> // Parse XML and display results<br /><br /> $current_tag = "";<br /><br /> $xml_parser = xml_parser_create("");<br /> xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, false);<br /> xml_set_element_handler($xml_parser, "start_tag", "end_tag");<br /> xml_set_character_data_handler($xml_parser, "contents");<br /> xml_parse($xml_parser, $result, true);<br /> xml_parser_free($xml_parser);<br /><br /> return $results['rank']."|".$results['linksincount'];<br />} <br /><br />function contents($parser, $data) {<br /> global $current_tag, $results;<br /> switch ($current_tag) { <br /> case "aws:LinksInCount":<br /> $results['linksincount'] .= $data;<br /> break;<br /> case "aws:Rank":<br /> $results['rank'] .= $data;<br /> break;<br /> }<br />}<br /><br />function start_tag($parser, $name) {<br /> global $current_tag, $results;<br /> $current_tag = $name;<br />}<br /><br />function end_tag() {<br /> global $current_tag;<br /> $current_tag = '';<br /><br />}<br /><br />// Returns the AWS url to get AWIS information for the given site<br /><br />function generate_url($site_url) {<br /> $timestamp = generate_timestamp();<br /> $site_enc = urlencode($site_url);<br /> $timestamp_enc = urlencode($timestamp);<br /> $signature_enc = urlencode(calculate_RFC2104HMAC(ACTION . $timestamp, SECRET_ACCESS_KEY));<br /><br /> return SERVICE_ENDPOINT<br /> . "AWSAccessKeyId=".ACCESS_KEY_ID<br /> . "&Action=".ACTION<br /> . "&ResponseGroup=".RESPONSE_GROUP<br /> . "&Timestamp=$timestamp_enc"<br /> . "&Signature=$signature_enc"<br /> . "&Url=$site_enc";<br /><br />}<br /><br /><br />// Calculate signature using HMAC: http://www.faqs.org/rfcs/rfc2104.html<br /><br />function calculate_RFC2104HMAC ($data, $key) {<br /> return base64_encode (<br /> pack("H*", sha1((str_pad($key, 64, chr(0x00))<br /> ^(str_repeat(chr(0x5c), 64))) .<br /> pack("H*", sha1((str_pad($key, 64, chr(0x00))<br /> ^(str_repeat(chr(0x36), 64))) . $data))))<br /> );<br />}<br /><br />// Timestamp format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'<br /><br />function generate_timestamp () {<br /> return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());<br />}<br /><br />// Make an http request to the specified URL and return the result<br /><br />function make_http_request($url){<br /> $ch = curl_init($url);<br /> curl_setopt($ch, CURLOPT_TIMEOUT, 4);<br /> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);<br /> $result = curl_exec($ch);<br /> curl_close($ch);<br /> return $result;<br />}Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-8040418341012804422009-08-05T23:13:00.000+07:002009-08-05T23:21:33.859+07:00strtok in PHP - a common mistake<a href="http://php.net/strtok">strtok</a>, that splits a string into tokens is a very useful function for the programmers. Here is an example code that shows the use of strtok function to extract integers from a comma separated string.<br /><code><br /><?php<br />$list = "1,2,4,10,8,0,20,30,9";<br /><br />$token = strtok($list, ",");<br />while($token)<br />{<br /> print $token."\n";<br /> $token = strtok(",");<br />}<br />?><br /></code><br />Using the code we get this output:<br /><code><br />1<br />2<br />4<br />10<br />8<br /></code><br />Where are the other four integers? Actually when the value of $token is zero (0) - the sixth integer in the list, while ($token) evaluates to False and the loop is broken there. Lets use while($token != FALSE) instead.<br /><code><br />$token = strtok($list, ",");<br />while($token != FALSE)<br />{<br /> print $token."\n";<br /> $token = strtok(",");<br />}<br /></code><br />Still the same output. Oh, the mistake is we used the '!=' operator which tests the equality between $token and FALSE. Here zero (0) is equal to FALSE. A stupid way to avoid the problem is to calculate the length - while(strlen($token)) and it will work definitely! as the length of the string '0' is 1. But best solution (to me) is to use the '!==' operator which means not identical. So the following code works fine:<br /><code><br /><?php<br />$list = "1,2,4,10,8,0,20,30,9";<br /><br />$token = strtok($list, ",");<br />while($token !== FALSE)<br />{<br /> print $token."\n";<br /> $token = strtok(",");<br />}<br />?><br /></code><br />Output:<br /><code><br />1<br />2<br />4<br />10<br />8<br />0<br />20<br />30<br />9<br /></code><br />It's always useful to know details about <a href="http://www.php.net/manual/en/language.operators.comparison.php">operators in PHP</a>.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com1tag:blogger.com,1999:blog-3735025482116810346.post-23708874324865863002009-05-13T00:48:00.000+06:002009-05-13T00:58:53.089+06:00Trouble with Facebook Client APII have working on facebook application development (it's a game named Fighter Jets), and facing some weired problem. I have decided to share my experience here.<br /><br />Today I tried the post link feature of the facebook API. First I tried the following code:<br /><code>$facebook->api_client->links_post($user_id, 'http://khaaan.com/','Best. Website. Ever.');</code><br />I got it from their <a href="http://wiki.developers.facebook.com/index.php/Links.post">API documentation</a>.<br /><br />I got error using it. It says that 'The url you supplied is invalid'. May be it's invalid. Then I changed the URL to http://www.google.com, which is valid definitely! Still getting the same problem!! WTF!<br /><br />Then I searched their forum and found that I am not the only victim, some people already faced this problem and one of them solved the problem in the following way:<br /><code>$facebook->api_client->links_post('http://khaaan.com/','Best. Website. Ever.', $user_id);</code><br /><br />Which works! Needed to use the user id as the third parameter, but from the example in the API documentation we see that it's the first parameter. <br /><br />I really don't understand why the documentation is wrong.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com10tag:blogger.com,1999:blog-3735025482116810346.post-56236556567400029352008-11-12T22:15:00.000+06:002008-11-12T22:18:15.955+06:00Forum for freelance software developersI got a new forum for freelancers. They call it <a href="http://www.freelancefest.com">FreelanceFest</a>. You can go and post your problems there. Hopefully someone will answer soon. There are language specific categories and also freelance site based categories available.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-52883179322660244912008-08-12T09:39:00.000+06:002008-08-12T09:46:23.480+06:00Convert FLV to MP3 using PerlFew days back, I found an interesting Perl module that converts FLV file to MP3. Here is the code:<br /><code><br />use FLV::ToMP3;<br /><br />$flv_filename = "/home/video/music.flv";<br />$mp3_filename = "test.mp3";<br /><br />my $converter = FLV::ToMP3->new();<br />$converter->parse_flv($flv_filename);<br />$converter->save($mp3_filename);<br /></code><br />Visit the following links for details:<br /><ul><li><a href="http://search.cpan.org/~cdolan/FLV-Info-0.19/lib/FLV/ToMP3.pm">FLV::ToMP3</a></li><li><a href="http://search.cpan.org/~cdolan/FLV-Info/bin/flv2mp3">flv2mp3</a></li></ul>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-91231306825166919882008-08-12T01:58:00.000+06:002008-08-12T02:04:14.140+06:00Send email using PHPSending emails using a PHP script / program is very easy. Just use the mail function: <code>mail($to, $subject, $body);</code><br /><br />Check <a href="http://www.php.net/function.mail">mail function</a> for details.<br /><br />There can be some problems if it's not configured properly. Check the <a href="http://www.php.net/manual/en/mail.setup.php">installation / configuration page</a> for details.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-30339081963400966652008-08-12T01:52:00.000+06:002008-08-12T01:57:16.537+06:00Install Perl modules using cpanInstallation of Perl modules is very simple. Just use the command in the terminal:<br /><div style="text-align: center;"><b><code>cpan -install ModuleName</code></b><br /></div><br />For example, to install LWP module, use the command:<br /><div style="text-align: center;"><b><code>cpan -install LWP</code></b><br /></div><br />To install Mail::Sendmail module, use the command:<br /><div style="text-align: center;"><b><code>cpan -install Mail::Sendmail</code></b></div>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-53603597354073646592008-08-10T01:42:00.000+06:002008-08-10T01:53:23.581+06:00Perl - return value of a functionCan you guess the output of the following Perl code?<br /><pre><br />$sum = add(3, 5);<br />print $sum."\n";<br /><br />sub add<br />{<br /> $a = shift;<br /> $b = shift;<br /> <br /> return ($a + $b);<br />}<br /></pre><br />Yes, it prints 8.<br /><br />Now what about the following code?<br /><pre><br />$sum = add(3, 5);<br />print $sum."\n";<br /><br />sub add<br />{<br /> $a = shift;<br /> $b = shift; <br />}<br /></pre><br />hmm... what should it print? It prints 5 ! A garbage value?<br />Not actually. I have found that in Perl if you don't return anything, it returns the value of the last variable in the function.<br /><br />Now you can tell the output of the following code :-)<br /><pre><br />$sum = add(3, 5);<br />print $sum."\n";<br /><br />sub add<br />{<br /> $a = shift;<br /> $b = shift;<br /> <br /> $c = 10;<br />}<br /></pre><br />yes, it's 10 !Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com1tag:blogger.com,1999:blog-3735025482116810346.post-81902055245258018602008-08-08T00:19:00.000+06:002008-08-08T00:33:31.187+06:00Count number of elements in array - PHP, Perl, PythonWe often need to count the number of elements in an array (or get the size of an array). Here is how to do it in PHP, Perl & Python:<br /><br />PHP: <code>$items = count($ara);</code><br /><br />Perl: <code>my $items = scalar(@ara);</code>, you can also try: <code>my $items = @ara;</code><br /><br />Python: <code>items = ara.__len__()</code>. Note that in Python it's called list. List can be used as array.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com1tag:blogger.com,1999:blog-3735025482116810346.post-33820910188642866282008-08-03T00:44:00.000+06:002008-08-03T00:57:45.287+06:00CGItemp**** issue in file uploadSometimes your file upload script produces temp files named CGItemp**** in the server (this happed to one of my Perl file upload script (cgi) running in a windows server). <br /><br />So I did some search in the Internet about the problem. Many people faced the same problem and most of them choose a simple solution. That is to delete those files using a program or manually. After spending some more time, I found that those temp files are filehandles that are being recorded in the server. Though the CGI.pm file should have taken care of it (i.e. delete those files automatically).<br /><br />I found that in my code I have opened a file handle which must be closed in order to get rid of this problem.<br /><br /><code><b>my $upload_file_handle = $q->upload("file_name");</b></code><br /><br />when this variable (file handle) is not required any more, it should be closed.<br /><br />So I added the line at the end of upload function: <br /><br /><code><b>close $upload_file_handle;</b></code><br /><br />It solved the problem!Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com1tag:blogger.com,1999:blog-3735025482116810346.post-81035879423015599042008-07-22T23:16:00.000+06:002008-07-22T23:40:13.696+06:00Objective-C for iPhone application development<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjN9yJED-fyoKONQJVAF10NmBOX4upv-qDOr-OTIg9q0eOdeWOKhouXue7d5cQz1JUm-XuPtfEct3DDAkMJoCg6ehCn-Mu8nQsah-3XlvuNUMW932IcvHP7tUTjQTmMmg3w9dcv44zVnXA/s1600-h/170px-IPhoneSeattle.jpg"><img style="float:right; margin:0 0 10px 10px;cursor:pointer; cursor:hand;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjN9yJED-fyoKONQJVAF10NmBOX4upv-qDOr-OTIg9q0eOdeWOKhouXue7d5cQz1JUm-XuPtfEct3DDAkMJoCg6ehCn-Mu8nQsah-3XlvuNUMW932IcvHP7tUTjQTmMmg3w9dcv44zVnXA/s200/170px-IPhoneSeattle.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5225889602217122594" /></a><br /><a href="http://www.apple.com/iphone/">iPhone</a> is getting popular day-by-day. Naturally the demand for iPhone applications is increasing. So if you are ready to take the next big step, you can start learning how to develop software for iPhone.<br /> <br />The operating system used in iPhone is called iPhone OS (which is also the operating system for iPod). Unfortunately iPhone doesn't support Java like most of the smart phones. The programming language that can be used to write programs for iPhone is <span style="font-weight:bold;">Objective-C</span>. If you already know it, then you are one step ahead. Else you can start learning it. You can read this tutorial: <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/">http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/</a> which is recommended by many.<br /><br />For resources, you must visit iPhone Developer's Center: <a href="http://developer.apple.com/iphone/">http://developer.apple.com/iphone/</a> and download the iPhone SDK.<br /><br />Please share your experience with iPhone application development.<br /><br />Wikipedia links: <a href="http://en.wikipedia.org/wiki/IPhone">iPhone</a>, <a href="http://en.wikipedia.org/wiki/Objective-C">Objective-C</a>, <a href="http://en.wikipedia.org/wiki/IPhone_OS">iPhone OS</a>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com3tag:blogger.com,1999:blog-3735025482116810346.post-19984807472211823122008-07-09T23:40:00.000+06:002008-07-10T00:01:36.289+06:00Create PDF file in PerlToday I tried to create a PDF file using a program. I choose the language Perl to do this task, because there should be one or more useful module for pdf creation in Perl (I shall try to do the same task using PHP and Python later).<br /><br />For PDF creation I found the module <a href="http://search.cpan.org/%7Eftassin/PDF-Create-0.01/lib/PDF/Create.pm">PDF::Create</a> very useful. If you want to create and/or modify a pdf file, then you can try <a href="http://search.cpan.org/%7Eareibens/PDF-API2-0.69/lib/PDF/API2.pm">PDF::API2</a>.<br /><br />Here is an article on pdf creation from the book PDF Hack, that uses PDF::API2 to create a pdf file: <a href="http://oreilly.com/pub/h/2429">Use Perl to create PDF</a>. Note that I had to change the sample code (line 11) <span style="font-size:120%;"><code>my $txt = $page->hybrid;</code></span> to <span style="font-size:120%;"><code>my $txt = $page->text;</code></span><br /><br />Hope you can create PDFs smoothly. Please share your experience.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-64389732051912158852008-06-21T00:04:00.001+06:002008-06-21T00:10:24.795+06:00Non-interactive SSH in LinuxThere are two machines, A and B in a network. Let the IP of A be 192.168.1.2, and IP of B be 192.168.1.8. You can access remotely from A to B using the command: <span style="font-size:110%;"><code style="font-weight: bold;">ssh guest@192.168.1.8</code></span>. It will ask you the password of the user guest in machine B. Now let me tell you a simple trick so that you don't need to enter the password any more. It's called non-interactive ssh.<br /><br />Suppose your username in machine A is pypy. Open the terminal. Go to the directory /home/pypy/.ssh (cd /home/pypy/.ssh). Now enter the follwoing command:<br /><span style="font-size:110%;"><code><b>ssh-keygen -t dsa</b></code></span><br />First it will ask you for a filename. Just press enter to keep it default (id_dsa) or you can enter any other name. Then it will ask you for a passphrase. Enter empty there (just press enter twice). Now you will see two files there named id_dsa (that has the private key) and id_dsa.pub (that contains the public key).<br /><code><br /><span style="font-size:110%;">pypy@pypy-laptop:~/.ssh$ <span style="font-weight: bold;">ssh-keygen -t dsa</span><br />Generating public/private dsa key pair.<br />Enter file in which to save the key (/home/pypy/.ssh/id_dsa):<br />Enter passphrase (empty for no passphrase):<br />Enter same passphrase again:<br />Your identification has been saved in /home/pypy/.ssh/id_dsa.<br />Your public key has been saved in /home/pypy/.ssh/id_dsa.pub.<br />The key fingerprint is:<br />fc:37:69:9e:bb:15:e7:55:cd:b9:52:12:e6:49:b1:6c pypy@pypy-laptop<br /></span></code><br />Key generation complete. Check the directory<br /><code><br /><span style="font-size:110%;">pypy@pypy-laptop:~/.ssh$ ls -lt<br />total 12<br />-rw------- 1 pypy pypy 668 2008-06-20 23:54 <span style="font-weight: bold;">id_dsa</span><br />-rw-r--r-- 1 pypy pypy 610 2008-06-20 23:54 <span style="font-weight: bold;">id_dsa.pub</span><br /></span></code><br />Now append the content of id_dsa.pub file to the file named authorized_keys2 in /home/guest/.ssh directory (if the file doesn't exist first create it) of machine B. You can do this using this command also:<br /><span style="font-size:110%;"><code style="font-weight: bold;">cat /home/pypy/.ssh/id_dsa.pub | ssh guest@192.168.1.8 'cat - >> ~/.ssh/authorized_keys2'</code></span><br /><br />(it will ask you for the password of user guest of machine B).<br /><br />Now done. Try to access machine B from machine A<br /><span style="font-size:110%;"><code>pypy@pypy-laptop:~/.ssh$ ssh guest@192.168.1.8</code></span><br /><br />Hopefully it won't ask you for a password :-)Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-91185515862362414612008-06-19T00:14:00.000+06:002008-06-19T00:19:10.127+06:00Perl script to display the content of a zip fileHere is a little script that shows the number of files in a zip file and the names of the files. Interesting thing is that, we don't need to unzip the file.<br /><br />Here is the code<br /><pre><br /><span style="font-size:110%;">use Archive::Zip qw( :ERROR_CODES :CONSTANTS );<br /><br />my $zip = Archive::Zip->new();<br /><br />my $zip_file_name = 'scraper.zip';<br /><br />$zip->read( $zip_file_name );<br /><br />print "Number of files in the zip file: ".$zip->numberOfMembers()."\n";<br />print "List of files:\n";<br /><br />my @members = $zip->memberNames();<br /><br />#now print the name of the files<br />foreach (@members)<br />{<br /> print $_, "\n";<br />}<br /></span></pre><br /><br />For details, please check <a href="http://search.cpan.org/%7Eadamk/Archive-Zip-1.23/lib/Archive/Zip.pm">http://search.cpan.org/~adamk/Archive-Zip-1.23/lib/Archive/Zip.pm</a>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-74737315305374969922008-06-15T23:21:00.000+06:002008-06-15T23:37:22.821+06:00Your crawler freezes? Use BackgroundWorker in C#When I wrote my first crawler with GUI in C#.NET (I used .NET so that I can create the GUI easily using Visual Studio) I got into a major problem. The GUI got frozen when I ran the crawler... I shared my problem with one of my friend who then told me about BackgroundWorker Thread. Then I got back home, explored BackgroundWorker, learned how to use it, and used it in my crawler and WOW! It worked fine then. So if you get into similar problem then you can also use BackgroundWorker.<br /><br />You will find it in Toolbox > Component > BackgroundWorker. Just drag it and drop on your form. Right click on it (it's backgroundWorker1 until you change the name) to change it's properties and add events. Now just code the events...<br /><br />You can go through this example in msdn <a href="http://msdn.microsoft.com/en-us/library/b2zk6580.aspx">http://msdn.microsoft.com/en-us/library/b2zk6580.aspx</a>. It's a useful one I think.Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com2tag:blogger.com,1999:blog-3735025482116810346.post-71466991360768764522008-06-12T00:17:00.000+06:002008-06-12T00:32:06.441+06:00Problem uploading large file in CGI scriptToday I had a problem uploading large file using the CGI upload script I have written using Perl couple of day back. I was getting the response: "413 Request entity too large". I searched Google and found out that this problem can occur for mainly two reasons: if size of the file being uploaded is greater than the value of $CGI::POST_MAX in the upload script, and if the value of the apache (web server) directive <strong>LimitRequestBody</strong> is lower than the file size. But both cases were handled. But I was still getting the 413 error. Then I found that it was my local server which prevented me to upload large file size. the 413 was coming from that machine instead of the server where the script is hosted :(Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-68046129214743776472008-06-12T00:01:00.000+06:002008-06-12T00:13:45.253+06:00How to send custom error message in http header from cgi scriptCouple of days ago, while I was writing a CGI script in Perl, it was needed to send custom error message in http response header. I would like to share with you how I have done this.<br /><br />First I have decided that for any kind of error in the code (for example, file not found, insecure path etc.) I shall return status 500 with the error message. Before this decision my code looked like this:<br /><code><br />...<br />my $query = new CGI;<br />print $query->header(-type=>'text/plain');<br />...<br /></code><br />So for any error in the script, I added the line:<br /><code>print $query->header(-type=>'text/plain', -status=>"500 $err_str");</code><br />But it wasn't working. The return value (status line in the response) still '200 OK'. Then I found that query header can't be set twice (once you set it, you can't change it). Then I removed the first line <code>print $query->header(-type=>'text/plain');</code> and modified the code in such a way that the header is printed once. In order to return error, I wrote a function and just called it in case of any error occurs (but I made sure the header is not printed before I call it). Here is the function:<br /><pre><br />sub catch_n_die<br />{<br /><br /> my $err_str = shift;<br /><br /> print $query->header(-type=>'text/plain', -status=>"500 $err_str");<br /><br /> exit;<br /><br />}<br /></pre>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-23609987422426976772008-06-06T01:05:00.000+06:002008-06-06T01:11:36.845+06:00Perl script to check the number of instances of a programTo get the number of instances of a program running in your machine you can use the following Perl code:<br /><code><br /><span style="font-size:120%;">my $program_name = 'abc.pl';<br />my $data = `ps ax | grep perl`;<br />my @ara = $data =~ /perl\s+$program_name/g;<br />my $count = @ara;<br />print "$count\n";</span><br /></code><br />Sometime it might be useful for you to know at the start of a program whether it's already running. You can get the name of your current Perl script/program from $0. If the name of your Perl script is program.pl, then $0 will contain program.pl. You can try <b><code>print $0;<code></b><br />Hope this tiny piece of code will be useful for you. :)Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0tag:blogger.com,1999:blog-3735025482116810346.post-39379938919861011822008-06-04T20:46:00.000+06:002008-06-04T21:04:28.154+06:00execute linux command using Perl, Python, PHPThose who program in Linux often need to execute/run linux commands from programs/scripts.<br /><br />Using python you can execute linux command is the following way:<br /><code><br /><span style="font-size:130%;">import os<br />os.system('ls -lt')</span><br /></code><br /><br />If you use Perl, you can do it in the following ways:<br />1. <span style="font-size:130%;"><code>system(mkdir $folder);</code></span><br />2. <span style="font-size:130%;"><code>qw(mkdir $folder);</code></span><br />3. <span style="font-size:130%;"><code>$temp = `mkdir $folder`; #back ticks </code></span><br />4. <span style="font-size:130%;"><code>exec($command);</code></span><br /><br />If you use back ticks or qw, $? will be set if any error occurs. So you can use it like this:<br /><code><br /><span style="font-size:130%;">qw(rm $filename);<br />if($?) {<br /> print STDERR "error deleting file\n";<br />}<br /></span></code><br /><br />There are also several options available to run linux commands using PHP. Take a look at here for detals: <a href="http://us2.php.net/manual/en/ref.exec.php">http://us2.php.net/manual/en/ref.exec.php</a>Tamim Shahriarhttp://www.blogger.com/profile/03476580865735017742noreply@blogger.com0