Sunday, December 13, 2015

Enumeration

import Cocoa

var someStrs = [String]()
var someStrs1 = [String]()
someStrs1.append("apple1")
someStrs1.append("apple2")
someStrs1 += ["Google"]

for(index,item) in enumerate(someStrs1){
println(index)
println(item)


}

someStrs.append("Apple")
someStrs.append("Amazon")
someStrs += ["Google"]

for (index, item) in enumerate(someStrs) {
   println("Value at index = \(index) is \(item)")
}

Friday, December 11, 2015

Hiding and Showing multiple tabel

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular Sort and Filter</title>

    <!-- CSS -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
    <style>
        body { padding-top:50px;
       
       
        }
       
      .ta  {
        overflow: auto;
        }
    </style>

    <!-- JS -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="js/real5.js"></script>

</head>
<body>
<div class="container" ng-app="sortApp" ng-controller="mainController">
  <p><a data-ng-click="showadd()" href="javascript:;" class="btn btn-primary">Add New User</a></p>
 
 
 
 
 
 

  <div style="width:600px;height:300px;line-height:3em;overflow:scroll;padding:5px;">



  <table class="table table-bordered table-striped">
   
    <thead>
      <tr>
        <td>
            Sushi Roll
        </td>
        <td>
          Fish Type
        </td>
        <td>
          Taste Level
        </td>
        <td>
          Taste Height
        </td>
      </tr>
    </thead>
   
    <tbody>
      <tr ng-repeat="x in names">
     
   
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="checked" ng-click="jalapenoSpicy()">
       
 
 
 
 
  </td>
        <td>{{ x.postId }}</td>
    <td>{{ x.id }}</td>
        <td>{{ x.email }}</td>
   
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
    </tbody>
   
  </table>

   </div>


<!-- for footer part  -->


<!--  <div class="container" ng-app="sortApp" ng-controller="mainController">-->
 
   <div class="alert alert-info">
    <!--  p>Sort Type: {{ sortType }}</p>
    <p>Sort Reverse: {{ sortReverse }}</p>
    <p>Search Query: {{ searchFish }}</p>-->
  </div>
  <div style="width:600px;height:300px;line-height:3em;overflow:scroll;padding:5px;">

<div class="check-element animate-hide" ng-hide="checked">

  <table class="table table-bordered table-striped">
    
    <thead>
      <tr>
        <td>
            Sushi Roll
        </td>
        <td>
          Fish Type
        </td>
        <td>
          Taste Level
        </td>
        <td>
          Taste Height
        </td>
      </tr>
    </thead>
  
    <tbody>
      <tr ng-repeat="x in names">
     
   
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="checked">
       
 
 
 
 
  </td>
        <td>{{ x.postId }}</td>
    <td>{{ x.id }}</td>
        <td>{{ x.email }}</td>
   
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
    </tbody>
  
    
  </table>

   </div>
    

 </div>


</body>
</html>




angular.module('sortApp', [])

.controller('mainController', function($scope,$http) {
  $scope.sortType     = 'name'; // set the default sort type
  $scope.sortReverse  = false;  // set the default sort order
  $scope.searchFish   = '';     // set the default search/filter term
 
  // create the list of sushi rolls
  $scope.sushi = [
    { name: 'Cali Roll', fish: 'Crab', tastiness: 2 },
    { name: 'Philly', fish: 'Tuna', tastiness: 4 },
    { name: 'Tiger', fish: 'Eel', tastiness: 7 },
    { name: 'Rainbow', fish: 'Variety', tastiness: 6 }
  ];
 
 
 
  $scope.jalapenoSpicy = function() {
      $scope.checked = !$scope.checked;
  };
 
  $http.get("http://jsonplaceholder.typicode.com/posts/1/comments")

  .success(function (response) {$scope.names = response});
 
});




Thursday, December 10, 2015

Array append() and assignment operator (+=)

import Cocoa

var someInts = [Int]()
var someStrings=[String]()

someStrings.append("a")
someStrings.append("b")
someStrings.append("c")
someStrings += ["d"]

var someVa = someStrings[3]
println(someVa)

someInts.append(20)
someInts.append(30)
someInts += [40]

var someVar = someInts[0]

println( "Value of first element is \(someVar)" )
println( "Value of second element is \(someInts[1])" )
println( "Value of third element is \(someInts[2])" )

Array Initialization and Looping

import Cocoa

var someInts = [Int](count: 3, repeatedValue: 10)
var someString=[String](count:7,repeatedValue:"10")
var somefloat=[Float](count:8,repeatedValue:1.0)

