Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Sponsored Ads
Recent Readers
Sponsored Ads
Referral Ads
HostGator
Site5
Lunarpages.com Web Hosting
LiquidWeb

Property getters & setters

In traditional OOP, if we wanted to get or set an object's private member, we would need to write a public method to do the job.
The reason behind making a member data private and then accessing it through a public method is to avoid the implementing-user to access it directly.
There can be many reasons for prohibiting direct access to member data to the implementing-code.
For example, you may want a radius of a Circle to be within the range of 10 - 500.

C++: Traditional OOP
class Circle
{
private:
int radius;

public:
Circle(int radius = 15)
{
setRadius(radius);
}

void setRadius(int radius)
{
if (radius < 10 || radius > 500)
{
this->radius = -1;
cout << "Radius must be within the range of 10 - 500" << endl;
}
else
this->radius = radius;
}

int getRadius()
{
return this->radius;
}
}

void main()
{
Circle c = Circle();
c.setRadius(25);
cout << c.getRadius();
}
C++

In languages like PHP & Python which has a weak type system, a further check of the data type may be necessary.
But for Python unfortunately even traditional getter & setter methods cannot be implemted because Python doesn't have a public or private. Everything is public by default - though a member can be made private by prefixing two underscores to it. But this is only for convention, it doesn't really serve its true purpose.

PHP 5 and C# .NET have a getter and setter method feature, making it look like we're accessing the data member directly.

PHP
<?php
class Circle
{
private $radius; # integer

# Constructor
public function __construct($radius = 15)
{
self::__set('radius', $radius);
}

# Setter
public function __set($name, $value)
{
switch ($name)
{
case 'radius':

if (!is_numeric($value)) # is_int() for strict type checking
throw new Exception('Radius must be of a numeric type');

if ($value < 10 || $value > 500)
throw new Exception('Radius must be within the range of 10 - 500');

$this->radius = $value;

break;

default:
throw new Exception("Attempt to set a non-existing property: $name");
break;
}
}

# Getter
public function __get($name)
{
if (in_array($name, array('radius')))
return $this->$name;

switch ($name)
{
default:
throw new Exception("Attempt to get a non-existing property: $name");
break;
}
}

}

$c = new Circle();
$c->radius = 25;
echo $c->radius;
>
PHP 5.x
C#
using System;

public class Circle
{
private int __radius = 5;

public Circle()
{
}

public Circle(int radius)
{
this.radius = radius; // This will call the property defined below
}

public int radius // Property getter/setter name cannot be the same as the member variable name
{
get
{
return __radius;
}

set
{
if (value < 10 || value > 500)
throw new Exception("Radius must be within the range of 10 - 500");

__radius = value;
}
}
}

public class main
{
public static void Main(string[] args)
{
Circle c = new Circle(); // Circle c = new Circle(5); will throw an Exception
c.radius = 25;
Console.WriteLine(c.radius);
}
}
.NET 2.0

C# .NET 3.0 has introduced Automatic Properties where you don't need to specify code for the getter & setter - the compiler takes generates the method body.

JavaScript does seem to have a getter and setter method which I came across just now when searching for the official source to Java 7's new features' documentation, but :

  • only within an object initializer - not inside a function so it doesn't seem to be of much use as we can't create instances
  • doesn't hide the member from being accessed directly
  • doesn't work in IE.

JavaScript
var someObj =
{
a : 7,
get b()
{
return this.a * 3;
},
set c(x)
{
this.a = x / 2;
}
}

someObj.foo1 = function()
{
//
}

alert(someObj.a);
someObj.c = 5;
alert(someObj.b);
someObj.foo1();
JavaScript 1.5

The Getter & Setter feature does not seem to be a much "wanted" feature in the Java community.
Still, this has been proposed by Rémi Forax for JDK 7.

Java: Proposal
public class Circle
{
private int __radius = 5;

public Circle()
{
}

public Circle(int radius)
{
this.radius = radius; // This will call the property defined below
}

public property int radius // Property getter/setter name cannot be the same as the member variable name
{
get
{
return __radius;
}

set (int radius)
{
if (radius < 10 || radius > 500)
throw new Exception("Radius must be within the range of 10 - 500");

__radius = radius;
// firePropertyChange(radius);
}
}

public static void main(String[] args)
{
Circle c = new Circle(2); // Circle c = new Circle(5); will throw an Exception
c.radius = 25;
System.out.println(c.radius);
}
}
JDK 7
Vanakkam !

Python's Classmethods

