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

« Newer Snippets
Older Snippets »
Showing 21-30 of 33 total

Keyboard shortcut for the green "zoom" button

// Ever since I started using OS X as my main OS (back at version 10.1), I kept wishing for a keyboard shortcut for the green button at the top left of each window. I wanted a quick way to maximize a window. Sadly, such a shortcut never came into being. I finally took the time to write an applescript to do the job. You can paste this script into Script Editor and save it in your ~/Library/Scripts/ folder. I saved my script as "Click Green Maximize Button of Frontmost Window.scpt". I then used QuickSilver's Triggers feature to assign the keyboard shortcut Control-Option-Z to run the script. I picked that key combination because it's easy to press. I remember it by thinking of the Z as standing for Zoom. Get QuickSilver here: http://www.versiontracker.com/dyn/moreinfo/macosx/22549

tell application "System Events"
	if UI elements enabled then
		set FrontApplication to (get name of every process whose frontmost is true) as string
		tell process FrontApplication
			click button 2 of window 1
			--button 2 is the green "zoom" button for all applications
			--window 1 is always the frontmost window.
		end tell
	else
		tell application "System Preferences"
			activate
			set current pane to pane "com.apple.preference.universalaccess"
			display dialog "UI element scripting is not enabled. Check 'Enable access for assistive devices'"
		end tell
	end if
end tell

StartupItem for daemontools on OS X

DaemonTools script

#!/bin/sh

. /etc/rc.common

PATH=/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin

StartService ()
{
    if [ ! -f /var/run/svscan.pid ]
    then
        ConsoleMessage "Starting svscan"

        # shutdown all the services and their logs (i.e., clean up)
        /usr/local/bin/svc -dx /var/service/* /var/service/*/log

        # launch svscan
        env - PATH=$PATH svscan /var/service > /var/log/svscan.log 2>&1 &
   
        # keep track of svscan's pid
        echo $! > /var/run/svscan.pid
    else
        ConsoleMessage "svscan already running"
    fi
}

StopService()
{
    ConsoleMessage "Stopping svscan and its services"

    # stop svscan
    kill `cat /var/run/svscan.pid`

    # remove the pid file
    rm /var/run/svscan.pid

    # shutdown all the services and their logs (i.e., clean up)
    /usr/local/bin/svc -dx /var/service/* /var/service/*/log
}

RestartService ()
{
    StopService
    StartService
}

RunService "$1"



StartupParameters.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Description</key>
	<string>Daemon tools svscan</string>
	<key>Provides</key>
	<array>
		<string>DaemonTools</string>
	</array>
    <key>Requires</key>
    <array>
        <string>Network Configuration</string>
    </array>
	<key>Uses</key>
	<array>
		<string>Network Configuration</string>
	</array>
	<key>OrderPreference</key>
	<string>Early</string>
</dict>
</plist>

Show/Hide Hidden Files

// for toggling invisible files on and off in the finder

-- found this script here: http://forums.macosxhints.com/showpost.php?p=251001&postcount=3
-- i added the "delay 5" because after running script, finder didn't relaunch, maybe that's not needed on a faster machine
-- it's for toggling invisible files on and off in the finder, use for when i need to copy .htaccess files via a GUI

on run
	set hiddenState to (do shell script "/usr/bin/defaults read com.apple.Finder AppleShowAllFiles")
	try
		if hiddenState = "0" or hiddenState contains "does not exist" then
			set showPrompt to display alert "Are you sure you want to show all hidden files?" message "The Finder will quit and relaunch afterwards." buttons {"Cancel", "Show Hidden Files"} default button "Show Hidden Files"
			if button returned of showPrompt = "Show Hidden Files" then
				tell application "Finder" to quit
				do shell script "/usr/bin/defaults write com.apple.Finder AppleShowAllFiles 1"
				delay 5 --give finder time to quit so it can be relaunched below
			else if button returned of showPrompt = "Cancel" then
				return 0
			end if
		else if hiddenState = "1" then
			set showPrompt to display alert "Are you sure you want to hide all hidden files?" message "The Finder will quit and relaunch afterwards." buttons {"Cancel", "Hide Hidden Files"} default button "Hide Hidden Files"
			if button returned of showPrompt = "Hide Hidden Files" then
				tell application "Finder" to quit
				do shell script "/usr/bin/defaults write com.apple.Finder AppleShowAllFiles 0"
				delay 5 --give finder time to quit so it can be relaunched below
			else if button returned of showPrompt = "Cancel" then
				return 0
			end if
		end if
	on error theError
		FinderCheck()
		display alert theError as critical message "Changes may or may not have been made."
	end try
	FinderCheck()