var someVar = someInts[0]
var someVar1 = someString[1]
var someVar2 = somefloat[2]
println(someVar)
println(someVar1)
println(someVar2)

for item in someInts {
   println(item)
}

for item1 in someString {
   println(item1)
}


Character

import Cocoa
let char1:Character="x"
var c="s"
var s=String ("hhfsdhfjsdhfjsdf")
var s1="fjdsfjsdfsdfs"
for ch in "Hello" {
   println(ch)
}
for ch1 in s {
println(ch1)
}
for s2 in s1{
println(s2)
}

String count and comparison

import Cocoa
// count
var varAa   = "Hello, Swift!"
var i=count(varAa)
var boolean=isEmpty(varAa)
println(boolean)

   



println( i)
// comparison
var vara="hel"
var varB   = "Hello, World!"

if vara == varB {
   println( "equal" )
} else {
   println( "e not equal" )
}

String

import Cocoa

// Empty string creation using String literal
var stringA = ""
var stringa=String ("asbss");
var sss=Int(5);
var ssss=Float(0.50);
var sssss=Bool(true);
if stringA.isEmpty {
   println( "stringA is empty" )
} else {
   println( "stringA is not empty" )
}

// Empty string creation using String instance
let stringB = String()

if stringB.isEmpty {
   println( "stringB is empty" )
} else {
   println( "stringB is not empty" )
}

fallthrough in switch

import Cocoa

var index = 100

switch index {
   case 100  :
      println( "Value of index is 100")
      fallthrough
   case 10,15  :
      println( "Value of index is either 10 or 15")
      fallthrough
   case 5  :
      println( "Value of index is 5")
   default :
      println( "default case")
}

Array

import Cocoa

var someInts:[Int] = [10, 20, 30]
var some:[Float]=[11.0,11.1,11.2]
var somestring:[String]=["abc","def","ijk","mnop"]

for index in someInts {
   println( "Value of  index is \(index)")
}
for so in some{
println(so)

}
for st in somestring{

println(st)
}



import Cocoa

var someInts:[Int] = [10, 20, 30]
var someString:[String]=["abc","def","ijk"]

for var index = 0; index < 3; ++index {
   println( "Value of someInts[\(index)] is \(someInts[index])")
}

for var index=0;index<2;++index{
println(someString[index])
}

Multiple Table and Web service call

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular Sort and Filter</title>

    <!-- CSS -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
    <style>
        body { padding-top:50px;
       
       
        }
       
      .ta  {
        overflow: auto;
        }
    </style>

    <!-- JS -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="js/real5.js"></script>

</head>
<body>
<div class="container" ng-app="sortApp" ng-controller="mainController">
 
  <div class="alert alert-info">
    <p>Sort Type: {{ sortType }}</p>
    <p>Sort Reverse: {{ sortReverse }}</p>
    <p>Search Query: {{ searchFish }}</p>
  </div>
  <div style="width:600px;height:300px;line-height:3em;overflow:scroll;padding:5px;">



  <table class="table table-bordered table-striped">
   
    <thead>
      <tr>
        <td>
            Sushi Roll
        </td>
        <td>
          Fish Type
        </td>
        <td>
          Taste Level
        </td>
        <td>
          Taste Height
        </td>
      </tr>
    </thead>
   
    <tbody>
      <tr ng-repeat="x in names">
     
   
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ x.postId }}</td>
    <td>{{ x.id }}</td>
        <td>{{ x.email }}</td>
   
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
    </tbody>
   
  </table>

   </div>
</div>

<!-- for footer part  -->


<div class="container" ng-app="sortApp" ng-controller="mainController">
 
   <div class="alert alert-info">
    <!--  p>Sort Type: {{ sortType }}</p>
    <p>Sort Reverse: {{ sortReverse }}</p>
    <p>Search Query: {{ searchFish }}</p>-->
  </div>
  <div style="width:600px;height:300px;line-height:3em;overflow:scroll;padding:5px;">



  <table class="table table-bordered table-striped">
   
    <thead>
      <tr>
        <td>
            Sushi Roll
        </td>
        <td>
          Fish Type
        </td>
        <td>
          Taste Level
        </td>
        <td>
          Taste Height
        </td>
      </tr>
    </thead>
   
    <tbody>
      <tr ng-repeat="x in names">
     
   
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ x.postId }}</td>
    <td>{{ x.id }}</td>
        <td>{{ x.email }}</td>
   
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
    </tbody>
   
  </table>

   </div>
