#!/usr/local/bin/ruby
# -*- encoding:utf-8 -*-
module Conv
TABLE = ('!'..'~').to_a
def to_s_conv(base, rs=[])
q, r = self.divmod base
rs.unshift TABLE[r]
q.to_s_conv(base, rs) if q > 0
rs.join
end
def to_i_conv(base)
self.split(//).reverse.map.with_index { |s, i| TABLE.index(s).to_i * base**i }.inject(:+)
end
end
class Fixnum
include Conv
alias to_s_orig to_s
def to_s(base=10)
base > 36 ? to_s_conv(base) : to_s_orig(base)
end
end
class Bignum
include Conv
alias to_s_orig to_s
def to_s(base=10)
base > 36 ? to_s_conv(base) : to_s_orig(base)
end
end
class String
include Conv
alias to_i_orig to_i
def to_i(base=10)
base > 36 ? to_i_conv(base) : to_i_orig(base)
end
end
x = 200_000_000_000
(2..94).each do |i|
s = x.to_s(i)
print "#{i} => #{s}:#{s.to_i(i)}\n"
end
Friday, July 23, 2010
conv.rb
to_s(base), to_i(base)を94まで対応
Thursday, July 22, 2010
TinyURL with Ruby
Points
- urlをDBのidに置き換え、さらにInteger#to_i(36)を使って短縮する
- cssをw3cサイトから借用
- 環境変数envから参照元つまり自サイトのurlを取得
%w(rubygems sinatra dm-core dm-timestamps dm-migrations uri).each { |lib| require lib }
configure :development do
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/chop.db")
end
get '/' do
haml :index
end
post '/' do
uri = URI::parse(params[:original])
raise "Invalid URL" unless [URI::HTTP, URI::HTTPS].any? { |scm| uri.kind_of? scm }
@url = Url.first_or_create(:original => uri.to_s)
haml :index
end
get '/:chopped' do |chopped|
redirect Url.first(:id => chopped.to_i(36)).original
end
error do
'Sorry there was a nasty error - ' + env['sinatra.error'].name
end
class Url
include DataMapper::Resource
property :id, Serial
property :original, String, :length => 255
property :created_at, DateTime
def chopped
self.id.to_s(36)
end
end
__END__
@@ layout
!!! 1.1
%html
%head
%title Chop!
%link{:rel => 'stylesheet', :href => 'http://www.w3.org/StyleSheets/Core/Modernist', :type => 'text/css'}
%body
= yield
@@ index
%h1.title Chop!
- unless @url.nil?
%code= @url.original
chopped to
%a{:href => env['HTTP_REFERER'] + @url.chopped}
= env['HTTP_REFERER'] + @url.chopped
%form{:method => 'post', :action => '/'}
Chop this:
%input{:type => 'text', :name => 'original', :size => '50'}
%input{:type => 'submit', :value => 'chop!'}
%small copyright ©
Friday, July 09, 2010
Monday, June 28, 2010
rmagick install
rmagickでフォントが読み込めないので
以下のサイトに従ってすべてを再インストール
http://web.elctech.com/2007/02/24/installing-rmagick-properly-in-osx/
うまくいかない
で
を追加
$ sudo port install imagemagick +myvar でインストール
以下のサイトに従ってすべてを再インストール
http://web.elctech.com/2007/02/24/installing-rmagick-properly-in-osx/
うまくいかない
で
$ sudo port edit imagemagick
variants myvar {
configure.args-append --with-gs-font-dir=/opt/local/share/ghostscript/fonts
}
を追加
$ sudo port install imagemagick +myvar でインストール
Wednesday, June 16, 2010
Saturday, June 05, 2010
Nokogiri libxml2 version warning
gem install nokogiri -- --with-xml2-include=/opt/local/include/libxml2 --with-xml2-lib=/opt/local/lib --with-xslt-dir=/opt/local
http://wiki.github.com/tenderlove/nokogiri/what-to-do-if-libxml2-is-being-a-jerk
Friday, June 04, 2010
GistのコードをGitHubに移管する
GistのコードをGitHubに移管する
- GitHubで新規プロジェクトをcreateする
- gistのremote nameを変える:git remote rename origin gist
- gistのworking directoryでそのremote(origin)を追加する: git remote add origin git@github.com:melborne/graphaz.git
- 新たなremoteにpushする: git push origin master
Monday, May 31, 2010
vim
VIMの環境設定
installされているVIMには以下のものがある
それでvi, vimで2が、mvimで3が呼ばれるように.zshrcを設定した。
installされているVIMには以下のものがある
- /usr/bin/vim or /usr/bin/vi
- /opt/local/bin/vim or /opt/local/bin/vi
- /Applications/MacVim.app "$@"'
- /Applications/Macport/Vim.app
それでvi, vimで2が、mvimで3が呼ばれるように.zshrcを設定した。
export EDITOR='/opt/local/bin/vim'
alias vi='$EDITOR'
alias vim='$EDITOR'
alias mvim='env LANG=ja_JP.UTF-8 open -a /Applications/MacVim.app "$@"'
Wednesday, May 26, 2010
post a bloops sound file to HatenaDiary
Bloopsで作った音楽をはてダにアップする手順
- SoundFlowerをインストールして、システムーサウンドの設定でその出力をsoundflower 2chに、GarageBandの設定で入力をsoundflower 2chにする
- GarageBandで自然音源からのトラックを作り、録音を開始。すぐにbloopsのプログラムを実行
- GarageBandで作成したファイルをiTunesで共有
- iTunesの一般設定ー読み込み設定でmp3を選び、ファイルをmp3に変換
- mp3ファイルをDropboxのPublicフォルダに置き、そのpublic linkを取得
- はてダで、[http://dl.dropbox.com/u/58702/SuperMarioBrothers.mp3:sound]のようにすれば完了
Friday, May 21, 2010
sound for termtter
sound for termtter
def self.bloops
b = Bloops.new
b.tempo = 216
sound = b.sound Bloops::SQUARE
sound.volume = 0.4
#Mario:d=16,o=6,b=100:
sound.sustain = 0.2
#sound.attack = 0.2
sound.decay = 0.5
b.tune sound, "32 + C E F# 8:A G E C - 8:A 8:F# 8:F# 8:F# 2:G"
b.play
sleep 1 while !b.stopped?
end
register_hook(
:name => :bloops,
:point => :output,
:exec => lambda { |statuses, event|
if event == :update_friends_timeline
bloops if statuses.any? { |s| s.text =~ /t/i }
end
}
)
bloopsaphone install
bloopsaphone install
sudo port install portaudio
sudo gem install bloopsaphone -- --with-opt-lib=/opt/local/lib --with-opt-include=/opt/local/include
Tuesday, May 18, 2010
ruby:rename_file
rename_file.rb
#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
def main
batch_name, file_type = user_inputs
cnt = 0
Dir["*.#{file_type}"].each_with_index do |file, i|
new_name = "#{batch_name}#{i+1}.#{file_type}"
unless File.exist?(new_name)
File.rename(file, new_name)
cnt += 1
end
end
puts "#{cnt} files renamed."
rescue => e
puts e
end
def user_inputs
batch_name = ARGV[0] || (print "Input batch name: "; STDIN.gets.chomp)
file_type = ARGV[1] || (print "Input target file type: "; STDIN.gets.downcase.chomp)
puts "Filename: '#{batch_name}[number].#{file_type}' OK? (y|n)"
exit unless STDIN.gets =~ /^y/i
return batch_name, file_type
end
main
Sunday, May 16, 2010
Saturday, May 15, 2010
Interpreter
tc_ast.rb
require "test/unit"ast.rb
require_relative "ast"
class TestAst < Test::Unit::TestCase
def test_bigger
assert_equal((91..100).to_a, bigger(90).evaluate(1..100))
end
def test_smaller
assert_equal([1,4,9,12], smaller(15).evaluate([1,20,4,66,23,9,40,12]))
end
def test_even
assert_equal([2,4,6,8,10,12,14,16], even.evaluate(1..16))
end
def test_odd
assert_equal([1,3,5,7,9,11,13,15], odd.evaluate(1..16))
end
def test_bigger_and_even
assert_equal([32,44,56],
( bigger(30) & even ).evaluate([4,32,11,23,56,7,43,44,2,14]))
end
def test_smaller_and_odd
assert_equal([7,11,23],
( smaller(30) & odd ).evaluate([4,32,11,23,56,7,43,44,2,14]))
end
def test_bigger_or_even
assert_equal([2,4,14,32,43,44,56],
( bigger(30) | even ).evaluate([4,32,11,23,56,7,43,44,2,14]))
end
def test_smaller_or_odd
assert_equal([2,4,7,11,14,23,43],
( smaller(30) | odd ).evaluate([4,32,11,23,56,7,43,44,2,14]))
end
def test_bigger_and_even_or_smaller_and_odd
assert_equal([7,11,23,44,56],
( ( bigger(40) & even ) | ( smaller(30) & odd ))
.evaluate([4,32,11,23,56,7,43,44,2,14]))
end
end
#!/usr/local/bin/ruby
# -*- encoding:utf-8 -*-
class Expression
def evaluate(context)
context.select { |x| yield(x) }
end
def &(other)
And.new(self, other)
end
def |(other)
Or.new(self, other)
end
end
class Bigger < Expression
def initialize(num)
@num = num
end
def evaluate(context)
super { |n| n > @num }
end
end
class Smaller < Expression
def initialize(num)
@num = num
end
def evaluate(context)
super { |n| n < @num }
end
end
class Even < Expression
def evaluate(context)
super { |n| n.even? }
end
end
class Odd < Expression
def evaluate(context)
super { |n| n.odd? }
end
end
class And < Expression
def initialize(exp1, exp2)
@exp1, @exp2 = exp1, exp2
end
def evaluate(context)
(@exp1.evaluate(context) & @exp2.evaluate(context)).sort
end
end
class Or < Expression
def initialize(exp1, exp2)
@exp1, @exp2 = exp1, exp2
end
def evaluate(context)
(@exp1.evaluate(context) | @exp2.evaluate(context)).sort
end
end
def bigger(num)
Bigger.new(num)
end
def smaller(num)
Smaller.new(num)
end
def even
Even.new
end
def odd
Odd.new
end
interpreter = bigger(70) & even | smaller(20) & odd
p interpreter.evaluate(1..100)
def extract(context)
(context.select { |n| n > 70 }.select { |n| n.even? } |
context.select { |n| n < 20 }.select { |n| n.odd? }).sort
end
p extract(1..100)
Thursday, May 13, 2010
Interpreter Pattern
#!/usr/local/bin/ruby
# -*- encoding:utf-8 -*-
require "find"
class Expression
def |(other)
Or.new(self, other)
end
def &(other)
And.new(self, other)
end
end
class All < Expression
def evaluate(dir)
results = []
Find.find(dir) do |p|
next unless File.file?(p)
results << p
end
results
end
end
class FileName < Expression
def initialize(pattern)
@pattern = pattern
end
def evaluate(dir)
results = []
Find.find(dir) do |p|
next unless File.file?(p)
name = File.basename(p)
results << p if File.fnmatch(@pattern, name)
end
results
end
end
class Not < Expression
def initialize(expression)
@expression = expression
end
def evaluate(dir)
All.new.evaluate(dir) - @expression.evaluate(dir)
end
end
class Or < Expression
def initialize(expression1, expression2)
@expression1, @expression2 = expression1, expression2
end
def evaluate(dir)
result1 =@expression1.evaluate(dir)
result2 =@expression2.evaluate(dir)
(result1 + result2).sort.uniq
end
end
class Bigger < Expression
def initialize(size)
@size = size
end
def evaluate(dir)
results = []
Find.find(dir) do |p|
next unless File.file?(p)
name = File.basename(p)
results << p if File.size(p) > @size
end
results
end
end
class Writable < Expression
def evaluate(dir)
results = []
Find.find(dir) do |p|
next unless File.file?(p)
name = File.basename(p)
results << p if File.writable?(p)
end
results
end
end
class And < Expression
def initialize(expression1, expression2)
@expression1, @expression2 = expression1, expression2
end
def evaluate(dir)
result1 =@expression1.evaluate(dir)
result2 =@expression2.evaluate(dir)
(result1 & result2)
end
end
def all
All.new
end
def bigger(size)
Bigger.new(size)
end
def file_name(pattern)
FileName.new(pattern)
end
def except(expression)
Not.new(expression)
end
def writable
Writable.new
end
p ((bigger(1000) & except(writable)) | file_name('*.mp3')).evaluate('/Users/keyes/Desktop/')
Tuesday, May 11, 2010
Friday, May 07, 2010
体調不良
体調不良だ
月曜日にスタバに行ってからおかしい
その日は暑くてスタバでは冷房が入っていてそれで体調を崩したらしい
それと共に複数の病気が同時並行的に襲ってきている
月曜日にスタバに行ってからおかしい
その日は暑くてスタバでは冷房が入っていてそれで体調を崩したらしい
それと共に複数の病気が同時並行的に襲ってきている
- 左手中指の爪の間から菌が入って指が腫れる。激痛。針で膿を出して、少し腫れと痛みは引いた。
- 右睾丸に痛み。副睾丸炎か。原因はよくわからないが、細菌性のものか。未だ痛みが引かず。
- 全体的に体がだるく、頭痛、歯痛、肩・首痛、腰痛あり。前々日指の痛みでの睡眠不足もあり、昨日は幾らでも寝られる感じ。今日はそうでもない。
Sunday, May 02, 2010
ruby DSL
#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
class Task
attr_accessor :name, :alarm, :coffee, :out
def initialize
end
def task(task_name)
@name = task_name
yield(self)
end
end
my_task = Task.new
my_task.instance_eval(DATA.read)
p my_task.name
p my_task.alarm
p my_task.coffee
p my_task.out
__END__
task 'morning' do |t|
t.alarm = '7:00'
t.coffee = :blue_mountain
t.out = '9:00'
end
fib by ruby
fib by ruby
#!/usr/local/bin/ruby
# -*- encoding:utf-8 -*-
require 'benchmark'
require "memoize"
include Memoize
def fib_time n
a, b = 0, 1
n.times do
a, b = a, a+b
end
a
end
def fib_inj n
(1..n).inject([0,1]) do |mem, i|
mem << mem[i-1] + mem[i]
end[-2]
end
def fib_inj2 n
(1..n).inject([0,1]) do |mem, i|
mem = mem[1], mem[0] + mem[1]
end[0]
end
def fib_recur n
return n if n < 2
fib_recur(n-1) + fib_recur(n-2)
end
def fib_memo n
return n if n < 2
@series ||= []
@series[n] ||= fib_memo(n-2) + fib_memo(n-1)
end
def fib_memoize n
return n if n < 2
fib_memoize(n-1) + fib_memoize(n-2)
end
memoize :fib_memoize
series = []
fib_proc = lambda do |n|
return n if n < 2
series[n] ||= fib_proc[n-1] + fib_proc[n-2]
end
def fib_proc_def(n)
series = []
_fib = lambda do |n|
return n if n < 2
series[n] ||= _fib[n-1] + _fib[n-2]
end
_fib[n]
end
N = 2500
Benchmark.bmbm do |x|
x.report "fib with time" do
fib_time N
end
x.report "fib with inject" do
fib_inj N
end
x.report "fib with inject2" do
fib_inj2 N
end
# x.report "fib with recur" do
# fib_recur N
# end
x.report "fib_memo" do
fib_memo N
end
# x.report "fib_memoize" do
# fib_memoize N
# end
x.report "fib_proc_def" do
fib_proc_def N
end
# x.report "fib_proc" do
# fib_proc[N]
# end
end
# series = []
# def fib_proc n
# return n if [0,1].include? n
# res = lambda { series[n] ||= fib_proc(n-1) + fib_proc(n-2) }
# res.call
# end
# p fib_proc(20)
Saturday, May 01, 2010
attr_accessor
attr_accessor
#!/usr/bin/env ruby -Ku
# -*- encoding: utf-8 -*-
class T
def self.access_attribute(name)
define_method(name) do
instance_variable_get("@#{name}")
end
define_method("#{name}=") do |word|
instance_variable_set("@#{name}", word)
end
end
end
class D < T
access_attribute :hello
def initialize(hello)
@hello = hello
end
end
d = D.new('Yah!')
p d.hello
d.hello = "YoY"
p d.hello
Subscribe to:
Posts (Atom)