end run

on FinderCheck()
	tell application "System Events"
		if (name of every process) does not contain "Finder" then
			tell application "Finder" to launch
		end if
	end tell
end FinderCheck

Open current Finder window in new iTerm tab

// cd to the current finder window folder in iTerm. Or drag a folder onto this script to cd to that folder in iTerm.

-- cd to the current finder window folder in iTerm. Or drag a folder onto this script to cd to that folder in iTerm.
-- found this script in the comments of this article: http://www.macosxhints.com/article.php?story=20050924210643297

-- Instructions for use:
-- paste this script into Script Editor and save as an application to ~/Library/Scripts/Applications/Finder/cd to in iTerm
-- run via the AppleScript Menu item (http://www.apple.com/applescript/scriptmenu/)
-- Or better yet, Control-click and drag it to the top of a finder window so it appears in every finder window.
-- Activate it by clicking on it or dragging a folder onto it.

-- Another nice touch is to give the saved script the same icon as iTerm.
-- To do this, in the finder, Get info (Command-I) of both iTerm and this saved script.
-- Click the iTerm icon (it will highlight blue) and copy it by pressing Comand-C.
-- Click on this script's icon and paste by pressing Command-V.

-- Another way to give it the same icon as iTerm is to save the script as an application bundle (instead of an application),
--  then copy the icon by entering these commands in iTerm:
-- $ cd ~/Library/Scripts/Applications/Finder/cd\ to\ in\ iTerm.app/Contents/Resources/
-- $ rm droplet.icns
-- $ cp /Applications/iTerm.app/Contents/Resources/iTerm.icns droplet.icns
-- $ touch ~/Library/Scripts/Applications/Finder/cd\ to\ in\ iTerm.app

-- script was opened by click in toolbar
on run
	tell application "Finder"
		try
			set currFolder to (folder of the front window as string)
		on error
			set currFolder to (path to desktop folder as string)
		end try
	end tell
	CD_to(currFolder, false)
end run

-- script run by draging file/folder to icon
on open (theList)
	set newWindow to false
	repeat with thePath in theList
		set thePath to thePath as string
		if not (thePath ends with ":") then
			set x to the offset of ":" in (the reverse of every character of thePath) as string
			set thePath to (characters 1 thru -(x) of thePath) as string
		end if
		CD_to(thePath, newWindow)
		set newWindow to true -- create window for any other files/folders
	end repeat
	return
end open

-- cd to the desired directory in iterm
on CD_to(theDir, newWindow)
	set theDir to quoted form of POSIX path of theDir as string
	tell application "iTerm"
		activate
		delay 1
		-- talk to the first terminal 
		tell the first terminal
			try
				-- launch a default shell in a new tab in the same terminal 
				launch session "Default Session"
			on error
				display dialog "There was an error creating a new tab in iTerm." buttons {"OK"}
			end try
			tell the last session
				try
					-- cd to the finder window
					write text "cd " & theDir
				on error
					display dialog "There was an error cding to the finder window." buttons {"OK"}
				end try
			end tell
		end tell
	end tell
end CD_to

Create VIPs on Mac OSX

Virtual IPs are so damn useful it hurts sometimes. On Mac OS X 10.1 and above, they're extremely easy to create:

Create a VIP on the same subnet as the primary interface(netmask must be 0xFFFFFFFF):

# ifconfig en1 inet 192.168.1.130 netmask 255.255.255.255 alias


Create a VIP on a different subnet:

# ifconfig en1 inet 192.168.64.25 netmask 255.255.255.0 alias


(Note: you may have to sub en0 for en1. Use ifconfig -a to find out what interfaces are available)

Now you have another IP that you can bring stuff up on that won't collide with other stuff running on the same port.

This is in no way limited to Rails but we can use it to illustrate. Create a VIP for 192.168.1.150 using the ifconfig command above. Then add a line to your /etc/hosts file as follows:

192.168.1.150  myapp


Now bring Rails up bound to that address on port 80:

$ cd devel/myapp
$ ./script/server -b myapp -p 80


http://myapp/ should now be on Rails.

Load OS X's environment.plist in your shell

To make environment variables available to Mac OS X GUI applications, those variables must be defined in your ~/.MacOSX/environment.plist. Sometimes you want to have those same environment variables available from your shell as well. If you're using Terminal, that's no problem--the variables from environment.plist are available. But what if you need to SSH into the machine?

Adhering to the DRY principle, this script can be launched from your shell's rc file to load up the environment variables from environment.plist. To load it into my tcsh environment, I use

if ($?SSH_CLIENT) then
    eval `~/bin/parseEnvironmentPlist.rb`
endif


And here's the ruby script:

#!/usr/bin/ruby

#
# A script for parsing ~/.MacOSX/environment.plist and loading the 
# environment variables it defines into a shell environment.
#

# determine which shell the user is running
# currently we support bash and tcsh
if /^\/[-A-Za-z\/]+\/(bash|tcsh)$/ =~ ENV['SHELL']
    shell = $1
else
    # if we can't determine the users shell, or if
    # it's an unsupported shell, bail out here
    exit 1
end

# a regex for matching <key>...</key> lines
# group 1 is the name of the key
key_re = /^\s*<key>([A-Za-z]+[_A-Za-z0-9]*)<\/key>\s*$/

# a regex for matching <string>...</string> value lines
# group 1 is the value of the environment variable
value_re = /^\s*<string>([-_:.\/0-9A-Za-z]+)<\/string>\s*$/

File.open("#{ENV['HOME']}/.MacOSX/environment.plist", "r") do |plist|

    currentKey = "" # the key we're currently processing
    
    # look at each line of the file to find keys
    # followed by values
    plist.each_line do |next_line| 
    
        # if we find a key, hold on to it 
        if key_re =~ next_line
            currentKey = $1
            currentValue = ""
        
        # since key lines alternate with value lines,
        # if we match a value line, we know it's a value
        # for the previously matched key
        elsif value_re =~ next_line
            currentValue = $1
        
            if shell == "bash"
                # output a setenv command to stdout that's 
                # suitable for running through bash's eval
                puts "#{currentKey}=#{currentValue}; export #{currentKey};"
            elsif shell == "tcsh"
                # output a setenv command to stdout that's 
                # suitable for running through tcsh's eval
                puts "setenv #{currentKey} #{currentValue};"
            else
                # we should never get to this point since we 
                # exit much earlier if the shell type can't be 
                # determined. But, just in case, exit here too.
                exit 1
            end
        
            currentKey = currentValue = ""
        end
    
    end

end


I wrote this script back when I was first learning Ruby, so A) that's why there are so many comments and 2) it could probably be improved, but it works for me!

Mount an SMB / Samba share from the OS X command line

mount_smbfs -W workgroup //user@SERVER/folder ./mntpoint

solve svn error "can't recode string" on Mac OS X

was getting this error on certain files until I added this to ~/.bash_profile :
export LC_CTYPE="en_US.UTF-8"
export LANG="en_US.UTF-8"

iTunes arrows search local library

A neat trick in iTunes 4.5 that changes the little arrows next to each artist/album/title to search your library for that string instead of the iTunes Music Store.

defaults write com.apple.iTunes invertStoreLinks -bool YES

turn off disk image verification

defaults write com.apple.frameworks.diskimages skip-verify true
« Newer Snippets
Older Snippets »
Showing 21-30 of 33 total