GO - Basic Variable declaration - Part 3

Image result for golang
Defining variables in the go
we use var to define a variabler in the GO. In GO we put the variable type only at the end of the variable name like:
var variable_name varaiable_type
var muNumber int

we can define multiple variable by this way
var variable1, variable2, variable3 variable_type
var num1, num2 int
here all variable will the of the type vatiable_type

defining the variable with the initial value
var variable_name type = value
eg. var age int = 14

defining multiple variable with intial value
var num1, num2, num3 = 2, 3, 4
// same as num1 = 2, num2 = 3, num3 = 4

lets define three variable without the type and the var keyword with their initial values
vname1, vname2, vname3 := v1, v2, v3
Now it looks much better. Use := to replace var and type, this is called a brief statement.
its simple but it has one limitation: this form can only be used inside of functions. You will get compile errors if you try to use it outside of function bodies. Therefore, we usually use var to define global variables.

blank variable 
"_" is known as blank variable in GO because it's blank :). for eg:
_ , a := 10, 20 
here 20 given to a but 10 is discarded, we will use this on the later examples in real case

NOTE: GO will give compile time error if we didnt use the variable which are already defined.

GO - Introduction - Part 1

Image result for golang

What is "go"?
Go or golang is the new programming language developed by google for their most roboost and to manage the large scale application.

Why go?
It is lightweight and more managable and is awesome for the web services and last but not the least it is easy to learn.

What are its features?

  1. Support for environment adopting patterns similar to dynamic languages. For example type inference (x := 0 is valid declaration of a variable x of type int)
  2. Compilation time is fast.
  3. InBuilt concurrency support: light-weight processes (via goroutines), channels, select statement.
  4. Conciseness, Simplicity, and Safety
  5. Support for Interfaces and Type embedding.


But to make it more simpler following features haves been ommited


  1. Production of statically linked native binaries without external dependencies.
  2. No support for type inheritance
  3. No support for method or operator overloading
  4. No support for circular dependencies among packages
  5. No support for pointer arithmetic
  6. No support for assertions
  7. No support for generic programming

Angular 2 - Part 9 [Template-Driven Form]


In this tutorial we will create a template-driven form which will contain username, email, password and gender fields. which is as shown below:


here is the template-driven.html template file for this form:

<h2>Template Driven</h2>
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
  <div ngModelGroup = "userData">
    <div class="form-group">
      <label for="username">Username: </label>
      <input type="text" class="form-control"
             minlength="4"
             id="username"
             [(ngModel)]="user.username" name="username" required
             >
    </div>
    
    <div class="form-group">
      <label for="email">Email: </label>
      <input type="text" class="form-control"
             pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
             id="email"
             [(ngModel)]="user.email" name="email" required
            >
    </div>
  </div>
  <div class="form-group">
    <label for="password">Password: </label>
    <input type="password" class="form-control"
           id="password"
           [(ngModel)]="user.password" name="password" required>
  </div>
  <div class="radio" *ngFor="let g of genders">
    <label>
      <input type="radio" [(ngModel)] = "user.gender" name="gender" [value]="g"> 
       {{g}}
    </label>
  </div>
  <button type="submit" class="btn btn-primary" >Submit</button>
</form>

Now let create a component for this form
template-driven.component.ts




import { Component, OnInit } from '@angular/core';
import {NgForm} from "@angular/forms";

@Component({
  selector: 'app-template-driven',
  templateUrl: './template-driven.component.html',
  styleUrls: ['./template-driven.component.css']
})
export class TemplateDrivenComponent{

  user = {
    username:"Yubraj",
    email:"yubraj@gmail.com",
    password:"asdfasdf",
    gender: "male"
  }
  
  genders = ["male", "female"];

  constructor() { }

  onSubmit(form: NgForm){
    console.log(form.value);
  }
}



What we did here is:
1. We created a html template
2. then we bind the html input with the user object which is in the component.
3. [(ngModel)]="user.username" .. is used to bind using two way data binding in the form
4. in the form we use (ngSubmit)="onSubmit()" to submit the form and #f is used to hold the form.
5. once submitting the form we will display the form value in the console.

What we need to implement is:
1. Only allow submission only when all the form data is valid.
2. show errors in the forms.

lets add some more attributes in the input fields i.e. #username, #email in order to represent the given field so we can show errors once it has been changed. Before that let us know that angular will add its own classes in the input field when running it, which are ng-valid if the form is valid and ng-invalid if the form is invalid as well as ng-dirty if the form value is changed and ng-touched if the form input
is touched or selected. which is as shown below:



so we modify the class ng-invalid and ng-valid which is used to highlight the input field if the data is not valid.

template-driven.component.css

.ng-invalid{ border-color: red; }
.ng-valid{  border-color: forestgreen; }

so once the input is invalid the border color will turn to red and on valid it will turn to green.


Adding the error message in the form:
we will add this line of code in the form to show the error in the form for each fields

<div class="alert alert-danger" role="alert" *ngIf="!username.valid">Invalid username</div>

here #username is used to reference the username input field in the form. So once it is invalid this above line will be displayed.  Similarly we can also make the submit button disabled if the form which is referenced by f. by this way:
<button type="submit" class="btn btn-primary" [disabled]="!f.valid">Submit</button>

lets check it out all together:

template-driven.component.html

<h2>Template Driven</h2>
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
  <div ngModelGroup = "userData">
    <div class="form-group">
      <label for="username">Username: </label>
      <input type="text" class="form-control"
             minlength="4"
             id="username"
             [(ngModel)]="user.username" name="username" required
             #username="ngModel">
    </div>
    <div class="alert alert-danger" role="alert" *ngIf="!username.valid">Invalid username</div>
    <div class="form-group">
      <label for="email">Email: </label>
      <input type="text" class="form-control"
             pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"
             id="email"
             [(ngModel)]="user.email" name="email" required
             #email="ngModel">
    </div>
    <div class="alert alert-danger" role="alert" *ngIf="!email.valid">Invalid email address</div>
  </div>
  <div class="form-group">
    <label for="password">Password: </label>
    <input type="password" class="form-control"
           id="password"
           [(ngModel)]="user.password" name="password" required>
  </div>
  <div class="radio" *ngFor="let g of genders">
    <label>
      <input type="radio" [(ngModel)] = "user.gender" name="gender" [value]="g"> {{g}}
    </label>
  </div>
  <button type="submit" class="btn btn-primary" [disabled]="!f.valid">Submit</button>
</form>


So here is the output:


This whole code is available in the github. check it out here 
#happyCoding


Angular 2 - Part 8 [ Forms ]


Forms in Angular has always been so interesting. We can do lots of stuffs in the forms using a little and simple techniques in angular. Forms are very important in the web applications. Forms are used to login, registrations and also for many stuffs. Dynamic web is not possible without the forms. In angular 1.x we have seen how angular helps us in developing much user friendly forms. In angular 1.x all the forms are template driven where as in angular 2 we can also create a data-driven forms too which are much easier and easy to learn as well.
So in the later two tutorial we will discuss on how we can create two types of forms using angular 2 which are: 
  1. Template-Driven: Most of the logic are included in the template 
  2. Data-Driven: Logic are applied via a internal implementations
Check it out the examples of each type of in the upcoming tutorials. 
#happyCoding


Anagram Solution in Java

Recently, I gave a technical interview one of the reputed software company in silicon valley. Here are the question and it's solution.

Problem: Anagram Problem

Anagram is a word that can be obtained by rearranging letter of the another word, using all the constituent letter exactly once.

Solution:




//Ouput will be

//{"apple", "perl"}, this is not anagram and to make we need to add: 2 character
  //{"lemon", "melon"} , this is anagram and it return 0

Angular 2 - Part 7 - [Routing]





This is the most interesting in the angular which makes our app super awesome. Using this techniques we can make our app single page application. In order to use this in angular 2 we need to use the @angular/router module. There are various steps to accomplish this feature in the angular app.

1. Set the base url
In every single page application we need to set the base URL in angular 2 we will do this using the
<base href="/" /> tag in the header section of the index.html page

2. Now we need to create a file in order to save all the routing information. So lets create a file call app.route.ts in the app directory. inside that we need to specify our routing information like:

import {Routes, RouterModule} from "@angular/router";
import {HomeComponent} from "./home/home.component";
import {VideosComponent} from "./videos/videos.component";
import {BlogsComponent} from "./blogs/blogs.component";
import {ContactComponent} from "./contact/contact.component";


const APP_ROUTE: Routes = [
  {path: '', component: HomeComponent},
  {path: "videos", component: VideosComponent},
  {path: "blogs", component: BlogsComponent},
  {path: "contact", component: ContactComponent}
];

export const routes = RouterModule.forRoot(APP_ROUTE);

here we are crating the routes as a constant value which stores all the routing information and is also ready to share with external elements using the export keyword. We have added this route information for the root using the forRoot().
so when ever we hit the root url the home componet will get called. similary if we hit url with /videos then the VideosComponent will get loaded and so on.

3. Now we need to import the route information in our app.module.ts file like:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { routes } from "./app-routing.module";
import { VideosComponent } from './videos/videos.component';
import { BlogsComponent } from './blogs/blogs.component';
import { ContactComponent } from './contact/contact.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    VideosComponent,
    BlogsComponent,
    ContactComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routes
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4. Now everything is set up. Then we need to decide where to use the routes. In my condition I have used this in the appComponet using the <router-outlet></router-outlet>. Which means the dynamic views will be loaded on this tag and other parts will remains the same. here is the code for the app-componet.html:

....
....
<main class="mdl-layout__content">
    <div class="page-content mdl-grid portfolio-max-width">
          <router-outlet></router-outlet>
      </div>
</main>
...
...

Here the view will be loaded dynamically inside the <router-outlet> tag.


5. Now we are ready to use this module but still we cannot use the #/youlink like tag like in
angular 1. To call the router link from the html we need to use routerLink attribute in the link like this


...
<nav class="mdl-navigation">
        <a class="mdl-navigation__link" routerLink="/"><i class="material-icons">home</i> Home</a>
        <a class="mdl-navigation__link video" routerLink="/videos"><i class="material-icons">music_video</i> Videos</a>
        <!--<a class="mdl-navigation__link" routerLink="/"><i class="material-icons">developer_board</i> Experiences</a>-->
        <a class="mdl-navigation__link blog" routerLink="/blogs"><i class="material-icons">library_books</i> Blogs</a>
        <a class="mdl-navigation__link contact" routerLink="/contact"><i class="material-icons">mail_outline</i> Contact</a>
      </nav>
...

Now if we run the application then we can see our router in effect. Here we can add extra attribute called routerLinkActive inorder to change the style for our active link. for this we need to pass the css class.


You can see the full code of the application used in this totorial at here
Stay tuned for more awesome tutorial. happy coding :)

Classifying Iris dataset using Naive Bayes Classifier

The Iris Dataset is a multivariate dataset. It has 5 attributes, the first one is sepal length (Numeric), second is sepal width (Numeric) third one is petal length (Numeric), the fourth one is petal width (Numeric) and the last one is the class itself. We have 150 rows that are equivalent to 150 flowers collected those flowers are divided into the different category. They are similar flowers that are Iris but the different category like Iris-setosa, Iris-versicolor, and Iris-virginica. It is important to know about these patterns because in future if you see similar data we can say that this data belong to the certain pattern. Based on these data, we can predict which kind of the Iris flower does new flower belongs. It is supervised data since we have the class (Nominal).
  

Data visualization:  As we can see there are three classes. Blue (Iris-setosa), Red (Iris-versicolor), and Sky Blue (Iris-virginica). There are equivalently distributed so during the analysis we don’t have to normalize it. There is same frequency of data of all class. Now let us analyze petal length graph. We can distinctly analyze that if the petal length is from 1 to 2 then it is of Iris-setosa. Similarly, we can analyze others using attributes graph.

Basically, the task is to assign a new data to one or more classes or categories is classification or categorization. Naive Bayes is a simple technique for constructing classifiers: models that assign class labels to problem instances, represented as vectors of feature values, where the class labels are drawn from some finite set. It assumes that the value of a particular feature is independent of the value of any other feature, given the class variable. For example, a fruit may be considered to be an apple if it is red, round, and about 10 cm in diameter. A naive Bayes classifier considers each of these features to contribute independently to the probability that this fruit is an apple, regardless of any possible correlations between the color, roundness and diameter features.

Python Code: Using Python weka wrapper for NaiveBayesUpdateable
Result


=== Summary ===
Correctly Classified Instances         144               96      %
Incorrectly Classified Instances         6                4      %
Kappa statistic                                             0.94 
Mean absolute error                                     0.0324
Root mean squared error                            0.1495
Relative absolute error                                 7.2883 %
Root relative squared error                          31.7089 %
Total Number of Instances                            150    

=== Confusion Matrix ===
  a                  b                    c                       <-- classified as
 50                0                    0                     |  a = Iris-setosa
  0                  48                 2                     |  b = Iris-versicolor
  0                 4                     46                  |  c = Iris-virginica

From this Confusion Matrix, we found that 50 of data is Iris-setosa from the above chart. Then it was able to classify 48 separate ways with 2 errors for Iris-versicolor. For Iris-virginica, 46 were rightly classified and 4 of them were an error.

