Friday, May 02, 2014

Java 8 New Features: Lambda Expressions Part 1

Java is an object-oriented programming language which we all know very well but with Java 8 (released on 18th March, 2014) it goes functional. What does that means? Functional Programming was there way before Java came out but still Java adopted the object-oriented paradigm. Why? Well one simple answer to this is, its popular back then, Why Java wants to adopt Functional Programming now? Well again, simple answer to this question is Modern Hardware now runs more than one CPU Core and as a Programmer we should put them to good use rather then using a single core. Concurrent Programming provides us coarse-grained parallelization that helps Programmers to write code that can put all Cores to good use.

Still accessing a large collection of data is a sequential process well we can make parallel using concurrent programming but thats not an easy task to do at all and even we can't guarantee the performance gains, if any or our data is not in a fragile state or how to design such things that we can reuse it in other projects as well.

If every major Java release since Java 5 adds something to the Java Concurrency API, same way after Java 5, Collections API now makes it easy for accessing the collection of data either sequential or parallel.

Secondly, While doing Event-Driven Programming many of our object instantiation are done via ad-hoc Anonymous Inner Classes and if the code is big the amount of class files it generates with '$' sign is quite a mess. In case, a project deadline is near and there is still a lot of code to write, many developer(s) self question including me "Why the hell we have to write so much boilerplate code and we still achieve very less as compared to other programming languages which runs on the Java Virtual Machine (JVM) like Scala, Groovy etc.. and other which don't run on the JVM but still very less boilerplate code like Python etc.."

As discussed, Java is an object-oriented programming language with exception to having primitives at language level we can either pass an Abstract Data Type (ADT) or Primitives as parameters.
Lets start with a question that we should ask our self before we know whats really changed in Java 8.

Q What are interfaces in Java?

A Very simple answer to this basic question can be  "An interface is 100% Abstract Classes that can only declare abstract methods or may have constant(s)."

If you have plans to move to Java 8 or preparing for an interview etc.., then think once Again?

Interfaces are there since the beginning and even a person who is introduced to Java Programming Language was told the same thing. With Java 8, which is the biggest release after Java 5 has changed things (I won't say a little, you will see it in a bit) so its better to be aware of, what interface were before Java 8 and what they have become Java 8 onward.

So whats really changed in Java 8 with respect to interface?

A new keyword added to the language 'default',
Interface can have default, static and abstract methods,
abstract methods cannot have body but default, static methods have body,
If an interface contains only one abstract method, other than overriding method(s) of Object class as abstract are considered functional interface,
There is a new annotation added in the language, @FunctionalInterface, it's optional, i.e., you can either mark an interface with this annotation or you can leave it, as far as it comply to the definition of @FunctionalInterface, Java treats it as functional interface, whereas, if you mark an interface with the annotation and later on add another abstract method, you will get compilation error.

Things covered so far...

Till Java 7,

lots of boilerplate code,
sequential access to data inside a collection,
Not much of parallel computing (except concurrency API, provides coarse-grained parallelization),
Event-driven Programming is a mess,
Strong typing,
Either we can pass a primitive or ADT as a parameter

Java 8 onward,

concise syntax,
sequential/parallel access to data inside a collection - out-of-the-box,
fine-grained parallelization,
No more Anonymous classes while doing Event-driven programming
type inference,
Now apart from passing primitives or ADT as a parameter, we can do pass lambdas or "code-as-data" as parameters.

Lambda Expressions

Lets now start with an exercise where we can see how things are done till Java 7 and how its improved in terms of syntax, performance etc..

Sunday, June 02, 2013

Java Basics: Enum Types

JDK 1.5 a.k.a Tiger release marked the addition of two new reference types into the language. A special Kind Class called Enum Types and a new kind of interface called an annotation Types.
In this blog post we will discuss about the Enum Types and how it is better than the existing approach int and String Enum pattern that many of us used or may still be using in (pity on programmers as they are missing out better approach to handle things and making the project fragile in long run) there projects.

Note: Enum has been made a reserved keyword in 1.5 migrating your existing project on JDK 1.5 might break your existing code if anywhere you have used enum as a variable name.

An Enum allows a programmer to define fixed set of named constants such as the planets in the Solar System, Suits in the deck of playing cards or Days in a Week.

Points to Remember:

1. Enum Types over a period of time can evolve into a full-fledged abstraction.
2. Enum Types are by nature immutable, so all fields should be marked final they can be public but it’s better to make them private and provide them public accessors. 
3. Before Enum Types a common int and String Enum pattern was used by the programmer which has many shortcomings.

Before JDK 1.5 – Existing int Enum Pattern

public static final int Day_SUNDAY  = 0;
public static final int Day_MONDAY = 1;
public static final int Day_TUESDAY = 2;
…..

 Shortcomings in above approach:

     No Type Safety: Your compiler without warning you will compile even if you pass any int value instead of the predefined set of values.

       No Namespace: You must prefix constants (in this case Day_) to avoid any confusion/collisions in case you introduce a new pattern in your project in future.

      Fragile: As int Enum pattern are compile-time constants, they are compiled in the files those uses them. It requires recompilation of all those files that uses them if any changes made to them else it will result in unexpected behavior.

      Uninformative: These patterns won’t allow you to carry any addition details printing them will not tell you more than what value each of them are assigned even the type is not known whether it’s a int or a String. Even the iteration over all the declared values is not possible and there is no way to find out the exact no. of declared constants.

Enum Types not only overcomes the above mentioned shortcomings in the existing approach but adds much more functionality that one can expect from it. Many programmers are aware of Enum Types even before they were introduced in JDK 1.5 due to its presence in languages like C/C++. They look similar to their counterparts in other languages (i.e., in C/C++ or C#) where they are just fancy int values whereas Java Enum Types are Real Java Classes and are much more powerful thanks to the Compiler which makes it possible under the hoods with no burden on programmers.

Enum in its Simplest Form:

enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}

Enum Types are final by virtue, having no accessible Constructor and hence are purely instance-controlled. Enum Types cannot be extended, and an Enum Type cannot extend other class or enum as all Enum Types are subclasses of java.lang.Enum maintaining the single level inheritance but all Enum Types can implement interfaces.

Enum Types can either defined as Top-Level full-fledged class or it can be nested static member in another reference types.

Enum Provides Type Safety: You can assign an Enum one of the defined constant otherwise Complier Error is thrown.

Comparison: Comparing Enum Types using == or equals() will be same.

Informative: Each Enum Constant can override if required the toString() to provide any information they want.

Namespaces: Constants with same name can exist as all constants can be accessed using the Enum name which cannot be same.

No Need to Recompile: As Enum Types are not compiled into the classes which use them, so we can add/remove or reorder any enum constant without compiling all the files that uses it.

You can define fields or methods in an Enum Types as you do in a Regular Java Class.
With Enum Types the order in which you define the fixed set of named constants matter a lot.
Java.lang.Enum overrides methods from Object class and made a few of them final and it also implements interfaces like Comparable and Serializable that handles Comparison and Serialization for you automatically.

Enum can be a Top-Level Class or if it’s defined inside a Top-Level Class then it acts as a static member class of that Top-Level Class.

Inside an Enum Type you can declare an abstract method in that case we have to @Override the abstract method with a concrete one for each named constant using Constant-Specific Class Body. Such methods are known as Constant-Specific Method Implementations.

The toString() method in its default form will return the Constant Name which is same as calling the name() method but as toString() method is not final it can be Overridden either for whole Enum in which case every Constant will share the same value or it can be Overridden for a few if not all as well that way an Enum Types achieves Polymorphism like any Regular Java Class.

Iteration and Size of Enum can be known using the values() method. The values() method return an Array which you can use to iterate and using the length variable its size can be easily known.

As mentioned before Order in which the Constants are defined is very important as whenever the constants are iterated it can be iterated in the order it’s defined in the Enum.
ordinal() method returns an integer indicating the index at which the constant is placed.



I will update this post with more information and examples. EnumSet and EnumMap later. 

Hope this Helps!
Please leave your comments.

Saturday, June 01, 2013

Groovy Basics: Hello World Example

In Dynamic Language, always remember one Rule of Thumb.

* When you're unsure what type you want your Object, always use the 'dynamically typed' keyword.

In Groovy, def simply means 'dynamically typed'.

As the Groovy Site says a dynamic language for the VM you must always remember Groovy Syntax feels Dynamic whereas once it's compiled it's the same Class File that Java Compiler (javac) Generates as Groovy runs on the VM and VM doesn't have a support for dynamic language. You will find Groovy Syntax Much Clear and More Readable as you write less code.

A Groovy File can either Contain Scripts, Class Definition or both. I usually don't prefer mixing Scripts and Class Definitions in a same file. I will come to this later.

You can check one-liner on the Groovy Shell instead of writing a Script file.

On Console/Prompt Type:

groovysh // It will open a Groovy Shell.

groovy:000> println "Hello, World."
Hello, World.
===> null
groovy:000>

OR Simply,

groovy:000> "Hello, World."
===> Hello, World.
groovy:000>

You will see the shell doesn't exit after the execution instead it's asking for your input again. This is called REPL - Read Evaluate Print Loop. You can type exit, quit, \q or \x to exit the shell.

You can also use the groovy command instead of going into the shell.

groovy -e "println 'Hello, World.'"

Here, -e <script> specify a command line script.

You can write that line in a new file and save it as HelloWorldScript.groovy try to run it,

groovy HelloWorldScript.groovy

OR

groovy HelloWorldScript

A Groovy File can have any of the below mentioned extension. You can run the groovy command without extension in which case groovy will look for all the files in your CLASSPATH with one of the below mentioned extention and .class extention as well once it's found, it will execute that or will throw an error in case file with the same name doesn't exist in the CLASSPATH.

.groovy
.gvy
.gy
.gsh

The groovy command runs your code without generating .class files. If you use groovyc compiler to explicitly compile your files first and then run them using the groovy command. You can do it. What if you made changes to your groovy source file and forgot to compile them? What will happen? No Worries! The groovy command is smart enough to load and run the right files for you that means suppose you make any changes to your source file but forgot to generate the .class file using the groovyc command (groovyc). the groovy command will ignore the .class file present in the path and will run the source file instead.

Now, Lets write a first HelloWorld.groovy program using the class definition,

You might notice that there are no import statements, parentheses, package prefix or a semi-colon.
Point to Remember: Like Java imports java.lang.* package by default Groovy imports the following packages by default. groovy.lang.*, groovy.util.*, java.lang.*, java.util.*, java.net.*, java.io.* and classes java.math.BigInteger and java.math.BigDecimal.

Another Point to remember here that Script files don't have a main method but they are still executed, As Each Script file turned into a Java class with the same name as filename that extends the groovy.lang.Script which contains the main method so the runtime can execute it.

As, I discussed earlier not to mix Scripts and Class Definitions in a Single file. Here is why,

Let me explain if the above error is still not clear. What Groovy does here is when it sees a Script inside a source file, it tries to create a class with the same name as source filename which in this case is HelloWorld. Their is a class definition inside the source file which has a same name i.e., HelloWorld for which a class will be created but when it comes to the Script it will fail to create as the class HelloWorld already exist.

How to fix?

You can fix this either by changing the Source Filename or Change the Class Name to make it run. Always try not to mix the Class Definition and Script in a same file.

As, I mentioned above that you need a Java VM to run the Groovy code you can run them directly using the Java Command. All you require is a single Groovy Jar in your classpath.

Compile and Run

First you have to generate a .class file using the Groovy Compiler.

Window Users:

C:\GROOVY-DEMOS>groovyc HelloWorld.groovy

Linux Users:

$ groovyc HelloWorld.groovy

To Run,

Window Users:

C:\GROOVY-DEMOS>java -classpath %CLASSPATH%;%GROOVY_HOME%\embeddable\groovy-all-2.1.3.jar HelloWorld

Linux Users:

$ java -classpath %CLASSPATH%:%GROOVY_HOME%/embeddable/groovy-all-2.1.3.jar HelloWorld


Note: Never put the groovy-all-<VERSION>.jar in your classpath, it will effect the groovysh command. If you get an error while running the groovysh command make sure you don't have groovy-all-<VERSION>.jar in your classpath.

If you are looking for editors/IDE with Groovy Support try Sublime Text 2 or IntelliJ Idea.

Hope this Helps!
Please leave your comments

Running Java And Groovy on Windows And Linux

Groovy, Another Language that runs on Java Virtual Machine. It supports both Static and Dynamic Typing. If you haven't heard about this language till now. No Problems!

As, Groovy runs on VM so you must install Java first. Groovy doesn't require you to be a Java Programmer but some hands-on will help you learn it fast. Those who already have installed Java must set the JAVA_HOME Environment Variable. Here is how you do.

On Windows Machine:

Right-Click My Computer -> Properties -> In Windows XP (Advanced) | In Windows 7 (Advanced System Settings) ->  Environment Variable -> New

Here You will see Two Panes. If you select the New on the First One it will set User-Specific Setting i.e., Only the Currently Logged In User can use Java and Groovy.

If you Choose the New from the System Variables, It will be available to all the existing users as well all users that you create later. Choose what you prefer.

Note: System Variables already Contains PATH Key/value pair. Never remove the existing value instead append to it or you end you with an unstable machine. If you are unsure always create the NEW PATH Key/value in the First Pane that way you are sure that your System Settings remains untouched.

Create a New Variable anywhere you prefer.

Variable Name:  JAVA_HOME
Variable Value:  PATH\TO\JAVA\FOLDER\WITHOUT\SEMI-COLON\AT\THE\END

For Example: I have installed Java in C:\jdk1.6

Variable Name:  JAVA_HOME
Variable Value:  c:\jdk1.6 \\ Never put a Semi-Colon at the end.

Once Done Press OK.

Now Create one more Environment Variable. Again by Clicking New any place you prefer:

Variable Name:  CLASSPATH
Variable Value:  .;%JAVA_HOME%\lib;

Note: You must put a Semi-Colon at the End. Press OK. The Reason to put a Semi-Colon here is a good practice as you might in near future append a new library to your CLASSPATH just to separate one from another you put a Windows PATH Separator.

Again, If you are unsure which pane to choose for this one always prefer the first one and add the below Key instead of updating your existing System Variable PATH key in global/system settings that way it will remain untouched.

Variable Name:  PATH
Variable Value:  %JAVA_HOME%\bin;

Note: Never Override a Key's Value always append to it.

On Linux Machine:

There is a ~/.bash_profile that is a start-up script which generally runs once. People find it common place to add environment variables such as PATH, JAVA_HOME, create aliases, etc.

Please remember the file ~/.bashrc is similar but ~/.bash_profile runs for Bash Shell whereas, ~/.bashrc runs for every Bash Shell.

Similarly, You can setup for all users i.e., Global Settings to do so you need to add the following entries mentioned below in /etc/profile.

Fire your Terminal or Console: I'm using ~/.bash_profile you can choose what you prefer.

Type: $ vi ~/.bash_profile

export JAVA_HOME=/PATH//TO/JAVA/FOLDER/WITHOUT/COLON/AT/THE/END
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=.:$JAVA_HOME/lib

You have to logout and login back to see the new changes in effect. Alternatively you can type the below command to see the changes immediately.

$ source ~/.bash_profile

OR

$ . ~/.bash_profile

Always Remember always place Binary files i.e., files that are executable in the PATH variable irrespective you are working on Windows or Linux OS. CLASSPATH is for libraries.

Now it's time to download Groovy. Please head over to their Site to download it and all we need is to extract it and add/update some Environment Variables. The same way we did for Java.

Groovy Site: http://groovy.codehaus.org/

You need to Add a New Environment Variable.

Variable Name:  GROOVY_HOME
Variable Value:  PATH//TO/GROOVY/FOLDER/(IN WINDOWS WITHOUT SEMI-COLON OR IN LINUX WITHOUT COLON)/AT/THE/END

Append to PATH Variable,

Windows Users: %GROOVY_HOME%\bin;
Linux Users: $GROOVY_HOME/bin

Make sure that there is a Semi-Colon (Windows), Colon (Linux Users) at the end before you append these values to it. You can confirm this using the echo command which works on both windows and Linux.

Windows Users: echo %PATH%
Linux Users: echo $PATH

If it's not present you must provide it otherwise it will not work. For Example: Instead of doing $GROOVY_HOME/bin
you do :$GROOVY_HOME/bin.

Remember Colon is a Linux Path Separator whereas, Semi-Colon is Windows.

Now As all the installations are done now we head over to test if everything is working fine or not.

Windows Users, Please open Command Prompt close any if already Opened. Linux Users either use the source command to make the settings available to existing Console or login again.

Now, Before we proceed any further we must check our installation.

At prompt or Terminal or Console,

Type:

javac -version // To See if the Java Compiler is Working or not.
java -version // To See if the java execution environment is ready to run anything you throw at it.

groovyc -version // To See if the Groovy Compiler is Working or not.
groovy -version // To See if the Groovy execution environment is ready to run anything you throw at it.

groovysh -version // It's something that only Groovy had not Java. It can execute commands you throw at it. It's a REPL - Read Evaluate Print Loop.

groovyConsole // It's a GUI Version.

I hope you don't ran into any problem. Next Article is coming up on Groovy.

Hope this Helps!
Please leave your comments.

Thursday, April 18, 2013

Howto Use Java Comparator and Comparable by Example

In Java, there are some built-in methods that provides basic sorting of Primitive types array or Wrapper classes but what If we wanted to sort a custom class that we have written for use in one of our Projects? Well the answer is to write a sorting algorithm of our own and use it wherever it's required.

In Java, there are two interfaces that can help us achieve our goal. The reason the language provides two interfaces instead of one giving code developers enough flexibility to choose the one that they find suitable to their requirement.

The first Interface which I prefer to call is the Simple Handy Internal Sorter is available in java.lang.Comparable  . The Second Interface which I prefer to call is the Highly Flexible External Sorter is available in java.util.Comparator.

The former one is Simple and Internal as it needs to be implemented on the class itself and it's simple as it allows the code developers to write only single sorting implementation. The latter one is Highly Flexible and External that means it allows the code developer the flexibility to write as many as required sorting implementation for their custom class as it's declaration and implementation is in a separate class.

Let's start with the Below Example where Custom Class CarMake have both Simple Handy Internal Sorter and Highly Flexible External Sorter.

CarMake.java

As you can see below the Simple Handy Internal Sorter is already implemented on the Custom Class.


CarMakeComparatorAsc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.




CarMakeComparatorDesc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.


And, Finally the only thing required is to test both the implementation using a CarMakeSortTest.java.

CarMakeSortTest.java


I Hope this post helps you learn basics of Custom Class Sorting. Please do write your feedback...

You can download the complete code from Github

Tuesday, April 03, 2012

Favor Composition to Inheritance

As we all know Java is an Object-Oriented Programming Language. OOP was developed in first place to increase code reuse and maintainability.

The Myth

Programmers introduced to OOP Language(s) have a mindset that code reuse can be achieved only by Inheritance (extends) in Java. But are not aware of the alternatives even if they came across them.

For Example:

List<Car> carRef = new ArrayList<Car>();  //Generic List of Car References

Q.  Why Inheritance is considered bad?

A.  Experienced Programmers are aware of the fact and even the Design Patterns states the same using Inheritance across boundaries are considered bad as author of that library may change the internal implementation details which might break our abstraction that depends on it blowing up the whole stack.


Better Alternative - Prefer Composition to Inheritance




-------------------------
I will soon add more on this. Please do post your comments if your thinking differs from me. I will try to incorporate you questions/suggestion here so everyone has a better idea on this concept.


Hope this Helps! Please write your comments it will help me improve.



Sunday, May 22, 2011

Linux Basics Walkthrough Part 1

Nowadays, Linux comes with pretty simple to use GUI. Professionals still prefers CLI to perform there tasks as they know the mantra GUI is simple but CLI is powerful. Let's dig into the basis.

1. Navigation

cd - Change Directory. For Example: cd /home/karan

2. Where I'm
 
pwd - prints the current working directory.


3. Who I'm

whoami - Shows user who is currently issuing command.

4. Feel Secure

passwd - Allows you to change the password for the user who is issuing the command.

Note: passwd <username> Allows Super Users/Admins to change the password of other users.

5. Reading files

cat - Allows user to view content of a file.

P.S. I'll be updating this post soon with lot more commands.

Hope this Helps! Please write your comments it will help me improve.

Tuesday, March 01, 2011

Python Basics: Python Complex Numbers

Python supports Complex Numbers and are built-in to the language. You can create complex numbers either by specifying the number in (real + imagJ) form or using a built-in method complex(a, b).

Complex Numbers:
  1. For Electronic Engineers python uses j or J instead of an i for imaginary numbers.
  2. j or J means square root of -1.
  3. You can perform arithmetic operations on Complex Numbers.
  4. Both real and imagJ part are floating-point numbers.
  5. Complex Number has a nonzero real part.
  6. cmath library. (for your reference.)
(Post in your comments if i left out something important so i can add in here.)

How Complex Numbers Works.

  1 #!/usr/local/bin/python3.2
  2 # Filename: ComplexNum.py
  3
  4 # How Imaginary Number Arithmetic Works.
  5 print('1j + 1j :', 1j + 1j)
  6 print('3j - 1j :', 3j - 1j)
  7 print('2j * 1j :', 2j * 1j)
  8 print('2j / 1j :', 2j / 1j)
  9
 10 # complex(real, imagJ)
 11 print('complex(1, 1) :', complex(1, 1))
 12
 13 # Make Complex Numbers bit More Complex. Arithmetic on real and imagJ parts. :)
 14 print('3 * complex(2, 3) :', 3 * complex(2, 3))
 15 print('2j * complex(4, 6) :', 2j * complex(4, 6))
 16 print('(2 + 4j) * complex(4, 2) :', (2 + 4j) * complex(4, 2))
 17 print('(2 + 4j) * (4 + 2j) :', (2 + 4j) * (4 + 2j))
 18 print('complex(2, 4) * complex(4, 2) :', complex(2, 4) * complex(4, 2))

You can download the file here: ComplexNum.py

Output:

1j + 1j : 2j
3j - 1j : 2j
2j * 1j : (-2+0j)
2j / 1j : (2+0j)
complex(1, 1) : (1+1j)
3 * complex(2, 3) : (6+9j)
2j * complex(4, 6) : (-12+8j)
(2 + 4j) * complex(4, 2) : 20j
(2 + 4j) * (4 + 2j) : 20j
complex(2, 4) * complex(4, 2) : 20j

Explanation:
  1. Line #5 & #6 are pretty much self-explained.
  2. Line #7 2j * 1j = 2j^2. As we know that j here means square root of -1. Now j^2 equals -1. leads to the output of (-2 + 0j). As we know that a complex number has a nonzero real part.
  3. Line #8 2j / 1j = (2+0j). Complex Part division is a bit harder maybe or not. Because we need to multiply but top and bottom by what we call complex conjugate. This is what you get when you change the sign of the imaginary part but not the real part. 2j/1j * -1j/-1j, i.e, -2j^2/-1j^2. Minus signs cancels out we are left with (2 + 0j).
  4. Line #11 uses python interpreter built-in function complex(a, b). But the output has nothing much that i can explain.
I believe rest of it is more or less self -explainable. But if you think they need explanation post in your comments. :)