Lets say I have an abstract class called Vehicle and 3 classes that descend from it are Bike, Car & Truck.
I use a static variable in Vehicle called total to keep track of the total number of Vehicles. But I really don't want to keep track of the total number general Vehicles. What I really want is to keep track of the total number of Bikes, Cars & Trucks individually. This is easy - just declare total in Bike, Car & Truck classes.

Now arises a situation where we need a function println in Vehicle that accesses total. We'll also include a function called set in Vehicle to explicitly set the value of total (instead of creating 10 instances to prove a point).

There are two scenarios to this, both of which are not possible :

  1. Declare a static variable total in Vehicle but different values persist in Bike::total, Car::total & Truck::total. This is impossible because total is Vehicle's static variable which is common to all. The following will output 2 2 2.
    PHP
    <?php
    abstract class Vehicle
    {
    protected static $total;

    public static function println()
    {
    echo self::$total."\n";
    }

    public static function set($value)
    {
    self::$total = $value;
    }
    }

    class Bike extends Vehicle
    {
    }

    class Car extends Vehicle
    {
    }

    class Truck extends Vehicle
    {
    }

    Bike::set(3);
    Car::set(5);
    Truck::set(2);

    $b = new Bike();
    $c = new Car();
    $t = new Truck();

    Bike::println()
    Car::println()
    Truck::println()

    // Is there any way for Bike's static variable to hold 3 and Car's static to hold 5 & Truck's static to hold 2 ?
    ?>
    PHP 5.2.5
  2. Declare the static variable total in each of Vehicle's subclasses, Bike, Car & Truck. But in this case, Vehicle's println needs to access the descendant class static variable like child::total which is not possible in most(all) languages.
    PHP
    <?php
    abstract class Vehicle
    {
    public static function println()
    {
    echo child::$total."\n";
    }

    public static function set($value)
    {
    child::$total = $value;
    }
    }

    class Bike extends Vehicle
    {
    public static $total; # Should've been protected, but then parent wouldn't able to access
    }

    class Car extends Vehicle
    {
    public static $total;
    }

    class Truck extends Vehicle
    {
    public static $total;
    }

    Bike::set(3);
    Car::set(5);
    Truck::set(2);

    $b = new Bike();
    $c = new Car();
    $t = new Truck();

    Bike::println();
    Car::println();
    Truck::println();
    ?>
    PHP 5.2.5

    It is possible to overcome this problem by setting and getting the value in the subclasses and use $this->childMethod() in the parent class, Vehicle.
    PHP
    <?php
    abstract class Vehicle
    {
    public function set($value)
    {
    $this->setChildValue($value);
    }

    public function println()
    {
    echo $this->getChildValue()."\n";
    }
    }

    class Bike extends Vehicle
    {
    protected static $total;

    public function getChildValue()
    {
    return self::$total;
    }

    public function setChildValue($value)
    {
    self::$total = $value;
    }
    }

    class Car extends Vehicle
    {
    protected static $total;

    public function getChildValue()
    {
    return self::$total;
    }

    public function setChildValue($value)
    {
    self::$total = $value;
    }
    }

    class Truck extends Vehicle
    {
    protected static $total;

    public function getChildValue()
    {
    return self::$total;
    }

    public function setChildValue($value)
    {
    self::$total = $value;
    }
    }

    $b = new Bike(); $b->set(3);
    $c = new Car(); $c->set(5);
    $t = new Truck(); $t->set(2);

    $b->println();
    $c->println();
    $t->println();
    ?>
    PHP 5.2.5

    But the two methods, getChildValue and setChildValue must be defined properly in all subclasses.
    __CLASS__ returns the class in which its called from and get_class($this) returns the class of the current instance.
    Example : echo __CLASS__; in a method in Vehicle will always output Vehicle, but get_class($this) will output the classname of the object (In this case, Bike, Car or Truck).
    If we could do get_class($this)::$total (Bike::$total), then it could've been easily solved.

    PHP
    <?php
    abstract class Vehicle
    {
    public function set($value)
    {
    get_class($this)::$total = $value;
    }

    public function println()
    {
    echo get_class($this)::$total."\n";
    }
    }

    class Bike extends Vehicle
    {
    public static $total;
    }

    class Car extends Vehicle
    {
    public static $total;
    }

    class Truck extends Vehicle
    {
    public static $total;
    }

    $b = new Bike(); $b->set(3);
    $c = new Car(); $c->set(5);
    $t = new Truck(); $t->set(2);

    $b->println();
    $c->println();
    $t->println();
    ?>
    PHP 5.2.5

The last method is possible in Python in two ways - self.__class__.total & classmethod. Python has a way to access class member of the caller's class, not just the class members in which its being accessed. Here each of the subclasses have a static member called total which gets created and assigned in its parent, Vehicle