The naive bayes model is comprised of a summary of the data in the training dataset. This summary is then used when making predictions. The summary of the training data collected involves the mean and the standard deviation for each attribute, by class value. For example, if there are two class values and 7 numerical attributes, then we need a mean and standard deviation for each attribute (7) and class value (2) combination that is 14 attribute summaries. These are required when making predictions to calculate the probability of specific attribute values belonging to each class value. We can break the preparation of this summary data down into the following sub-tasks:
1.       Separate Data By Class
2.       Calculate Mean
3.       Calculate Standard Deviation
4.       Summarize Dataset
5.       Summarize Attributes By Class

We are now ready to make predictions using the summaries prepared from our training data. Making predictions involves calculating the probability that a given data instance belongs to each class, then selecting the class with the largest probability of the prediction. We can divide this part into the following tasks:
1.       Calculate Gaussian Probability Density Function
2.       Calculate Class Probabilities
3.       Make a Prediction
4.       Estimate Accuracy

References
https://github.com/fracpete/python-weka-wrapper

Trouble Installing python-pip in Ubuntu




Recently I was facing problem installing the pip in my ubuntu 16.04. After some research I found a solution which is as follow:
python-pip is in the universe repositories, therefore use the steps below:
Try this steps one by one
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip

Simple Guess Number using Servlet

______________________________________________________________________________

HelloServlet.java
______________________________________________________________________________

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by yubraj on 11/6/16.
 */
@WebServlet(urlPatterns = {"/HelloServlet"})
public class HelloServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("Hello World");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }
}

________________________________________________________________________________

LogonServlet.java
______________________________________________________________________________

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by yubraj on 11/6/16.
 */
@WebServlet(name = "LogonServlet", urlPatterns = {"/LogonServlet"})
public class LogonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        if(username.equals("user") && password.equals("pass")){
            out.print("Welcome user");
        }else {
            out.print("Wrong UserId or Password! Please try again");
            out.println("<form method=POST action=LogonServlet>");
            out.println("Username=<input type=text name=username> <br>");
            out.println("Password=<input type=text name=password>");
            out.println("<input type=submit value='Logon'>");
            out.println("</form>");
        }
        out.println("</body>");
        out.println("</html>");
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<form method=POST action=LogonServlet>");
        out.println("Username=<input type=text name=username> <br>");
        out.println("Password=<input type=text name=password>");
        out.println("<input type=submit value='Logon'>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
        out.close();
    }
}


______________________________________________________________________________

guessNumber.java
______________________________________________________________________________

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

/**
 * Created by yubraj on 11/6/16.
 */
@WebServlet(name = "guessnumber", urlPatterns = {"/guessnumber"})
public class guessnumber extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        PrintWriter out = response.getWriter();
        int num = Integer.parseInt(request.getParameter("number"));
        int randNumber = Integer.parseInt(session.getAttribute("randNum").toString());

        out.println("<html>" +
                "<head>" +
                "<title>Guess Number Game</title>" +
                "</head>" +
                "<body>");
        if(num == randNumber){
            out.println("Congratulation you won");
            out.println("<br><a href='/guessnumber'>Try Again</a>");
        }else if(num>randNumber){
            out.println("Number is too high. Try Again!");
            out.println("<br><a href='/guessnumber'>Try Again</a>");
        }else{
            out.println("Number is too low. Try Again!");
            out.println("<br><a href='/guessnumber'>Try Again</a>");
        }
        out.println("</body></html>");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Random rand = new Random();
        int x = rand.nextInt(10);

        HttpSession session = request.getSession(true);
        session.setAttribute("randNum", x);

        PrintWriter out = response.getWriter();
        out.println("<html>" +
                "<head>" +
                    "<title>Guess Number Game</title>" +
                "</head>" +
                "<body>" +
                    "Enter the number between 1 and 10"+
                    "<form method=POST action=guessnumber>" +
                        "<input type=number name=number />" +
                        "<input type=SUBMIT value=Enter />" +
                    "</form>"+
                "</body></html>");
        System.out.println(x);
    }
}

------------------------------------------------------------------------------------------------------------
Web.xml
------------------------------------------------------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
    </servlet>
</web-app>

Simple Guess Number Game using JSP

