Responsive Web Design – Sample Code

Responsive Web Design – Sample Code

Created By: Debasis Das (25-Nov-2016)

There is no doubt that Websites needs to be designed to be responsive to different viewing areas and should be usable with equal ease in mobile, tablets and computer browser which has varied viewing areas.

However do we really need to start from scratch to develop a responsive website. Answer is no when there are magnificent CSS Templates like bootstrap that already handles it with ease and is easy to learn and implement. Bootstrap is well tested and used in millions of websites today.

In this article we are not suggesting to build your own responsive web design templates but rather focusing on the concept of RWD using some simple examples. For actual use one should rather use bootstrap.

RWD Sample 1

https://knowstack.github.io/html/rwd.html

rwd-2
rwd-1

<!doctype html>
<html lang="en">
<head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
    box-sizing: border-box;
}

[class*="col-"] {
    float: left;
    padding-top: 10px;
    padding-right:10px;
    padding-bottom:10px;
    padding-left:10px;
}
.row::after {
    content: "";
    clear: both;
    display: block;
}
.header{
	background-color: #239B56;
	padding:15px;
	color:#FFFFFF;
	border-radius: 0px;
	border:1px solid #989898;
}
.footer {
    background-color: #58D68D;
    color: #FFFFFF;
    text-align: center;
    font-size: 1.2em;
    padding: 15px;
    border-radius: 0px;
    border:1px solid #989898;
}
.well{
	background-color:#82E0AA; 
	border:1px solid #989898;
	border-radius: 5px;
	padding:10px;
}

    #main {
        min-height: 500px;
        background-color: #D1F2EB;
        padding:10px;
        border:1px solid #989898;
    }

/* For mobile phones: */
[class*="col-"] {
    width: 100%;
}
@media only screen and (min-width: 768px) {
    /* For desktop: */
    .col-1 {width: 8.33%;}
    .col-2 {width: 16.66%;}
    .col-3 {width: 25%;}
    .col-4 {width: 33.33%;}
    .col-5 {width: 41.66%;}
    .col-6 {width: 50%;}
    .col-7 {width: 58.33%;}
    .col-8 {width: 66.66%;}
    .col-9 {width: 75%;}
    .col-10 {width: 83.33%;}
    .col-11 {width: 91.66%;}
    .col-12 {width: 100%;}
}
</style>
</head>
<body>
<div class = "header" >
<h1>Responsive Web Design - Sample</h1>
</div>

<div class="row" id="main">
	<div class="col-3" > 
	<div class="well">
		3 Columns 
		<ul>
			<li>Home</li>
			<li>Page 1</li>
			<li>Page 2</li>
			<li>Page 3</li>
			<li>Contact Us</li>
	    </ul>
	</div>
	</div>
	<div class="col-6">
	<div class="well"> 6 Columns 
	Details<br>
	Details<br>
	Details<br>
	Details<br>
	Details<br>
	Details<br>
	</div>
	
	</div>
	<div class="col-3" > 
	
	<div class="well">3 Columns </div>
	</div>
</div>

<div class="footer">
  <p>Resize the browser window to see how the content respond to the resizing.</p>
</div>
</body>
</html>

RWD Sample 2

https://knowstack.github.io/html/rwdflex.html

rwd-flex-1
rwd-flex-2

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
    body {
        font: 24px Helvetica;
        background: #000000;
    }

    #main {
        min-height: 500px;
        margin: 0px;
        padding: 0px;
        display: flex;
        flex-flow: row;
    }
 
    #main > article {
        margin: 4px;
        padding: 5px;
        border: 1px solid #cccc33;
        border-radius: 7pt;
        background: #F7DC6F;
        flex: 3 1 60%;
        order: 2;
    }

    #main > nav {
        margin: 4px;
        padding: 5px;
        border: 1px solid #888888;
        border-radius: 7pt;
        background: #F1C40F;
        flex: 1 6 20%;
        order: 1;
    }
  
    #main > aside {
        margin: 4px;
        padding: 5px;
        border: 1px solid #888888;
        border-radius: 7pt;
        background: #B9770E;
        flex: 1 6 20%;
        order: 3;
    }
 
    header, footer {
        display: block;
        margin: 4px;
        padding: 5px;
        min-height: 100px;
        border: 1px solid #eebb55;
        border-radius: 7pt;
        background: #A04000;
    }
 
    /* Too narrow to support three columns */
    @media all and (max-width: 640px) {
        #main, #page {
            flex-direction: column;
        }

        #main > article, #main > nav, #main > aside {
        /* Return them to document order */
            order: 0;
        }
  
        #main > nav, #main > aside, header, footer {
            min-height: 50px;
            max-height: 50px;
        }
    }
    </style>
  </head>
  <body>
    <header>header</header>
    <div id='main'>
      <article>article</article>
      <nav>nav</nav>
      <aside>aside</aside>
    </div>
    <footer>footer</footer>
  </body>
</html>
Posted in CSS, HTML5, Web Technology Tagged with: ,

HTML5 Color Code

HTML5 Color Code

Created By: Debasis Das (25-Nov-2016) 

Placeholder for different color code palettes and themes for websites and presentation slide decks

html5-color-code-palette-1

html5-color-code-pallete-2

Posted in CSS, HTML5 Tagged with: , , ,

Angularjs To Do List Manager

Angularjs To Do List Manager

Created By: Debasis Das (21-Nov-2016)

Online Demo at https://knowstack.github.io/angularjs/todolist/

Download the source code at https://github.com/knowstack/angularjs/tree/master/todolist

angularjs todo list manager

angularjs todo list manager

Angularjs ToDo List Manager Source Code

