Popular posts

Pages

Sunday, July 28, 2013

Autorefresh page (or form submission) using jQuery

In this post you'll see how 'auto-refresh' feature can be put in a web-page (JSP here) or a form submission.

HTML
<span id="spanautorefresh">Refresh in:&nbsp;<label id="clock"></label>&nbsp;</span>

Above HTML is placed in some part of the page for user to know when the page is going to refresh. We'll use the 'clock' label to display remaining seconds to refresh.

jQuery
In our $(document).ready(function(){});, we'll put our jquery function which goes like below

// base functionality start
    var refresh=false;
    var refreshinterval=parseInt(60);
    clock = $("#clock").text(refreshinterval);


    var refreshfn = function autorefresh() {
        if(refresh) {
            var sec = parseInt(clock.text());
            sec = sec - parseInt(1);
            clock.text(sec);
            if(sec<1) {

              clock.text(refreshinterval);
              makeRequest();
              //window.location.reload();
            }
        }
    }; 


setInterval( refreshfn, 1000);

// base functionality ends


//Below 'click' handle is to 'pause' the timer
    $("#spanautorefresh").on('click',function() {
        if(refresh) refresh=false; else refresh=true;
    });


Now lets go through the code. First two lines are used to set the variables for status (refresh=false) and refreshInterval (in our case 60 seconds). Next we're storing the 'clock' label in clock variable for future use. The actual magic is done by the variable 'refreshfn', which is our function. Since we've set the refresh variable as 'false', as the page loads for the first time the timer is off. Once the user clicks on the span (which houses clock) the refresh variable is set to true.
The function 'setInterval( fn_name, milliSeconds ) is standard JS function which invokes the fn_name every milliSeconds ms. In our case it invokes refreshfn every 1000 ms or 1s. When this happens refreshfn is called and if refresh is 'true', the value of clock is reduced by 1. The IF block inside refreshfn checks the text value and if it is less than 1, a> sets the clock text back to 60, and b> calls makeRequest() function in this case. For standard auto-refresh, simply call the window.location.reload() JS function. In this case makeRequest() is doing jquery AJAX/POST request, sending a form data to page X and getting some values to populate a DIV element in current page.

Auto refresh can also be enabled in standard JSP using response headers. But jquery gives you much more control over the functionality and can be triggered by user's action and page state.

I hope you find this functionality useful and easy to implement!

Saturday, March 30, 2013

Taking the road ahead

Quite often, while making a decision, I find myself in deep thought over the available options. This is not uncommon, given the fact that life today throws at us a plethora of choices...
Its not wrong to think, not at all. And that decision, however small, still affects our life. Sometimes for a short while, choosing to go for a boring movie, or an year, buying a pair of super comfy shoes. Or for the whole life, say deciding over a life partner.

The problem here is, some of us (myself included), waste an extraordinary huge amount of time to decide over things. Most of the time, things that are not worth giving a tenth of the time they stole. We take our sweet time and keep meditating on them. What we forget in this process is, total time that we have is limited. Which makes it imperative, that we make most of the available time. Now if we spend more time on deciding whether to take choice A or B, where is the time left to exercise/enjoy the outcome of our decision, or maybe to rectify? For every one second added to the decision making process, one second is deducted from the time we could have utilized our life after that decision.

So, to maximize the available time, we need to allocate the right amount of time to decision-making and move on. We just cannot endlessly keep the decision open. But a question arises, if I take a hurried decision, would that not affect the quality of it? Isn't that risky? That was my way of thinking too. I would rather keep the decision open, than to choose an option which did not have 100% of my heart. Unfortunately it is the wrong approach. One, precious time is wasted. Two, the whole purpose that decision came to me, at that precise time was because it would have brought a value-add to me and my life at that point in time. When I keep the decision pending for a long time, that value diminishes gradually. So whole of that exercise becomes a waste.

The answer is: we have to take a leap of faith. Even if a single option does not emerge as the "winner", we must go with the one which seems to be closest, and trust our instincts. Anyway, even after much deliberation we could not conclude, which means there are (and will be) unknowns involved. So its better to take the leap, free our mental energy and concentrate towards other meaningful stuff. Because while that decision is open, we are unable to live life to the maximum. When we make this decision with this approach, suddenly everything changes. The situation comes under our control. The time we were about to spend further deciding, we can now utilize to drive our actions in favor of the selected option and make most of our life. This single fact, truly means a lot. Its like, once we take this decision, it brings us back into the game, where moving ahead is the mantra, and stopping is game-over.

Thursday, September 27, 2012

Perl program using HTTP Microsoft Translator API

Code


## LWP for bing translator

#use strict;
use LWP::UserAgent;
use URI::Escape;


$browser = LWP::UserAgent->new();

## 1 Prepare for POST query with your application registration details

$url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
$client_id = "YOUR-CLIENT-ID";
$client_secret = "YOUR-KEY";
$scope = "http://api.microsofttranslator.com";       # fixed
$grant_type = "client_credentials";                  # fixed

## POST request for the 'token'
$response = $browser->post( $url,
    [
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'scope' => $scope,
        'grant_type' => $grant_type
    ],
);

## Token received is in JSON format, but I've treated it as a string
## and parsed it using pattern matching.

my $content = $response->content;

@array = split(/,/,$content);
$var = $array[1];
$var =~ /"(.*)":"(.*)"/;
$token = uri_escape("Bearer " . $2);
print "Token is ", $token, "\n\n";

print "Sending text for translation\n";

## Text to be translated.

$text = uri_escape("This is my life.");

## 2 Prepare the URL for the GET request, with 'to' language and other parameters.

$url2 = "http://api.microsofttranslator.com/V2/Http.svc/Translate?text=" .     $text .
        "&to=" . "de" .
        "&appId=" . $token .
        "&contentType=text/plain";

$resp2 = $browser->get ($url2, 'Authorization' => $token);

## Here you get the translated string with some tags, which you can parse as per your wish
$value = $resp2->content;
print "\nTranslated text is ", $value;

Output


Sending text for translation
Translated text is <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Das ist mein Leben.</string>

Explanation

The above Perl code uses the Microsoft Translator API to convert text from one language to other language. Here is the link for the application http://www.bing.com/translator/.
Microsoft has provided couple of ways to use the API. Here, I've used the HTTP API in Perl, because well, that is what I know :p.

So first, you need to register yourself on Windows Azure Marketplace, then register your application (a simple entry) to get your KEY.
How this works is, every time you want to run your program to use the API, you request for a 'token' as a POST HTTP request. This token is valid for 10 minutes. Within this 10 minutes your program can use this token to make any text translation request.
Once you receive the token, make a GET request using this token and the return you get is a translated text.
The reason that I'm writing this, is because the documentation on MS site is not clear at all. I really liked the google implementation, it was straight forward. But then it became paid. I guess all good things come to an end after all.
You can explore more on the MS site http://msdn.microsoft.com/en-us/library/hh454950.aspx. Hope you find this interesting!

Sunday, September 25, 2011

Recovery from injury: 5 weeks and counting

