CALayer Sample Code – Part 1

CALayer Sample Code – Part 1

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

In this post we will create a simple CALayer and then change its properties like backgroundColor, borderWidth, borderColor, cornerRadius etc

CALayer Sample

CALayer Sample

CALayer Sample Code

//  AppDelegate.m
//  CALayerDemo1
//  Created by Debasis Das on 26/12/16.
//  Copyright © 2016 Knowstack. All rights reserved.

#import "AppDelegate.h"

@interface AppDelegate ()

@property (weak) IBOutlet NSWindow *window;
@property (weak) IBOutlet NSView *view1;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    

}

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

-(void)awakeFromNib{
    CALayer *rootLayer = [CALayer layer];
    rootLayer.backgroundColor = [[NSColor whiteColor] CGColor];
    rootLayer.bounds = [self.view1 bounds];
    rootLayer.cornerRadius = 10.0;
    rootLayer.borderColor = [[NSColor redColor] CGColor];
    rootLayer.borderWidth = 10.0;
    rootLayer.shadowOpacity = 1.0;
    rootLayer.shadowRadius = 10.0;
    self.view1.layer = rootLayer;
    [self.view1 setWantsLayer:YES];
    
}

-(IBAction)changeColor:(id)sender{
    self.view1.layer.backgroundColor = [[NSColor colorWithRed:randFloat() green:randFloat() blue:randFloat() alpha:1.0] CGColor];
}

-(IBAction)changeBorderWidth:(id)sender{
    [self.view1.layer setBorderWidth:([self.view1.layer borderWidth] >= 10.0 ? 0.0 : 10.0)];
}

-(IBAction)changeBorderColor:(id)sender{
    self.view1.layer.borderColor = [[NSColor colorWithRed:randFloat() green:randFloat() blue:randFloat() alpha:1.0] CGColor];
    
}

-(IBAction)changeSize:(id)sender{
    CGRect layerBounds = self.view1.layer.bounds;
    layerBounds.size.height = (layerBounds.size.height == 200.0) ? 320.0 : 200.0;
    [self.view1.layer setBounds:layerBounds];
    
 }

-(IBAction)changeCornerRadius:(id)sender{
    self.view1.layer.cornerRadius = (self.view1.layer.cornerRadius == 10.0)? 20:10;
}

-(IBAction)changeOpacity:(id)sender{
    self.view1.layer.opacity = (self.view1.layer.opacity == 1.0)? 0.5:1.0;
}

-(IBAction)toggleShadow:(id)sender{
    self.view1.layer.shadowOpacity = (self.view1.layer.shadowOpacity == 1.0)?0.0:1.0;
    self.view1.layer.shadowRadius = (self.view1.layer.shadowRadius == 10.0)?0.0:10.0;
    
}

-(IBAction)changeAll:(id)sender{
    [self changeColor:self];
    [self changeBorderWidth:self];
    [self changeSize:self];
    [self changeCornerRadius:self];
    [self changeOpacity:self];
    [self toggleShadow:self];
    
}

float randFloat() {
    return (random() % 1001) / 1000.0f;
}

@end

Posted in Cocoa, CoreAnimation, Mac OSX Animation, Objective C Tagged with: , ,

CoreAnimation Analog Clock

CoreAnimation Analog Clock

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

In this post we will create an analog clock using Core Animation. The final output will be as follows.

CoreAnimation Analog Clock

CoreAnimation Analog Clock

Core Animation Analog Clock Source Code

//  AppDelegate.m
//  AnalogClock
//  Created by Debasis Das on 31/12/16.
//  Copyright © 2016 Knowstack. All rights reserved.

#import "AppDelegate.h"

