Program to Compute Large Fibonacci Numbers in Hex

Sunday, December 27, 2009

Here's a Java program that calculates the n'th Fibonacci number in hexadecimal format, where n could be infinitely long. For those who don't know, Fibonacci series is a series which is calculated by summing up the last two numbers of the series. It starts from 1, 1, 2, 3, 5, 8, 13, 21...

Large Fibonacci numbers are particularly useful to calculate the Golden Ratio, which can be calculated by using the ratio of the last 2 infinitely large terms of the Fibonacci series. The approximation of the ratio improves as you progress farther in the series. For more interesting mathematical properties read the Wikipedia entry for Golden Ratio.

In this program, the hex values are stored in string because of the restrictions posed by the conventional data types. The series is calculated by summing up the last 2 numbers of the series using carry and adding digit by digit. Eg. 8 & 13 can be added by adding 8+3 and have one in unit's place and carry 1 to the ten's place, then adding 1+1 = 2; thus, the answer 21.

public class FibonacciNumber {

public static void main(String[] args) {

String h1 = "1"; // First Fibonacci Number
String h2 = "1"; // Second Fibonacci Number
String h3 = ""; // Next Fibonacci Number
String tempResult = "";
int i1=0, i2=0, i3;
Long ctr = new Long(0);

try {
// Loop till maximum value of Long
// Each run calculates the next number
while (ctr < Long.MAX_VALUE) {

i3 = 0;
h3 = "";
ctr++;

// This loop calculates the sum of the previous numbers digit by digit
for (int i = h1.length(), j = h2.length(); j > 0; i--, j--) {

if (i > 0) { // If a digit is left in i
i1 = Integer.parseInt(h1.substring(i - 1, i), 16);
i2 = Integer.parseInt(h2.substring(j - 1, j), 16);
i3 += i1 + i2;
} else if (h2.length() > h1.length()) {
// When h1 is shorter than h2. Eg. h1=8 h2=11
i2 = Integer.parseInt(h2.substring(j - 1, j), 16);
i3 += i2;
}

tempResult = Integer.toHexString(i3);

if (tempResult.length() == 2) // Handling carry digit
{
i3 = Integer.parseInt(tempResult.substring(0,1), 16);
h3 = tempResult.substring(1,2) + h3;
}
else // No carry digit
{
i3 = 0;
h3 = tempResult.substring(0,1) + h3;
}
}
if (i3 != 0)
h3 = tempResult.substring(0,1) + h3;

System.out.println(ctr + ": " + h3);

h1 = h2;
h2 = h3;

}
} catch (Exception ex) {

System.out.println(ex.toString());
}

}
}


The output of the program will look like:

1: 2
2: 3
3: 5
.
.
244: 3144535de4cae86ae251b1971896d58bf961e6b9d48
245: 4fb72becbf73267006f65a3aa504c57b1e9930e392d
246: 80fb7f4aa43e0edae9480bd1bd9b9b0717fb179d675
.
.
846: bc35110da32840cce42425afddfe8fde936030e7fda1d532615324be2a410804acef43394c0b512d5e34a2f5e77fbe0e82d80580f4fb592de0232add6f7e6f34127e8eb43165d008fe5
847: 130869a782cc70170bd47e47fb3034ecbbce810b2e7dce2a56c30baa1f3bc359eb13f26ed83e0f4357dbed6c374b79dfcf303e52c94a3996b1dfff19229baa1c0194727a75d25313cd62
.
.
Can go upto zillions of numbers.

What Do I Tweet About?

Sunday, November 29, 2009

From the past few months, I've been tweeting a lot (atleast reading a lot of them) and that's one of the reason I've been irregular on my blog. So, here's a cloud showing what I have been tweeting about.


Generated using Tweet Cloud.

Lost Generation

Tuesday, September 29, 2009


A nice video depicting some of the characteristics which our generation is adopting.

What to Write and What Not?

Friday, August 28, 2009

It has been quite some time since I last posted on my blog. I'm often in a dilemma when it comes to posting something on my blog, especially when posting non-tech stuff. In my previous posts, many a times I've talked about posting more personal stuff out here. Infact, in Jan 2008, I had a complete post on this. But alas, there is rarely anything personal on my blog.

Most of my recent posts make this blog look like a technology blog. Most of these are code samples, tips and tricks, technology reviews etc. One of the reasons for this is that, I kind of use this space for my own reference by posting stuff I might need to use in future. Also, at times, these help others looking for similar stuff (and I get visitors from search engines).

