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

About this user

Jonas Raoni Soares Silva http://jsfromhell.com

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

CSV Parser / Writer for PHP

CSV Parser / Writer

Example A:

   1  
   2  //cell separator, row separator, value enclosure
   3  $csv = new CSV(';', "\r\n", '"');
   4  
   5  //parse the string content
   6  $csv->setContent(file_get_contents('data.csv'));
   7  
   8  //returns an array with the CSV data
   9  print_r($csv->getArray());
  10  


Exemple B:

   1  
   2  $csv = new CSV(';', "\r\n", '"');
   3  //sets up the content through an array
   4  $csv->setArray(
   5  	array(
   6  		array('col"una1', "colu\r\nna2"),
   7  		array('col;una3', 'coluna4')
   8  	)
   9  );
  10  //retorns string with the CSV representation
  11  print $csv->getContent();
  12  


   1  
   2  <?php
   3  //+ Jonas Raoni Soares Silva
   4  //@ http://jsfromhell.com
   5  class CSV{
   6  	var $cellDelimiter;
   7  	var $valueEnclosure;
   8  	var $rowDelimiter;
   9  
  10  	function CSV($cellDelimiter, $rowDelimiter, $valueEnclosure){
  11  		$this->cellDelimiter = $cellDelimiter;
  12  		$this->valueEnclosure = $valueEnclosure;
  13  		$this->rowDelimiter = $rowDelimiter;
  14  		$this->o = array();
  15  	}
  16  	function getArray(){
  17  		return $this->o;
  18  	}
  19  	function setArray($o){
  20  		$this->o = $o;
  21  	}
  22  	function getContent(){
  23  		if(!(($bl = strlen($b = $this->rowDelimiter)) && ($dl = strlen($d = $this->cellDelimiter)) && ($ql = strlen($q = $this->valueEnclosure))))
  24  			return '';
  25  		for($o = $this->o, $i = -1; ++$i < count($o);){
  26  			for($e = 0, $j = -1; ++$j < count($o[$i]);)
  27  				(($e = strpos($o[$i][$j], $q) !== false) || strpos($o[$i][$j], $b) !== false || strpos($o[$i][$j], $d) !== false)
  28  				&& $o[$i][$j] = $q . ($e ? str_replace($q, $q . $q, $o[$i][$j]) : $o[$i][$j]) . $q;
  29  			$o[$i] = implode($d, $o[$i]);
  30  		}
  31  		return implode($b, $o);
  32  	}
  33  	function setContent($s){
  34  		$this->o = array();
  35  		if(!strlen($s))
  36  			return true;
  37  		if(!(($bl = strlen($b = $this->rowDelimiter)) && ($dl = strlen($d = $this->cellDelimiter)) && ($ql = strlen($q = $this->valueEnclosure))))
  38  			return false;
  39  		for($o = array(array('')), $this->o = &$o, $e = $r = $c = 0, $i = -1, $l = strlen($s); ++$i < $l;){
  40  			if(!$e && substr($s, $i, $bl) == $b){
  41  				$o[++$r][$c = 0] = '';
  42  				$i += $bl - 1;
  43  			}
  44  			elseif(substr($s, $i, $ql) == $q){
  45  				$e ? (substr($s, $i + $ql, $ql) == $q ?
  46  				$o[$r][$c] .= substr($s, $i += $ql, $ql) : $e = 0)
  47  				: (strlen($o[$r][$c]) == 0 ? $e = 1 : $o[$r][$c] .= substr($s, $i, $ql));
  48  				$i += $ql - 1;
  49  			}
  50  			elseif(!$e && substr($s, $i, $dl) == $d){
  51  				$o[$r][++$c] = '';
  52  				$i += $dl - 1;
  53  			}
  54  			else
  55  				$o[$r][$c] .= $s[$i];
  56  		}
  57  		return true;
  58  	}
  59  }
  60  ?>

Math Parser //JavaScript Class


This class is able to parse math expressions and also run user defined functions.

On JavaScript there's the "eval" function, that can do such things well, but this code objective was just to give me fun or a new challenge =)~

[UPDATED CODE AND HELP CAN BE FOUND HERE]

Usage:

   1  
   2  x = new MathProcessor;
   3  try{alert(x.parse("1+2-(3*4) + medium(2,3) - frac( 2.2231)"));}
   4  catch(e){alert(e);}


It's possible to add more functions to the class, just add them into the "methods" property ;]

