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

Matt Scilipoti

« Newer Snippets
Older Snippets »
Showing 11-20 of 46 total

Connect to MS SQL Server via ODBC vs OLEDB.

From http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer:

Connecting via the OLEDB adaptor seems to have it’s quirks. Another posibility is to connect via ODBC (tested with Rails 1.1.6)

e.g. for a trusted connection
development:
  adapter: sqlserver
  mode: odbc
  dsn: Driver={SQL Server};Server=<your server>;Database=<your db>;Trusted_Connection=yes;

Slipstream WinXP

From http://www.onecomputerguy.com/install/winxp_slipstream.htm:
Copy the contents of the WinXP CD to a dir (e.g. c:\cd\winxp).
Download the SP.
Run SP with -x (e.g. "xpsp2.exe -x"). This will verify, then request extractTo dir (e.g. c:\cd\xp_sp2).
ChangeDir to ExtractedSPDir\i386\update (e.g. c:\cd\xp_sp2\i386\update).
 c:\cd\xp_sp2\i386\update> update.exe  -S:c:\cd\winxp

Tagging Your Test Cases

From http://www.railtie.net/articles/2006/09/17/tagging-your-test-cases:
Here's a quick way to follow your tests a little more closely in your test.log. In your test setup, add the following line:
def setup
  RAILS_DEFAULT_LOGGER.debug "\n\e[0;31mRUNNING TEST CASE: #{name}\e[m\n"
end

Create Graphiz image from Dot file using DotNet

This is from http://vv.cs.byu.edu/cs312-003/archives/2005/01/graph_visualiza.html. Go there for more info.
 private void button2_Click(object sender, System.EventArgs e) {

string strCmdLine1 = "-Tsvg -o c:\\tmp\\foo.xml c:\\tmp\\ER.dot";
string strCmdLine2 = "-Tsvg -o c:\\tmp\\foo.xml c:\\tmp\\Heawood.dot";
System.Diagnostics.Process p = new System.Diagnostics.Process();

p.StartInfo.FileName = "\"C:\\Program Files\\ATT\\Graphviz\\bin\\dot.exe\"";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
if (graphIndex == 0)
p.StartInfo.Arguments = strCmdLine2;
else
p.StartInfo.Arguments = strCmdLine1;

p.Start();
p.WaitForExit();

axSVGCtl1.reload();
graphIndex = (graphIndex + 1) % 2;
}

smart plaintext wrapping

From http://blog.evanweaver.com/articles/2006/09/03/smart-plaintext-wrapping:
>>>
Very often you need to break plaintext at a specific width while retaining readability.
#!/opt/local/bin/ruby

class String

  def wrap(width, hanging_indent = 0, magic_lists = false)
    lines = self.split(/\n/)

    lines.collect! do |line|

      if magic_lists 
        line =~ /^([\s\-\d\.\:]*\s)/
      else 
        line =~ /^([\s]*\s)/
      end

      indent = $1.length + hanging_indent rescue hanging_indent

      buffer = ""
      first = true

      while line.length > 0
        first ? (i, first = 0, false) : i = indent              
        pos = width - i

        if line.length > pos and line[0..pos] =~ /^(.+)\s/
          subline = $1
        else 
          subline = line[0..pos]
        end
        buffer += " " * i + subline + "\n"
        line.tail!(subline.length)
      end
      buffer[0..-2]
    end

    lines.join("\n")

  end

  def tail!(pos)
    self[0..pos] = ""
    strip!
  end

end

if __FILE__ == $0
  File.open(ARGV[0]) do |f|
    puts f.read.wrap(ARGV[1].to_i, ARGV[2].to_i, ARGV[3] == "true")
  end
end

<<<

Verify Dates in Rails

From http://www.railtie.net/articles/2006/09/07/validate-dates-in-your-models:
>>>

The thing I find really nice is that if you pass it a malformed date, it returns nil. This means, in your model validations, you can add:
require 'chronic'

class Meeting < ActiveRecord::Base

  def validation
    errors.add :meeting_date, 'is not a valid date' if Chronic.parse(meeting_date.to_s).nil?
  end

end

<<<
Other Chronic examples:
>>>
mojombo in #caboose, just released his first version of Chronic, a new Ruby Gem for natural language processing of Dates and Times.
gem install chronic

irb:>
Chronic.parse('tomorrow')
    #=> Mon Aug 28 12:00:00 PDT 2006

Chronic.parse('monday', :context => :past)
    #=> Mon Aug 21 12:00:00 PDT 2006

Chronic.parse('this tuesday 5:00')
    #=> Tue Aug 29 17:00:00 PDT 2006

Chronic.parse('this tuesday 5:00', :ambiguous_time_range => :none)
    #=> Tue Aug 29 05:00:00 PDT 2006

Chronic.parse('may 27th', :now => Time.local(2000, 1, 1))
    #=> Sat May 27 12:00:00 PDT 2000

Chronic.parse('may 27th', :guess => false)
    #=> Sun May 27 00:00:00 PDT 2007..Mon May 28 00:00:00 PDT 2007


<<<

Rake Task for BDD Docs

From http://www.reevoo.com/blogs/bengriffiths/2005/06/24/a-test-by-any-other-name/:

We find that the pattern ‘test_should_***_on_***’ a useful way of naming tests – it’s an idea stolen from JBehave . If this test were to fail, I’m reminded that I should (!) ask myself the question ‘should the class I’m testing do this?’ before I go on a bug-hunt. The other advantage is that I can use my test classes to generate some simple documentation for my classes. Here’s a rake target that can do just that:


desc "Generate agiledox-like documentation for tests"
task :agiledox do
  tests = FileList['test/**/*_test.rb']
  tests.each do |file|
    m = %r".*/([^/].*)_test.rb".match(file)
    puts m[1]+" should:\n"
    test_definitions = File::readlines(file).select {|line| line =~ /.*def test.*/}
    test_definitions.each do |definition|
      m = %r"test_(should_)?(.*)".match(definition)
      puts " - "+m[2].gsub(/_/," ")
    end
  puts "\n"
 end
end

An example from our codebase, typing rake agiledox generates:

security_controller should:
- redirect to page stored in session on successful login
- store user object in session on successful login
- redirect to page stored in session after signup
- store user object in session after signup
- reject signup when passwords do not match
- reject signup when login too short
- report both errors if passwords dont match and username too short
- not store user in session if password not correct on signup
- remain on login page if password not correct on signup
- remove user from session on log out

ubuntu linux default locale

Overheard during a SliceHost chat:

David B.
I fixed the locale issues. For the curious this is all it takes for a default locale:
locale-gen en_US.UTF-8

full text searching for ri content

From ZenSpider, http://blog.zenspider.com/archives/2006/08/full_text_searc.html:
Check it out. Quick and dirty searching of ri content:

Updated using: http://blog.zenspider.com/archives/2006/08/new_and_improve.html

They added path independence and searching of gems and local installed ri/rdoc. Enjoy!
#!/usr/local/bin/ruby -w

require 'rdoc/ri/ri_paths'
require 'find'
require 'yaml'

search = ARGV.shift

puts "Searching for #{search}"
puts

dirs = RI::Paths::PATH
dirs.each do |dir|
  Dir.chdir dir do
    Find.find('.') do |path|
      next unless test ?f, path
      yaml = File.read path
      if yaml =~ /#{search}/io then
        full_name = $1 if yaml[/full_name: (.*)/]
        puts "** FOUND IN: #{full_name}"
        
        data = YAML.load yaml.gsub(/ \!.*/, '')
        desc = data['comment'].map { |x| x.values }.flatten.join("\n").gsub(/&quot;/, "'").gsub(/&lt;/, "<").gsub(/&gt;/, ">").gsub(/&amp;/, "&")
        puts
        puts desc
        puts
      end
    end
  end
end

Lets you do stuff like:
% ./risearch.rb duplicate
Searching for duplicate
[...]
** FOUND IN: Array#uniq!

Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
   a = [ 'a', 'a', 'b', 'b', 'c' ]
   a.uniq!   #=> ['a', 'b', 'c']
   b = [ 'a', 'b', 'c' ]
   b.uniq!   #=> nil

** FOUND IN: Array#|

Set Union---Returns a new array by joining this array with other_array, removing duplicates.
   [ 'a', 'b', 'c' ] | [ 'c', 'd', 'a' ]
          #=> [ 'a', 'b', 'c', 'd' ]
[...]

Posted by zenspider at August 15, 2006 04:16 PM | Bookmark This
Categories: Rails , Ruby , Toys

Linux : Open, Copy and Paste, Mouse or keyboard? Who cares - with this.

From http://news.u32.net/articles/2006/07/31/shell-vs-file-manager:

Would you rather click on files or type at them? This is the root of a dichotomy that has existed ever since day one (day one was some time in mid 1964 according to my sources). Except for TwoDudes' short-lived FinderShell, I have never seen a program that effectively combines the strengths of each environment. Why must we choose?

Here's a stupid trick that makes it easier to move data from mouse mode to finger mode and back. Add the following to ~/.bashrc or equivalent:
alias open=gnome-open
alias copy="xclip -i"
alias paste="xclip -o"

Now open opens pretty much anything:
open mswd.doc

opens mswd.doc in OpenOffice or AbiWord (whatever your default is).
open tt.mov

opens the QuickTime clip in a movie player.
open .

opens a new Nautilus window showing the current directory.
open http://u32.net

opens a new browser window showing this blog.

And copy and paste manipulate the clipboard:

* paste (with no arguments) prints the clipboard to the terminal.
* Select some text in a text editor and then run paste > newfile to save that selection to a file.
* copy bigfile copies the contents of bigfile into the clipboard.
* copy *.log copies the contents of all log files in the current directory.

Of course, you can combine these tricks:
paste | tr a-z A-Z | copy

converts the contents of the clipboard to upper-case.
paste | tr A-Za-z N-ZA-Mn-za-m | copy

will rot13 the clipboard.

More in blog post...
« Newer Snippets
Older Snippets »
Showing 11-20 of 46 total