Coming back to the dilemma about writing blog posts - it’s hard to decide what I want to share on my blog. I can't figure out how to post on the public domain. Many a times, I think about posting some small events and happenings in life. But then I just don't want to write a complete post about it. These personal posts can sometimes take a lot of time as it requires a lot of thought process to put everything together. Most of the times I just feel its not worth the time.

Some of these personal things just find another place on the web - my Twitter account. It’s much easier to tweet stuff rather than writing a large post about it. This is one of the reasons that I post less on my blog. I tweet about a wide variety of stuff, some of which would have been on my blog if there was no Twitter.

Talking about some social networking sites - there was a time, when I was very frequent on Facebook and Orkut but not any more. I do visit these occasionally, but hardly ever do things like changing my Facebook status. Previously, I've also been active on various forums where I've posted actively; but now a rare visitor to those forums too. For me these online habits evolve over time then go into long hibernation stretches and sometimes wake up for short spells of time.

Hopefully, in future I'll continue posting more useful stuff on this blog and cut down on these crap posts. Thank you for bearing with me through this post, I know it wasn't a nice read.

ASP.NET: Format Phone Numbers using RegEx

Monday, July 13, 2009

If you have a database having phone numbers in various formats, you would want to display them in a consistent format. A solution to display phone numbers in a standard format without worrying about the format in the database is to use regular expressions to format the phone numbers.