Hope this Helps! Please write your comments it will help me improve.

Monday, February 14, 2011

Java in Practice: Coding and UML Aggregation v/s Composition



Aggregation [ 'HAS-A' Relationship ]

class StereoSystem {
    private boolean state ;
    StereoSystem() {}
    StereoSystem(boolean state) {
        this.state = state ;
        System.out.println("Stereo System State: " + (state == true ? "On!" : "Off!")) ;
    }
}

class Car {
    private StereoSystem s ;
    Car() {}
    Car(String name, StereoSystem s) {
        this.s = s ;
    }
    public static void main(String[] args) {
        StereoSystem ss = new StereoSystem(true) ;  // true(System is ON.) or false (System is OFF)
        Car c = new Car("BMW", ss) ;
    }
}


In UML Aggregation is Expressed as


Composition [ 'Contains' Relationship ]

import java.util.Date ;

class Piston {
    private Date pistonDate ;
    Piston() {
        pistonDate = new Date() ;
        System.out.println("Manufactured Date :: " + pistonDate) ;
    }
}

class Engine {
    private Piston piston ;
    Engine() {
        piston = new Piston() ;
    }
    public static void main(String[] args) {
        Engine engine = new Engine() ;
    }
}

In UML Composition is Expressed as 






I originally posted this here: http://www.coderanch.com/t/443002/java/java/Java-Coding-UML-Aggregation-Composition


Hope this Helps! Please write your comments it will help me improve.

Python Basics: Built-in function abs usage

First of all Built-in functions are those functions that are available to us all the time without importing any python modules. Today we'll see how to use abs(x) function.
So, Let's get Started:
abs(x) function takes an argument that can be a integer or a floating point number. It returns you the absolute value of a given number. A argument can be complex number, in that case the magnitude is returned.
Simple Case:

Let, say if x is less than zero, i.e, x < 0, than -x is returned. Otherwise, if x is greater than or equal to zero, i.e, x >= 0, than x is returned.

Complex Case:

Let, say if x is complex, than in that case abs returns a square root of  x.imag**2 + x.real**2 (a.k.a magnitude) of a number.

We'll be discussing complex numbers in another post. But in any case the formula to compute them remains same.

Hope this Helps! Please write your comments it will help me improve.

Saturday, February 12, 2011

Fix: Weblogic ServletContext.getRealPath() returns null

Weblogic Server[WLS] returns null if your code is using Servlet.getRealPath() many of you expect that it's another weblogic server bug but it's not. An application can be deployed in two ways either exploded or archive. If you are deploying an application as exploded which is a folder containing your application you won't see such an error. But, if you deploy it as an archive which is like zipping the folder having extentions like war, ear etc.  you will see this error, and mostly we prefer to deploy our applications as archive rather than exploded. So, how to fix such an error.
So, Let's get started
Note:  The advantage of deploying an application as exploded over archive is the access to the application content is much faster.
It's a simple fix. You can fix this problem by approaching it in two ways one is application server level. The other is application level.

