Tuesday, December 8, 2015

How to Get a Random MAC Address:


====================================================

$ arp -a
wirelessap (192.168.0.1) at 94:fb:b2:38:7:b4 on en1 ifscope [ethernet]
? (192.168.0.255) at ff:ff:ff:ff:ff:ff on en1 ifscope [ethernet]
? (202.71.99.194) at 3c:7:54:38:9:a6 on en0 ifscope permanent [ethernet]



====================================================

How to Get a Random MAC Address
If you’re going for privacy, randomizing your MAC address is probably the best option. This command will do it automatically:
openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//' | xargs sudo ifconfig en0 ether


Checking and Changing Ethernet Address:



Checking Ethernet Address:
=====================

$ ifconfig   en0   |grep   ether

$ ether  3c:07:54:38:09:a6



Changing Ethernet Address:
======================

$ sudo ifconfig en0 ether   3c:07:54:38:09:b4



Saturday, October 10, 2015

Deleting "DS_Store" files on Mac OS

Remove all DS_Store files


  1. Select Applications > Utilities to launch Terminal.
  2. Enter the following UNIX command:
    sudo find / -name ".DS_Store" -depth -exec rm {} \;
  3. When prompted for a password enter your Mac OS X Administrator password.


Automatically remove DS_Store files periodically


  1. Select Applications > Utilities to launch Terminal.
  2. Enter the following UNIX command:
    sudo crontab -e
  3. When prompted for a password enter your Mac OS X Administrator password.
  4. In the vi editor, press the letter I on your keyboard once and enter the following command:
    15 1 * * * root find / -name ".DS_Store" -depth -exec rm {} \;
    This crontab entry has the following format:
    .
    The system automatically runs the command at 1:15 AM everyday. To configure the command for a different time, use different values.
    Note:
    This command is not run if your computer is switched off at the scheduled time.
  5. To save the entry press the Esc key once, then simultaneously press Shift+z+z.

Monday, September 28, 2015

Disabling App Transport Security in iOS 9.0

   <key> NSAppTransportSecurity </key>
   <dict> 
           <key>NSAllowsArbitraryLoads</key>  <true/>
   </dict > 

Thursday, July 9, 2015

Switch between JDK 1.7 and JDK 1.8

Edit .bash_profile and add the following:

setupjdk() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    sudo ln -nsf ${JAVA_HOME%/*} /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
}
setupjdk 1.8



$source ~/.bash_profile


Thursday, July 2, 2015

Wednesday, June 24, 2015

Increase UILabel height dynamically:

CGRect frame = self.securityValueLbl.frame;
CGSize maximumLabelSize = CGSizeMake(frame.size.width, 80); //MAXFLOAT

NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin;

NSDictionary *attr = @{NSFontAttributeName: self.securityValueLbl.font};
CGRect expectedLabelFrame = [self.securityValueLbl.text boundingRectWithSize:maximumLabelSize
                                             options:options
                                          attributes:attr
                                             context:nil];

frame.size.height = ceilf(expectedLabelFrame.size.height);
self.securityValueLbl.frame = frame;


Tuesday, June 16, 2015

NSDate Helper Functions:

Get Today's Date:
===========================================

NSDate* date = [NSDate date];



Create a Date From Scratch:
===========================================

NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.year = 2014;
comps.month = 3;
comps.day = 31;

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDate* date = [calendar dateFromComponents:comps];



Add a day to a Date:
===========================================

NSDate* date = [NSDate date];

NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = 1;

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDate* tomorrow = [calendar dateByAddingComponents:comps toDate:date options:nil];



Subtract a day from a Date:
===========================================

NSDate* date = [NSDate date];

NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = -1;

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDate* yesterday = [calendar dateByAddingComponents:comps toDate:date options:nil];



Convert a Date to a String:
===========================================

NSDate* date = [NSDate date];

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSString* dateString = [formatter stringFromDate:date];



Convert a String to a Date:
===========================================

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSDate* date = [formatter dateFromString:@"August 02, 2014"];



Find how many days are in a month:
===========================================

NSDate* date = [NSDate date];

NSCalendar* cal = [NSCalendar currentCalendar];
NSRange currentRange = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger numberOfDays = currentRange.length;



Calculate how much time something took:
===========================================
NSDate* start = [NSDate date];

for(int i = 0; i < 1000000000; i++);

NSDate* end = [NSDate date];
NSTimeInterval duration = [end timeIntervalSinceDate:start];



Find the Day Of Week for a specific Date:
===========================================
NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSInteger dow = [cal ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];



Enjoy!


Tuesday, June 9, 2015

Custom NSLog:


#define DSLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);



Get the last day of a month:

NSDate *curDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components

// set last of month
[comps setMonth:[comps month]+1];
[comps setDay:0];
NSDate *tDateMonth = [calendar dateFromComponents:comps];
NSLog(@"%@", tDateMonth);

Wednesday, June 3, 2015

NSFileProtectionKey :


// Create NSProtectionComplete attribute

NSDictionary *protectionComplete = [NSDictionary
dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];


// Set attribute on file at

[[[NSFileManager] defaultManager] setAttributes:protectionComplete
ofItemAtPath:filePath error:nil];


Tuesday, June 2, 2015

Dynamic height of UILabel


CGRect textRect = [text boundingRectWithSize:size
                                 options:NSStringDrawingUsesLineFragmentOrigin
                              attributes:@{NSFontAttributeName:FONT}
                                 context:nil];

CGSize size = textRect.size;

Friday, May 8, 2015

Using Blocks:


#import <Foundation/Foundation.h>

typedef void (^CompletionBlock)();
@interface SampleClass:NSObject
- (void)performActionWithCompletion:(CompletionBlock)completionBlock;
@end

@implementation SampleClass

- (void)performActionWithCompletion:(CompletionBlock)completionBlock{

    NSLog(@"Action Performed");
    completionBlock();
}

@end

int main()
{
    /* my first program in Objective-C */
    SampleClass *sampleClass = [[SampleClass alloc]init];
    [sampleClass performActionWithCompletion:^{
        NSLog(@"Completion is called to intimate action is performed.");
    }];
   
    return 0;
}



Declaring String Constants:



If they are specific and internal to a single class, declare them as static const at the top of the .m file, like so:

static NSString *const MyThingNotificationKey = @"MyThingNotificationKey";


====================================================================


If they pertain to a single class but should be public/used by other classes, declare them as extern in the header and define them in the .m:

//.h
extern NSString *const MyThingNotificationKey;

//.m
NSString *const MyThingNotificationKey = @"MyThingNotificationKey";

Detect screenshots in Objective C:


NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification
              object:nil
               queue:mainQueue
          usingBlock:^(NSNotification *note) {
             // executes after screenshot
          }];
         
         

Base64 Encoding and Decoding in iOS 7.0:


NSString *plainString = @"foo";

Encoding:
---------
NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v


Decoding:
---------
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo

Wednesday, April 29, 2015

HTML Table DOM:


var table = document.getElementsByTagName("Table");

var result = table[0];
var len = result.rows.length;

for(var i=1; i < len; i++){
  //console.log(row);
  var emailId = result.rows[i].cells[1].innerHTML;
  console.log(emailId);
}

Monday, April 27, 2015

Script to extract emails from WebPage:


var text = document.body.innerHTML;
function extractEmails (text)
{
    return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}