For implementing this into ASP.NET pages create a class in the App_Code folder of your web application. Create a static(C#) or shared(VB.NET) method in this class which gets the value of the phone number field as object to handle null values of phone numbers in the database. The code for this function is given below:

// C#
public class CommonFunctions
{   
    public static string FormatPhone(object phoneNo)
    {       
        string formattedPhone = phoneNo.ToString;
        // Extracting numbers from the string
        formattedPhone = Regex.Replace(formattedPhone, "[^0-9]", "");
        // The format is in third parameter of the replace function
        formattedPhone = Regex.Replace(formattedPhone, "(\\d{3})(\\d{3})(\\d{4})", "($1) $2-$3");
     
        return formattedPhone;
    }  
}
' VB.NET
Public Class CommonFunctions

Shared Function FormatPhone(ByVal phoneNo As Object) As String
Dim formattedPhone As String = phoneNo.ToString
' Extracting numbers from the string
formattedPhone = Regex.Replace(formattedPhone, "[^0-9]", "")
' The format is in third parameter of the replace function
formattedPhone = Regex.Replace(formattedPhone, "(\d{3})(\d{3})(\d{4})", "($1) $2-$3")
Return formattedPhone
End Function

End Class

The above function first abstracts all the digits from the phone number by using the "[^0-9]" regular expression; all characters which are not numbers are replaced by "". Then the phone numbers are broken into three groups using "(\d{3})(\d{3})(\d{4})" and the groups are then displayed as "($1) $2-$3". Thus, a phone number such as 123.456-7890 will first be converted into 1234567890 and then formatted as (123) 456-7890. You can modify the display format by changing the second replace function.

You can use this method from any ASP.NET data bound field as follows:

<%# CommonFunctions.FormatPhone(Eval("Phone")) %>

Though this example shows the use of this function for ASP.NET pages, it can be used for any .NET based application.

Free Remote Login Tools

Thursday, July 09, 2009

Remote login tools allow you to connect to your computer remotely. You get complete control over your desktop and you can work as if you were working on your own machine. The Windows standard "Remote Desktop Connection" tool is one of the best methods to connect to your computer remotely. But its difficult to use when your computer does not has a static IP address, is connected over a LAN or with a DSL modem which uses NAT.

Here are some tools which I've used for remotely connecting to my computer and should be helpful for others:

Live Mesh:
Live Mesh is one of the best free tools, I've come across. It has great remote desktop capabilities with features similar to the Remote Desktop connection. You would need the Mesh software to be installed on both machine and logged in with a live id. Live Mesh has many more capabilities apart from remote connection. It has a fabulous file synchronization service with 5GB of free storage space. I have been using it for the past 6 months and it has been really superb. Highly recommended if you work at multiple locations. (Also see an earlier post: Mesh up your Data on Live Mesh.)

TeamViewer:
TeamViewer is a simple tool which allows you to remotely connect to a computer and requires a combination of auto-generated id and passcode. You don't even need to install the tool, you can just run the program by selecting the appropriate option in the setup exe. Anyone having access to the id and passcode can run team viewer and remotely access the computer. This tool is good if you need a temporary access to a computer. I prefer this tool for troubleshooting someone's computer. It gives you the complete desktop access of the machine by sending snapshots of the workspace. It supports Windows and Mac.

These free tools are great alternatives to the paid remote desktop softwares such as GoToMyPC and other VPN based tools. There are many more free tools available, feel free to post a comment about them.

.NET: Convert Image Formats Programmatically

Tuesday, July 07, 2009

Using the .NET framework, you can easily convert images from one format to another with just a few lines of code. The System.Drawing namespace has the functions which help you to load and then save the image in the desired format. The formats supported by the ImageFormat class are: Bmp, Emf, Exif, Gif, Guid, Icon, Jpeg, MemoryBmp, Png, Tiff, Wmf. You can convert an image to any of these formats.

Here is a simple console application which reads all files in a given directory and converts them into .jpg images. It includes the System.IO namespace to read the files in the directory and the System.Drawing class for image functions. You would need to add a reference to System.Drawing class in the Console application. Also, make sure you only have images in the directory or specify a check in the code to read only image files.

// C#
using System.IO;
using System.Drawing;

static class Module1
{   
    public static void Main()
    {
        DirectoryInfo dir = new DirectoryInfo("C:\\something");
       
        foreach (FileInfo img in dir.GetFiles) {
            Image _image = Image.FromFile("C:\\something\\" + img.Name);
            _image.Save(img.Name, Imaging.ImageFormat.Jpeg);
        }
    }   
}
' VB.NET
Imports System.IO
Imports System.Drawing

Module Module1

Sub Main()
Dim dir As New DirectoryInfo("C:\something")

For Each img As FileInfo In dir.GetFiles
Dim _image As Image = Image.FromFile("C:\something\" & img.Name)
_image.Save(img.Name, Imaging.ImageFormat.Jpeg)
Next
End Sub

End Module

The output files would be written into your 'bin' directory if you execute this code from Visual Studio. If you need to change the output path, you can do so by adding a Path to the Save method.

ASP.NET: Changing Nested Controls on Repeater's ItemDataBound

Monday, June 22, 2009

ASP.NET Repeater is a great control to display a series of data in a custom formatted style. It gives you independence to choose your data layout rather than going with the standard table layouts of the DataGrid. When using repeaters it may be sometimes useful to modify a display control inside a repeater depending on the value of a DataItem which is bound to the repeater.

Here's a simple example on how to change value of a control in the repeater on ItemDataBound. The following code checks the value of the "id" column of the DataRow and checks if it matches with the one passed by query string. If that's the case it then updates a Label for that element.

' VB.NET:
Protected Sub rptr_ItemDataBound(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptr.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
If ((CType(e.Item.DataItem, System.Data.DataRowView)).Row("id").ToString() = Request.QueryString("id")) Then
CType(e.Item.FindControl("lblBoolDisplat"), Label).Text = "This value is being requested."
End If
End If
End Sub
// C#
protected void rptr_ItemDataBound(object source, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem))
{
if ((((System.Data.DataRowView)e.Item.DataItem).Row("id").ToString() == Request.QueryString("id")))
{
((Label)e.Item.FindControl("lblBoolDisplat")).Text = "This value is being requested.";
}
}
}

For C#, also add:
OnDataItemBound="rptr_ItemDataBound"
on the <asp:Repeater> tag in the ASP.NET page.

Though this is a very simple example, it is very useful in handling complex data. A similar logic is applied when nesting repeaters in a repeater. A nested repeater could be accessed as a nested control in the same way the label is being accessed in the above code.

Facebook phishing Scams on the Way!

Sunday, May 24, 2009

I received a message today which had "wwww whiteflash be". Its a phishing scam to extract Facebook login information. Searched twitter and found out multiple domains being used for the scam. Beware of entering any information on the following sites:

whiteflash.be
mymarket.be
vispace.be
goldbase.be
greenbuddy.be
silvertag.be
picoband.be

Google and other anti-phising services are yet not updated with these URL's to warn users. In general beware of any links that end with .be. The pages look like this:



These sites are hosted in China on IP: 211.95.78.98, with the following Whois record:

Domain: picoband
Status: REGISTERED
Registered: Fri May 22 2009

Licensee:
Not shown, please visit www.dns.be for webbased whois.

Agent:
Name: 1API GmbH
Website: www.1api.net

Nameservers:
ns1.everydns.net
ns2.everydns.net
ns3.everydns.net
ns4.everydns.net

If you have already entered your login information in any of these websites, I would suggest that you change your passwords immediately. Have a safe browsing experience!

Youtube's Background Image

Wednesday, May 20, 2009

I just saw the background image of YouTube and was amazed to discover that it has all the commonly used graphics on a single image. I don't know how many people have actually noticed that or used this technique, but it looks brilliant to me. Its superb to fit in so much in a png image which is less than 10KB and then using CSS to display the appropriate parts of the image for each div block.

It is common to use such images for hover buttons, where you just change the position of the image for hover effects. This ensures that you don't have to wait for the hover image to be loaded to see the effect. But, I never ever thought of encompassing all my graphic objects in a single image file and then displace the image as required using the background-position property in CSS. It would definitely make the page load much faster than having to download a plethora of small images which are scattered all around.

The YouTube background includes the header logo, the favorite rating stars, the button backgrounds, small buttons, gradients etc. Most of the images in this common background are used in all pages of the website and thus, its a good choice to group them all together as a single image and reduce the overall page load time.

If you want to view the background image, right click on a static background area (the gray header near the search box is a good choice) and select (in Firefox) view background image or (in IE) save background image. I'm sure, you would be surprised to see the huge png image. Alternatively, you might just want to visit this link to view the image.

Progress in Video Advertising

Sunday, May 10, 2009

With the popularity of Youtube and other online video streaming sites, video advertising is increasingly becoming a domain people want to explore. Video advertising is increasingly becoming popular and adds a new dimension to the text and banner based internet advertising. Its a very promising new form of internet advertising.

A lot of new methods are being developed for this new form of advertising. One of the most interesting ones is in-video advertising. Imagine advertising a product by placing it at an appropriate spot in the video and allow user to click on the product to view details and purchase it. Or just putting an advertisement on a building shown in the video. The video advertisement technologies are emerging to make all these things possible.

Innovid is one such company which has come out with some great techniques for In-Video advertising creating a brand experience which had not been possible before. They allow you to create videos with user interaction which is super cool. They have one of the most innovative advertising techniques which allows the advertisements to be placed in a streaming video. Check out their gallery for the ad methods they have developed.

Another interesting technology is Zunavision, which is developed by Stanford University and allows advertisers to dynamically add image or video in an already existing video. You just select a surface in the video to place your ad and it automatically adjusts the advertisements with the motion of the video. See the following video which describes how this technology works:




The future of video advertising seems great and can help monetize the video content people generate.

Micro-blogging on Twitter

Friday, May 08, 2009

The frequency of my posts on the blog have been decreasing over time. With all my buzy schedule, its difficult to update the blog regularly. I've recently started using twitter and have fallen in love with this concept of micro-blogging. Its so much easier to just write a line or two than writing a complete post on something you just saw. Its instant, its simple and its fun.

I have had lots of things I thought to blog about but most of them never make it out here because I don't have had the time to post them. But now, whenever I see something interesting, I tweet about it. Its also interesting to get almost instant replies about it. I find it better than the Facebook status updates.

Twitter has been there for a while and is gaining momentum. People have started using it for marketing, job search, networking and much more. There is a lot of spam out there too, but you have control over whom you want to follow and an option to control who should be following you. Your followers are the ones who can read your tweets and you get updates from people whom you are following.

You can follow me on on twitter: @gsmodi. Also, my twitter feed would now be posted on the right column of my blog.

YouTube and GMail on April Fool's Day

Wednesday, April 01, 2009

Today, you might have noticed the flipped YouTube or New GMail! Autopilot on top of your gmail. You might have twisted your screen or head to watch the new YouTube or tried to activate the non-existent autopilot on your settings tab. That's Google making you April Fool. Google always comes up with these amazing things on April Fool's day.

If you are a web developer, you might be wondering how did they code the flipped version. They would be using javascript to change the character's to a the charset of flipped characters. Here's a code that shows you an example.

Here's how a YouTube page looked today:

The GMail notification:

The description of AutoPilot:

The April Fool's description of CADIE (used for GMail's autopilot) can be found here.