Application Server Level

Goto Server Admin Console > Domain > Web Application > Archived Real Path Enabled. Enable this option restart the server and Bingo.!!!

It makes an entry into domain config.xml file something like this,

<web-app-container>
    <show-archived-real-path-enabled>true</show-archived-real-path-enabled>
</web-app-container>

Application Level

Create a xml file in WEB-INF folder name it weblogic.xml if it's not there by default. Add the following entry.

<container-descriptor>
    <show-archived-real-path-enabled>true</show-archived-real-path-enabled>
</container-descriptor>

Redeploy your application done.

Hope this Helps! Please write your comments it will help me improve.

Wednesday, February 09, 2011

JSF2.0: Unable to load JSF2.0/Primefaces jars on Weblogic Server 10.3.2 start up

I think except for the option to upgrade to a new version or applying a patchset there is a workaround that i tried and it worked for me.

Problem
It occurs because weblogic 10 is shipped with Mojarra JSF 1.2 and the version that we want to make it work is Mojarra JSF 2.0.

Solution
It's a simple fix. In weblogic there is a file called commEnv.bat/sh. If you are running windows edit the bat file, else if you are running Linux/Mac edit the sh file.

Search for PRE_CLASSPATH or WEBLOGIC_CLASSPATH and add a complete path to the jsf-api.jar, jsf-impl.jar before weblogic.jar and if you are using Primefaces, just append it afterwords. Restart the server, deploy your application make sure that jsf-api.jar and jsf-impl.jar are there in the lib folder, but you are now free to remove the primefaces jar as it is already loaded by weblogic at server start-up otherwise you will see the same error still your application won't break.


Topic Discussed
http://forums.oracle.com/forums/thread.jspa?threadID=1043858&start=30&tstart=0
http://www.coderanch.com/t/486434/JSF/java/Unable-load-primefaces-jar-Weblogic

Hope this Helps! Please write your comments it will help me improve.

Tuesday, February 08, 2011

Python Basics: Built-in function Print usage

Before embarking on a journey to learn any programming language most people create a sample Hello World application to see how the language works. Today we are going to learn this only with a variation of how you use it's in-built print function.

So, Let's get started.
I'll be using vim to write programs and python 3.2 to run it. If you are using windows prefer python IDLE which comes bundled with python.

1. Source Code: Vim 












Explanation:
1. The first line of the code is called the shebang line
2. Line 2 is a comment.
3. Line 4 uses the built-in print function to print the string on the standard output on screen.
4. Line 5 uses a variation of the function.
5. Line 7 is a comment
6. Line 9 has nothing special
7. from Line 10 onwards it shows you the variation of how to use the print function.
Before i explain you line no 10, 11 and 12 i want you to look at the definition of the function itself.
print([object...][, sep=' '][, end='\n'][, file=sys.stdout])
sep and end keyword arguments take a string and if nothing is given the defaults are taken and for last file keyword takes a file object and how it works is explained in Line 12. You might have noticed the output. It doesn't print out line 12 on the screen instead it writes that line to a file specified pybuf.txt. Here, open function returns you a file object and it is defined as follows.
open(filename, mode)
Both of them are strings. I'll explain open function later in detail except the filename is name of the file to be created if not existed and mode is set to 'a' which means append text to the end of a file.