<!doctype html>
<html lang="en" ng-app = 'KSTodoListTracker'>
  <head>
    <title>Knowstack To Do List Tracker</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="angular.min.js"></script>
    <link rel="stylesheet" href="styles/bootstrap.min.css">
    <style>
      .emptyMessage {
        font-weight: bold;
        color: red;
        font-size: 1.2em;
      }
      li {
        margin-bottom: 7px;
        font-size: 1.2em;
      }
      li > button {
        margin-left: 6px;
      }
      button > span {
        color: green;
      }
    </style>
    <script>
    
    (function () {
	'use strict';

		angular.module('KSTodoListTracker', [])
		.controller('ToDoListController', ToDoListController)
		.controller('CompletedItemsController', CompletedItemsController)
		.service('ToDoListService', ToDoListService);

		ToDoListController.$inject = ['ToDoListService'];
		CompletedItemsController.$inject = ['ToDoListService'];
		ToDoListService.$inject = ['$filter'];
		
		function ToDoListController(ToDoListService) {
			var showList = this;
	  		showList.items = ToDoListService.getTodoList();
	  		showList.newItem = "";

  			showList.completeToDoItem = function(itemIdex){
    		var itemName = showList.items[itemIdex]["name"];
    		ToDoListService.addCompletedItem(itemName);
    		ToDoListService.removeToDoItem(itemIdex);
  			};
  			
  			showList.deleteToDoItem = function(itemIndex){
  			ToDoListService.removeToDoItem(itemIndex);
  			};
  			
  			showList.addNewItem = function () {
    			ToDoListService.addToDoItem(showList.newItem);
  			}
		}

		function CompletedItemsController(ToDoListService) {
		  var showList = this;
		  showList.items = ToDoListService.getCompletedList();
		  showList.deleteCompletedItem = function(itemIndex){
		  ToDoListService.removeCompletedItem(itemIndex);
		  };
		}



		function ToDoListService($filter) {
		  var service = this;
		  var todoList = [];
		  var completedList = [];

		  service.getTodoList = function () {
			return todoList;
		  };
		  
		  service.getCompletedList = function () {
			return completedList;
		  };

		  service.removeToDoItem = function (itemIdex) {
			todoList.splice(itemIdex, 1);
		  };

		 service.removeCompletedItem = function(itemIndex){
		 	completedList.splice(itemIndex,1);
		 };
		 
		 service.addToDoItem = function(itemName){
		   var item = {
				name: itemName
				};
				todoList.push(item);
		 };

		 service.addCompletedItem = function(itemName){
		   var finalStr = itemName + ' completed on - ' +  $filter('date')(new Date(), 'yyyy-MM-dd hh:mm');
		   var item = {
				name: finalStr
				};
				completedList.push(item);
		 };
	}
})();

</script>
  </head>
<body>
  <div class="container">
  <h1>Knowstack To Do List Manager</h1>
  <div class="row">
    <div id="list1" class="col-md-6" ng-controller='ToDoListController as list1'>
       <h2>To Do:</h2>
       <form ng-submit="list1.addNewItem();" >
       <input type="text" class="form-control" ng-model="list1.newItem" placeholder="New To Do Item" >
       </form>
       <br>
       <ul class="list-group">
        <li class="list-group-item" ng-repeat="item in list1.items">
          {{ item.name }}
          <button type="button" class="btn btn-success btn-xs" ng-click="list1.completeToDoItem($index);">Mark as Complete</button>
          <button type="button" class="btn btn-danger btn-xs" ng-click="list1.deleteToDoItem($index);">Delete</button>
        </li>
      </ul>
    </div>
</div>
  <div class="row">
    <div id="list2" class="col-md-6" ng-controller='CompletedItemsController as list2'>
       <h2>Completed:</h2>
       <ul class="list-group">
        <li class="list-group-item" ng-repeat="item in list2.items">
         	{{ item.name}}
         	<button type="button" class="btn btn-danger btn-xs" ng-click="list2.deleteCompletedItem($index);">Delete</button>
        </li>
      </ul>
    </div>
</body>
</html>

Posted in angularjs, CSS, HTML5, Web Technology Tagged with: , ,

Table Filter in angularjs

Table Filter in angularjs

Created By:Debasis Das (15-Nov-2016)

In this post we will create a simple table with data read from a javascript array and using the ng-repeat command will load the same in a html table followed by filtering capability.

The filter applies to all the table column data elements

The demo can be found at https://knowstack.github.io/angularjs/filterTable/

angularjs-table-filter

angularjs-table-filter

HTML code (index.html)

<!doctype html>
<html lang="en" ng-app="TableFilterApp">
  <head>
    <title>Table Filter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="angular.min.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <style>

    </style>
  </head>
<body ng-controller="TableFilterAppController">
  <input type="text" class="form-control" placeholder="Enter Search Criteria" ng-model="searchQuery">
  <table>
    <thead>
      <tr>
        <th><a href="#" ng-click="sortType = 'empId'; sortReverse = !sortReverse"> Emp Id </a></th>
        <th><a href="#" ng-click="sortType = 'firstName'; sortReverse = !sortReverse"> First Name</a></th>
        <th><a href="#" ng-click="sortType = 'lastName'; sortReverse = !sortReverse"> Last Name </a></th>
        <th><a href="#" ng-click="sortType = 'emailId'; sortReverse = !sortReverse"> Email Id</a></th>
    </thead>
    <tbody>
      <tr ng-repeat="employee in employees | orderBy:sortType:sortReverse | filter:searchQuery">
        <td>{{ employee.empId }}</td>
        <td>{{ employee.firstName }}</td>
        <td>{{ employee.lastName }}</td>
        <td>{{employee.emailId}}</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

JS Code – app.js

