Archive for the 'Coding' Category

Groovy : Invoking One Script From Another

It was like one of those Aha! moments when I finally found how to invoke one script from within another. It is so simple!!

Say you have a script RunScript.groovy which is as follows:

        package com.singhanuvrat.sandbox

        println "Whoa!! ${input}"

Now you want this RunScript.groovy to be called from CallerScript.groovy with different values for the variable input. Our script will be:

        package com.singhanuvrat.sandbox

        GroovyScriptEngine gse = new GroovyScriptEngine("src/com/singhanuvrat/sandbox");
        Binding binding = new Binding();
        binding.setVariable("input", "world");
        gse.run("RunScript.groovy", binding);

Infact, using the binding, we can also extract value of variables from the called script. Now we shall have fun! :)

Popularity: 1% [?]

Puzzle: Complete the C Code Block

A very simple and trivial question:

I am giving a C code block that you need to complete. Here it is:

if(______) {
  printf(" Fair ");
}
else {
  printf(" Isaac ");
}

The question is this:

Propose a condition for the if statement so that the output of the block is Fair Isaac.

Popularity: 15% [?]

Java Code: Pair Class

A pair class. Nothing special. And of course, bits and pieces taken from other people’s code.

Popularity: 13% [?]

Parsing XML With Castor XML

After lot of trying I finally managed to get Castor tools working to parse XML files. And now that I have it working for me, I am always going to use it for XML parsing. It makes things so much simpler and easier.

Castor takes in a xml file and unmarshals it into Java objects. There are three ways to associate Java Classes with XML elements.

  • The first one is introspection. Given the class to the Unmarshelar, Castor populates the instance fields from XML.
  • The second is to use bindings defined by user.
  • The third is to use the XML Code Generator tool and have it generate Java Classes.

Of course, I used the third option, and that is the one I am going to mention here.

Castor jars can be downloaded from the Castor Project.It has a few dependencies. So I decided top use Maven. And I am already using Eclipse.

I imported the castor-code-generation jar. Then created a pom.xml file. I added a plugin to it:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>castor-maven-plugin</artifactId>
        <version>2.0</version>
        <configuration>
          <schema>config.xsd</schema>
          <packaging>pba.plgen.xml.binding</packaging>
          <properties>generation.properties</properties>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>generate</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

Where the properties file is:

# Specifies whether the sources generated should be source compatible with
# Java 1.4 or Java 5.0. Legal values are "1.4" and "5.0".  When "5.0" is
# selected, generated source will use Java 5 features such as generics and
# annotations.
# Defaults to "5.0".
#
org.exolab.castor.builder.javaVersion=5.0

# Set to true if you want to have an equals() and
# hashCode() method generated for each generated class;
# false by default
org.exolab.castor.builder.equalsmethod=true

# Specifies whether automatic class name conflict resolution
# should be used or not; defaults to false.
org.exolab.castor.builder.automaticConflictResolution=true

# Property specifying whether extra members/methods for extracting XML schema
# documentation should be made available; defaults to false
org.exolab.castor.builder.extraDocumentationMethods=false

Right Click -> Run As -> Maven generate-sources

And all the source code is generated.

Suppose that the root element is plgen. Then a class Plgen is generated. All the child nodes of plgen become instance variables of Plgen. To unmarshal the xml file,

        public void parse() {
		try {
			m_plgen = Plgen.unmarshal(new FileReader(m_configFilePath));
		} catch (MarshalException e) {
			e.printStackTrace();
		} catch (ValidationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

Well, I haven’t written this properly. But, its enough to make me remember how to get castor working again. My mission accomplished.

Popularity: 10% [?]

I Hate XMLs

XMLs have never been my favourite. Attributes, Elements, Values, Child nodes … aargh, they are so confusing. And yet, configuring an application using an xml file seems so simple.

I have written my own XML parsers using the DOM. The whole document gets mapped to a tree structure which you can iterate over and get any value you want. But I find it to be very restrictive, and most of my code depends on the structure of my xml file. I would like to make my xml parser independent of the xml file structure.

I came across Castor XML. It has tools to read the schema and generate Java Classes out of it. Then the xml file is parsed and objects are created. Now this is good. I think this should be much easier than iterating a tree. But !! I have spent a lot of time trying to get Castor working. Its dependencies !!! Damn.

Time to get back to xml parsing again.

Popularity: 11% [?]

Varargs

Just like you have variadic functions in C, Java has the Varagrs :) . Its usage is as simple as this :

public List<string> getModifiers(String... arg) {
  // arg is String[]
}

And the wonderful thing is that the arg is a String[].

Popularity: 4% [?]

Printing The Last 50 Lines Of A File

Having completed the coding of my BTP, I had to test the program. I wrote down a simple C program to do this and generate the outputs in log files in a specified folder. However, I messed it up big time. The actions included creating temporary files, catenating them and then moving them. I did it horribly wrong and ended up with lots of garbage in each log file. Only the last 50 lines of each file were the results, rest garbage.

I needed a way to retain the last 50 lines of each file and discard the rest. This is when I stumbled across the tail command. It does exactly this ! All you have to do call tail -50 <filename> for each of the files. Sweet !

A simple recursive loop, calling the tail command for each file, and yay I am done with my work. Now it is the time to analyse the results.

Popularity: 4% [?]

A Logger In C

Now I am working on this fair scheduling for my B Tech Project (BTP). Already having written a 1000 lines of code, it is a great pain to debug it. More so if you do not know which function might have caused the error. I needed a logger which could log all the events. The events include entering a function, any important calculation/decision it makes, any return values, so that if my program breaks down I can exactly pinpoint the source of error simply looking at the log file generated.

I have no idea if any inbuilt logging functionality exists for C programs or not. Either way, I did not have much time to google up and learn how to use it. I decided to make my own logger, a simple one, which would serve my purpose. It hardly took me 10 minutes to get over with it.

One of the important functionalities that I wanted my logger to have is indentation. The log should be properly indented, just the same way as we indent the code. When the program control enters a new function, the logging should get indented to right, and when it leaves the function, the logging should get indented by the same amount to the left. So I defined two macros, $$INDENT$$ and $$OUTDENT$$. To make them work, I defined a global variable – $$logIndent$$. The $$logIndent$$ would at any given time contain the amount of space by which the log has to be indented. Obviously, I initialized it with 0. Also defined is a global variable called $$indentVal$$ which is the amount of spaces with which the indentation should take place. I like the value to be 2. The two macros are

#define INDENT logIndent += indentVal
#define OUTDENT logIndent -= indentVal

int indentVal = 2;
int logIndent = 0;

I defined another macro called $$SPACES$$ which would print the number of spaces to produce the required indentation.

int tempIndent;
FILE *logFile;
#define SPACES for(tempIndent = 0; tempIndent < logIndent; tempIndent++) fprintf(logFile, " ");

Obviously $$tempIndent$$ is a globally declared temporary variable and $$logFile$$ is the file pointer to the file where the log has to be written. I initialize the $$logFile$$ pointer in the $$main()$$ part of my program.

And finally coming to the logger, I created a custom $$printf()$$ statement using the $$vprintf()$$ command. I call my logger as $$LogThis()$$. Its declaration is as follows

void LogThis(const char *format, ...);

It is constructed as follows

void LogThis(const char *format, ...) {
  va_list args;
  va_start(args, format);
  SPACES;
  vfprintf(logFile, format, args);
  va_end(args);
}

That’s it ! To use this logger, I have to do the following in my function :

#include <stdio .h>
#include <stdarg .h>
void TestLogger() {
  int returnVal;
  float retVal;

  LogThis("<testlogger>\n");
  INDENT;

  /**
   *  Inside the function do whatever you want to
   */

  LogThis("Returns: %d, %f\n", retrunVal, retVal)

  OUTDENT;
  LogThis("</testlogger>\n");
}

Done ! A well indented log will be produced. This has really helped me debug the code. I do not have to gdb from the last point that worked in my program. Instead, I know which function the program control was in when it threw an error. I need to gdb from that function onwards only, thus reducing the debuging time considerably. Also, in case of errors, I can increase the debugging data for that particular function, thus eliminating the need to use gdb at all.

Popularity: 5% [?]

php – Sessions

After a long long time I was back to coding in php. And by long time, I mean atleast 24 months ! Believe me, it wasn’t easy. More so because of the higher standard I have set for myself. My code this time shall be much neater and easier to read than it ever was.

The past four years of my life has been spent coding. And when you code so long, you modify your habits to get tuned to the proper way of coding. As it is said, a person spends more time reading a code than writing it. So this time I am taking special care of writing simpler and smaller functions so as to make the code more readable. Also, since I have been reading a lot of OOP these days, I am intent on providing an abstraction layer for the user, so that at the top most level coding should appear like writing a few english sentences rather than some cryptic mysqli_select_db things.

This is the first time I am trying to code in php following the OOP structure. Also, though this might seem strange, it is the first time I am using session variables in my design! Below is a trivia I had not known earlier, and spent 2 hours trying to understand what was wrong in my seemingly proper and correct code.

A session created with session_start will only be available to pages within the directory tree of the page that first created it.

i.e. If the page that first creates the session is /dir1/dir2/index.php and the user then goes to any page above dir2 (e.g. /dir1/index.php), session_start will create a new session rather than use the existing one.

Also I found the following class to be useful.

< ?php
class Session {
public static function Init() {
self::Commence();
}

public static function Set($fld, $val) {
self::Commence();
$_SESSION[$fld] = $val;
}

public static function un_set($fld) {
self::Commence();
unset($_SESSION[$fld]);
}

public static function Destroy() {
self::Commence();
unset($_SESSION);
session_destroy();
}

public static function Get($fld) {
self::Commence();
return $_SESSION[$fld];
}

public static function is_set($fld) {
self::Commence();
return isset($_SESSION[$fld]);
}

private function Commence() {
if(!isset($_SESSION['ready'])) {
session_start();
$_SESSION['ready'] = TRUE;
}
}
}
?>
Reblog this post [with Zemanta]

Popularity: 4% [?]

php5 OOP – Function Overloading

PHP

PHP

Starting php4, object oriented concepts have been made available to the programmer. Though not well developed, they paved the way for a more complete implementation of the OOP basics in the php5 version. However, one thing that remains lacking is the ability ot overload the functions.

Overloading of functions is quite an useful feature. In the simplest form, it gives you the freedom to declare a class with more than one constructors.

Not to get disheartened though, we have a simple enough way to work around this short coming. In php, when a call is made to a function that does not exist, then the control searches for the __call() function. We make use of this to carve out the over loading feature that we need.

Below, I am writing the code for a Register class which has two variables – name and pass. The constructor is being overloaded here.

class Register {
private $name;
private $pass;

public function Register() {
$num = func_num_args();
$args = func_get_args();

$funcName = 'Register'.$num;
$this->__call($funcName, $args);
}

private function Register0() {
$this->name = '';
$this->pass = '';
}

private function Register2($name, $pass) {
$this->name = $name;
$this->pass = $pass;
}

public function __call($funcName, $args) {
$this->call_user_func_array(array($this, $funcName), $args);
}

public function setName($name) {
$this->name = $name;
}

public function setPass($pass) {
$this->pass = $pass;
}
} // Register

// regA is using the Register2() constructor
$regA = new Register('Anu', '@#$#@$@$');

// regB is using the Register0() contructor
// and subsequently setting the values of name, pass
$regB = new Register();
$regB->setName('Anu');
$regB->setPass('@#$#@$@$');
Reblog this post [with Zemanta]

Popularity: 4% [?]