Python : Using __class__
class Vehicle:

def println(self):
print self.__class__.total

def set(self, value):
self.__class__.total = value

class Bike(Vehicle):
pass

class Car(Vehicle):
pass

class Truck(Vehicle):
pass

Bike().set(3) # Bike.total = 3
Car().set(5) # Car.total = 5
Truck().set(2) # Truck.total = 2

b = Bike()
c = Car()
t = Truck()

b.println()
c.println()
t.println()
Python 2.5.1
Python : Using classmethod
class Vehicle:

@classmethod
def println(cls):
print cls.total

@classmethod
def set(cls, value):
cls.total = value

class Bike(Vehicle):
pass

class Car(Vehicle):
pass

class Truck(Vehicle):
pass

Bike.set(3) # Bike.total = 3
Car.set(5) # Car.total = 5
Truck.set(2) # Truck.total = 2

b = Bike()
c = Car()
t = Truck()

b.println()
c.println()
t.println()

Bike.println()
Car.println()
Truck.println()
Python 2.5.1

self.__class__.total points to the static member total of the object's (this) class and not of the class Vehicle.
cls.total references the same thing as the first argument is actually the classname which is not passed in the parentheses, but by using the classname preceding the dot.

Vanakkam !

Export MySQL data to Excel compatible CSV format

One of the most often used feature in front-end GUI tools like phpMyAdmin is to export your data to an Microsoft Excel compatible CSV format. Excel compatible because, CSV functions in Python, PHP, Java or C# can read CSV files created using Excel. Because there is no CSV standard, we'll use Microsoft Excel's CSV format. Microsoft Excel uses 2 double-quotes to indicate a double-quote within a column-value enclosed by double-quotes.
For example, a Hello"World in Excel is internally "Hello""World" if you open the file in Notepad.

When you're dealing with large sets of data, its better to use MySQL in command-line mode for export. A stand-alone Py/PHP/Java script may do the job but it would still be faster in MySQL command-line mode.

Lets take a simple person-info table type as an example. `persons` is a table in database `community`.