Web Hosting Reviews

Monday, March 23, 2009

With so many web hosting companies out there, choosing a reliable web hosting is not an easy task. Today, while choosing a web hosting service you would be glutted with options to choose from. You would have a huge list of web hosts to choose from and it would be challenging to choose the one which best suits your needs. There are various websites where you can find reviews about various web hosts providing you the information you need. It is a good option to compare the plethora of hosting services by reading these web hosting reviews.

For a website, the things you need are domain, hosting and content. Choosing a right domain name is essential and it should be able to reflect the content on the website. But to put this content together you would need to host it a reliable place where it is secure and approachable without any downtime or delay. Your host should ensure fast processing and delivery of the requests on your website.

There would be a plethora of other factors you would need to consider to choose a good webhost. First and foremost you should look and the tools and technologies supported by the webhost like the platform, scripting support, databases or any other special requirement you might have. Then look at your other requirements, hosting uptime history and pricing aspects. You may find this article by web hosting geeks useful.

Undo Sending a Message in GMail

Thursday, March 19, 2009

It often happens that after clicking that send button of the email, we recall that there was something more to be added, a missing attachment or we just regret sending that email. Well, now if you are using GMail and can get a reflex in 5 seconds you can 'Undo' sending a message.

Google Labs has come up with the 'Undo Send' gadget which will allow you to cancel sending a message for which you have just pushed the Send button. The only catch is that you just have five seconds to take action. To activate this gadget in your GMail account, go to Settings and then select this gadget from the Labs tab.

