Pages

AngularJS Overview

Well, I am no expert in angularjs and its not a post where you will learn some new techniques in angular if you are an expert or you have already done some work in angular. This post will briefly describe the overall concept of AngularJS and the general things you do in angular and why you do it.

What is it?

AngularJS is a framework built on top of Javascript. Now, javascript is a browser scripting language and is very widely used because its the only scripting language supported by all the major browsers and almost all the modern web applications do not function without Javascript. AngularJS is a framework which make is much easier to do the general things, what we achieve by writing a lot of javascript.

Difference between Angularjs and Javascript or JQuery

Basically, we write very little code and achieve more in angular then we can using javascript or Jquery alone. The most common features of event handeling, and view changes are built into angularjs and we can plug it in the page with very less effort.

Architecture

AngularJS uses MV* design pattern. It has a two way binding between model and view. That means, if one changes, the other automatically changes. We include the angularjs file in the html, and then write the module and the controllers. Inside controllers, we have access to the scope, services and other things where we write our logics and variables. We can build a model from the servers data as well. 

Post Redirect Get pattern in Web application and Spring.

In Web application, we are aware that there are two ways of submitting data from browser to server through a form. Post and Get.
Now, what the Post Redirect and Get pattern advocates is that, it is not a good idea to display a page in a web application on POST requests. One most common problem is re-submit. Imagine a very delicate application, where one post method causes a lot of vital state changes in the server which might worth millions of dollars. Not just because of some load issue the client might refresh the browser and run into trouble. We as a web application developers could not rely on browsers alert warnings of re-submission.

Solution.

The post method should do the state change, put some parameters in the session, and do a get:redirect to another function or page which should display the attributes. Ideally, after being displayed, the session attributes should be erased from the session as the session is consuming memory and other resources which might grow.

Spring provides a very efficient solution to the problem with Flash attributes. What you do is handle the post request to one method, put the attributes in the flash attributes, and redirect the page to the get request in another method(possibly with same url), which will redirect it to a jsp file which displays the attributes.

    @RequestMapping(value="/submit", method=RequestMethod.POST )
    public String submit(Calculator calculator, Model model, 
     RedirectAttributes redirectAttributes) {
 
 List<String> errors = calculatorValidator.validate(calculator);
 
 redirectAttributes.addFlashAttribute("form", calculator);
 redirectAttributes.addFlashAttribute("errors", errors);
 
 return "redirect:submit";
    }
 
    @RequestMapping(value="/submit", method=RequestMethod.GET)
    public String get(){
 return "CalculatorForm";
    }


Java multiThread application | join method

Join method is used in java to wait until a child method is finished executing.

Scenario

Suppose you have to read multiple files from the os and put it into different list. You could create a runnable class that could read a file and store it in its own list. Now, the main could create multiple threads from this class in which case, the main class has to wait until all the file reading threads are finished running, so that it could run its own logic or algorithm. The object method join comes in handy in this scenario. Join method waits the current thread until the called method is finished executing.

Apache Spark and Big data

Apache spark is one of the latest projects from apache that makes it really easy to write Map reduce tasks both in single cluster and multiple cluster mode. I have not tried multiple cluster, but as per the documentation, all it required is some configurations.

Installation

All you need is JDK installed in your machine.

Apache Spark does not need any installation on single node local mode. It is available in many languages like java, python, scala . I am using Java for my case.
Create a Maven Java Project and add the following dependencies in your pom.xml file.
<dependency>
 <groupId>org.apache.spark</groupId>
 <artifactId>spark-core_2.10</artifactId>
 <version>1.3.1</version>
</dependency>

If you are creating a non-maven project, just download the spark-core_<version>.jar file and add it to the projects build path. Then search in the internet and try one of the word count examples. You can run the class directly from eclipse, which case it will expect the file in your local filesystem.

You can also download the compiled version of spark and extract it in your directory and then use that to run your project. In this case, you need to package the classes in your project, and hit the command.

spark-1.3.1-bin-hadoop2.6/bin/spark-submit --class com.spark.WordCount --master local[2] ./target/ApacheSparkExample-0.0.1-SNAPSHOT.jar ipsuminput/*.txt ipsumoutput


The spark will expect the input and output locations to be in the HDFS in this case.

Map and Fold | Basics

Map and fold is a different approach of solving a problem then we normally do in our daily computations.

Basic steps

  • The problem basically is a list of some values(eg a number array), and we have to do some operation on it to get the output.
  • There is a mapper f(x) which takes one value at a time, and creates another value as its output. The created value may be same or different depending upon the required result.
  • The Fold(g(x,y), I) function takes a function g(x,y) and an initial value I.
  • Given a problem in Map and fold, as a solution, we have to find the 
    • function f(x), 
    • function g(x,y), 
    • initial value I, 
    • And the interpretation of the final result.

A beginners program in JavaFx

Before code

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Main extends Application {

Java 8 Features | stream processing and lambda expressions

There are lots of programming languages in the world today, and some of them are quiet popular. Each language has their own features, syntax and rules. There is one method of programming called functional programming, where you declare what do you need rather then how do you do it. Lots of languages has these features, for example python, bash, c#. In spite of being one of the most popular languages, java has been behind in putting stream processing and lambda expressions into itself for almost four years and finally it did it.

Below are some of the code examples of stream processing and lambda expressions combined that, if you were unfamiliar with it, you will be blown away.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

public class BiFunctionExample {

 public static void main(String[] args) {
  biFunctionStringConcat();
  biFunctionExample();
  byFunctionFilterExample();
 }
 public static void byFunctionFilterExample(){
  List<Double> lst = new ArrayList<Double>();
  lst.add(2d);
  lst.add(200d);
  lst.add(6d);
  lst.add(60d);
  lst.add(122d);
  lst.add(876d);
  lst.add(738d);
  lst.add(333d);
  lst.add(112d);
  lst.add(98d);
  lst.add(0d);
  lst.add(3d);
  lst.add(1d);
  lst.add(6666d);
  
  List<Double> resultList = lst.stream()
   .sorted()
   .filter( x -> x > 20d )
   .collect(Collectors.toList());
  
  Double sumResultList = resultList.stream().reduce(0d,  Double::sum);
  Double max = resultList.stream().max(Comparator.comparing(x -> x)).get();
  String plusItems = resultList.stream()
    .map(x -> x.toString())
    .reduce((x, y) -> x + " + " + y)
    .get();
  
  System.out.println(resultList);
  System.out.println(plusItems);
  System.out.println("Sum = " + sumResultList);
  System.out.println("max = " + max);
 }

 public static void biFunctionExample() {
  BiFunction<Double, Double, List<Double>> bi = (x,y) -> {
   List<Double> list = new ArrayList<Double>();
   list.add(Math.pow(x, y));
   list.add(x * y);
   return list;
  };
  
  System.out.println(bi.apply(2d, 3d));
 }
 
 public static void biFunctionStringConcat(){
  BiFunction<String, String,String> bi = (x, y) -> {      
        return x + y;
      };

      System.out.println(bi.apply("rajan", " upadhyay"));
 }
}



Enjoy!!

Creating a simple Class Diagram

Question

Write a program that calculates the cost to send packages within the US. There are 3

different ways to send a package:

Multiple Inheritance in java

Its obvious that there are lot of problems related to ambiguity in multiple inheritance. While C++ found a solution to the problem, java decided not to go with multiple inheritance. Instead, they have a different way of doing it. Before implementing multiple inheritance equivalent in Java, you need to be familiar with a few terms.

Inheritance : It is the case when a child class extends a parent class. This is a "is a" relation.

Association: It is the situation where a class may have one or more objects of another class. There is a "has a" relationship between one object to another. The association may be strong when deleting the main objects automatically deletes the other objects as well. While if the other objects still have some value without the main object, such association is called weak association.

Rajan Array

. A Rajan array has the following property.
   a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...
The length of a Rajan array must be n*(n+1)/2 for some n.

Write a method named isRajanArray that returns 1 if its array argument is a Rajan array, otherwise it returns 0. If you are programming in Java or C# the function signature is
   int isRajanArray(int[ ] a)

If you are programming in C or C++, the function signature is
   int isRajanArray(int a[ ], int len) where len is the number of elements in a.

Examples
if a is
return
Reason
{2, 1, 1}
1
2 + 1 + 1
{2, 1, 1, 4, -1, -1}
1
2 = 1 + 1, 2 = 4 + -1 + -1
{6, 2, 4, 2, 2, 2, 1, 5, 0, 0}
1
6 = 2 + 4, 6 = 2 + 2 + 2, 6 = 1 + 5 + 0 + 0
{18, 9, 10, 6, 6, 6}
0
18 != 9 + 10
{-6, -3, -3, 8, -5, -4}
0
-6 != 8 + -5 + -4
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -2, -1}
1
0 = 0 + 0, 0 = 0 + 0 + 0, 0 = 0 + 0 + 0 + 0,
0 = 1 + 1 + 1 + -2 + -1
{3, 1, 2, 3, 0}
0
The length of the array is 5, but 5 does not equal n*(n+1)/2 for any value of n.



Solution:



int isRajanArray(int[] arr){
 
 int sumLength = 0;
 
 for(int i=1; sumLength < arr.length; i++){
  sumLength += i;
 }
 
 if(sumLength != arr.length){
  return false;
 }
 
 //logic to check the sum
 int sum = arr[0];
 
 sumLength = 0;
 int index = 0;
 
 int sum2 = 0;
 for(int j =1; sumLength < arr.length; j++){
  sum2 = 0;
  
  for(int k=0; k<j; k++){
   sum2+=arr[index++];
  }
  if(sum != sum2){
     return false;
     }
 }
 
 return true;
 
 
}

Enjoy

Prime count between two numbers | java

I was facing an algorithm problem where I have to find the total number of integers between two given integer. The two integers (start, end) count be any integer where start < end and they are both positive integers.

So here's what i did.

public static int primeCount(int start, int end){
  
  int count = 0;
  int mod = 0;
 
  firstloop:
  for(int i=start; i<=end; i++){
   
   if(i<=1){
    continue;
   }else if(i==2){
    count++;
    System.out.println(i);
    continue;
   }
   
   //secondloop:
   for(int j=2; j<=(int)(i/2); j++){
    mod = i % j;
    //System.out.println(i + "%" + j + " = " + mod);
    if(mod==0){
     //count++;
     //System.out.println(i);
     continue firstloop ;
    }
   }
   count++;
   System.out.println(i);
  }
  
  return count;
 }

one interesting thing here what is used is the labeled break continue feature of java which even many experienced professionals do not normally remember. You count specify the label in the break or continue statement to target which for loop you want to break or continue.

So you learned new thing. Enjoy..

Wonderful world of CSS Sprites

http://www.smashingmagazine.com/2009/04/27/the-mystery-of-CSS-sprites-techniques-tools-and-tutorials/

Portfolio in the web| Things to learn

http://www.adhamdannaway.com/blog/web-design/imitation-truly-is-the-sincerest-form-of-flattery

Reverse search in shell

I didn't know about it earlier. So I thought of writing about it.

If you are or shell user, there have been some situations where you have solved some problems with some shell commands. Then you remember only a part of the command and when you need the same command again, you can't remember exactly what the command was. Well, this is for people like you.

Reverse search helps you find the command you have typed in the past, with a little bit of help from you. It takes small fragment of command how much you remember, and suggests similar command you have applied in the past.

How to use it?

  • Press Ctrl + R in the shell
  • Type how much of the command you could remember
  • Use the arrow key, or Ctrl + R again to find the correct command
  • Press Enter finally when you found it.
  • Press Ctrl + G to get out of the search mode.

How to share files in virtualBox | Ubuntu Host and Ubuntu Guest

I was running a virtual machine Ubuntu12.04 in the host operating system Ubuntu12.04. In the virtual machine my development environment was already set and I want to set the same environment in the actual host operating system. The problem was that, I could not share some installation files from Guest operating system to the Host.

For this I did the following things.

  • Create a folder named "share" in the home directory.
  • Right click "Properties->share"
  • Install whatever software it prompts to install(samba server)
  • Then start the virtual machine instance
  • select Devices->Shared folders

Grails | Introduction

Grails is the latest technology which runs over JVM and is getting quiet popular. Actually I tried the very basics of this technology and I am impressed. Its very easy to get started with grails.


Spring Boot | An introduction

I was talking with my friends regarding some of the technologies we have been using in our jobs as a software developer. There I heard about Spring Boot. Best way to know about it is to go through its official documentation, each page. But, that takes some time. And even, some in-experienced people may not understand it fully. So I thought I would write the summary of what it actually is.

Resize the Virtual Disk Hard Drive Size | VirtualBox

Reference  http://derekmolloy.ie/resize-a-virtualbox-disk/

First shut down the instance.Then from the command prompt hit the following command

VBoxmanage modifyhd MyLinux.vdi --resize 20000

The output of this is
0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%

The above command changes the virtual capacity of the .vdi file to 20GB.

Now comes the real problem. Only the virtual size is changed to 20GB. The real size of the partitions inside the image is still the same. You need to extend the partition manually. The added space is there but in the state of unallocated space which could be confirmed by the command
df -hk

To extend the size of the partition (/dev/sda1), do the following steps.

  • Go to the site  http://gparted.sourceforge.net/livecd.php
  • Download the GParted Live on CD ISO file and save it in the disk.
  • In “VirtualBox” Create a new virtual machine and call it “GParted” with Type: “Linux” and Version “Linux 2.6″ or whatever version. Choose “Do not add a Hard Drive” and ignore the warning.
  • Pick the Gparted(Power Off) and click "SETTINGS".
  • Choose “Storage” and under “Controller: IDE Controller” add a new CD/DVD device. Browse to the location of your GParted ISO file and select it.
  • Then add the disk that you wish to resize under “Controller: SATA Controller”.
  • Press OK and start your GParted Virtual Machine and you should see it boot (very quickly). Choose Gparted Live (Default settings). Choose all the default settings and your language of choice. Press 0 to start X
You can see the unallocated space in the screen after the GParted has booted completely.
  • Select the swap (/dev/sda2) and delete that. Press Apply
  • Choose /dev/sda1 and click resize.
  • leave a free space of 1023 at the end. Allocate all other space for main partition. Then click apply. It might take some time.
  • Now re-add the swap space. Click the unallocated space. Right click "Add new partition" as "Extended partition" . Apply.
  • Press “+Add” and right-click the new “unallocated” to Create a new partition. Choose as “Create as: Logical Partition” and underneath “File System: linux-swap”
  • Press Apply. shutdown the Gparted and reboot the linux.

The rule of Three to build reusable software components

http://blog.codinghorror.com/rule-of-three/