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 28 total  RSS 

How to eat an elephant in Java

How do you eat an elephant? Well, 'bite by bite', they told me. In Java, this may look like this:

  Elephant elephant = ...; // get the elephant from somewhere

  while (!elephant.isEatenCompletely()) {
    elephant.haveOneBite();
  }



Why am I writing this? Well, simply to test my dzone account ;)

Point Inside a Polygon //JavaScript Function


Checks whether a point is inside a polygon.
Adapted from: [http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html]

[UPDATED CODE AND HELP CAN BE FOUND HERE: Point Inside a Polygon]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/is-point-in-poly [v1.0]

function isPointInPoly(poly, pt){
	for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
		((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
		&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
		&& (c = !c);
	return c;
}


Example

<script type="text/javascript">
//<![CDATA[

points = [
	{x: 0, y: 0},
	{x: 0, y: 50},
	{x: 50, y: 10},
	{x: -50, y: -10},
	{x: 0, y: -50},
	{x: 0, y: 0}
];

alert(isPointInPoly(points, {x: 10, y: 10}) ? "In" : "Out");

//]]>
</script>

Make Time "Stand Still" in Ruby

When writing tests, it's sometimes difficult to test results of methods that use current time. Two calls to Time.now can give different results and cause test failures. Here is some code that lets you execute a block during which Time.now will return a consistent value:

class Time

  # this code adds a Time.freeze method to make time "stand still"
  # during execution of a block. This can be helpful during testing of
  # methods that depend on Time.new or Time.now
  #
  # Example:
  #
  #   Time.freeze do
  #      puts Time.new.to_f
  #      # ... do stuff; real time passes
  #      puts Time.new.to_f     # outputs same time as above
  #   end
  #   # ... time returns to normal
  #
  # An optional Time object may be passed to freeze to a specific time:
  #
  #   Time.freeze(Time.at(2007, 11, 15)) do
  #      # ...
  #   end
  #
  # While inside the block, Time.frozen? will return true

  class << self

    def now
      @time || orig_new
    end

    alias_method :orig_freeze, :freeze
    alias_method :orig_new, :new
    alias_method :new, :now

    # makes time "stand still" during execution of a block. if no time is
    # supplied, the current time is used. While in the block, Time.new and
    # Time.now will always return the "frozen" value.
    def freeze(time = nil)
      raise "A block is required" unless block_given?
      begin
        prev = @time
        @time = time || now
        yield
      ensure
        @time = prev
      end
    end

    def frozen?
      !@time.nil?
    end

  end
end

Save db data to fixture files

rake db:fixtures:dump_all
он сохранит все данные из ваших таблиц development базы в ямлы для тестов rake

db:fixtures:dump_references
["areas","countries"]
сохранит только те таблицы которы епрописаны у него в конфиге, в данном случае это

namespace :db do
  namespace :fixtures do

    desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
    task :dump_all => :environment do
      sql = "SELECT * FROM %s"
      skip_tables = ["schema_info"]
      ActiveRecord::Base.establish_connection(:development)
      (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
        i = "000"
        File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
  
  namespace :fixtures do
    desc 'Create YAML test fixtures for references. Defaults to development database. 
    Set RAILS_ENV to override.'
    task :dump_references => :environment do
      sql = "SELECT * FROM %s"
      dump_tables = ["areas","countries"]
      ActiveRecord::Base.establish_connection(:development)
      dump_tables.each do |table_name|
        i = "000"
        file_name = "#{RAILS_ROOT}/test/fixtures/#{table_name}.yml"
        p "Fixture save for table #{table_name} to #{file_name}"
        File.open(file_name, 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
end 

A simple test case using Ruby and XML - Part III

This Ruby CGI script tests a class, by reading the testdata from an XML file, then outputs the result to the web browser. Refer to parts 1 http://urltea.com/1p7h [dzone.com], and II http://urltea.com/1p7m [dzone.com]

#file: test-feed.cgi

require 'test_feed'

puts "Content-Type: text/xml"
puts

puts "<test_report>"
tf = Test_feed.new()
puts tf.plan
puts "<actual>"
tf.print('create_file', tf.tested)
puts "</actual>"
puts "</test_report>"

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?


dit is een test

// description of your code here

// insert code here..

truncate Rails development/test logs

In rails applications development.log and test.log like to grow forever, which takes up space and makes them slow to grep. If I just delete them running processes with logs open might get confused. So I can use truncate instead:

truncate ~/www/*/log/*.log


Even easier, ask cron to do it for me every night:
4 22 * * * * truncate -s 0k  ~/www/*/log/*.log

test

// description of your code here

warum geht das nicht?
« Newer Snippets
Older Snippets »
Showing 1-10 of 28 total  RSS