</div>



</body>
</html>

angular.module('sortApp', [])

.controller('mainController', function($scope,$http) {
  $scope.sortType     = 'name'; // set the default sort type
  $scope.sortReverse  = false;  // set the default sort order
  $scope.searchFish   = '';     // set the default search/filter term
 
  // create the list of sushi rolls
  $scope.sushi = [
    { name: 'Cali Roll', fish: 'Crab', tastiness: 2 },
    { name: 'Philly', fish: 'Tuna', tastiness: 4 },
    { name: 'Tiger', fish: 'Eel', tastiness: 7 },
    { name: 'Rainbow', fish: 'Variety', tastiness: 6 }
  ];
 
 
  $http.get("http://jsonplaceholder.typicode.com/posts/1/comments")

  .success(function (response) {$scope.names = response});
 
});


Wednesday, December 9, 2015

Web Service and Table

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular Sort and Filter</title>

    <!-- CSS -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
    <style>
        body { padding-top:50px;
       
       
        }
       
      .ta  {
        overflow: auto;
        }
    </style>

    <!-- JS -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="js/real5.js"></script>

</head>
<body>
<div class="container" ng-app="sortApp" ng-controller="mainController">
 
  <div class="alert alert-info">
    <p>Sort Type: {{ sortType }}</p>
    <p>Sort Reverse: {{ sortReverse }}</p>
    <p>Search Query: {{ searchFish }}</p>
  </div>
  <div style="width:600px;height:300px;line-height:3em;overflow:scroll;padding:5px;">



  <table class="table table-bordered table-striped">
   
    <thead>
      <tr>
        <td>
            Sushi Roll
        </td>
        <td>
          Fish Type
        </td>
        <td>
          Taste Level
        </td>
        <td>
          Taste Height
        </td>
      </tr>
    </thead>
   
    <tbody>
      <tr ng-repeat="x in names">
     
   
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ x.postId }}</td>
    <td>{{ x.id }}</td>
        <td>{{ x.email }}</td>
   
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
    </tbody>
   
  </table>

   <div>
</div>
</body>
</html>
<!--  https://scotch.io/tutorials/sort-and-filter-a-table-using-angular-->


angular.module('sortApp', [])

.controller('mainController', function($scope,$http) {
  $scope.sortType     = 'name'; // set the default sort type
  $scope.sortReverse  = false;  // set the default sort order
  $scope.searchFish   = '';     // set the default search/filter term
 
  // create the list of sushi rolls
  $scope.sushi = [
    { name: 'Cali Roll', fish: 'Crab', tastiness: 2 },
    { name: 'Philly', fish: 'Tuna', tastiness: 4 },
    { name: 'Tiger', fish: 'Eel', tastiness: 7 },
    { name: 'Rainbow', fish: 'Variety', tastiness: 6 }
  ];
 
 
  $http.get("http://jsonplaceholder.typicode.com/posts/1/comments")

  .success(function (response) {$scope.names = response});
 
});


Tabel and scroll

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular Sort and Filter</title>

    <!-- CSS -->
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
    <style>
        body { padding-top:50px;
       
       
        }
       
      .ta  {
        overflow: auto;
        }
    </style>

    <!-- JS -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="referencereal/real5.js"></script>

</head>
<body>
<div class="container" ng-app="sortApp" ng-controller="mainController">
 
  <div class="alert alert-info">
    <p>Sort Type: {{ sortType }}</p>
    <p>Sort Reverse: {{ sortReverse }}</p>
    <p>Search Query: {{ searchFish }}</p>
  </div>
  <div style="width:600px;height:300px;line-height:3em;overflow:scroll;padding:5px;">



  <table class="table table-bordered table-striped">
   
    <thead>
      <tr>
        <td>
            Sushi Roll
        </td>
        <td>
          Fish Type
        </td>
        <td>
          Taste Level
        </td>
        <td>
          Taste Height
        </td>
      </tr>
    </thead>
   
    <tbody>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
      <tr ng-repeat="roll in sushi">
      <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
        <td>{{ roll.name }}</td>
        <td>{{ roll.fish }}</td>
        <td>{{ roll.tastiness }}</td>
      </tr>
    </tbody>
   
  </table>
  <div>
   <div>
</div>
</body>
</html>
<!--  https://scotch.io/tutorials/sort-and-filter-a-table-using-angular-->

Injecting $http and $scope and functions within controller

