diff options
Diffstat (limited to 'sample')
277 files changed, 5823 insertions, 13067 deletions
diff --git a/sample/README b/sample/README index 53d16de335..b55234a947 100644 --- a/sample/README +++ b/sample/README @@ -3,11 +3,10 @@ biorhythm.rb biorhythm calculator cal.rb cal(1) clone cbreak.rb no echo done by ioctl clnt.rb socket client -dbmtest.rb test for dbm +coverage.rb simple test code coverage tool dir.rb directory access dualstack-fetch.rb IPv6 demo dualstack-httpd.rb IPv6 demo -dstore.rb object database on dbm eval.rb simple evaluator export.rb method access example exyacc.rb extrace BNF from yacc file @@ -17,36 +16,28 @@ 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 -getopts.test test fot getopt.rb -goodfriday.rb print various christian calendar event. -io.rb io test -irb.rb interactive ruby less.rb front end for less list.rb stupid object sample list2.rb stupid object sample list3.rb stupid object sample -mine.rb simple mine sweeper -mkproto.rb extract prototype from C +mine.rb simple mine sweeper +mkproto.rb extract prototype from C mpart.rb split file int multi part -mrshtest.rb test marshal 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) rcs.rb random character stereogram (Ruby) rcs.dat data for random character stereogram -rd2html.rb rd (Ruby Document) to HTML translator -regx.rb regular expression tester sieve.rb sieve of Eratosthenes svr.rb socket server test.rb test suite used by `make test' time.rb /usr/bin/time clone +timeout.rb timeout test trojan.rb simple tool to find file that may be trojan horse. tsvr.rb socket server using thread uumerge.rb merge files and uudecode them diff --git a/sample/all-ruby-quine.rb b/sample/all-ruby-quine.rb new file mode 100644 index 0000000000..7686121468 --- /dev/null +++ b/sample/all-ruby-quine.rb @@ -0,0 +1,24 @@ + eval($s=("t='eval($s=('+d=34.chr;s=3 + 2.chr+$s*i=8;v=$VERSION||eval('begin;v=V + ERSION;rescue;v||RUBY_VERSION;end');f=('?'*8 + +'A|'+'?'*20+'G?c'+'?'*15+'A@CXx@~@_`OpGxCxp@~pO + xS|O~G?c?q?xC`AP|q?x_|C_xC_xO@H@cG?G?qA|_|_`GCpOxC|H +NFccqq@`_|OF@`?q?x_@x_x_`GB`O``O~G?C@qCxCxP@D@|G~C?pO|C? + pO|C?AP|A~HNN`ccxC|Q@L@B"+"GpGpc@p?x_`GB`???_@FO|OB@ + xC|P`@?c?q?HPx@~@_`G@`????@L^`?q?x?xq@|_|O~GC` + xA~@_@GBD').unpack('c*');w=4+v.length*u= + 15;r=10.chr;j=0;while-24+w*u>i=1+i + ;x=i%w;x>0||t=t+d+'+'+r+d;k= + i/w%12>2&&x%u>3&&x%u+i + /w*11-34+('-._'. + index(c=v[ + x/u,1] + )||c.hex +3)*99| + |0; k=f [k/6 ][k% + 6]; t=t +s[ + k*j =k+ j,1 + ]end;pr int (t+ + d+' ).s pli + t.j oin [0, + 609 ])# Y.E. '+r) + ").split .join)# 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 c7e26c4fff..f5d189014b 100644 --- a/sample/biorhythm.rb +++ b/sample/biorhythm.rb @@ -1,14 +1,13 @@ #!/usr/local/bin/ruby # -# biorhythm.rb - +# biorhythm.rb - # $Release Version: $ # $Revision$ -# $Date$ # by Yasuo OHBA(STAFS Development Room) # # -- # -# +# # # probably based on: @@ -26,124 +25,88 @@ # Environment: basic, dos, os9 include Math -require "date.rb" -require "parsearg.rb" -require "parsedate.rb" - -def usage() - print "Usage:\n" - print "biorhythm.rb [options]\n" - print " options...\n" - print " -D YYYYMMDD(birthday) : use default values.\n" - print " --sdate | --date YYYYMMDD : use system date; use specified date.\n" - print " --birthday YYYYMMDD : specifies your birthday.\n" - print " -v | -g : show values or graph.\n" - print " --days DAYS : graph range (only in effect for graphs).\n" - print " --help : help\n" -end -$USAGE = 'usage' +require "date" +require "optparse" +require "optparse/date" -def printHeader(y, m, d, p, w) +def print_header(y, m, d, p, w) print "\n>>> Biorhythm <<<\n" printf "The birthday %04d.%02d.%02d is a %s\n", y, m, d, w printf "Age in days: [%d]\n\n", p end -def getPosition(z) - pi = Math::PI +def get_position(z) 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 -def parsedate(s) - ParseDate::parsedate(s).values_at(0, 1, 2) -end - -def name_of_week(date) - Date::DAYNAMES[date.wday] +def prompt(msg) + $stderr.print msg + return gets.chomp end # # main program # -parseArgs(0, nil, "vg", "D:", "sdate", "date:", "birthday:", "days:") - -if $OPT_D - dd = Date.today - bd = Date.new(*parsedate($OPT_D)) - ausgabeart = "g" -else - if $OPT_birthday - bd = Date.new(*parsedate($OPT_birthday)) - else - STDERR.print("Birthday (YYYYMMDD) : ") - unless (si = STDIN.gets.chop).empty? - bd = Date.new(*parsedate(si)) - end - end - if !bd - STDERR.print "BAD Input Birthday!!\n" - exit() +options = { + :graph => true, + :date => Date.today, + :days => 9, +} +ARGV.options do |opts| + opts.on("-b", "--birthday=DATE", Date, "specify your birthday"){|v| + options[:birthday] = v + } + opts.on("--date=DATE", Date, "specify date to show"){|v| + options[:date] = v + } + opts.on("-g", "--show-graph", TrueClass, "show graph (default)"){|v| + options[:graph] = v + } + opts.on("-v", "--show-values", TrueClass, "show values"){|v| + options[:graph] = !v + } + opts.on("--days=DAYS", Integer, "graph range (only in effect for graph)"){|v| + options[:days] = v - 1 + } + opts.on_tail("-h", "--help", "show this message"){puts opts; exit} + begin + opts.parse! + rescue => ex + puts "Error: #{ex.message}" + puts opts + exit end +end - if $OPT_sdate - dd = Date.today - elsif $OPT_date - dd = Date.new(*parsedate($OPT_date)) - else - STDERR.print("Date [<RETURN> for Systemdate] (YYYYMMDD) : ") - unless (si = STDIN.gets.chop).empty? - dd = Date.new(*parsedate(si)) - end - end - dd ||= Date.today +bd = options[:birthday] || Date.parse(prompt("Your birthday (YYYYMMDD): ")) +dd = options[:date] || Date.today +ausgabeart = options[:graph] ? "g" : "v" +display_period = options[:days] - if $OPT_v - ausgabeart = "v" - elsif $OPT_g - ausgabeart = "g" - else - STDERR.print("Values for today or Graph (v/g) [default g] : ") - ausgabeart = STDIN.gets.chop - end -end if ausgabeart == "v" - printHeader(bd.year, bd.month, bd.day, dd - bd, name_of_week(bd)) + print_header(bd.year, bd.month, bd.day, dd - bd, bd.strftime("%a")) print "\n" - - phys, emot, geist = getPosition(dd - bd) + + phys, emot, geist = get_position(dd - bd) printf "Biorhythm: %04d.%02d.%02d\n", dd.year, dd.month, dd.day printf "Physical: %d%%\n", phys printf "Emotional: %d%%\n", emot printf "Mental: %d%%\n", geist print "\n" else - if $OPT_days - display_period = $OPT_days.to_i - elsif $OPT_D - display_period = 9 - else - STDERR.printf("Graph for how many days [default 10] : ") - display_period = STDIN.gets.chop - if display_period.empty? - display_period = 9 - else - display_period = display_period.to_i - 1 - end - end - - printHeader(bd.year, bd.month, bd.day, dd - bd, name_of_week(bd)) + print_header(bd.year, bd.month, bd.day, dd - bd, bd.strftime("%a")) print " P=physical, E=emotional, M=mental\n" print " -------------------------+-------------------------\n" print " Bad Condition | Good Condition\n" print " -------------------------+-------------------------\n" - + (dd - bd).step(dd - bd + display_period) do |z| - phys, emot, geist = getPosition(z) - + phys, emot, geist = get_position(z) + printf "%04d.%02d.%02d : ", dd.year, dd.month, dd.day p = (phys / 2.0 + 0.5).to_i e = (emot / 2.0 + 0.5).to_i diff --git a/sample/cal.rb b/sample/cal.rb index fa20352f71..97f75bcf1c 100644 --- a/sample/cal.rb +++ b/sample/cal.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -# cal.rb: Written by Tadayoshi Funaba 1998-2004 -# $Id: cal.rb,v 2.7 2004-01-10 23:52:51+09 tadf Exp $ +# cal.rb: Written by Tadayoshi Funaba 1998-2004,2006,2008 +# $Id: cal.rb,v 2.11 2008-01-06 08:42:17+09 tadf Exp $ require 'date' @@ -9,25 +9,25 @@ class Cal START = { - 'cn' => true, # China - 'de' => 2342032, # Germany (protestant states) - 'dk' => 2342032, # Denmark - 'es' => 2299161, # Spain - 'fi' => 2361390, # Finland - 'fr' => 2299227, # France - 'gb' => 2361222, # United Kingdom - 'gr' => 2423868, # Greece - 'hu' => 2301004, # Hungary - 'it' => 2299161, # Italy - 'jp' => true, # Japan - 'no' => 2342032, # Norway - 'pl' => 2299161, # Poland - 'pt' => 2299161, # Portugal - 'ru' => 2421639, # Russia - 'se' => 2361390, # Sweden - 'us' => 2361222, # United States - 'os' => false, # (old style) - 'ns' => true # (new style) + 'cn' => Date::GREGORIAN, # China + 'de' => 2342032, # Germany (protestant states) + 'dk' => 2342032, # Denmark + 'es' => 2299161, # Spain + 'fi' => 2361390, # Finland + 'fr' => 2299227, # France + 'gb' => 2361222, # United Kingdom + 'gr' => 2423868, # Greece + 'hu' => 2301004, # Hungary + 'it' => 2299161, # Italy + 'jp' => Date::GREGORIAN, # Japan + 'no' => 2342032, # Norway + 'pl' => 2299161, # Poland + 'pt' => 2299161, # Portugal + 'ru' => 2421639, # Russia + 'se' => 2361390, # Sweden + 'us' => 2361222, # United States + 'os' => Date::JULIAN, # (old style) + 'ns' => Date::GREGORIAN # (new style) } DEFAULT_START = 'gb' @@ -53,7 +53,7 @@ class Cal end def pict(y, m) - d = (1..31).detect{|d| Date.valid_date?(y, m, d, @start)} + d = (1..31).detect{|x| Date.valid_date?(y, m, x, @start)} fi = Date.new(y, m, d, @start) fi -= (fi.jd - @k + 1) % 7 @@ -71,8 +71,8 @@ class Cal ta = gr.collect{|xs| xs.join(' ')} ca = %w(January February March April May June July - August September October November December)[m - 1] - ca = ca + ' ' + y.to_s if not @opt_y + August September October November December)[m - 1] + ca = ca + ' ' + y.to_s if !@opt_y ca = ca.center(@mw) ta.unshift(ca) @@ -121,34 +121,46 @@ end if __FILE__ == $0 - require 'getopts' + require 'getoptlong' def usage warn 'usage: cal [-c iso3166] [-jmty] [[month] year]' exit 1 end - usage unless getopts('jmty', "c:#{Cal::DEFAULT_START}") + cal = Cal.new + + begin + GetoptLong.new(['-c', GetoptLong::REQUIRED_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 + when '-j'; cal.opt_j(true) + when '-m'; cal.opt_m(true) + when '-t'; cal.opt_t(true) + when '-y'; cal.opt_y(true) + end + end + rescue + usage + end y, m = ARGV.values_at(1, 0).compact.collect{|x| x.to_i} - $OPT_y ||= (y and not m) + cal.opt_y(true) if y && !m to = Date.today y ||= to.year m ||= to.mon - usage unless m >= 1 and m <= 12 + usage unless m >= 1 && m <= 12 usage unless y >= -4712 - usage if Cal::START[$OPT_c].nil? - - cal = Cal.new - - cal.opt_j($OPT_j) - cal.opt_m($OPT_m) - cal.opt_t($OPT_t) - cal.opt_y($OPT_y) - cal.opt_c($OPT_c) print cal.print(y, m) end + +# See Bird & Wadler's Introduction to functional programming 4.5. diff --git a/sample/cbreak.rb b/sample/cbreak.rb index cbb15d2f41..7f1385cce3 100644 --- a/sample/cbreak.rb +++ b/sample/cbreak.rb @@ -5,15 +5,15 @@ ECHO = 0x00000008 TIOCGETP = 0x40067408 TIOCSETP = 0x80067409 -def cbreak () - set_cbreak(TRUE) +def cbreak + set_cbreak(true) end -def cooked () - set_cbreak(FALSE) +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 new file mode 100644 index 0000000000..42ba89fd50 --- /dev/null +++ b/sample/coverage.rb @@ -0,0 +1,62 @@ +require "coverage.so" + +Coverage.start + +ext = ENV["COVERUBY_EXT"] || ".cov" +accum = ENV["COVERUBY_ACCUM"] +accum = !accum || accum == "" || !(%w(f n 0).include?(accum[0])) +pwd = Dir.pwd + +at_exit do + exit_exc = $! + Dir.chdir(pwd) do + Coverage.result.each do |sfile, covs| + cfile = sfile + ext + + writable = proc do |f| + File.writable?(f) || File.writable?(File.dirname(f)) + end + unless writable[cfile] + cfile = cfile.gsub(File::PATH_SEPARATOR, "#") + next unless writable[cfile] + end + + readlines = proc do |f| + File.read(f).force_encoding("ASCII-8BIT").lines.to_a + end + + sources = (readlines[sfile] rescue []) + + pcovs = [] + if accum + pcovs = (readlines[cfile] rescue []).map.with_index do |line, idx| + if line[/^\s*(?:(#####)|(\d+)|-):\s*\d+:(.*)$/n] + cov, line = $1 ? 0 : ($2 ? $2.to_i : nil), $3 + if !sources[idx] || sources[idx].chomp != line.chomp + warn("source file changed, ignoring: `#{ cfile }'") + break [] + end + cov + else + p line + warn("coverage file corrupted, ignoring: #{ cfile }") + break [] + end + end + unless pcovs.empty? || pcovs.size == covs.size + warn("coverage file changed, ignoring: `#{ cfile }'") + pcovs = [] + end + end + + File.open(cfile, "w") do |out| + covs.zip(sources, pcovs).each_with_index do |(cov, line, pcov), idx| + cov += pcov || 0 if cov + cov = (cov ? (cov == 0 ? "#####" : cov.to_s) : "-").rjust(9) + out.puts("%s:% 5d:%s" % [cov, idx + 1, line]) + end + end + end + end + raise exit_exc if exit_exc +end diff --git a/sample/dbmtest.rb b/sample/dbmtest.rb deleted file mode 100644 index c77cc2065b..0000000000 --- a/sample/dbmtest.rb +++ /dev/null @@ -1,14 +0,0 @@ -# ruby dbm acess -require "dbm" - -d = DBM.open("test") -keys = d.keys -if keys.length > 0 then - for k in keys; print k, "\n"; end - for v in d.values; print v, "\n"; end -else - d['foobar'] = 'FB' - d['baz'] = 'BZ' - d['quux'] = 'QX' -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..81257cd917 100644 --- a/sample/dir.rb +++ b/sample/dir.rb @@ -1,12 +1,7 @@ # directory access # list all files but .*/*~/*.o -dirp = Dir.open(".") -for f in dirp - case f - when /^\./, /~$/, /\.o/ - # do not print - else - print f, "\n" +Dir.foreach(".") do |file| + unless file.start_with?('.') or file.end_with?('~', '.o') + puts file end end -dirp.close diff --git a/sample/drb/README.rd b/sample/drb/README.rd deleted file mode 100644 index 5cf1f51913..0000000000 --- a/sample/drb/README.rd +++ /dev/null @@ -1,56 +0,0 @@ -= Sample scripts - -* array and iteretor - * darray.rb --- server - * darrayc.rb --- client - -* simple chat - * dchats.rb --- server - * dchatc.rb --- client - -* distributed chasen (for Japanese) - * dhasen.rb --- server - * dhasenc.rb --- client - -* simple log server - * dlogd.rb --- server - * dlogc.rb --- client - -* Queue server, and DRbUnknown demo - * dqueue.rb --- server - * dqin.rb --- client. push DQEntry objects. - * dqout.rb --- client. pop DQEntry objects. - * dqlib.rb --- define DQEntry - -* IdConv customize demo: reference by name - * name.rb --- server - * namec.rb --- client - -* extserv - * extserv_test.rb - -* IdConv customize demo 2: using TimerIdConv - * holders.rb --- server - * holderc.rb --- client - -* rinda, remote tuplespace - * rinda_ts.rb --- TupleSpace server. - * rindas.rb --- provide simple service via TupleSpace. - * rindac.rb --- service user - -* observer - cdbiff - ((<URI:http://namazu.org/~satoru/cdbiff/>)) - * dbiff.rb --- dcdbiff server - * dcdbiff.rb --- dcdbiff client - -* drbssl - * drbssl_s.rb - * drbssl_c.rb - -* add DRbProtocl - * http0.rb - * http0serv.rb - -* Rinda::Ring - * ring_place.rb - * ring_echo.rb diff --git a/sample/drb/README.rd.ja b/sample/drb/README.rd.ja deleted file mode 100644 index 04143b9ad5..0000000000 --- a/sample/drb/README.rd.ja +++ /dev/null @@ -1,59 +0,0 @@ -= ¥µ¥ó¥×¥ë¥¹¥¯¥ê¥×¥È - -* Array¤ò¥ê¥â¡¼¥È¤«¤éÍøÍѤ·¤Æ¥¤¥Æ¥ì¡¼¥¿¤ò»î¤¹¡£ - * darray.rb --- server - * darrayc.rb --- client - -* ´Ê°×¥Á¥ã¥Ã¥È - * dchats.rb --- server - * dchatc.rb --- client - -* ʬ»¶chasen - * dhasen.rb --- server - * dhasenc.rb --- client - -* ´Ê°×¥í¥°¥µ¡¼¥Ð - * dlogd.rb --- server - * dlogc.rb --- client - -* Queue¥µ¡¼¥Ð¡£ - ¥¯¥é¥¤¥¢¥ó¥Èdqin.rb¤ÏQueue¥µ¡¼¥Ð¤ÎÃΤé¤Ê¤¤¥ª¥Ö¥¸¥§¥¯¥È(DQEntry)¤ò - push¤¹¤ë¤¬DRbUnknown¤Ë¤è¤ê¥¯¥é¥¤¥¢¥ó¥Èdqout.rb¤¬pop¤Ç¤¤ë¡£ - * dqueue.rb --- server - * dqin.rb --- client¡£DQEntry¥ª¥Ö¥¸¥§¥¯¥È¤òpush¤¹¤ë - * dqout.rb --- client¡£DQEntry¥ª¥Ö¥¸¥§¥¯¥È¤òpop¤¹¤ë - * dqlib.rb --- DQEntry¤òÄêµÁ¤·¤¿¥é¥¤¥Ö¥é¥ê - -* ̾Á°¤Ë¤è¤ë»²¾È - IdConv¤ò¥«¥¹¥¿¥Þ¥¤¥º¤·¤Æid¤Ç¤Ê¤¯Ì¾Á°¤Ç»²¾È¤¹¤ëÎã - * name.rb --- server - * namec.rb --- client - -* extserv¤Î¥µ¥ó¥×¥ë - * extserv_test.rb - -* TimerIdConv¤Î»ÈÍÑÎã - * holders.rb --- server¡£ruby -d hodlers.rb¤È¤¹¤ë¤ÈTimerIdConv¤ò»ÈÍѤ¹¤ë¡£ - * holderc.rb --- client - -* rinda.rb¤Î»ÈÍÑÎã - * rinda_ts.rb --- TupleSpace¥µ¡¼¥Ð¡£ - * rindac.rb --- TupleSpace¤Îclient¤Ç¥¢¥×¥ê¥±¡¼¥·¥ç¥ó¤Îclient - * rindas.rb --- TupleSpace¤Îclient¤Ç¥¢¥×¥ê¥±¡¼¥·¥ç¥ó¤Îserver - -* observer¤Î»ÈÍÑÎã - cdbiff - ((<URI:http://namazu.org/~satoru/cdbiff/>)) - * dbiff.rb --- dcdbiff server - * dcdbiff.rb --- dcdbiff client - -* drbssl¤Î»ÈÍÑÎã - * drbssl_s.rb - * drbssl_c.rb - -* DRbProtocl¤ÎÄɲÃÎã - * http0.rb - * http0serv.rb - -* ring¤Î»ÈÍÑÎã - * ring_place.rb - * ring_echo.rb diff --git a/sample/drb/darray.rb b/sample/drb/darray.rb deleted file mode 100644 index bee295d278..0000000000 --- a/sample/drb/darray.rb +++ /dev/null @@ -1,13 +0,0 @@ -=begin - distributed Ruby --- Array - Copyright (c) 1999-2001 Masatoshi SEKI -=end - -require 'drb/drb' - -here = ARGV.shift -DRb.start_service(here, [1, 2, "III", 4, "five", 6]) -puts DRb.uri -puts '[return] to exit' -gets - diff --git a/sample/drb/darrayc.rb b/sample/drb/darrayc.rb deleted file mode 100644 index 6f5ff6bb5d..0000000000 --- a/sample/drb/darrayc.rb +++ /dev/null @@ -1,59 +0,0 @@ -=begin - distributed Ruby --- Array client - Copyright (c) 1999-2001 Masatoshi SEKI -=end - -require 'drb/drb' - -there = ARGV.shift || raise("usage: #{$0} <server_uri>") - -DRb.start_service(nil, nil) -ro = DRbObject.new(nil, there) -p ro.size - -puts "# collect" -a = ro.collect { |x| - x + x -} -p a - -puts "# find" -p ro.find { |x| x.kind_of? String } - -puts "# each, break" -ro.each do |x| - next if x == "five" - puts x -end - -puts "# each, break" -ro.each do |x| - break if x == "five" - puts x -end - -puts "# each, next" -ro.each do |x| - next if x == "five" - puts x -end - -puts "# each, redo" -count = 0 -ro.each do |x| - count += 1 - puts count - redo if count == 3 -end - -puts "# each, retry" -retried = false -ro.each do |x| - puts x - if x == 4 && !retried - puts 'retry' - retried = true - retry - end -end - diff --git a/sample/drb/dbiff.rb b/sample/drb/dbiff.rb deleted file mode 100644 index 8faef50b07..0000000000 --- a/sample/drb/dbiff.rb +++ /dev/null @@ -1,51 +0,0 @@ -# -# dbiff.rb - distributed cdbiff (server) -# * original: cdbiff by Satoru Takabayashi <http://namazu.org/~satoru/cdbiff> - -require 'drb/drb' -require 'drb/eq' -require 'drb/observer' - -class Biff - include DRb::DRbObservable - - def initialize(filename, interval) - super() - @filename = filename - @interval = interval - end - - def run - 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 - rescue - next - end - end - end -end - -def main - filename = "/var/mail/#{ENV['USER']}" - interval = 15 - uri = 'druby://:19903' - - biff = Biff.new(filename, interval) - - DRb.start_service(uri, biff) - biff.run -end - -main - diff --git a/sample/drb/dcdbiff.rb b/sample/drb/dcdbiff.rb deleted file mode 100644 index 6a24680c33..0000000000 --- a/sample/drb/dcdbiff.rb +++ /dev/null @@ -1,43 +0,0 @@ -# -# dcdbiff.rb - distributed cdbiff (client) -# * original: cdbiff by Satoru Takabayashi <http://namazu.org/~satoru/cdbiff> - -require 'drb/drb' -require 'drb/eq' - -class Notify - include DRbUndumped - - def initialize(biff, command) - @biff = biff - @command = command - - @biff.add_observer(self) - end - - def update(filename, time) - p [filename, time] if $DEBUG - system(@command) - end - - def done - begin - @biff.delete_observer(self) - rescue - end - end -end - -def main - command = 'eject' - uri = 'druby://localhost:19903' - - DRb.start_service - biff = DRbObject.new(nil, uri) - notify = Notify.new(biff, command) - - trap("INT"){ notify.done } - DRb.thread.join -end - -main diff --git a/sample/drb/dchatc.rb b/sample/drb/dchatc.rb deleted file mode 100644 index b506f5bbba..0000000000 --- a/sample/drb/dchatc.rb +++ /dev/null @@ -1,41 +0,0 @@ -=begin - distributed Ruby --- chat client - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -require 'drb/drb' - -class ChatClient - include DRbUndumped - - def initialize(name) - @name = name - @key = nil - end - attr_reader(:name) - attr_accessor(:key) - - def message(there, str) - raise 'invalid key' unless @key == there - puts str - end -end - -if __FILE__ == $0 - begin - there = ARGV.shift - name = ARGV.shift - raise "usage" unless (there and name) - rescue - $stderr.puts("usage: #{$0} <server_uri> <your_name>") - exit 1 - end - DRb.start_service - ro = DRbObject.new(nil, there) - - chat = ChatClient.new(name) - entry = ro.add_member(chat) - while gets - entry.say($_) - end -end diff --git a/sample/drb/dchats.rb b/sample/drb/dchats.rb deleted file mode 100644 index b3133d1163..0000000000 --- a/sample/drb/dchats.rb +++ /dev/null @@ -1,71 +0,0 @@ -=begin - distributed Ruby --- chat server - Copyright (c) 1999-2000 Masatoshi SEKI -=end -require 'thread' -require 'drb/drb' - -class ChatEntry - include DRbUndumped - - def initialize(server, there) - @server = server - @there = there - @name = there.name - @key = there.key = Time.now - end - attr :name, true - attr :there - - def say(str) - @server.distribute(@there, str) - end - - def listen(str) - @there.message(@key, str) - end -end - - -class ChatServer - def initialize - @mutex = Mutex.new - @members = {} - end - - def add_member(there) - client = ChatEntry.new(self, there) - @mutex.synchronize do - @members[there] = client - end - client - end - - def distribute(there, str) - name = @members[there].name - msg = "<#{name}> #{str}" - 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 - end - end - end -end - -if __FILE__ == $0 - here = ARGV.shift - DRb.start_service(here, ChatServer.new) - puts DRb.uri - puts '[return] to exit.' - gets -end diff --git a/sample/drb/dhasen.rb b/sample/drb/dhasen.rb deleted file mode 100644 index 5dac88853c..0000000000 --- a/sample/drb/dhasen.rb +++ /dev/null @@ -1,43 +0,0 @@ -=begin - distributed Ruby --- dRuby Sample Server --- chasen server - Copyright (c) 1999-2001 Masatoshi SEKI -=end - -=begin - How to play. - - Terminal 1 - | % ruby dhasen.rb - | druby://yourhost:7640 - - Terminal 2 - | % ruby dhasenc.rb druby://yourhost:7640 - -=end - -require 'drb/drb' -require 'chasen' -require 'thread' - -class Dhasen - include DRbUndumped - - def initialize - @mutex = Mutex.new - end - - def sparse(str, *arg) - @mutex.synchronize do - Chasen.getopt(*arg) - Chasen.sparse(str) - end - end -end - -if __FILE__ == $0 - DRb.start_service(nil, Dhasen.new) - puts DRb.uri - puts '[return] to exit.' - gets -end - diff --git a/sample/drb/dhasenc.rb b/sample/drb/dhasenc.rb deleted file mode 100644 index 8114e9228d..0000000000 --- a/sample/drb/dhasenc.rb +++ /dev/null @@ -1,13 +0,0 @@ -=begin - distributed Ruby --- dRuby Sample Client -- chasen client - Copyright (c) 1999-2001 Masatoshi SEKI -=end - -require 'drb/drb' - -there = ARGV.shift || raise("usage: #{$0} <server_uri>") -DRb.start_service -dhasen = DRbObject.new(nil, there) - -print dhasen.sparse("ËÜÆü¤Ï¡¢À²Å·¤Ê¤ê¡£", "-F", '(%BB %m %M)\n', "-j") -print dhasen.sparse("ËÜÆü¤Ï¡¢À²Å·¤Ê¤ê¡£", "-F", '(%m %M)\n') diff --git a/sample/drb/dlogc.rb b/sample/drb/dlogc.rb deleted file mode 100644 index c75bc7b520..0000000000 --- a/sample/drb/dlogc.rb +++ /dev/null @@ -1,16 +0,0 @@ -=begin - distributed Ruby --- Log test - Copyright (c) 1999-2001 Masatoshi SEKI -=end - -require 'drb/drb' - -there = ARGV.shift || raise("usage: #{$0} <server_uri>") - -DRb.start_service -ro = DRbObject.new(nil, there) -ro.log(123) -ro.log("hello") -sleep 2 -ro.log("wakeup") - diff --git a/sample/drb/dlogd.rb b/sample/drb/dlogd.rb deleted file mode 100644 index 9f9aa2fd56..0000000000 --- a/sample/drb/dlogd.rb +++ /dev/null @@ -1,39 +0,0 @@ -=begin - distributed Ruby --- Log server - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -require 'drb/drb' -require 'thread' - -class Logger - def initialize(fname) - @fname = fname.to_s - @fp = File.open(@fname, "a+") - @queue = Queue.new - @th = Thread.new { self.flush } - end - - def log(str) - @queue.push("#{Time.now}\t" + str.to_s) - end - - def flush - begin - while(1) - @fp.puts(@queue.pop) - @fp.flush - end - ensure - @fp.close - end - end -end - -if __FILE__ == $0 - here = ARGV.shift - DRb.start_service(here, Logger.new('/usr/tmp/dlogd.log')) - puts DRb.uri - DRb.thread.join -end - diff --git a/sample/drb/dqin.rb b/sample/drb/dqin.rb deleted file mode 100644 index 3ba1caa80c..0000000000 --- a/sample/drb/dqin.rb +++ /dev/null @@ -1,13 +0,0 @@ -=begin - distributed Ruby --- store - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -require 'drb/drb' -require 'dqlib' - -there = ARGV.shift || raise("usage: #{$0} <server_uri>") - -DRb.start_service -queue = DRbObject.new(nil, there) -queue.push(DQEntry.new(DRb.uri)) diff --git a/sample/drb/dqlib.rb b/sample/drb/dqlib.rb deleted file mode 100644 index 75f2e6115b..0000000000 --- a/sample/drb/dqlib.rb +++ /dev/null @@ -1,14 +0,0 @@ -class DQEntry - def initialize(name) - @name = name - end - - def greeting - "Hello, This is #{@name}." - end - alias to_s greeting -end - -if __FILE__ == $0 - puts DQEntry.new('DQEntry') -end diff --git a/sample/drb/dqout.rb b/sample/drb/dqout.rb deleted file mode 100644 index 4700e55cf7..0000000000 --- a/sample/drb/dqout.rb +++ /dev/null @@ -1,14 +0,0 @@ -=begin - distributed Ruby --- fetch - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -require 'drb/drb' -require 'dqlib' - -there = ARGV.shift || raise("usage: #{$0} <server_uri>") - -DRb.start_service -queue = DRbObject.new(nil, there) -entry = queue.pop -puts entry.greeting diff --git a/sample/drb/dqueue.rb b/sample/drb/dqueue.rb deleted file mode 100644 index 90ec56ce65..0000000000 --- a/sample/drb/dqueue.rb +++ /dev/null @@ -1,13 +0,0 @@ -=begin - distributed Ruby --- Queue - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -require 'thread' -require 'drb/drb' - -DRb.start_service(nil, Queue.new) -puts DRb.uri -puts '[return] to exit' -gets - diff --git a/sample/drb/drbc.rb b/sample/drb/drbc.rb deleted file mode 100644 index 00132b46c8..0000000000 --- a/sample/drb/drbc.rb +++ /dev/null @@ -1,45 +0,0 @@ -=begin - distributed Ruby --- dRuby Sample Client - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -require 'drb/drb' - -class DRbEx2 - include DRbUndumped - - def initialize(n) - @n = n - end - - def to_i - @n.to_i - end -end - -if __FILE__ == $0 - there = ARGV.shift - unless there - $stderr.puts("usage: #{$0} <server_uri>") - exit 1 - end - - DRb.start_service() - ro = DRbObject.new_with_uri(there) - - puts ro - p ro.to_a - puts ro.hello - p ro.hello - puts ro.sample(DRbEx2.new(1), 2, 3) - puts ro.sample(1, ro.sample(DRbEx2.new(1), 2, 3), DRbEx2.new(3)) - - begin - ro.err - rescue DRb::DRbUnknownError - p $! - p $!.unknown - rescue RuntimeError - p $! - end -end diff --git a/sample/drb/drbch.rb b/sample/drb/drbch.rb deleted file mode 100644 index 495ff1c346..0000000000 --- a/sample/drb/drbch.rb +++ /dev/null @@ -1,48 +0,0 @@ -=begin - distributed Ruby --- dRuby Sample Client - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -require 'drb/drb' -require 'drb/http' - -class DRbEx2 - include DRbUndumped - - def initialize(n) - @n = n - end - - def to_i - @n.to_i - end -end - -if __FILE__ == $0 - there = ARGV.shift - unless there - $stderr.puts("usage: #{$0} <server_uri>") - exit 1 - end - - DRb::DRbConn.proxy_map['x68k'] = 'http://x68k/~mas/http_cgi.rb' - - DRb.start_service() - ro = DRbObject.new(nil, there) - - puts ro - p ro.to_a - puts ro.hello - p ro.hello - puts ro.sample(DRbEx2.new(1), 2, 3) - puts ro.sample(1, ro.sample(DRbEx2.new(1), 2, 3), DRbEx2.new(3)) - - begin - ro.err - rescue DRb::DRbUnknownError - p $! - p $!.unknown - rescue RuntimeError - p $! - end -end diff --git a/sample/drb/drbm.rb b/sample/drb/drbm.rb deleted file mode 100644 index 37a26cdfa5..0000000000 --- a/sample/drb/drbm.rb +++ /dev/null @@ -1,59 +0,0 @@ -=begin - multiple DRbServer - Copyright (c) 1999-2002 Masatoshi SEKI -=end - -=begin - How to play. - - Terminal 1 - | % ruby drbm.rb - | druby://yourhost:7640 druby://yourhost:7641 - - Terminal 2 - | % ruby drbmc.rb druby://yourhost:7640 druby://yourhost:7641 - | [#<DRb::DRbObject .... @uri="druby://yourhost:7640">, "FOO"] - | [#<DRb::DRbObject .... @uri="druby://yourhost:7641">, "FOO"] - -=end - -require 'drb/drb' - -class Hoge - include DRbUndumped - def initialize(s) - @str = s - end - - def to_s - @str - end -end - -class Foo - def initialize(s='FOO') - @hoge = Hoge.new(s) - end - - def hello - @hoge - end -end - -class Bar < Foo - def initialize(foo) - @hoge = foo.hello - end -end - - -if __FILE__ == $0 - foo = Foo.new - s1 = DRb::DRbServer.new('druby://:7640', foo) - s2 = DRb::DRbServer.new('druby://:7641', Bar.new(foo)) - - puts "#{s1.uri} #{s2.uri}" - - gets -end - diff --git a/sample/drb/drbmc.rb b/sample/drb/drbmc.rb deleted file mode 100644 index c654fcea05..0000000000 --- a/sample/drb/drbmc.rb +++ /dev/null @@ -1,22 +0,0 @@ -=begin - multiple DRbServer client - Copyright (c) 1999-2002 Masatoshi SEKI -=end - -require 'drb/drb' - -if __FILE__ == $0 - s1 = ARGV.shift - s2 = ARGV.shift - unless s1 && s2 - $stderr.puts("usage: #{$0} <server_uri1> <server_uri2>") - exit 1 - end - - DRb.start_service() - r1 = DRbObject.new(nil, s1) - r2 = DRbObject.new(nil, s2) - - p [r1.hello, r1.hello.to_s] - p [r2.hello, r2.hello.to_s] -end diff --git a/sample/drb/drbs-acl.rb b/sample/drb/drbs-acl.rb deleted file mode 100644 index 151dd945d8..0000000000 --- a/sample/drb/drbs-acl.rb +++ /dev/null @@ -1,51 +0,0 @@ -=begin - distributed Ruby --- dRuby Sample Server - Copyright (c) 1999-2000 Masatoshi SEKI -=end - -=begin - How to play. - - Terminal 1 - | % ruby drbs.rb - | druby://yourhost:7640 - - Terminal 2 - | % ruby drbc.rb druby://yourhost:7640 - | "hello" - | 6 - | 10 - -=end - -require 'drb/drb' -require 'acl' - -class DRbEx - def initialize - @hello = 'hello' - end - - def hello - info = Thread.current['DRb'] - p info['socket'].peeraddr if info - @hello - end - - def sample(a, b, c) - a.to_i + b.to_i + c.to_i - end -end - -if __FILE__ == $0 - acl = ACL.new(%w(deny all - allow 192.168.1.* - allow localhost)) - - DRb.install_acl(acl) - - DRb.start_service(nil, DRbEx.new) - puts DRb.uri - DRb.thread.join -end - diff --git a/sample/drb/drbs.rb b/sample/drb/drbs.rb deleted file mode 100644 index b76e283c80..0000000000 --- a/sample/drb/drbs.rb +++ /dev/null @@ -1,64 +0,0 @@ -=begin - distributed Ruby --- dRuby Sample Server - Copyright (c) 1999-2000,2002 Masatoshi SEKI -=end - -=begin - How to play. - - Terminal 1 - | % ruby drbs.rb - | druby://yourhost:7640 - - Terminal 2 - | % ruby drbc.rb druby://yourhost:7640 - | "hello" - | .... - -=end - -require 'drb/drb' - -class DRbEx - include DRbUndumped - - def initialize - @hello = 'hello' - end - - def hello - cntxt = Thread.current['DRb'] - if cntxt - p cntxt['server'].uri - p cntxt['client'].peeraddr - end - Foo::Unknown.new - end - - def err - raise FooError - end - - def sample(a, b, c) - a.to_i + b.to_i + c.to_i - end -end - -class Foo - class Unknown - end -end - -class FooError < RuntimeError -end - -if __FILE__ == $0 - DRb.start_service(ARGV.shift || 'druby://:7640', DRbEx.new) - puts DRb.uri - Thread.new do - sleep 10 - DRb.stop_service - end - DRb.thread.join -end - diff --git a/sample/drb/drbssl_c.rb b/sample/drb/drbssl_c.rb deleted file mode 100644 index 65112f6e78..0000000000 --- a/sample/drb/drbssl_c.rb +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env ruby - -require 'drb' -require 'drb/ssl' - -there = ARGV.shift || "drbssl://localhost:3456" - -config = Hash.new -config[:SSLVerifyMode] = OpenSSL::SSL::VERIFY_PEER -config[:SSLVerifyCallback] = lambda{|ok,x509_store| - p [ok, x509_store.error_string] - true -} - -DRb.start_service(nil,nil,config) -h = DRbObject.new(nil, there) -while line = gets - p h.hello(line.chomp) -end diff --git a/sample/drb/drbssl_s.rb b/sample/drb/drbssl_s.rb deleted file mode 100644 index 94d02f63cc..0000000000 --- a/sample/drb/drbssl_s.rb +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env ruby - -require 'drb' -require 'drb/ssl' - -here = ARGV.shift || "drbssl://localhost:3456" - -class HelloWorld - include DRbUndumped - - def hello(name) - "Hello, #{name}." - end -end - -config = Hash.new -config[:verbose] = true -begin - data = open("sample.key"){|io| io.read } - config[:SSLPrivateKey] = OpenSSL::PKey::RSA.new(data) - data = open("sample.crt"){|io| io.read } - config[:SSLCertificate] = OpenSSL::X509::Certificate.new(data) -rescue - $stderr.puts "Switching to use self-signed certificate" - config[:SSLCertName] = - [ ["C","JP"], ["O","Foo.DRuby.Org"], ["CN", "Sample"] ] -end - -DRb.start_service(here, HelloWorld.new, config) -puts DRb.uri -$stdin.gets -DRb.stop_service diff --git a/sample/drb/extserv_test.rb b/sample/drb/extserv_test.rb deleted file mode 100644 index 83d871a6a2..0000000000 --- a/sample/drb/extserv_test.rb +++ /dev/null @@ -1,80 +0,0 @@ -=begin - dRuby sample - Copyright (c) 2000 Masatoshi SEKI - -= How to play - -* Terminal 1 - - % ruby -I. extserv_test.rb server - druby://yourhost:12345 - -* Terminal 2 - - % ruby -I. extserv_test.rb druby://yourhost:12345 - ... - -=end - -require 'drb/drb' - -def ARGV.shift - it = super() - raise "usage:\nserver: #{$0} server [<uri>]\nclient: #{$0} [quit] <uri>" unless it - it -end - -class Foo - include DRbUndumped - - def initialize(str) - @str = str - end - - def hello(it) - "#{it}: #{self}" - end - - def to_s - @str - end -end - -cmd = ARGV.shift -case cmd -when 'itest1', 'itest2' - require 'drb/extserv' - - front = Foo.new(cmd) - server = DRb::DRbServer.new(nil, front) - es = DRb::ExtServ.new(ARGV.shift, ARGV.shift, server) - server.thread.join - -when 'server' - require 'drb/extservm' - - DRb::ExtServManager.command['itest1'] = "ruby -I. #{$0} itest1" - DRb::ExtServManager.command['itest2'] = "ruby -I. #{$0} itest2" - - s = DRb::ExtServManager.new - DRb.start_service(ARGV.shift, s) - puts DRb.uri - DRb.thread.join - - -else - uri = (cmd == 'quit') ? ARGV.shift : cmd - - DRb.start_service - s = DRbObject.new(nil, uri) - t1 = s.service('itest1').front - puts t1 - t2 = s.service('itest2').front - puts t2 - puts t1.hello(t2) - if (cmd == 'quit') - s.service('itest1').stop_service - s.service('itest2').stop_service - end -end - diff --git a/sample/drb/gw_ct.rb b/sample/drb/gw_ct.rb deleted file mode 100644 index 0622784018..0000000000 --- a/sample/drb/gw_ct.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'drb/drb' - -class Foo - include DRbUndumped - - def foo(n) - n + n - end - - def bar(n) - yield(n) + yield(n) - end -end - -DRb.start_service(nil) -puts DRb.uri - -ro = DRbObject.new(nil, ARGV.shift) -ro[:tcp] = Foo.new -gets - -it = ro[:unix] -p [it, it.foo(1)] -gets - -p it.bar('2') {|n| n * 3} -gets - - diff --git a/sample/drb/gw_cu.rb b/sample/drb/gw_cu.rb deleted file mode 100644 index 0e5ed36b8f..0000000000 --- a/sample/drb/gw_cu.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'drb/drb' -require 'drb/unix' - -class Foo - include DRbUndumped - - def foo(n) - n + n - end - - def bar(n) - yield(n) + yield(n) - end -end - -DRb.start_service('drubyunix:', nil) -puts DRb.uri - -ro = DRbObject.new(nil, ARGV.shift) -ro[:unix] = Foo.new -gets - -it = ro[:tcp] -p [it, it.foo(1)] -gets - -p it.bar('2') {|n| n * 3} -gets diff --git a/sample/drb/gw_s.rb b/sample/drb/gw_s.rb deleted file mode 100644 index f91249b3e0..0000000000 --- a/sample/drb/gw_s.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'drb/drb' -require 'drb/unix' -require 'drb/gw' - -DRb.install_id_conv(DRb::GWIdConv.new) -gw = DRb::GW.new -s1 = DRb::DRbServer.new(ARGV.shift, gw) -s2 = DRb::DRbServer.new(ARGV.shift, gw) -gets diff --git a/sample/drb/holderc.rb b/sample/drb/holderc.rb deleted file mode 100644 index 8dd72ebd11..0000000000 --- a/sample/drb/holderc.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'drb/drb' - -begin - there = ARGV.shift || raise -rescue - $stderr.puts("usage: #{$0} <server_uri>") - exit 1 -end - -DRb.start_service() -ro = DRbObject.new(nil, there) - -ary = [] -10.times do - ary.push(ro.gen) -end - -sleep 5 if $DEBUG - -ary.each do |e| - p e.sample([1]) -end diff --git a/sample/drb/holders.rb b/sample/drb/holders.rb deleted file mode 100644 index 20939034cd..0000000000 --- a/sample/drb/holders.rb +++ /dev/null @@ -1,64 +0,0 @@ -=begin -= How to play. - -== with timeridconv: - % ruby -d holders.rb - druby://yourhost:1234 - - % ruby holderc.rb druby://yourhost:1234 - - -== without timeridconv: - % ruby holders.rb - druby://yourhost:1234 - - % ruby holderc.rb druby://yourhost:1234 -=end - - -require 'drb/drb' - -class DRbEx3 - include DRbUndumped - - def initialize(n) - @v = n - end - - def sample(list) - sum = 0 - list.each do |e| - sum += e.to_i - end - @v * sum - end -end - -class DRbEx4 - include DRbUndumped - - def initialize - @curr = 1 - end - - def gen - begin - @curr += 1 - DRbEx3.new(@curr) - ensure - GC.start - end - end -end - -if __FILE__ == $0 - if $DEBUG - require 'drb/timeridconv' - DRb.install_id_conv(DRb::TimerIdConv.new(2)) - end - - DRb.start_service(nil, DRbEx4.new) - puts DRb.uri - puts '[return] to exit' - gets -end diff --git a/sample/drb/http0.rb b/sample/drb/http0.rb deleted file mode 100644 index 7649925282..0000000000 --- a/sample/drb/http0.rb +++ /dev/null @@ -1,77 +0,0 @@ -require 'drb/drb' -require 'net/http' -require 'uri' - -module DRb - module HTTP0 - class StrStream - def initialize(str='') - @buf = str - end - attr_reader :buf - - def read(n) - begin - return @buf[0,n] - ensure - @buf[0,n] = '' - end - end - - def write(s) - @buf.concat s - end - end - - def self.uri_option(uri, config) - return uri, nil - end - - def self.open(uri, config) - unless /^http:/ =~ 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'] - 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) - end - - def recv_reply - @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 - end - end - end - DRbProtocol.add_protocol(HTTP0) -end diff --git a/sample/drb/http0serv.rb b/sample/drb/http0serv.rb deleted file mode 100644 index 100d126b8f..0000000000 --- a/sample/drb/http0serv.rb +++ /dev/null @@ -1,119 +0,0 @@ -require 'webrick' -require 'drb/drb' -require 'drb/http0' -require 'thread' - -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) - end - Server.new(uri, config) - end - - class Callback < WEBrick::HTTPServlet::AbstractServlet - def initialize(config, drb) - @config = config - @drb = drb - @queue = 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;' - end - - def req_body - @req.body - end - - def reply(body) - @queue.push(body) - end - - def close - @queue.push('') - end - end - - class Server - def initialize(uri, config) - @uri = uri - @config = config - @queue = Queue.new - setup_webrick(uri) - end - attr_reader :uri - - def close - @server.shutdown if @server - @server = nil - end - - def push(callback) - @queue.push(callback) - end - - def accept - client = @queue.pop - ServerSide.new(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 - end - end - - class ServerSide - def initialize(callback, config) - @callback = callback - @config = config - @msg = DRbMessage.new(@config) - @req_stream = StrStream.new(@callback.req_body) - end - - def close - @callback.close if @callback - @callback = nil - end - - def alive?; false; end - - def recv_request - 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 - end - end - end -end diff --git a/sample/drb/name.rb b/sample/drb/name.rb deleted file mode 100644 index 461f965c16..0000000000 --- a/sample/drb/name.rb +++ /dev/null @@ -1,118 +0,0 @@ -=begin - distributed Ruby --- NamedObject Sample - Copyright (c) 2000-2001 Masatoshi SEKI -=end - -=begin -How to play. - -* start server - Terminal 1 - | % ruby name.rb druby://yourhost:7640 - | druby://yourhost:7640 - | [return] to exit - -* start client - Terminal 2 - | % ruby namec.rb druby://yourhost:7640 - | #<DRb::DRbObject:0x40164174 @uri="druby://yourhost:7640", @ref="seq"> - | #<DRb::DRbObject:0x40163c9c @uri="druby://yourhost:7640", @ref="mutex"> - | 1 - | 2 - | [return] to continue - -* restart server - Terminal 1 - type [return] - | % ruby name.rb druby://yourhost:7640 - | druby://yourhost:7640 - | [return] to exit - -* continue client - Terminal 2 - type [return] - | 1 - | 2 -=end - -require 'thread.rb' -require 'drb/drb' - -module DRbNamedObject - DRbNAMEDICT = {} - attr_reader(:drb_name) - - def drb_name=(name) - @drb_name = name - Thread.exclusive do - raise(IndexError, name) if DRbNAMEDICT[name] - DRbNAMEDICT[name] = self - end - end -end - -class DRbNamedIdConv < DRb::DRbIdConv - def initialize - @dict = DRbNamedObject::DRbNAMEDICT - end - - def to_obj(ref) - @dict.fetch(ref) do super end - end - - def to_id(obj) - if obj.kind_of? DRbNamedObject - return obj.drb_name - else - return super - end - end -end - -class Seq - include DRbUndumped - include DRbNamedObject - - def initialize(v, name) - @counter = v - @mutex = Mutex.new - self.drb_name = name - end - - def next_value - @mutex.synchronize do - @counter += 1 - return @counter - end - end -end - -class Front - def initialize - seq = Seq.new(0, 'seq') - mutex = Mutex.new - mutex.extend(DRbUndumped) - mutex.extend(DRbNamedObject) - mutex.drb_name = 'mutex' - @name = {} - @name['seq'] = seq - @name['mutex'] = mutex - end - - def [](k) - @name[k] - end -end - -if __FILE__ == $0 - uri = ARGV.shift - - name_conv = DRbNamedIdConv.new - - DRb.install_id_conv(name_conv) - DRb.start_service(uri, Front.new) - puts DRb.uri - puts '[return] to exit' - gets -end - diff --git a/sample/drb/namec.rb b/sample/drb/namec.rb deleted file mode 100644 index f6db6f3022..0000000000 --- a/sample/drb/namec.rb +++ /dev/null @@ -1,36 +0,0 @@ -=begin - distributed Ruby --- NamedObject Sample Client - Copyright (c) 2000-2001 Masatoshi SEKI -=end - -require 'drb/drb' - -begin - there = ARGV.shift || raise -rescue - puts "usage: #{$0} <server_uri>" - exit 1 -end - -DRb.start_service() -ro = DRbObject.new(nil, there) - -seq = ro["seq"] -mutex = ro["mutex"] - -p seq -p mutex - -mutex.synchronize do - p seq.next_value - p seq.next_value -end - -puts '[return] to continue' -gets - -mutex.synchronize do - p seq.next_value - p seq.next_value -end - diff --git a/sample/drb/old_tuplespace.rb b/sample/drb/old_tuplespace.rb deleted file mode 100644 index 3e13b92ee1..0000000000 --- a/sample/drb/old_tuplespace.rb +++ /dev/null @@ -1,214 +0,0 @@ -#!/usr/local/bin/ruby -# TupleSpace -# 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 - end - @size = @list.size - end - - attr :size - alias length size - - def match(tuple) - return nil if tuple.size != self.size - @check_idx.each do |i| - unless @list[i] === tuple[i] - return false - end - end - return true - end - end - - def initialize - @que = {} - @waiting = {} - @que.taint # enable tainted comunication - @waiting.taint - self.taint - end - - def wakeup_waiting(tuple) - sz = tuple.length - return nil unless @waiting[sz] - - x = nil - i = -1 - found = false - @waiting[sz] = @waiting[sz].find_all { |x| - if x[0].match(tuple) - begin - x[1].wakeup - rescue ThreadError - end - false - else - true - end - } - end - - def put_waiting(template, thread) - sz = template.length - @waiting[sz] = [] unless @waiting[sz] - @waiting[sz].push([Template.new(template), thread]) - end - private :wakeup_waiting - private :put_waiting - - def get_que(template) - sz = template.length - return nil unless @que[sz] - - template = Template.new(template) - - x = nil - i = -1 - found = false - @que[sz].each_with_index do |x, i| - if template.match(x) - found = true - break - end - end - return nil unless found - - @que[sz].delete_at(i) - - return x - end - - def put_que(tuple) - sz = tuple.length - @que[sz] = [] unless @que[sz] - @que[sz].push tuple - end - private :get_que - private :put_que - - def out(*tuples) - tuples.each do |tuple| - Thread.critical = true - put_que(tuple) - wakeup_waiting(tuple) - Thread.critical = false - end - end - alias put out - alias write out - - 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 - end - ensure - Thread.critical = false - end - end - alias get in - alias take in - - def rd(template, non_block=false) - tuple = self.in(template, non_block) - out(tuple) - tuple - end - alias read rd - - def mv(dest, template, non_block=false) - tuple = self.in(template, non_block) - begin - dest.out(tuple) - rescue - self.out(tuple) - end - end - alias move mv -end - -if __FILE__ == $0 - ts = TupleSpace.new - clients = [] - servers = [] - - 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]) - end - } - end - - def client(ts, n) - Thread.start { - ac = Object.new - tuples = (1..10).collect { |i| - ['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]}" - end - } - end - - def watcher(ts) - Thread.start { - loop do - begin - sleep 1 - p ts.rd(['req', nil, nil], true) - rescue ThreadError - puts "'req' not found." - end - end - } - end - - (0..3).each do |n| - servers.push(server(ts, n)) - end - - (1..6).each do |n| - clients.push(client(ts, n)) - end - - (1..3).each do - watcher(ts) - end - - clients.each do |t| - t.join - end -end - - - diff --git a/sample/drb/rinda_ts.rb b/sample/drb/rinda_ts.rb deleted file mode 100644 index 6f2fae5c0f..0000000000 --- a/sample/drb/rinda_ts.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'drb/drb' -require 'rinda/tuplespace' - -uri = ARGV.shift -DRb.start_service(uri, Rinda::TupleSpace.new) -puts DRb.uri -DRb.thread.join diff --git a/sample/drb/rindac.rb b/sample/drb/rindac.rb deleted file mode 100644 index 72be09deaf..0000000000 --- a/sample/drb/rindac.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'drb/drb' -require 'rinda/rinda' - -uri = ARGV.shift || raise("usage: #{$0} <server_uri>") - -DRb.start_service -ts = Rinda::TupleSpaceProxy.new(DRbObject.new(nil, uri)) - -(1..10).each do |n| - ts.write(['sum', DRb.uri, n]) -end - -(1..10).each do |n| - ans = ts.take(['ans', DRb.uri, n, nil]) - p [ans[2], ans[3]] -end - diff --git a/sample/drb/rindas.rb b/sample/drb/rindas.rb deleted file mode 100644 index 9fd9ada2d1..0000000000 --- a/sample/drb/rindas.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'drb/drb' -require 'rinda/rinda' - -def do_it(v) - puts "do_it(#{v})" - v + v -end - -uri = ARGV.shift || raise("usage: #{$0} <server_uri>") - -DRb.start_service -ts = Rinda::TupleSpaceProxy.new(DRbObject.new(nil, uri)) - -while true - r = ts.take(['sum', nil, nil]) - v = do_it(r[2]) - ts.write(['ans', r[1], r[2], v]) -end diff --git a/sample/drb/ring_echo.rb b/sample/drb/ring_echo.rb deleted file mode 100644 index 0fde11b9e9..0000000000 --- a/sample/drb/ring_echo.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'drb/drb' -require 'drb/eq' -require 'rinda/ring' -require 'thread' - -class RingEcho - include DRbUndumped - def initialize(name) - @name = name - end - - def echo(str) - "#{@name}: #{str}" - end -end - -DRb.start_service - -renewer = Rinda::SimpleRenewer.new - -finder = Rinda::RingFinger.new -ts = finder.lookup_ring_any -ts.read_all([:name, :RingEcho, nil, nil]).each do |tuple| - p tuple[2] - puts tuple[2].echo('Hello, World') rescue nil -end -ts.write([:name, :RingEcho, RingEcho.new(DRb.uri), ''], renewer) - -$stdin.gets - diff --git a/sample/drb/ring_inspect.rb b/sample/drb/ring_inspect.rb deleted file mode 100644 index c096cd7034..0000000000 --- a/sample/drb/ring_inspect.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'rinda/ring' -require 'drb/drb' - -class Inspector - def initialize - end - - def primary - Rinda::RingFinger.primary - end - - def list_place - Rinda::RingFinger.to_a - end - - def list(idx = -1) - if idx < 0 - ts = primary - else - ts = list_place[idx] - raise "RingNotFound" unless ts - end - ts.read_all([:name, nil, nil, nil]) - end -end - -def main - DRb.start_service - r = Inspector.new -end diff --git a/sample/drb/ring_place.rb b/sample/drb/ring_place.rb deleted file mode 100644 index 0ceef7c65a..0000000000 --- a/sample/drb/ring_place.rb +++ /dev/null @@ -1,25 +0,0 @@ -require 'drb/drb' -require 'rinda/ring' -require 'rinda/tuplespace' - -unless $DEBUG - # Run as a daemon... - exit!( 0 ) if fork - Process.setsid - exit!( 0 ) if fork -end - -DRb.start_service(ARGV.shift) - -ts = Rinda::TupleSpace.new -place = Rinda::RingServer.new(ts) - -if $DEBUG - puts DRb.uri - DRb.thread.join -else - STDIN.reopen('/dev/null') - STDOUT.reopen('/dev/null', 'w') - STDERR.reopen('/dev/null', 'w') - DRb.thread.join -end diff --git a/sample/drb/simpletuple.rb b/sample/drb/simpletuple.rb deleted file mode 100644 index 3ae9208c79..0000000000 --- a/sample/drb/simpletuple.rb +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/local/bin/ruby -# SimpleTupleSpace -# 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 = {} - @waiting = {} - @hash.taint - @waiting.taint - self.taint - end - - def out(key, obj) - Thread.critical = true - @hash[key] ||= [] - @waiting[key] ||= [] - @hash[key].push obj - begin - t = @waiting[key].shift - @waiting.delete(key) if @waiting[key].length == 0 - t.wakeup if t - rescue ThreadError - retry - ensure - Thread.critical = false - end - end - - def in(key) - Thread.critical = true - @hash[key] ||= [] - @waiting[key] ||= [] - begin - loop do - if @hash[key].length == 0 - @waiting[key].push Thread.current - Thread.stop - else - return @hash[key].shift - end - end - ensure - @hash.delete(key) if @hash[key].length == 0 - Thread.critical = false - end - end -end - -if __FILE__ == $0 - ts = SimpleTupleSpace.new - clients = [] - servers = [] - - def server(ts) - Thread.start { - loop do - req = ts.in('req') - ac = req[0] - num = req[1] - ts.out(ac, num * num) - end - } - end - - def client(ts, n) - Thread.start { - ac = Object.new - ts.out('req', [ac, n]) - ans = ts.in(ac) - puts "#{n}: #{ans}" - } - end - - 3.times do - servers.push(server(ts)) - end - - (1..6).each do |n| - clients.push(client(ts, n)) - end - - clients.each do |t| - t.join - end -end - - diff --git a/sample/drb/speedc.rb b/sample/drb/speedc.rb deleted file mode 100644 index 14d526d48d..0000000000 --- a/sample/drb/speedc.rb +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/local/bin/ruby - -uri = ARGV.shift || raise("usage: #{$0} URI") -N = (ARGV.shift || 100).to_i - -case uri -when /^tcpromp:/, /^unixromp:/ - require 'romp' - - client = ROMP::Client.new(uri, false) - foo = client.resolve("foo") -when /^druby:/ - require 'drb/drb' - - DRb.start_service - foo = DRbObject.new(nil, uri) -end - -N.times do |n| - foo.foo(n) -end diff --git a/sample/drb/speeds.rb b/sample/drb/speeds.rb deleted file mode 100644 index 5dcd02a56b..0000000000 --- a/sample/drb/speeds.rb +++ /dev/null @@ -1,33 +0,0 @@ -class Foo - attr_reader :i - def initialize - @i = 0 - end - - def foo(i) - @i = i - i + i - end -end - -# server = ROMP::Server.new('tcpromp://localhost:4242', nil, true) - -uri = ARGV.shift || raise("usage: #{$0} URI") -foo = Foo.new - -case uri -when /^tcpromp:/, /^unixromp:/ - require 'romp' - - server = ROMP::Server.new(uri, nil, true) - server.bind(foo, "foo") - -when /^druby:/ - require 'drb/drb' - - DRb.start_service(uri, Foo.new) -end - -puts '[enter] to exit' -gets - 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 893b29feba..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) @@ -12,7 +11,7 @@ names = [] threads = [] res.each do |i| - s = TCPserver.new(i[3], i[1]) + s = TCPServer.new(i[3], i[1]) n = Socket.getnameinfo(s.getsockname, Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV).join(" port ") sockpool.push s names.push n @@ -26,25 +25,25 @@ end ls = mysock # copy to dynamic variable t = Thread.current STDERR.print "socket #{myname} listener started, pid #{$$} thread #{t}\n" - while TRUE + 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/eval.rb b/sample/eval.rb index 90b839e873..ed4b7c3de5 100644 --- a/sample/eval.rb +++ b/sample/eval.rb @@ -1,6 +1,6 @@ line = '' indent = 0 -$stdout.sync = TRUE +$stdout.sync = true print "ruby> " loop do l = gets 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 5818825e25..cbcc18d58b 100644 --- a/sample/exyacc.rb +++ b/sample/exyacc.rb @@ -1,22 +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 -$/ = nil - -while gets() - sbeg = $_.index("\n%%") + 1 - send = $_.rindex("\n%%") + 1 - $_ = $_[sbeg, send-sbeg] - sub!(/.*\n/, "") - gsub!(/'\{'/, "'\001'") - gsub!(/'\}'/, "'\002'") - gsub!(%r{\*/}, "\003\003") - gsub!(%r{/\*[^\003]*\003\003}, '') - while gsub!(/\{[^{}]*\}/, ''); end - gsub!(/'\001'/, "'{'") - gsub!(/'\002'/, "'}'") - while gsub!(/^[ \t]*\n(\s)/, '\1'); end - gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2') - print $_ +ARGF.each(nil) do |source| + sbeg = source.index("\n%%") + 1 + send = source.rindex("\n%%") + 1 + 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 59cc387792..0e5a08de5f 100644 --- a/sample/from.rb +++ b/sample/from.rb @@ -1,98 +1,113 @@ #! /usr/local/bin/ruby -require "parsedate" +require "time" require "kconv" -require "mailread" - -include ParseDate -include Kconv class String - - def kconv(code = Kconv::EUC) - Kconv.kconv(self, code, Kconv::AUTO) - end - def kjust(len) - len += 1 - me = self[0, len].ljust(len) - if me =~ /.$/ and $&.size == 2 - me[-2..-1] = ' ' - me[-2, 2] = ' ' + res = '' + rlen = 0 + self.each_char do |char| + delta = char.bytesize > 1 ? 2 : 1 + break if rlen + delta > len + rlen += delta + res += char end - me.chop! + res += ' ' * (len - rlen) if rlen < len + res end - end -if ARGV[0] == '-w' - wait = TRUE - ARGV.shift +def fromout(date, from, subj) + return 0 if !date + y, m, d = Time.parse(date).to_a.reverse[4, 3] if date + y ||= 0; m ||= 0; d ||= 0 + from ||= "sombody@somewhere" + from.delete!("\r\n") + from = from.kconv(Encoding.default_external).kjust(28) + subj ||= "(nil)" + subj.delete!("\r\n") + subj = subj.kconv(Encoding.default_external).kjust(40) + printf "%02d/%02d/%02d [%s] %s\n", y%100, m, d, from, subj + return 1 end -if ARGV.length == 0 - file = ENV['MAIL'] - user = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME'] -else - file = user = ARGV[0] - ARGV.clear -end +def get_mailfile(user) + file = user + unless user + file = ENV['MAIL'] + user = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME'] + end -if file == nil or !File.exist? file - [ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m| - if File.exist? f = "#{m}/mail/#{user}" - file = f - break + if file == nil or !File.exist?(file) + [ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m| + path = "#{m}/mail/#{user}" + if File.exist?(path) + file = path + break + end end end + file end -$outcount = 0; -def fromout(date, from, subj) - return if !date - y, m, d = parsedate(date) if date - y ||= 0; m ||= 0; d ||= 0 - if from - from.gsub! /\n/, "" - else - from = "sombody@somewhere" - end - if subj - subj.gsub! /\n/, "" - else - subj = "(nil)" +def from_main + if ARGV[0] == '-w' + wait = true + ARGV.shift end - if ENV['LANG'] =~ /sjis/i - lang = Kconv::SJIS - else - lang = Kconv::EUC - end - from = from.kconv(lang).kjust(28) - subj = subj.kconv(lang).kjust(40) - printf "%02d/%02d/%02d [%s] %s\n",y%100,m,d,from,subj - $outcount += 1 -end + file = get_mailfile(ARGV[0]) + + outcount = 0 + if File.exist?(file) + atime = File.atime(file) + mtime = File.mtime(file) + 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 File.exist?(file) - atime = File.atime(file) - mtime = File.mtime(file) - f = open(file, "r") - begin - until f.eof? - mail = Mail.new(f) - fromout mail.header['Date'],mail.header['From'],mail.header['Subject'] + 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 - ensure - f.close File.utime(atime, mtime, file) end + + if outcount == 0 + print "You have no mail.\n" + sleep 2 if wait + elsif wait + system "stty cbreak -echo" + $stdin.getc + system "stty cooked echo" + end end -if $outcount == 0 - print "You have no mail.\n" - sleep 2 if wait -elsif wait - system "stty cbreak -echo" - getc() - system "stty cooked echo" +if __FILE__ == $0 + from_main end + +__END__ + +=begin + += from.rb + +== USAGE + +ruby from.rb [-w] [username_or_filename] + +=end diff --git a/sample/fullpath.rb b/sample/fullpath.rb index 8472e5d8f4..112ca58081 100644 --- a/sample/fullpath.rb +++ b/sample/fullpath.rb @@ -3,7 +3,7 @@ if ARGV[0] =~ /-p/ ARGV.shift - path = ARGV.shift + path = ARGV.shift end if path == nil diff --git a/sample/getopts.test b/sample/getopts.test deleted file mode 100644 index 2866bccea8..0000000000 --- a/sample/getopts.test +++ /dev/null @@ -1,36 +0,0 @@ -#! /usr/local/bin/ruby - -load("parsearg.rb") - -def usage() - printf "Usage:\n" - printf "%s -d [-x x] [-y y] [--geometry geom] [--version] [string ...]\n", $0 -end - -$USAGE = 'usage' -parseArgs(0, "d&(x|y)", "dfg", "x:", "y:", "geometry:800x600", "version") -if ($OPT_d) - if $OPT_version - printf "version 1.0\n" - end - if ($OPT_x) - printf("x = %d\n", $OPT_x.to_i) - end - if ($OPT_y) - printf("y = %d\n", $OPT_y.to_i) - end - if ($OPT_geometry) - printf("geometry = %s\n", $OPT_geometry) - end - if $OPT_f - printf "f = TRUE\n" - end - if $OPT_g - printf "g = TRUE\n" - end -end - -while (ARGV.length != 0) - print "other = ", ARGV[0], "\n" - ARGV.shift -end diff --git a/sample/goodfriday.rb b/sample/goodfriday.rb deleted file mode 100644 index a95cfe819f..0000000000 --- a/sample/goodfriday.rb +++ /dev/null @@ -1,48 +0,0 @@ -#! /usr/bin/env ruby - -# goodfriday.rb: Written by Tadayoshi Funaba 1998, 2000, 2002 -# $Id: goodfriday.rb,v 1.1 1998-03-08 18:44:44+09 tadf Exp $ - -require 'date' - -def easter(y) - g = (y % 19) + 1 - c = (y / 100) + 1 - x = (3 * c / 4) - 12 - z = ((8 * c + 5) / 25) - 5 - d = (5 * y / 4) - x - 10 - e = (11 * g + 20 + z - x) % 30 - e += 1 if e == 25 and g > 11 or e == 24 - n = 44 - e - n += 30 if n < 21 - n = n + 7 - ((d + n) % 7) - if n <= 31 then [y, 3, n] else [y, 4, n - 31] end -end - -es = Date.new(*easter(Time.now.year)) -[[-9*7, 'Septuagesima Sunday'], - [-8*7, 'Sexagesima Sunday'], - [-7*7, 'Quinquagesima Sunday (Shrove Sunday)'], - [-48, 'Shrove Monday'], - [-47, 'Shrove Tuesday'], - [-46, 'Ash Wednesday'], - [-6*7, 'Quadragesima Sunday'], - [-3*7, 'Mothering Sunday'], - [-2*7, 'Passion Sunday'], - [-7, 'Palm Sunday'], - [-3, 'Maunday Thursday'], - [-2, 'Good Friday'], - [-1, 'Easter Eve'], - [0, 'Easter Day'], - [1, 'Easter Monday'], - [7, 'Low Sunday'], - [5*7, 'Rogation Sunday'], - [39, 'Ascension Day (Holy Thursday)'], - [42, 'Sunday after Ascension Day'], - [7*7, 'Pentecost (Whitsunday)'], - [50, 'Whitmonday'], - [8*7, 'Trinity Sunday'], - [60, 'Corpus Christi (Thursday after Trinity)']]. -each do |xs| - puts((es + xs.shift).to_s + ' ' + xs.shift) -end 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 221f7edb16..7458ba0244 100644 --- a/sample/list.rb +++ b/sample/list.rb @@ -22,6 +22,10 @@ class MyElem end class MyList + def initialize + @head = nil + end + def add_to_list(obj) elt = MyElem.new(obj) if @head @@ -75,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/list2.rb b/sample/list2.rb index 914cb8996e..1d71affc1b 100644 --- a/sample/list2.rb +++ b/sample/list2.rb @@ -9,7 +9,7 @@ class Point sprintf("%d@%d", @x, @y) end end - + list1 = [10, 20, Point.new(2, 3), Point.new(4, 5)] list2 = [20, Point.new(4, 5), list1] print("list1:\n", list1.join("\n"), "\n") diff --git a/sample/list3.rb b/sample/list3.rb index 1d756fdff0..110e405cf9 100644 --- a/sample/list3.rb +++ b/sample/list3.rb @@ -7,11 +7,11 @@ class Point self end - def to_s + def inspect sprintf("%d@%d", @x, @y) end end - + list1 = [10, 20, Point.new(2, 3), Point.new(4, 5)] list2 = [20, Point.new(4, 5), list1] print("list1: ", list1.inspect, "\n") 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/mine.rb b/sample/mine.rb index 8fc27e0c6d..77e0204bf6 100644..100755 --- a/sample/mine.rb +++ b/sample/mine.rb @@ -1,4 +1,7 @@ -#! /usr/bin/ruby -Ke +#! /usr/bin/ruby -Ku +# -*- coding: utf-8 -*- + +require 'io/console' class Board def clr @@ -12,19 +15,19 @@ class Board end def put(x, y, col, str) pos(x,y); colorstr(43,str) - pos(0,@hi); print "»Ä¤ê:",@mc,"/",@total," " + pos(0,@hi); print "残り:",@mc,"/",@total," " pos(x,y) end private :clr, :pos, :colorstr, :put - CHR=["¡¦","£±","£²","£³","£´","£µ","£¶","£·","£¸","¡ú","¡ü","@@"] + CHR=["・","1","ï¼’","3","ï¼”","5","ï¼–","ï¼—","8","★","â—","@@"] COL=[46,43,45] # default,opened,over def initialize(h,w,m) - # ¥²¡¼¥àÈפÎÀ¸À®(h:½Ä¡¤w:²£¡¤m:ÇúÃÆ¤Î¿ô) + # ゲーム盤ã®ç”Ÿæˆ(h:縦,w:横,m:çˆ†å¼¾ã®æ•°) @hi=h; @wi=w; @m=m reset end def reset - # ¥²¡¼¥àÈפò(ºÆ)½é´ü²½¤¹¤ë + # ゲーム盤を(å†)åˆæœŸåŒ–ã™ã‚‹ srand() @cx=0; @cy=0; @mc=@m @over=false @@ -46,7 +49,7 @@ class Board pos(@cx,@cy) end def mark - # ¸½ºß¤Î¥«¡¼¥½¥ë°ÌÃ֤˥ޡ¼¥¯¤ò¤Ä¤±¤ë + # ç¾åœ¨ã®ã‚«ãƒ¼ã‚½ãƒ«ä½ç½®ã«ãƒžãƒ¼ã‚¯ã‚’ã¤ã‘ã‚‹ if @state[@wi*@cy+@cx] != nil then return end @state[@wi*@cy+@cx] = "MARK" @mc=@mc-1; @@ -54,8 +57,8 @@ class Board put(@cx, @cy, COL[1], CHR[9]) end def open(x=@cx,y=@cy) - # ¸½ºß¤Î¥«¡¼¥½¥ë°ÌÃÖ¤ò¥ª¡¼¥×¥ó¤Ë¤¹¤ë - # ÇúÃÆ¤¬¤¢¤ì¤Ð¥²¡¼¥à¥ª¡¼¥Ð¡¼ + # ç¾åœ¨ã®ã‚«ãƒ¼ã‚½ãƒ«ä½ç½®ã‚’オープンã«ã™ã‚‹ + # 爆弾ãŒã‚れã°ã‚²ãƒ¼ãƒ オーãƒãƒ¼ if @state[@wi*y+x] =="OPEN" then return 0 end if @state[@wi*y+x] == nil then @total=@total-1 end if @state[@wi*y+x] =="MARK" then @mc=@mc+1 end @@ -75,7 +78,7 @@ class Board pos(@cx,@cy) end def fetch(x,y) - # (x,y)¤Î°ÌÃÖ¤ÎÇúÃÆ¤Î¿ô(0 or 1)¤òÊÖ¤¹ + # (x,y)ã®ä½ç½®ã®çˆ†å¼¾ã®æ•°(0 or 1)を返㙠if x < 0 then 0 elsif x >= @wi then 0 elsif y < 0 then 0 @@ -85,13 +88,13 @@ class Board end end def count(x,y) - # (x,y)¤ËÎÙÀܤ¹¤ëÇúÃÆ¤Î¿ô¤òÊÖ¤¹ + # (x,y)ã«éš£æŽ¥ã™ã‚‹çˆ†å¼¾ã®æ•°ã‚’返㙠fetch(x-1,y-1)+fetch(x,y-1)+fetch(x+1,y-1)+ fetch(x-1,y) + fetch(x+1,y)+ fetch(x-1,y+1)+fetch(x,y+1)+fetch(x+1,y+1) end def over(win) - # ¥²¡¼¥à¤Î½ªÎ» + # ゲームã®çµ‚了 quit unless win pos(@cx,@cy); print CHR[11] @@ -102,8 +105,8 @@ class Board end end def over? - # ¥²¡¼¥à¤Î½ªÎ»¥Á¥§¥Ã¥¯ - # ½ªÎ»½èÍý¤â¸Æ¤Ó½Ð¤¹ + # ゲームã®çµ‚了ãƒã‚§ãƒƒã‚¯ + # 終了処ç†ã‚‚呼ã³å‡ºã™ remain = (@mc+@total == 0) if @over || remain over(remain) @@ -113,8 +116,8 @@ class Board end end def quit - # ¥²¡¼¥à¤ÎÃæÃÇ(¤Þ¤¿¤Ï½ªÎ») - # È×Ì̤òÁ´¤Æ¸«¤»¤ë + # ゲームã®ä¸æ–(ã¾ãŸã¯çµ‚了) + # 盤é¢ã‚’å…¨ã¦è¦‹ã›ã‚‹ @hi.times do|y| pos(0,y) @wi.times do|x| @@ -124,26 +127,26 @@ class Board end end def down - # ¥«¡¼¥½¥ë¤ò²¼¤Ë + # カーソルを下㫠if @cy < @hi-1 then @cy=@cy+1; pos(@cx, @cy) end end def up - # ¥«¡¼¥½¥ë¤ò¾å¤Ë + # カーソルを上㫠if @cy > 0 then @cy=@cy-1; pos(@cx, @cy) end end def left - # ¥«¡¼¥½¥ë¤òº¸¤Ë + # カーソルを左㫠if @cx > 0 then @cx=@cx-1; pos(@cx, @cy) end end def right - # ¥«¡¼¥½¥ë¤ò±¦¤Ë + # カーソルをå³ã« if @cx < @wi-1 then @cx=@cx+1; pos(@cx, @cy) end end end bd=Board.new(10,10,10) -system("stty raw -echo") -begin + +IO.console.raw do loop do case STDIN.getc when ?n # new game @@ -169,7 +172,5 @@ begin bd.reset end end -ensure - system("stty -raw echo") end print "\n" diff --git a/sample/mkproto.rb b/sample/mkproto.rb index 754ca2dff2..e650fe8d47 100644 --- a/sample/mkproto.rb +++ b/sample/mkproto.rb @@ -1,24 +1,24 @@ $/ = nil while line = gets() - if /^((void|VALUE|int|char *\*|ID|struct [\w_]+ *\*|st_table *\*) *)?\n([\w\d_]+)\(.*\)\n\s*((.+;\n)*)\{/ =~ line + if /^((void|VALUE|int|char *\*|ID|struct \w+ *\*|st_table *\*) *)?\n(\w+)\(.*\)\n\s*((.+;\n)*)\{/ =~ line line = $' printf "%s %s(", $2, $3 args = [] for arg in $4.split(/;\n\s*/) arg.gsub!(/ +/, ' ') if arg =~ /,/ - if arg =~ /(([^*]+) *\** *[\w\d_]+),/ - type = $2.strip - args.push $1.strip - arg = $' - else - type = "" - end - while arg.sub!(/(\** *[\w\d_]+)(,|$)/, "") && $~ - 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/mpart.rb b/sample/mpart.rb index a88eba0ef6..eeb895d3de 100644 --- a/sample/mpart.rb +++ b/sample/mpart.rb @@ -2,11 +2,29 @@ # split into multi part # usage: mpart.rb [-nnn] file.. +class MPart < File + def self.new(basename, extname, part, parts) + super(sprintf("%s.%s%02d", basename, extname, part), "w"). + begin_mpart(basename, part, parts) + end + + def begin_mpart(basename, part, parts) + printf("%s part%02d/%02d\n", basename, part, parts) + write("BEGIN--cut here--cut here\n") + self + end + + def close + write("END--cut here--cut here\n") + super + end +end + lines = 1000 if (ARGV[0] =~ /^-(\d+)$/ ) - lines = $1.to_i; - ARGV.shift; + lines = $1.to_i + ARGV.shift end basename = ARGV[0] @@ -14,31 +32,23 @@ extname = "part" part = 1 line = 0 +ofp = nil fline = 0 -for i in ifp = open(basename) - fline = fline + 1 -end -ifp.close +File.foreach(basename) {fline += 1} parts = fline / lines + 1 -for i in ifp = open(basename) +File.foreach(basename) do |i| if line == 0 - ofp = open(sprintf("%s.%s%02d", basename, extname, part), "w") - printf(ofp, "%s part%02d/%02d\n", basename, part, parts) - ofp.write("BEGIN--cut here--cut here\n") + ofp = MPart.new(basename, extname, part, parts) end ofp.write(i) - line = line + 1 - if line >= lines and !ifp.eof? - ofp.write("END--cut here--cut here\n") + line += 1 + if line >= lines ofp.close - part = part + 1 + part += 1 line = 0 end end -ofp.write("END--cut here--cut here\n") ofp.close - -ifp.close diff --git a/sample/mrshtest.rb b/sample/mrshtest.rb deleted file mode 100644 index 8d2dc9936b..0000000000 --- a/sample/mrshtest.rb +++ /dev/null @@ -1,13 +0,0 @@ -include Marshal -a = 25.6; -pt = Struct.new('Point', :x,:y); -x = pt.new(10, 10) -y = pt.new(20, 20) -rt = Struct.new('Rectangle', :origin,:corner); -z = rt.new(x, y) -c = Object.new -s = [a, x, z, c, c, "fff"]; -p s -d = dump(s); -p d -p load(d) 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 8bb09e15ad..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 gets() - for word in split(/\W+/) +while line = gets() + 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 53885c0ba7..0000000000 --- a/sample/occur2.rb +++ /dev/null @@ -1,16 +0,0 @@ -# word occurrence listing -# usege: ruby occur2.rb file.. -freq = {} -while gets() - for word in split(/\W+/) - begin - freq[word] += 1 - rescue NameError - freq[word] = 1 - end - 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 386eef5f24..8b005bbb84 100644 --- a/sample/openssl/c_rehash.rb +++ b/sample/openssl/c_rehash.rb @@ -1,7 +1,6 @@ #!/usr/bin/env ruby require 'openssl' -require '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 @@ -157,11 +156,11 @@ private end def hash_name(name) - sprintf("%x", name.hash) + sprintf("%08x", name.hash) end def fingerprint(der) - 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/cert_store_view.rb b/sample/openssl/cert_store_view.rb deleted file mode 100644 index 26c4d527f7..0000000000 --- a/sample/openssl/cert_store_view.rb +++ /dev/null @@ -1,911 +0,0 @@ -#!/usr/bin/env ruby - -require 'fox' -require 'openssl' -require 'time' -require 'certstore' -require 'getopts' - -include Fox - -module CertDumpSupport - def cert_label(cert) - subject_alt_name = - cert.extensions.find { |ext| ext.oid == 'subjectAltName' } - if subject_alt_name - subject_alt_name.value.split(/\s*,\s/).each do |alt_name_pair| - alt_tag, alt_name = alt_name_pair.split(/:/) - return alt_name - end - end - name_label(cert.subject) - end - - def name_label(name) - ary = name.to_a - if (cn = ary.find { |rdn| rdn[0] == 'CN' }) - return cn[1] - end - if ary.last[0] == 'OU' - return ary.last[1] - end - name.to_s - end - - def name_text(name) - name.to_a.collect { |tag, value| - "#{tag} = #{value}" - }.reverse.join("\n") - end - - def bn_label(bn) - ("0" << sprintf("%X", bn)).scan(/../).join(" ") - end -end - -class CertDump - include CertDumpSupport - - def initialize(cert) - @cert = cert - end - - def get_dump(tag) - case tag - when 'Version' - version - when 'Serial' - serial - when 'Signature Algorithm' - signature_algorithm - when 'Issuer' - issuer - when 'Validity' - validity - when 'Not before' - not_before - when 'Not after' - not_after - when 'Subject' - subject - when 'Public key' - public_key - else - ext(tag) - end - end - - def get_dump_line(tag) - case tag - when 'Version' - version_line - when 'Serial' - serial_line - when 'Signature Algorithm' - signature_algorithm_line - when 'Subject' - subject_line - when 'Issuer' - issuer_line - when 'Validity' - validity_line - when 'Not before' - not_before_line - when 'Not after' - not_after_line - when 'Public key' - public_key_line - else - ext_line(tag) - end - end - -private - - def version - "Version: #{@cert.version + 1}" - end - - def version_line - version - end - - def serial - bn_label(@cert.serial) - end - - def serial_line - serial - end - - def signature_algorithm - @cert.signature_algorithm - end - - def signature_algorithm_line - signature_algorithm - end - - def subject - name_text(@cert.subject) - end - - def subject_line - @cert.subject.to_s - end - - def issuer - name_text(@cert.issuer) - end - - def issuer_line - @cert.issuer.to_s - end - - def validity - <<EOS -Not before: #{not_before} -Not after: #{not_after} -EOS - end - - def validity_line - "from #{@cert.not_before.iso8601} to #{@cert.not_after.iso8601}" - end - - def not_before - @cert.not_before.to_s - end - - def not_before_line - not_before - end - - def not_after - @cert.not_after.to_s - end - - def not_after_line - not_after - end - - def public_key - @cert.public_key.to_text - end - - def public_key_line - "#{@cert.public_key.class} -- " << public_key.scan(/\A[^\n]*/)[0] << '...' - end - - def ext(tag) - @cert.extensions.each do |ext| - if ext.oid == tag - return ext_detail(tag, ext.value) - end - end - "(unknown)" - end - - def ext_line(tag) - ext(tag).tr("\r\n", '') - end - - def ext_detail(tag, value) - value - end -end - -class CrlDump - include CertDumpSupport - - def initialize(crl) - @crl = crl - end - - def get_dump(tag) - case tag - when 'Version' - version - when 'Signature Algorithm' - signature_algorithm - when 'Issuer' - issuer - when 'Last update' - last_update - when 'Next update' - next_update - else - ext(tag) - end - end - - def get_dump_line(tag) - case tag - when 'Version' - version_line - when 'Signature Algorithm' - signature_algorithm_line - when 'Issuer' - issuer_line - when 'Last update' - last_update_line - when 'Next update' - next_update_line - else - ext_line(tag) - end - end - -private - - def version - "Version: #{@crl.version + 1}" - end - - def version_line - version - end - - def signature_algorithm - @crl.signature_algorithm - end - - def signature_algorithm_line - signature_algorithm - end - - def issuer - name_text(@crl.issuer) - end - - def issuer_line - @crl.issuer.to_s - end - - def last_update - @crl.last_update.to_s - end - - def last_update_line - last_update - end - - def next_update - @crl.next_update.to_s - end - - def next_update_line - next_update - end - - def ext(tag) - @crl.extensions.each do |ext| - if ext.oid == tag - return ext_detail(tag, ext.value) - end - end - "(unknown)" - end - - def ext_line(tag) - ext(tag).tr("\r\n", '') - end - - def ext_detail(tag, value) - value - end -end - -class RevokedDump - include CertDumpSupport - - def initialize(revoked) - @revoked = revoked - end - - def get_dump(tag) - case tag - when 'Serial' - serial - when 'Time' - time - else - ext(tag) - end - end - - def get_dump_line(tag) - case tag - when 'Serial' - serial_line - when 'Time' - time_line - else - ext_line(tag) - end - end - -private - - def serial - bn_label(@revoked.serial) - end - - def serial_line - serial - end - - def time - @revoked.time.to_s - end - - def time_line - time - end - - def ext(tag) - @revoked.extensions.each do |ext| - if ext.oid == tag - return ext_detail(tag, ext.value) - end - end - "(unknown)" - end - - def ext_line(tag) - ext(tag).tr("\r\n", '') - end - - def ext_detail(tag, value) - value - end -end - -class RequestDump - include CertDumpSupport - - def initialize(req) - @req = req - end - - def get_dump(tag) - case tag - when 'Version' - version - when 'Signature Algorithm' - signature_algorithm - when 'Subject' - subject - when 'Public key' - public_key - else - attributes(tag) - end - end - - def get_dump_line(tag) - case tag - when 'Version' - version_line - when 'Signature Algorithm' - signature_algorithm_line - when 'Subject' - subject_line - when 'Public key' - public_key_line - else - attributes_line(tag) - end - end - -private - - def version - "Version: #{@req.version + 1}" - end - - def version_line - version - end - - def signature_algorithm - @req.signature_algorithm - end - - def signature_algorithm_line - signature_algorithm - end - - def subject - name_text(@req.subject) - end - - def subject_line - @req.subject.to_s - end - - def public_key - @req.public_key.to_text - end - - def public_key_line - "#{@req.public_key.class} -- " << public_key.scan(/\A[^\n]*/)[0] << '...' - end - - def attributes(tag) - "(unknown)" - end - - def attributes_line(tag) - attributes(tag).tr("\r\n", '') - end -end - -class CertStoreView < FXMainWindow - class CertTree - include CertDumpSupport - - def initialize(observer, tree) - @observer = observer - @tree = tree - @tree.connect(SEL_COMMAND) do |sender, sel, item| - if item.data - @observer.getApp().beginWaitCursor do - @observer.show_item(item.data) - end - else - @observer.show_item(nil) - end - end - end - - def show(cert_store) - @tree.clearItems - @self_signed_ca_node = add_item_last(nil, "Trusted root CA") - @other_ca_node = add_item_last(nil, "Intermediate CA") - @ee_node = add_item_last(nil, "Personal") - @crl_node = add_item_last(nil, "CRL") - @request_node = add_item_last(nil, "Request") - @verify_path_node = add_item_last(nil, "Certification path") - show_certs(cert_store) - end - - def show_certs(cert_store) - remove_items(@self_signed_ca_node) - remove_items(@other_ca_node) - remove_items(@ee_node) - remove_items(@crl_node) - remove_items(@request_node) - import_certs(cert_store) - end - - def show_request(req) - node = add_item_last(@request_node, name_label(req.subject), req) - @tree.selectItem(node) - @observer.show_item(req) - end - - def show_verify_path(verify_path) - add_verify_path(verify_path) - end - - private - - def open_node(node) - node.expanded = node.opened = true - end - - def close_node(node) - node.expanded = node.opened = false - end - - def import_certs(cert_store) - cert_store.self_signed_ca.each do |cert| - add_item_last(@self_signed_ca_node, cert_label(cert), cert) - end - cert_store.other_ca.each do |cert| - add_item_last(@other_ca_node, cert_label(cert), cert) - end - cert_store.ee.each do |cert| - add_item_last(@ee_node, cert_label(cert), cert) - end - cert_store.crl.each do |crl| - node = add_item_last(@crl_node, name_label(crl.issuer), crl) - close_node(node) - crl.revoked.each do |revoked| - add_item_last(node, bn_label(revoked.serial), revoked) - end - end - cert_store.request.each do |req| - add_item_last(@requestnode, name_label(req.subject), req) - end - end - - def add_verify_path(verify_path) - node = @verify_path_node - last_cert = nil - verify_path.reverse_each do |ok, cert, crl_check, error_string| - warn = [] - if @observer.cert_store.is_ca?(cert) - warn << 'NO ARL' unless crl_check - else - warn << 'NO CRL' unless crl_check - end - warn_str = '(' << warn.join(", ") << ')' - warn_mark = warn.empty? ? '' : '!' - label = if ok - "OK#{warn_mark}..." + cert_label(cert) - else - "NG(#{error_string})..." + cert_label(cert) - end - label << warn_str unless warn.empty? - node = add_item_last(node, label, cert) - node.expanded = true - last_cert = cert - end - if last_cert - @tree.selectItem(node) - @observer.show_item(last_cert) - end - end - - def add_item_last(parent, label, obj = nil) - node = @tree.addItemLast(parent, FXTreeItem.new(label)) - node.data = obj if obj - open_node(node) - node - end - - def remove_items(node) - while node.getNumChildren > 0 - @tree.removeItem(node.getFirst) - end - end - end - - class CertInfo - def initialize(observer, table) - @observer = observer - @table = table - @table.leadingRows = 0 - @table.leadingCols = 0 - @table.trailingRows = 0 - @table.trailingCols = 0 - @table.showVertGrid(false) - @table.showHorzGrid(false) - @table.setTableSize(1, 2) - @table.setColumnWidth(0, 125) - @table.setColumnWidth(1, 350) - end - - def show(item) - @observer.show_detail(nil, nil) - if item.nil? - set_column_size(1) - return - end - case item - when OpenSSL::X509::Certificate - show_cert(item) - when OpenSSL::X509::CRL - show_crl(item) - when OpenSSL::X509::Revoked - show_revoked(item) - when OpenSSL::X509::Request - show_request(item) - else - raise NotImplementedError.new("Unknown item type #{item.class}.") - end - end - - private - - def show_cert(cert) - wrap = CertDump.new(cert) - items = [] - items << ['Version', wrap.get_dump_line('Version')] - items << ['Signature Algorithm', wrap.get_dump_line('Signature Algorithm')] - items << ['Issuer', wrap.get_dump_line('Issuer')] - items << ['Serial', wrap.get_dump_line('Serial')] - #items << ['Not before', wrap.get_dump_line('Not before')] - #items << ['Not after', wrap.get_dump_line('Not after')] - items << ['Subject', wrap.get_dump_line('Subject')] - items << ['Public key', wrap.get_dump_line('Public key')] - items << ['Validity', wrap.get_dump_line('Validity')] - (cert.extensions.sort { |a, b| a.oid <=> b.oid }).each do |ext| - items << [ext.oid, wrap.get_dump_line(ext.oid)] - end - show_items(cert, items) - end - - def show_crl(crl) - wrap = CrlDump.new(crl) - items = [] - items << ['Version', wrap.get_dump_line('Version')] - items << ['Signature Algorithm', wrap.get_dump_line('Signature Algorithm')] - items << ['Issuer', wrap.get_dump_line('Issuer')] - items << ['Last update', wrap.get_dump_line('Last update')] - items << ['Next update', wrap.get_dump_line('Next update')] - crl.extensions.each do |ext| - items << [ext.oid, wrap.get_dump_line(ext.oid)] - end - show_items(crl, items) - end - - def show_revoked(revoked) - wrap = RevokedDump.new(revoked) - items = [] - items << ['Serial', wrap.get_dump_line('Serial')] - items << ['Time', wrap.get_dump_line('Time')] - revoked.extensions.each do |ext| - items << [ext.oid, wrap.get_dump_line(ext.oid)] - end - show_items(revoked, items) - end - - def show_request(req) - wrap = RequestDump.new(req) - items = [] - items << ['Version', wrap.get_dump_line('Version')] - items << ['Signature Algorithm', wrap.get_dump_line('Signature Algorithm')] - items << ['Subject', wrap.get_dump_line('Subject')] - items << ['Public key', wrap.get_dump_line('Public key')] - req.attributes.each do |attr| - items << [attr.attr, wrap.get_dump_line(attr.oid)] - end - show_items(req, items) - end - - def show_items(obj, items) - set_column_size(items.size) - items.each_with_index do |ele, idx| - tag, value = ele - @table.setItemText(idx, 0, tag) - @table.getItem(idx, 0).data = tag - @table.setItemText(idx, 1, value.to_s) - @table.getItem(idx, 1).data = tag - end - @table.connect(SEL_COMMAND) do |sender, sel, loc| - item = @table.getItem(loc.row, loc.col) - @observer.show_detail(obj, item.data) - end - justify_table - end - - def set_column_size(size) - col0_width = @table.getColumnWidth(0) - col1_width = @table.getColumnWidth(1) - @table.setTableSize(size, 2) - @table.setColumnWidth(0, col0_width) - @table.setColumnWidth(1, col1_width) - end - - def justify_table - for col in 0..@table.numCols-1 - for row in 0..@table.numRows-1 - @table.getItem(row, col).justify = FXTableItem::LEFT - end - end - end - end - - class CertDetail - def initialize(observer, detail) - @observer = observer - @detail = detail - end - - def show(item, tag) - if item.nil? - @detail.text = '' - return - end - case item - when OpenSSL::X509::Certificate - show_cert(item, tag) - when OpenSSL::X509::CRL - show_crl(item, tag) - when OpenSSL::X509::Revoked - show_revoked(item, tag) - when OpenSSL::X509::Request - show_request(item, tag) - else - raise NotImplementedError.new("Unknown item type #{item.class}.") - end - end - - private - - def show_cert(cert, tag) - wrap = CertDump.new(cert) - @detail.text = wrap.get_dump(tag) - end - - def show_crl(crl, tag) - wrap = CrlDump.new(crl) - @detail.text = wrap.get_dump(tag) - end - - def show_revoked(revoked, tag) - wrap = RevokedDump.new(revoked) - @detail.text = wrap.get_dump(tag) - end - - def show_request(request, tag) - wrap = RequestDump.new(request) - @detail.text = wrap.get_dump(tag) - end - end - - attr_reader :cert_store - - def initialize(app, cert_store) - @cert_store = cert_store - @verify_filter = 0 - @verify_filename = nil - full_width = 800 - full_height = 500 - horz_pos = 300 - - super(app, "Certificate store", nil, nil, DECOR_ALL, 0, 0, full_width, - full_height) - - FXTooltip.new(self.getApp()) - - menubar = FXMenubar.new(self, LAYOUT_SIDE_TOP|LAYOUT_FILL_X) - file_menu = FXMenuPane.new(self) - FXMenuTitle.new(menubar, "&File", nil, file_menu) - file_open_menu = FXMenuPane.new(self) - FXMenuCommand.new(file_open_menu, "&Directory\tCtl-O").connect(SEL_COMMAND, - method(:on_cmd_file_open_dir)) - FXMenuCascade.new(file_menu, "&Open\tCtl-O", nil, file_open_menu) - FXMenuCommand.new(file_menu, "&Quit\tCtl-Q", nil, getApp(), FXApp::ID_QUIT) - - tool_menu = FXMenuPane.new(self) - FXMenuTitle.new(menubar, "&Tool", nil, tool_menu) - FXMenuCommand.new(tool_menu, "&Verify\tCtl-N").connect(SEL_COMMAND, - method(:on_cmd_tool_verify)) - FXMenuCommand.new(tool_menu, "&Show Request\tCtl-R").connect(SEL_COMMAND, - method(:on_cmd_tool_request)) - - base_frame = FXHorizontalFrame.new(self, LAYOUT_FILL_X | LAYOUT_FILL_Y) - splitter_horz = FXSplitter.new(base_frame, LAYOUT_SIDE_TOP | LAYOUT_FILL_X | - LAYOUT_FILL_Y | SPLITTER_TRACKING | SPLITTER_HORIZONTAL) - - # Cert tree - cert_tree_frame = FXHorizontalFrame.new(splitter_horz, LAYOUT_FILL_X | - LAYOUT_FILL_Y | FRAME_SUNKEN | FRAME_THICK) - cert_tree_frame.setWidth(horz_pos) - cert_tree = FXTreeList.new(cert_tree_frame, 0, nil, 0, - TREELIST_BROWSESELECT | TREELIST_SHOWS_LINES | TREELIST_SHOWS_BOXES | - TREELIST_ROOT_BOXES | LAYOUT_FILL_X | LAYOUT_FILL_Y) - @cert_tree = CertTree.new(self, cert_tree) - - # Cert info - splitter_vert = FXSplitter.new(splitter_horz, LAYOUT_SIDE_TOP | - LAYOUT_FILL_X | LAYOUT_FILL_Y | SPLITTER_TRACKING | SPLITTER_VERTICAL | - SPLITTER_REVERSED) - cert_list_base = FXVerticalFrame.new(splitter_vert, LAYOUT_FILL_X | - LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0) - cert_list_frame = FXHorizontalFrame.new(cert_list_base, FRAME_SUNKEN | - FRAME_THICK | LAYOUT_FILL_X | LAYOUT_FILL_Y) - cert_info = FXTable.new(cert_list_frame, 2, 10, nil, 0, FRAME_SUNKEN | - TABLE_COL_SIZABLE | LAYOUT_FILL_X | LAYOUT_FILL_Y, 0, 0, 0, 0, 2, 2, 2, 2) - @cert_info = CertInfo.new(self, cert_info) - - cert_detail_base = FXVerticalFrame.new(splitter_vert, LAYOUT_FILL_X | - LAYOUT_FILL_Y, 0,0,0,0, 0,0,0,0) - cert_detail_frame = FXHorizontalFrame.new(cert_detail_base, FRAME_SUNKEN | - FRAME_THICK | LAYOUT_FILL_X | LAYOUT_FILL_Y) - cert_detail = FXText.new(cert_detail_frame, nil, 0, TEXT_READONLY | - LAYOUT_FILL_X | LAYOUT_FILL_Y) - @cert_detail = CertDetail.new(self, cert_detail) - - show_init - end - - def create - super - show(PLACEMENT_SCREEN) - end - - def show_init - @cert_tree.show(@cert_store) - show_item(nil) - end - - def show_certs - @cert_tree.show_certs(@cert_store) - end - - def show_request(req) - @cert_tree.show_request(req) - end - - def show_verify_path(verify_path) - @cert_tree.show_verify_path(verify_path) - end - - def show_item(item) - @cert_info.show(item) if @cert_info - end - - def show_detail(item, tag) - @cert_detail.show(item, tag) if @cert_detail - end - - def verify(certfile) - path = verify_certfile(certfile) - show_certs # CRL could be change. - show_verify_path(path) - end - -private - - def on_cmd_file_open_dir(sender, sel, ptr) - dir = FXFileDialog.getOpenDirectory(self, "Open certificate directory", ".") - unless dir.empty? - begin - @cert_store = CertStore.new(dir) - rescue - show_error($!) - end - show_init - end - 1 - end - - def on_cmd_tool_verify(sender, sel, ptr) - dialog = FXFileDialog.new(self, "Verify certificate") - dialog.filename = '' - dialog.patternList = ["All Files (*)", "PEM formatted certificate (*.pem)"] - dialog.currentPattern = @verify_filter - if dialog.execute != 0 - @verify_filename = dialog.filename - verify(@verify_filename) - end - @verify_filter = dialog.currentPattern - 1 - end - - def on_cmd_tool_request(sender, sel, ptr) - dialog = FXFileDialog.new(self, "Show request") - dialog.filename = '' - dialog.patternList = ["All Files (*)", "PEM formatted certificate (*.pem)"] - if dialog.execute != 0 - req = @cert_store.generate_cert(dialog.filename) - show_request(req) - end - 1 - end - - def verify_certfile(filename) - begin - cert = @cert_store.generate_cert(filename) - result = @cert_store.verify(cert) - @cert_store.scan_certs - result - rescue - show_error($!) - [] - end - end - - def show_error(e) - msg = e.inspect + "\n" + e.backtrace.join("\n") - FXMessageBox.error(self, MBOX_OK, "Error", msg) - end -end - -getopts nil, "cert:" - -certs_dir = ARGV.shift or raise "#{$0} cert_dir" -certfile = $OPT_cert -app = FXApp.new("CertStore", "FoxTest") -cert_store = CertStore.new(certs_dir) -w = CertStoreView.new(app, cert_store) -app.create -if certfile - w.verify(certfile) -end -app.run diff --git a/sample/openssl/certstore.rb b/sample/openssl/certstore.rb index bbc637f668..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 @@ -48,7 +45,7 @@ class CertStore case guess_cert_type(cert) when CERT_TYPE_SELF_SIGNED true - when CERT_TYPE_OTHER + when CERT_TYPE_OTHER true else false @@ -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 844b6eea4e..a33dc3e95c 100644 --- a/sample/openssl/cipher.rb +++ b/sample/openssl/cipher.rb @@ -1,29 +1,54 @@ #!/usr/bin/env ruby require 'openssl' -text = "abcdefghijklmnopqrstuvwxyz" -key = "key" -alg = "DES-EDE3-CBC" -#alg = "AES-128-CBC" +def crypt_by_password(alg, pass, salt, text) + puts "--Setup--" + puts %(cipher alg: "#{alg}") + puts %(plain text: "#{text}") + puts %(password: "#{pass}") + puts %(salt: "#{salt}") + puts -puts "--Setup--" -puts %(clear text: "#{text}") -puts %(symmetric key: "#{key}") -puts %(cipher alg: "#{alg}") -puts + puts "--Encrypting--" + enc = OpenSSL::Cipher.new(alg) + enc.encrypt + enc.pkcs5_keyivgen(pass, salt) + cipher = enc.update(text) + cipher << enc.final + puts %(encrypted text: #{cipher.inspect}) + puts -puts "--Encrypting--" -des = OpenSSL::Cipher::Cipher.new(alg) -des.encrypt(key) #, "iv12345678") -cipher = des.update(text) -cipher << des.final -puts %(encrypted text: #{cipher.inspect}) -puts + puts "--Decrypting--" + dec = OpenSSL::Cipher.new(alg) + dec.decrypt + dec.pkcs5_keyivgen(pass, salt) + plain = dec.update(cipher) + plain << dec.final + puts %(decrypted text: "#{plain}") + puts +end + +def ciphers + ciphers = OpenSSL::Cipher.ciphers.sort + ciphers.each{|i| + if i.upcase != i && ciphers.include?(i.upcase) + ciphers.delete(i) + end + } + return ciphers +end -puts "--Decrypting--" -des = OpenSSL::Cipher::Cipher.new(alg) -des.decrypt(key) #, "iv12345678") -out = des.update(cipher) -out << des.final -puts %(decrypted text: "#{out}") +puts "Supported ciphers in #{OpenSSL::OPENSSL_VERSION}:" +ciphers.each_with_index{|name, i| + printf("%-15s", name) + puts if (i + 1) % 5 == 0 +} puts +puts + +alg = ARGV.shift || ciphers.first +pass = "secret password" +salt = "8 octets" # or nil +text = "abcdefghijklmnopqrstuvwxyz" + +crypt_by_password(alg, pass, salt, text) 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 29b356a7ad..3fbadf3361 100644 --- a/sample/openssl/echo_cli.rb +++ b/sample/openssl/echo_cli.rb @@ -2,20 +2,20 @@ require 'socket' require 'openssl' -require 'getopts' +require 'optparse' -getopts nil, "p:2000", "c:", "k:", "C:" +options = ARGV.getopts("p:c:k:C:") host = ARGV[0] || "localhost" -port = $OPT_p -cert_file = $OPT_c -key_file = $OPT_k -ca_path = $OPT_C +port = options["p"] || "2000" +cert_file = options["c"] +key_file = options["k"] +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 @@ -27,11 +27,18 @@ end s = TCPSocket.new(host, port) ssl = OpenSSL::SSL::SSLSocket.new(s, ctx) ssl.connect # start SSL session +p ssl.peer_cert +errors = Hash.new +OpenSSL::X509.constants.grep(/^V_(ERR_|OK)/).each do |name| + errors[OpenSSL::X509.const_get(name)] = name +end +p errors[ssl.verify_result] + ssl.sync_close = true # if true the underlying socket will be # closed in SSLSocket#close. (default: false) while line = $stdin.gets ssl.write line - print ssl.gets + puts ssl.gets.inspect end ssl.close diff --git a/sample/openssl/echo_svr.rb b/sample/openssl/echo_svr.rb index be8e10fa26..f20fb52bf5 100644 --- a/sample/openssl/echo_svr.rb +++ b/sample/openssl/echo_svr.rb @@ -2,20 +2,20 @@ require 'socket' require 'openssl' -require 'getopts' +require 'optparse' -getopts nil, "p:2000", "c:", "k:", "C:" +options = ARGV.getopts("p:c:k:C:") -port = $OPT_p -cert_file = $OPT_c -key_file = $OPT_k -ca_path = $OPT_C +port = options["p"] || "2000" +cert_file = options["c"] +key_file = options["k"] +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() @@ -55,8 +55,11 @@ tcps = TCPServer.new(port) ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx) loop do ns = ssls.accept + puts "connected from #{ns.peeraddr}" while line = ns.gets + puts line.inspect ns.write line end + puts "connection closed" ns.close end diff --git a/sample/openssl/gen_csr.rb b/sample/openssl/gen_csr.rb index 7c7f559995..34b23fec1c 100644 --- a/sample/openssl/gen_csr.rb +++ b/sample/openssl/gen_csr.rb @@ -1,33 +1,31 @@ #!/usr/bin/env ruby -require 'getopts' +require 'optparse' require 'openssl' -include OpenSSL - def usage myname = File::basename($0) $stderr.puts <<EOS -Usage: #{myname} name [keypair_file] +Usage: #{myname} [--key keypair_file] name name ... ex. /C=JP/O=RRR/OU=CA/CN=NaHi/emailAddress=nahi@example.org EOS exit end -getopts nil, "key:", "csrout:", "keyout:" -keypair_file = $OPT_key -csrout = $OPT_csrout || "csr.pem" -keyout = $OPT_keyout || "keypair.pem" +options = ARGV.getopts(nil, "key:", "csrout:", "keyout:") +keypair_file = options["key"] +csrout = options["csrout"] || "csr.pem" +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,13 +35,15 @@ 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| f << req.to_pem end +puts req.to_text +puts req.to_pem diff --git a/sample/openssl/smime_read.rb b/sample/openssl/smime_read.rb index 0f08f54f7e..b617c6e3a5 100644 --- a/sample/openssl/smime_read.rb +++ b/sample/openssl/smime_read.rb @@ -1,23 +1,22 @@ -require 'getopts' +require 'optparse' require 'openssl' -include OpenSSL -getopts nil, "c:", "k:", "C:" +options = ARGV.getopts("c:k:C:") -cert_file = $OPT_c -key_file = $OPT_k -ca_path = $OPT_C +cert_file = options["c"] +key_file = options["k"] +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 ce32cd8146..e1254d8748 100644 --- a/sample/openssl/smime_write.rb +++ b/sample/openssl/smime_write.rb @@ -1,23 +1,22 @@ require 'openssl' -require 'getopts' -include OpenSSL +require 'optparse' -getopts nil, "c:", "k:", "r:" +options = ARGV.getopts("c:k:r:") -cert_file = $OPT_c -key_file = $OPT_k -rcpt_file = $OPT_r +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/openssl/wget.rb b/sample/openssl/wget.rb index 0362ab980d..ee637204db 100644 --- a/sample/openssl/wget.rb +++ b/sample/openssl/wget.rb @@ -1,11 +1,11 @@ #!/usr/bin/env ruby require 'net/https' -require 'getopts' +require 'optparse' -getopts nil, 'C:' +options = ARGV.getopts('C:') -ca_path = $OPT_C +cert_store = options["C"] uri = URI.parse(ARGV[0]) if proxy = ENV['HTTP_PROXY'] @@ -18,11 +18,12 @@ h = Net::HTTP.new(uri.host, uri.port, prx_host, prx_port) h.set_debug_output($stderr) if $DEBUG if uri.scheme == "https" h.use_ssl = true - if ca_path - h.verify_mode = OpenSSL::SSL::VERIFY_PEER - h.ca_path = ca_path - else - $stderr.puts "!!! WARNING: PEER CERTIFICATE WON'T BE VERIFIED !!!" + if cert_store + if File.directory?(cert_store) + h.ca_path = cert_store + else + h.ca_file = cert_store + end end end diff --git a/sample/optparse/opttest.rb b/sample/optparse/opttest.rb index 683c450d57..b2013c5253 100644..100755 --- a/sample/optparse/opttest.rb +++ b/sample/optparse/opttest.rb @@ -13,59 +13,99 @@ ARGV.options do |opts| opts.banner << " argv..." - # separater + # separator opts.on_tail 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") {|@library|} + "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 ||= ''} + "edit ARGV files in place", # multiline description + "(make backup if EXTENSION supplied)") do + |inplace| + @inplace = inplace || '' + end - opts.on("-N=[NUM]", Integer) {|@number|} + opts.on("-N=[NUM]", Integer) do + |num| + @number = num + end # additional class - opts.on("-t", "--[no-]time[=TIME]", Time, "it's the 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|} + "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|} + 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|} + 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|} + 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(",")+")") {|@code|} + "("+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)") {|@type|} + 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") {|@verbose|} + 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") {|@quit|} + 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 |opt, var| - opts.on("--#{opt}", "added in runtime", &eval("proc {|@#{var}|}")) + opts.on("--#{opt}", "added in runtime", &eval("proc {|x|@#{var}=x}")) end opts.on_head("specific options:") diff --git a/sample/optparse/subcommand.rb b/sample/optparse/subcommand.rb new file mode 100755 index 0000000000..21c42dd60a --- /dev/null +++ b/sample/optparse/subcommand.rb @@ -0,0 +1,19 @@ +#! /usr/bin/ruby +# contributed by Minero Aoki. + +require 'optparse' + +parser = OptionParser.new +parser.on('-i') { puts "-i" } +parser.on('-o') { puts '-o' } + +subparsers = Hash.new {|h,k| + $stderr.puts "no such subcommand: #{k}" + exit 1 +} +subparsers['add'] = OptionParser.new.on('-i') { puts "add -i" } +subparsers['del'] = OptionParser.new.on('-i') { puts "del -i" } +subparsers['list'] = OptionParser.new.on('-i') { puts "list -i" } + +parser.order!(ARGV) +subparsers[ARGV.shift].parse!(ARGV) unless ARGV.empty? diff --git a/sample/philos.rb b/sample/philos.rb index 119e7c36b9..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 @@ -25,7 +24,7 @@ def eat(n) end def philosopher(n) - while TRUE + while true think n $forks[n].lock if not $forks[(n+1)%N].try_lock diff --git a/sample/prism/find_calls.rb b/sample/prism/find_calls.rb new file mode 100644 index 0000000000..30af56c719 --- /dev/null +++ b/sample/prism/find_calls.rb @@ -0,0 +1,105 @@ +# This script finds calls to a specific method with a certain keyword parameter +# within a given source file. + +require "prism" +require "pp" + +# For deprecation or refactoring purposes, it's often useful to find all of the +# places that call a specific method with a specific k eyword parameter. This is +# easily accomplished with a visitor such as this one. +class QuxParameterVisitor < Prism::Visitor + def initialize(calls) + @calls = calls + end + + def visit_call_node(node) + @calls << node if qux?(node) + super + end + + private + + def qux?(node) + # All nodes implement pattern matching, so you can use the `in` operator to + # pull out all of their individual fields. As you can see by this extensive + # pattern match, this is quite a powerful feature. + node in { + # This checks that the receiver is the constant Qux or the constant path + # ::Qux. We are assuming relative constants are fine in this case. + receiver: ( + Prism::ConstantReadNode[name: :Qux] | + Prism::ConstantPathNode[parent: nil, name: :Qux] + ), + # This checks that the name of the method is qux. We purposefully are not + # checking the call operator (., ::, or &.) because we want all of them. + # In other ASTs, this would be multiple node types, but prism combines + # them all into one for convenience. + name: :qux, + arguments: Prism::ArgumentsNode[ + # Here we're going to use the "find" pattern to find the keyword hash + # node that has the correct key. + arguments: [ + *, + Prism::KeywordHashNode[ + # Here we'll use another "find" pattern to find the key that we are + # specifically looking for. + elements: [ + *, + # Finally, we can assert against the key itself. Note that we are + # not looking at the value of hash pair, because we are only + # specifically looking for a key. + Prism::AssocNode[key: Prism::SymbolNode[unescaped: "qux"]], + * + ] + ], + * + ] + ] + } + end +end + +calls = [] +Prism.parse_stream(DATA).value.accept(QuxParameterVisitor.new(calls)) + +calls.each do |call| + print "CallNode " + puts PP.pp(call.location, +"") + print " " + puts call.slice +end + +# => +# CallNode (5,6)-(5,29) +# Qux.qux(222, qux: true) +# CallNode (9,6)-(9,30) +# Qux&.qux(333, qux: true) +# CallNode (20,6)-(20,51) +# Qux::qux(888, qux: ::Qux.qux(999, qux: true)) +# CallNode (20,25)-(20,50) +# ::Qux.qux(999, qux: true) + +__END__ +module Foo + class Bar + def baz1 + Qux.qux(111) + Qux.qux(222, qux: true) + end + + def baz2 + Qux&.qux(333, qux: true) + Qux&.qux(444) + end + + def baz3 + qux(555, qux: false) + 666.qux(666) + end + + def baz4 + Qux::qux(777) + Qux::qux(888, qux: ::Qux.qux(999, qux: true)) + end + end +end diff --git a/sample/prism/find_comments.rb b/sample/prism/find_comments.rb new file mode 100644 index 0000000000..6a26cd32b7 --- /dev/null +++ b/sample/prism/find_comments.rb @@ -0,0 +1,100 @@ +# This script finds all of the comments within a given source file for a method. + +require "prism" + +class FindMethodComments < Prism::Visitor + def initialize(target, comments, nesting = []) + @target = target + @comments = comments + @nesting = nesting + end + + # These visit methods are specific to each class. Defining a visitor allows + # you to group functionality that applies to all node types into a single + # class. You can find which method corresponds to which node type by looking + # at the class name, calling #type on the node, or by looking at the #accept + # method definition on the node. + def visit_module_node(node) + visitor = FindMethodComments.new(@target, @comments, [*@nesting, node.name]) + node.compact_child_nodes.each { |child| child.accept(visitor) } + end + + def visit_class_node(node) + # We could keep track of an internal state where we push the class name here + # and then pop it after the visit is complete. However, it is often simpler + # and cleaner to generate a new visitor instance when the state changes, + # because then the state is immutable and it's easier to reason about. This + # also provides for more debugging opportunity in the initializer. + visitor = FindMethodComments.new(@target, @comments, [*@nesting, node.name]) + node.compact_child_nodes.each { |child| child.accept(visitor) } + end + + def visit_def_node(node) + if [*@nesting, node.name] == @target + # Comments are always attached to locations (either inner locations on a + # node like the location of a keyword or the location on the node itself). + # Nodes are considered either "leading" or "trailing", which means that + # they occur before or after the location, respectively. In this case of + # documentation, we only want to consider leading comments. You can also + # fetch all of the comments on a location with #comments. + @comments.concat(node.location.leading_comments) + else + super + end + end +end + +# Most of the time, the concept of "finding" something in the AST can be +# accomplished either with a queue or with a visitor. In this case we will use a +# visitor, but a queue would work just as well. +def find_comments(result, path) + target = path.split(/::|#/).map(&:to_sym) + comments = [] + + result.value.accept(FindMethodComments.new(target, comments)) + comments +end + +result = Prism.parse_stream(DATA) +result.attach_comments! + +find_comments(result, "Foo#foo").each do |comment| + puts comment.inspect + puts comment.slice +end + +# => +# #<Prism::InlineComment @location=#<Prism::Location @start_offset=205 @length=27 start_line=13>> +# # This is the documentation +# #<Prism::InlineComment @location=#<Prism::Location @start_offset=235 @length=21 start_line=14>> +# # for the foo method. + +find_comments(result, "Foo::Bar#bar").each do |comment| + puts comment.inspect + puts comment.slice +end + +# => +# #<Prism::InlineComment @location=#<Prism::Location @start_offset=126 @length=23 start_line=7>> +# # This is documentation +# #<Prism::InlineComment @location=#<Prism::Location @start_offset=154 @length=21 start_line=8>> +# # for the bar method. + +__END__ +# This is the documentation +# for the Foo module. +module Foo + # This is documentation + # for the Bar class. + class Bar + # This is documentation + # for the bar method. + def bar + end + end + + # This is the documentation + # for the foo method. + def foo + end +end diff --git a/sample/prism/locate_nodes.rb b/sample/prism/locate_nodes.rb new file mode 100644 index 0000000000..7a51db4367 --- /dev/null +++ b/sample/prism/locate_nodes.rb @@ -0,0 +1,84 @@ +# This script locates a set of nodes determined by a line and column (in bytes). + +require "prism" +require "pp" + +# This method determines if the given location covers the given line and column. +# It's important to note that columns (and offsets) in prism are always in +# bytes. This is because prism supports all 90 source encodings that Ruby +# supports. You can always retrieve the column (or offset) of a location in +# other units with other provided APIs, like #start_character_column or +# #start_code_units_column. +def covers?(location, line:, column:) + start_line = location.start_line + end_line = location.end_line + + if start_line == end_line + # If the location only spans one line, then we only check if the line + # matches and that the column is covered by the column range. + line == start_line && (location.start_column...location.end_column).cover?(column) + else + # Otherwise, we check that it is on the start line and the column is greater + # than or equal to the start column, or that it is on the end line and the + # column is less than the end column, or that it is between the start and + # end lines. + (line == start_line && column >= location.start_column) || + (line == end_line && column < location.end_column) || + (line > start_line && line < end_line) + end +end + +# This method descends down into the AST whose root is `node` and returns the +# array of all of the nodes that cover the given line and column. +def locate(node, line:, column:) + queue = [node] + result = [] + + # We could use a recursive method here instead if we wanted, but it's + # important to note that that will not work for ASTs that are nested deeply + # enough to cause a stack overflow. + while (node = queue.shift) + result << node + + # Nodes have `child_nodes` and `compact_child_nodes`. `child_nodes` have + # consistent indices but include `nil` for optional fields that are not + # present, whereas `compact_child_nodes` has inconsistent indices but does + # not include `nil` for optional fields that are not present. + node.compact_child_nodes.find do |child| + queue << child if covers?(child.location, line: line, column: column) + end + end + + result +end + +result = Prism.parse_stream(DATA) +locate(result.value, line: 4, column: 14).each_with_index do |node, index| + print " " * index + print node.class.name.split("::", 2).last + print " " + puts PP.pp(node.location, +"") +end + +# => +# ProgramNode (1,0)-(7,3) +# StatementsNode (1,0)-(7,3) +# ModuleNode (1,0)-(7,3) +# StatementsNode (2,2)-(6,5) +# ClassNode (2,2)-(6,5) +# StatementsNode (3,4)-(5,7) +# DefNode (3,4)-(5,7) +# StatementsNode (4,6)-(4,21) +# CallNode (4,6)-(4,21) +# CallNode (4,6)-(4,15) +# ArgumentsNode (4,12)-(4,15) +# IntegerNode (4,12)-(4,15) + +__END__ +module Foo + class Bar + def baz + 111 + 222 + 333 + end + end +end diff --git a/sample/prism/make_tags.rb b/sample/prism/make_tags.rb new file mode 100644 index 0000000000..dc770ab1b0 --- /dev/null +++ b/sample/prism/make_tags.rb @@ -0,0 +1,302 @@ +# This script generates a tags file using Prism to parse the Ruby files. + +require "prism" + +# This visitor is responsible for visiting the nodes in the AST and generating +# the appropriate tags. The tags are stored in the entries array as strings. +class TagsVisitor < Prism::Visitor + # This represents an entry in the tags file, which is a tab-separated line. It + # houses the logic for how an entry is constructed. + class Entry + attr_reader :parts + + def initialize(name, filepath, pattern, type) + @parts = [name, filepath, pattern, type] + end + + def attribute(key, value) + parts << "#{key}:#{value}" + end + + def attribute_class(nesting, names) + return if nesting.empty? && names.length == 1 + attribute("class", [*nesting, names].flatten.tap(&:pop).join(".")) + end + + def attribute_inherits(names) + attribute("inherits", names.join(".")) if names + end + + def to_line + parts.join("\t") + end + end + + private_constant :Entry + + attr_reader :entries, :filepath, :lines, :nesting, :singleton + + # Initialize the visitor with the given parameters. The first three parameters + # are constant throughout the visit, while the last two are controlled by the + # visitor as it traverses the AST. These are treated as immutable by virtue of + # the visit methods constructing new visitors when they need to change. + def initialize(entries, filepath, lines, nesting = [], singleton = false) + @entries = entries + @filepath = filepath + @lines = lines + @nesting = nesting + @singleton = singleton + end + + # Visit a method alias node and generate the appropriate tags. + # + # alias m2 m1 + # + def visit_alias_method_node(node) + enter(node.new_name.unescaped.to_sym, node, "a") do |entry| + entry.attribute_class(nesting, [nil]) + end + + super + end + + # Visit a method call to attr_reader, attr_writer, or attr_accessor without a + # receiver and generate the appropriate tags. Note that this ignores the fact + # that these methods could be overridden, which is a limitation of this + # script. + # + # attr_accessor :m1 + # + def visit_call_node(node) + if !node.receiver && %i[attr_reader attr_writer attr_accessor].include?(name = node.name) + (node.arguments&.arguments || []).grep(Prism::SymbolNode).each do |argument| + if name != :attr_writer + enter(:"#{argument.unescaped}", argument, singleton ? "F" : "f") do |entry| + entry.attribute_class(nesting, [nil]) + end + end + + if name != :attr_reader + enter(:"#{argument.unescaped}=", argument, singleton ? "F" : "f") do |entry| + entry.attribute_class(nesting, [nil]) + end + end + end + end + + super + end + + # Visit a class node and generate the appropriate tags. + # + # class C1 + # end + # + def visit_class_node(node) + if (names = names_for(node.constant_path)) + enter(names.last, node, "c") do |entry| + entry.attribute_class(nesting, names) + entry.attribute_inherits(names_for(node.superclass)) + end + + node.body&.accept(copy_visitor([*nesting, names], singleton)) + end + end + + # Visit a constant path write node and generate the appropriate tags. + # + # C1::C2 = 1 + # + def visit_constant_path_write_node(node) + if (names = names_for(node.target)) + enter(names.last, node, "C") do |entry| + entry.attribute_class(nesting, names) + end + end + + super + end + + # Visit a constant write node and generate the appropriate tags. + # + # C1 = 1 + # + def visit_constant_write_node(node) + enter(node.name, node, "C") do |entry| + entry.attribute_class(nesting, [nil]) + end + + super + end + + # Visit a method definition node and generate the appropriate tags. + # + # def m1; end + # + def visit_def_node(node) + enter(node.name, node, (node.receiver || singleton) ? "F" : "f") do |entry| + entry.attribute_class(nesting, [nil]) + end + + super + end + + # Visit a module node and generate the appropriate tags. + # + # module M1 + # end + # + def visit_module_node(node) + if (names = names_for(node.constant_path)) + enter(names.last, node, "m") do |entry| + entry.attribute_class(nesting, names) + end + + node.body&.accept(copy_visitor([*nesting, names], singleton)) + end + end + + # Visit a singleton class node and generate the appropriate tags. + # + # class << self + # end + # + def visit_singleton_class_node(node) + case node.expression + when Prism::SelfNode + node.body&.accept(copy_visitor(nesting, true)) + when Prism::ConstantReadNode, Prism::ConstantPathNode + if (names = names_for(node.expression)) + node.body&.accept(copy_visitor([*nesting, names], true)) + end + else + node.body&.accept(copy_visitor([*nesting, nil], true)) + end + end + + private + + # Generate a new visitor with the given dynamic options. The static options + # are copied over automatically. + def copy_visitor(nesting, singleton) + TagsVisitor.new(entries, filepath, lines, nesting, singleton) + end + + # Generate a new entry for the given name, node, and type and add it into the + # list of entries. The block is used to add additional attributes to the + # entry. + def enter(name, node, type) + line = lines[node.location.start_line - 1].chomp + pattern = "/^#{line.gsub("\\", "\\\\\\\\").gsub("/", "\\/")}$/;\"" + + entry = Entry.new(name, filepath, pattern, type) + yield entry + + entries << entry.to_line + end + + # Retrieve the names for the given node. This is used to construct the class + # attribute for the tags. + def names_for(node) + case node + when Prism::ConstantPathNode + names = names_for(node.parent) + return unless names + + names << node.name + when Prism::ConstantReadNode + [node.name] + when Prism::SelfNode + [:self] + else + # dynamic + end + end +end + +# Parse the Ruby file and visit all of the nodes in the resulting AST. Once all +# of the nodes have been visited, the entries array should be populated with the +# tags. +result = Prism.parse_stream(DATA) +result.value.accept(TagsVisitor.new(entries = [], __FILE__, result.source.lines)) + +# Print the tags to STDOUT. +puts "!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;\" to lines/" +puts "!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/" +puts entries.sort + +# => +# !_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ +# !_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ +# C1 sample/prism/make_tags.rb /^ class C1$/;" c class:M1.M2 +# C2 sample/prism/make_tags.rb /^ class C2 < Object$/;" c class:M1.M2.C1 inherits:Object +# C6 sample/prism/make_tags.rb /^ C6 = 1$/;" C class:M1 +# C7 sample/prism/make_tags.rb /^ C7 = 2$/;" C class:M1 +# C9 sample/prism/make_tags.rb /^ C8::C9 = 3$/;" C class:M1.C8 +# M1 sample/prism/make_tags.rb /^module M1$/;" m +# M2 sample/prism/make_tags.rb /^ module M2$/;" m class:M1 +# M4 sample/prism/make_tags.rb /^ module M3::M4$/;" m class:M1.M3 +# M5 sample/prism/make_tags.rb /^ module self::M5$/;" m class:M1.self +# m1 sample/prism/make_tags.rb /^ def m1; end$/;" f class:M1.M2.C1.C2 +# m10 sample/prism/make_tags.rb /^ attr_accessor :m10, :m11$/;" f class:M1.M3.M4 +# m10= sample/prism/make_tags.rb /^ attr_accessor :m10, :m11$/;" f class:M1.M3.M4 +# m11 sample/prism/make_tags.rb /^ attr_accessor :m10, :m11$/;" f class:M1.M3.M4 +# m11= sample/prism/make_tags.rb /^ attr_accessor :m10, :m11$/;" f class:M1.M3.M4 +# m12 sample/prism/make_tags.rb /^ attr_reader :m12, :m13, :m14$/;" f class:M1.M3.M4 +# m13 sample/prism/make_tags.rb /^ attr_reader :m12, :m13, :m14$/;" f class:M1.M3.M4 +# m14 sample/prism/make_tags.rb /^ attr_reader :m12, :m13, :m14$/;" f class:M1.M3.M4 +# m15= sample/prism/make_tags.rb /^ attr_writer :m15$/;" f class:M1.M3.M4 +# m2 sample/prism/make_tags.rb /^ def m2; end$/;" f class:M1.M2.C1.C2 +# m3 sample/prism/make_tags.rb /^ alias m3 m1$/;" a class:M1.M2.C1.C2 +# m4 sample/prism/make_tags.rb /^ alias :m4 :m2$/;" a class:M1.M2.C1.C2 +# m5 sample/prism/make_tags.rb /^ def self.m5; end$/;" F class:M1.M2.C1.C2 +# m6 sample/prism/make_tags.rb /^ def m6; end$/;" F class:M1.M2.C1.C2 +# m7 sample/prism/make_tags.rb /^ def m7; end$/;" F class:M1.M2.C1.C2.C3 +# m8 sample/prism/make_tags.rb /^ def m8; end$/;" F class:M1.M2.C1.C2.C4.C5 +# m9 sample/prism/make_tags.rb /^ def m9; end$/;" F class:M1.M2.C1.C2. + +__END__ +module M1 + module M2 + class C1 + class C2 < Object + def m1; end + def m2; end + + alias m3 m1 + alias :m4 :m2 + + def self.m5; end + + class << self + def m6; end + end + + class << C3 + def m7; end + end + + class << C4::C5 + def m8; end + end + + class << c + def m9; end + end + end + end + end + + module M3::M4 + attr_accessor :m10, :m11 + attr_reader :m12, :m13, :m14 + attr_writer :m15 + end + + module self::M5 + end + + C6 = 1 + C7 = 2 + C8::C9 = 3 +end diff --git a/sample/prism/multiplex_constants.rb b/sample/prism/multiplex_constants.rb new file mode 100644 index 0000000000..e39f2c36f6 --- /dev/null +++ b/sample/prism/multiplex_constants.rb @@ -0,0 +1,138 @@ +# This script indexes the classes and modules within a set of files using the +# saved source functionality. + +require "prism" +require "etc" +require "tempfile" + +module Indexer + # A class that implements the #enter functionality so that it can be passed to + # the various save* APIs. This effectively bundles up all of the node_id and + # field_name pairs so that they can be written back to the parent process. + class Repository + attr_reader :scope, :entries + + def initialize + @scope = [] + @entries = [] + end + + def with(next_scope) + previous_scope = scope + @scope = scope + next_scope + yield + @scope = previous_scope + end + + def empty? + entries.empty? + end + + def enter(node_id, field_name) + entries << [scope.join("::"), node_id, field_name] + end + end + + # Visit the classes and modules in the AST and save their locations into the + # repository. + class Visitor < Prism::Visitor + attr_reader :repository + + def initialize(repository) + @repository = repository + end + + def visit_class_node(node) + repository.with(node.constant_path.full_name_parts) do + node.constant_path.save_location(repository) + visit(node.body) + end + end + + def visit_module_node(node) + repository.with(node.constant_path.full_name_parts) do + node.constant_path.save_location(repository) + visit(node.body) + end + end + end + + # Index the classes and modules within a file. If there are any entries, + # return them as a serialized string to the parent process. + def self.index(filepath) + repository = Repository.new + Prism.parse_file(filepath).value.accept(Visitor.new(repository)) + "#{filepath}|#{repository.entries.join("|")}" unless repository.empty? + end +end + +def index_glob(glob, count = Etc.nprocessors - 1) + process_ids = [] + filepath_writers = [] + index_reader, index_writer = IO.pipe + + # For each number in count, fork off a worker that has access to two pipes. + # The first pipe is the index_writer, to which it writes all of the results of + # indexing the various files. The second pipe is the filepath_reader, from + # which it reads the filepaths that it needs to index. + count.times do + filepath_reader, filepath_writer = IO.pipe + + process_ids << fork do + filepath_writer.close + index_reader.close + + while (filepath = filepath_reader.gets(chomp: true)) + results = Indexer.index(filepath) + index_writer.puts(results) if results + end + end + + filepath_reader.close + filepath_writers << filepath_writer + end + + index_writer.close + + # In a separate thread, write all of the filepaths to the various worker + # processes. This is done in a separate threads since puts will eventually + # block when each of the pipe buffers fills up. We write in a round-robin + # fashion to the various workers. This could be improved using a work-stealing + # algorithm, but is fine if you don't end up having a ton of variety in the + # size of your files. + writer_thread = + Thread.new do + Dir[glob].each_with_index do |filepath, index| + filepath_writers[index % count].puts(filepath) + end + end + + index = Hash.new { |hash, key| hash[key] = [] } + + # In a separate thread, read all of the results from the various worker + # processes and store them in the index. This is done in a separate thread so + # that reads and writes can be interleaved. This is important so that the + # index pipe doesn't fill up and block the writer. + reader_thread = + Thread.new do + while (line = index_reader.gets(chomp: true)) + filepath, *entries = line.split("|") + repository = Prism::Relocation.filepath(filepath).filepath.lines.code_unit_columns(Encoding::UTF_16LE).leading_comments + + entries.each_slice(3) do |(name, node_id, field_name)| + index[name] << repository.enter(Integer(node_id), field_name.to_sym) + end + end + end + + writer_thread.join + filepath_writers.each(&:close) + + reader_thread.join + index_reader.close + + process_ids.each { |process_id| Process.wait(process_id) } + index +end + +index_glob(File.expand_path("../../lib/**/*.rb", __dir__)) diff --git a/sample/prism/relocate_constants.rb b/sample/prism/relocate_constants.rb new file mode 100644 index 0000000000..faa48f6388 --- /dev/null +++ b/sample/prism/relocate_constants.rb @@ -0,0 +1,43 @@ +# This script finds the declaration of all classes and modules and stores them +# in a hash for an in-memory database of constants. + +require "prism" + +class RelocationVisitor < Prism::Visitor + attr_reader :index, :repository, :scope + + def initialize(index, repository, scope = []) + @index = index + @repository = repository + @scope = scope + end + + def visit_class_node(node) + next_scope = scope + node.constant_path.full_name_parts + index[next_scope.join("::")] << node.constant_path.save(repository) + node.body&.accept(RelocationVisitor.new(index, repository, next_scope)) + end + + def visit_module_node(node) + next_scope = scope + node.constant_path.full_name_parts + index[next_scope.join("::")] << node.constant_path.save(repository) + node.body&.accept(RelocationVisitor.new(index, repository, next_scope)) + end +end + +# Create an index that will store a mapping between the names of constants to a +# list of the locations where they are declared or re-opened. +index = Hash.new { |hash, key| hash[key] = [] } + +# Loop through every file in the lib directory of this repository and parse them +# with Prism. Then visit them using the RelocateVisitor to store their +# repository entries in the index. +Dir[File.expand_path("../../lib/**/*.rb", __dir__)].each do |filepath| + repository = Prism::Relocation.filepath(filepath).filepath.lines.code_unit_columns(Encoding::UTF_16LE) + Prism.parse_file(filepath).value.accept(RelocationVisitor.new(index, repository)) +end + +puts index["Prism::ParametersNode"].map { |entry| "#{entry.filepath}:#{entry.start_line}:#{entry.start_code_units_column}" } +# => +# prism/lib/prism/node.rb:13889:8 +# prism/lib/prism/node_ext.rb:267:8 diff --git a/sample/prism/visit_nodes.rb b/sample/prism/visit_nodes.rb new file mode 100644 index 0000000000..5ba703b0a3 --- /dev/null +++ b/sample/prism/visit_nodes.rb @@ -0,0 +1,63 @@ +# This script visits all of the nodes of a specific type within a given source +# file. It uses the visitor class to traverse the AST. + +require "prism" +require "pp" + +class CaseInsensitiveRegularExpressionVisitor < Prism::Visitor + def initialize(regexps) + @regexps = regexps + end + + # As the visitor is walking the tree, this method will only be called when it + # encounters a regular expression node. We can then call any regular + # expression -specific APIs. In this case, we are only interested in the + # regular expressions that are case-insensitive, which we can retrieve with + # the #ignore_case? method. + def visit_regular_expression_node(node) + @regexps << node if node.ignore_case? + super + end + + def visit_interpolated_regular_expression_node(node) + @regexps << node if node.ignore_case? + + # The default behavior of the visitor is to continue visiting the children + # of the node. Because Ruby is so dynamic, it's actually possible for + # another regular expression to be interpolated in statements contained + # within the #{} contained in this interpolated regular expression node. By + # calling `super`, we ensure the visitor will continue. Failing to call + # `super` will cause the visitor to stop the traversal of the tree, which + # can also be useful in some cases. + super + end +end + +result = Prism.parse_stream(DATA) +regexps = [] + +result.value.accept(CaseInsensitiveRegularExpressionVisitor.new(regexps)) +regexps.each do |node| + print node.class.name.split("::", 2).last + print " " + puts PP.pp(node.location, +"") + + if node.is_a?(Prism::RegularExpressionNode) + print " " + p node.unescaped + end +end + +# => +# InterpolatedRegularExpressionNode (3,9)-(3,47) +# RegularExpressionNode (3,16)-(3,22) +# "bar" +# RegularExpressionNode (4,9)-(4,15) +# "bar" + +__END__ +class Foo + REG1 = /foo/ + REG2 = /foo #{/bar/i =~ "" ? "bar" : "baz"}/i + REG3 = /bar/i +end 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 new file mode 100644 index 0000000000..199d98b79c --- /dev/null +++ b/sample/pty/expect_sample.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true +# +# sample program of expect.rb +# +# by A. Ito +# +# This program reports the latest version of Ruby interpreter +# by connecting to ftp server at ruby-lang.org. +# +require 'pty' +require 'expect' + +fnames = [] +PTY.spawn("ftp ftp.ruby-lang.org") do |r_f,w_f,pid| + w_f.sync = true + + $expect_verbose = false + + if !ENV['USER'].nil? + username = ENV['USER'] + elsif !ENV['LOGNAME'].nil? + username = ENV['LOGNAME'] + else + username = 'guest' + end + + 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" + end + + r_f.expect(/[^\-]> /) do |output| + for x in output[0].split("\n") + if x =~ /(ruby.*?\.tar\.gz)/ then + fnames.push $1 + end + end + end + begin + w_f.print "quit\n" + rescue + end +end + +print "The latest ruby interpreter is " +print fnames.sort.pop +print "\n" diff --git a/sample/pty/script.rb b/sample/pty/script.rb new file mode 100644 index 0000000000..c6659a4807 --- /dev/null +++ b/sample/pty/script.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true +require 'pty' + +if ARGV.size == 0 then + ofile = "typescript" +else + ofile = ARGV[0] +end + +logfile = File.open(ofile,"a") + +system "stty -echo raw lnext ^_" + +PTY.spawn("/bin/csh") do |r_pty,w_pty,pid| + + Thread.new do + while true + w_pty.print STDIN.getc.chr + w_pty.flush + end + end + + begin + while true + c = r_pty.sysread(512) + break if c.nil? + print c + STDOUT.flush + logfile.print c + end + rescue + # print $@,':',$!,"\n" + logfile.close + end +end + +system "stty echo -raw lnext ^v" diff --git a/sample/pty/shl.rb b/sample/pty/shl.rb new file mode 100644 index 0000000000..980748e8f5 --- /dev/null +++ b/sample/pty/shl.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true +# +# old-fashioned 'shl' like program +# by A. Ito +# +# commands: +# c creates new shell +# C-z suspends shell +# p lists all shell +# 0,1,... choose shell +# q quit + +require 'pty' +require 'io/console' + +$shells = [] + +$r_pty = nil +$w_pty = nil + +def writer + STDIN.raw! + begin + while true + c = STDIN.getc + if c == ?\C-z then + $reader.raise('Suspend') + return 'Suspend' + end + $w_pty.print c.chr + $w_pty.flush + end + rescue + $reader.raise('Exit') + return 'Exit' + ensure + STDIN.cooked! + end +end + +$reader = Thread.new { + while true + begin + Thread.stop unless $r_pty + c = $r_pty.getc + if c.nil? then + Thread.main.raise('Exit') + Thread.stop + end + print c.chr + STDOUT.flush + rescue + Thread.stop + end + end +} + +# $reader.raise(nil) + + +while true + print ">> " + STDOUT.flush + n = nil + case gets + when /^c/i + $shells << PTY.spawn("/bin/csh") + n = -1 + when /^p/i + $shells.each_with_index do |s, i| + if s + print i,"\n" + end + end + when /^([0-9]+)/ + n = $1.to_i + if $shells[n].nil? + print "\##{i} doesn't exist\n" + 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/rdoc/markup/rdoc2latex.rb b/sample/rdoc/markup/rdoc2latex.rb new file mode 100644 index 0000000000..aa8079eb90 --- /dev/null +++ b/sample/rdoc/markup/rdoc2latex.rb @@ -0,0 +1,15 @@ +#!/usr/local/bin/ruby +# Illustration of a script to convert an RDoc-style file to a LaTeX document + +require 'rdoc/markup' +require 'rdoc/markup/to_latex' + +p = RDoc::Markup.new +h = RDoc::Markup::ToLaTeX.new + +#puts "\\documentclass{report}" +#puts "\\usepackage{tabularx}" +#puts "\\usepackage{parskip}" +#puts "\\begin{document}" +puts p.convert(ARGF.read, h) +#puts "\\end{document}" diff --git a/sample/rdoc/markup/sample.rb b/sample/rdoc/markup/sample.rb new file mode 100644 index 0000000000..db5d88d150 --- /dev/null +++ b/sample/rdoc/markup/sample.rb @@ -0,0 +1,40 @@ +# This program illustrates the basic use of the SimpleMarkup +# class. It extracts the first comment block from the +# simple_markup.rb file and converts it into HTML on +# standard output. Run it using +# +# % ruby sample.rb +# +# You should be in the sample/rdoc/markup/ directory when you do this, +# as it hardwires the path to the files it needs to require. +# This isn't necessary in the code you write once you've +# installed the package. +# +# For a better way of formatting code comment blocks (and more) +# see the rdoc package. +# + +require 'rdoc/markup/simple_markup' +require 'rdoc/markup/simple_markup/to_html' + +# Extract the comment block from the source file + +input_string = "" + +File.foreach("../../../lib/rdoc/markup/simple_markup.rb") do |line| + break unless line.gsub!(/^\# ?/, '') + input_string << line +end + +# Create a markup object +markup = SM::SimpleMarkup.new + +# Attach it to an HTML formatter +h = SM::ToHtml.new + +# And convert out comment block to html. Wrap it a body +# tag pair to let browsers view it + +puts "<html><body>" +puts markup.convert(input_string, h) +puts "</body></html>" diff --git a/sample/regx.rb b/sample/regx.rb deleted file mode 100644 index aaf4b5f1ee..0000000000 --- a/sample/regx.rb +++ /dev/null @@ -1,23 +0,0 @@ -st = "\033[7m" -en = "\033[m" -#st = "<<" -#en = ">>" - -while TRUE - print "str> " - STDOUT.flush - input = gets - break if not input - if input != "" - str = input - str.chop! - end - print "pat> " - STDOUT.flush - re = gets - break if not re - re.chop! - str.gsub! re, "#{st}\\&#{en}" - print str, "\n" -end -print "\n" 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 new file mode 100644 index 0000000000..1e6b3bf550 --- /dev/null +++ b/sample/ripper/ruby2html.rb @@ -0,0 +1,116 @@ +#!/usr/bin/env ruby +# $originalId: ruby2html.rb,v 1.2 2005/09/23 22:53:47 aamine Exp $ + +TEMPLATE_LINE = __LINE__ + 2 +TEMPLATE = <<-EndTemplate +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<html> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=<%= encoding %>"> +<% if css %> + <link rel="stylesheet" type="text/css" href="<%= css %>"> +<% end %> + <title><%= File.basename(f.path) %></title> +</head> +<body> +<pre> +<% + if print_line_number + Ruby2HTML.compile(f).each_with_index do |line, idx| +%><%= sprintf('%4d %s', idx+1, line) %><% + end + else +%><%= Ruby2HTML.compile(f) %><% + end +%> +</pre> +</body> +</html> +EndTemplate + +require 'ripper' +require 'stringio' +require 'cgi' +require 'erb' +require 'optparse' + +def main + encoding = 'us-ascii' + css = nil + print_line_number = false + parser = OptionParser.new + parser.banner = "Usage: #{File.basename($0)} [-l] [<file>...]" + parser.on('--encoding=NAME', 'Character encoding [us-ascii].') {|name| + encoding = name + } + parser.on('--css=URL', 'Set a link to CSS.') {|url| + css = url + } + parser.on('-l', '--line-number', 'Show line number.') { + print_line_number = true + } + parser.on('--help', 'Prints this message and quit.') { + puts parser.help + exit 0 + } + begin + parser.parse! + rescue OptionParser::ParseError => err + $stderr.puts err + $stderr.puts parser.help + exit 1 + end + puts ruby2html(ARGF, encoding, css, print_line_number) +end + +class ERB + attr_accessor :lineno + + remove_method :result + def result(b) + eval(@src, b, (@filename || '(erb)'), (@lineno || 1)) + end +end + +def ruby2html(f, encoding, css, print_line_number) + 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()) +end + +class Ruby2HTML < Ripper::Filter + def Ruby2HTML.compile(f) + buf = StringIO.new + Ruby2HTML.new(f).parse(buf) + buf.string + end + + def on_default(event, tok, f) + f << CGI.escapeHTML(tok) + end + + def on_kw(tok, f) + f << %Q[<span class="resword">#{CGI.escapeHTML(tok)}</span>] + end + + def on_comment(tok, f) + f << %Q[<span class="comment">#{CGI.escapeHTML(tok.rstrip)}</span>\n] + end + + def on_tstring_beg(tok, f) + f << %Q[<span class="string">#{CGI.escapeHTML(tok)}] + end + + def on_tstring_end(tok, f) + f << %Q[#{CGI.escapeHTML(tok)}</span>] + end +end + +if $0 == __FILE__ + main +end diff --git a/sample/ripper/strip-comment.rb b/sample/ripper/strip-comment.rb new file mode 100644 index 0000000000..bd26b6a377 --- /dev/null +++ b/sample/ripper/strip-comment.rb @@ -0,0 +1,19 @@ +# $Id$ + +require 'ripper/filter' + +class CommentStripper < Ripper::Filter + def CommentStripper.strip(src) + new(src).parse(nil) + end + + def on_default(event, token, data) + print token + end + + def on_comment(token, data) + puts + end +end + +CommentStripper.strip(ARGF) diff --git a/sample/rss/list_description.rb b/sample/rss/list_description.rb deleted file mode 100644 index edb9ba07a4..0000000000 --- a/sample/rss/list_description.rb +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env ruby - -require "nkf" -class String - # From tdiary.rb - def shorten( len = 120 ) - lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ ) - lines[0].concat( '...' ) if lines[0] and lines[1] - lines[0] - end -end - -require "rss/parser" -require "rss/1.0" -require "rss/2.0" -require "rss/dublincore" - -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 = "euc-jp" - rescue RSS::UnknownConversionMethodError - error($!) if verbose - end - rss.channel.title ||= "Unknown" - rss.items.each do |item| - item.title ||= "Unknown" - 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 "Processing Time : #{processing_time}s" diff --git a/sample/rss/rss_recent.rb b/sample/rss/rss_recent.rb deleted file mode 100644 index 3ccb4a4505..0000000000 --- a/sample/rss/rss_recent.rb +++ /dev/null @@ -1,84 +0,0 @@ -#!/usr/bin/env ruby - -require "nkf" -class String - # From tdiary.rb - def shorten( len = 120 ) - lines = NKF::nkf( "-e -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ ) - lines[0].concat( '...' ) if lines[0] and lines[1] - lines[0] - end -end - -require "rss/parser" -require "rss/1.0" -require "rss/2.0" -require "rss/syndication" -require "rss/dublincore" - -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 = "euc-jp" - rescue RSS::UnknownConversionMethodError - error($!) if verbose - end - rss.items.each do |item| - if item.respond_to?(:pubDate) and item.pubDate - class << item - alias_method(:dc_date, :pubDate) - end - end - if item.respond_to?(:dc_date) and item.dc_date - items << [rss.channel, item] - end - 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 "Processing Time : #{processing_time}s" diff --git a/sample/rss/tdiary_plugin/rss-recent.rb b/sample/rss/tdiary_plugin/rss-recent.rb deleted file mode 100644 index 103d3358b0..0000000000 --- a/sample/rss/tdiary_plugin/rss-recent.rb +++ /dev/null @@ -1,118 +0,0 @@ -# rss-recent.rb: RSS recent plugin -# -# rss_recnet: show recnet list from RSS -# parameters (default): -# url: URL of RSS -# max: max of list itmes(5) -# cache_time: cache time(second) of RSS(60*60) -# -# -# Copyright (c) 2003 Kouhei Sutou <kou@cozmixng.org> -# Distributed under the GPL -# - -require "rss/rss" - -RSS_RECENT_FIELD_SEPARATOR = "\0" -RSS_RECENT_VERSION = "0.0.2" -RSS_RECENT_CONTENT_TYPE = { - "User-Agent" => "tDiary RSS recent plugin version #{RSS_RECENT_VERSION}. " << - "Using RSS parser version is #{::RSS::VERSION}." -} - - -def rss_recent(url, max=5, cache_time=3600) - cache_file = "#{@cache_path}/rss-recent.#{CGI.escape(url)}" - - rss_recent_cache_rss(url, cache_file, cache_time.to_i) - - return '' unless test(?r, cache_file) - - rv = "<ul>\n" - File.open(cache_file) do |f| - max.to_i.times do - title = f.gets(RSS_RECENT_FIELD_SEPARATOR) - break if title.nil? - rv << '<li>' - link = f.gets(RSS_RECENT_FIELD_SEPARATOR) - unless link.nil? - rv << %Q!<a href="#{CGI.escapeHTML(link.chomp(RSS_RECENT_FIELD_SEPARATOR))}">! - end - rv << CGI::escapeHTML(title.chomp(RSS_RECENT_FIELD_SEPARATOR)) - rv << '</a>' unless link.nil? - rv << "</li>\n" - end - end - rv << "</ul>\n" - - rv -end - -class InvalidResourceError < StandardError; end - -def rss_recent_cache_rss(url, cache_file, cache_time) - - begin - raise if Time.now > File.mtime(cache_file) + cache_time - rescue - require 'net/http' - require 'uri/generic' - require 'rss/parser' - require 'rss/1.0' - require 'rss/2.0' - - begin - ur = URI.parse(url) - - raise URI::InvalidURIError if ur.scheme != "http" - - rss_source = rss_recent_fetch_rss(ur) - - # parse RSS - rss = ::RSS::Parser.parse(rss_source, false) - raise ::RSS::Error if rss.nil? - - # pre processing - begin - rss.output_encoding = charset - rescue ::RSS::UnknownConversionMethodError - end - - tlary = rss.items.collect{|item| [item.title, item.link]} - rss_recent_write_to_cache(cache_file, tlary) - - rescue URI::InvalidURIError - rss_recent_write_to_cache(cache_file, [['Invalid URI', url]]) - rescue InvalidResourceError, ::RSS::Error - rss_recent_write_to_cache(cache_file, [['Invalid Resource', url]]) - end - end - -end - -def rss_recent_fetch_rss(uri) - rss = '' - begin - Net::HTTP.start(uri.host, uri.port || 80) do |http| - path = uri.path - path << "?#{uri.query}" if uri.query - req = http.request_get(path) - raise InvalidResourceError unless req.code == "200" - rss << req.body - end - rescue TimeoutError, SocketError - raise InvalidResourceError - end - rss -end - -def rss_recent_write_to_cache(cache_file, array_of_titles_and_links) - File.open(cache_file, 'w') do |f| - f.flock(File::LOCK_EX) - array_of_titles_and_links.each do |title, link| - f << "#{title}#{RSS_RECENT_FIELD_SEPARATOR}" - f << "#{link}#{RSS_RECENT_FIELD_SEPARATOR}" - end - f.flock(File::LOCK_UN) - end -end 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/soap/babelfish.rb b/sample/soap/babelfish.rb deleted file mode 100644 index eb2421449a..0000000000 --- a/sample/soap/babelfish.rb +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env ruby - -text = ARGV.shift || 'Hello world.' -lang = ARGV.shift || 'en_fr' - -require 'soap/rpc/driver' - -server = 'http://services.xmethods.net/perl/soaplite.cgi' -InterfaceNS = 'urn:xmethodsBabelFish' -wireDumpDev = nil # STDERR - -drv = SOAP::RPC::Driver.new(server, InterfaceNS) -drv.wiredump_dev = wireDumpDev -drv.add_method_with_soapaction('BabelFish', InterfaceNS + "#BabelFish", 'translationmode', 'sourcedata') - -p drv.BabelFish(lang, text) diff --git a/sample/soap/calc/calc.rb b/sample/soap/calc/calc.rb deleted file mode 100644 index 6bc78803b3..0000000000 --- a/sample/soap/calc/calc.rb +++ /dev/null @@ -1,17 +0,0 @@ -module CalcService - def self.add(lhs, rhs) - lhs + rhs - end - - def self.sub(lhs, rhs) - lhs - rhs - end - - def self.multi(lhs, rhs) - lhs * rhs - end - - def self.div(lhs, rhs) - lhs / rhs - end -end diff --git a/sample/soap/calc/calc2.rb b/sample/soap/calc/calc2.rb deleted file mode 100644 index e9cf6bbca7..0000000000 --- a/sample/soap/calc/calc2.rb +++ /dev/null @@ -1,29 +0,0 @@ -class CalcService2 - def initialize(value = 0) - @value = value - end - - def set(value) - @value = value - end - - def get - @value - end - - def +(rhs) - @value + rhs - end - - def -(rhs) - @value - rhs - end - - def *(rhs) - @value * rhs - end - - def /(rhs) - @value / rhs - end -end diff --git a/sample/soap/calc/client.rb b/sample/soap/calc/client.rb deleted file mode 100644 index 57a4c0ba5b..0000000000 --- a/sample/soap/calc/client.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'soap/rpc/driver' - -server = ARGV.shift || 'http://localhost:7000/' -# server = 'http://localhost:8808/server.cgi' - -calc = SOAP::RPC::Driver.new(server, 'http://tempuri.org/calcService') -#calc.wiredump_dev = STDERR -calc.add_method('add', 'lhs', 'rhs') -calc.add_method('sub', 'lhs', 'rhs') -calc.add_method('multi', 'lhs', 'rhs') -calc.add_method('div', 'lhs', 'rhs') - -puts 'add: 1 + 2 # => 3' -puts calc.add(1, 2) -puts 'sub: 1.1 - 2.2 # => -1.1' -puts calc.sub(1.1, 2.2) -puts 'multi: 1.1 * 2.2 # => 2.42' -puts calc.multi(1.1, 2.2) -puts 'div: 5 / 2 # => 2' -puts calc.div(5, 2) -puts 'div: 5.0 / 2 # => 2.5' -puts calc.div(5.0, 2) -puts 'div: 1.1 / 0 # => Infinity' -puts calc.div(1.1, 0) -puts 'div: 1 / 0 # => ZeroDivisionError' -puts calc.div(1, 0) diff --git a/sample/soap/calc/client2.rb b/sample/soap/calc/client2.rb deleted file mode 100644 index 2c53f09d42..0000000000 --- a/sample/soap/calc/client2.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'soap/rpc/driver' - -server = ARGV.shift || 'http://localhost:7000/' -# server = 'http://localhost:8808/server2.cgi' - -var = SOAP::RPC::Driver.new( server, 'http://tempuri.org/calcService' ) -var.add_method( 'set', 'newValue' ) -var.add_method( 'get' ) -var.add_method_as( '+', 'add', 'rhs' ) -var.add_method_as( '-', 'sub', 'rhs' ) -var.add_method_as( '*', 'multi', 'rhs' ) -var.add_method_as( '/', 'div', 'rhs' ) - -puts 'var.set( 1 )' -puts '# Bare in mind that another client set another value to this service.' -puts '# This is only a sample for proof of concept.' -var.set( 1 ) -puts 'var + 2 # => 1 + 2 = 3' -puts var + 2 -puts 'var - 2.2 # => 1 - 2.2 = -1.2' -puts var - 2.2 -puts 'var * 2.2 # => 1 * 2.2 = 2.2' -puts var * 2.2 -puts 'var / 2 # => 1 / 2 = 0' -puts var / 2 -puts 'var / 2.0 # => 1 / 2.0 = 0.5' -puts var / 2.0 -puts 'var / 0 # => 1 / 0 => ZeroDivisionError' -puts var / 0 diff --git a/sample/soap/calc/httpd.rb b/sample/soap/calc/httpd.rb deleted file mode 100644 index bebcff96c6..0000000000 --- a/sample/soap/calc/httpd.rb +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env ruby - -require 'webrick' -require 'soap/property' - -docroot = "." -port = 8808 -if opt = SOAP::Property.loadproperty("samplehttpd.conf") - docroot = opt["docroot"] - port = Integer(opt["port"]) -end - -s = WEBrick::HTTPServer.new( - :BindAddress => "0.0.0.0", - :Port => port, - :DocumentRoot => docroot, - :CGIPathEnv => ENV['PATH'] -) -trap(:INT){ s.shutdown } -s.start diff --git a/sample/soap/calc/samplehttpd.conf b/sample/soap/calc/samplehttpd.conf deleted file mode 100644 index 85e9995021..0000000000 --- a/sample/soap/calc/samplehttpd.conf +++ /dev/null @@ -1,2 +0,0 @@ -docroot = . -port = 8808 diff --git a/sample/soap/calc/server.cgi b/sample/soap/calc/server.cgi deleted file mode 100644 index c4fa687550..0000000000 --- a/sample/soap/calc/server.cgi +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env ruby - -require 'soap/rpc/cgistub' - -class CalcServer < SOAP::RPC::CGIStub - def initialize(*arg) - super - - require 'calc' - servant = CalcService - add_servant(servant, 'http://tempuri.org/calcService') - end -end - -status = CalcServer.new('CalcServer', nil).start diff --git a/sample/soap/calc/server.rb b/sample/soap/calc/server.rb deleted file mode 100644 index 12a3968b5a..0000000000 --- a/sample/soap/calc/server.rb +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env ruby - -require 'soap/rpc/standaloneServer' -require 'calc' - -class CalcServer < SOAP::RPC::StandaloneServer - def initialize(*arg) - super - - servant = CalcService - add_servant(servant, 'http://tempuri.org/calcService') - end -end - -if $0 == __FILE__ - status = CalcServer.new('CalcServer', nil, '0.0.0.0', 7000).start -end diff --git a/sample/soap/calc/server2.rb b/sample/soap/calc/server2.rb deleted file mode 100644 index 735721de64..0000000000 --- a/sample/soap/calc/server2.rb +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env ruby - -require 'soap/rpc/standaloneServer' -require 'calc2' - -class CalcServer2 < SOAP::RPC::StandaloneServer - def on_init - servant = CalcService2.new - add_method(servant, 'set', 'newValue') - add_method(servant, 'get') - add_method_as(servant, '+', 'add', 'lhs') - add_method_as(servant, '-', 'sub', 'lhs') - add_method_as(servant, '*', 'multi', 'lhs') - add_method_as(servant, '/', 'div', 'lhs') - end -end - -if $0 == __FILE__ - status = CalcServer2.new('CalcServer', 'http://tempuri.org/calcService', '0.0.0.0', 7000).start -end diff --git a/sample/soap/digraph.rb b/sample/soap/digraph.rb deleted file mode 100644 index 54ff302592..0000000000 --- a/sample/soap/digraph.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'soap/marshal' - -class Node; include SOAP::Marshallable - attr_reader :first, :second, :str - - def initialize(*init_next) - @first = init_next[0] - @second = init_next[1] - end -end - -n9 = Node.new -n81 = Node.new(n9) -n82 = Node.new(n9) -n7 = Node.new(n81, n82) -n61 = Node.new(n7) -n62 = Node.new(n7) -n5 = Node.new(n61, n62) -n41 = Node.new(n5) -n42 = Node.new(n5) -n3 = Node.new(n41, n42) -n21 = Node.new(n3) -n22 = Node.new(n3) -n1 = Node.new(n21, n22) - -File.open("digraph_marshalled_string.soap", "wb") do |f| - SOAP::Marshal.dump(n1, f) -end - -marshalledString = File.open("digraph_marshalled_string.soap") { |f| f.read } - -puts marshalledString - -newnode = SOAP::Marshal.unmarshal(marshalledString) - -puts newnode.inspect - -p newnode.first.first.__id__ -p newnode.second.first.__id__ -p newnode.first.first.first.first.__id__ -p newnode.second.first.second.first.__id__ - -File.unlink("digraph_marshalled_string.soap") diff --git a/sample/soap/exchange/client.rb b/sample/soap/exchange/client.rb deleted file mode 100644 index 2aa277afef..0000000000 --- a/sample/soap/exchange/client.rb +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env ruby - -require "soap/rpc/driver" - -ExchangeServiceNamespace = 'http://tempuri.org/exchangeService' - -server = ARGV.shift || "http://localhost:7000/" -# server = "http://localhost:8808/server.cgi" - -logger = nil -wiredump_dev = nil -# logger = Logger.new(STDERR) -# wiredump_dev = STDERR - -drv = SOAP::RPC::Driver.new(server, ExchangeServiceNamespace) -drv.wiredump_dev = wiredump_dev -drv.add_method("rate", "country1", "country2") - -p drv.rate("USA", "Japan") diff --git a/sample/soap/exchange/exchange.rb b/sample/soap/exchange/exchange.rb deleted file mode 100644 index 00f930deb8..0000000000 --- a/sample/soap/exchange/exchange.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'soap/rpc/driver' - -ExchangeServiceNamespace = 'http://tempuri.org/exchangeService' - -class Exchange - ForeignServer = "http://services.xmethods.net/soap" - Namespace = "urn:xmethods-CurrencyExchange" - - def initialize - @drv = SOAP::RPC::Driver.new(ForeignServer, Namespace) - @drv.add_method("getRate", "country1", "country2") - end - - def rate(country1, country2) - return @drv.getRate(country1, country2) - end -end diff --git a/sample/soap/exchange/httpd.rb b/sample/soap/exchange/httpd.rb deleted file mode 100644 index bebcff96c6..0000000000 --- a/sample/soap/exchange/httpd.rb +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env ruby - -require 'webrick' -require 'soap/property' - -docroot = "." -port = 8808 -if opt = SOAP::Property.loadproperty("samplehttpd.conf") - docroot = opt["docroot"] - port = Integer(opt["port"]) -end - -s = WEBrick::HTTPServer.new( - :BindAddress => "0.0.0.0", - :Port => port, - :DocumentRoot => docroot, - :CGIPathEnv => ENV['PATH'] -) -trap(:INT){ s.shutdown } -s.start diff --git a/sample/soap/exchange/samplehttpd.conf b/sample/soap/exchange/samplehttpd.conf deleted file mode 100644 index 85e9995021..0000000000 --- a/sample/soap/exchange/samplehttpd.conf +++ /dev/null @@ -1,2 +0,0 @@ -docroot = . -port = 8808 diff --git a/sample/soap/exchange/server.cgi b/sample/soap/exchange/server.cgi deleted file mode 100644 index 16bc85a042..0000000000 --- a/sample/soap/exchange/server.cgi +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/local/bin/ruby - -require 'soap/rpc/cgistub' -require 'exchange' - -class ExchangeServer < SOAP::RPC::CGIStub - def initialize(*arg) - super - servant = Exchange.new - add_servant(servant) - end -end - -status = ExchangeServer.new('SampleStructServer', ExchangeServiceNamespace).start diff --git a/sample/soap/exchange/server.rb b/sample/soap/exchange/server.rb deleted file mode 100644 index d510d54a76..0000000000 --- a/sample/soap/exchange/server.rb +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env ruby - -require 'soap/rpc/standaloneServer' -require 'exchange' - -class ExchangeServer < SOAP::RPC::StandaloneServer - def initialize(*arg) - super - servant = Exchange.new - add_servant(servant) - end -end - -if $0 == __FILE__ - status = ExchangeServer.new('SampleStructServer', ExchangeServiceNamespace, '0.0.0.0', 7000).start -end diff --git a/sample/soap/helloworld/hw_c.rb b/sample/soap/helloworld/hw_c.rb deleted file mode 100644 index 253d0a409b..0000000000 --- a/sample/soap/helloworld/hw_c.rb +++ /dev/null @@ -1,6 +0,0 @@ -require 'soap/rpc/driver' - -s = SOAP::RPC::Driver.new('http://localhost:2000/', 'urn:hws') -s.add_method("hello_world", "from") - -p s.hello_world(self.to_s) diff --git a/sample/soap/helloworld/hw_s.rb b/sample/soap/helloworld/hw_s.rb deleted file mode 100644 index b917f72fc0..0000000000 --- a/sample/soap/helloworld/hw_s.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'soap/rpc/standaloneServer' - -class HelloWorldServer < SOAP::RPC::StandaloneServer - def on_init - @log.level = Logger::Severity::DEBUG - add_method(self, 'hello_world', 'from') - end - - def hello_world(from) - "Hello World, from #{ from }" - end -end - -if $0 == __FILE__ - server = HelloWorldServer.new('hws', 'urn:hws', '0.0.0.0', 2000) - server.start -end diff --git a/sample/soap/icd/IICD.rb b/sample/soap/icd/IICD.rb deleted file mode 100644 index 3b1fa9b32c..0000000000 --- a/sample/soap/icd/IICD.rb +++ /dev/null @@ -1,17 +0,0 @@ -module IICD - # All methods in a single namespace?! - InterfaceNS = 'http://www.iwebmethod.net' - - Methods = [ - ['SearchWord', 'query', 'partial'], - ['GetItemById', 'id'], - ['EnumWords'], - ['FullTextSearch', 'query'], - ] - - def IICD.add_method(drv) - Methods.each do |method, *param| - drv.add_method_with_soapaction(method, InterfaceNS + "/#{ method }", *param ) - end - end -end diff --git a/sample/soap/icd/icd.rb b/sample/soap/icd/icd.rb deleted file mode 100644 index 6e1e51c996..0000000000 --- a/sample/soap/icd/icd.rb +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env ruby - -$KCODE = 'SJIS' - -require 'soap/rpc/driver' -require 'IICD'; include IICD - -server = 'http://www.iwebmethod.net/icd1.0/icd.asmx' -wiredump_dev = nil # STDERR - -icd = SOAP::RPC::Driver.new(server, IICD::InterfaceNS) -icd.wiredump_dev = wiredump_dev -icd.default_encodingstyle = SOAP::EncodingStyle::ASPDotNetHandler::Namespace -IICD::add_method(icd) - -puts "ƒL[ƒ[ƒh: 'microsoft'‚ÅŒ©o‚µŒŸõ" -result = icd.SearchWord('microsoft', true) - -id = nil -result.WORD.each do |word| - puts "Title: " << word.title - puts "Id: " << word.id - puts "English: " << word.english - puts "Japanese: " << word.japanese - puts "----" - id = word.id -end - -item = icd.GetItemById(id) -puts -puts -puts "Title: " << item.word.title -puts "ˆÓ–¡: " << item.meaning - -#p icd.EnumWords - -puts -puts -puts "ƒL[ƒ[ƒh: 'IBM'‚Å‘S•¶ŒŸõ" -icd.FullTextSearch("IBM").WORD.each do |word| - puts "Title: " << word.title - puts "Id: " << word.id - puts "English: " << word.english - puts "Japanese: " << word.japanese - puts "----" -end diff --git a/sample/soap/raa/iRAA.rb b/sample/soap/raa/iRAA.rb deleted file mode 100644 index 2b188fb887..0000000000 --- a/sample/soap/raa/iRAA.rb +++ /dev/null @@ -1,154 +0,0 @@ -require 'soap/mapping' - - -module RAA; extend SOAP - - -InterfaceNS = "http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/" -MappingRegistry = SOAP::Mapping::Registry.new - -Methods = [ - ['getAllListings', ['retval', 'return']], - ['getProductTree', ['retval', 'return']], - ['getInfoFromCategory', ['in', 'category'], [ 'retval', 'return']], - ['getModifiedInfoSince', ['in', 'time'], [ 'retval', 'return']], - ['getInfoFromName', ['in', 'name'], ['retval', 'return']], -] - - -class Category - include SOAP::Marshallable - - @@schema_type = 'Category' - @@schema_ns = InterfaceNS - - attr_reader :major, :minor - - def initialize(major, minor = nil) - @major = major - @minor = minor - end - - def to_s - "#{ @major }/#{ @minor }" - end - - def ==(rhs) - if @major != rhs.major - false - elsif !@minor or !rhs.minor - true - else - @minor == rhs.minor - end - end -end - -MappingRegistry.set( - ::RAA::Category, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new(InterfaceNS, "Category") } -) - -class Product - include SOAP::Marshallable - - @@schema_type = 'Product' - @@schema_ns = InterfaceNS - - attr_reader :id, :name - attr_accessor :short_description, :version, :status, :homepage, :download, :license, :description - - def initialize(name, short_description = nil, version = nil, status = nil, homepage = nil, download = nil, license = nil, description = nil) - @name = name - @short_description = short_description - @version = version - @status = status - @homepage = homepage - @download = download - @license = license - @description = description - end -end - -MappingRegistry.set( - ::RAA::Product, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new(InterfaceNS, "Product") } -) - -class Owner - include SOAP::Marshallable - - @@schema_type = 'Owner' - @@schema_ns = InterfaceNS - - attr_reader :id - attr_accessor :email, :name - - def initialize(email, name) - @email = email - @name = name - @id = "#{ @email }-#{ @name }" - end -end - -MappingRegistry.set( - ::RAA::Owner, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new(InterfaceNS, "Owner") } -) - -class Info - include SOAP::Marshallable - - @@schema_type = 'Info' - @@schema_ns = InterfaceNS - - attr_accessor :category, :product, :owner, :updated, :created - - def initialize(category = nil, product = nil, owner = nil, updated = nil, created = nil) - @category = category - @product = product - @owner = owner - @updated = updated - @created = created - end - - def <=>(rhs) - @updated <=> rhs.updated - end - - def eql?(rhs) - @product.name == rhs.product.name - end -end - -MappingRegistry.set( - ::RAA::Info, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new(InterfaceNS, "Info") } -) - -class StringArray < Array; end -MappingRegistry.set( - ::RAA::StringArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::XSDString::Type } -) - -class InfoArray < Array; end -MappingRegistry.set( - ::RAA::InfoArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new(InterfaceNS, 'Info') } -) - - -end diff --git a/sample/soap/raa/soap4r.rb b/sample/soap/raa/soap4r.rb deleted file mode 100644 index b93d1e7dbe..0000000000 --- a/sample/soap/raa/soap4r.rb +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env ruby - -require 'iRAA' -require 'soap/rpc/driver' - - -server = ARGV.shift || 'http://raa.ruby-lang.org/soap/1.0.2/' - -raa = SOAP::RPC::Driver.new(server, RAA::InterfaceNS) -raa.mapping_registry = RAA::MappingRegistry -RAA::Methods.each do |name, *params| - raa.add_method(name, params) -end -# raa.wiredump_dev = STDOUT - -p raa.getAllListings().sort - -p raa.getProductTree() - -p raa.getInfoFromCategory(RAA::Category.new("Library", "XML")) - -t = Time.at(Time.now.to_i - 24 * 3600) -p raa.getModifiedInfoSince(t) - -p raa.getModifiedInfoSince(DateTime.new(t.year, t.mon, t.mday, t.hour, t.min, t.sec)) - -o = raa.getInfoFromName("SOAP4R") -p o.class -p o.owner.name -p o diff --git a/sample/soap/sampleStruct/client.rb b/sample/soap/sampleStruct/client.rb deleted file mode 100644 index b55c7fdfc5..0000000000 --- a/sample/soap/sampleStruct/client.rb +++ /dev/null @@ -1,16 +0,0 @@ -require 'soap/rpc/driver' - -require 'iSampleStruct' - -server = ARGV.shift || 'http://localhost:7000/' -# server = 'http://localhost:8808/server.cgi' - -drv = SOAP::RPC::Driver.new(server, SampleStructServiceNamespace) -drv.wiredump_dev = STDERR -drv.add_method('hi', 'sampleStruct') - -o1 = SampleStruct.new -puts "Sending struct: #{ o1.inspect }" -puts -o2 = drv.hi(o1) -puts "Received (wrapped): #{ o2.inspect }" diff --git a/sample/soap/sampleStruct/httpd.rb b/sample/soap/sampleStruct/httpd.rb deleted file mode 100644 index bebcff96c6..0000000000 --- a/sample/soap/sampleStruct/httpd.rb +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env ruby - -require 'webrick' -require 'soap/property' - -docroot = "." -port = 8808 -if opt = SOAP::Property.loadproperty("samplehttpd.conf") - docroot = opt["docroot"] - port = Integer(opt["port"]) -end - -s = WEBrick::HTTPServer.new( - :BindAddress => "0.0.0.0", - :Port => port, - :DocumentRoot => docroot, - :CGIPathEnv => ENV['PATH'] -) -trap(:INT){ s.shutdown } -s.start diff --git a/sample/soap/sampleStruct/iSampleStruct.rb b/sample/soap/sampleStruct/iSampleStruct.rb deleted file mode 100644 index 399ea52eb8..0000000000 --- a/sample/soap/sampleStruct/iSampleStruct.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'soap/mapping' - -SampleStructServiceNamespace = 'http://tempuri.org/sampleStructService' - -class SampleStruct; include SOAP::Marshallable - attr_accessor :sampleArray - attr_accessor :date - - def initialize - @sampleArray = SampleArray[ "cyclic", self ] - @date = DateTime.now - end - - def wrap( rhs ) - @sampleArray = SampleArray[ "wrap", rhs.dup ] - @date = DateTime.now - self - end -end - -class SampleArray < Array; include SOAP::Marshallable -end diff --git a/sample/soap/sampleStruct/sampleStruct.rb b/sample/soap/sampleStruct/sampleStruct.rb deleted file mode 100644 index 394c1bff09..0000000000 --- a/sample/soap/sampleStruct/sampleStruct.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'iSampleStruct' - -class SampleStructService - def hi(struct) - ack = SampleStruct.new - ack.wrap(struct) - ack - end -end - -if __FILE__ == $0 - p SampleStructService.new.hi(SampleStruct.new) -end diff --git a/sample/soap/sampleStruct/samplehttpd.conf b/sample/soap/sampleStruct/samplehttpd.conf deleted file mode 100644 index 85e9995021..0000000000 --- a/sample/soap/sampleStruct/samplehttpd.conf +++ /dev/null @@ -1,2 +0,0 @@ -docroot = . -port = 8808 diff --git a/sample/soap/sampleStruct/server.cgi b/sample/soap/sampleStruct/server.cgi deleted file mode 100644 index 42751386a0..0000000000 --- a/sample/soap/sampleStruct/server.cgi +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/local/bin/ruby - -require 'soap/rpc/cgistub' -require 'sampleStruct' - -class SampleStructServer < SOAP::RPC::CGIStub - def initialize(*arg) - super - servant = SampleStructService.new - add_servant(servant) - end -end - -status = SampleStructServer.new('SampleStructServer', SampleStructServiceNamespace).start diff --git a/sample/soap/sampleStruct/server.rb b/sample/soap/sampleStruct/server.rb deleted file mode 100644 index 3caa31a052..0000000000 --- a/sample/soap/sampleStruct/server.rb +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env ruby - -require 'soap/rpc/standaloneServer' -require 'sampleStruct' - -class SampleStructServer < SOAP::RPC::StandaloneServer - def initialize(*arg) - super - servant = SampleStructService.new - add_servant(servant) - end -end - -if $0 == __FILE__ - status = SampleStructServer.new('SampleStructServer', SampleStructServiceNamespace, '0.0.0.0', 7000).start -end diff --git a/sample/svr.rb b/sample/svr.rb index 6169861abc..eb49ccf170 100644 --- a/sample/svr.rb +++ b/sample/svr.rb @@ -1,9 +1,12 @@ # socket example - server side # usage: ruby svr.rb +# this server might be blocked by an ill-behaved client. +# see tsvr.rb which is safe from client blocking. + require "socket" -gs = TCPserver.open(0) +gs = TCPServer.open(0) addr = gs.addr addr.shift printf("server is on %s\n", addr.join(":")) @@ -22,10 +25,9 @@ loop do print(s, " is gone\n") s.close socks.delete(s) - else - if str = s.gets + # single thread gets may block whole service + elsif str = s.gets s.write(str) - end end end end 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 ac0dfd0aea..65dd9abd10 100644 --- a/sample/test.rb +++ b/sample/test.rb @@ -1,2183 +1,2 @@ -#! /usr/bin/env ruby - -$KCODE = "none" -$testnum=0 -$ntest=0 -$failed = 0 - -def test_check(what) - printf "%s\n", what - $what = what - $testnum = 0 -end - -def test_ok(cond,n=1) - $testnum+=1 - $ntest+=1 - if cond - printf "ok %d\n", $testnum - else - where = caller(n)[0] - printf "not ok %s %d -- %s\n", $what, $testnum, where - $failed+=1 - end -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 = *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,2]) -a = *[*[]]; test_ok(a == nil) -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 == [[]]) -*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 == []) -*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 = *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,[]]) - -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 *nil; end; f {|a| test_ok(a == nil)} -def f; yield *1; end; f {|a| test_ok(a == 1)} -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]]; 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 *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,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 *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 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 *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 == nil) -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 == nil) -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 *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 == nil) -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 == nil) -def r; return *[*[]]; end; a = *r(); test_ok(a == nil) -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 == [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 *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 == [nil]) -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 == [nil]) -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 *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 == [nil]) -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 == [nil]) -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,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 *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,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]) - -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 *nil; end; test_ok(a == nil) -a = loop do break *1; end; test_ok(a == 1) -a = loop do break *[]; end; test_ok(a == nil) -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 == nil) -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 *nil; end; test_ok(a == [nil]) -*a = loop do break *1; end; test_ok(a == [1]) -*a = loop do break *[]; end; test_ok(a == [nil]) -*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 == [nil]) -*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 *nil; end; test_ok(a == [nil]) -*a = *loop do break *1; end; test_ok(a == [1]) -*a = *loop do break *[]; end; test_ok(a == [nil]) -*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 == [nil]) -*a = *loop do break *[*[1]]; end; test_ok(a == [1]) -*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 *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,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(nil){next *nil} -r(1){next *1} -r(nil){next *[]} -r(1){next *[1]} -r(nil){next *[nil]} -r([]){next *[[]]} -r(nil){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([nil]){next *nil} -r([1]){next *1} -r([nil]){next *[]} -r([1]){next *[1]} -r([nil]){next *[nil]} -r([]){next *[[]]} -r([1,2]){next *[1,2]} -r([nil]){next *[*[]]} -r([1]){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,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,nil,[]]){next *nil} -r([1,nil,[]]){next *1} -r([nil,nil,[]]){next *[]} -r([1,nil,[]]){next *[1]} -r([nil,nil,[]]){next *[nil]} -r([nil,nil,[]]){next *[[]]} -r([1,2,[]]){next *[1,2]} -r([nil,nil,[]]){next *[*[]]} -r([1,nil,[]]){next *[*[1]]} -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 tmp.gets() - line = $_ - gsub(/vt100/, 'VT100') - if $_ != line - $_.gsub!('VT100', 'Vt100') - redo - end - $bad = 1 if /vt100/ =~ $_ - $bad = 1 if /VT100/ =~ $_ -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 - test_ok(true) if $! == $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} -$y = {1, 2, 2, 4, 3, 6} - -test_ok($x[1] == 2) - -test_ok(begin - for k,v in $y - 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 = $y.keys.join(":") -test_ok($z == "1:2:3") - -$z = $y.values.join(":") -test_ok($z == "2:4:6") -test_ok($x == $y) - -$y.shift -test_ok($y.length == 2) - -$z = [1,2] -$y[$z] = 256 -test_ok($y[$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 - -tt{|i| break if i == 5} -test_ok(i == 5) - -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]) - -$done = false -$x = [] -for i in 1 .. 7 # see how retry works in iterator loop - if i == 4 and not $done - $done = true - retry - end - $x.push(i) -end -test_ok($x.size == 10) -test_ok($x == [1, 2, 3, 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 m - test_ok(block_given?) -end -m{p 'test'} - -def m - test_ok(block_given?,&proc{}) -end -m{p 'test'} - -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 argument_test(state, proc, *args) - x = state - begin - proc.call(*args) - rescue ArgumentError - x = !x - end - test_ok(x,2) -end - -argument_test(true, lambda{||}) -argument_test(false, lambda{||}, 1) -argument_test(true, lambda{|a,|}, 1) -argument_test(false, lambda{|a,|}) -argument_test(false, lambda{|a,|}, 1,2) - -def get_block(&block) - block -end - -test_ok(Proc == get_block{}.class) -argument_test(true, get_block{||}) -argument_test(true, get_block{||}, 1) -argument_test(true, get_block{|a,|}, 1) -argument_test(true, get_block{|a,|}) -argument_test(true, get_block{|a,|}, 1,2) - -argument_test(true, get_block(&lambda{||})) -argument_test(false, get_block(&lambda{||}),1) -argument_test(true, get_block(&lambda{|a,|}),1) -argument_test(false, get_block(&lambda{|a,|}),1,2) - -block = get_block{11} -test_ok(block.class == Proc) -test_ok(block.to_proc.class == Proc) -test_ok(block.clone.call == 11) -test_ok(get_block(&block).class == Proc) - -lambda = lambda{44} -test_ok(lambda.class == Proc) -test_ok(lambda.to_proc.class == Proc) -test_ok(lambda.clone.call == 44) -test_ok(get_block(&lambda).class == Proc) - -test_ok(Proc.new{|a,| a}.call(1,2,3) == 1) -argument_test(true, Proc.new{|a,|}, 1,2) - -def test_return1 - Proc.new { - return 55 - }.call + 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 - proc_call{return 42}+1 -end -test_ok(proc_return1() == 42) -def proc_return2 - proc_yield{return 42}+1 -end -test_ok(proc_return2() == 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, get_block{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 - get_block{break 55}.call - rescue LocalJumpError - $!.exit_value - end) - -def block_call(&block) - block.call -end - -def block_get(&block) - block -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}.call - 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}.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}.call - 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}.call - 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(&get_block{|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} - -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) - p i - $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 == 225) -test_ok(?\M-\C-a == 129) -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 != $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{|i| i} -test_ok($proc.call(2) == 2) -test_ok($proc.call(3) == 3) - -$proc = proc{|i| i*2} -test_ok($proc.call(2) == 4) -test_ok($proc.call(3) == 6) - -proc{ - iii=5 # nested local variable - $proc = proc{|i| - iii = i - } - $proc2 = proc { - $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{|sig| $x = 2} - Process.kill "SIGINT", $$ - sleep 0.1 - test_ok($x == 2) - - trap "SIGINT", proc{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 = proc{} -eval "i4 = 1", x -test_ok(eval("i4", x) == 1) -x = proc{proc{}}.call -eval "i4 = 22", x -test_ok(eval("i4", x) == 22) -$x = [] -x = proc{proc{}}.call -eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x -test_ok($x[4].call == 8) - -x = binding -eval "i = 1", x -test_ok(eval("i", x) == 1) -x = proc{binding}.call -eval "i = 22", x -test_ok(eval("i", x) == 22) -$x = [] -x = proc{binding}.call -eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x -test_ok($x[4].call == 8) -x = proc{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 { - p = binding - eval "foo11 = 1", p - foo22 = 5 - proc{foo11=22}.call - proc{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 - -p1 = proc{i7 = 0; proc{i7}}.call -test_ok(p1.call == 0) -eval "i7=5", p1 -test_ok(p1.call == 5) -test_ok(!defined?(i7)) - -p1 = proc{i7 = 0; proc{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) - -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` == 'nil') -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"` - -$bad = false -if (dir = File.dirname(File.dirname($0))) == '.' - dir = "" -else - dir << "/" -end - -def valid_syntax?(code, fname) - eval("BEGIN {return true}\n#{code}", nil, fname, 0) -rescue Exception - puts $!.message - false -end - -for script in Dir["#{dir}{lib,sample,ext}/**/*.rb"] - unless valid_syntax? IO::read(script), script - $bad = true - end -end -test_ok(!$bad) - -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 == "Uranus") -test_ok(Gods.ruler1 == "Uranus") -test_ok(Gods.ruler2 == "Uranus") -test_ok(Titans.ruler1 == "Uranus") -test_ok(Titans.ruler2 == "Uranus") -atlas = Titans.new -test_ok(atlas.ruler0 == "Uranus") -test_ok(atlas.ruler3 == "Zeus") -test_ok(atlas.ruler4 == "Cronus") - -test_check "trace" -$x = 1234 -$y = 0 -trace_var :$x, proc{$y = $x} -$x = 40414 -test_ok($y == $x) - -untrace_var :$x -$x = 19660208 -test_ok($y != $x) - -trace_var :$x, proc{$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 "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 - -if $failed > 0 - printf "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/time.rb b/sample/time.rb index 84fa9e1a8d..e16912052e 100644 --- a/sample/time.rb +++ b/sample/time.rb @@ -1,8 +1,12 @@ -#! /usr/local/bin/ruby -cmd = ARGV.join(" ") +#! /usr/bin/env ruby + b = Time.now -system(cmd) +system(*ARGV) e = Time.now -ut, st, cut, cst = Time.times.to_a -total = (e - b).to_f -STDERR.printf "%11.1f real %11.1f user %11.1f sys\n", total, cut, cst + +tms = Process.times +real = e - b +user = tms.cutime +sys = tms.cstime + +STDERR.printf("%11.1f real %11.1f user %11.1f sys\n", real, user, sys) diff --git a/sample/timeout.rb b/sample/timeout.rb new file mode 100644 index 0000000000..ad4459aff0 --- /dev/null +++ b/sample/timeout.rb @@ -0,0 +1,42 @@ +require 'timeout' + +def progress(n = 5) + n.times {|i| print i; STDOUT.flush; sleep 1} + puts "never reach" +end + +p Timeout.timeout(5) { + 45 +} +p Timeout.timeout(5, Timeout::Error) { + 45 +} +p Timeout.timeout(nil) { + 54 +} +p Timeout.timeout(0) { + 54 +} +begin + Timeout.timeout(5) {progress} +rescue => e + puts e.message +end +begin + Timeout.timeout(3) { + begin + Timeout.timeout(5) {progress} + rescue => e + puts "never reach" + end + } +rescue => e + puts e.message +end +class MyTimeout < StandardError +end +begin + 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..2a75888ef5 --- /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 + String + Struct + 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..ced791aa3d --- /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;31. +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/trick2022/01-tompng/Gemfile b/sample/trick2022/01-tompng/Gemfile new file mode 100644 index 0000000000..982b9de67f --- /dev/null +++ b/sample/trick2022/01-tompng/Gemfile @@ -0,0 +1,2 @@ +source 'https://rubygems.org' +gem 'matrix' diff --git a/sample/trick2022/01-tompng/Gemfile.lock b/sample/trick2022/01-tompng/Gemfile.lock new file mode 100644 index 0000000000..8bb3c69025 --- /dev/null +++ b/sample/trick2022/01-tompng/Gemfile.lock @@ -0,0 +1,13 @@ +GEM + remote: https://rubygems.org/ + specs: + matrix (0.4.2) + +PLATFORMS + x86_64-darwin-20 + +DEPENDENCIES + matrix + +BUNDLED WITH + 2.3.3 diff --git a/sample/trick2022/01-tompng/authors.markdown b/sample/trick2022/01-tompng/authors.markdown new file mode 100644 index 0000000000..26ebe24da6 --- /dev/null +++ b/sample/trick2022/01-tompng/authors.markdown @@ -0,0 +1,3 @@ +* Tomoya Ishida (tompng) + * tomoyapenguin@gmail.com + * cctld: jp diff --git a/sample/trick2022/01-tompng/entry.rb b/sample/trick2022/01-tompng/entry.rb new file mode 100644 index 0000000000..97beacc684 --- /dev/null +++ b/sample/trick2022/01-tompng/entry.rb @@ -0,0 +1,40 @@ + eval((s=%~c=(0..35 + ).map{s[2*_1+1]}*'';class$Inte + ger;def$quXinclude(Math ;spXo(a)=self* + a.pow(87X=h=32.chr;g=PI/480;ls=(sp*31X,89)%89; + def$abX+'eval((s=%'+(n=? .next)+s*88.chr+[nXs()=[a + =self%X+'.split(',sp*25+'?'+88.chr+');(0..36).mapX89,89- + a].miX{s[2*_1].split}',sp*31+".join.tr('$',$/)))"]*$/)Xn;end + ;reqX.split$/;trap(:INT){puts;exit};q=->t,i{a,y=((t+i*99)Xuire + 'matrX%960). ivmod(80);[(a*(7+i)+i*23)%79+(y+a)/(5+i%4)%2,39Xix';1 + 5.tiX-y/2]};p=->t,u{a=->b,c{(0..5).sum{(u%2-1)*E**(t*(b+c*_1)*gXmes{ + |i,*X.i+ i*u+=5+sin(u*u))}};x,z=a[5,3]. 5,3].rect;x+=y.Xv|z= + *?!Xi a[19,4];z+=w;r=(4+(x.abs+z.i).ab };t=(0..959).fX..? + W,?Xind{|t|(0..29).all?{x,y=q[t,_1];(x 2||h=ls[y][x]X[,* + ?]..X[/[^!-}]/]}};h=($**h+h).chr;eval( []} ->(x,yX?};a + =(0X,a,b){x=x*36+39.5;y=19.5-y*18;b*=1 |i|((yX..1 + 34)X-b).ceil..y+b).map{|j|((x-i)/a+(y j)/ .times{X.ma + p{zXx,z=p[t,_1];l=u```=0;while``````(l<1)``; u+```=0 ;d=x-y;X.in +dex(Xl+=(d.abs+(z-w``)``.i).ab``s*1.``1 ;x``,z=y``,w;o[v``=``x.r d.imag/Xc[i+ +15*Xd.abs*l*sin(2*``l-t``*g*80``-_1) l*(``1-l)/``6,a``=l*( -l)**2*0.X_1] +)};X7,a*2]&&o[v,z,``0.0``3,l**`` ``times``{|i``|(8+i).times{|Xw=* +MatXj|o[sin(i)/2+````` ```sin( `/2.0`````````)*j/200,j*0.0Xrix +[*(X5-1,0.02,0.1]``}} ``. q[t,``_1];m``[y][x]= };i=-X0.. +44).X1;$><<(['%%','[H .map{|j|(0..79).map{|k|x=(Xmap{ + |i,X -39.5)/35.8;y=( i+=1;m[j][k]?h:c[i]):ls[j]X*b| + v<<X[k];}*''}*$/<<0) 1)%9 te"`")#qv.jSaL{=;q(Q}4fXa.z + ip(Xjs(:#tK`Jm))FKO /A9(2'%iorvf7 eEa0uV xv+Q@qUU](L@&Py .1v'X0.. + ).suXydSEH{-GI|-5(,z G5evpq,[b50 D[ t {on,I?VStS`?G@LoqFCXm{|j + ,k|Xj1.QnxKz!mH%o# )b2Seut,]! 48 lBieJGi 5jeNPD#b}H3X-(p + =(iXaVz#8*+US,hgF 5#6]y-` 4hy HN hF75WjD!0IxJ$sX+k) + .powX+UP"cNUE9- G< tHvV;Ib <-s U T ? vlE xylg=x#X(i+k + ,88)XV9u$9lKb9 @C do7+-w >l { v9 { P l ga%]AK<e&'X+1)* + (j||(X4ifK/6S+ k} @@*a} 6rS xn"Q[M 8 `|g>$#BrjXb<<p; + 0))}XtbDp'Kc t2 Dat9C s C rL+ g,j]Tf B< eMI+zzkWX;b}] + .lup.XtVP<ak IM E/+)B jwv uB (Twqed D* dyf_dT7Xsolve + (v);13Xn:8 #_ RiSTO, [Fk m O]O#"+ a_ cT_.X5.time + s{c[i+X e5 T`FBEC q*f 2 o@{a<eUG aW PX15*_1] + =z[a[_1]X z_@`nll 7F1 2 [=^uS0z^ 6X||w.shif + t]}};eval(Xfg K#R N bp-E_Xc)~.split( + ?X);(0..36).map{s[2*_1].split} + .join.tr('$',$/))) diff --git a/sample/trick2022/01-tompng/remarks.markdown b/sample/trick2022/01-tompng/remarks.markdown new file mode 100644 index 0000000000..70601908b7 --- /dev/null +++ b/sample/trick2022/01-tompng/remarks.markdown @@ -0,0 +1,51 @@ +### Remarks + +Just run it with no argument: + + ruby entry.rb + +Or run it with one non-ascii half-width character argument: + + ruby entry.rb ⬮ + ruby entry.rb 𓆡 + +I confirmed the following implementations/platforms: + +* ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin19] +* ruby 3.1.0p0 (2021-12-25 revision fb4df44d16) [x86_64-darwin20] + +### Description + +This program is an aquatic quine. +Some characters in the code are overwritten with `" "`, but this program can restore the missing parts. +Every frame of this animation is an executable ruby program that let fishes start swimming again from their current position. + +### Internals + +#### Error Correction + +Error correction is performed for each block of length 135. +It consists of 89 kinds of characters(`[*('!'..'W'), '[', *(']'..'}')]`) and satisfies the following constraint. + +``` +matrix(size: 45x135) * block_vector(size: 135) % 89 == zero_vector(size: 45) +``` + +To restore the missing characters in the block, we need to solve a linear equation problem in modulo 89. +This can be achieved by using bundled gem 'matrix' and overwriting some methods. + +```ruby +require 'matrix' +matrix = Matrix[[3, 1, 4], [1, 5, 9], [2, 6, 5]] +class Integer + def quo(x) = self * x.pow(87, 89) % 89 # Fermat's little theorem. 89 is a prime number. + def abs() = [self % 89, 89 - self % 89].min # To avoid division by multiple of 89. +end +answer = matrix.lup.solve([1, 2, 3]) #=> Vector[24, 42, 83] +(matrix * answer).map { _1 % 89 } #=> Vector[1, 2, 3] +``` + +#### Resuming Animation + +The entire animation of this fish tank is a loop of 960 frames. +This program uses position of the floating bubbles to detect current frame number from the executed source code. diff --git a/sample/trick2022/02-tompng/authors.markdown b/sample/trick2022/02-tompng/authors.markdown new file mode 100644 index 0000000000..26ebe24da6 --- /dev/null +++ b/sample/trick2022/02-tompng/authors.markdown @@ -0,0 +1,3 @@ +* Tomoya Ishida (tompng) + * tomoyapenguin@gmail.com + * cctld: jp diff --git a/sample/trick2022/02-tompng/entry.rb b/sample/trick2022/02-tompng/entry.rb new file mode 100644 index 0000000000..2e2e2bcf74 --- /dev/null +++ b/sample/trick2022/02-tompng/entry.rb @@ -0,0 +1,32 @@ + q=->{!sleep _1/1e2};p=( + c=0..2).map{[_1/9r ,0,5**_1.i/3,1,0]} + require'socket';puts'op' "en http://localhost:#{( + w=TCPServer.new$*[0]||0).addr[1]}";Thread.new{q[2];f=[-1 + ]*s=3;t=Time.now.to_f;p.select!{0<_1[3]=[_1[3]+_1[4]/8.0,1 + ].min};9.times{h=p.map{[2**(_1*t.i)/_4**0.5/(1+Math.sin(2*t- + 9*_1%2)**32/16),_2+_4*( _3-_2)]};r=[s*3/2,84].min;g=->{x,y= +(s*(1+_1+1i)/2).rect;x<0 ||x>=s-1||y<0||y>=s-1?0:((l=f[y+1])[ +x+1]*(a=x%1)+(1-a)*l[x] )*(b=y%1)+(1-b)*((l=f[y])[x+1]*a+(1- +a)*l[x])};f=(1..r).map {|y|(1..r).map{|x|z=1.5+1.5i-3.0*(y +.i+x)/r;[h.sum{g[_1.*z +_2]}*0.9,1].min}};s=r};c=f.flatten +redo};loop{s=w.accept ; Thread.new{r=s.gets;h='HTTP/1.1 '+ +"200 OK\r\nContent-" 'T' "ype:text/html\r\n\r\n";r['/ ']?s. + <<(h+'<style>ifram' 'e{' 'opacity:0;height:0;}input{wid'+ + 'th:252px;}</styl' 'e>' '<form target="i"><input src="'+ + "g#{rand}\" type" '="im' 'age"><iframe name="i"></ifra'+ + 'me></form>'):r ['/g'] ?(h[/:.+l/]=?:'image/gif';s<< + h+'GIF8' '7a'+[84, + 84,246,0,*(0..383).map {15*_1. /(383r)**(3-_1% + 3)*17}].pack('v3c*'); loop{ s<<[67434785,5, + 44,84,84,7,c.map{_1* 127} .each_slice(126 + ).map{[127,128,*_1 ] .pack'c*'}*'', + 1,129].pack('V3x' 'v2na*c2x');q[ + 5];q.[]1while(r ==r=c)}):(x,y, + z=r.scan(/\d+/).map{_1.to_f/ + 126-1};z&&p<<[rand-0.5,( + z=x+y.i)*1.5,z/(z. + abs+0.9),0,-p[ + -3][4]=-1] + s.<<h);s + .close + }} diff --git a/sample/trick2022/02-tompng/remarks.markdown b/sample/trick2022/02-tompng/remarks.markdown new file mode 100644 index 0000000000..3b2d3fd84b --- /dev/null +++ b/sample/trick2022/02-tompng/remarks.markdown @@ -0,0 +1,32 @@ +### Remarks + +1. Run it with `ruby entry.rb 8080` + +2. Open "http://localhost:8080" + +3. Click on the screen and interact with it + +I confirmed the following implementations/platforms: + +* Ruby Version + * ruby 3.1.0p0 (2021-12-25 revision fb4df44d16) [x86_64-darwin20] +* Browser + * Chrome(macOS, Android) + * Firefox(macOS) + * Edge(macOS) + +### Description + +This program is an HTTP server that provides a fractal creature playground. +You can see the heartbeat of a mysterious fractal creature. Clicking on the screen will change the shape of the creature. +Surprisingly, this interactive webpage is built without JavaScript. + +### Internals + +Fractal: Iterated function system +Rendering from server: Streaming animated GIF +Sending click event to server: `<input type="image" src="streaming.gif">` with `<form target="invisible_iframe">` + +### Limitations + +Does not work on Safari and iOS. diff --git a/sample/trick2022/03-mame/authors.markdown b/sample/trick2022/03-mame/authors.markdown new file mode 100644 index 0000000000..0e420fdf5d --- /dev/null +++ b/sample/trick2022/03-mame/authors.markdown @@ -0,0 +1,3 @@ +* Yusuke Endoh + * mame@ruby-lang.org + * cctld: jp diff --git a/sample/trick2022/03-mame/entry.rb b/sample/trick2022/03-mame/entry.rb new file mode 100644 index 0000000000..f24595dfa9 --- /dev/null +++ b/sample/trick2022/03-mame/entry.rb @@ -0,0 +1,27 @@ +2022;"# + +.chars} {puts'TRICK+2022' + \ { ; +#';$><< b + ?! +};#{s=' ' # 0 +! s[0]? ( b=$<.read ;' +} ub( ,''} +';a= ''<<32 +b.lines {puts( ?.. *( +b.size) .gsub(/./) { +b.sub!( /^#$`\K(\S) + /x,a)?$1:a } + .rstrip)}): + ( [ 12,1,12,11]. +cycle { | i | t = ( s * + +10<< +10)* +10+ %(\e[A)* +10 +10. times{t[i* + _1 ] = 'TRICK+2022'[ + _1 ] };$><<t + sleep 1}) + }" diff --git a/sample/trick2022/03-mame/remarks.markdown b/sample/trick2022/03-mame/remarks.markdown new file mode 100644 index 0000000000..c38279f016 --- /dev/null +++ b/sample/trick2022/03-mame/remarks.markdown @@ -0,0 +1,96 @@ +Execute the program normally. + +``` +$ ruby entry.rb +``` + +It shakes a string. + +... Wait! This is not all. + +Next, please apply "leftward gravity" to each letter in the file. +IOW, if there is a space to the left of a letter, move it to the left. +Here, you may want to use the following command. + +``` +$ sed "s/ //g" entry.rb | tee up.rb +``` + +This program applies "upward gravity" to each letter in an input text. +The following demo will help you understand what this means. + +``` +$ cat test.txt +$ ruby up.rb test.txt +``` + +Now, here's where we come in. +Please apply "upward gravity" to entry.rb. + +``` +$ ruby up.rb entry.rb | tee left.rb +``` + +I think that you already noticed that. +This program applies "leftward gravity" to an input text. + +``` +$ cat test.txt +$ ruby left.rb test.txt +``` + +`sed` is no longer required to create `up.rb`; just use `left.rb`. + +``` +$ ruby left.rb entry.rb > up.rb +``` + +We've come to the final stage. +Please apply `left.rb` to `left.rb`. + +``` +$ ruby left.rb left.rb | tee horizontal.rb +$ ruby horizontal.rb +``` + +Of course, it is also possible to apply `up.rb` to `up.rb`. + +``` +$ ruby up.rb up.rb | tee vertical.rb +$ ruby vertical.rb +``` + +Can you tell how they work? Enjoy analyzing! + + + +--- +Code reading tips (spoiler) + +Some code fragments are highly reused between the programs. +For example, note that this program has one code fragment to input a text +(`b=$>.read`); `up.rb` and `left.rb` share and use this code fragment. +Also, `horizontal.rb` and `vertical.rb` share the fragment `puts'TRICK+2022'`. +Sometimes letters in very distant places are reused all over the place. + +Can you tell how it detects if it is already aligned or not yet? +Here is a simplified version of the gimmick to switch behavior when +left-aligned: + +``` +"\ #{puts('not left-aligned yet')} + # {puts('left-aligned')}" +``` + +And for top-aligned: + +``` +"# +xx{puts('top-aligned')} +x#{puts('not top-aligned yet')} +" +``` + +It is also necessary to detect "top-left-aligned" and "left-top-aligned". +I made tons of subtle adjustments and trial-and-error to create the program. +I no longer know precisely how it works. diff --git a/sample/trick2022/03-mame/test.txt b/sample/trick2022/03-mame/test.txt new file mode 100644 index 0000000000..18802153a9 --- /dev/null +++ b/sample/trick2022/03-mame/test.txt @@ -0,0 +1,13 @@ +T + R + I + C + K + | + | + | + | + 2 + 0 + 2 + 2 diff --git a/sample/trick2022/README.md b/sample/trick2022/README.md new file mode 100644 index 0000000000..3b2af6f86b --- /dev/null +++ b/sample/trick2022/README.md @@ -0,0 +1,14 @@ +This directory contains the award-winning entries of +the 4th Transcendental Ruby Imbroglio Contest for rubyKaigi (TRICK 2022). + +THESE ARE BAD EXAMPLES! You must NOT use them as a sample code. + +* 01-tompng/entry.rb: "Best fishbowl" -- Tomoya Ishida (tompng) +* 02-tompng/entry.rb: "Most interactive code" -- Tomoya Ishida (tompng) +* 03-mame/entry.rb: "Most anti-gravity" -- Yusuke Endoh + +These files are licensed under MIT license. + +For the contest outline and other winning entries, see: + +https://github.com/tric/trick2022 diff --git a/sample/trick2025/01-omoikane/authors.markdown b/sample/trick2025/01-omoikane/authors.markdown new file mode 100644 index 0000000000..5c6823c077 --- /dev/null +++ b/sample/trick2025/01-omoikane/authors.markdown @@ -0,0 +1,5 @@ +* Don Yang + * omoikane@uguu.org + * cctld: us + * bsky.app/profile/omoikane.bsky.social + * twitter.com/uguu_org diff --git a/sample/trick2025/01-omoikane/bf.rb b/sample/trick2025/01-omoikane/bf.rb new file mode 100644 index 0000000000..74f5abe7e4 --- /dev/null +++ b/sample/trick2025/01-omoikane/bf.rb @@ -0,0 +1,81 @@ +#!/usr/bin/ruby -w +# Simple BF interpretor. +# +# This works by translating input code into ruby and evaluating the +# translated ruby code. Doing it this way runs much faster than +# interpreting BF on our own. +# +# There is no error reporting whatsoever. A malformed input may result in +# a syntax error at run time, but good luck in finding where it came from. + + +# Setup empty tape and initial pointer position. Note that tape size is +# fixed. We can make it infinite by initializing it to "[]" here and +# adding some nil checks in the generated code, but avoiding those checks +# makes the program run ~10% faster. +$code = "t=Array.new(30000,0); p=0;" + +# Counters for pending add or shift operations. We buffer incoming +-<> +# operators and output a single merged operation when we encounter a +# different operator. +$buffered_add = 0 +$buffered_shift = 0 + +# Flush pending add operations, if any. +def flush_add + if $buffered_add != 0 + $code += "t[p]+=#{$buffered_add};" + $buffered_add = 0 + end +end + +# Flush pending shift operations, if any. +def flush_shift + if $buffered_shift != 0 + $code += "p+=#{$buffered_shift};" + $buffered_shift = 0 + end +end + +def flush_pending_ops + flush_add + flush_shift +end + +# Convert input characters to ruby. +ARGF.each_char{|c| + case c + when '+' + flush_shift + $buffered_add += 1 + when '-' + flush_shift + $buffered_add -= 1 + when '<' + flush_add + $buffered_shift -= 1 + when '>' + flush_add + $buffered_shift += 1 + when ',' + flush_pending_ops + $code += "if c=STDIN.getc;" + + "t[p]=c.ord;" + + "else;" + + "t[p]=-1;" + # EOF is interpreted as -1. + "end;" + when '.' + flush_pending_ops + $code += "print t[p].chr;" + when '[' + flush_pending_ops + $code += "while t[p]!=0;" + when ']' + flush_pending_ops + $code += "end;" + end +} +flush_pending_ops + +# Evaluate converted code. +eval $code diff --git a/sample/trick2025/01-omoikane/entry.rb b/sample/trick2025/01-omoikane/entry.rb new file mode 100644 index 0000000000..c84f8079ae --- /dev/null +++ b/sample/trick2025/01-omoikane/entry.rb @@ -0,0 +1,32 @@ + a=+Math::PI/13 + #Z---z';#za-mRUBY + #A-ZaA-Mn--\[+>+>++ + '"N-Z(\++\[->++++@" + b=\[->+> +>+>\[h_ + p%{} eact + zoraq ;%{ GF. rin); + %{eb} r A R p *""\] + <<<{{{ }<\]<b + ]<l(%w| } ; a;a=%Y/ + evar{|c)} <][ #pgny\W{f + chaa,b)]>++[ ->+>>>>>[40v + .tr(= ' ;eval(%w{r=u=b= y =0;%{ + (ct;c ) ; ] <<->--<<< < < ] >>[>, + exi}; a * = A RGV.siz e > 0 ? -1:1; + z=[] ; A R G F .ea c h _ l i n e{|i +|i.eac h _ g r aph e m e _ c l u ster +{|j|i f ( k = j.o r d ) < 3 3 ; r+=k< +32?k==9? 8 - r%8 : k = = 1 0 | |k==13 +?[u+=1,-r][ 1]: 0 : 1 ; e lse;z+=[[u, +r,j]];b+=r;y+=u;r+=1;end;}};if(s=z.si +ze)>0;b/=s;y/=s;m,n=z[0];i=Math::tan( +a/2);j=Math::sin(a);z.map!{|d|p=d[1]- +b;q=d[0]-y;p-=(i*q).round;m=[m,q+=(j* + p).round].min;n=[n,p-=(i*q).round]. + min;[q,p,d[2]]};r=n;u=m;z.sort.eac + h{|d|p,b=d;r=(u<p)?n:r;print"\n" + *(p-u),"\40"*(b-r),d[2];u=p;r= + b+1};print"\n";end}*"");%(]> + "tyvuts(}}.--.>--.>+.<++' + )b\40"gena.(c)2025<<< + #)#ehol""+a*.^_^ diff --git a/sample/trick2025/01-omoikane/remarks.markdown b/sample/trick2025/01-omoikane/remarks.markdown new file mode 100644 index 0000000000..2aa77d64e4 --- /dev/null +++ b/sample/trick2025/01-omoikane/remarks.markdown @@ -0,0 +1,71 @@ +### Summary + +This is a rot13 filter. Given an input text, it will **rotate** the text by **pi/13** radians. Two modes of operation are available, selected based on number of command line arguments. + +Rotate clockwise: + + ruby entry.rb < input.txt + +Rotate counterclockwise: + + ruby entry.rb input.txt + ruby entry.rb - < input.txt + +### Details + +This program interprets input as an ASCII art with each character representing individual square pixels, and produces a rotated image to stdout. All non-whitespace characters are preserved in output, only the positions of those characters are adjusted. While all the characters are preserved, the words and sentences will not be as readable in their newly rotated form. This makes the program suitable for obfuscating text. + + ruby entry.rb original.txt > rotated.txt + ruby entry.rb < rotated.txt > unrotated.txt + +But note that while `unrotated.txt` is often the same as `original.txt`, there is no hard guarantee due to integer rounding intricacies. Whether the original text can be recovered depends a lot on its shape, be sure to check that the output is reversible if you are using this rot13 filter to post spoilers and such. + +Reversibility does hold for `entry.rb`: + + ruby entry.rb entry.rb | ruby entry.rb | diff entry.rb - + ruby entry.rb < entry.rb | ruby entry.rb - | diff entry.rb - + +Also, there is a bit of text embedded in the rotated version: + + ruby entry.rb entry.rb | ruby + +But this text is encrypted! No problem, just rotate `entry.rb` the other way for the decryption tool: + + ruby entry.rb < entry.rb > caesar_cipher_shift_13.rb + ruby entry.rb entry.rb | ruby | ruby caesar_cipher_shift_13.rb + +If current shell is `bash` or `zsh`, this can be done all in one line: + + ruby entry.rb entry.rb | ruby | ruby <(ruby entry.rb < entry.rb) + +### Miscellaneous features + +To rotate to a different angle, edit the first line of `entry.rb`. Angles between -pi/2 and pi/2 will work best, anything outside that range produces more distortion than rotation, although the output might still be reversible. + +Setting angle to zero makes this program a filter that expands tabs, trim whitespaces, and canonicalize end-of-line sequences. + +This program preserves non-ASCII characters since input is tokenized with `each_grapheme_cluster`, although all characters that's not an ASCII space/tab/newline are given the same treatment. For example, the full-width space character (U+3000) will be transformed as if it's a half-width non-whitespace ASCII character. + +If input contains only whitespace characters, output will be empty. + +The layout is meant to resemble a daruma doll. There was still ~119 bytes of space left after fitting in 3 ruby programs, so I embedded a brainfuck program as well. + + ruby bf.rb entry.rb + +A `sample_input.txt` has been included for testing. After rotating this file 26 times either clockwise or counterclockwise, you should get back the original `sample_input.txt`. + + ruby entry.rb < sample_input.txt | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | diff sample_input.txt - + ruby entry.rb sample_input.txt | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | diff sample_input.txt - + +Additional development notes can be found in `spoiler_rot13.txt` (rotate clockwise to decode). + + ruby entry.rb < spoiler_rot13.txt + +### Compatibility + +Program has been verified to work under these environments: + + * ruby 3.2.2 on cygwin. + * ruby 2.5.1p57 on linux. + * ruby 2.7.4p191 on linux. + * ruby 2.7.1p83 on jslinux. diff --git a/sample/trick2025/01-omoikane/sample_input.txt b/sample/trick2025/01-omoikane/sample_input.txt new file mode 100644 index 0000000000..244530f265 --- /dev/null +++ b/sample/trick2025/01-omoikane/sample_input.txt @@ -0,0 +1,35 @@ + T U + S V + + R T U W + S V + + Q R W X + + Q X + P i h g f Y + j e + P k d Y + + O l c Z + O Z + m b + +* N N n + a A A * + + o z + M B + M p y B + + L q x C + r w + L s t u v C + K D + + K J E D + + I F + J H G E + + I F + H G diff --git a/sample/trick2025/01-omoikane/spoiler_rot13.txt b/sample/trick2025/01-omoikane/spoiler_rot13.txt new file mode 100644 index 0000000000..91636176b8 --- /dev/null +++ b/sample/trick2025/01-omoikane/spoiler_rot13.txt @@ -0,0 +1,470 @@ + . + text + ted t to + rota tex + dit HTML + to etes oss + sier wri acr + t earb"), ions . + ke itry. etat text + o ma "en erpr tive + ge te.g. e int: erna + L paut ( tiplsteps alt edit,he + a HTM inp muling cted ach dit tu + -w tes nt as havellow expe er ely ere yo + uby neragume can e fo the aftrect whethis + in/rt gee ar hat y th t. has stepindicesshat + usr/bcripingl ext tt tr texsult ion to prois w +#!/his s a s of t migh inale re rotatededis aich ts. +# TTakest. ece you origf th tra ts neike , wh tex + # stdou a piles, the ck i e exemenuld lusly ated the + # ite ang s tod che f th movu wotaneo rot pen + # To wrrent edit, an se orsort yoimul and nd o ne. + # diffe ome tion1-2. ecaue cu Whats s inal t, a en do + # ke srotaeps ous be thve. tex orig ayou t wh + # 1. Maply t st tediecausuitiated hold he l tex this + # 2. Apepea is lt bunint rot to rom ted. ated but + # 3. R cessficu is l and ough le fenabl upd nce, in + # pro diftextgina e en L fiipt the atie dable + # Thisalsoive ori larg HTMascr paste of p reay + # and rnat thedes: at's te a jav opy& bit its. t is Rubke }, + # alteeditrovi t th nerawith en c fair l ed thar ine-li, %w{ + # can pt p ayou to geser , th h a manua textasiequot %() + # scri a l ipt brow page witose ing 's eple %{}, + # Make scrin a TML textn th writt itulti of ter + ## 1. thisTML the H dit ly o lly:l, buas m use Ras t + # Run ut H via ly euick ficaiviauby hakestes. eral wan + # 2. outp its anualte q peciy trse R.rb m quo Gen nd we + # y ed to mitera by sactlecauntryouble for rs a + # Appl eed you g Rut exs, b. ele+d ithm acte + # 3. ll nlet ardins nouageientsing Algor char paperpplyg + # stiill regons ilangnvenmon ast ces: are nal ply ardin + # Youol w hingtatither e co com "A Feren els rigi sim regato + # to re trienny o quit the on diff r pix . O andailsnter + # e mole oo ma areourse asedtwo e ous. tionates detn ce o + # Onltiped tthatof c is bith sincalue rotardine toatio is n + # mumparors and ithm h, w ls, er v r of coot du rot here ns d + # coerat//, lgor Paet pixeract enteinput, but to r, tratio, an. + # op{}, on aAlan ing cha ng cthe as isspecion. ente opeinput two + # %W tati by blendinal ardiing ues th reunct on ctionthe ne or + # e roion" for orig reghift vale witer f tatirota of a li + # Thotat ort the tionut snate car_cen e roise hapeextr + # R supperve idera aboordixtra get stablockwhe s an ons. + # No pres consthingd coed e see ore terclon tting tatiugh + # - to nal any-basee neble, a mcoun lot nser e roltho + # itio sayto 0ng, wersi tingise/ds a by i oducd, a + # Addsn'trms undit rev elecockwepenible ] prstea + # - doensfor routpu in se clIt dvers pi/2t in ly to + # trategehe o care utivt. e re i/2, tex ical + # inke t tra onsecr ou mad [-pt the omat + # ma h exat c othen be weenstorible. aut + # wite theachon ca beto divers sted + # Evenantecel tati glesnd te re adju s. + # guar cane ro y ane tell b l be ment + # willn th Onlrang sti wil ele + # ofte gle.that ight idth text + # n anide ion m . W ble erialink + atiooutsrmat/ 13 entss. edita les. he scan l + Rotles nsfo:PI elemcell all tup . T we + # Ang traath: edit ter to eme) textthat + # the = M of harac ched graph ate uch her. + #NGLE ightre c.9em" atta al, rotD, sh ot + A e hesqua= "0 be seri me toue I eac + Linure GHT me to x, aphe uniqs to + # ens_HEI s na (y, d grme aation + #LINE clas "t" t of s anaphe rot + yle SS = a lis nateh grrent + # St_CLA as ordi eaciffe + EDIT nput he cogivess d + ad i ed td to acro + # Lo y neaddeheme + # onl is grap 0 + # Wemberame put _y = {|c| + # nuhe sd_in] ursor ster + # t loa = [ = c ine|_clu 8 + defdataor_x 0 ne{|lheme x % + cursal =h_li_grap 1 sor_r\n" ] + seri.eaceach= " "x +=" cur= "\ , c] + ARGFine. c =rsor_ "\t 8 - c = rial + l if cu c ==x +=" || x, se + lsifrsor_ "\n0 sor_ + e cu c ==x = 1 cur + lsifrsor_y += r_y, t + e cursor_ urso thay + cu [[c= 1 ilityed bext. + lse ta +=_x +1 obabollowal t + e daursor += e pron frigin + cerial ass. s thtatihe o + s of m easee roin t l be hat + end nter incrkwislts wilges thave + m ce nter clocresu heret ed We + } a fro n cee. a sa) o, taighion. + dat nter atio, i.e ver zer strotat + } turn n ce rotible vic frome.g.he r , + re tatio s asvers (or away er, er t tione. + nd e ro mase retion und cent aftcts: rotaitiv + e mput er ofll brota e rotionld betifa o. ox. ftern pos + # Co centon wiise ow wrotashouse ar zerng box aemai r + # ing tatilockw to hthe hey the d ofunding bon r othey + # Use roterc due ear an tduce nsteaf bounditati s atbilittion + # thcoun ely, ts nd tho re ty iter of bor ro factersiul op + # a unattifacaggegs t fini cenner oafte arti revusef f + # forte arore jthin e ino be cor and get theost er or + # Unsiblut mious itivon to before we losehe m centr fo + # vime o var postation ts be thatlso be t theedito + # coried owardf rotatinate e is we a to ause an and the t + # t nd tter of roordi thes andpears ll catesaddsm in tha + # Rou center ol co of ter,s ap s wienerrts rithd for + # - Set cenat al all cen mas cterly guppoalgo neer). + # - Seth th with ther of charat onso sion reatithe + # - suc ened d ofente. ing script alotat a gol e + # happnsteang cacts emovhis r thahe re iss to + # hat es i Usirtif nd rhy tditoent tther thi + # Wplacure.the a ng ais wan eplemsure for + # featite ertiich ave reimnot need + # desp t ins, whTo h to am any + # thashiftt. need. Ie is + # Note to g texill riptther + # massacin we wvascure + # repltes,ed jaot sa) + # deleerat am n(dat ze + # genl (Ienter ta.si + # tooet_cy = 0t| / da + #ef g = cach{|1] cy + d cxta.e+= t[0] ize, + da cx += t[ ta.s es. + cy / da inat + n cx oorda) + } etur to ccy, . + r ion cx, 2) gain + end rotatta, (a / X a + ply te(da:tan(a) | r in + # AprotaMath::sinp{|tnts. shea + def x = Math:a.maonte then + ry = n dater c cx Y, + retur Cent1] - cy r in me). + r # = t[0] - shead aphe eme. + x = t[ X, round , gr graph + y r in y).round erial ach + Shearx * x).roun x, s nd e + # -= (ry * y). (y, arou + x += (rx * ted ] pan + y -= ( updat[3] ne s + x urn 2], ith o + # Ret, t[ xt wfix) + [y, x L te_pre + HTM, id + } k ofdata0] n + d blocock(ata[ ].min + en rate e_bl = d t[1]].mi + Geneneratin_xt| _x, t[0] + # f ge_y, mch{|[min_y, + de minta.eax = [min >\n" + da min_y = ix}\" + min_ x pref + min_y {id_ + } x = min_=\"# r_y) + rsor_y = e id{|t| curso + cursor_"<preach y - + cuxt = ort.t < y * ( + teata.sx = or_y"\n" + d y, curs += = yin_x + if textor_y = m + cursor_x + curs [3] &" " + = t== "amp;" + end textext = "&= "< + ner_er_text xt =lt;"" ' + + in inner_tr_te= "&= "> '"> + if inninneext xt =gt;" SS +_s + + sif er_tr_te= "& x) +_CLA].to + el inninneext rsor_EDIT t[2 + sif er_t - cu"' + ix + + el inn (x ass=_pref + d " *n cl+ id low. + en += "<spa="' t + er be + ext '" id_tex numb + t 'nneran>" ial ns. + i</sp+ 1 ser colum + "= x re>" next. by + r_x n</p the airs them + urso + "\ find er p oup + c ext er, numbta) d gr + } rn t numbrialap(das an + retu ial f sewn_my row + nd serst or_dors b + e eacha liursoumbe + For rns te_cal n ]] + # Retuneraseri} |t| ] [t[2 + #ef geort = {ach{t[1]] += ] + d # Sumnsrt.emns[t[1] [t[2] + cola.socolumns[ ] = n. + dat if colu t[1] olum 0]]) . + e mns[ ch c [r[ ight + elscolu or ea 1] + he r by + rs f e - to t sortnext + end umbe .siz mber we the + al n r| [1, r l nu o if us + } seri [] |_, ip(r eria s, s get + Add ls =ach{ r.z xt s inateould ) + # erians.es += e ners. oordhat w [0]] + solumrial s d th pai n) c1, t ials + c se rial , finmberta) olum by [ser a + n se mberal nup(daw, cials 1] + extr + }etur l nuseriht_ma (ro ser e - one + r eria of _rig with all .siz get + end ch slistrsortartotate [2]}ials . e we ,' + r eas a e_cues snd r t| t ser airs sinc + '" + # Foturnerattuples a. map{|s[1, ue p) ine, o_s + # Re genput tuplbersort.erial valairsnewl 1].t + def# Input numta.sip(s keyal_ping + t[ + # inrial= dals.z s asserirail efix + # seals eria pairix, ut t + pr + serirn s mber(prefitho "' + retu l nu_mapies wate. '": + eriarsorentrtempl|t| _s + + end at st_cumap the .map{].to + Formnverate rom airs+ t[0 + # f coenerne fal_pfix + de # Gewliseri pre es. + # nurn "' + valu + ret' " nate + "\n ordi + } * f co) a[0] + d ge odata dat + en ranize(_x = + Getet_s minn_x + #ef gn_y,= min_y min 1 + d mix_x = mi|t| , x].max y + + max_y ach{t in_x, x].min min_ + mata.ex = = [max_x, y].max y - + da y, n_x = [min_y, y]. max_ + mix_x = [max_y 1, + man_y = [m n_x + + mix_y - mi + ma x_x + n ma + }etur + r ut + end _inp + loadty? ) a) GLE)) /td> + a = .emp (data(dat -ANNGLE ")}< > + datdatarn nter_size cy,y, A d> r> , "Ltd> }</td + if retu t_ce get cx,x, c /hea "><tdata)}</"R") + = geht = data,a, c le>< ng="4eft_ "M"ta, + end cy heig ate(e(dat /tit addiock(lata,t_da + cx,th, rototat est< ellpe_block(drigh + wid ta = = r te t 1" cerate_bllock( + t_dadata >Rota ng="{generatte_b l> + lefght_ OT" itle pacip">#{gennera labe + ri <<"Ed><t cells="top">##{ge le)</ + int <hea "1" align="toop"> "> togg or + prtml> der=t" valignn="t edit to l> errght, + <hody> bor"left" vvalig id="(ESC"><u izes-hei + <bableign="lefft" ox" dit nonet. minimline + <td align=="le heckble elay: tex hat sing + <td allignble>e="c>Enabdisplace . ne tcreap. + <ttd a</ta typdit"yle=" repor. anel he oy deerla + </tr>nputr="e" sters =cursct p ep tis bo ov + <p><il fohelpractmove sele nd keo thes t + <labeid=" chas = ab = s, also d lin + <div SCII keyft+to. "> aluean ae the ; + <li>Arrow shi und riptng vWe ccaus ght) + <li>Aab /+Z = vascpacio. ill tHei + <li>TCtrliv> xt/jaer-sratich wM");; offse + <<li>></d ="te lettect o muId("HT}" / p. + </ul typerentd aspt tontByHEIG dth + ipt iffesireg thalemeINE_ etWi + <scrry de deasin.getE"#{L 2) offs + // To thecrementht = 0.0 - p. + // tut ddocuHeig x += em";ght} + // bp = line= 0; 2; .0; + "{hei + var yle.t_x or =x < 2 = x / # + p.st bes_err 0; cingdth} + var min x = erSpa#{wi + var(var lett.abs( ) + for yle.Mathr > e + { p.ste = erro ; ; + var min_ r = e"em" + if( erro x + t_x;); }"; + { min__x = bes("L"IGHT + best ng =ByIdE_HE + Spaciment{LINt_x;"); T}"; + } tteretEle= "# besd("REIGH + e.lent.gight ng =tByINE_H; + } stylcumeneHeSpaciemen#{LIst_x + p.= doe.littergetEl = "= be + p style.leent.eighting + p.stylocumineHrSpac ta))} + p. = dle.lette e; t_da } + p.style.l tate.fals . (lefa))}ata)) + p.sty le sit = tion ns. _map(datht_d + p itabe_ed posi itio down_map(rig + / Wrnabl rsor ; pos rsor_down_map )} + /ar e t cu "M0" rsor e_cursor_down data) + v rrenor = t cu erate_cursor_ eft_)} ))} + / Cucurs o nex generate_cu ap(lata)_data + /var ng t "L", generat ht_map(dight + appi = map("M", gen _right_map(r + // Mdown rsor_map("R", ursor_right_m + var t_cursor_map( te_cursor_rig + { nvert_cursor_ nerate_cursor + #{convert_cu , generate_c + #{conver ("L", genera rs. + #{co ht = _map("M", ge ) pai + }; rig ursor_map("R" text + var rt_cursor_map nal + { onvert_cursor rigi + #{convert_c x, o n)) + #{conve uffi . (dow + #{c (id s []; ions tries + }; of ist = osit t.en ) + Listdo_l or p bjec ght) + // r un curs of O s(ri + va erse}; ue] ntrie + Rev = { {}; val ct.e + //r upft =[key, Obje + var lenst key; of + var(co e] = lue] + fo valu , va on. + { up[ [key ey; siti + onst = k e po ; + }or(c alue] . e sam tyle; + f ft[v okes$/; t th = style; + { le ystr!-~] rs a tyle = style + ed ke /^[ actele) x).style = s + } cepteys = char sty suffix).style + / AcditK for (id, (1);" + suffix).s + /ar e tyle tyle bstrd("L" + suffi + v et s setS d.sutById("M" + + // Stion = iementById("R . + func uffixetElementByI tion + { ar sent.getElemen posi + vocument.getEl n. sor + document.g itio s cur . 0"; + docum posd) viou tion ff808 + d rsoror(i pre posi nd:# ; + } te cuCurs t at rsor ); grou xt]) + Updan set ligh""); w cu f80"back erTe + // ctio highor, t ne :#80f = " .inn + fun lear curs ht a oundstyle ion. fix) + { // Ctyle( hlig ckgrid). osit suf + setS hig "bayId( me p "M" +t; + pdate id;sor,entB at sa yId(= text; + // Usor =(curElem ers entBext = text; + curStyle.get ractxt) ElemnerText = tex + setument cha, te .get).innerText + doc fort(id 1); umentffix).innerT + texteTex str( doc + suffix).in + } lace plac .subfix,("L" + suffix + Repon re = id[sufById("M" + su + //ncti fix ush(mentById("R" + fu r sufst.ptElementById + { vado_lit.getElement + uncument.getEle + document.ge it. [1]; + documen t ed ) ntry[1]; + do ecen = 0 t = entry[1]; + st r() th = rText = entry + } do moundo leng innerText = e + / Untion ist. ); ix).innerTex + /func do_l pop( suffix).inne + { f( un ist. L" + suffix). + i urn; do_l[0];Id("M" + suff + { ret = unntryntById("R" + + try = elementById(" + }ar enffixgetElementBy x); + var suent.getEleme suffi + vdocument.getEit ) ] + + document.e_ed or[0 + documnabl curs "; + if( e sor( line + { tCur "in + se us. lay = + } statt() it; disp + dit _edi e_ed yle. ; + } ge eggle nabl ).st one" + Chann to = !e) elp" = "n + //nctio dit dit ; Id("h play ; + fu le_ele_e sor)ntBy .dis edit + { enabenab (curleme tyle able_ ) + if( rsorgetE ").s = en S}") + { etCuent. ; help ked CLAS + socum "")yId(" chec DIT_ + d sor,entB t"). ("#{E + } e (curElem ("edi Name + els tyle.get ById lass + { setSment ment sByC { + docu tEle ment => + t.ge s. etEle ent) + } umen enernt.g (ev + doc listcume ick", + ent f do ("cl + } d ev t o ener ) => { + // Adonst Listedit nt) ) ) + for(c ventble_ id); (eve "Z" + { addE ena r(t. n", y == + t. if( urso ydow t.ke + { setC r("ke even + tene || + } tLis) e" ) = "z" + ); Evendit Escap ey = + } .addle_e == " nt.k ) ) + } mentenab key (eve "Z" + docuf( ! ent. (); && y == + i ( ev edit rlKey t.ke + { if gle_ t.ct even + { tog even " || + if( = "z + }lse ; ey = + e do() nt.k + { un (eve + n; y && s) ) + }etur rlKe tKey + r t.ct (edi ); + } even match .key + if( (); key. vent + { undo ent. or, er]); ) + ( ev curscurso wUp" e" ) + } e if ext(ght[ Arro spac + els aceTr(ri == " Back + { replurso .key ); n" ) == " + setC vent rsor] wDow key + f( e p[cu Arro vent. ) + } se i or(u == " || e " " + el Curs .key r]); ft" == + { set vent curso owLe .key + f( e own[ "Arr event + } se i or(d y == ; || M"} + el Curs t.ke or]) ght" ": "L"}; + { set even [curs owRi , "R": " + if( left "Arr "L", "R + } lse sor( y == ); "M": "R" + e tCur t.ke sor] "R", "M":; + { se even t[cur b" ) L": "M", r(1) + if( righ "Ta ? {"L": subst + }lse sor( ey == Key : {"sor. + e tCur nt.k hift cur { + { se eve ent.s ]] + ) => + if( = ev or[0 vent + }else ext [curs " ) , (e + { ar n nextsor); cape ick" + v r = (cur "Es ("cl + ursorsor ey == ener + cetCu nt.k tList + s eve ); Even + } if( dit( (); .add + else le_e fault it") + { togg ntDe ("ed + reve tById + } nt.p emen + eve etEl(); + ; nt.gedit + })cumegle_ + do tog + ; pt> > + })scri html + </ y></ + /bod + <OT + E diff --git a/sample/trick2025/02-mame/authors.markdown b/sample/trick2025/02-mame/authors.markdown new file mode 100644 index 0000000000..0e420fdf5d --- /dev/null +++ b/sample/trick2025/02-mame/authors.markdown @@ -0,0 +1,3 @@ +* Yusuke Endoh + * mame@ruby-lang.org + * cctld: jp diff --git a/sample/trick2025/02-mame/entry.rb b/sample/trick2025/02-mame/entry.rb new file mode 100644 index 0000000000..d5de370dc9 --- /dev/null +++ b/sample/trick2025/02-mame/entry.rb @@ -0,0 +1,34 @@ +From:pd <pd-@example.com> (`) +Date:Wed,01 Jan 2025 00:00:00 +0000 +Subject:[PATCH] +an(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#TRICK2025]} + +--- /dev/null ++++ pd.rb +@@ -0,0 +1,27 @@ ++%;`);;BEGIN{eval$s=%q[eval(%q[F=File;puts((dup)?(q="%;`);;BEGIN ++{eval$s=%q[#$s]}";U,*,V=R=(0..33.0).map{|t|q.gsub(/./){i=$`.siz ++e;c=(i/64*2i-26i+i%64-31)*1i**(t/16.5);x,y=c.rect;r=c.abs;r<13? ++4<=r&&r<6&&x>-4||-5<x&&x<=-3&&-6<y&&y<11??.:?X:$&}};B,A="---|%s ++\n+++|%s\n@@|-%s,%s|+%s,%s|@@\nFrom:pd|<pd-@example.com>|(`)\nD ++ate:%a,%d|%b|%Y|%T|%z\nSubject:[PATCH]|".tr(?|,z="\s")[/@.*\n/] ++,$`;(i=R.index(q))?(S,T=i<33?R[i,(f=->i{(Time.gm(2025)+86400*i) ++.strftime$'};o=f[i+1]+(fXXXXXXXXXXXXXXX[0]+q[/.*\z/]+?\n*2+A%[" ++/dev/null",v="pd.rb"]+XXXXXXXXXXXXXXXXXXXB%[0,0,1,27]+U.gsub(/^ ++/,?+)).lines[-i-2],EXXXXXXXXXXXXXXXXXXXXXXX,a=A%[v,v];V<<"\n(`\ ++n#{a+B%[0,0,1,1]}+dXXXXXXXXXXXXXXXXXXXXXXXXXup=(`)";2)]:($*.siz ++e!=2&&abort(["usagXXXXXXXXX.........XXXXXXXXXe:",$0,F,F]*z);$*. ++map{o=A%$*;F.read(XXXXXXXXX..XXXXXX..XXXXXXXX_1)});a=[i=0]*v=(s ++=[s]+S.lines).sizeXXXXXXXXX..XXXXXX..XXXXXXXX;c=b=s.map{c=_1&&[ ++c,?-+_1,i+=1]||0};XXXXXXXXX..XXXXXX..XXXXXXXXT.lines{|t|s.map{| ++s|a<<((s)?[x=a[-1]XXXXXXXXX.........XXXXXXXXX,y=a[-v]].max+((f= ++s==t)?1:0):0);c,d=(XXXXXXXX..XXXXXXXXXXXXXXXf)?[v+1,z+t]:s&&(x> ++y)?[1,?-+s]:[v,?++t]XXXXXXX..XXXXXXXXXXXXXX;b<<[b[-c],d,i+=1]}} ++;c=b[-1].flatten;b=c[(XXXXX..XXXXXXXXXXXX1..)%2];(b.map{_1[0]}* ++E).scan(/\s{,3}([-+]\s{,XXXXXXXXXXXXXXX6})*[-+]\s{,3}/){n=c[2*i ++=$`.size];o=o,B%[n%v+1-1/v,(m=c[2.*i+j=$&.size]-n)%v,T>""?n/v+1 ++:0,m/v],b[i,j]}):(o=[];a,b=[A,B].map{_1.sub(?+){'\+'}%(['(\S+)' ++]*4)};$<.read=~//;F.write$2,(s=F.readlines$1;o<<[:patching,F,$2 ++]*z;(*,n,i,m=[*$~].map{_1.to_i};n+=m;($'=~/\A((-)|\+)?(.*\n)/;$ ++2?s[i-=1,1]=[]:$1?s[i-1,0]=$3:n-=1;i+=1;n-=1)while+n>0)while/\A ++#{b}/=~$';s*E)while$'=~/^#{a}/);o):([*[?l]*799,1].shuffle*E).sc ++an(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#TRICK2025]} diff --git a/sample/trick2025/02-mame/remarks.markdown b/sample/trick2025/02-mame/remarks.markdown new file mode 100644 index 0000000000..8be86ebc2d --- /dev/null +++ b/sample/trick2025/02-mame/remarks.markdown @@ -0,0 +1,141 @@ +# A Lesser "Patch" Program + +This program is a minimalistic version of the traditional "patch" command, which looks like a patch. + +## Usage as a "Patch" Command + +The program reads a unified diff file from standard input and applies the changes to the specified files. + +To apply `test.patch` to `sample.rb`, use the following commands: + +``` +$ cp sample.orig.rb sample.rb +$ ruby entry.rb < test.patch +``` + +After running these commands, verify that `sample.rb` has been modified. + +## Usage as a Patch File + +Interestingly, this program is not just a patch-like tools -- it *is* a patch. +This duality allows it to be applied like a regular patch file. + +The following will create a file named pd.rb. + +``` +$ patch < entry.rb +``` + +Alternatively, you can achieve the same result using `entry.rb`: + +``` +$ ruby entry.rb < entry.rb +``` + +The generated `pd.rb` produces a new patch. + +``` +$ ruby pd.rb +``` + +The produced patch is self-referential, targeting `pd.rb` itself. +To apply it: + +``` +$ ruby pd.rb | ruby entry.rb +``` + +You'll notice the `p` logo rotates slightly counterclockwise. + +The modified `pd.rb` outputs the patch for itself again, apply the patch repeatedly--a total of 33 times! + +## From `p` to `d` + +The center `p` logo symbolizes a "patch." +When rotated 180 degrees, it resembles a `d`, signifying a transformation in functionality. +`pd.rb` now operates as a simplified "diff" command: + +``` +$ ruby pd.rb +usage: pd.rb File File + +$ ruby pd.rb sample.orig.rb sample.rb +--- sample.orig.rb ++++ sample.rb +... +``` + +## Integration with Git + +The patches are compatible with Git's `git am` command, which imports patches in mbox format. + +Start fresh by removing `pd.rb` and initializing a Git repository: + +``` +$ rm -f pd.rb +$ git init +Initialized empty Git repository in /home/... +``` + +And import `entry.rb` as a patch to the repository: + +``` +$ git am --committer-date-is-author-date entry.rb +Applying: +(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#_TRICK2025_]} +applying to an empty history +``` + +Verify the commit history: + +``` +$ git log +commit 1e32693f11c1df77bd797c7b3e9f108a3e139824 (HEAD -> main) +Author: pd (`) <pd-@example.com> +Date: Wed Jan 1 00:00:00 2025 +0000 + + +an(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#TRICK2025]} +``` + +Notice that the Author and Date are properly set. + +To apply subsequent patches: + +``` +$ for i in `seq 0 32`; do ruby pd.rb | git am --committer-date-is-author-date; done +``` + +*(A fun details: you will see the `b` logo!)* + +Now, view a commit history by the following command: + +``` +$ git log --oneline +``` + +You will rediscover the original `entry.rb` unexpectedly. + +If you set `--committer-date-is-author-date` appropriately, you should be able to run the output of `git log --oneline` as is. + +Try this unusual command: + +``` +$ git log --oneline | ruby - test.patch +``` + +## A Little Something Extra + +Interestingly, `pd.rb` -- functioning as a diff command -- is a patch to itself. +Reveal hidden details with: + +``` +$ ruby entry.rb pd.rb +$ ruby pd.rb +``` + +Can you spot the difference? + +## Limitations + +* I tested it with ruby 3.3.6, git 2.45.2, and GNU patch 2.7.6. +* No error check at all. The lesser patch do not care if there is a discrepancy between what is written in the patch and the input file, and will write over the existing file without prompt. +* It is assumed that the text files have a new line at the end. diff --git a/sample/trick2025/02-mame/sample.orig.rb b/sample/trick2025/02-mame/sample.orig.rb new file mode 100644 index 0000000000..3d880b387d --- /dev/null +++ b/sample/trick2025/02-mame/sample.orig.rb @@ -0,0 +1,8 @@ +def add(a, b) + a + b +end + +if __FILE__ == $0 + result = add(3, 5) + puts "Three plus five is #{ result }" +end diff --git a/sample/trick2025/02-mame/test.patch b/sample/trick2025/02-mame/test.patch new file mode 100644 index 0000000000..0a63ae8a4c --- /dev/null +++ b/sample/trick2025/02-mame/test.patch @@ -0,0 +1,16 @@ +--- sample.rb ++++ sample.rb +@@ -2,7 +2,13 @@ + a + b + end + ++def sub(a, b) ++ a - b ++end ++ + if __FILE__ == $0 + result = add(3, 5) + puts "Three plus five is #{ result }" ++ result = sub(5, 3) ++ puts "five minus three is #{ result }" + end diff --git a/sample/trick2025/03-tompng/authors.markdown b/sample/trick2025/03-tompng/authors.markdown new file mode 100644 index 0000000000..26ebe24da6 --- /dev/null +++ b/sample/trick2025/03-tompng/authors.markdown @@ -0,0 +1,3 @@ +* Tomoya Ishida (tompng) + * tomoyapenguin@gmail.com + * cctld: jp diff --git a/sample/trick2025/03-tompng/entry.rb b/sample/trick2025/03-tompng/entry.rb new file mode 100644 index 0000000000..0de2244979 --- /dev/null +++ b/sample/trick2025/03-tompng/entry.rb @@ -0,0 +1,74 @@ +eval->{%w[u=*? a..?i;l=*?j..? r;o=*?s..?z,?_ +;m='#-*&|^`!@$ '.chars;s=[[3] ,[0,1,3,4,6],[ +1,5],[1,4],[0, 4,6],[2,4],[2] ,[1,3,4,6],[], + [4], ];a= (0.. 7).m ap{[ + ?;*_ 1+'a 4',: a1,? x*(_ + 1+2) ]*"T /#{? x.*6 7-_1 + }/x; "};v =([c =[?x *150 + ]*4, a.reverse,[[6, 3,0].map{"a#{_ + 1}T/ #{?x*15}/x"}*( ?;*42)+';xx']* + 30,a .map{_1.tr'14' ,'25'},c,]*n=$ + /).g sub( /(^| ;)(; + *);/ ){$1 +?x* $2.s + ize+ ?;}; p,e= [0,1 + ].ma p{|t |g=( ["(m + fT/' /;#{a=(0..9).m ap{"f#{_1}T/l# + {_1} =1./"}*?;};C"' ;#{a.tr'l',?u} + ;?C" ",(0..9).map{| i|a="l#{i}T/'/ + + +;C"' ;";b ="#{o[i-1]+?=i fTi>0}%+";(1.. +9).m ap{a <<l[_1-1]+"T/% #{c=m[_1]}/;"; +b<<c +";# {(d=_1+i)>10?' ca='+o[d-11]:d +>9?' ca': o[d- 1]}= +%"+c };a+ b+[m [1.. +],?+ ,?"] *';? '}," +caT/ '/;C "';" +(1. +.8).map{u[8-_1 ]+"T/#{u[9-_1] }=1./;"}*''+u[ +0]+h='=1;?"',( 1..9).map{|i|" u#{i}T/'/;C"'; +"+(0..8-i).map {u[8-i-_1]+"T/ #{u[8-_1]}=1./ + ;"}* ''+u [i-1 ]+h} + ]*?; ).sp lit( /([^ + ;]+; )/); ((0. .43) + .map {|y| c='' ;q=- + >{a= (y-22).abs;b=( c.size+_1-78). + abs; [a<7&&b<59||b< 15,(b-30).abs< + 14][ t]};110.times{ c+=q[8]?g.shif + + + t||? ;:q[-t]??;:'T' };c.gsub(';T', + 'TT' ).rstrip}*n).g sub(/(;|T)(;;+ + )(;| $)/){$1+'/'+?x *($2.size-2)+' + /'+$ 3}}; F=Fi + le;1 0.ti mes{ + |i|a ="(n fT/m + f=l# {i}= '/;n + f=f# {i}=?';def/("+ s[i].map!{"a#{ + _1}" }*','+')=(';F. write"#{i}",a+ + ?x*( 150-a.size)+n+ v[..-5]+'))&&' + +n}; a,*b ="/) + &&de f((C nCn< + <A"; c=") )./( + ";d= 'T}' ,?A, + '__= <<B';u.map{|v| b<<v+"TT%(T<<# + {v}T )TT";d=d,v,"AC n#{v}=<<B"};o. + zip( l,m){a+=?;+_1+ "T/%#{_3}/";c+ + + +=(_3[?#]||?#+_ +3)+"))./("+_2+ +?,};F.write'+' +,n*2 6+[p [..- +10]+ (a+c ).tr ('!@',%("')).g +sub( /%([ '"`] )/,){$1},'#{TT +T'+b *';T T'+d *n,?B,')=']*n+ +n;a, b=[u ,o].map{|v|(0. +.8). map{ t=s[9-_1];t[0] +&&t+ =[1] ;v[8-_1]+"T/#{ +t*?= }#/" }*?; +';a3='+?x*25} +;F.w rite '=', [n*26]*2*e+a+n ++v+n +(b+ n+v) .tr(?a,?b)[..- +9]+' )if~ exit +'+n].join.tr(' +TRICK',_1)}[+" +\x2025"<<-?\\] diff --git a/sample/trick2025/03-tompng/remarks.markdown b/sample/trick2025/03-tompng/remarks.markdown new file mode 100644 index 0000000000..7f3f4ac6cf --- /dev/null +++ b/sample/trick2025/03-tompng/remarks.markdown @@ -0,0 +1,146 @@ +### Remarks + +Run it with no argument. It will generate 12 files: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + and =. + +```sh +ruby entry.rb +``` + +Concat and syntax highlight them. + +```sh +cat 2 0 + 2 5 = | ruby -run -e colorize +cat 4 + 1 5 + 4 + 1 8 = | ruby -run -e colorize +``` + +I confirmed the following implementations/platforms: + +* ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +MN +PRISM [arm64-darwin22] +* ruby 3.3.0 (2023-12-25 revision 5124f9ac75) +YJIT +MN [arm64-darwin22] + +### Description + +Did you know that Ruby syntax can perform additive operations on two-digit numbers without Ruby runtime? This entry demonstrates a syntax level computation of Ruby grammar. + +`ruby entry.rb` will generate 12 files: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + and =. +These files constitute a calculator system that runs on Ruby parser. + +To calculate `6 + 7`, concat `6`, `+`, `7` and `=`. + +```sh +cat 6 + 7 = +``` + +The concatenated output is a Ruby script that does nothing. It is also an ASCII art of `â–ˆ + â–ˆ = ██` rotated 90 degrees. +Now, let's try syntax highlighting that code. + +```sh +cat 6 + 7 = | ruby -run -e colorize +``` + +Wow! You can see the calculation result `6 + 7 = 13` as a colorized ASCII art! + +This system can also add more than two numbers. All numbers should be one or two digits, and the answer should be less than 100. + +```sh +cat 3 1 + 4 + 1 5 + 9 = | ruby -run -e colorize +cat 1 + 2 + 4 + 8 + 1 6 + 3 2 = | ruby -run -e colorize +cat 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 0 = | ruby -run -e colorize +``` + +If the syntax highlighting is hard to see, use this command to change the terminal color. + +```sh +printf "\e]11;#000000\a\e]10;#333333\a\e]4;1;#ffaaaa\a" +``` + +### Internals + +To perform calculation, you need a storage and a control flow statement. +Local variable existence can be used as a storage. +Ruby syntax provides conditional local variable definition and local variable reset with state carry over which can be used as a control flow statement. + +#### Conditional Local Variable Definition + +Ruby syntax can define new local variables conditionally. + +```ruby +# Defines x and y if a is defined +a /x = y = 1./ +# Defines x and y if a is not defined +a /1#/; x = y = 1 +# Defines x or y depend on the existence of local variable a +a /(x=1);'/;(y=1);?' +``` + +#### Local Variables Reset + +Local variables can be cleared by creating a new `def` scope. + +```ruby +x = y = z = 1 +def f +# x, y, z are cleared +``` + +#### State Carry Over + +Some state should be carried over to the next `def` scope. There are two tricks to do it. + +```ruby +a /%+/i; b /%-/i; def f(x)# +; def f(y) # -; def f(z) +``` + +```ruby +a %(<<A); b %(<<B); def f +x=<<C +A +y=<<C +B +z=<<C +C +``` + +In both examples above, local variable defined in the new scope will be: + +```ruby +x # if both a and b are not defined +y # if a is defined +z # if b is defined +``` + +Combining these two tricks, Ruby syntax can carry over two states to the next `def` scope. In this system, two states represents upper digit and lower digit. + +### File Structure + +```ruby +# File 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 +(code) && +``` + +```ruby +# File + +(code) && def f(arg)= +``` + +```ruby +# File = +(code) if exit +``` + +```ruby +# cat 1 2 + 3 + 4 5 = +(one) && +(two) && +(plus) && def f(arg)= +(three) && +(plus) && def f(arg)= +(four) && +(five) && +(equal) if exit +``` + +### Limitation + +Number to be added must be one or two digits. +Answer of the addition must be less than 100. diff --git a/sample/trick2025/04-tompng/authors.markdown b/sample/trick2025/04-tompng/authors.markdown new file mode 100644 index 0000000000..26ebe24da6 --- /dev/null +++ b/sample/trick2025/04-tompng/authors.markdown @@ -0,0 +1,3 @@ +* Tomoya Ishida (tompng) + * tomoyapenguin@gmail.com + * cctld: jp diff --git a/sample/trick2025/04-tompng/entry.rb b/sample/trick2025/04-tompng/entry.rb new file mode 100644 index 0000000000..881c1af871 --- /dev/null +++ b/sample/trick2025/04-tompng/entry.rb @@ -0,0 +1,36 @@ + $c=%q@E=" + \e[4%d;37m%s\e[m" + ;n=32.chr;pu ts"\e + [H\e[J#{$c=n*54+' $c=% + q'+[64.chr]*2*$c+';e val$ + c.'+n*10+"\n"+n*57+"spl it*' + '"+n*15}";n=l=0;R=->y=0 {n+=1 + ;l=$c.lines. map{|m|m=(0..79).chunk{380-n+ + 36*Math.sin(0.04.*it-n )<9*y}.map{a=_2.map{m[it]}*'' + ;_1&&E%[6,a]||a}*'';m!=l[~-y +=1]&&$><<"\e[#{y}H#{m}\e[37H + ";m}};N=(Integer$* [-1]resc ue+30)*H=44100;alias:r:rand + ;F=->e,w=1{a=b=c=0;d=( 1-e)**0 .5*20;->v=r-0.5{a=a*w*e+v + ;b=b*w*e*e+v;d.*a-2*b+c=c*w *e**3+ v}};A=->u,n,t{(0..n). + map{|i|u=u.shuffle.map{|w|R[]; a=u.s ample;b,c,d=[[0.5 + ,(0.2+r)*H/3*1.1**i,[[1+r/10,1+r/ 10]][ i]||[1.2+ + r/10,1.3+r/5]],[0.3,r*H/2,[1,1+r/5 ]]][t +];e,f=d.shuffle;g=b+r;h=b+r;(0..[w. size/e, a.size/f ++c].max).map{g*(w[it*e]||0)+h*(a[[it-c,0].ma x*f]||0)}}}};j=A[A +[(0..9).map{a=F[0.998,1i**0.02];(0..28097).m ap{a[].real.*0.1**(8.0*i +t/H)-8e-6}},14,0].transpose.map{|d|a=[0]*3e3 ;15.times{|i|R [];b=r + (3e3);d[i].each_with_index{a[c=_2+b]=(a[c] ||0)+_1*0.63**i}} ;a},9, + 1][4..].flatten(1).shuffle;y=(0..3).map{F[ 1-1e-5]};m=[-1,1].map {[F[1 + -1e-4],F[1-5e-5],it]};u=v=w=0;k=[],[],[] ;z=F[0.7,1i**0.5];File.o pen($ + *.grep(/[^\d]/)[0]||'output.wav','wb') {|f|f<<'RIFF'+[N*4+36,'WA VEfmt + ',32,16,1,2,H,H*4,4,16,'data',N*4].p ack('Va7cVvvVVvva4V');N.tim es{| + i|$><<E%[4,?#]if(i+1)*80/N!=i*80 /N;t=[i/1e5,(N-i)/2e5,1].min;a,b,c=k + .map{it.shift||(j[20*r,0]=[g =j.pop];a=1+r/3;it[0..]=(0..g.size).m + ap{g[it*a]||0};0)};u=u *0.96+r-0.5;v=v*0.99+d=r-0.5;w=w*0.8+d + ;x=(z[].*1+0 .59i).imag;e=y.map(&:[]);f.<<m.map{|o, + p,q|r=a+(b+c)/2+(b-c)*q/5;s=o[r.abs] + ;r=t*t*(3-2*t)*(r+s*w/1e4+p[s]*x/1 + e7+[[u,0],[v,1]].sum{_1*1.5**(e[ + _2]+q*e[_2+2]/9)}/32)/9;r/(1 + +r*r)**0.5*32768}.pack'v + *'}};puts@;eval$c. + split*'' diff --git a/sample/trick2025/04-tompng/remarks.markdown b/sample/trick2025/04-tompng/remarks.markdown new file mode 100644 index 0000000000..b2d848c07c --- /dev/null +++ b/sample/trick2025/04-tompng/remarks.markdown @@ -0,0 +1,43 @@ +# Seashore - Nature Sound + +Listen to the relaxing sound of ocean waves generated by Ruby. + +## Usage + +```sh +ruby entry.rb +ruby entry.rb seashore.wav 60 +``` + +The default filename is `output.wav` and the default duration is 30 seconds. + +Tested with ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +MN +PRISM [arm64-darwin22] + +## Noise + +Noise sound is created by applying low-pass/band-pass filter to a white noise signal. +Volume of the noise should change over time. This is also calculated by using low-pass filter. + +## Wave + +Sound of a single ocean wave is composed of hundreds of water splash sounds. +Each water splash sound is composed of thousands of water drops and bubbles. +This program creates this complicated sound by repeating sound mixing. + +```ruby +sound2 = mix(sound1.change_pitch(rand), sound1.change_pitch(rand).delay(rand)) +sound4 = mix(sound2.change_pitch(rand), sound2.change_pitch(rand).delay(rand)) +... +sound32768 = mix(sound16384.change_pitch(rand), sound16384.change_pitch(rand).delay(rand)) + +splash1 = mix(sound1.delay(rand), sound2.delay(rand), sound4.delay(rand), ..., sound16384.delay(rand)) +splash2 = mix(splash1.change_pitch(rand), splash1.change_pitch(rand).delay(rand)) +splash4 = mix(splash2.change_pitch(rand), splash2.change_pitch(rand).delay(rand)) +... +splash1024 = mix(splash512.change_pitch(rand), splash512.change_pitch(rand).delay(rand)) + +wave_sound = [splash32, splash64, ..., splash1024].sample +``` + +This kind of repetition is often used in fractal rendering. In other words, this operation is rendering a fractal shape to the spectrogram canvas. +It's an efficient way to create complex structure with low computational cost. diff --git a/sample/trick2025/05-tompng/authors.markdown b/sample/trick2025/05-tompng/authors.markdown new file mode 100644 index 0000000000..26ebe24da6 --- /dev/null +++ b/sample/trick2025/05-tompng/authors.markdown @@ -0,0 +1,3 @@ +* Tomoya Ishida (tompng) + * tomoyapenguin@gmail.com + * cctld: jp diff --git a/sample/trick2025/05-tompng/entry.rb b/sample/trick2025/05-tompng/entry.rb new file mode 100644 index 0000000000..4d30c5b5a9 --- /dev/null +++ b/sample/trick2025/05-tompng/entry.rb @@ -0,0 +1,118 @@ +module ReadableFizzBuzz + module Chain + end +end + +include ReadableFizzBuzz + +Chain::Itself = Chain + +module Chain::Itself + module Void + A = B = C = D = E = F = G = H = I = J = K = L = M = Void + N = O = P = Q = R = S = T = U = V = W = X = Y = Z = Void + + module Set + end + + module Put + end + + module WriteBack + end + + module Not + include Void + end + end + + module Off + include Void + end + + module Nil + A = B = C = D = E = F = G = H = I = J = K = L = M = Off + N = O = P = Q = R = S = T = U = V = W = X = Y = Z = Off + end + + module Next + include Nil + end + + module Current + include Nil + + Not = Off + Set = Put = Next + WriteBack = Current + end + + True = If = Current + On = Next + + module On + INT = 1 + FIZZ = 'Fizz' + BUZZ = 'Buzz' + PREFIX = '0b' + FORMAT = "%d%s%s\n" + NEXT = __FILE__ + end + + module Off + INT = 0 + FIZZ = BUZZ = nil + PREFIX = '0b1' + FORMAT = "%2$s%3$s\n" + NEXT = '/dev/null' + Not = True + end + + module Initial + C = D = True + end + + module ReadableFizzBuzz::Chain::Current + include Initial + end + + If::C::Set::E = If::E::Set::F = If::F::Set::C = On + If::D::Set::G = If::G::Set::H = If::H::Set::I = If::I::Set::J = If::J::Set::D = On + If::F::Not::J::Not::Set::B = On + If::K::Not::Set::K = On + If::K::WriteBack::L = True + If::L::Not::M::Set::M = On + If::L::M::Not::Put::M = On + If::L::M::WriteBack::N = True + If::N::Not::O::Set::O = On + If::N::O::Not::Put::O = On + If::N::O::WriteBack::P = True + If::P::Not::Q::Set::Q = On + If::P::Q::Not::Put::Q = On + If::P::Q::WriteBack::R = True + If::R::Not::S::Set::S = On + If::R::S::Not::Put::S = On + If::R::S::WriteBack::T = True + If::T::Not::U::Set::U = On + If::T::U::Not::Put::U = On + If::T::U::WriteBack::V = True + If::V::Not::W::Set::W = On + If::V::W::Not::Put::W = On + If::V::W::WriteBack::X = True + If::X::Not::Y::Set::Y = On + If::X::Y::Not::Put::Y = On + If::X::Y::WriteBack::Z = True + If::Z::Not::Set::A = On +end + +module Chain::Chain + Current = Chain::Next +end + +include Chain + +module Chain::Current + NUMBER = A::PREFIX, Y::INT, W::INT, U::INT, S::INT, Q::INT, O::INT, M::INT, K::INT + printf B::FORMAT, NUMBER.join, C::FIZZ, D::BUZZ + load A::NEXT +end diff --git a/sample/trick2025/05-tompng/remarks.markdown b/sample/trick2025/05-tompng/remarks.markdown new file mode 100644 index 0000000000..adb4bf4df8 --- /dev/null +++ b/sample/trick2025/05-tompng/remarks.markdown @@ -0,0 +1,106 @@ +### Remarks + +Just run it with no argument: + +```sh +ruby entry.rb +``` + +I confirmed the following implementations/platforms: + +- ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +MN +PRISM [arm64-darwin22] +- ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [aarch64-linux-musl] + +### Description + +Readability is important even for a simple fizz buzz program. + +These are the major ingredients of a spaghetti that makes program tasty and valuable but unreadable. + +- Many class definitions +- Many method definitions +- Many method calls +- Many variables +- Conditional branches + +These are what is acceptable for a readable program. + +- Many modules: Using only a single module in a program is not good. +- Many constants: Better than magic numbers. +- Module#include: Mixins are what module is for. +- Many file loads: Usually better than loading a large file only once. +- Minimal method calls: Needed for printing output. + +This program is doing something slightly difficult in the last few lines: print output and load ruby program. +In contrast, the rest part of this program is extremely simple and easy. Module definition, constant definition and module inclusion. That's all. + +### Internals + +Called methods + +- `Module#include` +- `Array#join` +- `Kernel#printf` +- `Kernel#load` + +Deeply nested module chain to avoid constant reassignment + +```ruby +10.times do + module Root + module Chain + module X; end + module Y; end + module Z; end + end + end + include Root + + module Chain::Chain + # Not a constant reassignment because Chain::Chain is always a new module + X = Chain::Y + Y = Chain::Z + Z = Chain::X + end + include Chain + p x: X, chain: Chain +end +``` + +Constant allocation + +| Constant | Purpose | +| ---------------------- | ----------------------- | +| A | Loop condition | +| B | Format (!Fizz && !Buzz) | +| C, E, F | Fizz rotation | +| D, G, H, I, J | Buzz rotation | +| K, M, O, Q, S, U, W, Y | Iteration bits | +| L, N, P, R, T, V, X, Z | Temporary carry bits | + +Instruction sequence with constant lookup magic + +```ruby +# B = 1 if A +If::A::Set::B = On + +# B = 1 if !A +If::A::Not::Set::B = On + +# C = 1 if !A && B +If::A::Not::B::Set::C = On + +# C = 1 if !A && !B +If::A::Not::B::Not::Set::C = On +``` + +Loop with `load __FILE__` + +```ruby +# A::NEXT is __FILE__ or '/dev/null' +load A::NEXT +``` + +### Limitation + +Needs `/dev/null` diff --git a/sample/trick2025/README.md b/sample/trick2025/README.md new file mode 100644 index 0000000000..1d71f54620 --- /dev/null +++ b/sample/trick2025/README.md @@ -0,0 +1,16 @@ +This directory contains the top-five entries of +the 5th Transcendental Ruby Imbroglio Contest for rubyKaigi (TRICK 2025). + +THESE ARE BAD EXAMPLES! You must NOT use them as a sample code. + +* 1st: "Most Revolutionary" - Don Yang +* 2nd: "Most Useful" - Yusuke Endoh +* 3rd: "Most Arithmetic" - Tomoya Ishida +* 4th: "Best ASMR" - Tomoya Ishida +* 5th: "Most Maintainable" - Tomoya Ishida + +These files are licensed under MIT license. + +For the contest outline and other winning entries, see: + +https://github.com/tric/trick2025 diff --git a/sample/trojan.rb b/sample/trojan.rb index 3a35ac21c2..cea0dae098 100644 --- a/sample/trojan.rb +++ b/sample/trojan.rb @@ -5,9 +5,9 @@ path = ENV['PATH'].split(File::PATH_SEPARATOR) for dir in path if File.directory?(dir) for f in d = Dir.open(dir) - fpath = File.join(dir, f) + 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/tsvr.rb b/sample/tsvr.rb index 52cdd32dce..2fa6c87ef9 100644 --- a/sample/tsvr.rb +++ b/sample/tsvr.rb @@ -3,7 +3,7 @@ require "socket" -gs = TCPserver.open(0) +gs = TCPServer.open(0) addr = gs.addr addr.shift printf("server is on %s\n", addr.join(":")) diff --git a/sample/uumerge.rb b/sample/uumerge.rb index 2576bcb864..1b81582c24 100644 --- a/sample/uumerge.rb +++ b/sample/uumerge.rb @@ -15,7 +15,7 @@ while line = gets() if out_stdout out = STDOUT else - out = open($file, "w") if $file != "" + out = File.open($file, "w") if $file != "" end out.binmode break 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/httpsd.rb b/sample/webrick/httpsd.rb deleted file mode 100644 index 9d82ef36cf..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("server.key"), - # :SSLCertificate => OpenSSL::X509::Certificate.new("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 diff --git a/sample/wsdl/amazon/AmazonSearch.rb b/sample/wsdl/amazon/AmazonSearch.rb deleted file mode 100644 index 1027592d85..0000000000 --- a/sample/wsdl/amazon/AmazonSearch.rb +++ /dev/null @@ -1,4693 +0,0 @@ -# http://soap.amazon.com -class ProductLineArray < Array - # Contents type should be dumped here... - @@schema_type = "ProductLineArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class ProductLine - @@schema_type = "ProductLine" - @@schema_ns = "http://soap.amazon.com" - - def Mode - @mode - end - - def Mode=(value) - @mode = value - end - - def ProductInfo - @productInfo - end - - def ProductInfo=(value) - @productInfo = value - end - - def initialize(mode = nil, - productInfo = nil) - @mode = mode - @productInfo = productInfo - end -end - -# http://soap.amazon.com -class ProductInfo - @@schema_type = "ProductInfo" - @@schema_ns = "http://soap.amazon.com" - - def TotalResults - @totalResults - end - - def TotalResults=(value) - @totalResults = value - end - - def TotalPages - @totalPages - end - - def TotalPages=(value) - @totalPages = value - end - - def ListName - @listName - end - - def ListName=(value) - @listName = value - end - - def Details - @details - end - - def Details=(value) - @details = value - end - - def initialize(totalResults = nil, - totalPages = nil, - listName = nil, - details = nil) - @totalResults = totalResults - @totalPages = totalPages - @listName = listName - @details = details - end -end - -# http://soap.amazon.com -class DetailsArray < Array - # Contents type should be dumped here... - @@schema_type = "DetailsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class Details - @@schema_type = "Details" - @@schema_ns = "http://soap.amazon.com" - - def Url - @url - end - - def Url=(value) - @url = value - end - - def Asin - @asin - end - - def Asin=(value) - @asin = value - end - - def ProductName - @productName - end - - def ProductName=(value) - @productName = value - end - - def Catalog - @catalog - end - - def Catalog=(value) - @catalog = value - end - - def KeyPhrases - @keyPhrases - end - - def KeyPhrases=(value) - @keyPhrases = value - end - - def Artists - @artists - end - - def Artists=(value) - @artists = value - end - - def Authors - @authors - end - - def Authors=(value) - @authors = value - end - - def Mpn - @mpn - end - - def Mpn=(value) - @mpn = value - end - - def Starring - @starring - end - - def Starring=(value) - @starring = value - end - - def Directors - @directors - end - - def Directors=(value) - @directors = value - end - - def TheatricalReleaseDate - @theatricalReleaseDate - end - - def TheatricalReleaseDate=(value) - @theatricalReleaseDate = value - end - - def ReleaseDate - @releaseDate - end - - def ReleaseDate=(value) - @releaseDate = value - end - - def Manufacturer - @manufacturer - end - - def Manufacturer=(value) - @manufacturer = value - end - - def Distributor - @distributor - end - - def Distributor=(value) - @distributor = value - end - - def ImageUrlSmall - @imageUrlSmall - end - - def ImageUrlSmall=(value) - @imageUrlSmall = value - end - - def ImageUrlMedium - @imageUrlMedium - end - - def ImageUrlMedium=(value) - @imageUrlMedium = value - end - - def ImageUrlLarge - @imageUrlLarge - end - - def ImageUrlLarge=(value) - @imageUrlLarge = value - end - - def MerchantId - @merchantId - end - - def MerchantId=(value) - @merchantId = value - end - - def MinPrice - @minPrice - end - - def MinPrice=(value) - @minPrice = value - end - - def MaxPrice - @maxPrice - end - - def MaxPrice=(value) - @maxPrice = value - end - - def MinSalePrice - @minSalePrice - end - - def MinSalePrice=(value) - @minSalePrice = value - end - - def MaxSalePrice - @maxSalePrice - end - - def MaxSalePrice=(value) - @maxSalePrice = value - end - - def MultiMerchant - @multiMerchant - end - - def MultiMerchant=(value) - @multiMerchant = value - end - - def MerchantSku - @merchantSku - end - - def MerchantSku=(value) - @merchantSku = value - end - - def ListPrice - @listPrice - end - - def ListPrice=(value) - @listPrice = value - end - - def OurPrice - @ourPrice - end - - def OurPrice=(value) - @ourPrice = value - end - - def UsedPrice - @usedPrice - end - - def UsedPrice=(value) - @usedPrice = value - end - - def RefurbishedPrice - @refurbishedPrice - end - - def RefurbishedPrice=(value) - @refurbishedPrice = value - end - - def CollectiblePrice - @collectiblePrice - end - - def CollectiblePrice=(value) - @collectiblePrice = value - end - - def ThirdPartyNewPrice - @thirdPartyNewPrice - end - - def ThirdPartyNewPrice=(value) - @thirdPartyNewPrice = value - end - - def NumberOfOfferings - @numberOfOfferings - end - - def NumberOfOfferings=(value) - @numberOfOfferings = value - end - - def ThirdPartyNewCount - @thirdPartyNewCount - end - - def ThirdPartyNewCount=(value) - @thirdPartyNewCount = value - end - - def UsedCount - @usedCount - end - - def UsedCount=(value) - @usedCount = value - end - - def CollectibleCount - @collectibleCount - end - - def CollectibleCount=(value) - @collectibleCount = value - end - - def RefurbishedCount - @refurbishedCount - end - - def RefurbishedCount=(value) - @refurbishedCount = value - end - - def ThirdPartyProductInfo - @thirdPartyProductInfo - end - - def ThirdPartyProductInfo=(value) - @thirdPartyProductInfo = value - end - - def SalesRank - @salesRank - end - - def SalesRank=(value) - @salesRank = value - end - - def BrowseList - @browseList - end - - def BrowseList=(value) - @browseList = value - end - - def Media - @media - end - - def Media=(value) - @media = value - end - - def ReadingLevel - @readingLevel - end - - def ReadingLevel=(value) - @readingLevel = value - end - - def Publisher - @publisher - end - - def Publisher=(value) - @publisher = value - end - - def NumMedia - @numMedia - end - - def NumMedia=(value) - @numMedia = value - end - - def Isbn - @isbn - end - - def Isbn=(value) - @isbn = value - end - - def Features - @features - end - - def Features=(value) - @features = value - end - - def MpaaRating - @mpaaRating - end - - def MpaaRating=(value) - @mpaaRating = value - end - - def EsrbRating - @esrbRating - end - - def EsrbRating=(value) - @esrbRating = value - end - - def AgeGroup - @ageGroup - end - - def AgeGroup=(value) - @ageGroup = value - end - - def Availability - @availability - end - - def Availability=(value) - @availability = value - end - - def Upc - @upc - end - - def Upc=(value) - @upc = value - end - - def Tracks - @tracks - end - - def Tracks=(value) - @tracks = value - end - - def Accessories - @accessories - end - - def Accessories=(value) - @accessories = value - end - - def Platforms - @platforms - end - - def Platforms=(value) - @platforms = value - end - - def Encoding - @encoding - end - - def Encoding=(value) - @encoding = value - end - - def ProductDescription - @productDescription - end - - def ProductDescription=(value) - @productDescription = value - end - - def Reviews - @reviews - end - - def Reviews=(value) - @reviews = value - end - - def SimilarProducts - @similarProducts - end - - def SimilarProducts=(value) - @similarProducts = value - end - - def FeaturedProducts - @featuredProducts - end - - def FeaturedProducts=(value) - @featuredProducts = value - end - - def Lists - @lists - end - - def Lists=(value) - @lists = value - end - - def Status - @status - end - - def Status=(value) - @status = value - end - - def Variations - @variations - end - - def Variations=(value) - @variations = value - end - - def initialize(url = nil, - asin = nil, - productName = nil, - catalog = nil, - keyPhrases = nil, - artists = nil, - authors = nil, - mpn = nil, - starring = nil, - directors = nil, - theatricalReleaseDate = nil, - releaseDate = nil, - manufacturer = nil, - distributor = nil, - imageUrlSmall = nil, - imageUrlMedium = nil, - imageUrlLarge = nil, - merchantId = nil, - minPrice = nil, - maxPrice = nil, - minSalePrice = nil, - maxSalePrice = nil, - multiMerchant = nil, - merchantSku = nil, - listPrice = nil, - ourPrice = nil, - usedPrice = nil, - refurbishedPrice = nil, - collectiblePrice = nil, - thirdPartyNewPrice = nil, - numberOfOfferings = nil, - thirdPartyNewCount = nil, - usedCount = nil, - collectibleCount = nil, - refurbishedCount = nil, - thirdPartyProductInfo = nil, - salesRank = nil, - browseList = nil, - media = nil, - readingLevel = nil, - publisher = nil, - numMedia = nil, - isbn = nil, - features = nil, - mpaaRating = nil, - esrbRating = nil, - ageGroup = nil, - availability = nil, - upc = nil, - tracks = nil, - accessories = nil, - platforms = nil, - encoding = nil, - productDescription = nil, - reviews = nil, - similarProducts = nil, - featuredProducts = nil, - lists = nil, - status = nil, - variations = nil) - @url = url - @asin = asin - @productName = productName - @catalog = catalog - @keyPhrases = keyPhrases - @artists = artists - @authors = authors - @mpn = mpn - @starring = starring - @directors = directors - @theatricalReleaseDate = theatricalReleaseDate - @releaseDate = releaseDate - @manufacturer = manufacturer - @distributor = distributor - @imageUrlSmall = imageUrlSmall - @imageUrlMedium = imageUrlMedium - @imageUrlLarge = imageUrlLarge - @merchantId = merchantId - @minPrice = minPrice - @maxPrice = maxPrice - @minSalePrice = minSalePrice - @maxSalePrice = maxSalePrice - @multiMerchant = multiMerchant - @merchantSku = merchantSku - @listPrice = listPrice - @ourPrice = ourPrice - @usedPrice = usedPrice - @refurbishedPrice = refurbishedPrice - @collectiblePrice = collectiblePrice - @thirdPartyNewPrice = thirdPartyNewPrice - @numberOfOfferings = numberOfOfferings - @thirdPartyNewCount = thirdPartyNewCount - @usedCount = usedCount - @collectibleCount = collectibleCount - @refurbishedCount = refurbishedCount - @thirdPartyProductInfo = thirdPartyProductInfo - @salesRank = salesRank - @browseList = browseList - @media = media - @readingLevel = readingLevel - @publisher = publisher - @numMedia = numMedia - @isbn = isbn - @features = features - @mpaaRating = mpaaRating - @esrbRating = esrbRating - @ageGroup = ageGroup - @availability = availability - @upc = upc - @tracks = tracks - @accessories = accessories - @platforms = platforms - @encoding = encoding - @productDescription = productDescription - @reviews = reviews - @similarProducts = similarProducts - @featuredProducts = featuredProducts - @lists = lists - @status = status - @variations = variations - end -end - -# http://soap.amazon.com -class KeyPhraseArray < Array - # Contents type should be dumped here... - @@schema_type = "KeyPhraseArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class KeyPhrase - @@schema_type = "KeyPhrase" - @@schema_ns = "http://soap.amazon.com" - - def KeyPhrase - @keyPhrase - end - - def KeyPhrase=(value) - @keyPhrase = value - end - - def Type - @type - end - - def Type=(value) - @type = value - end - - def initialize(keyPhrase = nil, - type = nil) - @keyPhrase = keyPhrase - @type = type - end -end - -# http://soap.amazon.com -class ArtistArray < Array - # Contents type should be dumped here... - @@schema_type = "ArtistArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class AuthorArray < Array - # Contents type should be dumped here... - @@schema_type = "AuthorArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class StarringArray < Array - # Contents type should be dumped here... - @@schema_type = "StarringArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class DirectorArray < Array - # Contents type should be dumped here... - @@schema_type = "DirectorArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class BrowseNodeArray < Array - # Contents type should be dumped here... - @@schema_type = "BrowseNodeArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class BrowseNode - @@schema_type = "BrowseNode" - @@schema_ns = "http://soap.amazon.com" - - def BrowseId - @browseId - end - - def BrowseId=(value) - @browseId = value - end - - def BrowseName - @browseName - end - - def BrowseName=(value) - @browseName = value - end - - def initialize(browseId = nil, - browseName = nil) - @browseId = browseId - @browseName = browseName - end -end - -# http://soap.amazon.com -class FeaturesArray < Array - # Contents type should be dumped here... - @@schema_type = "FeaturesArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class TrackArray < Array - # Contents type should be dumped here... - @@schema_type = "TrackArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class Track - @@schema_type = "Track" - @@schema_ns = "http://soap.amazon.com" - - def TrackName - @trackName - end - - def TrackName=(value) - @trackName = value - end - - def ByArtist - @byArtist - end - - def ByArtist=(value) - @byArtist = value - end - - def initialize(trackName = nil, - byArtist = nil) - @trackName = trackName - @byArtist = byArtist - end -end - -# http://soap.amazon.com -class AccessoryArray < Array - # Contents type should be dumped here... - @@schema_type = "AccessoryArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class PlatformArray < Array - # Contents type should be dumped here... - @@schema_type = "PlatformArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class Reviews - @@schema_type = "Reviews" - @@schema_ns = "http://soap.amazon.com" - - def AvgCustomerRating - @avgCustomerRating - end - - def AvgCustomerRating=(value) - @avgCustomerRating = value - end - - def TotalCustomerReviews - @totalCustomerReviews - end - - def TotalCustomerReviews=(value) - @totalCustomerReviews = value - end - - def CustomerReviews - @customerReviews - end - - def CustomerReviews=(value) - @customerReviews = value - end - - def initialize(avgCustomerRating = nil, - totalCustomerReviews = nil, - customerReviews = nil) - @avgCustomerRating = avgCustomerRating - @totalCustomerReviews = totalCustomerReviews - @customerReviews = customerReviews - end -end - -# http://soap.amazon.com -class CustomerReviewArray < Array - # Contents type should be dumped here... - @@schema_type = "CustomerReviewArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class CustomerReview - @@schema_type = "CustomerReview" - @@schema_ns = "http://soap.amazon.com" - - def Rating - @rating - end - - def Rating=(value) - @rating = value - end - - def Summary - @summary - end - - def Summary=(value) - @summary = value - end - - def Comment - @comment - end - - def Comment=(value) - @comment = value - end - - def initialize(rating = nil, - summary = nil, - comment = nil) - @rating = rating - @summary = summary - @comment = comment - end -end - -# http://soap.amazon.com -class SimilarProductsArray < Array - # Contents type should be dumped here... - @@schema_type = "SimilarProductsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class FeaturedProductsArray < Array - # Contents type should be dumped here... - @@schema_type = "FeaturedProductsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class FeaturedProduct - @@schema_type = "FeaturedProduct" - @@schema_ns = "http://soap.amazon.com" - - def Asin - @asin - end - - def Asin=(value) - @asin = value - end - - def Comment - @comment - end - - def Comment=(value) - @comment = value - end - - def initialize(asin = nil, - comment = nil) - @asin = asin - @comment = comment - end -end - -# http://soap.amazon.com -class ListArray < Array - # Contents type should be dumped here... - @@schema_type = "ListArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class VariationArray < Array - # Contents type should be dumped here... - @@schema_type = "VariationArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class Variation - @@schema_type = "Variation" - @@schema_ns = "http://soap.amazon.com" - - def Asin - @asin - end - - def Asin=(value) - @asin = value - end - - def ClothingSize - @clothingSize - end - - def ClothingSize=(value) - @clothingSize = value - end - - def ClothingColor - @clothingColor - end - - def ClothingColor=(value) - @clothingColor = value - end - - def Price - @price - end - - def Price=(value) - @price = value - end - - def SalePrice - @salePrice - end - - def SalePrice=(value) - @salePrice = value - end - - def Availability - @availability - end - - def Availability=(value) - @availability = value - end - - def MultiMerchant - @multiMerchant - end - - def MultiMerchant=(value) - @multiMerchant = value - end - - def MerchantSku - @merchantSku - end - - def MerchantSku=(value) - @merchantSku = value - end - - def initialize(asin = nil, - clothingSize = nil, - clothingColor = nil, - price = nil, - salePrice = nil, - availability = nil, - multiMerchant = nil, - merchantSku = nil) - @asin = asin - @clothingSize = clothingSize - @clothingColor = clothingColor - @price = price - @salePrice = salePrice - @availability = availability - @multiMerchant = multiMerchant - @merchantSku = merchantSku - end -end - -# http://soap.amazon.com -class MarketplaceSearch - @@schema_type = "MarketplaceSearch" - @@schema_ns = "http://soap.amazon.com" - - def MarketplaceSearchDetails - @marketplaceSearchDetails - end - - def MarketplaceSearchDetails=(value) - @marketplaceSearchDetails = value - end - - def initialize(marketplaceSearchDetails = nil) - @marketplaceSearchDetails = marketplaceSearchDetails - end -end - -# http://soap.amazon.com -class SellerProfile - @@schema_type = "SellerProfile" - @@schema_ns = "http://soap.amazon.com" - - def SellerProfileDetails - @sellerProfileDetails - end - - def SellerProfileDetails=(value) - @sellerProfileDetails = value - end - - def initialize(sellerProfileDetails = nil) - @sellerProfileDetails = sellerProfileDetails - end -end - -# http://soap.amazon.com -class SellerSearch - @@schema_type = "SellerSearch" - @@schema_ns = "http://soap.amazon.com" - - def SellerSearchDetails - @sellerSearchDetails - end - - def SellerSearchDetails=(value) - @sellerSearchDetails = value - end - - def initialize(sellerSearchDetails = nil) - @sellerSearchDetails = sellerSearchDetails - end -end - -# http://soap.amazon.com -class MarketplaceSearchDetails - @@schema_type = "MarketplaceSearchDetails" - @@schema_ns = "http://soap.amazon.com" - - def NumberOfOpenListings - @numberOfOpenListings - end - - def NumberOfOpenListings=(value) - @numberOfOpenListings = value - end - - def ListingProductInfo - @listingProductInfo - end - - def ListingProductInfo=(value) - @listingProductInfo = value - end - - def initialize(numberOfOpenListings = nil, - listingProductInfo = nil) - @numberOfOpenListings = numberOfOpenListings - @listingProductInfo = listingProductInfo - end -end - -# http://soap.amazon.com -class MarketplaceSearchDetailsArray < Array - # Contents type should be dumped here... - @@schema_type = "MarketplaceSearchDetailsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class SellerProfileDetails - @@schema_type = "SellerProfileDetails" - @@schema_ns = "http://soap.amazon.com" - - def SellerNickname - @sellerNickname - end - - def SellerNickname=(value) - @sellerNickname = value - end - - def OverallFeedbackRating - @overallFeedbackRating - end - - def OverallFeedbackRating=(value) - @overallFeedbackRating = value - end - - def NumberOfFeedback - @numberOfFeedback - end - - def NumberOfFeedback=(value) - @numberOfFeedback = value - end - - def NumberOfCanceledBids - @numberOfCanceledBids - end - - def NumberOfCanceledBids=(value) - @numberOfCanceledBids = value - end - - def NumberOfCanceledAuctions - @numberOfCanceledAuctions - end - - def NumberOfCanceledAuctions=(value) - @numberOfCanceledAuctions = value - end - - def StoreId - @storeId - end - - def StoreId=(value) - @storeId = value - end - - def StoreName - @storeName - end - - def StoreName=(value) - @storeName = value - end - - def SellerFeedback - @sellerFeedback - end - - def SellerFeedback=(value) - @sellerFeedback = value - end - - def initialize(sellerNickname = nil, - overallFeedbackRating = nil, - numberOfFeedback = nil, - numberOfCanceledBids = nil, - numberOfCanceledAuctions = nil, - storeId = nil, - storeName = nil, - sellerFeedback = nil) - @sellerNickname = sellerNickname - @overallFeedbackRating = overallFeedbackRating - @numberOfFeedback = numberOfFeedback - @numberOfCanceledBids = numberOfCanceledBids - @numberOfCanceledAuctions = numberOfCanceledAuctions - @storeId = storeId - @storeName = storeName - @sellerFeedback = sellerFeedback - end -end - -# http://soap.amazon.com -class SellerProfileDetailsArray < Array - # Contents type should be dumped here... - @@schema_type = "SellerProfileDetailsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class SellerSearchDetails - @@schema_type = "SellerSearchDetails" - @@schema_ns = "http://soap.amazon.com" - - def SellerNickname - @sellerNickname - end - - def SellerNickname=(value) - @sellerNickname = value - end - - def StoreId - @storeId - end - - def StoreId=(value) - @storeId = value - end - - def StoreName - @storeName - end - - def StoreName=(value) - @storeName = value - end - - def NumberOfOpenListings - @numberOfOpenListings - end - - def NumberOfOpenListings=(value) - @numberOfOpenListings = value - end - - def ListingProductInfo - @listingProductInfo - end - - def ListingProductInfo=(value) - @listingProductInfo = value - end - - def initialize(sellerNickname = nil, - storeId = nil, - storeName = nil, - numberOfOpenListings = nil, - listingProductInfo = nil) - @sellerNickname = sellerNickname - @storeId = storeId - @storeName = storeName - @numberOfOpenListings = numberOfOpenListings - @listingProductInfo = listingProductInfo - end -end - -# http://soap.amazon.com -class SellerSearchDetailsArray < Array - # Contents type should be dumped here... - @@schema_type = "SellerSearchDetailsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class ListingProductInfo - @@schema_type = "ListingProductInfo" - @@schema_ns = "http://soap.amazon.com" - - def ListingProductDetails - @listingProductDetails - end - - def ListingProductDetails=(value) - @listingProductDetails = value - end - - def initialize(listingProductDetails = nil) - @listingProductDetails = listingProductDetails - end -end - -# http://soap.amazon.com -class ListingProductDetailsArray < Array - # Contents type should be dumped here... - @@schema_type = "ListingProductDetailsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class ListingProductDetails - @@schema_type = "ListingProductDetails" - @@schema_ns = "http://soap.amazon.com" - - def ExchangeId - @exchangeId - end - - def ExchangeId=(value) - @exchangeId = value - end - - def ListingId - @listingId - end - - def ListingId=(value) - @listingId = value - end - - def ExchangeTitle - @exchangeTitle - end - - def ExchangeTitle=(value) - @exchangeTitle = value - end - - def ExchangeDescription - @exchangeDescription - end - - def ExchangeDescription=(value) - @exchangeDescription = value - end - - def ExchangePrice - @exchangePrice - end - - def ExchangePrice=(value) - @exchangePrice = value - end - - def ExchangeAsin - @exchangeAsin - end - - def ExchangeAsin=(value) - @exchangeAsin = value - end - - def ExchangeEndDate - @exchangeEndDate - end - - def ExchangeEndDate=(value) - @exchangeEndDate = value - end - - def ExchangeTinyImage - @exchangeTinyImage - end - - def ExchangeTinyImage=(value) - @exchangeTinyImage = value - end - - def ExchangeSellerId - @exchangeSellerId - end - - def ExchangeSellerId=(value) - @exchangeSellerId = value - end - - def ExchangeSellerNickname - @exchangeSellerNickname - end - - def ExchangeSellerNickname=(value) - @exchangeSellerNickname = value - end - - def ExchangeStartDate - @exchangeStartDate - end - - def ExchangeStartDate=(value) - @exchangeStartDate = value - end - - def ExchangeStatus - @exchangeStatus - end - - def ExchangeStatus=(value) - @exchangeStatus = value - end - - def ExchangeQuantity - @exchangeQuantity - end - - def ExchangeQuantity=(value) - @exchangeQuantity = value - end - - def ExchangeQuantityAllocated - @exchangeQuantityAllocated - end - - def ExchangeQuantityAllocated=(value) - @exchangeQuantityAllocated = value - end - - def ExchangeFeaturedCategory - @exchangeFeaturedCategory - end - - def ExchangeFeaturedCategory=(value) - @exchangeFeaturedCategory = value - end - - def ExchangeCondition - @exchangeCondition - end - - def ExchangeCondition=(value) - @exchangeCondition = value - end - - def ExchangeConditionType - @exchangeConditionType - end - - def ExchangeConditionType=(value) - @exchangeConditionType = value - end - - def ExchangeAvailability - @exchangeAvailability - end - - def ExchangeAvailability=(value) - @exchangeAvailability = value - end - - def ExchangeOfferingType - @exchangeOfferingType - end - - def ExchangeOfferingType=(value) - @exchangeOfferingType = value - end - - def ExchangeSellerState - @exchangeSellerState - end - - def ExchangeSellerState=(value) - @exchangeSellerState = value - end - - def ExchangeSellerCountry - @exchangeSellerCountry - end - - def ExchangeSellerCountry=(value) - @exchangeSellerCountry = value - end - - def ExchangeSellerRating - @exchangeSellerRating - end - - def ExchangeSellerRating=(value) - @exchangeSellerRating = value - end - - def initialize(exchangeId = nil, - listingId = nil, - exchangeTitle = nil, - exchangeDescription = nil, - exchangePrice = nil, - exchangeAsin = nil, - exchangeEndDate = nil, - exchangeTinyImage = nil, - exchangeSellerId = nil, - exchangeSellerNickname = nil, - exchangeStartDate = nil, - exchangeStatus = nil, - exchangeQuantity = nil, - exchangeQuantityAllocated = nil, - exchangeFeaturedCategory = nil, - exchangeCondition = nil, - exchangeConditionType = nil, - exchangeAvailability = nil, - exchangeOfferingType = nil, - exchangeSellerState = nil, - exchangeSellerCountry = nil, - exchangeSellerRating = nil) - @exchangeId = exchangeId - @listingId = listingId - @exchangeTitle = exchangeTitle - @exchangeDescription = exchangeDescription - @exchangePrice = exchangePrice - @exchangeAsin = exchangeAsin - @exchangeEndDate = exchangeEndDate - @exchangeTinyImage = exchangeTinyImage - @exchangeSellerId = exchangeSellerId - @exchangeSellerNickname = exchangeSellerNickname - @exchangeStartDate = exchangeStartDate - @exchangeStatus = exchangeStatus - @exchangeQuantity = exchangeQuantity - @exchangeQuantityAllocated = exchangeQuantityAllocated - @exchangeFeaturedCategory = exchangeFeaturedCategory - @exchangeCondition = exchangeCondition - @exchangeConditionType = exchangeConditionType - @exchangeAvailability = exchangeAvailability - @exchangeOfferingType = exchangeOfferingType - @exchangeSellerState = exchangeSellerState - @exchangeSellerCountry = exchangeSellerCountry - @exchangeSellerRating = exchangeSellerRating - end -end - -# http://soap.amazon.com -class SellerFeedback - @@schema_type = "SellerFeedback" - @@schema_ns = "http://soap.amazon.com" - - def Feedback - @feedback - end - - def Feedback=(value) - @feedback = value - end - - def initialize(feedback = nil) - @feedback = feedback - end -end - -# http://soap.amazon.com -class FeedbackArray < Array - # Contents type should be dumped here... - @@schema_type = "FeedbackArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class Feedback - @@schema_type = "Feedback" - @@schema_ns = "http://soap.amazon.com" - - def FeedbackRating - @feedbackRating - end - - def FeedbackRating=(value) - @feedbackRating = value - end - - def FeedbackComments - @feedbackComments - end - - def FeedbackComments=(value) - @feedbackComments = value - end - - def FeedbackDate - @feedbackDate - end - - def FeedbackDate=(value) - @feedbackDate = value - end - - def FeedbackRater - @feedbackRater - end - - def FeedbackRater=(value) - @feedbackRater = value - end - - def initialize(feedbackRating = nil, - feedbackComments = nil, - feedbackDate = nil, - feedbackRater = nil) - @feedbackRating = feedbackRating - @feedbackComments = feedbackComments - @feedbackDate = feedbackDate - @feedbackRater = feedbackRater - end -end - -# http://soap.amazon.com -class ThirdPartyProductInfo - @@schema_type = "ThirdPartyProductInfo" - @@schema_ns = "http://soap.amazon.com" - - def ThirdPartyProductDetails - @thirdPartyProductDetails - end - - def ThirdPartyProductDetails=(value) - @thirdPartyProductDetails = value - end - - def initialize(thirdPartyProductDetails = nil) - @thirdPartyProductDetails = thirdPartyProductDetails - end -end - -# http://soap.amazon.com -class ThirdPartyProductDetailsArray < Array - # Contents type should be dumped here... - @@schema_type = "ThirdPartyProductDetailsArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class ThirdPartyProductDetails - @@schema_type = "ThirdPartyProductDetails" - @@schema_ns = "http://soap.amazon.com" - - def OfferingType - @offeringType - end - - def OfferingType=(value) - @offeringType = value - end - - def SellerId - @sellerId - end - - def SellerId=(value) - @sellerId = value - end - - def SellerNickname - @sellerNickname - end - - def SellerNickname=(value) - @sellerNickname = value - end - - def ExchangeId - @exchangeId - end - - def ExchangeId=(value) - @exchangeId = value - end - - def OfferingPrice - @offeringPrice - end - - def OfferingPrice=(value) - @offeringPrice = value - end - - def Condition - @condition - end - - def Condition=(value) - @condition = value - end - - def ConditionType - @conditionType - end - - def ConditionType=(value) - @conditionType = value - end - - def ExchangeAvailability - @exchangeAvailability - end - - def ExchangeAvailability=(value) - @exchangeAvailability = value - end - - def SellerCountry - @sellerCountry - end - - def SellerCountry=(value) - @sellerCountry = value - end - - def SellerState - @sellerState - end - - def SellerState=(value) - @sellerState = value - end - - def ShipComments - @shipComments - end - - def ShipComments=(value) - @shipComments = value - end - - def SellerRating - @sellerRating - end - - def SellerRating=(value) - @sellerRating = value - end - - def initialize(offeringType = nil, - sellerId = nil, - sellerNickname = nil, - exchangeId = nil, - offeringPrice = nil, - condition = nil, - conditionType = nil, - exchangeAvailability = nil, - sellerCountry = nil, - sellerState = nil, - shipComments = nil, - sellerRating = nil) - @offeringType = offeringType - @sellerId = sellerId - @sellerNickname = sellerNickname - @exchangeId = exchangeId - @offeringPrice = offeringPrice - @condition = condition - @conditionType = conditionType - @exchangeAvailability = exchangeAvailability - @sellerCountry = sellerCountry - @sellerState = sellerState - @shipComments = shipComments - @sellerRating = sellerRating - end -end - -# http://soap.amazon.com -class KeywordRequest - @@schema_type = "KeywordRequest" - @@schema_ns = "http://soap.amazon.com" - - def keyword - @keyword - end - - def keyword=(value) - @keyword = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(keyword = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - price = nil) - @keyword = keyword - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @price = price - end -end - -# http://soap.amazon.com -class TextStreamRequest - @@schema_type = "TextStreamRequest" - @@schema_ns = "http://soap.amazon.com" - - def textStream - @textStream - end - - def textStream=(value) - @textStream = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(textStream = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - price = nil) - @textStream = textStream - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @price = price - end -end - -# http://soap.amazon.com -class PowerRequest - @@schema_type = "PowerRequest" - @@schema_ns = "http://soap.amazon.com" - - def power - @power - end - - def power=(value) - @power = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(power = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil) - @power = power - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - end -end - -# http://soap.amazon.com -class BrowseNodeRequest - @@schema_type = "BrowseNodeRequest" - @@schema_ns = "http://soap.amazon.com" - - def browse_node - @browse_node - end - - def browse_node=(value) - @browse_node = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def keywords - @keywords - end - - def keywords=(value) - @keywords = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(browse_node = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - keywords = nil, - price = nil) - @browse_node = browse_node - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @keywords = keywords - @price = price - end -end - -# http://soap.amazon.com -class AsinRequest - @@schema_type = "AsinRequest" - @@schema_ns = "http://soap.amazon.com" - - def asin - @asin - end - - def asin=(value) - @asin = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def offer - @offer - end - - def offer=(value) - @offer = value - end - - def offerpage - @offerpage - end - - def offerpage=(value) - @offerpage = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def initialize(asin = nil, - tag = nil, - type = nil, - devtag = nil, - offer = nil, - offerpage = nil, - locale = nil, - mode = nil) - @asin = asin - @tag = tag - @type = type - @devtag = devtag - @offer = offer - @offerpage = offerpage - @locale = locale - @mode = mode - end -end - -# http://soap.amazon.com -class BlendedRequest - @@schema_type = "BlendedRequest" - @@schema_ns = "http://soap.amazon.com" - - def blended - @blended - end - - def blended=(value) - @blended = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(blended = nil, - tag = nil, - type = nil, - devtag = nil, - locale = nil) - @blended = blended - @tag = tag - @type = type - @devtag = devtag - @locale = locale - end -end - -# http://soap.amazon.com -class UpcRequest - @@schema_type = "UpcRequest" - @@schema_ns = "http://soap.amazon.com" - - def upc - @upc - end - - def upc=(value) - @upc = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(upc = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil) - @upc = upc - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - end -end - -# http://soap.amazon.com -class SkuRequest - @@schema_type = "SkuRequest" - @@schema_ns = "http://soap.amazon.com" - - def sku - @sku - end - - def sku=(value) - @sku = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def merchant_id - @merchant_id - end - - def merchant_id=(value) - @merchant_id = value - end - - def keywords - @keywords - end - - def keywords=(value) - @keywords = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(sku = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - merchant_id = nil, - keywords = nil, - sort = nil, - locale = nil) - @sku = sku - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @merchant_id = merchant_id - @keywords = keywords - @sort = sort - @locale = locale - end -end - -# http://soap.amazon.com -class ArtistRequest - @@schema_type = "ArtistRequest" - @@schema_ns = "http://soap.amazon.com" - - def artist - @artist - end - - def artist=(value) - @artist = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def keywords - @keywords - end - - def keywords=(value) - @keywords = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(artist = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - keywords = nil, - price = nil) - @artist = artist - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @keywords = keywords - @price = price - end -end - -# http://soap.amazon.com -class AuthorRequest - @@schema_type = "AuthorRequest" - @@schema_ns = "http://soap.amazon.com" - - def author - @author - end - - def author=(value) - @author = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def keywords - @keywords - end - - def keywords=(value) - @keywords = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(author = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - keywords = nil, - price = nil) - @author = author - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @keywords = keywords - @price = price - end -end - -# http://soap.amazon.com -class ActorRequest - @@schema_type = "ActorRequest" - @@schema_ns = "http://soap.amazon.com" - - def actor - @actor - end - - def actor=(value) - @actor = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def keywords - @keywords - end - - def keywords=(value) - @keywords = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(actor = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - keywords = nil, - price = nil) - @actor = actor - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @keywords = keywords - @price = price - end -end - -# http://soap.amazon.com -class DirectorRequest - @@schema_type = "DirectorRequest" - @@schema_ns = "http://soap.amazon.com" - - def director - @director - end - - def director=(value) - @director = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def keywords - @keywords - end - - def keywords=(value) - @keywords = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(director = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - keywords = nil, - price = nil) - @director = director - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @keywords = keywords - @price = price - end -end - -# http://soap.amazon.com -class ExchangeRequest - @@schema_type = "ExchangeRequest" - @@schema_ns = "http://soap.amazon.com" - - def exchange_id - @exchange_id - end - - def exchange_id=(value) - @exchange_id = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(exchange_id = nil, - tag = nil, - type = nil, - devtag = nil, - locale = nil) - @exchange_id = exchange_id - @tag = tag - @type = type - @devtag = devtag - @locale = locale - end -end - -# http://soap.amazon.com -class ManufacturerRequest - @@schema_type = "ManufacturerRequest" - @@schema_ns = "http://soap.amazon.com" - - def manufacturer - @manufacturer - end - - def manufacturer=(value) - @manufacturer = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def mode - @mode - end - - def mode=(value) - @mode = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def keywords - @keywords - end - - def keywords=(value) - @keywords = value - end - - def price - @price - end - - def price=(value) - @price = value - end - - def initialize(manufacturer = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil, - locale = nil, - keywords = nil, - price = nil) - @manufacturer = manufacturer - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - @locale = locale - @keywords = keywords - @price = price - end -end - -# http://soap.amazon.com -class ListManiaRequest - @@schema_type = "ListManiaRequest" - @@schema_ns = "http://soap.amazon.com" - - def lm_id - @lm_id - end - - def lm_id=(value) - @lm_id = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(lm_id = nil, - page = nil, - tag = nil, - type = nil, - devtag = nil, - locale = nil) - @lm_id = lm_id - @page = page - @tag = tag - @type = type - @devtag = devtag - @locale = locale - end -end - -# http://soap.amazon.com -class WishlistRequest - @@schema_type = "WishlistRequest" - @@schema_ns = "http://soap.amazon.com" - - def wishlist_id - @wishlist_id - end - - def wishlist_id=(value) - @wishlist_id = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(wishlist_id = nil, - page = nil, - tag = nil, - type = nil, - devtag = nil, - locale = nil) - @wishlist_id = wishlist_id - @page = page - @tag = tag - @type = type - @devtag = devtag - @locale = locale - end -end - -# http://soap.amazon.com -class MarketplaceRequest - @@schema_type = "MarketplaceRequest" - @@schema_ns = "http://soap.amazon.com" - - def marketplace_search - @marketplace_search - end - - def marketplace_search=(value) - @marketplace_search = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def keyword - @keyword - end - - def keyword=(value) - @keyword = value - end - - def keyword_search - @keyword_search - end - - def keyword_search=(value) - @keyword_search = value - end - - def browse_id - @browse_id - end - - def browse_id=(value) - @browse_id = value - end - - def zipcode - @zipcode - end - - def zipcode=(value) - @zipcode = value - end - - def area_id - @area_id - end - - def area_id=(value) - @area_id = value - end - - def geo - @geo - end - - def geo=(value) - @geo = value - end - - def sort - @sort - end - - def sort=(value) - @sort = value - end - - def listing_id - @listing_id - end - - def listing_id=(value) - @listing_id = value - end - - def desc - @desc - end - - def desc=(value) - @desc = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def index - @index - end - - def index=(value) - @index = value - end - - def initialize(marketplace_search = nil, - tag = nil, - type = nil, - devtag = nil, - page = nil, - keyword = nil, - keyword_search = nil, - browse_id = nil, - zipcode = nil, - area_id = nil, - geo = nil, - sort = nil, - listing_id = nil, - desc = nil, - locale = nil, - index = nil) - @marketplace_search = marketplace_search - @tag = tag - @type = type - @devtag = devtag - @page = page - @keyword = keyword - @keyword_search = keyword_search - @browse_id = browse_id - @zipcode = zipcode - @area_id = area_id - @geo = geo - @sort = sort - @listing_id = listing_id - @desc = desc - @locale = locale - @index = index - end -end - -# http://soap.amazon.com -class SellerProfileRequest - @@schema_type = "SellerProfileRequest" - @@schema_ns = "http://soap.amazon.com" - - def seller_id - @seller_id - end - - def seller_id=(value) - @seller_id = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def desc - @desc - end - - def desc=(value) - @desc = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(seller_id = nil, - tag = nil, - type = nil, - devtag = nil, - page = nil, - desc = nil, - locale = nil) - @seller_id = seller_id - @tag = tag - @type = type - @devtag = devtag - @page = page - @desc = desc - @locale = locale - end -end - -# http://soap.amazon.com -class SellerRequest - @@schema_type = "SellerRequest" - @@schema_ns = "http://soap.amazon.com" - - def seller_id - @seller_id - end - - def seller_id=(value) - @seller_id = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def offerstatus - @offerstatus - end - - def offerstatus=(value) - @offerstatus = value - end - - def page - @page - end - - def page=(value) - @page = value - end - - def seller_browse_id - @seller_browse_id - end - - def seller_browse_id=(value) - @seller_browse_id = value - end - - def keyword - @keyword - end - - def keyword=(value) - @keyword = value - end - - def desc - @desc - end - - def desc=(value) - @desc = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def index - @index - end - - def index=(value) - @index = value - end - - def initialize(seller_id = nil, - tag = nil, - type = nil, - devtag = nil, - offerstatus = nil, - page = nil, - seller_browse_id = nil, - keyword = nil, - desc = nil, - locale = nil, - index = nil) - @seller_id = seller_id - @tag = tag - @type = type - @devtag = devtag - @offerstatus = offerstatus - @page = page - @seller_browse_id = seller_browse_id - @keyword = keyword - @desc = desc - @locale = locale - @index = index - end -end - -# http://soap.amazon.com -class SimilarityRequest - @@schema_type = "SimilarityRequest" - @@schema_ns = "http://soap.amazon.com" - - def asin - @asin - end - - def asin=(value) - @asin = value - end - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def type - @type - end - - def type=(value) - @type = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(asin = nil, - tag = nil, - type = nil, - devtag = nil, - locale = nil) - @asin = asin - @tag = tag - @type = type - @devtag = devtag - @locale = locale - end -end - -# http://soap.amazon.com -class ItemIdArray < Array - # Contents type should be dumped here... - @@schema_type = "ItemIdArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class ItemArray < Array - # Contents type should be dumped here... - @@schema_type = "ItemArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class Item - @@schema_type = "Item" - @@schema_ns = "http://soap.amazon.com" - - def ItemId - @itemId - end - - def ItemId=(value) - @itemId = value - end - - def ProductName - @productName - end - - def ProductName=(value) - @productName = value - end - - def Catalog - @catalog - end - - def Catalog=(value) - @catalog = value - end - - def Asin - @asin - end - - def Asin=(value) - @asin = value - end - - def ExchangeId - @exchangeId - end - - def ExchangeId=(value) - @exchangeId = value - end - - def Quantity - @quantity - end - - def Quantity=(value) - @quantity = value - end - - def ListPrice - @listPrice - end - - def ListPrice=(value) - @listPrice = value - end - - def OurPrice - @ourPrice - end - - def OurPrice=(value) - @ourPrice = value - end - - def MerchantSku - @merchantSku - end - - def MerchantSku=(value) - @merchantSku = value - end - - def initialize(itemId = nil, - productName = nil, - catalog = nil, - asin = nil, - exchangeId = nil, - quantity = nil, - listPrice = nil, - ourPrice = nil, - merchantSku = nil) - @itemId = itemId - @productName = productName - @catalog = catalog - @asin = asin - @exchangeId = exchangeId - @quantity = quantity - @listPrice = listPrice - @ourPrice = ourPrice - @merchantSku = merchantSku - end -end - -# http://soap.amazon.com -class ItemQuantityArray < Array - # Contents type should be dumped here... - @@schema_type = "ItemQuantityArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class ItemQuantity - @@schema_type = "ItemQuantity" - @@schema_ns = "http://soap.amazon.com" - - def ItemId - @itemId - end - - def ItemId=(value) - @itemId = value - end - - def Quantity - @quantity - end - - def Quantity=(value) - @quantity = value - end - - def initialize(itemId = nil, - quantity = nil) - @itemId = itemId - @quantity = quantity - end -end - -# http://soap.amazon.com -class AddItemArray < Array - # Contents type should be dumped here... - @@schema_type = "AddItemArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class AddItem - @@schema_type = "AddItem" - @@schema_ns = "http://soap.amazon.com" - - def ParentAsin - @parentAsin - end - - def ParentAsin=(value) - @parentAsin = value - end - - def Asin - @asin - end - - def Asin=(value) - @asin = value - end - - def MerchantId - @merchantId - end - - def MerchantId=(value) - @merchantId = value - end - - def ExchangeId - @exchangeId - end - - def ExchangeId=(value) - @exchangeId = value - end - - def Quantity - @quantity - end - - def Quantity=(value) - @quantity = value - end - - def initialize(parentAsin = nil, - asin = nil, - merchantId = nil, - exchangeId = nil, - quantity = nil) - @parentAsin = parentAsin - @asin = asin - @merchantId = merchantId - @exchangeId = exchangeId - @quantity = quantity - end -end - -# http://soap.amazon.com -class ShoppingCart - @@schema_type = "ShoppingCart" - @@schema_ns = "http://soap.amazon.com" - - def CartId - @cartId - end - - def CartId=(value) - @cartId = value - end - - def HMAC - @hMAC - end - - def HMAC=(value) - @hMAC = value - end - - def PurchaseUrl - @purchaseUrl - end - - def PurchaseUrl=(value) - @purchaseUrl = value - end - - def Items - @items - end - - def Items=(value) - @items = value - end - - def SimilarProducts - @similarProducts - end - - def SimilarProducts=(value) - @similarProducts = value - end - - def initialize(cartId = nil, - hMAC = nil, - purchaseUrl = nil, - items = nil, - similarProducts = nil) - @cartId = cartId - @hMAC = hMAC - @purchaseUrl = purchaseUrl - @items = items - @similarProducts = similarProducts - end -end - -# http://soap.amazon.com -class GetShoppingCartRequest - @@schema_type = "GetShoppingCartRequest" - @@schema_ns = "http://soap.amazon.com" - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def CartId - @cartId - end - - def CartId=(value) - @cartId = value - end - - def HMAC - @hMAC - end - - def HMAC=(value) - @hMAC = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def sims - @sims - end - - def sims=(value) - @sims = value - end - - def initialize(tag = nil, - devtag = nil, - cartId = nil, - hMAC = nil, - locale = nil, - sims = nil) - @tag = tag - @devtag = devtag - @cartId = cartId - @hMAC = hMAC - @locale = locale - @sims = sims - end -end - -# http://soap.amazon.com -class ClearShoppingCartRequest - @@schema_type = "ClearShoppingCartRequest" - @@schema_ns = "http://soap.amazon.com" - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def CartId - @cartId - end - - def CartId=(value) - @cartId = value - end - - def HMAC - @hMAC - end - - def HMAC=(value) - @hMAC = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(tag = nil, - devtag = nil, - cartId = nil, - hMAC = nil, - locale = nil) - @tag = tag - @devtag = devtag - @cartId = cartId - @hMAC = hMAC - @locale = locale - end -end - -# http://soap.amazon.com -class AddShoppingCartItemsRequest - @@schema_type = "AddShoppingCartItemsRequest" - @@schema_ns = "http://soap.amazon.com" - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def CartId - @cartId - end - - def CartId=(value) - @cartId = value - end - - def HMAC - @hMAC - end - - def HMAC=(value) - @hMAC = value - end - - def Items - @items - end - - def Items=(value) - @items = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def sims - @sims - end - - def sims=(value) - @sims = value - end - - def initialize(tag = nil, - devtag = nil, - cartId = nil, - hMAC = nil, - items = nil, - locale = nil, - sims = nil) - @tag = tag - @devtag = devtag - @cartId = cartId - @hMAC = hMAC - @items = items - @locale = locale - @sims = sims - end -end - -# http://soap.amazon.com -class RemoveShoppingCartItemsRequest - @@schema_type = "RemoveShoppingCartItemsRequest" - @@schema_ns = "http://soap.amazon.com" - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def CartId - @cartId - end - - def CartId=(value) - @cartId = value - end - - def HMAC - @hMAC - end - - def HMAC=(value) - @hMAC = value - end - - def Items - @items - end - - def Items=(value) - @items = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def sims - @sims - end - - def sims=(value) - @sims = value - end - - def initialize(tag = nil, - devtag = nil, - cartId = nil, - hMAC = nil, - items = nil, - locale = nil, - sims = nil) - @tag = tag - @devtag = devtag - @cartId = cartId - @hMAC = hMAC - @items = items - @locale = locale - @sims = sims - end -end - -# http://soap.amazon.com -class ModifyShoppingCartItemsRequest - @@schema_type = "ModifyShoppingCartItemsRequest" - @@schema_ns = "http://soap.amazon.com" - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def CartId - @cartId - end - - def CartId=(value) - @cartId = value - end - - def HMAC - @hMAC - end - - def HMAC=(value) - @hMAC = value - end - - def Items - @items - end - - def Items=(value) - @items = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def sims - @sims - end - - def sims=(value) - @sims = value - end - - def initialize(tag = nil, - devtag = nil, - cartId = nil, - hMAC = nil, - items = nil, - locale = nil, - sims = nil) - @tag = tag - @devtag = devtag - @cartId = cartId - @hMAC = hMAC - @items = items - @locale = locale - @sims = sims - end -end - -# http://soap.amazon.com -class OrderIdArray < Array - # Contents type should be dumped here... - @@schema_type = "OrderIdArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class Price - @@schema_type = "Price" - @@schema_ns = "http://soap.amazon.com" - - def Amount - @amount - end - - def Amount=(value) - @amount = value - end - - def CurrencyCode - @currencyCode - end - - def CurrencyCode=(value) - @currencyCode = value - end - - def initialize(amount = nil, - currencyCode = nil) - @amount = amount - @currencyCode = currencyCode - end -end - -# http://soap.amazon.com -class Package - @@schema_type = "Package" - @@schema_ns = "http://soap.amazon.com" - - def TrackingNumber - @trackingNumber - end - - def TrackingNumber=(value) - @trackingNumber = value - end - - def CarrierName - @carrierName - end - - def CarrierName=(value) - @carrierName = value - end - - def initialize(trackingNumber = nil, - carrierName = nil) - @trackingNumber = trackingNumber - @carrierName = carrierName - end -end - -# http://soap.amazon.com -class PackageArray < Array - # Contents type should be dumped here... - @@schema_type = "PackageArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class OrderItem - @@schema_type = "OrderItem" - @@schema_ns = "http://soap.amazon.com" - - def ItemNumber - @itemNumber - end - - def ItemNumber=(value) - @itemNumber = value - end - - def ASIN - @aSIN - end - - def ASIN=(value) - @aSIN = value - end - - def ExchangeId - @exchangeId - end - - def ExchangeId=(value) - @exchangeId = value - end - - def Quantity - @quantity - end - - def Quantity=(value) - @quantity = value - end - - def UnitPrice - @unitPrice - end - - def UnitPrice=(value) - @unitPrice = value - end - - def TotalPrice - @totalPrice - end - - def TotalPrice=(value) - @totalPrice = value - end - - def initialize(itemNumber = nil, - aSIN = nil, - exchangeId = nil, - quantity = nil, - unitPrice = nil, - totalPrice = nil) - @itemNumber = itemNumber - @aSIN = aSIN - @exchangeId = exchangeId - @quantity = quantity - @unitPrice = unitPrice - @totalPrice = totalPrice - end -end - -# http://soap.amazon.com -class OrderItemArray < Array - # Contents type should be dumped here... - @@schema_type = "OrderItemArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class ShortSummary - @@schema_type = "ShortSummary" - @@schema_ns = "http://soap.amazon.com" - - def OrderId - @orderId - end - - def OrderId=(value) - @orderId = value - end - - def SellerId - @sellerId - end - - def SellerId=(value) - @sellerId = value - end - - def Condition - @condition - end - - def Condition=(value) - @condition = value - end - - def TransactionDate - @transactionDate - end - - def TransactionDate=(value) - @transactionDate = value - end - - def TransactionDateEpoch - @transactionDateEpoch - end - - def TransactionDateEpoch=(value) - @transactionDateEpoch = value - end - - def Total - @total - end - - def Total=(value) - @total = value - end - - def Subtotal - @subtotal - end - - def Subtotal=(value) - @subtotal = value - end - - def Shipping - @shipping - end - - def Shipping=(value) - @shipping = value - end - - def Tax - @tax - end - - def Tax=(value) - @tax = value - end - - def Promotion - @promotion - end - - def Promotion=(value) - @promotion = value - end - - def StoreName - @storeName - end - - def StoreName=(value) - @storeName = value - end - - def Packages - @packages - end - - def Packages=(value) - @packages = value - end - - def OrderItems - @orderItems - end - - def OrderItems=(value) - @orderItems = value - end - - def ErrorCode - @errorCode - end - - def ErrorCode=(value) - @errorCode = value - end - - def ErrorString - @errorString - end - - def ErrorString=(value) - @errorString = value - end - - def initialize(orderId = nil, - sellerId = nil, - condition = nil, - transactionDate = nil, - transactionDateEpoch = nil, - total = nil, - subtotal = nil, - shipping = nil, - tax = nil, - promotion = nil, - storeName = nil, - packages = nil, - orderItems = nil, - errorCode = nil, - errorString = nil) - @orderId = orderId - @sellerId = sellerId - @condition = condition - @transactionDate = transactionDate - @transactionDateEpoch = transactionDateEpoch - @total = total - @subtotal = subtotal - @shipping = shipping - @tax = tax - @promotion = promotion - @storeName = storeName - @packages = packages - @orderItems = orderItems - @errorCode = errorCode - @errorString = errorString - end -end - -# http://soap.amazon.com -class ShortSummaryArray < Array - # Contents type should be dumped here... - @@schema_type = "ShortSummaryArray" - @@schema_ns = "http://soap.amazon.com" -end - -# http://soap.amazon.com -class GetTransactionDetailsRequest - @@schema_type = "GetTransactionDetailsRequest" - @@schema_ns = "http://soap.amazon.com" - - def tag - @tag - end - - def tag=(value) - @tag = value - end - - def devtag - @devtag - end - - def devtag=(value) - @devtag = value - end - - def key - @key - end - - def key=(value) - @key = value - end - - def OrderIds - @orderIds - end - - def OrderIds=(value) - @orderIds = value - end - - def locale - @locale - end - - def locale=(value) - @locale = value - end - - def initialize(tag = nil, - devtag = nil, - key = nil, - orderIds = nil, - locale = nil) - @tag = tag - @devtag = devtag - @key = key - @orderIds = orderIds - @locale = locale - end -end - -# http://soap.amazon.com -class GetTransactionDetailsResponse - @@schema_type = "GetTransactionDetailsResponse" - @@schema_ns = "http://soap.amazon.com" - - def ShortSummaries - @shortSummaries - end - - def ShortSummaries=(value) - @shortSummaries = value - end - - def initialize(shortSummaries = nil) - @shortSummaries = shortSummaries - end -end - diff --git a/sample/wsdl/amazon/AmazonSearchDriver.rb b/sample/wsdl/amazon/AmazonSearchDriver.rb deleted file mode 100644 index 01915e2735..0000000000 --- a/sample/wsdl/amazon/AmazonSearchDriver.rb +++ /dev/null @@ -1,511 +0,0 @@ -require 'AmazonSearch.rb' - -require 'soap/rpc/driver' - -class AmazonSearchPort < SOAP::RPC::Driver - MappingRegistry = ::SOAP::Mapping::Registry.new - - MappingRegistry.set( - KeywordRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "KeywordRequest") } - ) - MappingRegistry.set( - ProductInfo, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ProductInfo") } - ) - MappingRegistry.set( - DetailsArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "Details") } - ) - MappingRegistry.set( - TextStreamRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "TextStreamRequest") } - ) - MappingRegistry.set( - PowerRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "PowerRequest") } - ) - MappingRegistry.set( - BrowseNodeRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "BrowseNodeRequest") } - ) - MappingRegistry.set( - AsinRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "AsinRequest") } - ) - MappingRegistry.set( - BlendedRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "BlendedRequest") } - ) - MappingRegistry.set( - ProductLineArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ProductLine") } - ) - MappingRegistry.set( - UpcRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "UpcRequest") } - ) - MappingRegistry.set( - SkuRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SkuRequest") } - ) - MappingRegistry.set( - AuthorRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "AuthorRequest") } - ) - MappingRegistry.set( - ArtistRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ArtistRequest") } - ) - MappingRegistry.set( - ActorRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ActorRequest") } - ) - MappingRegistry.set( - ManufacturerRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ManufacturerRequest") } - ) - MappingRegistry.set( - DirectorRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "DirectorRequest") } - ) - MappingRegistry.set( - ListManiaRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ListManiaRequest") } - ) - MappingRegistry.set( - WishlistRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "WishlistRequest") } - ) - MappingRegistry.set( - ExchangeRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ExchangeRequest") } - ) - MappingRegistry.set( - ListingProductDetails, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ListingProductDetails") } - ) - MappingRegistry.set( - MarketplaceRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceRequest") } - ) - MappingRegistry.set( - MarketplaceSearch, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceSearch") } - ) - MappingRegistry.set( - MarketplaceSearchDetailsArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceSearchDetails") } - ) - MappingRegistry.set( - SellerProfileRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfileRequest") } - ) - MappingRegistry.set( - SellerProfile, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfile") } - ) - MappingRegistry.set( - SellerProfileDetailsArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfileDetails") } - ) - MappingRegistry.set( - SellerRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerRequest") } - ) - MappingRegistry.set( - SellerSearch, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerSearch") } - ) - MappingRegistry.set( - SellerSearchDetailsArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerSearchDetails") } - ) - MappingRegistry.set( - SimilarityRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SimilarityRequest") } - ) - MappingRegistry.set( - GetShoppingCartRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "GetShoppingCartRequest") } - ) - MappingRegistry.set( - ShoppingCart, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ShoppingCart") } - ) - MappingRegistry.set( - ItemArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "Item") } - ) - MappingRegistry.set( - SimilarProductsArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") } - ) - MappingRegistry.set( - ClearShoppingCartRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ClearShoppingCartRequest") } - ) - MappingRegistry.set( - AddShoppingCartItemsRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "AddShoppingCartItemsRequest") } - ) - MappingRegistry.set( - AddItemArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "AddItem") } - ) - MappingRegistry.set( - RemoveShoppingCartItemsRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "RemoveShoppingCartItemsRequest") } - ) - MappingRegistry.set( - ItemIdArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") } - ) - MappingRegistry.set( - ModifyShoppingCartItemsRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ModifyShoppingCartItemsRequest") } - ) - MappingRegistry.set( - ItemQuantityArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ItemQuantity") } - ) - MappingRegistry.set( - GetTransactionDetailsRequest, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "GetTransactionDetailsRequest") } - ) - MappingRegistry.set( - OrderIdArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://www.w3.org/2001/XMLSchema", "string") } - ) - MappingRegistry.set( - GetTransactionDetailsResponse, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "GetTransactionDetailsResponse") } - ) - MappingRegistry.set( - ShortSummaryArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ShortSummary") } - ) - MappingRegistry.set( - Details, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "Details") } - ) - MappingRegistry.set( - ProductLine, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ProductLine") } - ) - MappingRegistry.set( - MarketplaceSearchDetails, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "MarketplaceSearchDetails") } - ) - MappingRegistry.set( - SellerProfileDetails, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerProfileDetails") } - ) - MappingRegistry.set( - SellerSearchDetails, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "SellerSearchDetails") } - ) - MappingRegistry.set( - Item, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "Item") } - ) - MappingRegistry.set( - AddItem, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "AddItem") } - ) - MappingRegistry.set( - ItemQuantity, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ItemQuantity") } - ) - MappingRegistry.set( - ShortSummary, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("http://soap.amazon.com", "ShortSummary") } - ) - - Methods = [ - ["KeywordSearchRequest", "keywordSearchRequest", [ - ["in", "KeywordSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "KeywordRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["TextStreamSearchRequest", "textStreamSearchRequest", [ - ["in", "TextStreamSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "TextStreamRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["PowerSearchRequest", "powerSearchRequest", [ - ["in", "PowerSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "PowerRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["BrowseNodeSearchRequest", "browseNodeSearchRequest", [ - ["in", "BrowseNodeSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "BrowseNodeRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["AsinSearchRequest", "asinSearchRequest", [ - ["in", "AsinSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "AsinRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["BlendedSearchRequest", "blendedSearchRequest", [ - ["in", "BlendedSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "BlendedRequest"]], - ["retval", "return", - [::SOAP::SOAPArray, "http://soap.amazon.com", "ProductLine"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["UpcSearchRequest", "upcSearchRequest", [ - ["in", "UpcSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "UpcRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["SkuSearchRequest", "skuSearchRequest", [ - ["in", "SkuSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "SkuRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["AuthorSearchRequest", "authorSearchRequest", [ - ["in", "AuthorSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "AuthorRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["ArtistSearchRequest", "artistSearchRequest", [ - ["in", "ArtistSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ArtistRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["ActorSearchRequest", "actorSearchRequest", [ - ["in", "ActorSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ActorRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["ManufacturerSearchRequest", "manufacturerSearchRequest", [ - ["in", "ManufacturerSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ManufacturerRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["DirectorSearchRequest", "directorSearchRequest", [ - ["in", "DirectorSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "DirectorRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["ListManiaSearchRequest", "listManiaSearchRequest", [ - ["in", "ListManiaSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ListManiaRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["WishlistSearchRequest", "wishlistSearchRequest", [ - ["in", "WishlistSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "WishlistRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["ExchangeSearchRequest", "exchangeSearchRequest", [ - ["in", "ExchangeSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ExchangeRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ListingProductDetails"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["MarketplaceSearchRequest", "marketplaceSearchRequest", [ - ["in", "MarketplaceSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "MarketplaceRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "MarketplaceSearch"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["SellerProfileSearchRequest", "sellerProfileSearchRequest", [ - ["in", "SellerProfileSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerProfileRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerProfile"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["SellerSearchRequest", "sellerSearchRequest", [ - ["in", "SellerSearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "SellerSearch"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["SimilaritySearchRequest", "similaritySearchRequest", [ - ["in", "SimilaritySearchRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "SimilarityRequest"]], - ["retval", "return", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ProductInfo"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["GetShoppingCartRequest", "getShoppingCartRequest", [ - ["in", "GetShoppingCartRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "GetShoppingCartRequest"]], - ["retval", "ShoppingCart", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["ClearShoppingCartRequest", "clearShoppingCartRequest", [ - ["in", "ClearShoppingCartRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ClearShoppingCartRequest"]], - ["retval", "ShoppingCart", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["AddShoppingCartItemsRequest", "addShoppingCartItemsRequest", [ - ["in", "AddShoppingCartItemsRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "AddShoppingCartItemsRequest"]], - ["retval", "ShoppingCart", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["RemoveShoppingCartItemsRequest", "removeShoppingCartItemsRequest", [ - ["in", "RemoveShoppingCartItemsRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "RemoveShoppingCartItemsRequest"]], - ["retval", "ShoppingCart", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["ModifyShoppingCartItemsRequest", "modifyShoppingCartItemsRequest", [ - ["in", "ModifyShoppingCartItemsRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ModifyShoppingCartItemsRequest"]], - ["retval", "ShoppingCart", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "ShoppingCart"]]], - "http://soap.amazon.com", "http://soap.amazon.com"], - ["GetTransactionDetailsRequest", "getTransactionDetailsRequest", [ - ["in", "GetTransactionDetailsRequest", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "GetTransactionDetailsRequest"]], - ["retval", "GetTransactionDetailsResponse", - [::SOAP::SOAPStruct, "http://soap.amazon.com", "GetTransactionDetailsResponse"]]], - "http://soap.amazon.com", "http://soap.amazon.com"] - ] - - DefaultEndpointUrl = "http://soap.amazon.com/onca/soap3" - - def initialize(endpoint_url = nil) - endpoint_url ||= DefaultEndpointUrl - super(endpoint_url, nil) - self.mapping_registry = MappingRegistry - init_methods - end - -private - - def init_methods - Methods.each do |name_as, name, params, soapaction, namespace| - qname = XSD::QName.new(namespace, name_as) - @proxy.add_method(qname, soapaction, name, params) - add_rpc_method_interface(name, params) - end - end -end - diff --git a/sample/wsdl/amazon/sampleClient.rb b/sample/wsdl/amazon/sampleClient.rb deleted file mode 100644 index 3caad84e04..0000000000 --- a/sample/wsdl/amazon/sampleClient.rb +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env ruby - -# This file is a sample based on AmazonSearchServiceClient.rb, which can be -# generated by WSDL file and wsdl2ruby.rb. -# -# $ wsdl2ruby.rb --type client --force \ -# --wsdl http://soap.amazon.com/schemas3/AmazonWebServices.wsdl -# -# See wsdlDriver.rb to use WSDL file directly (slow). -require 'AmazonSearchDriver.rb' - -endpoint_url = ARGV.shift -obj = AmazonSearchPort.new(endpoint_url) - -# Uncomment the below line to see SOAP wiredumps. -# obj.wiredump_dev = STDERR - -# SYNOPSIS -# KeywordSearchRequest(keywordSearchRequest) -# -# ARGS -# keywordSearchRequest KeywordRequest - {urn:PI/DevCentral/SoapService}KeywordRequest -# -# RETURNS -# return ProductInfo - {urn:PI/DevCentral/SoapService}ProductInfo -# -# RAISES -# N/A -# -keywordSearchRequest = KeywordRequest.new("Ruby Object", "1", "books", "webservices-20", "lite", "", "+salesrank") -obj.keywordSearchRequest(keywordSearchRequest).Details.each do |detail| - puts "== #{detail.ProductName}" - puts "Author: #{detail.Authors.join(", ")}" - puts "Release date: #{detail.ReleaseDate}" - puts "List price: #{detail.ListPrice}, our price: #{detail.OurPrice}" - puts -end diff --git a/sample/wsdl/amazon/wsdlDriver.rb b/sample/wsdl/amazon/wsdlDriver.rb deleted file mode 100644 index e62a9a65b3..0000000000 --- a/sample/wsdl/amazon/wsdlDriver.rb +++ /dev/null @@ -1,52 +0,0 @@ -require 'soap/wsdlDriver' - -book = ARGV.shift || "Ruby" - -# AmazonSearch.rb is generated from WSDL. -# Run "wsdl2ruby.rb --wsdl http://soap.amazon.com/schemas3/AmazonWebServices.wsdl --classdef --force" -# http://soap.amazon.com/schemas3/AmazonWebServices.wsdl -require 'AmazonSearch.rb' - -=begin -Or, define the class by yourself like this. - -class KeywordRequest - def initialize(keyword = nil, - page = nil, - mode = nil, - tag = nil, - type = nil, - devtag = nil, - sort = nil) - @keyword = keyword - @page = page - @mode = mode - @tag = tag - @type = type - @devtag = devtag - @sort = sort - end -end -=end - -# You must get 'developer's token" from http://associates.amazon.com/exec/panama/associates/ntg/browse/-/1067662 to use Amazon Web Services 2.0. -#devtag = File.open(File.expand_path("~/.amazon_key")) { |f| f.read }.chomp -devtag = nil - -# v2: AMAZON_WSDL = 'http://soap.amazon.com/schemas2/AmazonWebServices.wsdl' -AMAZON_WSDL = 'http://soap.amazon.com/schemas3/AmazonWebServices.wsdl' -amazon = SOAP::WSDLDriverFactory.new(AMAZON_WSDL).create_driver -p "WSDL loaded" -amazon.generate_explicit_type = true -amazon.mandatorycharset = 'utf-8' # AWS should fix this bug. -#amazon.wiredump_dev = STDERR - -# Show sales rank. -req = KeywordRequest.new(book, "1", "books", "webservices-20", "lite", devtag, "+salesrank") -amazon.KeywordSearchRequest(req).Details.each do |detail| - puts "== #{detail.ProductName}" - puts "Author: #{detail.Authors.join(", ")}" - puts "Release date: #{detail.ReleaseDate}" - puts "List price: #{detail.ListPrice}, our price: #{detail.OurPrice}" - puts -end diff --git a/sample/wsdl/googleSearch/GoogleSearch.rb b/sample/wsdl/googleSearch/GoogleSearch.rb deleted file mode 100644 index e124208b91..0000000000 --- a/sample/wsdl/googleSearch/GoogleSearch.rb +++ /dev/null @@ -1,258 +0,0 @@ -# urn:GoogleSearch -class GoogleSearchResult - @@schema_type = "GoogleSearchResult" - @@schema_ns = "urn:GoogleSearch" - - def documentFiltering - @documentFiltering - end - - def documentFiltering=(value) - @documentFiltering = value - end - - def searchComments - @searchComments - end - - def searchComments=(value) - @searchComments = value - end - - def estimatedTotalResultsCount - @estimatedTotalResultsCount - end - - def estimatedTotalResultsCount=(value) - @estimatedTotalResultsCount = value - end - - def estimateIsExact - @estimateIsExact - end - - def estimateIsExact=(value) - @estimateIsExact = value - end - - def resultElements - @resultElements - end - - def resultElements=(value) - @resultElements = value - end - - def searchQuery - @searchQuery - end - - def searchQuery=(value) - @searchQuery = value - end - - def startIndex - @startIndex - end - - def startIndex=(value) - @startIndex = value - end - - def endIndex - @endIndex - end - - def endIndex=(value) - @endIndex = value - end - - def searchTips - @searchTips - end - - def searchTips=(value) - @searchTips = value - end - - def directoryCategories - @directoryCategories - end - - def directoryCategories=(value) - @directoryCategories = value - end - - def searchTime - @searchTime - end - - def searchTime=(value) - @searchTime = value - end - - def initialize(documentFiltering = nil, - searchComments = nil, - estimatedTotalResultsCount = nil, - estimateIsExact = nil, - resultElements = nil, - searchQuery = nil, - startIndex = nil, - endIndex = nil, - searchTips = nil, - directoryCategories = nil, - searchTime = nil) - @documentFiltering = documentFiltering - @searchComments = searchComments - @estimatedTotalResultsCount = estimatedTotalResultsCount - @estimateIsExact = estimateIsExact - @resultElements = resultElements - @searchQuery = searchQuery - @startIndex = startIndex - @endIndex = endIndex - @searchTips = searchTips - @directoryCategories = directoryCategories - @searchTime = searchTime - end -end - -# urn:GoogleSearch -class ResultElement - @@schema_type = "ResultElement" - @@schema_ns = "urn:GoogleSearch" - - def summary - @summary - end - - def summary=(value) - @summary = value - end - - def URL - @uRL - end - - def URL=(value) - @uRL = value - end - - def snippet - @snippet - end - - def snippet=(value) - @snippet = value - end - - def title - @title - end - - def title=(value) - @title = value - end - - def cachedSize - @cachedSize - end - - def cachedSize=(value) - @cachedSize = value - end - - def relatedInformationPresent - @relatedInformationPresent - end - - def relatedInformationPresent=(value) - @relatedInformationPresent = value - end - - def hostName - @hostName - end - - def hostName=(value) - @hostName = value - end - - def directoryCategory - @directoryCategory - end - - def directoryCategory=(value) - @directoryCategory = value - end - - def directoryTitle - @directoryTitle - end - - def directoryTitle=(value) - @directoryTitle = value - end - - def initialize(summary = nil, - uRL = nil, - snippet = nil, - title = nil, - cachedSize = nil, - relatedInformationPresent = nil, - hostName = nil, - directoryCategory = nil, - directoryTitle = nil) - @summary = summary - @uRL = uRL - @snippet = snippet - @title = title - @cachedSize = cachedSize - @relatedInformationPresent = relatedInformationPresent - @hostName = hostName - @directoryCategory = directoryCategory - @directoryTitle = directoryTitle - end -end - -# urn:GoogleSearch -class ResultElementArray < Array - # Contents type should be dumped here... - @@schema_type = "ResultElementArray" - @@schema_ns = "urn:GoogleSearch" -end - -# urn:GoogleSearch -class DirectoryCategoryArray < Array - # Contents type should be dumped here... - @@schema_type = "DirectoryCategoryArray" - @@schema_ns = "urn:GoogleSearch" -end - -# urn:GoogleSearch -class DirectoryCategory - @@schema_type = "DirectoryCategory" - @@schema_ns = "urn:GoogleSearch" - - def fullViewableName - @fullViewableName - end - - def fullViewableName=(value) - @fullViewableName = value - end - - def specialEncoding - @specialEncoding - end - - def specialEncoding=(value) - @specialEncoding = value - end - - def initialize(fullViewableName = nil, - specialEncoding = nil) - @fullViewableName = fullViewableName - @specialEncoding = specialEncoding - end -end - diff --git a/sample/wsdl/googleSearch/GoogleSearchDriver.rb b/sample/wsdl/googleSearch/GoogleSearchDriver.rb deleted file mode 100644 index 9901b89071..0000000000 --- a/sample/wsdl/googleSearch/GoogleSearchDriver.rb +++ /dev/null @@ -1,101 +0,0 @@ -require 'GoogleSearch.rb' - -require 'soap/rpc/driver' - -class GoogleSearchPort < SOAP::RPC::Driver - MappingRegistry = ::SOAP::Mapping::Registry.new - - MappingRegistry.set( - GoogleSearchResult, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("urn:GoogleSearch", "GoogleSearchResult") } - ) - MappingRegistry.set( - ResultElementArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("urn:GoogleSearch", "ResultElement") } - ) - MappingRegistry.set( - DirectoryCategoryArray, - ::SOAP::SOAPArray, - ::SOAP::Mapping::Registry::TypedArrayFactory, - { :type => XSD::QName.new("urn:GoogleSearch", "DirectoryCategory") } - ) - MappingRegistry.set( - ResultElement, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("urn:GoogleSearch", "ResultElement") } - ) - MappingRegistry.set( - DirectoryCategory, - ::SOAP::SOAPStruct, - ::SOAP::Mapping::Registry::TypedStructFactory, - { :type => XSD::QName.new("urn:GoogleSearch", "DirectoryCategory") } - ) - - Methods = [ - ["doGetCachedPage", "doGetCachedPage", [ - ["in", "key", - [SOAP::SOAPString]], - ["in", "url", - [SOAP::SOAPString]], - ["retval", "return", - [SOAP::SOAPBase64]]], - "urn:GoogleSearchAction", "urn:GoogleSearch"], - ["doSpellingSuggestion", "doSpellingSuggestion", [ - ["in", "key", - [SOAP::SOAPString]], - ["in", "phrase", - [SOAP::SOAPString]], - ["retval", "return", - [SOAP::SOAPString]]], - "urn:GoogleSearchAction", "urn:GoogleSearch"], - ["doGoogleSearch", "doGoogleSearch", [ - ["in", "key", - [SOAP::SOAPString]], - ["in", "q", - [SOAP::SOAPString]], - ["in", "start", - [SOAP::SOAPInt]], - ["in", "maxResults", - [SOAP::SOAPInt]], - ["in", "filter", - [SOAP::SOAPBoolean]], - ["in", "restrict", - [SOAP::SOAPString]], - ["in", "safeSearch", - [SOAP::SOAPBoolean]], - ["in", "lr", - [SOAP::SOAPString]], - ["in", "ie", - [SOAP::SOAPString]], - ["in", "oe", - [SOAP::SOAPString]], - ["retval", "return", - [::SOAP::SOAPStruct, "urn:GoogleSearch", "GoogleSearchResult"]]], - "urn:GoogleSearchAction", "urn:GoogleSearch"] - ] - - DefaultEndpointUrl = "http://api.google.com/search/beta2" - - def initialize(endpoint_url = nil) - endpoint_url ||= DefaultEndpointUrl - super(endpoint_url, nil) - self.mapping_registry = MappingRegistry - init_methods - end - -private - - def init_methods - Methods.each do |name_as, name, params, soapaction, namespace| - qname = XSD::QName.new(namespace, name_as) - @proxy.add_method(qname, soapaction, name, params) - add_rpc_method_interface(name, params) - end - end -end - diff --git a/sample/wsdl/googleSearch/README b/sample/wsdl/googleSearch/README deleted file mode 100644 index 461a5634dc..0000000000 --- a/sample/wsdl/googleSearch/README +++ /dev/null @@ -1,6 +0,0 @@ -wsdlDriver.rb: Do google search using WSDL. - -Whole files except wsdl.rb in this directory is created by wsdl2ruby.rb from -GoogleSearch.wsdl with options; - -% wsdl2ruby.rb --wsdl http://api.google.com/GoogleSearch.wsdl --classdef --client_skelton --servant_skelton --cgi_stub --standalone_server_stub --driver --force diff --git a/sample/wsdl/googleSearch/httpd.rb b/sample/wsdl/googleSearch/httpd.rb deleted file mode 100644 index bebcff96c6..0000000000 --- a/sample/wsdl/googleSearch/httpd.rb +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env ruby - -require 'webrick' -require 'soap/property' - -docroot = "." -port = 8808 -if opt = SOAP::Property.loadproperty("samplehttpd.conf") - docroot = opt["docroot"] - port = Integer(opt["port"]) -end - -s = WEBrick::HTTPServer.new( - :BindAddress => "0.0.0.0", - :Port => port, - :DocumentRoot => docroot, - :CGIPathEnv => ENV['PATH'] -) -trap(:INT){ s.shutdown } -s.start diff --git a/sample/wsdl/googleSearch/sampleClient.rb b/sample/wsdl/googleSearch/sampleClient.rb deleted file mode 100644 index b05d57be54..0000000000 --- a/sample/wsdl/googleSearch/sampleClient.rb +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env ruby - -# This file is a sample based on GoogleSearchClient.rb, which can be -# generated by WSDL file and wsdl2ruby.rb. -# -# $ wsdl2ruby.rb --type client --force \ -# --wsdl http://api.google.com/GoogleSearch.wsdl -# -# See wsdlDriver.rb to use WSDL file directly (slow). -require 'GoogleSearchDriver.rb' - -endpoint_url = ARGV.shift -obj = GoogleSearchPort.new(endpoint_url) - -# Uncomment the below line to see SOAP wiredumps. -# obj.wiredump_dev = STDERR - -# SYNOPSIS -# doGoogleSearch(key, q, start, maxResults, filter, restrict, safeSearch, lr, ie, oe) -# -# ARGS -# key - {http://www.w3.org/2001/XMLSchema}string -# q - {http://www.w3.org/2001/XMLSchema}string -# start - {http://www.w3.org/2001/XMLSchema}int -# maxResults - {http://www.w3.org/2001/XMLSchema}int -# filter - {http://www.w3.org/2001/XMLSchema}boolean -# restrict - {http://www.w3.org/2001/XMLSchema}string -# safeSearch - {http://www.w3.org/2001/XMLSchema}boolean -# lr - {http://www.w3.org/2001/XMLSchema}string -# ie - {http://www.w3.org/2001/XMLSchema}string -# oe - {http://www.w3.org/2001/XMLSchema}string -# -# RETURNS -# return GoogleSearchResult - {urn:GoogleSearch}GoogleSearchResult -# -# RAISES -# N/A -# -key = q = start = maxResults = filter = restrict = safeSearch = lr = ie = oe = nil -key = File.open(File.expand_path("~/.google_key")) { |f| f.read }.chomp -q = "Ruby" -start = 0 -maxResults = 10 -filter = false -restrict = "" -safeSearch = false -lr = "" -ie = "utf-8" -oe = "utf-8" -result = obj.doGoogleSearch(key, q, start, maxResults, filter, restrict, safeSearch, lr, ie, oe) - -result.resultElements.each do |ele| - puts "== #{ele.title}: #{ele.URL}" - puts ele.snippet - puts -end diff --git a/sample/wsdl/googleSearch/samplehttpd.conf b/sample/wsdl/googleSearch/samplehttpd.conf deleted file mode 100644 index 85e9995021..0000000000 --- a/sample/wsdl/googleSearch/samplehttpd.conf +++ /dev/null @@ -1,2 +0,0 @@ -docroot = . -port = 8808 diff --git a/sample/wsdl/googleSearch/sjissearch.sh b/sample/wsdl/googleSearch/sjissearch.sh deleted file mode 100644 index b8efb20647..0000000000 --- a/sample/wsdl/googleSearch/sjissearch.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - - -ruby -Ks wsdlDriver.rb 'Ruby ‚È‚Ð' diff --git a/sample/wsdl/googleSearch/wsdlDriver.rb b/sample/wsdl/googleSearch/wsdlDriver.rb deleted file mode 100644 index 9059aed2df..0000000000 --- a/sample/wsdl/googleSearch/wsdlDriver.rb +++ /dev/null @@ -1,23 +0,0 @@ -#require 'uconv' -require 'soap/wsdlDriver' - -word = ARGV.shift -# You must get key from http://www.google.com/apis/ to use Google Web APIs. -key = File.open(File.expand_path("~/.google_key")) { |f| f.read }.chomp - -GOOGLE_WSDL = 'http://api.google.com/GoogleSearch.wsdl' -# GOOGLE_WSDL = 'GoogleSearch.wsdl' - -def html2rd(str) - str.gsub(%r(<b>(.*?)</b>), '((*\\1*))').strip -end - - -google = SOAP::WSDLDriverFactory.new(GOOGLE_WSDL).create_driver -#google.wiredump_dev = STDERR -result = google.doGoogleSearch( key, word, 0, 10, false, "", false, "", 'utf-8', 'utf-8' ) -result.resultElements.each do |ele| - puts "== #{html2rd(ele.title)}: #{ele.URL}" - puts html2rd(ele.snippet) - puts -end diff --git a/sample/wsdl/raa/raa.wsdl b/sample/wsdl/raa/raa.wsdl deleted file mode 100644 index 78376893dd..0000000000 --- a/sample/wsdl/raa/raa.wsdl +++ /dev/null @@ -1,264 +0,0 @@ -<?xml version="1.0"?> -<definitions - name="RAA" - targetNamespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/" - xmlns:tns="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/" - xmlns:txd="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/" - xmlns="http://schemas.xmlsoap.org/wsdl/" - xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" - xmlns:xsd="http://www.w3.org/2001/XMLSchema" - xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" - xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" - xmlns:apachesoap="http://xml.apache.org/xml-soap"> - - <types> - <schema - xmlns="http://www.w3.org/2001/XMLSchema" - targetNamespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"> - - <complexType name="Category"> - <all> - <element name="major" type="string"/> - <element name="minor" type="string"/> - </all> - </complexType> - - <complexType name="Product"> - <all> - <element name="id" type="int"/> - <element name="name" type="string"/> - <element name="short_description" type="string"/> - <element name="version" type="string"/> - <element name="status" type="string"/> - <element name="homepage" type="anyURI"/> - <element name="download" type="anyURI"/> - <element name="license" type="string"/> - <element name="description" type="string"/> - </all> - </complexType> - - <complexType name="Owner"> - <all> - <element name="id" type="int"/> - <element name="email" type="anyURI"/> - <element name="name" type="string"/> - </all> - </complexType> - - <complexType name="Info"> - <all> - <element name="category" type="txd:Category"/> - <element name="product" type="txd:Product"/> - <element name="owner" type="txd:Owner"/> - <element name="created" type="xsd:dateTime"/> - <element name="updated" type="xsd:dateTime"/> - </all> - </complexType> - - <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/> - <complexType name="InfoArray"> - <complexContent> - <restriction base="soapenc:Array"> - <attribute ref="soapenc:arrayType" wsdl:arrayType="txd:Info[]"/> - </restriction> - </complexContent> - </complexType> - - <complexType name="StringArray"> - <complexContent> - <restriction base="soapenc:Array"> - <attribute ref="soapenc:arrayType" wsdl:arrayType="xsd:string[]"/> - </restriction> - </complexContent> - </complexType> - </schema> - - <!-- type definition for ApacheSOAP's Map --> - <schema - xmlns="http://www.w3.org/2001/XMLSchema" - targetNamespace="http://xml.apache.org/xml-soap"> - <complexType name="Map"> - <sequence> - <element name="item" minOccurs="0" maxOccurs="unbounded"> - <complexType> - <sequence> - <element name="key" type="anyType" /> - <element name="value" type="anyType" /> - </sequence> - </complexType> - </element> - </sequence> - </complexType> - </schema> - </types> - - <message name="getAllListingsRequest"/> - <message name="getAllListingsResponse"> - <part name="return" type="txd:StringArray"/> - </message> - - <message name="getProductTreeRequest"/> - <message name="getProductTreeResponse"> - <part name="return" type="apachesoap:Map"/> - </message> - - <message name="getInfoFromCategoryRequest"> - <part name="category" type="txd:Category"/> - </message> - <message name="getInfoFromCategoryResponse"> - <part name="return" type="txd:InfoArray"/> - </message> - - <message name="getModifiedInfoSinceRequest"> - <part name="timeInstant" type="xsd:dateTime"/> - </message> - <message name="getModifiedInfoSinceResponse"> - <part name="return" type="txd:InfoArray"/> - </message> - - <message name="getInfoFromNameRequest"> - <part name="productName" type="xsd:string"/> - </message> - <message name="getInfoFromNameResponse"> - <part name="return" type="txd:Info"/> - </message> - - <message name="getInfoFromOwnerIdRequest"> - <part name="ownerId" type="xsd:int"/> - </message> - <message name="getInfoFromOwnerIdResponse"> - <part name="return" type="txd:InfoArray"/> - </message> - - <portType name="RAABaseServicePortType"> - <operation name="getAllListings" - parameterOrder=""> - <input message="tns:getAllListingsRequest"/> - <output message="tns:getAllListingsResponse"/> - </operation> - - <operation name="getProductTree" - parameterOrder=""> - <input message="tns:getProductTreeRequest"/> - <output message="tns:getProductTreeResponse"/> - </operation> - - <operation name="getInfoFromCategory" - parameterOrder="category"> - <input message="tns:getInfoFromCategoryRequest"/> - <output message="tns:getInfoFromCategoryResponse"/> - </operation> - - <operation name="getModifiedInfoSince" - parameterOrder="timeInstant"> - <input message="tns:getModifiedInfoSinceRequest"/> - <output message="tns:getModifiedInfoSinceResponse"/> - </operation> - - <operation name="getInfoFromName" - parameterOrder="productName"> - <input message="tns:getInfoFromNameRequest"/> - <output message="tns:getInfoFromNameResponse"/> - </operation> - - <operation name="getInfoFromOwnerId" - parameterOrder="ownerId"> - <input message="tns:getInfoFromOwnerIdRequest"/> - <output message="tns:getInfoFromOwnerIdResponse"/> - </operation> - </portType> - - <binding name="RAABaseServicePortBinding" type="tns:RAABaseServicePortType"> - <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> - - <operation name="getAllListings"> - <soap:operation soapAction=""/> - <input> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </input> - <output> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </output> - </operation> - - <operation name="getProductTree"> - <soap:operation soapAction=""/> - <input> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </input> - <output> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </output> - </operation> - - <operation name="getInfoFromCategory"> - <soap:operation soapAction=""/> - <input> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </input> - <output> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </output> - </operation> - - <operation name="getModifiedInfoSince"> - <soap:operation soapAction=""/> - <input> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </input> - <output> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </output> - </operation> - - <operation name="getInfoFromName"> - <soap:operation soapAction=""/> - <input> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </input> - <output> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </output> - </operation> - - <operation name="getInfoFromOwnerId"> - <soap:operation soapAction=""/> - <input> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </input> - <output> - <soap:body use="encoded" - encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" - namespace="http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/"/> - </output> - </operation> - </binding> - - <service name="RAAService"> - <port name="RAABaseServicePort" binding="tns:RAABaseServicePortBinding"> - <soap:address location="http://raa.ruby-lang.org/soap/1.0.2/"/> - </port> - </service> -</definitions> diff --git a/sample/wsdl/raa/soap4r.rb b/sample/wsdl/raa/soap4r.rb deleted file mode 100644 index a70b3b5b21..0000000000 --- a/sample/wsdl/raa/soap4r.rb +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env ruby - -require 'soap/wsdlDriver' -wsdl = 'http://www.ruby-lang.org/xmlns/soap/interface/RAA/0.0.2/' -raa = SOAP::WSDLDriverFactory.new(wsdl).create_driver -raa.generate_explicit_type = true -p "WSDL loaded." - -class Category - def initialize(major, minor) - @major = major - @minor = minor - end -end - -p raa.getAllListings().sort - -p raa.getProductTree() - -p raa.getInfoFromCategory(Category.new("Library", "XML")) - -t = Time.at(Time.now.to_i - 24 * 3600) -p raa.getModifiedInfoSince(t) - -p raa.getModifiedInfoSince(DateTime.new(t.year, t.mon, t.mday, t.hour, t.min, t.sec)) - -o = raa.getInfoFromName("SOAP4R") -p o.type -p o.owner.name -p o - |
