code stringlengths 1 1.73M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env ruby
require 'logger'
logfile = 'shifting.log'
# Max 3 age ... logShifting.log, logShifting.log.0, and logShifting.log.1
shift_age = 3
# Shift log file about for each 1024 bytes.
shift_size = 1024
log = Logger.new(logfile, shift_age, shift_size)
def do_log(log)
log.debug('do_log1') { 'd' * rand(100... | Ruby |
#!/usr/local/bin/ruby
k, a, b, a1, b1 = 2, 4, 1, 12, 4
loop do
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d = a / b
d1 = a1 / b1
while d == d1
print d
$stdout.flush
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
end
e... | 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/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 |
require 'getopts'
require 'openssl'
include OpenSSL
getopts nil, "c:", "k:", "C:"
cert_file = $OPT_c
key_file = $OPT_k
ca_path = $OPT_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 = p7enc.decrypt(key, cert)
... | Ruby |
#!/usr/bin/env ruby
require 'getopts'
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
getopts nil, "key:", "csrout:", "keyout:"
keypair_file... | 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 |
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 |
require 'openssl'
require 'getopts'
include OpenSSL
getopts nil, "c:", "k:", "r:"
cert_file = $OPT_c
key_file = $OPT_k
rcpt_file = $OPT_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 << "This is a clear-sign... | Ruby |
#!/usr/bin/env ruby
require 'openssl'
text = "abcdefghijklmnopqrstuvwxyz"
pass = "secret password"
salt = "8 octets" # or nil
alg = "DES-EDE3-CBC"
#alg = "AES-128-CBC"
puts "--Setup--"
puts %(clear text: "#{text}")
puts %(password: "#{pass}")
puts %(salt: "#{salt}")
puts %(cipher alg: "#{al... | 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 'net/https'
require 'getopts'
getopts nil, 'C:'
ca_path = $OPT_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.set_debug_output($stder... | Ruby |
#!/usr/bin/env ruby
require 'socket'
require 'openssl'
require 'getopts'
getopts nil, "p:2000", "c:", "k:", "C:"
port = $OPT_p
cert_file = $OPT_c
key_file = $OPT_k
ca_path = $OPT_C
if cert_file && key_file
cert = OpenSSL::X509::Certificate.new(File::read(cert_file))
key = OpenSSL::PKey::RSA.new(File::r... | Ruby |
#!/usr/bin/env ruby
require 'socket'
require 'openssl'
require 'getopts'
getopts nil, "p:2000", "c:", "k:", "C:"
host = ARGV[0] || "localhost"
port = $OPT_p
cert_file = $OPT_c
key_file = $OPT_k
ca_path = $OPT_C
ctx = OpenSSL::SSL::SSLContext.new()
if cert_file && key_file
ctx.cert = OpenSSL::X509::Ce... | 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 '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... | 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 |
# 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
| 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 |
$/ = nil
while line = gets()
if /^((void|VALUE|int|char *\*|ID|struct [\w_]+ *\*|st_table *\*) *)?\n([\w\d_]+)\(.*\)\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_]+),/... | Ruby |
# 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"
end
end
dirp.close
| 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
end
def data
@data
end
def succ
@succ
end
# the method invoked by ``obj.data = val''
def succ=(ne... | Ruby |
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)
| 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 |
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 |
#! /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 |
# word occurrence listing
# usege: ruby occur.rb file..
freq = Hash.new(0)
while gets()
for word in split(/\W+/)
freq[word] += 1
end
end
for word in freq.keys.sort!
print word, " -- ", freq[word], "\n"
end
| 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 |
require 'erb'
class ERB
class ERBString < String
def to_s; self; end
def erb_concat(s)
if self.class === s
concat(s)
else
concat(erb_quote(s))
end
end
def erb_quote(s); s; end
end
end
class ERB4Html < ERB
def self.quoted(s)
HtmlString.new(s)
end
class... | 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 |
# 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.jo... | 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 |
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 |
=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("#{T... | 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:0... | 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 --- 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
| 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 |
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 |
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_... | 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 |
=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 |
#!/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.pu... | 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 |
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 |
=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
att... | Ruby |
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... | 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
c... | 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 i... | Ruby |
=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 i... | 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 |
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
| 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... | 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
mu... | 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 Dha... | 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 |
#!/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... | 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| ... | 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 --- 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 '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 |
=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 |
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 |
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 --- 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 |
=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"]
| [#... | Ruby |
require 'drb/drb'
require 'rinda/tuplespace'
uri = ARGV.shift
DRb.start_service(uri, Rinda::TupleSpace.new)
puts DRb.uri
DRb.thread.join
| 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.... | 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 == ... | Ruby |
=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... | 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
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 = DRbObjec... | Ruby |
# 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
| 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 |
#! /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 |
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"
| 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 |
# 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 |
#!/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"
items = []
verbose = false
def error(exception)
ma... | 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"
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"
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( "-e -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 |
#! /usr/local/bin/ruby -Kn
# usage: exyacc.rb [yaccfiles]
# this is coverted 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"... | 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 |
#! /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... | Ruby |
#! /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... | 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 |
#!./miniruby -s
# avoid warnings with -d.
$install_name ||= nil
$so_name ||= nil
srcdir = File.dirname(__FILE__)
$:.replace [srcdir+"/lib"] unless defined?(CROSS_COMPILING)
$:.unshift(".")
require "fileutils"
mkconfig = File.basename($0)
rbconfig_rb = ARGV[0] || 'rbconfig.rb'
unless File.directory?(dir = File.dirna... | Ruby |
#!./miniruby
load "./rbconfig.rb"
include RbConfig
srcdir = File.dirname(__FILE__)
$:.unshift File.expand_path("lib", srcdir)
require 'fileutils'
require 'shellwords'
require 'optparse'
require 'optparse/shellwords'
require 'tempfile'
STDOUT.sync = true
File.umask(0)
def parse_args(argv = ARGV)
$mantype = 'doc'
... | Ruby |
#!./miniruby
pure = true
while arg = ARGV[0]
break ARGV.shift if arg == '--'
/\A--([-\w]+)(?:=(.*))?\z/ =~ arg or break
arg, value = $1, $2
re = Regexp.new('\A'+arg.gsub(/\w+\b/, '\&\\w*')+'\z', "i")
case
when re =~ "srcdir"
srcdir = value
when re =~ "archdir"
archdir = value
when re =~ "extout... | Ruby |
#!./miniruby -s
$name = $library = $description = nil
SYM = {}
objs = ARGV.collect {|s| s.tr('/', '\\')}
IO.foreach("|dumpbin -symbols " + objs.join(' ')) do |l|
next if /^[0-9A-F]+ 0+ UNDEF / =~ l
next unless l.sub!(/.*?\s(\(\)\s+)?External\s+\|\s+/, "")
is_data = !$1
if /^[@_](?!\w+@\d+$)/ =~ l
next if... | Ruby |
#!./miniruby -sI.
require 'rbconfig'
CONFIG = Config::MAKEFILE_CONFIG
version = %w'MAJOR MINOR TEENY PATCHLEVEL'.map {|v| CONFIG[v] || '0'}
fversion = version.join(',')
rversion = version.join('.')
$ruby_name ||= CONFIG["RUBY_INSTALL_NAME"]
$rubyw_name ||= CONFIG["RUBYW_INSTALL_NAME"] || $ruby_name.sub(/ruby/, '\&w... | Ruby |
#!./miniruby
if RUBY_PATCHLEVEL.zero?
dirname = sprintf 'ruby-%s', RUBY_VERSION
tagname = dirname.gsub /ruby-(\d)\.(\d)\.(\d)/, 'v\1_\2_\3'
else
dirname = sprintf 'ruby-%s-p%u', RUBY_VERSION, RUBY_PATCHLEVEL
tagname = dirname.gsub /ruby-(\d)\.(\d)\.(\d)-p/, 'v\1_\2_\3_'
end
tgzname = dirname + '.tar.gz'
tbzname = ... | Ruby |
=begin
= monitor.rb
Copyright (C) 2001 Shugo Maeda <shugo@ruby-lang.org>
This library is distributed under the terms of the Ruby license.
You can freely distribute/modify this library.
== example
This is a simple example.
require 'monitor.rb'
buf = []
buf.extend(MonitorMixin)
empty_cond = buf.new_cond... | Ruby |
#
# = uri/mailto.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id: mailto.rb 11747 2007-02-15 02:41:45Z knu $
#
require 'uri/generic'
module URI
#
# RFC2368, The mailto URL scheme
#
class MailTo < Generic
... | Ruby |
require 'uri/ldap'
module URI
# The default port for LDAPS URIs is 636, and the scheme is 'ldaps:' rather
# than 'ldap:'. Other than that, LDAPS URIs are identical to LDAP URIs;
# see URI::LDAP.
class LDAPS < LDAP
DEFAULT_PORT = 636
end
@@schemes['LDAPS'] = LDAPS
end
| Ruby |
# = uri/common.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# Revision:: $Id: common.rb 14178 2007-12-10 09:31:55Z matz $
# License::
# You can redistribute it and/or modify it under the same term as Ruby.
#
module URI
module REGEXP
#
# Patterns used to parse URI's
#
module PATTERN
# :... | Ruby |
#
# = uri/http.rb
#
# Author:: Akira Yamada <akira@ruby-lang.org>
# License:: You can redistribute it and/or modify it under the same term as Ruby.
# Revision:: $Id: http.rb 11747 2007-02-15 02:41:45Z knu $
#
require 'uri/generic'
module URI
#
# The syntax of HTTP URIs is defined in RFC1738 section 3.3.
#
# ... | Ruby |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.