Create/Restore Internet Explorer desktop shortcut

Internet Explorer (IE) shortcut on Windows desktop is missing! May be it was deleted accidentally or missing due to some unexpected reason. So what would be the way to recreate it? You can create a shortcut just by right clicking on Windows Desktop. But you must give the application path to Internet Explorer installation. How would you find it?


You would do a search on Windows for iexplore.exe on your C drive (Windows drive); and you'll end up seeing a number of iexplore.exe files on your machine. Are these the ones you have to use? which one out of these?

Not exactly. The expected executable will not be shown by a Windows search. The correct file is a "protected operating system file", also it's hidden. By default Windows Explorer hides those files, but still you can view such files by changing the folder options as shown in the image.
Tools->Folder Options->View


The iexplore.exe executable will be available under;
C:\Program Files\Internet Explorer\iexplore.exe

So create a shortcut on Desktop by setting the location/target to the above executable.

Reason For The Lack of Posts These Days...

Today I’ve got a bad news for you guys. It’s that I won’t
be able to blog for almost a month. Sorry guys, it’ I know it’s
happened in the past but this time I’ve got a pretty good excuse –
EXAMS. That’s right my exams starts 10th July and guess what, I haven’t
studied much yet! It happens…always happens…


Hope you’d understand my problem, in the mean time you may want to read
some of my recent posts that got good readership:



Enjoy!

Change Apache Tomcat port 8080 to 80 or another port number

Change Apache Tomcat port 8080 to 80 or another port number. Whether it is Apache Tomcat 5 or Tomcat 6, by default Apache Tomcat runs on port 8080. But there can be situations where there are some other servers running on this same port forcing you to change the port of one of the servers. This article explains how to change this port 8080 on Tomcat (we tested this against Apache Tomcat 5.5 and 6.0 versions).

Here we’ll be using label to denote the folder where Tomcat is installed. In our systems, tomcat is installed in the following path.
=C:\Java\Tomcat_x.x

We need to edit the file named server.xml inside \conf folder.



In the server.xml file; locate the following segment.

<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector port="8080" … />

By changing this 8080 value of port attribute, server would start listening on new port number.

<Connector port="8081" … />


After saving the changed server.xml file, Tomcat server must be restarted (stop then start) to activate the change.

Related: How to change port 8080 in JBoss?

Creating Tool-Tip Text for WebPages Using CSS Only

Creating Tool-Tip Text for WebPages Using CSS Only


[You might also be interseted in Deigning
a Simple HTML Menu-Bar Using CSS
]


All right, so today we are going to use CSS along with some HTML to create
Tooltip text for WebPages without using JavaScript. Yeah, you heard it right
using only CSS and of course HTML. Do I need to explain what a Tooltip is, BTW?
Nah, you guys already know it. I do not think many sites use tooltips or anything
of that sort on their websites but in case you do or you just want to learn,
read on…


Well, the first thing that I want to tell is that the basic technique I’ll
be using to create tooltips is not mine, I saw someone using it for a slightly
different purpose, I changes it to suite mine. As I said earlier we’d
be using CSS and HTML only, I guess HTML is easier so here it is:


<a href="#"
class="tooltip">Hover Here<span>This
is the Tool-Tip Text</span></a>


As you can see there is nothing special, a plain simple link but wait what
is that <span> for? Good question! Well the text under the
<span> tag wouldn’t be visible unless you hover the
mouse over the link. When you do so that’d become visible, neatly formatted
to look just like a real Tooltip text. But how? You might ask. It has been classified
(class="tooltip") to do so.


The heart of all this is the CSS:



a.tooltip{
/* for postioning the tool-tip box relative to the link */
position:relative;

/* no underline needed */
text-decoration: none;
}

a.tooltip span{
/* tool-tip text will not be visible initially */
display: none;
}

a.tooltip:hover span{
/* make tool-tip text visible */
display:block;

/* for postioning */
position:absolute;
top:20px; left:20px;
padding: 5px;

/* width of the tool-tip box
if text is longer, it will be
made into two lines */
width:150px;

/* style the box to look like a tool-tip box */
border:1px solid #000;
background-color:#FFFFAA;
color:#000;
}


Now to make it more clear, I’d break the whole code into smaller pieces
and discuss what that does:


1.

a.tooltip { position:relative; }


This would make the tooltip (whenever) it appears to be positioned relatively
to where the link is.


2.

a.tooltip span { display: none; }


It’d (as you might have guessed) make the tooltip text (or the <span>
tag) to be invisible.


3.

  a.tooltip:hover span {  
display:block;
position:absolute;
top:20px;
left:20px;
padding: 5px;
width:150px;
border:1px solid #000;
background-color:#FFFFAA;
color:#000;
}


This defines what the <span> tag would be when mouse is
hovered over the link.


First it’d make the <span> visible (thus the tooltip
text) by using display: block;. Next it’d position and style the <span>
text to look like a “Real” tooltip.


Easy! Now it is…


Here is the complete code:



<html>
<head>

<title>ToolTip Text Example</title>
<style>
a.tooltip{
/* for postioning the tool-tip box relative to the link */
position:relative;

/* no underline needed */
text-decoration: none;
}