@interface AppDelegate ()
{
    //self.window.contentView will have a root layer and on top of the root layer we will add 3 layer.
    //Each layer representing a hand of the clock
    CALayer *hourLayer;
    CALayer *minuteLayer;
    CALayer *secondsLayer;
}
@property (weak) IBOutlet NSWindow *window;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    CALayer *layer = [CALayer layer];
    layer.frame = [self.window.contentView frame];
    layer.contents = [NSImage imageNamed:@"ClockFace"];
    [self.window.contentView setLayer:layer];
    [self.window.contentView setWantsLayer:YES];
    
    //Draw the hours hand layer
    hourLayer = [CALayer layer];
    hourLayer.backgroundColor = [[NSColor blackColor] CGColor];
    hourLayer.anchorPoint = CGPointMake(0.5, 0);
    hourLayer.position = CGPointMake(self.window.contentView.frame.size.width/2, self.window.contentView.frame.size.height/2);
    hourLayer.bounds = CGRectMake(0, 0, 10, self.window.contentView.frame.size.width/2 -100);
    [layer addSublayer:hourLayer];

    //Draw the minutes hand layer
    minuteLayer = [CALayer layer];
    minuteLayer.backgroundColor = [[NSColor blueColor] CGColor];
    minuteLayer.anchorPoint = CGPointMake(0.5, 0);
    minuteLayer.position = CGPointMake(self.window.contentView.frame.size.width/2, self.window.contentView.frame.size.height/2);
    minuteLayer.bounds = CGRectMake(0, 0, 6, self.window.contentView.frame.size.width/2 -50);
    [layer addSublayer:minuteLayer];

    //Draw the seconds hand layer
    secondsLayer = [CALayer layer];
    secondsLayer.backgroundColor = [[NSColor redColor] CGColor];
    secondsLayer.anchorPoint = CGPointMake(0.5, 0);
    secondsLayer.position = CGPointMake(self.window.contentView.frame.size.width/2, self.window.contentView.frame.size.height/2);
    secondsLayer.bounds = CGRectMake(0, 0, 3, self.window.contentView.frame.size.width/2 -20);
    [layer addSublayer:secondsLayer];

    //Place the hands at correct location
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour fromDate:[NSDate date]];
    
    NSInteger seconds = dateComponents.second;
    NSInteger minutes = dateComponents.minute;
    NSInteger hours = dateComponents.hour;
    
    //Calculate the angles for each hand of the analog clock
    CGFloat hourAngle = (hours * (360/12)) + (minutes * (1.0/60) * (360/12));
    CGFloat minuteAngle = minutes * (360/60);
    CGFloat secondsAngle = seconds * 360/60;

    
    hourLayer.transform = CATransform3DMakeRotation(hourAngle /180 *M_PI, 0, 0, 1);
    minuteLayer.transform = CATransform3DMakeRotation(minuteAngle /180 *M_PI, 0, 0, 1);
    secondsLayer.transform = CATransform3DMakeRotation(secondsAngle /180 *M_PI, 0, 0, 1);
    
    //Add 3 animations for each layer    
    CABasicAnimation *secondsAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    secondsAnimation.repeatCount = HUGE_VALF;
    secondsAnimation.duration = 60;
    secondsAnimation.removedOnCompletion = NO;
    secondsAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    secondsAnimation.fromValue = @(secondsAngle * M_PI / 180);
    secondsAnimation.byValue = @(-2 * M_PI);
    [secondsLayer addAnimation:secondsAnimation forKey:@"SecondAnimationKey"];

    CABasicAnimation *minutesAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    minutesAnimation.repeatCount = HUGE_VALF;
    minutesAnimation.duration = 60*60;
    minutesAnimation.removedOnCompletion = NO;
    minutesAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    minutesAnimation.fromValue = @(-minuteAngle * M_PI / 180);
    minutesAnimation.byValue = @(-2 * M_PI);
    [minuteLayer addAnimation:minutesAnimation forKey:@"MinutesAnimationKey"];

    CABasicAnimation *hoursAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    hoursAnimation.repeatCount = HUGE_VALF;
    hoursAnimation.duration = 60*60*12;
    hoursAnimation.removedOnCompletion = NO;
    hoursAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    hoursAnimation.fromValue = @(-hourAngle * M_PI / 180);
    hoursAnimation.byValue = @(-2 * M_PI);
    [hourLayer addAnimation:hoursAnimation forKey:@"HoursAnimationKey"];


}

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

@end

CoreAnimation Analog Clock Source Code

Posted in CoreAnimation, Mac OSX Animation Tagged with: , , ,

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: , ,

Recent Posts


Hit Counter provided by technology news