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 1-10 of 16 total  RSS 

A simple test case using Ruby and XML - Part II

This code tests for the success of a single Class. It reads in the test variables from an xml file and then performs a simple test. Refer to Part I (http://urltea.com/1p7h [dzone.com]) of the ruby code (testdata.rb), and Part III (http://urltea.com/1p7p [dzone.com])

#file: test_feed.rb

require 'testdata.rb'
require 'feed.rb'

include REXML

class Test_feed < Testdata

  def initialize()

    url = 'http://jamesrobertson.eu/test/feed/'
    testfile = "testfile.xml"
    load(url + testfile)

    @in_filepath = get_input('filepath')
    @in_project = get_input('project')
    @in_date = get_input('date')
    @out_filepath = get_output('filepath')
    @out_file = get_output('file')
  end

  def tested
    feed = Feed.new
    feed.create_file(@in_filepath, @in_project)
    File.exist?(@out_filepath + @out_file)
  end

end

#test 
#test_feed = Test_feed.new()
#puts test_feed.tested

A simple test case using Ruby and XML - Part I

Inspired by Gregg Pollack's, Ruby on Rails testing video http://tinyurl.com/ystb4o, this code reads an XML file containing test related variables, to use in an actual test case. Refer to parts II (http://urltea.com/1p7m [dzone.com]), and III (http://urltea.com/1p7p [dzone.com])

#file: testdata.rb

require 'net/http'
require 'rexml/document'

include REXML

class Testdata

  def initialize
  end

  def load(url)
    xml_data = Net::HTTP.get_response(URI.parse(url)).body
    @doc = Document.new(xml_data)
    true
  end

  def get_input(name)
    @doc.root.elements['test/inputs/input/' + name].text
  end

  def get_output(name)
    @doc.root.elements['test/outputs/output/' + name].text
  end

  def tested?()

  end

  def print(method, result)
    puts "<result method='#{method}'>#{result}</result>"
  end

  def plan
    @doc
  end

end

#test 
#url = 'http://m.jamesrobertson.eu/test/testdata/'
#testfile = "testfile.xml"

#td = Testdata.new
#td.load(url + testfile)
#print('get_input', #td.get_input('input1').scan('instring').length > 0)
#print('get_output', td.get_output('output1').scan('outstring').length > 0)

#puts test_feed.tested?


Populate PostgreSQL tables

This script in PHP populate with demo data tables Postgresql.
It insert serious registers automatically in a table.
Remove the primary key before run.

<?php
/** Rotina para popular tabela do PostgreSQL com massa de testes
  * Colaboração de Ribamar FS - http://ribafs.net - 14/03/2007
  * Requer remoção da chave primáia antes da execução.
  */ 
?>

<html><head><title>Inserir Registros de Teste</title></head>
<body bgcolor=''>
<h2 align=center>Cadastrar Tabela do PostgreSQL com Massa de Testes</h2>
<h3 align=center><font color=red>Remova chave primáia da tabela, antes de executar</font></h3>
<h4 align=center>Observe que nem todos os tipos de dados foram contemplados, alguns ficarão como string</h4>

<table align=center>
<form method='POST' name=frmIns action='popula_table_pg.php'>

<tr><td>Host</td><td><input type=text name='host' value='127.0.0.1'></td></tr>
<tr><td>Banco</td><td><input type=text name='banco' value='cliente'></td></tr>
<tr><td>Usuário</td><td><input type=text name='usuario' value='postgres'></td></tr>
<tr><td>Senha</td><td><input type=text name='senha' value='postgres'></td></tr>
<tr><td>Tabela</td><td><input type=text name='tabela' value='clientes'></td></tr>
<tr><td>Registros</td><td><input type=text name='registros' value=5></td></tr>
<tr><td></td><td><input type=submit name='popular' value='Popular'></td></tr>
</form>
</table>
</body>
</html>

<?php
if(isset($_POST['popular'])){
	$host=$_POST['host'];
	$banco=$_POST['banco'];
	$usuario=$_POST['usuario'];
	$senha=$_POST['senha'];
	$tabela=$_POST['tabela'];
	$registros=$_POST['registros'];

	$conexao=pg_connect("host=$host user=$usuario password=$senha dbname=$banco port=5432");
	if (!$conexao){
		die('Erro ao conectar ao banco<br>'.pg_last_error($conexao));
	}
	$str="SELECT * FROM $tabela";
	$consulta= pg_query($conexao,$str);
	$nc=pg_num_fields($consulta);
	$nr=pg_num_rows($consulta);

   $n='';//numericos (int, tinyint, smallint, bigint, etc)
   $r=''; //reais (float e double)
   $s="'";//strings
   $d=date('Y-m-d'); //datas
   $dt=date('Y-m-d H:i:s');//datatimes
   $o=''; //outros

   	$inscod .="INSERT INTO $tabela (";
   	for ($j = 0; $j < $nc; $j++) {
      $campo = pg_field_name($consulta, $j);
		if ($j < $nc-1)	$inscod .= "$campo,";
     	else $inscod .= "$campo";
	}
	$inscod .= ")";	 
    $inscod .= " VALUES (";

   for ($j = 0; $j < $nc; $j++) {   
   $tam   = pg_field_size($consulta, $j);
   if($tam == -1) $tam=20; //Caso queira limitar os campos ao máximo de 20 posiçes
		if ($j < $nc-1){ 
			switch (pg_field_type($consulta, $j)){
				case 'int4':
					$n=str_pad($n,$tam,'12345679890');
					$inscod .= "$n,";
					break;
     			case 'float4':
					$r=str_pad($r,$tam,'1234567890');
					$inscod .= "$r,";
					break;
				case 'bpchar':
				case 'varchar':
					$s=str_pad($s,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "$s',";
					break;
				case 'date':
		 		    $inscod .= "'$d',";
					break;
				case 'timestamp':
					$inscod .= "'$dt',";
					break;
				case 'text':
					$inscod .= "'$t'";
					break;
				default:
					$o=str_pad($o,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "'$o',";
					break;
			}
     	}else{
     		switch (pg_field_type($consulta, $j)){
				case 'int4':
					$n=str_pad($n,$tam,'1234567890');
					$inscod .= "$n";
					break;
     			case 'float4':
					$r=str_pad($r,$tam,'1234567890');
					$inscod .= "$r";
					break;
				case 'bpchar':
				case 'varchar':
					$s=str_pad($s,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "$s'";
					break;
				case 'date':
					$inscod .= "'$d'";
					break;
				case 'timestamp':
					$inscod .= "'$dt'";
					break;
				case 'text':
					$inscod .= "'$t'";
					break;
				default:
					$o=str_pad($o,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "'$o'";
					break;
     		}
     	}
     	
	}
    $inscod .=");";	
	
    for($r=1;$r<=$registros;$r++){	   
		//echo  $inscod;
	   	if(!pg_query($conexao,$inscod)) die ("Erro na inclusã<br>".pg_last_error($conexao));
    }	   
}
?>

Populate MySQL tables

This script in PHP to populate with demo data tables MySQL.
Remove the primary key before run.

<?php
/** Rotina para popular tabela do MySQL com massa de testes
  * Colaboração de Ribamar FS - http://ribafs.net - 14/03/2007
  * Requer remoção da chave primária antes da execução.
  */ 
?>

<html><head><title>Inserir Registros de Teste</title></head>
<body bgcolor=''>
<h2 align=center>Cadastrar Tabela do MySQL com Massa de Testes</h2>
<h3 align=center><font color=red>Remova chave primáia da tabela, antes de executar</font></h3>
<h4 align=center>Observe que nem todos os tipos de dados foram contemplados, alguns ficarão como string</h4>

<table align=center>
<form method='POST' name=frmIns action='popula_table.php'>

<tr><td>Host</td><td><input type=text name='host' value='127.0.0.1'></td></tr>
<tr><td>Banco</td><td><input type=text name='banco' value='cliente'></td></tr>
<tr><td>Usuáio</td><td><input type=text name='usuario' value='root'></td></tr>
<tr><td>Senha</td><td><input type=text name='senha'></td></tr>
<tr><td>Tabela</td><td><input type=text name='tabela' value='clientes'></td></tr>
<tr><td>Registros</td><td><input type=text name='registros' value=5></td></tr>
<tr><td></td><td><input type=submit name='popular' value='Popular'></td></tr>
</form>
</table>
</body>
</html>

<?php
if(isset($_POST['popular'])){
	$host=$_POST['host'];
	$banco=$_POST['banco'];
	$usuario=$_POST['usuario'];
	$senha=$_POST['senha'];
	$tabela=$_POST['tabela'];
	$registros=$_POST['registros'];
	$numericos=$_POST['numericos'];

	$conexao=mysql_connect($host,$usuario,$senha);
	if ($conexao){
		$sel=mysql_select_db($banco,$conexao);
		if(!$sel) die('Erro ao selecionar o banco'.mysql_error());
	}else{
		die ('Erro ao conectar ao banco '.mysql_error());
	}
	$str="SELECT * FROM $tabela";
	$consulta= mysql_query($str,$conexao);
	$nc=mysql_num_fields($consulta);
	$nr=mysql_num_rows($consulta);

   $n='';//numericos (int, tinyint, smallint, bigint, etc)
   $r=''; //reais (float e double)
   $s="'";//strings
   $d=date('Y-m-d'); //datas
   $dt=date('Y-m-d H:i:s');//datatimes
   $o=''; //outros

   	$inscod .="INSERT INTO $tabela (";
   	for ($j = 0; $j < $nc; $j++) {
      $campo = mysql_field_name($consulta, $j);
		if ($j < $nc-1)	$inscod .= "$campo,";
     	else $inscod .= "$campo";
	}
	$inscod .= ")";	 
    $inscod .= " VALUES (";

   for ($j = 0; $j < $nc; $j++) {   
   $tam   = mysql_field_len($consulta, $j);
   //if(($tam)>20) $tam=20; //Caso queira limitar os campos ao máximo de 20 posições
		if ($j < $nc-1){ 
			switch (mysql_field_type($consulta, $j)){
				case 'int':
					$n=str_pad($n,$tam,'12345679890');
					$inscod .= "$n,";
					break;
     			case 'real':
					$r=str_pad($r,$tam,'1234567890');
					$inscod .= "$r,";
					break;
				case 'string':
					$s=str_pad($s,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "$s',";
					break;
				case 'date':
		 		    $inscod .= "'$d',";
					break;
     			case 'datetime':
				case 'timestamp':
					$inscod .= "'$dt',";
					break;
				case 'blog':
					$inscod .= "'$t'";
					break;
				default:
					$o=str_pad($o,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "'$o',";
					break;
			}
     	}else{
     		switch (mysql_field_type($consulta, $j)){
				case 'int':
					$n=str_pad($n,$tam,'1234567890');
					$inscod .= "$n";
					break;
     			case 'real':
					$r=str_pad($r,$tam,'1234567890');
					$inscod .= "$r";
					break;
     			case 'string':
					$s=str_pad($s,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "$s'";
					break;
				case 'date':
					$inscod .= "'$d'";
					break;
	     		case 'datetime':
				case 'timestamp':
					$inscod .= "'$dt'";
					break;
				case 'blog':
					$inscod .= "'$t'";
					break;
				default:
					$o=str_pad($o,$tam,"abcdefghijklmnopqrstuvxyz");
					$inscod .= "'$o'";
					break;
     		}
     	}
     	
	}
    $inscod .=");";	
	
    for($r=1;$r<=$registros;$r++){	   
		//echo  $inscod;
	   	if(!mysql_query($inscod,$conexao)) die ("Erro na inclusão".mysql_error());
    }	   
}
?>

Persisting Application data using Hashtable and IsolatedStorage

// nice way to store application data and settings
// copied from: http://www.dotnetspider.com/kb/Article344.aspx

using System;
using System.Collections;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace CustomStorage
{
    [Serializable]
    public class ApplicationStorage : Hashtable
    {
        // File name. Let us use the entry assembly name with .dat as the extension.
        private string settingsFileName = 
                        System.Reflection.Assembly.GetEntryAssembly().GetName().Name + ".dat";
    
        // The default constructor.
        public ApplicationStorage()
        {
            LoadData();
        }
        
        // This constructor is required for deserializing our class from persistent storage.
        protected ApplicationStorage (SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
        
        private void LoadData()
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User 
                        | IsolatedStorageScope.Assembly, null, null );
            if ( isoStore.GetFileNames( settingsFileName ).Length == 0 )
            {
                // File not exists. Let us NOT try to DeSerialize it.
                return;
            }
            
            // Read the stream from Isolated Storage.
            Stream stream = new IsolatedStorageFileStream( settingsFileName, 
                        FileMode.OpenOrCreate, isoStore );
            if ( stream != null )
            {
                try
                {
                    // DeSerialize the Hashtable from stream.
                    IFormatter formatter = new BinaryFormatter();
                    Hashtable appData = ( Hashtable ) formatter.Deserialize(stream);
                    
                    // Enumerate through the collection and load our base Hashtable.
                    IDictionaryEnumerator enumerator = appData.GetEnumerator();
                    while ( enumerator.MoveNext() )
                    {
                        this[enumerator.Key] = enumerator.Value;
                    }
                }
                finally
                {
                    // We are done with it.
                    stream.Close();
                }
            }
        }
        
        public void ReLoad()
        {
            LoadData();
        }
        
        // Saves the configuration data to the persistent storage.
        public void Save()
        {
            // Open the stream from the IsolatedStorage.
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User 
                        | IsolatedStorageScope.Assembly, null, null );
            Stream stream = new IsolatedStorageFileStream( settingsFileName, 
                        FileMode.Create, isoStore );
        
            if ( stream != null )
            {
                try
                {
                    // Serialize the Hashtable into the IsolatedStorage.
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize( stream, (Hashtable)this );
                }
                finally
                {
                    stream.Close();
                }
            }
        }
    }
}


//sample usage

CustomStorage.ApplicationStorage storage = new CustomStorage.ApplicationStorage();

storage["name"] = "john";
storage["age"] = 23;
storage["address"] = "#10, Vasant Nagar";

storage.Save();

string name = storage["name"].ToString();
int age = int.parse(storage["age"].ToString());

makeSafe

Make data safe...among other things

function makeSafe($variable) {
	$variable = htmlentities($variable, ENT_QUOTES);
  	
	if (get_magic_quotes_gpc()) { 
		$variable = stripslashes($variable); 
	}
  	
	$variable = mysql_real_escape_string(trim($variable));
 	$variable = strip_tags($variable);
	$variable = str_replace("\r\n", "", $variable);
 	
	return $variable;
}

reverse linked list

Reverse Linked list by reversing links for each node or swapping the nodes at each end.

pretty tables for rails models

From http://www.rubyinside.com/columnized-text-datasets-in-rails-71.html:
Inspired by: http://blog.caboo.se/articles/2006/06/10/pretty-tables-for-ruby-objects

It gives a MySQL-command-line-client style textual view of data stored in your Rails database. The syntax worked like this:
Something.find(:all, :conditions => ‘whatever‘).pretty_print


class Array

  protected

    def columnized_row(fields, sized)
      r = []
      fields.each_with_index do |f, i|
        r << sprintf(�%0-#{sized[i]}s“, f.to_s.gsub(/\n|\r/, ‘’).slice(0, sized[i]))
      end
      r.join(’ | ‘)
    end

  public

  def columnized(options = {})
    sized = {}
    self.each do |row|
      row.attributes.values.each_with_index do |value, i|
        sized[i] = [sized[i].to_i, row.attributes.keys[i].length, value.to_s.length].max
        sized[i] = [options[:max_width], sized[i].to_i].min if options[:max_width]
      end
    end

    table = []
    table << header = columnized_row(self.first.attributes.keys, sized)
    table << header.gsub(/./, ‘-‘)
    self.each { |row| table << columnized_row(row.attributes.values, sized) }
    table.join(�\n“)
  end
end

class ActiveRecord::Base
  def columnized(options = {})
    [*self].columnized(options)
  end
end



To use:
>> puts Post.find(:all).columnized(:max_width => 10)
updated_at | title      | private | url | thumb      | metadata | movie      | id  | views | content    | user_id | created_at
——————————————————————————————————————————
Wed May 31 | tetwer     | 0       |     |            |          |            | 909 | 0     | video:xyzz | 1       | Wed May 31
Wed May 31 | bbbb       | 0       |     |            |          |            | 1   | 15    | // descrip | 1       | Tue May 23
Wed May 31 | cxzcxzx    | 0       |     |            |          |            | 906 | 19    | // descrip | 1       | Tue May 23
Wed May 31 | jklklkl;   | 0       |     |            |          |            | 907 | 35    | // descrip | 1       | Tue May 23


If you want to use it with your project, put the code into lib/columnized.rb, use require ‘columnized’, and you’re ready to roll. Unlike courtenay’s version, mine only supports max_width, but I didn’t consider changing the column separator too important.

Execute arbitary SQL in JDBC & get column names etc from the meta data

This will execute an arbitary SQL string in JDBC and extract the column names. I extracted this code from a much larger module I wrote years ago, so it isn't complete and hasn't been tested. You have been warned.

    /*
    ** connection is a java.sql.Connection obtained in the usual way.
    */

    PreparedStatement statement =
	connection.prepareStatement (sqlString);
    statement.setMaxRows (configModel.getMaxRows ());

    if (statement.execute ())
    {
	ResultSet resultSet = statement.getResultSet ();
	ResultSetMetaData metaData = resultSet.getMetaData ();

	/*
	** Get the column names.
	*/

	for (int i = 0 ; i < metaData.getColumnCount () ; i++)
	{
	    int columnType = metaData.getColumnType (i + 1);
	    String columnName = metaData.getColumnLabel (i + 1);

	    /*
	    ** Do something with columnType & columnName.
	    */

	}

	/*
	** Fetch the rows.
	*/

	while (resultSet.next ())
	{
	    String value;

	    for (int i = 0 ; i < metaData.getColumnCount () ; i++)
		value = resultSet.getString (i + 1);
	}
    }
    else
    {
	/*
	** Query was probably update/insert/delete.
	*/

	int rowCount = statement.getUpdateCount ();
    }

    statement.close ();

tip: recover from failed rails 'down' migration

From: http://jamis.jamisbuck.org/articles/2005/12/14/two-tips-for-working-with-databases-in-rails

The second tip is handy when you’re working on a migration. I find that the process (for me) works like this:

* Create the migration and run it.
* Discover I forgot something.
* Migrate down to the previous schema version.
* Change the migration and run it again.

(Repeat as necessary.) However, being the imperfect programmer that I am, I find that I often implement the #down method incorrectly, forgetting to drop a table or remove a column. Thus, when I try to run the migration again, it fails saying that the table/column already exists.

Using script/console and ActiveRecord::Schema, it becomes a cinch to clean up the artifacts:
ActiveRecord::Schema.define do
    drop_table :foos
    remove_column :bars, :blitz
    remove_column :bars, :things
  end
« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS