Month: March 2018

  • Polymorphism in Java – OOP – Code Example

    In previous posts we have discussed many important topics of object oriented programming like classes, objects, inheritance etc. In this post we will discuss polymorphism in Java which is another important OOP concept.

    What is Polymorphism in Java?

    The word polymorphism means ‘a state of having many shapes’. In terms of object oriented programming it’s the ability to process objects of various types and classes through a single uniform interface. An object, variable or function may take on multiple forms / shapes and this phenomenon is known as Polymorphism.

    Example of Polymorphism in JAVA:

    [js]

    public int add(int a, int b){

    return a+b;

    }

    public int add(int a, int b, int c){

    return a+b+c;

    }

    [/js]

    In above example we can see that the add function have 2 shapes/forms with varying number of input arguments. This is an example of Polymorphism.

    Types of Polymorphism in JAVA:

    There are two types of Polymorphism in JAVA namely static polymorphism and dynamic polymorphism.

    Static Polymorphism in JAVA:

    Static polymorphism is achieved through method overloading and is also known as compile time polymorphism or static binding. At compile time JAVA decides which method to call by checking the signature/prototype of the method. Following code example will make the concept clear.

    [js]

    //file name is Calculate.java

    Class Calculate{

    public int addNumbers(int a, int b){ //method 1

    return a+b;

    }

    public int addNumbers(int a, int b, int c){ //method 2

    return a+b+c;

    }

    public int addNumbers(double a, int b){  // method 3

    return (int)x+y;

    }

    }

    //main class Main.java

    Class Main{

    public static void main(String[] args){

    Calculate c1 = new Calculate();

    System.out.println(c1.addNumbers(4+5));   // method 1 will be called

    System.out.println(c1.addNumbers(4.5+16));  // method 3 will be called

    System.out.println(c1.addNumbers(3+6+12));  // method 2 will be called

    }

    }

    [/js]

    Dynamic Polymorphism in JAVA:

    Dynamic polymorphism is achieved through method overriding and is also known as dynamic binding or late binding. Let’s say parent class (Human) has a method named as run() and child class (Student) overrides that method run(). Now considering the class reference Java decides which method to call. Following example will elaborate the concept.

    [js]

    //Human class: Human.java

    Class Human{

    public void run(){

    System.out.println("Human is running");

    }

    }

    //Student class: Student.java

    Class Student extends Human{

    public void run(){

    System.out.println("Student is running");

    }

    }

    //Main class: Main.java

    Class Main{

    public static void main(String[] args){

    Human h1 = new Human();

    h1.run();    // prints ‘Human is running’

    h1 = new Student();   // polymorphism

    h1.run();  // prints ‘Student is running’

    }

    }

    [/js]

    In above example h1 is an object of Human class so when we called the run() method Java will call the run() method of Human class. Then we changed the h1 object’s reference to Student class (new shape/form which is polymorphism). Now Java will call the run() method of Student class because now the object’s reference is changed to Student class.

  • IS-A and HAS-A Relationships in Java – Code Example

    Code reuse-ability is the fundamental objective of object oriented programming. To achieve code reuse-ability objective, we use IS-A, HAS-A relationships. IS-A relationship is another name of inheritance or we can say that IS-A relationship is achieved through inheritance.

    In inheritance child class can inherit attributes and methods from its parent class. For example we have a Student class which inherits from Human class then it means that it follows the IS-A relationship because a Student IS-A Human. Further it should be noted that a Student IS-A Human but a Human may not be a Student. It means that child class can inherit attributes and methods from parent class but parent class cannot inherit attributes and methods from child class.

    Another way to achieve code reuse-ability objective is to use HAS-A relationship. In HAS-A relationship, we create instance of the class inside another class so that we can use the attributes and methods of that class. Following example code will clear the idea.

    [js]
    //RelationshipDemo.java which is the main class
    package relationshipdemo;
    public class RelationshipDemo {
    public static void main(String[] args) {
    // TODO code application logic here
    Student s1 = new Student();
    s1.setCNIC(1234);
    s1.getCNIC();
    s1.setRegNo(456);
    s1.getRegNo();
    s1.getAttendanceDate();
    }
    }

    //Human.java class

    package relationshipdemo;
    public class Human {
    int cnic;
    public void setCNIC(int x){
    cnic = x;
    }
    public void getCNIC(){
    System.out.printf("CNIC is: %d", cnic);
    }
    }

    // Student.java class

    package relationshipdemo;
    public class Student extends Human { // implementing inheritance i.e IS-A relationship
    int regNo;
    public void setRegNo(int y){
    regNo = y;
    }
    public void getRegNo(){
    System.out.printf("Reg No is: %d", regNo);
    }
    public void getAttendanceDate(){
    Attendance a1 = new Attendance(); // creating instance of Attendance class i.e HAS-A relationship
    a1.setDate(23);
    a1.getDate();
    }
    }

    // Attendance.java class

    package relationshipdemo;
    public class Attendance {
    int date;
    public void setDate(int z){
    date = z;
    }
    public void getDate(){
    System.out.printf("Date is: %d", date);
    }
    }
    [/js]

    OUTPUT:

    is-a and has-a relationship in java

  • Code Example To Generate Word Cloud Using R – Data Analysis

    Word cloud help us to understand and visualize important keywords in given textual data sets. R is a powerful programming language used for exploration and visualization of data. Following code snippet can be used to generate word cloud using R programming language.

    [js]

    install.packages("tm") // package for text mining
    install.packages("wordcloud") // to generate word cloud
    install.packages("RColorBrewer") // to add colors in the word cloud
    library(tm)     // loading tm package
    library(RColorBrewer) // loading RColorBrewer package
    library(wordcloud) // loading wordcloud package
    text_data <- read_csv("data.csv") // reading data from csv file
    text <- text_data$col_name      // extracting data from column ‘col_name’
    text_corpus <- Corpus(VectorSource(text)) // creating corpus from textual data
    inspect(text_corpus) // to view the corpus data

    toSpace <- content_transformer(function (x , pattern ) gsub(pattern, " ", x)) // it will replace given pattern to space
    formatted_text <- tm_map(text_corpus, toSpace, "/")   // replacing ‘/’ with space
    formatted_text <- tm_map(text_corpus, toSpace, "@")  // replacing ‘@’ with space
    formatted_text <- tm_map(text_corpus, toSpace, "\|")  // replacing ‘\|’ with space
    formatted_text <- tm_map(formatted_text, tolower)  // converting text to lowercase
    formatted_text <- tm_map(formatted_text, removeWords, stopwords("english")) // removing stopwords
    formatted_text <- tm_map(formatted_text, removePunctuation) // removing punctuation marks
    formatted_text <- tm_map(formatted_text, stripWhitespace)  // removing white spaces

    // following functions create table containing the word frequencies

    text_tdm <- TermDocumentMatrix(formatted_text)
    text_m <- as.matrix(text_tdm)
    text_v <- sort(rowSums(text_m), decreasing = TRUE)
    text_d <- data.frame(word=names(text_v), freq = text_v)
    head(text_d, 10) // visualize first 10 entries

    set.seed(1234)
    // following function actually creates the word cloud
    wordcloud(words = text_d$word, freq = text_d$freq, min.freq = 1, max.words=200, random.order=FALSE, rot.per=0.35, colors=brewer.pal(8, "Dark2"))

    [/js]

    Word Cloud using R

  • Useful R Packages for Data Analysis

    R is a powerful programming language used for exploring and analyzing data effectively. R provides many built in functions for data analysis. Furthermore there are many other R packages for data analysis which can extend the data analysis functionality. Following are some useful R packages which can be installed for specific tasks.

    Twitter Data Analysis:

    //rtweet.info

    install.packages(rtweet)

    Text Mining:

    install.packages(“tm”) // for text mining

    install.packages(“SnowballC”) // for text stemming

    install.packages(“wordcloud”)  // word-cloud generator

    install.packages(“stopwords”) // for multilingual stop words

    Colors:

    install.packages(“RColorBrewer”) // to add colors

    Visualization:

    install.packages(“ggplot2”) // for data visualization functions

     

  • Useful R Functions – Exploratory Data Analysis

    R is a programming language used for statistical analysis and exploratory data analysis projects. According to the official website:

    R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment which was developed at Bell Laboratories (formerly AT&T, now Lucent Technologies) by John Chambers and colleagues. [source]

    Following are some useful R functions which can be used for data exploration and visualization.

    To read data from CSV file:

    data_obj <- read_csv(“data.csv”)

    In above line data_obj is the object name in which your data will be saved, data.csv is the file name from which the data will be extracted.

    To get frequency of unique column values:

    some_variable <- as.data.frame(table(data_obj$col_name))

    In above line some_variable is the variable name in which you want to save the new data, data_obj is the object in which your raw data is saved, col_name is the column name in your raw data.

    To sort the data in Highest to Lowest (Descending Order) values in a column:

    sorted_values_descending <- data_obj[order(-data_obj$col_name), ]

    In above line sorted_values_descending is the variable name in which you want to save the new sorted data, data_obj is the object in which your raw data is saved, col_name is the column name in your raw data which will be used for sorting.

    To sort the data in Lowest to Highest (Ascending Order) values in a column:

    sorted_values_ascending <- data_obj[order(data_obj$col_name), ]

    In above line sorted_values_ascending is the variable name in which you want to save the new sorted data, data_obj is the object in which your raw data is saved, col_name is the column name in your raw data which will be used for sorting.

    To get some rows from the data (top to bottom):

    some_rows <- head(data_obj, 10)

    In above line some_rows is the variable name in which you want to save the rows data, data_obj is the object in which your raw data is saved, 10 is the number of rows you want to get.

    To get some rows from the data (bottom to top):

    some_rows <- tail(data_obj, 10)

    In above line some_rows is the variable name in which you want to save the rows data, data_obj is the object in which your raw data is saved, 10 is the number of rows you want to get.

    To Create Bar Plot (using geom_col()) from 2 Columns using ggplot2 package:

    g <- ggplot2::ggplot(data_obj, ggplot2::aes(x=data_obj$col1, y= data_obj$col1, l)) + ggplot2::geom_col() + ggplot2::xlab(“x axis label here”) + ggplot2::ylab(“y axis label here”) + ggplot2::ggtitle(“Plot title here”)

    In above line data_obj is the object in which your raw data is saved, col1 is the column name in data_obj which will be used for x axis, col2 is the column name in data_obj which will be used for y axis. Please make sure that ggplot2 package is installed before using this function.

    To Add Count on each Bar (geom_col()) in R using ggplot2 Package:

    g <- geom_text(data=data_obj, aes(label=col_name, y=col_name), colour=”red”, size=2.5)

    Scatter Plot in R using ggplot2 package:

    g <- ggplot(data_frame, aes(x=col_x, y=col_y)) + geom_point(col=”steelblue”, size=3)

    // change color using variable

    g <- ggplot(data_frame, aes(x=col_x, y=col_y)) + geom_point(col=col_y, size=3)

    To Remove Legend from Plots in R using ggplot2 Package:

    g <- g + theme(legend.position=”None”)

    To Change Legend Title in R using ggplot2 Package:

    g <- g + labs(col=”No of attacks”)

    To Change Legend Labels and Colors in R using ggplot2 Package:

    g <- g +  scale_color_manual(name=”Legend Title”,labels = c(“NA”,”High”,”Low”,”low”,”Medium”), values = c(” “=”blue”,”High”=”red”,”Low”=”yellow”,”low”=”yellow”,”Medium”=”orange”))

    Make x-axis Label Texts Vertical in R using ggplot2 Package:

    g <- g + theme(axis.text.x = element_text(angle = 90, hjust = 1))

    To Draw Best Fitting Line from Scatter Plot in R using ggplot2 Package:

    g <- g + geom_smooth(method=”lm”, col=”firebrick”)

    // lm stands for linear model

    To Limit x-axis and y-axis in R using ggplot2 Package:

    g <- g + xlim(0, 100) + ylim(0,10)

    To Add Titles and Labels in R using ggplot2 Package:

    g <- g + labs(title=”some title here”, subtitle=”subtitle here”, y=”y-axis label here”, x=”x-axis label here”, caption=”caption text here”)

    To Customize Axis Labels in R using ggplot2 Package:

    g <- g + scale_x_continuous(breaks=seq(0, 0.01, 0.1), labels = sprintf(“%1.2f%%”, seq(0, 0.1, 0.01))) + scale_y_continuous(breaks=seq(0, 1000000, 200000), labels = function(x){paste0(x/1000, ‘K’)})

    Bar Plot (using geom_bar()) to Pie Chart Using ggplot2 Package:

    bp <- ggplot2::ggplot(data_obj, ggplot2::aes(x=””, y=data_obj$col_name, fill = var_name))+ ggplot2::geom_bar( width = 1, stat = “identity”, show.legend = TRUE) + ggplot2::xlab(“x axis label here”) + ggplot2::ylab(“y axis label here”) + ggplot2::ggtitle(“Plot title here”)

    pie_chart <- bp + ggplot2::coord_polar(“y”, start=0)

    To Create Data Frame from Variables in R:

    var_data_frame <- data.frame(x = c(‘Male’, ‘Female’, ‘Children’), y = c(total_male, total_female, total_children))

    var_data_frame is the variable in which new data frame will be stored, x & y are the column names of the data frame, c() is used to create values of the column and total_male, total_female, total_children are variables. Its output will be:

    x                    y

    Male             120

    Female         200

    Children       500

    To Sum Values of a Column in R:

    total_col_values <- sum(data_obj$col_name, na.rm = TRUE)

    na.rm = TRUE is used to neglect missing values.

    To Exclude Empty / Missing Values from Data Frame in R

    data_obj <- data_obj[!(is.na(data_obj$col_name) | data_obj$col_name==””), ]

    To Map Locations Data in R using ggplot2 Package:

    pakistan <- map_data(“world”, “Pakistan”)

    map <- ggplot() + geom_polygon(data = pakistan, aes(x=long, y = lat, group = group), fill=”green” , color = “black”) + geom_point(data= pk_data, aes(x = Longitude, y = Latitude)) + xlab(“”) + ylab(“”) + ggtitle(“Title here”)

  • Inheritance in Java OOP – Code Example 2

    In previous post we learned about inheritance in Java programming by using simple code example. In this post we will consider another code example of inheritance in Java. In previous post we created a Car class (child class) which inherited some attributes and methods from Vehicle class (parent class). In this post we will create a Student class (child class) which will inherit attributes and methods from Human class (parent class).

    [js]

    //Student class code:

    package learningclassesaobjects;

    public class Student extends Human {
    int rollNo;

    public void setRollNo(int x){
    rollNo = x;
    }

    public void getRollNo(){
    System.out.printf("Your Roll No is: %dn", rollNo);
    }
    }

    //Human class code:

    package learningclassesaobjects;

    public class Human {
    int cnic;

    public void setCNIC(int x){
    cnic = x;
    }

    public void getCNIC(){
    System.out.printf("Your CNIC is : %dn", cnic);
    }

    }

    //Main class code:

    package learningclassesaobjects;

    public class Main {

    public static void main(String[] args) {
    Student aStudent = new Student(); //created an object of Student class
    aStudent.setCNIC(1234); // called a method of Human class which is parent class of Student class
    aStudent.setRollNo(3467); // called a method of Student class which is child class
    aStudent.getCNIC(); // called a method of Human class which is parent class of Student class
    aStudent.getRollNo(); // called a method of Student class which is child class
    }

    }

    [/js]

    Output:

  • Inheritance in Java OOP – Code Example 1

    In our previous post we learned how to create classes and objects by using code example. In this post we will learn inheritance which is another important object oriented programming (OOP) concept. Inheritance in Java is like a parent child relationship. As child inherit some properties or behaviors from parents, similarly in inheritance (OOP Concept) a child class can inherit properties and methods from parent class.

    Following simple code example explains the inheritance concepts in Java programming. This code consists of 3 Java classes, main class (LearningInheritance.java), parent class (Vehicle.java) and child class (Car.java). Create a new project in netbeans (java development IDE) with the name of LearningInheritance. Then create 2 more classes named as Vehicle and Car in your project. Following is the code example to understand inheritance.

    [js]

    // Code for Car Class (child class)

    package learninginheritance;

    public class Car extends Vehicle {
    int no_of_doors;

    public void setNoOfDoors(int d){
    no_of_doors = d;
    }

    public void getNoOfDoors(){
    System.out.printf("No of doors are: %dn", no_of_doors);
    }
    }

    // Code for Vehicle Class (parent class)

    package learninginheritance;

    public class Vehicle {
    int modelYear;
    int no_of_tires;

    public void setModelYear(int my){
    modelYear = my;
    }

    public void getModelYear(){
    System.out.printf("Model Year of the car is: %dn", modelYear);
    }

    public void setNoOfTires(int n_o_t){
    no_of_tires = n_o_t;
    }

    public void getNoOfTires(){
    System.out.printf("Number of Tires are: %dn", no_of_tires);
    }

    }

    // Code for LearningInheritance Class (main class)

    package learninginheritance;

    public class LearningInheritance {

    public static void main(String[] args) {
    Car myCar = new Car(); // created object of Car class which is child class
    myCar.setNoOfDoors(4); // defined number of doors for Car object
    myCar.getNoOfDoors(); // called a method of Car class which is child class, to get number of doors
    myCar.setNoOfTires(4); // defined number of tires for Car object
    myCar.getNoOfTires(); // called a method of Vehicle class which is parent class, to get number of tires
    myCar.setModelYear(2015); // defined model year for Car object
    myCar.getModelYear(); // called a method of Vehicle class which is parent class
    }

    }

    [/js]

    Output:

    inheritance in java

     

  • Limitations of Social Media Analysis for Participatory Urban Planning Process

    In previous post we discussed how social media participatory process can help city designers, planners or administrators in decision making process. In this post we discuss the limitations / shortcomings of social media participatory process for urban planning. This post is a short summary of the paper titled as ‘Missing intentionality: the limitations of social media analysis for participatory urban design’ by Luca Simeone.

    Objective:

    The objective of this case study was to find limitations of social media analysis for participatory urban planning process. They analysed what city inhabitants are publishing on their social media profiles to perceive what they think and how they live in urban environment. They mentioned the shortcomings / limitations they found during this urban planning process based on social media analysis.

    Data Set Used:

    They collected data from four different social media channels i.e Facebook, Twitter, Foursquare and Flickr. This data was then analyzed to see the most congested areas by tracking the number of contributions originated from specific geographic locations.

    Methodology:

    They proposed a method consisting of following steps:

    1. Collect data from social media channels
    2. Apply multiple strategies (like text mining) to analyze this data
    3. Choose the appropriate urban planning tasks e.g knowing user’s feelings towards local government policies, or to find best place to build hostel for university students etc.
    4. Visualize the results to see the patterns / results
    5. Make decisions based on the results

    Limitations:

    1. Not all city inhabitants have equal access to the technologies and skills to post Geo-located contributions
    2. Restricted access to social media data due to their privacy policy
    3. Lack of intention to participate in participatory process

    Author focused on the point that we analyse the social media data without knowing user’s intention. Whereas when we say participatory process then it means that user should be willing to participate in the design process or they should at-least know that their activities are being tracked for the purpose of planning process. According to author’s point of view this is the main limitation of this social media participatory process for urban planning.

    Conclusion:

    Social media analysis can be used to support urban design, decision making process. But at present their are certain limitations out of which lack of intentionality of the user’s is the major shortcoming of this process.

     

    References:

    https://www.researchgate.net/publication/274890298_Missing_intentionality_the_limitations_of_social_media_analysis_for_participatory_urban_design

  • Classes and Objects in Java Programming – Code Example

    In this post we will learn (java syntax) what are classes and objects in Java programming. Classes and objects are fundamental object oriented programming concepts. In previous post we discussed some important object oriented programming concepts. If you want to learn about classes and objects, class constructor method, constructor parameters, instance variables, class methods and main method then read this post.

    In this simple program we will learn how to create a class and class objects in Java programming. Further we will also learn how to create instance variables (attributes) and methods for class in Java programming.

    [js]

    package carclassjava;

    // following is the syntax to create a public class named as CarClassJava
    public class CarClassJava {
    int modelYear; // this is how we create an instance variable (attribute) in class

    // following is the constructor method for class
    public CarClassJava(int year){
    modelYear = year;
    }

    // following is the method of this class
    public void startEngine(){
    System.out.println("Car is started");
    }

    // following is the method of this class
    public void getModelYear(){
    System.out.printf("Car’s Model is: %dn", modelYear);
    }

    // following is the main method of this class. Every java program needs a main method
    public static void main(String[] args) {
    // Following is the syntax to create an object of class
    CarClassJava myCar = new CarClassJava(2015);
    myCar.startEngine(); // we called class method startEngine over the object myCar
    myCar.getModelYear(); // we called class method getModelYear over the object myCar
    }

    }

    [/js]

    Output:

    classes and objects in java

  • Social Media Participation in Urban Planning

    Social media is generating a huge amount of data every second and this data can be used to make important decisions about any particular topic. This post is a short summary of a research paper titled as ‘SOCIAL MEDIA PARTICIPATION IN URBAN PLANNING: A NEW WAY TO INTERACT AND TAKE DECISIONS’ by E. López-Ornelas, R. Abascal-Mena, S. Zepeda-Hernández.

    Textual analysis is performed on social media data to know the sentiments (opinions) of the people about any topic. This type of analysis is very important for organizations and institutions to make important decisions. In this paper they have used the installation of a new airport in Mexico City as a case of study to highlight the importance of conducting a study of this nature.

    Urban Planning and Social Media:

    Urban planning deals with efficient utilization of land and design of the urban environment including air and water infrastructure management. On the other hand social media and online web based communities are a great sources to collect public opinion about any topic. This paper studies different steps/phases to extract public opinion from social media (twitter) and analyse the public opinion about new airport in Maxico City.

    Design Process For Information Extraction from Social Media:

    This paper proposes a design process that will help urban planners to analyze all the information contained in social network. To extract and analyse social media data they proposed following four steps to be studied and applied:

    1. Structure Analysis: This analysis is used to know information generators, amount of available information and linkage between different information generators.
    2. Sentiment Analysis: It’s used to know the tendency of opinion about particular topic.
    3. Community Detection: It’s important to simplify the social network and to identify groups of users sharing same information.
    4. User Identification: It’s used to identify the users which are actually generating the information (opinion) about the topic.

    Results:

    This analysis shows that when the statement was made about the installation of new airport in Maxico City then there was a big concentration of opinions that were rejecting the project. New analysis was made after the 2 weeks of the announcement and results show that there were large number of opinions approving the project.

    Future Work:

    The authors of this paper used twitter data to extract public opinion. As a future work they proposed to analyse data from other social networking websites and then to compare the results from different social networking websites. This will also help to identify which social networking website generate better results.

    Moreover to map the locations of participants will help us identify biased opinions and hence getting better results.

    Conclusion:

    Social media can be used as a medium that support participatory process. It can be used in areas like urban planning to help make decisions based on the public opinion.

    References:

    https://www.int-arch-photogramm-remote-sens-spatial-inf-sci.net/XLII-4-W3/59/2017/isprs-archives-XLII-4-W3-59-2017.pdf