Ubuntu insights, Programming in groovy, java, et als!

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, March 18, 2012

TicTacToe Game in Pharo Smalltalk

For an absolute pharo/smalltalk beginner, I think this would be a good place to start with. This is a simple TicTacToe implementation with just three classes : TicTacToe, TicTacToeCell and TicTacToeModel using Morphs. Works on MVC based architecture with view and model separate (no specific class for controller though).

Object subclass: #TicTacToe
instanceVariableNames: 'container model'
classVariableNames: ''
poolDictionaries: ''
category: 'VK-Games'

initialize 
container := Morph new 

              layoutPolicy: TableLayout new; 
              color: Color transparent.
model := TicTacToeModel new:3.
self addRows.
self addControls.
^self.

addRows
| rowMorph aCell rowCol |
1 to:3 do:[ :row |
rowMorph := Morph new layoutPolicy: RowLayout new.
1 to: 3 do: [ :col |
aCell := TicTacToeCell new.
aCell setModel: (model) row: row col: col.
rowMorph addMorph: aCell.
].
container addMorph: rowMorph.
]

addControls
| rowMorph newGameButton exitGameButton |
rowMorph := Morph new 

             layoutPolicy: RowLayout new; 
             color: Color transparent.
newGameButton := self createCtrlLabelled: 'New'      onClickExecutes: [self restart].
exitGameButton := self createCtrlLabelled: 'Exit'  onClickExecutes: [container delete].
rowMorph addMorph: exitGameButton.
rowMorph addMorph: newGameButton.
container addMorph: rowMorph.

createCtrlLabelled: aString onClickExecutes: aBlock
| aCtrlButton |
aCtrlButton := SimpleButtonMorph new label: aString.
aCtrlButton color: (Color black alpha: 0.2).
aCtrlButton extent: 60@30.
aCtrlButton on: #click send: #value to: aBlock.
^aCtrlButton.

open 
container openInWorld.

restart
container delete.
Smalltalk garbageCollect.
TicTacToe new open.

*****************************************

SimpleButtonMorph subclass: #TicTacToeCell
instanceVariableNames: 'parentModel rowNum colNum'
classVariableNames: ''
poolDictionaries: ''
category: 'VK-Games'



initialize 
super initialize.
self label: ''.
self extent: 40@40.
self on: #click send: #value to: (self onClickExecutionBlock).
^self.



setModel: ticTacToeModel row: aRow col: aCol
parentModel := ticTacToeModel.
rowNum := aRow.
colNum := aCol.



onClickExecutionBlock
^[
(self label size) == 0
ifTrue:[
self label: (parentModel updateAtRow: rowNum 
                Col: colNum).
parentModel checkWinCondition.
self extent: 40@40.
].
 ]


***************************************** 

Matrix subclass: #TicTacToeModel
instanceVariableNames: 'filledCellCount currentFill winner'
classVariableNames: ''
poolDictionaries: ''
category: 'VK-Games'

initialize 
super initialize.
filledCellCount := 0.
currentFill := nil.
winner := nil.

updateAtRow: r Col: c
currentFill == nil
ifTrue:[ currentFill := 'X'. ]
ifFalse:[
currentFill == 'X'
ifTrue: [ currentFill := 'O'. ]
ifFalse: [ currentFill := 'X'. ]
].
self at: r at: c put: currentFill.
filledCellCount := filledCellCount + 1.
^currentFill.

checkWinCondition
filledCellCount >= 5 "for optimization. Win can occur minimum at 5th turn"
ifTrue: [
Transcript show: 'Yes'.
1 to: 3 do: [:idx |
self checkWinConditionInRow: idx.
self checkWinConditionInColumn: idx.
].
self checkWinConditionInDiagonals.
].
checkWinConditionInRow: rowNum
|set|
winner isNil
ifTrue: [
set := (self atRow: rowNum) asSet.
self checkWinConditionInSet: set
].
^winner.

checkWinConditionInColumn: colNum
|set|
winner isNil
ifTrue: [
set := (self atColumn: colNum) asSet.
self checkWinConditionInSet: set.
].
^winner.

checkWinConditionInDiagonals
|set1 set2 |
winner isNil
ifTrue: [
set1 := (self diagonal) asSet.
set2 := Set newFrom: {(self at: 1 at: 3). (self at: 2 at: 2). (self at: 3 at: 1)} asOrderedCollection.
self checkWinConditionInSet: set1.
self checkWinConditionInSet: set2.
].
^winner.

checkWinConditionInSet: aSet
aSet size == 1
ifTrue: [
(aSet includes: 'X')
ifTrue: [winner := 'P1'. Transcript open. Transcript show: 'Player 1 is the winner!!'.].
(aSet includes: 'O')
ifTrue: [winner := 'P2'.  Transcript open. Transcript show: 'Player 2 is the winner!!'.].
].



Friday, March 02, 2012

Find RSS Feed URL of a Webpage

Given a URL of a web page, one can programatically search through the meta tags of the webpage's content for alternate URL links (like atom or RSS feed links for the same) to thereon further use them to parse and process the content of the webpage. Typically this is the way Google Reader works. Here I present a very simple implementation of the same in pharo smalltalk.


Object subclass: #RSSReader
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'VamsiExperiments'


getURLContent: url
  "## Comment : Supply the url String of the webpage,
 
   ## example: http://nerdysermons.blogspot.in"
| urlContent |
urlContent := (url asUrl retrieveContents contents asString).
^urlContent



findAlternateLinksInUrlContent: urlContent
  "## Comment : The above fetched page content to 

   ## be passed here to get an ordered collection 
   ## of alternate links"      
| links|
links := OrderedCollection new.
urlContent linesDo:  [:line |
(line findString: '<link rel="alternate"') > 0
ifTrue: [
links add: (line findTokens:'"' includes: 'http://').
].  
].
^links.

Monday, December 05, 2011

Pharo Beginner : My first Smalltalk Program


DockingBarMorph new
  position: 0@225;

        addMorph: (SimpleButtonMorph new
                          label: 'Close';
                          target: [DockingBarMorph allInstances last delete];
     height: 55;
                          actionSelector: #value);

        addMorph: (SimpleButtonMorph new
            label: 'Open Transcript';
                          target: [Transcript open.
                                        Transcript show: '*** Default text in Transcript ***'
                                        ];
                          actionSelector: #value);

addMorph: (SimpleButtonMorph new
                        label: 'Open Browser';
     target: [Browser open.];
                        actionSelector:#value);

       addMorph: (SimpleButtonMorph new
                            label: 'New Workspace ';
                            target: [Workspace new open.];
                            actionSelector:#value);

addMorph: (SimpleButtonMorph new
                          label: 'Dock';
                          target: [UIManager inform: 'Hello world.. This is a sample Dock..'];
                         height: 55;
                          actionSelector: #value);
  openInWorld.


*************************

Tried to add up custom launchers for pharo development utilities. Currently implemented new Workspace open, System Browser, Transcript, etc.. Will have to make it complete so that the dock should be able to launch every component under the conventional right click popup in the pharo environment..

A simple pharo starter program which you can fiddle and extend, after a thorough understanding on ProfStef go.




Friday, December 02, 2011

Tutorial : List Operations in Python

#!usr/bin/python
""" All text within triple quotes is treated as comments in python """
""" This tutorial explains lists in python with the simplest operations as examples"""
""" Standard string concatenation using + operator """
""" Prints the message in a new line """
def printMessage(str):
print ">>>>> "+str
return


""" For loop : A similiar equivalent of each closure in groovy """
""" Note that indents are the only way to tell the interpreter about the blocks """
"""Also note that the below print it, prints elements in same line with space separated i.e a typical equivalent of System.out.print in java"""
def printList(aList):
for it in aList :
print it,
print
return



""" ********************** Start scripting : list operations ********************** """
list = [10, 1, 2, 3, 4, 5, 6]

"""*** Print the elements of the list *** """
list.append(9)
printMessage("Initial elements in the list : ")
printList(list)

"""*** add an element to the end of the list *** """
lastVal = 9
list.append(lastVal)
printMessage("Elements after appending a new element "+str(lastVal)+" at the end of the list : ")
printList(list)

"""*** insert element at index i *** """
insertVal = 8
indice = 7
list.insert(indice, insertVal)
printMessage("Elements after inserting : "+str(insertVal)+" at index : "+str(indice))
printList(list)

"""*** sort the elements ascending order by default *** """
list.sort()
printMessage("Elements after sort : ")
printList(list)

"""*** Reverse the elements : same as groovy *** """
list.reverse()
printMessage("Elements after reversal : ")
printList(list)

"""*** Removes the last element *** """
list.pop()
printMessage("Elements after removing last element : ")
printList(list)

"""*** Removes element at specified index *** """
index=3
list.pop(index)
"""Note the string cast below..A typical toString() equivalent in java"""
printMessage("Elements after removing element of index at : "+str(index))
printList(list)

"""*** Removes element with the value specified *** """
value=9
list.remove(value)
printMessage("Elements after removing the value : "+str(value))
printList(list)

""" *** number of times the element 1 occurs in a *** """
countFor = 1
printMessage("The number of times element : "+str(countFor)+" occurs in the list")
print list.count(countFor)

""" ****************** Some more looping and branch conditions ****************** """

""" *** Find the smallest element in the list using a typical for equivalent of eachWIthIndex groovy closure*** """
small = list[0]
smallestElementIndex = 0
for index, item in enumerate(list):
if item < small :
small = item
smallestElementIndex = index
print  "The smallest element of the list is "+str(small)+" at index "+str(smallestElementIndex)


""" *** While loop implementation *** """
printMessage("A simple while loop in python to convey : ")
sizeOfList = len(list)
i=0
while i<sizeOfList:
print "Python is fun \m/"
i = i + 1

--------------------------------------------------------------------------------------------------------------

Output for the above list operations performed :


>python -u "PythonBasicListOps.py"
>>>>> Initial elements in the list : 
10 1 2 3 4 5 6 9
>>>>> Elements after appending a new element 9 at the end of the list : 
10 1 2 3 4 5 6 9 9
>>>>> Elements after inserting : 8 at index : 7
10 1 2 3 4 5 6 8 9 9
>>>>> Elements after sort : 
1 2 3 4 5 6 8 9 9 10
>>>>> Elements after reversal : 
10 9 9 8 6 5 4 3 2 1
>>>>> Elements after removing last element : 
10 9 9 8 6 5 4 3 2
>>>>> Elements after removing element of index at : 3
10 9 9 6 5 4 3 2
>>>>> Elements after removing the value : 9
10 9 6 5 4 3 2
>>>>> The number of times element : 1 occurs in the list
0
The smallest element of the list is 2 at index 6
>>>>> A simple while loop in python to convey : 
Python is fun \m/
Python is fun \m/
Python is fun \m/
Python is fun \m/
Python is fun \m/
Python is fun \m/
Python is fun \m/
>Exit code: 0






Tuesday, November 22, 2011

Why Linked List is a Linear Data Structure?

Reminiscing my textbook definitions during graduation, all I ever read about linear data structures was that, they have elements placed adjacent to each other. Now, I curse myself for not being able to understand the inners of the concept rather than trying to perceive the whole thing at superficial level.

As I dig through this, I see that there are two aspects to the term linear. One is at the physical level (in bits and bytes of memory), other at the logical level (concerning the data structures used). At the logical level we talk about data structures as being linear or non linear. But in reality, at the physical level, computer memory is always linear i.e one memory block adjacent to other.

The concept of non linearity is (usually) implemented with the help of pointers that connect other memory chunks by storing their addresses. Technically, implementing pointers at the physical level is somehow helping us to understand non linearity at the logical level implementation of data structures. Assuming so, I was stumped at this point, wondering why a linked list is considered linear in spite of the nodes never being physically adjacent.

After an overwhelming head-breaking session, I started to see this differently. The terms linear and non linear are purely meant to be viewed at the logical level when used along side data structures. If a list is being used, irrespective of whether it is an array implementation or a linked list implementation, it should only be perceived as a data structure that stores elements adjacently (logically, abstract picture) and hence it is linear.

If the confusion still lasts, there is this thumb rule that you can take help of, to recheck if a data structure is linear or non linear. If you are required to sequentially traverse through all the elements of a data structure to access its nth element, then the data structure is linear. Else it is non-linear.

Example : Stacks, Queues, Lists are always linear. Irrespective of whether they are implemented using pointers or arrays, you need to sequentially traverse through the whole data structure to access the nth element which is not so in the case of trees and graphs wherein to access one element, traversing a specific branch might suffice.

Tuesday, November 08, 2011

Design Patterns : A prelude from a learner's viewpoint

“What do you understand about design patterns from the past nine months of code that you've written?”

This was the question put to me by my manager in today's meeting. The question was sudden and to be honest, I fumbled for words. I uttered few random sentences including the phrases “style of programming”, “the best way to apply a logic out of all available ways to do so”, etc. (which were pretty lame of course)


Now, I sit back in peace and try to fathom about design patterns based on my nine months of programming experience in the corporate world. When I try to rephrase the answer for the question, I find that I am really out of words to exactly describe what a design pattern exactly is, which is So in contrast with the ease with which the Gang of Four describes them to be.

From my understanding, I put it this way,

“A design pattern applied is THE possibly best fit (or the most optimized if not the best) approach that you adhere to while programming to find solution to a problem that you are trying to solve.” It is more generic a term and has got to do little or less with the specifics of a programming language used except for that it is widely used within the scope of Object Oriented Programming.

From what I understand, I believe and will continue to believe so, that, a design pattern is not limited to the few available standard textbook patterns like the factory pattern, singleton pattern, et al as suggested by the GoF. There can always be a pattern that is not a standard, is nameless and self defined, yet best suited for the task that you are working on. All the standard textbook patterns available can be safely regarded as hints to the problem you solve. Why I call it a hint more than the solution itself is that sometimes the pattern might just fit in so perfectly to a business scenario but sometimes it might not, Nevertheless it will take you closest to implementing a best solution to that problem.

My experience limits me to very few design patterns that I've worked with till date like the observer pattern, factory pattern, the yuckiest singleton pattern, etc but I guess this is what a design pattern is if you ask me, of course, from a noob's perspective.


Good that this post will not allow me to embarrass myself again by fumbling for words to phrase an answer when asked the same question and hopefully, at least in an year or two, I hope that I'd be in a position to answer any design pattern related question even in the midst of the midnight hour. Amen!


Monday, September 19, 2011

Serializing objects in Groovy

Never came across a more sexier way to serialize objects. Thanks to groovy goodness.


def map1 = ['1':'one']
def map2 = ['2':'two']

def file = new File("C:/serializedObjects.txt")

file.withObjectOutputStream { out ->
    out << map1
    out << map2          
}
                     
file.withObjectInputStream(getClass().classLoader){ ois ->
    ois.eachObject{
        println it                  
    }
}      

Friday, August 19, 2011

Build a Binary Tree & Perform an Inorder traversal



/*
* A simple groovy implementation to create a Binary Tree
* and to perform inorder traversal
*/

class Node{

    Node left, right
    int data
   
    Node(data){
        this.data = data
        left = null
        right = null
    }
}


class BTree{

    static def insert(Node node, val){
      if(val < node.data){
          if(node.left == null){
              node.left = new Node(val)
              println "inserting $val to the left of $node.data"
          }
         
          else insert(node.left, val)
      }
     
      else if(val > node.data){
          if(node.right == null){
              node.right = new Node(val)
              println "inserting $val to the right of $node.data"
          }
         
          else insert(node.right, val)
      }
     
    }
   
    //left, root, right
    static def printInOrder(Node node){
        if(node == null) return
       
        else{
            printInOrder(node.left)
            println node.data
            printInOrder(node.right)
        }
    }
}

//Shift to main if you aren't running this as a groovy script
def root = new Node(25)
BTree.insert(root, 10)
BTree.insert(root, 30)
BTree.insert(root, 24)
BTree.insert(root, 299)
BTree.insert(root, 266)
BTree.insert(root, 121)
BTree.insert(root, 920)

//Inorder traversal of the entered elements
BTree.printInOrder(root)


Wednesday, July 06, 2011

Programming Practices for the Corporate Developer


'A mediocre level in coding and proficiency in a programming language would suffice to develop an application'

Well, that was my mindset just post completion of my under graduation. Fortunately, it was blatantly proven wrong soon after I set foot into the corporate world. Technically, knowledge in programming is all one needs to develop a software application but in the corporate world, I've learned lately that the style of programming adapted is of more importance than that of programming itself. Here are few programming practices that are expected to be adapted by a software developer in the corporate world.

Design patterns

Perhaps the most important of all the programming practices is to strictly adhere to the standard design patterns available. We often come across such scenarios in the world of Object Oriented Programming where in multiple instance creation is a necessary operation yet it tremendously slows down the performance of the application. This is where design patterns come to rescue. For ex: Adapting a singleton design pattern would restrict the deliberate creation of unnecessary instances of an object. On the other hand adapting a design pattern like factory would efficiently handle multiple instances of an object that are too many yet necessary, so that selecting the appropriate instance of the same from the factory would be a lot easier than manually keeping track of the multiple instances. A programmer can always create his/her own design patterns too, adhering to which the re-usability can be exploited to the maximum enabling better performance of the application developed.

Naming Conventions

Naming conventions when considered petty or trivial can certainly lead to headaches while developing an application especially when there is scope for extensibility. A programmer must always be sensible enough to follow naming conventions, after all, he/she is not the only one dealing with the same piece of code in the corporate world. For example: Take a look at the creation of a java swing button with the name string 'Okay'.

JButton b = new JButton("Okay") //You suck buddy!!
JButton button = new JButton("Okay") //Duh!!! WTF ???
JButton okayButton = new JButton("Okay") // Hmm. Better!!

Hope it is clear from the above example! Never ever follow senseless or vague naming conventions. Nevertheless, a good piece of code will always be understood by any other programmer where as a bad code will never be.

Constant Refactoring

An application when developed from scratch starts off with a minimal set of classes and packages and it often grows so huge that it would be so damn difficult to manage the growing size and added functionality. So a programmer must make sure that the piece of code written must be made reusable to the maximum extent possible so that it can be further used again. Splitting up functionality into miniscule atomic functions specific to need would help a tonne. Further growing number of functions can again be refactored to different classes when one particular class gets cluttered with too many functions. And one level above, growing number of classes can further be split up under packages. Such constant refactoring code would make it easy for a programmer to rope in additional functional components and also the refactored code could be reused as well.

Ease of the programming vs performance of the application

Software applications when developed on dynamic languages are often susceptible to performance issues when the programming is deliberately done ineffective by a lazy programmer. For example: High end programming languages support dynamic binding that also adds to the ease of coding for a programmer. In one such instance, a programmer always has a choice to deliberately ignore mentioning the return type of a function so that it could be determined at run time later on. Such lazy programming practices can prove costly and lead to performance issues on a large scale considering the method's overall implementation. So a programmer must be intelligent enough to exploit the power of programming but never at the cost of the application's performance.

Considering that my experience in the IT industry is too less to talk more about better programming practices, the above are few things that the corporate world had taught me in the last couple of months. Hope that these few would help peers and the readers of this blog to code better in the corporate world.