Skip to content


I dug up my old posts

I had been blogging since 2009 but if you visited this blog until yesterday you could only see my posts from last few months. It is because I used to try out different blogging platforms and never used to take a backup and in the process I used to lose all my posts. This is mainly because I felt my posts were substandard and doesn’t deserve a place on the web. Some posts were on topics which I was sure I will not be working on again(like PHP, Perl etc).

But later I found it was a bad choice and regretted my move. I wish I could resurrect them. But they were no were left on the web (or atleast I thought so). Even when I was sure I won’t be needing them anymore since I stopped working on the technology some of those posts were actually good (Like the WordPress posts) because I have put a lot of effort in finding those and documenting them. From my comments which I got earlier I even knew they were helpful for others. So it was actually a crime I deleted it.

Though I have many blogs subscribed on my Google reader, I never religiously accessed them from there. I used to go to the source directly and read. So I was unaware I had all my blog posts archived in there. When I found out about it I was happy. I took the morning time to bring back all those old posts back to this site. Unfortunately I couldn’t bring back the comments. I wish you will find some of the posts helpful. I agree some of those old posts are very noobish and entry level, some may be even misinformed. So I believe you will look into it as posts from when I joined the industry.

I will not be or haven’t been using some of the technologies mentioned in those posts (say like C++ and Perl). So I don’t actually remember the concepts in those posts. I am sure I was knowledgeable about them at that time. Some technologies I might have forgotten but may be brushing up later (say like Ruby or C++). Some technologies I am sure I will not be playing with anymore (like Magento). So don’t expect more posts like those. A few of the initial posts are actually from my old blog which is till available but not maintained. I just moved them here so they are where they belong.

So fell free to go around and guage my growth as a programmer from the beginning till now. Thanks.

Posted in General.


Insertion Sort

I have decided to go back and relearn on my own the algorithm course which once took during college. I found a free course by Stanford on Coursera and is following it. I hope with my job and other engagements I could finish it successfully. These are some of the programs I wrote during learning. These are working code, but may not be the most optimised. I also follow the honor code from Coursera and will not be sharing any problem set or programming set answers.  I am also following the text ‘Introduction to Algorithms, Third Edition by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein‘. So let’s start with the basic algorithm introduced in it; the Insertion Sort.

Psuedocode
Assuming A is the array to be sorted.

for j = 1 .... j < A.length
	A[j] = key
	i = j - 1
	while i >= 0 and a[i] > key
        A[i+i] = A[i]
        i = i - 1
    A[i+i] = key

[NB: I have made a minor change in the array bound notation so that it starts from 0 and ends at n-1 as in real life arrays. The book depicts it from 1 to n, i found this better fitting to my mind]

Code
I have converted the above pseudo code to Java. I am adding it here. Beware, it is neither a perfect solution. I have used arrays so the size of the numbers that can be sorted is pre defined to 5. I knew I could have used ArrayList but my understanding of ArrayList is still low. I will write a better program on a later date, I promise.

import java.util.*;

public class InsertionSortTest {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int[] toSortArray = new int[5];

		System.out.println("Enter 5 digits that needes to be sorted");
		for(int count = 0; count < 5; count++) {
			toSortArray[count] = in.nextInt();
		}

		InsertionSort toSort = new InsertionSort(toSortArray);
		toSort.sortTheArray();
		toSort.printTheArray();
	}
}

class InsertionSort {
	public InsertionSort(int[] a) {
		sortMe = a;
	}

	public void sortTheArray() {
		for(int j = 1; j < sortMe.length;  j++) {
			int key = sortMe[j];
			int i  = j - 1;
			while (i >= 0 && sortMe[i] > key) {
				sortMe[i + 1] = sortMe[i];
				i = i - 1;
			}
			sortMe[i + 1] = key;
		}
	}

	public void printTheArray() {
		for (int i : sortMe)
			System.out.print(i + " ");
	}

	private int[] sortMe;
}

[NB: I have written this for my own education and later reference. So if you are a student please only use it a reference and don't use it for your home work as a whole. It's not that I don't like you using my code, but I don't want you failing the course]

Posted in Design and Analysis of Algorithms, Java, Theoretical Computer Science.

Tagged with , , .


Object Oriented Programming in Java – 2

[NB: These are actually a set of posts which are points I noted down while learning Java from Core Java Volume I by Cay Horstmann and Gay Cornell. This is in no way an attempt to copy their material  or serve as a substitute; but serves only as a quick cheat sheet for me to look into important topics quickly]

The first part of this post can be read here.  In this part we will be mostly discussing inheritance.

- super keyword is used to access the methods of the super class.
- super can be used to call the constructor of the super class also.

- protected fields can only be accessed by sub classes.

Polymorphism – an object variable can actually refer to multiple actual types.
Dynamic binding – Actually selecting the appropriate method at run time.

Substitution principle - You can use  a subclass object whenever the program expects a super class object.
A variable of Employee can refer to an object of Employee or any subclass of employee (for eg Manager).

Manager boss = new Manager(...);
Employee[] staff = new Employee[3];
staff[0] = b0ss;

Here staff[0] and boss refer to the same object. However staff[0] is an Employee object and thus we cannot call the methods of Manager on it. So staff[0].setBonus() is wrong while boss.setBonus() is correct.

You cannot assign a super class object to a sub class variable. so Manager m = staff[i]; is wrong.

Arrays of sub class references can be converted to arrays of super class references without cast.

Manager[] managers = new Managers[4];
Employee[] staff = managers;

The above code is correct. Now both staff and managers refers to the same array. So though even when it is legal to say staff[0] = new Employee(…); it is incorrect to do staff[0].setBonus(); cause  it is an Employee variable which doesn’t have access to that method. All arrays remember the element type with which they are created , and they monitor only compatible references are stored into them.

- final classes aren’t extensible.
- a final method cannot be overridden in sub class.
- fields can also be final. A final field cannot be changed after the object has been constructed. However if a class is declared as final, only the methods , not the fields are automatically final.

Abstract Classes
-
If a class has even one abstract method the class should be marked abstract.
- Abstract classes can have concrete methods and fields.
- If a class extending an abstract class hasn’t implemented all the abstract methods in the super class then it should also be termed as abstract class.
- A class can be declared as abstract even though it doesn’t have any abstract methods.
- An abstract class cannot be instantiated. But we can have object variables of abstract class, but such a variable must refer to an object of non abstract subclass. Also though we cannot call new on an abstract class they still have constructors.

Interface
- is a way of describing  what classes should do without specifying how they should do it.
- all methods in an interface is abstract.
- a class can implement more than one interface.
- Once we implement an interface in a class we should supply definitions to all the methods.
- Interfaces are not classes. Thus we cannot construct interface objects. But we can have interface variables. These variables should however refer to an object of a class that implements the interface.

Posted in Java.

Tagged with , , .


Object Oriented Programming in Java – I

[NB: These are actually a set of posts which are points I noted down while learning Java from Core Java Volume I by Cay Horstmann and Gay Cornell. This is in no way an attempt to copy their material  or serve as a substitute; but is serves only as a quick cheat sheet for me to look into important topics quickly]

Class – A template or blueprint from which objects are made.
Encapsulation – combining data and behavior in one package and hiding the implementation details from the user of the object.
Instance fields – data in an object.
Methods – procedures that work on data.
State – A specific object will have specific values for it’s instance fields. The set of those values are the current state of the object.

Constructors

  • A constructor has the same name as the class.
  • A class can have more than one constructor
  • A class can take zero, one, or more parameters.
  • Two constructors are different if the type and order are different. So ConsName(int size, String name) and ConsName(String name, int size) are different
  • A constructor can have no return value. There can be a method with the same name as the class, but the difference of this class to that of constructor is the return type.
  • A constructor is always called with the new operator.
  • If no constructor was explicitly created a default constructor is generated automatically.
  • The instance values will be initialized with default values in the default constructor.
  • A constructor can call another constructor through the this() keyword.

- You can have only one public class in a source file but you can have any number of non public classes.
- Never write accessor methods that return references to mutable objects. Always clone those mutable references.
- A method can access the private data of all of the objects of its class.
- Final methods (mostly used as helper methods).
- Final instance fields must be initialized when the object is constructed and after which it will not be  modified again.
- Static fields: only one field per class.
- Static final fields: constants
- Static methods: You don’t need an object to call these methods. You cannot access instance fields from a static method.

- Java uses pass by value. Even in case of references it is pass by value. We get a copy of the reference which refers to the original object. That is why instance fields changes in case of references inside a method. But a swap of objects inside a method will not cause the original references to be swapped.

