<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tully Rankin</title>
	<atom:link href="http://www.tullyrankin.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.tullyrankin.com</link>
	<description>My blog includes various articles on Linux, PHP, BASH, Programming, Security, and other technology related topics.</description>
	<lastBuildDate>Fri, 18 May 2012 08:18:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>State Pattern in PHP</title>
		<link>http://www.tullyrankin.com/state-pattern-in-php</link>
		<comments>http://www.tullyrankin.com/state-pattern-in-php#comments</comments>
		<pubDate>Sun, 04 Dec 2011 21:44:28 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=365</guid>
		<description><![CDATA[The state pattern is a behavioural software design pattern. It is used to allow an object to changes it&#8217;s behaviour when it&#8217;s internal state changes. Below is an example of the state pattern in PHP. I have taken a stop watch with 2 buttons and implemented the code using the state pattern. The first button [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fstate-pattern-in-php"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fstate-pattern-in-php&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>The state pattern is a behavioural software design pattern. It is used to allow an object to changes it&#8217;s behaviour when it&#8217;s internal state changes. Below is an example of the <strong>state pattern in PHP</strong>. I have taken a stop watch with 2 buttons and implemented the code using the state pattern. The first button will be the start/stop for the timer. The second button will reset the timer back to 0. Each time you hit stop, the code will output the time since it started in milliseconds.<br />
</p>
<pre name="code" class="php">
interface State {
    function press(StopWatchContext $context);
}

class StopState implements State {
    public function press(StopWatchContext $context) {
        $time = (microtime(TRUE) * 1000) - $context->getStartTime();
        printf("The stop watch is stopped. [Time] %d MS ", $time);;
        $context->setState($context->getStartState());
    }
}

class StartState implements State {
    public function press(StopWatchContext $context) {
        echo "The stop watch is running..";
        $context->setState($context->getStopState());
    }
}

class ResetState implements State {
    public function press(StopWatchContext $context) {
        echo "The stop watch is reset. ";
        $context->setStartTime(microtime(TRUE) * 1000);
        $context->setState($context->getStartState());
    }
}

class StopWatchContext {
    private $state;
    private $startTime;

    private $startState;
    private $stopState;
    private $resetState;

    public function __construct() {
        $this->setStartTime();
        $this->startState = new StartState();
        $this->stopState = new StopState();
        $this->resetState = new ResetState();
        $this->state = $this->startState;
    }

    public function setState(State $state) {
        $this->state = $state;
    }

    public function pressButton() {
        $this->state->press($this);
    }

    public function resetButton() {
        $this->setState(new ResetState());
        $this->pressButton();
    }

    public function getStartTime() {
        return $this->startTime;
    }

    public function setStartTime() {
        $this->startTime = microtime(TRUE) * 1000;
    }

    public function getStartState() {
        return $this->startState;
    }

    public function getStopState() {
        return $this->stopState;
    }

    public function getResetState() {
        return $this->resetState;
    }
}

$timer = new StopWatchContext();
$timer->pressButton(); //started
usleep(1200 * 1000); // sleeping 1.2 seconds
$timer->pressButton(); //stopped

$timer->pressButton(); //started
usleep(2000 * 1000); //sleeping 1.7 seconds (3200 MS)
$timer->pressButton();//stopped

$timer->resetButton(); //reset
$timer->pressButton();//started
sleep(2);//sleeping 2 seconds
$timer->pressButton(); //stopped
?>
</pre>
<p>
:: Output: :<br />
The stop watch is running.. <br />
The stop watch is stopped. [Time] 1200 MS<br />
The stop watch is running..<br />
The stop watch is stopped. [Time] 3200 MS <br />
The stop watch is reset. <br />
The stop watch is running.. <br />
The stop watch is stopped. [Time] 2000 MS </p>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/state-pattern-in-php/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java RSS Reader Example</title>
		<link>http://www.tullyrankin.com/java-rss-reader-example</link>
		<comments>http://www.tullyrankin.com/java-rss-reader-example#comments</comments>
		<pubDate>Mon, 07 Nov 2011 18:26:23 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[JAVA]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=361</guid>
		<description><![CDATA[Today I was working with the DOM in Java and decided to write a simple RSS reader. The code below is an example of a Java RSS Reader. You just give it an instance of URL through the setURL assessor. Then call the writeFeed() method which outputs the title/description/link of each item in the feed. [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fjava-rss-reader-example"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fjava-rss-reader-example&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today I was working with the DOM in Java and decided to write a simple RSS reader. The code below is an example of a Java RSS Reader. You just give it an instance of URL through the setURL assessor. Then call the writeFeed() method which outputs the title/description/link of each item in the feed.</p>
<pre class="java">import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class RSSReader {

   private static RSSReader instance = null;

   private URL rssURL;

   private RSSReader() {}

   public static RSSReader getInstance() {
      if (instance == null)
         instance = new RSSReader();
      return instance;
   }

   public void setURL(URL url) {
      rssURL = url;
   }

   public void writeFeed() {
      try {
         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
         Document doc = builder.parse(rssURL.openStream());

         NodeList items = doc.getElementsByTagName("item");

         for (int i = 0; i &lt; items.getLength(); i++) {
            Element item = (Element)items.item(i);
            System.out.println(getValue(item, "title"));
            System.out.println(getValue(item, "description"));
            System.out.println(getValue(item, "link"));
            System.out.println();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public String getValue(Element parent, String nodeName) {
      return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
   }

   public static void main(String[] args) {
      try {
         RSSReader reader = RSSReader.getInstance();
         reader.setURL(new URL("http://www.tullyrankin.com/feed/rss"));
         reader.writeFeed();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/java-rss-reader-example/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHPDOC For Vim</title>
		<link>http://www.tullyrankin.com/phpdoc-for-vim</link>
		<comments>http://www.tullyrankin.com/phpdoc-for-vim#comments</comments>
		<pubDate>Wed, 19 Oct 2011 18:20:04 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=357</guid>
		<description><![CDATA[My editor of choice for development has always been Vim. When I&#8217;m coding, I always leave PHPDOC comments for all classes, properties, and methods. I have been using a macro to include the basic PHPDOC comment header. This has worked fine for me so far. However, today I stumbled upon PHPDOC.vim plug-in. The plugin automatically [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fphpdoc-for-vim"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fphpdoc-for-vim&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>My editor of choice for development has always been Vim. When I&#8217;m coding, I always leave PHPDOC comments for all classes, properties, and methods. I have been using a macro to include the basic PHPDOC comment header. This has worked fine for me so far. However, today I stumbled upon PHPDOC.vim plug-in. The plugin automatically creates the PHPDOC comment for you the second it sees you creating a class, method, or adding a class property.</p>
<p>To install just download the plugin from the following link:<br />
<a href="http://markus.fischer.name/vim/phpdoc/phpdoc.vim">http://markus.fischer.name/vim/phpdoc/phpdoc.vim</a></p>
<p>Place the file in your plug in directory for vim.<br />
This can be found at <strong>~/.vim/plugin</strong></p>
<p>Once the plug in is installed, just open a PHP document and start creating a class, method, or property.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/phpdoc-for-vim/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google Keywords API PHP</title>
		<link>http://www.tullyrankin.com/google-keywords-api-php</link>
		<comments>http://www.tullyrankin.com/google-keywords-api-php#comments</comments>
		<pubDate>Tue, 10 May 2011 17:44:17 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=348</guid>
		<description><![CDATA[I wrote a PHP script that connects to Google Ananlytics API and retreives your top keywords. Google Analytics has a scheduler that can send you emails of your keywords, but this script can be used to return various formats and then be sent to another program or logged for further processing. The first couple lines [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fgoogle-keywords-api-php"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fgoogle-keywords-api-php&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I wrote a PHP script that connects to Google Ananlytics API and retreives your top keywords. Google Analytics has a scheduler that can send you emails of your keywords, but this script can be used to return various formats and then be sent to another program or logged for further processing.</p>
<p>The first couple lines have to do with the start-date and end-date of the statistics to return. Currently it&#8217;s set-up to run on a cron on the first of every month and send me a report of the last months keywords. This can easily be changed by modifying the startDate and endDate variables.</p>
<p>The Table ID which is the ID of your site in analytics, is set to retrieve it&#8217;s value as the first param given on the command line. So if your table id was 123456, you would call the script as &#8220;php googleAnalyticsFeed ga:123456&#8243;.</p>
<pre name="code" class="php">
define("GoogleNameSpace", "http://schemas.google.com/analytics/2009");
define("GoogleClientLoginURL", "https://www.google.com/accounts/ClientLogin");
define("GoogleUserEmail", "YOUR_EMAIL_HERE");
define("GoogleUserPass", "YOUR_PASSWORD_HERE");
define("GoogleFeedURL", "https://www.google.com/analytics/feeds/data");

#(First/Last day of previous month)
$lastDayOfMonth = date('Y-m-d', strtotime("-1 second ".date('m').'/01/'.date('Y')));
$firstDayOfMonth = date('Y-m-01', strtotime("-1 second ".date('m').'/01/'.date('Y')));

$table = $argv[1];              # Table ID for Site
$startDate = $firstDayOfMonth;  #Start Date to Search
$endDate = $lastDayOfMonth;     # End Date to Search
$max = 100;                     # Max-results to display

#Auth String
$auth = googleAuth(GoogleUserEmail, GoogleUserPass);

#Get XML Keyword Data
$xml = getKeywords($auth, $table, $startDate, $endDate, $max);

#Loop Through Results and Display (Count - Keyword)
$dom = new DomDocument();
$dom->loadXML($xml);
$entries = $dom->getElementsByTagName('entry');

foreach ($entries as $entry) {
    $keyword = $entry->getElementsByTagNameNS(GoogleNameSpace, 'dimension')->item(0)->getAttribute('value');
    $total = $entry->getElementsByTagNameNS(GoogleNameSpace, 'metric')->item(0)->getAttribute('value');
    printf("%5d - %s\n", $total, $keyword);
}

#Get Google Auth
function googleAuth($email, $pass) {
    $ch = curl_init(GoogleClientLoginURL);
    $postParams = array(
                    "Email"         =>  $email,
                    "Passwd"        =>  $pass,
                    "accountType"   =>  "GOOGLE",
                    "source"        =>  "curl-dataFeed-v2",
                    "service"       =>  "analytics");
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postParams));
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    preg_match('/Auth=.*/', $data, $auth);
    return $auth[0];
}

#Get Google Keywords
function getKeywords($auth, $table, $startDate, $endDate, $max) {
    $getParams = array(
                    "ids"           =>  $table,
                    "start-date"    =>  $startDate,
                    "end-date"      =>  $endDate,
                    "dimensions"    =>  "ga:keyword",
                    "metrics"       =>  "ga:visits",
                    "sort"          =>  "-ga:visits",
                    "max-results"   =>  $max,
                    "prettyprint"   =>  "false");
    $ch = curl_init(GoogleFeedURL.'?'.http_build_query($getParams));
    $header[0] = "Authorization: GoogleLogin $auth";
    $header[1] = "GData-Version: 2";

    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    return $data;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/google-keywords-api-php/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>keywords from apache logs</title>
		<link>http://www.tullyrankin.com/keywords-from-apache-logs</link>
		<comments>http://www.tullyrankin.com/keywords-from-apache-logs#comments</comments>
		<pubDate>Fri, 04 Mar 2011 19:48:14 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[Apache]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=335</guid>
		<description><![CDATA[I wrote a quick 1 liner last week to get the Google keywords/phrases people were searching to get to my site from the apache logs. The script parses the apache logs and searches for users coming from Google. It then parses each line and outputs the urldecoded version with the number of hits for each [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fkeywords-from-apache-logs"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fkeywords-from-apache-logs&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I wrote a quick 1 liner last week to get the Google keywords/phrases people were searching to get to my site from the apache logs. The script parses the apache logs and searches for users coming from Google. It then parses each line and outputs the urldecoded version with the number of hits for each keyword/phrase.<br />
</p>
<pre name="code" class="php">cat access_log access_ssl_log | grep --line-buffered 'www.google.com' | egrep --line-buffered -o 'q=.*\&amp;' | tr -d 'q=' | cut -d\&amp; -f1 | egrep --line-buffered '[a-zA-Z0-9]{1}\r' | php -R 'echo urldecode($argn) . "\n";' | sed -e 's/^[ \t]*//g' | sort | uniq -c | sort -n</pre>
<p>
<strong>&#8211;Sample Output&#8211;<br />
</strong><br />
2 java program to count freuency of letters<br />
2 letter freuency in java<br />
2 myslimport csv<br />
2 php bubble sort<br />
2 rand with vectors c++<br />
2 which logical unit of the computer retains information<br />
2 zend_form_element select<br />
4 google weather api<br />
4 php developer resume<br />
4 selection sort example<br />
5 six logical units of a computer</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/keywords-from-apache-logs/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MOV Files on PS3</title>
		<link>http://www.tullyrankin.com/mov-files-on-ps3</link>
		<comments>http://www.tullyrankin.com/mov-files-on-ps3#comments</comments>
		<pubDate>Mon, 21 Feb 2011 06:48:26 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=329</guid>
		<description><![CDATA[Learn how to play .MOV files on the PS3. This article uses FFMPEG to re-encode the video files to work on a PS3. Can be used over a media server.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fmov-files-on-ps3"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fmov-files-on-ps3&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>This last weekend I bought a new HD ZI8 camcorder. I wanted to play the movies files on my PS3. I run a media server using ushare on my Linux box. The ZI8 camcorder saves the recorded videos in .mov format. These files would not play on my PS3. After some research, I found a solution using ffmpeg. The command I use to convert these files to work on the PS3 using my media server is below.</p>
<pre name="code" class="php">
ffmpeg -i original_file.mov -acodec mp2 -ar 32000 -vcodec mpeg1video -qscale 14 new_file.mpg
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/mov-files-on-ps3/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend Form Element Select Helper</title>
		<link>http://www.tullyrankin.com/zend-form-element-select-helper</link>
		<comments>http://www.tullyrankin.com/zend-form-element-select-helper#comments</comments>
		<pubDate>Thu, 27 Jan 2011 01:27:16 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[zend form]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=324</guid>
		<description><![CDATA[Today I wrote a small helper that will transform an array to work with Zend Form Element Select. Zend Form Element Select uses the key of an array as the value, and the value as the key. I&#8217;m not sure why Zend did this, but I wrote a small helper class that can be used [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fzend-form-element-select-helper"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fzend-form-element-select-helper&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today I wrote a small helper that will transform an array to work with Zend Form Element Select. Zend Form Element Select uses the key of an array as the value, and the value as the key. I&#8217;m not sure why Zend did this, but I wrote a small helper class that can be used to re-arrange an array to work properly with the Zend Element Select. To use the class, just give it the array, the key you would like to use as the name, and the key you&#8217;d like to use for the value.</p>
<pre name="code" class="php">
class Helpers_FormHelper {

    public static function createNewArrayWithGivenKeyValuePairs(Array $data, $key, $value) {
        $transformedData = array();
        foreach ($data as $row) {
                    $transformedData[$row[$value]] = $row[$key];
        }
        return $transformedData;
    }
}
</pre>
<p>Example:</p>
<pre name="code" class="php">
Helpers_FormHelper::createNewArrayWithGivenKeyValuePairs($colors, 'name', 'id');
</pre>
<p>
<strong>Before</strong><br />
</p>
<pre name="code" class="php">
array
  0 =>
    array
      'id' => string '1' (length=1)
      'name' => string 'Red' (length=3)
  1 =>
    array
      'id' => string '2' (length=1)
      'name' => string 'Blue' (length=4)
  2 =>
    array
      'id' => string '3' (length=1)
      'name' => string 'Yellow' (length=6)
  3 =>
    array
      'id' => string '4' (length=1)
      'name' => string 'Orange' (length=6)
  4 =>
    array
      'id' => string '5' (length=1)
      'name' => string 'Green' (length=5)
</pre>
<p>
<strong>After</strong><br />
</p>
<pre name="code" class="php">
array
  1 => string 'Red' (length=8)
  2 => string 'Blue' (length=7)
  3 => string 'Yellow' (length=7)
  4 => string 'Orange' (length=6)
  5 => string 'Green' (length=8)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/zend-form-element-select-helper/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL Distance Between Two Locations</title>
		<link>http://www.tullyrankin.com/mysql-distance-between-two-locations</link>
		<comments>http://www.tullyrankin.com/mysql-distance-between-two-locations#comments</comments>
		<pubDate>Fri, 07 Jan 2011 08:48:22 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[MySQL]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=308</guid>
		<description><![CDATA[Problem: I need to return table rows within a set amount of miles from given latitude/longitude. Solution: 1. Create a MySQL function that takes the coordinates of point A and point B and returns the distance in miles. 2. Write a MySQL select statement that uses the newly created function to return rows where distance [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fmysql-distance-between-two-locations"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fmysql-distance-between-two-locations&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p><strong>Problem:<br />
</strong>I need to return table rows within a set amount of miles from  given latitude/longitude.</p>
<p><strong>Solution:</strong><br />
1. Create a MySQL function that takes the coordinates of point A and point B and returns the distance in miles.<br />
2. Write a MySQL select statement that uses the newly created function to return rows where distance is less then <b>X</b> miles.</p>
<p><a href="http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe">Calculate distance between two points on a globe.</a></p>
<pre name="code" class="sql">
DELIMITER //
CREATE FUNCTION `GetDistance`(
 lat1  numeric (9,6),
 lon1  numeric (9,6),
 lat2  numeric (9,6),
 lon2  numeric (9,6)
) RETURNS decimal(10,5)
    READS SQL DATA
BEGIN
  DECLARE  x  decimal (20,10);
  DECLARE  pi  decimal (21,20);
  SET  pi = 3.14159265358979323846;
  SET  x = sin( lat1 * pi/180 ) * sin( lat2 * pi/180  ) + cos(
 lat1 *pi/180 ) * cos( lat2 * pi/180 ) * cos(  abs( (lon2 * pi/180) -
 (lon1 *pi/180) ) );
  SET  x = acos( x );
  RETURN  ( 1.852 * 60.0 * ((x/pi)*180) ) / 1.609344;
END //
DELIMITER ;
</pre>
<p><strong>Example:</strong></p>
<pre name="code" class="sql">
mysql> select City, GetDistance(Latitude, Longitude, (SELECT Latitude from hotels where City = 'Pasadena' and StateProvince = 'CA' limit 1),(SELECT Longitude from hotels where City = 'Pasadena' and StateProvince = 'CA' limit 1)) as Distance from hotels where StateProvince = 'CA' group by City, StateProvince having Distance < 10 order by Distance DESC;
+----------------+----------+
| City           | Distance |
+----------------+----------+
| Duarte         |  9.83023 |
| Monrovia       |  9.03029 |
| El Monte       |  8.99051 |
| South El Monte |  8.80477 |
| Rosemead       |  8.09559 |
| Arcadia        |  6.91626 |
| Glendale       |  6.34357 |
| Monterey Park  |  5.67806 |
| San Gabriel    |  4.90842 |
| Alhambra       |  3.37174 |
| Pasadena       |  0.00000 |
+----------------+----------+
11 rows in set, 9240 warnings (0.36 sec)
</pre>
<p></p>
<p>Note: The above will return only unique cities that are within 10 miles of Pasadena, CA. To bring back all the matched rows just remove the "group by City, StateProvince".</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/mysql-distance-between-two-locations/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Website Domain Checker</title>
		<link>http://www.tullyrankin.com/website-domain-checker</link>
		<comments>http://www.tullyrankin.com/website-domain-checker#comments</comments>
		<pubDate>Wed, 03 Nov 2010 17:35:03 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=302</guid>
		<description><![CDATA[The Website Domain Checker script is used to check if any DNS records exist for the given domain. The response is either Available or Taken.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fwebsite-domain-checker"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fwebsite-domain-checker&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today I wanted to check a few domains and see if they were available or already taken. I figured the best way to do this would be to check if there was any DNS records for the requested domains. I did a quick look at the functions available to me in PHP, and came across the function <strong>checkdnsrr</strong>. The checkdnsrr function can be used to check a domain for any type of DNS records. So now that I found the function to use, I wrote a simple 6 line PHP script I can use from the command line. The script takes 1 parameter, the domain name.</p>
<p>To use the script from the command line, you would type <strong>./domainChecker tullyrankin.com</strong> where &#8220;tullyrankin.com&#8221; would be replaced with whatever domain you are checking. If the domain has no DNS records, the output will be &#8220;Domain is available!&#8221;. If the domain has any DNS records, the response will be &#8220;Domain is already taken&#8221;. The code for this script is below.</p>
<pre class="php">#!/usr/bin/php -f
&lt;?php
if ($argc &lt; 2)
	die("Usage: php ".basename($argv[0])." [domain]\n");

if (checkdnsrr($argv[1], "ANY"))
	echo "Domain is already taken\n";
else
	echo "Domain is available!\n";</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/website-domain-checker/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Qmail Queue</title>
		<link>http://www.tullyrankin.com/qmail-queue</link>
		<comments>http://www.tullyrankin.com/qmail-queue#comments</comments>
		<pubDate>Wed, 27 Oct 2010 22:58:56 +0000</pubDate>
		<dc:creator>Tully</dc:creator>
				<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://www.tullyrankin.com/?p=296</guid>
		<description><![CDATA[Today I wanted to check how many emails were in the queue for Qmail. I wanted to display where all the outgoing emails were getting sent, and get a count of how many are going to that email address. To complete this task, I put together a quick 1 liner that loops through the queued [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.tullyrankin.com%2Fqmail-queue"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.tullyrankin.com%2Fqmail-queue&amp;source=tullyrankin&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today I wanted to check how many emails were in the queue for Qmail. I wanted to display where all the outgoing emails were getting sent, and get a count of how many are going to that email address. To complete this task, I put together a quick 1 liner that loops through the queued emails, greps the &#8220;to&#8221; field, and then sorts and counts the results. The line of bash I wrote to do this is shown below.</p>
<p><span style="color: #000000;"><strong>for i in `find /var/qmail/queue/mess -type f`;do cat $i | egrep -o &#8216;To:.*[com,org,net]&#8216; | awk &#8216;{print $2}&#8217; &gt;&gt; /tmp/emailTmp;done; cat /tmp/emailTmp | sort | uniq -c | sort -n;rm -f /tmp/emailTmp; </strong></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.tullyrankin.com/qmail-queue/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