(function () {
'use strict';
angular.module('TableFilterApp', [])
.controller('TableFilterAppController', TableFilterAppController);

TableFilterAppController.$inject = ['$scope'];
function TableFilterAppController($scope) {
$scope.sortType='firstName';
$scope.sortReverse  = false;
$scope.searchQuery = '';
$scope.employees = [
  {empId:1000,firstName:'John',lastName:'Doe',emailId:'johndoe@knowstack.com'},
  {empId:1001,firstName:'Jane',lastName:'Doe',emailId:'janedoe@knowstack.com'},
  {empId:1002,firstName:'Mary',lastName:'Jane',emailId:'maryjane@knowstack.com'},
  {empId:1003,firstName:'William',lastName:'Smith',emailId:'williamsmith@knowstack.com'},
  {empId:1004,firstName:'Nishant',lastName:'Singh',emailId:'nishantsingh@knowstack.com'},
  {empId:1005,firstName:'Nishant',lastName:'Nishanko',emailId:'nishantnishanko@knowstack.com'},
  {empId:1006,firstName:'Robert',lastName:'Baratheon',emailId:'robert@knowstack.com'},
  {empId:1007,firstName:'Eddard',lastName:'Stark',emailId:'eddard@knowstack.com'},
  {empId:1008,firstName:'John',lastName:'Snow',emailId:'johnsnow@knowstack.com'},
  {empId:1009,firstName:'Rob',lastName:'Stark',emailId:'robstark@knowstack.com'},
];
}
})();

CSS code – style.css

body{
  padding: 20px;
}
table{
  margin-top: 10px;
  border: solid 1px;
  border-collapse: collapse;
}

th,td{
  border: 1px solid black;
}
th{
  background-color: #CCCCCC;
  font-size: 16px;
}
tr:hover {background-color: #f5f5f5}
tr:nth-child(even) {background-color: #eeccff}

Demo @ https://knowstack.github.io/angularjs/filterTable/
Download the source code from https://github.com/knowstack/angularjs/tree/master/filterTable

Posted in angularjs, CSS, HTML5, Web Technology Tagged with: , ,

R Programming Date and Time Tutorial

R Programming Date and Time Tutorial

Created By: Debasis Das (4-Sep-2016)

In this tutorial we will see how date and time works in R Programming and we will create a lot of samples

Date & Time in R

  • In R Programming Dates are represented by the Date Class and Times are represented by the POSIXct and POSIXlt classes.
  • Dates are stored internally as the number of days since 1970-01-01
  • In POSIXct Times are stored internally as the number of seconds since 1970-01-01
  • In POSIXlt times are stored as list of seconds, minutes, hours etc

Date and Time in R Programming

Sys.date()

lets get started with an example
> date1 <- Sys.Date()
> date1
[1] “2016-09-04″
> class(date1)
[1] “Date”
> unclass(date1)
[1] 17048
when we unclassed date1 we saw the number of days passed since 1970-01-01

as.Date()

We can also create dates using as.Date() function
> date2 <- as.Date(“2016-09-09″)
> date2
[1] “2016-09-09″
> class(date2)
[1] “Date”
> unclass(date2)
[1] 17053

For creating dates prior to 1970-01-01
> date3<-as.Date(“1967-01-01″)
> date3
[1] “1967-01-01″
> class(date3)
[1] “Date”
> unclass(date3)
[1] -1096
Here the date is stored as a negative number as the date is earlier than 1970-01-01


> weekdays(date1)
[1] “Sunday”
> format(date1,”%d %b %Y”)
[1] “04 Sep 2016″
> date4<-as.Date(“04/21/2016″, format=”%m/%d/%Y”)
> date4
[1] “2016-04-21″
> date5<-as.Date(“October 10,2016″,format = “%B %d,%Y”)
> date5
[1] “2016-10-10″

> weekdays(date5)
[1] “Monday”
> months(date5)
[1] “October”
> weekdays(time5)
[1] “Sunday”
> months(time5)
[1] “September”
> quarters(time5)
[1] “Q3″
> julian(time5)
Time difference of 17048.63 days
> julian(time5,origin = as.POSIXct(“2000-01-01″, tz = “GMT”))
Time difference of 6091.626 days


Formatting the date

The following symbols can be used with the format() function to print dates

%d – day as a number (0-31)

%a – abbreviated weekday (Mon)

%A – Unabbreviated weekday (Monday)

%m – month (00-12)

%b – abbreviated month – Jan

%B – unabbreviated month (January)

%y – 2 digit year (16)

%Y – 4 digit year (2016)

> today<-Sys.Date()
> today
[1] “2016-09-04″
> format(today, format=”%d-%m-%y”)
[1] “04-09-16″
> format(today, format=”%d-%m-%Y”)
[1] “04-09-2016″
> format(today, format=”%d-%b-%Y”)
[1] “04-Sep-2016″
> format(today, format=”%d-%B-%Y”)
[1] “04-September-2016″
> format(today, format=”%a %d-%B-%Y”)
[1] “Sun 04-September-2016″
> format(today, format=”%A %d-%B-%Y”)
[1] “Sunday 04-September-2016″


 

Time difference using difftime

> date4-date5
Time difference of -172 days
> date5-date4
Time difference of 172 days

> difftime(date5, date4, units = “weeks”)
Time difference of 24.57143 weeks
> difftime(date5, date4, units = “hours”)
Time difference of 4128 hours
> difftime(date5, date4, units = “secs”)
Time difference of 14860800 secs
> difftime(date5, date4, units = “days”)
Time difference of 172 days
> difftime(date5, date4, units = “mins”)
Time difference of 247680 mins
> difftime(date5, date4, units = “auto”)
Time difference of 172 days
> difftime(date5, date4) #units not specified here, so default should be used
Time difference of 172 days

> dateVec<-as.Date(c(“2016-01-01″,”2017-01-01″,”2019-01-01″))
> dateVec
[1] “2016-01-01″ “2017-01-01″ “2019-01-01″
> diff(dateVec)
Time differences in days
[1] 366 730


Creating a sequence of dates

> date5
[1] “2016-10-10″
> dateSequence<-seq(date5, length=10, by = “day”)
> dateSequence
[1] “2016-10-10″ “2016-10-11″ “2016-10-12″ “2016-10-13″ “2016-10-14″ “2016-10-15″ “2016-10-16″ “2016-10-17″ “2016-10-18″ “2016-10-19″
> dateSequence1<-seq(date5, length=10, by = “week”)
> dateSequence1
[1] “2016-10-10″ “2016-10-17″ “2016-10-24″ “2016-10-31″ “2016-11-07″ “2016-11-14″ “2016-11-21″ “2016-11-28″ “2016-12-05″ “2016-12-12″
> dateSequence2<-seq(date5, length=10, by = 2) #skipping one day, alternate day
> dateSequence2
[1] “2016-10-10″ “2016-10-12″ “2016-10-14″ “2016-10-16″ “2016-10-18″ “2016-10-20″ “2016-10-22″ “2016-10-24″ “2016-10-26″ “2016-10-28″


 

POSIXCt

> time1<-as.POSIXct(“2016-09-05 22:32:12″)
> time1
[1] “2016-09-05 22:32:12 IST”

> time2 <- as.POSIXct(“2016-09-06 18:32:07″, format = “%Y-%m-%d %H:%M:%S”)
> time2
[1] “2016-09-06 18:32:07 IST”

> time2-time1
Time difference of 19.99861 hours

> time2>time1
[1] TRUE

> time3<-time2+24
> time3
[1] “2016-09-06 18:32:31 IST”
> time2
[1] “2016-09-06 18:32:07 IST”
> time3-time2
Time difference of 24 secs

> unclass(time3)
[1] 1473166951


 

POSIXlt

> time4<-as.POSIXlt(“2016-09-04 23:56:23″)
> time4
[1] “2016-09-04 23:56:23 IST”
> unclass(time4)
$sec
[1] 23

$min
[1] 56

$hour
[1] 23

$mday
[1] 4

$mon
[1] 8

$year
[1] 116

$wday
[1] 0

$yday
[1] 247

$isdst
[1] 0

$zone
[1] “IST”

$gmtoff
[1] NA

> unlist(time4)
sec min hour mday mon year wday yday isdst zone gmtoff
“23” “56” “23” “4” “8” “116” “0” “247” “0” “IST” NA

> time4$sec
[1] 23
> time4$mday
[1] 4
> time4$zone
[1] “IST”

> str(unclass(time4))
List of 11
$ sec : num 23
$ min : int 56
$ hour : int 23
$ mday : int 4
$ mon : int 8
$ year : int 116
$ wday : int 0
$ yday : int 247
$ isdst : int 0
$ zone : chr “IST”
$ gmtoff: int NA

> time5<-as.POSIXlt(Sys.time())
> time5
[1] “2016-09-04 20:31:23 IST”
> class(time5)
[1] “POSIXlt” “POSIXt”

> str(unclass(time5))
List of 11
$ sec : num 23.9
$ min : int 31
$ hour : int 20
$ mday : int 4
$ mon : int 8
$ year : int 116
$ wday : int 0
$ yday : int 247
$ isdst : int 0
$ zone : chr “IST”
$ gmtoff: int 19800
– attr(*, “tzone”)= chr [1:3] “” “IST” “IST”

> time6<-“October 17, 1986 08:24″
> time6Created<-strptime(time6, “%B %d, %Y %H:%M”)
> time6Created
[1] “1986-10-17 08:24:00 IST”
> class(time6Created)
[1] “POSIXlt” “POSIXt”

Posted in R Programming Tagged with: , , , ,

R Data Frame Tutorial

R Data Frame Tutorial

By Debasis Das (29-Aug-2016)

In this R Data Frame tutorial we will load a data frame from a csv file and work on the data frame

Our csv has the following columns

  1. geo
  2. country
  3. product
  4. price
  5. unitsales
  6. revenue

You can download the csv used in this tutorial here UnitSales
R Data Frame CSV Snapshot

Check the current working directory

> getwd()
[1] "/Users/debasisdas"

Change the working directory

#set the working directory to the place where the csv is located
> setwd("/Users/debasisdas/Technology/R/")
> getwd()
[1] "/Users/debasisdas/Technology/R"

Load a data frame from a csv

> unitsales <- read.csv("UnitSales.csv") 
> unitsales
        geo      country     product price salesunit revenue
1  americas          usa    computer   800       100   80000
2  americas          usa     speaker    50        20    1000
3  americas          usa     monitor   150       200   30000
4  americas          usa accessories    30       100    3000
5  americas       mexico    computer   800       200  160000
6  americas       mexico     speaker    50        32    1600
7  americas       mexico     monitor   150       212   31800
8  americas       mexico accessories    30       432   12960
9  americas       brazil    computer   800       456  364800
10 americas       brazil     speaker    50       777   38850
11 americas       brazil     monitor   150       876  131400
12 americas       brazil accessories    30       987   29610
13     asia        india    computer   800       654  523200
14     asia        india     speaker    50       456   22800
15     asia        india     monitor   150       678  101700
16     asia        india accessories    30       102    3060
17     asia        china    computer   800       111   88800
18     asia        china     speaker    50        21    1050
19     asia        china     monitor   150        32    4800
20     asia        china accessories    30        32     960
21     asia rest of asia    computer   800        32   25600
22     asia rest of asia     speaker    50        11     550
23     asia rest of asia     monitor   150        11    1650
24     asia rest of asia accessories    30        11     330

Check the class of the object created by reading from csv

> class(unitsales)
[1] "data.frame"

Check the dimensions of the unitsales object

> dim(unitsales)
[1] 24  6
> length(unitsales)
[1] 6
> attributes(unitsales)
$names
[1] "geo"       "country"   "product"   "price"     "salesunit" "revenue"  

$class
[1] "data.frame"

$row.names
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

Check the number of rows and number of columns in a data frame

> nrow(unitsales)
[1] 24
> ncol(unitsales)
[1] 6

Data frame head function

> #Instead of printing out the entire data frame, it is often desirable to preview it with the head function beforehand.
> head(unitsales)
       geo country     product price salesunit revenue
1 americas     usa    computer   800       100   80000
2 americas     usa     speaker    50        20    1000
3 americas     usa     monitor   150       200   30000
4 americas     usa accessories    30       100    3000
5 americas  mexico    computer   800       200  160000
6 americas  mexico     speaker    50        32    1600

Get specific columns from the data frame

> #print only specific columns
> unitsales[c("geo","country","product","salesunit")]
        geo      country     product salesunit
1  americas          usa    computer       100
2  americas          usa     speaker        20
3  americas          usa     monitor       200
4  americas          usa accessories       100
5  americas       mexico    computer       200
6  americas       mexico     speaker        32
7  americas       mexico     monitor       212
8  americas       mexico accessories       432
9  americas       brazil    computer       456
10 americas       brazil     speaker       777
11 americas       brazil     monitor       876
12 americas       brazil accessories       987
13     asia        india    computer       654
14     asia        india     speaker       456
15     asia        india     monitor       678
16     asia        india accessories       102
17     asia        china    computer       111
18     asia        china     speaker        21
19     asia        china     monitor        32
20     asia        china accessories        32
21     asia rest of asia    computer        32
22     asia rest of asia     speaker        11
23     asia rest of asia     monitor        11
24     asia rest of asia accessories        11

Summary of data frame

> #print the summary of the unitsales data frame
> summary(unitsales)
       geo             country         product      price         salesunit        revenue      
 americas:12   brazil      :4   accessories:6   Min.   : 30.0   Min.   : 11.0   Min.   :   330  
 asia    :12   china       :4   computer   :6   1st Qu.: 45.0   1st Qu.: 32.0   1st Qu.:  1638  
               india       :4   monitor    :6   Median :100.0   Median :106.5   Median : 24200  
               mexico      :4   speaker    :6   Mean   :257.5   Mean   :272.6   Mean   : 69147  
               rest of asia:4                   3rd Qu.:312.5   3rd Qu.:456.0   3rd Qu.: 82200  
               usa         :4                   Max.   :800.0   Max.   :987.0   Max.   :523200  

Subset of data frame

> #subset
> #get the data only for usa
> subset(unitsales, country=="usa")
       geo country     product price salesunit revenue
1 americas     usa    computer   800       100   80000
2 americas     usa     speaker    50        20    1000
3 americas     usa     monitor   150       200   30000
4 americas     usa accessories    30       100    3000

Subset a data frame based on a condition

> #get the data only for usa and computers
> subset(unitsales, country=="usa" & product == "computer")
       geo country  product price salesunit revenue
1 americas     usa computer   800       100   80000


> #get the total revenue for all geos
> sum(unitsales["revenue"])
[1] 1659520

> #get the total revenue for geo = americas
> sum(subset(unitsales,geo=="americas")["revenue"])
[1] 885020

Aggregate a data frame

> #aggregate by country and revenue
> aggregate(unitsales$revenue, by = list(country=unitsales$country), FUN=sum)
       country      x
1       brazil 564660
2        china  95610
3        india 650760
4       mexico 206360
5 rest of asia  28130
6          usa 114000


> #aggregate by geo and revenue
> aggregate(unitsales$revenue, by = list(geo=unitsales$geo), FUN=sum)
       geo      x
1 americas 885020
2     asia 774500

Posted in R Programming Tagged with: , ,

Swift MapKit Annotation

Swift MapKit Annotation

Created By : Debasis Das (31-July-2016)

We will be working in a series of Sample Code and Proof of concepts to play around MapKit.framework.

This article is the first in the series to demonstrate swift mapkit annotation

Here we will load a MapView from a Plist files which contains the latitude and longitude of different places/cities in India.

We will use the simple pin annotations in the sample code

 

The output of the program is as given below

Swift Mapkit Annotation 1

Swift Mapkit Annotation 1

Swift Mapkit Annotation 2

Swift Mapkit Annotation 2

Sample Code

//  AppDelegate.swift
//  MapSampleOne
//  Created by Debasis Das on 28/07/16.
//  Copyright © 2016 Knowstack.com. All rights reserved.

import Cocoa
import MapKit

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, MKMapViewDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var mapView:MKMapView!
    var mapAnnotations:[PinAnnotation] = []

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        self.mapView.delegate = self
        //Setting the region to a state coordinate
        var newRegion:MKCoordinateRegion = MKCoordinateRegion()
        newRegion.center.latitude = 20.2961;
        newRegion.center.longitude = 85.8245;
        newRegion.span.latitudeDelta = 20.112872;
        newRegion.span.longitudeDelta = 20.109863;
        
        self.mapView.setRegion(newRegion, animated: true)
        
        //Reading cities and its latitude and longitude from a plist file
        let cityDetailsPath = NSBundle.mainBundle().pathForResource("IndianCitiesSample", ofType: "plist")
        let cityDetails = NSArray(contentsOfFile: cityDetailsPath!) as? [[String:String]]
        
        for city in cityDetails!{
            let lat = Double(city["latitude"]!)
            let lon = Double(city["longitude"]!)
            let title = city["title"]
            let subTitle = city["subTitle"]
            
            let annotation:PinAnnotation = PinAnnotation(coordinate: CLLocationCoordinate2DMake(lat!, lon!), title: title!, subtitle: subTitle!)
            self.mapAnnotations.append(annotation)
            

        }
        self.mapView.addAnnotations(self.mapAnnotations)

    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
    
    func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
        print(userLocation)
    }
    
    func mapView(mapView: MKMapView, didFailToLocateUserWithError error: NSError) {
        print(error)
    }

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
        let returnedAnnotationView:MKAnnotationView = PinAnnotation.createViewAnnotationForMap(self.mapView, annotation: annotation)
        let button = NSButton(frame: NSMakeRect(0,0,100,80))
        button.title = "More Info"
        button.target = self
        button.action = Selector("showMoreInfo:")
        button.bezelStyle = .RegularSquareBezelStyle
        returnedAnnotationView.rightCalloutAccessoryView = button
        return returnedAnnotationView
    }

    @IBAction func showMoreInfo(sender:AnyObject){
        print("show popover to show more info")
        let alert = NSAlert()
        alert.messageText = "show details"
        alert.addButtonWithTitle("OK")
        alert.informativeText = "Informative text goes here"
        alert.beginSheetModalForWindow(self.window, completionHandler: nil)
    }

}

//PinAnnotation class that implements the MKAnnotation protocol
class PinAnnotation:NSObject, MKAnnotation{
    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?
    
    init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) {
        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
    }
    
    class func createViewAnnotationForMap(mapView:MKMapView, annotation:MKAnnotation)->MKAnnotationView{
        if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("PinAnnotation"){
                return annotationView
        }else{
            let returnedAnnotationView:MKPinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier:"PinAnnotation")
            returnedAnnotationView.pinTintColor = NSColor.redColor()
            returnedAnnotationView.animatesDrop = true
            returnedAnnotationView.canShowCallout = true
            return returnedAnnotationView
            
        }
    }
}

You can download the sample code Swift MapKit Annotation – Sample One

Posted in MapKit, Swift Tagged with: , , , ,

Swift CAEmitterCell CAEmitterLayer Fireworks

Swift CAEmitterCell CAEmitterLayer Fireworks

Created By : Debasis Das (May 2016)

This post is inspired from the Firework Objective C App. The code has been re-written in Swift while removing the slider controls for controlling the fireworks. For the objective C version you can have a look at the below link

https://developer.apple.com/library/mac/samplecode/Fireworks/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009114

Sample Code

//  AppDelegate.swift
//  Swift-CAEmitterCell
//  Created by Debasis Das on 19/05/16.
//  Copyright © 2016 Knowstack. All rights reserved.

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate ,NSWindowDelegate{

    @IBOutlet weak var window: NSWindow!
    var rootLayer:CALayer = CALayer()
    var emitterLayer:CAEmitterLayer = CAEmitterLayer()
    @IBOutlet weak var mainView:NSView!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    override func awakeFromNib() {
        print("awakeFromNib")
        self.createFireWorks()
    }
    
    func windowDidResize(notification: NSNotification) {
        self.createFireWorks()
    }
    

    func createFireWorks(){
        self.rootLayer.bounds = self.mainView.bounds
        let color = CGColorCreateGenericRGB(0.0, 0.0, 0.0, 1.0)
        rootLayer.backgroundColor = color
        
        let image = NSImage(named: "particle")
        let img:CGImageRef = (image?.CGImageForProposedRect(nil, context: nil, hints: nil))!
        
        print(self.mainView.frame.size.width/2)
        emitterLayer.emitterPosition = CGPointMake(self.mainView.bounds.size.width/2, 20)
        emitterLayer.renderMode = kCAEmitterLayerAdditive
        
        
        let emitterCell = CAEmitterCell()
        emitterCell.emissionLongitude = CGFloat(M_PI / 2)
        emitterCell.emissionLatitude = 0
        emitterCell.lifetime = 2.6
        emitterCell.birthRate = 6
        emitterCell.velocity = 300
        emitterCell.velocityRange = 100
        emitterCell.yAcceleration = 150
        emitterCell.emissionRange = CGFloat(M_PI / 4)
        let newColor = CGColorCreateGenericRGB(0.5, 0.5, 0.5, 0.5);
        emitterCell.color = newColor;
        
        emitterCell.redRange = 0.9;
        emitterCell.greenRange = 0.9;
        emitterCell.blueRange = 0.9;
        emitterCell.name = "base"
        
        let flareCell =  CAEmitterCell()
        flareCell.contents = img;
        flareCell.emissionLongitude = CGFloat(4 * M_PI) / 2;
        flareCell.scale = 0.4;
        flareCell.velocity = 80;
        flareCell.birthRate = 45;
        flareCell.lifetime = 0.5;
        flareCell.yAcceleration = -350;
        flareCell.emissionRange = CGFloat(M_PI / 7);
        flareCell.alphaSpeed = -0.7;
        flareCell.scaleSpeed = -0.1;
        flareCell.scaleRange = 0.1;
        flareCell.beginTime = 0.01;
        flareCell.duration = 1.7;
        
        let fireworkCell = CAEmitterCell()
        
        fireworkCell.contents = img;
        fireworkCell.birthRate = 19999;
        fireworkCell.scale = 0.6;
        fireworkCell.velocity = 130;
        fireworkCell.lifetime = 100;
        fireworkCell.alphaSpeed = -0.2;
        fireworkCell.yAcceleration = -80;
        fireworkCell.beginTime = 1.5;
        fireworkCell.duration = 0.1;
        fireworkCell.emissionRange = 2 * CGFloat(M_PI);
        fireworkCell.scaleSpeed = -0.1;
        fireworkCell.spin = 2;
        
        emitterCell.emitterCells = [flareCell,fireworkCell]
        self.emitterLayer.emitterCells = [emitterCell]
        self.rootLayer.addSublayer(emitterLayer)
        self.mainView.layer = rootLayer
        self.mainView.wantsLayer = true
        self.mainView.needsDisplay = true

    }
}