<%@ page import="java.util.ArrayList" %>
<%--
  Created by IntelliJ IDEA.
  User: yubraj
  Date: 11/20/16
  Time: 4:27 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Number Guess System</title>
      <style>
          .error{ color: red; }
          .success { color: greenyellow; }
      </style>
  </head>
  <body>
    <h1>Hello world</h1>
    <%
        for(int i = 1; i<=10; i++){ %>
        <h5><%= +i%></h5>
    <% } %>
    <h1>Number Guess System</h1>
    <p>Guess Number within 1 and 10</p>

    <%
        final HttpSession       Sess = request.getSession();
        final boolean           JustStarted = Sess.isNew();
        final Integer           randomNumber;

        if(JustStarted){
                randomNumber = new Integer(new java.util.Random().nextInt(10));
                System.out.println("Random Number : " + randomNumber);
                Sess.setAttribute("number", randomNumber);
            } else {
                randomNumber = (Integer) Sess.getAttribute("number");
            }
    %>

    <%
        String inputText = request.getParameter("number");
        String errorMsg = null;
        boolean success = false;

        if(!JustStarted) {
            if (inputText != null && inputText.length() > 0) {
                int myNumber = Integer.parseInt(inputText);
                if (randomNumber != myNumber) {
                    if (myNumber > randomNumber)
                        errorMsg = "Number too large!";
                    else
                        errorMsg = "Number too Low!";
                } else {
                    errorMsg = "Congrats! you win";
                    success = true;
                }
            }
        }
    %>

    <div>
        <% if(errorMsg != null){ %>
            <p class="<% if(success){ %>
                        success
                       <% }else{ %>
                        error
                        <% } %>
                      ">
                <%= errorMsg %>
            </p>
        <% } %>
        <form method="post">
            <label for="number">Enter the Number : </label> <input type="tex" name="number" id="number" maxlength="3">
            <input type="submit" value="Submit">
        </form>
    </div>
  </body>
</html>

Angular 2 - Part 6 [ Understanding AppModule ]


In our angular-cli generated app we have one module called app.module.ts inside the app dir. So whats the use of this, as in the previous post we said that this is used to bootstrap the component but lets examine this line by line what all other stuffs it can do
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


  1. At first we are importing all the modules that are used in our app 
    1. BrowserModule :  registers critical application service providers. It also includes common directives like NgIf and NgFor which become immediately visible and usable in any of this modules component templates.
    2. NgModule: This module is used to import angular core Module lib
    3. FormsModule: This module is used to handle the input related tasks 
    4. HttpModule: This mdule is used to make http services available in our module
  2. @NgModule : It is imported from angular/core. Here we tell angular what is used in our app. 
    1. declaration: What directives we have used in our app, Components are directives. It basically tells which componets should I use through out my application.
    2. imports: which other modules should I use. like browser module is used to use other default directives.
    3. providers: is used if we want to have application wise services
    4. bootstrap:  it is used to bootstrap the components that is used in this module
  3. The export keyword enable out module to be used externally
Thats all for now. In the next session we will talk about the templates \m/

Angular 2 - Part 5 [ How Angular App get started ]


How Angular 2 App get started?
Angular 2 is a single page app and will contains only one file called index.html in the root folder. although this html file doennot even contains any js files then how the fuck it get started:

Index file
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>FirstApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>

Well when we compile and run the app then the angular-cli will dynamically add the required js files in the page. Which we can see the source in the page while its running


Well then where the fuck is our code?
The answer is it all we be inside the main.bundle.js file

here is the flow
  1. At first the angular app will always use main.ts file which will bootstrap the our app and create a js file at the run time. Inside teh main.ts file we have

    platformBrowserDynamic().bootstrapModule(AppModule);

    Which will load the AppModule from the module inside the app directory after importing it using

    import { AppModule } from './app/'; 
  2. Then the app will use the app.module.ts inside the app dir which will again bootstrap the AppComponent which we have created earlier in this series.

    bootstrap: [AppComponent]
  3. The Main this about angular 2 is that it will not load all the component at the beginning. It will only load the component which is in the index.html file which is app-root in our case. Its a lazy loading which will increase the performance.
  4. So the main flow is
    main.ts -> load the main module used in the index.html -> the main module will bootstrap the Component -> then main.ts will bootstrap the app and create a single main.bundle.js and add it to the main page -> then we enjoy :)

    Happy Coding geeks. In the next session we will talk about the AppModules \,,/



Angular 2 - Part 4 [ Understanding the Component ]



As we have seen angular is composed of lots of modules and component but what really is a component. Well we will learn this in this post

What our normal  app structure looks like - Here I am using the angular-cli


