Tuesday, February 28, 2017

Callbacks in JavaScript - Animating bubble sort with D3.js


Generally a callback means a function passed as a parameter to another function. But how can a function be a parameter to another function. It's possible as javascript treat it's functions as "first class objects". Therefore functions can be
  1. Stored in variables
    • var myFuctionVariable = function(){}
  2. Passed as arguments to functions
    • updateMe(myFuctionVariable);
  3. created within functions +  return a function - JavaScript Closure
    • function calculateArea(l) {
           return function(b) {
                if(b != undefined){
                return b*l;
               }else{
               return l*l;
               }
           }

      }
      console.log(calculateArea(10)()) //100
      console.log(calculateArea(10)(20) //200


      function sayHello(name){ 
      var sayText = "hey " + name;
      var speakOutLoud = function(){
      return sayText;
      }
      return speakOutLoud;
      }

      var kamal = new SayHello('Kamal'); //returns hey Kamal

So without waiting anymore time. Let's to a basic data visualization using javascript and d3.js. Here we'll be using callbacks. 


1. Create a basic html page


<!DOCTYPE html>
<html>
<head>
<title>AlgoViz</title>
<style type="text/css">
   span.bar {
display: inline-block;
width: 20px;
height: 75px;
background-color: teal;
margin: 5px;
transition: 3s;
}
</style>
</head>
<body>
<div id="graph">
</div>

<!-- include jQuery -->
<scrip src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

<!-- include d3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.6.0/d3.min.js"></script>

<!-- include the custom javascript you have created -->
<script type="text/javascript" src="sorting.js" ></script>

</body>
</html>

2. Let's create a sorting.js on the same folder 


//data array we are going to sort
var data = new Array(34, 23, 3, 76, 01, 90, 18, 50, 9); 

//see the callback functions
function genGraph(callback_sort,callback_update_graph,time){
     setTimeout( function() {
         //clearing the html body   
document.body.innerHTML = '';
         //updating the graph   
callback_update_graph(data)
        //bubblesort algorithm
        for (var i=0; i < data.length-1; i++) {
            if (data[i] < data[i+1]) {
                var temp = data[i];
                data[i] = data[i+1];
                data[i+1] = temp;
            }
            //calling the sort method 
           callback_sort(data[i]);
        }

      },time);

}


//update graph / draw graph using d3.js
var updateGraph = function(numbers) {
d3.select("body").selectAll("#graph")
    .data(numbers)
    .enter()
    .append("span")
    .attr("class", "bar")
    .style("height", function(d) {
        var barHeight = d * 5;
        return barHeight + "px";
    });
}


//this is just to print the array in the console for a better understanding
var sorter = function(no){
console.log("val = " + no);
}


//calling the generate graph function having sorter and updateGraph as parameters. 
for(var a = 1 ; a <= data.length ; a++){
    genGraph(sorter,updateGraph,a*800);
}

3. Now you can open the html page in a web browser.


In the following code fragment we are actually passing functions as parameters 

 genGraph(sorter,updateGraph,a*800);

or you can directly type the function as a parameter as given below.

genGraph(function(no){
    console.log("val = " + no);
},function(numbers) {
    d3.select("body").selectAll("#graph")
    .data(numbers)
    .enter()
    .append("span")
    .attr("class", "bar")
    .style("height", function(d) {
        var barHeight = d * 5;
        return barHeight + "px";
    });

Friday, February 24, 2017

JavaScript Prototype

1.What is it ?


Every javascript object is inherited from another object called as the prototype object. Through the prototype object we can add properties and functions to an existing object. When ever an object is created, it will be automatically inherited from a prototype object which is specific to the created object.
  1. Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
  2. Objects created with new Date() inherit the Date.prototype.
  3. The Object.prototype is on the top of the prototype chain.
  4. All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.  --quoted from w3schools
Simply, suppose that you are creating a function in javascript. That function also contain a prototype object.

//javascript prototypes
function Mammal(name,kingdom){
this.name = name;
this.kingdom = kingdom
this.info = function(){
return "name = " + this.name + ". kingdom = " + this.kingdom; 
}
}
//adding a static variable to the prototype object of the Mammal function
Mammal.prototype.sound = "GRRRRRRR"
//adding a static function to the prototype object of the Mammal functuon
Mammal.prototype.makeSound = function(){
return this.info() + ". And I make the sound " + this.sound;
}

var lion = new Mammal("lion", "Animalia");
console.log(lion.makeSound());
console.log(lion.info());

2. Printing out all the properties of a Javascript object


//let's print out all the properties of an object
for (var property in lion){
console.log(property + "\n");
}

3. Let's find out whether a certain property belongs to the object or it's specific prototype object


console.log(lion.hasOwnProperty("name")) // true, meaining this property belogns to the object itself not to it's prototype
console.log(lion.hasOwnProperty("kingdom")) // true
console.log(lion.hasOwnProperty("info")) //true
console.log(lion.hasOwnProperty("sound")) //false, meaing this property belongs to the prototype of that object
console.log(lion.hasOwnProperty("makeSound")) //false

4. let's create a program to search an array for a specific element using prototypes

Let's do a fun activity. In javascript there is an object called the Array object and we'll be adding a custom function to that array object to input an element and check whether it's present or not inside the array. To achieve this we'll be using a linear search of log(n) as an average.

//let's create a program to search an array for a specific element using prototypes
Array.prototype.findMe = function(number){
for(var i = 0; i < this.length ; i++){
if(this[i] == number){
return true;
}
}
return false;
}
var numberArray = [2,34,2,213,43,45];
console.log(numberArray.findMe(43)) 

JavaScript Object Basics - es 5 or less

1. JavaScript Objects example


var Customer = {
name : "Amal",
speak : function(){
return "my name is "+this.name;
},
address : {
number : 'abc',
street : '123 street',
city : 'Colombo'
}
};
console.log(Customer.speak())
console.log(Customer.address)
console.log(Customer.address.city)



2. Creating multiple, different objects of the same type


For this we can use the constructor function. Basically a constructor function allows us to get the functionality of a classes  found in OOP languages. Example for a javascript constructor function is given below.

//let's create a constructor function called Person
function Person(name,age,city){
this.name = name;
this.age = age;
this.city = city;
this.getInfo = function(){
return "My name is "+ this.name + ". My age is " + this.age + ". I live in " + this.city + ".";
};
}
// let's create a person called amal
var amal = new Person('Amal',18,'Colombo');
console.log(amal.getInfo())
//let's check whether amal is an instance of Person
console.log(amal instanceof Person )


4. Let's add an instance variable to the object we created just now (amal)


amal.mynickname = "amale"
amal.mycar = "corolla"
console.log(amal.mynickname);
console.log(amal.mycar);

//but Person.mynickname would give an error since mynickname is an instance varialbe, not static

This way custom variables which are not defined in the constructor function can be added to amal object. There variables specific only to the amal object.

5. Let's Pass an object to a function and change its value


//let's create a function and chage the name of the object amal
function changeName(personObject){
personObject.name = "Bob lee";
}
changeName(amal)
console.log(amal.getInfo());




* Objects are only going to be equal if they reference the exact same object. What the heck is that?  Let's clear that out.

//let's create 2 more persons called sunil and nimal
var sunil = new Person('sunil',20,'Kandy');
var animal = new Person('sunil',20,'Kandy');
console.log(sunil === nimal);


//by referring to the same object
var sunil_same_ref = sunil
console.log(sunil === sunil_same_ref)


In JavaScript,  === means we are checking for the value as well as the type of the variable and == means we are only checking for the value.










Monday, February 20, 2017

All about version controlling tools - GitHub / bitbucket Part - 3

2. Multiple users working on the same branch.

If two or more users are using the same repository to push code into, there will be conflicts. In order to resolve the issues checkout the steps below.

Let's take an example. Suppose that you already have a codebase in GitHub

|-- master
|-- dev(default)
    |-- feature/myfeature *

In the team what if 2 users are working on the same feature. So that they'll have to use the same branch(Not a good practice though). Let's take our 2 users as USER1 and USER2. Suppose that the USER1 and USER2 have already cloned the repo into the local machine.
git clone <ulr here>
Now both the users are working on the project. They have to stick with few guidelines in order to prevent from conflicts. 

1. Whenever they have completed something, commit locally but do not push to the feature/myfeature branch.

2. When ever they want to push the code to the branch follow the steps given below.
  1. git add --all
  2. git commit -m "your changes"
  3. git pull
  4. After pulling, there can be conflicts in the local code. You have to correct them manually and then 
  5. git commit -m "new changes" 
  6. and finally
  7. git push -u origifeature/myfeature
  8. if you get an error message, then repeat steps 3 to 7 again.

3. What is the difference between 'git pull' and 'git fetch'?

git pull is what you would do to bring a local branch up-to-date with its remote version, while also updating your other remote-tracking branches. In the simplest terms, git pull does a git fetch followed by a git merge.




Thursday, February 16, 2017

All about version controlling tools - GitHub / bitbucket Part - 2

In the part 2 of this series, we'll look at how to use GitHub with console.

1. Adding your local project to an empty gitbub repository's master branch

  1. Goto the github and create an empty repository.
  2. Then goto the empty repository.
  3. Copy the https or ssh url
  4. Then create a folder locally, in your computer to initialize the repository.
  5. Now "CD" into the created folder using command line.
  6. In the command line type the following commands in order to initialize the repository.
    1. Now copy your project to the newly created folder
    2. git init  #This command is used to start using git on a project that's not under git
    3. git add .
    4. git commit -m "initial commit"
    5. git remote add origin https://github.com/yourprofile/yourproject.git
    6. git push -u origin master #you can add different origins in order to push your local project to GitHub.
  7. Now that you have successfully copied the project into the GitHub, you can make changes to the code locally.
  8. If you are hoping to further develop the software. you'll have to create a developer branch. Let's think that you're going to further develop the software. Let's create the developer branch. when you create a developer branch, the code in the master branch will be automatically copied to this branch.
    1. git branch developer #this command creates a developer branch.
  9. Now before continuing further, set the default branch to developer branch.
    1. Goto settings on GitHub repo.
    2. Select branches tab
    3. Set the default branch 
  10. Then, to continue development, let's create a feature branch from the developer branch 
    1. git branch -b feature/new-component developer
  11. Let's switch to the feature/new-component branch.
    1. git checkout feature/new-component
  12. push it to the feature/new-component
    1. git add --all
    2. git commit -a -m "describe your changes here"
    3. git push -u origin feature/new-component
  13. Then once you have finished developing the particular feature, create a pull request to the developer branch and merge the code.
  14. Once you have completed an iteration of the software or the full software, create a pull request to the master branch from developer branch and merge the code with master branch
    1. create a pull request to the master branch from developer branch.
    2. merge the code with the master branch.
We are using the developer branch only for the purpose of further development and it will be merged to the master branch when you have completed an iteration of the software / program only, as an engineering best practice.

Important points to remember
  • If you have a team or if you are doing a group project, a feature branch must be created for each developer and the code should be push to that feature branch. When you have completed the development of a particular feature, then you can merge the feature branch with the developer branch.
  • If your team or group is fixing the bugs, bugs/identifier branch should be created for each member and merge the fixes to the developer branch. 
part 3

Wednesday, February 15, 2017

All about version controlling tools - GitHub / bitbucket Part - 1

1. What is "version control", and why should you care?

"Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later"

As defined about, If multiple people are developing a software, the version controlling tools may come in handy. Let's get started.

2. Github

Once you have registered with GitHub you'll be able to create a repository easily. Repository is a place where you are going to upload the code into. 
In a repository there are branches. A branch represents an independent line of development. Branches serve as an abstraction for the edit/stage/commit process.

3. The branch structure

Master branch : This is where the production code goes into. After completion of an release of the program / software, we create a pull request( Simply allows the user to notify others about the completion. Then other users can review the code and merge the code ) to the master branch from developer and merge the code with the master branch after a code review.

Developer branch : This is where the non production code goes into. When the software is being developed, the users can merge their developments with this branch after creating a pull request.

Feature branch : These are the branches where features of the main software are developed in. When a developer completes a certain feature of the software, this branch will be merged with the developer branch.

Bug fix branch : All the bug fixing will be done using this branch. After fixing a certain bug, this branch will be merged with the developer branch after creating a pull request.

When you have all the above branches, your repo may look like this : 

|-- master
|-- developer
    |-- feature/toolbox
    |-- feature/custom-view-controller---ios
    |-- feature/floating-button---ios
    |-- bugfix/error-302-navigation-controller-error
    |-- bugfix/error-701-runtime-error---ios



Terms :
  1. Origin - origin is an alias on your system for a particular remote repository url. It's not actually a property of that repository.
    1. git add origin <url here>
  2. Remote - Remotes are simply an alias that store the url of repositories. You can see what url belongs to each remote by using.
    1. git remote -v
  3. Fork - It only allows clone on the server side.
  4. Upstream - The original repo

Tuesday, February 14, 2017

How to add an animation to the UICollectionView on data reload()

When you reload the data in UICollectionView, it will just reload the data without any progress. To overcome this you can simply animate the UICollectionView reload event when tapping on a UICollectionViewCell. I'll be using "driveCellCollectionView" as the collection view.


UIView.transition(with: driveCellCollectionView, duration: 0.5, options: .transitionFlipFromLeft, animations: {
            //Do the data reload here
            self.driveCellCollectionView.reloadData()
        }, completion: nil)


Once you have done this, you can simply run. Stay tuned for more tutorials.

Javascript Class basics - ECMA Script 6

This is a tutorial on the 1st lab session of application frameworks subject conducted by pearson lanka for the SLIIT 3rd year first semester.

Basically the first activity is to write a program in java script to update the div in realtime as we type on. for this, the ideal javascript function is "oninput".


























The 2nd activity is to create a JavaScript class called Vehicle and Car. Car class should extend from Vehicle class. Vehicle class should have a method to set and price of the Vehicle.

Type the following html and include the automobile.js as given below














Then let's type the below code to achieve the results. Here I have used the latest version of the javascript.






































Finally save this file and run it. The next activity is to consume the GitHub api to get a list of users. This will be posted soon. Stay tuned!

You can get the full answers via this link

Tensor Flow

Tensor Flow is the open source machine learning / deep learning  platform used by google. They have implemented this in a wide variety of their products. Basically it can do numerical computation using data flow graphs. The Nodes in the graph represent mathematical operations. Edges represent the multidimensional data arrays (tensors) communicated between them hence tensor flow. Operation in tensor flow is a named abstract computation which can take input attribute and produce output attribute.

The speciality of tensor flow is that it can be implemented on android, iOS and raspberry pi so that  the mobile tensor flow can be used to process data within the device even without a network connection.

You can install tensor flow by following this guide. Once you are done, try the below program.

import tensorflow as tf
a = tf.constant(5)
b = tf.constant(6)
sess = tf.Session()
print(sess.run(a*b))

Output
30

Get the GitHub repo from here