Club 15CC

Like Pinterest for Hackers ~ 15CC Code

Task Code
CoffeeScript Override a Backbone.js Model’s Constructor in CoffeeScript »
class BehindTheBarApp.Models.Order extends Backbone.Model
  constructor: (@orders) ->
    super *arguments
Objective-C Sort an NSArray of Nested Dictionaries via a Key’s Value »
NSArray *arr = @[
                 @{@"label": @"one", @"count": @{@"k": @5} },
                 @{@"label": @"two", @"count": @{@"k": @9} },
                 @{@"label": @"three", @"count": @{@"k": @1} },
                 @{@"label": @"four", @"count": @{@"k": @100} },
                 ];

NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"count.k" ascending:NO];

NSArray *arr2 = [arr sortedArrayUsingDescriptors:@[sd]];
Ruby Swizzle an Instance Method in Ruby Keeping Reference to Original Version »
Spree::Shipment.class_eval do

  old_determine_state = instance_method(:determine_state)
  define_method(:determine_state) do
    result = old_determine_state.bind(self).()

    if result == 'ready'
      'pending'
    else
      result
    end
  end
end
C Doxygen Member Grouping vs Comment Sharing »
// MEMBER GROUPING
// Creates a headed section with the detailed description underneath the header
/** @name Channel-channel math ops.

      Channel-channel math ops with a bit more flexibility than the operator overloads; exception on bounds error if debug is set.

     \param ch          Source channel
     \return Reference to self for chaining
 */
//@{
...
//@}

// COMMENT SHARING
// No header but share the comment amongst all enclosed members.  Must set DISTRIBUTE_GROUP_DOC = YES in config

//@{
/** Brief description
      etc...
 */
...
//@}
iOS Draw a Shadow Under a UIView » Credits: 
self.layer.masksToBounds = NO;
self.layer.cornerRadius = 8; // optional
self.layer.shadowOffset = CGSizeMake(10, 10);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
iOS Vibrate / Buzz the iPhone Even When Not in Silent Mode » Seem like iPhone5+ might have changed the ability...
// Allocate system sound for buzz
SystemSoundID _soundID;
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"silence" ofType:@"wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)([NSURL fileURLWithPath: soundPath]), &_soundID);

// later...
AudioServicesPlayAlertSound(_soundID);  // ...PlayAlertSound, not ...PlaySystemSound
iOS Clone a UILabel in iOS »
// Warning: Not necessarily complete, but a good start ;)

// Size & position
UILabel *clonedLbl = [[UILabel alloc] initWithFrame:sourceLbl.frame];

// Text
clonedLbl.text = sourceLbl.text;
if ([sourceLbl respondsToSelector:@selector(attributedText)]) { // iOS 6+
    clonedLbl.attributedText = sourceLbl.attributedText;
}

// Format
clonedLbl.font = sourceLbl.font;
clonedLbl.textColor = sourceLbl.textColor;
clonedLbl.textAlignment = sourceLbl.textAlignment;
clonedLbl.lineBreakMode = sourceLbl.lineBreakMode;

clonedLbl.adjustsFontSizeToFitWidth  = sourceLbl.adjustsFontSizeToFitWidth;
clonedLbl.adjustsLetterSpacingToFitWidth  = sourceLbl.adjustsLetterSpacingToFitWidth;
clonedLbl.baselineAdjustment  = sourceLbl.baselineAdjustment;
clonedLbl.minimumFontSize = sourceLbl.minimumFontSize;    // deprecated in iOS6
clonedLbl.minimumScaleFactor  = sourceLbl.minimumScaleFactor;
clonedLbl.numberOfLines = sourceLbl.numberOfLines;

clonedLbl.shadowColor = sourceLbl.shadowColor;
clonedLbl.shadowOffset = sourceLbl.shadowOffset;
clonedLbl.backgroundColor = sourceLbl.backgroundColor;
clonedLbl.highlighted = sourceLbl.highlighted;
clonedLbl.highlightedTextColor = sourceLbl.highlightedTextColor;