MySQL
CREATE TABLE IF NOT EXISTS `persons` (
`ID` bigint(20) NOT NULL auto_increment,
`Name` varchar(255) NOT NULL,
`Address` varchar(255) NOT NULL,
`City` varchar(255) NOT NULL,
`State` varchar(255) NOT NULL,
`Zip` varchar(255) NOT NULL,
`Phone` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
MySQL 5.0.45
  1. mysqldump

    Dumping SQL via the mysqldump command-line tool is the most common use for database backup. Using mysqldump, it is possible to export to CSV but there are some limitations :

    • Its not possible to select columns, so you end up exporting all columns. And I can't see options for columns in the newer versions, 5.1 or 6.0, so I guess theres no way out here.
    • When exporting to CSV format, we indicate the column data is to be seperated by a comma by specifying options such as --fields-terminated-by=",". When using --fields-xx options, its mandatory to use the --tab=<dir name> option which specifies the folder to dump to. --tab accepts a foldername because it'll export the tables in a separate file text format to that folder. Even if we select only one table to dump, it'll still have to dump to the specified folder. So we can't output to a file by using pipe (mysqldump ... > los-angeles-persons.csv).
      Note: --result-file=<filename> option is used to output to a specified file but not in conjunction with the --tab option.
    • Its not possible to sort the result, expect by the PK (Primary Key) column by specifying the --order-by-primary option.
    mysqldump community persons --user=root --where="`City` LIKE '%Los Angeles%'" --tab="csv data" --fields-terminated-by="," --fields-enclosed-by="\"" --fields-escaped-by="\"\"" --lines-terminated-by="\r\n" --no-create-db --no-create-info -p

    This will export (dump) all persons located in Los Angeles into a folder named csv data (an existing folder relative to your current path).
    --fields-escaped-by="\"\"" : specify 2 double-quotes("") to indicate a double-quote(") - since the column values are enclosed by double-quotes(").
    Internally, this executes a SELECT INTO OUTFILE query.

  2. SELECT ... INTO OUTFILE

    Enter mysql in command-line mode.

    C:\MySQL\bin>mysql --user=root -p
    Enter password:
    Welcome to the MySQL monitor. Commands end with ; or \g.
    Your MySQL connection id is 81
    Server version: 5.0.45-community-nt-log MySQL Community Edition (GPL)

    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

    mysql> USE community;
    Database changed
    mysql> SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone`
    -> FROM `persons`
    -> WHERE `City` LIKE '%Los Angeles%'
    -> ORDER BY `Name` ASC, `Zip` ASC
    -> INTO OUTFILE 'los-angeles-persons.csv' FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
    Query OK, 299 rows affected (0.05 sec)

    mysql>

    This is probably the best option because you're inside the MySQL console.
    This selects only `Name`, `Address`, `City`, `State`, `Zip`, `Phone` columns and again filtered by Los Angeles city.
    The in INTO OUTFILE is relative to the database directory in the MySQL data directory. MySQL data directory is the one assigned to datadir= in the configuration file (my.ini or my.cnf).
    My path is D:\Data\MySQL\community\los-angeles-persons.csv (for default setup : C:\MySQL\data\community\los-angeles-persons.csv)

    Unfortunately, export options (FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n') can only be used with INTO OUTFILE option, so something like this in command-prompt is not possible:

    C:\MySQL\bin>mysql --user=root --database=community --execute="SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone` FROM `persons` WHERE `City` LIKE '%Los Angeles%' ORDER BY `Name` ASC, `Zip` ASC FIELDS ESCAPED BY '\"\"' TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n';" -p > los-angeles-persons.csv
  3. CONCAT()

    Because of limitations of the first two methods, piping output to a file using > is not possible.
    The only other way is to join all the column-values using the CONCAT() function.
    In script.sql enter

    USE `community`;

    DROP FUNCTION IF EXISTS toXLCell;
    delimiter ///
    CREATE FUNCTION toXLCell(s VARCHAR(1000)) RETURNS VARCHAR(1000) DETERMINISTIC
    BEGIN
    SET @XLs = CONCAT('"', REPLACE(s,'"','""'), '",');
    RETURN @XLs;
    END;
    ///
    delimiter ;

    SELECT
    CONCAT(toXLCell(`Name`), toXLCell(`Address`), toXLCell(`City`), toXLCell(`State`), toXLCell(`Zip`), toXLCell(`Phone`)) AS `Row`
    FROM `persons`
    WHERE `City` LIKE '%Los Angeles%'
    ORDER BY `Name` ASC, `Zip` ASC;
    C:\MySQL\bin>mysql --user=root -p < script.sql > los-angeles-persons.csv

    Using CONCAT & REPLACE may be tedious, but helps in batch scripts.

    This will create an extra empty column at the end because of the trailing comma. If default parameter value was supported , the function could've been defined as toXLCell(s VARCHAR(1000), bLast BIT(1) = FALSE) and toXLCell(`Phone`) would be changed to toXLCell(`Phone`, TRUE)

    MySQL doesn't support variable number of parameters, otherwise we could've had a function
    toXLLine(`Name`, `Address`, `City`, `State`, `Zip`, `Phone`)
    accepting variable number of column names.

Vanakkam !

Form submission using AJAX & HTML

One of the biggest concerns using AJAX based form submissions are JavaScript related issues :
  • What if JavaScript is disabled or not available on the client's browser ?
  • What if XMLHttpRequest / Msxml2.XMLHTTP / Microsoft.XMLHTTP aren't available ?
  • What if the creation of XMLHttpRequest object failed for some reason ?
  • What if all the JavaScript scripts didn't load properly and screwed up the damn thing ?
  • What if the user clicked the button much faster than the scripts to completely load ? You must be on a real slow connection for this to happen.
The only solution is to give your users the option to automatically fall back to the normal form submission if AJAX doesn't work. Relying solely on client side scripting should only be done only if the application demands it.
HTML
<form id="Comment-Form" action="http://mydomain.com/PostComment" method="post">
<div id="Comment-Box">
<table>
<tr><th>Leave a Comment</th></tr>
<tr><td id="Comment-Box-Msg" style="display:none"></td></tr>
<tr><td><textarea name="Comment" id="Comment-Reply" rows="10" cols="50"></textarea></td></tr>
<tr><td style="text-align:center">
<input type="submit" value="Post Comment" name="Submit" id="Comment-Button"/>
</td></tr>
</table>
</div>
</form>
HTML 4.01
JavaScript
window.onload = function() { init(); }
function init()
{
/*
This is set only after the entire page is loaded,
so if the button is clicked way before its loaded,
it'll 'normal' submit to the form's action value
*/
document.getElementById("Comment-Button").onclick = PostCommment;
}
function PostCommment()
{
// AJAX error : switch to <form> submit
if (ajax_error) document.getElementById("Comment-Form").submit();

// Do the form submission via AJAX

// To stop the <form> being submitted, since its done via AJAX
return false;
}
Javascript 1.5

This way, it ensures that if there is a problem with JavaScript or AJAX in particular, you can always fall back to the normal form submission.
Vanakkam !

Generating a Random String

PHP
<?php
class RandomText
{
const RAND_NUMBERS = 1;
const RAND_SMALL_LETTERS = 2;
const RAND_CAP_LETTERS = 4;
const RAND_ALL = 7;

/**
* @access public
* @param Type (INT) One of the random constants RAND_*
* @NoOfChars [INT] Optional - No of characters to generate
* @return (string) random string
* @example echo RandomText::Random_String(RandomText::RAND_NUMBERS + RandomText::RAND_CAP_LETTERS, 25);
*/
public static function Random_String($Type = self::RAND_NUMBERS, $NoOfChars = 6)
{
$strList = array();

// Convert to binary format and find out what combination of random characters are required
$binType = base_convert($Type, 10, 2);

// Loop through the bits from Right To Left
for ($i = strlen($binType) - 1; $i >= 0; $i--)
{
if ($binType[$i])
{
switch (pow(2, strlen($binType) - $i - 1))
{
default:

case self::RAND_NUMBERS:
$Ascii_Range = array(48, 57); // Numbers - Characters 0 to 9
break;

case self::RAND_SMALL_LETTERS:
$Ascii_Range = array(97, 122); // Small Letters - Characters a to z
break;

case self::RAND_CAP_LETTERS:
$Ascii_Range = array(65, 90); // Capital Letters - Characters A to Z
break;
}

for ($j = $Ascii_Range[0]; $j <= $Ascii_Range[1]; $j++)
$strList[] = chr($j);
}
}

$RndString = "";
for ($i = 0; $i < $NoOfChars; $i++)
$RndString .= $strList[rand(0, count($strList) - 1)];

return $RndString;
}
}

echo RandomText::Random_String(RandomText::RAND_NUMBERS + RandomText::RAND_CAP_LETTERS, 25);
?>
PHP 5.2.3
C#
using System;
using System.Text;

public class RandomText
{
public const int RAND_NUMBERS = 1;
public const int RAND_SMALL_LETTERS = 2;
public const int RAND_CAP_LETTERS = 4;
public const int RAND_ALL = 7;

public static string Random_String()
{
return Random_String(RAND_NUMBERS, 6);
}

public static string Random_String(int Type)
{
return Random_String(Type, 6);
}

public static string Random_String(int Type, int NoOfChars)
{
StringBuilder strList = new StringBuilder();
int[] Ascii_Range;
int i;

// Convert to binary format and find out what combination of random characters are required
string binType = Convert.ToString(Type, 2);

// Loop through the bits from Right To Left
for (i = binType.Length - 1; i >= 0; i--)
{
if (binType[i] == '1')
{
switch ((int)Math.Pow(2, binType.Length - i - 1))
{
default:

case RAND_NUMBERS:
Ascii_Range = new int[] {48, 57}; // Numbers - Characters 0 to 9
break;

case RAND_SMALL_LETTERS:
Ascii_Range = new int[] {97, 122}; // Small Letters - Characters a to z
break;

case RAND_CAP_LETTERS:
Ascii_Range = new int[] {65, 90}; // Capital Letters - Characters A to Z
break;
}

for (int j = Ascii_Range[0]; j <= Ascii_Range[1]; j++)
strList.Append((char)j);
}
}

StringBuilder RndString = new StringBuilder();
Random rnd = new Random();

for (i = 0; i < NoOfChars; i++)
RndString.Append(strList[rnd.Next(strList.Length - 1)]);

return RndString;
}

public static void Main(string[] args)
{
Console.WriteLine(RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25));
}
}
.NET 2.0
Java
import java.io.*;
import java.util.Random;