Well, that's it :)

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/classes/math-processor [v1.0]
   4  
   5  MathProcessor = function(){ //v1.0
   6      var o = this;
   7      o.o = {
   8          "+": function(a, b){ return +a + b; },
   9          "-": function(a, b){ return a - b; },
  10          "%": function(a, b){ return a % b; },
  11          "/": function(a, b){ return a / b; },
  12          "*": function(a, b){ return a * b; },
  13          "^": function(a, b){ return Math.pow(a, b); },
  14          "~": function(a, b){ return Math.sqrt(a, b); }
  15      };
  16      o.s = { "^": 3, "~": 3, "*": 2, "/": 2, "%": 1, "+": 0, "-": 0 };
  17      o.u = {"+": 1, "-": -1}, o.p = {"(": 1, ")": -1};
  18  };
  19  
  20  MathProcessor.prototype.parse = function(e){
  21      for(var n, x, o = [], s = [x = this.RPN(e.replace(/ /g, "").split(""))]; s.length;)
  22          for((n = s[s.length-1], --s.length); n[2]; o[o.length] = n, s[s.length] = n[3], n = n[2]);
  23      for(; (n = o.pop()) != undefined; n[0] = this.o[n[0]](isNaN(n[2][0]) ? this.f(n[2][0]) : n[2][0], isNaN(n[3][0]) ? this.f(n[3][0]) : n[3][0]));
  24      return +x[0];
  25  };
  26  
  27  MathProcessor.prototype.methods = {
  28      "div": function(a, b){ return parseInt(a / b); },
  29      "frac": function(a){ return a - parseInt(a); },
  30      "sum": function(n1, n2, n3, n){ for(var r = 0, a, l = (a = arguments).length; l; r += a[--l]); return r; },
  31      "medium": function(a, b){ return (a + b) / 2; }
  32  };
  33  
  34  MathProcessor.prototype.error = function(s){
  35      throw new Error("MathProcessor: " + (s || "Erro na expressão"));
  36  }
  37  
  38  MathProcessor.prototype.RPN = function(e){
  39      var _, r, c = r = [, , , 0];
  40      if(e[0] in this.u || !e.unshift("+"))
  41          for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
  42      (c[3] = [this.u[e.shift()], c, , 0])[1][0] = "*", (r = [, , c, 0])[2][1] = r;
  43      (c[2] = this.v(e))[1] = c;
  44      (!e.length && (r = c)) || (e[0] in this.s && ((c = r)[0] = e.shift(), !e.length && this.error()));
  45       while(e.length){
  46          if(e[0] in this.u){
  47              for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
  48              (c = c[3] = ["*", c, , 0])[2] = [-1, c, , 0];
  49          }
  50          (c[3] = this.v(e))[1] = c;
  51          e[0] in this.s && (c = this.s[e[0]] > this.s[c[0]] ?
  52              ((c[3] = (_ = c[3], c[2]))[1][2] = [e.shift(), c, _, 0])[2][1] = c[2]
  53              : r == c ? (r = [e.shift(), , c, 0])[2][1] = r
  54              : ((r[2] = (_ = r[2], [e.shift(), r, ,0]))[2] = _)[1] = r[2]);
  55      }
  56      return r;
  57  };
  58  
  59  MathProcessor.prototype.v = function(e){
  60      if("0123456789.".indexOf(e[0]) + 1){
  61          for(var i = -1, l = e.length; ++i < l && "0123456789.".indexOf(e[i]) + 1;);
  62          return [+e.splice(0,i).join(""), , , 0];
  63      }
  64      else if(e[0] == "("){
  65          for(var i = 0, l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
  66          return this.RPN(l = e.splice(0,i), l.shift(), !j && e.shift());
  67      }
  68      else{
  69          var i = 0, c = e[0].toLowerCase();
  70          if((c >= "a" && c <= "z") || c == "_"){
  71              while(((c = e[++i].toLowerCase()) >= "a" && c <= "z") || c == "_" || (c >= 0 && c <= 9));
  72              if(c == "("){
  73                  for(var l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
  74                  return [e.splice(0,i+1).join(""), , , 0];
  75              }
  76          }
  77      }
  78      this.error();
  79  }
  80  
  81  MathProcessor.prototype.f = function(e){
  82      var i = 0, n;
  83      if(((e = e.split(""))[i] >= "a" && e[i] <= "z") || e[i] == "_"){
  84          while((e[++i] >= "a" && e[i] <= "z") || e[i] == "_" || (e[i] >= 0 && e[i] <= 9));
  85          if(e[i] == "("){
  86              !this.methods[n = e.splice(0, i).join("")] && this.error("Função \"" + n + "\" não encontrada"), e.shift();
  87              for(var a = [], i = -1, j = 1; e[++i] && (e[i] in this.p && (j += this.p[e[i]]), j);)
  88                  j == 1 && e[i] == "," && (a.push(this.parse(e.splice(0, i).join(""))), e.shift(), i = -1);
  89              a.push(this.parse(e.splice(0,i).join(""))), !j && e.shift();
  90          }
  91          return this.methods[n].apply(this, a);
  92      }
  93  };

Path parser //Pascal class

An unit to get the special folders' path under windows and it also parses paths shortcuts in the form "$(shortcut)/folder/file.ext".

   1  
   2  unit PathParser;
   3  
   4  interface
   5  
   6  uses
   7    Classes, SysUtils, TypInfo, SysUtils2, ShlObj, ShellApi, Registry, Windows;
   8  
   9  type
  10    TSpecialFolder = ( sfDesktop, sfAppData, sfTemplates, sfPrograms,
  11      sfPersonal, sfFavorites, sfStartup, sfRecent, sfSendTo, sfStartMenu,
  12      sfFonts, sfHistory, sfCookies, sfInternetCache, sfCommonFavorites,
  13      sfCommonDesktop, sfCommonStartup, sfCommonPrograms, sfCommonStartMenu,
  14      sfProgramFiles, sfTemporary, sfWindows, sfSystem );
  15  
  16    TSpecialFolderSet = set of TSpecialFolder;
  17  
  18    TPathParser = class( TStringList )
  19    public
  20      constructor Create( const UseDefaultMap: Boolean = True );
  21      class function GetSpecialFolder( const Name: TSpecialFolder ): string;
  22      function Parse( Path: string ): string;
  23    end;
  24  
  25  
  26  implementation
  27  
  28  { TPathParser }
  29  
  30  uses Dialogs;
  31  
  32  constructor TPathParser.Create(const UseDefaultMap: Boolean);
  33  var
  34    I: TSpecialFolder;
  35  begin
  36    CaseSensitive := False;
  37    if UseDefaultMap then begin
  38      for I := Low( TSpecialFolder ) to High( TSpecialFolder ) do
  39        Add( RemoveSlash( LowerCase( Copy( GetEnumName( TypeInfo( TSpecialFolder ),
  40          Ord( I ) ), 3, MAX_PATH ) ) + '=' + GetSpecialFolder( I ) ) );
  41      Add( RemoveSlash( Format( 'windowsvolume=%s', [ GetSpecialFolder( sfWindows )[1] ] ) ) );
  42    end;
  43  end;
  44  
  45  class function TPathParser.GetSpecialFolder(
  46    const Name: TSpecialFolder): string;
  47  const
  48    FoldersMap: array[TSpecialFolder] of Cardinal = ( CSIDL_DESKTOP,
  49      CSIDL_APPDATA, CSIDL_TEMPLATES, CSIDL_PROGRAMS, CSIDL_PERSONAL,
  50      CSIDL_FAVORITES, CSIDL_STARTUP, CSIDL_RECENT, CSIDL_SENDTO, CSIDL_STARTMENU,
  51      CSIDL_FONTS, CSIDL_HISTORY, CSIDL_COOKIES, CSIDL_INTERNET_CACHE,
  52      CSIDL_COMMON_FAVORITES, CSIDL_COMMON_DESKTOPDIRECTORY, CSIDL_COMMON_STARTUP,
  53      CSIDL_COMMON_PROGRAMS, CSIDL_COMMON_STARTMENU, 0, 0, 0, 0 );
  54  var
  55    Res: Bool;
  56    Path: array[0..MAX_PATH-1] of Char;
  57    Reg: TRegistry;
  58  begin
  59    Result := '';
  60    case Name of
  61      sfWindows: GetWindowsDirectory( Path, MAX_PATH );
  62      sfTemporary: GetTempPath( MAX_PATH, Path );
  63      sfSystem: GetSystemDirectory( Path, MAX_PATH );
  64      sfProgramFiles:
  65      begin
  66        Reg := TRegistry.Create( KEY_READ );
  67        try
  68          Reg.RootKey := HKEY_LOCAL_MACHINE;
  69          Reg.OpenKey( 'SOFTWARE\Microsoft\Windows\CurrentVersion', False );
  70          Result := AddSlash( Reg.ReadString( 'ProgramFilesDir' ) );
  71        finally
  72          Reg.Free;
  73        end;
  74        Exit;
  75      end;
  76    else
  77      Res := ShGetSpecialFolderPath( 0, Path, FoldersMap[ Name ], False );
  78      if not Res then
  79        raise Exception.Create( ClassName + '.GetSpecialFolder: Error on ShGetSpecialFolderPath' );
  80    end;
  81    Result := AddSlash( Path );
  82  end;
  83  
  84  function TPathParser.Parse(Path: string): string;
  85  var
  86    S: string;
  87    I, I2, Pos: Integer;
  88  begin
  89    I := 1;
  90    while I <= Length( Path )-3 do
  91    begin
  92      if ( Path[I] = '$' ) and ( Path[I+1] = '(' ) then
  93      begin
  94        I2 := I + 2;
  95        while ( I2 <= Length( Path ) ) and ( Path[I2] <> ')' ) do
  96          Inc( I2 );
  97        if I2 > Length( Path ) then
  98          Break;
  99        S := Copy( Path, I + 2, I2 - ( I + 2 ) );
 100        System.Delete( Path, I, I2 - I + 1 );
 101        Pos := IndexOfName( S );
 102        if Pos > -1 then
 103        begin
 104          System.Insert( ValueFromIndex[Pos], Path, I );
 105          Inc( I, Length( ValueFromIndex[Pos] ) );
 106        end
 107        else
 108          raise Exception.CreateFmt( '%s.Parse: Variável "%s" inexistente', [ ClassName, S ] ); //I := I2 + 1;
 109      end
 110      else
 111        Inc( I );
 112    end;
 113    Result := Path;
 114  end;
 115  
 116  end.

Binary Data Parser //Javascript Class



This is a prototyped class written to serialize and unserialize binary data, so you can read and write binary data files to exchange with programs written in languages like C and Pascal.

Currently the class is able to handle just the following types: signed integers (small 8 bits, short 16 bits, int 32 bits), unsigned integers (byte 8 bits, word 16 bits, dword 32 bits) and floating point (IEEE754 float 32 bits and double 64 bits).

The endianess of the binary values representation can also be configured with the class.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


There's a php version right here.

Code

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/classes/binary-parser [v1.0]
   4  
   5  BinaryParser = function( bigEndian, allowExceptions ){
   6  	this.bigEndian = bigEndian;
   7  	this.allowExceptions = allowExceptions;
   8  };
   9  with( { p: BinaryParser.prototype } ){
  10  	with( {p: ( p.Buffer = function( bigEndian, buffer ){ this.bigEndian = bigEndian || 0; this.buffer = []; this.setBuffer( buffer ); } ).prototype } ){
  11  		p.setBuffer = function( data ){
  12  			if( data ){
  13  				for( var l, i = l = data.length, b = this.buffer = new Array( l ); i; b[l - i] = data.charCodeAt( --i ) );
  14  				this.bigEndian && b.reverse();
  15  			}
  16  		};
  17  		p.hasNeededBits = function( neededBits ){
  18  			return this.buffer.length >= -( -neededBits >> 3 );
  19  		};
  20  		p.checkBuffer = function( neededBits ){
  21  			if( !this.hasNeededBits( neededBits ) )
  22  				throw new Error( "checkBuffer::missing bytes" );
  23  		};
  24  		p.readBits = function( start, length ){
  25  			//shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
  26  			function shl( a, b ){
  27  				for( ; b--; a = ( ( a %= 0x7fffffff + 1 ) & 0x40000000 ) == 0x40000000 ? a * 2 : ( a - 0x40000000 ) * 2 + 0x7fffffff + 1 );
  28  				return a;
  29  			}
  30  			if( start < 0 || length <= 0 )
  31  				return 0;
  32  			this.checkBuffer( start + length );
  33  			for( var offsetLeft, offsetRight = start % 8, curByte = this.buffer.length - ( start >> 3 ) - 1, lastByte = this.buffer.length + ( -( start + length ) >> 3 ), diff = curByte - lastByte, sum = ( ( this.buffer[ curByte ] >> offsetRight ) & ( ( 1 << ( diff ? 8 - offsetRight : length ) ) - 1 ) ) + ( diff && ( offsetLeft = ( start + length ) % 8 ) ? ( this.buffer[ lastByte++ ] & ( ( 1 << offsetLeft ) - 1 ) ) << ( diff-- << 3 ) - offsetRight : 0 ); diff; sum += shl( this.buffer[ lastByte++ ], ( diff-- << 3 ) - offsetRight ) );
  34  			return sum;
  35  		};
  36  	}
  37  	p.warn = function( msg ){
  38  		if( this.allowExceptions )
  39  			throw new Error( msg );
  40  		return 1;
  41  	};
  42  	p.decodeFloat = function( data, precisionBits, exponentBits ){
  43  		var b = new this.Buffer( this.bigEndian, data );
  44  		b.checkBuffer( precisionBits + exponentBits + 1 );
  45  		var bias = Math.pow( 2, exponentBits - 1 ) - 1, signal = b.readBits( precisionBits + exponentBits, 1 ), exponent = b.readBits( precisionBits, exponentBits ), significand = 0,
  46  		divisor = 2, curByte = b.buffer.length + ( -precisionBits >> 3 ) - 1;
  47  		do
  48  			for( var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
  49  		while( precisionBits -= startBit );
  50  		return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0