Swift NSEmitterCell NSEmitterLayer
You can download the project here Swift-CAEmitterCell

Posted in Swift Tagged with: , ,

Different ways of loading a d3js data

Different ways of loading a d3js data

Created By:Debasis Das (May 2016)

In this article we will discuss the different ways of loading a d3js data.

In the post we will load a d3 chart’s data from json, csv, tsv and from a local variable.

We will load a simple column chart with data sourced from different types.

d3js csv tsv json 2 d3js csv tsv json 1

Approach 1 – Loading D3 from CSV (Comma separated value)

http://www.knowstack.com/webtech/d3jsData/d3fromCsv.html

<!DOCTYPE html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" type="text/css" href="css/barchart.css">
</head>
<body>
<script src="js/d3.v3.min.js"></script>
<script src="js/d3.tip.v0.6.3.js"></script>
<script>

var margin = {top: 40, right: 20, bottom: 30, left: 70},
    width = 460 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10, "");

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Salary:</strong> <span style='color:red'>" + d.Salary + "</span>";
  })
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.call(tip);

d3.csv("data/employeeSalary.csv", type, function(error, data) {
  if (error) throw error;

  x.domain(data.map(function(d) { return d.Employee; }));
  y.domain([0, d3.max(data, function(d) { return d.Salary; })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", -36)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Salary");

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.Employee); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.Salary); })
      .attr("height", function(d) { return height - y(d.Salary); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide);
});

function type(d) {
  d.Salary = +d.Salary;
  return d;
}
</script>

Approach 2 – Loading D3 from TSV (Tab separated value)

http://www.knowstack.com/webtech/d3jsData/d3fromTsv.html

<!DOCTYPE html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" type="text/css" href="css/barchart.css">
</head>
<body>
<script src="js/d3.v3.min.js"></script>
<script src="js/d3.tip.v0.6.3.js"></script>
<script>

var margin = {top: 40, right: 20, bottom: 30, left: 70},
    width = 460 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10, "");

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Salary:</strong> <span style='color:red'>" + d.Salary + "</span>";
  })
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.call(tip);

d3.tsv("data/employeeSalary.tsv", type, function(error, data) {
  if (error) throw error;

  x.domain(data.map(function(d) { return d.Employee; }));
  y.domain([0, d3.max(data, function(d) { return d.Salary; })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", -36)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Salary");

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.Employee); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.Salary); })
      .attr("height", function(d) { return height - y(d.Salary); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide);
});

function type(d) {
  d.Salary = +d.Salary;
  return d;
}

</script>
<body>

</body>

Approach 3 – Loading D3 from JSON

http://www.knowstack.com/webtech/d3jsData/d3fromJson.html

<!DOCTYPE html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" type="text/css" href="css/barchart.css">
</head>
<body>
<script src="js/d3.v3.min.js"></script>
<script src="js/d3.tip.v0.6.3.js"></script>
<script>

var margin = {top: 40, right: 20, bottom: 30, left: 70},
    width = 460 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10, "");

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Salary:</strong> <span style='color:red'>" + d.Salary + "</span>";
  })
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.call(tip);
d3.json("data/employeeSalary.json", function(error, data) {

  if (error) throw error;

  x.domain(data.map(function(d) { return d.Employee; }));
  y.domain([0, d3.max(data, function(d) { return d.Salary; })]);

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", -36)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Salary");

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.Employee); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.Salary); })
      .attr("height", function(d) { return height - y(d.Salary); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide);
});

function type(d) {
  d.Salary = +d.Salary;
  return d;
}

</script>

Approach 4 – Loading D3 from a local variable

http://www.knowstack.com/webtech/d3jsData/d3fromInlineData.html

<!DOCTYPE html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" type="text/css" href="css/barchart.css">
</head>
<body>
<script src="js/d3.v3.min.js"></script>
<script src="js/d3.tip.v0.6.3.js"></script>
<script>

var margin = {top: 40, right: 20, bottom: 30, left: 70},
    width = 460 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var data=[{"Employee":"John Doe","Salary":58},{"Employee":"Jane Doe","Salary":81},{"Employee":"Mary Jane","Salary":39},{"Employee":"Debasis Das","Salary":80},{"Employee":"Nishant Singh","Salary":99}];

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10, "");

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Salary:</strong> <span style='color:red'>" + d.Salary + "</span>";
  })
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.call(tip);



x.domain(data.map(function(d) { return d.Employee; }));
y.domain([0, d3.max(data, function(d) { return d.Salary; })]);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
.append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", -36)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Salary");

svg.selectAll(".bar")
  .data(data)
.enter().append("rect")
  .attr("class", "bar")
  .attr("x", function(d) { return x(d.Employee); })
  .attr("width", x.rangeBand())
  .attr("y", function(d) { return y(d.Salary); })
  .attr("height", function(d) { return height - y(d.Salary); })
  .on('mouseover', tip.show)
  .on('mouseout', tip.hide);


function type(d) {
  d.Salary = +d.Salary;
  return d;
}

</script>

References & further read

https://d3js.org/
https://github.com/d3/d3/wiki/Gallery

Posted in CSS, d3js, HTML5, Web Technology Tagged with: , , , , ,

Swift CAEmitterCell CAEmitterLayer Sample Code

Swift CAEmitterCell Sample Code

Created By: Debasis Das (May 2016)

This post is inspired by the Objective C version of the Fire Demo Application from developer.apple.com and the flow is rewritten in Swift.

https://developer.apple.com/library/mac/samplecode/Fire/Introduction/Intro.html

The output of the program is as follows

Code