a.tooltip span{
/* tool-tip text will not be visible initially */
display: none;
}

a.tooltip:hover span{
/* make tool-tip text visible */
display:block;

/* for postioning */
position:absolute;
top:20px; left:20px;
padding: 5px;

/* width of the tool-tip box
if text is longer, it will be
made into two lines */
width:150px;

/* style the box to look like a tool-tip box */
border:1px solid #000;
background-color:#FFFFAA;
color:#000;
}
</style>

</head>
<body>
<a href="#" class="tooltip">Hover Here<span>This is the Tool-Tip Text</span></a>

</body>
</html>



Previous Posts:


Basic Web Scraping: Pulling Out Data From Google Search Results

Basic Web Scraping: Scraping Google Search Results


[UPDATE (22-AUG-2009): THIS IS THE NEW WORKING VERSION.]


Today we are going to discuss a bit advanced topic, not in the sense that it’d
be difficult to understand (I always try to make things easier anyway) but that
you won’t find an apparent use of it. What we are going to do today is
what is called Web Scraping. By the way web scraping means retrieving data from
web and pulling out useful information out of it for our use. Of course this
wouldn’t be the next best web scraper rather it would la a basic foundation
on how simple a web scraper can be.


OK let’s kick off guys!


As is obvious we are going to scrape Google’s Web Search Results to retrieve
the number of pages indexed for a search term.


Scarping Google Results for Number of Pages Indexed


To retrieve results for a search term we need the URL, for this fire up your
favorite Browser and browse to the Search Engine’s (Google, or whatever)
homepage, type in any search query and hit enter.


OK now look at the address bar, in my case I looked like below, your’
should be similar or whatever:


http://www.google.com/search?hl=en&q=learning+c&btnG=Google+Search



On inspection you can see pour search term in the URL which is ‘URL Encoded’
(changes some character such as spaces to codes). There we have it, you can
place any search keyword (urlencoded, very simple with PHP’s in-built
function) and fetch that page. But how in a script, you might ask. Because that
is what we need.


Well using the following function:


file_get_contents();


[UPDATE: WE'LL BE USING THE FOLLOWING USER-DEFINED FUNCTION INSTEAD. READ COMMENTS FOR MORE INFORMATION:



function my_fetch($url,$user_agent='Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)')


{

    
$ch curl_init();

    
curl_setopt ($chCURLOPT_URL$url);

    
curl_setopt ($chCURLOPT_USERAGENT$user_agent);


    
curl_setopt ($chCURLOPT_HEADER0);

    
curl_setopt ($chCURLOPT_RETURNTRANSFER1);

    
curl_setopt ($chCURLOPT_REFERER'http://www.google.com/');


    
$result curl_exec ($ch);

    
curl_close ($ch);

    return 
$result;

}



]


If you have been following this blog for sometime, you might remember we once
used it in my Creating
a Simple Shout Box in PHP
post to fetch contents from a local file.
Yeah its beauty is that it can fetch remote (HTTP) files too.


$data = file_get_contents("http://www.google.com/search?hl=en&q=learning+c&btnG=Google+Search");


[UPDATE: NOW USING:


$data = my_fetch("http://www.google.com/search?hl=en&q=learning+c&btnG=Google+Search");


]


Above code will fetch the Google Search Results for the keyword we searched
for in the browser, $data will contain the HTML source.


Since we have to scrape the total number of pages indexed for a particular
search term (displayed as “Results 1 - 10 of about XXXX …”)
we would find some text near that number(XXXX in this case). In this case that
text is simply “Results 1 - 10 of about”, its also unique throughout
the page hence if we could find it in the code returned we can easily find the
needed data. One more thing we can ease off searching by first stripping off
HTML from the code returned so that only text remains. This part can be implemented
as below:


    $data=my_fetch("http://www.google.com/search?hl=en&q=".$s."&btnG=Google+Search");


    

    
//strip off HTML


    
$data=strip_tags($data);




    
$find='Results 1 - 10 of about ';


    
$find2=' for';




    
//have text beginning from $find


    
$data=strstr($data,$find);




    
//find position of $find2


    
$pos=strpos($data,$find2);




    
//take substring out, which'd be the number we want


    
$search_number=substr($data,strlen($find), $pos-strlen($find));


Here is the complete code:



<html>

<head>

<title>Google Result Scraper</title>

</head>



<body>

<p align="center" style="font-size: 500%"><font color="#0000FF">G</font><font


     color="#FF0000">o</font><font color="#FFFF00">o</font><font

     color="#0000FF">g</font><font color="#00FF00">l</font><font

     color="#FF0000">e</font><font size="2"><br />


Result Scraper</font></p>



<?php

function my_fetch($url,$user_agent='Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)')


{

$ch curl_init();

curl_setopt ($chCURLOPT_URL$url);

curl_setopt ($chCURLOPT_USERAGENT$user_agent);


curl_setopt ($chCURLOPT_HEADER0);

curl_setopt ($chCURLOPT_RETURNTRANSFER1);

curl_setopt ($chCURLOPT_REFERER'http://www.google.com/');


$result curl_exec ($ch);

curl_close ($ch);

return 
$result;

}



$s $_GET['s'];


if (isset(
$s))

{

echo 
"<p><i>Search for $s</i></p>";

    
$s urlencode($s);


    
$data my_fetch("http://www.google.com/search?hl=en&q=" $s "&btnG=Google+Search");

    
//strip off HTML

    
$data strip_tags($data);


    
//now $data only has text NO HTML

    //these have to found out in the fetched data

    
$find 'Results 1 - 10 of about ';


    
$find2 ' for';

    
//have text beginning from $find

    
$data strstr($data$find);


    
//find position of $find2

    //there might be many occurence

    //but it'd give position of the first one,


    //which is what we want, anyway

    
$pos strpos($data$find2);



//take substring out, which'd be the number we want


$search_number=substr($data,strlen($find), $pos-strlen($find));




echo 
"Pages Indexed: $search_number";

}

else

{

    
?>



<form name="form1" id="form1" method="get" action="">


<div align="center">

<p>  <input name="s" type="text" id="s" size="50" />

<input type="submit" name="Submit" value="Count" /></p>


</div>

</form>

<p>&nbsp;</p>

<p>&nbsp;</p>

<p>&nbsp;</p>

<p>&nbsp;</p>


<p>

<?php

}

?>

</p>

<p align="right"><font size="2">by <a

     href="http://learning-computer-programming.blogspot.com/">Learning

Computer Programming</a></font></p>


</body>

</html>


Wow, our first scarper is completed. It has a nice interface, you type in search
phrase click ‘Count’ and there you are. It displays the number of
pages that contains that term same as on Google.


Have fun guys and do comment!


P.S.: You might want to read String
Manipulation Function in PHP I
and String
Manipulation Function in PHP II
if you are not much familiar with the
string manipulation functions we are using in the code above.


Previous Posts:


Exploring Erlang with Map/Reduce

Under the category of "Concurrent Oriented Programming", Erlang has got some good attention recently due to some declared success from Facebook engineers of using Erlang in large scale applications. Tempted to figure out the underlying ingredients of Erlang, I decided to spent some time to learn the language.


Multi-threading Problem

Multiple threads of execution is a common programming model in modern languages because it enable a more efficient use of computing resources provided by multi-core and multi-machine architecture. One of question to be answered though, is how these parallel threads of execution interact and work co-operative to solve the application problem.

There are basically two models for communication between concurrent executions. One is based on a "Shared Memory" model which one thread of execution write the information into a shared place where other threads will read from. Java's thread model is based on such a "shared memory" semantics. The typical problem of this model is that concurrent update requires very sophisticated protection scheme, otherwise uncoordinated access can result in inconsistent data.

Unfortunately, this protection scheme is very hard to analyze once there are multiple threads start to interact in combinatorial explosion number of different ways. Hard to debug deadlock problem are frequently pop up. To reduce the complexity, using a coarse grain locking model is usually recommended but this may reduce the concurrency.

Erlang has picked the other model based on "message passing". In this model, any information that needs to be shared will be "copied" into a message and send to other executions. In this model, each thread of execution has its state "completely local" (not viewable by other thread of executions). Their local state is updated when they learn what is going on in other threads by receiving their messages. This model mirrors how people in real life interact with each other.


Erlang Sequential Processing

Coming from an object oriented imperative programming background, there are a couple of things I need to unlearn/learn in Erlang.

Erlang is a functional programming language and have no OO concepts. Erlang code is structured as "function" at a basic unit, grouped under a "module". Each "function" takes a number of inputs parameters and produce an output value. Like many functional programming language, Erlang encourage the use of "pure function" which is "side-effect-free" and "deterministic". "Side-effect-free" means there is no state changes within the execution of the function. "Deterministic" means the same output will always be produced from the same input.

Erlang has a very different concept in variable assignment in that all variables in Erlang is immutable. In other words, every variable can only be assigned once and from then onwards can never be changed. So I cannot do X = X + 1, and I have to use a new variable and assigned it with the changed value, e.g. Y = X + 1. This "immutability" characteristic simplify debugging a lot because I don't need to worry about how the value of X is changed at different point of execution (it simply won't change).

Another uncommon thing about Erlang is that there is no "while loop" construct in the language. To achieve the looping effect, you need to code the function in a recursive way, basically putting a terminal clause to check for the exit condition, as well as carefully structure the logic in a tail recursion fashion. Otherwise, you may run out of memory in case the stack grow too much. Tail recursion function means the function either returns a value (but not an expression) or a recursive function call. Erlang is smart enough to do tail recursion across multiple functions, such as if funcA calls funcB, which calls funcC, which call funcA. Tail recursion is especially important in writing server daemon which typically make a self recursive call after process a request.


Erlang Parallel Processing

The execution thread in Erlang is called a "Process". Don't be confused with OS-level processes, Erlang process is extremely light-weight, much lighter than Java threads. A process is created by a spawn(Node, Module, Function, Arguments) function call and it terminates when that function is return.

