Algorithms in Computational Geometry – Part 2
Posted by Sai Panyam in Technology on April 8, 2010
In Part 1 we discussed the base technique for determining relative orientation. We used that to answer the first two questions: To find relative orientation of two points and two directed segments with a common end point. In Part 2 we answer the next two questions:
- Given two line segments p0p1 and p1p2, if we traverse from p0 to p2, did we make a left, right or no turn at p1?
- Do line segments p1p2 and p3p4 intersect?
We build on what we learned in Part 1, the cross product.
Download the demo application here
Determining whether consecutive segments turn left or right
Given two line segments p0p1 and p1p2 we simply check whether the directed segment p0p2 is clockwise or counterclockwise relative to directed segment p0p1. This is similar to the solution to question 2 in Part 1. If the cross product is negative, then p0p2 is counterclockwise to p0p1. Hence we should turn left when we reach p1 to reach p2 while traversing p0, p1 and p2. If the cross product is 0 (boundary condition) then it means all the three points are collinear (on the same line). The image below shows the three possible scenarios

Using the cross product to determine how p0p1 and p1p2 turn at p1
Determining whether two line segments intersect
Two line segments intersect if and only if either or both of the following conditions are true:
- Each line segment straddles the other line segment.
- An end point of one line segment is on the other line segment
A line segment p1p2 straddles another line if p1 and p2 are on opposite sides of the line. A boundary condition occurs when one of the end points is on the other line.
Algorithm
Calculate the orientation (using cross product!) di for each point of one segment w.r.t the end points of the other segment. For line segments p1p2 and p3p4 we will get d1, d2, d3 and d4.
if none of the di are collinear (i.e. di !=0) we check if d1 and d2 and d3 and d4 have opposite orientations (if one is clockwise,other should be counterclockwise). If this condition is true then we know that the line segments straddle each other and hence intersect. If it is false we can straight away say they don’t intersect.
If any di is collinear (boundary condition) and the corresponding pi is on the other line segment, the lines intersect.

Shows the different cases that we encounter visually
bool Intersects(p1, p2, p3, p4)
{
d1 = CrossProduct (p1p3, p1p2)
d2 = CrossProduct (p1p4, p1p2)
d3 = CrossProduct (p3p1, p3p4)
d4 = CrossProduct (p3p2, p3p4)
if( ((d1 > 0 and d2<0) or (d2 > 0 and d1<0)) and ((d3 > 0 and d4<0) or (d4 > 0 and d3<0)))
{
then return true
}
else if (d1 = 0 and PointOnLine (p3, p4, p1))
{
then return true
}
else if (d2 = 0 and PointOnLine (p3, p4, p2))
{
then return true
}
else if (d3 = 0 and PointOnLine (p1, p2, p3))
{
then return true
}
else if (d4 = 0 and PointOnLine (p1, p2, p4))
{
then return true
}
else
{
return false
}
}
bool PointOnLine (pi, pj, pk)
{
if ( Min (xi, xj)<= xk <= Max (xi, xj) and Min (yi, yj)<= yk <= Max (yi, yj) )
{
return true
}
else
{
return false
}
}
Algorithms in Computational Geometry – Part 1
Posted by Sai Panyam in Technology on April 8, 2010
Computational Geometry (CG) deals with algorithms for solving geometric problems. It is used in computer graphics, robotics, computer aided design,statistics among others. A typical CG problem takes as input a set of geometric objects like a set of points, a set of line segments etc. The output is most commonly finding certain attributes of the geometric objects. For e.g. we are interested in answering the following questions in two dimensions (in a plane):
- Given two points p1 & p2 in a co-ordinate plane, is the directed segment p0p1 clockwise, counterclockwise or collinear to directed segment p0p2? Where p0 is the origin of the co-ordinate plane
- Given two directed segments p0p1 and p0p2, is p0p1 clockwise, counterclockwise or collinear to p0p2 with respect to the common end point p0?
- Given two line segments p0p1 and p1p2, if we traverse from p0 to p2, did we make a left, right or no turn at p1?
- Do line segments p1p2 and p3p4 intersect?
Download the demo application here
Before we proceed any further a few definitions. Clockwise and Counterclockwise are intuitively easy to understand. They have the usual colloquial meaning. There is one thing to note though. A co-ordinate plane is not a watch face! Here we are determining the relative orientations of one segment w.r.t the other. Instead of trying to explain it in words, I will show you a picture (should replace a thousand words!).