clonedLbl.enabled = sourceLbl.enabled;
clonedLbl.userInteractionEnabled = sourceLbl.userInteractionEnabled;
clonedLbl.preferredMaxLayoutWidth = sourceLbl.preferredMaxLayoutWidth;
iOS Get the Default Output Stream Format for an Audio Unit in iOS »
AudioComponentDescription inputDescription = {0};
inputDescription.componentType = kAudioUnitType_Output;
inputDescription.componentSubType = kAudioUnitSubType_RemoteIO;
inputDescription.componentManufacturer = kAudioUnitManufacturer_Apple;

// Get component
AudioUnit inputUnit;
size_t s = sizeof(AudioStreamBasicDescription);
AudioComponent inputComponent = AudioComponentFindNext(NULL, &inputDescription);
AudioComponentInstanceNew(inputComponent, &inputUnit);

// Read the stream format
AudioStreamBasicDescription asbd;
AudioUnitGetProperty(inputUnit,
                     kAudioUnitProperty_StreamFormat,
                     kAudioUnitScope_Output,
                     0,
                     (void *)&asbd,
                     &s);

// Inspect with debugger, etc...
iOS Get iPhone/iPad Screen Dimensions »
CGSize screenSize = UIScreen.mainScreen.applicationFrame.size;
iOS Present Your UIView Subview With a 3D Flip »
// Somewhere in your UIView...
self.layer.transform = CATransform3DMakeRotation(-90.0f*M_PI/180.f, 1.0, 1.0, 0.0); // start: hidden at 90deg
CATransform3D trans3D = CATransform3DMakeRotation(0.0f*M_PI/180.f, 1.0, 1.0, 0.0); // end: angle and rotation vector (axis)
CABasicAnimation *transformAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
transformAnimation.removedOnCompletion = NO;
transformAnimation.toValue = [NSValue valueWithCATransform3D:trans3D];
transformAnimation.fillMode = kCAFillModeForwards;
[self.layer addAnimation:transformAnimation forKey:@"transform"];
iOS Convert a Float to a Price in a Specific Locale with NSNumberFormatter »
float newPrice = 1234.56;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-GB"];
myLabel.text = [formatter stringFromNumber:@(newPrice)];
Objective-C Objective-C Block Definition Syntax Master Cheatsheet » A very good reference: 
//
// TYPEDEFS
//
typedef int (^MyBlockTypeWithArgs)(int, int);
typedef int (^MySimpleBlockType)();
// Obj-C object argument/return types are ok too of course...

//
// LOCAL VARS
//
int (^multiply)(int, int) = ^int(int a, int b) { return a*b; };
int (^multiply)(int, int) = ^(int a, int b) { return a*b; };        // same as above
MyBlockTypeWithArgs multiple = ^(int a, int b) { return a*b; };
MySimpleBlockType doSomething = ^{ [self _doSomething]; }; 

//
// PROPERTIES (same as local vars)
//
@property (nonatomic, copy) int (^multiply)(int, int);
@property (nonatomic, strong) MyBlockTypeWithArgs callbackBlock;

//
// METHOD ARGUMENTS
//
@interface MyClass
- (void)doItWithBlock:(int(^)(int, int))blockTakingArgs;
- (void)doItWithBlock3:(void (^)())simpleBlock;
- (void)doItWithBlock:(MyBlockTypeWithArgs)block;
@end
iOS Play a Short Sound / Audio Clip on iOS – 2 Ways »
// Cocoa-style:  AVAudioPlayer
#import <AVFoundation/AVFoundation.h>
clickSound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSBundle.mainBundle URLForResource:@"click" withExtension:@"mp3"] error:NULL];
clickSound.volume = 0.5;
[clickSound playAtTime:0];  // OR...
clickSound.currentTime = 0;
[clickSound play];

// Cocoa-style:  AVPlayer
#import <AVFoundation/AVFoundation.h>
clickSound = [AVPlayer playerWithURL:[NSBundle.mainBundle URLForResource:@"click" withExtension:@"mp3"]];
// Note, no volume on this :(
clickSound seekToTime:CMTimeMake(0,1)];   // rewind if play occurs repeatedly and loading is only on init
[clickSound play];

