Saturday, March 27, 2010

Termcolor example

# -*- coding: utf-8 -*-
require 'rubygems'
require 'termcolor'

puts TermColor.parse <<EOS

    <on_blue><white><bold>TermColor Example</bold></white></on_blue>

    <on_green><white>Termcolor</white></on_green> is a library for <red><bold>ANSI</bold></red> <blink><blue>c</blue><yellow>o</yellow><green>l</green>o<red>r</red></blink> formatting like <on_magenta>HTML</on_magenta>
    for output in terminal.

EOS

["REVERSE", "ON_RED", "DARK", "MAGENTA", "ColorScheme", "RESET", "RED", "ON_BLUE", "BLINK", "ON_BLACK", "BOLD", "BLUE", "ON_WHITE", "QuestionError", "CLEAR", "BLACK", "ON_YELLOW", "SampleColorScheme", "UNDERSCORE", "WHITE", "SystemExtensions", "ERASE_CHAR", "YELLOW", "ON_CYAN", "CONCEALED", "ON_GREEN", "CHARACTER_MODE", "UNDERLINE", "CYAN", "Question", "Menu", "VERSION", "ERASE_LINE", "GREEN", "ON_MAGENTA"]

Thursday, March 25, 2010

macのIPアドレス設定

  • 各マシンのIPアドレス設定は、Router(RT-200NE)のDHCPで自動割り当てしている
  • RouterのIPは192.168.1.1でマシンへの割り当ての開始IPは192.168.1.2で個数は50個にしている
  • よって各マシンのIPアドレスは変わり得るので、ローカルでのマシンの特定はそのホスト名で行う
  • host名はhostnameコマンドで得られ、現在はkeyesmac.localとcoosamac.localになっている
  • coosa_login.sh, backup_*.shの設定をこれにしたがって変えた

Test with outside resources with stub or mock ::Ruby Best Practices

user inputに係るテスト
  1. StringIOによるスタブ
  2. flexmock libraryを使ったスタブ

tc_question.rb

require "test/unit"

require_relative "question"
require_relative "test_unit_extensions"
require "flexmock/test_unit"
#require "stringio"

class TestQuestion < Test::Unit::TestCase
  def setup
   # @input = StringIO.new
   # @output = StringIO.new
    @input = flexmock("input")
    @output = flexmock("output")
    @questioner = Questioner.new(@input, @output)
    @question = "Are you happy?"
  end

  %w(y Y YeS YES yes).each do |yes|
    must "return true when parsing #{yes}" do
      expect_output @question
      provide_input(yes)
      assert @questioner.ask(@question), "Expect #{yes} to be true"
    end
  end

  %w(n N no nO).each do |no|
    must "return false when parsing #{no}" do
      expect_output @question
      provide_input(no)
      assert ! @questioner.ask(@question), "Expect #{no} to be false"
    end
  end

  [["y", true],["n", false]].each do |input, state|
    must "conginue to ask for inpu until given #{input}" do
      %w(Yesterday North kittens).each do |i|
        expect_output @question
        provide_input(i)
        expect_output "I don't understand."
      end
      expect_output @question
      provide_input(input)
      assert_equal state, @questioner.ask(@question)
    end
  end


#  must "respond 'Good I'm Grad' when inquire_about_happiness gets 'yes'" do
#    def @questioner.ask(quesiotn); true; end
#    assert_equal "Good I'm Glad", @questioner.inquire_about_happiness
#  end
#
#  must "respond 'That's Too Bad' when inquire_about_happiness gets 'no'" do
#    def @questioner.ask(quesiotn); false; end
#    assert_equal "That's Too Bad", @questioner.inquire_about_happiness
#  end

  must "respond 'Good I'm Grad' when inquire_about_happiness gets 'yes'" do
    stubbed = flexmock(@questioner, :ask => true)
    assert_equal "Good I'm Glad", stubbed.inquire_about_happiness
  end

  must "respond 'That's Too Bad' when inquire_about_happiness gets 'no'" do
    stubbed = flexmock(@questioner, :ask => false)
    assert_equal "That's Too Bad", stubbed.inquire_about_happiness
  end

  def provide_input(string)
   # @input << string
   # @input.rewind
    @input.should_receive(:gets => string).once
  end

  def expect_output(string)
    # assert_equal string, @output.string
    @output.should_receive(:puts).with(string).once
  end
end