<!doctype html>
<html>
<head>
  <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-sanitize.min.js"></script>

  <script src="scroll/ng-scrollbar.min.js"></script>
<link rel="stylesheet" href="scroll/ng-scrollbar.min.css" >
 
 
  <style>
    .scrollme {
      max-height: 200px;
    }
  </style>
</head>
<body>

<div ng-app="myapp">
  <div class="container" ng-controller="myctrl">

    <div class="page-header">
      <h1>ngScrollBar <small>example</small></h1>
    </div>
    Bar is shown: {{barShown}}
    <div class="well" >
      <div class="scrollme" ng-scrollbar is-bar-shown="barShown">
        <table>
  <tr ng-repeat="x in names">
  <td>
 
            <input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors.red">
       
 
 
 
 
  </td>
    <td>{{ x.postId }}</td>
    <td>{{ x.id }}</td>
        <td>{{ x.email }}</td>
   
        <td>{{ x.body }}</td>
   
       
   
  </tr>
 
 
 
</table>   
       
      </div>
    </div>
  </div>
</div>

<script>
  var myapp = angular.module('myapp', ['ngSanitize', 'ngScrollbar']);
  myapp.controller('myctrl', function ($scope,$http) {
    $scope.$on('scrollbar.show', function(){
      console.log('Scrollbar show');
    });
    $scope.$on('scrollbar.hide', function(){
      console.log('Scrollbar hide');
    });
   
    $http.get("http://jsonplaceholder.typicode.com/posts/1/comments")

    .success(function (response) {$scope.names = response});
   
   
  });
</script>

</body>
</html>

Type Annotations

You can provide a type annotation when you declare a constant, to be clear about the kind of values the constant can store


import Cocoa



let constB:Float = 3.14159
let constc:Int = 3.14159// double is not allowed here 

println(constB)

println(constc)

produces following error 
main.swift:6:18: error: 'Double' is not convertible to 'Int'
let constc:Int = 3.14159

Constants Declaration

import Cocoa

let constA = 42
let constB = "abc"
let constc = 42.00
let constd = true
let conste = false
println(constA)
println(constB)
println(constc)
println(constd)
println(conste)

Optional Binding

import Cocoa

var myString:String?
var myint:Int?

myString = "Hello, Swift!"

if let yourString = myString {
   println("Your string has - \(yourString)")
}else{
   println("Your string does not have a value")
}

if let yourInt = myint {
   println("Your int has - \(yourInt)")
}else{
   println("Your yourInt does not have a value")
}

Swift - Optionals


var myString:String?
println(myString)// prints nil

By default it prints null

var perhapsStr: String?  = nil

println(myString)// prints nil


var myString:String="aa"
println(myString) // prints aa


like case it can be unwrap like

var myString:String?
myString="abc"
println(myString)


declaring multiple modules in same js file

module1.js
var app1 = angular.module('app1', []);

    app1.controller('Ctrl1', function ($scope)
    {
      $scope.name = "abishkar";
    });

    var app2 = angular.module('app2', []);

    app2.controller('Ctrl2', function ($scope)
    {
      $scope.name = "bhattarai";
    });

    angular.element(document).ready(function() {
      angular.bootstrap(document.getElementById('app2'), ['app2']);
    });  

module1.html

<script src="http://code.angularjs.org/1.2.9/angular.min.js" type="text/javascript"></script>
<script src="js/module1.js" type="text/javascript"></script>

<body>
  <div ng-app="app1">
    <div ng-controller="Ctrl1">
      <span>{{name}}</span>
    </div>
  </div>
  <div id="app2">
    <div ng-controller="Ctrl2">
      <span>{{name}}</span>
    </div>
  </div>
</body>

Sunday, December 6, 2015

Optionals

import Cocoa

var myString:String? = "dd"

if myString != nil {
   println(myString)
}else{
   println("myString has nil value")
}


import Cocoa

/* My first program in Swift */
var myString = "Hello, World!"

println(myString)
typealias Feet = Int
var distance: Feet = 100
println(distance)

typealias Feet1 = Float
var distance1: Feet1 = 200.0099
println(distance1)

var varB:Float

varB = 3.14159
println(varB)

var myString1:String? = nil

if myString1 != nil {
   println(myString)
}else{
   println("myString has nil value")
}

Basic

var myString = "Hello, World!"

println(myString)
typealias Feet = Int
var distance: Feet = 100
println(distance)

typealias Feet1 = Float
var distance1: Feet1 = 200.0099
println(distance1)

