<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:refactormycode.com,2007:users698friends</id>
  <link type="application/atom+xml" href="http://refactormycode.com/users/698/friends" rel="self"/>
  <title>mrxinu friends</title>
  <updated>Tue Jul 29 13:51:19 +0000 2008</updated>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor14025</id>
    <published>2008-07-29T13:51:19+00:00</published>
    <title>[PHP] On Object with Field names as resources</title>
    <content type="html">&lt;p&gt;I did something similar not long ago. I needed one ORM in PHP but Doctrine (&lt;a href="http://www.phpdoctrine.org/" target="_blank"&gt;http://www.phpdoctrine.org/&lt;/a&gt;) was not a option  because I had some restriction on my env. So I went and wrote some very light ORM.&lt;/p&gt;

&lt;p&gt;The idea is similar with yours, since is kind a big code I will try to show the basic.&lt;/p&gt;

&lt;p&gt;I have some classes AbstractTable, AbstractEntry, TableFactory and DBTypeMapper. I think is pretty straight forward their functions. The first catch is that TableFactory scans a subdir looking for a table definition, this because a table definition mention primary keys but not the columns. &lt;/p&gt;

&lt;p&gt;TableFactory gives you a object if your table type, since this object is a AbstractTable, mostly operations in a table is centrilized in this class. If I get one query that is too specific for a table I just implement the method inside the table definition file. &lt;/p&gt;

&lt;p&gt;I will paste a simple method of AbstractTable, find() which searchs for a entry based on table primary keys. Note that this method returns a object of type entry, so each table has his own class and each entry has too.&lt;/p&gt;

&lt;p&gt;One final consideration is type mapping, I wanted to pass a object of type 'entry' to find similar entries and etc. So I wrote a simple type mapper based on Oracle&#180;s types. In AbstractTable code look at method find_by_entry(), it receives one abstract entry and searchs the database for it, but since PHP isn&#180;t strogly typed I had to figure out what type is the column before create the 'where' clause. &lt;/p&gt;

&lt;p&gt;The catch with DBTypeMapper is that it fetches the meta information from Oracle when given a table name and use defined handlers for each type. &lt;/p&gt;

&lt;p&gt;All works well for a lightweight ORM, I wouldn&#180;t bet this kind of structure for a really big framework, not without some revisions. In the and I will paste what a sample of a code using this structure to be more clear.&lt;/p&gt;

&lt;p&gt;Hope this helps.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;## TableFactory [php]
&amp;lt;?php

class TableFactory {

  public static function getTable($tableName) {

    $tableName = ucfirst(strtolower($tableName));

    if(include_once('tables/'.$tableName.'.php')) {
      return new $tableName;
    }
    else {
      throw new Exception('tabela '.$tableName.' n&#227;o definida no diret&#243;rio &amp;quot;tables/&amp;quot; ');
    }
  }
}
?&amp;gt;

## A table definition [php]
&amp;lt;?php
// table manip...
class Basic_login extends AbstractTable {

  protected $primary_key = 'LOGIN_ID';

}

class Basic_login_entry extends AbstractEntry { }

?&amp;gt;

## AbstractTable [php]

&amp;lt;?php

  public function find($id) {
    return $this-&amp;gt;find_by($this-&amp;gt;primary_key,$id);
  }

  public function find_by($column, $value) {

    $select = 'SELECT * FROM '.strtoupper(get_class($this)).
      ' WHERE '.strtoupper($column).' = '.$value;

    $stmt = $this-&amp;gt;ocihelper-&amp;gt;parse($select);

    $this-&amp;gt;ocihelper-&amp;gt;execute($stmt);

    return $this-&amp;gt;_map_result($stmt);
  }

 protected function _map_result($stmt) {
    $entries = array();

    while($row = oci_fetch_assoc($stmt)) {

      // class represents a entry in table
      $entryClass = get_class($this); $entryClass .='_entry';
      $entry = new $entryClass;

      // map columns found to fields...
      foreach($row as $field =&amp;gt; $value) {
        $property = strtolower($field);
        if(!oci_field_is_null($stmt,$field)) {
          $entry-&amp;gt;$property = $value;
        }
      }
      $entries[] = $entry;
    }

    // return all entries found
    return $entries;
  }

  public function find_by_entry(AbstractEntry $entry) {

    $this-&amp;gt;is_entry_eq_class($entry);

    $this-&amp;gt;dbtypemapper-&amp;gt;map($entry);

    $sql = &amp;quot;SELECT * FROM &amp;quot;.strtoupper(get_class($this)). &amp;quot; WHERE &amp;quot;;

    $terms;
    foreach($entry-&amp;gt;get_fields() as $field) {
      $terms[] = strtoupper($field).'='.$entry-&amp;gt;$field;
    }
    
    $sql .= implode(' AND ',$terms);

    $stmt = $this-&amp;gt;ocihelper-&amp;gt;parse($sql);

    $this-&amp;gt;ocihelper-&amp;gt;execute($stmt);

    return $this-&amp;gt;_map_result($stmt);
  }
?&amp;gt;

## DBTypeMapper [php]

&amp;lt;?php

class DBTypeMapper {

  private $conn;

  public function __construct() {
    $this-&amp;gt;conn = DBConnection::get()-&amp;gt;handle();
  }

  public function map(AbstractEntry $entry) {

    // get the table name from entry object.
    $table_name = strtoupper(str_replace('_entry', '', get_class($entry)));

    if(!IsSet($this-&amp;gt;cache[$table_name])) $this-&amp;gt;load_table_schema($table_name);

    // calling handlers for each type found
    foreach($this-&amp;gt;cache[$table_name] as $column =&amp;gt; $type) {
      $property = strtolower($column);
      if(IsSet($this-&amp;gt;handlers[$type]) &amp;amp;&amp;amp; IsSet($entry-&amp;gt;$property)) {
        $entry-&amp;gt;$property = $this-&amp;gt;handlers[$type]-&amp;gt;map($entry-&amp;gt;$property);
      }
    }
  }

  private function load_table_schema($table_name) {

    $table_name = strtoupper($table_name); // oracle uses upper case.

    $sql = &amp;quot;
      SELECT COLUMN_NAME, DATA_TYPE 
      FROM USER_TAB_COLUMNS
      WHERE TABLE_NAME='$table_name'&amp;quot;;

    $stmt = oci_parse($this-&amp;gt;conn,$sql);

    if (!$stmt) {
      $e = oci_error($this-&amp;gt;conn);
      throw new Exception($e['message']);
    }

    $r = oci_execute($stmt, OCI_DEFAULT);

    if (!$r) {
      $e = oci_error($stmt);
      throw new Exception($e['message']);
    }

    while($row = oci_fetch_array($stmt)) {
      $this-&amp;gt;cache[$table_name][$row['COLUMN_NAME']] = $row['DATA_TYPE'];
      $datatypes[$row['DATA_TYPE']] = true;
    }

    // load handlers for types found
    foreach(array_keys($datatypes) as $type) {
      $class_name = 'Map_'.$type;
      if(!IsSet($this-&amp;gt;handlers[$type])) {
        if(class_exists($class_name)) {
          $this-&amp;gt;handlers[$type] = new $class_name();
        }
        else {
          $this-&amp;gt;handlers[$type] = new Map_GENERIC();
        }
      }
    }
  }

}

// Type mappers. Estas classes formatam os dados
// corretamente para o banco de dados conforme o esquema
// exportado pela tabela em user_tab_columns no ORACLE.
// Ex. uma data do tipo 10/02/2008 ser&#225; formatada pelo 
// mapper Map_DATE para to_date('10/02/2008' 'dd/mm/yyyy')
interface TypeMapper {
  static function map($field);
  //static function unmap($field);
}

class Map_GENERIC implements TypeMapper {
  public static function map($field) {
    return $field;
  }
}

class Map_DATE extends Map_GENERIC implements TypeMapper {
  public static function map($field) {
    if($field == '') return;

    if(preg_match('/^(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})$/', $field, $m)) {
      return &amp;quot;TO_DATE('$m[1]','dd/mm/yyyy hh24:mi:ss')&amp;quot;;
    }
    elseif(preg_match('/^(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2})$/', $field, $m)) {
      return &amp;quot;TO_DATE('$m[1]','dd/mm/yyyy hh24:mi')&amp;quot;;
    }
    elseif(preg_match('/^(\d{2}\/\d{2}\/\d{4} \d{2})$/', $field, $m)) {
      return &amp;quot;TO_DATE('$m[1]','dd/mm/yyyy hh24')&amp;quot;;
    }
    elseif(preg_match('/^(\d{2}\/\d{2}\/\d{4})$/', $field, $m)) {
      return &amp;quot;TO_DATE('$m[1]','dd/mm/yyyy')&amp;quot;;
    }
    elseif(preg_match('/^(\d{2}\/\d{2}\/\d{2})$/', $field, $m)) {
      return &amp;quot;TO_DATE('$m[1]','dd/mm/yy')&amp;quot;;
    }
    elseif(preg_match('/^(\d{10})$/', $field, $m)) { // epoch time
      return &amp;quot;(TO_DATE('19700101','YYYYMMDD')+ $field/86400)&amp;quot;;
    }
    else {
      throw new Exception(&amp;quot;Don&#180;t know how to convert ($field) to date for ORACLE.&amp;quot;);
    }
  }
}

class Map_VARCHAR2 extends Map_GENERIC implements TypeMapper {
  public static function map($field) {
    $field = preg_replace(&amp;quot;/'/&amp;quot;,&amp;quot;\'&amp;quot;,$field); // escape '
    return &amp;quot;'$field'&amp;quot;;
  }
}

?&amp;gt;

## Sample of a insert [php]

&amp;lt;?php

// $config_date, $serial_number and etc were previous given...

$t_conf   = TableFactory::getTable('single_conf');

$new_config_id = $t_conf-&amp;gt;next_seq_value();

$new_entry = $t_conf-&amp;gt;new_entry();

$new_entry-&amp;gt;config_id                 = $new_config_id;
$new_entry-&amp;gt;date                      = $config_date;
$new_entry-&amp;gt;enable                    = 1;
$new_entry-&amp;gt;serialnumber              = $serial_number;
$new_entry-&amp;gt;username                  = $username;
$new_entry-&amp;gt;source                    = $source;

$t_conf-&amp;gt;insert($new_entry);


?&amp;gt;

&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/400-object-with-field-names-as-resources/refactors/14025" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor13443</id>
    <published>2008-07-21T05:59:01+00:00</published>
    <title>[Perl] On MAC Formatting</title>
    <content type="html">&lt;p&gt;I think there's a million ways to this, I think a simple call will keep the code smaller. The trick here is, first the 'g' flag turns the match operation a kind a loop, if put it in a while will work too. The join function catches all matches and glue with ':' and the group (?:0x) will take care on avoiding match the prefix '0x'.
&lt;br /&gt;Hope this helps.&lt;/p&gt;

&lt;pre&gt;## refact [perl]
#!/usr/bin/perl
use strict;
use warnings;

# sample snmp return
my $mac_address = '0x001617479a5e';

print qq{Original MAC Address: $mac_address\n};

$mac_address = join(':',($mac_address =~ m/(?:0x)?(\w{2})/g));

print qq{Reformatted MAC Address: $mac_address\n};
&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/390-mac-formatting/refactors/13443" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor12056</id>
    <published>2008-06-28T04:13:05+00:00</published>
    <title>[Bash] On kill nginx master proces</title>
    <content type="html">&lt;p&gt;In Linux check the &amp;quot;pkill&amp;quot; command.&lt;/p&gt;

&lt;pre&gt;## [bash]

pkill &amp;quot;nginx: master&amp;quot;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/338-kill-nginx-master-proces/refactors/12056" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor4154</id>
    <published>2008-03-19T16:54:46+00:00</published>
    <title>[Perl] On Hello world!</title>
    <content type="html">&lt;p&gt;A simple one, don&#180;t know if is more obscure but certainly fun.&lt;/p&gt;

&lt;pre&gt;perl -e &amp;quot;$_='doHole klrWlg';$_.=$1,print$2while s/(..)(.)//;&amp;quot;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/262-hello-world/refactors/4154" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor4093</id>
    <published>2008-03-18T04:01:59+00:00</published>
    <title>[Perl] On Example of Net::Ping</title>
    <content type="html">&lt;p&gt;I think there's not much to say about this code, I've just changed the (&amp;quot;) to (') in the ICMP because you don't need to interpolate a variable there, and made the call directly using a chain call. &lt;/p&gt;

&lt;pre&gt;#!/usr/bin/perl -w

# This scrit use the Net::Ping Module to ping an 
# host (value of $ARGV[0]). The protocol is icmp,
# timeout is 5 seconds, and bytes sent are 256. 
#
# Example:
#
# [root@localhost scripts]# perl ping.pl google.com
# google.com up

use Net::Ping;

if(Net::Ping-&amp;gt;new('icmp', 5, 256)-&amp;gt;ping($ARGV[0])) {
        print &amp;quot;$ARGV[0] up\n&amp;quot;;
}
else {
        print &amp;quot;$ARGV[0] down\n&amp;quot;;
}&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/258-example-of-net-ping/refactors/4093" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor1741</id>
    <published>2008-01-25T00:30:53+00:00</published>
    <title>[Java] On clean up nested loops?</title>
    <content type="html">&lt;p&gt;I think you can remove the nested loop doing a sort before find the duplicates, then going in one step using a Set data structure to keep the duplicates. &lt;/p&gt;

&lt;p&gt;The gain is that the Set structure will take care of future duplicates and you avoid the double trip in the Array. This assuming you can sort your items.&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;## sort before [java]

java.util.Arrays.sort(cArray);

for(int i = 0; i &amp;lt; cArray.length - 1; i++) {
	if(cArray[i].equals(cArray[i + 1])) {
		dupes.add(cArray[i]);
	}
}&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/215-clean-up-nested-loops/refactors/1741" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor817</id>
    <published>2007-11-10T15:01:03+00:00</published>
    <title>[Java] On Incompatible Types</title>
    <content type="html">&lt;p&gt;Hi, here some explanation of what was going on in your code.&lt;/p&gt;

&lt;p&gt;In line 15: 
&lt;br /&gt;When you have a local variable with the same name of a instance variable you should tell the java compiler what is what. In fact is a good practice always refer to instance variables with &amp;quot;this.variableName&amp;quot;.&lt;/p&gt;

&lt;p&gt;In line 38:
&lt;br /&gt;That's is a incompatible type, you begin a String array and try to put one double inside. Remember that your &amp;quot;values&amp;quot; instance variable is of double type, so the &amp;quot;tmp&amp;quot; variable should be a double too.&lt;/p&gt;

&lt;p&gt;In line 40:
&lt;br /&gt;Two problems here, first is that you should return a String not a Range object, remember the your method declaration:
&lt;br /&gt;   public String reverseString()&lt;/p&gt;

&lt;p&gt;The second problem is that you try to construct a Range object with your &amp;quot;tmp&amp;quot; variable (of String[] type before refactoring), but your Range should be constructed only with integers, javac will complain about this too.&lt;/p&gt;

&lt;p&gt;Hope this helps.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/147-incompatible-types/refactors/817" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor815</id>
    <published>2007-11-10T02:20:17+00:00</published>
    <title>[Java] On Cannot Ref from Static Content</title>
    <content type="html">&lt;p&gt;Mark,
&lt;br /&gt; I see you are beginning in the Java World, welcome. For this particular issue you can read this short article (&lt;a href="http://www.leepoint.net/notes-java/flow/methods/50static-methods.html" target="_blank"&gt;http://www.leepoint.net/notes-java/flow/methods/50static-methods.html&lt;/a&gt;) about static and non-static methods, this site has a lot information you can use.&lt;/p&gt;

&lt;p&gt; Hope this helps.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/145-cannot-ref-from-static-content/refactors/815" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor738</id>
    <published>2007-11-05T16:09:23+00:00</published>
    <title>[Java] On Equals Method</title>
    <content type="html">&lt;p&gt;Wheres the hashCode() implementation? &lt;/p&gt;

&lt;p&gt;Here is a complete description of what you need to know about equals() and hashCode().&lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.geocities.com/technofundo/tech/java/equalhash.html" target="_blank"&gt;http://www.geocities.com/technofundo/tech/java/equalhash.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;and here is a old refactoring post about the subject of equals() and hashCode()&lt;/p&gt;

&lt;p&gt;&lt;a href="http://refactormycode.com/codes/27-sample-java-program#refactor_160" target="_blank"&gt;http://refactormycode.com/codes/27-sample-java-program#refactor_160&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hope this help.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/135-equals-method/refactors/738" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor729</id>
    <published>2007-11-05T11:58:21+00:00</published>
    <title>[Java] On Errors With Exception</title>
    <content type="html">&lt;p&gt;Here is my corrections they are identified in the code. &lt;/p&gt;

&lt;p&gt;You got your contructor argument wrong, the lenght of a array should be tested with a &amp;quot;&amp;lt;&amp;quot; not a &amp;quot;&amp;lt;=&amp;quot; since arrays in java start at zero, but the length have the size. So a array as &amp;quot;new String[10]&amp;quot; will have 10 elements starting at 0 to 9, That was your first ArrayOutOfBoundsException.&lt;/p&gt;

&lt;p&gt;The park() method tested with a &amp;quot;&amp;gt;&amp;quot;, but should be &amp;quot;&amp;lt;&amp;quot; for the same reason as above.&lt;/p&gt;

&lt;p&gt;And finally &amp;quot;numCars&amp;quot; should be incremented with &amp;quot;numCars++&amp;quot;, because integers has a default of &amp;quot;0&amp;quot;, so you want park the car then increment, not increment then park the car.&lt;/p&gt;

&lt;p&gt;Hope this helps.
&lt;/p&gt;

&lt;pre&gt;## Parks [java]

public class Parks {
    private String[] parkingBays;
    private int numCars;

    public Parks(int capacity) {
        parkingBays = new String[capacity]; // changed &amp;quot;numCars&amp;quot; to &amp;quot;capacity&amp;quot;

        for (int i = 0; i &amp;lt; parkingBays.length; i++) { // changed &amp;quot;&amp;lt;=&amp;quot; to &amp;quot;&amp;lt;&amp;quot;
            parkingBays[i] = &amp;quot;Empty&amp;quot;;
        }
    }
    public boolean park(String car) {
        
        if (numCars &amp;lt; parkingBays.length){ // changed &amp;quot;&amp;gt;&amp;quot; to &amp;quot;&amp;lt;&amp;quot;
            parkingBays[numCars++] = car; // changed &amp;quot;++numCars&amp;quot; to &amp;quot;numCars++&amp;quot;
        }
        else {
            return false;
        }
        return true;
    }


    /**
     * For Testing
     */
    public static void main(String [] args) {
        Parks p = new Parks(20);
        boolean spaces = true;
        while (spaces) {
            spaces = p.park(&amp;quot;car1&amp;quot;);
            spaces = p.park(&amp;quot;car2&amp;quot;);
        }
        for (String car : p.parkingBays)
            System.out.println(car);
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/134-errors-with-exception/refactors/729" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor644</id>
    <published>2007-10-30T05:20:03+00:00</published>
    <title>[PHP] On Robots Reader</title>
    <content type="html">&lt;p&gt;Hi, when I saw your code I thought that a class Robot could be useful, the nicest thing was that I found a Perl module (WWW::RobotRules) that do exactly what your code propose but in a OO way. &lt;/p&gt;

&lt;p&gt;What I did was translate the Perl module to PHP. You can tweak around to see if help on your problem.  I'm not a professional PHP programmer so maybe some specific optimization can be done.&lt;/p&gt;

&lt;p&gt;Some caveats: the regular expression engine PCRE does not allow repeat quantifiers on lookahead assertions. (see: &lt;a href="http://www.php.net/manual/en/reference.pcre.pattern.syntax.php" target="_blank"&gt;http://www.php.net/manual/en/reference.pcre.pattern.syntax.php&lt;/a&gt;) but in the original Perl module were some, actually one, I don't think will differ but keep it in mind (in the function useragent()). I've could not test this code enough so care should be taken.   &lt;/p&gt;

&lt;p&gt;As you probably will notice I didn't translated all functionality of the original module, there's no time keeping and one object WWW_Robot should e used for only one domain.&lt;/p&gt;

&lt;p&gt;Hope this helps.
&lt;/p&gt;

&lt;pre&gt;## WWW_Robot [php]
&amp;lt;?
class WWW_Robot {

  var $url;
  var $useragent = &amp;quot;*&amp;quot;;

  // array which we mark the disallowed paths
  var $rules = null;

   /* Should find and parse the robots file,
    * cache the result for -&amp;gt;allowed() subsequent calls.
    * If the file could not be found -&amp;gt;allowed() should
    * return TRUE for any call.
    */
  function parseURL($url_given) {

    // boolean flags...
    $is_me   = false;
    $is_anon = false;
    $me_disallowed   = null;
    $anon_disallowed = null;

    $this-&amp;gt;url = parse_url($url_given);

    $robot_file_data = $this-&amp;gt;retrieve_robot_file($this-&amp;gt;url);

    if(! isset($robot_file_data) ) { // robots.txt not exists

    }
    else { // robots.txt file exists

      foreach(explode(&amp;quot;\n&amp;quot;,$robot_file_data) as $line) {

        $line = preg_replace(&amp;quot;/\015$/&amp;quot;, &amp;quot;&amp;quot;, $line); // removing CRs if exists.

        if(preg_match(&amp;quot;/\s*\#/&amp;quot;, $line)) continue; // skipping comments.

        $line = preg_replace(&amp;quot;/\s*\#.*/&amp;quot;, &amp;quot;&amp;quot;, $line); // removing comments at end of a line.

        if(preg_match(&amp;quot;/^\s*$/&amp;quot;, $line)) {
          if($is_me) break;
          $is_anon = false;
        }
        elseif(preg_match(&amp;quot;/^User-Agent:\s*(.*)/i&amp;quot;, $line, $found)) {

          $ua = preg_replace(&amp;quot;/\s+$/&amp;quot;, &amp;quot;&amp;quot;, $found[1]); // removing tralling space.

          if($is_me) {
          }
          elseif( $ua == '*' ) {
            $is_anon = true;
          }
          elseif($this-&amp;gt;match_with_me($ua)) {
            $is_me = true;
          }

        }
        elseif(preg_match(&amp;quot;/^Disallow:\s*(.*)/i&amp;quot;, $line, $found)) {

          if(!isset($ua)) $is_anon = true; // disalow w/o previous UA, assuming *

          $disallow = strtolower(preg_replace(&amp;quot;/\s+$/&amp;quot;, &amp;quot;&amp;quot;, $found[1]));


          if($is_me) {
            $me_disallowed[]   = $disallow;
          }
          elseif($is_anon) {
            $anon_disallowed[] = $disallow;
          }

        }
        else {
          /* Google, and probably others, uses a Allow in robots.txt, this is probably a extenssion
           * of the robots.txt syntax, we do not support these. 
           * If want to to see warnings about these lines uncomment the
           * code below.
           */
          
          //trigger_error(&amp;quot;Strange line in robots file: $line&amp;quot;, E_USER_WARNING);
        }

      }// end foreach()

      if($is_me) {
        $this-&amp;gt;rules = $me_disallowed;
      }
      else {
        $this-&amp;gt;rules = $anon_disallowed;
      }

    }// end else robots.txt file exsits.
  }// end parseURL()

  function match_with_me($ua) {
    if(strtolower($this-&amp;gt;useragent) == strtolower($ua)) {
      return true;
    }
    else {
      return false;
    }
  }

  function retrieve_robot_file($from_url) {

    $robot_file = @file_get_contents($from_url['scheme'].'://'.$from_url['host'].'/robots.txt');

    return $robot_file;
  }


  /*
   * This method returns true if our agent has permission
   * to enter (crawl) the PATH argument. 
   */
  function allowed($path) {

    if(!isset($this-&amp;gt;rules)) return true;

    foreach($this-&amp;gt;rules as $rule) {

      $strcmp_result = strcmp($rule, strtolower($path));

      $pos;

      if($strcmp_result == 0) {
        return false; // we have a match
      }
      elseif($strcmp_result &amp;lt; 0) {
        $pos = strpos($path, $rule, 0);
      }
      else {
        $pos = strpos($rule, $path, 0);
      }

      if($pos === 0) return false;
    }

    return true; // if we could not find a rule to disallow
  }


  // get/set for useragent...
  function useragent($ua = null) {

    if(isset($ua)) {
      $this-&amp;gt;me_disallowed   = null; // cleaning data
      $this-&amp;gt;anon_disallowed = null; // cleaning data
      $this-&amp;gt;useragent = preg_replace(&amp;quot;!/\s*\d+.\d+\s*$!&amp;quot;, &amp;quot;&amp;quot;, $ua); // original re: s!/?\s*\d+.\d+\s*$!!
    }

    return $this-&amp;gt;useragent; // to inform our current useragent.
  }

} //end class
?&amp;gt;


## test code [php]

&amp;lt;?

   // test code...
  $robot = new WWW_Robot;
  $robot-&amp;gt;useragent(&amp;quot;Some UserAgent&amp;quot;);
  $robot-&amp;gt;parseURL(&amp;quot;http://www.google.com.br&amp;quot;);

  // can we crawl this dir in google?
  echo  &amp;quot;-&amp;gt;&amp;quot;.$robot-&amp;gt;allowed(&amp;quot;/defauts/&amp;quot;).&amp;quot;&amp;lt;-\n&amp;quot;;

  // can we crawl this dir in google?
  echo  &amp;quot;-&amp;gt;&amp;quot;.$robot-&amp;gt;allowed(&amp;quot;/trends/&amp;quot;).&amp;quot;&amp;lt;-\n&amp;quot;;

?&amp;gt;
&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/116-robots-reader/refactors/644" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor553</id>
    <published>2007-10-26T13:47:22+00:00</published>
    <title>[Java] On Detect neighboring pixels</title>
    <content type="html">&lt;p&gt;I&#180;m behind a very nasty firewall/network and I&#180;ve made a mistake on the above code, missed &amp;quot;thisY + 1&amp;quot; inside the second for. Since I can&#180;t edit it I will paste here the same code corrected.&lt;/p&gt;

&lt;pre&gt;// See above code, already fixed.&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/110-detect-neighboring-pixels/refactors/553" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor550</id>
    <published>2007-10-26T13:19:26+00:00</published>
    <title>[Java] On Detect neighboring pixels</title>
    <content type="html">&lt;p&gt;Here's a simple way. Note that if you ever want to get the 24 neighbors you just need to use &amp;quot;2&amp;quot; where I&#180;m using &amp;quot;1&amp;quot; and expand the array.&lt;/p&gt;

&lt;pre&gt;## neighbors [java]

/** 
  * This is a method which will gather the pixels
  * of the 8 pixels surrounding a given pixel
  * @param thisX is the x of the pixel in case
  * @param thisY is the y of the pixel in case
  */
   
  
  public Pixel[] getNeighbors(int thisX, int thisY)
  {
     Pixel[] pixels = new Pixel[8];

     int index = 0;

     for(int i = thisX - 1; i &amp;lt;= thisX + 1; i++) 
     {
       for(int j = thisY - 1; j &amp;lt;= thisY + 1; j++) 
       {
         if(i == thisX &amp;amp;&amp;amp; j == thisY) continue;
           pixels[index] = getPixel(i,j);
           index++;
       }
     }

     return pixels;
  }&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/110-detect-neighboring-pixels/refactors/550" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor525</id>
    <published>2007-10-24T02:45:19+00:00</published>
    <title>[Ruby] On Getting QWERTY misstypes</title>
    <content type="html">&lt;p&gt;Hi, I don't how to write a Ruby solution but you can have some idea looking at this Perl module.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://search.cpan.org/~krburton/String-KeyboardDistance-1.01/KeyboardDistance.pm" target="_blank"&gt;http://search.cpan.org/~krburton/String-KeyboardDistance-1.01/KeyboardDistance.pm&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/100-getting-qwerty-misstypes/refactors/525" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor443</id>
    <published>2007-10-16T23:31:06+00:00</published>
    <title>[Java] On Email addresses validator</title>
    <content type="html">&lt;p&gt;matrixise, this is more a design choice, theres no performance impact, at least with 15000 emails, in a test a made here. As I don't know if EmailValidator class will have another methods I prefer stay in non-static territory. If you are positive that EmailValidator will be something like a util class( see Effective Java by Joshua Bloch) you can declare isValid() as static.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/73-email-addresses-validator/refactors/443" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor390</id>
    <published>2007-10-12T02:34:21+00:00</published>
    <title>[Perl] On Cache::Cache subroutine with multiple variables returned</title>
    <content type="html">&lt;p&gt;Hi, I made some modifications in your code I believe will work, here some mock tests worked. The problem probably was how you tested how get() returned. I made some obs inside the code as well.&lt;/p&gt;

&lt;p&gt;Some tips:
&lt;br /&gt;  Avoid the * inside a SQL, you never know when someone will add a column and make your code fail.
&lt;br /&gt;  If you know that your SQL will return one and only one row (your code implies this condition) you can avoid the prepare and execute with
&lt;br /&gt;   selectcol_arrayref(), here is one example from my legacy code:&lt;/p&gt;

&lt;p&gt;        my($domain_id) = @{$self-&amp;gt;{dbh}-&amp;gt;selectcol_arrayref(&amp;quot;
&lt;br /&gt;              SELECT domain_id FROM domain_project
&lt;br /&gt;              WHERE project_id='$project_id'
&lt;br /&gt;         &amp;quot;)};&lt;/p&gt;

&lt;p&gt; Hope that helps.&lt;/p&gt;

&lt;pre&gt;## perl [perl]

 
# always use strict and warnings, this can solve hours of debuging!
use strict;
use warnings;

use Cache::FileCache;

# defined somewere else...
my $dbh;
my $t;

my $cache = new Cache::FileCache( );
# $cache-&amp;gt;clear(); # clear all cached information.`

# this subroutine works just fine
sub stockInfoFresh
{
	my ($tick) = @_; # this is a better way to get arguments
	
	$tick =~ tr/a-z/A-Z/; # to uppercase
	
	my $first_let = substr($tick,0,1);
	
	my $name = &amp;quot;Ticker not found&amp;quot;;
	my $exch = '';
	
    my $sth = $dbh-&amp;gt;prepare(&amp;quot;SELECT * FROM `Stock` WHERE `Ticker` = '$tick'&amp;quot;); $sth-&amp;gt;execute;
	
    # this implies that you will work with one and only one row.
    # if multiple rows this should be inside a while loop.
    my @stockid = $sth-&amp;gt;fetchrow_array;
	
	if ($stockid[0]) {
		$name = $stockid[1];
		$exch = $stockid[2];
	}

    $sth-&amp;gt;finish;
	
    # when returning a array try to avoid return a array as
    # ($one, $two, @three), this syntax can raise difficult bugs.
	return($tick, $first_let, $name, $exch, $stockid[0]);
}

# this subroutine fails
sub stockInfo
{
	my ($tick) = @_; # this is a better way to get a argument

    # get returns a array reference, you should get in a scalar
    # just to test if FileCache returned something    
	my $stockInfo = $cache-&amp;gt;get( &amp;quot;stockInfo&amp;quot; . $tick );

    # I will save the result in this array.
    my @stockInfo;

	if( not $stockInfo  )
	{
		@stockInfo = &amp;amp;stockInfoFresh($tick);
		
		$cache-&amp;gt;set( &amp;quot;stockInfo&amp;quot; . $tick, \@stockInfo, &amp;quot;1 hour&amp;quot; );
	}
    else {
        # if FileCache returned something is a reference to an array
        # so now lets dereference it.
        @stockInfo = @{$stockInfo};
    }

	# at this point, $stockInfo[0] is empty

	return @stockInfo;
}


my($tick, $first_let, $name, $exch, $stockid) = &amp;amp;stockInfo($t);


print &amp;quot;$tick $first_let $name $exch $stockid\n&amp;quot;;
&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/76-cache-cache-subroutine-with-multiple-variables-returned/refactors/390" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor387</id>
    <published>2007-10-12T01:10:48+00:00</published>
    <title>[Java] On Email addresses validator</title>
    <content type="html">&lt;p&gt;Here my thoughts about your code. First I see you are using Java 5 so I will use the Scanner class. It's always very hard to validate emails address, in &amp;quot;Mastering Regular Expressions&amp;quot; Jeffrey Friedl shows 6.598 bytes long regexp (end of the book) to validate emails. &lt;/p&gt;

&lt;p&gt;So I prefer use one specialized class to check the email. In mail.jar in jboss distribution you find one class to handle this (javax.mail.internet.InternetAddress).&lt;/p&gt;

&lt;p&gt;The code bellow works, but I do not trim empty spaces and etc since I don't your real input format.&lt;/p&gt;

&lt;pre&gt;## EmailCheck [java]


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

public class ValidatorRefact {

	private static final String ORIG_FILE = &amp;quot;org.txt&amp;quot;;
	private static final String NEW_FILE  = &amp;quot;new.txt&amp;quot;;
	
	
	public static void main(String[] args) throws IOException {
		
		// a keep email list...
		List&amp;lt;String&amp;gt; origEmails = new LinkedList&amp;lt;String&amp;gt;();

		
		// buffering original file
		Scanner origScan = new Scanner(new File(ORIG_FILE));

		while(origScan.hasNextLine()) {
			origEmails.add(origScan.nextLine());
		}
		origScan.close();
		
		// our cleaned file
		FileWriter newFile = new FileWriter(new File(NEW_FILE));
		
		// this class is our email check helper.
		EmailValidatorRefact emailCheck = new EmailValidatorRefact();
		
		// the output loop, only valid emails are written
		for(String email : origEmails ) {
			if(emailCheck.isValid(email)) {
				newFile.write(email + &amp;quot;\n&amp;quot;);
			} 
		}
	
		newFile.close();

	}

}

class EmailValidatorRefact {
	
	public boolean isValid(String email) {
		
		if(email == null) return false;
		
		try {
			new InternetAddress(email,true);
		} catch (AddressException e) {
			return false;
		}
		
		return true;	
	}
}
&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/73-email-addresses-validator/refactors/387" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor358</id>
    <published>2007-10-10T05:00:58+00:00</published>
    <title>[Bash] On Open a new tab in current directory from iTerm</title>
    <content type="html">&lt;p&gt;Macournoyer, I tried your function and it opens the server on my window then launches me to another tab. I prefer stay in my tab and launch the process in another tab. After some digging I came up with the code bellow, the difference in the command call is that you don't need use the &amp;quot;;&amp;quot;.&lt;/p&gt;

&lt;p&gt;So, what was: tab; script/server
&lt;br /&gt;Now should be: tab script/server&lt;/p&gt;

&lt;p&gt;The only thing I could not solve is that iTerm changes the tab on a launch, so I had to bring it back with a &amp;quot;select session&amp;quot; call.&lt;/p&gt;

&lt;pre&gt;## [bash]

tab()
{
        osascript -e &amp;quot;
        tell application \&amp;quot;iTerm\&amp;quot;
         tell the first terminal
          set currentSession to current session
          launch session \&amp;quot;Default Session\&amp;quot;
          tell the last session
           write text \&amp;quot;cd $(pwd)\&amp;quot;
           write text \&amp;quot;$*\&amp;quot;
          end tell
          select currentSession
         end tell
        end tell&amp;quot;
}&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/63-open-a-new-tab-in-current-directory-from-iterm/refactors/358" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor312</id>
    <published>2007-10-06T15:40:51+00:00</published>
    <title>[Java] On Hello World</title>
    <content type="html">&lt;p&gt;Ok, your HelloWorld is not problematic and not need a refactoring, but just for fun you can avoid call the main method.&lt;/p&gt;

&lt;pre&gt;## HelloWorld [java]


public class HelloWorld {
    static {
        System.out.println(&amp;quot;Hello World&amp;quot;);
        System.exit(0);
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/66-hello-world/refactors/312" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor225</id>
    <published>2007-10-02T21:49:08+00:00</published>
    <title>[Java] On Fastest way to sort doubles and their key - like in an array - in descending order</title>
    <content type="html">&lt;p&gt;I forgot to paste the Quicksort here is.&lt;/p&gt;

&lt;pre&gt;## Quicksort (Java)

/* Copyright (c) 2007 the authors listed at the following URL, and/or
the authors of referenced articles or incorporated external code:
http://en.literateprograms.org/Quicksort_(Java)?action=history&amp;amp;offset=20061122163828

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
&amp;quot;Software&amp;quot;), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED &amp;quot;AS IS&amp;quot;, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Retrieved from: http://en.literateprograms.org/Quicksort_(Java)?oldid=8141
*/




public class Quicksort {
	
	static &amp;lt;T extends Comparable&amp;lt;? super T&amp;gt;&amp;gt; void quicksort(T[] array)
 {
		
		quicksort(array, 0, array.length - 1);

	}
	
	static &amp;lt;T extends Comparable&amp;lt;? super T&amp;gt;&amp;gt; void quicksort(T[] array, int left0, int right0)
 {
		
		int left, right;
		T pivot, temp;
		left = left0;
		right = right0 + 1;

		
		pivot = array[left0];

		
		do {
			
			do left++; while (left &amp;lt; array.length &amp;amp;&amp;amp; array[left].compareTo(pivot) &amp;lt; 0);

			
			do right--; while (array[right].compareTo(pivot) &amp;gt; 0);

			
			if (left &amp;lt; right) {
				temp = array[left];
				array[left] = array[right];
				array[right] = temp;
			}

		}
		while (left &amp;lt;= right);
 
		
		temp = array[left0];
		array[left0] = array[right];
		array[right] = temp;

		
		if (left0 &amp;lt; right) quicksort(array, left0, right);
		if (left &amp;lt; right0) quicksort(array, left, right0);

	}
	
}

&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/43-fastest-way-to-sort-doubles-and-their-key-like-in-an-array-in-descending-order/refactors/225" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor224</id>
    <published>2007-10-02T21:45:43+00:00</published>
    <title>[Java] On Fastest way to sort doubles and their key - like in an array - in descending order</title>
    <content type="html">&lt;p&gt;Well, first of all I'm not an expert in sort algorithms. What I did was use a Quicksort to verify if the sorting time improves and seems that worked.&lt;/p&gt;

&lt;p&gt;Let's talk about the code bellow. Arrays.sort() uses a modified version of Mergesort, checking Wikipedia ( &lt;a href="http://en.wikipedia.org/wiki/Sorting_algorithm#List_of_sorting_algorithms" target="_blank"&gt;http://en.wikipedia.org/wiki/Sorting_algorithm#List_of_sorting_algorithms&lt;/a&gt; ) you will see that Mergesort is a pretty good algorithm, but since Quicksort is very popular I've tested it in your code. &lt;/p&gt;

&lt;p&gt;The Quicksort implementation I've tested was found in ( &lt;a href="http://en.literateprograms.org/Quicksort_" target="_blank"&gt;http://en.literateprograms.org/Quicksort_&lt;/a&gt;(Java) ) and this code accept objects that implement a Comparable interface, so your code should work. &lt;/p&gt;

&lt;p&gt;I had to change your compareTo() method to keep right the spec in Comparable interface. If you want a reverse sort you can revert the walk in the &amp;quot;for&amp;quot;. StackOverflows can happen, and happened in this case, if your compareTo() break the spec of Comparable interface.&lt;/p&gt;

&lt;p&gt;For a loop of 10000000 sorts, Arrays.sort() takes about 12 seconds and Quicksort about 10 seconds in my machine. The code used to test is bellow too so you can test in your machine as well.&lt;/p&gt;

&lt;pre&gt;## Relation [java]

import java.util.Arrays;

class Relation implements Comparable&amp;lt;Relation&amp;gt; {

  public Relation(double array_value, int array_index) {
    this.array_value = array_value;
    this.array_index = array_index;
  }

  public double getValue() {
    return array_value;
  }

  public int getIndex() {
    return array_index;
  }

  //*** We need descending order
  public int compareTo(Relation relation) {

    double cmp_to = ((Relation) relation).array_value;
    double my_val = array_value;
 
    if (my_val &amp;gt; cmp_to) {
			return 1;
    } else if(my_val &amp;lt; cmp_to) {
			return -1;
    } else {
			return 0;
	}

  }
  
  private double array_value;
  private int array_index;
  
}


## SortWithIndexRefact [java]

public class SortWithIndexRefact {
  
  public static void main(String[] args) {

    
    //*** Some test data: 9 values and 9 keys will form 9 pairs...
    int keys[] = { 
			14, 12, 42, 56, 36, 61, 78, 83, 93 
	};
    double values[] = { 
			48.2d, 103.6d, 4.3d, 4.8d, 99.0d, 1.2d, 4.8d, 48.2d, 4.8d 
	};

    
    //*** A new array that will hold all the pairs
    Relation[] all_relations = new Relation[keys.length];    


    //*** Keys and Values in a new relation object are grouped and stored in the all_relations array    
    for (int i = 0, n = keys.length; i &amp;lt; n; i++) {
      all_relations[i] = new Relation(values[i], keys[i]);
    }


    //*** Display the pairs before sorting them
    System.out.println(&amp;quot;\nORIGINAL:\n------------&amp;quot;);
    for (Relation relation : all_relations) {
      System.out.println(relation.getValue() +&amp;quot; =&amp;gt; &amp;quot;+ relation.getIndex());
    }


    //*** Sort the array
 


     // This is the test, a recurrent loop of the same sort
	Relation[] relation_temp = new Relation[all_relations.length];

	for(int i = 0; i &amp;lt;= 10000000; i++) {
          relation_temp = all_relations.clone();

          // change the comment to test different algorithms
          
          //Arrays.sort(relation_temp);
          Quicksort.quicksort(relation_temp);
	}


    //*** Display the pairs after sorting them    
    System.out.println(&amp;quot;\nSORTED:\n------------&amp;quot;);
    for (Relation relation : relation_temp) {
      System.out.println(relation.getValue() +&amp;quot; =&amp;gt; &amp;quot;+ relation.getIndex());
    }
  }
}

## Quicksort [java]
&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/43-fastest-way-to-sort-doubles-and-their-key-like-in-an-array-in-descending-order/refactors/224" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor197</id>
    <published>2007-10-02T06:41:39+00:00</published>
    <title>[Java] On Fastest way to sort doubles and their key - like in an array - in descending order</title>
    <content type="html">&lt;p&gt;There&#194;&#180;s a reason to not use a TreeMap? (&lt;a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html" target="_blank"&gt;http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html&lt;/a&gt;)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/43-fastest-way-to-sort-doubles-and-their-key-like-in-an-array-in-descending-order/refactors/197" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor177</id>
    <published>2007-10-01T18:16:07+00:00</published>
    <title>[Java] On Parse a Calendar object from a user-provided String</title>
    <content type="html">&lt;p&gt;I've tried your code and my refact just simplifies the input handling as you asked.&lt;/p&gt;

&lt;pre&gt;## code [java]

import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * Parse a format string into a Calendar object.
 * For concreteness, use ISO-8601 format only
 * For simplicity, date only, no time
 */
public class pcal {
  /**
   * Create a Calendar instance from ISO 8601 String, timezone
   * @param cal describes the date 
   * @param tz which timezone for this instance
   * @return a Calendar if possible, else null
   */
  public static Calendar parse(String cal, TimeZone tz) {
    Calendar ret = Calendar.getInstance(tz);
    SimpleDateFormat df = new SimpleDateFormat(&amp;quot;yyyy-MM-dd&amp;quot;);
    try {
	  ret.setTime(df.parse(cal));
	  ret.set(Calendar.HOUR_OF_DAY,0);
	  ret.set(Calendar.MINUTE,0);
	  ret.set(Calendar.SECOND,0);
      // get here and we know the format is correct
    } catch (ParseException e) {
      // ignore the parse failure
	  return null;
    }
    return ret;
  }
  public static void main(String[] a)  {
    TimeZone tz = TimeZone.getTimeZone(&amp;quot;America/Los_Angeles&amp;quot;);
    for(String s : a) {
      Calendar c = parse(s,tz);
      if(null == c) {
        System.out.println(s+&amp;quot; -&amp;gt; &amp;quot;+c);
      } else {
        System.out.println(s+&amp;quot; -&amp;gt; &amp;quot;+c.getTime());
      }
    }
  }
}

&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/41-parse-a-calendar-object-from-a-user-provided-string/refactors/177" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor160</id>
    <published>2007-10-01T11:19:47+00:00</published>
    <title>[Java] On sample java program</title>
    <content type="html">&lt;p&gt;Some observations, for anyone who is trying to implement equals() should read: &lt;a href="http://www.geocities.com/technofundo/tech/java/equalhash.html" target="_blank"&gt;http://www.geocities.com/technofundo/tech/java/equalhash.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Simon Hutchinson (refactoring above) provides the right way to implement a equals(). I disagree with people that inserted jakarta commons in the code because this has consequences in whole software, adding dependences increase complexity, load, size and in this special case is unnecessary. In fact in a refactoring process will be more practical only rewrite the code. &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/27-sample-java-program/refactors/160" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:refactormycode.com,2007:Refactor136</id>
    <published>2007-09-30T12:52:52+00:00</published>
    <title>[Perl] On Random sentence generator</title>
    <content type="html">&lt;p&gt;As Relipuj I didn't know what is the specs you want. I've just made your code work cause your regular expression had a little problem. &lt;/p&gt;

&lt;p&gt;My fix just fill up the &amp;quot;@matches&amp;quot; array with the words returned by google. First I remove &amp;quot;[&amp;quot;,&amp;quot;]&amp;quot; and &amp;quot;, then I split the line by &amp;quot;,&amp;quot;. This a simple fix and is not a refactor, since refactor implies a working code to begin with.&lt;/p&gt;

&lt;pre&gt;## code [perl]

#!/usr/bin/perl
use LWP::Simple;
$url = &amp;quot;http://suggestqueries.google.com/complete/search?output=firefox&amp;amp;qu=&amp;quot;;
$word = $ARGV[0];
for (1..25) {
    $content = get($url . $word);
    $content =~ s/[\[|\]|&amp;quot;]//g;
    @matches = split(/,/,$content); 
    last if not @matches;
    $x = int(rand(@matches / 2));
    $line .= $matches[2 * $x];
    $word = $matches[2 * $x + 1];
}
print $line . &amp;quot;\n&amp;quot;;&lt;/pre&gt;</content>
    <author>
      <name>Marco Valtas</name>
      <email>mavcunha.gravatar@mailnull.com</email>
    </author>
    <link type="text/html" href="http://refactormycode.com/codes/24-random-sentence-generator/refactors/136" rel="alternate"/>
  </entry>
</feed>
