Pages

Wednesday, July 27, 2011

Convert YouTube Videos to MP3

I often find songs on YouTube that I can't obtain elsewhere, especially obscure remixes of popular songs. While it is possible to listen to them directly on YouTube this gets tiresome quickly since you can't add the songs into a GrooveShark or iTunes playlist or play them on your iPod.
I've used several services online that will convert a YouTube video to MP3 format and allow you to download it. These services are covered in banner ads, encode MP3s in low quality and frequently don't work at all.
While browsing MacUpdate.com, I discovered a free program called "YouTube to MP3", it's completely free and allows you to extract only the audio from a YouTube video. This program allows you to select the bitrate, and format. You select the YouTube video you want to download by either clicking the paste from clipboard button or manually typing the URL in. Another nice feature this program has is downloading several songs at the same time.

The program runs on Mac and Windows and can be downloaded from here: http://www.mediahuman.com/download.html

Friday, July 8, 2011

Backup a MySQL Database Nightly

I run several websites, which use MySQL, and I've discovered the importance of backing up my databases regularly. I've had tables become corrupt, and hard drives go without warning. It's important to have a backup plan so you can restore your website quickly if something goes wrong.

The easiest way to backup a MySQL database is to use the mysqldump program, which is included with MySQL server. The mysqldump program allows you to dump a database or table to an SQL file which can be quickly restored using the MySQL command line client. You can ensure your backup is executed on a regular basis using the crontab.

Here is a sample shell script for backing up a MySQL database:

#!/bin/sh

DATE=`date +%Y-%m-%d`
cd /PATH_TO_BACKUP/db_backup
mkdir $DATE
/usr/local/mysql/bin/mysqldump -u root DATABASENAME > /PATH_TO_BACKUP/db_backup/$DATE/DATABASENAME.sql
gzip $DATE/DATABASENAME.sql

The first line stores the current date as a string of the form YYYY-MM-DD, the next two lines change to the directory where you want the backup to be stored and creates a folder named the current date. The next line creates the actual backup using mysqldump, using the root@localhost account. The final line compresses the backup using the gzip utility, this is optional, but it is a good idea if you have a large database.

You can add this script to your crontab and have it execute daily by first typing:

sudo crontab -e

Then adding the following line into your crontab:

1 0 * * * sh /PATH_TO_BACKUP_SCRIPT/backup_mysql.sh

This will execute the script at one minute past midnight every night, but you can easily change this to suit your needs.

We can easily restore from our backup in a few easy steps. First open Terminal and navigate to the folder where our backup is stored. Then type:

gunzip -c DATABASENAME.sql.gz | mysql -u root DATABASENAME

This will decompress our backup, recreate the table structure and import all the data that was stored in the tables. Make sure you have created the database in MySQL prior attempting to restore.

Wednesday, June 29, 2011

Change Your Bash Prompt

The Bash command prompt can easily be changed by modifying the value of the PS1 environment variable. For example: PS1='yes master?> ' will change your command prompt in terminal to "yes master?> ". If you want your command prompt change to become permanent add it to your .bash_profile or .profile file in your home directory.

In addition to changing your bash profile to a simple string of text there are a number of special characters that can be used. The special characters can be used to add things like the current working directory or the current time to your prompt. Below is a list of these special characters taken from the bash manual:

\a A bell character.
\d The date, in "Weekday Month Date" format (e.g., "Tue May 26").
\D{format} The format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required.
\e An escape character.
\h The hostname, up to the first `.'.
\H The hostname.
\j The number of jobs currently managed by the shell.
\l The basename of the shell's terminal device name.
\n A newline.
\r A carriage return.
\s The name of the shell, the basename of $0 (the portion following the final slash).
\t The time, in 24-hour HH:MM:SS format.
\T The time, in 12-hour HH:MM:SS format.
\@ The time, in 12-hour am/pm format.
\A The time, in 24-hour HH:MM format.
\u The username of the current user.
\v The version of Bash (e.g., 2.00)
\V The release of Bash, version + patchlevel (e.g., 2.00.0)
\w The current working directory, with $HOME abbreviated with a tilde (uses the $PROMPT_DIRTRIM variable).
\W The basename of $PWD, with $HOME abbreviated with a tilde.
\! The history number of this command.
\# The command number of this command.
\$ If the effective uid is 0, #, otherwise $.
\nnn The character whose ASCII code is the octal value nnn.
\\ A backslash.
\[ Begin a sequence of non-printing characters. This could be used to embed a terminal control sequence into the prompt.
\] End a sequence of non-printing characters.

Friday, June 24, 2011

Fun With Speech Synthesis

This is a fun way to freak out anyone around a remote Mac using SSH and the builtin text to speech libraries in OS X. The idea is to SSH into a remote Mac and execute the say command, which will convert a string of text into speech. You can use this to "talk" to people around your remote Mac. For example:

say -v "Zarvox" "hello world"

Will speak the phrase "hello world", using the voice Zarvox. If you don't specify a voice the default from the System Preferences will be used. Here is a list of other voices you can use:

Alex
Bruce
Fred
Junior
Ralph
Agnes
Kathy
Princess
Vicki
Victoria
Albert
Bad News
Bahh
Bells
Boing
Bubbles
Cellos
Deranged
Good News
Hysterical
Pipe Organ
Trinoids
Whisper
Zarvox

On the off chance that the Mac you are attempting to have speak has its volume turned down or is muted, you can also turn the volume up using the following command:

sudo osascript -e "set Volume 10"

This will set the system volume to maximum to ensure that any bystanders can hear your Mac speak. Setting the volume does however require the root password.

Monday, June 13, 2011

Programmatically Calculate Battery Charge

This is a cool way to determine what the charge of your battery is on a Mac laptop using Perl. Basically we execute the command ioreg -l in a shell and filter out all the results except MaxCapacity and CurrentCapacity, then we use regular expressions to parse out just the values. From there it's just a matter of calculating what percentage current capacity is of the max capacity and printing out the results.

#!/usr/bin/perl -w

my $MaxCapacity = `ioreg -l | grep 'MaxCapacity'`;
my $CurrentCapacity = `ioreg -l | grep 'CurrentCapacity'`;

$MaxCapacity =~ /(\d+)/;
$MaxCapacity = $1;

$CurrentCapacity =~ /(\d+)/;
$CurrentCapacity = $1;

printf("Battery Charge: %d %%" . "\n", (($CurrentCapacity / $MaxCapacity) * 100));

Executing the script produces something similar to:

Battery Charge: 90 %

If you execute this on a Mac that doesn't have a battery you will probably get a division by zero error.

Friday, June 10, 2011

Shorten a URL on bit.ly using CURL

I often have to shorten URLs when I'm tweeting or simply sending a URL to a friend via email or on instant messenger. Since I generally have a terminal window open I figured it would be expeditious to come up with a shell script to do this for me.

The first thing you have to do is sign up for an account on bit.ly if you haven't already, next you have to obtain an API key. You can sign up for a bit.ly account at: http://bit.ly/a/sign_up if you already have an account you can get your API key at: http://bit.ly/a/your_api_key.

First create a shell script called shorten.sh:

#!/bin/bash

curl -s "http://api.bitly.com/v3/shorten?login=YOURLOGIN&apiKey=YOURAPIKEY&longUrl=$1&format=txt" | pbcopy

This script uses curl in silent mode to connect to the bit.ly API and shorten the url specified by longUrl. Since we want to shorten a variety of URLs I've used $1, which refers to the first argument the script was invoked with. You'll also notice the format parameter, this can be set to xml, json or txt, we're using txt so we don't have to do any parsing. We are piping the output of our curl command into pbcopy a command line utility provided by OS X which provides copying to the clipboard. Pbcopy basically copies all output it receives into the clipboard.

Make sure to fill in YOURLOGIN with your bit.ly login and YOURAPIKEY with your bit.ly API key. Save the shell script somewhere it's not going to be deleted by accident or moved. If you use bash open your .bash_profile file in your home directory. You may have to create it if you haven't made any changes to it before. Add the following line:

alias shorten='/bin/bash /PATHTOSCRIPT/shorten.sh'

Where PATHTOSCRIPT is the path to where you have stored your script. This alias will allow us to invoke our script from anywhere using "shorten" instead of the full path to the script. In order for your .bash_profile to be reloaded and the alias to become active, you need to either type source .bash_profile or open a new terminal window.

Now when you type:

shorten YOURURL

Where YOURURL is any URL you wish to shorten, the shortened version will be copied directly into your machine's clipboard.

Tuesday, June 7, 2011

Analytics For iOS Developers

I have a couple of iPhone apps in the App Store and I was getting quite frustrated with having to haul out a calculator every time I wanted to figure out how many downloads each of my Apps have in total. iTunes Connect seems to be very limited in the data it displays to developers and also how long that data is retained for.

Enter App Figures, a service that syncs with your iTunes connect account daily, and downloads and stores the data. In addition to storing updates, downloads, ranking, and reviews for each app in your account, it also stores iAd statistics. The data is presented in a really nice format with lots of graphs, it is quite reminiscent of Google Analytics.

If you're looking for a better way to keep track of your App Store apps check out http://www.appfigures.com. You can try out the service for free, and once the trial period is up it only costs $4.99 a month and includes tracking of 2 apps.