var varB:Float

varB = 3.14159
println(varB)

Saturday, December 5, 2015

AngularJS Directives

The ng-app directive initializes an AngularJS application.
The ng-init directive initializes application data.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Wednesday, December 2, 2015

Routes

index.html 
<!doctype html>

<head>
    <meta charset="utf-8">
    <title>Backbone.js Routes Example</title>

    <link rel="stylesheet" href="assets/css/bootstrap-1.2.0.min.css" />
    <link rel="stylesheet" href="assets/css/styles.css" />

    <script src="assets/js/jquery-1.6.4.min.js"></script>
    <script src="assets/js/underscore-min.js"></script>
    <script src="assets/js/backbone-min.js"></script>
    <script src="assets/js/application.js"></script>

</head>

<body>


<ul class="route">
    <li class="home-route"><a>Home</a></li>
    <li class="about-route"><a>About</a></li>
    <li class="contact-route"><a>Contact</a></li>
</ul>

<div id="home-page" class="pages">Hi I'm the home page!</div>
<div id="about-page" class="pages">Hi I'm the about page!</div>
<div id="contact-page" class="pages">Hi I'm the contact page!</div>

</body>
</html>


$(function(){

    var ApplicationRouter = Backbone.Router.extend({

        //map url routes to contained methods
        routes: {
            "": "home",
            "home": "home",
            "about": "about",
            "contact": "contact"
        },

        deselectRoutes: function(){
            //deselect all navigation Routes
            $('ul.route li').removeClass('active');
        },

        selectRoutes: function(Routes){
            //deselect all navigation Routes
            this.deselectRoutes();
            //select passed navigation Routes by selector
            $(Routes).addClass('active');
        },

        hidePages: function(){
            //hide all pages with 'pages' class
            $('div.pages').hide();
        },

        showPage: function(page){
            //hide all pages
            this.hidePages();
            //show passed page by selector
            $(page).show();
        },

        home: function() {
            this.showPage('div#home-page');
            this.selectRoutes('li.home-route');
        },

        about: function() {
            this.showPage('div#about-page');
            this.selectRoutes('li.about-route');
        },

        contact: function() {
            this.showPage('div#contact-page');
            this.selectRoutes('li.contact-route');
        }

    });

    var ApplicationView = Backbone.View.extend({

        //bind view to body element (all views should be bound to DOM elements)
        el: $('body'),

        //observe navigation click events and map to contained methods
        events: {
            'click ul.route li.home-route a': 'displayHome',
            'click ul.route li.about-route a': 'displayAbout',
            'click ul.route li.contact-route a': 'displayContact'
        },

        //called on instantiation
        initialize: function(){
            //set dependency on ApplicationRouter
            this.router = new ApplicationRouter();

            //call to begin monitoring uri and route changes
            Backbone.history.start();
        },

        displayHome: function(){
            //update url and pass true to execute route method
            this.router.navigate("home", true);
        },

        displayAbout: function(){
            //update url and pass true to execute route method
            this.router.navigate("about", true);
        },

        displayContact: function(){
            //update url and pass true to execute route method
            this.router.navigate("contact", true);
        }

    });

    //load application
    new ApplicationView();

});

Tuesday, December 1, 2015

Model,collection and Template

index.html 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>

<script id="personTemplate" type="text/template">
    <strong><%= name %></strong> (<%= age %>) - <%= occupation %>
</script>

<script src="js/underscore.js"></script>
<script src="js/jquery.js"></script>
<script src="js/backbone.js"></script>
<script src="js/main1.js"></script>
</body>
</html>


main1.js



// Person Model
var Person = Backbone.Model.extend({
    defaults: {
        name: 'Guest User',
        age: 30,
        occupation: 'worker'
    }
});

// A List of People
var PeopleCollection = Backbone.Collection.extend({
    model: Person
});


// View for all people
var PeopleView = Backbone.View.extend({
    tagName: 'ul',

    render: function() {
        this.collection.each(function(person) {
            var personView = new PersonView({ model: person });
            this.$el.append(personView.render().el);
        }, this);

        return this;
    }
});

// The View for a Person
var PersonView = Backbone.View.extend({
    tagName: 'li',


    template: _.template($('#personTemplate').html() ),
   
    render: function() {
        this.$el.html( this.template(this.model.toJSON()) );
        return this;
    }
});

var peopleCollection = new PeopleCollection([
    {
        name: 'abishkar',
        age: 26
    },
    {
        name: 'ram',
        age: 25,
        occupation: 'web designer'
    },
    {
        name: 'hari',
        age: 26,
        occupation: 'Java Developer'
    }
]);

var peopleView = new PeopleView({ collection: peopleCollection });
$(document.body).append(peopleView.render().el);

Event


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script> 
<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

<div id="search_container"></div>

<script type="text/javascript">
  var SearchView = Backbone.View.extend({
    initialize: function(){
      this.render();
    },
    render: function(){
      var template = _.template( $("#search_template").html(), {} );
      this.$el.html( template );
    },
    events: {
      "click input[type=button]": "doSearch"
    },
    doSearch: function( event ){
      // Button clicked, you can access the element that was clicked with event.currentTarget
      alert( "Search for " + $("#search_input").val() );
    }
  });

  var search_view = new SearchView({ el: $("#search_container") });
</script>

Modules

module1.html
    <!DOCTYPE html>
 
    <head>     
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
      <script src="js/script.js"></script>
      <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src="js/module1.js"></script>
      <script src="js/module2.js"></script>
    </head>
    <body>
    <div ng-app="HelloWorldApp">
    <div ng-controller="HelloWorldController">
        <h1>{{greeting}}</h1>
    </div>

   </body>
    </html>

module2.html


    <!DOCTYPE html>
 
    <head>
     

     
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
      <script src="js/script.js"></script>
      <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src="js/module1.js"></script>
      <script src="js/module2.js"></script>
    </head>
    <body>



<div ng-app="HelloUserApp">
    <div ng-controller="HelloUserController">
       
        <h1>{{greeting}}</h1>
        <h2></h2>
    </div>
</div>



 
  
  
  
  
   </body>
    </html>


module1.js

 angular.module('HelloWorldApp', [])
   .controller('HelloWorldController', function($scope) {
       $scope.greeting = "Hello World";
});
  
module2.js

 angular.module('HelloUserApp', [])
   .controller('HelloUserController', function($scope) {
       $scope.greeting = "Hello World";
   });

$routeProvider

var scotchApp = angular.module('scotchApp', []);

//configure our routes
scotchApp.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        });
});



// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
    // create a message to display in our view
    $scope.message = 'Everyone come and see how good I look!';
});

scotchApp.controller('aboutController', function($scope) {
    $scope.message = 'Look! I am an about page.';
});

scotchApp.controller('contactController', function($scope) {
    $scope.message = 'Contact us! JK. This is just a demo.';
});

Monday, November 30, 2015

Defining multiple controller

<div class="widget" ng-controller="widgetController">
    <p>Stuff here</p>
</div>

<div class="menu" ng-controller="menuController">
    <p>Other stuff here</p>
</div>
 
 
function widgetController($scope) {
   // stuff here
}

function menuController($scope) {
   // stuff here
} 

Friday, November 27, 2015

Simple post request response

$(document).ready(function() {

    //Stops the submit request
    $("#myAjaxRequestForm").submit(function(e){
           e.preventDefault();
    });
  
    //checks for the button click event
    $("#myButton").click(function(e){
         
            //get the form data and then serialize that
            dataString = $("#myAjaxRequestForm").serialize();
          
            //get the form data using another method
            var countryCode = $("input#countryCode").val();
            dataString = "countryCode=" + countryCode;
          
            //make the AJAX request, dataType is set to json
            //meaning we are expecting JSON data in response from the server
            $.ajax({
                type: "POST",
                url: "CountryInformation",
                data: dataString,
                dataType: "json",
              
                //if received a response from the server
                success: function( data, textStatus, jqXHR) {
                    //our country code was correct so we have some information to display
                     if(data.success){
                         $("#ajaxResponse").html("");
                         $("#ajaxResponse").append("<b>Country Code:</b> " + data.countryInfo.code + "<br/>");
                         $("#ajaxResponse").append("<b>Country Name:</b> " + data.countryInfo.name + "<br/>");
                         $("#ajaxResponse").append("<b>Continent:</b> " + data.countryInfo.continent + "<br/>");
                         $("#ajaxResponse").append("<b>Region:</b> " + data.countryInfo.region + "<br/>");
                         $("#ajaxResponse").append("<b>Life Expectancy:</b> " + data.countryInfo.lifeExpectancy + "<br/>");
                         $("#ajaxResponse").append("<b>GNP:</b> " + data.countryInfo.gnp + "<br/>");
                     }
                     //display error message
                     else {
                         $("#ajaxResponse").html("<div><b>Country code in Invalid!</b></div>");
                     }
                },
              
                //If there was no resonse from the server
                error: function(jqXHR, textStatus, errorThrown){
                     console.log("Something really bad happened " + textStatus);
                      $("#ajaxResponse").html(jqXHR.responseText);
                },
              
                //capture the request before it was sent to server
                beforeSend: function(jqXHR, settings){
                    //adding some Dummy data to the request
                    settings.data += "&dummyData=whatever";
                    //disable the button until we get the response
                    $('#myButton').attr("disabled", true);
                },
              
                //this is called after the response or error functions are finsihed
                //so that we can take some action
                complete: function(jqXHR, textStatus){
                    //enable the button
                    $('#myButton').attr("disabled", false);
                }
    
            });       
    });

});