Here we have app.component.ts file inside the app directory which contains following beautiful lines of code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}

  1. The class name for this component is AppComponent
  2. The AppComponent is imported from core angular i.e. @angular/core 
  3. @Component is a decorator which makes this class something special, without this decorator this class will be nothing.
  4. Inside @Component decorator we have
    1. selector : The selector is what allow us to use our component. Its like creating our own html tag which contains certain user define properties. This selectors normally acts like a css selector. 
      1. Lets say we want to use selector as a ID or a class rather then creating this a new tag then we just need to modify selector as
        selector: '.app-root ' for class or
        selector: '#app-root' for id
        So that for eg. whenever we call div with class app-root then the same above component get loaded inside the div and for the ID as well.
    2. templateUrl : yeah! you are right every component must contains the html either inline type or may be load the different html page as shown in the given code. Here we are loading external html page in this component. If we are using the external html page then we need to use templateUrl otherwise we can write html also like

      template : '<div class="myAwesomeClass">{{title}}</div>';
    3. styleUrls: This is same as we decribed in the template section. we can define our own custom css for our componet either using the external css file or inline.
  5. export this keyword enable our component to be exported and use by other component too. 
    1. here title is a property which will be used in our template using the {{}} which is as we can compare with the scope in the angularjs 1
Thats all coders follow next tutorial for more happy coding moments \,,/



Anuglar 2 - Part 3 - Installing through Angular-Cli



we can now install the angular 2 cli in our system so that it can be used in the future with ease. It can also used to create the angular project with the simple commands in the terminal

for this we need to follow the following commands. Remember I am using the ubuntu terminal some commands can vary in windows and in mac it may need sudo permission :)

Step 1 
Install Angular-cli globally by using npm install -g angular-cli

Step 2
Make new directory using the command mkdir or whatever other technique you want. For this I am using mkdir myAngApp

Step 3
create a angular app in the above created directory using ng new <name of your project>
like ng new first-app

Step 4
now go to the project directory by cd first-app and then serve the angular project using the ng serve.
Now you can view the project in browser using localhost:3000 or what ever port your system has assigned please view the terminal for the port info.


WOW you have done it Congrats please tune for the next part for more happy coding :)

Angular 2 - Hello Angular's new world



Before starting this part please make sure that you have installed node in yout system. 
For this complete series I am using node v6.2.2 in the ubuntu 16.04 LTS system.

Step 1: Create your app directory
goto terminal or cmd and type mkdir myapp


Step 2: Open any text editor and create below files and save them in the respective dir i.e. myapp dir

Package.json : [The package.json will contain the packages that our apps require. These packages are installed and maintained with npm (Node Package Manager).]

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/common": "~2.1.0",
    "@angular/compiler": "~2.1.0",
    "@angular/core": "~2.1.0",
    "@angular/forms": "~2.1.0",
    "@angular/http": "~2.1.0",
    "@angular/platform-browser": "~2.1.0",
    "@angular/platform-browser-dynamic": "~2.1.0",
    "@angular/router": "~3.1.0",
    "@angular/upgrade": "~2.1.0",
    "angular-in-memory-web-api": "~0.1.5",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.39",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.3",
    "typings":"^1.4.0"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}

Note:: A large number of libraries of the JavaScript extends JavaScript environment with features and syntax which is not natively recognized by the TypeScript compiler. Thetypings.json file is used to identify TypeScript definition files in your Angular application.
In the above code, there are three typing files as shown below:
  1. core-js: It brings ES2015/ES6 capabilities to our ES5 browsers.
  2. jasmine: It is the typing for Jasmine test framework.
  3. node: It is used for the code that references objects in the nodejs environment.

systemjs.config.js

(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);

Step 3: To install packages
npm install

Step 4: Create new dir called app
mkdir app and create 

1. app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: '<h1>My First Angular App</h1>'
})
export class AppComponent { 
}

NOTE:: 
The above code will import the Component and View package from angular2/core.
  1. The @Component is an Angular 2 decorator that allows you to associate metadata with the component class.
  2. The my-app can be used as HTML tag to injecting and can be used as a component.
  3. The export specifies that, this component will be available outside the file.

2. app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }   from './app.component';
import { ContactComponent }   from './dataBind/dataBind.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent]
})

export class AppModule { }

3. main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

NOTE::
  1. The main.ts file tells Angular to load the component.
  2. To launch the application, we need to import both Angular's browser bootstrap function and root component of the application.

STEP 5:: Create index.html in the roor dir
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
    <data-bind></data-bind>
  </body>
</html>


STEP 6: Now Run 
using the terminal command npm start


Now the page will be opened in the browser with the text "My first Angular App" text