<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: Joeldg's Code Snippets</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 06 Sep 2008 13:17:59 GMT</pubDate>
    <description>DZone Snippets: Joeldg's Code Snippets</description>
    <item>
      <title>weighted distribution functions</title>
      <link>http://snippets.dzone.com/posts/show/3321</link>
      <description>I had to write a scheduler once upon a time and this was what I ended up using to do the schedule for users.. days had different weights, and certain users were management and others not (management didn't want to be scheduled on weekends.. go figure)..&lt;br /&gt;&lt;br /&gt;works well, and I am pretty sure that five years later this function is still getting a lot of use.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;?&lt;br /&gt;# users "user"=&gt;weight, "user"=&gt;weight ...&lt;br /&gt;$users = array("manager"=&gt;1,"peon"=&gt;4, "middlemngr"=&gt;3, "sales"=&gt;3, "other peon"=&gt;4);&lt;br /&gt;asort($users);&lt;br /&gt;&lt;br /&gt;############################################################################################################&lt;br /&gt;function distrib($arr){&lt;br /&gt;    $weight_total = array_sum($arr);&lt;br /&gt;    $vals = array_values($arr);&lt;br /&gt;    &lt;br /&gt;    // loop through and figure out the percentage for each user.&lt;br /&gt;    while ( list($key, $val) = each($arr) ){&lt;br /&gt;       $curr = $val;&lt;br /&gt;       //$percent =  (($curr * 100) / $total); // percentage of highest..&lt;br /&gt;       $percent =  (($curr / $weight_total) * 100); // this is for % of sum(total)&lt;br /&gt;       $percent_int = floor($percent);&lt;br /&gt;           $percent_float = number_format($percent, 1);    &lt;br /&gt;       &lt;br /&gt;       // now set up our return array.. "user"=&gt;percentage, "user"=&gt;percentage ...&lt;br /&gt;       $ret[$key] = $percent_float;&lt;br /&gt;    }//wend&lt;br /&gt;  // send it back&lt;br /&gt;  return $ret;&lt;br /&gt;}// end function&lt;br /&gt;&lt;br /&gt;############################################################################################################&lt;br /&gt;// this function spits back a placement for a user..&lt;br /&gt;// theoretically this should have an even distribution based on our distribution list.&lt;br /&gt;// dist_arr = output from distrib()&lt;br /&gt;function determine_placement($dist_arr, $rndval=""){&lt;br /&gt;    if ($rndval == "") { $rndval = mt_rand(0,100); } //set a rnd val&lt;br /&gt;    $running = 0; // private $running default&lt;br /&gt;    while (list($key, $val) = each ($dist_arr)){&lt;br /&gt;        $running  = $val;&lt;br /&gt;        if ($rndval &lt; $running) {&lt;br /&gt;            return $key;&lt;br /&gt;        }&lt;br /&gt;    }//wend&lt;br /&gt;    return false;&lt;br /&gt;}//end function&lt;br /&gt;&lt;br /&gt;############################################################################################################&lt;br /&gt;// just to test the output&lt;br /&gt;function test_output($dist_arr){&lt;br /&gt;    while (list($key, $val) = each ($dist_arr)){&lt;br /&gt;        echo "&lt;td width=\"$val%\"&gt;$key  ($val%)&lt;/td&gt;\n";&lt;br /&gt;    }//wend&lt;br /&gt;}//end function&lt;br /&gt;&lt;br /&gt;$gen_distrib = distrib($users);&lt;br /&gt;?&gt;&lt;br /&gt;&lt;br /&gt;&lt;table width=1 border=1 cellpadding=0 cellspacing=0&gt;&lt;br /&gt;&lt;tr&gt;&lt;br /&gt;&lt;? test_output(distrib($placement)); ?&gt;&lt;br /&gt;&lt;/tr&gt;&lt;br /&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 18 Jan 2007 00:03:27 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3321</guid>
      <author>joeldg (joeldg)</author>
    </item>
    <item>
      <title>useful normalizing functions (php)</title>
      <link>http://snippets.dzone.com/posts/show/3320</link>
      <description>useful normalizing functions for transfer of data into a neural net safe array (0-1) or for fitting data for a graph etc..&lt;br /&gt;&lt;br /&gt;can also be used in reverse by using the array largest and least values.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;?&lt;br /&gt;function normalize($arr,$LO=0.01,$HI=0.99)&lt;br /&gt;{&lt;br /&gt;  $Min =  2147483647;&lt;br /&gt;  $Max = -2147483647;&lt;br /&gt;  for ($a=0; $a&lt;count($arr); $a++) {&lt;br /&gt;    $Min = min($Min, $arr[$a]);&lt;br /&gt;    $Max = max($Max, $arr[$a]);&lt;br /&gt;  }&lt;br /&gt;  $Mean = 0;&lt;br /&gt;  for ($a=0; $a&lt;count($arr); $a++) {&lt;br /&gt;    $div = $Max-$Min;&lt;br /&gt;    if($div == 0){$div = 1;}&lt;br /&gt;    $arr [$a] = (($arr[$a]-$Min) / ($div)) * ($HI-$LO)   $LO;&lt;br /&gt;    $Mean  = $arr[$a] / count($arr);&lt;br /&gt;  }&lt;br /&gt;  return $arr;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;    dual-way recursive greedy grabber..&lt;br /&gt;    begins at a position in an array and grabs all "in order" parts up and&lt;br /&gt;    down from that point and returns them preserving keys.&lt;br /&gt;*/&lt;br /&gt;function section_greedy($stack, $start=0, $stop=2){&lt;br /&gt;    $check2 = array_slice_key ($stack, $start-1, $stop);&lt;br /&gt;    if ($start &gt;= 0 &amp;&amp; $stop &lt;= count($stack) 1){ // limit recursion to bounds.&lt;br /&gt;    if (is_in_rorder_key($check2)){&lt;br /&gt;        $check =  $check2;&lt;br /&gt;        $begin = $start-1; $ending = $stop;        &lt;br /&gt;        $check3 = section_greedy($start-1, $stop 1); //recurse up&lt;br /&gt;        if(is_in_rorder_key($check3)){&lt;br /&gt;            $check = $check3;&lt;br /&gt;            $moremore = section_greedy($start, $stop 1); //recurse down&lt;br /&gt;            if(is_in_rorder_key($moremore)){&lt;br /&gt;                $check =  $moremore;&lt;br /&gt;                $begin = $start-2; $ending = $stop 2;&lt;br /&gt;            }//fi&lt;br /&gt;        }//fi&lt;br /&gt;    }else{&lt;br /&gt;        $check =  array_slice_key($stack, $start, $stop);&lt;br /&gt;        $begin = $start; $ending = $stop;&lt;br /&gt;    }//fi&lt;br /&gt;    }//fi&lt;br /&gt;    return $check;&lt;br /&gt;}//end function&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;returns an array of movements up/down and the change.&lt;br /&gt;Array(&lt;br /&gt;    [down] =&gt; 1178.36&lt;br /&gt;    [up] =&gt; 419.05&lt;br /&gt;    [change] =&gt; -759.31&lt;br /&gt;)&lt;br /&gt;*/&lt;br /&gt;function examine_movement($arr){&lt;br /&gt;    while(list($key,$val) = each($arr)){&lt;br /&gt;        if($oldval == ""){$oldval = $val;}&lt;br /&gt;        if($val &gt; $oldval){&lt;br /&gt;            $ret[up] += $val-$oldval;&lt;br /&gt;        }else{&lt;br /&gt;            $ret[down] += $oldval-$val;&lt;br /&gt;        }&lt;br /&gt;        $oldval = $val;        &lt;br /&gt;    }//wend&lt;br /&gt;    $ret[change] = $ret[up] - $ret[down];&lt;br /&gt;    return $ret;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;?&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 17 Jan 2007 23:53:22 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3320</guid>
      <author>joeldg (joeldg)</author>
    </item>
    <item>
      <title>Colorized text from php in unix terminals</title>
      <link>http://snippets.dzone.com/posts/show/3292</link>
      <description>Colorized text from php in unix terminals&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# first define colors to use&lt;br /&gt;$_colors = array(&lt;br /&gt;        LIGHT_RED      =&gt; "[1;31m",&lt;br /&gt;        LIGHT_GREEN     =&gt; "[1;32m",&lt;br /&gt;        YELLOW         =&gt; "[1;33m",&lt;br /&gt;        LIGHT_BLUE     =&gt; "[1;34m",&lt;br /&gt;        MAGENTA     =&gt; "[1;35m",&lt;br /&gt;        LIGHT_CYAN     =&gt; "[1;36m",&lt;br /&gt;        WHITE         =&gt; "[1;37m",&lt;br /&gt;        NORMAL         =&gt; "[0m",&lt;br /&gt;        BLACK         =&gt; "[0;30m",&lt;br /&gt;        RED         =&gt; "[0;31m",&lt;br /&gt;        GREEN         =&gt; "[0;32m",&lt;br /&gt;        BROWN         =&gt; "[0;33m",&lt;br /&gt;        BLUE         =&gt; "[0;34m",&lt;br /&gt;        CYAN         =&gt; "[0;36m",&lt;br /&gt;        BOLD         =&gt; "[1m",&lt;br /&gt;        UNDERSCORE     =&gt; "[4m",&lt;br /&gt;        REVERSE     =&gt; "[7m",&lt;br /&gt;&lt;br /&gt;);&lt;br /&gt;##############################################&lt;br /&gt;# Output colorized text to terminal run&lt;br /&gt;# php scripts..&lt;br /&gt;##############################################&lt;br /&gt;function termcolored($text, $color="NORMAL", $back=1){&lt;br /&gt;    global $_colors;&lt;br /&gt;    $out = $_colors["$color"];&lt;br /&gt;    if($out == ""){ $out = "[0m"; }&lt;br /&gt;    if($back){&lt;br /&gt;        return chr(27)."$out$text".chr(27)."[0m";#.chr(27);&lt;br /&gt;    }else{&lt;br /&gt;        echo chr(27)."$out$text".chr(27).chr(27)."[0m";#.chr(27);&lt;br /&gt;    }//fi&lt;br /&gt;}// end function&lt;br /&gt;##############################################&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 16 Jan 2007 23:30:29 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3292</guid>
      <author>joeldg (joeldg)</author>
    </item>
    <item>
      <title>terminal *live* text graph in php, unix terminal</title>
      <link>http://snippets.dzone.com/posts/show/3291</link>
      <description>I often run php scripts from the command line in linux and need a way to view time series of data, often I need to see the number of mysql queries or want to view other stats.&lt;br /&gt;That look like the following, it moves from right to left in real time as the data points change. &lt;br /&gt;&lt;code&gt;&lt;br /&gt;+local mysql: 565 queries/sec 189----------------------+&lt;br /&gt; |                                                      |&lt;br /&gt; |                                       %              |&lt;br /&gt; |                                       %              |&lt;br /&gt; |                                       %              |&lt;br /&gt; |                                       %              |&lt;br /&gt; |                                       %              |&lt;br /&gt; |                   %                   %              |&lt;br /&gt; | %   %%   %% % %  %%%%%                % %%        %% |&lt;br /&gt; |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%% %%%%%%  %%%%%|&lt;br /&gt; |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|&lt;br /&gt;+-------------------------------------high: 100, low: 1+&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Just copy and past the following code into a file called "termgraph.php" and change the mysql password (if needed) and change the database name (if needed as it it set to work with the default mysql install), then run it and see, very easy to modify this to work with whatever you need. In addition, you can also do colored graphs in terminals using another function I am going to post here.&lt;br /&gt;&lt;br /&gt;This needs a couple changes to work with your mysql database, but the graphs are fun to watch, hope you enjoy this.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;?&lt;br /&gt;// see *EDIT* below for one other change you will need to make&lt;br /&gt;function DatabaseConnect() {&lt;br /&gt;    if (!($mylink = mysql_connect("localhost", "root", ""))){&lt;br /&gt;            print  "ERROR";&lt;br /&gt;            exit;&lt;br /&gt;        }//fi&lt;br /&gt;        mysql_select_db("test") or die(mysql_error());&lt;br /&gt;}// end function&lt;br /&gt;DatabaseConnect();&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;    remove flatspots in array..&lt;br /&gt;    areas where the data does not change.&lt;br /&gt;    this is good for data that only changes during certain times&lt;br /&gt;    and the dead time has no bearing on the changes.&lt;br /&gt;    -joeldg&lt;br /&gt;*/&lt;br /&gt;function remove_flatspots($arr, $pkey=true){&lt;br /&gt;    while(list($key,$val) = each($arr)){&lt;br /&gt;        if($val &lt;&gt; $oldval){&lt;br /&gt;            if($pkey == true){&lt;br /&gt;                $ret[$key] = $val;&lt;br /&gt;            }else{&lt;br /&gt;                $ret[] = $val;&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        $oldval = $val;&lt;br /&gt;    }&lt;br /&gt;    return $ret;&lt;br /&gt;}&lt;br /&gt;/*&lt;br /&gt;    take two arrays, remove the flatspots in the first.&lt;br /&gt;    return an array containing the first with it's corresponding&lt;br /&gt;    values in the second array..&lt;br /&gt;    -joeldg&lt;br /&gt;*/&lt;br /&gt;function dual_remove_flatspots($arr1, $arr2, $pkey=true){&lt;br /&gt;    while(list($key,$val) = each($arr1)){&lt;br /&gt;        if($val &lt;&gt; $oldval){&lt;br /&gt;            if($pkey == true){&lt;br /&gt;                $ret[0][$key] = $val;&lt;br /&gt;                $ret[1][$key] = $arr2[$key];&lt;br /&gt;            }else{&lt;br /&gt;                $ret[0][] = $val;&lt;br /&gt;                $ret[1][] = $arr2[$key];&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        $oldval = $val;&lt;br /&gt;    }&lt;br /&gt;    return $ret;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// return lowest val of array -joeldg&lt;br /&gt;function least($inarr){&lt;br /&gt;    $ret = $inarr[0];&lt;br /&gt;    for($i=0;$i&lt;count($inarr);$i++){&lt;br /&gt;        if(intval($inarr[$i]) &lt;= $ret){ $ret = $inarr[$i]; }&lt;br /&gt;    }//rof&lt;br /&gt;    return $ret;&lt;br /&gt;}// end function&lt;br /&gt;// return higest val of array -joeldg&lt;br /&gt;function most($inarr){&lt;br /&gt;    while(list($key,$val) = each($inarr)){&lt;br /&gt;        if ($ret==""){$ret = $val;}&lt;br /&gt;        if($ret &lt;= intval($val)){ $ret = $val; }&lt;br /&gt;    }//rof&lt;br /&gt;    return $ret;&lt;br /&gt;}// end function&lt;br /&gt;/*&lt;br /&gt;	array normalize function &lt;br /&gt;	-joeldg&lt;br /&gt;*/&lt;br /&gt;function normalize($arr,$LO=0.01,$HI=0.99)&lt;br /&gt;{&lt;br /&gt;  $Min = +2147483647;&lt;br /&gt;  $Max = -2147483647;&lt;br /&gt;  for ($a=0; $a&lt;count($arr); $a++) {&lt;br /&gt;    $Min = min($Min, $arr[$a]);&lt;br /&gt;    $Max = max($Max, $arr[$a]);&lt;br /&gt;  }&lt;br /&gt;  $Mean = 0;&lt;br /&gt;  for ($a=0; $a&lt;count($arr); $a++) {&lt;br /&gt;    $div = $Max-$Min;&lt;br /&gt;    if($div == 0){$div = 1;}&lt;br /&gt;    $arr [$a] = (($arr[$a]-$Min) / ($div)) * ($HI-$LO) + $LO;&lt;br /&gt;    $Mean += $arr[$a] / count($arr);&lt;br /&gt;  }&lt;br /&gt;  return $arr;&lt;br /&gt;}&lt;br /&gt;/*&lt;br /&gt;	array normalize function, preserve key&lt;br /&gt;	-joeldg&lt;br /&gt;*/&lt;br /&gt;function normalizekey($arr,$LO=0.01,$HI=0.99)&lt;br /&gt;{&lt;br /&gt;  $Min = +2147483647;&lt;br /&gt;  $Max = -2147483647;&lt;br /&gt;  while(list($key, $a)=each($arr)){&lt;br /&gt;    $Min = min($Min, $arr[$key]);&lt;br /&gt;    $Max = max($Max, $arr[$key]);&lt;br /&gt;  }&lt;br /&gt;  reset($arr);&lt;br /&gt;  $Mean = 0;&lt;br /&gt;  while(list($key,$a)=each($arr)){&lt;br /&gt;    $div = $Max-$Min;&lt;br /&gt;    if($div == 0){$div = 1;}&lt;br /&gt;    $arr [$key] = (($arr[$key]-$Min) / ($div)) * ($HI-$LO) + $LO;&lt;br /&gt;    $Mean += $arr[$key] / count($arr);&lt;br /&gt;  }&lt;br /&gt;  $retarr[0] = $arr;&lt;br /&gt;  $retarr[1][0]=$Max;&lt;br /&gt;  $retarr[1][1]=$Min;&lt;br /&gt;  &lt;br /&gt;  return $retarr;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/*&lt;br /&gt;display a textual graph in an xterm.&lt;br /&gt;written because I want to view timeseries data and not have to jump over to a browser.&lt;br /&gt;*/&lt;br /&gt;#&lt;br /&gt;#    transform an array point to a position within the total&lt;br /&gt;#&lt;br /&gt;function point2arr($point, $total=20){&lt;br /&gt;    $p = round($point);&lt;br /&gt;    for($a=0;$a&lt;$total;$a++){&lt;br /&gt;        if($a &lt;= $p){&lt;br /&gt;            $ret[] = "%";#chr(127);&lt;br /&gt;        }else{&lt;br /&gt;            $ret[] = " ";&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;    return $ret;&lt;br /&gt;}&lt;br /&gt;// get the width and height of a unix terminal&lt;br /&gt;function get_term_specs(){&lt;br /&gt;    $b = `stty -a`;&lt;br /&gt;    $c = explode("\n",$b);&lt;br /&gt;    $d = explode(";", $c[0]);&lt;br /&gt;    $f = explode(" ",$d[1]);&lt;br /&gt;    $ret[h] = $f[2];&lt;br /&gt;    $f = explode(" ",$d[2]);&lt;br /&gt;    $ret[w] = intval($f[2]);    &lt;br /&gt;    return $ret;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;function genchars($char, $total, $title="", $echo=false, $way=STR_PAD_RIGHT){&lt;br /&gt;    $ret .= "+";&lt;br /&gt;    #if($echo){ echo termcolored("+", WHITE); }&lt;br /&gt;    #if(!$echo){ $ret .= "+"; }&lt;br /&gt;        #$back = termcolored($title, "YELLOW");&lt;br /&gt;        $back = $title;&lt;br /&gt;        $ret .= str_pad($back, $total+strlen($back)-strlen($title)-2, $char, $way);&lt;br /&gt;    #if(!$echo){ $ret .= "+"; }&lt;br /&gt;    #if($echo){ echo termcolored("+", WHITE); }&lt;br /&gt;    $ret .= "+";&lt;br /&gt;    return $ret;&lt;br /&gt;}&lt;br /&gt;// vertical graph&lt;br /&gt;function print_vert_graph($arr, $total=20, $border="-"){&lt;br /&gt;    $arr = normalize($arr, 0, $total);&lt;br /&gt;    $out[] = genchars($border, $total);&lt;br /&gt;    for($a=0;$a&lt;count($arr);$a++){&lt;br /&gt;        $out[] = point2arr($arr[$a], $total);&lt;br /&gt;    }&lt;br /&gt;    $out[] = genchars($border, $total);&lt;br /&gt;    for($a=0;$a&lt;count($out);$a++){&lt;br /&gt;        for($b=0;$b&lt;count($out[$a]);$b++){&lt;br /&gt;            echo $out[$a][$b];&lt;br /&gt;        }&lt;br /&gt;        echo "\n";&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;}&lt;br /&gt;// transform matrix &lt;br /&gt;function transformmat($arr,$total=20){&lt;br /&gt;    $width = count($arr[0]);&lt;br /&gt;    $c=$width-1;&lt;br /&gt;    for($w=0;$w&lt;$width;$w++){&lt;br /&gt;        for($a=0;$a&lt;count($arr);$a++){&lt;br /&gt;            $ret[$c][$a] = $arr[$a][$w];&lt;br /&gt;        }&lt;br /&gt;        $c--;&lt;br /&gt;    }&lt;br /&gt;    return $ret;&lt;br /&gt;}&lt;br /&gt;// horizontal graphing&lt;br /&gt;function print_horz_graph($arr, $total=20, $border="-", $title="", $w=""){&lt;br /&gt;    if($w &lt;&gt; ""){&lt;br /&gt;        array_reverse($arr);&lt;br /&gt;        $end = count($arr)-1;&lt;br /&gt;        reset($arr);&lt;br /&gt;        while(list($key,$val)=each($arr)){&lt;br /&gt;            $newarr[] = $arr[$key];&lt;br /&gt;            $end--;&lt;br /&gt;            if($end &lt;= 0){break;}&lt;br /&gt;        }&lt;br /&gt;        #array_reverse($newarr);&lt;br /&gt;        $arr=$newarr;&lt;br /&gt;    }&lt;br /&gt;    #print_R($arr);&lt;br /&gt;    $bottom = "high: ".most($arr).", low: ".least($arr);&lt;br /&gt;    $arr = normalize($arr, 0, $total-2);&lt;br /&gt;    #$out[] = genchars($border, $total);&lt;br /&gt;    for($a=0;$a&lt;count($arr);$a++){&lt;br /&gt;        $out[] = point2arr($arr[$a], $total);&lt;br /&gt;    }&lt;br /&gt;    $out = transformmat($out,$total);&lt;br /&gt;    $ret .= genchars("-", count($out[0])+2, $title, false);&lt;br /&gt;    #echo "\n";&lt;br /&gt;    $ret .= "\n";&lt;br /&gt;    for($a=0;$a&lt;count($out);$a++){&lt;br /&gt;        #echo termcolored("|", WHITE);&lt;br /&gt;        $ret .=  " |";&lt;br /&gt;        for($b=0;$b&lt;count($out[$a]);$b++){&lt;br /&gt;            $ret .= $out[$a][$b];&lt;br /&gt;        }&lt;br /&gt;        $ret .= "|";&lt;br /&gt;        #echo termcolored("|", WHITE);&lt;br /&gt;        $ret .= "\n";&lt;br /&gt;    }&lt;br /&gt;    $ret .= genchars("-", count($out[0])+2, $bottom, false, STR_PAD_LEFT);&lt;br /&gt;    $ret .= "\n";&lt;br /&gt;    return $ret;&lt;br /&gt;    &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// *EDIT* change mysql to whatever table you want to test&lt;br /&gt;// this default should work for fun..&lt;br /&gt;$db_list = mysql_list_tables("mysql");&lt;br /&gt;while ($row = mysql_fetch_row($db_list)) {&lt;br /&gt;   $tables[] = trim("{$row[0]}");&lt;br /&gt;}&lt;br /&gt;$testarr_z = array();&lt;br /&gt;$testarr = array();&lt;br /&gt;$qcount = 0;&lt;br /&gt;$start = microtime(true);&lt;br /&gt;&lt;br /&gt;while(1){&lt;br /&gt;	$hw = get_term_specs();&lt;br /&gt;	array_pad($testarr_z, ($hw['w'] - 6), 0);&lt;br /&gt;&lt;br /&gt;	array_pad($testarr, ($hw['w'] - 6), 0);&lt;br /&gt;	$time_start = microtime(true);&lt;br /&gt;	$tab = $tables[rand(0,count($tables))];&lt;br /&gt;	&lt;br /&gt;	$amt = rand(500, 5000);&lt;br /&gt;	$sql = "SELECT * FROM $tab LIMIT 0,$amt";&lt;br /&gt;	$res = mysql_db_query("oracle", $sql);&lt;br /&gt;	$qcount++;&lt;br /&gt;	&lt;br /&gt;	$time_end = microtime(true);&lt;br /&gt;	$time = $time_end - $time_start;&lt;br /&gt;	$testarr_z[] = $time;&lt;br /&gt;	@mysql_free_result($res);&lt;br /&gt;	&lt;br /&gt;	if(count($testarr_z)&gt; ($hw['w'] - 6)){&lt;br /&gt;		array_shift($testarr_z);&lt;br /&gt;	}&lt;br /&gt;	$testarr = normalize($testarr_z, 1, 100);&lt;br /&gt;&lt;br /&gt;	$testarr = remove_flatspots($testarr, false);&lt;br /&gt;	$tottime = $time_end - $start;&lt;br /&gt;	$qps = round($qcount/$tottime);&lt;br /&gt;	echo print_horz_graph($testarr, $hw['h']-3, "-", "local mysql: $qcount queries/sec $qps", $hw['w']-1);&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;?&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 16 Jan 2007 23:11:44 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3291</guid>
      <author>joeldg (joeldg)</author>
    </item>
    <item>
      <title>Rails - &#8216;poor mans&#8217; SQL cache.</title>
      <link>http://snippets.dzone.com/posts/show/3286</link>
      <description>Rails memcached is not very easy to introduce to a large rails installation. Memcached also chews up a lot of memory on the box and overall cached model does not work the way I needed it to. Basically, I have just a &#226;&#8364;&#339;few&#226;&#8364;? queries that I needed to cache because pagination sucks just that bad in rails.&lt;br /&gt;So, I built my own cache, similar to how I build them in PHP except I am not using disk cache, I am using MySQL itself to cache it&#226;&#8364;&#8482;s own results&lt;br /&gt;&lt;br /&gt;First, we need a table to hold all this info (note the &#226;&#8364;&#732;blob&#226;&#8364;&#8482; field)&lt;br /&gt;&lt;code&gt;&lt;br /&gt;CREATE TABLE `cacheditems` (&lt;br /&gt;`id` int(11) NOT NULL auto_increment,&lt;br /&gt;`cachekey` varchar(255) default NULL,&lt;br /&gt;`created` datetime default NULL,&lt;br /&gt;`expires` datetime default NULL,&lt;br /&gt;`content` longblob,&lt;br /&gt;`cachehit` int(11) NOT NULL,&lt;br /&gt;PRIMARY KEY  (`id`),&lt;br /&gt;KEY `cacheditems_cachekey_index` (`cachekey`),&lt;br /&gt;KEY `cacheditems_created_index` (`created`),&lt;br /&gt;KEY `cacheditems_expires_index` (`expires`)&lt;br /&gt;)&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Then we create a model called &#226;&#8364;&#339;cacheditem&#226;&#8364;? which has the following functions&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'digest/sha1'&lt;br /&gt;class Cacheditem &lt; ActiveRecord::Base&lt;br /&gt;&lt;br /&gt;def self.checkfor(sql)&lt;br /&gt;key = Digest::MD5.hexdigest(Marshal.dump(sql))&lt;br /&gt;logger.info "%%% checking for key #{key}"&lt;br /&gt;#logger.info "%%% checking by sql #{sql[0]}"&lt;br /&gt;Cacheditem.find( :first, :conditions =&gt; [ &#226;&#8364;&#339;cachekey = ? AND expires &gt; NOW()&#226;&#8364;?, key] )&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def self.getcached(sql)&lt;br /&gt;key = Digest::MD5.hexdigest(Marshal.dump(sql))&lt;br /&gt;logger.info &#226;&#8364;&#339;%%% getting by key #{key}&#226;&#8364;?&lt;br /&gt;#logger.info &#226;&#8364;&#339;%%% getting by sql #{sql[0]}&#226;&#8364;?&lt;br /&gt;getc = Cacheditem.find( :first, :conditions =&gt; [ &#226;&#8364;&#339;cachekey = ?&#226;&#8364;?, key] )&lt;br /&gt;hitcount = getc.cachehit + 1&lt;br /&gt;Cacheditem.update(getc.id, {:cachehit =&gt; hitcount})&lt;br /&gt;Cacheditem.delete_all &#226;&#8364;&#339;expires &lt; NOW()"  # cleaner&lt;br /&gt;return Marshal.load( getc.content )&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def self.storeresult(sql, result)&lt;br /&gt;key = Digest::MD5.hexdigest(Marshal.dump(sql))&lt;br /&gt;logger.info "%%% storing by key #{key}"&lt;br /&gt;content = Marshal.dump(result)&lt;br /&gt;logger.level = (4) # this stops display in logs of the marshal data&lt;br /&gt;ci = new()&lt;br /&gt;ci.cachekey    = key&lt;br /&gt;ci.created       = Time.now()&lt;br /&gt;ci.expires        = 30.minutes.from_now() # change as needed&lt;br /&gt;ci.content        = content&lt;br /&gt;ci.cachehit       = 0&lt;br /&gt;ci.save&lt;br /&gt;return  result&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Then, in application.rb I added the following function&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def find_by_sql_cache(sql)&lt;br /&gt;iscached = Cacheditem.checkfor(sql)&lt;br /&gt;if iscached&lt;br /&gt;Cacheditem.getcached(sql)&lt;br /&gt;else&lt;br /&gt;result = connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }&lt;br /&gt;Cacheditem.storeresult(sql, result)&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;just throw &#226;&#8364;&#339;_cache&#226;&#8364;? after any &#226;&#8364;&#339;find_by_sql&#226;&#8364;? statement you have a need to cache and there you are.&lt;br /&gt;&lt;br /&gt;This works very fast, very well, and doesn&#226;&#8364;&#8482;t hog your memory. It cleans up after itself in the database, and perhaps it does that too much.. It would be easy to add in a standard garbage collection function which runs on a random but I felt this gave me much better stats of the actual thirty-minute cache&#226;&#8364;&#166;&lt;br /&gt;If you use zabbix for monitoring your network, you can have fun graphs of cache statistics by adding the following to your zabbix_agentd.conf&lt;br /&gt;&lt;code&gt;&lt;br /&gt;UserParameter=mysql.totalcache,mysql &#226;&#8364;&#8220;batch &#226;&#8364;&#8220;skip-column-names -D {YOUR_DATABASE} -u{YOUR_USERNAME} -p{YOUR_PASSWORD} -e &#226;&#8364;&#339;SELECT count( * ) AS total, SUM( cachehit ) AS amount from cacheditems;&#226;&#8364;? | cut -f1&lt;br /&gt;UserParameter=mysql.cachehits,mysql &#226;&#8364;&#8220;batch &#226;&#8364;&#8220;skip-column-names -D {YOUR_DATABASE} -u{YOUR_USERNAME} -p{YOUR_PASSWORD} -e &#226;&#8364;&#339;SELECT count( * ) AS total, SUM( cachehit ) AS amount from cacheditems;&#226;&#8364;? | cut -f2&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 15 Jan 2007 22:55:31 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3286</guid>
      <author>joeldg (joeldg)</author>
    </item>
  </channel>
</rss>