document.write(extractEmails(text).join('
'));

alert(extractEmails(text).join('\n'));


Cell Separator Inset:



For iOS 7.0:
============

if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
    [tableView setSeparatorInset:UIEdgeInsetsZero];
}

or

[tableView setSeparatorInset:UIEdgeInsetsZero];
   
   
For iOS 8.0:
============

tableView.layoutMargins = UIEdgeInsetsZero;
cell.layoutMargins = UIEdgeInsetsZero;


======================================================


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
           [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

Thursday, March 26, 2015

Adding Custom Gradient to Button:


-(CAGradientLayer *)getCAGradientLayerWithFrame : (CGRect)bounds {
  CAGradientLayer *gradientLayer = [CAGradientLayer layer];
 
  bounds.origin.y    = bounds.size.height - 6;
  bounds.size.height = 6;

  gradientLayer.frame = bounds;
  gradientLayer.colors = [NSArray arrayWithObjects:
                          (id)[UIColor orangeColor].CGColor,
                          (id)[UIColor orangeColor].CGColor,
                          nil];
 
  gradientLayer.locations = [NSArray arrayWithObjects:
                             [NSNumber numberWithFloat:0.0f],
                             [NSNumber numberWithFloat:1.0f],
                             nil];

  return gradientLayer;
}




- (IBAction)btnAction:(id)sender {
 
  UIButton *btn = (UIButton *)sender;
  NSArray *subLayersArr = [btn.layer sublayers];
 
  NSLog(@"subLayersArr : %@", subLayersArr);
 
 
  CAGradientLayer *subLayer = nil;
  if ([subLayersArr count]) {
    subLayer = [subLayersArr objectAtIndex:0];
  }
 
  NSLog(@"subLayer : %@", subLayer);
 
 
  btn.selected = !btn.selected;

  if (btn.selected) {
    subLayer.hidden = NO;
  } else {
    subLayer.hidden = YES;
  }
 
}


Usage:
=====
CAGradientLayer *layer = [self getCAGradientLayerWithFrame:self.aButton.layer.bounds];
self.aButton.backgroundColor = [UIColor yellowColor];
[self.aButton.layer addSublayer:layer];





Tuesday, March 24, 2015

Hide StatusBar in iOS


UIStatusBarHidden

UIViewControllerBasedStatusBarAppearance

Custom SplitViewController:



- (void)viewDidLayoutSubviews
{
  [super viewDidLayoutSubviews];
 
  //NSLog(@"CustomSplitViewController is called"); 260, 764
 
  const CGFloat kMasterViewWidth = 260.0;
 
  float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
 
  NSLog(@"systemVersion : %0.2f", systemVersion);
 
 
  if(systemVersion < 8.0f){
  
      UIViewController *masterViewController = [self.viewControllers objectAtIndex:0];
      UIViewController *detailViewController = [self.viewControllers objectAtIndex:1];
    
      if (detailViewController.view.frame.origin.x > 0.0) {
        // Adjust the width of the master view
        CGRect masterViewFrame = masterViewController.view.frame;
        CGFloat deltaX = masterViewFrame.size.width - kMasterViewWidth;
        masterViewFrame.size.width -= deltaX;
        masterViewController.view.frame = masterViewFrame;
      
        // Adjust the width of the detail view
        CGRect detailViewFrame = detailViewController.view.frame;
        detailViewFrame.origin.x -= deltaX;
        detailViewFrame.size.width += deltaX;
        detailViewController.view.frame = detailViewFrame;
      
        [masterViewController.view setNeedsLayout];
        [detailViewController.view setNeedsLayout];
      }
  
  } else {
  
    self.maximumPrimaryColumnWidth = kMasterViewWidth;
  
  }
 
 
}



Thursday, February 26, 2015

NSDataDetector Example:


NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];

NSString *stringValue =  @"Two links: useyourloaf.com and apple.com";
NSURL *url = nil;
NSTextCheckingResult *result = [detector firstMatchInString:stringValue
                                                    options:0
                                                      range:NSMakeRange(0, stringValue.length)];
if (result.resultType == NSTextCheckingTypeLink)
{
    url = result.URL;
}
NSLog(@"matched: %@", url);
// matched: http://useyourloaf.com

//--------------------------------------------------------------------

NSString *stringValue = @"Two links: useyourloaf.com and apple.com";   
[detector enumerateMatchesInString:stringValue
                           options:0
                             range:NSMakeRange(0, stringValue.length)
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
    if (result.resultType == NSTextCheckingTypeLink)
    {
        NSLog(@"matched: %@",result.URL);
    }        
}];
// matched: http://useyourloaf.com
// matched: http://apple.com


//====================================================================

NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
  if ([match resultType] == NSTextCheckingTypeLink) {
    NSURL *url = [match URL];
    NSLog(@"found URL: %@", url);
  }
}


//====================================================================


Sunday, January 25, 2015

HTML Options Looping


var aa = document.getElementById("Criteria_FlightNo");
var str = "{";
for(var i=0; i < aa.options.length; i++){
  str += "\"" + aa.options[i].value + "\"" +  ":" + "\"" + aa.options[i].innerHTML + "\"";
  if(i!= aa.options.length-1){
    str += ",";
  }
}
str += "}";
console.log(str);