code
stringlengths
1
1.73M
language
stringclasses
1 value
=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))
Ruby
=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:0x4...
Ruby
require 'drb/drb' require 'rinda/tuplespace' uri = ARGV.shift DRb.start_service(uri, Rinda::TupleSpace.new) puts DRb.uri DRb.thread.join
Ruby
#!/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::...
Ruby
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.ne...
Ruby
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...
Ruby
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.reo...
Ruby
=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("#{Ti...
Ruby
# # 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 = interva...
Ruby
=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")
Ruby
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
Ruby
=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...
Ruby
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_an...
Ruby
=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>...
Ruby
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...
Ruby
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 ...
Ruby
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) s1.thread.join s2.thread.join
Ruby
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
Ruby
=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 DRb.thread.join
Ruby
#!/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, o...
Ruby
# # 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(f...
Ruby
=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 Dhase...
Ruby
=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 DRb.thread.join
Ruby
=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 ...
Ruby
=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 ini...
Ruby
#!/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(...
Ruby
=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 mut...
Ruby
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...
Ruby
=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 == the...
Ruby
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
Ruby
#!/usr/bin/env ruby if ARGV[0] == "-c" out_stdout = 1 ARGV.shift end $sawbegin = 0 $sawend = 0 while line = gets() if /^begin\s*(\d*)\s*(\S*)/ =~ line $mode, $file = $1, $2 $sawbegin+=1 if out_stdout out = STDOUT else out = open($file, "w") if $file != "" end out.binmode ...
Ruby
# calculate Fibonacci(20) # for benchmark def fib(n) if n<2 n else fib(n-2)+fib(n-1) end end print(fib(20), "\n");
Ruby
line = '' indent = 0 $stdout.sync = true print "ruby> " loop do l = gets if l.nil? break if line.empty? else line += l if l =~ /,\s*$/ print "ruby| " next end if l =~ /^\s*(class|module|def|if|unless|case|while|until|for|begin)\b[^_]/ indent += 1 end if l =~ /^\s*end\...
Ruby
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, :SSLEna...
Ruby
require "webrick" class HelloServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET(req, res) res["content-type"] = "text/plain" res.body = "Hello, world.\n" end end
Ruby
require "webrick" require "./demo-app" class DemoServlet < WEBrick::HTTPServlet::AbstractServlet include DemoApplication end
Ruby
require "webrick" require "webrick/httpproxy" # The :ProxyContentHandler proc will be invoked before sending a response to # the User-Agent. You can inspect the pair of request and response messages # (or edit the response message if necessary). pch = Proc.new{|req, res| p [ req.request_line, res.status_line ] } ...
Ruby
#!/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
Ruby
#!/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
Ruby
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" encty...
Ruby
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...
Ruby
#!/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
Ruby
# 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) addr = gs.addr addr.shift printf("server is on %s\n", addr.join(":")) socks = [gs] loop do nsock = select(socks); ...
Ruby
#! /usr/bin/env ruby b = Time.now system(*ARGV) e = Time.now 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)
Ruby
# ioctl example works on Sun CBREAK = 0x00000002 ECHO = 0x00000008 TIOCGETP = 0x40067408 TIOCSETP = 0x80067409 def cbreak () set_cbreak(true) end def cooked () set_cbreak(false) end def set_cbreak (on) tty = "\0" * 256 STDIN.ioctl(TIOCGETP, tty) ttys = tty.unpack("C4 S") if on ttys[4] |= CBREAK ...
Ruby
# 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
Ruby
# 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'
Ruby
# 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
Ruby
# 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 add...
Ruby
# 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, @subtr...
Ruby
# Linked list example -- short version # using inspect class Point def initialize(x, y) @x = x; @y = y self end def to_s 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") print("list2: ", ...
Ruby
require 'timeout' def progress(n = 5) n.times {|i| print i; STDOUT.flush; sleep 1; i+= 1} puts "never reach" end p timeout(5) { 45 } p timeout(5, TimeoutError) { 45 } p timeout(nil) { 54 } p timeout(0) { 54 } begin timeout(5) {progress} rescue => e puts e.message end begin timeout(3) { begin ...
Ruby
#! ./ruby # split into multi part # usage: mpart.rb [-nnn] file.. lines = 1000 if (ARGV[0] =~ /^-(\d+)$/ ) lines = $1.to_i; ARGV.shift; end basename = ARGV[0] extname = "part" part = 1 line = 0 fline = 0 for i in ifp = open(basename) fline = fline + 1 end ifp.close parts = fline / lines + 1 for i in ifp = ...
Ruby
# random dot steraogram # usage: rcs.rb rcs.dat sw = 40.0 # width of original pattern dw = 78.0 # width of generating Random Character Streogram hdw = dw / 2.0 w = 20.0 # distance between eyes h =1.0 # distance from screen and base plane d = 0.2 # z value unit ss="abcdefghijklmnopqrstuvwxyz0123456789#!$%^&*()-=\\[];...
Ruby
#! /usr/local/bin/ruby ZCAT = "/usr/local/bin/zcat" LESS = "/usr/local/bin/less" FILE = ARGV.pop OPTION = (if ARGV.length == 0; "" else ARGV.join(" "); end) if FILE =~ /\.(Z|gz)$/ exec(format("%s %s | %s %s", ZCAT, FILE, LESS, OPTION)) elsif FILE == nil exec(format("%s %s", LESS, OPTION)) else print(format("%s...
Ruby
# simple webpage fetcher # The code demonstrates how a multi-protocol client should be written. # TCPSocket is using getaddrinfo() internally, so there should be no problem. require "socket" if ARGV.size != 1 STDERR.print "requires URL\n" exit end url = ARGV[0] if url !~ /^http:\/\/([^\/]+)(\/.*)$/ STDERR.pri...
Ruby
$/ = nil while line = gets() 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+),/ type = $2...
Ruby
# 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 pat...
Ruby
#!/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{docume...
Ruby
# 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
Ruby
def fact(n) return 1 if n == 0 f = 1 n.downto(1) do |i| f *= i end return f end print fact(ARGV[0].to_i), "\n"
Ruby
# word occurrence listing # usege: ruby occur2.rb file.. freq = {} ARGF.each_line do |line| for word in line.split(/\W+/) freq[word] ||= 0 freq[word] += 1 end end for word in freq.keys.sort printf("%s -- %d\n", word, freq[word]) end
Ruby
require 'openssl' require 'optparse' include OpenSSL options = ARGV.getopts("c:k: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)) data = "Content-Type: text/plain\r\n" data << "\r\n" data <<...
Ruby
require 'optparse' require 'openssl' include OpenSSL options = ARGV.getopts("c:k: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) data = p7e...
Ruby
#!/usr/bin/env ruby require 'openssl' 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 "--Encrypting--" enc = OpenSSL::Cipher::Cipher.new(alg) enc...
Ruby
#!/usr/bin/env ruby require 'socket' require 'openssl' require 'optparse' options = ARGV.getopts("p:c:k:C:") host = ARGV[0] || "localhost" 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 ...
Ruby
#!/usr/bin/env ruby require 'socket' require 'openssl' require 'optparse' options = ARGV.getopts("p:c:k: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 = ...
Ruby
require 'c_rehash' require 'crlstore' class CertStore include OpenSSL include X509 attr_reader :self_signed_ca attr_reader :other_ca attr_reader :ee attr_reader :crl attr_reader :request def initialize(certs_dir) @certs_dir = certs_dir @c_store = CHashDir.new(@certs_dir) @c_store.hash_di...
Ruby
#!/usr/bin/env ruby require 'openssl' include OpenSSL::X509 def cert2text(cert_str) [Certificate, CRL, Request].each do |klass| begin puts klass.new(cert_str).to_text return rescue end end raise ArgumentError.new('Unknown format.') end if ARGV.empty? cert2text(STDIN.read) else ARGV....
Ruby
#!/usr/bin/env ruby require 'openssl' require 'digest/md5' class CHashDir include Enumerable def initialize(dirpath) @dirpath = dirpath @fingerprint_cache = @cert_cache = @crl_cache = nil end def hash_dir(silent = false) # ToDo: Should lock the directory... @silent = silent @fingerprint_...
Ruby
#!/usr/bin/env ruby require 'net/https' require 'optparse' options = ARGV.getopts('C:') cert_store = options["C"] uri = URI.parse(ARGV[0]) if proxy = ENV['HTTP_PROXY'] prx_uri = URI.parse(proxy) prx_host = prx_uri.host prx_port = prx_uri.port end h = Net::HTTP.new(uri.host, uri.port, prx_host, prx_port) h.se...
Ruby
begin require 'http-access2' rescue LoadError STDERR.puts("Cannot load http-access2. CRL might not be fetched.") end require 'c_rehash' class CrlStore def initialize(c_store) @c_store = c_store @c_store.hash_dir(true) end def find_crl(cert) do_find_crl(cert) end private def do_find_crl(c...
Ruby
#!/usr/bin/env ruby require 'optparse' require 'openssl' include OpenSSL def usage myname = File::basename($0) $stderr.puts <<EOS Usage: #{myname} [--key keypair_file] name name ... ex. /C=JP/O=RRR/OU=CA/CN=NaHi/emailAddress=nahi@example.org EOS exit end options = ARGV.getopts(nil, "key:", "csrout:", "keyou...
Ruby
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 = pr...
Ruby
# socket example - client side # usage: ruby clnt.rb [host] port require "socket" if ARGV.length >= 2 host = ARGV.shift else host = "localhost" end print("Trying ", host, " ...") STDOUT.flush s = TCPSocket.open(host, ARGV.shift) print(" done\n") print("addr: ", s.addr.join(":"), "\n") print("peer: ", s.peeraddr.j...
Ruby
#! /usr/local/bin/ruby 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) if File.file?(fpath) && (File.stat(fpath).mode & 022) != 0 printf("file %s is writable from other users\n", fpath) end end ...
Ruby
#! /usr/local/bin/ruby # convert ls-lR filename into fullpath. if ARGV[0] =~ /-p/ ARGV.shift path = ARGV.shift end if path == nil path = "" elsif path !~ %r|/$| path += "/" end while line = gets() case line when /:$/ path = line.chop.chop + "/" when /^total/, /^d/ when /^(.*\d )(.+)$/ print($...
Ruby
# socket example - server side using thread # usage: ruby tsvr.rb require "socket" gs = TCPServer.open(0) addr = gs.addr addr.shift printf("server is on %s\n", addr.join(":")) loop do Thread.start(gs.accept) do |s| print(s, " is accepted\n") while line = s.gets s.write(line) end print(s, " is...
Ruby
# Linked list example class MyElem # object initializer called from Class#new def initialize(item) # @variables are instance variable, no declaration needed @data = item @succ = nil @head = nil end def data @data end def succ @succ end # the method invoked by ``obj.data = val'...
Ruby
# simple httpd # 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) sockpool = [] names = [] threads = [] res.each do |i| s = TCPServer.new(i[3], i[1]) n = Socke...
Ruby
# method access permission # output: # foobar # Foo class Foo public :printf def baz print "baz\n" end private :baz def quux print "in QUUX " baz() end end def foobar print "foobar\n" end f = Foo.new #Foo.private :printf class Foo # redefines foobar's scope public :foobar end f.foobar ...
Ruby
#! /usr/local/bin/ruby require "time" require "kconv" class String def kjust(len) res = '' rlen = 0 self.each_char do |char| delta = char.bytesize > 1 ? 2 : 1 break if rlen + delta > len rlen += delta res += char end res += ' ' * (len - rlen) if rlen < len res end e...
Ruby
# Linked list example -- short version class Point def initialize(x, y) @x = x; @y = y self end def to_s 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") print("list2:\n", list2.join("...
Ruby
#!/usr/bin/ruby -I. require 'optparse' require 'optparse/time' require 'pp' # keywords CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary] CODE_ALIASES = {"jis" => "iso-2022-jp", "sjis" => "shift_jis"} POSSIBLE_CODES = "(#{(CODES+CODE_ALIASES.keys).join(',')})" ARGV.options do |opts| opts.banner << " argv..." ...
Ruby
#! /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'] =...
Ruby
#! /usr/bin/env ruby # 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' class Cal START = { 'cn' => Date::GREGORIAN, # China 'de' => 2342032, # Germany (protestant states) 'dk' => 2342032, # Denmark 'e...
Ruby
#!/usr/local/bin/ruby # # biorhythm.rb - # $Release Version: $ # $Revision: 31573 $ # by Yasuo OHBA(STAFS Development Room) # # -- # # # # probably based on: # # Newsgroups: comp.sources.misc,de.comp.sources.os9 # From: fkk@stasys.sta.sub....
Ruby
# # 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...
Ruby
# # 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' $shells = [] $n_shells = 0 $r_pty = nil $w_pty = nil def writer system "stty -echo raw" be...
Ruby
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 ...
Ruby
# word occurrence listing # usege: ruby occur.rb file.. freq = Hash.new(0) while line = gets() for word in line.split(/\W+/) freq[word] += 1 end end for word in freq.keys.sort! print word, " -- ", freq[word], "\n" end
Ruby
#! /usr/local/bin/ruby require "thread" require "observer" class Tick include Observable def initialize Thread.start do loop do sleep 0.999 now = Time.now changed notify_observers(now.hour, now.min, now.sec) end end end end class Clock def initialize(tick) @tick = tick @tick.a...
Ruby
#! /usr/bin/env ruby # -*- coding: us-ascii -*- $testnum=0 $ntest=0 $failed = 0 def test_check(what) STDERR.print "\nsample/test.rb:#{what} " $what = what $testnum = 0 end def test_ok(cond,n=1) $testnum+=1 $ntest+=1 where = (st = caller(n)) ? st[0] : "caller error! (n=#{n}, trace=#{caller(0).join(', ')}"...
Ruby
# sieve of Eratosthenes max = Integer(ARGV.shift || 100) sieve = [] for i in 2 .. max sieve[i] = i end for i in 2 .. Math.sqrt(max) next unless sieve[i] (i*i).step(max, i) do |j| sieve[j] = nil end end puts sieve.compact.join(", ")
Ruby
#!/usr/bin/env ruby require "rss" feeds = [] verbose = false encoding = "UTF-8" def error(exception) mark = "=" * 20 mark = "#{mark} error #{mark}" STDERR.puts mark STDERR.puts exception.class STDERR.puts exception.message STDERR.puts exception.backtrace STDERR.puts mark end before_time = Time.now ARG...
Ruby
#!/usr/bin/env ruby require "rss" def error(exception) mark = "=" * 20 mark = "#{mark} error #{mark}" puts mark puts exception.class puts exception.message puts exception.backtrace puts mark end verbose = false before_time = Time.now ARGV.each do |fname| if fname == '-v' verbose = true next ...
Ruby
#!/usr/bin/env ruby require "rss" feeds = [] verbose = false encoding = "UTF-8" to_version = "1.0" def error(exception) mark = "=" * 20 mark = "#{mark} error #{mark}" STDERR.puts mark STDERR.puts exception.class STDERR.puts exception.message STDERR.puts exception.backtrace STDERR.puts mark end before_...
Ruby
#!/usr/bin/env ruby require "nkf" class String # From tdiary.rb def shorten( len = 120 ) lines = NKF::nkf( "-t -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ ) lines[0].concat( '...' ) if lines[0] and lines[1] lines[0] end end require "rss" items = [] verbose = false def error(exception) ma...
Ruby
#!/usr/bin/env ruby require "nkf" class String # From tdiary.rb def shorten( len = 120 ) lines = NKF::nkf( "-t -m0 -f#{len}", self.gsub( /\n/, ' ' ) ).split( /\n/ ) lines[0].concat( '...' ) if lines[0] and lines[1] lines[0] end end require "rss" channels = {} verbose = false def error(exception) ...
Ruby
# # 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 end $state = "-o"*N def wait sleep rand(20)/10.0 end def think(n) wait end def eat(n) wait end def philosopher(n) while true think n $fork...
Ruby