This feature was just announced on the GMail blog. It reads:
"This feature can't pull back an email that's already gone; it just holds your message for five seconds so you have a chance to hit the panic button. And don't worry – if you close Gmail or your browser crashes in those few seconds, we'll still send your message."

The feature is definitely great but I believe the interval of 5 seconds is somewhat low. It should have been somewhere around 20-30 seconds or it would had been better if you were given an option to choose a custom time. I would have selected about a minute.

Did You Know? - Interesting Video

Friday, March 06, 2009

Here's a very interesting video, which demonstrates the paradigm shift in technology and globalization over the past few years. It was presented by Richard Sanders, President of Sony BMG International on 4 May 2008 to 150 of the company's top executives gathered in Rome for Sony BMG’s annual Global Management Meeting. It illustrates the demand for changing business processes in these "exponential times".

So, enjoy this amazing video - Right Here, Right Now:




To know more about the producers of the video, click here.

Looking for Drivers?

Friday, February 27, 2009

Those who often change operating systems or frequently add/remove peripherals know how difficult is it to find drivers to get everything working smoothly. Each time you need to find a driver you need to go to each device manufacturers website and search through to find the required driver. Wouldn't it be good if there was a place where you could find all the drivers you need? Here's a website I found which has a huge listing of device drivers for almost all types of hardware.

Apart from these listings, you also get free tool which automatically detects outdated drivers and give you the option to update your drivers. This tool searches through your devices and gets you the latest version of the device driver available from the manufacturer. When unable to find the original driver for the peripherals, most people compromise with compatible drivers which sometimes result in system crashes. By scanning through this tool you don't have to worry with these issues anymore.

So, whether you are trying to update an old system you use for research and need those intel drivers for it or you need hp drivers for your printer and you have lost the product CD that came with it. Just go through the website and get the driver you need without the hassle of doing all those long searches to find the driver you need.

The 25 Worst Programming Errors

Sunday, January 25, 2009

The SANS Institute recently released the list of the top 25 worst programming errors. This list is prepared by experts from more than 30 US and international cyber security organizations, which includes Symantec, Microsoft, DHS's National Cyber Security Division among others. It enumerates the most dangerous programming mistakes that lead to critical security vulnerabilities.

This list is a great read for people involved in software design and development. It not only provides the vulnerabilities caused by these errors, but also provides design and implementation guidelines to prevent these errors. It also provides solutions to rectify these errors. Developers can use these fairly extensive prevention and remediation steps to mitigate or eliminate weakness in their systems.

The composition is organized in three categories - Insecure Interaction Between Components (9 errors), Risky Resource Management (9 errors) and Porous Defenses (7 errors). Insecure Interaction Between Components includes errors like 'Improper Input Validations' giving attackers a gateway to your application; 'Cross-Site Scripting (XSS)' which can allow an attacker to steal information by using user vulnerabilities. Risky Resource Management identifies vulnerabilities caused due to 'External Control of Critical State Data'; 'Untrusted Search Path' for resources; etc. The Porous Defenses enumerates improper use defensive techniques such as 'Improper Access Control', 'Hard-Coded Password' among others.

The online version of the list is available out here. You can also download the pdf version of the document.