Archive for the ‘Language’ Category


Lightweight IPv4


Published in: Development, Language, PHPPosted by Jdub7 on 08/03/09


Introduction

For a midsize project I wanted to store IP ranges in the database with the option to to also store CIDR blocks. CIDR blocks, though powerful are somewhat difficult for a typical user. Additional using them is not as precise for all ip ranges. There are a plethora of tools available on the internet that will do what I would like. However, incorporating these tools would not be practical. What I want is to mimic the functionality of these tools so that it can be easily imported into any of my projects. The most coveted tool for me would be to convert an IP range to a precise range of CIDR blocks. This required specific functionality not naturally provided in PHP.

  • Check for Valid Netmask
  • Check whether an IP address is within a CIDR block.
  • Take user input and a Netmask and make it into a valid CIDR block.
  • CIDR number into Netmask
  • Netmask to CIDR
  • Take an IP range and fit it into an exact range of CIDR blocks.

This presents some difficulty in that PHP’s network functions are not thorough enough. The revelation came when I realized that an IP address is merely a number. In fact the whole protocol is rooted in binary using very specific patterns. With that in mind I thought we could develop very light weight methods to solve our problem.

The Code

It is important to note that the methods provided are meant for IPv4 addresses only are only tested on a 32bit system. Also, I did not care to do much in the way of error checking, but doing so, like testing whether the CIDR number is unsigned and less than or equal to 32, should be trivial.

Though the solution I sought after would require PHP I didn’t limit myself to that language only. In fact the PHP code I found seemed inefficient. Most involved a number conversions or parsing the address using sprintf using loops and nested if statements. Indeed the most efficient code, which shouldn’t surprise most was in ANSI C. Bit Twiddling Hacks resource proved very useful.

About Binary

I am not attempting to teach binary math. Since the code does not “read like prose” a small amount of knowledge is required in order to understand the code. Some excellent resources are Wikipedia’s article on CIDR and PHP binary operators.


Joy Of Groovy


Published in: Development, Groovy, LanguagePosted by yighu on 07/29/09


In my work and my volunteer, I need to do a lot of scripting for all kinds of things such as system administration, data migration etc. I have used shell script, perl and many other tools on and off for a long time before. Scripting with Groovy brings me much joy and fun.

Groovy brings the full Java language and its own flavors to your finger tips while you are typing and thinking your tasks and you can do a lot of things very easily and much simpler than other scripting. Here I will put up a few examples that demonstrate a few tricks that can simplify a lot of daily scripting work:

  1. File Manipulation
  2. Configuration
  3. Database Access
  4. Logging

Suppose you want to create a file and put stuff in it. This is how you do it:

def file=new File(“test.txt”)

do this: file.append(“line 1\n”) file.append(“line 2\n”)

Now the file has 2 lines.

Later some where, you want to do something with the data in the file, for example email the data to some one, this is how you get the content for the file: def content=file.txt()

Suppose you want to write a method, for example log(String text). The log method basically append what ever text into a log file.

binding['writer']=new File(“log.txt”)

def log(String text){ writer.append(text+”\n”) }

Now suppose, instead of putting the log into a log file, I want to put the log into a database table for easy to search or may be for data warehousing purpose, you can easily change the above log method without touching the rest of your code.

def log(String text){ sql.execute(“insert into usertrace(id,description) value(?,?)”,[nextid(),text]) }

where nextid() is simply a method that return you the next id of table usertrace.

Now what is sql here? Before I talk sql, I need to touch the groovy configuration a bit.

The ConfigSlurper is a cool thing.

You might have been used to manipulate the java Property class which you need to load the property file and then use getter method to fetch the string property you want. The groovy way is much simpler.

In this code, MyConfig.groovy is a groovy class which contains name/value pairs, one of them is called sql like this:

sql=groovy.sql.Sql.newInstance(“jdbc:postgresql://localhost:5432/helloworld”,”username”,”password”,”org.postgresql.Driver”)

This is how you get the property sql.

binding['cfg']=new ConfigSlurper().parse(new File(‘MyConfig.groovy’).toURL()) binding['sql']=cfg.sql

Notice that the new variable sql is an object, not just a String as in Java Property file. Then you can execute the method of the object sql, like we did in the above log method.

Have fun so far! As you explore Groovy, you will discover them more.


Custom Error Constructors in JavaScript


Published in: JavaScript, UncategorizedPosted by Elijah Grey on


[Note to person reviewing this: You should make a JavaScript post category.]

Most of the time, the standard six native error constructors and the one generic error constructor are not specific enough for an error. What if you want your library to throw a custom SecurityError if it detects an XSS vector on a website? I made a function to create such constructors that behave the exact same way the native error constructors, like SyntaxError by using methods like Error.prototype.toString and the standard error object format. This code makes throwing a custom fake error constructor made with ErrorConstructor("SyntaxError") have the same output as a native SyntaxError in a JavaScript shell. I’ve tested the code in Firefox 3/3.5 and Opera 9.6 and it seems to work fine. Comment and say if it works in your browser too.

function ErrorConstructor(constructorName) {
  var errorConstructor = function(message, fileName, lineNumber) {
  // don't directly name this function, .name is used by Error.prototype.toString
    if (this == window) return new arguments.callee(message, fileName, lineNumber);
    this.name = errorConstructor.name;
    this.message = message||"";
    this.fileName = fileName||location.href;
    if (!isNaN(+lineNumber)) this.lineNumber = +lineNumber;
    else this.lineNumber = 1;
  }
  errorConstructor.name = constructorName||Error.prototype.name;
  errorConstructor.prototype.toString = Error.prototype.toString;

  return errorConstructor;
}

Usage: ErrorConstructor([constructorName])

Note: If no constructorName is specified, the default of Error.prototype.name is used

Usage for generated error constructor: errorConstructor([message[, location[, lineNumber]])

Examples:

var SecurityError = ErrorConstructor("Security Error"),
MarkupError = ErrorConstructor("(X)HTML Markup Error");
//these will both throw a SecurityError starting with "Security Error on line 83:"
var xss_error = "Possible XSS Vector\n\
 JSON XHR response parsed with eval()\n\
 Recommended fix: Parse JSON with JSON.parse";
throw new SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
throw SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
//these will both throw the following MarkupError:
//"(X)HTML Markup Error on line 1: Invalid DOCTYPE"
throw new MarkupError("Invalid DOCTYPE");
throw MarkupError("Invalid DOCTYPE");

CSS Rounded Corner Roundup


Published in: CSSPosted by Jon Henshaw on 07/27/08


The past several years have introduced many different solutions for creating rounded corners using CSS. Some of the solutions use images, while others don’t – while others require assistance from JavaScript. The great thing about Snipplr is that we capture all of these rounded corner techniques on one page. Below is a highlight of some of the best rounded corner techniques.

100% CSS ROUNDED CORNERS !! No IE sorry!

As is common with techniques that use Web standards, when implemented, they don’t work with Internet Explorer (IE). This is one simple technique that uses very simple CSS that adjusts the border radius, but alas, croaks in IE.

Rounded Corners Without Images Or JavaScript

We move onto the next solution that theoretically does work in IE and also doesn’t require images or JavaScript (JS). Unfortunately, it does utilize a lot of CSS code.

Rounded Corners With Images

Failing to be impressed with a lack of images, one can opt for images with this technique. The CSS gets a little shorter and slightly more elegant — now we’re getting somewhere reasonable.

Anti-Aliased Curvy Corners

But if you like to live on the edge and you crave more code that you can shake a stick at, then Curvy Corners is for you. It’s all JS, all the time. It will create on-the-fly rounded corners for any HTML DIV element, that (supposedly) looks as good as any graphically created corners.

If none of the above solutions peak your interest, then feel free to peruse the full list of rounded corner solutions.


Snipplr Ruby Gem, Bringing Snipplr Into the Command Line


Published in: Bash, RubyPosted by narkisr on 07/16/08


Command Line Interface (CLI) has long been my favorite interface when handling code, it makes it easy to edit, search and traverse your code base with tools like vim, find and grep.

Common CLI usage includes the copy and pasting of code snippets. However, keeping track of all those snippets isn’t easy , Snipplr makes the storage and retrieval of snippets easy as pie but requires a Web browser. The Snipplr Ruby Gem is intended to bridge the gap with a simple unified interface. Let’s take for example a scenario on which we would want to get a specific snippet that contains Spring in its title and add it to a file:

Read the rest of this entry »