Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Fjölnir �sgeirsson http://ninjakitten.us

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS 

How to draw your own table header... (with borders)

// It's a bit hacky at the beginning, but nstableheadercell wasn't exactly making things easy for me

- (void)_drawThemeContents:(NSRect)cellFrame highlighted:(BOOL)highlighted inView:(NSTableHeaderView *)view;
{
	int index = [view columnAtPoint:NSMakePoint(cellFrame.origin.x + 1,cellFrame.origin.y + 1)];
	NSRect headerRect;
	if(index != -1)
		headerRect = [view headerRectOfColumn:index];
	else
		headerRect = NSZeroRect;
	
	[headerImage drawInRect:cellFrame
				   fromRect:NSZeroRect
				  operation:NSCompositeSourceOver
				   fraction:1.0];
	
	[[NSColor colorWithCalibratedRed:207.0/255.0
							   green:207.0/255.0
								blue:207.0/255.0
							   alpha:1.0] set];
	NSRectFill(NSMakeRect(headerRect.origin.x, headerRect.origin.y + 1, headerRect.size.width, headerRect.size.height - 2));
	[headerImage drawInRect:NSMakeRect(headerRect.origin.x, headerRect.origin.y, headerRect.size.width - 1, headerRect.size.height)
				   fromRect:NSZeroRect
				  operation:NSCompositeSourceOver
				   fraction:1.0];
}

How to make the system notify you of audio cd insertion

// Uses the DiskArbitration framework to notify ya of when new audio cds are inserted

NSDictionary *match = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"IOCDMedia", [NSNumber numberWithBool:YES], nil] forKeys:[NSArray arrayWithObjects:(NSString *)kDADiskDescriptionMediaKindKey, kDADiskDescriptionMediaWholeKey, nil]];
		