<html>
<head>
    <title>jQuery Ajax POST data Request and Response Example</title>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="app.js"></script>

</head>
<body>

    <form id="myAjaxRequestForm">
        <fieldset>
            <legend>jQuery Ajax Form data Submit Request</legend>

                <p>
                    <label for="countryCode">Country Code:</label><br />
                    <input id="countryCode" type="text" name="countryCode" />
                </p>
                <p>
                    <input id="myButton" type="button" value="Submit" />
                </p>
        </fieldset>
    </form>
    <div id="anotherSection">
        <fieldset>
            <legend>Response from jQuery Ajax Request</legend>
                 <div id="ajaxResponse"></div>
        </fieldset>
    </div>  

</body>
</html>

Simple Ajax request response

<!DOCTYPE html>
<html>
    <head>
        <title>Hello jQuery</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="app.js"></script>
    </head>

    <body>
        <div>
            <p class="greeting-id">The ID is </p>
            <p class="greeting-content">The content is </p>
        </div>
    </body>
</html>


$(document).ready(function() {
    $.ajax({
        url: "http://rest-service.guides.spring.io/greeting"
    }).then(function(data) {
       $('.greeting-id').append(data.id);
       $('.greeting-content').append(data.content);
    });
});

Thursday, November 26, 2015

Backbone.Collection

collections are ordered sets of models, where you can get and set models in the collection, listen for events when any element in the collection changes, and fetching for model’s data from the server

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>To-do App in Backbone.js</title>
 
  <!-- ========= -->
  <!--    CSS    -->
  <!-- ========= -->
  <style type="text/css">
    /* Hides bullet points from todo list */
    #todoapp ul {
      list-style-type: none;
    }
  </style> 
</head>
<body>
  <!-- ========= -->
  <!-- Your HTML -->
  <!-- ========= -->

    <section id="todoapp">
    <header id="header">
      <h1>Todos</h1>
      <input id="new-todo" placeholder="">
    </header>
    <section id="main">
      <ul id="todo-list"></ul>
    </section>
  </section>
 

 

  <!-- ========= -->
  <!-- Libraries -->
  <!-- ========= -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script>

  <!-- =============== -->
  <!-- Javascript code -->
  <!-- =============== -->
  <script type="text/javascript">
    'use strict';

    var app = {}; // create namespace for our app
   
    //--------------
    // Models
    //--------------
    app.Todo = Backbone.Model.extend({
      defaults: {
        title: '',
        completed: false
      }
    });

    app.TodoList = Backbone.Collection.extend({
        model: app.Todo,
        localStorage: new Store("backbone-todo")
      });

      // instance of the Collection
      app.todoList = new app.TodoList();

   
  
    //--------------
    // Initializers
    //--------------  

    app.appView = new app.AppView();

  </script>
 
</body>
</html>

Backbone.Model

Models  contains the interactive data and the logic surrounding it, such as data validation, getters and setters, default values, data initialization, conversions .

following code creates model with 2 instance variables  title and completed
var app = {}; // create namespace for our app

    app.Todo = Backbone.Model.extend({
      defaults: {
        title: '',
        completed: false
      }
    });

execute following in browser console 
var todo = new app.Todo({title: 'Learn Backbone.js', completed: false}); // create object with the attributes specified.
todo.get('title'); // "Learn Backbone.js" 

Backbone’s Templates