public class RandomText
{
public static final int RAND_NUMBERS = 1;
public static final int RAND_SMALL_LETTERS = 2;
public static final int RAND_CAP_LETTERS = 4;
public static final int RAND_ALL = 7;

public static String Random_String()
{
return Random_String(RAND_NUMBERS, 6);
}

public static String Random_String(int Type)
{
return Random_String(Type, 6);
}

public static String Random_String(int Type, int NoOfChars)
{
StringBuilder strList = new StringBuilder();
int[] Ascii_Range;
int i;

// Convert to binary format and find out what combination of random characters are required
String binType = Integer.toString(Type, 2); // Type.toString(2);

// Loop through the bits from Right To Left
for (i = binType.length() - 1; i >= 0; i--)
{
if (binType.charAt(i) == '1')
{
switch ((int)Math.pow(2, binType.length() - i - 1))
{
default:

case RAND_NUMBERS:
Ascii_Range = new int[] {48, 57}; // Numbers - Characters 0 to 9
break;

case RAND_SMALL_LETTERS:
Ascii_Range = new int[] {97, 122}; // Small Letters - Characters a to z
break;

case RAND_CAP_LETTERS:
Ascii_Range = new int[] {65, 90}; // Capital Letters - Characters A to Z
break;
}

for (int j = Ascii_Range[0]; j <= Ascii_Range[1]; j++)
strList.append((char)j);
}
}

StringBuilder RndString = new StringBuilder();
Random rnd = new Random();

for (i = 0; i < NoOfChars; i++)
RndString.append(strList.charAt(rnd.nextInt(strList.length() - 1)));

return RndString.toString();
}

public static void main(String[] args) throws Exception
{
System.out.println(RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25));
}
}
JDK 6.0
JavaScript
function RandomText()
{
this.RAND_NUMBERS = 1;
this.RAND_SMALL_LETTERS = 2;
this.RAND_CAP_LETTERS = 4;
this.RAND_ALL = 7;

this.Random_String = function(Type, NoOfChars)
{
var strList = "";
var Ascii_Range;
var i;

// Convert to binary format and find out what combination of random characters are required
binType = Type.toString(2);

// Loop through the bits from Right To Left
for (i = binType.length - 1; i >= 0; i--)
{
if (binType[i] == '1')
{
switch (Math.pow(2, binType.length - i - 1))
{
default:

case this.RAND_NUMBERS:
Ascii_Range = new Array(48, 57); // Numbers - Characters 0 to 9
break;

case this.RAND_SMALL_LETTERS:
Ascii_Range = new Array(97, 122); // Small Letters - Characters a to z
break;

case this.RAND_CAP_LETTERS:
Ascii_Range = new Array(65, 90); // Capital Letters - Characters A to Z
break;
}

for (var j = Ascii_Range[0]; j <= Ascii_Range[1]; j++)
strList += String.fromCharCode(j);
}
}

var RndString = "";
for (i = 0; i < NoOfChars; i++)
RndString += strList[Math.floor(Math.random() * strList.length)];

return RndString;
}
}

var oRandomText = new RandomText();
alert(oRandomText.Random_String(oRandomText.RAND_NUMBERS + oRandomText.RAND_CAP_LETTERS, 25));
JavaScript 1.5
Python
import array
import random

def int2bin(n):
"Convert an integer to binary - no built-in function"
bStr = ''
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr

class RandomText:

RAND_NUMBERS = 1;
RAND_SMALL_LETTERS = 2;
RAND_CAP_LETTERS = 4;
RAND_ALL = 7;

def Random_String(Type = RAND_NUMBERS, NoOfChars = 6):
strList = array.array('c', '')

# Convert to binary format and find out what combination of random characters are required
binType = int2bin(Type)

# Loop through the bits from Right To Left
for i in range(len(binType) - 1, -1, -1):

if binType[i] == '1':

x = 2 ** (len(binType) - i - 1)

if x == RandomText.RAND_NUMBERS:
Ascii_Range = [48, 57] # Numbers - Characters 0 to 9
elif x == RandomText.RAND_SMALL_LETTERS:
Ascii_Range = [97, 122] # Small Letters - Characters a to z
elif x == RandomText.RAND_CAP_LETTERS:
Ascii_Range = [65, 90] # Capital Letters - Characters A to Z
else:
Ascii_Range = [48, 57] # Numbers - Characters 0 to 9

for j in range(Ascii_Range[0], Ascii_Range[1] + 1):
strList.append(chr(j))

RndString = array.array('c', '')

for i in range(0, NoOfChars):
RndString.append(strList[random.randint(0, len(strList) - 1)])

return RndString.tostring()

Random_String = staticmethod(Random_String)


print RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25)
Python 2.5
Vanakkam !

Detecting the Absolute URI

In PHP there's a function called parse_url which splits a given absolute url into various parts as an array.

PHP
<?php
function AbsURI()
{
$ThisLink = 'http'.(isset($_SERVER["HTTPS"]) ? $_SERVER["HTTPS"] == 'off' ? '' : 's' : '').
'://'.
$_SERVER['HTTP_HOST'].
$_SERVER['REQUEST_URI'];

$UrlParts = parse_url($ThisLink);

$Path = $UrlParts['path'];

// Get rid of filename.html in /folder1/folder2/filename.html
$Path = preg_replace('#(/)([^/]*?\..*?$)#i', '$1', $Path);

// Make it standard to have trailing / at the end of a foldername
if (substr($Path, -1) != '/')
$Path .= '/';

$absURI = $UrlParts['scheme'].'://'.$UrlParts['host'].$Path;

return $absURI;
}
?>
You can probably get the absolute URI with something as simple as :
PHP
<?php
$s = substr($_SERVER["SCRIPT_FILENAME"], strlen($_SERVER["DOCUMENT_ROOT"]));
// Not very sure if the above always evaluates to $_SERVER["SCRIPT_NAME"]