Erlang processes communicate with each other by passing messages. Process ids are used by the sender to specify the recipient addresses. The send call happens asynchronously and returns immediately. The receiving process will make a synchronous receive call and specify a number of matching patterns. Arriving messages that match the pattern will be delivered to the receiving process, otherwise it will stay in the queue forever. Therefore, it is good practices to have a match all pattern to clean up garbage message. The receive call also accepts a timeout parameter so that it will return if no matched messages happen within the timeout period.

Error handling in Erlang is also quite different from other programming languages. Although Erlang provides a try/catch model, it is not the preferred approach. Instead of catching the error and handle it within the local process, the process should simply die and let another process to take care of what should be done after its crash. Erlang have the concept of having processes "linked" to each other and monitor the life status among themselves. In a default setting, a dying process will propagate an exit signal to all the processes it links to (links are bi-directional). So there is a chaining effect that when one process die, the whole chain of processes will die. However, a process can redefine its behavior after receiving the exit signal. Instead of "dying", a process can choose to handle the error (perhaps by restarting the dead process).


Other Erlang Features

Pattern matching is a common programming construct in many places of Erlang, namely "Function calls", "Variable assignment", "Case statements" and "Receive messages". It takes some time to get used to this style. After that I feel this construct to be very powerful.

Another cool feature that Erlang provides is the code hot swap. By specifying the module name when making the function call, a running Erlang process can execute the latest code without restarting itself. This is a powerful features for code evolution because you don't need to shutdown the VM when deploying new code.

Since the function itself can be passed as a message to a remote process, execute code remotely is extremely easy in Erlang. The problem of installation, deployment is pretty much non-existent in Erlang

Map/Reduce using Erlang

After learning the basic concepts, my next step is to search for a problem and get some hands on with the language. Based on a work-partition, aggregation, parallel processing model, Map/Reduce seems to have the characteristic model that aligns very nicely into Erlang's parallel processing model. So I pick my project to implement a simple Map/Reduce framework in Erlang.

Here is the Erlang implementation ...




First of all, I need some Helper functions

-module(mapreduce).
-export([reduce_task/2, map_task/2,
test_reduce_task/0, test_map_reduce/0,
repeat_exec/2]).

%%% Execute the function N times,
%%% and put the result into a list
repeat_exec(N,Func) ->
lists:map(Func, lists:seq(0, N-1)).


%%% Identify the reducer process by
%%% using the hashcode of the key
find_reducer(Processes, Key) ->
Index = erlang:phash(Key, length(Processes)),
lists:nth(Index, Processes).

%%% Identify the mapper process by random
find_mapper(Processes) ->
case random:uniform(length(Processes)) of
0 ->
find_mapper(Processes);
N ->
lists:nth(N, Processes)
end.

%%% Collect result synchronously from
%%% a reducer process
collect(Reduce_proc) ->
Reduce_proc ! {collect, self()},
receive
{result, Result} ->
Result
end.



Main function

The MapReduce() function is the entry point of the system.
  1. It first starts all the R number of Reducer processes
  2. It starts all the M number of Mapper processes, passing them the R reducer processes ids
  3. For each line of input data, it randomly pick one of the M mapper processes and send the line to it
  4. Wait until the completion has finished
  5. Collect result from the R reducer processes
  6. Return the collected result
The corresponding Erlang code is as follows ...
%%% The entry point of the map/reduce framework
map_reduce(M, R, Map_func,
Reduce_func, Acc0, List) ->

%% Start all the reducer processes
Reduce_processes =
repeat_exec(R,
fun(_) ->
spawn(mapreduce, reduce_task,
[Acc0, Reduce_func])
end),

io:format("Reduce processes ~w are started~n",
[Reduce_processes]),

%% Start all mapper processes
Map_processes =
repeat_exec(M,
fun(_) ->
spawn(mapreduce, map_task,
[Reduce_processes, Map_func])
end),

io:format("Map processes ~w are started~n",
[Map_processes]),

%% Send the data to the mapper processes
Extract_func =
fun(N) ->
Extracted_line = lists:nth(N+1, List),
Map_proc = find_mapper(Map_processes),
io:format("Send ~w to map process ~w~n",
[Extracted_line, Map_proc]),
Map_proc ! {map, Extracted_line}
end,

repeat_exec(length(List), Extract_func),

timer:sleep(2000),

%% Collect the result from all reducer processes
io:format("Collect all data from reduce processes~n"),
All_results =
repeat_exec(length(Reduce_processes),
fun(N) ->
collect(lists:nth(N+1, Reduce_processes))
end),
lists:flatten(All_results).



Map Process

The Map processes, once started, will perform the following ...
  1. Receive the input line
  2. Execute the User provided Map function to turn into a list of key, value pairs
  3. For each key and value, select a reducer process and send the key, value to it
The corresponding Erlang code will be as follows ...

%%% The mapper process
map_task(Reduce_processes, MapFun) ->
receive
{map, Data} ->
IntermediateResults = MapFun(Data),
io:format("Map function produce: ~w~n",
[IntermediateResults ]),
lists:foreach(
fun({K, V}) ->
Reducer_proc =
find_reducer(Reduce_processes, K),
Reducer_proc ! {reduce, {K, V}}
end, IntermediateResults),

map_task(Reduce_processes, MapFun)
end.



Reduce Process