Yep! first plaster of my life.
Got the plaster on my leg cut yesterday. Yeah, i did not mention that I hurt my ankle on 15 Aug 2011 (independence ??) badly. The sad part is, it did not happen doing some sport or hi-octane activity..yep. I had gone to check out on houses for a very good friend and was climbing down stairs near my apartment. Trust me, it wasn't the poor stairs' fault. It was me who was hurrying down ..kind of running :(. Actually, I do that quite often, ie., running while coming downstairs. That is ..no wait..'was' one of my bad habits. Blame my long frame and legs! You know the momentum feels really good while coming down. Anyway, so I ran down the whole stairs and had put my first step on the ground. The ground had some pebbles perhaps..and my left ankle got twisted inwards...it pained like hell when I heard the cluck-cluck sound coming from the feet-side. Here I should mention that in the past too, i've had my ankle twisted quite a number of times, and my ankles are prone to such events. But never did I ended up in this kind of pain. It had always been a sprain which subsided in a few hours.

After hurting my ankle I almost toppled and would have fallen had I not re-balanced myself quickly. Came back home ..hopping on one leg, did a tiny iodex massage and went for a nap. Two hours later I woke up to feel the damn pain, couldn't keep my foot on the ground. Had swelling around the joint too. Mom and I knew that things were not OK and we should visit the hospital. Doc advised plaster for 3-4 weeks and told us that i had a fracture.
Inspite of a five week rest I was disappointed when I did not find the recovery which I expected  ...you know it was my first (and hopefully last!)...some pain is still there if i try to walk normally. To avoid the pain, I have to put my feet slowly, cautiously and being aware of the angle of foot lift and drop. Also have to walk with a stick. Now I've put an anklet, to give support to the joint. I have a feeling that it'll take yet another month for 90% recovery ...too long!

By the way, the whole experience was, in a way, an eye opener. First, body cannot take twists and turns and punishments as it could take..say 3-4 years ago. It grows old :(. Not that I was not aware of this..I have always been somewhat of a fitness-freak, but there is nothing like 'first-hand experience', 'first encounter' or 'pehla-nasha'...call it whatever you want. It is now that I've truly understood..from the bottom of my body.. that regular exercize is super important to keep the bones and other inside stuff (immune, digestion, metabolism level, skin quality, blood flow, bp, heart muscle etc) strong and capable for absorbing jerks and shocks, thereby avoiding the hospital visits. Second, as we grow old we should stop our childish habits ...like running down the stairs ...

Saturday, April 23, 2011

A Beautiful Thought

When I read it at first, I did not think of it much. But as I dwelt upon it, gradually the truth behind the idea made itself completely evident. I had heard it umpteen times before, from elders, in books, in the form of quotes, but this was the simplest and most effective form of it. It is: "Thoughts crystallize into actions, and actions quickly solidify into habits". Simple as that. It is very succinct and discreet, but holds the wisdom of worlds.
To test the veracity of the said statement, I took examples from my own experience. To my surprise, it never failed. And why should it? Of-course some wise man must have seen the world before he said it.

Thoughts, then, are the ultimate foundation upon which the outcome of every event of our life rest. Which is why every great man, be it Bapu, Einstein or as a matter of fact even Hitler, emphasized on changing the core thoughts of the masses to obtain desired result. It is only natural that thoughts which reside inside of us, will, in someway express themselves. It is then, only a matter of time and circumstance, that the faithful servant of thought, Action, will show itself. And it is straight-forward enough, you will reap the outcomes of the similar fashion. You will agree with me that if one continues to be in some state of mind, he becomes, or in other words, starts living that state sooner or later. He becomes that state eventually. That state becomes his habit of living and it is certain that everything that will follow in his life will be a mere extension to his state of mind.
Let us take the very typical example of a dissatisfied employee. He may be unhappy with his compensation, environment, the way his employer behaves with him, or he does not find himself suitably skilled with the role of the job. If the employee is a person who harbors only negative thoughts, let us see what is most likely to happen. Since he is unhappy with his work, all negatives thoughts surround him. He thinks ill of his boss, lowly of his job and his life. Action follow thoughts. His interest will suddenly decline in job. He is mostly seen cribbing about everything in his life and polluting the air around him by spreading negativity. Now as a result of all this, the only logical outcome is that the boss notices that he is a non-performer and is morally degrading the environment, and dismisses him, perhaps after some counselling which turns out to be futile and ends in a fight. So, we see that the thoughts which the person fixated upon, finally, resulted in negative outcome for him and most probably for people around him, like his family. Now in same circumstances, had the person been of a positive mindset, the outcome would have been greatly opposite. He thinks foremost, that as he is unhappy about his job he has to do something about it. He thinks of improving his skills, or speaking to the boss, about what is it that is wrong with him. As the thoughts mature, his actions imitate them. He starts building his skills and makes himself better than he was yesterday, or the day before. His mood also cheers up. The quality of his work improves inch by inch and it begins to shine. Then it becomes a habit. With his new found energy and enthusiasm he gives innovative ideas and profitable inputs to the business. A day comes, when amazed by the changes, his boss gives him a raise, and starts trusting him. Good things begin to happen. New opportunities also find him, like a much better job, good friends, and eventually his life takes a 360 degree turn. And he then himself becomes the the state, with which he started.

These examples are common in life and I have witnessed both cases first hand. It can be confidently said, that if one controls his thoughts, he can change his life. There is nothing which can stop him. Because the truth is, what you think, you become. It will not happen suddenly, but gradually it is bound to happen. All that is required to build your thinking and keep your thoughts high and unperturbed. Nature is such, that what you keep thinking, will slowly surround you in your everyday life. From no-where, things, opportunities, people and events which match your frequency of thinking will come to you from all directions. If you are sensitive you may already have noticed it happen at some point, but may have attributed it to chance. It is not chance but a law of nature.

There are no limits to the benefits that we can draw from this knowledge. We can reach anywhere we want, we can learn any skill we wish to, we can be as rich as aspire ...anything is possible. The only mandate is, those positive thoughts, are to be kept alive in one's mind, undiminished, untarnished by tiny obstacles, which naturally will come along the way. There is absolutely nothing which cannot be achieved. Remember, what we think, we will do. And what we do, the outcome will invariably be of same nature. Keep your thinking high and you will always reach higher.

- the usual me

Saturday, April 9, 2011

perl script to use google language translate API

I created this script which translated text from one language to another using yahoo's http://babelfish.yahoo.com/ services. But its not the one which i'm going to talk about. That is because in the yahoo version i used perl's LWP module to do a post query on the yahoo server and get back the http response, much like what we see on a browser, and got the translated text using pattern matching operations. That is one crude way of getting things done, but it works!

Now this does the same job but using google services (translate.google.com) and the respective APIs. Its a more sophisticated and efficient way of achieve the same result. Google has exposed the API and the methods for doing this job. You can call them from applications such as - your software, your mobile app, your website or a small script (like tihs one), etc. Mind you, it is illegal to use it for commercial purposes.

For this translate API, you've to generate an activation key (tied to your google account). 
First section is the creation of a LWP::UserAgent object. Then for sanity, convert the text to webformat. Then I've created the url with editable parameters as variables. The text to be converted is $str and needs to be given as command line argument. I like German so its my language of choice for converted text. The response object is created by the get function on UA object. The 'content' method is used on response object for the output, whereas the error state and message are captured in 'is_success' and 'status_line' methods of the response obj. Again, for the desired line in the http response content we need to use pattern matching as shown.

The idea is, how the google (or any) api can be leveraged with perl's lwp module to do some fun programming or something more useful which can solve real problems at your work/school/college. If you've something to share, do comment.
Here's the code:

## google translate API

# https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q=hello%20world&source=en&target=de

use Strict;
use LWP::UserAgent;
use URI::Escape;

if ($ARGV[0] eq "") {
print "Usage: perl lwp12 \"text to be converted\""; die; }
$ua = LWP::UserAgent->new();

$str = uri_escape ($ARGV[0]);
$tolang = "de";

$url = "https://www.googleapis.com/language/translat/v2?key=<yourPersonalKeyHere>&q=" 
. $str 
. "&source=en&target="
. $tolang;

$resp = $ua->get ($url);

if ($resp->is_success) {
$newstr = $resp->content;
$newstr =~ /Text":\s"(.*)"\n/;
print "Text in $tolang:\n$1\n"; }

else { print "Program failed with message: ", $resp->status_line;}
# END


Here is how it runs:

>perl lwp12googletranslate.pl "My first program."
Text in de:
Mein erstes Programm.


Output while error handling:

>perl lwp12googletranslate.pl "my first wife"
Program failed with message: 404 Not Found

Monday, April 4, 2011

perl program to report port status

This program here checks and reports the status of ports on a windows machine. The objective was to check whether some application (web site) was running and hence using those ports. The logic is simple. The ports (actually, ip:port combination) which are needed to be monitored are listed in a file. This could have been kept inside the code, for better performance. But i wanted to keep the "logic" portion separate from "data" portion so data / logic can be edited independently without affecting other by mistake. And ofcourse it is easier for the user to open a file and edit the port file, rather than going through the code and getting in unimportant details. So the port status is available thru windows "netstat -an" command. The status of our ports is checked and the output is logged into a separate log file. This log file, by the way, is read by another software which then puts the data on display for the user. Here's the program. First section is the custom timestamp for log file. Then every port entry in our file (first foreach loop) is compared with every netstat o/p line (second foreach loop) and mark a flag if matched. Then get out of inner loop, check the flag value, and log the entry with a custom message. I guess thats about it. At some places, such as pattern matching, it can be done more efficiently (with less characters) but i like to keep it simple. i think some advanced users may be able to do it with lesser line of code too. Basically it is a straight forward program which produces desired results. For perl beginners it might prove to be helpful and can be used in other similar situations.

#
#
# Purpose: Script to report status of active ports on Windows machine
# Associated Files: 
# 1. portlist.txt - list of ports. File required in current directory.
# 2. log_status.txt - port status log. File is generated in current directory.
# Date: 29 March 2011 
# Author: Abhishek Danej
# Revisions:
#

use Strict;
use Time::Local;

##
## USER EDITABLE PARAMETERS
##
$portfile = "portlist4.txt"; #path to list of ports file
$logfile = "log_status.txt"; #path to log file
$true_msg = "Listening"; #success message in log file
$false_msg = "Not found"; #failure message in log file
##
## END
##

## NON USER EDITRABLE SECTION

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$mon = $mon+1;
foreach $val ($sec, $min, $hour, $mday, $mon) {
$val = "0" . $val if ($val < 10); 
}
$timestamp = ($year+1900) . "-" . $mon . "-" . $mday . "," . $hour . ":" .  $min . ":" . $sec;

#$timestamp = scalar(localtime());
$host = `hostname`;
chop ($host);

open (LOG, ">>$logfile") || die "Cannot open Log file";

#@portlist = ("4757","1111","1101","6000","7153","57153");
unless (open (PORTS, "<$portfile")) {
print LOG "$timestamp ERROR: Cannot open portlist.txt file, program quitting.\n";
die "Cannot open port file."; }
@portlist = <PORTS>;

open (FH, "netstat -an |");
@lines = <FH>;

foreach $ip_port (@portlist) {

$flag = 0;
$ip_port =~ s/\s*\b(\d+\.\d+\.\d+\.\d+):(\d+)\b.*\n*/$1:$2/;
next if ($ip_port !~ /:/);
print "Now checking: $ip_port";
# EACH LINE OF NETSTAT
foreach $line (@lines) {
if ($line =~ /$ip_port\b/ && $line =~ /LISTENING/ && $line =~ /\b0.0.0.0\b/) {
$flag = 1;
last; }
}
if ($flag == 1) {
print LOG "$timestamp,$host,$ip_port,$true_msg\n"; }
else {
print LOG "$timestamp,$host,$ip_port,$false_msg\n"; }

}

close (PORTS);
close (LOG);
# END