Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

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

Unix time

   1  
   2  Function UnixTime(gmtHrsOffset)
   3  	UnixTime = DateDiff("s", "1/1/1970 00:00:00", Now()) - (3600 * gmtHrsOffset)
   4  End Function
   5  
   6  Repsonse.Write(UnixTime(-5)) 'E.S.T.


Adding in the GMT offset allowed this to match PHP's time() function on a separate server.

StopWatch - Why is my app so slow ???

StopWatch is a small class allowing to manage multiple concurrent stopwatches to measure time elapsed between two calls. Nothing is done while time is rolling (no thread, no loop), it only stores and compares timestamps.

   1  
   2  import java.util.Hashtable;
   3  
   4  public class StopWatch {
   5      private static final Hashtable startTime = new Hashtable();
   6      
   7      public static void start(String id){
   8          startTime.put(id,new Long(System.currentTimeMillis()));
   9      }
  10  
  11      public static long stop(String id){
  12          return System.currentTimeMillis() - ((Long)startTime.remove(id)).longValue();
  13      }
  14  }


Example of use :
   1  
   2  public main(String[] args) {
   3      // Start a global stopwatch
   4      StopWatch.start("GLOBAL");
   5  
   6      // evaluate time used by task 1
   7      StopWatch.start("TASK1");
   8      executeTask1();
   9      System.out.println("Time elapsed for task 1 : " + StopWatch.stop("TASK1") + "ms";
  10  
  11      // evaluate time used by task 2
  12      StopWatch.start("TASK2");
  13      executeTask2();
  14      System.out.println("Time elapsed for task 2 : " + StopWatch.stop("TASK2") + "ms";
  15  
  16      // Display time elapsed for full processing
  17      System.out.println("Total processing time : " + StopWatch.stop("GLOBAL") + "ms";
  18  }

terminal *live* text graph in php, unix terminal

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.
That look like the following, it moves from right to left in real time as the data points change.
   1  
   2  +local mysql: 565 queries/sec 189----------------------+
   3   |                                                      |
   4   |                                       %              |
   5   |                                       %              |
   6   |                                       %              |
   7   |                                       %              |
   8   |                                       %              |
   9   |                   %                   %              |
  10   | %   %%   %% % %  %%%%%                % %%        %% |
  11   |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%% %%%%%%  %%%%%|
  12   |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|
  13  +-------------------------------------high: 100, low: 1+

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.

This needs a couple changes to work with your mysql database, but the graphs are fun to watch, hope you enjoy this.

   1  
   2  <?
   3  // see *EDIT* below for one other change you will need to make
   4  function DatabaseConnect() {
   5      if (!($mylink = mysql_connect("localhost", "root", ""))){
   6              print  "ERROR";
   7              exit;
   8          }//fi
   9          mysql_select_db("test") or die(mysql_error());
  10  }// end function
  11  DatabaseConnect();
  12  
  13  /*
  14      remove flatspots in array..
  15      areas where the data does not change.
  16      this is good for data that only changes during certain times
  17      and the dead time has no bearing on the changes.
  18      -joeldg
  19  */
  20  function remove_flatspots($arr, $pkey=true){
  21      while(list($key,$val) = each($arr)){
  22          if($val <> $oldval){
  23              if($pkey == true){
  24                  $ret[$key] = $val;
  25              }else{
  26                  $ret[] = $val;
  27              }
  28          }
  29          $oldval = $val;
  30      }
  31      return $ret;
  32  }
  33  /*
  34      take two arrays, remove the flatspots in the first.
  35      return an array containing the first with it's corresponding
  36      values in the second array..
  37      -joeldg
  38  */
  39  function dual_remove_flatspots($arr1, $arr2, $pkey=true){
  40      while(list($key,$val) = each($arr1)){
  41          if($val <> $oldval){
  42              if($pkey == true){
  43                  $ret[0][$key] = $val;
  44                  $ret[1][$key] = $arr2[$key];
  45              }else{
  46                  $ret[0][] = $val;
  47                  $ret[1][] = $arr2[$key];
  48              }
  49          }
  50          $oldval = $val;
  51      }
  52      return $ret;
  53  }
  54  
  55  // return lowest val of array -joeldg
  56  function least($inarr){
  57      $ret = $inarr[0];
  58      for($i=0;$i<count($inarr);$i++){
  59          if(intval($inarr[$i]) <= $ret){ $ret = $inarr[$i]; }
  60      }//rof
  61      return $ret;
  62  }// end function
  63  // return higest val of array -joeldg
  64  function most($inarr){
  65      while(list($key,$val) = each($inarr)){
  66          if ($ret==""){$ret = $val;}
  67          if($ret <= intval($val)){ $ret = $val; }
  68      }//rof
  69      return $ret;
  70  }// end function
  71  /*
  72  	array normalize function 
  73  	-joeldg
  74  */
  75  function normalize($arr,$LO=0.01,$HI=0.99)
  76  {
  77    $Min = +2147483647;
  78    $Max = -2147483647;
  79    for ($a=0; $a<count($arr); $a++) {
  80      $Min = min($Min, $arr[$a]);
  81      $Max = max($Max, $arr[$a]);
  82    }
  83    $Mean = 0;
  84    for ($a=0; $a<count($arr); $a++) {
  85      $div = $Max-$Min;
  86      if($div == 0){$div = 1;}
  87      $arr [$a] = (($arr[$a]-$Min) / ($div)) * ($HI-$LO) + $LO;
  88      $Mean += $arr[$a] / count($arr);
  89    }
  90    return $arr;
  91  }
  92  /*
  93  	array normalize function, preserve key
  94  	-joeldg
  95  */
  96  function normalizekey($arr,$LO=0.01,$HI=0.99)
  97  {
  98    $Min = +2147483647;
  99    $Max = -2147483647;
 100    while(list($key, $a)=each($arr)){
 101      $Min = min($Min, $arr[$key]);
 102      $Max = max($Max, $arr[$key]);
 103    }
 104    reset($arr);
 105    $Mean = 0;
 106    while(list($key,$a)=each($arr)){
 107      $div = $Max-$Min;
 108      if($div == 0){$div = 1;}
 109      $arr [$key] = (($arr[$key]-$Min) / ($div)) * ($HI-$LO) + $LO;
 110      $Mean += $arr[$key] / count($arr);
 111    }
 112    $retarr[0] = $arr;
 113    $retarr[1][0]=$Max;
 114    $retarr[1][1]=$Min;
 115    
 116    return $retarr;
 117  }
 118  
 119  /*
 120  display a textual graph in an xterm.
 121  written because I want to view timeseries data and not have to jump over to a browser.
 122  */
 123  #
 124  #    transform an array point to a position within the total
 125  #
 126  function point2arr($point, $total=20){
 127      $p = round($point);
 128      for($a=0;$a<$total;$a++){
 129          if($a <= $p){
 130              $ret[] = "%";#chr(127);
 131          }else{
 132              $ret[] = " ";
 133          }
 134      }
 135      return $ret;
 136  }
 137  // get the width and height of a unix terminal
 138  function get_term_specs(){
 139      $b = `stty -a`;
 140      $c = explode("\n",$b);
 141      $d = explode(";", $c[0]);
 142      $f = explode(" ",$d[1]);
 143      $ret[h] = $f[2];
 144      $f = explode(" ",$d[2]);
 145      $ret[w] = intval($f[2]);    
 146      return $ret;
 147  }
 148  
 149  function genchars($char, $total, $title="", $echo=false, $way=STR_PAD_RIGHT){
 150      $ret .= "+";
 151      #if($echo){ echo termcolored("+", WHITE); }
 152      #if(!$echo){ $ret .= "+"; }
 153          #$back = termcolored($title, "YELLOW");
 154          $back = $title;
 155          $ret .= str_pad($back, $total+strlen($back)-strlen($title)-2, $char, $way);
 156      #if(!$echo){ $ret .= "+"; }
 157      #if($echo){ echo termcolored("+", WHITE); }
 158      $ret .= "+";
 159      return $ret;
 160  }
 161  // vertical graph
 162  function print_vert_graph($arr, $total=20, $border="-"){
 163      $arr = normalize($arr, 0, $total);
 164      $out[] = genchars($border, $total);
 165      for($a=0;$a<count($arr);$a++){
 166          $out[] = point2arr($arr[$a], $total);
 167      }
 168      $out[] = genchars($border, $total);
 169      for($a=0;$a<count($out);$a++){
 170          for($b=0;$b<count($out[$a]);$b++){
 171              echo $out[$a][$b];
 172          }
 173          echo "\n";
 174      }
 175      
 176  }
 177  // transform matrix 
 178  function transformmat($arr,$total=20){
 179      $width = count($arr[0]);
 180      $c=$width-1;
 181      for($w=0;$w<$width;$w++){
 182          for($a=0;$a<count($arr);$a++){
 183              $ret[$c][$a] = $arr[$a][$w];
 184          }
 185          $c--;
 186      }
 187      return $ret;
 188  }
 189  // horizontal graphing
 190  function print_horz_graph($arr, $total=20, $border="-", $title="", $w=""){
 191      if($w <> ""){
 192          array_reverse($arr);
 193          $end = count($arr)-1;
 194          reset($arr);
 195          while(list($key,$val)=each($arr)){
 196              $newarr[] = $arr[$key];
 197              $end--;
 198              if($end <= 0){break;}
 199          }
 200          #array_reverse($newarr);
 201          $arr=$newarr;
 202      }
 203      #print_R($arr);
 204      $bottom = "high: ".most($arr).", low: ".least($arr);
 205      $arr = normalize($arr, 0, $total-2);
 206      #$out[] = genchars($border, $total);
 207      for($a=0;$a<count($arr);$a++){
 208          $out[] = point2arr($arr[$a], $total);
 209      }
 210      $out = transformmat($out,$total);
 211      $ret .= genchars("-", count($out[0])+2, $title, false);
 212      #echo "\n";
 213      $ret .= "\n";
 214      for($a=0;$a<count($out);$a++){
 215          #echo termcolored("|", WHITE);
 216          $ret .=  " |";
 217          for($b=0;$b<count($out[$a]);$b++){
 218              $ret .= $out[$a][$b];
 219          }
 220          $ret .= "|";
 221          #echo termcolored("|", WHITE);
 222          $ret .= "\n";
 223      }
 224      $ret .= genchars("-", count($out[0])+2, $bottom, false, STR_PAD_LEFT);
 225      $ret .= "\n";
 226      return $ret;
 227      
 228  }
 229  
 230  // *EDIT* change mysql to whatever table you want to test
 231  // this default should work for fun..
 232  $db_list = mysql_list_tables("mysql");
 233  while ($row = mysql_fetch_row($db_list)) {
 234     $tables[] = trim("{$row[0]}");
 235  }
 236  $testarr_z = array();
 237  $testarr = array();
 238  $qcount = 0;
 239  $start = microtime(true);
 240  
 241  while(1){
 242  	$hw = get_term_specs();
 243  	array_pad($testarr_z, ($hw['w'] - 6), 0);
 244  
 245  	array_pad($testarr, ($hw['w'] - 6), 0);
 246  	$time_start = microtime(true);
 247  	$tab = $tables[rand(0,count($tables))];
 248  	
 249  	$amt = rand(500, 5000);
 250  	$sql = "SELECT * FROM $tab LIMIT 0,$amt";
 251  	$res = mysql_db_query("oracle", $sql);
 252  	$qcount++;
 253  	
 254  	$time_end = microtime(true);
 255  	$time = $time_end - $time_start;
 256  	$testarr_z[] = $time;
 257  	@mysql_free_result($res);
 258  	
 259  	if(count($testarr_z)> ($hw['w'] - 6)){
 260  		array_shift($testarr_z);
 261  	}
 262  	$testarr = normalize($testarr_z, 1, 100);
 263  
 264  	$testarr = remove_flatspots($testarr, false);
 265  	$tottime = $time_end - $start;
 266  	$qps = round($qcount/$tottime);
 267  	echo print_horz_graph($testarr, $hw['h']-3, "-", "local mysql: $qcount queries/sec $qps", $hw['w']-1);
 268  
 269  }
 270  
 271  ?>

time since

// returns the time since $original (unix date)

   1  
   2  function time_since($original) {
   3      // array of time period chunks
   4      $chunks = array(
   5          array(60 * 60 * 24 * 365 , 'year'),
   6          array(60 * 60 * 24 * 30 , 'month'),
   7          array(60 * 60 * 24 * 7, 'week'),
   8          array(60 * 60 * 24 , 'day'),
   9          array(60 * 60 , 'hour'),
  10          array(60 , 'minute'),
  11      );
  12      
  13      $today = time(); /* Current unix time  */
  14      $since = $today - $original;
  15  	
  16  	if($since > 604800) {
  17  		$print = date("M jS", $original);
  18  	
  19  		if($since > 31536000) {
  20  				$print .= ", " . date("Y", $original);
  21  			}
  22  
  23  		return $print;
  24  
  25  	}
  26      
  27      // $j saves performing the count function each time around the loop
  28      for ($i = 0, $j = count($chunks); $i < $j; $i++) {
  29          
  30          $seconds = $chunks[$i][0];
  31          $name = $chunks[$i][1];
  32          
  33          // finding the biggest chunk (if the chunk fits, break)
  34          if (($count = floor($since / $seconds)) != 0) {
  35              // DEBUG print "<!-- It's $name -->\n";
  36              break;
  37          }
  38      }
  39  
  40      $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
  41  
  42      return $print . " ago";
  43  
  44  }

Timesince

   1  
   2  <?php
   3  
   4  /* Works out the time since the entry post, takes a an argument in unix time (seconds) */
   5  function time_since($original) {
   6      // array of time period chunks
   7      $chunks = array(
   8          array(60 * 60 * 24 * 365 , 'year'),
   9          array(60 * 60 * 24 * 30 , 'month'),
  10          array(60 * 60 * 24 * 7, 'week'),
  11          array(60 * 60 * 24 , 'day'),
  12          array(60 * 60 , 'hour'),
  13          array(60 , 'minute'),
  14      );
  15      
  16      $today = time(); /* Current unix time  */
  17      $since = $today - $original;
  18      
  19      // $j saves performing the count function each time around the loop
  20      for ($i = 0, $j = count($chunks); $i < $j; $i++) {
  21          
  22          $seconds = $chunks[$i][0];
  23          $name = $chunks[$i][1];
  24          
  25          // finding the biggest chunk (if the chunk fits, break)
  26          if (($count = floor($since / $seconds)) != 0) {
  27              // DEBUG print "<!-- It's $name -->\n";
  28              break;
  29          }
  30      }
  31      
  32      $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
  33      
  34      if ($i + 1 < $j) {
  35          // now getting the second item
  36          $seconds2 = $chunks[$i + 1][0];
  37          $name2 = $chunks[$i + 1][1];
  38          
  39          // add second item if it's greater than 0
  40          if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
  41              $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
  42          }
  43      }
  44      return $print;
  45  }
  46  
  47  ?>

time

With time you can list the resources that a certain command takes up. For example,
   1  time dd if=/dev/random of=/dev/null count=10

will output the number of resources taken up by moving 10 blocks of random data to memory.

now-gmt - Current time, given in GMT

   1  
   2  now-gmt: has [t] [
   3      t: now  
   4      t: t + negate t/zone  
   5      t/zone: none  
   6      t
   7  ]

Javascript - Sleep

// Effettuare uno sleep dello script di uno script

   1  
   2  function pause(millisecondi)
   3  {
   4      var now = new Date();
   5      var exitTime = now.getTime() + millisecondi;
   6  
   7      while(true)
   8      {
   9          now = new Date();
  10          if(now.getTime() > exitTime) return;
  11      }
  12  }

Fix for ActiveRecord SQL Server adapter dates

The SQL Server adapter for ActiveRecord uses Time objects to cast dates from the db. This fails for dates before 1970, thus some birthdates come back as nil. This is some kludge to use a DateTime in that case so we still get the value.

A better approach may be to convert this code to use DateTime objects exclusively, but I'm not sure of the speed implications of doing so. The code below first tries to cast the value to a Time object; if that fails, it tries a DateTime object; if that fails, it returns nil.

Stick this in a plugin to use with Rails.

   1  
   2  module ActiveRecord
   3    module ConnectionAdapters
   4      class ColumnWithIdentity
   5        def cast_to_time(value)
   6          return value if value.is_a?(Time) or value.is_a?(DateTime)
   7          time_array = ParseDate.parsedate(value)
   8          time_array[0] ||= 2000
   9          time_array[1] ||= 1
  10          time_array[2] ||= 1
  11          Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
  12        end
  13        def cast_to_datetime(value)
  14          if value.is_a?(Time) or value.is_a?(DateTime)
  15            if value.year != 0 and value.month != 0 and value.day != 0
  16              return value
  17            else
  18              return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
  19            end
  20          end
  21          return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
  22          value
  23        end
  24      end
  25    end
  26  end

User Friendly Time Entry

http://www.railtie.net/articles/2006/04/22/user-friendly-time-entry
Posted by Bob Silva Sat, 22 Apr 2006 08:49:00 GMT

Have a need to track time spent on something? Here's an easy way to allow your users to enter their time in a smart way (anyway they want). This example accepts fractional hours, overflowing minutes and converts and displays them as the user would expect. They are stored in your database as minutes (integer) and displayed as hours/minutes (regardless of how they were input).

Model Code (model.rb):

   1  
   2  def set_travel_time(hours, minutes)
   3    self.travel_time = ((hours.to_f * 60) + minutes.to_i).to_i
   4  end
   5  
   6  def get_travel_time
   7    travel_time.to_i.divmod(60)
   8  end


Controller Code (models_controller.rb):

   1  
   2  def create
   3    @model.new(...)
   4    ...
   5    @model.set_travel_time(params[:hours], params[:minutes])
   6    ...
   7    if @model.save
   8    ...
   9  end
  10  
  11  def edit
  12    @model = Model.find(...)
  13    ...
  14    @hours, @minutes = @model.get_travel_time
  15    ...
  16  end


View Code (_form.rhtml):

   1  
   2  <%= text_field_tag 'hours', @hours -%> hours 
   3  <%= text_field_tag 'minutes', @minutes -%> minutes 



For plugin ideas, see dollars_and_cents: http://blog.codahale.com/2006/05/18/dollars_and_cents-a-rails-plugin/

One of the big problems with a database-agnostic framework like ActiveRecord is that it doesn’t have a decent data type for money. Yes, you can use a FLOAT, but then you end up charging someone $12.3000000000000001, which is just awkward. This plugin stores as INT, but displays as Currency.
« Newer Snippets
Older Snippets »
Showing 21-30 of 51 total