The darkly shaded orientation region contains vectors counterclockwise relative to p. The lightly shaded region contains vectors clockwise to p
Two vectors are collinear if they are pointing in the same or opposite direction. In the picture all vectors that lie along the diagonal will be collinear to p.
With definitions out of the way, let us proceed to answer the initial queries that we posed. A brute force method of computing whether two line segments intersect, would be to find the line equations of the form y=mx + c where m is the slope and c the y-intercept and then compute the point of intersection, and verify whether this point lies on both lines. This involves a lot of expensive computational resources. Further this involves division which is sensitive to round-off errors depending upon the precision of the division operation. For e.g. almost parallel line segments will give incorrect results.
The algorithms given here will only use additions, multiplications, subtractions and comparisons ! No trigonometry also !
We do this by computing the cross product. This is a fundamental technique that is at the base of most CG algorithms. Let me say that again. Cross Product is a most fundamental and important technique for solving CG problems. A cross product p1 X p2 is defined as the determinant of the matrix comprising of x and y values of the points.

Determinant of the above matrix will be equal to (x1y2-x2y1)
If the cross product is positive then p1 is clockwise to p2. A boundary condition occurs if the cross product is 0. In that case p1 and p2 are collinear.
Proof: We use trigonometric function tan on the angle formed by the point (x,y), origin (0,0) and (x,0) for both the points. If the ratio of one tangent to other determines orientation depending upon whether the value is greater than 1 or not.
//Clockwise: x1y2-x2y1>0 //So x1y2>x2y1 //alternatively (x1y2)/(x2y1)>1 //rearranging the terms (y2/x2)/(y1/x1)>1 //Notice that tan θ is the ratio of opposite side by adjacent side //in a right angled triangle //so the numerator of the above fraction is tan θ2 and //denominator tan θ1 (tan θ2)/(tan θ1)>1 If the angle θ2 is greater than θ1 then we have proved that p1 is clockwise to p2
The above technique of using cross product makes for an easy and efficient way to answer Question 1.
To answer Question 2 just involves an extra pre-processing step before doing the cross product. To determine whether two directed segments p0p1 and p0p2, is p0p1 clockwise, counterclockwise or collinear to p0p2 with respect to the common end point p0 we just translate the axis to use p0 as the origin and use the cross product as above.
// To translate the origin to the common end point p0 //We let p1' (p prime) be the point where x1' =x1 - x0 and y1' =y1 - y0 //We do the above for p2 and calculate its prime: p2' x2' =x2 - x0 and y2' =y2 - y0 //Then we calculate the cross product of p1' x p2' If it is positive then the directed segment p0p1 is clockwise to directed segment p0p2
In Part 2 we will answer questions 3 & 4 using the techniques and principles learned here.
A simple way to encrypt query strings
Posted by Sai Panyam in Technology on March 26, 2010
Query strings are used to carry information. We might need to obfuscate them and provide some basic security without writing some elaborate encryption mechanism. Some standard ways of obfuscating, you will find is to Base64Encode the query string(remember to Url encode the resulting string as it is going to be on a url!):
string data="query string";
string encodedData = String.Empty;
try
{
byte[] data_byte = Encoding.UTF8.GetBytes(data);
encodedData = HttpUtility.UrlEncode(Convert.ToBase64String(data_byte));
}
catch (Exception exception)
{
//Log exception
}
return encodedData;
While this works, it provides only obfuscation, but no security. Anyone can do the reverse:
string data="encoded data";
string decodedData = String.Empty;
try
{
byte[] data_byte = Convert.FromBase64String(HttpUtiltity.UrlDecode(data));
decodedData = Encoding.UTF8.GetString(data_byte);
}
catch (Exception exception)
{
//Log exception
}
return decodedData;
A little more advanced method is to use PasswordDeriveBytes class in .NET to do proper encryption. This has since been replaced with Rfc2898DeriveBytes in .NET 2.0. The reason you would want to use Rfc2898DeriveBytes is because it meets the PKCS #5 standard, which PasswordDerrivedBytes, does not. Both of them are present in System.Security.Cryptography namespace.
What we need to do is:
- Generate the encryption key and IV(Initialization Vector) from the password and salt.
- Create a new instance of the encryptor with the key and IV.
- Encrypt the query string.
We are not done yet. Improper use of Rfc2898DeriveBytes will result in a performance impact on large sets of data. The cause is the call to GetBytes(int32) method on Rfc2898DeriveBytes class. It uses a pseudo-random number generator based on HMACSHA1. GetBytes initializes a new instance of HMAC is the killer in terms of performance. But the redeeming factor is, subsequent calls to GetBytes does not need to do this initialization.
So we change our implementation to do this expensive call once. Since there is no need to create a new instance of Rfc2898DeriveBytes for each call to encrypt, we will use the same key but change the IV for each message. So remove Rfc2898DeriveBytes from the Encrypt method and pass along the key and IV instead of the password and salt.
Putting all this together here is the final code (fast and efficient):
public static class MyHelper
{
#region Private variables and Constants
private const string ENCRYPTION_KEY = "Wx0Te1rc0pA";
// Generated from Pass Phrase "xxxxxxxx12012010" or some pass phrase that you can remember from
// https://www.bigbiz.com/genkey.html Key Generator Site
private const string QUERY_PARTS_DELIMITOR = "&";
private const string QUERY_PARAMS_DELIMITOR = "=";
///
/// The salt value used to strengthen the encryption.
///
private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY);
private readonly static byte[] key;
private readonly static byte[] iv;
private static readonly Rfc2898DeriveBytes keyGenerator;
#endregion
#region Constructor
static MyHelper()
{
//We create the Rfc2898DerveBytes once as
//Rfc2898DeriveBytes uses a pseudo-random number generator based on HMACSHA1.
//When calling GetBytes it initializes a new instance of HMAC which takes some time.
//Subsequent calls to GetBytes does not need to do this initialization.
keyGenerator =new Rfc2898DeriveBytes(ENCRYPTION_KEY,SALT);
key = keyGenerator.GetBytes(32);
//Generate Initialization Vector - This will be less expensive as we have already intialized Rfc2898DeriveBytes
iv = keyGenerator.GetBytes(16);
}
#endregion
#region Encrypt/Decrypt Methods
///
/// Encrypts any string using the Rijndael algorithm.
///
///
The string to encrypt.
///
The name of the query string paramater
/// A Base64 encrypted string.
public static string Encrypt(string inputText, string queryStringParam)
{
//Create a new RijndaelManaged cipher for the symmetric algorithm from the key and iv
RijndaelManaged rijndaelCipher = new RijndaelManaged {Key = key, IV = iv};
byte[] plainText = Encoding.Unicode.GetBytes(inputText);
using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor())
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
return "?" + queryStringParam + "=" + Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
///
/// Decrypts a previously encrypted string.
///
///
The encrypted string to decrypt.
/// A decrypted string.
public static string Decrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] encryptedData = Convert.FromBase64String(inputText);
using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(key, iv))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}
#endregion
}
The only draw back is this doesn’t give you full security. This method will provide basic security in terms of stopping the hacker from deterministically manipulating the encrypted string. So it is a more a deterrence than a verification strategy. We can tell if someone tampers with the encrypted string only if the decryption ‘fails’ to decrypt to something you recognize or expect.
“God Mode” in Windows 7
Posted by Sai Panyam in Technology on January 6, 2010
If you haven’t heard about “GodMode” in Windows 7, then read on. Windows 7 has a “GodMode” feature, which isn’t as grandiose as it sounds. Actually GodMode is not even the name that Microsoft has given it. In fact Microsoft doesn’t have an official name for it, as the feature itself is undocumented. GodMode is the name given by bloggers who found it accidentally. I cannot imagine how they could have found it aside from getting some inside information from Microsoft developers themselves. I will attempt to give it a definition.
GodMode: A feature that transforms a folder to a shortcut pointing to some windows tasks, just by appending a folder name with a period (‘.’), followed by a special string (‘{GUID}’).
It includes direct access to all kinds of settings, from choosing a location to managing power settings to identifying biometric sensors, to name a few.
To keep them all grouped together and ‘know’ what they do with a glance, I followed this pattern-
[folder name].{GUID}
In my case, I chose ‘GodMode’ as the folder name. Once the shortcut is made, I change the name to the following format before moving on to the next God Mode- [folder name].[feature name] For e.g. with the Control Panel God Mode, I would call it something like ‘GodMode.ControlPanel’.
This is how it looks on my computer:
God Mode Folders
Here is a list of God Modes that I have found so far with a short description:
Control Panel : {ED7BA470-8E54-465E-825C-99712043E01C}
Description: A shortcut to all Control Panel functions
Location Info : {00C6D95F-329C-409a-81D7-C46C66EA7F33}
Description: A shortcut to set up default location for programs to use when a location sensor, such as GPS receiver, is unavailable. On can also enter Geographic location (latitude and longitude) too.
Biometric Info : {0142e4d0-fb7a-11dc-ba4a-000ffe7ab428}
Description: A shortcut showing the information of any biometric device like fingerprint reader etc, if installed.
Power Plan : {025A5937-A6BE-4686-A844-36FE4BEC8B6D}
Description: A shortcut to select the power consumption settings for your computer.
System Tray : {05d7b0f4-2121-4eff-bf6b-ed3f69b894d9}
Description: A shortcut which opens the icon and notifications settings, where you can set whether you want to show/hide icons in system tray and whether to show only notifications etc.
Windows Vault : {1206F5F1-0569-412C-8FEC-3204630DFB70}
Description: A shortcut which points to Windows Vault. We can store credentials for automatic logon here.
Program Install: {15eae92e-f17a-4431-9f28-805e482dafd4}
Description: A shortcut to install a program from the network.
Default Programs: {17cd9488-1228-4b2f-88ce-4298e93e0966}
Description: A shortcut to choose programs that Windows uses by default.
Manage Wireless: {1FA9085F-25A2-489B-85D4-86326EEDCD87}
Description: A shortcut to manage wireless networks.
Manage Network: {208D2C60-3AEA-1069-A2D7-08002B30309D}
Description: A shortcut to network computers, websites, FTP sites etc.
Remarks: This God Mode doesn’t allow us to rename the folder to anything else. It keeps changing back to ‘Network (MS)’
Manage Network: {1D2680C9-0E2A-469d-B787-065558BC7D43}
Description: A shortcut to GAC (Global Assembly Cache).
Remarks: This God Mode doesn’t change its folder icon or hide its GUID string like others. But it correctly points to the GAC on the computer.
Computer Drives: {20D04FE0-3AEA-1069-A2D8-08002B30309D}
Description: A shortcut which shows the current drives on the computer.
Printers: {2227A280-3AEA-1069-A2DE-08002B30309D}
Description: A shortcut to the printers added to the computer.
Remote Connections: {241D7C96-F8BF-4F85-B01F-E2B043341A4B}
Description: A shortcut to manage your RemoteApp and Desktop Connections.
Windows Firewall: {4026492F-2F69-46B8-B9BF-5654FC07E423}
Description: A shortcut to setup Windows Firewall settings to prevent malicious hackers from getting access to your computer.
Computer Performance: {78F3955E-3B90-4184-BD14-5397C15F1EFC}
Description: A shortcut to get your computer’s speed and performance information.
Dr Richard Feynman-The Messenger Lectures
Posted by Sai Panyam in Science on July 16, 2009
I became aware of the great physicist Dr Richard Feynman in 1988-1989 through his 1985 memoirs, ”Surely You’re Joking, Mr. Feynman” . I was immediately taken by his wit, humor and his easy way of explaining concepts. I knew about his work on the Presidential commission investigating the explosion of the space shuttle Challenger. His famous experiment of throwing an O-ring seal in ice water to demonstrate why the shuttle blew up caught the attention of the world. Dr Richard P. Feynman is arguably the most brilliant, iconoclastic and influential of the postwar generation of theoretical physicists.
I sort of forgot about him for many years. Then out of the blue I see this today. Bill Gates has bought and released to the world a series of video lectures given by Feynman at Cornell University. Called Project Tuva, it shows Feynam at his best: caustic, humorous and at the same time very insightful.
It was a delight to finally put a face to the man, who made quite a impression on the young me through his book. I am grateful to Bill Gates for bringing to the masses this gem.
Here is the link to the video series.
http://research.microsoft.com/apps/tools/tuva/index.html
[You will need Silverlight installed to view this lectures]
Star Trek – The Geriatric Years
Posted by Sai Panyam in Entertainment on June 25, 2009
In the year that Start Trek the early years has been released (2009), it is fitting that we need to look at how they would be now. Here is a funny video on the geriatric years.
This would really be worth it, for die hard Star Trek fans like me. In a future post I would like to explore why Star Trek was such an iconic and successful series
Why WordPress instead of DNN?
Posted by Sai Panyam in Frameworks on May 29, 2009
The irony of a site which evangelizes .NET using WordPress is not lost on me. I was on DNN (DotNetNuke) till recently. Also I wasn’t just a simple user. I wrote and hosted a few modules for DNN myself. People who visited my site in my previous avatar, would know that I also open sourced my modules (Random quotes, Review, Simple Download etc).
Then why did I move to WordPress? After following DNN till version 3.1, I couldn’t keep up with the changes and modifications that were required for upgrading my DNN installation. I was spending more time in upgrading and troubleshooting than on my main mission of evangelizing .NET. Also the cost of hosting DNN was high. I had to pay for SQL Server usage on top of hosting. I wouldn’t mind paying for SQL Server hosting if it brought me more value than just running DNN. But it didn’t.
Also the time it took to setup and run DNN was immense in comparison to WordPress. I could get my new revamped site up and running in exactly 15-30 mins!!!!! Yes minutes not hours….
Most of my time was spent selecting the theme than anything else. I also realized that most of my previous DNN modules were available and in better shape in WordPress plug ins. Another plus was the ease of setup, upgrade and site management. Hosting was also really cheap… No SQL Server etc.
Here is a breakdown of my tasks and the amount of time taken vis-a-vis DNN
| Task | DNN | WordPress |
| Learning Framework | 5 Days | 2 Hours |
| Setup | 2 Days | 30 Minutes |
| Modules/Plugins Installation | 1 Day | 30 Minutes |
| Data for Modules/Plugins | 2 Days | 3 Hours |
| Troubleshooting | 3 Days | None |
| Upgrade for Modules/Plugins and framework | 5 Days | Automatic/Almost Instantaneous |
| Adding new features | 1-2 Weeks | 30-60 Minutes |
| Ongoing Maintenance | 1 Day | 30 Minutes |
As you can see from the table above. I saved a lot of sweat, toil and tears. Maybe there are other web frameworks in .NET which are just as easy as WordPress, but I am ignorant of them.
All in all this post is not about bashing DNN. It is about why WordPress is such a superior CMS. Though people use it for setting up their blogs, in my experience its CMS functionality is even better and underutilized.
I am seriously considering becoming a PHP developer just to be in sync with WordPress. Though it isn’t necessary, I could follow along the PHP code just fine. A combination of Google and my own knowledge of coding constructs helped me customise my site and relaunch it. You will see more blogging from me, since I have more time now….
