Weird Code

Main Page | Recent changes | Random | Special
Edit this page | Page history | Discuss this page
 


Page type: Uncategorised

Contents

[edit] Keeping error messages with their tests

This one isn't weird as such but can make for some pretty hard read to code. Rather than using the following type of checking structure...

	if (discombobulate(fadgit))
	{
		// fadgit succesfully discombobulated
		if (myCat.isHungry())
		{
			myCat.feed();
		}
		else
		{
			DialogResult msgResult = MessageBox.Show("Cat isn't hungry, feed anyway?", "Fat Cat?", MessageBoxButtons.YesNo);
			if (msgResult == DialogResult.Yes)
			{
				myCat.feed();
			}
		}
	}
	else
	{
		MessageBox.Show("PANIC STATIONS!!! Fadgit Discombobulation Failed!");
		System.Windows.Forms.Application.Exit();
	}

If you consider the amount of indentation as a measure of how hard the code is to read then if you take the above example to a greater extremes, with more checks then it can get ridiculous and the larger the code becomes the further the error messages are from the thing that caused them. So I prefer this...

	bool feedCat = false; //mean default value :P

	if (discombobulate(fadgit))
	{
		MessageBox.Show("PANIC STATIONS!!! Fadgit Discombobulation Failed!");
		System.Windows.Forms.Application.Exit();
	}

	if (myCat.isHungry())
	{
		feedCat = true;
	}
	else
	{
		DialogResult msgResult = MessageBox.Show("Cat isn't hungry, feed anyway?", "Fat Cat?", MessageBoxButtons.YesNo);
		feedCat = (msgResult.Equals(DialogResult.Yes));
	}

	if (feedCat)
	{
		myCat.feed();
	}

This has the added advantage that if you decided to add a parameter to the feed() function then you need only change it once here. I take no responsibility for you overfeeding your cat.

[edit] Ball Games, Catch and Throw

C#

	try
	{
		using (MemoryStream ms = new MemoryStream())
		{
			imageToConvert.Save(ms, formatOfImage);
			Ret = ms.ToArray();
		}
	}
	catch (Exception) { throw; }

Here's a fun little game for all the family, a nice game of catch. Remember afterwards to keep the fun going by quickly throwing again.


[edit] If true, yay true!

C#

	if(digit.Trim() == "1")
	{
		return true;
	}
	else
	{
		return false;
	}

Right...

[edit] Meanwhile

C# (Variable names and context has been changed to protect the innocent)

	bool next = true;
	for (int i = 2; next; i++)
	{	
		//--This code is played by psuedocode--
		strLength = spreadsheet.row(i).cell(0)
		//-------------------------------------

		if(strLength.Trim() == "" || strLength == null)
		{
			next = false;
		}
		else
		{
			decimal length = decimalValue(strLength);
			if(curLength >= length)
			{
				purchLength = curLength;
				//--more psuedocode--
				spreadsheet.close()
				//-------------------
				return decimalValue(spreadsheet.row(i).cell(width));
			}
		}
	}

This bizarre loop demonstrates an understanding of how for loops work, but doesn't really seem appropriate.

	i = 2
	do
	{
		strLength = spreadsheet.row(i).cell(0)
		if(curLength >= decimalValue(strLength))
		{
			purchLength = curLength;
			spreadsheet.close()
			return decimalValue(spreadsheet.row(i++).cell(width));
		}
	} while (strLength.Trim() == "" || strLength == null)

Now isn't that better?

I don't think so - as I read it (I'm not a C# programmer, so correct me if I'm wrong) the return value will be wrong in the second version because "i" will have been incremented by the "++i" further up. "i-1" would be required in this reference. It would be better to move the "++i" out of the assignment of strLength, and stick it as a stand alone operation after the if statement to make the data flow easier to follow. Dyn

Yeah, you're right I think it's right now.

[edit] Sometimes you just have to

from xml.dom import minidom

# meow
def getCat(trackTitle, allInfo):
    # for each track info row
    for tInfo in allInfo:
        infos = tInfo.split("\t")
        track = infos[3] # fourth column
        if trackTitle == track:
            return infos[8].split(" ")[0].split("/")[2][:3]+"0s"
    return "goof"

###########################################################
# Main

allTrackInfo = file("tracks.txt").readlines()

doc = minidom.parse("file.xml").documentElement
for el in doc.getElementsByTagName("title"):
    songElement = el.parentNode
    trackTitle = el.firstChild.nodeValue
    categoryElement = songElement.getElementsByTagName("category")[0]
    categoryElement.firstChild.nodeValue = getCat(trackTitle, allTrackInfo)

f=file("outfile.xml","w")
f.write(doc.toxml())
f.close()

[edit] Nice Security

Found at http://www.m4040.com/SecurityAccess.htm I especially like the threat of the IP being logged.

If you feel like cracking this algorithm it's worth knowing that Javascript is not good with big numbers and the value 2214815803840443000 is slightly different from what you would get in other languages that are good with big numbers.

<script>
//Encrypted Password script- By Rob Heslop
//Script featured on Dynamic Drive 
//Visit http://www.dynamicdrive.com 

function submitentry(){
password = document.password1.password2.value.toLowerCase()
username = document.password1.username2.value.toLowerCase()
passcode = 1
usercode = 1
for(i = 0; i < password.length; i++) {
passcode *= password.charCodeAt(i);
}
for(x = 0; x < username.length; x++) {
usercode *= username.charCodeAt(x);
}
//CHANGE THE NUMBERS BELOW TO REFLECT YOUR USERNAME/PASSWORD
if(usercode==2214815803840443000&&passcode==2214815803840443000)
//CHANGE THE NUMBERS ABOVE TO REFLECT YOUR USERNAME/PASSWORD
{
window.location=password+".htm"}
else{
alert("You are not authorized by M40. Your IP address has been recorded.")}
}
</script>