Backbone has a utility/helper library called underscore.js and you can use their template solution out of box.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Hello World in Backbone.js</title>
</head>
<body>
  <!-- ========= -->
  <!-- Your HTML -->
  <!-- ========= -->

  <div id="container">Loading...</div>

  <!-- ========= -->
  <!-- Libraries -->
  <!-- ========= -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script> 
 
  <!-- =============== -->
  <!-- Javascript code -->
  <!-- =============== -->
  <script type="text/javascript">
    var AppView = Backbone.View.extend({
      el: $('#container'),
      // template
      template: _.template("<h3>Hello <%= who %><h3>"),
      initialize: function(){
        this.render();
      },
      render: function(){
        this.$el.html(this.template({who: 'world!'}));
      }
    });

    var appView = new AppView();
  </script>
 
</body>
</html>

Backbone’s Views

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Hello World in Backbone.js</title>
</head>
<body>
  <div id="container">Loading...</div>
  <!-- ========= -->
  <!-- Your HTML -->
  <!-- ========= -->

  <!-- ========= -->
  <!-- Libraries -->
  <!-- ========= -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.0/backbone.localStorage-min.js" type="text/javascript"></script> 
 
  <!-- =============== -->
  <!-- Javascript code -->
  <!-- =============== -->
  <script type="text/javascript">
  var AppView = Backbone.View.extend({
      // el - stands for element. Every view has a element associate in with HTML
      //      content will be rendered.
      el: '#container',
      // It's the first function called when this view it's instantiated.
      initialize: function(){
        this.render();
      },
      // $el - it's a cached jQuery object (el), in which you can use jQuery functions
      //       to push content. Like the Hello World in this case.
      render: function(){
        this.$el.html("Hello World");
      }
    });
  //var appView = new AppView();
  </script>
 
</body>
</html>

Transition from one event to another using web service

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">


<p ng-hide="myVar">
User name: <input type=text ng-model="names.id"><br>
Password: <input type=text ng-model="names.title"><br><br>

<button ng-click="toggle()">submit</button>

</p>

<p ng-hide="myVar1">
welcome
<p></p>
User name: <input type=text ng-model="names.id"><br>
Password: <input type=text ng-model="names.title"><br><br>


</p>



</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope,$http) {
    $scope.firstName = "John",
    $scope.lastName = "Doe"
   
   

    $scope.toggle = function() {
        $scope.myVar = !$scope.myVar;
        $scope.myVar1 = $scope.myVar1;
        $http.get("http://jsonplaceholder.typicode.com/posts/1")

        .success(function (response) {
           
            $scope.names = response;
            $scope.id=names.postId;
            $scope.title=names.title;
           


           
        }
       
        );
    };
});
</script>

</body>
</html>

Event and Web Service

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">


<p ng-hide="myVar">
First Name: <input type=text ng-model="names.id"><br>
Last Name: <input type=text ng-model="names.title"><br><br>

<button ng-click="toggle()">submit</button>

</p>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope,$http) {
    $scope.firstName = "John",
    $scope.lastName = "Doe"
    $scope.myVar = false;
    $scope.toggle = function() {
        $http.get("http://jsonplaceholder.typicode.com/posts/1")

        .success(function (response) {
           
            $scope.names = response;
            $scope.id=names.postId;
            $scope.title=names.title;

           
        }
       
        );
    };
});
</script>

</body>
</html>

Setting data from web service

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example60-production</title>
 

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
 

 
</head>
<body ng-app="bindExample">
  <script>
  var app = angular.module('bindExample', []);
  app.controller('ExampleController', function($scope, $http) {
      $http.get("http://jsonplaceholder.typicode.com/posts/1")

    .success(function (response) {
       
        $scope.names = response;
        $scope.id=names.postId;
        $scope.title=names.title;

       
    }
   
    );
  });
</script>
<div ng-controller="ExampleController">
    <label>Id <input type="text" ng-model="names.id"></label><br>
        <label>Msg <input type="text" ng-model="names.title"></label><br>
   
    
 
 
</div>
</body>
</html>

ContextLoaderListener

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringMVCloginExample</display-name>
  <!-- <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> -->
 
  <servlet>
<servlet-name>springLoginApplication</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--  <init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath://resource//springWeb.xml</param-value>
</init-param>-->
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
      <servlet-name>springLoginApplication</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
 
</web-app>

This configuration does not searches for applicationcontext.xml file but also searches for springLoginApplication-servlet.xml in WEB-INF folder .You can import other xml file in springLoginApplication-servlet.xml WEB-INF folder

content of springLoginApplication-servlet.xml  and springBeanConfiguration.xml file must be within
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.jcg" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/jsp/" />
      <property name="suffix" value=".jsp" />
     
   </bean>
 

   
   
   
     
 
   
     
 
 




<import resource="springBeanConfiguration.xml"/>


</beans>