On the other hand, the reducer processes will execute as follows ...
  1. Receive the key, value from the Mapper process
  2. Get the current accumulated value by the key. If no accumulated value is found, use the initial accumulated value
  3. Invoke the user provided reduce function to calculate the new accumulated value
  4. Store the new accumulated value under the key

The corresponding Erlang code will be as follows ...

%%% The reducer process
reduce_task(Acc0, ReduceFun) ->
receive
{reduce, {K, V}} ->
Acc = case get(K) of
undefined ->
Acc0;
Current_acc ->
Current_acc
end,
put(K, ReduceFun(V, Acc)),
reduce_task(Acc0, ReduceFun);
{collect, PPid} ->
PPid ! {result, get()},
reduce_task(Acc0, ReduceFun)
end.


Word Count Example

To test the Map/Reduce framework using a word count example ...

%%% Testing of Map reduce using word count
test_map_reduce() ->
M_func = fun(Line) ->
lists:map(
fun(Word) ->
{Word, 1}
end, Line)
end,

R_func = fun(V1, Acc) ->
Acc + V1
end,

map_reduce(3, 5, M_func, R_func, 0,
[[this, is, a, boy],
[this, is, a, girl],
[this, is, lovely, boy]]).


This is the result when execute the test program.

Erlang (BEAM) emulator version 5.6.1 [smp:2] [async-threads:0]

Eshell V5.6.1 (abort with ^G)
1> c (mapreduce).
{ok,mapreduce}
2>
2> mapreduce:test_map_reduce().
Reduce processes [<0.37.0>,<0.38.0>,<0.39.0>,<0.40.0>,<0.41.0>] are started
Map processes [<0.42.0>,<0.43.0>,<0.44.0>] are started
Send [this,is,a,boy] to map process <0.42.0>
Send [this,is,a,girl] to map process <0.43.0>
Map function produce: [{this,1},{is,1},{a,1},{boy,1}]
Send [this,is,lovely,boy] to map process <0.44.0>
Map function produce: [{this,1},{is,1},{a,1},{girl,1}]
Map function produce: [{this,1},{is,1},{lovely,1},{boy,1}]
Collect all data from reduce processes
[{is,3},{this,3},{boy,2},{girl,1},{a,2},{lovely,1}]
3>


The complete Erlang code is attached here ...

-module(mapreduce).
-export([reduce_task/2, map_task/2,
test_reduce_task/0, test_map_reduce/0,
repeat_exec/2]).

%%% Execute the function N times,
%%% and put the result into a list
repeat_exec(N,Func) ->
lists:map(Func, lists:seq(0, N-1)).


%%% Identify the reducer process by
%%% using the hashcode of the key
find_reducer(Processes, Key) ->
Index = erlang:phash(Key, length(Processes)),
lists:nth(Index, Processes).

%%% Identify the mapper process by random
find_mapper(Processes) ->
case random:uniform(length(Processes)) of
0 ->
find_mapper(Processes);
N ->
lists:nth(N, Processes)
end.

%%% Collect result synchronously from
%%% a reducer process
collect(Reduce_proc) ->
Reduce_proc ! {collect, self()},
receive
{result, Result} ->
Result
end.


%%% The reducer process
reduce_task(Acc0, ReduceFun) ->
receive
{reduce, {K, V}} ->
Acc = case get(K) of
undefined ->
Acc0;
Current_acc ->
Current_acc
end,
put(K, ReduceFun(V, Acc)),
reduce_task(Acc0, ReduceFun);
{collect, PPid} ->
PPid ! {result, get()},
reduce_task(Acc0, ReduceFun)
end.

%%% The mapper process
map_task(Reduce_processes, MapFun) ->
receive
{map, Data} ->
IntermediateResults = MapFun(Data),
io:format("Map function produce: ~w~n",
[IntermediateResults ]),
lists:foreach(
fun({K, V}) ->
Reducer_proc =
find_reducer(Reduce_processes, K),
Reducer_proc ! {reduce, {K, V}}
end, IntermediateResults),

map_task(Reduce_processes, MapFun)
end.


%%% The entry point of the map/reduce framework
map_reduce(M, R, Map_func,
Reduce_func, Acc0, List) ->

%% Start all the reducer processes
Reduce_processes =
repeat_exec(R,
fun(_) ->
spawn(mapreduce, reduce_task,
[Acc0, Reduce_func])
end),

io:format("Reduce processes ~w are started~n",
[Reduce_processes]),

%% Start all mapper processes
Map_processes =
repeat_exec(M,
fun(_) ->
spawn(mapreduce, map_task,
[Reduce_processes, Map_func])
end),

io:format("Map processes ~w are started~n",
[Map_processes]),

%% Send the data to the mapper processes
Extract_func =
fun(N) ->
Extracted_line = lists:nth(N+1, List),
Map_proc = find_mapper(Map_processes),
io:format("Send ~w to map process ~w~n",
[Extracted_line, Map_proc]),
Map_proc ! {map, Extracted_line}
end,

repeat_exec(length(List), Extract_func),

timer:sleep(2000),

%% Collect the result from all reducer processes
io:format("Collect all data from reduce processes~n"),
All_results =
repeat_exec(length(Reduce_processes),
fun(N) ->
collect(lists:nth(N+1, Reduce_processes))
end),
lists:flatten(All_results).