2. Output: Python 3.2












3. pybuf.txt file





Monday, February 07, 2011

Install Python 3.2 on Linux [Ubuntu]

First of all, I don't see a point to show you how to install Python on Windows. It's dead easy download the installer from python.org and in few clicks you will have python up and running. Installing Python on Linux is bit different and requires some pre-work to be done.

So Let's get started.
Note: Every Modern Linux had a python Installed. You can verify this by opening your Terminal and typing python. It will open the python shell for you. Do not remove the installed version.
Step 1: Pre-requisites for Ubuntu

To be able to compile Python Source, you will need few packages. Fire up the terminal and execute this command
sudo apt-get install build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev
It will take some time to finish depending upon your bandwidth. :)

Step 2: Downloading Python Sources and extracting them on your disk

Download a tarball from the python site here is a direct link. Once, the download is completed you can extract the files by doing a right-click on the file and then clicking the extract option
OR
Fire up the terminal and execute this command which will download the file first and extract it on the disk.
wget http://www.python.org/ftp/python/3.2/Python-3.2rc2.tgz && tar -xvf Python-3.2rc2.tgz
Step 3: Installing Python 3.2

Fire up a new Terminal and execute the following commands individually.

1.   ./configure
2.   make
3.  sudo make altinstall

Hope this Helps! Please write your comments it will help me improve.