question.rb
class Questioner
  def initialize(_in=STDIN, out=STDOUT)
    @input = _in
    @output = out
  end

  def inquire_about_happiness
    ask("Are you happy?") ? "Good I'm Glad" : "That's Too Bad"
  end

  def ask(question)
    @output.puts question
    response = yes_or_no(@input.gets.chomp)
    response.nil? ? ask(question) : response
  end

  def yes_or_no(response)
    case response
    when /^y(es)?$/i
      true
    when /^no?$/i
      false
    else
      @output.puts "I don't understand."
      nil
    end
  end
end

if $0 == __FILE__
  qs = Questioner.new
  p qs.inquire_about_happiness
end



Wednesday, March 24, 2010

QuickSilver Scoring method

class String
  def to_score(abbrev)
    return 0.9 if abbrev.empty?
    return 0.0 if length < abbrev.length

    tail = ""
    loop do
      return 0 if abbrev.empty?
      unless md = match(/#{abbrev}/i)
        abbrev, tail = abbrev.split_at(-1)
        next
      else
        remaining_score = md.post_match.to_score(tail)
        return calc_score(md, remaining_score)
      end
    end
  end

  protected
  def calc_score(md, remaining_score)
    if remaining_score.zero?
      0
    else
      score = (1 * md.to_s.length) + (remaining_score * md.post_match.length)
      if md.pre_match =~ /[\s_]+$/
        score += 0.85 * (md.pre_match.length - $&.length) + 1 * $&.length
      elsif !md.pre_match.empty? and md.to_s =~ /^[A-Z]/
        score += 0.85 * md.pre_match.gsub(/[A-Z]/, "").length
      end
      score / self.length
    end
  end

  def split_at(index)
    return slice(0...index), ( slice(index..-1) || "" )
  end
end

Tuesday, March 23, 2010

Test::Ruby Best Practices


-Keep your test cases atomic.
#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
require "test/unit"
require_relative "test_unit_extensions"
require_relative "prawn"

class TestInlineStyleParsing < Test::Unit::TestCase
  def setup
    @parser = Prawn::Document::Text::StyleParser
  end

  must "parse italic tags" do
    assert_equal ["Hello ", "<i>", "Fine", "</i>", " World"],
                  @parser.process("Hello <i>Fine</i> World")
  end

  must "parse bold tags" do
    assert_equal ["Some very ", "<b>", "bold text", "</b>"],
                  @parser.process("Some very <b>bold text</b>")
  end

  must "parse mixed italic and bold tags" do
    assert_equal ["Hello ", "<i>", "Fine ", "<b>", "World", "</b>", "</i>"],
                  @parser.process("Hello <i>Fine <b>World</b></i>")
  end

  must "not split out other tags than <i> <b> </i> </b>" do
    assert_equal ["Hello <indigo>Ch", "</b>", "arl", "</b>", "ie</indigo>"],
                  @parser.process("Hello <indigo>Ch</b>arl</b>ie</indigo>")
  end

  must "be able to check whether a string needs to be parsed" do
    assert ! @parser.style_tag?("Hello World")
    assert @parser.style_tag?("Hello <i>Fine</i> World")
  end
end

#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
module StyleParser
  extend self

  TAG_PATTERN = %r{(</?[ib]>)}

  def process(text)
    text.split(TAG_PATTERN).reject { |x| x.empty? }
  end

  def style_tag?(text)
    !!(text =~ TAG_PATTERN)
  end
end

class Prawn
  class Document
    class Text
      include StyleParser
    end
  end
end
 
-Test not only input & output but also error cases.
#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
require "test/unit"
require_relative "test_unit_extensions"
require_relative "lockbox"

class LockBoxTest < Test::Unit::TestCase
  def setup
    @lock_box = LockBox.new(password: "secret", content: "My Secret Message")
  end

  must "raise an error when an invalid password is used" do
    assert_raises(LockBox::InvalidPassword) do
      @lock_box.unlock("kitten")
    end
  end

  must "Not raise error when a valid password is used" do
    assert_nothing_raised do
      @lock_box.unlock("secret")
    end
  end

  must "prevent access to content by default" do
    assert_raises(LockBox::UnauthorizedAccess) do
      @lock_box.content
    end
  end

  must "allow access to content when box is properly unlocked" do
    assert_nothing_raised do
      @lock_box.unlock("secret")
      @lock_box.content
    end
  end
end

#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
class LockBox
  UnauthorizedAccess = Class.new(StandardError)
  InvalidPassword = Class.new(StandardError)

  def initialize(options)
    @locked = true
    @password = options[:password]
    @content = options[:content]
  end

  def unlock(pass)
    @password == pass ? @locked = false : raise(InvalidPassword)
  end

  def content
    @locked ? raise(UnauthorizedAccess) : @content
  end
end

 
-Use rake task to test multiple files.

#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
require "rake/testtask"

task  :default => [:test]

Rake::TestTask.new do |test|
  test.libs << "test"
  test.test_files = Dir["test/tc_*.rb"]
  test.verbose = true
end

Wednesday, March 17, 2010

GoodReaderの使い方

  1. WifiをONにする
  2. Folderを開き移動でサーバーへ接続を選択
  3. アドレス:http://10.0.1.2:8080に接続
  4. GoodReaderを開き接続アイコンクリック
  5. 接続が完了するとMac側でフォルダが開くのでそこにファイルをドロップ

Tuesday, March 16, 2010

火曜日

あと少ししか生きられないとして何したい?
という話でmacbook買いたいと答えたら
そんなにほしいなら買ったほうがいいんじゃないかと展開
さちが盛り上がってる
macbookは去年の6月にリニューアルされてるから
そろそろまたリニューアルの可能性ありなので
少し様子見ながら検討したい

久しぶりに新宿へ
OIOIのパン屋でパンを買って屋上で食べる
GW並の日差しを浴びながら
パンのセレクトに成功し満足
なぜか人が少ない
雑貨店でメモ帳購入

AUDTCを換金するためルミネへ
ところが閉店で西口みずほへ
AUD1000が8万イェンに!
何かを疑われたのか担当にオーストラリアの近況を聞かれる

UNIQLOを経由し高島屋&紀伊国屋へ
1時間フリータイム
興味のある本数冊発見
さちは鍋の把手引取りとアスパラ買う
疲れるもなんとか歩いて帰宅

あとなんだっけ?

Mac地デジ録画検討するもあえなく撃沈!

macで地デジを見たり録画したりできる製品があるというので調べてみた

CaptyTV Hi-Vision(PIX-DT181-PU0) - 製品特長 | 株式会社ピクセラ http://www.pixela.co.jp/products/tv_capture/captytv_hi_vision_pix_dt181_pu0/index.html

室内アンテナと合わせて3万以内で買えて
画質も申し分ないし、BSデジタルまで見れるらしい
Macを起動していなくても予約録画ができるらしい
リモコンで操作ができて追っかけ再生なんかもできるらしい
アンテナは室内でも十分キレイに映るらしい
DVDに焼くこともできるらしいから
そこからiPodでも見れるかもしれない

ところが!

Tiger非対応!

さらに!

Intel Core Duo!

残念ながらわが家のmac miniでは視聴できません...

Monday, March 15, 2010

termiosのインストール

これを使えばterminalでechoを無くしたり
リターンしないで入力を受け付けたりするようにできる

gem install termiosするも1.9.2も1.8.7もうまくインストールがいかない
arika..githubからソースをDLしてインストール

tar zxvf file.gz

ruby extconf.rb
make && make install
これでうまくいった

Saturday, March 13, 2010

rb-appscriptにはASDictionaryとASTranslateが必須

ASDictionaryは各アプリ毎のappscript APIの辞書
ASTranslateはapplescriptをruby scriptに変換するツール
これは必須

Barbar Sati

I had my hair cut today by Sati!
very short, but i like it.

iTermとMacVimのWindowの透過度をkeyboard shortcutで変える

iTerm
  1. apple scriptで以下のようなtransparency_to05.scptとtransparency_to3.scptを書く
  2. /Users/keyes/Library/Application Support/iTerm/Scripts/にそれらを置く(folderが無ければ作る)。そうするとiTermにスクリプトメニューが現れる
  3. Preference/keyboardの設定でshortcutを割り当てる
transparency_to05.scpt
tell application "iTerm"
    activate
    tell current session of the last terminal
          set transparency to "0.05"
    end tell
end tell

ちなみにapplescript で引数を渡すには以下のようにする
ほんとうはこれに引数を渡したものをセットしたい

on run argv
  tell application "iTerm"
      activate
      tell current session of the last terminal
          set transparency to item 1 of argv
      end tell
  end tell
end run

MacVim
  1. .gvimrcに以下を追加
map + :set transparency+=10<CR>
map ; :set transparency-=10<CR>

Saturday, March 06, 2010

2010年3月電気代

11,772円(521KW)
去年が 12782円ということで
あまり変化なし

Wednesday, March 03, 2010

Patent.vimの使い方

:call PatTemplate('template')
とかする
すぐ忘れるのでメモしないとダメだな