// Core Foundation style
#import <AudioToolbox/AudioToolbox.h>
AudioServicesCreateSystemSoundID(.... URL ...., &mySound);
AudioServicesPlaySystemSound(mySound);
AudioServicesDisposeSystemSoundID(mySound);
C++ C++ Operator Overloading Boilerplate »
// Arithmetic
R T::operator +(S b);
R T::operator -(S b);
R T::operator +();
R T::operator -();
R T::operator *(S b);
R T::operator /(S b);
R T::operator %(S b);
R T::operator +=(S b);
R T::operator -=(S b);
R T::operator *=(S b);
R T::operator /=(S b);
R T::operator %=(S b);
// Note: C++ uses the unnamed dummy-parameter int to differentiate between prefix and suffix increment operators.
R T::operator ++();
R T::operator ++(int);
R T::operator --();
R T::operator --(int);

// Comparison
R T::operator ==(S b);
R T::operator !=(S b);
R T::operator >(S b);
R T::operator <(S b);
R T::operator >=(S b);
R T::operator <=(S b);

// Member Access and Functor-behavior
R T::operator [](S b);
T::operator R();
R T::operator *();
R T::operator ->();
R T::operator ->*(S a);
R T::operator ()(S a1, U a2, ...);
R T::operator ,(S b);

// Assignment, reference & copy
R T::operator &();
R T::operator =(S b);

// (De)Allocation
void* T::operator new(size_t x);
void* T::operator new[](size_t x);
void T::operator delete(void* x);
void T::operator delete[](void* x);

// Logic
R T::operator !();
R T::operator &&(S b);
R T::operator ||(S b);

// Bitwise
R T::operator ~();
R T::operator &(S b);
R T::operator |(S b);
R T::operator ^(S b);
R T::operator <<(S b);
R T::operator >>(S b);
R T::operator &=(S b);
R T::operator |=(S b);
R T::operator ^=(S b);
R T::operator <<=(S b);
R T::operator >>=(S b);
iOS Implement a Custom Back Button in your UINavigationController »
// Within your child VC which is about to be pushed
UIImage *btnImgOff = [UIImage imageNamed:@"back_button_off"];
UIImage *btnImgOn = [UIImage imageNamed:@"back_button_on"];    
UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, btnImgOff.size.width, btnImgOff.size.height)];
[backBtn setBackgroundImage:btnImgOff forState:UIControlStateNormal];
[backBtn setBackgroundImage:btnImgOn forState:UIControlStateHighlighted]; // optional
[backBtn addEventHandler:^(id sender) {
    [self.navigationController popViewControllerAnimated:YES];
} forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.hidesBackButton = YES;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
bash Create Resized and Renamed Non-Retina Images with Sed & ImageMagick »
ls | sed -n 's/\(.*\)\(@2x\)\(.*\)/convert "\1\2\3" -resize 50% "\1\3"/p' | sh
Linux Copy Matching Files in All Subfolders to Target (Flatten) »
find . -iname *.png -print | xargs -I file cp file ./
iOS Rotate a UIView (2D) »
view.transform = CGAffineTransformMakeRotation(angleClockwise);
Objective-C Add Ivars & Properties to an Objective-C Category via Runtime »
/// An sort-of hack (not that bad really) for adding ivars and properies to Categories 

// .h file
@interface UIView (Marshmallows)
@property (nonatomic) CGFloat rotation;
@end

// .m file
#import <objc/runtime.h>

/// Key for objc_*AssociatedObject functions
static char _rotation;

@implementation UIView (Marshmallows)

- (CGFloat)rotation
{
    // Convert from object
    NSNumber *n = objc_getAssociatedObject(self, &_rotation);
    return n.floatValue;
}

- (void)setRotation:(CGFloat)rotation
{
    CGFloat delta = rotation - _rotation;
    self.transform = CGAffineTransformMakeRotation(delta);

    // Must convert to an object for this trick to work
    objc_setAssociatedObject(self, &_rotation, @(rotation), OBJC_ASSOCIATION_COPY);
}

@end
iOS Get a String of a Number Rounded to a Decimal Place in Cocoa/iOS »
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
nf.maximumFractionDigits = 1;
aLabel.text = [nf stringFromNumber:@(sender.value)];
Git Show the Date When a File Was First Added to a Git Repo »
git log --format=%aD --follow -- <FILE> | tail -1