$ThisPath = 'http'.
(isset($_SERVER["HTTPS"]) ? $_SERVER["HTTPS"] == 'off' ? '' : 's' : '').
'://'.$_SERVER['HTTP_HOST'].
substr($s, 0, strrpos($s, '/') + 1);
?>
but unfortunately, how filename & directory name values are stored in $_SERVER varies in server setup and relying on it may not be 100% accurate, though in 99% of the cases, it should do just fine.

There's another reason to use the 2nd snippet instead of the 1st - that's if a RewriteRule is used for the given current url ($ThisLink).
Lets say I had the 1st code snippet in absURI.php in test folder in my document root. So http://localhost/test/absURI.php would be the link. And something like this in my .htaccess file :
Apache
RewriteEngine On
RewriteRule ^fakefolder/test\.html$ absURI.php
and I access the url using http://localhost/test/fakefolder/test.html?a=2&b=c
AbsURI() will end up returning http://localhost/test/fakefolder/ which would be incorrect.

Tested on different hosts having Apache 2.0.x.
Vanakkam !

All Possible Permutations

All possible permutations of a string - Total number of permutations of a given word taking all n letters is n!.
For example, the word post will give 24 possible permutations inclusive of the original word (post).

  1. post
  2. pots
  3. psot
  4. psto
  5. ptos
  6. ptso
  7. opts
  8. opst
  9. ostp
  10. ospt
  11. otsp
  12. otps
  13. spot
  14. spto
  15. sopt
  16. sotp
  17. stpo
  18. stop
  19. tpso
  20. tpos
  21. tosp
  22. tops
  23. tsop
  24. tspo

This snippet here doesn't exactly output permutations of a string, but its indexes - which should correspond to the array indexes.

C++
// All possible permutations upto n digits

#include<fstream.h>
#include<conio.h>

unsigned long fact(unsigned long);
void swap(int[], int, int);
void display(int[]);
void Add(int[], int);

ofstream fout("out.txt");

void main()
{
int j, k, n;
unsigned long i;

cout << "How many digits ? "; cin >> n;

int *key = new int[n + 1];
key[0] = n; // n contains the total no: of digits

for (i = 1; i <=key[0]; i++)
key[i] = i;

display(key);
swap(key, key[0], key[0] - 1);
display(key);

for (i = 3; i <= fact(key[0]); i+=2)
{
for (j = key[0] - 1; j >= 0; j--)
{
if ((i-1) % fact(j) == 0)
{
Add(key, key[0] - j);
for (k = 1; k <= key[0] - j - 1; k++)
{
if (key[k] == key[key[0] - j])
{
Add(key, key[0] - j);
k = 0;
}
}
}
}

display(key);
swap(key, key[0], key[0] - 1);
display(key);
}

cout << "Total no: of permutations = " << key[0] << "! = " << i - 1;
fout.close();
}

unsigned long fact(unsigned long f) { return f == 0 ? 1: f * fact(f - 1); }

void swap(int k[], int a, int b)
{
int t = k[a];
k[a] = k[b];
k[b] = t;
}

void display(int k[])
{
for(int i = 1; i <= k[0]; i++)
fout << k[i];

fout << '\n';
}

void Add(int k[], int i)
{
k[i]++;
if (k[i] == k[0] + 1)
k[i] = 1;
}

Now, its pretty obvious why I had the permutations written to a file instead of console output. 9! is 362,880 but 10! is 10 times 9! which is more than 3.5 million lines of text.

Update : I have ported the C code in Java with some modifications in the way output is handled. This is much safer than that big for loop.

Java
/*
javac Permutations.java
java Permutations post
*/
public class Permutations
{
private int[] key;
private String word, pWord;
private int n, i = 1;

public Permutations(String word)
{
this.word = word;

n = word.length();
key = new int[n + 1];

for (int i = 1; i <= n; i++)
key[i] = i;
}

public boolean next()
{
if (i == 1)
{
build();
}
else if (i == fact(n) + 1)
{
return false;
}
else if (i % 2 == 0)
{
swap(n, n - 1);
build();
}
else if (i % 2 == 1)
{
int j, k;

for (j = n - 1; j >= 0; j--)
{
if ((i - 1) % fact(j) == 0)
{
add(n - j);
for (k = 1; k <= n - j - 1; k++)
{
if (key[k] == key[n - j])
{
add(n - j);
k = 0;
}
}
}
}

build();
}

i++;
return true;
}

private long fact(long f) { return f == 0 ? 1: f * fact(f - 1); }

private void swap(int a, int b)
{
int t = key[a];
key[a] = key[b];
key[b] = t;
}

private void build()
{
StringBuilder s = new StringBuilder();

for(int i = 1; i <= n; i++)
s.append(word.charAt(key[i] - 1));

pWord = s.toString();
}

private void add(int i)
{
key[i]++;
if (key[i] == n + 1)
key[i] = 1;
}

public String nextWord()
{
return pWord;
}

public static void main(String[] args)
{
if (args.length == 0)
{
System.out.println("Got to give an argument");
System.exit(0);
}

Permutations p = new Permutations(args[0]);
while (p.next())
{
System.out.println(p.nextWord());
}
}
}
JDK 1.6