- Initialization blocks : These are executed whenever an object  of that class is constructed. No matter which constructor is called, first the initialization block is run then only the body of the constructor is run.
- Static initialization blocks:  to initialize static instance fields.

- The instance fields in a class will automatically get initialized but the local variables inside a method needs to be explicitly initialized.

- finalize() method is used to reclaim important resources, but it is not the safest method.

Packages
- for organizing your work
- to get unique class names and separate the classes from others provided by others.
- a class can use all classes from it’s own package and all public classes from other packages.
- if there is name clashes between two classes from different packages you can use specific imports or use full package names.
- you can use static imports to import static fields and methods.

Posted in Java.

Tagged with , , .


Learning Erlang

Today I was in a mood to learn something totally different; something which I haven’t tried so far; something which is totally new to my programming mind. I have heard and knew Scala, Erlang, Haskell, Clojure etc are the best contenders. I decided I will try Scala and Clojure later only after get into grips with some Java and LISP, since they run on JVM and one is a newway of doing LISP (I know the thought is faulty and we need not necessarily know Java and LISP before diving it, but in some things I am a bit compulsive). I decided to give Erlang a try first because I understood it has much lesser steep in the education curve. So I went to the Erlang site, downloaded the compiler and started working on the User Guide.

Till now I have gone through only the initial chapters and problems on the site, but it has already given me new perspectives. It has already given me new insights into the term ‘variable’. I got a new understanding on the word ‘assign’. The fact that an Erlang variable can only be bounded once and we can never change the value later was kind of a shock to me at first.  I was baffled by the fact that a language would exist without a feature of reassignment. I asked around in IRC and that is when I got an insight on how variables are treated in Erlang. The ‘=’ operation is not strictky assignment operation. It is actually a ‘MATCH’ operator. If you write something like Left = Right. it is only checking if the left matches the right and returns a true or false. If it is seeing Left for the first time, and that is when assignment happens.  And once it is assigned, it cannot change.

Another thing I was stunned was when I was going through lists. Var =  [1, 2, 3]. returns [1, 2, 3]. But Var2 = [97, 98, 99].  returns the string “abc”. I again asked in IRC what if I wanted the list of numbers [97, 98, 99] and the answer was that that is exactly what I have got with me “abc”. A String is a list of their ASCII values. So to do something like

[97, 98, 99].each do { |i| i + 1 }

to return a list of [98, 99, 100] the code in Erlang will be like

[X + 1 || X <- "abc"]

I also find it amusing about the use of full stops instead of semicolons for ending the statement. Overall Erlang had been a new experience to it and I believe I have started to like it. After I finish the User Guide I will continue with Learn you some Erlang.

And I have found some decent blogs on Erlang which I will be visiting
Mitchell Hashimoto
Yariv Sadan
Jack Moffitt
Joe Armstrong

Priority for my NExt year is Java, so I am not sure how much I will be involved with Erlang. But I wish I could do some serious look into it.

Posted in Erlang.

Tagged with .


Plans for 2012: To be a better programmer

After 5 years of a career in PHP web application development I will be moving to Java development from March of 2012. I have started brushing my Java gyan and learning more on the enterprise aspects of the language.

As the year is about to end, I thought it would be a good time to have a look back at my career and get a good perspective of my abilities and to plan for the future. I have seen the Comptetency matrix before and thought it will be a decent scale. I am hereby measuring myself on that scale and is setting a goal for the next year.

The current level is given and the expected value for 2012 end is given in the bracket. After each section the steps needed to be taken and the books to be read are given with further explanation on why some levels stay the same and why some change. The idea is not to read all the books in full. It is a continuous process and some books will take years to understand fully.

Computer Science

  • Data structures : level 1 (level 2)
  • Algorithms :  level 1 (level 2)
  • Systems Programming :     level 1 (level 1)

I had studied these subjects in college, but to tell you the truth haven’t used most of the concepts after it. So my knowledge is shaky and I need to build on it. The importance is on learning data structures and algorithms and whether I will look into compilers will depend on my time, that is why it is still on level 1.

Books to study:

  1. Classic Data Structures
  2. Introduction to a Algorithms 
  3. Compilers: Principles, Techniques and Tools

Software Engineering

  • Source Code and Version Control   :   level 1 (level 2)
  • Build Automation                                   :   level 0 (level 0)
  • Automated testing                                 :   level 0 (level 1)

Me being a PHP developer most of my life never aided me in any sense in using automated tools or testing, that is is why I am still in level 0. Coming new to live Java development, I am not sure what is waiting for me. That is ehy there is no greater gain in this field. Regarding version control I have played with Git, mainly at github and is using SVN at work. But still I am just a passive user. need to learn more.

Books to study:

  1. Pragmatic version control: Using Subversion
  2. Pragmatic version control: Using Git 
Programming

  • Problem Decomposition                          :    level 1 (level 2)
  • System Decomposition                             :    level 1 (level 2)
  • Communication                                           :    level 2 (level 3)
  • Code Organization  (within file)             :    level 1 (level 2)
  • Code organization  (across project)    :    level 1 (level 2)
  • Source Code Organization                       :    level 1 (level 2)
  • Code readability                                          :    level 2 (level 2) 
  • Defensive coding                                         :    level 0 (level 1)
  • Error handling                                              :    level 0 (level 2)
  • IDE                                                                     :    level 0 (level 2)
  • API                                                                     :    level 0 (level 1)
  • Frameworks                                                   :    level 1 (level 2)
  • Requirements                                                :    level 2 (level 3)
  • Scripting                                                          :    level 2 (level 2)
  • Database                                                          :    level 2 (level 3) 
This is a vast topic many things are to be covered here.Books to read:
Programming Language 
(This list is not complete. It may add new books depending on my needs at job, say for example books for Hibernate, Struts, webservices. Also depending on the time and urgency I may or may not read some of the above too. But to read them all is the aim. If not in 2012, may be in 2013)Software Engineering Books 
There is a good chance that I will not read even one of the above books fully, but the aim is at least read a few important pages from each. Learn the important patterns for example. After all it is a continuous process.
Experience
  • Languages with professional experience     :   level 1 (level 2)
  • Platforms                        ”               ”                         :    level 1 (level 1)
  • Years of experience                                              :    level 1 (level 2)
  •  Domain Knowledge                                              :    level 1  (level 2)
Knowledge
  • Tool knowledge                                                      :    level 1 (level 2)
  • Languages exposed to                                         :    level 1 (level 2)
  • Codebase knowledge                                            :    level 1 (level 2)
  • Knowledge of upcoming technologies          :    level 1 (level 2)
  • Platform internals                                                 :    level 1 (level 2)
  • Books                                                                          :    level 1 (level 2)
  • Blogs                                                                            :   level 2 (level 3)
But if you see this a big list and it is normally not possible to read even through the quarter of the books which are mentioned.  Just now I was leafing through Code complete and I read in it about a study where it is said, a normal programmer won’t read more than a book a year. So I am onto a huge task and I will consider this a success even if I complete a substantial chunk of it.

Posted in General, Software Engineering.


Add rich text editor to custom post fields.

I created a custom posts with a lot of custom text areas and was thinking how to add some WYSIWYG editor to them. I new it was possible as WordPress has the functionality. A simple google search resturned the result. I’m not republishing it as my own. It is ‘guikubivan‘ who should get the credit. I’m just adding it here for my own future reference.

This is link with the solution.
Adding tinyMCE Editor for custom field when editing post page

Posted in PHP, Wordpress.


Get the published date of a post in wordpress; a small caveat.

This might not be a very revolutionary thing for many of you WordPress veterans out there, but when I got stuck on this issue later this morning, it took me some time to get it fixed. So I believe it is worth a mention.

As most of you might be knowing the_date() is the function which will return the published date of a post.  But if you don’t read more about this little function, you will also run in circles as I did wondering why it is not behaving like the way you wanted.

I was using the loop to print all my posts and was using the function to print the published date for each. But it was only printing the date for the first entry. I wondered whether my loop is faulty. It shouldn’t be, as I was getting the title, content and everything else as I needed. That’s when I decided to check the WordPress Codex. And there it is written in the top of the page as a special note.

When there are multiple posts on a page published under the SAME DAY, the_date() only displays the date for the first post (that is, the first instance of the_date()).

Ha! that’s it. As said in the documentation, the correct function to use here is get_the_date().

Though I spent some time fruitlessly, I learned a new lesson through this incident. Always search the official documentation first than scouring the net.

Posted in PHP, Wordpress.


Show the custom posts of a particular category in WordPress

This is a small follow up post to my earlier post of creating different categories for different post types in WordPress. After I created the posts in different categories I needed to show them on my front end. Since each post type was divided into different categories, I needed to have separate pages which showed only posts from a particular category. Justin’s post showed us the way to show all the posts from the custom post type. That function is correct, but I needed to add in details of the newly added categories. After some research I found out the method for that too. Here I’m sharing it with you. The important thing from a WordPress point of view is to think categories as taxonomies and each sub category as term. This is just a loose association. More on it will be followed in a different post.

So if you have read the earlier post, I have various members in who has been categorized as per their career. I wanted to show the list of all members who are doctors. So I added the following to Justin’s code.
‘taxonomy’ => ‘ doctor’. So the full code looked like this (which is WRONG!!!)

<?php $loop = new WP_Query(array('post_type'=>'members', 'taxonomy'=>'doctor')); ?>
 <?php while ($loop->have_posts()) : $loop->the_post();  ?>
 <?php the_title( '<h2><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a></h2>' );  ?>
 <div>
 <?php the_post_thumbnail(); ?>
 <?php the_content(); ?>
 </div>
 <?php endwhile; ?>

But als this didn’t work, I had to do a lot of alteration to this code before making it work. I was straying because my understanding of WordPress taxonomies was very little. As I said before WordPress has both taxonomiesand terms. So in my case the taxonomy was ‘member_career‘ which I created using the  register_taxonomy()function in the function.php file from the theme.. And ‘doctor’ was a term which I created from the Admin back end. I needed to add both of these in the array parameter in the WP_Query() function.

So I have to correct the above code  with

<?php $loop = new WP_Query(array('post_type'=>'members', 'taxonomy'=>'member_career', 'term' => 'doctor')); ?> 

And finally the full code will look like this (RIGHT!!!)

<?php $loop = new WP_Query(array('post_type'=>'members', 'taxonomy'=>'member_career', 'term' => 'doctor'')); ?>
<?php while ($loop->have_posts()) : $loop->the_post();  ?>
<?php the_title( '<h2><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a></h2>' );  ?>
<div>
<?php the_post_thumbnail(); ?>
<?php the_content(); ?>
</div>
<?php endwhile; ?>

Posted in PHP, Wordpress.


Create separate categories (taxonomies) for each custom post type in wordpress

Recently I’m working on a project where WordPress is used as a CMS . I have worked with WordPress before, but mostly that was merely as a blog engine.  So most of the CMS features that WordPress 3 offers is new to me and when some issue arises, I have to do extensive Googling to come out with a solution. Today morning I was provided with a another opportunity to  learn something new.

I wanted to create multiple custom post types for the site and needed some methodology to categorize a post type. Similar to something we did when we added a post in the blog we made with WordPress. So initially my thoughts were on how to enable categories for my custom post type. So I googled and found that adding‘taxonomies’ => array(‘category’) inside the register_post_type() method that you use to create the custom post type will enable category for you. But this had a big drawback.

The category that you enabled now is actually the generic category that you get when adding a post. So all the custom post types will share all the categories. This is not what I expected. I wanted separate categories for each of my custom post types. For example, for my custom post type called ‘Members’ I wanted job like Lawyer, Doctor etc tyo be a category and for the other post type called ‘Publications’ I wanted the publication frequency like Weekly, Monthly, Yearly etc to be the category. This was not possible with the other method. But thankfully it is possible. What you need  is the register_taxonomy() method. I found it hard to find this function. The culprit was my thought. I searched for the term ‘category’, but in WordPress ‘taxonomy” is the better and apt term.

So here is what I did.

// add taxonomies to categorize different custom post types
add_action( 'init', 'build_taxonomies', 0);

function build_taxonomies() {
register_taxonomy( 'publication_frequency', 'publications', array( 'hierarchical' => true, 'label' => 'Publication Frequency', 'query_var' => true, 'rewrite' => true ) );
register_taxonomy( 'member_career', 'members', array( 'hierarchical' => true, 'label' => 'Member Career', 'query_var' => true, 'rewrite' => true ) );
}

Now if you check your dashboard, you will see links ‘Publication Frequency’ and ‘Member Career’ under the respective post type. You can use them as you would use a category in a normal post. The first parameter to the register_taxonomy() function is a slug and the second one is the custom post type. Make sure you have the same name you used while making the post type.

[NB: The following sites helped me finding this out and it has more authoritative explanation on these topics
1. Create custom post types : Tutorial by Justin Tadlock.
2. Create custom taxonomies : Tutorial from NetTuts+.]

 

Posted in Wordpress.