//  AppDelegate.swift
//  Swift_CAEmitterCell_Fire
//  Original Objective C Code https://developer.apple.com/library/mac/samplecode/Fire/Introduction/Intro.html
//  Created by Debasis Das on 28/05/16.
//  Copyright © 2016 Knowstack. All rights reserved.

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var gasSlider:NSSlider!
    var rootLayer:CALayer = CALayer()
    var fireEmitterLayer:CAEmitterLayer = CAEmitterLayer()
    var smokeEmitterLayer:CAEmitterLayer = CAEmitterLayer()
    @IBOutlet weak var mainView:NSView!

    
    


    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    override func awakeFromNib() {
        self.rootLayer.bounds = self.mainView.bounds
        let color = CGColorCreateGenericRGB(0.0, 0.0, 0.0, 1.0)
        rootLayer.backgroundColor = color
        
        let fireImage = NSImage(named: "fire")
        let fireImg:CGImageRef = (fireImage?.CGImageForProposedRect(nil, context: nil, hints: nil))!
        
        let smokeImage = NSImage(named: "fire")
        let smokeImg:CGImageRef = (smokeImage?.CGImageForProposedRect(nil, context: nil, hints: nil))!
        
        
        //Create the fire emitter layer
        self.fireEmitterLayer = CAEmitterLayer()
        self.fireEmitterLayer.emitterPosition = CGPointMake(225, 50)
        self.fireEmitterLayer.emitterMode = kCAEmitterLayerOutline
        self.fireEmitterLayer.emitterShape = kCAEmitterLayerLine
        self.fireEmitterLayer.renderMode = kCAEmitterLayerAdditive
        self.fireEmitterLayer.emitterSize = CGSizeMake(0, 0)
        
        //Create the smoke emitter layer
        self.smokeEmitterLayer = CAEmitterLayer()
        self.smokeEmitterLayer.emitterPosition = CGPointMake(225, 50)
        self.smokeEmitterLayer.emitterMode = kCAEmitterLayerPoints
        
        //Create the fire emitter cell
        let fireCell = CAEmitterCell()
        fireCell.emissionLongitude = CGFloat(M_PI);
        fireCell.birthRate = 0;
        fireCell.velocity = 80;
        fireCell.velocityRange = 30;
        fireCell.emissionRange = 1.1;
        fireCell.yAcceleration = 200;
        fireCell.scaleSpeed = 0.3;
        let fireColor = CGColorCreateGenericRGB(0.8, 0.4, 0.2, 0.10)
        fireCell.color = fireColor;
        fireCell.contents = fireImg
        fireCell.name = "fire" //Name the cell so that it can be animated later using keypaths
        
        
        //Add the fire emitter cell to the fire emitter layer
        self.fireEmitterLayer.emitterCells = [fireCell]
        
        //Create the smoke emitter cell
        let smokeCell = CAEmitterCell()
        smokeCell.birthRate = 11
        smokeCell.emissionLongitude = CGFloat(M_PI / 2)
        smokeCell.lifetime = 0
        smokeCell.velocity = 40
        smokeCell.velocityRange = 20
        smokeCell.emissionRange = CGFloat(M_PI / 4)
        smokeCell.spin = 1
        smokeCell.spinRange = 6
        smokeCell.yAcceleration = 160
        smokeCell.contents = smokeImg
        let smokeColor = CGColorCreateGenericRGB(0.2, 0.2, 0.2, 0.10)
        smokeCell.color = smokeColor;
        smokeCell.scale = 0.1
        smokeCell.alphaSpeed = -0.12
        smokeCell.scaleSpeed = 0.7
        smokeCell.name = "smoke" //Name the cell so that it can be animated later using keypaths
        
        //Add the smoke emitter cell to the smoke emitter layer
        self.smokeEmitterLayer.emitterCells = [smokeCell]
        
        //Add the two emitter layers to the root layer
        rootLayer.addSublayer(self.smokeEmitterLayer)
        rootLayer.addSublayer(self.fireEmitterLayer)
        
        
        self.mainView.layer = rootLayer
        self.mainView.wantsLayer = true
        self.mainView.needsDisplay = true
        
        self.sliderChanged(self)

    }
    
    @IBAction func sliderChanged(sender:AnyObject){
        let gas:Float = Float((self.gasSlider.intValue)/100)
        let birthRt:NSNumber = gas * 1000
        let gasRange:NSNumber = gas * 0.35
        let gasNum:NSNumber = gas
        self.fireEmitterLayer.setValue(birthRt, forKeyPath: "emitterCells.fire.birthRate")
        self.fireEmitterLayer.setValue(gasNum, forKeyPath: "emitterCells.fire.lifetime")
        self.fireEmitterLayer.setValue(gasRange, forKeyPath: "emitterCells.fire.lifetimeRange")
        self.fireEmitterLayer.emitterSize = CGSizeMake(CGFloat(50 * gas), 0)
        
        let smokeNum:NSNumber = gas * 4
        self.smokeEmitterLayer.setValue(smokeNum, forKeyPath: "emitterCells.smoke.lifetime")
        let color = CGColorCreateGenericRGB(0.2, 0.2, 0.2, CGFloat(gas * 0.1))
        self.smokeEmitterLayer.setValue(color, forKeyPath: "emitterCells.smoke.color")

    }
}


Swift CAEmitterCell CAEmitterLayer 3

Swift CAEmitterCell CAEmitterLayer 3

Swift CAEmitterCell CAEmitterLayer 2

Swift CAEmitterCell CAEmitterLayer 2

Swift CAEmitterCell CAEmitterLayer 1

Swift CAEmitterCell CAEmitterLayer 1

The Code can be downloaded here Swift_CAEmitterCell_Fire

Posted in Swift Tagged with: , , ,

Recent Posts


Hit Counter provided by technology news