PS: I wrote this half a decade ago but never documented it. I'll try to update it with an explanation soon.

Vanakkam !

fputcsv for PHP4

I found it strange why fgetcsv() was included since version 3.0.8 and fputcsv() only since 5.1.0RC1 when both are so closely interrelated. Heres fputcsv for ones not running on a minimum of PHP 5.1.0RC1.
PHP
if (!function_exists('fputcsv'))
include_once("php4.inc.php");
Assuming php4.inc.php includes functions that natively exist in PHP 5 and not in version 4.
PHP
function fputcsv($fh, $arr)
{
$csv = "";
while (list($key, $val) = each($arr))
{
$val = str_replace('"', '""', $val);
$csv .= '"'.$val.'",';
}
$csv = substr($csv, 0, -1);
$csv .= "\n";
if (!@fwrite($fh, $csv))
return FALSE;
}
The str_replace('"', '""', $val); is because Excel doesn't seem to understand \".
Vanakkam !

Absolute path of current php file in execution

Sometimes it is necessary to know the absolute path of the current php-file in execution. A common example is when you have loaded a 3rd-party module and all its related files (like php, css, js, images etc) are in a folder of its own and moving these related files to your own specific-folders for the sake of organization can be disadvantageous instead of structuring them to match your own. If moving the files to different locations, editing the module code could end up being cumbersome. Hence, modules are like Java packages where all the files are kept in a separate folder and better left untouched. In php, if we can extract a lot of file and folder information from these global variables $_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME'], $_SERVER['SCRIPT_NAME'], $_SERVER['PHP_SELF'] But none of these would give the current php-file name in consideration if mod_rewrite, include() etc were used to retrieve a php file. PHP's __FILE__ magic constant is the only way to retrieve the absolute path. Given this path you can create a OO module within which you can access the related-files within the folder and thus be independent of any CMS. This is one very simple function you'll come across but I still felt the need to emphasize on this function.
PHP
<?php
echo __FILE__AbsolutePath(__FILE__)."\n";

function __FILE__AbsolutePath($Filename)
{
switch (PHP_OS)
{
case "WINNT": $needle = "\\"; break;
case "Linux": $needle = "/"; break;
default: $needle = "/"; break; // TODO : Mac check
}
$AbsPath = substr($Filename, 0, strrpos($Filename, $needle));
return $AbsPath;
}
?>
I haven't done a MAC and other OS checks. If you have tried this on an OS that shows a different value for PHP_OS, please do share it with others.

Update: Getting the current file equivalent to __FILE__ can be retrieved using the debug_backtrace() function.
PHP
<?php
function __FILE__AbsolutePath()
{
$d = debug_backtrace();
$Filename = $d[0]['file'];

switch (PHP_OS)
{
case "WINNT": $needle = "\\"; break;
case "Linux": $needle = "/"; break;
default: $needle = "/"; break; // TODO : Mac check
}
$AbsPath = substr($Filename, 0, strrpos($Filename, $needle));
return $AbsPath;
}
?>
Vanakkam !

get_file_contents

Sometimes we need to retrieve a remote file/url's content which is easily done using PHP's file_get_contents(). This returns FALSE on failure but on many occasions file_get_contents() returns FALSE due to a network error or server overload and could've worked the next second. Here is a function get_file_contents(), that tries to retrieve the url's contents over and over again until its TRUE (it has successfully fetched the contents) or until it has exhausted the number of tries. Because threading is not yet available in PHP, it is not recommended to set the $totalTries to a higher value.
PHP
function get_file_contents($url, $totalTries = 5)
{
$Tries = 0;
do
{
if ($Tries > 0) sleep(1); # Wait for a sec before retrieving again
$contents = @file_get_contents($url);
$Tries++;
} while ($Tries <= $totalTries && $contents === FALSE);
if ($contents == "") $contents = FALSE;
return $contents;
}
This ends the beginning of my first post here !
Vanakkam !