_session = DASessionCreate(kCFAllocatorDefault);
DASessionScheduleWithRunLoop(_session, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
DARegisterDiskAppearedCallback(_session, (CFDictionaryRef)match, diskAppearedCallback, NULL);
DARegisterDiskDisappearedCallback(_session, (CFDictionaryRef)match, diskDisappearedCallback, NULL);

Genres defined in ID3v2 and Winamp extensions

Why oh why not just store strings?

NSMutableArray *genres = [NSMutableArray array];
[genres addObject:@"Blues"];
[genres addObject:@"Classic Rock"];
[genres addObject:@"Country"];
[genres addObject:@"Dance"];
[genres addObject:@"Disco"];
[genres addObject:@"Funk"];
[genres addObject:@"Grunge"];
[genres addObject:@"Hip-Hop"];
[genres addObject:@"Jazz"];
[genres addObject:@"Metal"];
[genres addObject:@"New Age"];
[genres addObject:@"Oldies"];
[genres addObject:@"Other"];
[genres addObject:@"Pop"];
[genres addObject:@"R&B"];
[genres addObject:@"Rap"];
[genres addObject:@"Reggae"];
[genres addObject:@"Rock"];
[genres addObject:@"Techno"];
[genres addObject:@"Industrial"];
[genres addObject:@"Alternative"];
[genres addObject:@"Ska"];
[genres addObject:@"Death Metal"];
[genres addObject:@"Pranks"];
[genres addObject:@"Soundtrack"];
[genres addObject:@"Euro-Techno"];
[genres addObject:@"Ambient"];
[genres addObject:@"Trip-Hop"];
[genres addObject:@"Vocal"];
[genres addObject:@"Jazz+Funk"];
[genres addObject:@"Fusion"];
[genres addObject:@"Trance"];
[genres addObject:@"Classical"];
[genres addObject:@"Instrumental"];
[genres addObject:@"Acid"];
[genres addObject:@"House"];
[genres addObject:@"Game"];
[genres addObject:@"Sound Clip"];
[genres addObject:@"Gospel"];
[genres addObject:@"Noise"];
[genres addObject:@"AlternRock"];
[genres addObject:@"Bass"];
[genres addObject:@"Soul"];
[genres addObject:@"Punk"];
[genres addObject:@"Space"];
[genres addObject:@"Meditative"];
[genres addObject:@"Instrumental Pop"];
[genres addObject:@"Instrumental Rock"];
[genres addObject:@"Ethnic"];
[genres addObject:@"Gothic"];
[genres addObject:@"Darkwave"];
[genres addObject:@"Techno-Industrial"];
[genres addObject:@"Electronic"];
[genres addObject:@"Pop-Folk"];
[genres addObject:@"Eurodance"];
[genres addObject:@"Dream"];
[genres addObject:@"Southern Rock"];
[genres addObject:@"Comedy"];
[genres addObject:@"Cult"];
[genres addObject:@"Gangsta"];
[genres addObject:@"Top 40"];
[genres addObject:@"Christian Rap"];
[genres addObject:@"Pop/Funk"];
[genres addObject:@"Jungle"];
[genres addObject:@"Native American"];
[genres addObject:@"Cabaret"];
[genres addObject:@"New Wave"];
[genres addObject:@"Psychadelic"];
[genres addObject:@"Rave"];
[genres addObject:@"Showtunes"];
[genres addObject:@"Trailer"];
[genres addObject:@"Lo-Fi"];
[genres addObject:@"Tribal"];
[genres addObject:@"Acid Punk"];
[genres addObject:@"Acid Jazz"];
[genres addObject:@"Polka"];
[genres addObject:@"Retro"];
[genres addObject:@"Musical"];
[genres addObject:@"Rock & Roll"];
[genres addObject:@"Hard Rock"];
[genres addObject:@"Folk"];
[genres addObject:@"Folk-Rock"];
[genres addObject:@"National Folk"];
[genres addObject:@"Swing"];
[genres addObject:@"Fast Fusion"];
[genres addObject:@"Bebob"];
[genres addObject:@"Latin"];
[genres addObject:@"Revival"];
[genres addObject:@"Celtic"];
[genres addObject:@"Bluegrass"];
[genres addObject:@"Avantgarde"];
[genres addObject:@"Gothic Rock"];
[genres addObject:@"Progressive Rock"];
[genres addObject:@"Psychedelic Rock"];
[genres addObject:@"Symphonic Rock"];
[genres addObject:@"Slow Rock"];
[genres addObject:@"Big Band"];
[genres addObject:@"Chorus"];
[genres addObject:@"Easy Listening"];
[genres addObject:@"Acoustic"];
[genres addObject:@"Humour"];
[genres addObject:@"Speech"];
[genres addObject:@"Chanson"];
[genres addObject:@"Opera"];
[genres addObject:@"Chamber Music"];
[genres addObject:@"Sonata"];
[genres addObject:@"Symphony"];
[genres addObject:@"Booty Bass"];
[genres addObject:@"Primus"];
[genres addObject:@"Porn Groove"];
[genres addObject:@"Satire"];
[genres addObject:@"Slow Jam"];
[genres addObject:@"Club"];
[genres addObject:@"Tango"];
[genres addObject:@"Samba"];
[genres addObject:@"Folklore"];
[genres addObject:@"Ballad"];
[genres addObject:@"Power Ballad"];
[genres addObject:@"Rhythmic Soul"];
[genres addObject:@"Freestyle"];
[genres addObject:@"Duet"];
[genres addObject:@"Punk Rock"];
[genres addObject:@"Drum Solo"];
[genres addObject:@"A capella"];
[genres addObject:@"Euro-House"];
[genres addObject:@"Dance Hall"];

Matrix rotator

This method rotates a matrix
Example output:
~/Desktop% ruby rotate.rb
normal
12345
00000
fooba
rotated left
50a
40b
30o
20o
10f
rotated right
f01
o02
o03
b04
a05

def rotateMatrix(matrix, direction)
  # - You must Rotate the matrix neo!
  oldMap = matrix

  # Get the number of lines in the old map (they're the new columns)
  lineCount = oldMap.size
  # Get the number of columns in the old map (We have that many rows now)
  columnCount = oldMap[0].size
  @map = []
  columnCount.times { @map.push [] }

  # Loop through every line in the old map, retrieve the appropriate column
  # and make a horizontal column with it's contents
  # we'll take one (old)line at a time and rotate it.
  onLine = 0
  oldMap.each do |oldLine|
    onColumn = 0
    oldLine.each do
      case direction
      when :right
        @map[(columnCount - 1) - onColumn][(lineCount - 1) - onLine] = oldLine[(columnCount - 1) - onColumn]
      when :left
        @map[onColumn][onLine] = oldLine[(columnCount - 1) - onColumn]
      end
      onColumn += 1
    end
    onLine += 1
  end
  @map
end

def rotateRight(matrix)
  rotateMatrix(matrix, :right)
end

def rotateLeft(matrix)
  rotateMatrix(matrix, :left)
end

Alphabetical sorter

// This function sorts an array of objects that include this code, alphabetically
// That's nothing new, except this sorts strings starting with a number correctly!

  # ---
  # Sorting
  # ---
def <=>(other)
    regex = /^[\d]+/
    if self.title =~ regex
      our_num = Regexp.last_match[0].to_i
      if other.title =~ regex
        other_num = Regexp.last_match[0].to_i
        return our_num <=> other_num
      end
    end
    self.title <=> other.title
  end

File icon giver/getter/whatever

This code uses acts_as_attachment (that's the attachment.filename) but you can of course replace it with anything.
It gets the file extension then looks up that extension in a dir full of files named extension.png
if none is found, unknown.png is used


<%
extension = File.extname(attachment.filename).gsub(/\./, "")
# get a file icon
icon_path = nil
Dir.entries("#{RAILS_ROOT}/public/images/filetypes").each do |entry|
	entry_extension = File.extname(entry)
	if entry.gsub(entry_extension, "") === extension
		icon_path = "/images/filetypes/" + entry
		break
	end
end
icon_path = "/images/filetypes/unknown.png" if icon_path.nil?
 %>
<%= image_tag icon_path %>
<span class="attachment_name"><%= attachment.filename %></span><br />

all_children!

This snippet just gives you all the children of a model that acts_as_tree

  def all_children
    Page.all_children_for self
  end
  
  def self.all_children_for(parent, arr = [])
    parent.children.each { |child| arr.push child }
    parent.children.each { |child| all_children_for child, arr }
    arr
  end

Youtube url code

This is a part of a ruby-cocoa app I'm writing.
(TubeSock is just terrible)

require 'net/http'
require 'uri'

class YouTubeMovie
  attr_accessor :viewer_url, :movie_url, :get_params
  def initialize(url)
    @viewer_url = url
    setMovieURL
  end
  def setMovieURL
    # Get the viewer page html
    req = Net::HTTP::Get.new @viewer_url
    viewer_page = nil
    res = Net::HTTP.start(@viewer_url.host, @viewer_url.port) do |request|
      viewer_page = request.request(req)
    end
    # Extract the required info.
    # in the html there's a line like so:
    # var fo = new SWFObject("/player2.swf?video_id=AUnPDmmnF0U&l=1363&t=OEgsToPDskJUmKC_b_nXO_yUrNLKSY18&nc=13369344", "movie_player", "450", "370", 7, "#FFFFFF");
    # we want to extract the ?video_id=AUnPDmmnF0U&l=1363&t=OEgsToPDskJUmKC_b_nXO_yUrNLKSY18&nc=13369344
    # this regex does that...
    regex = Regexp.new(/\?video_id=[\w]+&l=[\w]+&t=[\w]+&nc=[\d]+/)
    @get_params = regex.match(viewer_page.body).to_s
    @movie_url = URI.parse('http://www.youtube.com/get_video' + @get_params)
    p 'movie url: ' + @movie_url.to_s
  end
end
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS