diff options
Diffstat (limited to 'sample')
147 files changed, 2744 insertions, 3495 deletions
diff --git a/sample/README b/sample/README index 796aba1dc3..b55234a947 100644 --- a/sample/README +++ b/sample/README @@ -16,7 +16,6 @@ fib.pl Fibonacci number (Perl) fib.py Fibonacci number (Python) fib.rb Fibonacci number (Ruby) fib.scm Fibonacci number (Scheme) -freq.rb count word occurrence from.rb scan mail spool fullpath.rb convert ls -lR to fullpath format less.rb front end for less @@ -29,7 +28,6 @@ mpart.rb split file int multi part observ.rb observer design pattern sample occur.pl count word occurrence (Perl) occur.rb count word occurrence (Ruby) -occur2.rb count word occurrence - another style philos.rb famous dining philosophers pi.rb calculate PI rcs.awk random character stereogram (AWK) diff --git a/sample/benchmark.rb b/sample/benchmark.rb new file mode 100644 index 0000000000..de5d66f505 --- /dev/null +++ b/sample/benchmark.rb @@ -0,0 +1,19 @@ +require 'benchmark' + +include Benchmark + +n = ARGV[0].to_i.nonzero? || 50000 +puts %Q([#{n} times iterations of `a = "1"']) +benchmark(CAPTION, 7, FORMAT) do |x| + x.report("for:") {for _ in 1..n; _ = "1"; end} # Benchmark.measure + x.report("times:") {n.times do ; _ = "1"; end} + x.report("upto:") {1.upto(n) do ; _ = "1"; end} +end + +benchmark do + [ + measure{for _ in 1..n; _ = "1"; end}, # Benchmark.measure + measure{n.times do ; _ = "1"; end}, + measure{1.upto(n) do ; _ = "1"; end} + ] +end diff --git a/sample/biorhythm.rb b/sample/biorhythm.rb index bd7c39f5aa..f5d189014b 100644 --- a/sample/biorhythm.rb +++ b/sample/biorhythm.rb @@ -25,7 +25,7 @@ # Environment: basic, dos, os9 include Math -require "date.rb" +require "date" require "optparse" require "optparse/date" @@ -36,11 +36,10 @@ def print_header(y, m, d, p, w) end def get_position(z) - pi = Math::PI z = Integer(z) - phys = (50.0 * (1.0 + sin((z / 23.0 - (z / 23)) * 360.0 * pi / 180.0))).to_i - emot = (50.0 * (1.0 + sin((z / 28.0 - (z / 28)) * 360.0 * pi / 180.0))).to_i - geist =(50.0 * (1.0 + sin((z / 33.0 - (z / 33)) * 360.0 * pi / 180.0))).to_i + phys = (50.0 * (1.0 + sin((z / 23.0 - (z / 23)) * 360.0 * PI / 180.0))).to_i + emot = (50.0 * (1.0 + sin((z / 28.0 - (z / 28)) * 360.0 * PI / 180.0))).to_i + geist =(50.0 * (1.0 + sin((z / 33.0 - (z / 33)) * 360.0 * PI / 180.0))).to_i return phys, emot, geist end diff --git a/sample/cal.rb b/sample/cal.rb index 387657490f..97f75bcf1c 100644 --- a/sample/cal.rb +++ b/sample/cal.rb @@ -71,7 +71,7 @@ class Cal ta = gr.collect{|xs| xs.join(' ')} ca = %w(January February March April May June July - August September October November December)[m - 1] + August September October November December)[m - 1] ca = ca + ' ' + y.to_s if !@opt_y ca = ca.center(@mw) @@ -132,10 +132,10 @@ if __FILE__ == $0 begin GetoptLong.new(['-c', GetoptLong::REQUIRED_ARGUMENT], - ['-j', GetoptLong::NO_ARGUMENT], - ['-m', GetoptLong::NO_ARGUMENT], - ['-t', GetoptLong::NO_ARGUMENT], - ['-y', GetoptLong::NO_ARGUMENT]). + ['-j', GetoptLong::NO_ARGUMENT], + ['-m', GetoptLong::NO_ARGUMENT], + ['-t', GetoptLong::NO_ARGUMENT], + ['-y', GetoptLong::NO_ARGUMENT]). each do |opt, arg| case opt when '-c'; cal.opt_c(arg) || raise diff --git a/sample/cbreak.rb b/sample/cbreak.rb index 76b534a76a..7f1385cce3 100644 --- a/sample/cbreak.rb +++ b/sample/cbreak.rb @@ -5,15 +5,15 @@ ECHO = 0x00000008 TIOCGETP = 0x40067408 TIOCSETP = 0x80067409 -def cbreak () +def cbreak set_cbreak(true) end -def cooked () +def cooked set_cbreak(false) end -def set_cbreak (on) +def set_cbreak(on) tty = "\0" * 256 STDIN.ioctl(TIOCGETP, tty) ttys = tty.unpack("C4 S") @@ -30,7 +30,7 @@ end cbreak(); print("this is no-echo line: "); -readline().print +readline().display cooked(); print("this is echo line: "); readline() diff --git a/sample/cgi-session-pstore.rb b/sample/cgi-session-pstore.rb new file mode 100644 index 0000000000..ec8b4989d6 --- /dev/null +++ b/sample/cgi-session-pstore.rb @@ -0,0 +1,11 @@ +require 'cgi' +require 'cgi/session/pstore' + +STDIN.reopen(IO::NULL) +cgi = CGI.new +session = CGI::Session.new(cgi, 'database_manager' => CGI::Session::PStore) +session['key'] = {'k' => 'v'} +puts session['key'].class +fail unless Hash === session['key'] +puts session['key'].inspect +fail unless session['key'].inspect == '{"k"=>"v"}' diff --git a/sample/coverage.rb b/sample/coverage.rb index 1e036f95f9..8e8d6167e2 100644 --- a/sample/coverage.rb +++ b/sample/coverage.rb @@ -38,7 +38,7 @@ at_exit do end cov else - p line + p line warn("coverage file corrupted, ignoring: #{ cfile }") break [] end diff --git a/sample/delegate.rb b/sample/delegate.rb new file mode 100644 index 0000000000..dc7ea2a0af --- /dev/null +++ b/sample/delegate.rb @@ -0,0 +1,31 @@ +require 'delegate' + +class ExtArray < DelegateClass(Array) + def initialize() + super([]) + end +end + +ary = ExtArray.new +p ary.class +ary.push 25 +p ary +ary.push 42 +ary.each {|x| p x} + +foo = Object.new +def foo.test + 25 +end +def foo.iter + yield self +end +def foo.error + raise 'this is OK' +end +foo2 = SimpleDelegator.new(foo) +p foo2 +foo2.instance_eval{print "foo\n"} +p foo.test == foo2.test # => true +p foo2.iter{[55,true]} # => true +foo2.error # raise error! diff --git a/sample/dir.rb b/sample/dir.rb index b627383946..0c55078973 100644 --- a/sample/dir.rb +++ b/sample/dir.rb @@ -3,7 +3,7 @@ dirp = Dir.open(".") for f in dirp case f - when /^\./, /~$/, /\.o/ + when /\A\./, /~\z/, /\.o\z/ # do not print else print f, "\n" diff --git a/sample/drb/README.rd.ja b/sample/drb/README.ja.rdoc index ec78dc70dd..1697b1b704 100644 --- a/sample/drb/README.rd.ja +++ b/sample/drb/README.ja.rdoc @@ -42,7 +42,7 @@ * rindas.rb --- TupleSpaceのclientでアプリケーションのserver * observerの使用例 - cdbiff - ((<URI:http://namazu.org/~satoru/cdbiff/>)) + cdbiff - http://namazu.org/~satoru/cdbiff/ * dbiff.rb --- dcdbiff server * dcdbiff.rb --- dcdbiff client @@ -50,7 +50,7 @@ * drbssl_s.rb * drbssl_c.rb -* DRbProtoclの追加例 +* DRbProtocolの追加例 * http0.rb * http0serv.rb diff --git a/sample/drb/README.rd b/sample/drb/README.rdoc index 5cf1f51913..fcb4182410 100644 --- a/sample/drb/README.rd +++ b/sample/drb/README.rdoc @@ -22,7 +22,7 @@ * dqout.rb --- client. pop DQEntry objects. * dqlib.rb --- define DQEntry -* IdConv customize demo: reference by name +* IdConv customize demo: reference by name * name.rb --- server * namec.rb --- client @@ -39,15 +39,15 @@ * rindac.rb --- service user * observer - cdbiff - ((<URI:http://namazu.org/~satoru/cdbiff/>)) + cdbiff - http://namazu.org/~satoru/cdbiff/ * dbiff.rb --- dcdbiff server * dcdbiff.rb --- dcdbiff client * drbssl * drbssl_s.rb * drbssl_c.rb - -* add DRbProtocl + +* add DRbProtocol * http0.rb * http0serv.rb diff --git a/sample/drb/acl.rb b/sample/drb/acl.rb new file mode 100644 index 0000000000..d93eb9c1fc --- /dev/null +++ b/sample/drb/acl.rb @@ -0,0 +1,15 @@ +require 'drb/acl' + +list = %w(deny all + allow 192.168.1.1 + allow ::ffff:192.168.1.2 + allow 192.168.1.3 +) + +addr = ["AF_INET", 10, "lc630", "192.168.1.3"] + +acl = ACL.new +p acl.allow_addr?(addr) + +acl = ACL.new(list, ACL::DENY_ALLOW) +p acl.allow_addr?(addr) diff --git a/sample/drb/dbiff.rb b/sample/drb/dbiff.rb index b50edc0898..290eb1d28b 100644 --- a/sample/drb/dbiff.rb +++ b/sample/drb/dbiff.rb @@ -19,18 +19,18 @@ class Biff last = Time.now while true begin - sleep(@interval) - current = File::mtime(@filename) - if current > last - changed - begin - notify_observers(@filename, current) - rescue Error - end - last = current - end + sleep(@interval) + current = File::mtime(@filename) + if current > last + changed + begin + notify_observers(@filename, current) + rescue Error + end + last = current + end rescue - next + next end end end diff --git a/sample/drb/dchats.rb b/sample/drb/dchats.rb index ccb2c7c9c5..c96486a452 100644 --- a/sample/drb/dchats.rb +++ b/sample/drb/dchats.rb @@ -2,7 +2,6 @@ distributed Ruby --- chat server Copyright (c) 1999-2000 Masatoshi SEKI =end -require 'thread' require 'drb/drb' class ChatEntry @@ -29,7 +28,7 @@ end class ChatServer def initialize - @mutex = Mutex.new + @mutex = Thread::Mutex.new @members = {} end @@ -47,16 +46,16 @@ class ChatServer msg2 = ">#{name}< #{str}" @mutex.synchronize do for m in @members.keys - begin - if m == there - @members[m].listen(msg2) - else - @members[m].listen(msg) - end - rescue - p $! - @members.delete(m) - end + begin + if m == there + @members[m].listen(msg2) + else + @members[m].listen(msg) + end + rescue + p $! + @members.delete(m) + end end end end diff --git a/sample/drb/dhasen.rb b/sample/drb/dhasen.rb index 651b9c6c8a..13ff38940e 100644 --- a/sample/drb/dhasen.rb +++ b/sample/drb/dhasen.rb @@ -17,13 +17,12 @@ require 'drb/drb' require 'chasen' -require 'thread' class Dhasen include DRbUndumped def initialize - @mutex = Mutex.new + @mutex = Thread::Mutex.new end def sparse(str, *arg) diff --git a/sample/drb/dlogd.rb b/sample/drb/dlogd.rb index fef7ca0f1d..a87e660346 100644 --- a/sample/drb/dlogd.rb +++ b/sample/drb/dlogd.rb @@ -4,13 +4,12 @@ =end require 'drb/drb' -require 'thread' class Logger def initialize(fname) @fname = fname.to_s @fp = File.open(@fname, "a+") - @queue = Queue.new + @queue = Thread::Queue.new @th = Thread.new { self.flush } end @@ -21,8 +20,8 @@ class Logger def flush begin while(1) - @fp.puts(@queue.pop) - @fp.flush + @fp.puts(@queue.pop) + @fp.flush end ensure @fp.close diff --git a/sample/drb/dqueue.rb b/sample/drb/dqueue.rb index 1c8878c080..a9afa8c858 100644 --- a/sample/drb/dqueue.rb +++ b/sample/drb/dqueue.rb @@ -3,10 +3,9 @@ Copyright (c) 1999-2000 Masatoshi SEKI =end -require 'thread' require 'drb/drb' -DRb.start_service(nil, Queue.new) +DRb.start_service(nil, Thread::Queue.new) puts DRb.uri DRb.thread.join diff --git a/sample/drb/gw_cu.rb b/sample/drb/gw_cu.rb index 0e5ed36b8f..8079cbdc4f 100644 --- a/sample/drb/gw_cu.rb +++ b/sample/drb/gw_cu.rb @@ -13,7 +13,7 @@ class Foo end end -DRb.start_service('drubyunix:', nil) +DRb.start_service('drbunix:', nil) puts DRb.uri ro = DRbObject.new(nil, ARGV.shift) diff --git a/sample/drb/http0.rb b/sample/drb/http0.rb index d4c9f6b7fb..e40d810311 100644 --- a/sample/drb/http0.rb +++ b/sample/drb/http0.rb @@ -6,20 +6,20 @@ module DRb module HTTP0 class StrStream def initialize(str='') - @buf = str + @buf = str end attr_reader :buf def read(n) - begin - return @buf[0,n] - ensure - @buf[0,n] = '' - end + begin + return @buf[0,n] + ensure + @buf[0,n] = '' + end end def write(s) - @buf.concat s + @buf.concat s end end @@ -29,47 +29,47 @@ module DRb def self.open(uri, config) unless /^http:/ =~ uri - raise(DRbBadScheme, uri) unless uri =~ /^http:/ - raise(DRbBadURI, 'can\'t parse uri:' + uri) + raise(DRbBadScheme, uri) unless uri =~ /^http:/ + raise(DRbBadURI, 'can\'t parse uri:' + uri) end ClientSide.new(uri, config) end class ClientSide def initialize(uri, config) - @uri = uri - @res = nil - @config = config - @msg = DRbMessage.new(config) - @proxy = ENV['HTTP_PROXY'] + @uri = uri + @res = nil + @config = config + @msg = DRbMessage.new(config) + @proxy = ENV['HTTP_PROXY'] end def close; end def alive?; false; end def send_request(ref, msg_id, *arg, &b) - stream = StrStream.new - @msg.send_request(stream, ref, msg_id, *arg, &b) - @reply_stream = StrStream.new - post(@uri, stream.buf) + stream = StrStream.new + @msg.send_request(stream, ref, msg_id, *arg, &b) + @reply_stream = StrStream.new + post(@uri, stream.buf) end def recv_reply - @msg.recv_reply(@reply_stream) + @msg.recv_reply(@reply_stream) end def post(url, data) - it = URI.parse(url) - path = [(it.path=='' ? '/' : it.path), it.query].compact.join('?') - http = Net::HTTP.new(it.host, it.port) - sio = StrStream.new - http.post(path, data, {'Content-Type'=>'application/octetstream;'}) do |str| - sio.write(str) - if @config[:load_limit] < sio.buf.size - raise TypeError, 'too large packet' - end - end - @reply_stream = sio + it = URI.parse(url) + path = [(it.path=='' ? '/' : it.path), it.query].compact.join('?') + http = Net::HTTP.new(it.host, it.port) + sio = StrStream.new + http.post(path, data, {'Content-Type'=>'application/octetstream;'}) do |str| + sio.write(str) + if @config[:load_limit] < sio.buf.size + raise TypeError, 'too large packet' + end + end + @reply_stream = sio end end end diff --git a/sample/drb/http0serv.rb b/sample/drb/http0serv.rb index 8318123fa9..2e853312e1 100644 --- a/sample/drb/http0serv.rb +++ b/sample/drb/http0serv.rb @@ -1,118 +1,119 @@ require 'webrick' require 'drb/drb' -require 'drb/http0' -require 'thread' +require_relative 'http0' module DRb module HTTP0 def self.open_server(uri, config) unless /^http:/ =~ uri - raise(DRbBadScheme, uri) unless uri =~ /^http:/ - raise(DRbBadURI, 'can\'t parse uri:' + uri) + raise(DRbBadScheme, uri) unless uri =~ /^http:/ + raise(DRbBadURI, 'can\'t parse uri:' + uri) end Server.new(uri, config) end class Callback < WEBrick::HTTPServlet::AbstractServlet def initialize(config, drb) - @config = config - @drb = drb - @queue = Queue.new + @config = config + @drb = drb + @queue = Thread::Queue.new end def do_POST(req, res) - @req = req - @res = res - @drb.push(self) - @res.body = @queue.pop - @res['content-type'] = 'application/octet-stream;' + @req = req + @res = res + @drb.push(self) + @res.body = @queue.pop + @res['content-type'] = 'application/octet-stream;' end def req_body - @req.body + @req.body end def reply(body) - @queue.push(body) + @queue.push(body) end def close - @queue.push('') + @queue.push('') end end class Server def initialize(uri, config) - @uri = uri - @config = config - @queue = Queue.new - setup_webrick(uri) + @uri = uri + @config = config + @queue = Thread::Queue.new + setup_webrick(uri) end attr_reader :uri def close - @server.shutdown if @server - @server = nil + @server.shutdown if @server + @server = nil end def push(callback) - @queue.push(callback) + @queue.push(callback) end def accept - client = @queue.pop - ServerSide.new(client, @config) + client = @queue.pop + ServerSide.new(uri, client, @config) end def setup_webrick(uri) - logger = WEBrick::Log::new($stderr, WEBrick::Log::FATAL) - u = URI.parse(uri) - s = WEBrick::HTTPServer.new(:Port => u.port, - :AddressFamily => Socket::AF_INET, - :BindAddress => u.host, - :Logger => logger, - :ServerType => Thread) - s.mount(u.path, Callback, self) - @server = s - s.start + logger = WEBrick::Log::new($stderr, WEBrick::Log::FATAL) + u = URI.parse(uri) + s = WEBrick::HTTPServer.new(:Port => u.port, + :AddressFamily => Socket::AF_INET, + :BindAddress => u.host, + :Logger => logger, + :ServerType => Thread) + s.mount(u.path, Callback, self) + @server = s + s.start end end class ServerSide - def initialize(callback, config) - @callback = callback - @config = config - @msg = DRbMessage.new(@config) - @req_stream = StrStream.new(@callback.req_body) + def initialize(uri, callback, config) + @uri = uri + @callback = callback + @config = config + @msg = DRbMessage.new(@config) + @req_stream = StrStream.new(@callback.req_body) end + attr_reader :uri def close - @callback.close if @callback - @callback = nil + @callback.close if @callback + @callback = nil end def alive?; false; end def recv_request - begin - @msg.recv_request(@req_stream) - rescue - close - raise $! - end + begin + @msg.recv_request(@req_stream) + rescue + close + raise $! + end end def send_reply(succ, result) - begin - return unless @callback - stream = StrStream.new - @msg.send_reply(stream, succ, result) - @callback.reply(stream.buf) - rescue - close - raise $! - end + begin + return unless @callback + stream = StrStream.new + @msg.send_reply(stream, succ, result) + @callback.reply(stream.buf) + rescue + close + raise $! + end end end end diff --git a/sample/drb/name.rb b/sample/drb/name.rb index 9527d47764..6d88186dab 100644 --- a/sample/drb/name.rb +++ b/sample/drb/name.rb @@ -35,16 +35,16 @@ How to play. | 2 =end -require 'thread.rb' require 'drb/drb' module DRbNamedObject DRbNAMEDICT = {} + DRBNAMEMUTEX = Thread::Mutex.new attr_reader(:drb_name) def drb_name=(name) @drb_name = name - Thread.exclusive do + DRBNAMEMUTEX.synchronize do raise(IndexError, name) if DRbNAMEDICT[name] DRbNAMEDICT[name] = self end @@ -75,7 +75,7 @@ class Seq def initialize(v, name) @counter = v - @mutex = Mutex.new + @mutex = Thread::Mutex.new self.drb_name = name end @@ -90,7 +90,7 @@ end class Front def initialize seq = Seq.new(0, 'seq') - mutex = Mutex.new + mutex = Thread::Mutex.new mutex.extend(DRbUndumped) mutex.extend(DRbNamedObject) mutex.drb_name = 'mutex' diff --git a/sample/drb/old_tuplespace.rb b/sample/drb/old_tuplespace.rb index 0da9fa84c3..2d5310086e 100644 --- a/sample/drb/old_tuplespace.rb +++ b/sample/drb/old_tuplespace.rb @@ -3,15 +3,13 @@ # Copyright (c) 1999-2000 Masatoshi SEKI # You can redistribute it and/or modify it under the same terms as Ruby. -require 'thread' - class TupleSpace class Template def initialize(list) @list = list @check_idx = [] @list.each_with_index do |x, i| - @check_idx.push i if x + @check_idx.push i if x end @size = @list.size end @@ -22,9 +20,9 @@ class TupleSpace def match(tuple) return nil if tuple.size != self.size @check_idx.each do |i| - unless @list[i] === tuple[i] - return false - end + unless @list[i] === tuple[i] + return false + end end return true end @@ -33,7 +31,7 @@ class TupleSpace def initialize @que = {} @waiting = {} - @que.taint # enable tainted comunication + @que.taint # enable tainted communication @waiting.taint self.taint end @@ -47,13 +45,13 @@ class TupleSpace found = false @waiting[sz] = @waiting[sz].find_all { |x| if x[0].match(tuple) - begin - x[1].wakeup - rescue ThreadError - end - false + begin + x[1].wakeup + rescue ThreadError + end + false else - true + true end } end @@ -77,8 +75,8 @@ class TupleSpace found = false @que[sz].each_with_index do |x, i| if template.match(x) - found = true - break + found = true + break end end return nil unless found @@ -110,17 +108,17 @@ class TupleSpace def in(template, non_block=false) begin loop do - Thread.critical = true - tuple = get_que(template) - unless tuple - if non_block - raise ThreadError, "queue empty" - end - put_waiting(template, Thread.current) - Thread.stop - else - return tuple - end + Thread.critical = true + tuple = get_que(template) + unless tuple + if non_block + raise ThreadError, "queue empty" + end + put_waiting(template, Thread.current) + Thread.stop + else + return tuple + end end ensure Thread.critical = false @@ -155,11 +153,11 @@ if __FILE__ == $0 def server(ts, id) Thread.start { loop do - req = ts.in(['req', nil, nil]) - ac = req[1] - num = req[2] - sleep id - ts.out([ac, id, num, num * num]) + req = ts.in(['req', nil, nil]) + ac = req[1] + num = req[2] + sleep id + ts.out([ac, id, num, num * num]) end } end @@ -168,14 +166,14 @@ if __FILE__ == $0 Thread.start { ac = Object.new tuples = (1..10).collect { |i| - ['req', ac, i * 10 + n] + ['req', ac, i * 10 + n] } ts.out(*tuples) ts.out(tuples[0]) puts "out: #{n}" 11.times do |i| - ans = ts.in([ac, nil, nil, nil]) - puts "client(#{n}) server(#{ans[1]}) #{ans[2]} #{ans[3]}" + ans = ts.in([ac, nil, nil, nil]) + puts "client(#{n}) server(#{ans[1]}) #{ans[2]} #{ans[3]}" end } end @@ -183,12 +181,12 @@ if __FILE__ == $0 def watcher(ts) Thread.start { loop do - begin - sleep 1 - p ts.rd(['req', nil, nil], true) - rescue ThreadError - puts "'req' not found." - end + begin + sleep 1 + p ts.rd(['req', nil, nil], true) + rescue ThreadError + puts "'req' not found." + end end } end diff --git a/sample/drb/ring_echo.rb b/sample/drb/ring_echo.rb index 3b743cab8e..c54628b54c 100644 --- a/sample/drb/ring_echo.rb +++ b/sample/drb/ring_echo.rb @@ -1,7 +1,6 @@ require 'drb/drb' require 'drb/eq' require 'rinda/ring' -require 'thread' class RingEcho include DRbUndumped diff --git a/sample/drb/ring_place.rb b/sample/drb/ring_place.rb index 0ceef7c65a..11c6c2fe80 100644 --- a/sample/drb/ring_place.rb +++ b/sample/drb/ring_place.rb @@ -18,8 +18,8 @@ if $DEBUG puts DRb.uri DRb.thread.join else - STDIN.reopen('/dev/null') - STDOUT.reopen('/dev/null', 'w') - STDERR.reopen('/dev/null', 'w') + STDIN.reopen(IO::NULL) + STDOUT.reopen(IO::NULL, 'w') + STDERR.reopen(IO::NULL, 'w') DRb.thread.join end diff --git a/sample/drb/simpletuple.rb b/sample/drb/simpletuple.rb index 1b9b7a35a7..4bb4b1cff9 100644 --- a/sample/drb/simpletuple.rb +++ b/sample/drb/simpletuple.rb @@ -3,8 +3,6 @@ # Copyright (c) 1999-2000 Masatoshi SEKI # You can redistribute it and/or modify it under the same terms as Ruby. -require 'thread' - class SimpleTupleSpace def initialize @hash = {} @@ -58,10 +56,10 @@ if __FILE__ == $0 def server(ts) Thread.start { loop do - req = ts.in('req') - ac = req[0] - num = req[1] - ts.out(ac, num * num) + req = ts.in('req') + ac = req[0] + num = req[1] + ts.out(ac, num * num) end } end diff --git a/sample/dualstack-fetch.rb b/sample/dualstack-fetch.rb index 1897a3d8e9..18d33cc45a 100644 --- a/sample/dualstack-fetch.rb +++ b/sample/dualstack-fetch.rb @@ -38,7 +38,7 @@ end STDERR.print "conntecting to #{host} port #{port}\n" c = TCPSocket.new(host, port) dest = Socket.getnameinfo(c.getpeername, - Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV) + Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV) STDERR.print "conntected to #{dest[0]} port #{dest[1]}\n" c.print "GET #{path} HTTP/1.0\n" c.print "Host: #{host}\n" diff --git a/sample/dualstack-httpd.rb b/sample/dualstack-httpd.rb index 11c5201d74..ab02e17aea 100644 --- a/sample/dualstack-httpd.rb +++ b/sample/dualstack-httpd.rb @@ -3,7 +3,6 @@ # The code demonstrates how a multi-protocol daemon should be written. require "socket" -require "thread" port = 8888 res = Socket.getaddrinfo(nil, port, nil, Socket::SOCK_STREAM, nil, Socket::AI_PASSIVE) @@ -29,22 +28,22 @@ end while true as = ls.accept Thread.start do - STDERR.print "socket #{myname} accepted, thread ", Thread.current, "\n" - s = as # copy to dynamic variable - str = '' - while line = s.gets - break if line == "\r\n" or line == "\n" - str << line - end - STDERR.print "socket #{myname} got string\n" - s.write("HTTP/1.0 200 OK\n") - s.write("Content-type: text/plain\n\n") - s.write("this is test: my name is #{myname}, you sent:\n") - s.write("---start\n") - s.write(str) - s.write("---end\n") - s.close - STDERR.print "socket #{myname} processed, thread ", Thread.current, " terminating\n" + STDERR.print "socket #{myname} accepted, thread ", Thread.current, "\n" + s = as # copy to dynamic variable + str = '' + while line = s.gets + break if line == "\r\n" or line == "\n" + str << line + end + STDERR.print "socket #{myname} got string\n" + s.write("HTTP/1.0 200 OK\n") + s.write("Content-type: text/plain\n\n") + s.write("this is test: my name is #{myname}, you sent:\n") + s.write("---start\n") + s.write(str) + s.write("---end\n") + s.close + STDERR.print "socket #{myname} processed, thread ", Thread.current, " terminating\n" end end end diff --git a/sample/export.rb b/sample/export.rb index 949e5b10bf..2ab2e93f2e 100644 --- a/sample/export.rb +++ b/sample/export.rb @@ -30,7 +30,7 @@ f.printf "%s\n", Foo f.quux -class Bar<Foo +class Bar < Foo def quux super baz() diff --git a/sample/exyacc.rb b/sample/exyacc.rb index c96ebfd676..cbcc18d58b 100644 --- a/sample/exyacc.rb +++ b/sample/exyacc.rb @@ -1,20 +1,20 @@ #! /usr/local/bin/ruby -Kn # usage: exyacc.rb [yaccfiles] -# this is coverted from exyacc.pl in the camel book +# this is covered from exyacc.pl in the camel book ARGF.each(nil) do |source| sbeg = source.index("\n%%") + 1 send = source.rindex("\n%%") + 1 - grammer = source[sbeg, send-sbeg] - grammer.sub!(/.*\n/, "") - grammer.gsub!(/'\{'/, "'\001'") - grammer.gsub!(/'\}'/, "'\002'") - grammer.gsub!(%r{\*/}, "\003\003") - grammer.gsub!(%r{/\*[^\003]*\003\003}, '') - while grammer.gsub!(/\{[^{}]*\}/, ''); end - grammer.gsub!(/'\001'/, "'{'") - grammer.gsub!(/'\002'/, "'}'") - while grammer.gsub!(/^[ \t]*\n(\s)/, '\1'); end - grammer.gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2') - print grammer + grammar = source[sbeg, send-sbeg] + grammar.sub!(/.*\n/, "") + grammar.gsub!(/'\{'/, "'\001'") + grammar.gsub!(/["']\}["']/, "'\002'") + grammar.gsub!(%r{\*/}, "\003\003") + grammar.gsub!(%r{/\*[^\003]*\003\003}, '') + while grammar.gsub!(/\{[^{}]*\}/, ''); end + grammar.gsub!(/'\001'/, "'{'") + grammar.gsub!(/'\002'/, "'}'") + while grammar.gsub!(/^[ \t]*\n(\s)/, '\1'); end + grammar.gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2') + print grammar end diff --git a/sample/fact.rb b/sample/fact.rb index d8147a40f1..9f6ca72ca7 100644 --- a/sample/fact.rb +++ b/sample/fact.rb @@ -4,6 +4,6 @@ def fact(n) n.downto(1) do |i| f *= i end - return f + f end -print fact(ARGV[0].to_i), "\n" +puts fact(ARGV[0].to_i) diff --git a/sample/fib.awk b/sample/fib.awk index 7ebe8930f5..9589f97965 100644 --- a/sample/fib.awk +++ b/sample/fib.awk @@ -1,5 +1,5 @@ - function fib(n) { - if ( n<2 ) return n; else return fib(n-2) + fib(n-1) - } +function fib(n) { + if ( n<2 ) return n; else return fib(n-2) + fib(n-1) +} - BEGIN { print fib(20); } +BEGIN { print fib(20); } diff --git a/sample/fib.pl b/sample/fib.pl index 945a4929a7..4c35eaae31 100644 --- a/sample/fib.pl +++ b/sample/fib.pl @@ -1,10 +1,10 @@ sub fib { my($n)=@_; if ($n<2) { - return $n; + return $n; } else { - return fib($n-2)+fib($n-1); + return fib($n-2)+fib($n-1); } } diff --git a/sample/fib.py b/sample/fib.py index 8318021d24..90dc1e09ed 100644 --- a/sample/fib.py +++ b/sample/fib.py @@ -6,5 +6,5 @@ def fib(n): else: return fib(n-2)+fib(n-1) -print fib(20) +print(fib(20)) diff --git a/sample/fib.scm b/sample/fib.scm index b246ca50ac..d2dc770282 100644 --- a/sample/fib.scm +++ b/sample/fib.scm @@ -1,7 +1,7 @@ (define (fib n) (if (< n 2) - n - (+ (fib (- n 2)) (fib (- n 1))))) + n + (+ (fib (- n 2)) (fib (- n 1))))) (display (fib 20)) (newline) diff --git a/sample/freq.rb b/sample/freq.rb deleted file mode 100644 index 362753f71f..0000000000 --- a/sample/freq.rb +++ /dev/null @@ -1,12 +0,0 @@ -# word occurrence listing -# usege: ruby freq.rb file.. -freq = Hash.new(0) -while line = gets() - line.scan(/\w+/) do |word| - freq[word] += 1 - end -end - -for word in freq.keys.sort! - print word, " -- ", freq[word], "\n" -end diff --git a/sample/from.rb b/sample/from.rb index 918745e55f..db1299c869 100644 --- a/sample/from.rb +++ b/sample/from.rb @@ -43,8 +43,8 @@ def get_mailfile(user) [ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m| path = "#{m}/mail/#{user}" if File.exist?(path) - file = path - break + file = path + break end end end @@ -64,23 +64,23 @@ def from_main mtime = File.mtime(file) open(file, "r") do |f| until f.eof? - header = {} - f.each_line do |line| - next if /^From / =~ line # skip From-line - break if /^$/ =~ line # end of header - - if /^(?<attr>\S+?):\s*(?<value>.*)/ =~ line - attr.capitalize! - header[attr] = value - elsif attr - header[attr] += "\n" + line.lstrip - end - end - - f.each_line do |line| - break if /^From / =~ line - end - outcount += fromout(header['Date'], header['From'], header['Subject']) + header = {} + f.each_line do |line| + next if /^From / =~ line # skip From-line + break if /^$/ =~ line # end of header + + if /^(?<attr>\S+?):\s*(?<value>.*)/ =~ line + attr.capitalize! + header[attr] = value + elsif attr + header[attr] += "\n" + line.lstrip + end + end + + f.each_line do |line| + break if /^From / =~ line + end + outcount += fromout(header['Date'], header['From'], header['Subject']) end end File.utime(atime, mtime, file) diff --git a/sample/iseq_loader.rb b/sample/iseq_loader.rb new file mode 100644 index 0000000000..8c271405d6 --- /dev/null +++ b/sample/iseq_loader.rb @@ -0,0 +1,243 @@ +# +# iseq_loader.rb - sample of compiler/loader for binary compiled file +# +# Usage as a compiler: ruby iseq_loader.rb [file or directory] ... +# +# It compiles and stores specified files. +# If directories are specified, then compiles and stores all *.rb files. +# (using Dir.glob) +# +# TODO: add remove option +# TODO: add verify option +# +# Usage as a loader: simply require this file with the following setting. +# +# Setting with environment variables. +# +# * RUBY_ISEQ_LOADER_STORAGE to select storage type +# * dbm: use dbm +# * fs: [default] use file system. locate a compiled binary files in same +# directory of scripts like Rubinius. foo.rb.yarb will be created for foo.rb. +# * fs2: use file system. locate compiled file in specified directory. +# * nothing: do nothing. +# +# * RUBY_ISEQ_LOADER_STORAGE_DIR to select directory +# * default: ~/.ruby_binaries/ +# +# * RUBY_ISEQ_LOADER_STORAGE_COMPILE_IF_NOT_COMPILED +# * true: store compiled file if compiled data is not available. +# * false: [default] do nothing if there is no compiled iseq data. + +class RubyVM::InstructionSequence + $ISEQ_LOADER_LOADED = 0 + $ISEQ_LOADER_COMPILED = 0 + $ISEQ_LOADER_IGNORED = 0 + LAUNCHED_TIME = Time.now + COMPILE_FILE_ENABLE = false || true + COMPILE_VERBOSE = $VERBOSE || false # || true + COMPILE_DEBUG = ENV['RUBY_ISEQ_LOADER_DEBUG'] + COMPILE_IF_NOT_COMPILED = ENV['RUBY_ISEQ_LOADER_STORAGE_COMPILE_IF_NOT_COMPILED'] == 'true' + + at_exit{ + STDERR.puts "[ISEQ_LOADER] #{Process.pid} time: #{Time.now - LAUNCHED_TIME}, " + + "loaded: #{$ISEQ_LOADER_LOADED}, " + + "compiled: #{$ISEQ_LOADER_COMPILED}, " + + "ignored: #{$ISEQ_LOADER_IGNORED}" + } if COMPILE_VERBOSE + + unless cf_dir = ENV['RUBY_ISEQ_LOADER_STORAGE_DIR'] + cf_dir = File.expand_path("~/.ruby_binaries") + unless File.exist?(cf_dir) + Dir.mkdir(cf_dir) + end + end + CF_PREFIX = "#{cf_dir}/cb." + + class NullStorage + def load_iseq fname; end + def compile_and_save_isq fname; end + def unlink_compiled_iseq; end + end + + class BasicStorage + def initialize + require 'digest/sha1' + end + + def load_iseq fname + iseq_key = iseq_key_name(fname) + if compiled_iseq_exist?(fname, iseq_key) && compiled_iseq_is_younger?(fname, iseq_key) + $ISEQ_LOADER_LOADED += 1 + STDERR.puts "[ISEQ_LOADER] #{Process.pid} load #{fname} from #{iseq_key}" if COMPILE_DEBUG + binary = read_compiled_iseq(fname, iseq_key) + iseq = RubyVM::InstructionSequence.load_from_binary(binary) + # p [extra_data(iseq.path), RubyVM::InstructionSequence.load_from_binary_extra_data(binary)] + # raise unless extra_data(iseq.path) == RubyVM::InstructionSequence.load_from_binary_extra_data(binary) + iseq + elsif COMPILE_IF_NOT_COMPILED + compile_and_save_iseq(fname, iseq_key) + else + $ISEQ_LOADER_IGNORED += 1 + # p fname + nil + end + end + + def extra_data fname + "SHA-1:#{::Digest::SHA1.file(fname).digest}" + end + + def compile_and_save_iseq fname, iseq_key = iseq_key_name(fname) + $ISEQ_LOADER_COMPILED += 1 + STDERR.puts "[RUBY_COMPILED_FILE] compile #{fname}" if COMPILE_DEBUG + iseq = RubyVM::InstructionSequence.compile_file(fname) + + binary = iseq.to_binary(extra_data(fname)) + write_compiled_iseq(fname, iseq_key, binary) + iseq + end + + # def unlink_compiled_iseq; nil; end # should implement at sub classes + + private + + def iseq_key_name fname + fname + end + + # should implement at sub classes + # def compiled_iseq_younger? fname, iseq_key; end + # def compiled_iseq_exist? fname, iseq_key; end + # def read_compiled_file fname, iseq_key; end + # def write_compiled_file fname, iseq_key, binary; end + end + + class FSStorage < BasicStorage + def initialize + super + require 'fileutils' + @dir = CF_PREFIX + "files" + unless File.directory?(@dir) + FileUtils.mkdir_p(@dir) + end + end + + def unlink_compiled_iseq + File.unlink(compile_file_path) + end + + private + + def iseq_key_name fname + "#{fname}.yarb" # same directory + end + + def compiled_iseq_exist? fname, iseq_key + File.exist?(iseq_key) + end + + def compiled_iseq_is_younger? fname, iseq_key + File.mtime(iseq_key) >= File.mtime(fname) + end + + def read_compiled_iseq fname, iseq_key + File.open(iseq_key, 'rb'){|f| f.read} + end + + def write_compiled_iseq fname, iseq_key, binary + File.open(iseq_key, 'wb'){|f| f.write(binary)} + end + end + + class FS2Storage < FSStorage + def iseq_key_name fname + @dir + fname.gsub(/[^A-Za-z0-9\._-]/){|c| '%02x' % c.ord} # special directory + end + end + + class DBMStorage < BasicStorage + def initialize + require 'dbm' + @db = DBM.open(CF_PREFIX+'db') + end + + def unlink_compiled_iseq + @db.delete fname + end + + private + + def date_key_name fname + "date.#{fname}" + end + + def iseq_key_name fname + "body.#{fname}" + end + + def compiled_iseq_exist? fname, iseq_key + @db.has_key? iseq_key + end + + def compiled_iseq_is_younger? fname, iseq_key + date_key = date_key_name(fname) + if @db.has_key? date_key + @db[date_key].to_i >= File.mtime(fname).to_i + end + end + + def read_compiled_iseq fname, iseq_key + @db[iseq_key] + end + + def write_compiled_iseq fname, iseq_key, binary + date_key = date_key_name(fname) + @db[iseq_key] = binary + @db[date_key] = Time.now.to_i + end + end + + STORAGE = case ENV['RUBY_ISEQ_LOADER_STORAGE'] + when 'dbm' + DBMStorage.new + when 'fs' + FSStorage.new + when 'fs2' + FS2Storage.new + when 'null' + NullStorage.new + else + FSStorage.new + end + + STDERR.puts "[ISEQ_LOADER] use #{STORAGE.class} " if COMPILE_VERBOSE + + def self.load_iseq fname + STORAGE.load_iseq(fname) + end + + def self.compile_and_save_iseq fname + STORAGE.compile_and_save_iseq fname + end + + def self.unlink_compiled_iseq fname + STORAGE.unlink_compiled_iseq fname + end +end + +if __FILE__ == $0 + ARGV.each{|path| + if File.directory?(path) + pattern = File.join(path, '**/*.rb') + Dir.glob(pattern){|file| + begin + RubyVM::InstructionSequence.compile_and_save_iseq(file) + rescue SyntaxError => e + STDERR.puts e + end + } + else + RubyVM::InstructionSequence.compile_and_save_iseq(path) + end + } +end diff --git a/sample/list.rb b/sample/list.rb index 85899ce7ff..7458ba0244 100644 --- a/sample/list.rb +++ b/sample/list.rb @@ -5,7 +5,6 @@ class MyElem # @variables are instance variable, no declaration needed @data = item @succ = nil - @head = nil end def data @@ -23,6 +22,10 @@ class MyElem end class MyList + def initialize + @head = nil + end + def add_to_list(obj) elt = MyElem.new(obj) if @head @@ -76,6 +79,6 @@ $list2.add_to_list(20) $list2.add_to_list(Point.new(4, 5)) $list2.add_to_list($list1) -# parenthesises around method arguments can be ommitted unless ambiguous. +# parenthesises around method arguments can be omitted unless ambiguous. print "list1:\n", $list1, "\n" print "list2:\n", $list2, "\n" diff --git a/sample/list3.rb b/sample/list3.rb index 1d9f04b710..110e405cf9 100644 --- a/sample/list3.rb +++ b/sample/list3.rb @@ -7,7 +7,7 @@ class Point self end - def to_s + def inspect sprintf("%d@%d", @x, @y) end end diff --git a/sample/logger/app.rb b/sample/logger/app.rb index 924bcba4b0..97b62bca30 100644 --- a/sample/logger/app.rb +++ b/sample/logger/app.rb @@ -41,6 +41,6 @@ end status = MyApp.new(1, 2, 3).start if status != 0 - puts 'Some error(s) occured.' + puts 'Some error(s) occurred.' puts 'See "app.log".' end diff --git a/sample/mkproto.rb b/sample/mkproto.rb index 6e7fc0f788..e650fe8d47 100644 --- a/sample/mkproto.rb +++ b/sample/mkproto.rb @@ -7,18 +7,18 @@ while line = gets() for arg in $4.split(/;\n\s*/) arg.gsub!(/ +/, ' ') if arg =~ /,/ - if arg =~ /(([^*]+) *\** *\w+),/ - type = $2.strip - args.push $1.strip - arg = $' - else - type = "" - end - while arg.sub!(/(\** *\w+)(,|$)/, "") && $~ - args.push type + " " + $1.strip - end + if arg =~ /(([^*]+) *\** *\w+),/ + type = $2.strip + args.push $1.strip + arg = $' + else + type = "" + end + while arg.sub!(/(\** *\w+)(,|$)/, "") && $~ + args.push type + " " + $1.strip + end else - args.push arg.strip + args.push arg.strip end end printf "%s);\n", args.join(', ') diff --git a/sample/net-imap.rb b/sample/net-imap.rb new file mode 100644 index 0000000000..b93ecb746e --- /dev/null +++ b/sample/net-imap.rb @@ -0,0 +1,167 @@ +require 'net/imap' +require "getoptlong" + +$stdout.sync = true +$port = nil +$user = ENV["USER"] || ENV["LOGNAME"] +$auth = "login" +$ssl = false +$starttls = false + +def usage + <<EOF +usage: #{$0} [options] <host> + + --help print this message + --port=PORT specifies port + --user=USER specifies user + --auth=AUTH specifies auth type + --starttls use starttls + --ssl use ssl +EOF +end + +begin + require 'io/console' +rescue LoadError + def _noecho(&block) + system("stty", "-echo") + begin + yield STDIN + ensure + system("stty", "echo") + end + end +else + def _noecho(&block) + STDIN.noecho(&block) + end +end + +def get_password + print "password: " + begin + return _noecho(&:gets).chomp + ensure + puts + end +end + +def get_command + printf("%s@%s> ", $user, $host) + if line = gets + return line.strip.split(/\s+/) + else + return nil + end +end + +parser = GetoptLong.new +parser.set_options(['--debug', GetoptLong::NO_ARGUMENT], + ['--help', GetoptLong::NO_ARGUMENT], + ['--port', GetoptLong::REQUIRED_ARGUMENT], + ['--user', GetoptLong::REQUIRED_ARGUMENT], + ['--auth', GetoptLong::REQUIRED_ARGUMENT], + ['--starttls', GetoptLong::NO_ARGUMENT], + ['--ssl', GetoptLong::NO_ARGUMENT]) +begin + parser.each_option do |name, arg| + case name + when "--port" + $port = arg + when "--user" + $user = arg + when "--auth" + $auth = arg + when "--ssl" + $ssl = true + when "--starttls" + $starttls = true + when "--debug" + Net::IMAP.debug = true + when "--help" + usage + exit + end + end +rescue + abort usage +end + +$host = ARGV.shift +unless $host + abort usage +end + +imap = Net::IMAP.new($host, :port => $port, :ssl => $ssl) +begin + imap.starttls if $starttls + class << password = method(:get_password) + alias to_str call + end + imap.authenticate($auth, $user, password) + while true + cmd, *args = get_command + break unless cmd + begin + case cmd + when "list" + for mbox in imap.list("", args[0] || "*") + if mbox.attr.include?(Net::IMAP::NOSELECT) + prefix = "!" + elsif mbox.attr.include?(Net::IMAP::MARKED) + prefix = "*" + else + prefix = " " + end + print prefix, mbox.name, "\n" + end + when "select" + imap.select(args[0] || "inbox") + print "ok\n" + when "close" + imap.close + print "ok\n" + when "summary" + unless messages = imap.responses["EXISTS"][-1] + puts "not selected" + next + end + if messages > 0 + for data in imap.fetch(1..-1, ["ENVELOPE"]) + print data.seqno, ": ", data.attr["ENVELOPE"].subject, "\n" + end + else + puts "no message" + end + when "fetch" + if args[0] + data = imap.fetch(args[0].to_i, ["RFC822.HEADER", "RFC822.TEXT"])[0] + puts data.attr["RFC822.HEADER"] + puts data.attr["RFC822.TEXT"] + else + puts "missing argument" + end + when "logout", "exit", "quit" + break + when "help", "?" + print <<EOF +list [pattern] list mailboxes +select [mailbox] select mailbox +close close mailbox +summary display summary +fetch [msgno] display message +logout logout +help, ? display help message +EOF + else + print "unknown command: ", cmd, "\n" + end + rescue Net::IMAP::Error + puts $! + end + end +ensure + imap.logout + imap.disconnect +end diff --git a/sample/observ.rb b/sample/observ.rb index 72e5178b38..ef4a9f60f5 100644 --- a/sample/observ.rb +++ b/sample/observ.rb @@ -1,6 +1,5 @@ #! /usr/local/bin/ruby -require "thread" require "observer" class Tick @@ -8,10 +7,10 @@ class Tick def initialize Thread.start do loop do - sleep 0.999 - now = Time.now - changed - notify_observers(now.hour, now.min, now.sec) + sleep 0.999 + now = Time.now + changed + notify_observers(now.hour, now.min, now.sec) end end end @@ -28,5 +27,5 @@ class Clock end end -clock = Clock.new(Tick.new) +Clock.new(Tick.new) sleep diff --git a/sample/occur.pl b/sample/occur.pl index 1f5fcf27a4..331ce50211 100644 --- a/sample/occur.pl +++ b/sample/occur.pl @@ -1,9 +1,9 @@ while (<>) { - for (split(/\W+/)) { - $freq{$_}++; - } + for (split(/\W+/)) { + $freq{$_}++; + } } for (sort keys %freq) { - print "$_ -- $freq{$_}\n"; + print "$_ -- $freq{$_}\n"; } diff --git a/sample/occur.rb b/sample/occur.rb index 4ec6ae479b..5927ebc889 100644 --- a/sample/occur.rb +++ b/sample/occur.rb @@ -1,8 +1,8 @@ # word occurrence listing -# usege: ruby occur.rb file.. +# usage: ruby occur.rb file.. freq = Hash.new(0) while line = gets() - for word in line.split(/\W+/) + line.scan(/\w+/) do |word| freq[word] += 1 end end diff --git a/sample/occur2.rb b/sample/occur2.rb deleted file mode 100644 index ca87d0ddef..0000000000 --- a/sample/occur2.rb +++ /dev/null @@ -1,13 +0,0 @@ -# word occurrence listing -# usege: ruby occur2.rb file.. -freq = {} -ARGF.each_line do |line| - for word in line.split(/\W+/) - freq[word] ||= 0 - freq[word] += 1 - end -end - -for word in freq.keys.sort - printf("%s -- %d\n", word, freq[word]) -end diff --git a/sample/open3.rb b/sample/open3.rb new file mode 100644 index 0000000000..bc6cdfe3bf --- /dev/null +++ b/sample/open3.rb @@ -0,0 +1,12 @@ +require 'open3' + +a = Open3.popen3("nroff -man") +Thread.start do + while line = gets + a[0].print line + end + a[0].close +end +while line = a[1].gets + print ":", line +end diff --git a/sample/openssl/c_rehash.rb b/sample/openssl/c_rehash.rb index afbb654517..de4b66e902 100644 --- a/sample/openssl/c_rehash.rb +++ b/sample/openssl/c_rehash.rb @@ -1,7 +1,6 @@ #!/usr/bin/env ruby require 'openssl' -require 'digest/md5' class CHashDir include Enumerable @@ -54,13 +53,13 @@ class CHashDir OpenSSL::X509::Certificate.new(str) rescue begin - OpenSSL::X509::CRL.new(str) + OpenSSL::X509::CRL.new(str) rescue - begin - OpenSSL::X509::Request.new(str) - rescue - nil - end + begin + OpenSSL::X509::Request.new(str) + rescue + nil + end end end end @@ -75,15 +74,15 @@ private Dir.chdir(@dirpath) do delete_symlink Dir.glob('*.pem') do |pemfile| - cert = load_pem_file(pemfile) - case cert - when OpenSSL::X509::Certificate - link_hash_cert(pemfile, cert) - when OpenSSL::X509::CRL - link_hash_crl(pemfile, cert) - else - STDERR.puts("WARNING: #{pemfile} does not contain a certificate or CRL: skipping") unless @silent - end + cert = load_pem_file(pemfile) + case cert + when OpenSSL::X509::Certificate + link_hash_cert(pemfile, cert) + when OpenSSL::X509::CRL + link_hash_crl(pemfile, cert) + else + STDERR.puts("WARNING: #{pemfile} does not contain a certificate or CRL: skipping") unless @silent + end end end end @@ -103,7 +102,7 @@ private } unless filepath unless @silent - STDERR.puts("WARNING: Skipping duplicate certificate #{org_filename}") + STDERR.puts("WARNING: Skipping duplicate certificate #{org_filename}") end else (@cert_cache[name_hash] ||= []) << path(filepath) @@ -118,7 +117,7 @@ private } unless filepath unless @silent - STDERR.puts("WARNING: Skipping duplicate CRL #{org_filename}") + STDERR.puts("WARNING: Skipping duplicate CRL #{org_filename}") end else (@crl_cache[name_hash] ||= []) << path(filepath) @@ -132,7 +131,7 @@ private filepath = yield(idx) break unless FileTest.symlink?(filepath) or FileTest.exist?(filepath) if @fingerprint_cache[filepath] == fingerprint - return false + return false end idx += 1 end @@ -147,7 +146,7 @@ private File.symlink(from, to) rescue File.open(to, "w") do |f| - f << File.read(from) + f << File.read(from) end end end @@ -161,7 +160,7 @@ private end def fingerprint(der) - Digest::MD5.hexdigest(der).upcase + OpenSSL::Digest.hexdigest('MD5', der).upcase end end diff --git a/sample/openssl/cert2text.rb b/sample/openssl/cert2text.rb index 50da224e76..fe14e51d3a 100644 --- a/sample/openssl/cert2text.rb +++ b/sample/openssl/cert2text.rb @@ -1,10 +1,13 @@ #!/usr/bin/env ruby require 'openssl' -include OpenSSL::X509 def cert2text(cert_str) - [Certificate, CRL, Request].each do |klass| + [ + OpenSSL::X509::Certificate, + OpenSSL::X509::CRL, + OpenSSL::X509::Request, + ].each do |klass| begin puts klass.new(cert_str).to_text return diff --git a/sample/openssl/certstore.rb b/sample/openssl/certstore.rb index c0bc21bcbb..72e59f6dad 100644 --- a/sample/openssl/certstore.rb +++ b/sample/openssl/certstore.rb @@ -3,9 +3,6 @@ require 'crlstore' class CertStore - include OpenSSL - include X509 - attr_reader :self_signed_ca attr_reader :other_ca attr_reader :ee @@ -17,11 +14,11 @@ class CertStore @c_store = CHashDir.new(@certs_dir) @c_store.hash_dir(true) @crl_store = CrlStore.new(@c_store) - @x509store = Store.new + @x509store = OpenSSL::X509::Store.new @self_signed_ca = @other_ca = @ee = @crl = nil # Uncomment this line to let OpenSSL to check CRL for each certs. - # @x509store.flags = V_FLAG_CRL_CHECK | V_FLAG_CRL_CHECK_ALL + # @x509store.flags = OpenSSL::X509::V_FLAG_CRL_CHECK | OpenSSL::X509::V_FLAG_CRL_CHECK_ALL add_path scan_certs @@ -76,27 +73,27 @@ private result = @x509store.verify(cert) do |ok, ctx| cert = ctx.current_cert if ctx.current_crl - crl_map[cert.subject] = true + crl_map[cert.subject] = true end if ok - if !ctx.current_crl - if crl = @crl_store.find_crl(cert) - crl_map[cert.subject] = true - if crl.revoked.find { |revoked| revoked.serial == cert.serial } - ok = false - error_string = 'certification revoked' - end - end - end + if !ctx.current_crl + if crl = @crl_store.find_crl(cert) + crl_map[cert.subject] = true + if crl.revoked.find { |revoked| revoked.serial == cert.serial } + ok = false + error_string = 'certification revoked' + end + end + end end error_map[cert.subject] = error_string if error_string ok end error = if result - nil - else - error_map[cert.subject] || @x509store.error_string - end + nil + else + error_map[cert.subject] || @x509store.error_string + end return error, crl_map end @@ -105,13 +102,13 @@ private cert = generate_cert(certfile) case guess_cert_type(cert) when CERT_TYPE_SELF_SIGNED - @self_signed_ca << cert + @self_signed_ca << cert when CERT_TYPE_OTHER - @other_ca << cert + @other_ca << cert when CERT_TYPE_EE - @ee << cert + @ee << cert else - raise "Unknown cert type." + raise "Unknown cert type." end end @c_store.get_crls.each do |crlfile| @@ -128,21 +125,21 @@ private # Ignores criticality of extensions. It's 'guess'ing. case ext.oid when 'basicConstraints' - /CA:(TRUE|FALSE), pathlen:(\d+)/ =~ ext.value - ca = ($1 == 'TRUE') unless ca + /CA:(TRUE|FALSE), pathlen:(\d+)/ =~ ext.value + ca = ($1 == 'TRUE') unless ca when 'keyUsage' - usage = ext.value.split(/\s*,\s*/) - ca = usage.include?('Certificate Sign') unless ca + usage = ext.value.split(/\s*,\s*/) + ca = usage.include?('Certificate Sign') unless ca when 'nsCertType' - usage = ext.value.split(/\s*,\s*/) - ca = usage.include?('SSL CA') unless ca + usage = ext.value.split(/\s*,\s*/) + ca = usage.include?('SSL CA') unless ca end end if ca if self_signed - CERT_TYPE_SELF_SIGNED + CERT_TYPE_SELF_SIGNED else - CERT_TYPE_OTHER + CERT_TYPE_OTHER end else CERT_TYPE_EE diff --git a/sample/openssl/cipher.rb b/sample/openssl/cipher.rb index 58b10d6046..a33dc3e95c 100644 --- a/sample/openssl/cipher.rb +++ b/sample/openssl/cipher.rb @@ -10,7 +10,7 @@ def crypt_by_password(alg, pass, salt, text) puts puts "--Encrypting--" - enc = OpenSSL::Cipher::Cipher.new(alg) + enc = OpenSSL::Cipher.new(alg) enc.encrypt enc.pkcs5_keyivgen(pass, salt) cipher = enc.update(text) @@ -19,7 +19,7 @@ def crypt_by_password(alg, pass, salt, text) puts puts "--Decrypting--" - dec = OpenSSL::Cipher::Cipher.new(alg) + dec = OpenSSL::Cipher.new(alg) dec.decrypt dec.pkcs5_keyivgen(pass, salt) plain = dec.update(cipher) diff --git a/sample/openssl/crlstore.rb b/sample/openssl/crlstore.rb index b305913eb0..e3a592567c 100644 --- a/sample/openssl/crlstore.rb +++ b/sample/openssl/crlstore.rb @@ -24,22 +24,22 @@ private end unless crlfiles = @c_store.get_crls(ca.subject) if crl = renew_crl(cert, ca) - @c_store.add_crl(crl) - return crl + @c_store.add_crl(crl) + return crl end return nil end crlfiles.each do |crlfile| next unless crl = load_crl(crlfile) if crl.next_update < Time.now - if new_crl = renew_crl(cert, ca) - @c_store.delete_crl(crl) - @c_store.add_crl(new_crl) - crl = new_crl - end + if new_crl = renew_crl(cert, ca) + @c_store.delete_crl(crl) + @c_store.add_crl(new_crl) + crl = new_crl + end end if check_valid(crl, ca) - return crl + return crl end end nil @@ -49,7 +49,7 @@ private @c_store.get_certs(cert.issuer).each do |cafile| ca = load_cert(cafile) if cert.verify(ca.public_key) - return ca + return ca end end nil @@ -58,10 +58,10 @@ private def fetch(location) if /\AURI:(.*)\z/ =~ location begin - c = HTTPAccess2::Client.new(ENV['http_proxy'] || ENV['HTTP_PROXY']) - c.get_content($1) + c = HTTPAccess2::Client.new(ENV['http_proxy'] || ENV['HTTP_PROXY']) + c.get_content($1) rescue NameError, StandardError - nil + nil end else nil @@ -103,10 +103,10 @@ private def renew_crl(cert, ca) if cdp = get_cdp(cert) if new_crl_str = fetch(cdp) - new_crl = load_crl_str(new_crl_str) - if check_valid(new_crl, ca) - return new_crl - end + new_crl = load_crl_str(new_crl_str) + if check_valid(new_crl, ca) + return new_crl + end end end false diff --git a/sample/openssl/echo_cli.rb b/sample/openssl/echo_cli.rb index 069a21ec94..3fbadf3361 100644 --- a/sample/openssl/echo_cli.rb +++ b/sample/openssl/echo_cli.rb @@ -15,7 +15,7 @@ ca_path = options["C"] ctx = OpenSSL::SSL::SSLContext.new() if cert_file && key_file ctx.cert = OpenSSL::X509::Certificate.new(File::read(cert_file)) - ctx.key = OpenSSL::PKey::RSA.new(File::read(key_file)) + ctx.key = OpenSSL::PKey.read(File::read(key_file)) end if ca_path ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER diff --git a/sample/openssl/echo_svr.rb b/sample/openssl/echo_svr.rb index 719de6be84..f20fb52bf5 100644 --- a/sample/openssl/echo_svr.rb +++ b/sample/openssl/echo_svr.rb @@ -13,9 +13,9 @@ ca_path = options["C"] if cert_file && key_file cert = OpenSSL::X509::Certificate.new(File::read(cert_file)) - key = OpenSSL::PKey::RSA.new(File::read(key_file)) + key = OpenSSL::PKey.read(File::read(key_file)) else - key = OpenSSL::PKey::RSA.new(512){ print "." } + key = OpenSSL::PKey::RSA.new(2048){ print "." } puts cert = OpenSSL::X509::Certificate.new cert.version = 2 @@ -25,7 +25,7 @@ else cert.issuer = name cert.not_before = Time.now cert.not_after = Time.now + 3600 - cert.public_key = key.public_key + cert.public_key = key ef = OpenSSL::X509::ExtensionFactory.new(nil,cert) cert.extensions = [ ef.create_extension("basicConstraints","CA:FALSE"), @@ -37,7 +37,7 @@ else ef.issuer_certificate = cert cert.add_extension ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always") - cert.sign(key, OpenSSL::Digest::SHA1.new) + cert.sign(key, "SHA1") end ctx = OpenSSL::SSL::SSLContext.new() diff --git a/sample/openssl/gen_csr.rb b/sample/openssl/gen_csr.rb index 4228707fdb..34b23fec1c 100644 --- a/sample/openssl/gen_csr.rb +++ b/sample/openssl/gen_csr.rb @@ -3,8 +3,6 @@ require 'optparse' require 'openssl' -include OpenSSL - def usage myname = File::basename($0) $stderr.puts <<EOS @@ -21,13 +19,13 @@ keyout = options["keyout"] || "keypair.pem" $stdout.sync = true name_str = ARGV.shift or usage() -name = X509::Name.parse(name_str) +name = OpenSSL::X509::Name.parse(name_str) keypair = nil if keypair_file - keypair = PKey::RSA.new(File.open(keypair_file).read) + keypair = OpenSSL::PKey.read(File.read(keypair_file)) else - keypair = PKey::RSA.new(1024) { putc "." } + keypair = OpenSSL::PKey::RSA.new(2048) { putc "." } puts puts "Writing #{keyout}..." File.open(keyout, "w", 0400) do |f| @@ -37,11 +35,11 @@ end puts "Generating CSR for #{name_str}" -req = X509::Request.new +req = OpenSSL::X509::Request.new req.version = 0 req.subject = name -req.public_key = keypair.public_key -req.sign(keypair, Digest::MD5.new) +req.public_key = keypair +req.sign(keypair, "MD5") puts "Writing #{csrout}..." File.open(csrout, "w") do |f| diff --git a/sample/openssl/smime_read.rb b/sample/openssl/smime_read.rb index 17394f9b8d..b617c6e3a5 100644 --- a/sample/openssl/smime_read.rb +++ b/sample/openssl/smime_read.rb @@ -1,6 +1,5 @@ require 'optparse' require 'openssl' -include OpenSSL options = ARGV.getopts("c:k:C:") @@ -10,14 +9,14 @@ ca_path = options["C"] data = $stdin.read -cert = X509::Certificate.new(File::read(cert_file)) -key = PKey::RSA.new(File::read(key_file)) -p7enc = PKCS7::read_smime(data) +cert = OpenSSL::X509::Certificate.new(File::read(cert_file)) +key = OpenSSL::PKey::read(File::read(key_file)) +p7enc = OpenSSL::PKCS7::read_smime(data) data = p7enc.decrypt(key, cert) -store = X509::Store.new +store = OpenSSL::X509::Store.new store.add_path(ca_path) -p7sig = PKCS7::read_smime(data) +p7sig = OpenSSL::PKCS7::read_smime(data) if p7sig.verify([], store) puts p7sig.data end diff --git a/sample/openssl/smime_write.rb b/sample/openssl/smime_write.rb index 5a5236c750..e1254d8748 100644 --- a/sample/openssl/smime_write.rb +++ b/sample/openssl/smime_write.rb @@ -1,6 +1,5 @@ require 'openssl' require 'optparse' -include OpenSSL options = ARGV.getopts("c:k:r:") @@ -8,16 +7,16 @@ cert_file = options["c"] key_file = options["k"] rcpt_file = options["r"] -cert = X509::Certificate.new(File::read(cert_file)) -key = PKey::RSA.new(File::read(key_file)) +cert = OpenSSL::X509::Certificate.new(File::read(cert_file)) +key = OpenSSL::PKey::read(File::read(key_file)) data = "Content-Type: text/plain\r\n" data << "\r\n" data << "This is a clear-signed message.\r\n" -p7sig = PKCS7::sign(cert, key, data, [], PKCS7::DETACHED) -smime0 = PKCS7::write_smime(p7sig) +p7sig = OpenSSL::PKCS7::sign(cert, key, data, [], OpenSSL::PKCS7::DETACHED) +smime0 = OpenSSL::PKCS7::write_smime(p7sig) -rcpt = X509::Certificate.new(File::read(rcpt_file)) -p7enc = PKCS7::encrypt([rcpt], smime0) -print PKCS7::write_smime(p7enc) +rcpt = OpenSSL::X509::Certificate.new(File::read(rcpt_file)) +p7enc = OpenSSL::PKCS7::encrypt([rcpt], smime0) +print OpenSSL::PKCS7::write_smime(p7enc) diff --git a/sample/optparse/opttest.rb b/sample/optparse/opttest.rb index 9247af494f..b2013c5253 100755 --- a/sample/optparse/opttest.rb +++ b/sample/optparse/opttest.rb @@ -18,49 +18,89 @@ ARGV.options do opts.on_tail("common options:") # no argument, shows at tail - opts.on_tail("--help", "show this message") {puts opts; exit} + opts.on_tail("--help", "show this message") do + puts opts + exit + end # mandatory argument opts.on("-r", "--require=LIBRARY", String, - "require the LIBRARY, before", - "executing your script") {|lib|@library=lib} + "require the LIBRARY, before", + "executing your script") do + |lib| + @library = lib + end # optional argument opts.on("-i", "--inplace=[EXTENSION]", - "edit ARGV files in place", # multiline description - "(make backup if EXTENSION supplied)") {|inplace| @inplace = inplace || ''} + "edit ARGV files in place", # multiline description + "(make backup if EXTENSION supplied)") do + |inplace| + @inplace = inplace || '' + end - opts.on("-N=[NUM]", Integer) {|num|@number=num} + opts.on("-N=[NUM]", Integer) do + |num| + @number = num + end # additional class - opts.on("-t", "--[no-]time[=TIME]", Time, "it's the time") {|time|@time=time} + opts.on("-t", "--[no-]time[=TIME]", Time, "it's the time") do + |time| + @time = time + end # limit argument syntax opts.on("-[0-7]", "-F", "--irs=[OCTAL]", OptionParser::OctalInteger, - "specify record separator", "(\\0, if no argument)") {|irs|@irs=irs} + "specify record separator", "(\\0, if no argument)") do + |irs| + @irs = irs + end # boolean switch(default true) @exec = true - opts.on("-n", "--no-exec[=FLAG]", TrueClass, "not really execute") {|exec|@exec=exec} + opts.on("-n", "--no-exec[=FLAG]", TrueClass, "not really execute") do + |exec| + @exec = exec + end # array - opts.on("-a", "--list[=LIST,LIST]", Array, "list") {|list|@list=list} + opts.on("-a", "--list[=LIST,LIST]", Array, "list") do + |list| + @list = list + end # fixed size array - opts.on("--pair[=car,cdr]", Array, "pair") {|x,y|@x=x; @y=y} + opts.on("--pair[=car,cdr]", Array, "pair") do + |x, y| + @x = x + @y = y + end # keyword completion opts.on("--code=CODE", CODES, CODE_ALIASES, "select coding system", - "("+CODES.join(",")+",", " "+CODE_ALIASES.keys.join(",")+")") {|c|@code=c} + "("+CODES.join(",")+",", " "+CODE_ALIASES.keys.join(",")+")") do + |c| + @code = c + end # optional argument with keyword completion - opts.on("--type[=TYPE]", [:text, :binary], "select type(text, binary)") {|t|@type=t} + opts.on("--type[=TYPE]", [:text, :binary], "select type(text, binary)") do + |t| + @type = t + end # boolean switch with optional argument(default false) - opts.on("-v", "--[no-]verbose=[FLAG]", "run verbosely") {|v|@verbose=v} + opts.on("-v", "--[no-]verbose=[FLAG]", "run verbosely") do + |v| + @verbose = v + end # easy way, set local variable - opts.on("-q", "--quit", "quit when ARGV is empty") {|q|@quit=q} + opts.on("-q", "--quit", "quit when ARGV is empty") do + |q| + @quit = q + end # adding on the fly opts.on("--add=SWITCH=[ARG]", "add option on the fly", /\A(\w+)(?:=.+)?\Z/) do diff --git a/sample/philos.rb b/sample/philos.rb index 5c8f43c819..c38aa4a1cc 100644 --- a/sample/philos.rb +++ b/sample/philos.rb @@ -1,14 +1,13 @@ # # The Dining Philosophers - thread example # -require "thread" srand #srand N=9 # number of philosophers $forks = [] for i in 0..N-1 - $forks[i] = Mutex.new + $forks[i] = Thread::Mutex.new end $state = "-o"*N diff --git a/sample/pstore.rb b/sample/pstore.rb new file mode 100644 index 0000000000..38c2305516 --- /dev/null +++ b/sample/pstore.rb @@ -0,0 +1,19 @@ +require 'pstore' + +db = PStore.new("/tmp/foo") +db.transaction do + p db.roots + ary = db["root"] = [1,2,3,4] + ary[1] = [1,1.5] +end + +1000.times do + db.transaction do + db["root"][0] += 1 + p db["root"][0] + end +end + +db.transaction(true) do + p db["root"] +end diff --git a/sample/pty/expect_sample.rb b/sample/pty/expect_sample.rb index d3b072b83c..199d98b79c 100644 --- a/sample/pty/expect_sample.rb +++ b/sample/pty/expect_sample.rb @@ -1,9 +1,10 @@ +# frozen_string_literal: true # # sample program of expect.rb # # by A. Ito # -# This program reports the latest version of ruby interpreter +# This program reports the latest version of Ruby interpreter # by connecting to ftp server at ruby-lang.org. # require 'pty' @@ -23,8 +24,17 @@ PTY.spawn("ftp ftp.ruby-lang.org") do |r_f,w_f,pid| username = 'guest' end - r_f.expect(/^(Name).*: |(word):|> /) do - w_f.puts($1 ? "ftp" : $2 ? "#{username}@" : "cd pub/ruby") + r_f.expect(/^Name.*: /) do + w_f.puts("ftp") + end + r_f.expect(/word:/) do + w_f.puts("#{username}@") + end + r_f.expect(/> /) do + w_f.puts("cd pub/ruby") + end + r_f.expect("> ") do + w_f.print "pass\n" end r_f.expect("> ") do w_f.print "dir\n" diff --git a/sample/pty/script.rb b/sample/pty/script.rb index 903a6f75bd..c6659a4807 100644 --- a/sample/pty/script.rb +++ b/sample/pty/script.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true require 'pty' if ARGV.size == 0 then @@ -34,4 +35,3 @@ PTY.spawn("/bin/csh") do |r_pty,w_pty,pid| end system "stty echo -raw lnext ^v" - diff --git a/sample/pty/shl.rb b/sample/pty/shl.rb index cdaf8d7398..980748e8f5 100644 --- a/sample/pty/shl.rb +++ b/sample/pty/shl.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true # # old-fashioned 'shl' like program # by A. Ito @@ -10,39 +11,40 @@ # q quit require 'pty' +require 'io/console' $shells = [] -$n_shells = 0 $r_pty = nil $w_pty = nil def writer - system "stty -echo raw" + STDIN.raw! begin while true c = STDIN.getc - if c == 26 then # C-z - $reader.raise(nil) + if c == ?\C-z then + $reader.raise('Suspend') return 'Suspend' end $w_pty.print c.chr $w_pty.flush end rescue - $reader.raise(nil) + $reader.raise('Exit') return 'Exit' ensure - system "stty echo -raw" + STDIN.cooked! end end $reader = Thread.new { while true begin - next if $r_pty.nil? + Thread.stop unless $r_pty c = $r_pty.getc if c.nil? then + Thread.main.raise('Exit') Thread.stop end print c.chr @@ -59,19 +61,14 @@ $reader = Thread.new { while true print ">> " STDOUT.flush + n = nil case gets when /^c/i - $shells[$n_shells] = PTY.spawn("/bin/csh") - $r_pty,$w_pty = $shells[$n_shells] - $n_shells += 1 - $reader.run - if writer == 'Exit' - $n_shells -= 1 - $shells[$n_shells] = nil - end + $shells << PTY.spawn("/bin/csh") + n = -1 when /^p/i - for i in 0..$n_shells - unless $shells[i].nil? + $shells.each_with_index do |s, i| + if s print i,"\n" end end @@ -79,14 +76,18 @@ while true n = $1.to_i if $shells[n].nil? print "\##{i} doesn't exist\n" - else - $r_pty,$w_pty = $shells[n] - $reader.run - if writer == 'Exit' then - $shells[n] = nil - end + n = nil end when /^q/i exit end + if n + $r_pty, $w_pty, pid = $shells[n] + $reader.run + if writer == 'Exit' then + Process.wait(pid) + $shells[n] = nil + $shells.pop until $shells.empty? or $shells[-1] + end + end end diff --git a/sample/rcs.awk b/sample/rcs.awk index 08979285c9..e64af5b628 100644 --- a/sample/rcs.awk +++ b/sample/rcs.awk @@ -1,33 +1,33 @@ BEGIN { - sw = 40.0; - dw = 78.0; - hdw = dw / 2.0; - w = 20.0; - h =1.0; - d = 0.2; - ss="abcdefghijklmnopqrstuvwxyz0123456789!#$%^&*()-=\\[];'`,./"; - rnd = srand(); + sw = 40.0; + dw = 78.0; + hdw = dw / 2.0; + w = 20.0; + h =1.0; + d = 0.2; + ss="abcdefghijklmnopqrstuvwxyz0123456789!#$%^&*()-=\\[];'`,./"; + rnd = srand(); } { - xr = -hdw; y = h * 1.0; maxxl = -999; - s = ""; - while (xr < hdw) { - x = xr * (1 + y) - y * w / 2; - i = (x / (1 + h) + sw /2); - c = (0 < i && i < length($0)) ? substr($0, i, 1) : "0"; - y = h - d * c; - xl = xr - w * y / (1 + y); - if (xl < -hdw || xl >= hdw || xl <= maxxl) { - t = rand() * length(ss); - c = substr(ss, t, 1); - } - else { - c = substr(s, xl + hdw, 1); - maxxl = xl; - } - s = s c; - xr = xr + 1; + xr = -hdw; y = h * 1.0; maxxl = -999; + s = ""; + while (xr < hdw) { + x = xr * (1 + y) - y * w / 2; + i = (x / (1 + h) + sw /2); + c = (0 < i && i < length($0)) ? substr($0, i, 1) : "0"; + y = h - d * c; + xl = xr - w * y / (1 + y); + if (xl < -hdw || xl >= hdw || xl <= maxxl) { + t = rand() * length(ss); + c = substr(ss, t, 1); } - print s; + else { + c = substr(s, xl + hdw, 1); + maxxl = xl; + } + s = s c; + xr = xr + 1; + } + print s; } diff --git a/sample/rinda-ring.rb b/sample/rinda-ring.rb new file mode 100644 index 0000000000..f9bd934029 --- /dev/null +++ b/sample/rinda-ring.rb @@ -0,0 +1,22 @@ +require 'rinda/ring' + +DRb.start_service +case ARGV.shift +when 's' + require 'rinda/tuplespace' + ts = Rinda::TupleSpace.new + Rinda::RingServer.new(ts) + $stdin.gets +when 'w' + finger = Rinda::RingFinger.new(nil) + finger.lookup_ring do |ts2| + p ts2 + ts2.write([:hello, :world]) + end +when 'r' + finger = Rinda::RingFinger.new(nil) + finger.lookup_ring do |ts2| + p ts2 + p ts2.take([nil, nil]) + end +end diff --git a/sample/ripper/ruby2html.rb b/sample/ripper/ruby2html.rb index 8f64f5a713..1e6b3bf550 100644 --- a/sample/ripper/ruby2html.rb +++ b/sample/ripper/ruby2html.rb @@ -73,7 +73,11 @@ class ERB end def ruby2html(f, encoding, css, print_line_number) - erb = ERB.new(TEMPLATE, nil, '>') + if RUBY_VERSION >= '2.6' + erb = ERB.new(TEMPLATE, trim_mode: '>') + else + erb = ERB.new(TEMPLATE, nil, '>') + end erb.filename = __FILE__ erb.lineno = TEMPLATE_LINE erb.result(binding()) diff --git a/sample/rss/blend.rb b/sample/rss/blend.rb deleted file mode 100755 index 351f6f373f..0000000000 --- a/sample/rss/blend.rb +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env ruby - -require "rss" - -feeds = [] -verbose = false -encoding = "UTF-8" - -def error(exception) - mark = "=" * 20 - mark = "#{mark} error #{mark}" - STDERR.puts mark - STDERR.puts exception.class - STDERR.puts exception.message - STDERR.puts exception.backtrace - STDERR.puts mark -end - -before_time = Time.now -ARGV.each do |fname| - if fname == '-v' - verbose = true - next - end - rss = nil - f = File.new(fname).read - begin - ## do validate parse - rss = RSS::Parser.parse(f) - rescue RSS::InvalidRSSError - error($!) if verbose - ## do non validate parse for invalid RSS 1.0 - begin - rss = RSS::Parser.parse(f, false) - rescue RSS::Error - ## invalid RSS. - error($!) if verbose - end - rescue RSS::Error - error($!) if verbose - end - if rss.nil? - STDERR.puts "#{fname} does not include RSS 1.0 or 0.9x/2.0" - else - begin - rss.output_encoding = encoding - rescue RSS::UnknownConversionMethodError - error($!) if verbose - end - feeds << rss - end -end -processing_time = Time.now - before_time - -rss = RSS::Maker.make("1.0") do |maker| - maker.encoding = encoding - maker.channel.about = "http://example.com/blend.rdf" - maker.channel.title = "blended feeds" - maker.channel.link = "http://example.com/" - maker.channel.description = "blended feeds generated by RSS Parser" - - feeds.each do |feed| - feed.items.each do |item| - item.setup_maker(maker.items) - end - end - - maker.items.each do |item| - item.title ||= "UNKNOWN" - item.link ||= "UNKNOWN" - end - - maker.items.do_sort = true - maker.items.max_size = 15 -end -puts rss - -STDERR.puts "Used XML parser: #{RSS::Parser.default_parser}" -STDERR.puts "Processing time: #{processing_time}s" diff --git a/sample/rss/convert.rb b/sample/rss/convert.rb deleted file mode 100755 index e6bff4c623..0000000000 --- a/sample/rss/convert.rb +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env ruby - -require "rss" - -feeds = [] -verbose = false -encoding = "UTF-8" -to_version = "1.0" - -def error(exception) - mark = "=" * 20 - mark = "#{mark} error #{mark}" - STDERR.puts mark - STDERR.puts exception.class - STDERR.puts exception.message - STDERR.puts exception.backtrace - STDERR.puts mark -end - -before_time = Time.now -ARGV.each do |fname| - case fname - when '-v' - verbose = true - next - when /^-t(0\.91|1\.0|2\.0|atom)$/ - to_version = $1 - next - end - rss = nil - f = File.read(fname) - begin - ## do validate parse - rss = RSS::Parser.parse(f) - rescue RSS::InvalidRSSError - error($!) if verbose - ## do non validate parse for invalid RSS 1.0 - begin - rss = RSS::Parser.parse(f, false) - rescue RSS::Error - ## invalid RSS. - error($!) if verbose - end - rescue RSS::Error - error($!) if verbose - end - if rss.nil? - STDERR.puts "#{fname} does not include RSS 1.0 or 0.9x/2.0" - else - begin - rss.output_encoding = encoding - rescue RSS::UnknownConversionMethodError - error($!) if verbose - end - feeds << [fname, rss] - end -end -processing_time = Time.now - before_time - -feeds.each do |fname, rss| - converted_rss = rss.to_xml(to_version) - output_name = fname.sub(/(\.[^\.]+)$/, "-#{to_version}\\1") - File.open(output_name, "w") do |output| - output.print(converted_rss) - end -end - -STDERR.puts "Used XML parser: #{RSS::Parser.default_parser}" -STDERR.puts "Processing time: #{processing_time}s" diff --git a/sample/rss/list_description.rb b/sample/rss/list_description.rb deleted file mode 100755 index 990974d8f5..0000000000 --- a/sample/rss/list_description.rb +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env ruby - -require "nkf" -class String - # From tdiary.rb - def shorten( len = 120 ) - lines = NKF::nkf( "-t -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ ) - lines[0].concat( '...' ) if lines[0] and lines[1] - lines[0] - end -end - -require "rss" - -channels = {} -verbose = false - -def error(exception) - mark = "=" * 20 - mark = "#{mark} error #{mark}" - puts mark - puts exception.class - puts exception.message - puts exception.backtrace - puts mark -end - -before_time = Time.now -ARGV.each do |fname| - if fname == '-v' - verbose = true - next - end - rss = nil - f = File.new(fname).read - begin - ## do validate parse - rss = RSS::Parser.parse(f) - rescue RSS::InvalidRSSError - error($!) if verbose - ## do non validate parse for invalid RSS 1.0 - begin - rss = RSS::Parser.parse(f, false) - rescue RSS::Error - ## invalid RSS. - error($!) if verbose - end - rescue RSS::Error - error($!) if verbose - end - if rss.nil? - puts "#{fname} does not include RSS 1.0 or 0.9x/2.0" - else - begin - rss.output_encoding = "utf-8" - rescue RSS::UnknownConversionMethodError - error($!) if verbose - end - - rss = rss.to_rss("1.0") do |maker| - maker.channel.about ||= maker.channel.link - maker.channel.description ||= "No description" - maker.items.each do |item| - item.title ||= "No title" - item.link ||= "UNKNOWN" - end - end - next if rss.nil? - - rss.items.each do |item| - channels[rss.channel.title] ||= [] - channels[rss.channel.title] << item if item.description - end - end -end -processing_time = Time.now - before_time - -channels.sort do |x, y| - x[0] <=> y[0] -end[0..20].each do |title, items| - puts "Channel: #{title}" unless items.empty? - items.sort do |x, y| - x.title <=> y.title - end[0..10].each do |item| - puts " Item: #{item.title.shorten(50)}" - puts " Description: #{item.description.shorten(50)}" - end -end - -puts "Used XML parser: #{RSS::Parser.default_parser}" -puts "Processing time: #{processing_time}s" diff --git a/sample/rss/re_read.rb b/sample/rss/re_read.rb deleted file mode 100755 index c386ab20f6..0000000000 --- a/sample/rss/re_read.rb +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env ruby - -require "rss" - -def error(exception) - mark = "=" * 20 - mark = "#{mark} error #{mark}" - puts mark - puts exception.class - puts exception.message - puts exception.backtrace - puts mark -end - -verbose = false -before_time = Time.now - -ARGV.each do |fname| - if fname == '-v' - verbose = true - next - end - source = nil - File.open(fname) do |f| - source = f.read - end - - rss = nil - read = false - begin - rss = RSS::Parser.parse(source) - puts "Re-read valid feed: #{fname}" - RSS::Parser.parse(rss.to_s) - read = true - rescue RSS::InvalidRSSError - error($!) if verbose - ## do non validate parse for invalid feed - begin - rss = RSS::Parser.parse(source, false) - rescue RSS::Error - ## invalid feed - error($!) if verbose - end - rescue RSS::Error - error($!) if verbose - end - - if rss.nil? - puts "Invalid feed: #{fname}" - elsif !read - puts "Re-read invalid feed: #{fname}" - begin - RSS::Parser.parse(rss.to_s) - rescue RSS::Error - puts " Error occurred: #{fname}" - error($!) if verbose - end - end -end - -processing_time = Time.now - before_time - -puts "Used XML parser: #{RSS::Parser.default_parser}" -puts "Processing time: #{processing_time}s" diff --git a/sample/rss/rss_recent.rb b/sample/rss/rss_recent.rb deleted file mode 100755 index 14c861284e..0000000000 --- a/sample/rss/rss_recent.rb +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env ruby - -require "nkf" -class String - # From tdiary.rb - def shorten( len = 120 ) - lines = NKF::nkf( "-t -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ ) - lines[0].concat( '...' ) if lines[0] and lines[1] - lines[0] - end -end - -require "rss" - -items = [] -verbose = false - -def error(exception) - mark = "=" * 20 - mark = "#{mark} error #{mark}" - puts mark - puts exception.class - puts exception.message - puts exception.backtrace - puts mark -end -before_time = Time.now -ARGV.each do |fname| - if fname == '-v' - verbose = true - next - end - rss = nil - f = File.new(fname).read - begin - ## do validate parse - rss = RSS::Parser.parse(f) - rescue RSS::InvalidRSSError - error($!) if verbose - ## do non validate parse for invalid RSS 1.0 - begin - rss = RSS::Parser.parse(f, false) - rescue RSS::Error - ## invalid RSS. - error($!) if verbose - end - rescue RSS::Error - error($!) if verbose - end - if rss.nil? - puts "#{fname} does not include RSS 1.0 or 0.9x/2.0" - else - begin - rss.output_encoding = "utf-8" - rescue RSS::UnknownConversionMethodError - error($!) if verbose - end - - rss = rss.to_rss("1.0") do |maker| - maker.channel.about ||= maker.channel.link - maker.channel.description ||= "No description" - maker.items.each do |item| - item.title ||= "UNKNOWN" - item.link ||= "UNKNOWN" - end - end - next if rss.nil? - - rss.items.each do |item| - items << [rss.channel, item] if item.dc_date - end - end -end -processing_time = Time.now - before_time - -items.sort do |x, y| - y[1].dc_date <=> x[1].dc_date -end[0..20].each do |channel, item| - puts "#{item.dc_date.localtime.iso8601}: " << - "#{channel.title}: #{item.title}" - puts " Description: #{item.description.shorten(50)}" if item.description -end - -puts "Used XML parser: #{RSS::Parser.default_parser}" -puts "Processing time: #{processing_time}s" diff --git a/sample/simple-bench.rb b/sample/simple-bench.rb new file mode 100644 index 0000000000..607fdbf6e9 --- /dev/null +++ b/sample/simple-bench.rb @@ -0,0 +1,140 @@ +require 'benchmark' + +def foo0 +end +def foo3 a, b, c +end +def foo6 a, b, c, d, e, f +end + +def iter0 + yield +end + +def iter1 + yield 1 +end + +def iter3 + yield 1, 2, 3 +end + +def iter6 + yield 1, 2, 3, 4, 5, 6 +end + +(1..6).each{|i| + kws = (1..i).map{|e| "k#{e}: #{e}"} + eval %Q{ + def foo_kw#{i}(#{kws.join(', ')}) + end + } + + kws = (1..i).map{|e| "k#{e}:"} + eval %Q{ + def foo_required_kw#{i}(#{kws.join(', ')}) + end + } +} + +(1..6).each{|i| + kws = (1..i).map{|e| "k#{e}: #{e} + 1"} + eval %Q{ + def foo_complex_kw#{i}(#{kws.join(', ')}) + end + } +} + +(1..6).each{|i| + kws = (1..i).map{|e| "k#{e}: #{e}"} + eval %Q{ + def iter_kw#{i} + yield #{kws.join(', ')} + end + } +} + +ary1 = [1] +ary2 = [[1, 2, 3, 4, 5]] + +test_methods = %Q{ + # empty 1 + # empty 2 + foo0 + foo3 1, 2, 3 + foo6 1, 2, 3, 4, 5, 6 + foo_kw1 + foo_kw2 + foo_kw3 + foo_kw4 + foo_kw5 + foo_kw6 + foo_kw6 k1: 1 + foo_kw6 k1: 1, k2: 2 + foo_kw6 k1: 1, k2: 2, k3: 3 + foo_kw6 k1: 1, k2: 2, k3: 3, k4: 4 + foo_kw6 k1: 1, k2: 2, k3: 3, k4: 4, k5: 5 + foo_kw6 k1: 1, k2: 2, k3: 3, k4: 4, k5: 5, k6: 6 + foo_required_kw1 k1: 1 + foo_required_kw2 k1: 1, k2: 2 + foo_required_kw3 k1: 1, k2: 2, k3: 3 + foo_required_kw4 k1: 1, k2: 2, k3: 3, k4: 4 + foo_required_kw5 k1: 1, k2: 2, k3: 3, k4: 4, k5: 5 + foo_required_kw6 k1: 1, k2: 2, k3: 3, k4: 4, k5: 5, k6: 6 + foo_complex_kw1 + foo_complex_kw2 + foo_complex_kw3 + foo_complex_kw4 + foo_complex_kw5 + foo_complex_kw6 + foo_complex_kw6 k1: 1 + foo_complex_kw6 k1: 1, k2: 2 + foo_complex_kw6 k1: 1, k2: 2, k3: 3 + foo_complex_kw6 k1: 1, k2: 2, k3: 3, k4: 4 + foo_complex_kw6 k1: 1, k2: 2, k3: 3, k4: 4, k5: 5 + foo_complex_kw6 k1: 1, k2: 2, k3: 3, k4: 4, k5: 5, k6: 6 + iter0{} + iter1{} + iter1{|a|} + iter3{} + iter3{|a|} + iter3{|a, b, c|} + iter6{} + iter6{|a|} + iter6{|a, b, c, d, e, f, g|} + iter0{|k1: nil, k2: nil, k3: nil, k4: nil, k5: nil, k6: nil|} + iter_kw1{|k1: nil, k2: nil, k3: nil, k4: nil, k5: nil, k6: nil|} + iter_kw2{|k1: nil, k2: nil, k3: nil, k4: nil, k5: nil, k6: nil|} + iter_kw3{|k1: nil, k2: nil, k3: nil, k4: nil, k5: nil, k6: nil|} + iter_kw4{|k1: nil, k2: nil, k3: nil, k4: nil, k5: nil, k6: nil|} + iter_kw5{|k1: nil, k2: nil, k3: nil, k4: nil, k5: nil, k6: nil|} + iter_kw6{|k1: nil, k2: nil, k3: nil, k4: nil, k5: nil, k6: nil|} + ary1.each{|e|} + ary1.each{|e,|} + ary1.each{|a, b, c, d, e|} + ary2.each{|e|} + ary2.each{|e,|} + ary2.each{|a, b, c, d, e|} +} + +N = 10_000_000 + +max_line = test_methods.each_line.max_by{|line| line.strip.size} +max_size = max_line.strip.size + +Benchmark.bm(max_size){|x| + + str = test_methods.each_line.map{|line| line.strip! + next if line.empty? + %Q{ + x.report(#{line.dump}){ + i = 0 + while i<#{N} + #{line} + i+=1 + end + } + } + }.join("\n") + eval str +} diff --git a/sample/tempfile.rb b/sample/tempfile.rb new file mode 100644 index 0000000000..5a363614a3 --- /dev/null +++ b/sample/tempfile.rb @@ -0,0 +1,8 @@ +require 'tempfile' + +f = Tempfile.new("foo") +f.print("foo\n") +f.close +f.open +p f.gets # => "foo\n" +f.close! diff --git a/sample/test.rb b/sample/test.rb index 26cf0a1d97..65dd9abd10 100755..100644 --- a/sample/test.rb +++ b/sample/test.rb @@ -1,2352 +1,2 @@ -#! /usr/bin/env ruby -# -*- coding: us-ascii -*- - -$testnum=0 -$ntest=0 -$failed = 0 -class Progress - def initialize - @color = nil - @quiet = nil - ARGV.each do |arg| - case arg - when /\A--color(?:=(?:always|(auto)|(never)|(.*)))?\z/ - warn "unknown --color argument: #$3" if $3 - @color = $1 ? nil : !$2 - when /\A-(q|-quiet)\z/ - @quiet = true - end - end - @tty = STDERR.tty? && !STDOUT.tty? && /dumb/ !~ ENV["TERM"] - case @color - when nil - @color = @tty - end - if @color - # dircolors-like style - colors = (colors = ENV['TEST_COLORS']) ? Hash[colors.scan(/(\w+)=([^:]*)/)] : {} - @passed = "\e[#{colors["pass"] || "32"}m" - @failed = "\e[#{colors["fail"] || "31"}m" - @reset = "\e[m" - else - @passed = @failed = @reset = "" - end - extend(Rotator) if @tty - end - - def passed_string - "." - end - def failed_string - "#{@failed}F#{@reset}" - end - def init_string - end - def finish_string - if @quiet - "\n" - else - "#{@passed}#{@ok ? 'OK' : ''} #{$testnum}#{@reset}\n" - end - end - def pass - STDERR.print passed_string - end - def fail - @ok = false - STDERR.print failed_string - end - def init - @ok = true - STDERR.print init_string - end - def finish - STDERR.print finish_string - end - - module Rotator - ROTATOR = %w[- \\ | /] - BS = "\b" * ROTATOR[0].size - def passed_string - "#{BS}#{ROTATOR[(@count += 1) % ROTATOR.size]}" - end - def failed_string - "#{BS}#{super}#{ROTATOR[@count % ROTATOR.size]}" - end - def init_string - @count = 0 - " " - end - def finish_string - s = "#{BS}#{' ' * BS.size}#{BS}#{super}" - s.gsub!(/\n/, "\r\e[2K\r") if @quiet - s - end - end -end -PROGRESS = Progress.new - -def test_check(what) - unless $ntest.zero? - PROGRESS.finish - end - STDERR.print "sample/test.rb:#{what} " - PROGRESS.init - $what = what - $testnum = 0 -end - -def test_ok(cond,n=1) - $testnum+=1 - $ntest+=1 - where = (st = caller(n)) ? st[0] : "caller error! (n=#{n}, trace=#{caller(0).join(', ')}" - if cond - PROGRESS.pass - printf "ok %d (%s)\n", $testnum, where - else - PROGRESS.fail - printf "not ok %s %d -- %s\n", $what, $testnum, where - $failed+=1 - end - STDOUT.flush - STDERR.flush -end - -# make sure conditional operators work - -test_check "assignment" - -a=[]; a[0] ||= "bar"; -test_ok(a[0] == "bar") -h={}; h["foo"] ||= "bar"; -test_ok(h["foo"] == "bar") - -aa = 5 -aa ||= 25 -test_ok(aa == 5) -bb ||= 25 -test_ok(bb == 25) -cc &&=33 -test_ok(cc == nil) -cc = 5 -cc &&=44 -test_ok(cc == 44) - -a = nil; test_ok(a == nil) -a = 1; test_ok(a == 1) -a = []; test_ok(a == []) -a = [1]; test_ok(a == [1]) -a = [nil]; test_ok(a == [nil]) -a = [[]]; test_ok(a == [[]]) -a = [1,2]; test_ok(a == [1,2]) -a = [*[]]; test_ok(a == []) -a = [*[1]]; test_ok(a == [1]) -a = [*[1,2]]; test_ok(a == [1,2]) - -a = *[]; test_ok(a == []) -a = *[1]; test_ok(a == [1]) -a = *[nil]; test_ok(a == [nil]) -a = *[[]]; test_ok(a == [[]]) -a = *[1,2]; test_ok(a == [1,2]) -a = *[*[]]; test_ok(a == []) -a = *[*[1]]; test_ok(a == [1]) -a = *[*[1,2]]; test_ok(a == [1,2]) - -a, = nil; test_ok(a == nil) -a, = 1; test_ok(a == 1) -a, = []; test_ok(a == nil) -a, = [1]; test_ok(a == 1) -a, = [nil]; test_ok(a == nil) -a, = [[]]; test_ok(a == []) -a, = 1,2; test_ok(a == 1) -a, = [1,2]; test_ok(a == 1) -a, = [*[]]; test_ok(a == nil) -a, = [*[1]]; test_ok(a == 1) -a, = *[1,2]; test_ok(a == 1) -a, = [*[1,2]]; test_ok(a == 1) - -a, = *[]; test_ok(a == nil) -a, = *[1]; test_ok(a == 1) -a, = *[nil]; test_ok(a == nil) -a, = *[[]]; test_ok(a == []) -a, = *[1,2]; test_ok(a == 1) -a, = *[*[]]; test_ok(a == nil) -a, = *[*[1]]; test_ok(a == 1) -a, = *[*[1,2]]; test_ok(a == 1) - -*a = nil; test_ok(a == [nil]) -*a = 1; test_ok(a == [1]) -*a = []; test_ok(a == []) -*a = [1]; test_ok(a == [1]) -*a = [nil]; test_ok(a == [nil]) -*a = [[]]; test_ok(a == [[]]) -*a = [1,2]; test_ok(a == [1,2]) -*a = [*[]]; test_ok(a == []) -*a = [*[1]]; test_ok(a == [1]) -*a = [*[1,2]]; test_ok(a == [1,2]) - -*a = *[]; test_ok(a == []) -*a = *[1]; test_ok(a == [1]) -*a = *[nil]; test_ok(a == [nil]) -*a = *[[]]; test_ok(a == [[]]) -*a = *[1,2]; test_ok(a == [1,2]) -*a = *[*[]]; test_ok(a == []) -*a = *[*[1]]; test_ok(a == [1]) -*a = *[*[1,2]]; test_ok(a == [1,2]) - -a,b,*c = nil; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = 1; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = []; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = [1]; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = [nil]; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = [[]]; test_ok([a,b,c] == [[],nil,[]]) -a,b,*c = [1,2]; test_ok([a,b,c] == [1,2,[]]) -a,b,*c = [*[]]; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = [*[1]]; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = [*[1,2]]; test_ok([a,b,c] == [1,2,[]]) - -a,b,*c = *[]; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = *[1]; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = *[nil]; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = *[[]]; test_ok([a,b,c] == [[],nil,[]]) -a,b,*c = *[1,2]; test_ok([a,b,c] == [1,2,[]]) -a,b,*c = *[*[]]; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = *[*[1]]; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = *[*[1,2]]; test_ok([a,b,c] == [1,2,[]]) - -def f; yield nil; end; f {|a| test_ok(a == nil)} -def f; yield 1; end; f {|a| test_ok(a == 1)} -def f; yield []; end; f {|a| test_ok(a == [])} -def f; yield [1]; end; f {|a| test_ok(a == [1])} -def f; yield [nil]; end; f {|a| test_ok(a == [nil])} -def f; yield [[]]; end; f {|a| test_ok(a == [[]])} -def f; yield [*[]]; end; f {|a| test_ok(a == [])} -def f; yield [*[1]]; end; f {|a| test_ok(a == [1])} -def f; yield [*[1,2]]; end; f {|a| test_ok(a == [1,2])} -def f; yield *[]; end; f {|a| test_ok(a == nil)} -def f; yield *[1]; end; f {|a| test_ok(a == 1)} -def f; yield *[nil]; end; f {|a| test_ok(a == nil)} -def f; yield *[[]]; end; f {|a| test_ok(a == [])} -def f; yield *[*[]]; end; f {|a| test_ok(a == nil)} -def f; yield *[*[1]]; end; f {|a| test_ok(a == 1)} -def f; yield *[*[1,2]]; end; f {|a| test_ok(a == 1)} - -def f; yield; end; f {|a,| test_ok(a == nil)} -def f; yield nil; end; f {|a,| test_ok(a == nil)} -def f; yield 1; end; f {|a,| test_ok(a == 1)} -def f; yield []; end; f {|a,| test_ok(a == nil)} -def f; yield [1]; end; f {|a,| test_ok(a == 1)} -def f; yield [nil]; end; f {|a,| test_ok(a == nil)} -def f; yield [[]]; end; f {|a,| test_ok(a == [])} -def f; yield [*[]]; end; f {|a,| test_ok(a == nil)} -def f; yield [*[1]]; end; f {|a,| test_ok(a == 1)} -def f; yield [*[1,2]]; end; f {|a,| test_ok(a == 1)} - -def f; yield *[]; end; f {|a,| test_ok(a == nil)} -def f; yield *[1]; end; f {|a,| test_ok(a == 1)} -def f; yield *[nil]; end; f {|a,| test_ok(a == nil)} -def f; yield *[[]]; end; f {|a,| test_ok(a == nil)} -def f; yield *[*[]]; end; f {|a,| test_ok(a == nil)} -def f; yield *[*[1]]; end; f {|a,| test_ok(a == 1)} -def f; yield *[*[1,2]]; end; f {|a,| test_ok(a == 1)} - -def f; yield; end; f {|*a| test_ok(a == [])} -def f; yield nil; end; f {|*a| test_ok(a == [nil])} -def f; yield 1; end; f {|*a| test_ok(a == [1])} -def f; yield []; end; f {|*a| test_ok(a == [[]])} -def f; yield [1]; end; f {|*a| test_ok(a == [[1]])} -def f; yield [nil]; end; f {|*a| test_ok(a == [[nil]])} -def f; yield [[]]; end; f {|*a| test_ok(a == [[[]]])} -def f; yield [1,2]; end; f {|*a| test_ok(a == [[1,2]])} -def f; yield [*[]]; end; f {|*a| test_ok(a == [[]])} -def f; yield [*[1]]; end; f {|*a| test_ok(a == [[1]])} -def f; yield [*[1,2]]; end; f {|*a| test_ok(a == [[1,2]])} - -def f; yield *[]; end; f {|*a| test_ok(a == [])} -def f; yield *[1]; end; f {|*a| test_ok(a == [1])} -def f; yield *[nil]; end; f {|*a| test_ok(a == [nil])} -def f; yield *[[]]; end; f {|*a| test_ok(a == [[]])} -def f; yield *[*[]]; end; f {|*a| test_ok(a == [])} -def f; yield *[*[1]]; end; f {|*a| test_ok(a == [1])} -def f; yield *[*[1,2]]; end; f {|*a| test_ok(a == [1,2])} - -def f; yield; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield nil; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield 1; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])} -def f; yield []; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield [1]; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])} -def f; yield [nil]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield [[]]; end; f {|a,b,*c| test_ok([a,b,c] == [[],nil,[]])} -def f; yield [*[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield [*[1]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])} -def f; yield [*[1,2]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,2,[]])} - -def f; yield *[]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield *[1]; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])} -def f; yield *[nil]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield *[[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield *[*[]]; end; f {|a,b,*c| test_ok([a,b,c] == [nil,nil,[]])} -def f; yield *[*[1]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,nil,[]])} -def f; yield *[*[1,2]]; end; f {|a,b,*c| test_ok([a,b,c] == [1,2,[]])} - -def r; return; end; a = r(); test_ok(a == nil) -def r; return nil; end; a = r(); test_ok(a == nil) -def r; return 1; end; a = r(); test_ok(a == 1) -def r; return []; end; a = r(); test_ok(a == []) -def r; return [1]; end; a = r(); test_ok(a == [1]) -def r; return [nil]; end; a = r(); test_ok(a == [nil]) -def r; return [[]]; end; a = r(); test_ok(a == [[]]) -def r; return [*[]]; end; a = r(); test_ok(a == []) -def r; return [*[1]]; end; a = r(); test_ok(a == [1]) -def r; return [*[1,2]]; end; a = r(); test_ok(a == [1,2]) - -def r; return *[]; end; a = r(); test_ok(a == []) -def r; return *[1]; end; a = r(); test_ok(a == [1]) -def r; return *[nil]; end; a = r(); test_ok(a == [nil]) -def r; return *[[]]; end; a = r(); test_ok(a == [[]]) -def r; return *[*[]]; end; a = r(); test_ok(a == []) -def r; return *[*[1]]; end; a = r(); test_ok(a == [1]) -def r; return *[*[1,2]]; end; a = r(); test_ok(a == [1,2]) - -def r; return *[[]]; end; a = *r(); test_ok(a == [[]]) -def r; return *[*[1,2]]; end; a = *r(); test_ok(a == [1,2]) - -def r; return; end; *a = r(); test_ok(a == [nil]) -def r; return nil; end; *a = r(); test_ok(a == [nil]) -def r; return 1; end; *a = r(); test_ok(a == [1]) -def r; return []; end; *a = r(); test_ok(a == []) -def r; return [1]; end; *a = r(); test_ok(a == [1]) -def r; return [nil]; end; *a = r(); test_ok(a == [nil]) -def r; return [[]]; end; *a = r(); test_ok(a == [[]]) -def r; return [1,2]; end; *a = r(); test_ok(a == [1,2]) -def r; return [*[]]; end; *a = r(); test_ok(a == []) -def r; return [*[1]]; end; *a = r(); test_ok(a == [1]) -def r; return [*[1,2]]; end; *a = r(); test_ok(a == [1,2]) - -def r; return *[]; end; *a = r(); test_ok(a == []) -def r; return *[1]; end; *a = r(); test_ok(a == [1]) -def r; return *[nil]; end; *a = r(); test_ok(a == [nil]) -def r; return *[[]]; end; *a = r(); test_ok(a == [[]]) -def r; return *[1,2]; end; *a = r(); test_ok(a == [1,2]) -def r; return *[*[]]; end; *a = r(); test_ok(a == []) -def r; return *[*[1]]; end; *a = r(); test_ok(a == [1]) -def r; return *[*[1,2]]; end; *a = r(); test_ok(a == [1,2]) - -def r; return *[[]]; end; *a = *r(); test_ok(a == [[]]) -def r; return *[1,2]; end; *a = *r(); test_ok(a == [1,2]) -def r; return *[*[1,2]]; end; *a = *r(); test_ok(a == [1,2]) - -def r; return; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return nil; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return 1; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]]) -def r; return []; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return [1]; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]]) -def r; return [nil]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return [[]]; end; a,b,*c = r(); test_ok([a,b,c] == [[],nil,[]]) -def r; return [1,2]; end; a,b,*c = r(); test_ok([a,b,c] == [1,2,[]]) -def r; return [*[]]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return [*[1]]; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]]) -def r; return [*[1,2]]; end; a,b,*c = r(); test_ok([a,b,c] == [1,2,[]]) - -def r; return *[]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return *[1]; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]]) -def r; return *[nil]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return *[[]]; end; a,b,*c = r(); test_ok([a,b,c] == [[],nil,[]]) -def r; return *[1,2]; end; a,b,*c = r(); test_ok([a,b,c] == [1,2,[]]) -def r; return *[*[]]; end; a,b,*c = r(); test_ok([a,b,c] == [nil,nil,[]]) -def r; return *[*[1]]; end; a,b,*c = r(); test_ok([a,b,c] == [1,nil,[]]) -def r; return *[*[1,2]]; end; a,b,*c = r(); test_ok([a,b,c] == [1,2,[]]) - -f = lambda {|r,| test_ok([] == r)} -f.call([], *[]) - -f = lambda {|r,*l| test_ok([] == r); test_ok([1] == l)} -f.call([], *[1]) - -f = lambda{|x| x} -test_ok(f.call(42) == 42) -test_ok(f.call([42]) == [42]) -test_ok(f.call([[42]]) == [[42]]) -test_ok(f.call([42,55]) == [42,55]) - -f = lambda{|x,| x} -test_ok(f.call(42) == 42) -test_ok(f.call([42]) == [42]) -test_ok(f.call([[42]]) == [[42]]) -test_ok(f.call([42,55]) == [42,55]) - -f = lambda{|*x| x} -test_ok(f.call(42) == [42]) -test_ok(f.call([42]) == [[42]]) -test_ok(f.call([[42]]) == [[[42]]]) -test_ok(f.call([42,55]) == [[42,55]]) -test_ok(f.call(42,55) == [42,55]) - -f = lambda { |a, b=42, *c| [a,b,c] } -test_ok(f.call(1 ) == [1,42,[ ]] ) -test_ok(f.call(1,43 ) == [1,43,[ ]] ) -test_ok(f.call(1,43,44) == [1,43,[44]] ) - -f = lambda { |a, b=(a|16), *c, &block| [a,b,c,block&&block[]] } -test_ok(f.call(8 ) == [8,24,[ ],nil] ) -test_ok(f.call(8,43 ) == [8,43,[ ],nil] ) -test_ok(f.call(8,43,44) == [8,43,[44],nil] ) -test_ok(f.call(8 ){45} == [8,24,[ ],45 ] ) -test_ok(f.call(8,43 ){45} == [8,43,[ ],45 ] ) -test_ok(f.call(8,43,44){45} == [8,43,[44],45 ] ) - -f = lambda { |a, b=42, *c, d| [a,b,c,d] } -test_ok(f.call(1 ,99) == [1,42,[ ],99] ) -test_ok(f.call(1,43 ,99) == [1,43,[ ],99] ) -test_ok(f.call(1,43,44,99) == [1,43,[44],99] ) - -f = lambda { |a, b=(a|16), &block| [a,b,block&&block[]] } -test_ok(f.call(8 ) == [8,24,nil] ) -test_ok(f.call(8,43) == [8,43,nil] ) -test_ok(f.call(8,43) == [8,43,nil] ) -test_ok(f.call(8 ){45} == [8,24,45 ] ) -test_ok(f.call(8,43){45} == [8,43,45 ] ) -test_ok(f.call(8,43){45} == [8,43,45 ] ) - -f = lambda { |a, b=42, d| [a,b,d] } -test_ok(f.call(1 ,99) == [1,42,99] ) -test_ok(f.call(1,43,99) == [1,43,99] ) -test_ok(f.call(1,43,99) == [1,43,99] ) - -f = lambda { |b=42, *c, &block| [b,c,block&&block[]] } -test_ok(f.call( ) == [42,[ ],nil] ) -test_ok(f.call(43 ) == [43,[ ],nil] ) -test_ok(f.call(43,44) == [43,[44],nil] ) -test_ok(f.call( ){45} == [42,[ ],45 ] ) -test_ok(f.call(43 ){45} == [43,[ ],45 ] ) -test_ok(f.call(43,44){45} == [43,[44],45 ] ) - -f = lambda { |b=42, *c, d| [b,c,d] } -test_ok(f.call( 99) == [42,[ ],99] ) -test_ok(f.call(43 ,99) == [43,[ ],99] ) -test_ok(f.call(43,44,99) == [43,[44],99] ) - -f = lambda { |b=42, &block| [b,block&&block[]] } -test_ok(f.call( ) == [42,nil] ) -test_ok(f.call(43) == [43,nil] ) -test_ok(f.call(43) == [43,nil] ) -test_ok(f.call( ){45} == [42,45 ] ) -test_ok(f.call(43){45} == [43,45 ] ) -test_ok(f.call(43){45} == [43,45 ] ) - -f = lambda { |b=42, d| [b,d] } -test_ok(f.call( 99) == [42,99] ) -test_ok(f.call(43,99) == [43,99] ) -test_ok(f.call(43,99) == [43,99] ) - - -a,=*[1] -test_ok(a == 1) -a,=*[[1]] -test_ok(a == [1]) -a,=*[[[1]]] -test_ok(a == [[1]]) - -x, (y, z) = 1, 2, 3 -test_ok([1,2,nil] == [x,y,z]) -x, (y, z) = 1, [2,3] -test_ok([1,2,3] == [x,y,z]) -x, (y, z) = 1, [2] -test_ok([1,2,nil] == [x,y,z]) - -a = loop do break; end; test_ok(a == nil) -a = loop do break nil; end; test_ok(a == nil) -a = loop do break 1; end; test_ok(a == 1) -a = loop do break []; end; test_ok(a == []) -a = loop do break [1]; end; test_ok(a == [1]) -a = loop do break [nil]; end; test_ok(a == [nil]) -a = loop do break [[]]; end; test_ok(a == [[]]) -a = loop do break [*[]]; end; test_ok(a == []) -a = loop do break [*[1]]; end; test_ok(a == [1]) -a = loop do break [*[1,2]]; end; test_ok(a == [1,2]) - -a = loop do break *[]; end; test_ok(a == []) -a = loop do break *[1]; end; test_ok(a == [1]) -a = loop do break *[nil]; end; test_ok(a == [nil]) -a = loop do break *[[]]; end; test_ok(a == [[]]) -a = loop do break *[*[]]; end; test_ok(a == []) -a = loop do break *[*[1]]; end; test_ok(a == [1]) -a = loop do break *[*[1,2]]; end; test_ok(a == [1,2]) - -*a = loop do break; end; test_ok(a == [nil]) -*a = loop do break nil; end; test_ok(a == [nil]) -*a = loop do break 1; end; test_ok(a == [1]) -*a = loop do break []; end; test_ok(a == []) -*a = loop do break [1]; end; test_ok(a == [1]) -*a = loop do break [nil]; end; test_ok(a == [nil]) -*a = loop do break [[]]; end; test_ok(a == [[]]) -*a = loop do break [1,2]; end; test_ok(a == [1,2]) -*a = loop do break [*[]]; end; test_ok(a == []) -*a = loop do break [*[1]]; end; test_ok(a == [1]) -*a = loop do break [*[1,2]]; end; test_ok(a == [1,2]) - -*a = loop do break *[]; end; test_ok(a == []) -*a = loop do break *[1]; end; test_ok(a == [1]) -*a = loop do break *[nil]; end; test_ok(a == [nil]) -*a = loop do break *[[]]; end; test_ok(a == [[]]) -*a = loop do break *[1,2]; end; test_ok(a == [1,2]) -*a = loop do break *[*[]]; end; test_ok(a == []) -*a = loop do break *[*[1]]; end; test_ok(a == [1]) -*a = loop do break *[*[1,2]]; end; test_ok(a == [1,2]) - -*a = *loop do break *[[]]; end; test_ok(a == [[]]) -*a = *loop do break *[1,2]; end; test_ok(a == [1,2]) -*a = *loop do break *[*[1,2]]; end; test_ok(a == [1,2]) - -a,b,*c = loop do break; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break nil; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break 1; end; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = loop do break []; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break [1]; end; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = loop do break [nil]; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break [[]]; end; test_ok([a,b,c] == [[],nil,[]]) -a,b,*c = loop do break [1,2]; end; test_ok([a,b,c] == [1,2,[]]) -a,b,*c = loop do break [*[]]; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break [*[1]]; end; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = loop do break [*[1,2]]; end; test_ok([a,b,c] == [1,2,[]]) - -a,b,*c = loop do break *[]; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break *[1]; end; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = loop do break *[nil]; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break *[[]]; end; test_ok([a,b,c] == [[],nil,[]]) -a,b,*c = loop do break *[1,2]; end; test_ok([a,b,c] == [1,2,[]]) -a,b,*c = loop do break *[*[]]; end; test_ok([a,b,c] == [nil,nil,[]]) -a,b,*c = loop do break *[*[1]]; end; test_ok([a,b,c] == [1,nil,[]]) -a,b,*c = loop do break *[*[1,2]]; end; test_ok([a,b,c] == [1,2,[]]) - -def r(val); a = yield(); test_ok(a == val, 2); end -r(nil){next} -r(nil){next nil} -r(1){next 1} -r([]){next []} -r([1]){next [1]} -r([nil]){next [nil]} -r([[]]){next [[]]} -r([]){next [*[]]} -r([1]){next [*[1]]} -r([1,2]){next [*[1,2]]} - -r([]){next *[]} -r([1]){next *[1]} -r([nil]){next *[nil]} -r([[]]){next *[[]]} -r([]){next *[*[]]} -r([1]){next *[*[1]]} -r([1,2]){next *[*[1,2]]} - -def r(val); *a = yield(); test_ok(a == val, 2); end -r([nil]){next} -r([nil]){next nil} -r([1]){next 1} -r([]){next []} -r([1]){next [1]} -r([nil]){next [nil]} -r([[]]){next [[]]} -r([1,2]){next [1,2]} -r([]){next [*[]]} -r([1]){next [*[1]]} -r([1,2]){next [*[1,2]]} - -def r(val); *a = *yield(); test_ok(a == val, 2); end -r([[]]){next *[[]]} -r([1,2]){next *[1,2]} -r([1,2]){next *[*[1,2]]} - -def r(val); a,b,*c = yield(); test_ok([a,b,c] == val, 2); end -r([nil,nil,[]]){next} -r([nil,nil,[]]){next nil} -r([1,nil,[]]){next 1} -r([nil,nil,[]]){next []} -r([1,nil,[]]){next [1]} -r([nil,nil,[]]){next [nil]} -r([[],nil,[]]){next [[]]} -r([1,2,[]]){next [1,2]} -r([nil,nil,[]]){next [*[]]} -r([1,nil,[]]){next [*[1]]} -r([1,2,[]]){next [*[1,2]]} - -def r(val); a,b,*c = *yield(); test_ok([a,b,c] == val, 2); end -r([[],nil,[]]){next *[[]]} -r([1,2,[]]){next *[1,2]} -r([1,2,[]]){next *[*[1,2]]} - -test_check "condition" - -$x = '0'; - -$x == $x && test_ok(true) -$x != $x && test_ok(false) -$x == $x || test_ok(false) -$x != $x || test_ok(true) - -# first test to see if we can run the tests. - -test_check "if/unless"; - -$x = 'test'; -test_ok(if $x == $x then true else false end) -$bad = false -unless $x == $x - $bad = true -end -test_ok(!$bad) -test_ok(unless $x != $x then true else false end) - -test_check "case" - -case 5 -when 1, 2, 3, 4, 6, 7, 8 - test_ok(false) -when 5 - test_ok(true) -end - -case 5 -when 5 - test_ok(true) -when 1..10 - test_ok(false) -end - -case 5 -when 1..10 - test_ok(true) -else - test_ok(false) -end - -case 5 -when 5 - test_ok(true) -else - test_ok(false) -end - -case "foobar" -when /^f.*r$/ - test_ok(true) -else - test_ok(false) -end - -test_check "while/until"; - -tmp = open("while_tmp", "w") -tmp.print "tvi925\n"; -tmp.print "tvi920\n"; -tmp.print "vt100\n"; -tmp.print "Amiga\n"; -tmp.print "paper\n"; -tmp.close - -# test break - -tmp = open("while_tmp", "r") -test_ok(tmp.kind_of?(File)) - -while line = tmp.gets() - break if /vt100/ =~ line -end - -test_ok(!tmp.eof? && /vt100/ =~ line) -tmp.close - -# test next -$bad = false -tmp = open("while_tmp", "r") -while line = tmp.gets() - next if /vt100/ =~ line - $bad = 1 if /vt100/ =~ line -end -test_ok(!(!tmp.eof? || /vt100/ =~ line || $bad)) -tmp.close - -# test redo -$bad = false -tmp = open("while_tmp", "r") -while line = tmp.gets() - lastline = line - line = line.gsub(/vt100/, 'VT100') - if lastline != line - line.gsub!('VT100', 'Vt100') - redo - end - $bad = 1 if /vt100/ =~ line - $bad = 1 if /VT100/ =~ line -end -test_ok(tmp.eof? && !$bad) -tmp.close - -sum=0 -for i in 1..10 - sum += i - i -= 1 - if i > 0 - redo - end -end -test_ok(sum == 220) - -# test interval -$bad = false -tmp = open("while_tmp", "r") -while line = tmp.gets() - break if 3 - case line - when /vt100/, /Amiga/, /paper/ - $bad = true - end -end -test_ok(!$bad) -tmp.close - -File.unlink "while_tmp" or `/bin/rm -f "while_tmp"` -test_ok(!File.exist?("while_tmp")) - -i = 0 -until i>4 - i+=1 -end -test_ok(i>4) - - -# exception handling -test_check "exception"; - -begin - raise "this must be handled" - test_ok(false) -rescue - test_ok(true) -end - -$bad = true -begin - raise "this must be handled no.2" -rescue - if $bad - $bad = false - retry - test_ok(false) - end -end -test_ok(true) - -# exception in rescue clause -$string = "this must be handled no.3" -begin - begin - raise "exception in rescue clause" - rescue - raise $string - end - test_ok(false) -rescue => e - test_ok($! == e) - test_ok(e.message == $string) - test_ok(e != $string) -end - -# exception in ensure clause -begin - begin - raise "this must be handled no.4" - ensure - raise "exception in ensure clause" - end - test_ok(false) -rescue - test_ok(true) -end - -$bad = true -begin - begin - raise "this must be handled no.5" - ensure - $bad = false - end -rescue -end -test_ok(!$bad) - -$bad = true -begin - begin - raise "this must be handled no.6" - ensure - $bad = false - end -rescue -end -test_ok(!$bad) - -$bad = true -while true - begin - break - ensure - $bad = false - end -end -test_ok(!$bad) - -test_ok(catch(:foo) { - loop do - loop do - throw :foo, true - break - end - break - test_ok(false) # should no reach here - end - false - }) - -test_check "array" -test_ok([1, 2] + [3, 4] == [1, 2, 3, 4]) -test_ok([1, 2] * 2 == [1, 2, 1, 2]) -test_ok([1, 2] * ":" == "1:2") - -test_ok([1, 2].hash == [1, 2].hash) - -test_ok([1,2,3] & [2,3,4] == [2,3]) -test_ok([1,2,3] | [2,3,4] == [1,2,3,4]) -test_ok([1,2,3] - [2,3] == [1]) - -$x = [0, 1, 2, 3, 4, 5] -test_ok($x[2] == 2) -test_ok($x[1..3] == [1, 2, 3]) -test_ok($x[1,3] == [1, 2, 3]) - -$x[0, 2] = 10 -test_ok($x[0] == 10 && $x[1] == 2) - -$x[0, 0] = -1 -test_ok($x[0] == -1 && $x[1] == 10) - -$x[-1, 1] = 20 -test_ok($x[-1] == 20 && $x.pop == 20) - -# array and/or -test_ok(([1,2,3]&[2,4,6]) == [2]) -test_ok(([1,2,3]|[2,4,6]) == [1,2,3,4,6]) - -# compact -$x = [nil, 1, nil, nil, 5, nil, nil] -$x.compact! -test_ok($x == [1, 5]) - -# uniq -$x = [1, 1, 4, 2, 5, 4, 5, 1, 2] -$x.uniq! -test_ok($x == [1, 4, 2, 5]) - -# empty? -test_ok(!$x.empty?) -$x = [] -test_ok($x.empty?) - -# sort -$x = ["it", "came", "to", "pass", "that", "..."] -$x = $x.sort.join(" ") -test_ok($x == "... came it pass that to") -$x = [2,5,3,1,7] -$x.sort!{|a,b| a<=>b} # sort with condition -test_ok($x == [1,2,3,5,7]) -$x.sort!{|a,b| b-a} # reverse sort -test_ok($x == [7,5,3,2,1]) - -# split test -$x = "The Book of Mormon" -test_ok($x.split(//).reverse!.join == $x.reverse) -test_ok($x.reverse == $x.reverse!) -test_ok("1 byte string".split(//).reverse.join(":") == "g:n:i:r:t:s: :e:t:y:b: :1") -$x = "a b c d" -test_ok($x.split == ['a', 'b', 'c', 'd']) -test_ok($x.split(' ') == ['a', 'b', 'c', 'd']) -test_ok(defined? "a".chomp) -test_ok("abc".scan(/./) == ["a", "b", "c"]) -test_ok("1a2b3c".scan(/(\d.)/) == [["1a"], ["2b"], ["3c"]]) -# non-greedy match -test_ok("a=12;b=22".scan(/(.*?)=(\d*);?/) == [["a", "12"], ["b", "22"]]) - -$x = [1] -test_ok(($x * 5).join(":") == '1:1:1:1:1') -test_ok(($x * 1).join(":") == '1') -test_ok(($x * 0).join(":") == '') - -*$x = *(1..7).to_a -test_ok($x.size == 7) -test_ok($x == [1, 2, 3, 4, 5, 6, 7]) - -$x = [1,2,3] -$x[1,0] = $x -test_ok($x == [1,1,2,3,2,3]) - -$x = [1,2,3] -$x[-1,0] = $x -test_ok($x == [1,2,1,2,3,3]) - -$x = [1,2,3] -$x.concat($x) -test_ok($x == [1,2,3,1,2,3]) - -test_check "hash" -$x = {1=>2, 2=>4, 3=>6} - -test_ok($x[1] == 2) - -test_ok(begin - for k,v in $x - raise if k*2 != v - end - true - rescue - false - end) - -test_ok($x.length == 3) -test_ok($x.has_key?(1)) -test_ok($x.has_value?(4)) -test_ok($x.values_at(2,3) == [4,6]) -test_ok($x == {1=>2, 2=>4, 3=>6}) - -$z = $x.keys.sort.join(":") -test_ok($z == "1:2:3") - -$z = $x.values.sort.join(":") -test_ok($z == "2:4:6") -test_ok($x == $x) - -$x.shift -test_ok($x.length == 2) - -$z = [1,2] -$x[$z] = 256 -test_ok($x[$z] == 256) - -$x = Hash.new(0) -$x[1] = 1 -test_ok($x[1] == 1) -test_ok($x[2] == 0) - -$x = Hash.new([]) -test_ok($x[22] == []) -test_ok($x[22].equal?($x[22])) - -$x = Hash.new{[]} -test_ok($x[22] == []) -test_ok(!$x[22].equal?($x[22])) - -$x = Hash.new{|h,k| $z = k; h[k] = k*2} -$z = 0 -test_ok($x[22] == 44) -test_ok($z == 22) -$z = 0 -test_ok($x[22] == 44) -test_ok($z == 0) -$x.default = 5 -test_ok($x[23] == 5) - -$x = Hash.new -def $x.default(k) - $z = k - self[k] = k*2 -end -$z = 0 -test_ok($x[22] == 44) -test_ok($z == 22) -$z = 0 -test_ok($x[22] == 44) -test_ok($z == 0) - -test_check "iterator" - -test_ok(!iterator?) - -def ttt - test_ok(iterator?) -end -ttt{} - -# yield at top level -test_ok(!defined?(yield)) - -$x = [1, 2, 3, 4] -$y = [] - -# iterator over array -for i in $x - $y.push i -end -test_ok($x == $y) - -# nested iterator -def tt - 1.upto(10) {|i| - yield i - } -end - -i=0 -tt{|i| break if i == 5} -test_ok(i == 0) - -def tt2(dummy) - yield 1 -end - -def tt3(&block) - tt2(raise(ArgumentError,""),&block) -end - -$x = false -begin - tt3{} -rescue ArgumentError - $x = true -rescue Exception -end -test_ok($x) - -def tt4 &block - tt2(raise(ArgumentError,""),&block) -end -$x = false -begin - tt4{} -rescue ArgumentError - $x = true -rescue Exception -end -test_ok($x) - -# iterator break/redo/next/retry -done = true -loop{ - break - done = false # should not reach here -} -test_ok(done) - -done = false -$bad = false -loop { - break if done - done = true - next - $bad = true # should not reach here -} -test_ok(!$bad) - -done = false -$bad = false -loop { - break if done - done = true - redo - $bad = true # should not reach here -} -test_ok(!$bad) - -$x = [] -for i in 1 .. 7 - $x.push i -end -test_ok($x.size == 7) -test_ok($x == [1, 2, 3, 4, 5, 6, 7]) - -# append method to built-in class -class Array - def iter_test1 - collect{|e| [e, yield(e)]}.sort{|a,b|a[1]<=>b[1]} - end - def iter_test2 - a = collect{|e| [e, yield(e)]} - a.sort{|a,b|a[1]<=>b[1]} - end -end -$x = [[1,2],[3,4],[5,6]] -test_ok($x.iter_test1{|x|x} == $x.iter_test2{|x|x}) - -class IterTest - def initialize(e); @body = e; end - - def each0(&block); @body.each(&block); end - def each1(&block); @body.each {|*x| block.call(*x) } end - def each2(&block); @body.each {|*x| block.call(x) } end - def each3(&block); @body.each {|x| block.call(*x) } end - def each4(&block); @body.each {|x| block.call(x) } end - def each5; @body.each {|*x| yield(*x) } end - def each6; @body.each {|*x| yield(x) } end - def each7; @body.each {|x| yield(*x) } end - def each8; @body.each {|x| yield(x) } end - - def f(a) - a - end -end -test_ok(IterTest.new(nil).method(:f).to_proc.call([1]) == [1]) -m = /\w+/.match("abc") -test_ok(IterTest.new(nil).method(:f).to_proc.call([m]) == [m]) - -IterTest.new([0]).each0 {|x| test_ok(x == 0)} -IterTest.new([1]).each1 {|x| test_ok(x == 1)} -IterTest.new([2]).each2 {|x| test_ok(x == [2])} -#IterTest.new([3]).each3 {|x| test_ok(x == 3)} -IterTest.new([4]).each4 {|x| test_ok(x == 4)} -IterTest.new([5]).each5 {|x| test_ok(x == 5)} -IterTest.new([6]).each6 {|x| test_ok(x == [6])} -#IterTest.new([7]).each7 {|x| test_ok(x == 7)} -IterTest.new([8]).each8 {|x| test_ok(x == 8)} - -IterTest.new([[0]]).each0 {|x| test_ok(x == [0])} -IterTest.new([[1]]).each1 {|x| test_ok(x == [1])} -IterTest.new([[2]]).each2 {|x| test_ok(x == [[2]])} -IterTest.new([[3]]).each3 {|x| test_ok(x == 3)} -IterTest.new([[4]]).each4 {|x| test_ok(x == [4])} -IterTest.new([[5]]).each5 {|x| test_ok(x == [5])} -IterTest.new([[6]]).each6 {|x| test_ok(x == [[6]])} -IterTest.new([[7]]).each7 {|x| test_ok(x == 7)} -IterTest.new([[8]]).each8 {|x| test_ok(x == [8])} - -IterTest.new([[0,0]]).each0 {|*x| test_ok(x == [[0,0]])} -IterTest.new([[8,8]]).each8 {|*x| test_ok(x == [[8,8]])} - -def m0(v) - v -end - -def m1 - m0(block_given?) -end -test_ok(m1{p 'test'}) -test_ok(!m1) - -def m - m0(block_given?,&Proc.new{}) -end -test_ok(m1{p 'test'}) -test_ok(!m1) - -class C - include Enumerable - def initialize - @a = [1,2,3] - end - def each(&block) - @a.each(&block) - end -end - -test_ok(C.new.collect{|n| n} == [1,2,3]) - -test_ok(Proc == lambda{}.class) -test_ok(Proc == Proc.new{}.class) -lambda{|a|test_ok(a==1)}.call(1) -def block_test(klass, &block) - test_ok(klass === block) -end - -block_test(NilClass) -block_test(Proc){} - -def call_argument_test(state, proc, *args) - x = state - begin - proc.call(*args) - rescue ArgumentError - x = !x - end - test_ok(x,2) -end - -call_argument_test(true, lambda{||}) -call_argument_test(false, lambda{||}, 1) -call_argument_test(true, lambda{|a,|}, 1) -call_argument_test(false, lambda{|a,|}) -call_argument_test(false, lambda{|a,|}, 1,2) - -call_argument_test(true, Proc.new{||}) -call_argument_test(true, Proc.new{||}, 1) -call_argument_test(true, Proc.new{|a,|}, 1) -call_argument_test(true, Proc.new{|a,|}) -call_argument_test(true, Proc.new{|a,|}, 1,2) - -def block_get(&block) - block -end - -test_ok(Proc == block_get{}.class) -call_argument_test(true, block_get{||}) -call_argument_test(true, block_get{||}, 1) -call_argument_test(true, block_get{|a,|}, 1) -call_argument_test(true, block_get{|a,|}) -call_argument_test(true, block_get{|a,|}, 1,2) - -call_argument_test(true, block_get(&lambda{||})) -call_argument_test(false, block_get(&lambda{||}),1) -call_argument_test(true, block_get(&lambda{|a,|}),1) -call_argument_test(false, block_get(&lambda{|a,|}),1,2) - -blk = block_get{11} -test_ok(blk.class == Proc) -test_ok(blk.to_proc.class == Proc) -test_ok(blk.clone.call == 11) -test_ok(block_get(&blk).class == Proc) - -lmd = lambda{44} -test_ok(lmd.class == Proc) -test_ok(lmd.to_proc.class == Proc) -test_ok(lmd.clone.call == 44) -test_ok(block_get(&lmd).class == Proc) - -test_ok(Proc.new{|a,| a}.yield(1,2,3) == 1) -call_argument_test(true, Proc.new{|a,|}, 1,2) - -test_ok(Proc.new{|&b| b.call(10)}.call {|x| x} == 10) -test_ok(Proc.new{|a,&b| b.call(a)}.call(12) {|x| x} == 12) - -def test_return1 - Proc.new { - return 55 - }.yield + 5 -end -test_ok(test_return1() == 55) -def test_return2 - lambda { - return 55 - }.call + 5 -end -test_ok(test_return2() == 60) - -def proc_call(&b) - b.call -end -def proc_yield() - yield -end -def proc_return1 - lambda{return 42}.call+1 -end -test_ok(proc_return1() == 43) -def proc_return2 - ->{return 42}.call+1 -end -test_ok(proc_return2() == 43) -def proc_return3 - proc_call{return 42}+1 -end -test_ok(proc_return3() == 42) -def proc_return4 - proc_yield{return 42}+1 -end -test_ok(proc_return4() == 42) - -def ljump_test(state, proc, *args) - x = state - begin - proc.call(*args) - rescue LocalJumpError - x = !x - end - test_ok(x,2) -end - -ljump_test(false, block_get{break}) -ljump_test(true, lambda{break}) - -def exit_value_test(&block) - block.call -rescue LocalJumpError - $!.exit_value -end - -test_ok(45 == exit_value_test{break 45}) - -test_ok(55 == begin - block_get{break 55}.call - rescue LocalJumpError - $!.exit_value - end) - -def block_call(&block) - block.call -end - -def test_b1 - block_call{break 11} -end -test_ok(test_b1() == 11) - -def ljump_rescue(r) - begin - yield - rescue LocalJumpError => e - r if /from proc-closure/ =~ e.message - end -end - -def test_b2 - ljump_rescue(22) do - block_get{break 21}.call - end -end -test_ok(test_b2() == 22) - -def test_b3 - ljump_rescue(33) do - Proc.new{break 31}.yield - end -end -test_ok(test_b3() == 33) - -def test_b4 - lambda{break 44}.call -end -test_ok(test_b4() == 44) - -def test_b5 - ljump_rescue(55) do - b = block_get{break 54} - block_call(&b) - end -end -test_ok(test_b5() == 55) - -def test_b6 - b = lambda{break 67} - block_call(&b) - 66 -end -test_ok(test_b6() == 66) - -def util_r7 - block_get{break 78} -end - -def test_b7 - b = util_r7() - ljump_rescue(77) do - block_call(&b) - end -end -test_ok(test_b7() == 77) - -def util_b8(&block) - block_call(&block) -end - -def test_b8 - util_b8{break 88} -end -test_ok(test_b8() == 88) - -def util_b9(&block) - lambda{block.call; 98}.call -end - -def test_b9 - util_b9{break 99} -end -test_ok(test_b9() == 99) - -def util_b10 - util_b9{break 100} -end - -def test_b10 - util_b10() -end -test_ok(test_b10() == 100) - -def test_b11 - ljump_rescue(111) do - loop do - Proc.new{break 110}.yield - break 112 - end - end -end -test_ok(test_b11() == 111) - -def test_b12 - loop do - break lambda{break 122}.call - break 121 - end -end -test_ok(test_b12() == 122) - -def test_b13 - ljump_rescue(133) do - while true - Proc.new{break 130}.yield - break 131 - end - end -end -test_ok(test_b13() == 133) - -def test_b14 - while true - break lambda{break 144}.call - break 143 - end -end -test_ok(test_b14() == 144) - -def test_b15 - [0].each {|c| yield 1 } - 156 -end -test_ok(test_b15{|e| break 155 } == 155) - -def marity_test(m) - method = method(m) - test_ok(method.arity == method.to_proc.arity, 2) -end -marity_test(:test_ok) -marity_test(:marity_test) -marity_test(:p) - -lambda(&method(:test_ok)).call(true) -lambda(&block_get{|a,n| test_ok(a,n)}).call(true, 2) - -class ITER_TEST1 - def a - block_given? - end -end - -class ITER_TEST2 < ITER_TEST1 - def a - test_ok(super) - super - end -end -test_ok(ITER_TEST2.new.a {}) - -class ITER_TEST3 - def foo x - return yield if block_given? - x - end -end - -class ITER_TEST4 < ITER_TEST3 - def foo x - test_ok(super == yield) - test_ok(super(x, &nil) == x) - end -end - -ITER_TEST4.new.foo(44){55} - -class ITER_TEST5 - def tt(aa) - aa - end - - def uu(a) - class << self - define_method(:tt) do |sym| - super(sym) - end - end - end - - def xx(*x) - x.size - end -end - -a = ITER_TEST5.new -a.uu(12) -test_ok(a.tt(1) == 1) - -class ITER_TEST6 < ITER_TEST5 - def xx(*a) - a << 12 - super - end -end - -test_ok(ITER_TEST6.new.xx([24]) == 2) - -test_check "float" -test_ok(2.6.floor == 2) -test_ok((-2.6).floor == -3) -test_ok(2.6.ceil == 3) -test_ok((-2.6).ceil == -2) -test_ok(2.6.truncate == 2) -test_ok((-2.6).truncate == -2) -test_ok(2.6.round == 3) -test_ok((-2.4).truncate == -2) -test_ok((13.4 % 1 - 0.4).abs < 0.0001) -nan = 0.0/0 -def nan_test(x,y) - test_ok(x != y) - test_ok((x < y) == false) - test_ok((x > y) == false) - test_ok((x <= y) == false) - test_ok((x >= y) == false) -end -nan_test(nan, nan) -nan_test(nan, 0) -nan_test(nan, 1) -nan_test(nan, -1) -nan_test(nan, 1000) -nan_test(nan, -1000) -nan_test(nan, 1_000_000_000_000) -nan_test(nan, -1_000_000_000_000) -nan_test(nan, 100.0); -nan_test(nan, -100.0); -nan_test(nan, 0.001); -nan_test(nan, -0.001); -nan_test(nan, 1.0/0); -nan_test(nan, -1.0/0); - -#s = "3.7517675036461267e+17" -#test_ok(s == sprintf("%.16e", s.to_f)) -f = 3.7517675036461267e+17 -test_ok(f == sprintf("%.16e", f).to_f) - - -test_check "bignum" -def fact(n) - return 1 if n == 0 - f = 1 - while n>0 - f *= n - n -= 1 - end - return f -end -$x = fact(40) -test_ok($x == $x) -test_ok($x == fact(40)) -test_ok($x < $x+2) -test_ok($x > $x-2) -test_ok($x == 815915283247897734345611269596115894272000000000) -test_ok($x != 815915283247897734345611269596115894272000000001) -test_ok($x+1 == 815915283247897734345611269596115894272000000001) -test_ok($x/fact(20) == 335367096786357081410764800000) -$x = -$x -test_ok($x == -815915283247897734345611269596115894272000000000) -test_ok(2-(2**32) == -(2**32-2)) -test_ok(2**32 - 5 == (2**32-3)-2) - -$good = true; -for i in 1000..1014 - $good = false if ((1 << i) != (2**i)) -end -test_ok($good) - -$good = true; -n1= 1 << 1000 -for i in 1000..1014 - $good = false if ((1 << i) != n1) - n1 *= 2 -end -test_ok($good) - -$good = true; -n2=n1 -for i in 1..10 - n1 = n1 / 2 - n2 = n2 >> 1 - $good = false if (n1 != n2) -end -test_ok($good) - -$good = true; -for i in 4000..4096 - n1 = 1 << i; - if (n1**2-1) / (n1+1) != (n1-1) - $good = false - end -end -test_ok($good) - -b = 10**80 -a = b * 9 + 7 -test_ok(7 == a.modulo(b)) -test_ok(-b + 7 == a.modulo(-b)) -test_ok(b + -7 == (-a).modulo(b)) -test_ok(-7 == (-a).modulo(-b)) -test_ok(7 == a.remainder(b)) -test_ok(7 == a.remainder(-b)) -test_ok(-7 == (-a).remainder(b)) -test_ok(-7 == (-a).remainder(-b)) - -test_ok(10**40+10**20 == 10000000000000000000100000000000000000000) -test_ok(10**40/10**20 == 100000000000000000000) - -a = 677330545177305025495135714080 -b = 14269972710765292560 -test_ok(a % b == 0) -test_ok(-a % b == 0) - -def shift_test(a) - b = a / (2 ** 32) - c = a >> 32 - test_ok(b == c) - - b = a * (2 ** 32) - c = a << 32 - test_ok(b == c) -end - -shift_test(-4518325415524767873) -shift_test(-0xfffffffffffffffff) - -test_check "string & char" - -test_ok("abcd" == "abcd") -test_ok("abcd" =~ /abcd/) -test_ok("abcd" === "abcd") -# compile time string concatenation -test_ok("ab" "cd" == "abcd") -test_ok("#{22}aa" "cd#{44}" == "22aacd44") -test_ok("#{22}aa" "cd#{44}" "55" "#{66}" == "22aacd445566") -test_ok("abc" !~ /^$/) -test_ok("abc\n" !~ /^$/) -test_ok("abc" !~ /^d*$/) -test_ok(("abc" =~ /d*$/) == 3) -test_ok("" =~ /^$/) -test_ok("\n" =~ /^$/) -test_ok("a\n\n" =~ /^$/) -test_ok("abcabc" =~ /.*a/ && $& == "abca") -test_ok("abcabc" =~ /.*c/ && $& == "abcabc") -test_ok("abcabc" =~ /.*?a/ && $& == "a") -test_ok("abcabc" =~ /.*?c/ && $& == "abc") -test_ok(/(.|\n)*?\n(b|\n)/ =~ "a\nb\n\n" && $& == "a\nb") - -test_ok(/^(ab+)+b/ =~ "ababb" && $& == "ababb") -test_ok(/^(?:ab+)+b/ =~ "ababb" && $& == "ababb") -test_ok(/^(ab+)+/ =~ "ababb" && $& == "ababb") -test_ok(/^(?:ab+)+/ =~ "ababb" && $& == "ababb") - -test_ok(/(\s+\d+){2}/ =~ " 1 2" && $& == " 1 2") -test_ok(/(?:\s+\d+){2}/ =~ " 1 2" && $& == " 1 2") - -$x = <<END; -ABCD -ABCD -END -$x.gsub!(/((.|\n)*?)B((.|\n)*?)D/, '\1\3') -test_ok($x == "AC\nAC\n") - -test_ok("foobar" =~ /foo(?=(bar)|(baz))/) -test_ok("foobaz" =~ /foo(?=(bar)|(baz))/) - -$foo = "abc" -test_ok("#$foo = abc" == "abc = abc") -test_ok("#{$foo} = abc" == "abc = abc") - -foo = "abc" -test_ok("#{foo} = abc" == "abc = abc") - -test_ok('-' * 5 == '-----') -test_ok('-' * 1 == '-') -test_ok('-' * 0 == '') - -foo = '-' -test_ok(foo * 5 == '-----') -test_ok(foo * 1 == '-') -test_ok(foo * 0 == '') - -$x = "a.gif" -test_ok($x.sub(/.*\.([^\.]+)$/, '\1') == "gif") -test_ok($x.sub(/.*\.([^\.]+)$/, 'b.\1') == "b.gif") -test_ok($x.sub(/.*\.([^\.]+)$/, '\2') == "") -test_ok($x.sub(/.*\.([^\.]+)$/, 'a\2b') == "ab") -test_ok($x.sub(/.*\.([^\.]+)$/, '<\&>') == "<a.gif>") - -# character constants(assumes ASCII) -test_ok("a"[0] == ?a) -test_ok(?a == ?a) -test_ok(?\C-a == "\1") -test_ok(?\M-a == "\341") -test_ok(?\M-\C-a == "\201") -test_ok("a".upcase![0] == ?A) -test_ok("A".downcase![0] == ?a) -test_ok("abc".tr!("a-z", "A-Z") == "ABC") -test_ok("aabbcccc".tr_s!("a-z", "A-Z") == "ABC") -test_ok("abcc".squeeze!("a-z") == "abc") -test_ok("abcd".delete!("bc") == "ad") - -$x = "abcdef" -$y = [ ?a, ?b, ?c, ?d, ?e, ?f ] -$bad = false -$x.each_byte {|i| - if i.chr != $y.shift - $bad = true - break - end -} -test_ok(!$bad) - -s = "a string" -s[0..s.size]="another string" -test_ok(s == "another string") - -s = <<EOS -#{ -[1,2,3].join(",") -} -EOS -test_ok(s == "1,2,3\n") -test_ok("Just".to_i(36) == 926381) -test_ok("-another".to_i(36) == -23200231779) -test_ok(1299022.to_s(36) == "ruby") -test_ok(-1045307475.to_s(36) == "-hacker") -test_ok("Just_another_Ruby_hacker".to_i(36) == 265419172580680477752431643787347) -test_ok(-265419172580680477752431643787347.to_s(36) == "-justanotherrubyhacker") - -a = [] -(0..255).each {|n| - ch = [n].pack("C") - a.push ch if /a#{Regexp.quote ch}b/x =~ "ab" -} -test_ok(a.size == 0) - -test_check "assignment" -a = nil -test_ok(defined?(a)) -test_ok(a == nil) - -# multiple asignment -a, b = 1, 2 -test_ok(a == 1 && b == 2) - -a, b = b, a -test_ok(a == 2 && b == 1) - -a, = 1,2 -test_ok(a == 1) - -a, *b = 1, 2, 3 -test_ok(a == 1 && b == [2, 3]) - -a, (b, c), d = 1, [2, 3], 4 -test_ok(a == 1 && b == 2 && c == 3 && d == 4) - -*a = 1, 2, 3 -test_ok(a == [1, 2, 3]) - -*a = 4 -test_ok(a == [4]) - -*a = nil -test_ok(a == [nil]) - -test_check "call" -def aaa(a, b=100, *rest) - res = [a, b] - res += rest if rest - return res -end - -# not enough argument -begin - aaa() # need at least 1 arg - test_ok(false) -rescue - test_ok(true) -end - -begin - aaa # no arg given (exception raised) - test_ok(false) -rescue - test_ok(true) -end - -test_ok(aaa(1) == [1, 100]) -test_ok(aaa(1, 2) == [1, 2]) -test_ok(aaa(1, 2, 3, 4) == [1, 2, 3, 4]) -test_ok(aaa(1, *[2, 3, 4]) == [1, 2, 3, 4]) - -test_check "proc" -$proc = Proc.new{|i| i} -test_ok($proc.call(2) == 2) -test_ok($proc.call(3) == 3) - -$proc = Proc.new{|i| i*2} -test_ok($proc.call(2) == 4) -test_ok($proc.call(3) == 6) - -Proc.new{ - iii=5 # nested local variable - $proc = Proc.new{|i| - iii = i - } - $proc2 = Proc.new { - $x = iii # nested variables shared by procs - } - # scope of nested variables - test_ok(defined?(iii)) -}.call -test_ok(!defined?(iii)) # out of scope - -loop{iii=5; test_ok(eval("defined? iii")); break} -loop { - iii = 10 - def dyna_var_check - loop { - test_ok(!defined?(iii)) - break - } - end - dyna_var_check - break -} -$x=0 -$proc.call(5) -$proc2.call -test_ok($x == 5) - -if defined? Process.kill - test_check "signal" - - $x = 0 - trap "SIGINT", Proc.new{|sig| $x = 2} - Process.kill "SIGINT", $$ - 100.times { - sleep 0.1 - break if $x != 0 - } - test_ok($x == 2) - - trap "SIGINT", Proc.new{raise "Interrupt"} - - x = false - begin - Process.kill "SIGINT", $$ - sleep 0.1 - rescue - x = $! - end - test_ok(x && /Interrupt/ =~ x.message) -end - -test_check "eval" -test_ok(eval("") == nil) -$bad=false -eval 'while false; $bad = true; print "foo\n" end' -test_ok(!$bad) - -test_ok(eval('TRUE')) -test_ok(eval('true')) -test_ok(!eval('NIL')) -test_ok(!eval('nil')) -test_ok(!eval('FALSE')) -test_ok(!eval('false')) - -$foo = 'test_ok(true)' -begin - eval $foo -rescue - test_ok(false) -end - -test_ok(eval("$foo") == 'test_ok(true)') -test_ok(eval("true") == true) -i = 5 -test_ok(eval("i == 5")) -test_ok(eval("i") == 5) -test_ok(eval("defined? i")) - -# eval with binding -def test_ev - local1 = "local1" - lambda { - local2 = "local2" - return binding - }.call -end - -$x = test_ev -test_ok(eval("local1", $x) == "local1") # normal local var -test_ok(eval("local2", $x) == "local2") # nested local var -$bad = true -begin - p eval("local1") -rescue NameError # must raise error - $bad = false -end -test_ok(!$bad) - -module EvTest - EVTEST1 = 25 - evtest2 = 125 - $x = binding -end -test_ok(eval("EVTEST1", $x) == 25) # constant in module -test_ok(eval("evtest2", $x) == 125) # local var in module -$bad = true -begin - eval("EVTEST1") -rescue NameError # must raise error - $bad = false -end -test_ok(!$bad) - -x = binding #! YARV Limitation: Proc.new{} -eval "i4 = 1", x -test_ok(eval("i4", x) == 1) -x = Proc.new{binding}.call #! YARV Limitation: Proc.new{Proc.new{}}.call -eval "i4 = 22", x -test_ok(eval("i4", x) == 22) -$x = [] -x = Proc.new{binding}.call #! YARV Limitation: Proc.new{Proc.new{}}.call -eval "(0..9).each{|i5| $x[i5] = Proc.new{i5*2}}", x -test_ok($x[4].call == 8) - -x = binding -eval "i = 1", x -test_ok(eval("i", x) == 1) -x = Proc.new{binding}.call -eval "i = 22", x -test_ok(eval("i", x) == 22) -$x = [] -x = Proc.new{binding}.call -eval "(0..9).each{|i5| $x[i5] = Proc.new{i5*2}}", x -test_ok($x[4].call == 8) -x = Proc.new{binding}.call -eval "for i6 in 1..1; j6=i6; end", x -test_ok(eval("defined? i6", x)) -test_ok(eval("defined? j6", x)) - -Proc.new { - p = binding - eval "foo11 = 1", p - foo22 = 5 - Proc.new{foo11=22}.call - Proc.new{foo22=55}.call - test_ok(eval("foo11", p) == eval("foo11")) - test_ok(eval("foo11") == 1) - test_ok(eval("foo22", p) == eval("foo22")) - test_ok(eval("foo22") == 55) -}.call if false #! YARV Limitation - -#! YARV Limitation: p1 = Proc.new{i7 = 0; Proc.new{i7}}.call -p1 = Proc.new{i7 = 0; binding}.call -#! YARV Limitation: test_ok(p1.call == 0) -eval "i7=5", p1 -#! YARV Limitation: test_ok(p1.call == 5) -test_ok(!defined?(i7)) - -if false #! YARV Limitation -p1 = Proc.new{i7 = 0; Proc.new{i7}}.call -i7 = nil -test_ok(p1.call == 0) -eval "i7=1", p1 -test_ok(p1.call == 1) -eval "i7=5", p1 -test_ok(p1.call == 5) -test_ok(i7 == nil) -end - -test_check "system" -test_ok(`echo foobar` == "foobar\n") -test_ok(`./miniruby -e 'print "foobar"'` == 'foobar') - -tmp = open("script_tmp", "w") -tmp.print "print $zzz\n"; -tmp.close - -test_ok(`./miniruby -s script_tmp -zzz` == 'true') -test_ok(`./miniruby -s script_tmp -zzz=555` == '555') - -tmp = open("script_tmp", "w") -tmp.print "#! /usr/local/bin/ruby -s\n"; -tmp.print "print $zzz\n"; -tmp.close - -test_ok(`./miniruby script_tmp -zzz=678` == '678') - -tmp = open("script_tmp", "w") -tmp.print "this is a leading junk\n"; -tmp.print "#! /usr/local/bin/ruby -s\n"; -tmp.print "print $zzz\n"; -tmp.print "__END__\n"; -tmp.print "this is a trailing junk\n"; -tmp.close - -test_ok(`./miniruby -x script_tmp` == '') -test_ok(`./miniruby -x script_tmp -zzz=555` == '555') - -tmp = open("script_tmp", "w") -for i in 1..5 - tmp.print i, "\n" -end -tmp.close - -`./miniruby -i.bak -pe '$_.sub!(/^[0-9]+$/){$&.to_i * 5}' script_tmp` -done = true -tmp = open("script_tmp", "r") -while tmp.gets - if $_.to_i % 5 != 0 - done = false - break - end -end -tmp.close -test_ok(done) - -File.unlink "script_tmp" or `/bin/rm -f "script_tmp"` -File.unlink "script_tmp.bak" or `/bin/rm -f "script_tmp.bak"` - -test_check "const" -TEST1 = 1 -TEST2 = 2 - -module Const - TEST3 = 3 - TEST4 = 4 -end - -module Const2 - TEST3 = 6 - TEST4 = 8 -end - -include Const - -test_ok([TEST1,TEST2,TEST3,TEST4] == [1,2,3,4]) - -include Const2 -STDERR.print "intentionally redefines TEST3, TEST4\n" if $VERBOSE -test_ok([TEST1,TEST2,TEST3,TEST4] == [1,2,6,8]) - - -test_ok((String <=> Object) == -1) -test_ok((Object <=> String) == 1) -test_ok((Array <=> String) == nil) - -test_check "clone" -foo = Object.new -def foo.test - "test" -end -bar = foo.clone -def bar.test2 - "test2" -end - -test_ok(bar.test2 == "test2") -test_ok(bar.test == "test") -test_ok(foo.test == "test") - -begin - foo.test2 - test_ok false -rescue NoMethodError - test_ok true -end - -module M001; end -module M002; end -module M003; include M002; end -module M002; include M001; end -module M003; include M002; end - -test_ok(M003.ancestors == [M003, M002, M001]) - -test_check "marshal" -$x = [1,2,3,[4,5,"foo"],{1=>"bar"},2.5,fact(30)] -$y = Marshal.dump($x) -test_ok($x == Marshal.load($y)) - -StrClone=String.clone; -test_ok(Marshal.load(Marshal.dump(StrClone.new("abc"))).class == StrClone) - -[[1,2,3,4], [81, 2, 118, 3146]].each { |w,x,y,z| - a = (x.to_f + y.to_f / z.to_f) * Math.exp(w.to_f / (x.to_f + y.to_f / z.to_f)) - ma = Marshal.dump(a) - b = Marshal.load(ma) - test_ok(a == b) -} - -test_check "pack" - -$format = "c2x5CCxsdils_l_a6"; -# Need the expression in here to force ary[5] to be numeric. This avoids -# test2 failing because ary2 goes str->numeric->str and ary does not. -ary = [1,-100,127,128,32767,987.654321098 / 100.0,12345,123456,-32767,-123456,"abcdef"] -$x = ary.pack($format) -ary2 = $x.unpack($format) - -test_ok(ary.length == ary2.length) -test_ok(ary.join(':') == ary2.join(':')) -test_ok($x =~ /def/) - -$x = [-1073741825] -test_ok($x.pack("q").unpack("q") == $x) - -test_check "math" -test_ok(Math.sqrt(4) == 2) - -include Math -test_ok(sqrt(4) == 2) - -test_check "struct" -struct_test = Struct.new("Test", :foo, :bar) -test_ok(struct_test == Struct::Test) - -test = struct_test.new(1, 2) -test_ok(test.foo == 1 && test.bar == 2) -test_ok(test[0] == 1 && test[1] == 2) - -a, b = test.to_a -test_ok(a == 1 && b == 2) - -test[0] = 22 -test_ok(test.foo == 22) - -test.bar = 47 -test_ok(test.bar == 47) - -test_check "variable" -test_ok($$.instance_of?(Fixnum)) - -# read-only variable -begin - $$ = 5 - test_ok false -rescue NameError - test_ok true -end - -foobar = "foobar" -$_ = foobar -test_ok($_ == foobar) - -class Gods - @@rule = "Uranus" # private to Gods - def ruler0 - @@rule - end - - def self.ruler1 # <= per method definition style - @@rule - end - class << self # <= multiple method definition style - def ruler2 - @@rule - end - end -end - -module Olympians - @@rule ="Zeus" - def ruler3 - @@rule - end -end - -class Titans < Gods - @@rule = "Cronus" # do not affect @@rule in Gods - include Olympians - def ruler4 - @@rule - end -end - -test_ok(Gods.new.ruler0 == "Cronus") -test_ok(Gods.ruler1 == "Cronus") -test_ok(Gods.ruler2 == "Cronus") -test_ok(Titans.ruler1 == "Cronus") -test_ok(Titans.ruler2 == "Cronus") -atlas = Titans.new -test_ok(atlas.ruler0 == "Cronus") -test_ok(atlas.ruler3 == "Zeus") -test_ok(atlas.ruler4 == "Cronus") - -test_check "trace" -$x = 1234 -$y = 0 -trace_var :$x, Proc.new{$y = $x} -$x = 40414 -test_ok($y == $x) - -untrace_var :$x -$x = 19660208 -test_ok($y != $x) - -trace_var :$x, Proc.new{$x *= 2} -$x = 5 -test_ok($x == 10) - -untrace_var :$x - -test_check "defined?" - -test_ok(defined?($x)) # global variable -test_ok(defined?($x) == 'global-variable')# returns description - -foo=5 -test_ok(defined?(foo)) # local variable - -test_ok(defined?(Array)) # constant -test_ok(defined?(Object.new)) # method -test_ok(!defined?(Object.print))# private method -test_ok(defined?(1 == 2)) # operator expression - -class Foo - def foo - p :foo - end - protected :foo - def bar(f) - test_ok(defined?(self.foo)) - test_ok(defined?(f.foo)) - end -end -f = Foo.new -test_ok(defined?(f.foo) == nil) -f.bar(f) - -def defined_test - return !defined?(yield) -end - -test_ok(defined_test) # not iterator -test_ok(!defined_test{}) # called as iterator - -test_check "alias" -class Alias0 - def foo; "foo" end -end -class Alias1<Alias0 - alias bar foo - def foo; "foo+" + super end -end -class Alias2<Alias1 - alias baz foo - undef foo -end - -x = Alias2.new -test_ok(x.bar == "foo") -test_ok(x.baz == "foo+foo") - -# test_check for cache -test_ok(x.baz == "foo+foo") - -class Alias3<Alias2 - def foo - defined? super - end - def bar - defined? super - end - def quux - defined? super - end -end -x = Alias3.new -test_ok(!x.foo) -test_ok(x.bar) -test_ok(!x.quux) - -test_check "path" -test_ok(File.basename("a") == "a") -test_ok(File.basename("a/b") == "b") -test_ok(File.basename("a/b/") == "b") -test_ok(File.basename("/") == "/") -test_ok(File.basename("//") == "/") -test_ok(File.basename("///") == "/") -test_ok(File.basename("a/b////") == "b") -test_ok(File.basename("a.rb", ".rb") == "a") -test_ok(File.basename("a.rb///", ".rb") == "a") -test_ok(File.basename("a.rb///", ".*") == "a") -test_ok(File.basename("a.rb///", ".c") == "a.rb") -test_ok(File.dirname("a") == ".") -test_ok(File.dirname("/") == "/") -test_ok(File.dirname("/a") == "/") -test_ok(File.dirname("a/b") == "a") -test_ok(File.dirname("a/b/c") == "a/b") -test_ok(File.dirname("/a/b/c") == "/a/b") -test_ok(File.dirname("/a/b/") == "/a") -test_ok(File.dirname("/a/b///") == "/a") -case Dir.pwd -when %r'\A\w:' - test_ok(/\A\w:\/\z/ =~ File.expand_path(".", "/")) - test_ok(/\A\w:\/a\z/ =~ File.expand_path("a", "/")) - dosish = true -when %r'\A//' - test_ok(%r'\A//[^/]+/[^/]+\z' =~ File.expand_path(".", "/")) - test_ok(%r'\A//[^/]+/[^/]+/a\z' =~ File.expand_path(".", "/")) - dosish = true -else - test_ok(File.expand_path(".", "/") == "/") - test_ok(File.expand_path("sub", "/") == "/sub") -end -if dosish - test_ok(File.expand_path("/", "//machine/share/sub") == "//machine/share") - test_ok(File.expand_path("/dir", "//machine/share/sub") == "//machine/share/dir") - test_ok(File.expand_path("/", "z:/sub") == "z:/") - test_ok(File.expand_path("/dir", "z:/sub") == "z:/dir") -end -test_ok(File.expand_path(".", "//") == "//") -test_ok(File.expand_path("sub", "//") == "//sub") - -# test_check "Proc#binding" -ObjectSpace.each_object(Proc){|o| - begin - b = o.binding - eval 'self', b - rescue ArgumentError - end -} - -test_check "gc" -begin - 1.upto(10000) { - tmp = [0,1,2,3,4,5,6,7,8,9] - } - tmp = nil - test_ok true -rescue - test_ok false -end -class S - def initialize(a) - @a = a - end -end -l=nil -100000.times { - l = S.new(l) -} -GC.start -test_ok true # reach here or dumps core -l = [] -100000.times { - l.push([l]) -} -GC.start -test_ok true # reach here or dumps core - -ObjectSpace.each_object{|o| - o.class.name -} - -test_ok true # reach here or dumps core - -PROGRESS.finish -if $failed > 0 - printf "not ok/test: %d failed %d\n", $ntest, $failed -else - printf "end of test(test: %d)\n", $ntest -end +# backward compatibility for chkbuild +require_relative '../basictest/test' diff --git a/sample/testunit/adder.rb b/sample/testunit/adder.rb deleted file mode 100644 index aa5c88cc7b..0000000000 --- a/sample/testunit/adder.rb +++ /dev/null @@ -1,13 +0,0 @@ -# Author:: Nathaniel Talbott. -# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. -# License:: Ruby license. - -class Adder - def initialize(number) - @number = number - end - def add(number) - return @number + number - end -end - diff --git a/sample/testunit/subtracter.rb b/sample/testunit/subtracter.rb deleted file mode 100644 index 2c08247805..0000000000 --- a/sample/testunit/subtracter.rb +++ /dev/null @@ -1,12 +0,0 @@ -# Author:: Nathaniel Talbott. -# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. -# License:: Ruby license. - -class Subtracter - def initialize(number) - @number = number - end - def subtract(number) - return @number - number - end -end diff --git a/sample/testunit/tc_adder.rb b/sample/testunit/tc_adder.rb deleted file mode 100644 index 8453beb20a..0000000000 --- a/sample/testunit/tc_adder.rb +++ /dev/null @@ -1,18 +0,0 @@ -# Author:: Nathaniel Talbott. -# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. -# License:: Ruby license. - -require 'test/unit' -require 'adder' - -class TC_Adder < Test::Unit::TestCase - def setup - @adder = Adder.new(5) - end - def test_add - assert_equal(7, @adder.add(2), "Should have added correctly") - end - def teardown - @adder = nil - end -end diff --git a/sample/testunit/tc_subtracter.rb b/sample/testunit/tc_subtracter.rb deleted file mode 100644 index d2c8313350..0000000000 --- a/sample/testunit/tc_subtracter.rb +++ /dev/null @@ -1,18 +0,0 @@ -# Author:: Nathaniel Talbott. -# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. -# License:: Ruby license. - -require 'test/unit' -require 'subtracter' - -class TC_Subtracter < Test::Unit::TestCase - def setup - @subtracter = Subtracter.new(5) - end - def test_subtract - assert_equal(3, @subtracter.subtract(2), "Should have subtracted correctly") - end - def teardown - @subtracter = nil - end -end diff --git a/sample/testunit/ts_examples.rb b/sample/testunit/ts_examples.rb deleted file mode 100644 index 3d24dd6522..0000000000 --- a/sample/testunit/ts_examples.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Author:: Nathaniel Talbott. -# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. -# License:: Ruby license. - -require 'test/unit' -require 'tc_adder' -require 'tc_subtracter' diff --git a/sample/timeout.rb b/sample/timeout.rb index 2870ddb239..ad4459aff0 100644 --- a/sample/timeout.rb +++ b/sample/timeout.rb @@ -1,31 +1,31 @@ require 'timeout' def progress(n = 5) - n.times {|i| print i; STDOUT.flush; sleep 1; i+= 1} + n.times {|i| print i; STDOUT.flush; sleep 1} puts "never reach" end -p timeout(5) { +p Timeout.timeout(5) { 45 } -p timeout(5, TimeoutError) { +p Timeout.timeout(5, Timeout::Error) { 45 } -p timeout(nil) { +p Timeout.timeout(nil) { 54 } -p timeout(0) { +p Timeout.timeout(0) { 54 } begin - timeout(5) {progress} + Timeout.timeout(5) {progress} rescue => e puts e.message end begin - timeout(3) { + Timeout.timeout(3) { begin - timeout(5) {progress} + Timeout.timeout(5) {progress} rescue => e puts "never reach" end @@ -36,7 +36,7 @@ end class MyTimeout < StandardError end begin - timeout(2, MyTimeout) {progress} + Timeout.timeout(2, MyTimeout) {progress} rescue MyTimeout => e puts e.message end diff --git a/sample/trick2013/README.md b/sample/trick2013/README.md new file mode 100644 index 0000000000..d6458c9d51 --- /dev/null +++ b/sample/trick2013/README.md @@ -0,0 +1,15 @@ +This directory contains the award-winning entries of +the 1st Transcendental Ruby Imbroglio Contest for rubyKaigi (TRICK 2013). + +THESE ARE BAD EXAMPLES! You must NOT use them as a sample code. + +* kinaba/entry.rb: "Best pangram" - Gold award +* mame/entry.rb: "Most classic" - Bronze award +* shinh/entry.rb: "Most Readable" - Silver award +* yhara/entry.rb: "Worst abuse of constants" - Dishonorable mention + +These files are licensed under MIT license. + +For the contest outline and other winning entries, see: + +https://github.com/tric/trick2013 diff --git a/sample/trick2013/kinaba/authors.markdown b/sample/trick2013/kinaba/authors.markdown new file mode 100644 index 0000000000..84c011ee05 --- /dev/null +++ b/sample/trick2013/kinaba/authors.markdown @@ -0,0 +1,3 @@ +* kinaba + * kiki@kmonos.net + * cctld: jp diff --git a/sample/trick2013/kinaba/entry.rb b/sample/trick2013/kinaba/entry.rb new file mode 100644 index 0000000000..8a3f855e46 --- /dev/null +++ b/sample/trick2013/kinaba/entry.rb @@ -0,0 +1 @@ +!@THEqQUICKbBROWNfFXjJMPSvVLAZYDGgkyz&[%r{\"}mosx,4>6]|?'while(putc 3_0-~$.+=9/2^5;)<18*7and:`# diff --git a/sample/trick2013/kinaba/remarks.markdown b/sample/trick2013/kinaba/remarks.markdown new file mode 100644 index 0000000000..dcdce7e9ae --- /dev/null +++ b/sample/trick2013/kinaba/remarks.markdown @@ -0,0 +1,37 @@ +### Remarks + +Just run it with no argument: + + ruby entry.rb + +I confirmed the following implementations/platforms: + +* ruby 2.0.0p0 (2013-02-24) [i386-mswin32\_100] + +### Description + +The program prints each ASCII character from 0x20 ' ' to 0x7e '~' exactly once. + +The program contains each ASCII character from 0x20 ' ' to 0x7e '~' exactly once. + +### Internals + +The algorithm is the obvious loop "32.upto(126){|x| putc x}". + +It is not so hard to transform it to use each character *at most once*. The only slight difficulty comes from the constraint that we cannot "declare and then use" variables, because then the code will contain the variable name twice. This restriction is worked around by the $. global variable, the best friend of Ruby golfers. + +The relatively interesting part is to use all the characters *at least once*. Of course, this is easily accomplished by putting everything into a comment (i.e., #unused...) or to a string literal (%(unused...), note that normal string literals are forbidden since they use quotation marks twice). Hey, but that's not fun at all! I tried to minimize the escapeway. + +* "@THEqQUICKbBROWNfFXjJMPSvVLAZYDGgkyz". Trash box of unused alphabet. I wish I could have used "gkyz" somewhere else. + +* "%r{\"}mosx". Regex literal, with %-syntax. I don't even know what each m,o,s,x means... + +* "?'" Symbol literal. The quote characters (' " \`) are the first obstacle to this trial because they have to be used in pair usually. These are escaped as \" and ?' and :\`. + +* "4>6" "3\_0-~$.+=9/2^5" "18\*7". I had to consume many arithmetic operators +-\*/^~<>, but I only have ten literals 0 to 9 and $. as operands. Besides I have to express the print loop. This is an interesting puzzle. + +* "(putc ...;)<18*7". Trail semicolon doesn't change the value of the expression. + +### Limitation + +n/a. diff --git a/sample/trick2013/mame/authors.markdown b/sample/trick2013/mame/authors.markdown new file mode 100644 index 0000000000..e99cd71554 --- /dev/null +++ b/sample/trick2013/mame/authors.markdown @@ -0,0 +1,3 @@ +* Yusuke Endoh + * mame@tsg.ne.jp + * cctld: jp diff --git a/sample/trick2013/mame/entry.rb b/sample/trick2013/mame/entry.rb new file mode 100644 index 0000000000..8abfc2be40 --- /dev/null +++ b/sample/trick2013/mame/entry.rb @@ -0,0 +1,97 @@ + eval$C=%q(at_exit{ + open("/dev/dsp","wb"){|g|h=[0]*80 + $><<"\s"*18+"eval$C=%q(#$C);S=%:" + (S<<m=58).lines{|l|s=[128]*n=20E2 + t=0; h.map!{|v|d=?!==l[ + t]?1 :(l[ + t]== ?#)? + 0*v= 6:03 + (v<1 ?[]: + 0..n -1). + each {|z| + s[z] +=2* + M.sin(($*[0] ||1) + .to_f*M.sin(y= 40*(z+m)*2** + (t/12E0)/463)+ y)*(v-z*d/n)}; + t+=1;v-d};m+= n;g.flush<<(s. + pack"C*"); puts(l)}}};M= + Math);S=%: + + Jesu, Joy of Man's Desiring + Johann Sebastian Bach + + # + | # + | # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # + # # # # + | | | # + | #| # + # # | # + | | | # + | | # # + # # # # + | | # | + | | # # + # # # # + | | | # + | | # + # # # # + | | # | + | # # | + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | | # # + # # # # + | | | # + | # # + # # # + | | | # + | # | # + # # # # + | | | | + | | | | + | | | | + | | | | + | | | | + | | | | + | | | | + | | | | + | | | | + | | | | + | | | : diff --git a/sample/trick2013/mame/remarks.markdown b/sample/trick2013/mame/remarks.markdown new file mode 100644 index 0000000000..488681d88d --- /dev/null +++ b/sample/trick2013/mame/remarks.markdown @@ -0,0 +1,47 @@ +### Remarks + +Run the program under a platform that `/dev/dsp` is available. +For example, if you are using pulseaudio, use `padsp`: + + padsp ruby entry.rb + +Please see Limitation if you want to run this program on os x. + +I confirmed the following platforms. + +* ruby 2.0.0p0 (2013-02-24 revision 39474) [x86\_64-linux] +* ruby 1.9.3p194 (2012-04-20 revision 35410) [x86\_64-linux] +* ruby 1.9.3p327 (2012-11-10 revision 37606) [x86\_64-darwin10.8.0] + +For those who are lazy, I'm attaching a screencast. + +### Description + +This program is a music-box quine. +It prints itself with playing "Jesu, Joy of Man's Desiring". + +### Internal + +Like a real music box, this program consists of a mechanical part (code) and a piano roll. +In the piano roll, `#` represents a pin that hits a note, and `|` represents a slur. +The leftmost column corresponds 110Hz (low A). +Every column corresponds a semitone higher than the left one. + +This program uses [the frequency modulation synthesis](https://en.wikipedia.org/wiki/Frequency_modulation_synthesis) to play the sound like a music-box. +You can create a different-sounding tone by changing the parameter. +For example, the following will play the sound like a harpsichord. + + padsp ruby entry.rb 2.0 + +Note that this program does *not* use an idiom to remove whitespace, such as `.split.join`. All newlines and spaces do not violate any of the Ruby syntax rules. + +### Limitation + +On os x, `/dev/dsp` is not available. +You have to use sox by replacing the following part: + + open("/dev/dsp","wb") + +with: + + IO.popen("./pl","wb") diff --git a/sample/trick2013/shinh/authors.markdown b/sample/trick2013/shinh/authors.markdown new file mode 100644 index 0000000000..7ea2298a1a --- /dev/null +++ b/sample/trick2013/shinh/authors.markdown @@ -0,0 +1,2 @@ +Shinichiro Hamaji +Japan, .jp diff --git a/sample/trick2013/shinh/entry.rb b/sample/trick2013/shinh/entry.rb new file mode 100644 index 0000000000..cd4517358a --- /dev/null +++ b/sample/trick2013/shinh/entry.rb @@ -0,0 +1,10 @@ +begin with an easy program. +you should be able to write +a program unless for you, +program in ruby language is +too difficult. At the end +of your journey towards the +ultimate program; you must +be a part of a programming +language. You will end if +you != program diff --git a/sample/trick2013/shinh/remarks.markdown b/sample/trick2013/shinh/remarks.markdown new file mode 100644 index 0000000000..1cd190db9f --- /dev/null +++ b/sample/trick2013/shinh/remarks.markdown @@ -0,0 +1,4 @@ +This program is a meaningless poem. +This does nothing for you. +Almost everything in this code is junk, +but you and program would confuse you a bit. diff --git a/sample/trick2013/yhara/authors.markdown b/sample/trick2013/yhara/authors.markdown new file mode 100644 index 0000000000..c0adc2bfdb --- /dev/null +++ b/sample/trick2013/yhara/authors.markdown @@ -0,0 +1,3 @@ +* Yutaka Hara + * yutaka.hara.gmail.com + * cctld: jp diff --git a/sample/trick2013/yhara/entry.rb b/sample/trick2013/yhara/entry.rb new file mode 100644 index 0000000000..3666f271fa --- /dev/null +++ b/sample/trick2013/yhara/entry.rb @@ -0,0 +1,28 @@ +def _(&b)$><<->(x){x ? (String===x ?x.upcase: +(Class===x ? x : x.class).name[$a?0:($a=5)]): +" "}[ begin b[];rescue Exception;$!;end ] end + +_ { 1.tap } +_ { method(:p).unbind } +_ { eval "{ " } +_ { Thread.current.join } +_ { nil } +_ { select } +_ { ruby } +_ { self.class } +_ { Thread.current.group } +_ { nil.to_h } +_ { "\xFF".encode("big5") } +_ { raise } +_ { [0][1] } +_ { Regexp.compile "*" } +_ { RUBY_COPYRIGHT[32] } +_ { binding } +_ { :s.class.name[1] } +_ { warn } +_ { [a: :b][0] } +_ { methods } +_ { IO.class } +_ { {}.fetch(0) } +_ { open " " } +_ { 1000000.chr } diff --git a/sample/trick2013/yhara/remarks.en.markdown b/sample/trick2013/yhara/remarks.en.markdown new file mode 100644 index 0000000000..bd821e882c --- /dev/null +++ b/sample/trick2013/yhara/remarks.en.markdown @@ -0,0 +1,23 @@ +### Remarks + +Just run it with no argument: + + ruby entry.rb + +I confirmed the following implementations/platforms: + +* ruby 2.0.0p0 (2013-02-24 revision 39474) [x86\_64-darwin12.2.1] + +### Description + +It prints JUST ANOTHER RUBY HACKER + +### Internals + +This script uses characters in constants in Object class. It +intentionally raises some exceptions. The second 'U' comes from +RUBY\_COPYRIGHT, "Yukihiro Matsumoto". + +### Limitation + +This program does not work on JRuby because "return" does not raise an exception. diff --git a/sample/trick2013/yhara/remarks.markdown b/sample/trick2013/yhara/remarks.markdown new file mode 100644 index 0000000000..99cb4b557c --- /dev/null +++ b/sample/trick2013/yhara/remarks.markdown @@ -0,0 +1,24 @@ +### Remarks + +引数なしで普通に実行してください。 + + ruby entry.rb + +以下の実装・プラットフォームで動作確認しています。 + +* ruby 2.0.0p0 (2013-02-24 revision 39474) [x86\_64-darwin12.2.1] + +### Description + +JUST ANOTHER RUBY HACKERと表示します。 + +### Internals + +Objectクラスの定数から文字を拾っています。 +そのために、意図的に例外を起こしています。 +「U」が一つしか見つからなかったので、もう一個はRUBY\_COPYRIGHTの +「Yukihiro Matsumoto」から取っています。 + +### Limitation + +JRubyはreturnがエラーにならなくて、動きませんでした。 diff --git a/sample/trick2015/README.md b/sample/trick2015/README.md new file mode 100644 index 0000000000..6cae824796 --- /dev/null +++ b/sample/trick2015/README.md @@ -0,0 +1,16 @@ +This directory contains the award-winning entries of +the 2nd Transcendental Ruby Imbroglio Contest for rubyKaigi (TRICK 2015). + +THESE ARE BAD EXAMPLES! You must NOT use them as a sample code. + +* kinaba/entry.rb: "Best piphilology" - **Gold award** +* ksk\_1/entry.rb: "Most unreadable ALU" - **Silver award** +* monae/entry.rb: "Doubling amphisbaena award" - **Bronze award** +* eregon/entry.rb: "Least general solver" - 4th prize +* ksk\_2/entry.rb: "Most general solver" - 5th prize + +These files are licensed under MIT license. + +For the contest outline and other winning entries, see: + +https://github.com/tric/trick2015 diff --git a/sample/trick2015/eregon/authors.markdown b/sample/trick2015/eregon/authors.markdown new file mode 100644 index 0000000000..68ca8cdfe0 --- /dev/null +++ b/sample/trick2015/eregon/authors.markdown @@ -0,0 +1,3 @@ +* Benoit Daloze (eregon) + * eregontp@gmail.com + * cctld: be diff --git a/sample/trick2015/eregon/entry.rb b/sample/trick2015/eregon/entry.rb new file mode 100644 index 0000000000..51d5c768b2 --- /dev/null +++ b/sample/trick2015/eregon/entry.rb @@ -0,0 +1,16 @@ +class String;def[]*a;$*<<a;b;end;end; +_=0;z="C=Fiber;s=$*;a=*0..8;l=C.new{e +xit},*a.product(a).select{|r,c|s[r][c +]==0}."[1,9,_, _,_,8, _,_,5]+"map{|r, +c|C.ne"[_,_,2, _,5,_, _,8,9]+"w{o=s[r +][c];l"[8,_,6, 7,4,_, _,_,_]+"oop{(1. +.9).map{|n|C.yield(s[r][c]=n)if a.non +e?{|k|"[_,_,_, _,_,4, _,9,2]+"s[r][k] +==n||s"[_,2,3, _,7,_, 8,1,_]+"[k][c]= +=n||s["[5,6,_, 8,_,_, _,_,_]+"r-r%3+k +%3][c-c%3+k/3]==n}};s[r][c]=o;C.yield +}}},C."[_,_,_, _,2,7, 9,_,3]+"new{loo +p{puts"[9,3,_, _,8,_, 1,_,_]+" s.map{ +|r|r*'"[2,_,_, 5,_,_, _,4,8]+" '}<<'' +;C.yield}};c=l[i=1];loop{c=l[i+=c.res +ume ? 1:-1]}";eval z.tr ?\n,'' diff --git a/sample/trick2015/eregon/remarks.markdown b/sample/trick2015/eregon/remarks.markdown new file mode 100644 index 0000000000..a56f24da71 --- /dev/null +++ b/sample/trick2015/eregon/remarks.markdown @@ -0,0 +1,70 @@ +### Remarks + +Just run it without arguments: + + ruby entry.rb + +I confirmed the following implementations and platforms: + +* Linux: + * ruby 2.3.0dev (2015-10-30 trunk 52394) [x86\_64-linux] + * ruby 2.2.2p95 (2015-04-13 revision 50295) [x86\_64-linux] + * ruby 2.0.0p647 (2015-08-18) [x86\_64-linux] +* Darwin: + * ruby 2.0.0p247 (2013-06-27 revision 41674) [x86\_64-darwin10.8.0] + * jruby 9.0.3.0 (2.2.2) 2015-10-21 633c9aa Java HotSpot(TM) 64-Bit Server VM 25.11-b03 on 1.8.0\_11-b12 +jit [darwin-x86\_64] + * rubinius 2.2.6.n74 (2.1.0 94b3a9b4 2014-03-15 JI) [x86\_64-darwin12.5.0] + +### Description + +This program shows all solutions of any sudoku puzzle. + +The embedded sudoku puzzle can be changed at wish. + +Giving an empty puzzle (all `0` or `_`), the program will print every possible completed sudoku puzzle. +We do not however make any time guarantee on such behavior. + +The program is rather small for the task: the solver is actually 302 characters long, +assuming the sudoku puzzle is in a variable `s` and encoded as an array of rows of numbers. + +### Internals + +* The program implements backtracking and keeps state in a very elegant way. +* The whole program never goes deeper than 9 stack frames, + but yet can backtrack up to 81 levels! +* The main loop of a program is a dance between cells. + On one end is the solutions, on the other the program ends. +* The program only uses *infinite* loops and no `break`. +* The program interleaves the creation of the solver and the puzzle. +* The program is easy to deobfuscate but finding how it works will be more challenging. +* The last line contains a smiley. + +The author likes good numbers: + + $ wc entry.rb + 15 42 600 + +The inspiration for this entry comes from: + +* A newspaper sudoku with multiple solutions +* An inspiring paper: `Revisiting Coroutines` + +Various tricks used for brevity: + +* The method defined is one of the fews which may contain neither parenthesis nor spaces. +* The program uses the return value of Fiber.yield without arguments. +* `String#b` is used as a very short `self`. + +Design issues: + +* Since `return`-ing from a Fiber is not allowed, the programs must `exit`. +* The program reveals that the cartesian product operator is still too long: `a.product(a)` while it could be `a*a`. + +Note: + +* In the original code, the last cell was: `C.new{loop{yield s; C.yield}}`, + implementing some sort of "forwarding coroutine". + +### Limitation + +* The program does not want any *argument* with you and will quit quietly if you try some. diff --git a/sample/trick2015/kinaba/authors.markdown b/sample/trick2015/kinaba/authors.markdown new file mode 100644 index 0000000000..23d4448cf3 --- /dev/null +++ b/sample/trick2015/kinaba/authors.markdown @@ -0,0 +1,4 @@ +* kinaba + * twitter.com/kinaba + * kiki@kmonos.net + * cctld: jp diff --git a/sample/trick2015/kinaba/entry.rb b/sample/trick2015/kinaba/entry.rb new file mode 100644 index 0000000000..aa077dc240 --- /dev/null +++ b/sample/trick2015/kinaba/entry.rb @@ -0,0 +1,150 @@ +big, temp = Array 100000000**0x04e2 +srand big +alias $curTerm $initTerm + +Numeric +Interrupt + +big += big +printout _pi_ finish if $never +init ||= big +$counter ||= 02 + +private +@mainloop +while 0x00012345 >= $counter + + Rational aprx = 3.141592r + numbase = 0o0000 + + @justonce + def increment + $initTerm ||= Integer srand * 0x00000002 + srand $counter += 0x00000001 + + $noaction + Integer rand + $noaction + rand + rand + alias $line_cnt $. + end + + @lets_just + @assume + diameter = 100000 + + @you + @then_have + permtr |= +3_14159 + + return if $nomeaning + + @onlyuse + increment + + beautiful computer action if $nothing + $sigmaTerm ||= init + $curTerm /= srand and init + pi, = Integer $sigmaTerm unless $nomean + + iterator? + $counter += 1 + atan real_one multiplied by__four unless + srand +big && $counter >> 0b1 + + Enumerable + Fixnum + Bignum + Math + Complex + Comparable + TrueClass + Dir + Encoding + Proc + Hash + Method + Enumerator + Exception + Fiber + Errno + FalseClass + Mutex + NilClass + IO + GC + + num = numbase |= srand + + ENV + Float + MatchData + Proc + TracePoint + KeyError + p or + FileTest + File + EOFError + p + p + p + Binding + Time + Class + + $sigmaTerm += $curTerm + puts a HelloWorld if $nomean + SystemExit + + !LoadError + 31i + 3.1415e0 + Array 14 + 3 + IndexError + Range + false + 55555 + NameError + + Object + @ori + @ent + RubyVM + + pi += 3_3_1_3_8 + + @use + @lots_of + @keywords + begin + self + $noaction + not $important + nil + __FILE__.object_id + rescue + next + redo if __LINE__ + defined? +$nomeaning + $noaction + $nomean + break $never + ensure + class PiCompute + end + end + + This code cannot _ be executed with typical style unless true + $curTerm *= num +end + +@ll_set +@re_U_ok + +$Enjoy +$Superb +$TRICK15 and a number + +print pi diff --git a/sample/trick2015/kinaba/remarks.markdown b/sample/trick2015/kinaba/remarks.markdown new file mode 100644 index 0000000000..6316c51fb6 --- /dev/null +++ b/sample/trick2015/kinaba/remarks.markdown @@ -0,0 +1,85 @@ +### Remarks + +Just run it with no argument: + + $ ruby entry.rb + +I confirmed the following implementation/platform: + +- ruby 2.2.3p173 (2015-08-18 revision 51636) [x64-mingw32] + + +### Description + +The program is a [Piphilology](https://en.wikipedia.org/wiki/Piphilology#Examples_in_English) +suitable for Rubyists to memorize the digits of [Pi](https://en.wikipedia.org/wiki/Pi). + +In English, the poems for memorizing Pi start with a word consisting of 3-letters, +1-letter, 4-letters, 1-letter, 5-letters, ... and so on. 10-letter words are used for the +digit `0`. In Ruby, the lengths of the lexical tokens tell you the number. + + $ ruby -r ripper -e \ + 'puts Ripper.tokenize(STDIN).grep(/\S/).map{|t|t.size%10}.join' < entry.rb + 31415926535897932384626433832795028841971693993751058209749445923078164062862... + +The program also tells you the first 10000 digits of Pi, by running. + + $ ruby entry.rb + 31415926535897932384626433832795028841971693993751058209749445923078164062862... + + +### Internals + +Random notes on what you might think interesting: + +- The 10000 digits output of Pi is seriously computed with no cheets. It is calculated + by the formula `Pi/2 = 1 + 1/3 + 1/3*2/5 + 1/3*2/5*3/7 + 1/3*2/5*3/7*4/9 + ...`. + +- Lexical tokens are not just space-separated units. For instance, `a*b + cdef` does + not represent [3,1,4]; rather it's [1,1,1,1,4]. The token length + burden imposes hard constraints on what we can write. + +- That said, Pi is [believed](https://en.wikipedia.org/wiki/Normal_number) to contain + all digit sequences in it. If so, you can find any program inside Pi in theory. + In practice it isn't that easy particularly under the TRICK's 4096-char + limit rule. Suppose we want to embed `g += hij`. We have to find [1,2,3] from Pi. + Assuming uniform distribution, it occurs once in 1000 digits, which already consumes + 5000 chars in average to reach the point. We need some TRICK. + + - `alias` of global variables was useful. It allows me to access the same value from + different token-length positions. + + - `srand` was amazingly useful. Since it returns the "previous seed", the token-length + `5` essentially becomes a value-store that can be written without waiting for the + 1-letter token `=`. + +- Combination of these techniques leads to a carefully chosen 77-token Pi computation + program (quoted below), which is embeddable to the first 242 tokens of Pi. + Though the remaining 165 tokens are just no-op fillers, it's not so bad compared to + the 1000/3 = 333x blowup mentioned above. + + + big, temp = Array 100000000**0x04e2 + srand big + alias $curTerm $initTerm + big += big + init ||= big + $counter ||= 02 + while 0x00012345 >= $counter + numbase = 0x0000 + $initTerm ||= Integer srand * 0x00000002 + srand $counter += 0x00000001 + $sigmaTerm ||= init + $curTerm /= srand + pi, = Integer $sigmaTerm + $counter += 1 + srand +big && $counter >> 0b1 + num = numbase |= srand + $sigmaTerm += $curTerm + pi += 3_3_1_3_8 + $curTerm *= num + end + print pi + +- By the way, what's the blowup ratio of the final code, then? + It's 242/77, whose first three digits are, of course, 3.14. diff --git a/sample/trick2015/ksk_1/authors.markdown b/sample/trick2015/ksk_1/authors.markdown new file mode 100644 index 0000000000..bd6d41f6c7 --- /dev/null +++ b/sample/trick2015/ksk_1/authors.markdown @@ -0,0 +1,3 @@ +* Keisuke Nakano + * ksk@github, ksknac@twitter + * cctld: jp diff --git a/sample/trick2015/ksk_1/entry.rb b/sample/trick2015/ksk_1/entry.rb new file mode 100644 index 0000000000..64d3efd799 --- /dev/null +++ b/sample/trick2015/ksk_1/entry.rb @@ -0,0 +1 @@ +%%%while eval '_=%%r%%(.)...\1=%%=~[%%%%,,,,,%%%s ?=]*%%%%%%#"]*%%%%3x+1?%%'.% %%",%*p(_||=eval($**%%%)) diff --git a/sample/trick2015/ksk_1/remarks.markdown b/sample/trick2015/ksk_1/remarks.markdown new file mode 100644 index 0000000000..a0b8bbcdcc --- /dev/null +++ b/sample/trick2015/ksk_1/remarks.markdown @@ -0,0 +1,120 @@ +### Remarks + +The program is run with a positive integer as an argument, e.g., +```shell + ruby entry.rb 27 +``` +It has been confirmed to be run on +``` + ruby 1.9.3p385 (2013-02-06 revision 39114) [x86_64-darwin11.4.2] + ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin13] + ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux] +``` + + +### Description + +The program prints a Collatz sequence started with a given number, +that is, it repeatedly outputs numbers obtained by applying the +following Half-Or-Triple-Plus-One (HOTPO) process to the previous +number: + +> If the number is even, divide it by two, otherwise, multiply it by three and add one. + +until the number becomes 1. Collatz conjectured that no matter from +the process starts it always eventually terminates. This is still +an open problem, hence the program may not terminate for some +numbers. It is known that there is no such exception below 2<sup>60</sup>. + + +### Internals + +The source code does not contain either conditional branch or arithmetic operation. +The trick shall be revealed step by step. + +First, the code is obfuscated by using `%`-notations, +`*`(String#join), `%`-formatting, restructuring, and so on. +Here is an equivalent readable program: +```ruby +n = ARGV[0].to_i +begin + # do nothing +end while begin + puts n + n = (/(.)...\1=/ =~ eval('[",,,,,"'+ '",'*n + ' ?=].join#"].join("3x+1?")')) +end +``` +The line +```ruby + n = (/(.)...\1=/ =~ eval('[",,,,,"'+ '",'*n + ' ?=].join#"].join("3x+1?")')) +``` +performs the HOTPO process. +The `eval` expression here returns a string as explained in detail later. +Since *regex*`=~`*str* returns index of first match of *regex* in *str*, +the regular expression `(.)...\1` must match the string +at index `n/2` if `n` is even and +at `3*n+1` if `n` is odd greater than 1. +The match must fail in the case of `n = 1` so that it returns `nil`. + +The key of simulating the even-odd conditional branch on `n` in the +HOTPO process is an `n`-length sequence of the incomplete fragments +`",` where the double-quote `"` changes its role of opening/closing +string literals alternately. If `n` is even, the string in the `eval` +expression is evaluated as +```ruby + => '[",,,,,"'+ '",' + '",' + '",' + ... + '",' + ' ?=].join#...' + => '[",,,,,"",",",...", ?=].join#...' +``` +where the last double-quote `"` is closing hence the code after `#` is +ignored as comments. Note that `"ab""cd"` in Ruby is equivalent to +`"abcd"`. Therefore the `eval` expression is evaluated into +```ruby + ",,,,,...,=" +``` +where the number of commas is `5+n/2`. +As a result, the regular expression `(.)...\1=` matches `,,,,,=` +at the end of string, that is, at index `5+n/2-5 = n/2`. + +If `n` is odd, the string in the `eval` expression is evaluated as +```ruby + => '[",,,,,"'+ '",' + '",' + '",' + '",' + ... + '",' + ' ?=].join#"].join("3x+1?")' + => '[",,,,,"",",",",...,", ?=].join#"].join("3x+1?")' +``` +where the last element in the array is `", ?=].join#"`. Threfore the +`eval` expression is evaluated into +``` + ",,,,,,3x+1?,3x+1?,...,3x+1?, ?=].join#" +``` +where the number of `,3x+1?` is `(n-1)/2`. As a result, the regular +expression `(.)...\1=` matches `?, ?=` at the almost end of string, +that is, at index `5+(n-1)/2*6-1 = 3n+1`, provided that the match +fails in the case of `n = 1` because the symbol `?` occurs only once +in the string. + +One may notice that the string `3x+1` in the code could be other +four-character words. I chose it because the Collatz conjecture is +also called the 3x+1 problem. + + +### Variant + +The Collatz conjecture is equivalently stated as, + +> no matter from the HOTPO process starts, it always eventually + reaches the cycle of 4, 2, and 1 + +instead of termination of the process at 1. This alternative +statement makes the program simpler because we do not have to care the +case of n = 1. It can be obtained by replacing the regular expression +is simply `/=/` and removing a padding `",,,,,"`. The program no +longer terminates, though. + + +### Limitation + +The implementation requires to manipulate long strings even for some +small starting numbers. For example, starting from 1,819, the number +will reach up to 1,276,936 which causes SystemStackError on Ruby 1.9.3. +The program works on Ruby 2.0.0 and 2.2.3, though. + + diff --git a/sample/trick2015/ksk_2/abnormal.cnf b/sample/trick2015/ksk_2/abnormal.cnf new file mode 100644 index 0000000000..084303f041 --- /dev/null +++ b/sample/trick2015/ksk_2/abnormal.cnf @@ -0,0 +1,6 @@ +c Example CNF format file +c +p cnf 4 3 +1 3 -4 0 +4 0 2 +-3 diff --git a/sample/trick2015/ksk_2/authors.markdown b/sample/trick2015/ksk_2/authors.markdown new file mode 100644 index 0000000000..bd6d41f6c7 --- /dev/null +++ b/sample/trick2015/ksk_2/authors.markdown @@ -0,0 +1,3 @@ +* Keisuke Nakano + * ksk@github, ksknac@twitter + * cctld: jp diff --git a/sample/trick2015/ksk_2/entry.rb b/sample/trick2015/ksk_2/entry.rb new file mode 100644 index 0000000000..55b488e3a8 --- /dev/null +++ b/sample/trick2015/ksk_2/entry.rb @@ -0,0 +1 @@ +_='s %sSATISFIABLE';puts eval$<.read.gsub(/.*p.*?(\d+).*?$|\d+/m){$1?%w[?-* +'=-'=~/#{'(-?)'* }-*=(?=]*$1:$&>?0?"\\#$&$|":'$)(?='}+')/x?[_%p%i=0,[*$~].map{|x|x>?-?:v:eval(x+?1)*i-=1}*" "]:_%:UN' diff --git a/sample/trick2015/ksk_2/quinn.cnf b/sample/trick2015/ksk_2/quinn.cnf new file mode 100644 index 0000000000..556a9b33f5 --- /dev/null +++ b/sample/trick2015/ksk_2/quinn.cnf @@ -0,0 +1,21 @@ +c quinn.cnf +c +p cnf 16 18 + 1 2 0 + -2 -4 0 + 3 4 0 + -4 -5 0 + 5 -6 0 + 6 -7 0 + 6 7 0 + 7 -16 0 + 8 -9 0 + -8 -14 0 + 9 10 0 + 9 -10 0 +-10 -11 0 + 10 12 0 + 11 12 0 + 13 14 0 + 14 -15 0 + 15 16 0
\ No newline at end of file diff --git a/sample/trick2015/ksk_2/remarks.markdown b/sample/trick2015/ksk_2/remarks.markdown new file mode 100644 index 0000000000..187a6804d2 --- /dev/null +++ b/sample/trick2015/ksk_2/remarks.markdown @@ -0,0 +1,204 @@ +### Remarks + +The program is run with a data file from the standard input, e.g., +```shell + ruby entry.rb < data +``` +where ``<`` can be omitted. The data file must be in the DIMACS CNF +format (see Description for detail). It has been confirmed to be run on +``` + ruby 1.9.3p385 (2013-02-06 revision 39114) [x86_64-darwin11.4.2] + ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin13] + ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux] +``` +For particular inputs, the program works differently on these environments +(see Limitation). + + +### Description + +The program is a very small SAT solver with 194 bytes making use of a +powerful feature of Regexp matching in Ruby. It receives a data file +from the standard input in the DIMACS CNF that is a standard format +for inputs of SAT solvers. For example, the text in the DIMACS CNF +format, +``` +c +c This is a sample input file. +c +p cnf 3 5 + 1 -2 3 0 +-1 2 0 +-2 -3 0 + 1 2 -3 0 + 1 3 0 +``` +corresponds to a propositional formula in conjunctive normal form, + + (L1 ∨ ¬L2 ∨ L3) ∧ + (¬L1 ∨ L2) ∧ + (¬L2 ∨ ¬L3) ∧ + (L1 ∨ L2 ∨ ¬L3) ∧ + (L1 ∨ L3). + +In the DIMACS CNF format, the lines starting with ``c`` are comments +that are allowed only before the line ``p cnf ...``. The line ``p cnf +3 5`` represents that the problem is given in conjunctive normal form +with 3 variables (L1,L2,and L3) and 5 clauses. A clause is given by a +sequence of the indices of positive literals and the negative indices +of negative literals. Each clause is terminated by ``0``. For the +input above, the program outputs +``` +s SATISFIABLE +v 1 2 -3 +``` +because the formula is satisfiable by L1=true, L2=true, and L3=false. +If an unsatisfiable formula is given, the program should output +``` +s UNSATISFIABLE +``` +This specification is common in most exiting SAT solvers and required +for entries of [SAT competition](http://www.satcompetition.org/). + +The program is very small with no other external libraries thanks to +the wealth of string manipulations in Ruby. It is much smaller than +existing small SAT solvers like [minisat](http://minisat.se/) and +[picosat](http://fmv.jku.at/picosat/)! + + +### Internals + +The basic idea of the program is a translation from DIMACS CNF format +into Ruby. For example, the data file above is translated into a +``Regexp`` matching expression equivalent to +```ruby + '---=-' =~ + /(-?)(-?)(-?)-*=(?=\1$|-\2$|\3$|$)(?=-\1$|\2$|$)(?=-\2$|-\3$|$)(?=\1$|\2$|-\3$|$)(?=\1$|\3$|$)(?=)/ +``` +that returns ``MatchData`` if the formula is satisfiable and otherwise +returns ``nil``. The beginning of regular expression +``(-?)(-?)(-?)-*=`` matches a string ``"---="`` so that each +capturing pattern ``(-?)`` matches either ``"-"`` or `""`, which +corresponds to an assignment of true or false, respectively, for a +propositional variable. Each clause is translated into positive +lookahead assertion like ``(?=\1$|-\2$|\3$|$)`` that matches +``"-"`` only when ``\1`` holds ``"-"``, ``\2`` holds ``""``, or ``\3`` +holds ``"-"``. This exactly corresponds to the condition for +L1∨¬L2∨L3 to be true. The last case ``|$`` never matches +``"-"`` but it is required for making the translation simple. +The last meaningless positive lookahead assertion ``(?=)`` is added +for a similar reason. This translation is based on +[Abigail's idea](http://perl.plover.com/NPC/NPC-3SAT.html) where a +3SAT formula is translated into a similar Perl regular expression. +The differences are the submitted Ruby program translates directly +from the DIMACS CNF format and tries to make the code shorter by using +lookahead assertion which can also make matching more faster. + +Thanks to the ``x`` option for regular expression, the input above is +simply translated into +```ruby + ?-*3+'=-'=~/#{'(-?)'*3}-*=(?= + \1$| -\2$| \3$| $)(?= + -\1$| \2$| $)(?= + -\2$| -\3$| $)(?= + \1$| \2$| -\3$| $)(?= + \1$| \3$| $)(?= + )/x +``` +which has a structure similar to the DIMACS CNF format. + +The part of formatting outputs in the program is obfuscated as an +inevitable result of 'golfing' the original program +```ruby + if ...the matching expression above... then + puts 's SATISFIABLE' + puts 'v '+$~[1..-1].map.with_index{|x,i| + if x == '-' then + i+1 + else + ['-',i+1].join + end + }.join(' ') + else + puts 's UNSATISFIABLE' + end +``` +In the satisfiable case, the MatchData ``$~`` obtained by the regular expression +has the form of +``` + #<MatchData "---=" 1:"-" 2:"-" 3:""> +``` +which should be translated into a string ``1 2 -3``. The golfed code simply +does it by `eval(x+?1)*i-=1` where ``x`` is matched string ``"x"`` or ``""`` +and ``i`` be a negated index. + + +### Data files + +The submission includes some input files in the DIMACS CNF format for +testing the program. + +* [sample.cnf](sample.cnf) : an example shown above. + +* [unsat.cnf](unsat.cnf) : an example of an unsatisfiable formula. + +* [quinn.cnf](quinn.cnf) : an example from Quinn's text, 16 variables and 18 clauses + (available from [http://people.sc.fsu.edu/~jburkardt/data/cnf/cnf.html]) + +* [abnormal.cnf](abnormal.cnf) : an example from [the unofficial manual of the DIMACS challenge](http://www.domagoj-babic.com/uploads/ResearchProjects/Spear/dimacs-cnf.pdf) + where a single clause may be on multiple lines. + +* [uf20-01.cnf](uf20-01.cnf) : an example, with 20 variables and 91 clauses, from [SATLIB benchmark suite](http://www.cs.ubc.ca/~hoos/SATLIB/benchm.html). The last two lines are removed from the original because they are illegal in the DIMACS CNF format (all examples in 'Uniform Random-3-SAT' of the linked page need this modification). + + +### Limitation + +The program may not work when the number of variables exceeds 99 +because ``\nnn`` in regular expression with number ``nnn`` does not +always represent backreference but octal notation of characters. For +example, +```ruby + /#{"(x)"*999}:\502/=~"x"*999+":x" + /#{"(x)"*999}:\661/=~"x"*999+":x" + /#{"(x)"*999}:\775/=~"x"*999+":x" +``` +fail due to the syntax error (invalid escape), while +```ruby + /#{"(x)"*999}:\508/=~"x"*999+":x" + /#{"(x)"*999}:\691/=~"x"*999+":x" + /#{"(x)"*999}:\785/=~"x"*999+":x" +``` +succeed (to return 0) because 508, 691, and 785 are not in octal notation. +Since Ruby 1.9.3 incorrectly returns ``nil`` instead of terminating +with the error for +```ruby + /#{"(x)"*999}:\201/=~"x"*999+":x" + /#{"(x)"*999}:\325/=~"x"*999+":x" +``` +the present SAT solver may unexpectedly return "UNSATISFIABLE" even +for satisfiable inputs. This happens when the number is in octal +notation starting with either 2 or 3. + +In the case of the number starting with 1, the code like the above +does work on all versions of Ruby I tried. For example, +```ruby + /#{"(x)"*999}:\101/=~"x"*999+":x" + /#{"(x)"*999}:\177/=~"x"*999+":x" +``` +succeed (to return 0). Interestingly, +```ruby + /#{"(x)"*999}:\101/=~"x"*999+":\101" + /#{"(x)"*999}:\177/=~"x"*999+":\177" +``` +return ``nil``, while +```ruby + /:\101/=~":\101" + /:\177/=~":\177" +``` +succeed to return 0. The meaning of ``\1nn`` in regular expression +seems to depend on the existence of capturing expressions. + +In spite of these Ruby's behaviors, we have a good news! The present +SAT solver does not suffer from the issues because the program cannot +return solutions in practical time for inputs with variables more than +40. diff --git a/sample/trick2015/ksk_2/sample.cnf b/sample/trick2015/ksk_2/sample.cnf new file mode 100644 index 0000000000..295f81c942 --- /dev/null +++ b/sample/trick2015/ksk_2/sample.cnf @@ -0,0 +1,9 @@ +c +c This is a sample input file. +c +p cnf 3 5 + 1 -2 3 0 +-1 2 0 +-2 -3 0 + 1 2 -3 0 + 1 3 0 diff --git a/sample/trick2015/ksk_2/uf20-01.cnf b/sample/trick2015/ksk_2/uf20-01.cnf new file mode 100644 index 0000000000..0d9503c451 --- /dev/null +++ b/sample/trick2015/ksk_2/uf20-01.cnf @@ -0,0 +1,99 @@ +c This Formular is generated by mcnf +c +c horn? no +c forced? no +c mixed sat? no +c clause length = 3 +c +p cnf 20 91 + 4 -18 19 0 +3 18 -5 0 +-5 -8 -15 0 +-20 7 -16 0 +10 -13 -7 0 +-12 -9 17 0 +17 19 5 0 +-16 9 15 0 +11 -5 -14 0 +18 -10 13 0 +-3 11 12 0 +-6 -17 -8 0 +-18 14 1 0 +-19 -15 10 0 +12 18 -19 0 +-8 4 7 0 +-8 -9 4 0 +7 17 -15 0 +12 -7 -14 0 +-10 -11 8 0 +2 -15 -11 0 +9 6 1 0 +-11 20 -17 0 +9 -15 13 0 +12 -7 -17 0 +-18 -2 20 0 +20 12 4 0 +19 11 14 0 +-16 18 -4 0 +-1 -17 -19 0 +-13 15 10 0 +-12 -14 -13 0 +12 -14 -7 0 +-7 16 10 0 +6 10 7 0 +20 14 -16 0 +-19 17 11 0 +-7 1 -20 0 +-5 12 15 0 +-4 -9 -13 0 +12 -11 -7 0 +-5 19 -8 0 +1 16 17 0 +20 -14 -15 0 +13 -4 10 0 +14 7 10 0 +-5 9 20 0 +10 1 -19 0 +-16 -15 -1 0 +16 3 -11 0 +-15 -10 4 0 +4 -15 -3 0 +-10 -16 11 0 +-8 12 -5 0 +14 -6 12 0 +1 6 11 0 +-13 -5 -1 0 +-7 -2 12 0 +1 -20 19 0 +-2 -13 -8 0 +15 18 4 0 +-11 14 9 0 +-6 -15 -2 0 +5 -12 -15 0 +-6 17 5 0 +-13 5 -19 0 +20 -1 14 0 +9 -17 15 0 +-5 19 -18 0 +-12 8 -10 0 +-18 14 -4 0 +15 -9 13 0 +9 -5 -1 0 +10 -19 -14 0 +20 9 4 0 +-9 -2 19 0 +-5 13 -17 0 +2 -10 -18 0 +-18 3 11 0 +7 -9 17 0 +-15 -6 -3 0 +-2 3 -13 0 +12 3 -2 0 +-2 -3 17 0 +20 -15 -16 0 +-5 -17 -19 0 +-20 -18 11 0 +-9 1 -5 0 +-19 9 17 0 +12 -2 17 0 +4 -16 -5 0 diff --git a/sample/trick2015/ksk_2/unsat.cnf b/sample/trick2015/ksk_2/unsat.cnf new file mode 100644 index 0000000000..7283933a9f --- /dev/null +++ b/sample/trick2015/ksk_2/unsat.cnf @@ -0,0 +1,11 @@ +c +c This is a sample input file. +c (unsatisfiable) +c +p cnf 3 5 +1 -2 3 0 +-1 2 0 +-2 -3 0 +1 2 -3 0 +1 3 0 +-1 -2 3 0 diff --git a/sample/trick2015/monae/authors.markdown b/sample/trick2015/monae/authors.markdown new file mode 100644 index 0000000000..58d63b16ac --- /dev/null +++ b/sample/trick2015/monae/authors.markdown @@ -0,0 +1 @@ +monae (@monae, jp) diff --git a/sample/trick2015/monae/entry.rb b/sample/trick2015/monae/entry.rb new file mode 100644 index 0000000000..6961df21cd --- /dev/null +++ b/sample/trick2015/monae/entry.rb @@ -0,0 +1,26 @@ + ;; ;; ;; ;; + ;; ;; ;; ;; + ;;eval$s =%q[i=1# + eval(%q[ xxxxxxxx + xx xxxx xx xx xxxx xx + xx xxxx xx xx xxxx xx + xxxxxxxx xxxxxxxx + xxxxxxxx xxxxxxxx + xx xx xxxxxxxxxx xx xxxxxxxx + j, t, p=0,[?;]," ev al$s=%qx +[#$s]".split*"";i,j,t=i-j,i+j,(x + [b=?\s]*j.abs+t).map{|s|r=t.shix +ft ||b;r.gsub!(?;){p.slice!0}if $x + f| |=p>p=p.center(i*i+j*j,?;);r ,x + s=[s,r]if(i*j<0);(b*i.abs+s).ljx + ust(r.size).gsub(b){r[$`.size]|x + |b}}unti l$ f;puts(t)# xx xx + xxxxxxxx xx xxxxxxxxxx xx xx +xxxxxxxx xxxxxxxx + xxxxxxxx xxxxxxxx +xx xxxx xx xx xxxx xx + xx xxxx xx xx xxxx xx + xxxxxxxx x].gsub\ + /x.*|\s/ ,"")#];; + ;; ;; ;; ;; + ;; ;; ;; ;; diff --git a/sample/trick2015/monae/remarks.markdown b/sample/trick2015/monae/remarks.markdown new file mode 100644 index 0000000000..48be61bd12 --- /dev/null +++ b/sample/trick2015/monae/remarks.markdown @@ -0,0 +1,25 @@ + +# How to run + +``` +ruby entry.rb +ruby entry.rb | ruby +ruby entry.rb | ruby | ruby +ruby entry.rb | ruby | ruby | ruby +... +``` + +Confirmed on the following environments: +- ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14] +- ruby 2.0.0p353 (2013-11-22) [i386-mingw32] + +# Description + +A simple quine which prints itself twice +on a slightly complex base. + +> geminum caput amphisbaenae, hoc est et a cauda, +> tamquam parum esset uno ore fundi venenum. +> aliis squamas esse, aliis picturas, omnibus exitiale virus. +> +> — <cite>GAIUS PLINIUS SECUNDUS, Naturalis Historia 8.85.1</cite> diff --git a/sample/trick2018/01-kinaba/authors.markdown b/sample/trick2018/01-kinaba/authors.markdown new file mode 100644 index 0000000000..d0df0b379d --- /dev/null +++ b/sample/trick2018/01-kinaba/authors.markdown @@ -0,0 +1,3 @@ +* kinaba + * twitter.com/kinaba + * cctld: jp diff --git a/sample/trick2018/01-kinaba/entry.rb b/sample/trick2018/01-kinaba/entry.rb new file mode 100644 index 0000000000..eb8284d5ab --- /dev/null +++ b/sample/trick2018/01-kinaba/entry.rb @@ -0,0 +1,8 @@ +alias BEGIN for unless def class +super true or return defined? next +break while begin undef do end +rescue then retry else undef module +nil ensure case if yield __LINE__ +self and redo elsif not __FILE__ +alias END in end when __ENCODING__ +end until false end diff --git a/sample/trick2018/01-kinaba/remarks.markdown b/sample/trick2018/01-kinaba/remarks.markdown new file mode 100644 index 0000000000..d0b9fdffde --- /dev/null +++ b/sample/trick2018/01-kinaba/remarks.markdown @@ -0,0 +1,55 @@ +### Remarks + +Just run it with no argument: + + ruby entry.rb + +(Anyway it is just a no-op program. The above command only verifies +that entry.rb is a valid Ruby program.) + +I confirmed the following implementations/platforms: + +* ruby 2.5.0p0 (2017-12-25 revision 61468) [x64-mingw32] + +### Description + +First, look at + +https://docs.ruby-lang.org/ja/latest/doc/spec=2flexical.html#reserved + +and then, look at entry.rb. + +The source code of entry.rb consists only of reserved words of Ruby, +and all the reserved words are used in the code, in a way that the code +forms a valid Ruby program. No compile error, no warning, or no runtime error. + + +### Internals + +Difficult (and interesting) points of the theme are: + +* Since many of the reserved words define program structures, we cannot + use them independently. For instance, `retry` must be inside `rescue`, + or `break`/`next`/`redo` must be inside a looping construct. + Or, jump-out statements cannot occur at a position that requires a + value; `if return then true end` is a "void value expression" syntax error. +* Inserting newlines for each 6 word (to match with the spec html) is also + an interesting challenge, since Ruby is sensitive to newlines. + +Tricks used in the code are: + +* def/alias/undef can take even reserved words as parameters. + That is, `def class ... end` defines a method named `class`. + The feature is crucial since otherwise `BEGIN` etc inevitably + introduces non-reserved tokens (like `{}`). +* `defined?` can take some reserved words too (which I didn't know + until trying to write this program.) +* "void value expression" can be avoided by using `or` or `and`. + `if begin return end then true end` is a syntax error, but + `if begin false or return end then true end` is not. + + +### Limitation + +Sad to say that it's not a "perfect pangram". +It uses 'alias' and 'undef' twice, and 'end' 4 times. diff --git a/sample/trick2018/02-mame/authors.markdown b/sample/trick2018/02-mame/authors.markdown new file mode 100644 index 0000000000..0e420fdf5d --- /dev/null +++ b/sample/trick2018/02-mame/authors.markdown @@ -0,0 +1,3 @@ +* Yusuke Endoh + * mame@ruby-lang.org + * cctld: jp diff --git a/sample/trick2018/02-mame/entry.rb b/sample/trick2018/02-mame/entry.rb new file mode 100644 index 0000000000..cc4ef9cbc4 --- /dev/null +++ b/sample/trick2018/02-mame/entry.rb @@ -0,0 +1,15 @@ +'';eval(r=%q(->z{r="'';eval(r=\ +%q(#{r}))[%q`#{z}`]";i=-040;30. +times{|n|(15+n%2*15-n/2).times{ +r<<r[i+=(1.-n&2)*(32-n%2*31)]}} +i=r[524,0]=?\0;eval(r[479..-1]) +c['"']}))[%q`GFEDCBA"+"[e\"'"'t +kE*;;\";" TRICK2018 ";tb,;{{r +2E0$ob[us@*0)[90,336])_#i\n}s#i +0H}>["t]];};o[1,?\n*8];ex"-}eac +1Hl<1[-1]*2*t=n%2];o[14-n,0)mvk +8M$<4,?\n];15.times{|n|;o[35ie2 +!Pss.slice!(0,1)+x;sleep(0.0t;0 +'W=%q"<<95<<$s<<95;o=->n,x{n.'1 +;@[2]}|\e../,%@s="'%trick2018!8 +eval$s=%q_eval($s.gsub!(/#{%@`] diff --git a/sample/trick2018/02-mame/remarks.markdown b/sample/trick2018/02-mame/remarks.markdown new file mode 100644 index 0000000000..88b32c205a --- /dev/null +++ b/sample/trick2018/02-mame/remarks.markdown @@ -0,0 +1,16 @@ +This program quines with animation. + +``` +$ ruby entry.rb +``` + +Of course, the output is executable. + +``` +$ ruby entry.rb > output +$ ruby output +``` + +Note, we don't cheat. This program uses escape sequences just for moving the cursor. It doesn't use attribution change nor overwrite to hide any code. + +The program is crafted so that it works in two ways; it works as a normal program text, and, it also works when it is rearranged in a spiral order. Some parts of the code are actually overlapped. diff --git a/sample/trick2018/03-tompng/Gemfile b/sample/trick2018/03-tompng/Gemfile new file mode 100644 index 0000000000..a24ff779dc --- /dev/null +++ b/sample/trick2018/03-tompng/Gemfile @@ -0,0 +1,2 @@ +source 'https://rubygems.org' +gem 'chunky_png' diff --git a/sample/trick2018/03-tompng/Gemfile.lock b/sample/trick2018/03-tompng/Gemfile.lock new file mode 100644 index 0000000000..467f5c3495 --- /dev/null +++ b/sample/trick2018/03-tompng/Gemfile.lock @@ -0,0 +1,13 @@ +GEM + remote: https://rubygems.org/ + specs: + chunky_png (1.3.8) + +PLATFORMS + ruby + +DEPENDENCIES + chunky_png + +BUNDLED WITH + 1.16.1 diff --git a/sample/trick2018/03-tompng/authors.markdown b/sample/trick2018/03-tompng/authors.markdown new file mode 100644 index 0000000000..26ebe24da6 --- /dev/null +++ b/sample/trick2018/03-tompng/authors.markdown @@ -0,0 +1,3 @@ +* Tomoya Ishida (tompng) + * tomoyapenguin@gmail.com + * cctld: jp diff --git a/sample/trick2018/03-tompng/entry.rb b/sample/trick2018/03-tompng/entry.rb new file mode 100644 index 0000000000..26416c7019 --- /dev/null +++ b/sample/trick2018/03-tompng/entry.rb @@ -0,0 +1,31 @@ +X=[];class String def-@;replace ?-+self end;def-a;X.reject!{|x|x. +__id__==__id__};a.replace(self+?-+a) end end;at_exit{eval C=(Zlib +.inflate((X*?-).tr(?-,'').tr('q-z','0-9').to_i(26).digits(0x100). +pack'C*'))};def method_missing n;(X<<n.to_s)[-1]end;require'zlib' +fzygtoxyzgntmdmuwvfoffbpmvzojpkhczvjvjdbtscnldwbdoprackddovivvmkz +ponzmosvtjciwkgaslscxxxwudeesmmqpfhislxuxnnypulxstzgobyaekqqhbjcg +mvko------------ddkeys----eivhnccaqyiw---bzyccmt-----------ymtnge +jwhi--------------pjxf------mdarbtumnv---qasda--------------gmwdt +wrtk---qtpzgnce----fsl-------fkgzgtbpp---gwnm----pxkpqkdiw---owga +momz---yjjvpnvar---zeo---v-----duvalwu---nsqt---waofemwakivnyqkjd +fzag---uhvusmkl----kzb---rhc----iutzjr---mqlh---ayijpwativpweaato +xexs--------------rvgv---pjdz-----lkkg---uiaw---lovitupw-----fwmn +kfru------------jvjpgv---jskycf----pal---gbuf---hfdnywog-----iuca +pntn---apmkqroeuzwuwkw---gqnmgof-----b---hlpl---vkkyhfyrqfr--jwrl +kmdb---dhspujhmtgrkccu---uonfummdt-------rqfw----bpiactehwp--fncq +yzvz---gdaxebplhfndran---ytfmviryeh------hqwkl---------------nced +bibu---fnkdthgldhkxxjg---rwnmpudhbqin----gucoyki------------hfura +cqdgqpyzqfzknvdjoxxhpjulwwyebtocxdrvklbuviwwcatlmdosxfvwntzbijguy +iglrvvzlxerflupxvsyujfacuwhrvmnecgtewtqkhtdggcltejiyqcluclkycwvzg +vvxfysvttfbeglvrlngntdngzyhqrmltazwdydxrsvjploembhgxdvfmmhepbschm +brn--iqrcdb--evv----tqp------lg--uein-wzut--mr------wkh------foqz +zsf--srjnjp--ampb--pfio--hgtekx--rrr---fwd--jn--xqkezcz--vsb--nya +khrc--evlr--oioxs--mqce--bqfmag--bwz---xda--qw--jnuzelr--qzi--itx +mdxd--duso--wxbot--nmon--ugnbdpc--a--c--e--hlg--twxndre--tby--rhg +evhbn--zb--dtxmiz--dpia------vie--h--i--t--shh------kfn------owna +ealmt--kb--scxdjy--smvl--dqmgebk--t--s--t--gfd--updcbnc--rh--dwwp +dvpnxb----wpljjdy--kolc--qflyleok---xkv---usbj--jhrawbn--ewx--bgf +eaqwrw----ejwxhet--dice--eoczconm---urz---rqyp--hovvvfc--bskj--el +aocjcts--jtumwxm----mgy------xpaoq-jtwqr-aipay------dhy--iync--hk +sckddmvuvvuhhqstumaykvczaaujrumqbbqsdvdycplyrlkkojlxnkrhbbrmnjxyf +cdtcmpfmjvthwkpzucbblttgumomlxnxwjeypfeagaukfzeokzxjebkpigcvlqnso diff --git a/sample/trick2018/03-tompng/output.txt b/sample/trick2018/03-tompng/output.txt new file mode 100644 index 0000000000..ed9a4079cc --- /dev/null +++ b/sample/trick2018/03-tompng/output.txt @@ -0,0 +1,44 @@ +undef p;X=[];class String def-@;replace ?-+dup end;def-a;X.reject!{|x|x.__id__==__id__};a.replace(self+?-+a) end end;at_exit{eval C= +(Zlib.inflate (X*?-).tr(?-,'').tr('q-z','0-9').to_i(26).digits(256).pack'C*')};def method_missing n;(X<<n.to_s)[-1]end;require'zlib' +gmlztzdculbtzgtjfetuh---k--htf----d-----------------------------------------------------g-b-----s--t-g--------jmuwescmgchftikfjafccs +ivchcveidpvxdabnvwyga-f--v-------xf----------------------------------------------------q-v---l-------q---------liiNeawriayymwooxgxqw +rfosepqsmojseyezmwbhi--------------ew--------------------------------------------------m---k-r-----------vwu--hiotltdmczwyjmlvbyfqwq +uvvykqdjednoqgtcmtfbzs---------f----o--------------------------------------------------t--a------m----x---f-----dldzsakyofetfozfpmrq +geusutariiiNiulkjbwlm-----d------------------------------------------------------------j---------o---------x--j-uitzrgwpupwhvendhyno +uubvnssiywkklwwdufhhi-rw----k---v-------------------------------------------------------sty-----yg---l---c-v----wkffpskpumolqmkeryzg +zrxdaiposwybbzgxdnegh-----g-----ma--n---------------------------------------------------------j----n--b-n-------yqavmscswdogpcgopygt +axiqfswlhzeamvymdnteo---q-q-w--------------------------fhrmj-----------------hkou-----------f-----d----u-o------evcuxxegekfgivzzujan +nslioftsvqvtkeigvfgwr-------------lyco-----------------igyvg-----------------okuk---------m--b-u--d--y------s---dadjrlykfhtermzfyktu +btoxzfpPicxxfligbivvf--------h----yrat---------------------------------------vjwd---------------------d-ki--o--tyqosehopkwttigwwfskp +komzvnyrvkjcjwbmdwdkp----------vxphiNdtawn--xms-saketo--jnld----ezulntdaz----nzna-----vhjwt------h----x--x--o--saxxsrkgktqotaluylbkk +sclegratyaarmgmepheml----------hwgglhlrfcx--znvmpfsgjx-onhju---gtxsmzqprlt---mjzy---frhdk-------------v---mj----dzjujmbgldfwoybgicwu +tfhgnhlzxlwtdtkgzlaca-------------gmex------arlm--------rvmh-ajtgf-----pqal--wcux-zatyi-------------------------xnluwybcugjclmablshn +tnjohqtqzivgmyutrssil-------------lcwq------jrf--------gcaii-maie------------vvnfjfqwo--------------------------filivosyhkxcvuwdibwj +tyxjiopiFqypvwdzoatuq-------------tdln------cnx---------ffuf-ajvq------------tyyypglpzmj------------------------vtqzwewqdsijrbymvpwn +niNffphoehukpvvmzvhyd-------------ahqd------nfr---------jeqk--toap-----mxhyg-tedv---otrwy-----------------------mjxnrktackwxwiajdnuc +kkxhuwbvibpvgvcampadi-------------ebmencqz--obf--------wfprz---qmrotkijiqv---ggfp-----hlzw----------------------kastwdpxiyftmypuxbtu +xetudmwzpomktgnjkcsyc---------------fwpdx---xb----j-----se-k------tllakc-----gjoo-------we------mic---lktk------ubtnrxvrjzuqlrfrsnmf +okdvfvcdbdqkckjialskk---------------------------v---u-------l----------------------------------z--q--qfg--------aaliNbxbjjpxebboneye +kcbkjmdclwnfawtfnwkeq----------------------------------j---y-------------------------------a---jmbyo-sgef--gf---extljbozuoofgyvsilct +xzoqmsqgzjxxpjqwkjkdd------------------------o--------m-------f---------------------------------n--de-ajz-rzv---fhnpbkrwdxoozpxeaxaf +mbcwxuiqdwcmadheiykaa-----------------------q-f------l---i---------------------------------r----zf---k--y---fi--dcnycheytylcgnioauee +yekiNacriqoevtdjerqbp----------------------------w---yy-----my----------------------------ko--mnbpskr--c-----j--ozyqpbfovhbhyoprzgqr +czwtuopxkdbphocfawvbk--------------------------q-s----j--b---------------------------------hd-xsb----bfiNp--w---fmwuvfambdqvxtzldwmh +xysnyrseydlkjcwfbsjnr-------------------------d-d-------------------------------------------f-enpss---qllpwr----almsdidvjwoigvldfqoa +lrpbixjpofxocxlflscpo------------------------------q-fyu--z-------------------------------------kfd-z---n-------bqxurujnxzurrdgcojks +jetyfdkcekckxbyosbfws-------------wdfhgwuvejjmf-----sxjubpvgcsl-------tnmixpv---------eurabjsdvstfv-------------qcyiqhonwoyixqeonfvp +mopPhywsozohitutgmmrb------------zxwtxe--riedeo---mspgpnv--pimlh------jhtzajk--------qqovvq---ldbrh-------------xtooxpayonpcvvtmvpra +vvuyiunpoeagdzqjecsub------------klrw------snrc---rrct------aajom--------nsyk--------peea-------azq-------------iNjefdkfhnagjicqwmsm +mbwwbfgehhbdmvvlflmee---------------------hkejn---jtbo-------jdtje-------jcei---------afyz-----smtc-------------kksvfjyuaqtohxiohhlz +dvfmfrzcmnsfruhqgjuxz------------------dfxdnlk----kkra-------xmmtf-------jwkw----------rdoozxtcho---------------bbwwferxwnnmdzcniicv +mfneisdlyeqwynldjgonj----------------jgrjvc-------uxga-------ghnpr-------sers--------scbknx----gmjo-------------moedtnlbflhtlkjibrqk +gobwqshnpbdcpjmjaeczr--------------iscsxs---------zfpo-------hhfwy-------qbba-------vhlxc-------ntod------------ndwzdomaptumzejiwqbn +snucynymvfpnadyqkzfcv-------------ggze------------kuvfs-----zuhod--------mylo-------jhwyp-----z-pywd------------dqfmpnevmtqcikbrilto +aotyxkipebdkassogpcbl-----------wgackesmvvsrihhd---orzndjndlzpb----------eobf-------kkayixzyotqfafa-w-----------mjjxoomwdglwvccozzut +rthesuszfwycsqqrtxlot-----------ejcqlhriilqbtrys------lwbkzmvp-----------zzwm-------l--qijwfllndzb-ik-----------mmokqomjepdcotnsiNig +nloryyoswwdmefywnnuhph------------------------------------------------------r--r-nd-----h--x--------------------hlgzeqqslwxgtjgghquf +nssngjtiudsrvfuxjzclhjhj----------------------------------------------------------t----------------k-f-mp-------obhyehqebtpjbkeepqzt +ezogzsimfynqmkteaipejo-g-yser-----------------------------------------------e------h-------------i---y----------qpgcqnltivmmsximbbsy +wtjjolwyoselcumgklqwpldkl-ulm-m---------------------------------------------------------------q---u-f--l--------buixfiitufktsqdtnrei +tgrtitcewseetlpeuuujb-osdokjozc------------------------------------------n---d-----f--------g--------q--g-------jyyqtezuzmcxgpcwuwfx +dpPayqmzxrwhbswwalygfurtkruw-u-k---------------------------------------------d---h------i----------c----i-------ulowcddvjbxthqlxjzbe diff --git a/sample/trick2018/03-tompng/remarks.markdown b/sample/trick2018/03-tompng/remarks.markdown new file mode 100644 index 0000000000..fe9eec5989 --- /dev/null +++ b/sample/trick2018/03-tompng/remarks.markdown @@ -0,0 +1,19 @@ +### Remarks + +Bundle install + this program depends on `gem chunky_png` + +Run it with the following command: + bundle exec ruby entry.rb trick.png + bundle exec ruby entry.rb [other png file] + +I confirmed the following implementations/platforms: + +* ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-darwin16] +* ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16] + +### Description + +This program is a png image viewer. +The output is an asciiart of the given png file, +and it is also a source code of the png viewer itself. diff --git a/sample/trick2018/03-tompng/trick.png b/sample/trick2018/03-tompng/trick.png Binary files differnew file mode 100644 index 0000000000..d4bb0bd7c3 --- /dev/null +++ b/sample/trick2018/03-tompng/trick.png diff --git a/sample/trick2018/04-colin/authors.markdown b/sample/trick2018/04-colin/authors.markdown new file mode 100644 index 0000000000..a846d12535 --- /dev/null +++ b/sample/trick2018/04-colin/authors.markdown @@ -0,0 +1,3 @@ +* Colin Fulton + * justcolin@gmail.com + * cctld: us diff --git a/sample/trick2018/04-colin/entry.rb b/sample/trick2018/04-colin/entry.rb new file mode 100644 index 0000000000..442a8ea3a8 --- /dev/null +++ b/sample/trick2018/04-colin/entry.rb @@ -0,0 +1,2 @@ +# Copyright 2018. Available for use under the terms of the MIT License. +$🚀=0;def 🤔 🏷,🤔=0,&b;puts ' '*$🚀+(🤔 ?"":"🚫 ")+🏷;$🚀+=4;b&.[];$🚀-=4;end diff --git a/sample/trick2018/04-colin/remarks.markdown b/sample/trick2018/04-colin/remarks.markdown new file mode 100644 index 0000000000..5f4f1a8dfe --- /dev/null +++ b/sample/trick2018/04-colin/remarks.markdown @@ -0,0 +1,62 @@ +### Remarks + +Create a Ruby file that requires entry.rb with a series of test in it the run the file using ruby: + +``` +ruby name_of_test_file.rb +``` + +To create a test, call 🤔 with two arguments. The first is a string describing what this tests, the second argument is the test assertion. If the assertion is truthy, the test passes. If the assertion is falsy, the test fails. + +``` +string_1 = "Hello world!" +string_2 = "This is not the same!" + +🤔 "The two strings are equal", + string_1 == string_2 +``` + +To create a group of tests under a label, call 🤔 with a string describing the group and a block containing the tests in that group. + +``` +🤔 "This is a group of tests" do + # Add other groups and/or tests here. +end +``` + +Here is an example: + +``` +require './entry' + +🤔 "Math" do + 🤔 "Addition" do + 🤔 "One plus one equals two.", + 1+1 == 2 + 🤔 "One plus one equals eleven. (This should fail.)", + 1+1 == 11 + end + + 🤔 "Subtraction" do + 🤔 "One minus one equals zero.", + 1-1 == 0 + 🤔 "Ten minus one equal nine.", + 10-1 == 9 + end +end +``` + +It has been tested with the following Ruby versions: + +* ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17] +* ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15] +* If you replace `b&.[]` with `b&&b[]` it will work with ruby 2.0.0 as well, but it will be one character longer. + + +### Description + +The goal was to create a testing library where the test files looked good and the output looked good in as few characters as possible. The result is 68 characters and has one method to handle everything. + +### Limitation + +Your terminal program must support Unicode characters for the test output to look correct. If your terminal does not support Unicode, simply replace the 🚫 in the code with whatever character you want to prefix failing tests. diff --git a/sample/trick2018/05-tompng/authors.markdown b/sample/trick2018/05-tompng/authors.markdown new file mode 100644 index 0000000000..26ebe24da6 --- /dev/null +++ b/sample/trick2018/05-tompng/authors.markdown @@ -0,0 +1,3 @@ +* Tomoya Ishida (tompng) + * tomoyapenguin@gmail.com + * cctld: jp diff --git a/sample/trick2018/05-tompng/entry.rb b/sample/trick2018/05-tompng/entry.rb new file mode 100644 index 0000000000..31522b6de2 --- /dev/null +++ b/sample/trick2018/05-tompng/entry.rb @@ -0,0 +1,41 @@ + X=[];def self.method_missing n;n.to_s.chars;end + l=[];def l.-a;X<<a=[nil,*a];a;end;def l.+a;self-a;end + class Array;def-@;[]-self;end;def-a;replace [*self,nil,*a + ]end;alias +@ -@;alias + -;end;def gen3d f;yield;b=['solid obj'];w, + h=X[0].size,X.size;X<<[];a=->r,z,dr,dz{;r-=w/2.0;z*=2;r2,z2=r+dr,z+dz*2;if r>0||r2> + 0;r=[0,r].max;r2=[0,r2].max;16.times{|i|m=Math;p=m::PI/8;;c,s=m.cos(t=i*p),m.sin(t) + c2,s2=m.cos(t=(i+1)*p),m.sin(t);t-=p/2;[[0,1,2],[0,2,3]].map{|a|b.push [:facet,'n'+ + + 'ormal',dz*m.cos(t),dz*m.sin(t),-dr]*' ','outer loop',a.map{|i|'v'+ + ++ "ertex #{[[r*c,r*s,z],[r*c2,r*s2,z],[r2*c2,r2*s2,z2],[r2* + +c, r2*s,z2]][i]*' '}"},:endloop,:endfacet}}end};(0...h). + map{| y|w.times{|x|[X[y-1][x]||a[x,y,1,0],X[y+1][x]|| + a[x+1,y+ + 1,-1,0],X[ + y][x-+1]||a[ + x,y+1,0,-1],X[y + ][x++1]||a[x+1,y, + 0,1]]if X[y][x]}} + s=[b,'end'+b[0]]* + $/;File.write(f, + s);X.replace( + []);end + +gen3d 'wine_glass.stl' do + l--ww------------------ww--l + l--ww------------------ww--l + l--ww++++++++++++++++++ww--l + l--ww++++++++++++++++++ww--l + l--ww++++++++++++++++++ww--l + l--ww++++++++++++++++++ww--l + l---ww++++++++++++++++ww---l + l----www++++++++++++www----l + l------www++++++++www------l + l--------wwwwwwwwww--------l + l-----------wwww-----------l + l------------ww------------l + l------------ww------------l + l------------ww------------l + l-----------wwww-----------l + l---------wwwwwwww---------l + l----wwwwwwwwwwwwwwwwww----l +end diff --git a/sample/trick2018/05-tompng/preview_of_output.png b/sample/trick2018/05-tompng/preview_of_output.png Binary files differnew file mode 100644 index 0000000000..db511ee2f3 --- /dev/null +++ b/sample/trick2018/05-tompng/preview_of_output.png diff --git a/sample/trick2018/05-tompng/remarks.markdown b/sample/trick2018/05-tompng/remarks.markdown new file mode 100644 index 0000000000..b4e5708a43 --- /dev/null +++ b/sample/trick2018/05-tompng/remarks.markdown @@ -0,0 +1,31 @@ +### Remarks + +Just run it with no argument: + + ruby entry.rb + +I confirmed the following implementations/platforms: + +* ruby 2.5.0p0 (2017-12-25 revision 61468) [x86_64-darwin16] +* ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16] +* ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16] + +### Description + +This program will generate `wine_glass.stl`, a 3D data file(STL format) of a wine glass. +You can change the shape by modifying the DSL part. +For sake cup: +```ruby +gen3d 'ochoko.stl' do + l------------------------l + l-ww------------------ww-l + l-ww------------------ww-l + l-ww++++++++++++++++++ww-l + l-ww++++++++++++++++++ww-l + l--ww++++++++++++++++ww--l + l---wwww++++++++++wwww---l + l----wwwwwwwwwwwwwwww----l + l----www----------www----l +end +``` +`+` and `-` are the same meaning(just for appearance) diff --git a/sample/trick2018/README.md b/sample/trick2018/README.md new file mode 100644 index 0000000000..345500b00a --- /dev/null +++ b/sample/trick2018/README.md @@ -0,0 +1,16 @@ +This directory contains the award-winning entries of +the 3rd Transcendental Ruby Imbroglio Contest for rubyKaigi (TRICK 2018). + +THESE ARE BAD EXAMPLES! You must NOT use them as a sample code. + +* 01-kinaba/entry.rb: "Most reserved" - **Gold award** +* 02-mame/entry.rb: "Best spiral" - **Silver award** +* 03-tompng/entry.rb: "Best png viewer" - **Bronze award** +* 04-colin/entry.rb: "Best one-liner" - 4th prize +* 05-tompng/entry.rb: "Most three-dimensional" - 5th prize + +These files are licensed under MIT license. + +For the contest outline and other winning entries, see: + +https://github.com/tric/trick2018 diff --git a/sample/trojan.rb b/sample/trojan.rb index 2be9567b98..cea0dae098 100644 --- a/sample/trojan.rb +++ b/sample/trojan.rb @@ -7,7 +7,7 @@ for dir in path for f in d = Dir.open(dir) fpath = File.join(dir, f) if File.file?(fpath) && (File.stat(fpath).mode & 022) != 0 - printf("file %s is writable from other users\n", fpath) + printf("file %s is writable from other users\n", fpath) end end d.close diff --git a/sample/weakref.rb b/sample/weakref.rb new file mode 100644 index 0000000000..b9f38f954f --- /dev/null +++ b/sample/weakref.rb @@ -0,0 +1,9 @@ +require 'weakref' + +foo = Object.new +p foo.to_s # original's class +foo = WeakRef.new(foo) +p foo.to_s # should be same class +ObjectSpace.garbage_collect +ObjectSpace.garbage_collect +p foo.to_s # should raise exception (recycled) diff --git a/sample/webrick/demo-app.rb b/sample/webrick/demo-app.rb deleted file mode 100644 index c7a2a0a6a4..0000000000 --- a/sample/webrick/demo-app.rb +++ /dev/null @@ -1,66 +0,0 @@ -require "pp" - -module DemoApplication - def initialize(config, enctype) - super - @enctype = enctype - end - - def do_GET(req, res) - if req.path_info != "/" - res.set_redirect(WEBrick::HTTPStatus::Found, req.script_name + "/") - end - res.body =<<-_end_of_html_ - <HTML> - <FORM method="POST" enctype=#{@enctype}> - text: <INPUT type="text" name="text"><BR> - file: <INPUT type="file" name="file"><BR> - check: - <INPUT type="checkbox" name="check" value="a">a, - <INPUT type="checkbox" name="check" value="b">b, - <INPUT type="checkbox" name="check" value="c">c, - <BR> - <INPUT type="submit"> - </FORM> - </HTML> - _end_of_html_ - res['content-type'] = 'text/html; charset=iso-8859-1' - end - - def do_POST(req, res) - if req["content-length"].to_i > 1024*10 - raise WEBrick::HTTPStatus::Forbidden, "file size too large" - end - res.body =<<-_end_of_html_ - <HTML> - <H2>Query Parameters</H2> - #{display_query(req.query)} - <A href="#{req.path}">return</A> - <H2>Request</H2> - <PRE>#{WEBrick::HTMLUtils::escape(PP::pp(req, "", 80))}</PRE> - <H2>Response</H2> - <PRE>#{WEBrick::HTMLUtils::escape(PP::pp(res, "", 80))}</PRE> - </HTML> - _end_of_html_ - res['content-type'] = 'text/html; charset=iso-8859-1' - end - - private - - def display_query(q) - ret = "" - q.each{|key, val| - ret << "<H3>#{WEBrick::HTMLUtils::escape(key)}</H3>" - ret << "<TABLE border=1>" - ret << make_tr("val", val.inspect) - ret << make_tr("val.to_a", val.to_a.inspect) - ret << make_tr("val.to_ary", val.to_ary.inspect) - ret << "</TABLE>" - } - ret - end - - def make_tr(arg0, arg1) - "<TR><TD>#{arg0}</TD><TD>#{WEBrick::HTMLUtils::escape(arg1)}</TD></TR>" - end -end diff --git a/sample/webrick/demo-multipart.cgi b/sample/webrick/demo-multipart.cgi deleted file mode 100644 index 0893fadadf..0000000000 --- a/sample/webrick/demo-multipart.cgi +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env ruby -require "webrick/cgi" -require "webrick/https" # should load if it runs on HTTPS server -require "./demo-app" - -class DemoCGI < WEBrick::CGI - include DemoApplication -end - -config = { :NPH => false } -cgi = DemoCGI.new(config, "multipart/form-data") -cgi.start diff --git a/sample/webrick/demo-servlet.rb b/sample/webrick/demo-servlet.rb deleted file mode 100644 index 9c18cc65d1..0000000000 --- a/sample/webrick/demo-servlet.rb +++ /dev/null @@ -1,6 +0,0 @@ -require "webrick" -require "./demo-app" - -class DemoServlet < WEBrick::HTTPServlet::AbstractServlet - include DemoApplication -end diff --git a/sample/webrick/demo-urlencoded.cgi b/sample/webrick/demo-urlencoded.cgi deleted file mode 100644 index e4706f8b59..0000000000 --- a/sample/webrick/demo-urlencoded.cgi +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env ruby -require "webrick/cgi" -require "webrick/https" # should load if it runs on HTTPS server -require "./demo-app" - -class DemoCGI < WEBrick::CGI - include DemoApplication -end - -config = { :NPH => false } -cgi = DemoCGI.new(config, "application/x-www-form-urlencoded") -cgi.start diff --git a/sample/webrick/hello.cgi b/sample/webrick/hello.cgi deleted file mode 100644 index 35d2240df0..0000000000 --- a/sample/webrick/hello.cgi +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env ruby -require "webrick/cgi" - -class HelloCGI < WEBrick::CGI - def do_GET(req, res) - res["content-type"] = "text/plain" - res.body = "Hello, world.\n" - end -end - -HelloCGI.new.start diff --git a/sample/webrick/hello.rb b/sample/webrick/hello.rb deleted file mode 100644 index 4d02676818..0000000000 --- a/sample/webrick/hello.rb +++ /dev/null @@ -1,8 +0,0 @@ -require "webrick" - -class HelloServlet < WEBrick::HTTPServlet::AbstractServlet - def do_GET(req, res) - res["content-type"] = "text/plain" - res.body = "Hello, world.\n" - end -end diff --git a/sample/webrick/httpd.rb b/sample/webrick/httpd.rb deleted file mode 100644 index b0edf47582..0000000000 --- a/sample/webrick/httpd.rb +++ /dev/null @@ -1,23 +0,0 @@ -require "webrick" - -httpd = WEBrick::HTTPServer.new( - :DocumentRoot => File::dirname(__FILE__), - :Port => 10080, - :Logger => WEBrick::Log.new($stderr, WEBrick::Log::DEBUG), - :AccessLog => [ - [ $stderr, WEBrick::AccessLog::COMMON_LOG_FORMAT ], - [ $stderr, WEBrick::AccessLog::REFERER_LOG_FORMAT ], - [ $stderr, WEBrick::AccessLog::AGENT_LOG_FORMAT ], - ], - :CGIPathEnv => ENV["PATH"] # PATH environment variable for CGI. -) - -require "./hello" -httpd.mount("/hello", HelloServlet) - -require "./demo-servlet" -httpd.mount("/urlencoded", DemoServlet, "application/x-www-form-urlencoded") -httpd.mount("/multipart", DemoServlet, "multipart/form-data") - -trap(:INT){ httpd.shutdown } -httpd.start diff --git a/sample/webrick/httpproxy.rb b/sample/webrick/httpproxy.rb deleted file mode 100644 index c84457ece7..0000000000 --- a/sample/webrick/httpproxy.rb +++ /dev/null @@ -1,25 +0,0 @@ -require "webrick" -require "webrick/httpproxy" - -# The :ProxyContentHandler proc will be invoked before sending a response to -# the User-Agent. You can inspect the pair of request and response messages -# (or edit the response message if necessary). - -pch = Proc.new{|req, res| - p [ req.request_line, res.status_line ] -} - -def upstream_proxy - if prx = ENV["http_proxy"] - return URI.parse(prx) - end - return nil -end - -httpd = WEBrick::HTTPProxyServer.new( - :Port => 10080, - :ProxyContentHandler => pch, - :ProxyURI => upstream_proxy -) -Signal.trap(:INT){ httpd.shutdown } -httpd.start diff --git a/sample/webrick/httpsd.rb b/sample/webrick/httpsd.rb deleted file mode 100644 index a120782c3c..0000000000 --- a/sample/webrick/httpsd.rb +++ /dev/null @@ -1,33 +0,0 @@ -require "webrick" -require "webrick/https" - -hostname = WEBrick::Utils::getservername -subject = [["O", "ruby-lang.org"], ["OU", "sample"], ["CN", hostname]] -comment = "Comment for self-signed certificate" - -httpd = WEBrick::HTTPServer.new( - :DocumentRoot => File::dirname(__FILE__), - :Port => 10443, - :SSLEnable => true, - - # Specify key pair and server certificate. - # :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read("server.key")), - # :SSLCertificate => OpenSSL::X509::Certificate.new(File.read("server.crt")), - - # specify the following SSL options if you want to use auto - # generated self-signed certificate. - :SSLCertName => subject, - :SSLComment => comment, - - :CGIPathEnv => ENV["PATH"] # PATH environment variable for CGI. -) - -require "./hello" -httpd.mount("/hello", HelloServlet) - -require "./demo-servlet" -httpd.mount("/urlencoded", DemoServlet, "application/x-www-form-urlencoded") -httpd.mount("/multipart", DemoServlet, "multipart/form-data") - -trap(:INT){ httpd.shutdown } -httpd.start |