%%% Testing of Map reduce using word count
test_map_reduce() ->
M_func = fun(Line) ->
lists:map(
fun(Word) ->
{Word, 1}
end, Line)
end,

R_func = fun(V1, Acc) ->
Acc + V1
end,

map_reduce(3, 5, M_func, R_func, 0,
[[this, is, a, boy],
[this, is, a, girl],
[this, is, lovely, boy]]).



Summary

From this exercise of implementing a simple Map/Reduce model using Erlang, I found that Erlang is very powerful in developing distributed systems.

Creating a Simple HTML Form Validation System Using JavaScript


OK, so today we are going to create a simple Form Validator Script using JavaScript
that would not let a HTML form be submitted unless all required field are filled
in. JavaScript is widely used for this purpose as it does not need server processing
hence no form sending and pageload is required.


When you are using data submission via form on your website there are a few
other methods that you can employ other than JavaScript; first, not to use validation
at all (NOT RECOMMENDED), second, to use validation in the script and make it
show appropriate message (need pageload).


So definitely we’ll be using JavaScript and you should in most cases,
too. Let’s kick off guys!


Now before we begin I want to tell you one thing, we will only be checking
(validating) if all the required fields are filled or not and NOT whether what
is filled in is acceptable. Of course we can use JavaScript to validate whether,
let’s say the filled email address is appropriate or not but that would
be the topic of some future posts.


So for now we just need to check all the required fields of the form to see
if they are filled in or not. Suppose if we have a form (named "form")
with four Input Boxes (namely ‘Name’,, ‘Address’, ‘Email’,
’PhoneNumber’), we can use the following piece of JavaScript code
to check them:



if(form.Name.value=='')
alert("Name field is required. Please fill it in.");

if(form.Address.value=='')
alert("Address field is required. Please fill it in.");

if(form.Email.value=='')
alert("Email field is required. Please fill it in.");

if(form.PhoneNumber.value=='')
alert("Phone Number field is required. Please fill it in.");


Since form elements reside between the <form></form>
tags, we would wrap the above code as a JavaScript function and make the form
invoke it when ‘Submit’ button is pressed.



<html>
<head>

<title>JavaScript Form Validation Script</title>


<script language="JavaScript" type="text/JavaScript">

function checkForm(thisform)
{
if(thisform.Name.value=='')
{
alert("Name field is required. Please fill it in.");
return false;
}
if(thisform.Address.value=='')
{
alert("Address field is required. Please fill it in.");
return false;
}
if(thisform.Email.value=='')
{
alert("Email field is required. Please fill it in.");
return false;
}
if(thisform.PhoneNumber.value=='')
{
alert("Phone Number field is required. Please fill it in.");
return false;
}
//if all is OK submit the form

thisform.submit();
}
</script>


</head>

<body>
<form name="form1" id="form1" method="post" action="--SCRIPT.PHP--">

<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>

<td width="121">Name</td>
<td width="379"><input name="Name" type="text" id="Name" /></td>

</tr>
<tr>
<td>Address</td>
<td><input name="Address" type="text" id="Address" /></td>

</tr>
<tr>
<td>Email</td>
<td><input name="Email" type="text" id="Email" /></td>

</tr>
<tr>
<td>Phone Number</td>
<td><input name="PhoneNumber" type="text" id="PhoneNumber" /></td>

</tr>
<tr>
<!--This is NOT a Submit (type) Button which automatically submits the form on click, rather we are using
Simple Button and the JavaScript code to submit it -->
<td><input name="Submit" type="button" id="Submit" onclick="checkForm(this.form)" value="Submit" /></td>

<td>&nbsp;</td>
</tr>
</table>
</form>
</body>

</html>



In the above code, instead of hard coding the form’s name (or object
name) in the function ‘checkForm’ we are passing it from the form.
When any form elements is found to be empty respective message is shown via
the Message Box (using alert() ).


To use the above code (JavaScript function) with your existing forms, you’d
need to make some changes to the function regarding the name and number of form
elements you want to validate. You’d also have to change the Message (alert)
shown, if required.


One last thing, if the user has turned off Java Script or their browser does
not support it, form would not be validated and you might end up receiving half-filled
information for this scenario you could employ double validation using both
JavaScript and server-side (in the script data is getting sent to). Of course
it’s very unlikely but you should be ready for everything.


Previous Posts:


Deigning a Simple HTML Menu-Bar Using CSS

Deigning a Simple HTML Menu-Bar Using CSS


In this post I’m going to show how you can create a menu-bar (list of
hyperlinks) using CSS styling. This requires that you at least have some basic
knowledge of HTML and preferably CSS too. If you can’t figure out what
a menu-bar looks like, scroll to the bottom.


Seen! Though pretty much the same can be implemented using tables but that
is not web developers prefer.


In HTML there is not standard tag for creating a menu like item therefore we
would be customized or style a standard tag. We’ll be using the ‘unordered
list’ <ul></li> tag to do so, in this case every item i.e.
<li></li> will be items in the menu.


Let us first start by creating an unordered list as follows:




<ul>

    <li>Item 1</li>

    <li>Item 2</li>


</ul>


It shows up something like below:



  • Item 1

  • Item 2


Obviously this is not what we want; items here are displaying Bullets and are
one below the other while we want them to be in one line, one after the other.
To achieve this we’ll style his ‘unordered list’ by defining
a CSS class, then applying it to this tag.




<head>

<style>

.menu ul

{

    list-style: none;

}

</style>

</head>



<body>


<div class="menu">

    <ul>


        <li>Item 1</li>


        <li>Item 2</li>


    </ul>

</div>


</body>



Here we have defined a CSS class in between the <style></style>
tags. It contains the property list-style: none for the <ul>
tag, this would make the unordered list classified by menu class
to NOT to display the bullets beside each item.




  • Item 1


  • Item 2


Great! And by the way if you don’t know what a CSS class is, for now
you can think of it as a way of defining properties in CSS which could be used
in HTML to classify different parts or tags to have properties as defined. You
can see in the above code we have used <div class="menu"></div>
to classify that portion and all the tags between it to have the special
property defined in CSS.


Coming to the menu bar, it still has a big problem that it doesn’t look
like a Menu. Well the same list would look like a menu if we style it, for this
we would have to define display: inline for the <li>
tag of the unordered list. This would make the items in the list to be in ONE
line hence look like a Menu.


<head>

<style>

.menu ul

{

    list-style: none;

}



/*We want the <li> (items) to be inline*/


.menu ul li

{

    display: inline;

}

</style>

</head>



<body>

<div class="menu">

   <ul>   

    <li>Item 1</li>

    <li>Item 2</li>

    <li>Item 3</li>

    <li>Item 4</li>

   </ul>

</div>

</body>


Menu bar would look like:



  • Item 1

  • Item 2

  • Item 3

  • Item 4


Ok now our menu bar is almost done, now we just have to make it more attractive
and to react to mouse activity. For this we’ll add some more code to the
CSS (style sheet):


Added stuff is self explanatory, padding is used to increase the clickable
are of the menu items. Now the Menu Bar would look like:



NOTE: Hover effect is not working here, because Icannot add stylesheet for
seperate pages in Blogger and I don't want to mess up the CSS Validity of this
page.


Below is the complete code listing:



<html>
<head>

<title>Menu Bar Using CSS</title>

<style>
.menu ul
{
list-style: none;
}

.menu ul li
{
display: inline;
}

.menu ul li a
{
/*Increase Clickable Area*/
padding: 8px;
padding-left: 15px;
padding-right: 15px;

/*Remove the Underline for the Link*/
text-decoration: none;

color: #000;
background: #ccc;
}

/*On Mouse Over the Link*/
.menu ul li a:hover
{
color: #fff;
background: #000;
}
</style>

</head>

<body>
<div class="menu">

<ul>

<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li
><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>

</ul>
</div>
</body>
</html>



Previous Posts:


Blogger: Method to Add 'Link to This Post' Widget on Your Posts

Blogger: Method to Add ‘Link to This Post’ Widget on Your Posts


[Today I’m going to provide you with a code that
you can put on your Blogger Blogs. It’ll give your visitors a very easy
way to link to your posts if they like it. Scroll to the bottom to see it in
action! You might also want to read New
Working Method of Making Blogger Title Tags SEO Friendly
]




When it comes to Search Engine rankings, link popularity is no doubt one of
the most important factors especially organic link popularity.


Nowadays Search Engines’ algorithms have become so intelligent and sophisticated
that they could differentiate between different types of links; paid, reciprocal,
organic etc. to name some, automatically and not let discouraged factors manipulate
rankings much (in some cases by even penalizing those site).


Coming to Organic Link Building, there is no better way to do (or at least
increase) Link Building than to ask or encourage your visitors. You see, I’ve
it at the bottom of this post. This way you are asking peoples for links as
well as providing them with the HTML code to ease the process a bit. Now if
peoples like our post or site and HTML code is what they have to copy and paste,
you stand a better chance of getting links than with many other techniques.
One more BIG advantage is that as the code would generate anchor text (text
of the hyperlink) same as the post title, again odds are that you’d get
your main and relevant keywords in the links; rather than ‘this great
post’ which some peoples prefer!


Below is the code that does this:



<!-- By Arvind Gupta -- http://learning-computer-programming.blogspot.com/ -->

<div align='center' style='border: 1px solid #646464; padding: 10px; margin: 20px;'> 


<p style='font-size: 150%; background: #C8C8C8; padding: 5px;'>Show Some Love!</p>

<p>If you like this post please consider 


  making a reference to it from other Blogs, Forums, Profiles etc. by copying 

  and pasting the following HTML code. Thank You!<br/>


  <br/>

<textarea cols='40' id='bloglinking' name='bloglinking' onFocus='select()' rows='3'>&lt;a href=&quot;<data:post.url/>&quot;&gt;<data:post.title/>&lt;/a&gt;</textarea><br />


    <!--My Link-->

    <font color="#999999" size="1"><em>Link To This Post </em>Widget by <a href="http://learning-computer-programming.blogspot.com/">Learning 


    Computer Programming</a></font></p>

    <!--/My Link-->

</div>



First, you may want to change text so as to be unique in asking people to link
to you ;-).

WARNING: You must not delete my link though… Nah! Just kidding, YOU CAN
DELETE IT if you wish to.


Now you are ready with code, open your Blog’s Dashboard move to Layout
-> Edit HTML
, tick Expand Widget Template check
box. Now there are two places where you can place it, either at the top or at
the bottom (like mine) of the post, I personally prefer it at the bottom.


To place it at the TOP, find some code that looks like below (in the middle
of the code listing):



...

...

<div class='post-header-line-1'/>



<div class='post-body'>


[--PUT THE CODE HERE--]



<p><data:post.body/></p>

<div style='clear: both;'/> <!-- clear for photos floats --></div>

<div class='post-footer'>


<p class='post-footer-line post-footer-line-1'><span class='post-author'>

<b:if cond='data:top.showAuthor'>

<data:top.authorLabel/> <data:post.author/>

</b:if>

...

...



And place our code as and where stated.


To have it at the BOTTOM, paste the code in a slightly different place as::


...

...

<div class='post-header-line-1'/>


<div class='post-body'>

<p><data:post.body/></p>

<div style='clear: both;'/> <!-- clear for photos floats --></div>

<div class='post-footer'>


[--PUT THE CODE HERE--]


<p class='post-footer-line post-footer-line-1'><span class='post-author'>

<b:if cond='data:top.showAuthor'>

<data:top.authorLabel/> <data:post.author/>

</b:if>

...

...



Previous Posts:


One More Use of Web Cookies

One More Use of Web Cookies


Ok, so we were discussing about Cookies
in the last post, continuing the discussion today we’ll see one more example
of where cookie is almost irreplaceable by any other method.


If you remember the post Creating
a Simple Visitor Counter in PHP
, although we named it ‘Visitor
Counter’, what it actually counted was the number of times a page was
requested. So, for example one person can request a page ten times and counter
would show ten but actually the number of visitor id ONE. Ten is the number
of page views.


Now you may have got what I’m up to today! Yeah we’ll employ cookies
to track whether consecutive page requests came form the same visitor

or not. If it is then another counter for number of page views will be incremented
instead.


We cannot use Session
Variables
as they by default last only until the session is over. We’ll
make the cookie expire after twenty four hour or one day period after that again
the first request by a previously visited visitor would rather be counted as
a visit and not a page view.


We’re taking the time of twenty four hours as most counters do the same,
counting the same visitor as again unique after that time.


To make the counting process more clear, let’s take an example. If I
request a website with our counter on, the first time both ‘visitors’
and ‘pageviews’ (we’ll have two counters) would increment.
No if I make consecutive requests to the pages, only the ‘pageviews’
counter would increment. Again after 24-hours (cookie expiry, if I request the
site again, both the counters would again increment (since I’d be unique
for that time) and the process repeats.


Below is the code with enough comments to make the additional part very clear,
you can read Creating
a Simple Visitor Counter in PHP
to see how to integrate this to existing
sites.


<?php

/* 

Script: Visitor Counter with Cookies

Filename:
counter.php

Date: 4-Jun-08 

Copyright 2008 Arvind Gupta 

http://learning-computer-programming.blogspot.com/ 



Use: Include this file in the web page (PHP) you want to have the Counter on.


     Call 'showCounter();' to show the counter.




You are free to modify, change, publish or do whatever with this script 


as long as this note is intact. Thank You! 

*/ 



//function

function showCounter()


{

    
//open the file in read & write mode


    
$fp=fopen("counter.txt","r+");


    
//fetch data


    //there will be two data in the file


    //first the number of visitors

    //and second pageviews

    
$data=fgets($fp,20);


    

    
//data will be seperated with a ' ' space


    //so breaking it into two seperate values


    
$data=explode(' ',$data);


    

    
//have the sepearte values in variables


    
$visitors=(int)$data[0];


    
$pageloads=(int)$data[1];;


    

    
//if NOT a unique visitor


    
if($_COOKIE['unique']=='no')


        
//increment PAGEVIEWS


        
$pageloads++;


    else
//if first tine visitor (unique in 24 hours)


        
{


            
//increment both VISITORS and PAGEVIEWS


            
$visitors++;


            
$pageloads++;


            

            
//set cookie, because visitor is not unique


            //from now on till 24 hours


            

            //first calculate the expiry time of the cookie


            //mktime generates current time in UNIX time format


            //(in seconds) we add 24*60*60 (no. of seconds in 24 hours)


            //to that


            
$expiry=mktime()+24*60*60;


            
setcookie('unique','no',$expire);


        }

    

    
//seek to the start of file


    
fseek($fp,0);


    

    
//write the new value


    //in the format we have used


    
fputs($fp,$visitors.' '.$pageloads);


    

    
fclose($fp);




    
//printf function is used to pad the 


    //pageload value, to make it look


    //good

    
return (printf("Visitors: <h1><span style=\"color: #fff; background: #000;\">%010d</span></h1>Pageviews:<h1><span style=\"color: #fff; background: #000;\">%010d</span></h1>",$visitors,$pageloads));


}

?>


Previous Posts:


Check out this stream