repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/shell/single_shot_wrapper.rb
|
require 'open3'
module RVM
module Shell
# Implementation of the abstract wrapper class that opens a new
# instance of bash when a command is run, only keeping it around
# for the lifetime of the command. Possibly inefficient but for
# the moment simplest and hence default implementation.
class SingleShotWrapper < AbstractWrapper
attr_accessor :current
# Runs a given command in the current shell.
# Defaults the command to true if empty.
def run_command(command)
command = "true" if command.to_s.strip.empty?
with_shell_instance do
stdin.puts wrapped_command(command)
stdin.close
out, err = stdout.read, stderr.read
out, status, _ = raw_stdout_to_parts(out)
return status, out, err
end
end
# Runs a command, ensuring no output is collected.
def run_command_silently(command)
with_shell_instance do
stdin.puts silent_command(command)
end
end
protected
# yields stdio, stderr and stdin for a shell instance.
# If there isn't a current shell instance, it will create a new one.
# In said scenario, it will also cleanup once it is done.
def with_shell_instance(&blk)
no_current = @current.nil?
if no_current
@current = Open3.popen3(self.shell_executable)
invoke_setup!
end
yield
ensure
@current = nil if no_current
end
# Direct access to each of the named descriptors
def stdin; @current[0]; end
def stdout; @current[1]; end
def stderr; @current[2]; end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/sample/cbreak.rb
|
<filename>.rvm/src/ruby-2.3.0/sample/cbreak.rb
# 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
ttys[4] &= ~ECHO
else
ttys[4] &= ~CBREAK
ttys[4] |= ECHO
end
tty = ttys.pack("C4 S")
STDIN.ioctl(TIOCSETP, tty)
end
cbreak();
print("this is no-echo line: ");
readline().print
cooked();
print("this is echo line: ");
readline()
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/bootstraptest/test_flow.rb
|
<gh_stars>0
assert_equal %q{[1, 2, 4, 5, 6, 7, 8]}, %q{$a = []; begin; ; $a << 1
[1,2].each{; $a << 2
break; $a << 3
}; $a << 4
begin; $a << 5
ensure; $a << 6
end; $a << 7
; $a << 8
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 5, 6, 7, 8]}, %q{$a = []; begin; ; $a << 1
begin; $a << 2
[1,2].each do; $a << 3
break; $a << 4
end; $a << 5
ensure; $a << 6
end; $a << 7
; $a << 8
; rescue Exception; $a << 99; end; $a}
assert_equal %q{ok}, %q{
["a"].inject("ng"){|x,y|
break :ok
}
}
assert_equal %q{ok}, %q{
unless ''.respond_to? :lines
class String
def lines
self
end
end
end
('a').lines.map{|e|
break :ok
}
}
assert_equal %q{[1, 2, 4, 5]}, %q{$a = []; begin; ; $a << 1
["a"].inject("ng"){|x,y|; $a << 2
break :ok; $a << 3
}; $a << 4
; $a << 5
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 4, 5]}, %q{$a = []; begin; ; $a << 1
('a'..'b').map{|e|; $a << 2
break :ok; $a << 3
}; $a << 4
; $a << 5
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 5, 7, 8]}, %q{$a = []; begin; ; $a << 1
[1,2].each do; $a << 2
begin; $a << 3
break; $a << 4
ensure; $a << 5
end; $a << 6
end; $a << 7
; $a << 8
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 6, 9, 10]}, %q{$a = []; begin; ; $a << 1
i=0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
begin; $a << 5
ensure; $a << 6
break; $a << 7
end; $a << 8
end; $a << 9
; $a << 10
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 7, 10, 11]}, %q{$a = []; begin; ; $a << 1
i=0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
begin; $a << 5
raise; $a << 6
ensure; $a << 7
break; $a << 8
end; $a << 9
end; $a << 10
; $a << 11
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 7, 10, 11]}, %q{$a = []; begin; ; $a << 1
i=0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
begin; $a << 5
raise; $a << 6
rescue; $a << 7
break; $a << 8
end; $a << 9
end; $a << 10
; $a << 11
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 5, 8, 9]}, %q{$a = []; begin; ; $a << 1
[1,2].each do; $a << 2
begin; $a << 3
raise StandardError; $a << 4
ensure; $a << 5
break; $a << 6
end; $a << 7
end; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 5, 8, 9]}, %q{$a = []; begin; ; $a << 1
[1,2].each do; $a << 2
begin; $a << 3
raise StandardError; $a << 4
rescue; $a << 5
break; $a << 6
end; $a << 7
end; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 6, 8, 10, 11]}, %q{$a = []; begin; ; $a << 1
[1,2].each do; $a << 2
begin; $a << 3
begin; $a << 4
break; $a << 5
ensure; $a << 6
end; $a << 7
ensure; $a << 8
end; $a << 9
end; $a << 10
; $a << 11
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 6, 7, 8, 10, 13, 3, 4, 5, 6, 7, 8, 10, 13, 3, 4, 5, 6, 7, 8, 10, 13, 14, 15]}, %q{$a = []; begin; ; $a << 1
i = 0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
j = 0; $a << 5
while j<3; $a << 6
j+=1; $a << 7
begin; $a << 8
raise; $a << 9
rescue; $a << 10
break; $a << 11
end; $a << 12
end; $a << 13
end; $a << 14
; $a << 15
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 15, 3, 4, 5, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 15, 3, 4, 5, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 15, 16, 17]}, %q{$a = []; begin; ; $a << 1
i = 0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
j = 0; $a << 5
while j<3; $a << 6
j+=1; $a << 7
1.times{; $a << 8
begin; $a << 9
raise; $a << 10
rescue; $a << 11
break; $a << 12
end; $a << 13
}; $a << 14
end; $a << 15
end; $a << 16
; $a << 17
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 6, 7, 8, 10, 13, 3, 4, 5, 6, 7, 8, 10, 13, 3, 4, 5, 6, 7, 8, 10, 13, 14, 15]}, %q{$a = []; begin; ; $a << 1
i = 0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
j = 0; $a << 5
while j<3; $a << 6
j+=1; $a << 7
begin; $a << 8
raise; $a << 9
ensure; $a << 10
break; $a << 11
end; $a << 12
end; $a << 13
end; $a << 14
; $a << 15
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 15, 3, 4, 5, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 15, 3, 4, 5, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 6, 7, 8, 9, 11, 14, 15, 16, 17]}, %q{$a = []; begin; ; $a << 1
i = 0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
j = 0; $a << 5
while j<3; $a << 6
j+=1; $a << 7
1.times{; $a << 8
begin; $a << 9
raise; $a << 10
ensure; $a << 11
break; $a << 12
end; $a << 13
}; $a << 14
end; $a << 15
end; $a << 16
; $a << 17
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 5, 8, 9]}, %q{$a = []; begin; ; $a << 1
while true; $a << 2
begin; $a << 3
break; $a << 4
ensure; $a << 5
break; $a << 6
end; $a << 7
end; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 5, 99]}, %q{
$a = [];
begin; ; $a << 1
while true; $a << 2
begin; $a << 3
break; $a << 4
ensure; $a << 5
raise; $a << 6
end; $a << 7
end; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 6, 8, 9, 10, 11]}, %q{$a = []; begin; ; $a << 1
begin; $a << 2
[1,2].each do; $a << 3
begin; $a << 4
break; $a << 5
ensure; $a << 6
end; $a << 7
end; $a << 8
ensure; $a << 9
end; $a << 10
; $a << 11
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 4, 99]}, %q{$a = []; begin; ; $a << 1
begin; $a << 2
raise StandardError; $a << 3
ensure; $a << 4
end; $a << 5
; $a << 6
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4]}, %q{$a = []; begin; ; $a << 1
begin; $a << 2
ensure; $a << 3
end ; $a << 4
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 5, 99]}, %q{$a = []; begin; ; $a << 1
[1,2].each do; $a << 2
begin; $a << 3
break; $a << 4
ensure; $a << 5
raise StandardError; $a << 6
end; $a << 7
end; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{3}, %q{
def m a, b
a + b
end
m(1,
while true
break 2
end
)
}
assert_equal %q{4}, %q{
def m a, b
a + b
end
m(1,
(i=0; while i<2
i+=1
class C
next 2
end
end; 3)
)
}
assert_equal %q{34}, %q{
def m a, b
a+b
end
m(1, 1.times{break 3}) +
m(10, (1.times{next 3}; 20))
}
assert_equal %q{[1, 2, 3, 6, 7]}, %q{$a = []; begin; ; $a << 1
3.times{; $a << 2
class C; $a << 3
break; $a << 4
end; $a << 5
}; $a << 6
; $a << 7
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 8, 9]}, %q{$a = []; begin; ; $a << 1
3.times{; $a << 2
class A; $a << 3
class B; $a << 4
break; $a << 5
end; $a << 6
end; $a << 7
}; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 2, 3, 2, 3, 6, 7]}, %q{$a = []; begin; ; $a << 1
3.times{; $a << 2
class C; $a << 3
next; $a << 4
end; $a << 5
}; $a << 6
; $a << 7
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 2, 3, 4, 2, 3, 4, 8, 9]}, %q{$a = []; begin; ; $a << 1
3.times{; $a << 2
class C; $a << 3
class D; $a << 4
next; $a << 5
end; $a << 6
end; $a << 7
}; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 6, 7]}, %q{$a = []; begin; ; $a << 1
while true; $a << 2
class C; $a << 3
break; $a << 4
end; $a << 5
end; $a << 6
; $a << 7
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 8, 9]}, %q{$a = []; begin; ; $a << 1
while true; $a << 2
class C; $a << 3
class D; $a << 4
break; $a << 5
end; $a << 6
end; $a << 7
end; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5, 8, 9]}, %q{$a = []; begin; ; $a << 1
i=0; $a << 2
while i<3; $a << 3
i+=1; $a << 4
class C; $a << 5
next 10; $a << 6
end; $a << 7
end; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{1}, %q{
1.times{
while true
class C
begin
break
ensure
break
end
end
end
}
}
assert_equal %q{[1, 2, 3, 5, 2, 3, 5, 7, 8]}, %q{$a = []; begin; ; $a << 1
[1,2].each do; $a << 2
begin; $a << 3
next; $a << 4
ensure; $a << 5
end; $a << 6
end; $a << 7
; $a << 8
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 2, 6, 3, 5, 7, 8]}, %q{$a = []; begin; ; $a << 1
o = "test"; $a << 2
def o.test(a); $a << 3
return a; $a << 4
ensure; $a << 5
end; $a << 6
o.test(123); $a << 7
; $a << 8
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 4, 7, 5, 8, 9]}, %q{$a = []; begin; ; $a << 1
def m1 *args; $a << 2
; $a << 3
end; $a << 4
def m2; $a << 5
m1(:a, :b, (return 1; :c)); $a << 6
end; $a << 7
m2; $a << 8
; $a << 9
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 8, 2, 3, 4, 5, 9, 10]}, %q{$a = []; begin; ; $a << 1
def m(); $a << 2
begin; $a << 3
2; $a << 4
ensure; $a << 5
return 3; $a << 6
end; $a << 7
end; $a << 8
m; $a << 9
; $a << 10
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 3, 11, 4, 5, 6, 7, 12, 13]}, %q{$a = []; begin; ; $a << 1
def m2; $a << 2
end; $a << 3
def m(); $a << 4
m2(begin; $a << 5
2; $a << 6
ensure; $a << 7
return 3; $a << 8
end); $a << 9
4; $a << 10
end; $a << 11
m(); $a << 12
; $a << 13
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[1, 16, 2, 3, 4, 5, 6, 7, 10, 11, 17, 18]}, %q{$a = []; begin; ; $a << 1
def m; $a << 2
1; $a << 3
1.times{; $a << 4
2; $a << 5
begin; $a << 6
3; $a << 7
return; $a << 8
4; $a << 9
ensure; $a << 10
5; $a << 11
end; $a << 12
6; $a << 13
}; $a << 14
7; $a << 15
end; $a << 16
m(); $a << 17
; $a << 18
; rescue Exception; $a << 99; end; $a}
assert_equal %q{[:ok, :ok2, :last]}, %q{
a = []
i = 0
begin
while i < 1
i+=1
begin
begin
next
ensure
a << :ok
end
ensure
a << :ok2
end
end
ensure
a << :last
end
a
}
assert_equal %q{[:ok, :ok2, :last]}, %q{
a = []
i = 0
begin
while i < 1
i+=1
begin
begin
break
ensure
a << :ok
end
ensure
a << :ok2
end
end
ensure
a << :last
end
a
}
assert_equal %q{[:ok, :ok2, :last]}, %q{
a = []
i = 0
begin
while i < 1
if i>0
break
end
i+=1
begin
begin
redo
ensure
a << :ok
end
ensure
a << :ok2
end
end
ensure
a << :last
end
a
}
assert_equal %Q{ENSURE\n}, %q{
def test
while true
return
end
ensure
puts("ENSURE")
end
test
}, '[ruby-dev:37967]'
[['[ruby-core:28129]', %q{
class Bug2728
include Enumerable
define_method(:dynamic_method) do
"dynamically defined method"
end
def each
begin
yield :foo
ensure
dynamic_method
end
end
end
e = Bug2728.new
}],
['[ruby-core:28132]', %q{
class Bug2729
include Enumerable
def each
begin
yield :foo
ensure
proc {}.call
end
end
end
e = Bug2729.new
}],
['[ruby-core:39125]', %q{
class Bug5234
include Enumerable
def each
begin
yield :foo
ensure
proc
end
end
end
e = Bug5234.new
}],
['[ruby-dev:45656]', %q{
class Bug6460
include Enumerable
def each
begin
yield :foo
ensure
1.times { Proc.new }
end
end
end
e = Bug6460.new
}]].each do |bug, src|
assert_equal "foo", src + %q{e.detect {true}}, bug
assert_equal "true", src + %q{e.any? {true}}, bug
assert_equal "false", src + %q{e.all? {false}}, bug
assert_equal "true", src + %q{e.include?(:foo)}, bug
end
assert_equal('ok', %q{
class FOO < RuntimeError; end
class BAR < RuntimeError; end
def m
raise FOO
end
set_trace_func(proc{|t,| raise BAR if t == 'return'})
begin
m
rescue BAR
'ok'
end
}, '[ruby-core:51128] [ruby-trunk - Bug #7624]')
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/tool/gen_dummy_probes.rb
|
#!/usr/bin/ruby
# -*- coding: us-ascii -*-
text = ARGF.read
text.gsub!(/^(?!#)(.*)/){$1.upcase}
# remove comments
text.gsub!(%r'(?:^ *)?/\*.*?\*/\n?'m, '')
# remove the pragma declarations
text.gsub!(/^#pragma.*\n/, '')
# replace the provider section with the start of the header file
text.gsub!(/PROVIDER RUBY \{/, "#ifndef\t_PROBES_H\n#define\t_PROBES_H\n#define DTRACE_PROBES_DISABLED 1\n")
# finish up the #ifndef sandwich
text.gsub!(/\};/, "\n#endif\t/* _PROBES_H */")
text.gsub!(/__/, '_')
text.gsub!(/\((.+?)(?=\);)/) {
"(arg" << (0..$1.count(',')).to_a.join(", arg")
}
text.gsub!(/ *PROBE ([^\(]*)(\([^\)]*\));/, "#define RUBY_DTRACE_\\1_ENABLED() 0\n#define RUBY_DTRACE_\\1\\2\ do \{ \} while\(0\)")
puts "/* -*- c -*- */"
print text
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/dynect.rb
|
require 'fog/dynect/dns'
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/-test-/iseq_load/extconf.rb
|
# frozen_string_literal: false
create_makefile("-test-/iseq_load/iseq_load")
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/sample/demos-en/goldberg.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
#
# Ruby/Tk Goldverg demo (called by 'widget')
#
# Based on Tcl/Tk8.5a2 widget demos.
# The following is the original comment of TkGoldberg.tcl.
#
#>>##+#################################################################
#>>#
#>># TkGoldberg.tcl
#>># by <NAME>, March 13, 2003
#>>#
#>># "Man will always find a difficult means to perform a simple task"
#>># <NAME>
#>>#
#>># Reproduced here with permission.
#>>#
#>>##+#################################################################
#>>#
#>># <NAME> 2003-03-21: this started out as a simple little program
#>># but was so much fun that it grew and grew. So I apologize about the
#>># size but I just couldn't resist sharing it.
#>>#
#>># This is a whizzlet that does a Rube Goldberg type animation, the
#>># design of which comes from an New Years e-card from IncrediMail.
#>># That version had nice sound effects which I eschewed. On the other
#>># hand, that version was in black and white (actually dark blue and
#>># light blue) and this one is fully colorized.
#>>#
#>># One thing I learned from this project is that drawing filled complex
#>># objects on a canvas is really hard. More often than not I had to
#>># draw each item twice--once with the desired fill color but no
#>># outline, and once with no fill but with the outline. Another trick
#>># is erasing by drawing with the background color. Having a flood fill
#>># command would have been extremely helpful.
#>>#
#>># Two wiki pages were extremely helpful: Drawing rounded rectangles
#>># which I generalized into Drawing rounded polygons, and regular
#>># polygons which allowed me to convert ovals and arcs into polygons
#>># which could then be rotated (see Canvas Rotation). I also wrote
#>># Named Colors to aid in the color selection.
#>>#
#>># I could comment on the code, but it's just 26 state machines with
#>># lots of canvas create and move calls.
if defined?($goldberg_demo) && $goldberg_demo
$goldberg_demo.destroy
$goldberg_demo = nil
end
# demo toplevel widget
$goldberg_demo = TkToplevel.new {|w|
title("Tk Goldberg (demonstration)")
iconname("goldberg")
# positionWindow(w)
}
base_frame = TkFrame.new($goldberg_demo).pack(:fill=>:both, :expand=>true)
=begin
# label
msg = TkLabel.new($goldberg_demo) {
font 'Arial 10'
wraplength '4i'
justify 'left'
text "This is a demonstration of just how complex you can make your animations become. Click the ball to start things moving!\n\n\"Man will always find a difficult means to perform a simple task\"\n - <NAME>"
}
msg.pack('side'=>'top')
=end
=begin
# frame
TkFrame.new($goldberg_demo) {|frame|
TkButton.new(frame) {
text 'Dismiss'
command proc{
tmppath = $goldberg_demo
$goldberg_demo = nil
tmppath.destroy
}
}.pack('side'=>'left', 'expand'=>'yes')
TkButton.new(frame) {
text 'See Code'
command proc{showCode 'goldberg'}
}.pack('side'=>'left', 'expand'=>'yes')
}.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m')
=end
#########################################
class TkGoldberg_Demo
def initialize(parent)
@parent = parent
@S = {}
@S['title'] = 'Tk Goldberg'
@S['speed'] = TkVariable.new(5)
@S['cnt'] = TkVariable.new(0)
@S['message'] = TkVariable.new("\\nWelcome\\nto\\nRuby/Tk")
@S['pause'] = TkVariable.new
@S['details'] = TkVariable.new(true)
@S['mode'] = TkVariable.new(:MSTART, :symbol)
# :MSTART, :MGO, :MPAUSE, :MSSTEP, :MBSTEP, :MDONE, :MDEBUG
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
@speed = [1, 10, 20, 50, 80, 100, 150, 200, 300, 400, 500]
# colors
@C = {}
@C['fg'] = 'black'
# @C['bg'] = 'gray75'
@C['bg'] = 'cornflowerblue'
@C['0'] = 'white'; @C['1a'] = 'darkgreen'; @C['1b'] = 'yellow'
@C['2'] = 'red'; @C['3a'] = 'green'; @C['3b'] = 'darkblue'
@C['4'] = @C['fg']; @C['5a'] = 'brown'; @C['5b'] = 'white'
@C['6'] = 'magenta'; @C['7'] = 'green'; @C['8'] = @C['fg']
@C['9'] = 'blue4'; @C['10a'] = 'white'; @C['10b'] = 'cyan'
@C['11a'] = 'yellow'; @C['11b'] = 'mediumblue'; @C['12'] = 'tan2'
@C['13a'] = 'yellow'; @C['13b'] = 'red'; @C['14'] = 'white'
@C['15a'] = 'green'; @C['15b'] = 'yellow'; @C['16'] = 'gray65'
@C['17'] = '#A65353'; @C['18'] = @C['fg']; @C['19'] = 'gray50'
@C['20'] = 'cyan'; @C['21'] = 'gray65'; @C['22'] = @C['20']
@C['23a'] = 'blue'; @C['23b'] = 'red'; @C['23c'] = 'yellow'
@C['24a'] = 'red'; @C['24b'] = 'white';
@STEP = TkVariable.new_hash
@STEP.default_value_type = :numeric
@XY = {}
@XY6 = {
'-1'=>[366, 207], '-2'=>[349, 204], '-3'=>[359, 193], '-4'=>[375, 192],
'-5'=>[340, 190], '-6'=>[349, 177], '-7'=>[366, 177], '-8'=>[380, 176],
'-9'=>[332, 172], '-10'=>[342, 161], '-11'=>[357, 164],
'-12'=>[372, 163], '-13'=>[381, 149], '-14'=>[364, 151],
'-15'=>[349, 146], '-16'=>[333, 148], '0'=>[357, 219],
'1'=>[359, 261], '2'=>[359, 291], '3'=>[359, 318], '4'=>[361, 324],
'5'=>[365, 329], '6'=>[367, 334], '7'=>[367, 340], '8'=>[366, 346],
'9'=>[364, 350], '10'=>[361, 355], '11'=>[359, 370], '12'=>[359, 391],
'13,0'=>[360, 456], '13,1'=>[376, 456], '13,2'=>[346, 456],
'13,3'=>[330, 456], '13,4'=>[353, 444], '13,5'=>[368, 443],
'13,6'=>[339, 442], '13,7'=>[359, 431], '13,8'=>[380, 437],
'13,9'=>[345, 428], '13,10'=>[328, 434], '13,11'=>[373, 424],
'13,12'=>[331, 420], '13,13'=>[360, 417], '13,14'=>[345, 412],
'13,15'=>[376, 410], '13,16'=>[360, 403]
}
@timer = TkTimer.new(@speed[@S['speed'].numeric]){|timer|
timer.set_interval(go)
}
do_display
reset
# Start everything going
@timer.start
end
def do_display()
@ctrl = TkFrame.new(@parent, :relief=>:ridge, :bd=>2, :padx=>5, :pady=>5)
@screen = TkFrame.new(@parent, :bd=>2,
:relief=>:raised).pack(:side=>:left, :fill=>:both,
:expand=>true)
@canvas = TkCanvas.new(@parent, :width=>850, :height=>700,
:bg=>@C['bg'], :highlightthickness=>0){
scrollregion([0, 0, 1000, 1000]) # Kludge to move everything up
yview_moveto(0.05)
}.pack(:in=>@screen, :side=>:top, :fill=>:both, :expand=>true)
@canvas.bind('3'){ @pause.invoke }
@canvas.bind('Destroy'){ @timer.stop }
do_ctrl_frame
do_detail_frame
# msg = TkLabel.new(@parent, :bg=>@C['bg'], :fg=>'white') {
msg = Tk::Label.new(@parent, :bg=>@C['bg'], :fg=>'white') {
font 'Arial 10'
wraplength 600
justify 'left'
text "This is a demonstration of just how complex you can make your animations become. Click the ball to start things moving!\n\"Man will always find a difficult means to perform a simple task\" - <NAME>"
}
msg.place(:in=>@canvas, :relx=>0, :rely=>0, :anchor=>:nw)
frame = TkFrame.new(@parent, :bg=>@C['bg'])
# TkButton.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
Tk::Button.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
text 'Dismiss'
command proc{
tmppath = $goldberg_demo
$goldberg_demo = nil
tmppath.destroy
}
}.pack('side'=>'left')
# TkButton.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
Tk::Button.new(frame, :bg=>@C['bg'], :activebackground=>@C['bg']) {
text 'See Code'
command proc{showCode 'goldberg'}
}.pack('side'=>'left', 'padx'=>5)
# @show = TkButton.new(frame, :text=>'>>', :command=>proc{show_ctrl},
@show = Tk::Button.new(frame, :text=>'>>', :command=>proc{show_ctrl},
:bg=>@C['bg'], :activebackground=>@C['bg'])
@show.pack('side'=>'left')
frame.place(:in=>@canvas, :relx=>1, :rely=>0, :anchor=>:ne)
Tk.update
end
def do_ctrl_frame
@start = Tk::Button.new(@parent, :text=>'Start', :bd=>6,
:command=>proc{do_button(0)})
if font = @start['font']
@start.font(font.weight('bold'))
end
@pause = TkCheckbutton.new(@parent, :text=>'Pause', :font=>font,
:command=>proc{do_button(1)}, :relief=>:raised,
:variable=>@S['pause'])
@step = TkButton.new(@parent, :text=>'Single Step', :font=>font,
:command=>proc{do_button(2)})
@bstep = TkButton.new(@parent, :text=>'Big Step', :font=>font,
:command=>proc{do_button(4)})
@reset = TkButton.new(@parent, :text=>'Reset', :font=>font,
:command=>proc{do_button(3)})
@details = TkFrame.new(@parent, :bd=>2, :relief=>:ridge)
@detail = TkCheckbutton.new(@parent, :text=>'Details', :font=>font,
:relief=>:raised, :variable=>@S['details'])
@msg_entry = TkEntry.new(@parent, :textvariable=>@S['message'],
:justify=>:center)
@speed_scale = TkScale.new(@parent, :orient=>:horizontal,
:from=>1, :to=>10, :font=>font,
:variable=>@S['speed'], :bd=>2,
:relief=>:ridge, :showvalue=>false)
@about = TkButton.new(@parent, :text=>'About',
:command=>proc{about}, :font=>font)
Tk.grid(@start, :in=>@ctrl, :row=>0, :sticky=>:ew)
@ctrl.grid_rowconfigure(1, :minsize=>10)
Tk.grid(@pause, :in=>@ctrl, :row=>2, :sticky=>:ew)
Tk.grid(@step, :in=>@ctrl, :sticky=>:ew)
Tk.grid(@bstep, :in=>@ctrl, :sticky=>:ew)
Tk.grid(@reset, :in=>@ctrl, :sticky=>:ew)
@ctrl.grid_rowconfigure(10, :minsize=>20)
Tk.grid(@details, :in=>@ctrl, :row=>11, :sticky=>:ew)
Tk.grid(@detail, :in=>@details, :row=>0, :sticky=>:ew)
@ctrl.grid_rowconfigure(50, :weight=>1)
@S['mode'].trace('w', proc{|*args| active_GUI(*args)})
@S['details'].trace('w', proc{|*args| active_GUI(*args)})
@S['speed'].trace('w', proc{|*args| active_GUI(*args)})
Tk.grid(@msg_entry, :in=>@ctrl, :row=>98, :sticky=>:ew, :pady=>5)
Tk.grid(@speed_scale, :in=>@ctrl, :row=>99, :sticky=>:ew)
Tk.grid(@about, :in=>@ctrl, :row=>100, :sticky=>:ew)
@reset.bind('3'){@S['mode'].value = -1} # Debugging
end
def do_detail_frame
@f_details = TkFrame.new(@details)
@label = TkLabel.new(@f_details, :textvariable=>@S['cnt'],
:bd=>1, :relief=>:solid, :bg=>'white')
Tk.grid(@label, '-', '-', '-', :sticky=>:ew, :row=>0)
idx = 1
loop {
break unless respond_to?("move#{idx}")
l = TkLabel.new(@f_details, :text=>idx, :anchor=>:e,
:width=>2, :bd=>1, :relief=>:solid, :bg=>'white')
@STEP[idx] = 0
ll = TkLabel.new(@f_details, :textvariable=>@STEP.ref(idx),
:width=>5, :bd=>1, :relief=>:solid, :bg=>'white')
row = (idx + 1)/2
col = ((idx + 1) & 1) * 2
Tk.grid(l, :sticky=>:ew, :row=>row, :column=>col)
Tk.grid(ll, :sticky=>:ew, :row=>row, :column=>(col + 1))
idx += 1
}
@f_details.grid_columnconfigure(1, :weight=>1)
end
def show_ctrl
if @ctrl.winfo_mapped?
@ctrl.pack_forget
@show.text('>>')
else
@ctrl.pack(:side=>:right, :fill=>:both, :ipady=>5)
@show.text('<<')
end
end
def draw_all
reset_step
@canvas.delete(:all)
idx = 0
loop{
m = "draw#{idx}"
break unless respond_to?(m)
send(m)
idx += 1
}
end
def active_GUI(var1, var2, op)
st = {false=>:disabled, true=>:normal}
m = @S['mode'].to_sym
@S['pause'].value = (m == :MPAUSE)
@start.state(st[m != :MGO])
@pause.state(st[m != :MSTART && m != :MDONE])
@step.state(st[m != :MGO && m != :MDONE])
@bstep.state(st[m != :MGO && m != :MDONE])
@reset.state(st[m != :MSTART])
if @S['details'].bool
Tk.grid(@f_details, :in=>@details, :row=>2, :sticky=>:ew)
else
Tk.grid_forget(@f_details)
end
@speed_scale.label("Speed: #{@S['speed'].value}")
end
def start
@S['mode'].value = :MGO
end
def do_button(what)
case what
when 0 # Start
reset if @S['mode'].to_sym == :MDONE
@S['mode'].value = :MGO
when 1 # Pause
@S['mode'].value = ((@S['pause'].bool)? :MPAUSE: :MGO)
when 2 # Step
@S['mode'].value = :MSSTEP
when 3 # Reset
reset
when 4 # Big step
@S['mode'].value = :MBSTEP
end
end
def go(who = nil)
now = Tk::Clock.clicks(:miliseconds)
if who # Start here for debugging
@S['active'] = [who]
@S['mode'].value = :MGO
end
return if @S['mode'].to_sym == :MDEBUG # Debugging
# If not paused, do the next move
n = next_step if @S['mode'].to_sym != :MPAUSE
@S['mode'].value = :MPAUSE if @S['mode'].to_sym == :MSSTEP # Single step
@S['mode'].value = :MSSTEP if @S['mode'].to_sym == :MBSTEP && n # big step
elapsed = Tk::Clock.clicks(:miliseconds) - now
delay = @speed[@S['speed'].to_i] - elapsed
delay = 1 if delay <= 0
return delay
end
def next_step
retval = false # Return value
if @S['mode'].to_sym != :MSTART && @S['mode'].to_sym != :MDONE
@S['cnt'].numeric += 1
end
alive = []
@S['active'].each{|who|
who = who.to_i
n = send("move#{who}")
if (n & 1).nonzero? # This guy still alive
alive << who
end
if (n & 2).nonzero? # Next guy is active
alive << (who + 1)
retval = true
end
if (n & 4).nonzero? # End of puzzle flag
@S['mode'].value = :MDONE # Done mode
@S['active'] = [] # No more animation
return true
end
}
@S['active'] = alive
return retval
end
def about
msg = "Ruby/Tk Version ::\nby <NAME> (<EMAIL>)\n\n"
msg += "Original Version ::\n"
msg += "#{@S['title']}\nby <NAME>ter, March 2003\n(Reproduced by kind permission of the author)\n\n"
msg += "Man will always find a difficult means to perform a simple task"
msg += "\n<NAME>"
Tk.messageBox(:message=>msg, :title=>'About')
end
################################################################
#
# All the drawing and moving routines
#
# START HERE! banner
def draw0
color = @C['0']
TkcText.new(@canvas, [579, 119], :text=>'START HERE!',
:fill=>color, :anchor=>:w,
:tag=>'I0', :font=>['Times Roman', 12, :italic, :bold])
TkcLine.new(@canvas, [719, 119, 763, 119], :tag=>'I0', :fill=>color,
:width=>5, :arrow=>:last, :arrowshape=>[18, 18, 5])
@canvas.itembind('I0', '1'){ start }
end
def move0(step = nil)
step = get_step(0, step)
if @S['mode'].to_sym != :MSTART # Start the ball rolling
move_abs('I0', [-100, -100]) # Hide the banner
return 2
end
pos = [
[673, 119], [678, 119], [683, 119], [688, 119],
[693, 119], [688, 119], [683, 119], [678, 119]
]
step = step % pos.length
move_abs('I0', pos[step])
return 1
end
# Dropping ball
def draw1
color = @C['1a']
color2 = @C['1b']
TkcPolygon.new(@canvas,
[ 844, 133, 800, 133, 800, 346, 820, 346,
820, 168, 844, 168, 844, 133 ],
:width=>3, :fill=>color, :outline=>'')
TkcPolygon.new(@canvas,
[ 771, 133, 685, 133, 685, 168, 751, 168,
751, 346, 771, 346, 771, 133 ],
:width=>3, :fill=>color, :outline=>'')
TkcOval.new(@canvas, box(812, 122, 9),
:tag=>'I1', :fill=>color2, :outline=>'')
@canvas.itembind('I1', '1'){ start }
end
def move1(step = nil)
step = get_step(1, step)
pos = [
[807, 122], [802, 122], [797, 123], [793, 124], [789, 129], [785, 153],
[785, 203], [785, 278, :x], [785, 367], [810, 392], [816, 438],
[821, 503], [824, 585, :y], [838, 587], [848, 593], [857, 601],
[-100, -100]
]
return 0 if step >= pos.length
where = pos[step]
move_abs('I1', where)
move15a if where[2] == :y
return 3 if where[2] == :x
return 1
end
# Lighting the match
def draw2
color = @C['2']
# Fulcrum
TkcPolygon.new(@canvas, [750, 369, 740, 392, 760, 392],
:fill=>@C['fg'], :outline=>@C['fg'])
# Strike box
TkcRectangle.new(@canvas, [628, 335, 660, 383],
:fill=>'', :outline=>@C['fg'])
(0..2).each{|y|
yy = 335 + y*16
TkcBitmap.new(@canvas, [628, yy], :bitmap=>'gray25',
:anchor=>:nw, :foreground=>@C['fg'])
TkcBitmap.new(@canvas, [644, yy], :bitmap=>'gray25',
:anchor=>:nw, :foreground=>@C['fg'])
}
# Lever
TkcLine.new(@canvas, [702, 366, 798, 366],
:fill=>@C['fg'], :width=>6, :tag=>'I2_0')
# R strap
TkcLine.new(@canvas, [712, 363, 712, 355],
:fill=>@C['fg'], :width=>3, :tag=>'I2_1')
# L strap
TkcLine.new(@canvas, [705, 363, 705, 355],
:fill=>@C['fg'], :width=>3, :tag=>'I2_2')
# Match stick
TkcLine.new(@canvas, [679, 356, 679, 360, 717, 360, 717, 356, 679, 356],
:fill=>@C['fg'], :width=>3, :tag=>'I2_3')
# Match head
TkcPolygon.new(@canvas,
[ 671, 352, 677.4, 353.9, 680, 358.5, 677.4, 363.1,
671, 365, 664.6, 363.1, 662, 358.5, 664.6, 353.9 ],
:fill=>color, :outline=>color, :tag=>'I2_4')
end
def move2(step = nil)
step = get_step(2, step)
stages = [0, 0, 1, 2, 0, 2, 1, 0, 1, 2, 0, 2, 1]
xy = []
xy[0] = [
686, 333, 692, 323, 682, 316, 674, 309, 671, 295, 668, 307,
662, 318, 662, 328, 671, 336
]
xy[1] = [
687, 331, 698, 322, 703, 295, 680, 320, 668, 297, 663, 311,
661, 327, 671, 335
]
xy[2] = [
686, 331, 704, 322, 688, 300, 678, 283, 678, 283, 674, 298,
666, 309, 660, 324, 672, 336
]
if step >= stages.length
@canvas.delete('I2')
return 0
end
if step == 0 # Rotate the match
beta = 20
ox, oy = anchor('I2_0', :s) # Where to pivot
i = 0
until @canvas.find_withtag("I2_#{i}").empty?
rotate_item("I2_#{i}", ox, oy, beta)
i += 1
end
# For the flame
TkcPolygon.new(@canvas, [], :tag=>'I2', :smooth=>true, :fill=>@C['2'])
return 1
end
@canvas.coords('I2', xy[stages[step]])
return ((step == 7)? 3: 1)
end
# Weight and pulleys
def draw3
color = @C['3a']
color2 = @C['3b']
xy = [ [602, 296], [577, 174], [518, 174] ]
xy.each{|x, y| # 3 Pulleys
TkcOval.new(@canvas, box(x, y, 13),
:fill=>color, :outline=>@C['fg'], :width=>3)
TkcOval.new(@canvas, box(x, y, 2), :fill=>@C['fg'], :outline=>@C['fg'])
}
# Wall to flame
TkcLine.new(@canvas, [750, 309, 670, 309], :tag=>'I3_s',
:width=>3, :fill=>@C['fg'], :smooth=>true)
# Flame to pulley 1
TkcLine.new(@canvas, [670, 309, 650, 309], :tag=>'I3_0',
:width=>3, :fill=>@C['fg'], :smooth=>true)
TkcLine.new(@canvas, [650, 309, 600, 309], :tag=>'I3_1',
:width=>3, :fill=>@C['fg'], :smooth=>true)
# Pulley 1 half way to 2
TkcLine.new(@canvas, [589, 296, 589, 235], :tag=>'I3_2',
:width=>3, :fill=>@C['fg'])
# Pulley 1 other half to 2
TkcLine.new(@canvas, [589, 235, 589, 174], :width=>3, :fill=>@C['fg'])
# Across the top
TkcLine.new(@canvas, [577, 161, 518, 161], :width=>3, :fill=>@C['fg'])
# Down to weight
TkcLine.new(@canvas, [505, 174, 505, 205], :tag=>'I3_w',
:width=>3, :fill=>@C['fg'])
# Draw the weight as 2 circles, two rectangles and 1 rounded rectangle
x1, y1, x2, y2 = [515, 207, 495, 207]
TkcOval.new(@canvas, box(x1, y1, 6),
:tag=>'I3_', :fill=>color2, :outline=>color2)
TkcOval.new(@canvas, box(x2, y2, 6),
:tag=>'I3_', :fill=>color2, :outline=>color2)
TkcRectangle.new(@canvas, x1, y1 - 6, x2, y2 + 6,
:tag=>'I3_', :fill=>color2, :outline=>color2)
TkcPolygon.new(@canvas, round_rect([492, 220, 518, 263], 15),
:smooth=>true, :tag=>'I3_', :fill=>color2, :outline=>color2)
TkcLine.new(@canvas, [500, 217, 511, 217],
:tag=>'I3_', :fill=>color2, :width=>10)
# Bottom weight target
TkcLine.new(@canvas, [502, 393, 522, 393, 522, 465],
:tag=>'I3__', :fill=>@C['fg'], :joinstyle=>:miter, :width=>10)
end
def move3(step = nil)
step = get_step(3, step)
pos = [ [505, 247], [505, 297], [505, 386.5], [505, 386.5] ]
rope = []
rope[0] = [750, 309, 729, 301, 711, 324, 690, 300]
rope[1] = [750, 309, 737, 292, 736, 335, 717, 315, 712, 320]
rope[2] = [750, 309, 737, 309, 740, 343, 736, 351, 725, 340]
rope[3] = [750, 309, 738, 321, 746, 345, 742, 356]
return 0 if step >= pos.length
@canvas.delete("I3_#{step}") # Delete part of the rope
move_abs('I3_', pos[step]) # Move weight down
@canvas.coords('I3_s', rope[step]) # Flapping rope end
@canvas.coords('I3_w', [505, 174].concat(pos[step]))
if step == 2
@canvas.move('I3__', 0, 30)
return 2
end
return 1
end
# Cage and door
def draw4
color = @C['4']
x0, y0, x1, y1 = [527, 356, 611, 464]
# Horizontal bars
y0.step(y1, 12){|y|
TkcLine.new(@canvas, [x0, y, x1, y], :fill=>color, :width=>1)
}
# Vertical bars
x0.step(x1, 12){|x|
TkcLine.new(@canvas, [x, y0, x, y1], :fill=>color, :width=>1)
}
# Swing gate
TkcLine.new(@canvas, [518, 464, 518, 428],
:tag=>'I4', :fill=>color, :width=>1)
end
def move4(step = nil)
step = get_step(4, step)
angles = [-10, -20, -30, -30]
return 0 if step >= angles.length
rotate_item('I4', 518, 464, angles[step])
@canvas.raise('I4')
return((step == 3)? 3: 1)
end
# Mouse
def draw5
color = @C['5a']
color2 = @C['5b']
xy = [377, 248, 410, 248, 410, 465, 518, 465] # Mouse course
xy.concat [518, 428, 451, 428, 451, 212, 377, 212]
TkcPolygon.new(@canvas, xy, :fill=>color2, :outline=>@C['fg'], :width=>3)
xy = [
534.5, 445.5, 541, 440, 552, 436, 560, 436, 569, 440, 574, 446,
575, 452, 574, 454, 566, 456, 554, 456, 545, 456, 537, 454, 530, 452
]
TkcPolygon.new(@canvas, xy, :tag=>['I5', 'I5_0'], :fill=>color)
TkcLine.new(@canvas, [573, 452, 592, 458, 601, 460, 613, 456], # Tail
:tag=>['I5', 'I5_1'], :fill=>color, :smooth=>true, :width=>3)
xy = box(540, 446, 2) # Eye
xy = [540, 444, 541, 445, 541, 447, 540, 448, 538, 447, 538, 445]
TkcPolygon.new(@canvas, xy, :tag=>['I5', 'I5_2'], :fill=>@C['bg'],
:outline=>'', :smooth=>true)
xy = [538, 454, 535, 461] # Front leg
TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_3'], :fill=>color, :width=>2)
xy = [566, 455, 569, 462] # Back leg
TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_4'], :fill=>color, :width=>2)
xy = [544, 455, 545, 460] # 2nd front leg
TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_5'], :fill=>color, :width=>2)
xy = [560, 455, 558, 460] # 2nd back leg
TkcLine.new(@canvas, xy, :tag=>['I5', 'I5_6'], :fill=>color, :width=>2)
end
def move5(step = nil)
step = get_step(5, step)
pos = [
[553, 452], [533, 452], [513, 452], [493, 452], [473, 452],
[463, 442, 30], [445.5, 441.5, 30], [425.5, 434.5, 30], [422, 414],
[422, 394], [422, 374], [422, 354], [422, 334], [422, 314], [422, 294],
[422, 274, -30], [422, 260.5, -30, :x], [422.5, 248.5, -28], [425, 237]
]
return 0 if step >= pos.length
x, y, beta, nxt = pos[step]
move_abs('I5', [x, y])
if beta
ox, oy = centroid('I5_0')
(0..6).each{|id| rotate_item("I5_#{id}", ox, oy, beta) }
end
return 3 if nxt == :x
return 1
end
# Dropping gumballs
def draw6
color = @C['6']
xy = [324, 130, 391, 204] # Ball holder
xy = round_rect(xy, 10)
TkcPolygon.new(@canvas, xy, :smooth=>true,
:outline=>@C['fg'], :width=>3, :fill=>color)
xy = [339, 204, 376, 253] # Below the ball holder
TkcRectangle.new(@canvas, xy, :outline=>@C['fg'], :width=>3,
:fill=>color, :tag=>'I6c')
xy = box(346, 339, 28)
TkcOval.new(@canvas, xy, :fill=>color, :outline=>'') # Roter
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>2, :style=>:arc,
:start=>80, :extent=>205)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>2, :style=>:arc,
:start=>-41, :extent=>85)
xy = box(346, 339, 15) # Center of rotor
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['fg'], :tag=>'I6m')
xy = [352, 312, 352, 254, 368, 254, 368, 322] # Top drop to rotor
TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'')
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2)
xy = [353, 240, 367, 300] # Poke bottom hole
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
xy = [341, 190, 375, 210] # Poke another hole
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
xy = [
368, 356, 368, 403, 389, 403, 389, 464, 320, 464, 320, 403,
352, 403, 352, 366
]
TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'',
:width=>2) # Below rotor
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2)
xy = box(275, 342, 7) # On/off rotor
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['fg'])
xy = [276, 334, 342, 325] # Fan belt top
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = [276, 349, 342, 353] # Fan belt bottom
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = [337, 212, 337, 247] # What the mouse pushes
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I6_')
xy = [392, 212, 392, 247]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I6_')
xy = [337, 230, 392, 230]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>7, :tag=>'I6_')
who = -1 # All the balls
colors = %w(red cyan orange green blue darkblue)
colors *= 3
(0..16).each{|i|
loc = -i
color = colors[i]
x, y = @XY6["#{loc}"]
TkcOval.new(@canvas, box(x, y, 5),
:fill=>color, :outline=>color, :tag=>"I6_b#{i}")
}
draw6a(12) # The wheel
end
def draw6a(beta)
@canvas.delete('I6_0')
ox, oy = [346, 339]
(0..3).each{|i|
b = beta + i * 45
x, y = rotate_c(28, 0, 0, 0, b)
xy = [ox + x, oy + y, ox - x, oy - y]
TkcLine.new(@canvas, xy, :tag=>'I6_0', :fill=>@C['fg'], :width=>2)
}
end
def move6(step = nil)
step = get_step(6, step)
return 0 if step > 62
if step < 2 # Open gate for balls to drop
@canvas.move('I6_', -7, 0)
if step == 1 # Poke a hole
xy = [348, 226, 365, 240]
TkcRectangle.new(@canvas, xy, :fill=>@canvas.itemcget('I6c', :fill),
:outline=>'')
end
return 1
end
s = step - 1 # Do the gumball drop dance
(0..(((s - 1)/3).to_i)).each{|i|
tag = "I6_b#{i}"
break if @canvas.find_withtag(tag).empty?
loc = s - 3*i
if @XY6["#{loc},#{i}"]
move_abs(tag, @XY6["#{loc},#{i}"])
elsif @XY6["#{loc}"]
move_abs(tag, @XY6["#{loc}"])
end
}
if s % 3 == 1
first = (s + 2)/3
i = first
loop {
tag = "I6_b#{i}"
break if @canvas.find_withtag(tag).empty?
loc = first - i
move_abs(tag, @XY6["#{loc}"])
i += 1
}
end
if s >= 3 # Rotate the motor
idx = s % 3
draw6a(12 + s * 15)
end
return((s == 3)? 3 : 1)
end
# On/off switch
def draw7
color = @C['7']
xy = [198, 306, 277, 374] # Box
TkcRectangle.new(@canvas, xy, :outline=>@C['fg'], :width=>2,
:fill=>color, :tag=>'I7z')
@canvas.lower('I7z')
xy = [275, 343, 230, 349]
TkcLine.new(@canvas, xy, :tag=>'I7', :fill=>@C['fg'], :arrow=>:last,
:arrowshape=>[23, 23, 8], :width=>6)
xy = [225, 324] # On button
x, y = xy
TkcOval.new(@canvas, box(x, y, 3), :fill=>@C['fg'], :outline=>@C['fg'])
xy = [218, 323] # On text
font = ['Times Roman', 8]
TkcText.new(@canvas, xy, :text=>'on', :anchor=>:e,
:fill=>@C['fg'], :font=>font)
xy = [225, 350] # Off button
x, y = xy
TkcOval.new(@canvas, box(x, y, 3), :fill=>@C['fg'], :outline=>@C['fg'])
xy = [218, 349] # Off text
TkcText.new(@canvas, xy, :text=>'off', :anchor=>:e,
:fill=>@C['fg'], :font=>font)
end
def move7(step = nil)
step = get_step(7, step)
numsteps = 30
return 0 if step > numsteps
beta = 30.0 / numsteps
rotate_item('I7', 275, 343, beta)
return((step == numsteps)? 3: 1)
end
# Electricity to the fan
def draw8
sine([271, 248, 271, 306], 5, 8, :tag=>'I8_s', :fill=>@C['8'], :width=>3)
end
def move8(step = nil)
step = get_step(8, step)
return 0 if step > 3
if step == 0
sparkle(anchor('I8_s', :s), 'I8')
return 1
elsif step == 1
move_abs('I8', anchor('I8_s', :c))
elsif step == 2
move_abs('I8', anchor('I8_s', :n))
else
@canvas.delete('I8')
end
return((step == 2)? 3: 1)
end
# Fan
def draw9
color = @C['9']
xy = [266, 194, 310, 220]
TkcOval.new(@canvas, xy, :outline=>color, :fill=>color)
xy = [280, 209, 296, 248]
TkcOval.new(@canvas, xy, :outline=>color, :fill=>color)
xy = [
288, 249, 252, 249, 260, 240, 280, 234,
296, 234, 316, 240, 324, 249, 288, 249
]
TkcPolygon.new(@canvas, xy, :fill=>color, :smooth=>true)
xy = [248, 205, 265, 214, 264, 205, 265, 196] # Spinner
TkcPolygon.new(@canvas, xy, :fill=>color)
xy = [255, 206, 265, 234] # Fan blades
TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
:width=>3, :tag=>'I9_0')
xy = [255, 176, 265, 204]
TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
:width=>3, :tag=>'I9_0')
xy = [255, 206, 265, 220]
TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
:width=>1, :tag=>'I9_1')
xy = [255, 190, 265, 204]
TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'],
:width=>1, :tag=>'I9_1')
end
def move9(step = nil)
step = get_step(9, step)
if (step & 1).nonzero?
@canvas.itemconfigure('I9_0', :width=>4)
@canvas.itemconfigure('I9_1', :width=>1)
@canvas.lower('I9_1', 'I9_0')
else
@canvas.itemconfigure('I9_0', :width=>1)
@canvas.itemconfigure('I9_1', :width=>4)
@canvas.lower('I9_0', 'I9_1')
end
return 3 if step == 0
return 1
end
# Boat
def draw10
color = @C['10a']
color2 = @C['10b']
xy = [191, 230, 233, 230, 233, 178, 191, 178] # Sail
TkcPolygon.new(@canvas, xy, :fill=>color, :width=>3, :outline=>@C['fg'],
:tag=>'I10')
xy = box(209, 204, 31) # Front
TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :style=>:pie,
:start=>120, :extent=>120, :tag=>'I10')
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
:start=>120, :extent=>120, :tag=>'I10')
xy = box(249, 204, 31) # Back
TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>3,
:style=>:pie, :start=>120, :extent=>120, :tag=>'I10')
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
:start=>120, :extent=>120, :tag=>'I10')
xy = [200, 171, 200, 249] # Mast
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I10')
xy = [159, 234, 182, 234] # Bow sprit
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I10')
xy = [180, 234, 180, 251, 220, 251] # Hull
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>6, :tag=>'I10')
xy = [92, 255, 221, 255] # Waves
sine(xy, 2, 25, :fill=>color2, :width=>1, :tag=>'I10w')
xy = @canvas.coords('I10w')[4..-5] # Water
xy.concat([222, 266, 222, 277, 99, 277])
TkcPolygon.new(@canvas, xy, :fill=>color2, :outline=>color2)
xy = [222, 266, 222, 277, 97, 277, 97, 266] # Water bottom
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = box(239, 262, 17)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
:start=>95, :extent=>103)
xy = box(76, 266, 21)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
:extent=>190)
end
def move10(step = nil)
step = get_step(10, step)
pos = [
[195, 212], [193, 212], [190, 212], [186, 212], [181, 212], [176, 212],
[171, 212], [166, 212], [161, 212], [156, 212], [151, 212], [147, 212],
[142, 212], [137, 212], [132, 212, :x], [127, 212], [121, 212],
[116, 212], [111, 212]
]
return 0 if step >= pos.length
where = pos[step]
move_abs('I10', where)
return 3 if where[2] == :x
return 1
end
# 2nd ball drop
def draw11
color = @C['11a']
color2 = @C['11b']
xy = [23, 264, 55, 591] # Color the down tube
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>'')
xy = box(71, 460, 48) # Color the outer loop
TkcOval.new(@canvas, xy, :fill=>color, :outline=>'')
xy = [55, 264, 55, 458] # Top right side
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = [55, 504, 55, 591] # Bottom right side
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = box(71, 460, 48) # Outer loop
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
:start=>110, :extent=>-290, :tag=>'I11i')
xy = box(71, 460, 16) # Inner loop
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>'',
:width=>3, :tag=>'I11i')
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>@C['bg'], :width=>3)
xy = [23, 264, 23, 591] # Left side
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = box(1, 266, 23) # Top left curve
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3,
:style=>:arc, :extent=>90)
xy = box(75, 235, 9) # The ball
TkcOval.new(@canvas, xy, :fill=>color2, :outline=>'',
:width=>3, :tag=>'I11')
end
def move11(step = nil)
step = get_step(11, step)
pos = [
[75, 235], [70, 235], [65, 237], [56, 240], [46, 247], [38, 266],
[38, 296], [38, 333], [38, 399], [38, 475], [74, 496], [105, 472],
[100, 437], [65, 423], [-100, -100], [38, 505], [38, 527, :x], [38, 591]
]
return 0 if step >= pos.length
where = pos[step]
move_abs('I11', where)
return 3 if where[2] == :x
return 1
end
# Hand
def draw12
xy = [
20, 637, 20, 617, 20, 610, 20, 590, 40, 590, 40, 590,
60, 590, 60, 610, 60, 610
]
xy.concat([60, 610, 65, 620, 60, 631]) # Thumb
xy.concat([60, 631, 60, 637, 60, 662, 60, 669, 52, 669,
56, 669, 50, 669, 50, 662, 50, 637])
y0 = 637 # Bumps for fingers
y1 = 645
50.step(21, -10){|x|
x1 = x - 5
x2 = x - 10
xy << x << y0 << x1 << y1 << x2 << y0
}
TkcPolygon.new(@canvas, xy, :fill=>@C['12'], :outline=>@C['fg'],
:smooth=>true, :tag=>'I12', :width=>3)
end
def move12(step = nil)
step = get_step(12, step)
pos = [[42.5, 641, :x]]
return 0 if step >= pos.length
where = pos[step]
move_abs('I12', where)
return 3 if where[2] == :x
return 1
end
# Fax
def draw13
color = @C['13a']
xy = [86, 663, 149, 663, 149, 704, 50, 704, 50, 681, 64, 681, 86, 671]
xy2 = [
784, 663, 721, 663, 721, 704, 820, 704, 820, 681, 806, 681, 784, 671
]
radii = [2, 9, 9, 8, 5, 5, 2]
round_poly(@canvas, xy, radii, :width=>3,
:outline=>@C['fg'], :fill=>color)
round_poly(@canvas, xy2, radii, :width=>3,
:outline=>@C['fg'], :fill=>color)
xy = [56, 677]
x, y = xy
TkcRectangle.new(@canvas, box(x, y, 4), :fill=>'', :outline=>@C['fg'],
:width=>3, :tag=>'I13')
xy = [809, 677]
x, y = xy
TkcRectangle.new(@canvas, box(x, y, 4), :fill=>'', :outline=>@C['fg'],
:width=>3, :tag=>'I13R')
xy = [112, 687] # Label
TkcText.new(@canvas, xy, :text=>'FAX', :fill=>@C['fg'],
:font=>['Times Roman', 12, :bold])
xy = [762, 687]
TkcText.new(@canvas, xy, :text=>'FAX', :fill=>@C['fg'],
:font=>['<NAME>', 12, :bold])
xy = [138, 663, 148, 636, 178, 636] # Paper guide
TkcLine.new(@canvas, xy, :smooth=>true, :fill=>@C['fg'], :width=>3)
xy = [732, 663, 722, 636, 692, 636]
TkcLine.new(@canvas, xy, :smooth=>true, :fill=>@C['fg'], :width=>3)
sine([149, 688, 720, 688], 5, 15,
:tag=>'I13_s', :fill=>@C['fg'], :width=>3)
end
def move13(step = nil)
step = get_step(13, step)
numsteps = 7
if step == numsteps + 2
move_abs('I13_star', [-100, -100])
@canvas.itemconfigure('I13R', :fill=>@C['13b'], :width=>2)
return 2
end
if step == 0 # Button down
@canvas.delete('I13')
sparkle([-100, -100], 'I13_star') # Create off screen
return 1
end
x0, y0 = anchor('I13_s', :w)
x1, y1 = anchor('I13_s', :e)
x = x0 + (x1 - x0) * (step - 1) / numsteps.to_f
move_abs('I13_star', [x, y0])
return 1
end
# Paper in fax
def draw14
color = @C['14']
xy = [102, 661, 113, 632, 130, 618] # Left paper edge
TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
:width=>3, :tag=>'I14L_0')
xy = [148, 629, 125, 640, 124, 662] # Right paper edge
TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
:width=>3, :tag=>'I14L_1')
draw14a('L')
xy = [
768.0, 662.5, 767.991316225, 662.433786215, 767.926187912, 662.396880171
]
TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
:width=>3, :tag=>'I14R_0')
@canvas.lower('I14R_0')
# NB. these numbers are VERY sensitive, you must start with final size
# and shrink down to get the values
xy = [
745.947897349, 662.428358855, 745.997829056, 662.452239237, 746.0, 662.5
]
TkcLine.new(@canvas, xy, :smooth=>true, :fill=>color,
:width=>3, :tag=>'I14R_1')
@canvas.lower('I14R_1')
end
def draw14a(side)
color = @C['14']
xy = @canvas.coords("I14#{side}_0")
xy2 = @canvas.coords("I14#{side}_1")
x0, y0, x1, y1, x2, y2 = xy
x3, y3, x4, y4, x5, y5 = xy2
zz = [
x0, y0, x0, y0, xy, x2, y2, x2, y2,
x3, y3, x3, y3, xy2, x5, y5, x5, y5
].flatten
@canvas.delete("I14#{side}")
TkcPolygon.new(@canvas, zz, :tag=>"I14#{side}", :smooth=>true,
:fill=>color, :outline=>color, :width=>3)
@canvas.lower("I14#{side}")
end
def move14(step = nil)
step = get_step(14, step)
# Paper going down
sc = 0.9 - 0.05*step
if sc < 0.3
@canvas.delete('I14L')
return 0
end
ox, oy = @canvas.coords('I14L_0')
@canvas.scale('I14L_0', ox, oy, sc, sc)
ox, oy = @canvas.coords('I14L_1')[-2..-1]
@canvas.scale('I14L_1', ox, oy, sc, sc)
draw14a('L')
# Paper going up
sc = 0.35 + 0.05*step
sc = 1/sc
ox, oy = @canvas.coords('I14R_0')
@canvas.scale('I14R_0', ox, oy, sc, sc)
ox, oy = @canvas.coords('I14R_1')[-2..-1]
@canvas.scale('I14R_1', ox, oy, sc, sc)
draw14a('R')
return((step == 10)? 3: 1)
end
# Light beam
def draw15
color = @C['15a']
xy = [824, 599, 824, 585, 820, 585, 829, 585]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I15a')
xy = [789, 599, 836, 643]
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
xy = [778, 610, 788, 632]
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
xy = [766, 617, 776, 625]
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
xy = [633, 600, 681, 640]
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>3)
xy = [635, 567, 657, 599]
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2)
xy = [765, 557, 784, 583]
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2)
sine([658, 580, 765, 580], 3, 15,
:tag=>'I15_s', :fill=>@C['fg'], :width=>3)
end
def move15a
color = @C['15b']
@canvas.scale('I15a', 824, 599, 1, 0.3) # Button down
xy = [765, 621, 681, 621]
TkcLine.new(@canvas, xy, :dash=>'-', :width=>3, :fill=>color, :tag=>'I15')
end
def move15(step = nil)
step = get_step(15, step)
numsteps = 6
if step == numsteps + 2
move_abs('I15_star', [-100, -100])
return 2
end
if step == 0 # Break the light beam
sparkle([-100, -100], 'I15_star')
xy = [765, 621, 745, 621]
@canvas.coords('I15', xy)
return 1
end
x0, y0 = anchor('I15_s', :w)
x1, y1 = anchor('I15_s', :e)
x = x0 + (x1 - x0) * (step - 1) / numsteps.to_f
move_abs('I15_star', [x, y0])
return 1
end
# Bell
def draw16
color = @C['16']
xy = [722, 485, 791, 556]
TkcRectangle.new(@canvas, xy, :fill=>'', :outline=>@C['fg'], :width=>3)
xy = box(752, 515, 25) # Bell
TkcOval.new(@canvas, xy, :fill=>color, :outline=>'black',
:tag=>'I16b', :width=>2)
xy = box(752, 515, 5) # Bell button
TkcOval.new(@canvas, xy, :fill=>'black', :outline=>'black', :tag=>'I16b')
xy = [784, 523, 764, 549] # Clapper
TkcLine.new(@canvas, xy, :width=>3, :tag=>'I16c', :fill=>@C['fg'])
xy = box(784, 523, 4)
TkcOval.new(@canvas, xy, :fill=>@C['fg'], :outline=>@C['fg'], :tag=>'I16d')
end
def move16(step = nil)
step = get_step(16, step)
# Note: we never stop
ox, oy = [760, 553]
if (step & 1).nonzero?
beta = 12
@canvas.move('I16b', 3, 0)
else
beta = -12
@canvas.move('I16b', -3, 0)
end
rotate_item('I16c', ox, oy, beta)
rotate_item('I16d', ox, oy, beta)
return ((step == 1)? 3: 1)
end
# Cat
def draw17
color = @C['17']
xy = [584, 556, 722, 556]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = [584, 485, 722, 485]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3)
xy = [664, 523, 717, 549] # Body
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :fill=>color, :width=>3,
:style=>:chord, :start=>128, :extent=>260, :tag=>'I17')
xy = [709, 554, 690, 543] # Paw
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>color,
:width=>3, :tag=>'I17')
xy = [657, 544, 676, 555]
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :fill=>color,
:width=>3, :tag=>'I17')
xy = box(660, 535, 15) # Lower face
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :style=>:arc,
:start=>150, :extent=>240, :tag=>'I17_')
TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
:style=>:chord, :start=>150, :extent=>240, :tag=>'I17_')
xy = [674, 529, 670, 513, 662, 521, 658, 521, 650, 513, 647, 529] # Ears
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>'', :width=>1,
:tag=>['I17_', 'I17_c'])
xy = [652, 542, 628, 539] # Whiskers
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
xy = [652, 543, 632, 545]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
xy = [652, 546, 632, 552]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
xy = [668, 543, 687, 538]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
:tag=>['I17_', 'I17_w'])
xy = [668, 544, 688, 546]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
:tag=>['I17_', 'I17_w'])
xy = [668, 547, 688, 553]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
:tag=>['I17_', 'I17_w'])
xy = [649, 530, 654, 538, 659, 530] # Left eye
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
:smooth=>true, :tag=>'I17')
xy = [671, 530, 666, 538, 661, 530] # Right eye
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
:smooth=>true, :tag=>'I17')
xy = [655, 543, 660, 551, 665, 543] # Mouth
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2,
:smooth=>true, :tag=>'I17')
end
def move17(step = nil)
step = get_step(17, step)
if step == 0
@canvas.delete('I17') # Delete most of the cat
xy = [655, 543, 660, 535, 665, 543] # Mouth
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
:smooth=>true, :tag=>'I17_')
xy = box(654, 530, 4) # Left eye
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :fill=>'',
:tag=>'I17_')
xy = box(666, 530, 4) # Right eye
TkcOval.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :fill=>'',
:tag=>'I17_')
@canvas.move('I17_', 0, -20) # Move face up
xy = [652, 528, 652, 554] # Front leg
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
xy = [670, 528, 670, 554] # 2nd front leg
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
xy = [ # Body
675, 506, 694, 489, 715, 513, 715, 513, 715, 513, 716, 525,
716, 525, 716, 525, 706, 530, 695, 530, 679, 535, 668, 527,
668, 527, 668, 527, 675, 522, 676, 517, 677, 512
]
TkcPolygon.new(@canvas, xy, :fill=>@canvas.itemcget('I17_c', :fill),
:outline=>@C['fg'], :width=>3, :smooth=>true,
:tag=>'I17_')
xy = [716, 514, 716, 554] # Back leg
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
xy = [694, 532, 694, 554] # 2nd back leg
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I17_')
xy = [715, 514, 718, 506, 719, 495, 716, 488] # Tail
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3,
:smooth=>true, :tag=>'I17_')
@canvas.raise('I17w') # Make whiskers visible
@canvas.move('I17_', -5, 0) # Move away from the wall a bit
return 2
end
return 0
end
# Sling shot
def draw18
color = @C['18']
xy = [721, 506, 627, 506] # Sling hold
TkcLine.new(@canvas, xy, :width=>4, :fill=>@C['fg'], :tag=>'I18')
xy = [607, 500, 628, 513] # Sling rock
TkcOval.new(@canvas, xy, :fill=>color, :outline=>'', :tag=>'I18a')
xy = [526, 513, 606, 507, 494, 502] # Sling band
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>4, :tag=>'I18b')
xy = [485, 490, 510, 540, 510, 575, 510, 540, 535, 491] # Sling
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>6)
end
def move18(step = nil)
step = get_step(18, step)
pos = [
[587, 506], [537, 506], [466, 506], [376, 506], [266, 506, :x],
[136, 506], [16, 506], [-100, -100]
]
b = []
b[0] = [490, 502, 719, 507, 524, 512] # Band collapsing
b[1] = [
491, 503, 524, 557, 563, 505, 559, 496, 546, 506, 551, 525,
553, 536, 538, 534, 532, 519, 529, 499
]
b[2] = [
491, 503, 508, 563, 542, 533, 551, 526, 561, 539, 549, 550, 530, 500
]
b[3] = [
491, 503, 508, 563, 530, 554, 541, 562, 525, 568, 519, 544, 530, 501
]
return 0 if step >= pos.length
if step == 0
@canvas.delete('I18')
@canvas.itemconfigure('I18b', :smooth=>true)
end
if b[step]
@canvas.coords('I18b', b[step])
end
where = pos[step]
move_abs('I18a', where)
return 3 if where[2] == :x
return 1
end
# Water pipe
def draw19
color = @C['19']
xx = [[249, 181], [155, 118], [86, 55], [22, 0]]
xx.each{|x1, x2|
TkcRectangle.new(@canvas, x1, 453, x2, 467,
:fill=>color, :outline=>'', :tag=>'I19')
TkcLine.new(@canvas, x1, 453, x2, 453,
:fill=>@C['fg'], :width=>1) # Pipe top
TkcLine.new(@canvas, x1, 467, x2, 467,
:fill=>@C['fg'], :width=>1) # Pipe bottom
}
@canvas.raise('I11i')
xy = box(168, 460, 16) # Bulge by the joint
TkcOval.new(@canvas, xy, :fill=>color, :outline=>'')
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1, :style=>:arc,
:start=>21, :extent=>136)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1, :style=>:arc,
:start=>-21, :extent=>-130)
xy = [249, 447, 255, 473] # First joint 26x6
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
xy = box(257, 433, 34) # Bend up
TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
:style=>:pie, :start=>0, :extent=>-91)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
:style=>:arc, :start=>0, :extent=>-90)
xy = box(257, 433, 20)
TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
:style=>:pie, :start=>0, :extent=>-92)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
:style=>:arc, :start=>0, :extent=>-90)
xy = box(257, 421, 34) # Bend left
TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
:style=>:pie, :start=>0, :extent=>91)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
:style=>:arc, :start=>0, :extent=>90)
xy = box(257, 421, 20)
TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
:style=>:pie, :start=>0, :extent=>90)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
:style=>:arc, :start=>0, :extent=>90)
xy = box(243, 421, 34) # Bend down
TkcArc.new(@canvas, xy, :outline=>'', :fill=>color, :width=>1,
:style=>:pie, :start=>90, :extent=>90)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
:style=>:arc, :start=>90, :extent=>90)
xy = box(243, 421, 20)
TkcArc.new(@canvas, xy, :outline=>'', :fill=>@C['bg'], :width=>1,
:style=>:pie, :start=>90, :extent=>90)
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>1,
:style=>:arc, :start=>90, :extent=>90)
xy = [270, 427, 296, 433] # 2nd joint bottom
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
xy = [270, 421, 296, 427] # 2nd joint top
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
xy = [249, 382, 255, 408] # Third joint right
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
xy = [243, 382, 249, 408] # Third joint left
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
xy = [203, 420, 229, 426] # Last joint
TkcRectangle.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>1)
xy = box(168, 460, 6) # Handle joint
TkcOval.new(@canvas, xy, :fill=>@C['fg'], :outline=>'', :tag=>'I19a')
xy = [168, 460, 168, 512] # Handle bar
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>5, :tag=>'I19b')
end
def move19(step = nil)
step = get_step(19, step)
angles = [30, 30, 30]
return 2 if step == angles.length
ox, oy = centroid('I19a')
rotate_item('I19b', ox, oy, angles[step])
return 1
end
# Water pouring
def draw20
# do nothing
end
def move20(step = nil)
step = get_step(20, step)
pos = [451, 462, 473, 484, 496, 504, 513, 523, 532]
freq = [20, 40, 40, 40, 40, 40, 40, 40, 40]
pos = [
[451, 20], [462, 40], [473, 40], [484, 40], [496, 40],
[504, 40], [513, 40], [523, 40], [532, 40, :x]
]
return 0 if step >= pos.length
@canvas.delete('I20')
where = pos[step]
y, f = where
h20(y, f)
return 3 if where[2] == :x
return 1
end
def h20(y, f)
color = @C['20']
@canvas.delete('I20')
sine([208, 428, 208, y], 4, f, :tag=>['I20', 'I20s'],
:width=>3, :fill=>color, :smooth=>true)
TkcLine.new(@canvas, @canvas.coords('I20s'), :width=>3,
:fill=>color, :smooth=>1, :tag=>['I20', 'I20a'])
TkcLine.new(@canvas, @canvas.coords('I20s'), :width=>3,
:fill=>color, :smooth=>1, :tag=>['I20', 'I20b'])
@canvas.move('I20a', 8, 0)
@canvas.move('I20b', 16, 0)
end
# Bucket
def draw21
color = @C['21']
xy = [217, 451, 244, 490] # Right handle
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21_a')
xy = [201, 467, 182, 490] # Left handle
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21_a')
xy = [245, 490, 237, 535] # Right side
xy2 = [189, 535, 181, 490] # Left side
TkcPolygon.new(@canvas, xy + xy2, :fill=>color, :outline=>'',
:tag=>['I21', 'I21f'])
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>2, :tag=>'I21')
TkcLine.new(@canvas, xy2, :fill=>@C['fg'], :width=>2, :tag=>'I21')
xy = [182, 486, 244, 498] # Top
TkcOval.new(@canvas, xy, :fill=>color, :outline=>'', :width=>2,
:tag=>['I21', 'I21f'])
TkcOval.new(@canvas, xy, :fill=>'', :outline=>@C['fg'], :width=>2,
:tag=>['I21', 'I21t'])
xy = [189, 532, 237, 540] # Bottom
TkcOval.new(@canvas, xy, :fill=>color, :outline=>@C['fg'], :width=>2,
:tag=>['I21', 'I21b'])
end
def move21(step = nil)
step = get_step(21, step)
numsteps = 30
return 0 if step >= numsteps
x1, y1, x2, y2 = @canvas.coords('I21b')
# lx1, ly1, lx2, ly2 = @canvas.coords('I21t')
lx1, ly1, lx2, ly2 = [183, 492, 243, 504]
f = step / numsteps.to_f
y2 = y2 - 3
xx1 = x1 + (lx1 - x1) * f
yy1 = y1 + (ly1 - y1) * f
xx2 = x2 + (lx2 - x2) * f
yy2 = y2 + (ly2 - y2) * f
@canvas.itemconfigure('I21b', :fill=>@C['20'])
@canvas.delete('I21w')
TkcPolygon.new(@canvas, x2, y2, x1, y1, xx1, yy1, xx2, yy1,
:tag=>['I21', 'I21w'], :outline=>'', :fill=>@C['20'])
@canvas.lower('I21w', 'I21')
@canvas.raise('I21b')
@canvas.lower('I21f')
return((step == numsteps - 1)? 3: 1)
end
# Bucket drop
def draw22
# do nothing
end
def move22(step = nil)
step = get_step(22, step)
pos = [[213, 513], [213, 523], [213, 543, :x], [213, 583], [213, 593]]
@canvas.itemconfigure('I21f', :fill=>@C['22']) if step == 0
return 0 if step >= pos.length
where = pos[step]
move_abs('I21', where)
h20(where[1], 40)
@canvas.delete('I21_a') # Delete handles
return 3 if where[2] == :x
return 1
end
# Blow dart
def draw23
color = @C['23a']
color2 = @C['23b']
color3 = @C['23c']
xy = [185, 623, 253, 650] # Block
TkcRectangle.new(@canvas, xy, :fill=>'black', :outline=>@C['fg'],
:width=>2, :tag=>'I23a')
xy = [187, 592, 241, 623] # Balloon
TkcOval.new(@canvas, xy, :outline=>'', :fill=>color, :tag=>'I23b')
TkcArc.new(@canvas, xy, :outline=>@C['fg'], :width=>3, :tag=>'I23b',
:style=>:arc, :start=>12, :extent=>336)
xy = [239, 604, 258, 589, 258, 625, 239, 610] # Balloon nozzle
TkcPolygon.new(@canvas, xy, :outline=>'', :fill=>color, :tag=>'I23b')
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23b')
xy = [285, 611, 250, 603] # Dart body
TkcOval.new(@canvas, xy, :fill=>color2, :outline=>@C['fg'],
:width=>3, :tag=>'I23d')
xy = [249, 596, 249, 618, 264, 607, 249, 596] # Dart tail
TkcPolygon.new(@canvas, xy, :fill=>color3, :outline=>@C['fg'],
:width=>3, :tag=>'I23d')
xy = [249, 607, 268, 607] # Dart detail
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23d')
xy = [285, 607, 305, 607] # Dart needle
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I23d')
end
def move23(step = nil)
step = get_step(23, step)
pos = [
[277, 607], [287, 607], [307, 607, :x], [347, 607], [407, 607],
[487, 607], [587, 607], [687, 607], [787, 607], [-100, -100]
]
return 0 if step >= pos.length
if step <= 1
ox, oy = anchor('I23a', :n)
@canvas.scale('I23b', ox, oy, 0.9, 0.5)
end
where = pos[step]
move_abs('I23d', where)
return 3 if where[2] == :x
return 1
end
# Balloon
def draw24
color = @C['24a']
xy = [366, 518, 462, 665] # Balloon
TkcOval.new(@canvas, xy, :fill=>color, :outline=>@C['fg'],
:width=>3, :tag=>'I24')
xy = [414, 666, 414, 729] # String
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :width=>3, :tag=>'I24')
xy = [410, 666, 404, 673, 422, 673, 418, 666] # Nozzle
TkcPolygon.new(@canvas, xy, :fill=>color, :outline=>@C['fg'],
:width=>3, :tag=>'I24')
xy = [387, 567, 390, 549, 404, 542] # Reflections
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
:width=>2, :tag=>'I24')
xy = [395, 568, 399, 554, 413, 547]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
:width=>2, :tag=>'I24')
xy = [403, 570, 396, 555, 381, 553]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
:width=>2, :tag=>'I24')
xy = [408, 564, 402, 547, 386, 545]
TkcLine.new(@canvas, xy, :fill=>@C['fg'], :smooth=>true,
:width=>2, :tag=>'I24')
end
def move24(step = nil)
step = get_step(24, step)
return 0 if step > 4
return 2 if step == 4
if step == 0
@canvas.delete('I24') # Exploding balloon
xy = [
347, 465, 361, 557, 271, 503, 272, 503, 342, 574, 259, 594,
259, 593, 362, 626, 320, 737, 320, 740, 398, 691, 436, 738,
436, 739, 476, 679, 528, 701, 527, 702, 494, 627, 548, 613,
548, 613, 480, 574, 577, 473, 577, 473, 474, 538, 445, 508,
431, 441, 431, 440, 400, 502, 347, 465, 347, 465
]
TkcPolygon.new(@canvas, xy, :tag=>'I24', :fill=>@C['24b'],
:outline=>@C['24a'], :width=>10, :smooth=>true)
msg = Tk.subst(@S['message'].value)
TkcText.new(@canvas, centroid('I24'), :text=>msg, :tag=>['I24', 'I24t'],
:justify=>:center, :font=>['Times Roman', 18, :bold])
return 1
end
@canvas.itemconfigure('I24t', :font=>['Times Roman', 18 + 6*step, :bold])
@canvas.move('I24', 0, -60)
ox, oy = centroid('I24')
@canvas.scale('I24', ox, oy, 1.25, 1.25)
return 1
end
# Displaying the message
def move25(step = nil)
step = get_step(25, step)
if step == 0
@XY['25'] = Tk::Clock.clicks(:miliseconds)
return 1
end
elapsed = Tk::Clock.clicks(:miliseconds) - @XY['25']
return 1 if elapsed < 5000
return 2
end
# Collapsing balloon
def move26(step = nil)
step = get_step(26, step)
if step >= 3
@canvas.delete('I24', 'I26')
TkcText.new(@canvas, 430, 740, :anchor=>:s, :tag=>'I26',
:text=>'click to continue',
:font=>['Times Roman', 24, :bold])
@canvas.bind('1', proc{reset})
return 4
end
ox, oy = centroid('I24')
@canvas.scale('I24', ox, oy, 0.8, 0.8)
@canvas.move('I24', 0, 60)
@canvas.itemconfigure('I24t', :font=>['Times Roman', 30 - 6*step, :bold])
return 1
end
################################################################
#
# Helper functions
#
def box(x, y, r)
[x - r, y - r, x + r, y + r]
end
def move_abs(item, xy)
x, y = xy
ox, oy = centroid(item)
dx = x - ox
dy = y - oy
@canvas.move(item, dx, dy)
end
def rotate_item(item, ox, oy, beta)
xy = @canvas.coords(item)
xy2 = []
0.step(xy.length - 1, 2){|idx|
x, y = xy[idx, 2]
xy2.concat(rotate_c(x, y, ox, oy, beta))
}
@canvas.coords(item, xy2)
end
def rotate_c(x, y, ox, oy, beta)
# rotates vector (ox,oy)->(x,y) by beta degrees clockwise
x -= ox # Shift to origin
y -= oy
beta = beta * Math.atan(1) * 4 / 180.0 # Radians
xx = x * Math.cos(beta) - y * Math.sin(beta) # Rotate
yy = x * Math.sin(beta) + y * Math.cos(beta)
xx += ox # Shift back
yy += oy
[xx, yy]
end
def reset
draw_all
@canvas.bind_remove('1')
@S['mode'].value = :MSTART
@S['active'] = [0]
end
# Each Move## keeps its state info in STEP, this retrieves and increments it
def get_step(who, step)
if step
@STEP[who] = step
else
if !@STEP.exist?(who) || @STEP[who] == ""
@STEP[who] = 0
else
@STEP[who] += 1
end
end
@STEP[who]
end
def reset_step
@S['cnt'].value = 0
@STEP.keys.each{|k| @STEP[k] = ''}
end
def sine(xy0, amp, freq, opts = {})
x0, y0, x1, y1 = xy0
step = 2
xy = []
if y0 == y1 # Horizontal
x0.step(x1, step){|x|
beta = (x - x0) * 2 * Math::PI / freq
y = y0 + amp * Math.sin(beta)
xy << x << y
}
else
y0.step(y1, step){|y|
beta = (y - y0) * 2 * Math::PI / freq
x = x0 + amp * Math.sin(beta)
xy << x << y
}
end
TkcLine.new(@canvas, xy, opts)
end
def round_rect(xy, radius, opts={})
x0, y0, x3, y3 = xy
r = @canvas.winfo_pixels(radius)
d = 2 * r
# Make sure that the radius of the curve is less than 3/8 size of the box!
maxr = 0.75
if d > maxr * (x3 - x0)
d = maxr * (x3 - x0)
end
if d > maxr * (y3 - y0)
d = maxr * (y3 - y0)
end
x1 = x0 + d
x2 = x3 - d
y1 = y0 + d
y2 = y3 - d
xy = [x0, y0, x1, y0, x2, y0, x3, y0, x3, y1, x3, y2]
xy.concat([x3, y3, x2, y3, x1, y3, x0, y3, x0, y2, x0, y1])
return xy
end
def round_poly(canv, xy, radii, opts)
lenXY = xy.length
lenR = radii.length
if lenXY != 2*lenR
raise "wrong number of vertices and radii"
end
knots = []
x0 = xy[-2]; y0 = xy[-1]
x1 = xy[0]; y1 = xy[1]
xy << xy[0] << xy[1]
0.step(lenXY - 1, 2){|i|
radius = radii[i/2]
r = canv.winfo_pixels(radius)
x2 = xy[i+2]; y2 = xy[i+3]
z = _round_poly2(x0, y0, x1, y1, x2, y2, r)
knots.concat(z)
x0 = x1; y0 = y1
x1 = x2; y1 = y2
}
TkcPolygon.new(canv, knots, {:smooth=>true}.update(opts))
end
def _round_poly2(x0, y0, x1, y1, x2, y2, radius)
d = 2 * radius
maxr = 0.75
v1x = x0 - x1
v1y = y0 - y1
v2x = x2 - x1
v2y = y2 - y1
vlen1 = Math.sqrt(v1x*v1x + v1y*v1y)
vlen2 = Math.sqrt(v2x*v2x + v2y*v2y)
if d > maxr * vlen1
d = maxr * vlen1
end
if d > maxr * vlen2
d = maxr * vlen2
end
xy = []
xy << (x1 + d * v1x / vlen1) << (y1 + d * v1y / vlen1)
xy << x1 << y1
xy << (x1 + d * v2x / vlen2) << (y1 + d * v2y / vlen2)
return xy
end
def sparkle(oxy, tag)
xy = [
[299, 283], [298, 302], [295, 314], [271, 331],
[239, 310], [242, 292], [256, 274], [281, 273]
]
xy.each{|x, y|
TkcLine.new(@canvas, 271, 304, x, y,
:fill=>'white', :width=>3, :tag=>tag)
}
move_abs(tag, oxy)
end
def centroid(item)
anchor(item, :c)
end
def anchor(item, where)
x1, y1, x2, y2 = @canvas.bbox(item)
case(where)
when :n
y = y1
when :s
y = y2
else
y = (y1 + y2) / 2.0
end
case(where)
when :w
x = x1
when :e
x = x2
else
x = (x1 + x2) / 2.0
end
return [x, y]
end
end
TkGoldberg_Demo.new(base_frame)
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/ripper/lib/ripper/sexp.rb
|
# frozen_string_literal: false
#
# $Id: sexp.rb 53143 2015-12-16 05:31:54Z naruse $
#
# Copyright (c) 2004,2005 <NAME>
#
# This program is free software.
# You can distribute and/or modify this program under the Ruby License.
# For details of Ruby License, see ruby/COPYING.
#
require 'ripper/core'
class Ripper
# [EXPERIMENTAL]
# Parses +src+ and create S-exp tree.
# Returns more readable tree rather than Ripper.sexp_raw.
# This method is mainly for developer use.
#
# require 'ripper'
# require 'pp'
#
# pp Ripper.sexp("def m(a) nil end")
# #=> [:program,
# [[:def,
# [:@ident, "m", [1, 4]],
# [:paren, [:params, [[:@ident, "a", [1, 6]]], nil, nil, nil, nil]],
# [:bodystmt, [[:var_ref, [:@kw, "nil", [1, 9]]]], nil, nil, nil]]]]
#
def Ripper.sexp(src, filename = '-', lineno = 1)
builder = SexpBuilderPP.new(src, filename, lineno)
sexp = builder.parse
sexp unless builder.error?
end
# [EXPERIMENTAL]
# Parses +src+ and create S-exp tree.
# This method is mainly for developer use.
#
# require 'ripper'
# require 'pp'
#
# pp Ripper.sexp_raw("def m(a) nil end")
# #=> [:program,
# [:stmts_add,
# [:stmts_new],
# [:def,
# [:@ident, "m", [1, 4]],
# [:paren, [:params, [[:@ident, "a", [1, 6]]], nil, nil, nil]],
# [:bodystmt,
# [:stmts_add, [:stmts_new], [:var_ref, [:@kw, "nil", [1, 9]]]],
# nil,
# nil,
# nil]]]]
#
def Ripper.sexp_raw(src, filename = '-', lineno = 1)
builder = SexpBuilder.new(src, filename, lineno)
sexp = builder.parse
sexp unless builder.error?
end
class SexpBuilder < ::Ripper #:nodoc:
private
def dedent_element(e, width)
if (n = dedent_string(e[1], width)) > 0
e[2][1] += n
end
e
end
def on_heredoc_dedent(val, width)
sub = proc do |cont|
cont.map! do |e|
if Array === e
case e[0]
when :@tstring_content
e = dedent_element(e, width)
when /_add\z/
e[1] = sub[e[1]]
end
elsif String === e
dedent_string(e, width)
end
e
end
end
sub[val]
val
end
events = private_instance_methods(false).grep(/\Aon_/) {$'.to_sym}
(PARSER_EVENTS - events).each do |event|
module_eval(<<-End, __FILE__, __LINE__ + 1)
def on_#{event}(*args)
args.unshift :#{event}
args
end
End
end
SCANNER_EVENTS.each do |event|
module_eval(<<-End, __FILE__, __LINE__ + 1)
def on_#{event}(tok)
[:@#{event}, tok, [lineno(), column()]]
end
End
end
end
class SexpBuilderPP < SexpBuilder #:nodoc:
private
def on_heredoc_dedent(val, width)
val.map! do |e|
next e if Symbol === e and /_content\z/ =~ e
if Array === e and e[0] == :@tstring_content
e = dedent_element(e, width)
elsif String === e
dedent_string(e, width)
end
e
end
val
end
def _dispatch_event_new
[]
end
def _dispatch_event_push(list, item)
list.push item
list
end
PARSER_EVENT_TABLE.each do |event, arity|
if /_new\z/ =~ event and arity == 0
alias_method "on_#{event}", :_dispatch_event_new
elsif /_add\z/ =~ event
alias_method "on_#{event}", :_dispatch_event_push
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/securerandom.rb
|
# -*- coding: us-ascii -*-
# frozen_string_literal: true
begin
require 'openssl'
rescue LoadError
end
# == Secure random number generator interface.
#
# This library is an interface to secure random number generators which are
# suitable for generating session keys in HTTP cookies, etc.
#
# You can use this library in your application by requiring it:
#
# require 'securerandom'
#
# It supports the following secure random number generators:
#
# * openssl
# * /dev/urandom
# * Win32
#
# === Examples
#
# Generate random hexadecimal strings:
#
# require 'securerandom'
#
# p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
# p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
# p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
#
# Generate random base64 strings:
#
# p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
# p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
# p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
#
# Generate random binary strings:
#
# p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
# p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
#
# Generate UUIDs:
#
# p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
# p SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
#
module SecureRandom
if defined? OpenSSL::Random
def self.gen_random(n)
@pid = 0 unless defined?(@pid)
pid = $$
unless @pid == pid
now = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)
ary = [now, @pid, pid]
OpenSSL::Random.random_add(ary.join("").to_s, 0.0)
seed = Random.raw_seed(16)
if (seed)
OpenSSL::Random.random_add(seed, 16)
end
@pid = pid
end
return OpenSSL::Random.random_bytes(n)
end
else
def self.gen_random(n)
ret = Random.raw_seed(n)
unless ret
raise NotImplementedError, "No random device"
end
unless ret.length == n
raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
end
ret
end
end
end
module Random::Formatter
# SecureRandom.random_bytes generates a random binary string.
#
# The argument _n_ specifies the length of the result string.
#
# If _n_ is not specified or is nil, 16 is assumed.
# It may be larger in future.
#
# The result may contain any byte: "\x00" - "\xff".
#
# p SecureRandom.random_bytes #=> "\xD8\\\xE0\xF4\r\xB2\xFC*WM\xFF\x83\x18\xF45\xB6"
# p SecureRandom.random_bytes #=> "m\xDC\xFC/\a\x00Uf\xB2\xB2P\xBD\xFF6S\x97"
#
# If a secure random number generator is not available,
# +NotImplementedError+ is raised.
def random_bytes(n=nil)
n = n ? n.to_int : 16
gen_random(n)
end
# SecureRandom.hex generates a random hexadecimal string.
#
# The argument _n_ specifies the length, in bytes, of the random number to be generated.
# The length of the resulting hexadecimal string is twice of _n_.
#
# If _n_ is not specified or is nil, 16 is assumed.
# It may be larger in the future.
#
# The result may contain 0-9 and a-f.
#
# p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
# p SecureRandom.hex #=> "91dc3bfb4de5b11d029d376634589b61"
#
# If a secure random number generator is not available,
# +NotImplementedError+ is raised.
def hex(n=nil)
random_bytes(n).unpack("H*")[0]
end
# SecureRandom.base64 generates a random base64 string.
#
# The argument _n_ specifies the length, in bytes, of the random number
# to be generated. The length of the result string is about 4/3 of _n_.
#
# If _n_ is not specified or is nil, 16 is assumed.
# It may be larger in the future.
#
# The result may contain A-Z, a-z, 0-9, "+", "/" and "=".
#
# p SecureRandom.base64 #=> "/2BuBuLf3+WfSKyQbRcc/A=="
# p SecureRandom.base64 #=> "6BbW0pxO0YENxn38HMUbcQ=="
#
# If a secure random number generator is not available,
# +NotImplementedError+ is raised.
#
# See RFC 3548 for the definition of base64.
def base64(n=nil)
[random_bytes(n)].pack("m*").delete("\n")
end
# SecureRandom.urlsafe_base64 generates a random URL-safe base64 string.
#
# The argument _n_ specifies the length, in bytes, of the random number
# to be generated. The length of the result string is about 4/3 of _n_.
#
# If _n_ is not specified or is nil, 16 is assumed.
# It may be larger in the future.
#
# The boolean argument _padding_ specifies the padding.
# If it is false or nil, padding is not generated.
# Otherwise padding is generated.
# By default, padding is not generated because "=" may be used as a URL delimiter.
#
# The result may contain A-Z, a-z, 0-9, "-" and "_".
# "=" is also used if _padding_ is true.
#
# p SecureRandom.urlsafe_base64 #=> "b4GOKm4pOYU_-BOXcrUGDg"
# p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
#
# p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
# p SecureRandom.urlsafe_base64(nil, true) #=> "-M8rLhr7JEpJlqFGUMmOxg=="
#
# If a secure random number generator is not available,
# +NotImplementedError+ is raised.
#
# See RFC 3548 for the definition of URL-safe base64.
def urlsafe_base64(n=nil, padding=false)
s = [random_bytes(n)].pack("m*")
s.delete!("\n")
s.tr!("+/", "-_")
s.delete!("=") unless padding
s
end
=begin
# SecureRandom.random_number generates a random number.
#
# If a positive integer is given as _n_,
# +SecureRandom.random_number+ returns an integer, such that:
# +0 <= SecureRandom.random_number(n) < n+.
#
# p SecureRandom.random_number(100) #=> 15
# p SecureRandom.random_number(100) #=> 88
#
# If 0 is given or an argument is not given,
# +SecureRandom.random_number+ returns a float, such that:
# +0.0 <= SecureRandom.random_number() < 1.0+.
#
# p SecureRandom.random_number #=> 0.596506046187744
# p SecureRandom.random_number #=> 0.350621695741409
#
def random_number(n=0)
if 0 < n
if defined? OpenSSL::BN
OpenSSL::BN.rand_range(n).to_i
else
hex = n.to_s(16)
hex = '0' + hex if (hex.length & 1) == 1
bin = [hex].pack("H*")
mask = bin[0].ord
mask |= mask >> 1
mask |= mask >> 2
mask |= mask >> 4
begin
rnd = random_bytes(bin.length)
rnd[0] = (rnd[0].ord & mask).chr
end until rnd < bin
rnd.unpack("H*")[0].hex
end
else
# assumption: Float::MANT_DIG <= 64
if defined? OpenSSL::BN
i64 = OpenSSL::BN.rand(64, -1).to_i
else
i64 = random_bytes(8).unpack("Q")[0]
end
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
end
end
=end
# SecureRandom.uuid generates a random v4 UUID (Universally Unique IDentifier).
#
# p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
# p SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
# p SecureRandom.uuid #=> "62936e70-1815-439b-bf89-8492855a7e6b"
#
# The version 4 UUID is purely random (except the version).
# It doesn't contain meaningful information such as MAC addresses, timestamps, etc.
#
# The result contains 122 random bits (15.25 random bytes).
#
# See RFC 4122 for details of UUID.
#
def uuid
ary = random_bytes(16).unpack("NnnnnN")
ary[2] = (ary[2] & 0x0fff) | 0x4000
ary[3] = (ary[3] & 0x3fff) | 0x8000
"%08x-%04x-%04x-%04x-%04x%08x" % ary
end
private
def gen_random(n)
self.bytes(n)
end
end
SecureRandom.extend(Random::Formatter)
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/sff/discover.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/rspec_integration.rb
|
# :stopdoc:
#
# One useful feature of log messages in your code is that they provide a
# convenient instrumentation point for testing. Through log messages you can
# confirm that internal methods were called or that certain code paths were
# executed. This example demonstrates how to capture log output during testing
# for later analysis.
#
# The Logging framework provides an RSpec helper that will direct log output
# to a StringIO appender. Log lines can be read from this IO destination
# during tests.
#
require 'rspec'
require 'logging'
require 'rspec/logging_helper'
# Configure RSpec to capture log messages for each test. The output from the
# logs will be stored in the @log_output variable. It is a StringIO instance.
RSpec.configure do |config|
include RSpec::LoggingHelper
config.capture_log_messages
end
# Now within your specs you can check that various log events were generated.
describe 'SuperLogger' do
it 'should be able to read a log message' do
logger = Logging.logger['SuperLogger']
logger.debug 'foo bar'
logger.warn 'just a little warning'
@log_output.readline.should be == 'DEBUG SuperLogger: foo bar'
@log_output.readline.should be == 'WARN SuperLogger: just a little warning'
end
end
# :startdoc:
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/spec/logging_helper.rb
|
require File.expand_path('../../rspec/logging_helper', __FILE__)
Spec::LoggingHelper = RSpec::LoggingHelper
if defined? Spec::Runner::Configuration
class Spec::Runner::Configuration
include Spec::LoggingHelper
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/psych/test_emitter.rb
|
# -*- coding: utf-8 -*-
# frozen_string_literal: false
require_relative 'helper'
module Psych
class TestEmitter < TestCase
def setup
super
@out = StringIO.new('')
@emitter = Psych::Emitter.new @out
end
def test_line_width
@emitter.line_width = 10
assert_equal 10, @emitter.line_width
end
def test_set_canonical
@emitter.canonical = true
assert_equal true, @emitter.canonical
@emitter.canonical = false
assert_equal false, @emitter.canonical
end
def test_indentation_set
assert_equal 2, @emitter.indentation
@emitter.indentation = 5
assert_equal 5, @emitter.indentation
end
def test_emit_utf_8
@emitter.start_stream Psych::Nodes::Stream::UTF8
@emitter.start_document [], [], false
@emitter.scalar '日本語', nil, nil, false, true, 1
@emitter.end_document true
@emitter.end_stream
assert_match('日本語', @out.string)
end
def test_start_stream_arg_error
assert_raises(TypeError) do
@emitter.start_stream 'asdfasdf'
end
end
def test_start_doc_arg_error
@emitter.start_stream Psych::Nodes::Stream::UTF8
[
[nil, [], false],
[[nil, nil], [], false],
[[], 'foo', false],
[[], ['foo'], false],
[[], [nil,nil], false],
[[1,1], [[nil, "tag:TALOS"]], 0],
].each do |args|
assert_raises(TypeError) do
@emitter.start_document(*args)
end
end
end
def test_scalar_arg_error
@emitter.start_stream Psych::Nodes::Stream::UTF8
@emitter.start_document [], [], false
[
[:foo, nil, nil, false, true, 1],
['foo', Object.new, nil, false, true, 1],
['foo', nil, Object.new, false, true, 1],
['foo', nil, nil, false, true, :foo],
[nil, nil, nil, false, true, 1],
].each do |args|
assert_raises(TypeError) do
@emitter.scalar(*args)
end
end
end
def test_start_sequence_arg_error
@emitter.start_stream Psych::Nodes::Stream::UTF8
@emitter.start_document [], [], false
assert_raises(TypeError) do
@emitter.start_sequence(nil, Object.new, true, 1)
end
assert_raises(TypeError) do
@emitter.start_sequence(nil, nil, true, :foo)
end
end
def test_resizing_tags
tags = []
version = [1,1]
obj = Object.new
obj.instance_variable_set(:@tags, tags)
def obj.to_str
(1..10).map{|x| @tags.push(["AAAA","BBBB"])}
return "x"
end
tags.push([obj, "tag:TALOS"])
@emitter.start_document(version, tags, 0)
assert(true)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/treectrl/layout.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/treectrl/layout.rb
#
# Demo: Layout
#
def demoLayout(t)
t.configure(:showroot=>false, :showrootbutton=>true, :showbuttons=>true,
:showlines=>true, :itemheight=>0, :selectmode=>:browse)
if $HasColumnCreate
t.column_create(:text=>'Layout')
else
t.column_configure(0, :text=>'Layout')
end
t.element_create('e1', :rect, :width=>30, :height=>30, :fill=>'gray20')
t.element_create('e2', :rect, :width=>30, :height=>30, :fill=>'gray40',
:outline=>'blue', :outlinewidth=>3)
t.element_create('e3', :rect, :fill=>'gray60')
t.element_create('e4', :rect, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'], 'gray80', []
])
t.element_create('e5', :rect, :fill=>'{sky blue}', :width=>20, :height=>20)
t.element_create('e6', :rect, :fill=>'{sea green}', :width=>30, :height=>16)
t.element_create('e7', :rect, :fill=>'{sky blue}', :width=>30, :height=>16)
t.element_create('e8', :rect, :fill=>'gray70', :height=>1)
s = t.style_create('s1')
t.style_elements(s, ['e4', 'e3', 'e1', 'e2', 'e5', 'e6', 'e7'])
t.style_layout(s, 'e1', :padx=>[28, 4], :pady=>4)
t.style_layout(s, 'e2', :expand=>:es, :padx=>[0, 38])
t.style_layout(s, 'e3', :union=>['e1', 'e2'], :ipadx=>4, :ipady=>4, :pady=>2)
t.style_layout(s, 'e4', :detach=>true, :iexpand=>:es)
t.style_layout(s, 'e5', :detach=>true, :padx=>[2,0], :pady=>2, :iexpand=>:s)
t.style_layout(s, 'e6', :detach=>true, :expand=>:ws,
:padx=>[0,2], :pady=>[2,0])
t.style_layout(s, 'e7', :detach=>true, :expand=>:wn,
:padx=>[0,2], :pady=>[0,2])
if $Version_1_1_OrLater
i = t.item_create(:button=>true)
else
i = t.item_create
t.item_hasbutton(i, true)
end
t.item_style_set(i, 0, s)
t.item_lastchild(:root, i)
parent = i
i = t.item_create()
unless $Version_1_1_OrLater
t.item_hasbutton(i, false)
end
t.item_style_set(i, 0, s)
t.item_lastchild(parent, i)
###
s = t.style_create('s2')
t.style_elements(s, ['e4', 'e3', 'e1'])
t.style_layout(s, 'e1', :padx=>8, :pady=>8, :iexpand=>:e)
t.style_layout(s, 'e3', :union=>['e1'], :ipadx=>[20,4], :ipady=>[4,12])
t.style_layout(s, 'e4', :detach=>true, :iexpand=>:es)
if $Version_1_1_OrLater
i = t.item_create(:button=>true)
else
i = t.item_create
t.item_hasbutton(i, true)
end
t.item_style_set(i, 0, s)
t.item_lastchild(:root, i)
i2 = t.item_create()
unless $Version_1_1_OrLater
t.item_hasbutton(i2, false)
end
t.item_style_set(i2, 0, s)
t.item_lastchild(i, i2)
###
s = t.style_create('s3')
t.style_elements(s, ['e4', 'e3', 'e1', 'e5', 'e6'])
t.style_layout(s, 'e4', :union=>['e1', 'e6'], :ipadx=>8, :ipady=>[8,0])
t.style_layout(s, 'e3', :union=>['e1', 'e5'], :ipadx=>4, :ipady=>4)
t.style_layout(s, 'e5', :ipady=>[0,20])
if $Version_1_1_OrLater
i = t.item_create(:button=>true)
else
i = t.item_create
t.item_hasbutton(i, true)
end
t.item_style_set(i, 0, s)
t.item_lastchild(:root, i)
i2 = t.item_create()
unless $Version_1_1_OrLater
t.item_hasbutton(i2, false)
end
t.item_style_set(i2, 0, s)
t.item_lastchild(i, i2)
###
t.element_create('eb', :border, :background=>@SystemButtonFace,
:relief=>[:sunken, ['selected'], :raised, []],
:thickness=>2, :filled=>true)
t.element_create('et', :text)
text = "Here is a text element surrounded by a border element.\nResize the column to watch me wrap."
s = t.style_create('e4')
t.style_elements(s, ['eb', 'et'])
t.style_layout(s, 'eb', :union=>['et'], :ipadx=>2, :ipady=>2)
t.style_layout(s, 'et', :squeeze=>:x)
if $Version_1_1_OrLater
i = t.item_create(:button=>true)
else
i = t.item_create
t.item_hasbutton(i, true)
end
t.item_style_set(i, 0, s)
t.item_text(i, 0, text)
t.item_lastchild(:root, i)
parent = i
i = t.item_create()
unless $Version_1_1_OrLater
t.item_hasbutton(i, false)
end
t.item_style_set(i, 0, s)
t.item_text(i, 0, text)
t.item_lastchild(parent, i)
###
styleNum = 5
[
[:horizontal, [:s, :ns, :n]],
[:vertical, [:e, :we, :w]]
].each{|orient, expandList|
expandList.each{|expand|
s = t.style_create("s#{styleNum}", :orient=>orient)
t.style_elements(s, ['e4', 'e8', 'e2', 'e5', 'e6'])
t.style_layout(s, 'e4', :detach=>true, :iexpand=>:es)
t.style_layout(s, 'e8', :detach=>true, :expand=>:n, :iexpand=>:e)
t.style_layout(s, 'e2', :expand=>expand)
t.style_layout(s, 'e5', :expand=>expand)
t.style_layout(s, 'e6', :expand=>expand)
styleNum += 1
i = t.item_create()
t.item_style_set(i, 0, s)
t.item_lastchild(:root, i)
}
}
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/spec/unit/knife/bootstrap_windows_winrm_spec.rb
|
#
# Author:: <NAME>(<<EMAIL>>)
# Copyright:: Copyright (c) 2014-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'spec_helper'
require 'winrm/output'
Chef::Knife::Winrm.load_deps
describe Chef::Knife::BootstrapWindowsWinrm do
before do
Chef::Config.reset
bootstrap.config[:run_list] = []
allow(bootstrap).to receive(:validate_options!).and_return(nil)
allow(bootstrap).to receive(:sleep).and_return(10)
allow(Chef::Knife::WinrmSession).to receive(:new).and_return(session)
allow(File).to receive(:exist?).with(anything).and_call_original
allow(File).to receive(:exist?).with(File.expand_path(Chef::Config[:validation_key])).and_return(true)
end
after do
allow(bootstrap).to receive(:sleep).and_return(10)
end
let(:session_opts) do
{
user: "Administrator",
password: "<PASSWORD>",
port: "5986",
transport: :ssl,
host: "localhost"
}
end
let(:bootstrap) { Chef::Knife::BootstrapWindowsWinrm.new(['winrm', '-d', 'windows-chef-client-msi', '-x', session_opts[:user], '-P', session_opts[:password], session_opts[:host]]) }
let(:session) { Chef::Knife::WinrmSession.new(session_opts) }
let(:arch_session_result) {
o = WinRM::Output.new
o[:data] << {stdout: "X86\r\n"}
o
}
let(:arch_session_results) { [arch_session_result] }
let(:initial_fail_count) { 4 }
context "knife secret-file && knife secret options are passed" do
before do
Chef::Config.reset
Chef::Config[:knife][:encrypted_data_bag_secret_file] = "/tmp/encrypted_data_bag_secret"
Chef::Config[:knife][:encrypted_data_bag_secret] = "data_bag_secret_key_passed_under_knife_secret_option"
end
it "gives preference to secret key passed under knife's secret-file option" do
allow(Chef::EncryptedDataBagItem).to receive(:load_secret).with(
Chef::Config[:knife][:encrypted_data_bag_secret_file]).
and_return("data_bag_secret_key_passed_under_knife_secret_file_option")
expect(bootstrap.load_correct_secret).to eq(
"data_bag_secret_key_passed_under_knife_secret_file_option")
end
end
context "cli secret-file && cli secret options are passed" do
before do
Chef::Config.reset
bootstrap.config[:encrypted_data_bag_secret_file] = "/tmp/encrypted_data_bag_secret"
bootstrap.config[:encrypted_data_bag_secret] = "data_bag_secret_key_passed_under_cli_secret_option"
end
it "gives preference to secret key passed under cli's secret-file option" do
allow(Chef::EncryptedDataBagItem).to receive(:load_secret).with(
bootstrap.config[:encrypted_data_bag_secret_file]).
and_return("data_bag_secret_key_passed_under_cli_secret_file_option")
expect(bootstrap.load_correct_secret).to eq(
"data_bag_secret_key_passed_under_cli_secret_file_option")
end
end
context "knife secret-file, knife secret, cli secret-file && cli secret options are passed" do
before do
Chef::Config.reset
Chef::Config[:knife][:encrypted_data_bag_secret_file] = "/tmp/knife_encrypted_data_bag_secret"
Chef::Config[:knife][:encrypted_data_bag_secret] = "data_bag_secret_key_passed_under_knife_secret_option"
bootstrap.config[:encrypted_data_bag_secret_file] = "/tmp/cli_encrypted_data_bag_secret"
bootstrap.config[:encrypted_data_bag_secret] = "data_bag_secret_key_passed_under_cli_secret_option"
end
it "gives preference to secret key passed under cli's secret-file option" do
allow(Chef::EncryptedDataBagItem).to receive(:load_secret).with(
Chef::Config[:knife][:encrypted_data_bag_secret_file]).
and_return("data_bag_secret_key_passed_under_knife_secret_file_option")
allow(Chef::EncryptedDataBagItem).to receive(:load_secret).with(
bootstrap.config[:encrypted_data_bag_secret_file]).
and_return("data_bag_secret_key_passed_under_cli_secret_file_option")
expect(bootstrap.load_correct_secret).to eq(
"data_bag_secret_key_passed_under_cli_secret_file_option")
end
end
context "knife secret-file && cli secret options are passed" do
before do
Chef::Config.reset
Chef::Config[:knife][:encrypted_data_bag_secret_file] = "/tmp/encrypted_data_bag_secret"
bootstrap.config[:encrypted_data_bag_secret] = "data_bag_secret_key_passed_under_cli_secret_option"
end
it "gives preference to secret key passed under cli's secret option" do
allow(Chef::EncryptedDataBagItem).to receive(:load_secret).with(
Chef::Config[:knife][:encrypted_data_bag_secret_file]).
and_return("data_bag_secret_key_passed_under_knife_secret_file_option")
expect(bootstrap.load_correct_secret).to eq(
"data_bag_secret_key_passed_under_cli_secret_option")
end
end
context "knife secret && cli secret-file options are passed" do
before do
Chef::Config.reset
Chef::Config[:knife][:encrypted_data_bag_secret] = "data_bag_secret_key_passed_under_knife_secret_option"
bootstrap.config[:encrypted_data_bag_secret_file] = "/tmp/encrypted_data_bag_secret"
end
it "gives preference to secret key passed under cli's secret-file option" do
allow(Chef::EncryptedDataBagItem).to receive(:load_secret).with(
bootstrap.config[:encrypted_data_bag_secret_file]).
and_return("data_bag_secret_key_passed_under_cli_secret_file_option")
expect(bootstrap.load_correct_secret).to eq(
"data_bag_secret_key_passed_under_cli_secret_file_option")
end
end
context "cli secret-file option is passed" do
before do
Chef::Config.reset
bootstrap.config[:encrypted_data_bag_secret_file] = "/tmp/encrypted_data_bag_secret"
end
it "takes the secret key passed under cli's secret-file option" do
allow(Chef::EncryptedDataBagItem).to receive(:load_secret).with(
bootstrap.config[:encrypted_data_bag_secret_file]).
and_return("data_bag_secret_key_passed_under_cli_secret_file_option")
expect(bootstrap.load_correct_secret).to eq(
"data_bag_secret_key_passed_under_cli_secret_file_option")
end
end
it 'should raise an error if the relay_command returns an unknown response' do
allow(session).to receive(:exit_code).and_return(500)
allow(bootstrap).to receive(:wait_for_remote_response)
allow(session).to receive(:relay_command).and_return(WinRM::Output.new)
allow(bootstrap.ui).to receive(:info)
expect {
bootstrap.run
}.to raise_error(/Response to 'echo %PROCESSOR_ARCHITECTURE%' command was invalid:/)
end
it 'should pass exit code from failed winrm call' do
allow(session).to receive(:exit_code).and_return(500)
allow(bootstrap).to receive(:wait_for_remote_response)
allow(bootstrap).to receive(:create_bootstrap_bat_command)
allow(session).to receive(:relay_command).and_return(arch_session_result)
allow(bootstrap.ui).to receive(:info)
expect {
bootstrap.run_with_pretty_exceptions
}.to raise_error(SystemExit) { |e|
expect(e.status).to eq(500)
}
end
it 'should retry if a 401 is received from WinRM' do
call_result_sequence = Array.new(initial_fail_count) {lambda {raise WinRM::WinRMHTTPTransportError.new('', '401')}}
call_result_sequence.push(0)
allow(bootstrap).to receive(:run_command).and_return(*call_result_sequence)
allow(bootstrap).to receive(:print)
allow(bootstrap.ui).to receive(:info)
expect(bootstrap).to receive(:run_command).exactly(call_result_sequence.length).times
bootstrap.send(:wait_for_remote_response, 2)
end
it 'should retry if something other than a 401 is received from WinRM' do
call_result_sequence = Array.new(initial_fail_count) {lambda {raise WinRM::WinRMHTTPTransportError.new('', '500')}}
call_result_sequence.push(0)
allow(bootstrap).to receive(:run_command).and_return(*call_result_sequence)
allow(bootstrap).to receive(:print)
allow(bootstrap.ui).to receive(:info)
expect(bootstrap).to receive(:run_command).exactly(call_result_sequence.length).times
bootstrap.send(:wait_for_remote_response, 2)
end
it 'should keep retrying at 10s intervals if the timeout in minutes has not elapsed' do
call_result_sequence = Array.new(initial_fail_count) {lambda {raise WinRM::WinRMHTTPTransportError.new('', '500')}}
call_result_sequence.push(0)
allow(bootstrap).to receive(:run_command).and_return(*call_result_sequence)
allow(bootstrap).to receive(:print)
allow(bootstrap.ui).to receive(:info)
expect(bootstrap).to receive(:run_command).exactly(call_result_sequence.length).times
bootstrap.send(:wait_for_remote_response, 2)
end
it 'should have a wait timeout of 2 minutes by default' do
expect(bootstrap).to receive(:relay_winrm_command).with("echo %PROCESSOR_ARCHITECTURE%").and_return(arch_session_results)
allow(bootstrap).to receive(:run_command).and_raise(WinRM::WinRMHTTPTransportError.new('','500'))
allow(bootstrap).to receive(:create_bootstrap_bat_command).and_raise(SystemExit)
expect(bootstrap).to receive(:wait_for_remote_response).with(2)
allow(bootstrap).to receive(:validate_name_args!).and_return(nil)
allow(bootstrap.ui).to receive(:info)
bootstrap.config[:auth_timeout] = bootstrap.options[:auth_timeout][:default]
expect { bootstrap.bootstrap }.to raise_error(SystemExit)
end
it 'should not a wait for timeout on Errno::ECONNREFUSED' do
allow(bootstrap).to receive(:run_command).and_raise(Errno::ECONNREFUSED.new)
allow(bootstrap.ui).to receive(:info)
bootstrap.config[:auth_timeout] = bootstrap.options[:auth_timeout][:default]
expect(bootstrap.ui).to receive(:error).with("Connection refused connecting to localhost:5985.")
# wait_for_remote_response is protected method, So define singleton test method to call it.
bootstrap.define_singleton_method(:test_wait_for_remote_response){wait_for_remote_response(bootstrap.options[:auth_timeout][:default])}
expect { bootstrap.test_wait_for_remote_response }.to raise_error(Errno::ECONNREFUSED)
end
it 'should stop retrying if more than 2 minutes has elapsed' do
times = [ Time.new(2014, 4, 1, 22, 25), Time.new(2014, 4, 1, 22, 51), Time.new(2014, 4, 1, 22, 28) ]
allow(Time).to receive(:now).and_return(*times)
run_command_result = lambda {raise WinRM::WinRMHTTPTransportError, '401'}
allow(bootstrap).to receive(:validate_name_args!).and_return(nil)
allow(bootstrap).to receive(:run_command).and_return(run_command_result)
allow(bootstrap).to receive(:print)
allow(bootstrap.ui).to receive(:info)
allow(bootstrap.ui).to receive(:error)
expect(bootstrap).to receive(:run_command).exactly(1).times
bootstrap.config[:auth_timeout] = bootstrap.options[:auth_timeout][:default]
expect { bootstrap.bootstrap }.to raise_error /Command execution failed./
end
it 'successfully bootstraps' do
allow(bootstrap).to receive(:wait_for_remote_response)
expect(bootstrap).to receive(:relay_winrm_command).with("echo %PROCESSOR_ARCHITECTURE%").and_return(arch_session_results)
allow(bootstrap).to receive(:create_bootstrap_bat_command)
allow(bootstrap).to receive(:run_command).and_return(0)
expect(bootstrap.bootstrap).to eq(0)
expect(Chef::Config[:knife][:architecture]).to eq(:i686)
end
context "when the target node is 64 bit" do
let(:arch_session_result) {
o = WinRM::Output.new
o[:data] << {stdout: "AMD64\r\n"}
o
}
it 'successfully bootstraps' do
allow(bootstrap).to receive(:wait_for_remote_response)
expect(bootstrap).to receive(:relay_winrm_command).with("echo %PROCESSOR_ARCHITECTURE%").and_return(arch_session_results)
allow(bootstrap).to receive(:create_bootstrap_bat_command)
allow(bootstrap).to receive(:run_command).and_return(0)
expect(bootstrap.bootstrap).to eq(0)
expect(Chef::Config[:knife][:architecture]).to eq(:x86_64)
end
end
context "when validation_key is not present" do
context "using chef 11", :chef_lt_12_only do
before do
allow(File).to receive(:exist?).with(File.expand_path(Chef::Config[:validation_key])).and_return(false)
end
it 'raises an exception if validation_key is not present in chef 11' do
expect(bootstrap.ui).to receive(:error)
expect { bootstrap.bootstrap }.to raise_error(SystemExit)
end
end
context "using chef 12", :chef_gte_12_only do
before do
allow(File).to receive(:exist?).with(File.expand_path(Chef::Config[:validation_key])).and_return(false)
bootstrap.client_builder = instance_double("Chef::Knife::Bootstrap::ClientBuilder", :run => nil, :client_path => nil)
Chef::Config[:knife] = {:chef_node_name => 'foo.example.com'}
end
it 'raises an exception if winrm_authentication_protocol is basic and transport is plaintext' do
Chef::Config[:knife] = {:winrm_authentication_protocol => 'basic', :winrm_transport => 'plaintext', :chef_node_name => 'foo.example.com'}
expect(bootstrap.ui).to receive(:error)
expect { bootstrap.run }.to raise_error(SystemExit)
end
it 'raises an exception if chef_node_name is not present ' do
Chef::Config[:knife] = {:chef_node_name => nil}
expect(bootstrap.client_builder).not_to receive(:run)
expect(bootstrap.client_builder).not_to receive(:client_path)
expect(bootstrap.ui).to receive(:error)
expect { bootstrap.bootstrap }.to raise_error(SystemExit)
end
end
end
context "when doing chef vault", :chef_gte_12_only do
let(:vault_handler) { double('vault_handler', :doing_chef_vault? => true) }
let(:node_name) { 'foo.example.com' }
before do
allow(bootstrap).to receive(:wait_for_remote_response)
expect(bootstrap).to receive(:relay_winrm_command).with("echo %PROCESSOR_ARCHITECTURE%").and_return(arch_session_results)
allow(bootstrap).to receive(:create_bootstrap_bat_command)
allow(bootstrap).to receive(:run_command).and_return(0)
bootstrap.config[:chef_node_name] = node_name
bootstrap.chef_vault_handler = vault_handler
end
context "builder does not respond to client" do
before do
bootstrap.client_builder = instance_double("Chef::Knife::Bootstrap::ClientBuilder", :run => nil, :client_path => nil)
end
it "passes a node search query to the handler" do
expect(vault_handler).to receive(:run).with(node_name: node_name)
bootstrap.bootstrap
end
end
context "builder responds to client" do
let(:client) { Chef::ApiClient.new }
before do
bootstrap.client_builder = double("Chef::Knife::Bootstrap::ClientBuilder", :run => nil, :client_path => nil, :client => client)
end
it "passes a node search query to the handler" do
expect(vault_handler).to receive(:run).with(client)
bootstrap.bootstrap
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/evaluation/dictionary_generator.rb
|
<reponame>arnab0073/idea
require 'open-uri'
require 'cgi'
require 'json'
per_page = 500
base_url = "https://simple.wiktionary.org/w/api.php?action=query&aplimit=#{per_page}&list=allpages&format=json"
filename = "evaluation/dictionary.yml"
count = nil
apfrom = ""
num = 0
titles = []
begin
url = base_url + "&apfrom=#{apfrom}"
puts "downloading page %2d: #{url}" % num
body = open(url).read
json = JSON.load(body)
count = json["query"]["allpages"].size
apfrom = CGI.escape(json["query"]["allpages"].last['title']) if count > 0
titles += json["query"]["allpages"].map {|hash| hash["title"] }
num += 1
end while count == per_page
require 'yaml'
File.open(filename, 'w') do |file|
file.write(titles.uniq.to_yaml)
end
puts "
Number of titles: #{titles.uniq.size}
Dictionary saved: #{filename}
"
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/java_spec.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/java_spec.rb
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper.rb')
describe Ohai::System, "plugin java (Java5 Client VM)" do
before(:each) do
@ohai = Ohai::System.new
@ohai.stub!(:require_plugin).and_return(true)
@ohai[:languages] = Mash.new
@status = 0
@stdout = ""
@stderr = "java version \"1.5.0_16\"\nJava(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284)\nJava HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing)"
@ohai.stub!(:run_command).with({:no_status_check => true, :command => "java -version"}).and_return([@status, @stdout, @stderr])
end
it "should run java -version" do
@ohai.should_receive(:run_command).with({:no_status_check => true, :command => "java -version"}).and_return([0, "", "java version \"1.5.0_16\"\nJava(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284)\nJava HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing)"])
@ohai._require_plugin("java")
end
it "should set java[:version]" do
@ohai._require_plugin("java")
@ohai.languages[:java][:version].should eql("1.5.0_16")
end
it "should set java[:runtime][:name] to runtime name" do
@ohai._require_plugin("java")
@ohai.languages[:java][:runtime][:name].should eql("Java(TM) 2 Runtime Environment, Standard Edition")
end
it "should set java[:runtime][:build] to runtime build" do
@ohai._require_plugin("java")
@ohai.languages[:java][:runtime][:build].should eql("1.5.0_16-b06-284")
end
it "should set java[:hotspot][:name] to hotspot name" do
@ohai._require_plugin("java")
@ohai.languages[:java][:hotspot][:name].should eql("Java HotSpot(TM) Client VM")
end
it "should set java[:hotspot][:build] to hotspot build" do
@ohai._require_plugin("java")
@ohai.languages[:java][:hotspot][:build].should eql("1.5.0_16-133, mixed mode, sharing")
end
it "should not set the languages[:java] tree up if java command fails" do
@status = 1
@stdout = ""
@stderr = "Some error output here"
@ohai.stub!(:run_command).with({:no_status_check => true, :command => "java -version"}).and_return([@status, @stdout, @stderr])
@ohai._require_plugin("java")
@ohai.languages.should_not have_key(:java)
end
end
describe Ohai::System, "plugin java (Java6 Server VM)" do
before(:each) do
@ohai = Ohai::System.new
@ohai.stub!(:require_plugin).and_return(true)
@ohai[:languages] = Mash.new
@status = 0
@stdout = ""
@stderr = "java version \"1.6.0_22\"\nJava(TM) 2 Runtime Environment (build 1.6.0_22-b04)\nJava HotSpot(TM) Server VM (build 17.1-b03, mixed mode)"
@ohai.stub!(:run_command).with({:no_status_check => true, :command => "java -version"}).and_return([@status, @stdout, @stderr])
end
it "should run java -version" do
@ohai.should_receive(:run_command).with({:no_status_check => true, :command => "java -version"}).and_return([0, "", "java version \"1.6.0_22\"\nJava(TM) 2 Runtime Environment (build 1.6.0_22-b04)\nJava HotSpot(TM) Server VM (build 17.1-b03, mixed mode)"])
@ohai._require_plugin("java")
end
it "should set java[:version]" do
@ohai._require_plugin("java")
@ohai.languages[:java][:version].should eql("1.6.0_22")
end
it "should set java[:runtime][:name] to runtime name" do
@ohai._require_plugin("java")
@ohai.languages[:java][:runtime][:name].should eql("Java(TM) 2 Runtime Environment")
end
it "should set java[:runtime][:build] to runtime build" do
@ohai._require_plugin("java")
@ohai.languages[:java][:runtime][:build].should eql("1.6.0_22-b04")
end
it "should set java[:hotspot][:name] to hotspot name" do
@ohai._require_plugin("java")
@ohai.languages[:java][:hotspot][:name].should eql("Java HotSpot(TM) Server VM")
end
it "should set java[:hotspot][:build] to hotspot build" do
@ohai._require_plugin("java")
@ohai.languages[:java][:hotspot][:build].should eql("17.1-b03, mixed mode")
end
it "should not set the languages[:java] tree up if java command fails" do
@status = 1
@stdout = ""
@stderr = "Some error output here"
@ohai.stub!(:run_command).with({:no_status_check => true, :command => "java -version"}).and_return([@status, @stdout, @stderr])
@ohai._require_plugin("java")
@ohai.languages.should_not have_key(:java)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/string.rb
|
<gh_stars>0
module Net
module NTLM
class String < Field
def initialize(opts)
super(opts)
@size = opts[:size]
end
def parse(str, offset=0)
if @active and str.size >= offset + @size
@value = str[offset, @size]
@size
else
0
end
end
def serialize
if @active
@value.to_s
else
""
end
end
def value=(val)
@value = val
@size = @value.nil? ? 0 : @value.size
@active = (@size > 0)
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/vsphere/requests/compute/cloudinit_to_customspec.rb
|
module Fog
module Compute
class Vsphere
class Real
def cloudinit_to_customspec(user_data)
raise ArgumentError, "user_data can't be nil" if user_data.nil?
custom_spec = { 'customization_spec' => Hash.new }
user_data = YAML.load(user_data)
# hostname expects a string, REQUIRED
# netmask expects a string
# dns expects an array
# gateway expects an array
# domain expects a string, REQUIRED
# domainsuffixlist expects an array, REQUIRED
# timezone expects a string, for example Europe/Copenhagen, REQUIRED
custom_spec['hostname'] = user_data['hostname'] if user_data.key?('hostname')
custom_spec['ipsettings'] = { 'ip' => user_data['ip'] } if user_data.key?('ip')
custom_spec['ipsettings']['subnetMask'] = user_data['netmask'] if user_data.key?('netmask')
custom_spec['ipsettings']['dnsServerList'] = user_data['dns'] if user_data.key?('dns')
custom_spec['ipsettings']['gateway'] = user_data['gateway'] if user_data.key?('gateway')
custom_spec['domain'] = user_data['domain'] if user_data.key?('domain')
custom_spec['dnsSuffixList'] = user_data['domainsuffixlist'] if user_data.key?('domainsuffixlist')
custom_spec['time_zone'] = user_data['timezone'] if user_data.key?('timezone')
custom_spec
end
end
class Mock
def cloudinit_to_customspec(user_data)
raise ArgumentError, "user_data can't be nil" if user_data.nil?
custom_spec = { 'customization_spec' => Hash.new }
user_data = YAML.load(user_data)
custom_spec['hostname'] = user_data['hostname'] if user_data.key?('hostname')
custom_spec['ipsettings'] = { 'ip' => user_data['ip'] } if user_data.key?('ip')
custom_spec['ipsettings']['subnetMask'] = user_data['netmask'] if user_data.key?('netmask')
custom_spec['ipsettings']['dnsServerList'] = user_data['dns'] if user_data.key?('dns')
custom_spec['ipsettings']['gateway'] = user_data['gateway'] if user_data.key?('gateway')
custom_spec['domain'] = user_data['domain'] if user_data.key?('domain')
custom_spec['dnsSuffixList'] = user_data['domainsuffixlist'] if user_data.key?('domainsuffixlist')
custom_spec['time_zone'] = user_data['timezone'] if user_data.key?('timezone')
custom_spec
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/-test-/load/dot.dot/extconf.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/-test-/load/dot.dot/extconf.rb
create_makefile("-test-/load/dot.dot/dot.dot")
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/figmemo_sample.rb
|
#!/usr/bin/env ruby
require 'tk'
begin
# try to use Img extension
require 'tkextlib/tkimg'
rescue Exception
# cannot use Img extention --> ignore
end
############################
# scrolled_canvas
class TkScrolledCanvas < TkCanvas
include TkComposite
def initialize_composite(keys={})
@h_scr = TkScrollbar.new(@frame)
@v_scr = TkScrollbar.new(@frame)
@canvas = TkCanvas.new(@frame)
@path = @canvas.path
@canvas.xscrollbar(@h_scr)
@canvas.yscrollbar(@v_scr)
TkGrid.rowconfigure(@frame, 0, :weight=>1, :minsize=>0)
TkGrid.columnconfigure(@frame, 0, :weight=>1, :minsize=>0)
@canvas.grid(:row=>0, :column=>0, :sticky=>'news')
@h_scr.grid(:row=>1, :column=>0, :sticky=>'ew')
@v_scr.grid(:row=>0, :column=>1, :sticky=>'ns')
delegate('DEFAULT', @canvas)
delegate('background', @canvas, @h_scr, @v_scr)
delegate('activebackground', @h_scr, @v_scr)
delegate('troughcolor', @h_scr, @v_scr)
delegate('repeatdelay', @h_scr, @v_scr)
delegate('repeatinterval', @h_scr, @v_scr)
delegate('borderwidth', @frame)
delegate('relief', @frame)
delegate_alias('canvasborderwidth', 'borderwidth', @canvas)
delegate_alias('canvasrelief', 'relief', @canvas)
delegate_alias('scrollbarborderwidth', 'borderwidth', @h_scr, @v_scr)
delegate_alias('scrollbarrelief', 'relief', @h_scr, @v_scr)
configure(keys) unless keys.empty?
end
end
############################
class PhotoCanvas < TkScrolledCanvas
USAGE = <<EOT
--- WHAT IS ---
You can write comments on the loaded image, and save it as a Postscipt
file (original image file is not modified). Each comment is drawn as a
set of an indicator circle, an arrow, and a memo text. See the following
how to write comments.
This can save the list of memo texts to another file. It may useful to
search the saved Postscript file by the comments on them.
This may not support multibyte characters (multibyte texts are broken on
a Postscript file). It depends on features of canvas widgets of Tcl/Tk
libraries linked your Ruby/Tk. If you use Tcl/Tk8.0-jp (Japanized Tcl/Tk),
you can (possibly) get a Japanese Postscript file.
--- BINDINGS ---
* Button-1 : draw comments by following steps
1st - Set center of a indicator circle.
2nd - Set head position of an arrow.
3rd - Set tail position of an arrow, and show an entry box.
Input a memo text and hit 'Enter' key to entry the comment.
* Button-2-drag : scroll the canvas
* Button-3 : when drawing, cancel current drawing
* Double-Button-3 : delete the clicked comment (text, arrow, and circle)
EOT
def initialize(*args)
super(*args)
self.highlightthickness = 0
self.selectborderwidth = 0
@photo = TkPhotoImage.new
@img = TkcImage.new(self, 0, 0, :image=>@photo)
width = self.width
height = self.height
@scr_region = [-width, -height, width, height]
self.scrollregion(@scr_region)
self.xview_moveto(0.25)
self.yview_moveto(0.25)
@col = 'red'
@font = 'Helvetica -12'
@memo_id_num = -1
@memo_id_head = 'memo_'
@memo_id_tag = nil
@overlap_d = 2
@state = TkVariable.new
@border = 2
@selectborder = 1
@delta = @border + @selectborder
@entry = TkEntry.new(self, :relief=>:ridge, :borderwidth=>@border,
:selectborderwidth=>@selectborder,
:highlightthickness=>0)
@entry.bind('Return'){@state.value = 0}
@mode = old_mode = 0
_state0()
bind('2', :x, :y){|x,y| scan_mark(x,y)}
bind('B2-Motion', :x, :y){|x,y| scan_dragto(x,y)}
bind('3'){
next if (old_mode = @mode) == 0
@items.each{|item| item.delete }
_state0()
}
bind('Double-3', :widget, :x, :y){|w, x, y|
next if old_mode != 0
x = w.canvasx(x)
y = w.canvasy(y)
tag = nil
w.find_overlapping(x - @overlap_d, y - @overlap_d,
x + @overlap_d, y + @overlap_d).find{|item|
! (item.tags.find{|name|
if name =~ /^(#{@memo_id_head}\d+)$/
tag = $1
end
}.empty?)
}
w.delete(tag) if tag
}
end
#-----------------------------------
private
def _state0() # init
@mode = 0
@memo_id_num += 1
@memo_id_tag = @memo_id_head + @memo_id_num.to_s
@target = nil
@items = []
@mark = [0, 0]
bind_remove('Motion')
bind('ButtonRelease-1', proc{|x,y| _state1(x,y)}, '%x', '%y')
end
def _state1(x,y) # set center
@mode = 1
@target = TkcOval.new(self,
[canvasx(x), canvasy(y)], [canvasx(x), canvasy(y)],
:outline=>@col, :width=>3, :tags=>[@memo_id_tag])
@items << @target
@mark = [x,y]
bind('Motion', proc{|x,y| _state2(x,y)}, '%x', '%y')
bind('ButtonRelease-1', proc{|x,y| _state3(x,y)}, '%x', '%y')
end
def _state2(x,y) # create circle
@mode = 2
r = Integer(Math.sqrt((x-@mark[0])**2 + (y-@mark[1])**2))
@target.coords([canvasx(@mark[0] - r), canvasy(@mark[1] - r)],
[canvasx(@mark[0] + r), canvasy(@mark[1] + r)])
end
def _state3(x,y) # set line start
@mode = 3
@target = TkcLine.new(self,
[canvasx(x), canvasy(y)], [canvasx(x), canvasy(y)],
:arrow=>:first, :arrowshape=>[10, 14, 5],
:fill=>@col, :tags=>[@memo_id_tag])
@items << @target
@mark = [x, y]
bind('Motion', proc{|x,y| _state4(x,y)}, '%x', '%y')
bind('ButtonRelease-1', proc{|x,y| _state5(x,y)}, '%x', '%y')
end
def _state4(x,y) # create line
@mode = 4
@target.coords([canvasx(@mark[0]), canvasy(@mark[1])],
[canvasx(x), canvasy(y)])
end
def _state5(x,y) # set text
@mode = 5
if x - @mark[0] >= 0
justify = 'left'
dx = - @delta
if y - @mark[1] >= 0
anchor = 'nw'
dy = - @delta
else
anchor = 'sw'
dy = @delta
end
else
justify = 'right'
dx = @delta
if y - @mark[1] >= 0
anchor = 'ne'
dy = - @delta
else
anchor = 'se'
dy = @delta
end
end
bind_remove('Motion')
@entry.value = ''
@entry.configure(:justify=>justify, :font=>@font, :foreground=>@col)
ewin = TkcWindow.new(self, [canvasx(x)+dx, canvasy(y)+dy],
:window=>@entry, :state=>:normal, :anchor=>anchor,
:tags=>[@memo_id_tag])
@entry.focus
@entry.grab
@state.wait
@entry.grab_release
ewin.delete
@target = TkcText.new(self, [canvasx(x), canvasy(y)],
:anchor=>anchor, :justify=>justify,
:fill=>@col, :font=>@font, :text=>@entry.value,
:tags=>[@memo_id_tag])
_state0()
end
#-----------------------------------
public
def load_photo(filename)
@photo.configure(:file=>filename)
end
def modified?
! ((find_withtag('all') - [@img]).empty?)
end
def fig_erase
(find_withtag('all') - [@img]).each{|item| item.delete}
end
def reset_region
width = @photo.width
height = @photo.height
if width > @scr_region[2]
@scr_region[0] = -width
@scr_region[2] = width
end
if height > @scr_region[3]
@scr_region[1] = -height
@scr_region[3] = height
end
self.scrollregion(@scr_region)
self.xview_moveto(0.25)
self.yview_moveto(0.25)
end
def get_texts
ret = []
find_withtag('all').each{|item|
if item.kind_of?(TkcText)
ret << item[:text]
end
}
ret
end
end
############################
# define methods for menu
def open_file(canvas, fname)
if canvas.modified?
ret = Tk.messageBox(:icon=>'warning',:type=>'okcancel',:default=>'cancel',
:message=>'Canvas may be modified. Realy erase? ')
return if ret == 'cancel'
end
filetypes = [
['GIF Files', '.gif'],
['GIF Files', [], 'GIFF'],
['PPM Files', '.ppm'],
['PGM Files', '.pgm']
]
begin
if Tk::Img::package_version != ''
filetypes << ['JPEG Files', ['.jpg', '.jpeg']]
filetypes << ['PNG Files', '.png']
filetypes << ['PostScript Files', '.ps']
filetypes << ['PDF Files', '.pdf']
filetypes << ['Windows Bitmap Files', '.bmp']
filetypes << ['Windows Icon Files', '.ico']
filetypes << ['PCX Files', '.pcx']
filetypes << ['Pixmap Files', '.pixmap']
filetypes << ['SGI Files', '.sgi']
filetypes << ['Sun Raster Files', '.sun']
filetypes << ['TGA Files', '.tga']
filetypes << ['TIFF Files', '.tiff']
filetypes << ['XBM Files', '.xbm']
filetypes << ['XPM Files', '.xpm']
end
rescue
end
filetypes << ['ALL Files', '*']
fpath = Tk.getOpenFile(:filetypes=>filetypes)
return if fpath.empty?
begin
canvas.load_photo(fpath)
rescue => e
Tk.messageBox(:icon=>'error', :type=>'ok',
:message=>"Fail to read '#{fpath}'.\n#{e.message}")
end
canvas.fig_erase
canvas.reset_region
fname.value = fpath
end
# --------------------------------
def save_memo(canvas, fname)
initname = fname.value
if initname != '-'
initname = File.basename(initname, File.extname(initname))
fpath = Tk.getSaveFile(:filetypes=>[ ['Text Files', '.txt'],
['ALL Files', '*'] ],
:initialfile=>initname)
else
fpath = Tk.getSaveFile(:filetypes=>[ ['Text Files', '.txt'],
['ALL Files', '*'] ])
end
return if fpath.empty?
begin
fid = open(fpath, 'w')
rescue => e
Tk.messageBox(:icon=>'error', :type=>'ok',
:message=>"Fail to open '#{fname.value}'.\n#{e.message}")
end
begin
canvas.get_texts.each{|txt|
fid.print(txt, "\n")
}
ensure
fid.close
end
end
# --------------------------------
def ps_print(canvas, fname)
initname = fname.value
if initname != '-'
initname = File.basename(initname, File.extname(initname))
fpath = Tk.getSaveFile(:filetypes=>[ ['Postscript Files', '.ps'],
['ALL Files', '*'] ],
:initialfile=>initname)
else
fpath = Tk.getSaveFile(:filetypes=>[ ['Postscript Files', '.ps'],
['ALL Files', '*'] ])
end
return if fpath.empty?
bbox = canvas.bbox('all')
canvas.postscript(:file=>fpath, :x=>bbox[0], :y=>bbox[1],
:width=>bbox[2] - bbox[0], :height=>bbox[3] - bbox[1])
end
# --------------------------------
def quit(canvas)
ret = Tk.messageBox(:icon=>'warning', :type=>'okcancel',
:default=>'cancel',
:message=>'Realy quit? ')
exit if ret == 'ok'
end
# --------------------------------
# setup root
root = TkRoot.new(:title=>'Fig Memo')
# create canvas frame
canvas = PhotoCanvas.new(root).pack(:fill=>:both, :expand=>true)
usage_frame = TkFrame.new(root, :relief=>:ridge, :borderwidth=>2)
hide_btn = TkButton.new(usage_frame, :text=>'hide usage',
:font=>{:size=>8}, :pady=>1,
:command=>proc{usage_frame.unpack})
hide_btn.pack(:anchor=>'e', :padx=>5)
usage = TkLabel.new(usage_frame, :text=>PhotoCanvas::USAGE,
:font=>'Helvetica 8', :justify=>:left).pack
show_usage = proc{
usage_frame.pack(:before=>canvas, :fill=>:x, :expand=>true)
}
fname = TkVariable.new('-')
f = TkFrame.new(root, :relief=>:sunken, :borderwidth=>1).pack(:fill=>:x)
label = TkLabel.new(f, :textvariable=>fname,
:font=>{:size=>-12, :weight=>:bold},
:anchor=>'w').pack(:side=>:left, :fill=>:x, :padx=>10)
# create menu
mspec = [
[ ['File', 0],
['Show Usage', proc{show_usage.call}, 5],
'---',
['Open Image File', proc{open_file(canvas, fname)}, 0],
['Save Memo Texts', proc{save_memo(canvas, fname)}, 0],
'---',
['Save Postscript', proc{ps_print(canvas, fname)}, 5],
'---',
['Quit', proc{quit(canvas)}, 0]
]
]
root.add_menubar(mspec)
# manage wm_protocol
root.protocol(:WM_DELETE_WINDOW){quit(canvas)}
# show usage
show_usage.call
# --------------------------------
# start eventloop
Tk.mainloop
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/systemu-2.6.5/samples/e.rb
|
#
# any environment vars specified are merged into the child's environment
#
require 'systemu'
env = %q( ruby -r yaml -e" puts ENV[ 'answer' ] " )
status = systemu env, 1=>stdout='', 'env'=>{ 'answer' => 0b101010 }
puts stdout
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/include.rb
|
# frozen_string_literal: false
##
# A Module included in a class with \#include
#
# RDoc::Include.new 'Enumerable', 'comment ...'
class RDoc::Include < RDoc::Mixin
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/appenders/file.rb
|
module Logging::Appenders
# Accessor / Factory for the File appender.
#
def self.file( *args )
fail ArgumentError, '::Logging::Appenders::File needs a name as first argument.' if args.empty?
::Logging::Appenders::File.new(*args)
end
# This class provides an Appender that can write to a File.
#
class File < ::Logging::Appenders::IO
# call-seq:
# File.assert_valid_logfile( filename ) => true
#
# Asserts that the given _filename_ can be used as a log file by ensuring
# that if the file exists it is a regular file and it is writable. If
# the file does not exist, then the directory is checked to see if it is
# writable.
#
# An +ArgumentError+ is raised if any of these assertions fail.
#
def self.assert_valid_logfile( fn )
if ::File.exist?(fn)
if not ::File.file?(fn)
raise ArgumentError, "#{fn} is not a regular file"
elsif not ::File.writable?(fn)
raise ArgumentError, "#{fn} is not writeable"
end
elsif not ::File.writable?(::File.dirname(fn))
raise ArgumentError, "#{::File.dirname(fn)} is not writable"
end
true
end
# call-seq:
# File.new( name, :filename => 'file' )
# File.new( name, :filename => 'file', :truncate => true )
# File.new( name, :filename => 'file', :layout => layout )
#
# Creates a new File Appender that will use the given filename as the
# logging destination. If the file does not already exist it will be
# created. If the :truncate option is set to +true+ then the file will
# be truncated before writing begins; otherwise, log messages will be
# appended to the file.
#
def initialize( name, opts = {} )
@fn = opts.fetch(:filename, name)
raise ArgumentError, 'no filename was given' if @fn.nil?
@fn = ::File.expand_path(@fn)
self.class.assert_valid_logfile(@fn)
@mode = opts.fetch(:truncate, false) ? 'w' : 'a'
self.encoding = opts.fetch(:encoding, self.encoding)
@mode = "#{@mode}:#{self.encoding}" if self.encoding
super(name, ::File.new(@fn, @mode), opts)
end
# Returns the path to the logfile.
#
def filename() @fn.dup end
# Reopen the connection to the underlying logging destination. If the
# connection is currently closed then it will be opened. If the connection
# is currently open then it will be closed and immediately opened.
#
def reopen
@mutex.synchronize {
if defined? @io and @io
flush
@io.close rescue nil
end
@io = ::File.new(@fn, @mode)
}
super
self
end
end # FileAppender
end # Logging::Appenders
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/tabset.rb
|
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
# Create a listbox with two items (one and two)
l = TkListbox.new(:selectmode=>:single, :exportselection=>false).pack
l.insert('end', 'one')
l.insert('end', 'two')
l.selection_set(0)
# Define a proc that knows how to select an item
# from a list given an index from the tabset -command callback.
selectItem = proc{|item|
l.selection_clear(l.curselection)
l.selection_set(item)
l.see(item)
}
# Create a tabset, set its -command to call selectItem
# Add two labels to the tabset (one and two).
ts = Tk::Iwidgets::Tabset.new(:command=>selectItem)
ts.add(:label=>1)
ts.add(:label=>2)
ts.select(0)
ts.pack(:fill=>:x, :expand=>true)
# Define a proc that knows how to select a tab
# given a y pixel coordinate from the list..
selectTab = proc{|y| ts.select(l.nearest(y)) }
# bind button 1 press to the selectTab procedure.
l.bind('ButtonPress-1', proc{|y| selectTab.call(y) }, '%y')
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/test_gem_name_tuple.rb
|
<reponame>arnab0073/idea<gh_stars>1-10
# frozen_string_literal: false
require 'rubygems/test_case'
require 'rubygems/name_tuple'
class TestGemNameTuple < Gem::TestCase
def test_full_name
n = Gem::NameTuple.new "a", Gem::Version.new(0), "ruby"
assert_equal "a-0", n.full_name
n = Gem::NameTuple.new "a", Gem::Version.new(0), nil
assert_equal "a-0", n.full_name
n = Gem::NameTuple.new "a", Gem::Version.new(0), ""
assert_equal "a-0", n.full_name
n = Gem::NameTuple.new "a", Gem::Version.new(0), "other"
assert_equal "a-0-other", n.full_name
end
def test_platform_normalization
n = Gem::NameTuple.new "a", Gem::Version.new(0), "ruby"
assert_equal "ruby", n.platform
n = Gem::NameTuple.new "a", Gem::Version.new(0), nil
assert_equal "ruby", n.platform
n = Gem::NameTuple.new "a", Gem::Version.new(0), ""
assert_equal "ruby", n.platform
end
def test_spec_name
n = Gem::NameTuple.new "a", Gem::Version.new(0), "ruby"
assert_equal "a-0.gemspec", n.spec_name
end
def test_spaceship
a = Gem::NameTuple.new 'a', Gem::Version.new(0), Gem::Platform::RUBY
a_p = Gem::NameTuple.new 'a', Gem::Version.new(0), Gem::Platform.local
assert_equal 1, a_p.<=>(a)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rest-client-1.6.9/lib/restclient/raw_response.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/rest-client-1.6.9/lib/restclient/raw_response.rb<gh_stars>100-1000
module RestClient
# The response from RestClient on a raw request looks like a string, but is
# actually one of these. 99% of the time you're making a rest call all you
# care about is the body, but on the occassion you want to fetch the
# headers you can:
#
# RestClient.get('http://example.com').headers[:content_type]
#
# In addition, if you do not use the response as a string, you can access
# a Tempfile object at res.file, which contains the path to the raw
# downloaded request body.
class RawResponse
include AbstractResponse
attr_reader :file
def initialize tempfile, net_http_res, args
@net_http_res = net_http_res
@args = args
@file = tempfile
end
def to_s
@file.open
@file.read
end
def size
File.size file
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_markup_pre_process.rb
|
# coding: utf-8
# frozen_string_literal: false
require 'rdoc/test_case'
class TestRDocMarkupPreProcess < RDoc::TestCase
def setup
super
@tempfile = Tempfile.new 'test_rdoc_markup_pre_process'
@file_name = File.basename @tempfile.path
@dir = File.dirname @tempfile.path
@pp = RDoc::Markup::PreProcess.new @tempfile.path, [@dir, File.dirname(__FILE__)]
end
def teardown
super
@tempfile.close!
end
def test_class_register
RDoc::Markup::PreProcess.register 'for_test' do raise 'fail' end
assert_equal %w[for_test], RDoc::Markup::PreProcess.registered.keys
end
def test_class_post_process
RDoc::Markup::PreProcess.post_process do end
assert_equal 1, RDoc::Markup::PreProcess.post_processors.length
end
def test_include_file
@tempfile.write <<-INCLUDE
# -*- mode: rdoc; coding: utf-8; fill-column: 74; -*-
Regular expressions (<i>regexp</i>s) are patterns which describe the
contents of a string.
INCLUDE
@tempfile.flush
@tempfile.rewind
content = @pp.include_file @file_name, '', nil
expected = <<-EXPECTED
Regular expressions (<i>regexp</i>s) are patterns which describe the
contents of a string.
EXPECTED
assert_equal expected, content
end
def test_include_file_encoding_incompatible
skip "Encoding not implemented" unless Object.const_defined? :Encoding
@tempfile.write <<-INCLUDE
# -*- mode: rdoc; coding: utf-8; fill-column: 74; -*-
π
INCLUDE
@tempfile.flush
@tempfile.rewind
content = @pp.include_file @file_name, '', Encoding::US_ASCII
expected = "?\n"
assert_equal expected, content
end
def test_include_file_in_other_directory
content = nil
out, err = capture_io do
content = @pp.include_file "test.txt", '', nil
end
assert_empty out
assert_empty err
assert_equal "test file\n", content
end
def test_handle
text = "# :main: M\n"
out = @pp.handle text
assert_same out, text
assert_equal "#\n", text
end
def test_handle_comment
text = "# :main: M\n"
c = comment text
out = @pp.handle c
assert_same out, text
assert_equal "#\n", text
end
def test_handle_markup
c = comment ':markup: rd'
@pp.handle c
assert_equal 'rd', c.format
end
def test_handle_markup_empty
c = comment ':markup:'
@pp.handle c
assert_equal 'rdoc', c.format
end
def test_handle_post_process
cd = RDoc::CodeObject.new
RDoc::Markup::PreProcess.post_process do |text, code_object|
code_object.metadata[:stuff] = text
:junk
end
text = "# a b c\n"
out = @pp.handle text, cd
assert_same out, text
assert_equal "# a b c\n", text
assert_equal "# a b c\n", cd.metadata[:stuff]
end
def test_handle_unregistered
text = "# :x: y\n"
out = @pp.handle text
assert_same out, text
assert_equal "# :x: y\n", text
end
def test_handle_directive_blankline
result = @pp.handle_directive '#', 'arg', 'a, b'
assert_equal "#:arg: a, b\n", result
end
def test_handle_directive_downcase
method = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'ARG', 'a, b', method
assert_equal 'a, b', method.params
end
def test_handle_directive_arg
method = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'arg', 'a, b', method
assert_equal 'a, b', method.params
end
def test_handle_directive_arg_no_context
result = @pp.handle_directive '', 'arg', 'a, b', nil
assert_equal ":arg: a, b\n", result
end
def test_handle_directive_args
method = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'args', 'a, b', method
assert_equal 'a, b', method.params
end
def test_handle_directive_block
result = @pp.handle_directive '', 'x', 'y' do |directive, param|
''
end
assert_empty result
end
def test_handle_directive_block_false
result = @pp.handle_directive '', 'x', 'y' do |directive, param|
false
end
assert_equal ":x: y\n", result
end
def test_handle_directive_block_nil
result = @pp.handle_directive '', 'x', 'y' do |directive, param|
nil
end
assert_equal ":x: y\n", result
end
def test_handle_directive_category
context = RDoc::Context.new
original_section = context.current_section
@pp.handle_directive '', 'category', 'other', context
refute_equal original_section, context.current_section
end
def test_handle_directive_doc
code_object = RDoc::CodeObject.new
code_object.document_self = false
code_object.force_documentation = false
@pp.handle_directive '', 'doc', nil, code_object
assert code_object.document_self
assert code_object.force_documentation
end
def test_handle_directive_doc_no_context
result = @pp.handle_directive '', 'doc', nil
assert_equal "\n", result
end
def test_handle_directive_enddoc
code_object = RDoc::CodeObject.new
@pp.handle_directive '', 'enddoc', nil, code_object
assert code_object.done_documenting
end
def test_handle_directive_include
@tempfile.write 'included'
@tempfile.flush
result = @pp.handle_directive '', 'include', @file_name
assert_equal 'included', result
end
def test_handle_directive_main
@pp.options = RDoc::Options.new
@pp.handle_directive '', 'main', 'M'
assert_equal 'M', @pp.options.main_page
end
def test_handle_directive_notnew
m = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'notnew', nil, m
assert m.dont_rename_initialize
end
def test_handle_directive_not_new
m = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'not_new', nil, m
assert m.dont_rename_initialize
end
def test_handle_directive_not_dash_new
m = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'not-new', nil, m
assert m.dont_rename_initialize
end
def test_handle_directive_nodoc
code_object = RDoc::CodeObject.new
code_object.document_self = true
code_object.document_children = true
@pp.handle_directive '', 'nodoc', nil, code_object
refute code_object.document_self
assert code_object.document_children
end
def test_handle_directive_nodoc_all
code_object = RDoc::CodeObject.new
code_object.document_self = true
code_object.document_children = true
@pp.handle_directive '', 'nodoc', 'all', code_object
refute code_object.document_self
refute code_object.document_children
end
def test_handle_directive_nodoc_no_context
result = @pp.handle_directive '', 'nodoc', nil
assert_equal "\n", result
end
def test_handle_directive_registered
RDoc::Markup::PreProcess.register 'x'
result = @pp.handle_directive '', 'x', 'y'
assert_nil result
result = @pp.handle_directive '', 'x', 'y' do |directive, param|
false
end
assert_equal ":x: y\n", result
result = @pp.handle_directive '', 'x', 'y' do |directive, param|
''
end
assert_equal '', result
end
def test_handle_directive_registered_block
called = nil
RDoc::Markup::PreProcess.register 'x' do |directive, param|
called = [directive, param]
'blah'
end
result = @pp.handle_directive '', 'x', 'y'
assert_equal 'blah', result
assert_equal %w[x y], called
end
def test_handle_directive_registered_code_object
RDoc::Markup::PreProcess.register 'x'
code_object = RDoc::CodeObject.new
@pp.handle_directive '', 'x', 'y', code_object
assert_equal 'y', code_object.metadata['x']
code_object.metadata.clear
result = @pp.handle_directive '', 'x', 'y' do |directive, param|
false
end
assert_equal ":x: y\n", result
assert_empty code_object.metadata
result = @pp.handle_directive '', 'x', 'y' do |directive, param|
''
end
assert_equal '', result
assert_empty code_object.metadata
end
def test_handle_directive_startdoc
code_object = RDoc::CodeObject.new
code_object.stop_doc
code_object.force_documentation = false
@pp.handle_directive '', 'startdoc', nil, code_object
assert code_object.document_self
assert code_object.document_children
assert code_object.force_documentation
end
def test_handle_directive_stopdoc
code_object = RDoc::CodeObject.new
@pp.handle_directive '', 'stopdoc', nil, code_object
refute code_object.document_self
refute code_object.document_children
end
def test_handle_directive_title
@pp.options = RDoc::Options.new
@pp.handle_directive '', 'title', 'T'
assert_equal 'T', @pp.options.title
end
def test_handle_directive_unhandled
code_object = RDoc::CodeObject.new
@pp.handle_directive '', 'x', 'y', code_object
assert_equal 'y', code_object.metadata['x']
code_object.metadata.clear
@pp.handle_directive '', 'x', '', code_object
assert_includes code_object.metadata, 'x'
end
def test_handle_directive_unhandled_block
code_object = RDoc::CodeObject.new
@pp.handle_directive '', 'x', 'y', code_object do
false
end
assert_empty code_object.metadata
@pp.handle_directive '', 'x', 'y', code_object do
nil
end
assert_equal 'y', code_object.metadata['x']
code_object.metadata.clear
@pp.handle_directive '', 'x', 'y', code_object do
''
end
assert_empty code_object.metadata
end
def test_handle_directive_yield
method = RDoc::AnyMethod.new nil, 'm'
method.params = 'index, &block'
@pp.handle_directive '', 'yield', 'item', method
assert_equal 'item', method.block_params
assert_equal 'index', method.params
end
def test_handle_directive_yield_block_param
method = RDoc::AnyMethod.new nil, 'm'
method.params = '&block'
@pp.handle_directive '', 'yield', 'item', method
assert_equal 'item', method.block_params
assert_empty method.params
end
def test_handle_directive_yield_no_context
method = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'yield', 'item', method
assert_equal 'item', method.block_params
end
def test_handle_directive_yields
method = RDoc::AnyMethod.new nil, 'm'
@pp.handle_directive '', 'yields', 'item', method
assert_equal 'item', method.block_params
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/set.rb
|
# frozen_string_literal: false
module Psych
class Set < ::Hash
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/lib/did_you_mean/spell_checkers/name_error_checkers/class_name_checker.rb
|
# -*- frozen-string-literal: true -*-
require 'delegate'
module DidYouMean
class ClassNameChecker
include SpellCheckable
attr_reader :class_name
def initialize(exception)
@class_name, @receiver = exception.name, exception.receiver
end
def candidates
{class_name => class_names}
end
def class_names
scopes.flat_map do |scope|
scope.constants.map do |c|
ClassName.new(c, scope == Object ? "" : "#{scope}::")
end
end
end
def corrections
super.map(&:full_name)
end
def scopes
@scopes ||= @receiver.to_s.split("::").inject([Object]) do |_scopes, scope|
_scopes << _scopes.last.const_get(scope)
end.uniq
end
class ClassName < SimpleDelegator
attr :namespace
def initialize(name, namespace = '')
super(name)
@namespace = namespace
end
def full_name
self.class.new("#{namespace}#{__getobj__}")
end
end
private_constant :ClassName
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/visitors/to_ruby.rb
|
# frozen_string_literal: false
require 'psych/scalar_scanner'
require 'psych/class_loader'
require 'psych/exception'
unless defined?(Regexp::NOENCODING)
Regexp::NOENCODING = 32
end
module Psych
module Visitors
###
# This class walks a YAML AST, converting each node to Ruby
class ToRuby < Psych::Visitors::Visitor
def self.create
class_loader = ClassLoader.new
scanner = ScalarScanner.new class_loader
new(scanner, class_loader)
end
attr_reader :class_loader
def initialize ss, class_loader
super()
@st = {}
@ss = ss
@domain_types = Psych.domain_types
@class_loader = class_loader
end
def accept target
result = super
return result if @domain_types.empty? || !target.tag
key = target.tag.sub(/^[!\/]*/, '').sub(/(,\d+)\//, '\1:')
key = "tag:#{key}" unless key =~ /^(?:tag:|x-private)/
if @domain_types.key? key
value, block = @domain_types[key]
return block.call value, result
end
result
end
def deserialize o
if klass = resolve_class(Psych.load_tags[o.tag])
instance = klass.allocate
if instance.respond_to?(:init_with)
coder = Psych::Coder.new(o.tag)
coder.scalar = o.value
instance.init_with coder
end
return instance
end
return o.value if o.quoted
return @ss.tokenize(o.value) unless o.tag
case o.tag
when '!binary', 'tag:yaml.org,2002:binary'
o.value.unpack('m').first
when /^!(?:str|ruby\/string)(?::(.*))?$/, 'tag:yaml.org,2002:str'
klass = resolve_class($1)
if klass
klass.allocate.replace o.value
else
o.value
end
when '!ruby/object:BigDecimal'
require 'bigdecimal'
class_loader.big_decimal._load o.value
when "!ruby/object:DateTime"
class_loader.date_time
require 'date'
@ss.parse_time(o.value).to_datetime
when '!ruby/encoding'
::Encoding.find o.value
when "!ruby/object:Complex"
class_loader.complex
Complex(o.value)
when "!ruby/object:Rational"
class_loader.rational
Rational(o.value)
when "!ruby/class", "!ruby/module"
resolve_class o.value
when "tag:yaml.org,2002:float", "!float"
Float(@ss.tokenize(o.value))
when "!ruby/regexp"
klass = class_loader.regexp
o.value =~ /^\/(.*)\/([mixn]*)$/m
source = $1
options = 0
lang = nil
($2 || '').split('').each do |option|
case option
when 'x' then options |= Regexp::EXTENDED
when 'i' then options |= Regexp::IGNORECASE
when 'm' then options |= Regexp::MULTILINE
when 'n' then options |= Regexp::NOENCODING
else lang = option
end
end
klass.new(*[source, options, lang].compact)
when "!ruby/range"
klass = class_loader.range
args = o.value.split(/([.]{2,3})/, 2).map { |s|
accept Nodes::Scalar.new(s)
}
args.push(args.delete_at(1) == '...')
klass.new(*args)
when /^!ruby\/sym(bol)?:?(.*)?$/
class_loader.symbolize o.value
else
@ss.tokenize o.value
end
end
private :deserialize
def visit_Psych_Nodes_Scalar o
register o, deserialize(o)
end
def visit_Psych_Nodes_Sequence o
if klass = resolve_class(Psych.load_tags[o.tag])
instance = klass.allocate
if instance.respond_to?(:init_with)
coder = Psych::Coder.new(o.tag)
coder.seq = o.children.map { |c| accept c }
instance.init_with coder
end
return instance
end
case o.tag
when nil
register_empty(o)
when '!omap', 'tag:yaml.org,2002:omap'
map = register(o, Psych::Omap.new)
o.children.each { |a|
map[accept(a.children.first)] = accept a.children.last
}
map
when /^!(?:seq|ruby\/array):(.*)$/
klass = resolve_class($1)
list = register(o, klass.allocate)
o.children.each { |c| list.push accept c }
list
else
register_empty(o)
end
end
def visit_Psych_Nodes_Mapping o
if Psych.load_tags[o.tag]
return revive(resolve_class(Psych.load_tags[o.tag]), o)
end
return revive_hash(register(o, {}), o) unless o.tag
case o.tag
when /^!ruby\/struct:?(.*)?$/
klass = resolve_class($1) if $1
if klass
s = register(o, klass.allocate)
members = {}
struct_members = s.members.map { |x| class_loader.symbolize x }
o.children.each_slice(2) do |k,v|
member = accept(k)
value = accept(v)
if struct_members.include?(class_loader.symbolize(member))
s.send("#{member}=", value)
else
members[member.to_s.sub(/^@/, '')] = value
end
end
init_with(s, members, o)
else
klass = class_loader.struct
members = o.children.map { |c| accept c }
h = Hash[*members]
s = klass.new(*h.map { |k,v|
class_loader.symbolize k
}).new(*h.map { |k,v| v })
register(o, s)
s
end
when /^!ruby\/object:?(.*)?$/
name = $1 || 'Object'
if name == 'Complex'
class_loader.complex
h = Hash[*o.children.map { |c| accept c }]
register o, Complex(h['real'], h['image'])
elsif name == 'Rational'
class_loader.rational
h = Hash[*o.children.map { |c| accept c }]
register o, Rational(h['numerator'], h['denominator'])
elsif name == 'Hash'
revive_hash(register(o, {}), o)
else
obj = revive((resolve_class(name) || class_loader.object), o)
obj
end
when /^!(?:str|ruby\/string)(?::(.*))?$/, 'tag:yaml.org,2002:str'
klass = resolve_class($1)
members = {}
string = nil
o.children.each_slice(2) do |k,v|
key = accept k
value = accept v
if key == 'str'
if klass
string = klass.allocate.replace value
else
string = value
end
register(o, string)
else
members[key] = value
end
end
init_with(string, members.map { |k,v| [k.to_s.sub(/^@/, ''),v] }, o)
when /^!ruby\/array:(.*)$/
klass = resolve_class($1)
list = register(o, klass.allocate)
members = Hash[o.children.map { |c| accept c }.each_slice(2).to_a]
list.replace members['internal']
members['ivars'].each do |ivar, v|
list.instance_variable_set ivar, v
end
list
when '!ruby/range'
klass = class_loader.range
h = Hash[*o.children.map { |c| accept c }]
register o, klass.new(h['begin'], h['end'], h['excl'])
when /^!ruby\/exception:?(.*)?$/
h = Hash[*o.children.map { |c| accept c }]
e = build_exception((resolve_class($1) || class_loader.exception),
h.delete('message'))
init_with(e, h, o)
when '!set', 'tag:yaml.org,2002:set'
set = class_loader.psych_set.new
@st[o.anchor] = set if o.anchor
o.children.each_slice(2) do |k,v|
set[accept(k)] = accept(v)
end
set
when /^!ruby\/hash-with-ivars(?::(.*))?$/
hash = $1 ? resolve_class($1).allocate : {}
register o, hash
o.children.each_slice(2) do |key, value|
case key.value
when 'elements'
revive_hash hash, value
when 'ivars'
value.children.each_slice(2) do |k,v|
hash.instance_variable_set accept(k), accept(v)
end
end
end
hash
when /^!map:(.*)$/, /^!ruby\/hash:(.*)$/
revive_hash register(o, resolve_class($1).allocate), o
when '!omap', 'tag:yaml.org,2002:omap'
map = register(o, class_loader.psych_omap.new)
o.children.each_slice(2) do |l,r|
map[accept(l)] = accept r
end
map
when /^!ruby\/marshalable:(.*)$/
name = $1
klass = resolve_class(name)
obj = register(o, klass.allocate)
if obj.respond_to?(:init_with)
init_with(obj, revive_hash({}, o), o)
elsif obj.respond_to?(:marshal_load)
marshal_data = o.children.map(&method(:accept))
obj.marshal_load(marshal_data)
obj
else
raise ArgumentError, "Cannot deserialize #{name}"
end
else
revive_hash(register(o, {}), o)
end
end
def visit_Psych_Nodes_Document o
accept o.root
end
def visit_Psych_Nodes_Stream o
o.children.map { |c| accept c }
end
def visit_Psych_Nodes_Alias o
@st.fetch(o.anchor) { raise BadAlias, "Unknown alias: #{o.anchor}" }
end
private
def register node, object
@st[node.anchor] = object if node.anchor
object
end
def register_empty object
list = register(object, [])
object.children.each { |c| list.push accept c }
list
end
SHOVEL = '<<'
def revive_hash hash, o
o.children.each_slice(2) { |k,v|
key = accept(k)
val = accept(v)
if key == SHOVEL && k.tag != "tag:yaml.org,2002:str"
case v
when Nodes::Alias, Nodes::Mapping
begin
hash.merge! val
rescue TypeError
hash[key] = val
end
when Nodes::Sequence
begin
h = {}
val.reverse_each do |value|
h.merge! value
end
hash.merge! h
rescue TypeError
hash[key] = val
end
else
hash[key] = val
end
else
hash[key] = val
end
}
hash
end
def merge_key hash, key, val
end
def revive klass, node
s = register(node, klass.allocate)
init_with(s, revive_hash({}, node), node)
end
def init_with o, h, node
c = Psych::Coder.new(node.tag)
c.map = h
if o.respond_to?(:init_with)
o.init_with c
elsif o.respond_to?(:yaml_initialize)
if $VERBOSE
warn "Implementing #{o.class}#yaml_initialize is deprecated, please implement \"init_with(coder)\""
end
o.yaml_initialize c.tag, c.map
else
h.each { |k,v| o.instance_variable_set(:"@#{k}", v) }
end
o
end
# Convert +klassname+ to a Class
def resolve_class klassname
class_loader.load klassname
end
end
class NoAliasRuby < ToRuby
def visit_Psych_Nodes_Alias o
raise BadAlias, "Unknown alias: #{o.anchor}"
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkmultilistframe.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkmultilistframe.rb<gh_stars>1-10
#
# tkmultilistframe.rb : multiple listbox widget on scrollable frame
# by <NAME> (<EMAIL>)
#
require 'tk'
class TkMultiListFrame < TkListbox
include TkComposite
# lbox_height : height of listboxes (pixel)
# title_info : array [ [<title_string>,<init_width>], ... ]
# keys : hash {<option>=><value>, ... }
def initialize_composite(lbox_height, title_info, keys={})
# argument check
if (! title_info.kind_of? Array) or (title_info.size < 2)
raise
end
# mode
@keep_minsize = true
@show_each_hscr = true
@show_win_hscr = true
# init arrays
@base_list = []
@rel_list = []
@title_list = []
@title_cmd = []
@lbox_list = []
@hscr_list = []
# decide total width
@lbox_total = title_info.size
@width_total = 0
title_info.each{|title, width, cmd|
@width_total += width.to_f
@title_cmd << cmd
}
# rel-table of label=>index
@name_index = {}
# size definition
@window_width = @width_total
@sash = 5
@scrbar_width = 15
@scrbar_border = 3
@lbox_border = 1
@title_border = 3
@h_l_thick = 0
# init status
@mode = :title
# virtical scrollbar
=begin
@v_scroll = TkScrollbar.new(@frame, 'highlightthickness'=>@h_l_thick,
'borderwidth'=>@scrbar_border,
'orient'=>'vertical', 'width'=>@scrbar_width)
=end
@v_scroll = TkYScrollbar.new(@frame, 'highlightthickness'=>@h_l_thick,
'borderwidth'=>@scrbar_border,
'width'=>@scrbar_width)
# horizontal scrollbar
=begin
@h_scroll = TkScrollbar.new(@frame, 'highlightthickness'=>@h_l_thick,
'borderwidth'=>@scrbar_border,
'orient'=>'horizontal', 'width'=>@scrbar_width)
=end
@h_scroll = TkXScrollbar.new(@frame, 'highlightthickness'=>@h_l_thick,
'borderwidth'=>@scrbar_border,
'width'=>@scrbar_width)
# create base flames
@c_title = TkCanvas.new(@frame, 'highlightthickness'=>@h_l_thick,
'width'=>@window_width)
@f_title = TkFrame.new(@c_title, 'width'=>@width_total)
@w_title = TkcWindow.new(@c_title, 0, 0,
'window'=>@f_title, 'anchor'=>'nw')
@c_lbox = TkCanvas.new(@frame, 'highlightthickness'=>@h_l_thick,
'width'=>@window_width)
@f_lbox = TkFrame.new(@c_lbox, 'width'=>@width_total)
@w_lbox = TkcWindow.new(@c_lbox, 0, 0, 'window'=>@f_lbox, 'anchor'=>'nw')
@c_hscr = TkCanvas.new(@frame, 'highlightthickness'=>@h_l_thick,
'width'=>@window_width)
@f_hscr = TkFrame.new(@c_hscr, 'width'=>@width_total)
@w_hscr = TkcWindow.new(@c_hscr, 0, 0, 'window'=>@f_hscr, 'anchor'=>'nw')
# create each listbox
sum = 0.0
@rel_list << sum/@width_total
title_info.each_with_index{|(label, width), idx|
# set relation between label and index
if @name_index.include?(label)
@name_index[label] << idx
else
@name_index[label] = [idx]
end
# calculate relative positioning
sum += width
@rel_list << sum/@width_total
# title field
f = TkFrame.new(@f_title, 'width'=>width)
base = [f]
title = TkLabel.new(f, 'text'=>label, 'borderwidth'=>@title_border,
'relief'=>'raised', 'highlightthickness'=>@h_l_thick)
title_binding(title, idx)
title.pack('fill'=>'x')
@title_list << title
f.place('relx'=>@rel_list[idx], 'y'=>0, 'anchor'=>'nw', 'width'=>1,
'relheight'=>1.0,
'relwidth'=>@rel_list[idx+1] - @rel_list[idx])
# listbox field
f = TkFrame.new(@f_lbox, 'width'=>width)
base << f
@lbox_list << TkListbox.new(f, 'highlightthickness'=>@h_l_thick,
'borderwidth'=>@lbox_border
).pack('fill'=>'both', 'expand'=>true)
f.place('relx'=>@rel_list[idx], 'y'=>0, 'anchor'=>'nw', 'width'=>1,
'relwidth'=>@rel_list[idx+1] - @rel_list[idx], 'relheight'=>1.0)
# scrollbar field
f = TkFrame.new(@f_hscr, 'width'=>width)
base << f
=begin
@hscr_list << TkScrollbar.new(f, 'orient'=>'horizontal',
'width'=>@scrbar_width,
'borderwidth'=>@scrbar_border,
'highlightthickness'=>@h_l_thick
).pack('fill'=>'x', 'anchor'=>'w')
=end
@hscr_list << TkXScrollbar.new(f, 'width'=>@scrbar_width,
'borderwidth'=>@scrbar_border,
'highlightthickness'=>@h_l_thick
).pack('fill'=>'x', 'anchor'=>'w')
f.place('relx'=>@rel_list[idx], 'y'=>0, 'anchor'=>'nw', 'width'=>1,
'relwidth'=>@rel_list[idx+1] - @rel_list[idx])
=begin
@lbox_list[idx].xscrollcommand proc{|first, last|
@hscr_list[idx].set first, last
}
@hscr_list[idx].command proc{|*args| @lbox_list[idx].xview *args}
=end
@lbox_list[idx].xscrollbar(@hscr_list[idx])
# add new base
@base_list << base
}
# pad
# @f_title_pad = TkFrame.new(@frame)
@f_title_pad = TkFrame.new(@frame, 'relief'=>'raised',
'borderwidth'=>@title_border,
'highlightthickness'=>@h_l_thick)
@f_scr_pad = TkFrame.new(@frame, 'relief'=>'sunken',
'borderwidth'=>1,
'highlightthickness'=>@h_l_thick)
# height check
title_height = 0
@title_list.each{|w|
h = w.winfo_reqheight
title_height = h if title_height < h
}
hscr_height = 0
@hscr_list.each{|w|
h = w.winfo_reqheight
hscr_height = h if hscr_height < h
}
@f_title.height title_height
@f_lbox.height lbox_height
@f_hscr.height hscr_height
# set control procedure for virtical scroll
=begin
@lbox_list.each{|lbox|
lbox.yscrollcommand proc{|first, last|
@v_scroll.set first, last
}
}
@v_scroll.command proc{|*args| @lbox_list.each{|lbox| lbox.yview *args} }
=end
@v_scroll.assign(*@lbox_list)
# set control procedure for horizoncal scroll
=begin
@c_title.xscrollcommand proc{|first, last|
@h_scroll.set first, last
}
@c_lbox.xscrollcommand proc{|first, last|
@h_scroll.set first, last
}
@c_hscr.xscrollcommand proc{|first, last|
@h_scroll.set first, last
}
@h_scroll.command proc{|*args|
@c_title.xview *args
@c_lbox.xview *args
@c_hscr.xview *args if @show_each_hscr
}
=end
@h_scroll.assign(@c_title, @c_lbox, @c_hscr)
# binding for listboxes
@lbox_mode = {}
@lbox_mode['browse'] = browse_mode_bindtag
@lbox_mode['single'] = single_mode_bindtag
@lbox_mode['extended'] = extended_mode_bindtag
@lbox_mode['multiple'] = multiple_mode_bindtag
@current_mode = 'browse'
@lbox_list.each_with_index{|l, idx|
l.bind('Shift-Key-Left',
proc{|w| focus_shift(w, -1); Tk.callback_break}, '%W')
l.bind('Shift-Key-Right',
proc{|w| focus_shift(w, 1); Tk.callback_break}, '%W')
l.bind('Button-2', proc{|x, y|
@lbox_mark_x = x
@lbox_list.each{|lbox| lbox.scan_mark(x, y)}
}, '%x %y')
l.bind('B2-Motion', proc{|x, y|
@lbox_list.each{|lbox| lbox.scan_dragto(@lbox_mark_x, y)}
l.scan_dragto(x, y)
}, '%x %y')
l.bindtags(l.bindtags.unshift(@lbox_mode[@current_mode]))
}
bbox = @w_title.bbox
@c_title.height(bbox[3])
@c_title.scrollregion(bbox)
bbox = @w_lbox.bbox
@c_lbox.height(bbox[3])
@c_lbox.scrollregion(bbox)
if @show_each_hscr
bbox = @w_hscr.bbox
@c_hscr.height(bbox[3])
@c_hscr.scrollregion(bbox)
end
# alignment
TkGrid.rowconfigure(@frame, 0, 'weight'=>0)
TkGrid.rowconfigure(@frame, 1, 'weight'=>1)
TkGrid.rowconfigure(@frame, 2, 'weight'=>0)
TkGrid.rowconfigure(@frame, 3, 'weight'=>0)
TkGrid.columnconfigure(@frame, 0, 'weight'=>1)
TkGrid.columnconfigure(@frame, 1, 'weight'=>0)
TkGrid.columnconfigure(@frame, 2, 'weight'=>0)
@v_scroll.grid('row'=>1, 'column'=>2, 'sticky'=>'ns')
@c_title.grid('row'=>0, 'column'=>0, 'sticky'=>'news')
@f_title_pad.grid('row'=>0, 'column'=>2, 'sticky'=>'news')
@c_lbox.grid('row'=>1, 'column'=>0, 'sticky'=>'news')
@c_hscr.grid('row'=>2, 'column'=>0, 'sticky'=>'ew') if @show_each_hscr
@h_scroll.grid('row'=>3, 'column'=>0, 'sticky'=>'ew') if @show_win_hscr
@f_scr_pad.grid('row'=>2, 'rowspan'=>2, 'column'=>2, 'sticky'=>'news')
# binding for 'Configure' event
@c_lbox.bind('Configure',
proc{|height, width| reconstruct(height, width)},
'%h %w')
# set default receiver of method calls
@path = @lbox_list[0].path
# configure options
keys = {} unless keys
keys = _symbolkey2str(keys)
# 'mode' option of listboxes
sel_mode = keys.delete('mode')
mode(sel_mode) if sel_mode
# 'scrollbarwidth' option == 'width' option of scrollbars
width = keys.delete('scrollbarwidth')
scrollbarwidth(width) if width
# options for listbox titles
title_font = keys.delete('titlefont')
titlefont(title_font) if title_font
title_fg = keys.delete('titleforeground')
titleforeground(title_fg) if title_fg
title_bg = keys.delete('titlebackground')
titlebackground(title_bg) if title_bg
# set receivers for configure methods
delegate('DEFAULT', *@lbox_list)
delegate('activebackground', @v_scroll, @h_scroll, *@hscr_list)
delegate('troughcolor', @v_scroll, @h_scroll, *@hscr_list)
delegate('repeatdelay', @v_scroll, @h_scroll, *@hscr_list)
delegate('repeatinterval', @v_scroll, @h_scroll, *@hscr_list)
delegate('borderwidth', @frame)
delegate('width', @c_lbox, @c_title, @c_hscr)
delegate('relief', @frame)
# configure
configure(keys) if keys.size > 0
end
private :initialize_composite
# set 'mode' option of listboxes
def mode(sel_mode)
@lbox_list.each{|l|
tags = l.bindtags
tags = tags - [ @lbox_mode[@current_mode] ]
l.bindtags(tags.unshift(@lbox_mode[sel_mode]))
@current_mode = sel_mode
}
end
# keep_minsize?
def keep_minsize?
@keep_minsize
end
def keep_minsize(bool)
@keep_minsize = bool
end
# each hscr
def show_each_hscr
@show_each_hscr = true
@c_hscr.grid('row'=>2, 'column'=>0, 'sticky'=>'ew')
end
def hide_each_hscr
@show_each_hscr = false
@c_hscr.ungrid
end
# window hscroll
def show_win_hscr
@show_win_hscr = true
@h_scroll.grid('row'=>3, 'column'=>0, 'sticky'=>'ew')
end
def hide_win_hscr
@show_each_hscr = false
@h_scroll.ungrid
end
# set scrollbar width
def scrollbarwidth(width)
@scrbar_width = width
@v_scroll['width'] = @scrbar_width
@h_scroll['width'] = @scrbar_width
@hscr_list.each{|hscr| hscr['width'] = @scrbar_width}
self
end
# set scrollbar border
def scrollbarborder(width)
@scrbar_border = width
@v_scroll['border'] = @scrbar_border
@h_scroll['border'] = @scrbar_border
@hscr_list.each{|hscr| hscr['border'] = @scrbar_border}
self
end
# set listbox borders
def listboxborder(width)
@lbox_border = width
@lbox_list.each{|w| w['border'] = @lbox_border}
self
end
# set listbox relief
def listboxrelief(relief)
@lbox_list.each{|w| w['relief'] = relief}
self
end
# set title borders
def titleborder(width)
@title_border = width
@f_title_pad['border'] = @title_border
@title_list.each{|label| label['border'] = @title_border}
self
end
# set title font
def titlefont(font)
@title_list.each{|label| label['font'] = font}
title_height = 0
@title_list.each{|w|
h = w.winfo_reqheight
title_height = h if title_height < h
}
@f_title.height title_height
bbox = @w_title.bbox
@c_title.height(bbox[3])
@c_title.scrollregion(bbox)
self
end
# set title foreground color
def titleforeground(fg)
@title_list.each{|label| label['foreground'] = fg}
self
end
# set title background color
def titlebackground(bg)
@f_title_pad['background'] = bg
@title_list.each{|label| label['background'] = bg}
self
end
# set title cmds
def titlecommand(idx, cmd=Proc.new)
@title_cmd[idx] = cmd
end
# call title cmds
def titleinvoke(idx)
@title_cmd[idx].call if @title_cmd[idx]
end
# get label widgets of listbox titles
def titlelabels(*indices)
@title_list[*indices]
end
# get listbox widgets
def columns(*indices)
@lbox_list[*indices]
end
def activate(idx)
@lbox_list.each{|lbox| lbox.activate(idx)}
end
def bbox(idx)
@lbox_list.collect{|lbox| lbox.bbox(idx)}
end
def delete(*idx)
@lbox_list.collect{|lbox| lbox.delete(*idx)}
end
def get(*idx)
if idx.size == 1
@lbox_list.collect{|lbox| lbox.get(*idx)}
else
list = @lbox_list.collect{|lbox| lbox.get(*idx)}
result = []
list[0].each_with_index{|line, index|
result << list.collect{|lines| lines[index]}
}
result
end
end
def _line_array_to_hash(line)
result = {}
@name_index.each_pair{|label, indices|
if indices.size == 1
result[label] = line[indices[0]]
else
result[label] = indices.collect{|index| line[index]}
end
}
result
end
private :_line_array_to_hash
def get_by_hash(*idx)
get_result = get(*idx)
if idx.size == 1
_line_array_to_hash(get_result)
else
get_result.collect{|line| _line_array_to_hash(line)}
end
end
def insert(idx, *lines)
lbox_ins = []
(0..@lbox_list.size).each{lbox_ins << []}
lines.each{|line|
if line.kind_of? Hash
array = []
@name_index.each_pair{|label, indices|
if indices.size == 1
array[indices[0]] = line[label]
else
if line[label].kind_of? Array
indices.each_with_index{|index, num|
array[index] = line[label][num]
}
else
array[indices[0]] = line[label]
end
end
}
line = array
end
@name_index.each_pair{|label, indices|
if indices.size == 1
lbox_ins[indices[0]] << line[indices[0]]
else
indices.each{|index| lbox_ins[index] << line[index]}
end
}
}
@lbox_list.each_with_index{|lbox, index|
lbox.insert(idx, *lbox_ins[index]) if lbox_ins[index]
}
end
def selection_anchor(index)
@lbox_list.each{|lbox| lbox.selection_anchor(index)}
end
def selection_clear(first, last=None)
@lbox_list.each{|lbox| lbox.selection_clear(first, last=None)}
end
def selection_set(first, last=None)
@lbox_list.each{|lbox| lbox.selection_set(first, last=None)}
end
###########################################
private
def reconstruct(height, width)
if @keep_minsize && width <= @width_total
@f_title.width(@width_total)
@f_lbox.width(@width_total)
@f_hscr.width(@width_total) if @show_each_hscr
@window_width = @width_total
else
@f_title.width(width)
@f_lbox.width(width)
@f_hscr.width(width) if @show_each_hscr
@window_width = width
end
@f_lbox.height(height)
@c_title.scrollregion(@w_title.bbox)
@c_lbox.scrollregion(@w_lbox.bbox)
@c_hscr.scrollregion(@w_hscr.bbox) if @show_each_hscr
(0..(@rel_list.size - 2)).each{|idx|
title, lbox, hscr = @base_list[idx]
title.place('relwidth'=>@rel_list[idx+1] - @rel_list[idx])
lbox.place('relwidth'=>@rel_list[idx+1] - @rel_list[idx],
'relheight'=>1.0)
hscr.place('relwidth'=>@rel_list[idx+1] - @rel_list[idx])
}
end
def resize(x)
idx = @sel_sash
return if idx == 0
# adjustment of relative positioning
delta = (x - @x) / @frame_width
if delta < @rel_list[idx-1] - @rel_list[idx] + (2*@sash/@frame_width)
delta = @rel_list[idx-1] - @rel_list[idx] + (2*@sash/@frame_width)
elsif delta > @rel_list[idx+1] - @rel_list[idx] - (2*@sash/@frame_width)
delta = @rel_list[idx+1] - @rel_list[idx] - (2*@sash/@frame_width)
end
@rel_list[idx] += delta
# adjustment of leftside widget of the sash
title, lbox, hscr = @base_list[idx - 1]
title.place('relwidth'=>@rel_list[idx] - @rel_list[idx-1])
lbox.place('relwidth'=>@rel_list[idx] - @rel_list[idx-1], 'relheight'=>1.0)
hscr.place('relwidth'=>@rel_list[idx] - @rel_list[idx-1])
# adjustment of rightside widget of the sash
title, lbox, hscr = @base_list[idx]
title.place('relwidth'=>@rel_list[idx+1] - @rel_list[idx],
'relx'=>@rel_list[idx])
lbox.place('relwidth'=>@rel_list[idx+1] - @rel_list[idx],
'relx'=>@rel_list[idx], 'relheight'=>1.0)
hscr.place('relwidth'=>@rel_list[idx+1] - @rel_list[idx],
'relx'=>@rel_list[idx])
# update reference position
@x = x
end
def motion_cb(w, x, idx)
if x <= @sash && idx > 0
w.cursor 'sb_h_double_arrow'
@mode = :sash
@sel_sash = idx
elsif x >= w.winfo_width - @sash && idx < @lbox_total - 1
w.cursor 'sb_h_double_arrow'
@mode = :sash
@sel_sash = idx + 1
else
w.cursor ""
@mode = :title
@sel_sash = 0
end
end
def title_binding(title, index)
title.bind('Motion', proc{|w, x, idx| motion_cb(w, x, idx.to_i)},
"%W %x #{index}")
title.bind('Enter', proc{|w, x, idx| motion_cb(w, x, idx.to_i)},
"%W %x #{index}")
title.bind('Leave', proc{|w| w.cursor ""}, "%W")
title.bind('Button-1',
proc{|w, x|
if @mode == :sash
@x = x
@frame_width = TkWinfo.width(@f_title).to_f
else
title.relief 'sunken'
end
},
'%W %X')
title.bind('ButtonRelease-1',
proc{|w, x, idx|
i = idx.to_i
if @mode == :title && @title_cmd[i].kind_of?(Proc)
@title_cmd[i].call
end
title.relief 'raised'
motion_cb(w,x,i)
},
"%W %x #{index}")
title.bind('B1-Motion', proc{|x| resize(x) if @mode == :sash}, "%X")
end
#################################
def browse_mode_bindtag
t = TkBindTag.new
t.bind('Button-1',
proc{|w, y| w.focus; select_line(w, w.nearest(y))}, '%W %y')
t.bind('B1-Motion', proc{|w, y| select_line(w, w.nearest(y))}, '%W %y')
t.bind('Shift-Button-1',
proc{|w, y| active_line(w, w.nearest(y))}, '%W %y')
t.bind('Key-Up', proc{|w| select_shift(w, -1)}, '%W')
t.bind('Key-Down', proc{|w| select_shift(w, 1)}, '%W')
t.bind('Control-Home', proc{|w| select_line(w, 0)}, '%W')
t.bind('Control-End', proc{|w| select_line(w, 'end')}, '%W')
t.bind('space', proc{|w| select_line(w, w.index('active').to_i)}, '%W')
t.bind('Select', proc{|w| select_line(w, w.index('active').to_i)}, '%W')
t.bind('Control-slash',
proc{|w| select_line(w, w.index('active').to_i)}, '%W')
t
end
########################
def single_mode_bindtag
t = TkBindTag.new
t.bind('Button-1',
proc{|w, y| w.focus; select_only(w, w.nearest(y))}, '%W %y')
t.bind('ButtonRelease-1',
proc{|w, y| active_line(w, w.nearest(y))}, '%W %y')
t.bind('Shift-Button-1',
proc{|w, y| active_line(w, w.nearest(y))}, '%W %y')
t.bind('Key-Up', proc{|w| select_shift(w, -1)}, '%W')
t.bind('Key-Down', proc{|w| select_shift(w, 1)}, '%W')
t.bind('Control-Home', proc{|w| select_line(w, 0)}, '%W')
t.bind('Control-End', proc{|w| select_line(w, 'end')}, '%W')
t.bind('space', proc{|w| select_line(w, w.index('active').to_i)}, '%W')
t.bind('Select', proc{|w| select_line(w, w.index('active').to_i)}, '%W')
t.bind('Control-slash',
proc{|w| select_line(w, w.index('active').to_i)}, '%W')
t.bind('Control-backslash',
proc{@lbox_list.each{|l| l.selection_clear(0, 'end')}})
t
end
########################
def extended_mode_bindtag
t = TkBindTag.new
t.bind('Button-1',
proc{|w, y| w.focus; select_only(w, w.nearest(y))}, '%W %y')
t.bind('B1-Motion', proc{|w, y| select_range(w, w.nearest(y))}, '%W %y')
t.bind('ButtonRelease-1',
proc{|w, y| active_line(w, w.nearest(y))}, '%W %y')
t.bind('Shift-Button-1',
proc{|w, y| select_range(w, w.nearest(y))}, '%W %y')
t.bind('Shift-B1-Motion',
proc{|w, y| select_range(w, w.nearest(y))}, '%W %y')
t.bind('Control-Button-1',
proc{|w, y| select_toggle(w, w.nearest(y))}, '%W %y')
t.bind('Control-B1-Motion',
proc{|w, y| select_drag(w, w.nearest(y))}, '%W %y')
t.bind('Key-Up', proc{|w| active_shift(w, -1)}, '%W')
t.bind('Key-Down', proc{|w| active_shift(w, 1)}, '%W')
t.bind('Shift-Up', proc{|w| select_expand(w, -1)}, '%W')
t.bind('Shift-Down', proc{|w| select_expand(w, 1)}, '%W')
t.bind('Control-Home', proc{|w| select_line2(w, 0)}, '%W')
t.bind('Control-End', proc{|w| select_line2(w, 'end')}, '%W')
t.bind('Control-Shift-Home', proc{|w| select_range(w, 0)}, '%W')
t.bind('Control-Shift-End', proc{|w| select_range(w, 'end')}, '%W')
t.bind('space', proc{|w| select_active(w)}, '%W')
t.bind('Select', proc{|w| select_active(w)}, '%W')
t.bind('Control-slash', proc{|w| select_all}, '%W')
t.bind('Control-backslash', proc{|w| clear_all}, '%W')
t
end
########################
def multiple_mode_bindtag
t = TkBindTag.new
t.bind('Button-1',
proc{|w, y| w.focus; select_line3(w, w.nearest(y))}, '%W %y')
t.bind('ButtonRelease-1',
proc{|w, y| active_line(w, w.nearest(y))}, '%W %y')
t.bind('Key-Up', proc{|w| active_shift(w, -1)}, '%W')
t.bind('Key-Down', proc{|w| active_shift(w, 1)}, '%W')
t.bind('Control-Home', proc{|w| select_line2(w, 0)}, '%W')
t.bind('Control-End', proc{|w| select_line2(w, 'end')}, '%W')
t.bind('Control-Shift-Home', proc{|w| active_line(w, 0)}, '%W')
t.bind('Control-Shift-End', proc{|w| active_line(w, 'end')}, '%W')
t.bind('space', proc{|w| select_active(w)}, '%W')
t.bind('Select', proc{|w| select_active(w)}, '%W')
t.bind('Control-slash', proc{|w| select_all}, '%W')
t.bind('Control-backslash', proc{|w| clear_all}, '%W')
t
end
########################
def active_line(w, idx)
@lbox_list.each{|l| l.activate(idx)}
end
def select_only(w, idx)
@lbox_list.each{|l|
l.selection_clear(0, 'end')
l.selection_anchor(idx)
l.selection_set('anchor')
}
end
def select_range(w, idx)
@lbox_list.each{|l|
l.selection_clear(0, 'end')
l.selection_set('anchor', idx)
}
end
def select_toggle(w, idx)
st = w.selection_includes(idx)
@lbox_list.each{|l|
l.selection_anchor(idx)
if st == 1
l.selection_clear(idx)
else
l.selection_set(idx)
end
}
end
def select_drag(w, idx)
st = w.selection_includes('anchor')
@lbox_list.each{|l|
if st == 1
l.selection_set('anchor', idx)
else
l.selection_clear('anchor', idx)
end
}
end
def select_line(w, idx)
@lbox_list.each{|l|
l.selection_clear(0, 'end')
l.activate(idx)
l.selection_anchor(idx)
l.selection_set('anchor')
}
w.selection_set('anchor')
end
def select_line2(w, idx)
@lbox_list.each{|l|
l.activate(idx)
l.selection_anchor(idx)
l.selection_set('anchor')
}
end
def select_line3(w, idx)
@lbox_list.each{|l|
l.selection_set(idx)
}
end
def select_active(w)
idx = l.activate(idx)
@lbox_list.each{|l|
l.selection_set(idx)
}
end
def select_expand(w, dir)
idx = w.index('active').to_i + dir
if idx < 0
idx = 0
elsif idx >= w.size
idx = w.size - 1
end
@lbox_list.each{|l|
l.activate(idx)
l.selection_set(idx)
}
end
def active_shift(w, dir)
idx = w.index('active').to_i + dir
if idx < 0
idx = 0
elsif idx >= w.size
idx = w.size - 1
end
@lbox_list.each{|l|
l.activate(idx)
l.selection_anchor(idx)
}
end
def select_shift(w, dir)
idx = w.index('anchor').to_i + dir
if idx < 0
idx = 0
elsif idx >= w.size
idx = w.size - 1
end
@lbox_list.each{|l|
l.selection_clear(0, 'end')
l.activate(idx)
l.selection_anchor(idx)
l.selection_set('anchor')
}
end
def select_all
@lbox_list.each{|l|
l.selection_set(0, 'end')
}
end
def clear_all
@lbox_list.each{|l|
l.selection_clear(0, 'end')
}
end
def focus_shift(w, dir)
idx = @lbox_list.index(w) + dir
return if idx < 0
return if idx >= @lbox_list.size
@lbox_list[idx].focus
end
########################
end
################################################
# test
################################################
if __FILE__ == $0
l = TkMultiListFrame.new(nil, 200,
[ ['L1', 200, proc{p 'click L1'}],
['L2', 100],
['L3', 200] ],
'width'=>350,
#'titleforeground'=>'yellow',
'titleforeground'=>'white',
#'titlebackground'=>'navy',
'titlebackground'=>'blue',
'titlefont'=>'courier'
).pack('fill'=>'both', 'expand'=>true)
l.insert('end', [1,2,3])
l.insert('end', [4,5,6])
l.insert('end', [4,5,6], [4,5,6])
l.insert('end', ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
'cccccccccccccccccccccccccccccccccccccccccccccccccccc'])
l.insert('end', [1,2,3])
l.insert('end', [4,5,6], [4,5,6])
l.insert('end', ['aaaaaaaaaaaaaaa','bbbbbbbbbbbbbb','ccccccccccccccccc'])
l.insert('end', [1,2,3])
l.insert('end', [4,5,6], [4,5,6])
l.insert('end', ['aaaaaaaaaaaaaaa','bbbbbbbbbbbbbb','ccccccccccccccccc'])
l.insert('end', [1,2,3])
l.insert('end', [4,5,6], [4,5,6])
l.insert('end', ['aaaaaaaaaaaaaaa','bbbbbbbbbbbbbb','ccccccccccccccccc'])
l.insert('end', [1,2,3])
l.insert('end', [4,5,6], [4,5,6])
p l.columns(1)
p l.columns(1..3)
p l.columns(1,2)
Tk.mainloop
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/ripper/tools/generate-param-macros.rb
|
# frozen_string_literal: false
off = true
ARGF.each do |line|
case line
when /RIPPER_PARAMS_DECL_BEGIN/
off = false
when /RIPPER_PARAMS_DECL_END/
exit
when /ripper/
next if off
var = line.scan(/\w+/).last or next
base = var.sub(/ripper_/, '')
puts %"\#define #{base}\t\t(parser->ripper_#{base})"
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-authentication-1.4.1/spec/mixlib/authentication/mixlib_authentication_spec.rb
|
#
# Author:: <NAME> (<<EMAIL>>)
# Author:: <NAME> (<<EMAIL>>)
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2009, 2010 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper"))
require "rubygems"
require "ostruct"
require "openssl"
require "mixlib/authentication/signatureverification"
require "time"
# TODO: should make these regular spec-based mock objects.
class MockRequest
attr_accessor :env, :params, :path, :raw_post
def initialize(path, params, headers, raw_post)
@path = path
@params = params
@env = headers
@raw_post = raw_post
end
def method
"POST"
end
end
class MockFile
def initialize
@have_read = nil
end
def self.length
BODY.length
end
def read(len, out_str)
if @have_read.nil?
@have_read = 1
out_str[0..-1] = BODY
BODY
else
nil
end
end
end
# Uncomment this to get some more info from the methods we're testing.
#Mixlib::Authentication::Log.logger = Logger.new(STDERR)
#Mixlib::Authentication::Log.level :debug
describe "Mixlib::Authentication::SignedHeaderAuth" do
# NOTE: Version 1.0 will be the default until Chef 11 is released.
it "should generate the correct string to sign and signature, version 1.0 (default)" do
expect(V1_0_SIGNING_OBJECT.canonicalize_request).to eq(V1_0_CANONICAL_REQUEST)
# If you need to regenerate the constants in this test spec, print out
# the results of res.inspect and copy them as appropriate into the
# the constants in this file.
expect(V1_0_SIGNING_OBJECT.sign(PRIVATE_KEY)).to eq(EXPECTED_SIGN_RESULT_V1_0)
end
it "should generate the correct string to sign and signature, version 1.1" do
expect(V1_1_SIGNING_OBJECT.proto_version).to eq("1.1")
expect(V1_1_SIGNING_OBJECT.canonicalize_request).to eq(V1_1_CANONICAL_REQUEST)
# If you need to regenerate the constants in this test spec, print out
# the results of res.inspect and copy them as appropriate into the
# the constants in this file.
expect(V1_1_SIGNING_OBJECT.sign(PRIVATE_KEY)).to eq(EXPECTED_SIGN_RESULT_V1_1)
end
it "should generate the correct string to sign and signature for version 1.3 with SHA256" do
expect(V1_3_SHA256_SIGNING_OBJECT.proto_version).to eq("1.3")
expect(V1_3_SHA256_SIGNING_OBJECT.algorithm).to eq("sha256")
expect(V1_3_SHA256_SIGNING_OBJECT.server_api_version).to eq("1")
expect(V1_3_SHA256_SIGNING_OBJECT.canonicalize_request).to eq(V1_3_SHA256_CANONICAL_REQUEST)
# If you need to regenerate the constants in this test spec, print out
# the results of res.inspect and copy them as appropriate into the
# the constants in this file.
expect(V1_3_SHA256_SIGNING_OBJECT.sign(PRIVATE_KEY)).to eq(EXPECTED_SIGN_RESULT_V1_3_SHA256)
end
it "should generate the correct string to sign and signature for non-default proto version when used as a mixin" do
algorithm = "sha1"
version = "1.1"
V1_1_SIGNING_OBJECT.proto_version = "1.0"
expect(V1_1_SIGNING_OBJECT.proto_version).to eq("1.0")
expect(V1_1_SIGNING_OBJECT.canonicalize_request(algorithm, version)).to eq(V1_1_CANONICAL_REQUEST)
# If you need to regenerate the constants in this test spec, print out
# the results of res.inspect and copy them as appropriate into the
# the constants in this file.
expect(V1_1_SIGNING_OBJECT.sign(PRIVATE_KEY, algorithm, version)).to eq(EXPECTED_SIGN_RESULT_V1_1)
end
it "should not choke when signing a request for a long user id with version 1.1" do
expect { LONG_SIGNING_OBJECT.sign(PRIVATE_KEY, "sha1", "1.1") }.not_to raise_error
end
it "should choke when signing a request for a long user id with version 1.0" do
expect { LONG_SIGNING_OBJECT.sign(PRIVATE_KEY, "sha1", "1.0") }.to raise_error(OpenSSL::PKey::RSAError)
end
it "should choke when signing a request with a bad version" do
expect { V1_1_SIGNING_OBJECT.sign(PRIVATE_KEY, "sha1", "poo") }.to raise_error(Mixlib::Authentication::AuthenticationError)
end
it "should choke when signing a request with a bad algorithm" do
expect { V1_1_SIGNING_OBJECT.sign(PRIVATE_KEY, "sha_poo", "1.1") }.to raise_error(Mixlib::Authentication::AuthenticationError)
end
end
describe "Mixlib::Authentication::SignatureVerification" do
before(:each) do
@user_private_key = PRIVATE_KEY
end
it "should authenticate a File-containing request V1.1 - Merb" do
request_params = MERB_REQUEST_PARAMS.clone
request_params["file"] =
{ "size" => MockFile.length, "content_type" => "application/octet-stream", "filename" => "zsh.tar.gz", "tempfile" => MockFile.new }
mock_request = MockRequest.new(PATH, request_params, MERB_HEADERS_V1_1, "")
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
service = Mixlib::Authentication::SignatureVerification.new
res = service.authenticate_user_request(mock_request, @user_private_key)
expect(res).not_to be_nil
end
it "should authenticate a File-containing request V1.3 SHA256 - Merb" do
request_params = MERB_REQUEST_PARAMS.clone
request_params["file"] =
{ "size" => MockFile.length, "content_type" => "application/octet-stream", "filename" => "zsh.tar.gz", "tempfile" => MockFile.new }
mock_request = MockRequest.new(PATH, request_params, MERB_HEADERS_V1_3_SHA256, "")
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
service = Mixlib::Authentication::SignatureVerification.new
res = service.authenticate_user_request(mock_request, @user_private_key)
expect(res).not_to be_nil
end
it "should authenticate a File-containing request from a v1.0 client - Passenger" do
request_params = PASSENGER_REQUEST_PARAMS.clone
request_params["tarball"] = MockFile.new
mock_request = MockRequest.new(PATH, request_params, PASSENGER_HEADERS_V1_0, "")
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
auth_req = Mixlib::Authentication::SignatureVerification.new
res = auth_req.authenticate_user_request(mock_request, @user_private_key)
expect(res).not_to be_nil
end
it "should authenticate a normal (post body) request v1.3 SHA256 - Merb" do
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, MERB_HEADERS_V1_3_SHA256, BODY)
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
service = Mixlib::Authentication::SignatureVerification.new
res = service.authenticate_user_request(mock_request, @user_private_key)
expect(res).not_to be_nil
end
it "should authenticate a normal (post body) request v1.1 - Merb" do
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, MERB_HEADERS_V1_1, BODY)
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
service = Mixlib::Authentication::SignatureVerification.new
res = service.authenticate_user_request(mock_request, @user_private_key)
expect(res).not_to be_nil
end
it "should authenticate a normal (post body) request from a v1.0 client - Merb" do
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, MERB_HEADERS_V1_0, BODY)
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
service = Mixlib::Authentication::SignatureVerification.new
res = service.authenticate_user_request(mock_request, @user_private_key)
expect(res).not_to be_nil
end
it "shouldn't authenticate if an Authorization header is missing" do
headers = MERB_HEADERS_V1_1.clone
headers.delete("HTTP_X_OPS_SIGN")
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, headers, BODY)
allow(Time).to receive(:now).and_return(TIMESTAMP_OBJ)
#Time.stub!(:now).and_return(TIMESTAMP_OBJ)
auth_req = Mixlib::Authentication::SignatureVerification.new
expect { auth_req.authenticate_user_request(mock_request, @user_private_key) }.to raise_error(Mixlib::Authentication::AuthenticationError)
expect(auth_req).not_to be_a_valid_request
expect(auth_req).not_to be_a_valid_timestamp
expect(auth_req).not_to be_a_valid_signature
expect(auth_req).not_to be_a_valid_content_hash
end
it "shouldn't authenticate if Authorization header is wrong" do
headers = MERB_HEADERS_V1_1.clone
headers["HTTP_X_OPS_CONTENT_HASH"] += "_"
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, headers, BODY)
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
auth_req = Mixlib::Authentication::SignatureVerification.new
res = auth_req.authenticate_user_request(mock_request, @user_private_key)
expect(res).to be_nil
expect(auth_req).not_to be_a_valid_request
expect(auth_req).to be_a_valid_timestamp
expect(auth_req).to be_a_valid_signature
expect(auth_req).not_to be_a_valid_content_hash
end
it "shouldn't authenticate if the timestamp is not within bounds" do
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, MERB_HEADERS_V1_1, BODY)
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ - 1000)
auth_req = Mixlib::Authentication::SignatureVerification.new
res = auth_req.authenticate_user_request(mock_request, @user_private_key)
expect(res).to be_nil
expect(auth_req).not_to be_a_valid_request
expect(auth_req).not_to be_a_valid_timestamp
expect(auth_req).to be_a_valid_signature
expect(auth_req).to be_a_valid_content_hash
end
it "shouldn't authenticate if the signature is wrong" do
headers = MERB_HEADERS_V1_1.dup
headers["HTTP_X_OPS_AUTHORIZATION_1"] = "epicfail"
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, headers, BODY)
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
auth_req = Mixlib::Authentication::SignatureVerification.new
res = auth_req.authenticate_user_request(mock_request, @user_private_key)
expect(res).to be_nil
expect(auth_req).not_to be_a_valid_request
expect(auth_req).not_to be_a_valid_signature
expect(auth_req).to be_a_valid_timestamp
expect(auth_req).to be_a_valid_content_hash
end
it "shouldn't authenticate if the signature is wrong for v1.3 SHA256" do
headers = MERB_HEADERS_V1_3_SHA256.dup
headers["HTTP_X_OPS_AUTHORIZATION_1"] = "epicfail"
mock_request = MockRequest.new(PATH, MERB_REQUEST_PARAMS, headers, BODY)
expect(Time).to receive(:now).at_least(:once).and_return(TIMESTAMP_OBJ)
auth_req = Mixlib::Authentication::SignatureVerification.new
res = auth_req.authenticate_user_request(mock_request, @user_private_key)
expect(res).to be_nil
expect(auth_req).not_to be_a_valid_request
expect(auth_req).not_to be_a_valid_signature
expect(auth_req).to be_a_valid_timestamp
expect(auth_req).to be_a_valid_content_hash
end
end
USER_ID = "spec-user"
DIGESTED_USER_ID = Base64.encode64(Digest::SHA1.new.digest(USER_ID)).chomp
BODY = "Spec Body"
HASHED_BODY = "DFteJZPVv6WKdQmMqZUQUumUyRs=" # Base64.encode64(Digest::SHA1.digest("Spec Body")).chomp
HASHED_BODY_SHA256 = "hDlKNZhIhgso3Fs0S0pZwJ0xyBWtR1RBaeHs1DrzOho="
TIMESTAMP_ISO8601 = "2009-01-01T12:00:00Z"
TIMESTAMP_OBJ = Time.parse("Thu Jan 01 12:00:00 -0000 2009")
PATH = "/organizations/clownco"
HASHED_CANONICAL_PATH = "YtBWDn1blGGuFIuKksdwXzHU9oE=" # Base64.encode64(Digest::SHA1.digest("/organizations/clownco")).chomp
V1_0_ARGS = {
:body => BODY,
:user_id => USER_ID,
:http_method => :post,
:timestamp => TIMESTAMP_ISO8601, # fixed timestamp so we get back the same answer each time.
:file => MockFile.new,
:path => PATH,
}
V1_1_ARGS = {
:body => BODY,
:user_id => USER_ID,
:http_method => :post,
:timestamp => TIMESTAMP_ISO8601, # fixed timestamp so we get back the same answer each time.
:file => MockFile.new,
:path => PATH,
:proto_version => 1.1,
}
V1_3_ARGS_SHA256 = {
:body => BODY,
:user_id => USER_ID,
:http_method => :post,
:timestamp => TIMESTAMP_ISO8601, # fixed timestamp so we get back the same answer each time.
:file => MockFile.new,
:path => PATH,
:proto_version => "1.3",
:headers => {
"X-OpS-SeRvEr-ApI-VerSiOn" => "1",
}
# This defaults to sha256
}
LONG_PATH_LONG_USER_ARGS = {
:body => BODY,
:user_id => "A" * 200,
:http_method => :put,
:timestamp => TIMESTAMP_ISO8601, # fixed timestamp so we get back the same answer each time.
:file => MockFile.new,
:path => PATH + "/nodes/#{"A" * 250}",
}
REQUESTING_ACTOR_ID = "c0f8a68c52bffa1020222a56b23cccfa"
# Content hash is ???TODO
X_OPS_CONTENT_HASH = "DFteJZPVv6WKdQmMqZUQUumUyRs="
X_OPS_CONTENT_HASH_SHA256 = "hDlKNZhIhgso3Fs0S0pZwJ0xyBWtR1RBaeHs1DrzOho="
X_OPS_AUTHORIZATION_LINES_V1_0 = [
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"9q4rlh/+1tBReg60QdsmDRsw/cdO1GZrKtuCwbuD4+nbRdVBKv72rqHX9cu0",
"utju9jzczCyB+sSAQWrxSsXB/b8vV2qs0l4VD2ML+w==",
]
X_OPS_AUTHORIZATION_LINES = [
"UfZD9dRz6rFu6LbP5Mo1oNHcWYxpNIcUfFCffJS1FQa0GtfU/vkt3/O5HuCM",
"1wIFl/U0f5faH9EWpXWY5NwKR031Myxcabw4t4ZLO69CIh/3qx1XnjcZvt2w",
"c2R9bx/43IWA/r8w8Q6decuu0f6ZlNheJeJhaYPI8piX/aH+uHBH8zTACZu8",
"vMnl5MF3/OIlsZc8cemq6eKYstp8a8KYq9OmkB5IXIX6qVMJHA6fRvQEB/7j",
"281Q7oI/O+lE8AmVyBbwruPb7Mp6s4839eYiOdjbDwFjYtbS3XgAjrHlaD7W",
"FDlbAG7H8Dmvo+wBxmtNkszhzbBnEYtuwQqT8nM/8A==",
]
X_OPS_AUTHORIZATION_LINES_V1_3_SHA256 = [
"FZOmXAyOBAZQV/uw188iBljBJXOm+m8xQ/8KTGLkgGwZNcRFxk1m953XjE3W",
"VGy1dFT76KeaNWmPCNtDmprfH2na5UZFtfLIKrPv7xm80V+lzEzTd9WBwsfP",
"42dZ9N+V9I5SVfcL/lWrrlpdybfceJC5jOcP5tzfJXWUITwb6Z3Erg3DU3Uh",
"H9h9E0qWlYGqmiNCVrBnpe6Si1gU/Jl+rXlRSNbLJ4GlArAPuL976iTYJTzE",
"MmbLUIm3JRYi00Yb01IUCCKdI90vUq1HHNtlTEu93YZfQaJwRxXlGkCNwIJe",
"fy49QzaCIEu1XiOx5Jn+4GmkrZch/RrK9VzQWXgs+w==",
]
# We expect Mixlib::Authentication::SignedHeaderAuth#sign to return this
# if passed the BODY above, based on version
EXPECTED_SIGN_RESULT_V1_0 = {
"X-Ops-Content-Hash" => X_OPS_CONTENT_HASH,
"X-Ops-Userid" => USER_ID,
"X-Ops-Sign" => "algorithm=sha1;version=1.0;",
"X-Ops-Authorization-1" => X_OPS_AUTHORIZATION_LINES_V1_0[0],
"X-Ops-Authorization-2" => X_OPS_AUTHORIZATION_LINES_V1_0[1],
"X-Ops-Authorization-3" => X_OPS_AUTHORIZATION_LINES_V1_0[2],
"X-Ops-Authorization-4" => X_OPS_AUTHORIZATION_LINES_V1_0[3],
"X-Ops-Authorization-5" => X_OPS_AUTHORIZATION_LINES_V1_0[4],
"X-Ops-Authorization-6" => X_OPS_AUTHORIZATION_LINES_V1_0[5],
"X-Ops-Timestamp" => TIMESTAMP_ISO8601,
}
EXPECTED_SIGN_RESULT_V1_1 = {
"X-Ops-Content-Hash" => X_OPS_CONTENT_HASH,
"X-Ops-Userid" => USER_ID,
"X-Ops-Sign" => "algorithm=sha1;version=1.1;",
"X-Ops-Authorization-1" => X_OPS_AUTHORIZATION_LINES[0],
"X-Ops-Authorization-2" => X_OPS_AUTHORIZATION_LINES[1],
"X-Ops-Authorization-3" => X_OPS_AUTHORIZATION_LINES[2],
"X-Ops-Authorization-4" => X_OPS_AUTHORIZATION_LINES[3],
"X-Ops-Authorization-5" => X_OPS_AUTHORIZATION_LINES[4],
"X-Ops-Authorization-6" => X_OPS_AUTHORIZATION_LINES[5],
"X-Ops-Timestamp" => TIMESTAMP_ISO8601,
}
EXPECTED_SIGN_RESULT_V1_3_SHA256 = {
"X-Ops-Content-Hash" => X_OPS_CONTENT_HASH_SHA256,
"X-Ops-Userid" => USER_ID,
"X-Ops-Sign" => "algorithm=sha256;version=1.3;",
"X-Ops-Authorization-1" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[0],
"X-Ops-Authorization-2" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[1],
"X-Ops-Authorization-3" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[2],
"X-Ops-Authorization-4" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[3],
"X-Ops-Authorization-5" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[4],
"X-Ops-Authorization-6" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[5],
"X-Ops-Timestamp" => TIMESTAMP_ISO8601,
}
OTHER_HEADERS = {
# An arbitrary sampling of non-HTTP_* headers are in here to
# exercise that code path.
"REMOTE_ADDR" => "127.0.0.1",
"PATH_INFO" => "/organizations/local-test-org/cookbooks",
"REQUEST_PATH" => "/organizations/local-test-org/cookbooks",
"CONTENT_TYPE" => "multipart/form-data; boundary=----RubyMultipartClient6792ZZZZZ",
"CONTENT_LENGTH" => "394",
}
# This is what will be in request.params for the Merb case.
MERB_REQUEST_PARAMS = {
"name" => "zsh", "action" => "create", "controller" => "chef_server_api/cookbooks",
"organization_id" => "local-test-org", "requesting_actor_id" => REQUESTING_ACTOR_ID
}
MERB_HEADERS_V1_3_SHA256 = {
# These are used by signatureverification.
"HTTP_HOST" => "127.0.0.1",
"HTTP_X_OPS_SIGN" => "algorithm=sha256;version=1.3;",
"HTTP_X_OPS_REQUESTID" => "127.0.0.1 1258566194.85386",
"HTTP_X_OPS_TIMESTAMP" => TIMESTAMP_ISO8601,
"HTTP_X_OPS_CONTENT_HASH" => X_OPS_CONTENT_HASH_SHA256,
"HTTP_X_OPS_USERID" => USER_ID,
"HTTP_X_OPS_SERVER_API_VERSION" => "1",
"HTTP_X_OPS_AUTHORIZATION_1" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[0],
"HTTP_X_OPS_AUTHORIZATION_2" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[1],
"HTTP_X_OPS_AUTHORIZATION_3" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[2],
"HTTP_X_OPS_AUTHORIZATION_4" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[3],
"HTTP_X_OPS_AUTHORIZATION_5" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[4],
"HTTP_X_OPS_AUTHORIZATION_6" => X_OPS_AUTHORIZATION_LINES_V1_3_SHA256[5],
}.merge(OTHER_HEADERS)
# Tis is what will be in request.env for the Merb case.
MERB_HEADERS_V1_1 = {
# These are used by signatureverification.
"HTTP_HOST" => "127.0.0.1",
"HTTP_X_OPS_SIGN" => "algorithm=sha1;version=1.1;",
"HTTP_X_OPS_REQUESTID" => "127.0.0.1 1258566194.85386",
"HTTP_X_OPS_TIMESTAMP" => TIMESTAMP_ISO8601,
"HTTP_X_OPS_CONTENT_HASH" => X_OPS_CONTENT_HASH,
"HTTP_X_OPS_USERID" => USER_ID,
"HTTP_X_OPS_AUTHORIZATION_1" => X_OPS_AUTHORIZATION_LINES[0],
"HTTP_X_OPS_AUTHORIZATION_2" => X_OPS_AUTHORIZATION_LINES[1],
"HTTP_X_OPS_AUTHORIZATION_3" => X_OPS_AUTHORIZATION_LINES[2],
"HTTP_X_OPS_AUTHORIZATION_4" => X_OPS_AUTHORIZATION_LINES[3],
"HTTP_X_OPS_AUTHORIZATION_5" => X_OPS_AUTHORIZATION_LINES[4],
"HTTP_X_OPS_AUTHORIZATION_6" => X_OPS_AUTHORIZATION_LINES[5],
}.merge(OTHER_HEADERS)
# Tis is what will be in request.env for the Merb case.
MERB_HEADERS_V1_0 = {
# These are used by signatureverification.
"HTTP_HOST" => "127.0.0.1",
"HTTP_X_OPS_SIGN" => "version=1.0",
"HTTP_X_OPS_REQUESTID" => "127.0.0.1 1258566194.85386",
"HTTP_X_OPS_TIMESTAMP" => TIMESTAMP_ISO8601,
"HTTP_X_OPS_CONTENT_HASH" => X_OPS_CONTENT_HASH,
"HTTP_X_OPS_USERID" => USER_ID,
"HTTP_X_OPS_AUTHORIZATION_1" => X_OPS_AUTHORIZATION_LINES_V1_0[0],
"HTTP_X_OPS_AUTHORIZATION_2" => X_OPS_AUTHORIZATION_LINES_V1_0[1],
"HTTP_X_OPS_AUTHORIZATION_3" => X_OPS_AUTHORIZATION_LINES_V1_0[2],
"HTTP_X_OPS_AUTHORIZATION_4" => X_OPS_AUTHORIZATION_LINES_V1_0[3],
"HTTP_X_OPS_AUTHORIZATION_5" => X_OPS_AUTHORIZATION_LINES_V1_0[4],
"HTTP_X_OPS_AUTHORIZATION_6" => X_OPS_AUTHORIZATION_LINES_V1_0[5],
}.merge(OTHER_HEADERS)
PASSENGER_REQUEST_PARAMS = {
"action" => "create",
#"tarball"=>#<File:/tmp/RackMultipart20091120-25570-mgq2sa-0>,
"controller" => "api/v1/cookbooks",
"cookbook" => "{\"category\":\"databases\"}",
}
PASSENGER_HEADERS_V1_1 = {
# These are used by signatureverification.
"HTTP_HOST" => "127.0.0.1",
"HTTP_X_OPS_SIGN" => "algorithm=sha1;version=1.1;",
"HTTP_X_OPS_REQUESTID" => "127.0.0.1 1258566194.85386",
"HTTP_X_OPS_TIMESTAMP" => TIMESTAMP_ISO8601,
"HTTP_X_OPS_CONTENT_HASH" => X_OPS_CONTENT_HASH,
"HTTP_X_OPS_USERID" => USER_ID,
"HTTP_X_OPS_AUTHORIZATION_1" => X_OPS_AUTHORIZATION_LINES[0],
"HTTP_X_OPS_AUTHORIZATION_2" => X_OPS_AUTHORIZATION_LINES[1],
"HTTP_X_OPS_AUTHORIZATION_3" => X_OPS_AUTHORIZATION_LINES[2],
"HTTP_X_OPS_AUTHORIZATION_4" => X_OPS_AUTHORIZATION_LINES[3],
"HTTP_X_OPS_AUTHORIZATION_5" => X_OPS_AUTHORIZATION_LINES[4],
"HTTP_X_OPS_AUTHORIZATION_6" => X_OPS_AUTHORIZATION_LINES[5],
}.merge(OTHER_HEADERS)
PASSENGER_HEADERS_V1_0 = {
# These are used by signatureverification.
"HTTP_HOST" => "127.0.0.1",
"HTTP_X_OPS_SIGN" => "version=1.0",
"HTTP_X_OPS_REQUESTID" => "127.0.0.1 1258566194.85386",
"HTTP_X_OPS_TIMESTAMP" => TIMESTAMP_ISO8601,
"HTTP_X_OPS_CONTENT_HASH" => X_OPS_CONTENT_HASH,
"HTTP_X_OPS_USERID" => USER_ID,
"HTTP_X_OPS_AUTHORIZATION_1" => X_OPS_AUTHORIZATION_LINES_V1_0[0],
"HTTP_X_OPS_AUTHORIZATION_2" => X_OPS_AUTHORIZATION_LINES_V1_0[1],
"HTTP_X_OPS_AUTHORIZATION_3" => X_OPS_AUTHORIZATION_LINES_V1_0[2],
"HTTP_X_OPS_AUTHORIZATION_4" => X_OPS_AUTHORIZATION_LINES_V1_0[3],
"HTTP_X_OPS_AUTHORIZATION_5" => X_OPS_AUTHORIZATION_LINES_V1_0[4],
"HTTP_X_OPS_AUTHORIZATION_6" => X_OPS_AUTHORIZATION_LINES_V1_0[5],
}.merge(OTHER_HEADERS)
# generated with
# openssl genrsa -out private.pem 2048
# openssl rsa -in private.pem -out public.pem -pubout
PUBLIC_KEY_DATA = <<EOS
-----BEGIN PUBLIC KEY-----
<KEY>
EOS
PRIVATE_KEY_DATA = <<EOS
-----<KEY>
EOS
PRIVATE_KEY = OpenSSL::PKey::RSA.new(PRIVATE_KEY_DATA)
V1_0_CANONICAL_REQUEST_DATA = <<EOS
Method:POST
Hashed Path:#{HASHED_CANONICAL_PATH}
X-Ops-Content-Hash:#{HASHED_BODY}
X-Ops-Timestamp:#{TIMESTAMP_ISO8601}
X-Ops-UserId:#{USER_ID}
EOS
V1_0_CANONICAL_REQUEST = V1_0_CANONICAL_REQUEST_DATA.chomp
V1_1_CANONICAL_REQUEST_DATA = <<EOS
Method:POST
Hashed Path:#{HASHED_CANONICAL_PATH}
X-Ops-Content-Hash:#{HASHED_BODY}
X-Ops-Timestamp:#{TIMESTAMP_ISO8601}
X-Ops-UserId:#{DIGESTED_USER_ID}
EOS
V1_1_CANONICAL_REQUEST = V1_1_CANONICAL_REQUEST_DATA.chomp
V1_3_SHA256_CANONICAL_REQUEST_DATA = <<EOS
Method:POST
Path:#{PATH}
X-Ops-Content-Hash:#{HASHED_BODY_SHA256}
X-Ops-Sign:version=1.3
X-Ops-Timestamp:#{TIMESTAMP_ISO8601}
X-Ops-UserId:#{USER_ID}
X-Ops-Server-API-Version:1
EOS
V1_3_SHA256_CANONICAL_REQUEST = V1_3_SHA256_CANONICAL_REQUEST_DATA.chomp
V1_3_SHA256_SIGNING_OBJECT = Mixlib::Authentication::SignedHeaderAuth.signing_object(V1_3_ARGS_SHA256)
V1_1_SIGNING_OBJECT = Mixlib::Authentication::SignedHeaderAuth.signing_object(V1_1_ARGS)
V1_0_SIGNING_OBJECT = Mixlib::Authentication::SignedHeaderAuth.signing_object(V1_0_ARGS)
LONG_SIGNING_OBJECT = Mixlib::Authentication::SignedHeaderAuth.signing_object(LONG_PATH_LONG_USER_ARGS)
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/benchmark/other-lang/loop.rb
|
i=0
while i<30000000
i+=1
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkentry.rb
|
#
# tkentry.rb - load tk/entry.rb
#
require 'tk/entry'
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/executable-hooks-1.3.2/lib/executable-hooks/regenerate_binstubs_command.rb
|
<filename>.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/executable-hooks-1.3.2/lib/executable-hooks/regenerate_binstubs_command.rb
require 'rubygems/command_manager'
require 'rubygems/installer'
require 'rubygems/version'
require 'executable-hooks/wrapper'
class RegenerateBinstubsCommand < Gem::Command
def initialize
super 'regenerate_binstubs', 'Re run generation of executable wrappers for gems.'
end
def arguments # :nodoc:
"STRING start of gem name to regenerate binstubs"
end
def usage # :nodoc:
"#{program_name} [STRING]"
end
def defaults_str # :nodoc:
""
end
def description # :nodoc:
'Re run generation of executable wrappers for all gems. '+
'Wrappers will be compatible with both rubygems and bundler. '+
'The switcher is BUNDLE_GEMFILE environment variable, '+
'when set it switches to bundler mode, when not set, '+
'then the command will work as it was with pure rubygems.'
end
def execute
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('2.0.0') then
# https://github.com/rubygems/rubygems/issues/326
puts "try also: gem pristine --binstubs"
end
ExecutableHooks::Wrapper.install
execute_no_wrapper
end
def execute_no_wrapper
require 'executable-hooks/installer'
name = get_one_optional_argument || ''
specs = installed_gems.select{|spec| spec.name =~ /^#{name}/i }
specs.each do |spec|
unless spec.executables.empty?
try_to_fix_binstubs(spec) or
try_to_install_binstubs(spec) or
$stderr.puts "##{spec.name} #{spec.version} not found in GEM_PATH"
end
end
end
private
def try_to_fix_binstubs(spec)
executable_paths =
spec.executables.map do |executable|
path = expanded_bin_paths.detect{|path| File.exist?(File.join(path, executable)) }
File.join(path, executable) if path
end
return false if executable_paths.include?(nil) # not found
executable_shebangs =
executable_paths.map do |path|
[path, File.readlines(path).map(&:chomp)]
end
return false if executable_shebangs.detect{|path, lines| !lines[0] =~ /^#!\// }
puts "#{spec.name} #{spec.version}"
executable_mode = 0111
executable_shebangs.map do |path, lines|
lines[0] = "#!#{ExecutableHooksInstaller.env_path} #{ExecutableHooks::Wrapper.expanded_wrapper_name}"
File.open(path, "w") do |file|
file.puts(lines)
end
mode = File.stat(path).mode
File.chmod(mode | executable_mode, path) if mode & executable_mode != executable_mode
end
end
def expanded_bin_paths
@expanded_bin_paths ||= begin
paths = expanded_gem_paths.map{|path| File.join(path, "bin") }
paths << RbConfig::CONFIG["bindir"]
paths
end
end
def try_to_install_binstubs(spec)
org_gem_path = expanded_gem_paths.find{|path|
File.exists? File.join path, 'gems', spec.full_name
} || Gem.dir
cache_gem = File.join(org_gem_path, 'cache', spec.file_name)
if File.exist? cache_gem
puts "#{spec.name} #{spec.version}"
inst = Gem::Installer.new Dir[cache_gem].first, :wrappers => true, :force => true, :install_dir => org_gem_path
ExecutableHooksInstaller.bundler_generate_bin(inst)
else
false
end
end
def expanded_gem_paths
@expanded_gem_paths ||=
Gem.path.map do |path|
paths = [path]
while File.symlink?(path)
path = File.readlink(path)
paths << path
end
paths
end.flatten
end
def installed_gems
if Gem::VERSION > '1.8' then
Gem::Specification.to_a
else
Gem.source_index.map{|name,spec| spec}
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkline.rb
|
<gh_stars>10-100
require "tkclass"
$tkline_init = FALSE
def start_random
return if $tkline_init
$tkline_init = TRUE
if defined? Thread
Thread.start do
loop do
sleep 2
Line.new($c, rand(400), rand(200), rand(400), rand(200))
end
end
end
end
Label.new('text'=>'Please press or drag button-1').pack
$c = Canvas.new
$c.pack
$start_x = start_y = 0
def do_press(x, y)
$start_x = x
$start_y = y
$current_line = Line.new($c, x, y, x, y)
start_random
end
def do_motion(x, y)
if $current_line
$current_line.coords $start_x, $start_y, x, y
end
end
def do_release(x, y)
if $current_line
$current_line.coords $start_x, $start_y, x, y
$current_line.fill 'black'
$current_line = nil
end
end
$c.bind("1", proc{|e| do_press e.x, e.y})
$c.bind("B1-Motion", proc{|x, y| do_motion x, y}, "%x %y")
$c.bind("ButtonRelease-1", proc{|x, y| do_release x, y}, "%x %y")
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rubygems/commands/generate_index_command.rb
|
# frozen_string_literal: false
require 'rubygems/command'
require 'rubygems/indexer'
##
# Generates a index files for use as a gem server.
#
# See `gem help generate_index`
class Gem::Commands::GenerateIndexCommand < Gem::Command
def initialize
super 'generate_index',
'Generates the index files for a gem server directory',
:directory => '.', :build_modern => true
add_option '-d', '--directory=DIRNAME',
'repository base dir containing gems subdir' do |dir, options|
options[:directory] = File.expand_path dir
end
add_option '--[no-]modern',
'Generate indexes for RubyGems',
'(always true)' do |value, options|
options[:build_modern] = value
end
add_option '--update',
'Update modern indexes with gems added',
'since the last update' do |value, options|
options[:update] = value
end
end
def defaults_str # :nodoc:
"--directory . --modern"
end
def description # :nodoc:
<<-EOF
The generate_index command creates a set of indexes for serving gems
statically. The command expects a 'gems' directory under the path given to
the --directory option. The given directory will be the directory you serve
as the gem repository.
For `gem generate_index --directory /path/to/repo`, expose /path/to/repo via
your HTTP server configuration (not /path/to/repo/gems).
When done, it will generate a set of files like this:
gems/*.gem # .gem files you want to
# index
specs.<version>.gz # specs index
latest_specs.<version>.gz # latest specs index
prerelease_specs.<version>.gz # prerelease specs index
quick/Marshal.<version>/<gemname>.gemspec.rz # Marshal quick index file
The .rz extension files are compressed with the inflate algorithm.
The Marshal version number comes from ruby's Marshal::MAJOR_VERSION and
Marshal::MINOR_VERSION constants. It is used to ensure compatibility.
EOF
end
def execute
# This is always true because it's the only way now.
options[:build_modern] = true
if not File.exist?(options[:directory]) or
not File.directory?(options[:directory]) then
alert_error "unknown directory name #{directory}."
terminate_interaction 1
else
indexer = Gem::Indexer.new options.delete(:directory), options
if options[:update] then
indexer.update_index
else
indexer.generate_index
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/systemu-2.6.5/samples/b.rb
|
<gh_stars>100-1000
#
# quite a few keys can be passed to the command to alter it's behaviour. if
# either stdout or stderr is supplied those objects should respond_to? '<<'
# and only status will be returned
#
require 'systemu'
date = %q( ruby -e" t = Time.now; STDOUT.puts t; STDERR.puts t " )
stdout, stderr = '', ''
status = systemu date, 'stdout' => stdout, 'stderr' => stderr
p [ status, stdout, stderr ]
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/labeledframe.rb
|
<gh_stars>10-100
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
lf = Tk::Iwidgets::Labeledframe.new(:labeltext=>'Entry Frame', :labelpos=>:n)
lf.pack(:fill=>:both, :expand=>true, :padx=>10, :pady=>10)
cs = lf.child_site
Tk::Iwidgets::Entryfield.new(cs, :labeltext=>'Name:').pack(:side=>:top, :fill=>:x)
Tk::Iwidgets::Spinint.new(cs, :labeltext=>'Number:').pack(:side=>:top, :fill=>:x)
Tk::Iwidgets::Pushbutton.new(cs, :text=>'Details:').pack(:side=>:top, :fill=>:x)
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/-test-/array/resize/extconf.rb
|
<reponame>arnab0073/idea<gh_stars>0
create_makefile("-test-/array/resize")
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/markup/inline.rb
|
# frozen_string_literal: false
warn "requiring rdoc/markup/inline is deprecated and will be removed in RDoc 4." if $-w
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkclass.rb
|
#
# tkclass.rb - Tk classes
# Date: 2000/11/27 09:23:36
# by <NAME> <<EMAIL>>
#
# $Id: tkclass.rb 25189 2009-10-02 12:04:37Z akr $
require "tk"
TopLevel = TkToplevel
Frame = TkFrame
Label = TkLabel
Button = TkButton
Radiobutton = TkRadioButton
Checkbutton = TkCheckButton
Message = TkMessage
Entry = TkEntry
Spinbox = TkSpinbox
Text = TkText
Scale = TkScale
Scrollbar = TkScrollbar
Listbox = TkListbox
Menu = TkMenu
Menubutton = TkMenubutton
Canvas = TkCanvas
Arc = TkcArc
Bitmap = TkcBitmap
Line = TkcLine
Oval = TkcOval
Polygon = TkcPolygon
Rectangle = TkcRectangle
TextItem = TkcText
WindowItem = TkcWindow
BitmapImage = TkBitmapImage
PhotoImage = TkPhotoImage
Selection = TkSelection
Winfo = TkWinfo
Pack = TkPack
Grid = TkGrid
Place = TkPlace
Variable = TkVariable
Font = TkFont
VirtualEvent = TkVirtualEvent
def Mainloop
Tk.mainloop
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/checkbox.rb
|
<gh_stars>10-100
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
cb = Tk::Iwidgets::Checkbox.new
cb.add('bold', :text=>'Bold')
cb.add('italic', :text=>'Italic')
cb.add('underline', :text=>'Underline')
cb.select('underline')
cb.pack(:expand=>true, :fill=>:both, :padx=>10, :pady=>10)
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/lib/zombie_hunter.rb
|
# frozen_string_literal: false
module ZombieHunter
def after_teardown
super
assert_empty(Process.waitall)
end
end
Test::Unit::TestCase.include ZombieHunter
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/fix_openssl_warnings.rb
|
<filename>.rvm/src/ruby-2.3.0/test/rubygems/fix_openssl_warnings.rb
# frozen_string_literal: false
##
# HACK: this drives me BONKERS
if defined? OpenSSL then
class OpenSSL::X509::ExtensionFactory
alias :old_create_ext :create_ext
def create_ext(*args)
@config ||= nil
old_create_ext(*args)
end
end
end if RUBY_VERSION < "1.9"
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/code_objects.rb
|
# frozen_string_literal: false
# This file was used to load all the RDoc::CodeObject subclasses at once. Now
# autoload handles this.
require 'rdoc'
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/message/type1.rb
|
<reponame>arnab0073/idea
module Net
module NTLM
class Message
# @private false
class Type1 < Message
string :sign, {:size => 8, :value => SSP_SIGN}
int32LE :type, {:value => 1}
int32LE :flag, {:value => DEFAULT_FLAGS[:TYPE1] }
security_buffer :domain, {:value => ""}
security_buffer :workstation, {:value => Socket.gethostname }
string :os_version, {:size => 8, :value => "", :active => false }
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/specifications/knife-windows-1.4.1.gemspec
|
# -*- encoding: utf-8 -*-
# stub: knife-windows 1.4.1 ruby lib
Gem::Specification.new do |s|
s.name = "knife-windows"
s.version = "1.4.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["<NAME>"]
s.date = "2016-05-04"
s.description = "Plugin that adds functionality to Chef's Knife CLI for configuring/interacting with nodes running Microsoft Windows"
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/chef/knife-windows"
s.licenses = ["Apache-2.0"]
s.required_ruby_version = Gem::Requirement.new(">= 1.9.1")
s.rubygems_version = "2.5.1"
s.summary = "Plugin that adds functionality to Chef's Knife CLI for configuring/interacting with nodes running Microsoft Windows"
s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<winrm>, ["~> 1.7"])
s.add_development_dependency(%q<pry>, [">= 0"])
else
s.add_dependency(%q<winrm>, ["~> 1.7"])
s.add_dependency(%q<pry>, [">= 0"])
end
else
s.add_dependency(%q<winrm>, ["~> 1.7"])
s.add_dependency(%q<pry>, [">= 0"])
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/zlib/extconf.rb
|
#
# extconf.rb
#
# $Id: extconf.rb 37561 2012-11-08 08:34:18Z usa $
#
require 'mkmf'
require 'rbconfig'
dir_config 'zlib'
if %w'z libz zlib1 zlib zdll zlibwapi'.find {|z| have_library(z, 'deflateReset')} and
have_header('zlib.h') then
defines = []
message 'checking for kind of operating system... '
os_code = with_config('os-code') ||
case RUBY_PLATFORM.split('-',2)[1]
when 'amigaos' then
os_code = 'AMIGA'
when /\Aos2[\-_]emx\z/ then
os_code = 'OS2'
when /mswin|mingw|bccwin/ then
# NOTE: cygwin should be regarded as Unix.
os_code = 'WIN32'
else
os_code = 'UNIX'
end
os_code = 'OS_' + os_code.upcase
OS_NAMES = {
'OS_MSDOS' => 'MS-DOS',
'OS_AMIGA' => 'Amiga',
'OS_VMS' => 'VMS',
'OS_UNIX' => 'Unix',
'OS_ATARI' => 'Atari',
'OS_OS2' => 'OS/2',
'OS_MACOS' => 'MacOS',
'OS_TOPS20' => 'TOPS20',
'OS_WIN32' => 'Win32',
'OS_VMCMS' => 'VM/CMS',
'OS_ZSYSTEM' => 'Z-System',
'OS_CPM' => 'CP/M',
'OS_QDOS' => 'QDOS',
'OS_RISCOS' => 'RISCOS',
'OS_UNKNOWN' => 'Unknown',
}
unless OS_NAMES.key? os_code then
raise "invalid OS_CODE `#{os_code}'"
end
message "#{OS_NAMES[os_code]}\n"
defines << "OS_CODE=#{os_code}"
$defs.concat(defines.collect{|d|' -D'+d})
have_func('crc32_combine', 'zlib.h')
have_func('adler32_combine', 'zlib.h')
have_type('z_crc_t', 'zlib.h')
create_makefile('zlib')
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/sample/pty/expect_sample.rb
|
#
# sample program of expect.rb
#
# by <NAME>
#
# 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).*: |(word):|> /) do
w_f.puts($1 ? "ftp" : $2 ? "#{username}@" : "cd pub/ruby")
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"
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/lib/tkextlib/bwidget/progressdlg.rb
|
<filename>.rvm/src/ruby-2.3.0/ext/tk/lib/tkextlib/bwidget/progressdlg.rb
# frozen_string_literal: false
#
# tkextlib/bwidget/progressdlg.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/variable'
require 'tkextlib/bwidget.rb'
require 'tkextlib/bwidget/progressbar'
require 'tkextlib/bwidget/messagedlg'
module Tk
module BWidget
class ProgressDlg < Tk::BWidget::MessageDlg
end
end
end
class Tk::BWidget::ProgressDlg
TkCommandNames = ['ProgressDlg'.freeze].freeze
WidgetClassName = 'ProgressDlg'.freeze
WidgetClassNames[WidgetClassName] ||= self
def create_self(keys)
# NOT create widget for reusing the object
super(keys)
@keys['textvariable'] = TkVariable.new unless @keys.key?('textvariable')
@keys['variable'] = TkVariable.new unless @keys.key?('variable')
end
def textvariable
@keys['textvariable']
end
def text
@keys['textvariable'].value
end
def text= (txt)
@keys['textvariable'].value = txt
end
def variable
@keys['variable']
end
def value
@keys['variable'].value
end
def value= (val)
@keys['variable'].value = val
end
def create
window(tk_call(self.class::TkCommandNames[0], @path, *hash_kv(@keys)))
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/syck/extconf.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/syck/extconf.rb
require 'mkmf'
have_header( "st.h" )
create_makefile( "syck" )
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/benchmark/bm_so_meteor_contest.rb
|
<gh_stars>10-100
#!/usr/bin/env ruby
#
# The Computer Language Shootout
# http://shootout.alioth.debian.org
# contributed by <NAME> (Ruby novice)
# PROGRAM: the main body is at the bottom.
# 1) read about the problem here: http://www-128.ibm.com/developerworks/java/library/j-javaopt/
# 2) see how I represent a board as a bitmask by reading the blank_board comments
# 3) read as your mental paths take you
def print *args
end
# class to represent all information about a particular rotation of a particular piece
class Rotation
# an array (by location) containing a bit mask for how the piece maps at the given location.
# if the rotation is invalid at that location the mask will contain false
attr_reader :start_masks
# maps a direction to a relative location. these differ depending on whether it is an even or
# odd row being mapped from
@@rotation_even_adder = { :west => -1, :east => 1, :nw => -7, :ne => -6, :sw => 5, :se => 6 }
@@rotation_odd_adder = { :west => -1, :east => 1, :nw => -6, :ne => -5, :sw => 6, :se => 7 }
def initialize( directions )
@even_offsets, @odd_offsets = normalize_offsets( get_values( directions ))
@even_mask = mask_for_offsets( @even_offsets)
@odd_mask = mask_for_offsets( @odd_offsets)
@start_masks = Array.new(60)
# create the rotational masks by placing the base mask at the location and seeing if
# 1) it overlaps the boundries and 2) it produces a prunable board. if either of these
# is true the piece cannot be placed
0.upto(59) do | offset |
mask = is_even(offset) ? (@even_mask << offset) : (@odd_mask << offset)
if (blank_board & mask == 0 && !prunable(blank_board | mask, 0, true)) then
imask = compute_required( mask, offset)
@start_masks[offset] = [ mask, imask, imask | mask ]
else
@start_masks[offset] = false
end
end
end
def compute_required( mask, offset )
board = blank_board
0.upto(offset) { | i | board |= 1 << i }
board |= mask
return 0 if (!prunable(board | mask, offset))
board = flood_fill(board,58)
count = 0
imask = 0
0.upto(59) do | i |
if (board[i] == 0) then
imask |= (1 << i)
count += 1
end
end
(count > 0 && count < 5) ? imask : 0
end
def flood_fill( board, location)
return board if (board[location] == 1)
board |= 1 << location
row, col = location.divmod(6)
board = flood_fill( board, location - 1) if (col > 0)
board = flood_fill( board, location + 1) if (col < 4)
if (row % 2 == 0) then
board = flood_fill( board, location - 7) if (col > 0 && row > 0)
board = flood_fill( board, location - 6) if (row > 0)
board = flood_fill( board, location + 6) if (row < 9)
board = flood_fill( board, location + 5) if (col > 0 && row < 9)
else
board = flood_fill( board, location - 5) if (col < 4 && row > 0)
board = flood_fill( board, location - 6) if (row > 0)
board = flood_fill( board, location + 6) if (row < 9)
board = flood_fill( board, location + 7) if (col < 4 && row < 9)
end
board
end
# given a location, produces a list of relative locations covered by the piece at this rotation
def offsets( location)
if is_even( location) then
@even_offsets.collect { | value | value + location }
else
@odd_offsets.collect { | value | value + location }
end
end
# returns a set of offsets relative to the top-left most piece of the rotation (by even or odd rows)
# this is hard to explain. imagine we have this partial board:
# 0 0 0 0 0 x [positions 0-5]
# 0 0 1 1 0 x [positions 6-11]
# 0 0 1 0 0 x [positions 12-17]
# 0 1 0 0 0 x [positions 18-23]
# 0 1 0 0 0 x [positions 24-29]
# 0 0 0 0 0 x [positions 30-35]
# ...
# The top-left of the piece is at position 8, the
# board would be passed as a set of positions (values array) containing [8,9,14,19,25] not necessarily in that
# sorted order. Since that array starts on an odd row, the offsets for an odd row are: [0,1,6,11,17] obtained
# by subtracting 8 from everything. Now imagine the piece shifted up and to the right so it's on an even row:
# 0 0 0 1 1 x [positions 0-5]
# 0 0 1 0 0 x [positions 6-11]
# 0 0 1 0 0 x [positions 12-17]
# 0 1 0 0 0 x [positions 18-23]
# 0 0 0 0 0 x [positions 24-29]
# 0 0 0 0 0 x [positions 30-35]
# ...
# Now the positions are [3,4,8,14,19] which after subtracting the lowest value (3) gives [0,1,5,11,16] thus, the
# offsets for this particular piece are (in even, odd order) [0,1,5,11,16],[0,1,6,11,17] which is what
# this function would return
def normalize_offsets( values)
min = values.min
even_min = is_even(min)
other_min = even_min ? min + 6 : min + 7
other_values = values.collect do | value |
if is_even(value) then
value + 6 - other_min
else
value + 7 - other_min
end
end
values.collect! { | value | value - min }
if even_min then
[values, other_values]
else
[other_values, values]
end
end
# produce a bitmask representation of an array of offset locations
def mask_for_offsets( offsets )
mask = 0
offsets.each { | value | mask = mask + ( 1 << value ) }
mask
end
# finds a "safe" position that a position as described by a list of directions can be placed
# without falling off any edge of the board. the values returned a location to place the first piece
# at so it will fit after making the described moves
def start_adjust( directions )
south = east = 0;
directions.each do | direction |
east += 1 if ( direction == :sw || direction == :nw || direction == :west )
south += 1 if ( direction == :nw || direction == :ne )
end
south * 6 + east
end
# given a set of directions places the piece (as defined by a set of directions) on the board at
# a location that will not take it off the edge
def get_values ( directions )
start = start_adjust(directions)
values = [ start ]
directions.each do | direction |
if (start % 12 >= 6) then
start += @@rotation_odd_adder[direction]
else
start += @@rotation_even_adder[direction]
end
values += [ start ]
end
# some moves take you back to an existing location, we'll strip duplicates
values.uniq
end
end
# describes a piece and caches information about its rotations to as to be efficient for iteration
# ATTRIBUTES:
# rotations -- all the rotations of the piece
# type -- a numeic "name" of the piece
# masks -- an array by location of all legal rotational masks (a n inner array) for that location
# placed -- the mask that this piece was last placed at (not a location, but the actual mask used)
class Piece
attr_reader :rotations, :type, :masks
attr_accessor :placed
# transform hashes that change one direction into another when you either flip or rotate a set of directions
@@flip_converter = { :west => :west, :east => :east, :nw => :sw, :ne => :se, :sw => :nw, :se => :ne }
@@rotate_converter = { :west => :nw, :east => :se, :nw => :ne, :ne => :east, :sw => :west, :se => :sw }
def initialize( directions, type )
@type = type
@rotations = Array.new();
@map = {}
generate_rotations( directions )
directions.collect! { | value | @@flip_converter[value] }
generate_rotations( directions )
# creates the masks AND a map that returns [location, rotation] for any given mask
# this is used when a board is found and we want to draw it, otherwise the map is unused
@masks = Array.new();
0.upto(59) do | i |
even = true
@masks[i] = @rotations.collect do | rotation |
mask = rotation.start_masks[i]
@map[mask[0]] = [ i, rotation ] if (mask)
mask || nil
end
@masks[i].compact!
end
end
# rotates a set of directions through all six angles and adds a Rotation to the list for each one
def generate_rotations( directions )
6.times do
rotations.push( Rotation.new(directions))
directions.collect! { | value | @@rotate_converter[value] }
end
end
# given a board string, adds this piece to the board at whatever location/rotation
# important: the outbound board string is 5 wide, the normal location notation is six wide (padded)
def fill_string( board_string)
location, rotation = @map[@placed]
rotation.offsets(location).each do | offset |
row, col = offset.divmod(6)
board_string[ row*5 + col, 1 ] = @type.to_s
end
end
end
# a blank bit board having this form:
#
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 0 0 0 0 0 1
# 1 1 1 1 1 1
#
# where left lest significant bit is the top left and the most significant is the lower right
# the actual board only consists of the 0 places, the 1 places are blockers to keep things from running
# off the edges or bottom
def blank_board
0b111111100000100000100000100000100000100000100000100000100000100000
end
def full_board
0b111111111111111111111111111111111111111111111111111111111111111111
end
# determines if a location (bit position) is in an even row
def is_even( location)
(location % 12) < 6
end
# support function that create three utility maps:
# $converter -- for each row an array that maps a five bit row (via array mapping)
# to the a a five bit representation of the bits below it
# $bit_count -- maps a five bit row (via array mapping) to the number of 1s in the row
# @@new_regions -- maps a five bit row (via array mapping) to an array of "region" arrays
# a region array has three values the first is a mask of bits in the region,
# the second is the count of those bits and the third is identical to the first
# examples:
# 0b10010 => [ 0b01100, 2, 0b01100 ], [ 0b00001, 1, 0b00001]
# 0b01010 => [ 0b10000, 1, 0b10000 ], [ 0b00100, 1, 0b00100 ], [ 0b00001, 1, 0b00001]
# 0b10001 => [ 0b01110, 3, 0b01110 ]
def create_collector_support
odd_map = [0b11, 0b110, 0b1100, 0b11000, 0b10000]
even_map = [0b1, 0b11, 0b110, 0b1100, 0b11000]
all_odds = Array.new(0b100000)
all_evens = Array.new(0b100000)
bit_counts = Array.new(0b100000)
new_regions = Array.new(0b100000)
0.upto(0b11111) do | i |
bit_count = odd = even = 0
0.upto(4) do | bit |
if (i[bit] == 1) then
bit_count += 1
odd |= odd_map[bit]
even |= even_map[bit]
end
end
all_odds[i] = odd
all_evens[i] = even
bit_counts[i] = bit_count
new_regions[i] = create_regions( i)
end
$converter = []
10.times { | row | $converter.push((row % 2 == 0) ? all_evens : all_odds) }
$bit_counts = bit_counts
$regions = new_regions.collect { | set | set.collect { | value | [ value, bit_counts[value], value] } }
end
# determines if a board is punable, meaning that there is no possibility that it
# can be filled up with pieces. A board is prunable if there is a grouping of unfilled spaces
# that are not a multiple of five. The following board is an example of a prunable board:
# 0 0 1 0 0
# 0 1 0 0 0
# 1 1 0 0 0
# 0 1 0 0 0
# 0 0 0 0 0
# ...
#
# This board is prunable because the top left corner is only 3 bits in area, no piece will ever fit it
# parameters:
# board -- an initial bit board (6 bit padded rows, see blank_board for format)
# location -- starting location, everything above and to the left is already full
# slotting -- set to true only when testing initial pieces, when filling normally
# additional assumptions are possible
#
# Algorithm:
# The algorithm starts at the top row (as determined by location) and iterates a row at a time
# maintainng counts of active open areas (kept in the collector array) each collector contains
# three values at the start of an iteration:
# 0: mask of bits that would be adjacent to the collector in this row
# 1: the number of bits collected so far
# 2: a scratch space starting as zero, but used during the computation to represent
# the empty bits in the new row that are adjacent (position 0)
# The exact procedure is described in-code
def prunable( board, location, slotting = false)
collectors = []
# loop accross the rows
(location / 6).to_i.upto(9) do | row_on |
# obtain a set of regions representing the bits of the curent row.
regions = $regions[(board >> (row_on * 6)) & 0b11111]
converter = $converter[row_on]
# track the number of collectors at the start of the cycle so that
# we don't compute against newly created collectors, only existing collectors
initial_collector_count = collectors.length
# loop against the regions. For each region of the row
# we will see if it connects to one or more existing collectors.
# if it connects to 1 collector, the bits from the region are added to the
# bits of the collector and the mask is placed in collector[2]
# If the region overlaps more than one collector then all the collectors
# it overlaps with are merged into the first one (the others are set to nil in the array)
# if NO collectors are found then the region is copied as a new collector
regions.each do | region |
collector_found = nil
region_mask = region[2]
initial_collector_count.times do | collector_num |
collector = collectors[collector_num]
if (collector) then
collector_mask = collector[0]
if (collector_mask & region_mask != 0) then
if (collector_found) then
collector_found[0] |= collector_mask
collector_found[1] += collector[1]
collector_found[2] |= collector[2]
collectors[collector_num] = nil
else
collector_found = collector
collector[1] += region[1]
collector[2] |= region_mask
end
end
end
end
if (collector_found == nil) then
collectors.push(Array.new(region))
end
end
# check the existing collectors, if any collector overlapped no bits in the region its [2] value will
# be zero. The size of any such reaason is tested if it is not a muliple of five true is returned since
# the board is prunable. if it is a multiple of five it is removed.
# Collector that are still active have a new adjacent value [0] set based n the matched bits
# and have [2] cleared out for the next cycle.
collectors.length.times do | collector_num |
collector = collectors[collector_num]
if (collector) then
if (collector[2] == 0) then
return true if (collector[1] % 5 != 0)
collectors[collector_num] = nil
else
# if a collector matches all bits in the row then we can return unprunable early for the
# follwing reasons:
# 1) there can be no more unavailable bits bince we fill from the top left downward
# 2) all previous regions have been closed or joined so only this region can fail
# 3) this region must be good since there can never be only 1 region that is nuot
# a multiple of five
# this rule only applies when filling normally, so we ignore the rule if we are "slotting"
# in pieces to see what configurations work for them (the only other time this algorithm is used).
return false if (collector[2] == 0b11111 && !slotting)
collector[0] = converter[collector[2]]
collector[2] = 0
end
end
end
# get rid of all the empty converters for the next round
collectors.compact!
end
return false if (collectors.length <= 1) # 1 collector or less and the region is fine
collectors.any? { | collector | (collector[1] % 5) != 0 } # more than 1 and we test them all for bad size
end
# creates a region given a row mask. see prunable for what a "region" is
def create_regions( value )
regions = []
cur_region = 0
5.times do | bit |
if (value[bit] == 0) then
cur_region |= 1 << bit
else
if (cur_region != 0 ) then
regions.push( cur_region)
cur_region = 0;
end
end
end
regions.push(cur_region) if (cur_region != 0)
regions
end
# find up to the counted number of solutions (or all solutions) and prints the final result
def find_all
find_top( 1)
find_top( 0)
print_results
end
# show the board
def print_results
print "#{@boards_found} solutions found\n\n"
print_full_board( @min_board)
print "\n"
print_full_board( @max_board)
print "\n"
end
# finds solutions. This special version of the main function is only used for the top level
# the reason for it is basically to force a particular ordering on how the rotations are tested for
# the first piece. It is called twice, first looking for placements of the odd rotations and then
# looking for placements of the even locations.
#
# WHY?
# Since any found solution has an inverse we want to maximize finding solutions that are not already found
# as an inverse. The inverse will ALWAYS be 3 one of the piece configurations that is exactly 3 rotations away
# (an odd number). Checking even vs odd then produces a higher probability of finding more pieces earlier
# in the cycle. We still need to keep checking all the permutations, but our probability of finding one will
# diminsh over time. Since we are TOLD how many to search for this lets us exit before checking all pieces
# this bennifit is very great when seeking small numbers of solutions and is 0 when looking for more than the
# maximum number
def find_top( rotation_skip)
board = blank_board
(@pieces.length-1).times do
piece = @pieces.shift
piece.masks[0].each do | mask, imask, cmask |
if ((rotation_skip += 1) % 2 == 0) then
piece.placed = mask
find( 1, 1, board | mask)
end
end
@pieces.push(piece)
end
piece = @pieces.shift
@pieces.push(piece)
end
# the normail find routine, iterates through the available pieces, checks all rotations at the current location
# and adds any boards found. depth is acheived via recursion. the overall approach is described
# here: http://www-128.ibm.com/developerworks/java/library/j-javaopt/
# parameters:
# start_location -- where to start looking for place for the next piece at
# placed -- number of pieces placed
# board -- current state of the board
#
# see in-code comments
def find( start_location, placed, board)
# find the next location to place a piece by looking for an empty bit
while board[start_location] == 1
start_location += 1
end
@pieces.length.times do
piece = @pieces.shift
piece.masks[start_location].each do | mask, imask, cmask |
if ( board & cmask == imask) then
piece.placed = mask
if (placed == 9) then
add_board
else
find( start_location + 1, placed + 1, board | mask)
end
end
end
@pieces.push(piece)
end
end
# print the board
def print_full_board( board_string)
10.times do | row |
print " " if (row % 2 == 1)
5.times do | col |
print "#{board_string[row*5 + col,1]} "
end
print "\n"
end
end
# when a board is found we "draw it" into a string and then flip that string, adding both to
# the list (hash) of solutions if they are unique.
def add_board
board_string = "99999999999999999999999999999999999999999999999999"
@all_pieces.each { | piece | piece.fill_string( board_string ) }
save( board_string)
save( board_string.reverse)
end
# adds a board string to the list (if new) and updates the current best/worst board
def save( board_string)
if (@all_boards[board_string] == nil) then
@min_board = board_string if (board_string < @min_board)
@max_board = board_string if (board_string > @max_board)
@all_boards.store(board_string,true)
@boards_found += 1
# the exit motif is a time saver. Ideally the function should return, but those tests
# take noticable time (performance).
if (@boards_found == @stop_count) then
print_results
exit(0)
end
end
end
##
## MAIN BODY :)
##
create_collector_support
@pieces = [
Piece.new( [ :nw, :ne, :east, :east ], 2),
Piece.new( [ :ne, :se, :east, :ne ], 7),
Piece.new( [ :ne, :east, :ne, :nw ], 1),
Piece.new( [ :east, :sw, :sw, :se ], 6),
Piece.new( [ :east, :ne, :se, :ne ], 5),
Piece.new( [ :east, :east, :east, :se ], 0),
Piece.new( [ :ne, :nw, :se, :east, :se ], 4),
Piece.new( [ :se, :se, :se, :west ], 9),
Piece.new( [ :se, :se, :east, :se ], 8),
Piece.new( [ :east, :east, :sw, :se ], 3)
];
@all_pieces = Array.new( @pieces)
@min_board = "99999999999999999999999999999999999999999999999999"
@max_board = "00000000000000000000000000000000000000000000000000"
@stop_count = ARGV[0].to_i || 2089
@all_boards = {}
@boards_found = 0
find_all ######## DO IT!!!
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/lib/puma/server.rb
|
<gh_stars>0
require 'rack'
require 'stringio'
require 'puma/thread_pool'
require 'puma/const'
require 'puma/events'
require 'puma/null_io'
require 'puma/compat'
require 'puma/reactor'
require 'puma/client'
require 'puma/puma_http11'
require 'socket'
module Puma
# The HTTP Server itself. Serves out a single Rack app.
class Server
include Puma::Const
attr_reader :thread
attr_reader :events
attr_accessor :app
attr_accessor :min_threads
attr_accessor :max_threads
attr_accessor :persistent_timeout
attr_accessor :auto_trim_time
# Create a server for the rack app +app+.
#
# +events+ is an object which will be called when certain error events occur
# to be handled. See Puma::Events for the list of current methods to implement.
#
# Server#run returns a thread that you can join on to wait for the server
# to do it's work.
#
def initialize(app, events=Events::DEFAULT)
@app = app
@events = events
@check, @notify = IO.pipe
@ios = [@check]
@status = :stop
@min_threads = 0
@max_threads = 16
@auto_trim_time = 1
@thread = nil
@thread_pool = nil
@persistent_timeout = PERSISTENT_TIMEOUT
@persistent_check, @persistent_wakeup = IO.pipe
@first_data_timeout = FIRST_DATA_TIMEOUT
@unix_paths = []
@proto_env = {
"rack.version".freeze => Rack::VERSION,
"rack.errors".freeze => events.stderr,
"rack.multithread".freeze => true,
"rack.multiprocess".freeze => false,
"rack.run_once".freeze => false,
"SCRIPT_NAME".freeze => ENV['SCRIPT_NAME'] || "",
# Rack blows up if this is an empty string, and Rack::Lint
# blows up if it's nil. So 'text/plain' seems like the most
# sensible default value.
"CONTENT_TYPE".freeze => "text/plain",
"QUERY_STRING".freeze => "",
SERVER_PROTOCOL => HTTP_11,
SERVER_SOFTWARE => PUMA_VERSION,
GATEWAY_INTERFACE => CGI_VER
}
@envs = {}
ENV['RACK_ENV'] ||= "development"
end
# On Linux, use TCP_CORK to better control how the TCP stack
# packetizes our stream. This improves both latency and throughput.
#
if RUBY_PLATFORM =~ /linux/
# 6 == Socket::IPPROTO_TCP
# 3 == TCP_CORK
# 1/0 == turn on/off
def cork_socket(socket)
socket.setsockopt(6, 3, 1) if socket.kind_of? TCPSocket
end
def uncork_socket(socket)
socket.setsockopt(6, 3, 0) if socket.kind_of? TCPSocket
end
else
def cork_socket(socket)
end
def uncork_socket(socket)
end
end
# Tell the server to listen on host +host+, port +port+.
# If +optimize_for_latency+ is true (the default) then clients connecting
# will be optimized for latency over throughput.
#
# +backlog+ indicates how many unaccepted connections the kernel should
# allow to accumulate before returning connection refused.
#
def add_tcp_listener(host, port, optimize_for_latency=true, backlog=1024)
s = TCPServer.new(host, port)
if optimize_for_latency
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
s.listen backlog
@ios << s
s
end
def inherit_tcp_listener(host, port, fd)
s = TCPServer.for_fd(fd)
@ios << s
s
end
def add_ssl_listener(host, port, ctx, optimize_for_latency=true, backlog=1024)
s = TCPServer.new(host, port)
if optimize_for_latency
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
s.listen backlog
ssl = OpenSSL::SSL::SSLServer.new(s, ctx)
env = @proto_env.dup
env[HTTPS_KEY] = HTTPS
@envs[ssl] = env
@ios << ssl
s
end
def inherited_ssl_listener(fd, ctx)
s = TCPServer.for_fd(fd)
@ios << OpenSSL::SSL::SSLServer.new(s, ctx)
s
end
# Tell the server to listen on +path+ as a UNIX domain socket.
#
def add_unix_listener(path, umask=nil)
@unix_paths << path
# Let anyone connect by default
umask ||= 0
begin
old_mask = File.umask(umask)
s = UNIXServer.new(path)
@ios << s
ensure
File.umask old_mask
end
s
end
def inherit_unix_listener(path, fd)
@unix_paths << path
s = UNIXServer.for_fd fd
@ios << s
s
end
def backlog
@thread_pool and @thread_pool.backlog
end
def running
@thread_pool and @thread_pool.spawned
end
# Runs the server.
#
# If +background+ is true (the default) then a thread is spun
# up in the background to handle requests. Otherwise requests
# are handled synchronously.
#
def run(background=true)
BasicSocket.do_not_reverse_lookup = true
@status = :run
@thread_pool = ThreadPool.new(@min_threads, @max_threads) do |client|
process_now = false
begin
process_now = client.eagerly_finish
rescue HttpParserError => e
client.close
@events.parse_error self, client.env, e
rescue IOError
client.close
else
if process_now
process_client client
else
client.set_timeout @first_data_timeout
@reactor.add client
end
end
end
@reactor = Reactor.new self, @thread_pool
@reactor.run_in_thread
if @auto_trim_time
@thread_pool.auto_trim!(@auto_trim_time)
end
if background
@thread = Thread.new { handle_servers }
return @thread
else
handle_servers
end
end
def handle_servers
begin
check = @check
sockets = @ios
pool = @thread_pool
while @status == :run
begin
ios = IO.select sockets
ios.first.each do |sock|
if sock == check
break if handle_check
else
c = Client.new sock.accept, @envs.fetch(sock, @proto_env)
pool << c
end
end
rescue Errno::ECONNABORTED
# client closed the socket even before accept
client.close rescue nil
rescue Object => e
@events.unknown_error self, e, "Listen loop"
end
end
@reactor.clear! if @status == :restart
@reactor.shutdown
graceful_shutdown if @status == :stop
ensure
unless @status == :restart
@ios.each { |i| i.close }
@unix_paths.each { |i| File.unlink i }
end
end
end
# :nodoc:
def handle_check
cmd = @check.read(1)
case cmd
when STOP_COMMAND
@status = :stop
return true
when HALT_COMMAND
@status = :halt
return true
when RESTART_COMMAND
@status = :restart
return true
end
return false
end
# Given a connection on +client+, handle the incoming requests.
#
# This method support HTTP Keep-Alive so it may, depending on if the client
# indicates that it supports keep alive, wait for another request before
# returning.
#
def process_client(client)
begin
close_socket = true
while true
case handle_request(client)
when false
return
when :async
close_socket = false
return
when true
unless client.reset
close_socket = false
client.set_timeout @persistent_timeout
@reactor.add client
return
end
end
end
# The client disconnected while we were reading data
rescue IOError, SystemCallError => e
# Swallow them. The ensure tries to close +client+ down
# The client doesn't know HTTP well
rescue HttpParserError => e
@events.parse_error self, client.env, e
# Server error
rescue StandardError => e
@events.unknown_error self, e, "Read"
ensure
begin
client.close if close_socket
rescue IOError, SystemCallError
# Already closed
rescue StandardError => e
@events.unknown_error self, e, "Client"
end
end
end
# Given a Hash +env+ for the request read from +client+, add
# and fixup keys to comply with Rack's env guidelines.
#
def normalize_env(env, client)
if host = env[HTTP_HOST]
if colon = host.index(":")
env[SERVER_NAME] = host[0, colon]
env[SERVER_PORT] = host[colon+1, host.bytesize]
else
env[SERVER_NAME] = host
env[SERVER_PORT] = PORT_80
end
else
env[SERVER_NAME] = LOCALHOST
env[SERVER_PORT] = PORT_80
end
unless env[REQUEST_PATH]
# it might be a dumbass full host request header
uri = URI.parse(env[REQUEST_URI])
env[REQUEST_PATH] = uri.path
raise "No REQUEST PATH" unless env[REQUEST_PATH]
end
env[PATH_INFO] = env[REQUEST_PATH]
# From http://www.ietf.org/rfc/rfc3875 :
# "Script authors should be aware that the REMOTE_ADDR and
# REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
# may not identify the ultimate source of the request.
# They identify the client for the immediate request to the
# server; that client may be a proxy, gateway, or other
# intermediary acting on behalf of the actual source client."
#
env[REMOTE_ADDR] = client.peeraddr.last
end
# Given the request +env+ from +client+ and a partial request body
# in +body+, finish reading the body if there is one and invoke
# the rack app. Then construct the response and write it back to
# +client+
#
# +cl+ is the previously fetched Content-Length header if there
# was one. This is an optimization to keep from having to look
# it up again.
#
def handle_request(req)
env = req.env
client = req.io
normalize_env env, client
env[PUMA_SOCKET] = client
body = req.body
env[RACK_INPUT] = body
env[RACK_URL_SCHEME] = env[HTTPS_KEY] ? HTTPS : HTTP
# A rack extension. If the app writes #call'ables to this
# array, we will invoke them when the request is done.
#
after_reply = env[RACK_AFTER_REPLY] = []
begin
begin
status, headers, res_body = @app.call(env)
status = status.to_i
if status == -1
unless headers.empty? and res_body == []
raise "async response must have empty headers and body"
end
return :async
end
rescue => e
@events.unknown_error self, e, "Rack app"
status, headers, res_body = lowlevel_error(e)
end
content_length = nil
no_body = false
if res_body.kind_of? Array and res_body.size == 1
content_length = res_body[0].bytesize
end
cork_socket client
if env[HTTP_VERSION] == HTTP_11
allow_chunked = true
keep_alive = env[HTTP_CONNECTION] != CLOSE
include_keepalive_header = false
# An optimization. The most common response is 200, so we can
# reply with the proper 200 status without having to compute
# the response header.
#
if status == 200
client.write HTTP_11_200
else
client.write "HTTP/1.1 "
client.write status.to_s
client.write " "
client.write HTTP_STATUS_CODES[status]
client.write "\r\n"
no_body = status < 200 || STATUS_WITH_NO_ENTITY_BODY[status]
end
else
allow_chunked = false
keep_alive = env[HTTP_CONNECTION] == KEEP_ALIVE
include_keepalive_header = keep_alive
# Same optimization as above for HTTP/1.1
#
if status == 200
client.write HTTP_10_200
else
client.write "HTTP/1.0 "
client.write status.to_s
client.write " "
client.write HTTP_STATUS_CODES[status]
client.write "\r\n"
no_body = status < 200 || STATUS_WITH_NO_ENTITY_BODY[status]
end
end
colon = COLON
line_ending = LINE_END
headers.each do |k, vs|
case k
when CONTENT_LENGTH2
content_length = vs
next
when TRANSFER_ENCODING
allow_chunked = false
content_length = nil
when CONTENT_TYPE
next if no_body
end
vs.split(NEWLINE).each do |v|
client.write k
client.write colon
client.write v
client.write line_ending
end
end
if no_body
client.write line_ending
return keep_alive
end
if include_keepalive_header
client.write CONNECTION_KEEP_ALIVE
elsif !keep_alive
client.write CONNECTION_CLOSE
end
if content_length
client.write CONTENT_LENGTH_S
client.write content_length.to_s
client.write line_ending
chunked = false
elsif allow_chunked
client.write TRANSFER_ENCODING_CHUNKED
chunked = true
end
client.write line_ending
res_body.each do |part|
if chunked
client.write part.bytesize.to_s(16)
client.write line_ending
client.write part
client.write line_ending
else
client.write part
end
client.flush
end
if chunked
client.write CLOSE_CHUNKED
client.flush
end
ensure
uncork_socket client
body.close
res_body.close if res_body.respond_to? :close
after_reply.each { |o| o.call }
end
return keep_alive
end
# Given the requset +env+ from +client+ and the partial body +body+
# plus a potential Content-Length value +cl+, finish reading
# the body and return it.
#
# If the body is larger than MAX_BODY, a Tempfile object is used
# for the body, otherwise a StringIO is used.
#
def read_body(env, client, body, cl)
content_length = cl.to_i
remain = content_length - body.bytesize
return StringIO.new(body) if remain <= 0
# Use a Tempfile if there is a lot of data left
if remain > MAX_BODY
stream = Tempfile.new(Const::PUMA_TMP_BASE)
stream.binmode
else
# The body[0,0] trick is to get an empty string in the same
# encoding as body.
stream = StringIO.new body[0,0]
end
stream.write body
# Read an odd sized chunk so we can read even sized ones
# after this
chunk = client.readpartial(remain % CHUNK_SIZE)
# No chunk means a closed socket
unless chunk
stream.close
return nil
end
remain -= stream.write(chunk)
# Raed the rest of the chunks
while remain > 0
chunk = client.readpartial(CHUNK_SIZE)
unless chunk
stream.close
return nil
end
remain -= stream.write(chunk)
end
stream.rewind
return stream
end
# A fallback rack response if +@app+ raises as exception.
#
def lowlevel_error(e)
[500, {}, ["Puma caught this error: #{e}\n#{e.backtrace.join("\n")}"]]
end
# Wait for all outstanding requests to finish.
#
def graceful_shutdown
@thread_pool.shutdown if @thread_pool
end
# Stops the acceptor thread and then causes the worker threads to finish
# off the request queue before finally exiting.
#
def stop(sync=false)
@persistent_wakeup.close
@notify << STOP_COMMAND
@thread.join if @thread && sync
end
def halt(sync=false)
@persistent_wakeup.close
@notify << HALT_COMMAND
@thread.join if @thread && sync
end
def begin_restart
@persistent_wakeup.close
@notify << RESTART_COMMAND
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/lib/tk/msgcat.rb
|
<filename>.rvm/src/ruby-2.3.0/ext/tk/lib/tk/msgcat.rb<gh_stars>0
# frozen_string_literal: false
#
# tk/msgcat.rb : methods for Tcl message catalog
# by <NAME> <<EMAIL>>
#
require 'tk'
#class TkMsgCatalog
class TkMsgCatalog < TkObject
include TkCore
extend Tk
#extend TkMsgCatalog
TkCommandNames = [
'::msgcat::mc'.freeze,
'::msgcat::mcmax'.freeze,
'::msgcat::mclocale'.freeze,
'::msgcat::mcpreferences'.freeze,
'::msgcat::mcload'.freeze,
'::msgcat::mcset'.freeze,
'::msgcat::mcmset'.freeze,
'::msgcat::mcunknown'.freeze
].freeze
tk_call_without_enc('package', 'require', 'Tcl', '8.2')
PACKAGE_NAME = 'msgcat'.freeze
def self.package_name
PACKAGE_NAME
end
if self.const_defined? :FORCE_VERSION
tk_call_without_enc('package', 'require', 'msgcat', FORCE_VERSION)
else
tk_call_without_enc('package', 'require', 'msgcat')
end
MSGCAT_EXT = '.msg'
UNKNOWN_CBTBL = TkUtil.untrust(Hash.new{|hash,key| hash[key] = {}})
TkCore::INTERP.add_tk_procs('::msgcat::mcunknown', 'args', <<-'EOL')
if {[set st [catch {eval {ruby_cmd TkMsgCatalog callback} [namespace current] $args} ret]] != 0} {
#return -code $st $ret
set idx [string first "\n\n" $ret]
if {$idx > 0} {
return -code $st \
-errorinfo [string range $ret [expr $idx + 2] \
[string length $ret]] \
[string range $ret 0 [expr $idx - 1]]
} else {
return -code $st $ret
}
} else {
return $ret
}
EOL
def self.callback(namespace, locale, src_str, *args)
src_str = sprintf(src_str, *args) unless args.empty?
cmd_tbl = TkMsgCatalog::UNKNOWN_CBTBL[TkCore::INTERP.__getip]
cmd = cmd_tbl[namespace]
cmd = cmd_tbl['::'] unless cmd # use global scope as interp default
return src_str unless cmd # no cmd -> return src-str (default action)
begin
cmd.call(locale, src_str)
rescue SystemExit
exit(0)
rescue Interrupt
exit!(1)
rescue Exception => e
begin
msg = _toUTF8(e.class.inspect) + ': ' +
_toUTF8(e.message) + "\n" +
"\n---< backtrace of Ruby side >-----\n" +
_toUTF8(e.backtrace.join("\n")) +
"\n---< backtrace of Tk side >-------"
if TkCore::WITH_ENCODING
msg.force_encoding('utf-8')
else
msg.instance_variable_set(:@encoding, 'utf-8')
end
rescue Exception
msg = e.class.inspect + ': ' + e.message + "\n" +
"\n---< backtrace of Ruby side >-----\n" +
e.backtrace.join("\n") +
"\n---< backtrace of Tk side >-------"
end
fail(e, msg)
end
end
def initialize(namespace = nil)
if namespace.kind_of?(TkNamespace)
@namespace = namespace
elsif namespace == nil
@namespace = TkNamespace.new('::') # global namespace
else
@namespace = TkNamespace.new(namespace)
end
@path = @namespace.path
@msgcat_ext = '.msg'
end
attr_accessor :msgcat_ext
def method_missing(id, *args)
# locale(src, trans) ==> set_translation(locale, src, trans)
loc = id.id2name
case args.length
when 0 # set locale
self.locale=(loc)
when 1 # src only, or trans_list
if args[0].kind_of?(Array)
# trans_list
#list = args[0].collect{|src, trans|
# [ Tk::UTF8_String.new(src), Tk::UTF8_String.new(trans) ]
#}
self.set_translation_list(loc, args[0])
else
# src
#self.set_translation(loc, Tk::UTF8_String.new(args[0]))
self.set_translation(loc, args[0])
end
when 2 # src and trans, or, trans_list and enc
if args[0].kind_of?(Array)
# trans_list
self.set_translation_list(loc, *args)
else
#self.set_translation(loc, args[0], Tk::UTF8_String.new(args[1]))
self.set_translation(loc, *args)
end
when 3 # src and trans and enc
self.set_translation(loc, *args)
else
super(id, *args)
# fail NameError, "undefined method `#{name}' for #{self.to_s}", error_at
end
end
# *args ::= form, arg, arg, ...
def self.translate(*args)
dst = args.collect{|src|
tk_call_without_enc('::msgcat::mc', _get_eval_string(src, true))
}
Tk.UTF8_String(sprintf(*dst))
end
class << self
alias mc translate
alias [] translate
end
def translate(*args)
dst = args.collect{|src|
@namespace.eval{tk_call_without_enc('::msgcat::mc',
_get_eval_string(src, true))}
}
Tk.UTF8_String(sprintf(*dst))
end
alias mc translate
alias [] translate
def self.maxlen(*src_strings)
tk_call('::msgcat::mcmax', *src_strings).to_i
end
def maxlen(*src_strings)
@namespace.eval{tk_call('::msgcat::mcmax', *src_strings).to_i}
end
def self.locale
tk_call('::msgcat::mclocale')
end
def locale
@namespace.eval{tk_call('::msgcat::mclocale')}
end
def self.locale=(locale)
tk_call('::msgcat::mclocale', locale)
end
def locale=(locale)
@namespace.eval{tk_call('::msgcat::mclocale', locale)}
end
def self.preferences
tk_split_simplelist(tk_call('::msgcat::mcpreferences'))
end
def preferences
tk_split_simplelist(@namespace.eval{tk_call('::msgcat::mcpreferences')})
end
def self.load_tk(dir)
number(tk_call('::msgcat::mcload', dir))
end
def self.load_rb(dir)
count = 0
preferences().each{|loc|
file = File.join(dir, loc + self::MSGCAT_EXT)
if File.readable?(file)
count += 1
if TkCore::WITH_ENCODING
eval(IO.read(file, :encoding=>"ASCII-8BIT"))
else
eval(IO.read(file))
end
end
}
count
end
def load_tk(dir)
number(@namespace.eval{tk_call('::msgcat::mcload', dir)})
end
def load_rb(dir)
count = 0
preferences().each{|loc|
file = File.join(dir, loc + @msgcat_ext)
if File.readable?(file)
count += 1
if TkCore::WITH_ENCODING
@namespace.eval(IO.read(file, :encoding=>"ASCII-8BIT"))
else
@namespace.eval(IO.read(file))
end
end
}
count
end
def self.load(dir)
self.load_rb(dir)
end
alias load load_rb
def self.set_translation(locale, src_str, trans_str=None, enc='utf-8')
if trans_str && trans_str != None
trans_str = Tk.UTF8_String(_toUTF8(trans_str, enc))
Tk.UTF8_String(ip_eval_without_enc("::msgcat::mcset {#{locale}} {#{_get_eval_string(src_str, true)}} {#{trans_str}}"))
else
Tk.UTF8_String(ip_eval_without_enc("::msgcat::mcset {#{locale}} {#{_get_eval_string(src_str, true)}}"))
end
end
def set_translation(locale, src_str, trans_str=None, enc='utf-8')
if trans_str && trans_str != None
trans_str = Tk.UTF8_String(_toUTF8(trans_str, enc))
Tk.UTF8_String(@namespace.eval{
ip_eval_without_enc("::msgcat::mcset {#{locale}} {#{_get_eval_string(src_str, true)}} {#{trans_str}}")
})
else
Tk.UTF8_String(@namespace.eval{
ip_eval_without_enc("::msgcat::mcset {#{locale}} {#{_get_eval_string(src_str, true)}}")
})
end
end
def self.set_translation_list(locale, trans_list, enc='utf-8')
# trans_list ::= [ [src, trans], [src, trans], ... ]
list = []
trans_list.each{|src, trans|
if trans && trans != None
list << _get_eval_string(src, true)
list << Tk.UTF8_String(_toUTF8(trans, enc))
else
list << _get_eval_string(src, true) << ''
end
}
#number(tk_call_without_enc('::msgcat::mcmset', locale, list))
number(ip_eval_without_enc("::msgcat::mcmset {#{locale}} {#{_get_eval_string(list)}}"))
end
def set_translation_list(locale, trans_list, enc='utf-8')
# trans_list ::= [ [src, trans], [src, trans], ... ]
list = []
trans_list.each{|src, trans|
if trans && trans != None
list << _get_eval_string(src, true)
list << Tk.UTF8_String(_toUTF8(trans, enc))
else
list << _get_eval_string(src, true) << ''
end
}
number(@namespace.eval{
#tk_call_without_enc('::msgcat::mcmset', locale, list)
ip_eval_without_enc("::msgcat::mcmset {#{locale}} {#{_get_eval_string(list)}}")
})
end
def self.def_unknown_proc(cmd=Proc.new)
TkMsgCatalog::UNKNOWN_CBTBL[TkCore::INTERP.__getip]['::'] = cmd
end
def def_unknown_proc(cmd=Proc.new)
TkMsgCatalog::UNKNOWN_CBTBL[TkCore::INTERP.__getip][@namespace.path] = cmd
end
end
TkMsgCat = TkMsgCatalog
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/openssl/test_pkcs5.rb
|
<filename>.rvm/src/ruby-2.3.0/test/openssl/test_pkcs5.rb
# frozen_string_literal: false
require_relative 'utils'
class OpenSSL::TestPKCS5 < Test::Unit::TestCase
def test_pbkdf2_hmac_sha1_rfc6070_c_1_len_20
p ="password"
s = "<PASSWORD>"
c = 1
dk_len = 20
raw = %w{ 0c 60 c8 0f 96 1f 0e 71
f3 a9 b5 24 af 60 12 06
2f e0 37 a6 }
expected = [raw.join('')].pack('H*')
value = OpenSSL::PKCS5.pbkdf2_hmac_sha1(p, s, c, dk_len)
assert_equal(expected, value)
end
def test_pbkdf2_hmac_sha1_rfc6070_c_2_len_20
p ="password"
s = "<PASSWORD>"
c = 2
dk_len = 20
raw = %w{ ea 6c 01 4d c7 2d 6f 8c
cd 1e d9 2a ce 1d 41 f0
d8 de 89 57 }
expected = [raw.join('')].pack('H*')
value = OpenSSL::PKCS5.pbkdf2_hmac_sha1(p, s, c, dk_len)
assert_equal(expected, value)
end
def test_pbkdf2_hmac_sha1_rfc6070_c_4096_len_20
p ="password"
s = "<PASSWORD>"
c = 4096
dk_len = 20
raw = %w{ 4b 00 79 01 b7 65 48 9a
be ad 49 d9 26 f7 21 d0
65 a4 29 c1 }
expected = [raw.join('')].pack('H*')
value = OpenSSL::PKCS5.pbkdf2_hmac_sha1(p, s, c, dk_len)
assert_equal(expected, value)
end
# takes too long!
# def test_pbkdf2_hmac_sha1_rfc6070_c_16777216_len_20
# p ="password"
# s = "<PASSWORD>"
# c = 16777216
# dk_len = 20
# raw = %w{ ee fe 3d 61 cd 4d a4 e4
# e9 94 5b 3d 6b a2 15 8c
# 26 34 e9 84 }
# expected = [raw.join('')].pack('H*')
# value = OpenSSL::PKCS5.pbkdf2_hmac_sha1(p, s, c, dk_len)
# assert_equal(expected, value)
# end
def test_pbkdf2_hmac_sha1_rfc6070_c_4096_len_25
p ="<PASSWORD>"
s = "<PASSWORD>"
c = 4096
dk_len = 25
raw = %w{ 3d 2e ec 4f e4 1c 84 9b
80 c8 d8 36 62 c0 e4 4a
8b 29 1a 96 4c f2 f0 70
38 }
expected = [raw.join('')].pack('H*')
value = OpenSSL::PKCS5.pbkdf2_hmac_sha1(p, s, c, dk_len)
assert_equal(expected, value)
end
def test_pbkdf2_hmac_sha1_rfc6070_c_4096_len_16
p ="<PASSWORD>"
s = "sa\0lt"
c = 4096
dk_len = 16
raw = %w{ 56 fa 6a a7 55 48 09 9d
cc 37 d7 f0 34 25 e0 c3 }
expected = [raw.join('')].pack('H*')
value = OpenSSL::PKCS5.pbkdf2_hmac_sha1(p, s, c, dk_len)
assert_equal(expected, value)
end
def test_pbkdf2_hmac_sha256_c_20000_len_32
#unfortunately no official test vectors available yet for SHA-2
p ="password"
s = OpenSSL::Random.random_bytes(16)
c = 20000
dk_len = 32
digest = OpenSSL::Digest::SHA256.new
value1 = OpenSSL::PKCS5.pbkdf2_hmac(p, s, c, dk_len, digest)
value2 = OpenSSL::PKCS5.pbkdf2_hmac(p, s, c, dk_len, digest)
assert_equal(value1, value2)
end if OpenSSL::PKCS5.respond_to?(:pbkdf2_hmac)
end if defined?(OpenSSL::TestUtils)
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/openssl/test_cipher.rb
|
# frozen_string_literal: false
require_relative 'utils'
if defined?(OpenSSL::TestUtils)
class OpenSSL::TestCipher < Test::Unit::TestCase
class << self
def has_cipher?(name)
ciphers = OpenSSL::Cipher.ciphers
# redefine method so we can use the cached ciphers value from the closure
# and need not recompute the list each time
define_singleton_method :has_cipher? do |name|
ciphers.include?(name)
end
has_cipher?(name)
end
def has_ciphers?(list)
list.all? { |name| has_cipher?(name) }
end
end
def setup
@c1 = OpenSSL::Cipher::Cipher.new("DES-EDE3-CBC")
@c2 = OpenSSL::Cipher::DES.new(:EDE3, "CBC")
@key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
@iv = "\0\0\0\0\0\0\0\0"
@hexkey = "0000000000000000000000000000000000000000000000"
@hexiv = "0000000000000000"
@data = "DATA"
end
def teardown
@c1 = @c2 = nil
end
def test_crypt
@c1.encrypt.pkcs5_keyivgen(@key, @iv)
@c2.encrypt.pkcs5_keyivgen(@key, @iv)
s1 = @c1.update(@data) + @c1.final
s2 = @c2.update(@data) + @c2.final
assert_equal(s1, s2, "encrypt")
@c1.decrypt.pkcs5_keyivgen(@key, @iv)
@c2.decrypt.pkcs5_keyivgen(@key, @iv)
assert_equal(@data, @c1.update(s1)+@c1.final, "decrypt")
assert_equal(@data, @c2.update(s2)+@c2.final, "decrypt")
end
def test_info
assert_equal("DES-EDE3-CBC", @c1.name, "name")
assert_equal("DES-EDE3-CBC", @c2.name, "name")
assert_kind_of(Fixnum, @c1.key_len, "key_len")
assert_kind_of(Fixnum, @c1.iv_len, "iv_len")
end
def test_dup
assert_equal(@c1.name, @c1.dup.name, "dup")
assert_equal(@c1.name, @c1.clone.name, "clone")
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
tmpc = @c1.dup
s1 = @c1.update(@data) + @c1.final
s2 = tmpc.update(@data) + tmpc.final
assert_equal(s1, s2, "encrypt dup")
end
def test_reset
@c1.encrypt
@c1.key = @key
@c1.iv = @iv
s1 = @c1.update(@data) + @c1.final
@c1.reset
s2 = @c1.update(@data) + @c1.final
assert_equal(s1, s2, "encrypt reset")
end
def test_empty_data
@c1.encrypt
assert_raise(ArgumentError){ @c1.update("") }
end
def test_initialize
assert_raise(RuntimeError) {@c1.__send__(:initialize, "DES-EDE3-CBC")}
assert_raise(RuntimeError) {OpenSSL::Cipher.allocate.final}
end
def test_ctr_if_exists
begin
cipher = OpenSSL::Cipher.new('aes-128-ctr')
cipher.encrypt
cipher.pkcs5_keyivgen('password')
c = cipher.update('hello,world') + cipher.final
cipher.decrypt
cipher.pkcs5_keyivgen('password')
assert_equal('hello,world', cipher.update(c) + cipher.final)
end
end if has_cipher?('aes-128-ctr')
if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00907000
def test_ciphers
OpenSSL::Cipher.ciphers.each{|name|
next if /netbsd/ =~ RUBY_PLATFORM && /idea|rc5/i =~ name
begin
assert_kind_of(OpenSSL::Cipher::Cipher, OpenSSL::Cipher::Cipher.new(name))
rescue OpenSSL::Cipher::CipherError => e
next if /wrap/ =~ name and e.message == 'wrap mode not allowed'
raise
end
}
end
def test_AES
pt = File.read(__FILE__)
%w(ECB CBC CFB OFB).each{|mode|
c1 = OpenSSL::Cipher::AES256.new(mode)
c1.encrypt
c1.pkcs5_keyivgen("passwd")
ct = c1.update(pt) + c1.final
c2 = OpenSSL::Cipher::AES256.new(mode)
c2.decrypt
c2.pkcs5_keyivgen("passwd")
assert_equal(pt, c2.update(ct) + c2.final)
}
end
def test_AES_crush
500.times do
assert_nothing_raised("[Bug #2768]") do
# it caused OpenSSL SEGV by uninitialized key
OpenSSL::Cipher::AES128.new("ECB").update "." * 17
end
end
end
end
if has_ciphers?(['aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm'])
def test_authenticated
cipher = OpenSSL::Cipher.new('aes-128-gcm')
assert(cipher.authenticated?)
cipher = OpenSSL::Cipher.new('aes-128-cbc')
refute(cipher.authenticated?)
end
def test_aes_gcm
['aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm'].each do |algo|
pt = "You should all use Authenticated Encryption!"
cipher, key, iv = new_encryptor(algo)
cipher.auth_data = "aad"
ct = cipher.update(pt) + cipher.final
tag = cipher.auth_tag
assert_equal(16, tag.size)
decipher = new_decryptor(algo, key, iv)
decipher.auth_tag = tag
decipher.auth_data = "aad"
assert_equal(pt, decipher.update(ct) + decipher.final)
end
end
def test_aes_gcm_short_tag
['aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm'].each do |algo|
pt = "You should all use Authenticated Encryption!"
cipher, key, iv = new_encryptor(algo)
cipher.auth_data = "aad"
ct = cipher.update(pt) + cipher.final
tag = cipher.auth_tag(8)
assert_equal(8, tag.size)
decipher = new_decryptor(algo, key, iv)
decipher.auth_tag = tag
decipher.auth_data = "aad"
assert_equal(pt, decipher.update(ct) + decipher.final)
end
end
def test_aes_gcm_wrong_tag
pt = "You should all use Authenticated Encryption!"
cipher, key, iv = new_encryptor('aes-128-gcm')
cipher.auth_data = "aad"
ct = cipher.update(pt) + cipher.final
tag = cipher.auth_tag
decipher = new_decryptor('aes-128-gcm', key, iv)
tag.setbyte(-1, (tag.getbyte(-1) + 1) & 0xff)
decipher.auth_tag = tag
decipher.auth_data = "aad"
assert_raise OpenSSL::Cipher::CipherError do
decipher.update(ct) + decipher.final
end
end
def test_aes_gcm_wrong_auth_data
pt = "You should all use Authenticated Encryption!"
cipher, key, iv = new_encryptor('aes-128-gcm')
cipher.auth_data = "aad"
ct = cipher.update(pt) + cipher.final
tag = cipher.auth_tag
decipher = new_decryptor('aes-128-gcm', key, iv)
decipher.auth_tag = tag
decipher.auth_data = "daa"
assert_raise OpenSSL::Cipher::CipherError do
decipher.update(ct) + decipher.final
end
end
def test_aes_gcm_wrong_ciphertext
pt = "You should all use Authenticated Encryption!"
cipher, key, iv = new_encryptor('aes-128-gcm')
cipher.auth_data = "aad"
ct = cipher.update(pt) + cipher.final
tag = cipher.auth_tag
decipher = new_decryptor('aes-128-gcm', key, iv)
decipher.auth_tag = tag
decipher.auth_data = "aad"
assert_raise OpenSSL::Cipher::CipherError do
decipher.update(ct[0..-2] << ct[-1].succ) + decipher.final
end
end
end
private
def new_encryptor(algo)
cipher = OpenSSL::Cipher.new(algo)
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
[cipher, key, iv]
end
def new_decryptor(algo, key, iv)
OpenSSL::Cipher.new(algo).tap do |cipher|
cipher.decrypt
cipher.key = key
cipher.iv = iv
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/lib/chef/knife/winrm_session.rb
|
<gh_stars>0
#
# Author:: <NAME> <<EMAIL>>
# Copyright:: Copyright (c) 2015-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/application'
require 'winrm'
class Chef
class Knife
class WinrmSession
attr_reader :host, :endpoint, :port, :output, :error, :exit_code
def initialize(options)
configure_proxy
@host = options[:host]
@port = options[:port]
url = "#{options[:host]}:#{options[:port]}/wsman"
scheme = options[:transport] == :ssl ? 'https' : 'http'
@endpoint = "#{scheme}://#{url}"
opts = Hash.new
opts = {:user => options[:user], :pass => options[:password], :basic_auth_only => options[:basic_auth_only], :disable_sspi => options[:disable_sspi], :no_ssl_peer_verification => options[:no_ssl_peer_verification], :ssl_peer_fingerprint => options[:ssl_peer_fingerprint]}
options[:transport] == :kerberos ? opts.merge!({:service => options[:service], :realm => options[:realm], :keytab => options[:keytab]}) : opts.merge!({:ca_trust_path => options[:ca_trust_path]})
Chef::Log.debug("WinRM::WinRMWebService options: #{opts}")
Chef::Log.debug("Endpoint: #{endpoint}")
Chef::Log.debug("Transport: #{options[:transport]}")
@winrm_session = WinRM::WinRMWebService.new(@endpoint, options[:transport], opts)
transport = @winrm_session.instance_variable_get(:@xfer)
http_client = transport.instance_variable_get(:@httpcli)
Chef::HTTP::DefaultSSLPolicy.new(http_client.ssl_config).set_custom_certs
@winrm_session.set_timeout(options[:operation_timeout]) if options[:operation_timeout]
end
def relay_command(command)
remote_id = @winrm_session.open_shell
command_id = @winrm_session.run_command(remote_id, command)
Chef::Log.debug("#{@host}[#{remote_id}] => :run_command[#{command}]")
session_result = get_output(remote_id, command_id)
@winrm_session.cleanup_command(remote_id, command_id)
Chef::Log.debug("#{@host}[#{remote_id}] => :command_cleanup[#{command}]")
@exit_code = session_result[:exitcode]
@winrm_session.close_shell(remote_id)
Chef::Log.debug("#{@host}[#{remote_id}] => :shell_close")
session_result
end
private
def get_output(remote_id, command_id)
@winrm_session.get_command_output(remote_id, command_id) do |out,error|
print_data(@host, out) if out
print_data(@host, error, :red) if error
end
end
def print_data(host, data, color = :cyan)
if data =~ /\n/
data.split(/\n/).each { |d| print_data(host, d, color) }
elsif !data.nil?
print Chef::Knife::Winrm.ui.color(host, color)
puts " #{data}"
end
end
def configure_proxy
if Chef::Config.respond_to?(:export_proxies)
Chef::Config.export_proxies
else
Chef::Application.new.configure_proxy_environment_variables
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/erb/test_erb_command.rb
|
# -*- coding: us-ascii -*-
# frozen_string_literal: false
require 'test/unit'
class TestErbCommand < Test::Unit::TestCase
def test_var
assert_in_out_err(["-w",
File.expand_path("../../../bin/erb", __FILE__),
"var=hoge"],
"<%=var%>", ["hoge"])
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/rubygems/commands/crash_command.rb
|
# frozen_string_literal: false
class Gem::Commands::CrashCommand < Gem::Command
raise "crash"
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/tk/sample/tcltklib/sample1.rb
|
<reponame>arnab0073/idea
#! /usr/local/bin/ruby -d
# -*- encoding: utf-8 -*-
# frozen_string_literal: false
# -d オプションを付けると, デバッグ情報を表示する.
# tcltk ライブラリのサンプル
# まず, ライブラリを require する.
require "tcltk"
# 以下は, Test1 のインスタンスの initialize() で,
# tcl/tk に関する処理を行う例である.
# 必ずしもそのようにする必要は無く,
# (もし, そうしたければ) class の外で tcl/tk に関する処理を行っても良い.
class Test1
# 初期化(インタプリタを生成してウィジェットを生成する).
def initialize()
#### 使う前のおまじない
# インタプリタの生成.
ip = TclTkInterpreter.new()
# コマンドに対応するオブジェクトを c に設定しておく.
c = ip.commands()
# 使用するコマンドに対応するオブジェクトは変数に入れておく.
append, bind, button, destroy, incr, info, label, place, set, wm =
c.values_at(
"append", "bind", "button", "destroy", "incr", "info", "label", "place",
"set", "wm")
#### tcl/tk のコマンドに対応するオブジェクト(TclTkCommand)の操作
# 実行する時は, e() メソッドを使う.
# (以下は, tcl/tk における info command r* を実行.)
print info.e("command", "r*"), "\n"
# 引数は, まとめた文字列にしても同じ.
print info.e("command r*"), "\n"
# 変数を用いなくとも実行できるが, 見ためが悪い.
print c["info"].e("command", "r*"), "\n"
# インタプリタのメソッドとしても実行できるが, 効率が悪い.
print ip.info("command", "r*"), "\n"
####
# 以下, 生成したオブジェクトは変数に代入しておかないと
# GC の対象になってしまう.
#### tcl/tk の変数に対応するオブジェクト(TclTkVariable)の操作
# 生成と同時に値を設定する.
v1 = TclTkVariable.new(ip, "20")
# 読み出しは get メソッドを使う.
print v1.get(), "\n"
# 設定は set メソッドを使う.
v1.set(40)
print v1.get(), "\n"
# set コマンドを使って読み出し, 設定は可能だが見ためが悪い.
# e() メソッド等の引数に直接 TclTkObject や数値を書いても良い.
set.e(v1, 30)
print set.e(v1), "\n"
# tcl/tk のコマンドで変数を操作できる.
incr.e(v1)
print v1.get(), "\n"
append.e(v1, 10)
print v1.get(), "\n"
#### tcl/tk のウィジェットに対応するオブジェクト(TclTkWidget)の操作
# ルートウィジェットを取り出す.
root = ip.rootwidget()
# ウィジェットの操作.
root.e("configure -height 300 -width 300")
# タイトルを付けるときは wm を使う.
wm.e("title", root, $0)
# 親ウィジェットとコマンドを指定して, ウィジェットを作る.
l1 = TclTkWidget.new(ip, root, label, "-text {type `x' to print}")
# place すると表示される.
place.e(l1, "-x 0 -rely 0.0 -relwidth 1 -relheight 0.1")
# コマンド名は文字列で指定しても良いが, 見ためが悪い.
# (コマンド名は独立した引数でなければならない.)
l2 = TclTkWidget.new(ip, root, "label")
# ウィジェットの操作.
l2.e("configure -text {type `q' to exit}")
place.e(l2, "-x 0 -rely 0.1 -relwidth 1 -relheight 0.1")
#### tcl/tk のコールバックに対応するオブジェクト(TclTkCallback)の操作
# コールバックを生成する.
c1 = TclTkCallback.new(ip, proc{sample(ip, root)})
# コールバックを持つウィジェットを生成する.
b1 = TclTkWidget.new(ip, root, button, "-text sample -command", c1)
place.e(b1, "-x 0 -rely 0.2 -relwidth 1 -relheight 0.1")
# イベントループを抜けるには destroy.e(root) する.
c2 = TclTkCallback.new(ip, proc{destroy.e(root)})
b2 = TclTkWidget.new(ip, root, button, "-text exit -command", c2)
place.e(b2, "-x 0 -rely 0.3 -relwidth 1 -relheight 0.1")
#### イベントのバインド
# script の追加 (bind tag sequence +script) は今のところできない.
# (イテレータ変数の設定がうまくいかない.)
# 基本的にはウィジェットに対するコールバックと同じ.
c3 = TclTkCallback.new(ip, proc{print("q pressed\n"); destroy.e(root)})
bind.e(root, "q", c3)
# bind コマンドで % 置換によりパラメータを受け取りたいときは,
# proc{} の後ろに文字列で指定すると,
# 置換結果をイテレータ変数を通して受け取ることができる.
# ただし proc{} の後ろの文字列は,
# bind コマンドに与えるコールバック以外で指定してはいけない.
c4 = TclTkCallback.new(ip, proc{|i| print("#{i} pressed\n")}, "%A")
bind.e(root, "x", c4)
# TclTkCallback を GC の対象にしたければ,
# dcb() (または deletecallbackkeys()) する必要がある.
cb = [c1, c2, c3, c4]
c5 = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, root, w)}, "%W")
bind.e(root, "<Destroy>", c5)
cb.push(c5)
#### tcl/tk のイメージに対応するオブジェクト(TclTkImage)の操作
# データを指定して生成する.
i1 = TclTkImage.new(ip, "photo", "-file maru.gif")
# ラベルに張り付けてみる.
l3 = TclTkWidget.new(ip, root, label, "-relief raised -image", i1)
place.e(l3, "-x 0 -rely 0.4 -relwidth 0.2 -relheight 0.2")
# 空のイメージを生成して後で操作する.
i2 = TclTkImage.new(ip, "photo")
# イメージを操作する.
i2.e("copy", i1)
i2.e("configure -gamma 0.5")
l4 = TclTkWidget.new(ip, root, label, "-relief raised -image", i2)
place.e(l4, "-relx 0.2 -rely 0.4 -relwidth 0.2 -relheight 0.2")
####
end
# サンプルのためのウィジェットを生成する.
def sample(ip, parent)
bind, button, destroy, grid, toplevel, wm = ip.commands().values_at(
"bind", "button", "destroy", "grid", "toplevel", "wm")
## toplevel
# 新しいウインドウを開くには, toplevel を使う.
t1 = TclTkWidget.new(ip, parent, toplevel)
# タイトルを付けておく
wm.e("title", t1, "sample")
# ウィジェットが破壊されたとき, コールバックが GC の対象になるようにする.
cb = []
cb.push(c = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, t1, w)}, "%W"))
bind.e(t1, "<Destroy>", c)
# ボタンの生成.
wid = []
# toplevel ウィジェットを破壊するには destroy する.
cb.push(c = TclTkCallback.new(ip, proc{destroy.e(t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text close -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_label(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text label -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_button(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text button -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_checkbutton(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text checkbutton -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_radiobutton(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text radiobutton -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_scale(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text scale -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_entry(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text entry -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_text(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text text -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_raise(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text raise/lower -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_modal(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text message/modal -command",
c))
cb.push(c = TclTkCallback.new(ip, proc{test_menu(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text menu -command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_listbox(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text listbox/scrollbar",
"-command", c))
cb.push(c = TclTkCallback.new(ip, proc{test_canvas(ip, t1)}))
wid.push(TclTkWidget.new(ip, t1, button, "-text canvas -command", c))
# grid で表示する.
ro = co = 0
wid.each{|w|
grid.e(w, "-row", ro, "-column", co, "-sticky news")
ro += 1
if ro == 7
ro = 0
co += 1
end
}
end
# inittoplevel(ip, parent, title)
# 以下の処理をまとめて行う.
# 1. toplevel ウィジェットを作成する.
# 2. コールバックを登録する配列を用意し, toplevel ウィジェットの
# <Destroy> イベントにコールバックを削除する手続きを登録する.
# 3. クローズボタンを作る.
# 作成した toplevel ウィジェット, クローズボタン, コールバック登録用変数
# を返す.
# ip: インタプリタ
# parent: 親ウィジェット
# title: toplevel ウィジェットのウインドウのタイトル
def inittoplevel(ip, parent, title)
bind, button, destroy, toplevel, wm = ip.commands().values_at(
"bind", "button", "destroy", "toplevel", "wm")
# 新しいウインドウを開くには, toplevel を使う.
t1 = TclTkWidget.new(ip, parent, toplevel)
# タイトルを付けておく
wm.e("title", t1, title)
# ウィジェットが破壊されたとき, コールバックが GC の対象になるようにする.
cb = []
cb.push(c = TclTkCallback.new(ip, proc{|w| TclTk.dcb(cb, t1, w)}, "%W"))
bind.e(t1, "<Destroy>", c)
# close ボタンを作っておく.
# toplevel ウィジェットを破壊するには destroy する.
cb.push(c = TclTkCallback.new(ip, proc{destroy.e(t1)}))
b1 = TclTkWidget.new(ip, t1, button, "-text close -command", c)
return t1, b1, cb
end
# label のサンプル.
def test_label(ip, parent)
button, global, label, pack = ip.commands().values_at(
"button", "global", "label", "pack")
t1, b1, cb = inittoplevel(ip, parent, "label")
## label
# いろいろな形のラベル.
l1 = TclTkWidget.new(ip, t1, label, "-text {default(flat)}")
l2 = TclTkWidget.new(ip, t1, label, "-text raised -relief raised")
l3 = TclTkWidget.new(ip, t1, label, "-text sunken -relief sunken")
l4 = TclTkWidget.new(ip, t1, label, "-text groove -relief groove")
l5 = TclTkWidget.new(ip, t1, label, "-text ridge -relief ridge")
l6 = TclTkWidget.new(ip, t1, label, "-bitmap error")
l7 = TclTkWidget.new(ip, t1, label, "-bitmap questhead")
# pack しても表示される.
pack.e(b1, l1, l2, l3, l4, l5, l6, l7, "-pady 3")
## -textvariable
# tcltk ライブラリの実装では, コールバックは tcl/tk の``手続き''を通して
# 呼ばれる. したがって, コールバックの中で(大域)変数にアクセスするときは,
# global する必要がある.
# global する前に変数に値を設定してしまうとエラーになるので,
# tcl/tk における表現形だけ生成して, 実際に値を設定しないように,
# 2 番目の引数には nil を与える.
v1 = TclTkVariable.new(ip, nil)
global.e(v1)
v1.set(100)
# -textvariable で変数を設定する.
l6 = TclTkWidget.new(ip, t1, label, "-textvariable", v1)
# コールバックの中から変数を操作する.
cb.push(c = TclTkCallback.new(ip, proc{
global.e(v1); v1.set(v1.get().to_i + 10)}))
b2 = TclTkWidget.new(ip, t1, button, "-text +10 -command", c)
cb.push(c = TclTkCallback.new(ip, proc{
global.e(v1); v1.set(v1.get().to_i - 10)}))
b3 = TclTkWidget.new(ip, t1, button, "-text -10 -command", c)
pack.e(l6, b2, b3)
end
# button のサンプル.
def test_button(ip, parent)
button, pack = ip.commands().values_at("button", "pack")
t1, b1, cb = inittoplevel(ip, parent, "button")
## button
# コールバック内で参照する変数は先に宣言しておかなければならない.
b3 = b4 = nil
cb.push(c = TclTkCallback.new(ip, proc{b3.e("flash"); b4.e("flash")}))
b2 = TclTkWidget.new(ip, t1, button, "-text flash -command", c)
cb.push(c = TclTkCallback.new(ip, proc{b2.e("configure -state normal")}))
b3 = TclTkWidget.new(ip, t1, button, "-text normal -command", c)
cb.push(c = TclTkCallback.new(ip, proc{b2.e("configure -state disabled")}))
b4 = TclTkWidget.new(ip, t1, button, "-text disable -command", c)
pack.e(b1, b2, b3, b4)
end
# checkbutton のサンプル.
def test_checkbutton(ip, parent)
checkbutton, global, pack = ip.commands().values_at(
"checkbutton", "global", "pack")
t1, b1, cb = inittoplevel(ip, parent, "checkbutton")
## checkbutton
v1 = TclTkVariable.new(ip, nil)
global.e(v1)
# -variable で変数を設定する.
ch1 = TclTkWidget.new(ip, t1, checkbutton, "-onvalue on -offvalue off",
"-textvariable", v1, "-variable", v1)
pack.e(b1, ch1)
end
# radiobutton のサンプル.
def test_radiobutton(ip, parent)
global, label, pack, radiobutton = ip.commands().values_at(
"global", "label", "pack", "radiobutton")
t1, b1, cb = inittoplevel(ip, parent, "radiobutton")
## radiobutton
v1 = TclTkVariable.new(ip, nil)
global.e(v1)
# ヌルストリングは "{}" で指定する.
v1.set("{}")
l1 = TclTkWidget.new(ip, t1, label, "-textvariable", v1)
# -variable で同じ変数を指定すると同じグループになる.
ra1 = TclTkWidget.new(ip, t1, radiobutton,
"-text radio1 -value r1 -variable", v1)
ra2 = TclTkWidget.new(ip, t1, radiobutton,
"-text radio2 -value r2 -variable", v1)
cb.push(c = TclTkCallback.new(ip, proc{global.e(v1); v1.set("{}")}))
ra3 = TclTkWidget.new(ip, t1, radiobutton,
"-text clear -value r3 -variable", v1, "-command", c)
pack.e(b1, l1, ra1, ra2, ra3)
end
# scale のサンプル.
def test_scale(ip, parent)
global, pack, scale = ip.commands().values_at(
"global", "pack", "scale")
t1, b1, cb = inittoplevel(ip, parent, "scale")
## scale
v1 = TclTkVariable.new(ip, nil)
global.e(v1)
v1.set(219)
# コールバック内で参照する変数は先に宣言しておかなければならない.
sca1 = nil
cb.push(c = TclTkCallback.new(ip, proc{global.e(v1); v = v1.get();
sca1.e("configure -background", format("#%02x%02x%02x", v, v, v))}))
sca1 = TclTkWidget.new(ip, t1, scale,
"-label scale -orient h -from 0 -to 255 -variable", v1, "-command", c)
pack.e(b1, sca1)
end
# entry のサンプル.
def test_entry(ip, parent)
button, entry, global, pack = ip.commands().values_at(
"button", "entry", "global", "pack")
t1, b1, cb = inittoplevel(ip, parent, "entry")
## entry
v1 = TclTkVariable.new(ip, nil)
global.e(v1)
# ヌルストリングは "{}" で指定する.
v1.set("{}")
en1 = TclTkWidget.new(ip, t1, entry, "-textvariable", v1)
cb.push(c = TclTkCallback.new(ip, proc{
global.e(v1); print(v1.get(), "\n"); v1.set("{}")}))
b2 = TclTkWidget.new(ip, t1, button, "-text print -command", c)
pack.e(b1, en1, b2)
end
# text のサンプル.
def test_text(ip, parent)
button, pack, text = ip.commands().values_at(
"button", "pack", "text")
t1, b1, cb = inittoplevel(ip, parent, "text")
## text
te1 = TclTkWidget.new(ip, t1, text)
cb.push(c = TclTkCallback.new(ip, proc{
# 1 行目の 0 文字目から最後までを表示し, 削除する.
print(te1.e("get 1.0 end")); te1.e("delete 1.0 end")}))
b2 = TclTkWidget.new(ip, t1, button, "-text print -command", c)
pack.e(b1, te1, b2)
end
# raise/lower のサンプル.
def test_raise(ip, parent)
button, frame, lower, pack, raise = ip.commands().values_at(
"button", "frame", "lower", "pack", "raise")
t1, b1, cb = inittoplevel(ip, parent, "raise/lower")
## raise/lower
# button を隠すテストのために, frame を使う.
f1 = TclTkWidget.new(ip, t1, frame)
# コールバック内で参照する変数は先に宣言しておかなければならない.
b2 = nil
cb.push(c = TclTkCallback.new(ip, proc{raise.e(f1, b2)}))
b2 = TclTkWidget.new(ip, t1, button, "-text raise -command", c)
cb.push(c = TclTkCallback.new(ip, proc{lower.e(f1, b2)}))
b3 = TclTkWidget.new(ip, t1, button, "-text lower -command", c)
lower.e(f1, b3)
pack.e(b2, b3, "-in", f1)
pack.e(b1, f1)
end
# modal なウィジェットのサンプル.
def test_modal(ip, parent)
button, frame, message, pack, tk_chooseColor, tk_getOpenFile,
tk_messageBox = ip.commands().values_at(
"button", "frame", "message", "pack", "tk_chooseColor",
"tk_getOpenFile", "tk_messageBox")
# 最初に load されていないライブラリは ip.commands() に存在しないので,
# TclTkLibCommand を生成する必要がある.
tk_dialog = TclTkLibCommand.new(ip, "tk_dialog")
t1, b1, cb = inittoplevel(ip, parent, "message/modal")
## message
mes = "これは message ウィジェットのテストです."
mes += "以下は modal なウィジェットのテストです."
me1 = TclTkWidget.new(ip, t1, message, "-text {#{mes}}")
## modal
# tk_messageBox
cb.push(c = TclTkCallback.new(ip, proc{
print tk_messageBox.e("-type yesnocancel -message messageBox",
"-icon error -default cancel -title messageBox"), "\n"}))
b2 = TclTkWidget.new(ip, t1, button, "-text messageBox -command", c)
# tk_dialog
cb.push(c = TclTkCallback.new(ip, proc{
# ウィジェット名を生成するためにダミーの frame を生成.
print tk_dialog.e(TclTkWidget.new(ip, t1, frame),
"dialog dialog error 2 yes no cancel"), "\n"}))
b3 = TclTkWidget.new(ip, t1, button, "-text dialog -command", c)
# tk_chooseColor
cb.push(c = TclTkCallback.new(ip, proc{
print tk_chooseColor.e("-title chooseColor"), "\n"}))
b4 = TclTkWidget.new(ip, t1, button, "-text chooseColor -command", c)
# tk_getOpenFile
cb.push(c = TclTkCallback.new(ip, proc{
print tk_getOpenFile.e("-defaultextension .rb",
"-filetypes {{{Ruby Script} {.rb}} {{All Files} {*}}}",
"-title getOpenFile"), "\n"}))
b5 = TclTkWidget.new(ip, t1, button, "-text getOpenFile -command", c)
pack.e(b1, me1, b2, b3, b4, b5)
end
# menu のサンプル.
def test_menu(ip, parent)
global, menu, menubutton, pack = ip.commands().values_at(
"global", "menu", "menubutton", "pack")
tk_optionMenu = TclTkLibCommand.new(ip, "tk_optionMenu")
t1, b1, cb = inittoplevel(ip, parent, "menu")
## menu
# menubutton を生成する.
mb1 = TclTkWidget.new(ip, t1, menubutton, "-text menu")
# menu を生成する.
me1 = TclTkWidget.new(ip, mb1, menu)
# mb1 から me1 が起動されるようにする.
mb1.e("configure -menu", me1)
# cascade で起動される menu を生成する.
me11 = TclTkWidget.new(ip, me1, menu)
# radiobutton のサンプル.
v1 = TclTkVariable.new(ip, nil); global.e(v1); v1.set("r1")
me11.e("add radiobutton -label radio1 -value r1 -variable", v1)
me11.e("add radiobutton -label radio2 -value r2 -variable", v1)
me11.e("add radiobutton -label radio3 -value r3 -variable", v1)
# cascade により mb11 が起動されるようにする.
me1.e("add cascade -label cascade -menu", me11)
# checkbutton のサンプル.
v2 = TclTkVariable.new(ip, nil); global.e(v2); v2.set("none")
me1.e("add checkbutton -label check -variable", v2)
# separator のサンプル.
me1.e("add separator")
# command のサンプル.
v3 = nil
cb.push(c = TclTkCallback.new(ip, proc{
global.e(v1, v2, v3); print "v1: ", v1.get(), ", v2: ", v2.get(),
", v3: ", v3.get(), "\n"}))
me1.e("add command -label print -command", c)
## tk_optionMenu
v3 = TclTkVariable.new(ip, nil); global.e(v3); v3.set("opt2")
om1 = TclTkWidget.new(ip, t1, tk_optionMenu, v3, "opt1 opt2 opt3 opt4")
pack.e(b1, mb1, om1, "-side left")
end
# listbox のサンプル.
def test_listbox(ip, parent)
clipboard, frame, grid, listbox, lower, menu, menubutton, pack, scrollbar,
selection = ip.commands().values_at(
"clipboard", "frame", "grid", "listbox", "lower", "menu", "menubutton",
"pack", "scrollbar", "selection")
t1, b1, cb = inittoplevel(ip, parent, "listbox")
## listbox/scrollbar
f1 = TclTkWidget.new(ip, t1, frame)
# コールバック内で参照する変数は先に宣言しておかなければならない.
li1 = sc1 = sc2 = nil
# 実行時に, 後ろにパラメータがつくコールバックは,
# イテレータ変数でそのパラメータを受け取ることができる.
# (複数のパラメータはひとつの文字列にまとめられる.)
cb.push(c1 = TclTkCallback.new(ip, proc{|i| li1.e("xview", i)}))
cb.push(c2 = TclTkCallback.new(ip, proc{|i| li1.e("yview", i)}))
cb.push(c3 = TclTkCallback.new(ip, proc{|i| sc1.e("set", i)}))
cb.push(c4 = TclTkCallback.new(ip, proc{|i| sc2.e("set", i)}))
# listbox
li1 = TclTkWidget.new(ip, f1, listbox,
"-xscrollcommand", c3, "-yscrollcommand", c4,
"-selectmode extended -exportselection true")
for i in 1..20
li1.e("insert end {line #{i} line #{i} line #{i} line #{i} line #{i}}")
end
# scrollbar
sc1 = TclTkWidget.new(ip, f1, scrollbar, "-orient horizontal -command", c1)
sc2 = TclTkWidget.new(ip, f1, scrollbar, "-orient vertical -command", c2)
## selection/clipboard
mb1 = TclTkWidget.new(ip, t1, menubutton, "-text edit")
me1 = TclTkWidget.new(ip, mb1, menu)
mb1.e("configure -menu", me1)
cb.push(c = TclTkCallback.new(ip, proc{
# clipboard をクリア.
clipboard.e("clear")
# selection から文字列を読み込み clipboard に追加する.
clipboard.e("append {#{selection.e('get')}}")}))
me1.e("add command -label {selection -> clipboard} -command",c)
cb.push(c = TclTkCallback.new(ip, proc{
# li1 をクリア.
li1.e("delete 0 end")
# clipboard から文字列を取り出し, 1 行ずつ
selection.e("get -selection CLIPBOARD").split(/\n/).each{|line|
# li1 に挿入する.
li1.e("insert end {#{line}}")}}))
me1.e("add command -label {clipboard -> listbox} -command",c)
grid.e(li1, "-row 0 -column 0 -sticky news")
grid.e(sc1, "-row 1 -column 0 -sticky ew")
grid.e(sc2, "-row 0 -column 1 -sticky ns")
grid.e("rowconfigure", f1, "0 -weight 100")
grid.e("columnconfigure", f1, "0 -weight 100")
f2 = TclTkWidget.new(ip, t1, frame)
lower.e(f2, b1)
pack.e(b1, mb1, "-in", f2, "-side left")
pack.e(f2, f1)
end
# canvas のサンプル.
def test_canvas(ip, parent)
canvas, lower, pack = ip.commands().values_at("canvas", "lower", "pack")
t1, b1, cb = inittoplevel(ip, parent, "canvas")
## canvas
ca1 = TclTkWidget.new(ip, t1, canvas, "-width 400 -height 300")
lower.e(ca1, b1)
# rectangle を作る.
idr = ca1.e("create rectangle 10 10 20 20")
# oval を作る.
ca1.e("create oval 60 10 100 50")
# polygon を作る.
ca1.e("create polygon 110 10 110 30 140 10")
# line を作る.
ca1.e("create line 150 10 150 30 190 10")
# arc を作る.
ca1.e("create arc 200 10 250 50 -start 0 -extent 90 -style pieslice")
# i1 は本当は, どこかで破壊しなければならないが, 面倒なので放ってある.
i1 = TclTkImage.new(ip, "photo", "-file maru.gif")
# image を作る.
ca1.e("create image 100 100 -image", i1)
# bitmap を作る.
ca1.e("create bitmap 260 50 -bitmap questhead")
# text を作る.
ca1.e("create text 320 50 -text {drag rectangle}")
# window を作る(クローズボタン).
ca1.e("create window 200 200 -window", b1)
# bind により rectangle を drag できるようにする.
cb.push(c = TclTkCallback.new(ip, proc{|i|
# i に x と y を受け取るので, 取り出す.
x, y = i.split(/ /); x = x.to_f; y = y.to_f
# 座標を変更する.
ca1.e("coords current #{x - 5} #{y - 5} #{x + 5} #{y + 5}")},
# x, y 座標を空白で区切ったものをイテレータ変数へ渡すように指定.
"%x %y"))
# rectangle に bind する.
ca1.e("bind", idr, "<B1-Motion>", c)
pack.e(ca1)
end
end
# test driver
if ARGV.size == 0
print "#{$0} n で, n 個のインタプリタを起動します.\n"
n = 1
else
n = ARGV[0].to_i
end
print "start\n"
ip = []
# インタプリタ, ウィジェット等の生成.
for i in 1 .. n
ip.push(Test1.new())
end
# 用意ができたらイベントループに入る.
TclTk.mainloop()
print "exit from mainloop\n"
# インタプリタが GC されるかのテスト.
ip = []
print "GC.start\n" if $DEBUG
GC.start() if $DEBUG
print "end\n"
exit
# end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ripper/test_ripper.rb
|
# frozen_string_literal: false
begin
require 'ripper'
require 'test/unit'
ripper_test = true
module TestRipper; end
rescue LoadError
end
class TestRipper::Ripper < Test::Unit::TestCase
def setup
@ripper = Ripper.new '1 + 1'
end
def test_column
assert_nil @ripper.column
end
def test_encoding
assert_equal Encoding::UTF_8, @ripper.encoding
ripper = Ripper.new('# coding: iso-8859-15')
ripper.parse
assert_equal Encoding::ISO_8859_15, ripper.encoding
ripper = Ripper.new('# -*- coding: iso-8859-15 -*-')
ripper.parse
assert_equal Encoding::ISO_8859_15, ripper.encoding
end
def test_end_seen_eh
@ripper.parse
assert_not_predicate @ripper, :end_seen?
ripper = Ripper.new('__END__')
ripper.parse
assert_predicate ripper, :end_seen?
end
def test_filename
assert_equal '(ripper)', @ripper.filename
filename = "ripper"
ripper = Ripper.new("", filename)
filename.clear
assert_equal "ripper", ripper.filename
end
def test_lineno
assert_nil @ripper.lineno
end
def test_parse
assert_nil @ripper.parse
end
def test_yydebug
assert_not_predicate @ripper, :yydebug
end
def test_yydebug_equals
@ripper.yydebug = true
assert_predicate @ripper, :yydebug
end
end if ripper_test
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/tests/google/models/compute/backend_services_tests.rb
|
<reponame>arnab0073/idea
require 'securerandom'
Shindo.tests("Fog::Compute[:google] | backend_services model", ['google']) do
random_string = SecureRandom.hex
@health_check = create_test_http_health_check(Fog::Compute[:google])
collection_tests(Fog::Compute[:google].backend_services, {:name => "fog-backend-services-test-#{random_string}",
:health_checks => [@health_check]})
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/environment/alias.rb
|
<reponame>arnab0073/idea
module RVM
class Environment
# Returns a hash of aliases.
def alias_list
lines = normalize_array(rvm(:alias, :list).stdout)
lines.inject({}) do |acc, current|
alias_name, ruby_string = current.to_s.split(" => ")
unless alias_name.empty? || ruby_string.empty?
acc[alias_name] = ruby_string
end
acc
end
end
# Shows the full ruby string that a given alias points to.
def alias_show(name)
normalize rvm(:alias, :show, name.to_s).stdout
end
# Deletes an alias and returns the exit status.
def alias_delete(name)
rvm(:alias, :delete, name.to_s).successful?
end
# Creates an alias with the given name.
def alias_create(name, ruby_string)
rvm(:alias, :create, name.to_s, ruby_string.to_s).successful?
end
# Returns an aliases proxy which can be used in a more Ruby-like manner.
def aliases
@aliases ||= AliasWrapper.new(self)
end
# Provides a Ruby-like wrapper to the alias functionality.
class AliasWrapper
def initialize(parent)
@parent = parent
end
# Shows the value of a given alias.
def show(name)
@parent.alias_show name
end
alias [] show
# Deletes the given alias.
def delete(name)
@parent.alias_delete name
end
# Creates an alias with a given name and ruby string.
def create(name, ruby_string)
@parent.alias_create name, ruby_string
end
alias []= create
# Returns a hash of all aliases.
def list
@parent.alias_list
end
alias all list
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/xenserver/requests/compute/create_vdi.rb
|
module Fog
module Compute
class XenServer
class Real
def create_vdi( config )
raise ArgumentError.new('Invalid #config') if config.nil?
raise ArgumentError.new('Missing #virtual_size attribute') if config[:virtual_size].nil?
raise ArgumentError.new('Missing #read_only attribute') if config[:read_only].nil?
raise ArgumentError.new('Missing #type attribute') if config[:type].nil?
raise ArgumentError.new('Missing #sharable attribute') if config[:sharable].nil?
raise ArgumentError.new('Missing #other_config attribute') if config[:other_config].nil?
if config[:storage_repository].nil? && config[:SR].nil? && config[:__sr].nil?
raise ArgumentError.new('Missing StorageRepository reference.')
end
unless config[:storage_repository].nil?
Fog::Logger.deprecation(
'The attribute #storage_repository is deprecated. Use #SR instead.'
)
config[:SR] = config[:storage_repository].reference
end
unless config[:__sr].nil?
Fog::Logger.deprecation(
'The attribute #__sr is deprecated. Use #SR instead.'
)
config[:SR] = config[:__sr]
end
unless config[:name].nil?
Fog::Logger.deprecation(
'The attribute #name is deprecated. Use #name_label instead.'
)
config[:name_label] = config[:name]
end
unless config[:description].nil?
Fog::Logger.deprecation(
'The attribute #description is deprecated. Use #name_description instead.'
)
config[:name_description] = config[:description]
end
config.reject! { |k,v| (k == :__sr) or (k == :storage_repository) }
@connection.request({:parser => Fog::Parsers::XenServer::Base.new, :method => 'VDI.create'}, config )
end
end
class Mock
def create_vdi( ref )
Fog::Mock.not_implemented
end
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rest-client-1.6.9/lib/restclient/net_http_ext.rb
|
<reponame>arnab0073/idea
module Net
class HTTP
# Adding the patch method if it doesn't exist (rest-client issue: https://github.com/archiloque/rest-client/issues/79)
if !defined?(Net::HTTP::Patch)
# Code taken from this commit: https://github.com/ruby/ruby/commit/ab70e53ac3b5102d4ecbe8f38d4f76afad29d37d#lib/net/http.rb
class Protocol
# Sends a PATCH request to the +path+ and gets a response,
# as an HTTPResponse object.
def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
send_entity(path, data, initheader, dest, Patch, &block)
end
# Executes a request which uses a representation
# and returns its body.
def send_entity(path, data, initheader, dest, type, &block)
res = nil
request(type.new(path, initheader), data) {|r|
r.read_body dest, &block
res = r
}
unless @newimpl
res.value
return res, res.body
end
res
end
end
class Patch < HTTPRequest
METHOD = 'PATCH'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
end
#
# Replace the request method in Net::HTTP to sniff the body type
# and set the stream if appropriate
#
# Taken from:
# http://www.missiondata.com/blog/ruby/29/streaming-data-to-s3-with-ruby/
alias __request__ request
def request(req, body=nil, &block)
if body != nil && body.respond_to?(:read)
req.body_stream = body
return __request__(req, nil, &block)
else
return __request__(req, body, &block)
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/clipboard.rb
|
#
# tk/clipboard.rb : methods to treat clipboard
#
require 'tk'
module TkClipboard
include Tk
extend Tk
TkCommandNames = ['clipboard'.freeze].freeze
def self.clear(win=nil)
if win
tk_call_without_enc('clipboard', 'clear', '-displayof', win)
else
tk_call_without_enc('clipboard', 'clear')
end
end
def self.clear_on_display(win)
tk_call_without_enc('clipboard', 'clear', '-displayof', win)
end
def self.get(type=nil)
if type
tk_call_without_enc('clipboard', 'get', '-type', type)
else
tk_call_without_enc('clipboard', 'get')
end
end
def self.get_on_display(win, type=nil)
if type
tk_call_without_enc('clipboard', 'get', '-displayof', win, '-type', type)
else
tk_call_without_enc('clipboard', 'get', '-displayof', win)
end
end
def self.set(data, keys=nil)
clear
append(data, keys)
end
def self.set_on_display(win, data, keys=nil)
clear(win)
append_on_display(win, data, keys)
end
def self.append(data, keys=nil)
args = ['clipboard', 'append']
args.concat(hash_kv(keys))
args.concat(['--', data])
tk_call(*args)
end
def self.append_on_display(win, data, keys=nil)
args = ['clipboard', 'append', '-displayof', win]
args.concat(hash_kv(keys))
args.concat(['--', data])
tk_call(*args)
end
def clear
TkClipboard.clear_on_display(self)
self
end
def get(type=nil)
TkClipboard.get_on_display(self, type)
end
def set(data, keys=nil)
TkClipboard.set_on_display(self, data, keys)
self
end
def append(data, keys=nil)
TkClipboard.append_on_display(self, data, keys)
self
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rdoc/test_rdoc_require.rb
|
<gh_stars>10-100
# frozen_string_literal: false
require File.expand_path '../xref_test_case', __FILE__
class TestRDocRequire < XrefTestCase
def setup
super
@req = RDoc::Require.new 'foo', 'comment'
end
def test_initialize
assert_equal 'foo', @req.name
req = RDoc::Require.new '"foo"', ''
assert_equal 'foo', @req.name
req = RDoc::Require.new '\'foo\'', ''
assert_equal 'foo', @req.name
req = RDoc::Require.new '|foo|', ''
assert_equal 'foo', @req.name, 'for fortran?'
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/lib/net/http.rb
|
#
# = net/http.rb
#
# Copyright (c) 1999-2007 <NAME>
# Copyright (c) 1999-2007 <NAME>
# Copyright (c) 2001 <NAME>
#
# Written and maintained by <NAME> <<EMAIL>>.
# HTTPS support added by GOTOU Yuuzou <<EMAIL>>.
#
# This file is derived from "http-access.rb".
#
# Documented by Minero Aoki; converted to RDoc by <NAME>.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms of ruby itself ---
# Ruby Distribution License or GNU General Public License.
#
# See Net::HTTP for an overview and examples.
#
require 'net/protocol'
require 'uri'
autoload :OpenSSL, 'openssl'
module Net #:nodoc:
# :stopdoc:
class HTTPBadResponse < StandardError; end
class HTTPHeaderSyntaxError < StandardError; end
# :startdoc:
# == An HTTP client API for Ruby.
#
# Net::HTTP provides a rich library which can be used to build HTTP
# user-agents. For more details about HTTP see
# [RFC2616](http://www.ietf.org/rfc/rfc2616.txt)
#
# Net::HTTP is designed to work closely with URI. URI::HTTP#host,
# URI::HTTP#port and URI::HTTP#request_uri are designed to work with
# Net::HTTP.
#
# If you are only performing a few GET requests you should try OpenURI.
#
# == Simple Examples
#
# All examples assume you have loaded Net::HTTP with:
#
# require 'net/http'
#
# This will also require 'uri' so you don't need to require it separately.
#
# The Net::HTTP methods in the following section do not persist
# connections. They are not recommended if you are performing many HTTP
# requests.
#
# === GET
#
# Net::HTTP.get('example.com', '/index.html') # => String
#
# === GET by URI
#
# uri = URI('http://example.com/index.html?count=10')
# Net::HTTP.get(uri) # => String
#
# === GET with Dynamic Parameters
#
# uri = URI('http://example.com/index.html')
# params = { :limit => 10, :page => 3 }
# uri.query = URI.encode_www_form(params)
#
# res = Net::HTTP.get_response(uri)
# puts res.body if res.is_a?(Net::HTTPSuccess)
#
# === POST
#
# uri = URI('http://www.example.com/search.cgi')
# res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
# puts res.body
#
# === POST with Multiple Values
#
# uri = URI('http://www.example.com/search.cgi')
# res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50')
# puts res.body
#
# == How to use Net::HTTP
#
# The following example code can be used as the basis of a HTTP user-agent
# which can perform a variety of request types using persistent
# connections.
#
# uri = URI('http://example.com/some_path?query=string')
#
# Net::HTTP.start(uri.host, uri.port) do |http|
# request = Net::HTTP::Get.new uri.request_uri
#
# response = http.request request # Net::HTTPResponse object
# end
#
# Net::HTTP::start immediately creates a connection to an HTTP server which
# is kept open for the duration of the block. The connection will remain
# open for multiple requests in the block if the server indicates it
# supports persistent connections.
#
# The request types Net::HTTP supports are listed below in the section "HTTP
# Request Classes".
#
# If you wish to re-use a connection across multiple HTTP requests without
# automatically closing it you can use ::new instead of ::start. #request
# will automatically open a connection to the server if one is not currently
# open. You can manually close the connection with #finish.
#
# === Response Data
#
# uri = URI('http://example.com/index.html')
# res = Net::HTTP.get_response(uri)
#
# # Headers
# res['Set-Cookie'] # => String
# res.get_fields('set-cookie') # => Array
# res.to_hash['set-cookie'] # => Array
# puts "Headers: #{res.to_hash.inspect}"
#
# # Status
# puts res.code # => '200'
# puts res.message # => 'OK'
# puts res.class.name # => 'HTTPOK'
#
# # Body
# puts res.body if res.response_body_permitted?
#
# === Following Redirection
#
# Each Net::HTTPResponse object belongs to a class for its response code.
#
# For example, all 2XX responses are instances of a Net::HTTPSuccess
# subclass, a 3XX response is an instance of a Net::HTTPRedirection
# subclass and a 200 response is an instance of the Net::HTTPOK class. For
# details of response classes, see the section "HTTP Response Classes"
# below.
#
# Using a case statement you can handle various types of responses properly:
#
# def fetch(uri_str, limit = 10)
# # You should choose a better exception.
# raise ArgumentError, 'too many HTTP redirects' if limit == 0
#
# response = Net::HTTP.get_response(URI(uri_str))
#
# case response
# when Net::HTTPSuccess then
# response
# when Net::HTTPRedirection then
# location = response['location']
# warn "redirected to #{location}"
# fetch(location, limit - 1)
# else
# response.value
# end
# end
#
# print fetch('http://www.ruby-lang.org')
#
# === POST
#
# A POST can be made using the Net::HTTP::Post request class. This example
# creates a urlencoded POST body:
#
# uri = URI('http://www.example.com/todo.cgi')
# req = Net::HTTP::Post.new(uri.path)
# req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')
#
# res = Net::HTTP.start(uri.hostname, uri.port) do |http|
# http.request(req)
# end
#
# case res
# when Net::HTTPSuccess, Net::HTTPRedirection
# # OK
# else
# res.value
# end
#
# At this time Net::HTTP does not support multipart/form-data. To send
# multipart/form-data use Net::HTTPRequest#body= and
# Net::HTTPRequest#content_type=:
#
# req = Net::HTTP::Post.new(uri.path)
# req.body = multipart_data
# req.content_type = 'multipart/form-data'
#
# Other requests that can contain a body such as PUT can be created in the
# same way using the corresponding request class (Net::HTTP::Put).
#
# === Setting Headers
#
# The following example performs a conditional GET using the
# If-Modified-Since header. If the files has not been modified since the
# time in the header a Not Modified response will be returned. See RFC 2616
# section 9.3 for further details.
#
# uri = URI('http://example.com/cached_response')
# file = File.stat 'cached_response'
#
# req = Net::HTTP::Get.new(uri.request_uri)
# req['If-Modified-Since'] = file.mtime.rfc2822
#
# res = Net::HTTP.start(uri.hostname, uri.port) {|http|
# http.request(req)
# }
#
# open 'cached_response', 'w' do |io|
# io.write res.body
# end if res.is_a?(Net::HTTPSuccess)
#
# === Basic Authentication
#
# Basic authentication is performed according to
# [RFC2617](http://www.ietf.org/rfc/rfc2617.txt)
#
# uri = URI('http://example.com/index.html?key=value')
#
# req = Net::HTTP::Get.new(uri.request_uri)
# req.basic_auth 'user', 'pass'
#
# res = Net::HTTP.start(uri.hostname, uri.port) {|http|
# http.request(req)
# }
# puts res.body
#
# === Streaming Response Bodies
#
# By default Net::HTTP reads an entire response into memory. If you are
# handling large files or wish to implement a progress bar you can instead
# stream the body directly to an IO.
#
# uri = URI('http://example.com/large_file')
#
# Net::HTTP.start(uri.host, uri.port) do |http|
# request = Net::HTTP::Get.new uri.request_uri
#
# http.request request do |response|
# open 'large_file', 'w' do |io|
# response.read_body do |chunk|
# io.write chunk
# end
# end
# end
# end
#
# === HTTPS
#
# HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl=.
#
# uri = URI('https://secure.example.com/some_path?query=string')
#
# Net::HTTP.start(uri.host, uri.port,
# :use_ssl => uri.scheme == 'https').start do |http|
# request = Net::HTTP::Get.new uri.request_uri
#
# response = http.request request # Net::HTTPResponse object
# end
#
# In previous versions of ruby you would need to require 'net/https' to use
# HTTPS. This is no longer true.
#
# === Proxies
#
# Net::HTTP::Proxy has the same methods as Net::HTTP but its instances always
# connect via the proxy instead of directly to the given host.
#
# proxy_addr = 'your.proxy.host'
# proxy_port = 8080
#
# Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http|
# # always connect to your.proxy.addr:8080
# }
#
# Net::HTTP::Proxy returns a Net::HTTP instance when proxy_addr is nil so
# there is no need for conditional code.
#
# See Net::HTTP::Proxy for further details and examples such as proxies that
# require a username and password.
#
# == HTTP Request Classes
#
# Here is the HTTP request class hierarchy.
#
# * Net::HTTPRequest
# * Net::HTTP::Get
# * Net::HTTP::Head
# * Net::HTTP::Post
# * Net::HTTP::Put
# * Net::HTTP::Proppatch
# * Net::HTTP::Lock
# * Net::HTTP::Unlock
# * Net::HTTP::Options
# * Net::HTTP::Propfind
# * Net::HTTP::Delete
# * Net::HTTP::Move
# * Net::HTTP::Copy
# * Net::HTTP::Mkcol
# * Net::HTTP::Trace
#
# == HTTP Response Classes
#
# Here is HTTP response class hierarchy. All classes are defined in Net
# module and are subclasses of Net::HTTPResponse.
#
# HTTPUnknownResponse:: For unhandled HTTP extensions
# HTTPInformation:: 1xx
# HTTPContinue:: 100
# HTTPSwitchProtocol:: 101
# HTTPSuccess:: 2xx
# HTTPOK:: 200
# HTTPCreated:: 201
# HTTPAccepted:: 202
# HTTPNonAuthoritativeInformation:: 203
# HTTPNoContent:: 204
# HTTPResetContent:: 205
# HTTPPartialContent:: 206
# HTTPRedirection:: 3xx
# HTTPMultipleChoice:: 300
# HTTPMovedPermanently:: 301
# HTTPFound:: 302
# HTTPSeeOther:: 303
# HTTPNotModified:: 304
# HTTPUseProxy:: 305
# HTTPTemporaryRedirect:: 307
# HTTPClientError:: 4xx
# HTTPBadRequest:: 400
# HTTPUnauthorized:: 401
# HTTPPaymentRequired:: 402
# HTTPForbidden:: 403
# HTTPNotFound:: 404
# HTTPMethodNotAllowed:: 405
# HTTPNotAcceptable:: 406
# HTTPProxyAuthenticationRequired:: 407
# HTTPRequestTimeOut:: 408
# HTTPConflict:: 409
# HTTPGone:: 410
# HTTPLengthRequired:: 411
# HTTPPreconditionFailed:: 412
# HTTPRequestEntityTooLarge:: 413
# HTTPRequestURITooLong:: 414
# HTTPUnsupportedMediaType:: 415
# HTTPRequestedRangeNotSatisfiable:: 416
# HTTPExpectationFailed:: 417
# HTTPServerError:: 5xx
# HTTPInternalServerError:: 500
# HTTPNotImplemented:: 501
# HTTPBadGateway:: 502
# HTTPServiceUnavailable:: 503
# HTTPGatewayTimeOut:: 504
# HTTPVersionNotSupported:: 505
#
# There is also the Net::HTTPBadResponse exception which is raised when
# there is a protocol error.
#
class HTTP < Protocol
# :stopdoc:
Revision = %q$Revision: 42461 $.split[1]
HTTPVersion = '1.1'
begin
require 'zlib'
require 'stringio' #for our purposes (unpacking gzip) lump these together
HAVE_ZLIB=true
rescue LoadError
HAVE_ZLIB=false
end
# :startdoc:
# Turns on net/http 1.2 (ruby 1.8) features.
# Defaults to ON in ruby 1.8 or later.
def HTTP.version_1_2
true
end
# Returns true if net/http is in version 1.2 mode.
# Defaults to true.
def HTTP.version_1_2?
true
end
def HTTP.version_1_1? #:nodoc:
false
end
class << HTTP
alias is_version_1_1? version_1_1? #:nodoc:
alias is_version_1_2? version_1_2? #:nodoc:
end
#
# short cut methods
#
#
# Gets the body text from the target and outputs it to $stdout. The
# target can either be specified as
# (+uri+), or as (+host+, +path+, +port+ = 80); so:
#
# Net::HTTP.get_print URI('http://www.example.com/index.html')
#
# or:
#
# Net::HTTP.get_print 'www.example.com', '/index.html'
#
def HTTP.get_print(uri_or_host, path = nil, port = nil)
get_response(uri_or_host, path, port) {|res|
res.read_body do |chunk|
$stdout.print chunk
end
}
nil
end
# Sends a GET request to the target and returns the HTTP response
# as a string. The target can either be specified as
# (+uri+), or as (+host+, +path+, +port+ = 80); so:
#
# print Net::HTTP.get(URI('http://www.example.com/index.html'))
#
# or:
#
# print Net::HTTP.get('www.example.com', '/index.html')
#
def HTTP.get(uri_or_host, path = nil, port = nil)
get_response(uri_or_host, path, port).body
end
# Sends a GET request to the target and returns the HTTP response
# as a Net::HTTPResponse object. The target can either be specified as
# (+uri+), or as (+host+, +path+, +port+ = 80); so:
#
# res = Net::HTTP.get_response(URI('http://www.example.com/index.html'))
# print res.body
#
# or:
#
# res = Net::HTTP.get_response('www.example.com', '/index.html')
# print res.body
#
def HTTP.get_response(uri_or_host, path = nil, port = nil, &block)
if path
host = uri_or_host
new(host, port || HTTP.default_port).start {|http|
return http.request_get(path, &block)
}
else
uri = uri_or_host
new(uri.hostname, uri.port).start {|http|
return http.request_get(uri.request_uri, &block)
}
end
end
# Posts HTML form data to the specified URI object.
# The form data must be provided as a Hash mapping from String to String.
# Example:
#
# { "cmd" => "search", "q" => "ruby", "max" => "50" }
#
# This method also does Basic Authentication iff +url+.user exists.
# But userinfo for authentication is deprecated (RFC3986).
# So this feature will be removed.
#
# Example:
#
# require 'net/http'
# require 'uri'
#
# HTTP.post_form URI('http://www.example.com/search.cgi'),
# { "q" => "ruby", "max" => "50" }
#
def HTTP.post_form(url, params)
req = Post.new(url.request_uri)
req.form_data = params
req.basic_auth url.user, url.password if url.user
new(url.hostname, url.port).start {|http|
http.request(req)
}
end
#
# HTTP session management
#
# The default port to use for HTTP requests; defaults to 80.
def HTTP.default_port
http_default_port()
end
# The default port to use for HTTP requests; defaults to 80.
def HTTP.http_default_port
80
end
# The default port to use for HTTPS requests; defaults to 443.
def HTTP.https_default_port
443
end
def HTTP.socket_type #:nodoc: obsolete
BufferedIO
end
# call-seq:
# HTTP.start(address, port, p_addr, p_port, p_user, p_pass, &block)
# HTTP.start(address, port=nil, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt, &block)
#
# Creates a new Net::HTTP object, then additionally opens the TCP
# connection and HTTP session.
#
# Arguments are the following:
# _address_ :: hostname or IP address of the server
# _port_ :: port of the server
# _p_addr_ :: address of proxy
# _p_port_ :: port of proxy
# _p_user_ :: user of proxy
# _p_pass_ :: <PASSWORD> of <PASSWORD>
# _opt_ :: optional hash
#
# _opt_ sets following values by its accessor.
# The keys are ca_file, ca_path, cert, cert_store, ciphers,
# close_on_empty_response, key, open_timeout, read_timeout, ssl_timeout,
# ssl_version, use_ssl, verify_callback, verify_depth and verify_mode.
# If you set :use_ssl as true, you can use https and default value of
# verify_mode is set as OpenSSL::SSL::VERIFY_PEER.
#
# If the optional block is given, the newly
# created Net::HTTP object is passed to it and closed when the
# block finishes. In this case, the return value of this method
# is the return value of the block. If no block is given, the
# return value of this method is the newly created Net::HTTP object
# itself, and the caller is responsible for closing it upon completion
# using the finish() method.
def HTTP.start(address, *arg, &block) # :yield: +http+
arg.pop if opt = Hash.try_convert(arg[-1])
port, p_addr, p_port, p_user, p_pass = *arg
port = https_default_port if !port && opt && opt[:use_ssl]
http = new(address, port, p_addr, p_port, p_user, p_pass)
if opt
if opt[:use_ssl]
opt = {verify_mode: OpenSSL::SSL::VERIFY_PEER}.update(opt)
end
http.methods.grep(/\A(\w+)=\z/) do |meth|
key = $1.to_sym
opt.key?(key) or next
http.__send__(meth, opt[key])
end
end
http.start(&block)
end
class << HTTP
alias newobj new
end
# Creates a new Net::HTTP object without opening a TCP connection or
# HTTP session.
# The +address+ should be a DNS hostname or IP address.
# If +p_addr+ is given, creates a Net::HTTP object with proxy support.
def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
end
# Creates a new Net::HTTP object for the specified server address,
# without opening the TCP connection or initializing the HTTP session.
# The +address+ should be a DNS hostname or IP address.
def initialize(address, port = nil)
@address = address
@port = (port || HTTP.default_port)
@curr_http_version = HTTPVersion
@no_keepalive_server = false
@close_on_empty_response = false
@socket = nil
@started = false
@open_timeout = nil
@read_timeout = 60
@continue_timeout = nil
@debug_output = nil
@use_ssl = false
@ssl_context = nil
@enable_post_connection_check = true
@compression = nil
@sspi_enabled = false
if defined?(SSL_ATTRIBUTES)
SSL_ATTRIBUTES.each do |name|
instance_variable_set "@#{name}", nil
end
end
end
def inspect
"#<#{self.class} #{@address}:#{@port} open=#{started?}>"
end
# *WARNING* This method opens a serious security hole.
# Never use this method in production code.
#
# Sets an output stream for debugging.
#
# http = Net::HTTP.new
# http.set_debug_output $stderr
# http.start { .... }
#
def set_debug_output(output)
warn 'Net::HTTP#set_debug_output called after HTTP started' if started?
@debug_output = output
end
# The DNS host name or IP address to connect to.
attr_reader :address
# The port number to connect to.
attr_reader :port
# Number of seconds to wait for the connection to open. Any number
# may be used, including Floats for fractional seconds. If the HTTP
# object cannot open a connection in this many seconds, it raises a
# TimeoutError exception. The default value is +nil+.
attr_accessor :open_timeout
# Number of seconds to wait for one block to be read (via one read(2)
# call). Any number may be used, including Floats for fractional
# seconds. If the HTTP object cannot read data in this many seconds,
# it raises a TimeoutError exception. The default value is 60 seconds.
attr_reader :read_timeout
# Setter for the read_timeout attribute.
def read_timeout=(sec)
@socket.read_timeout = sec if @socket
@read_timeout = sec
end
# Seconds to wait for 100 Continue response. If the HTTP object does not
# receive a response in this many seconds it sends the request body. The
# default value is +nil+.
attr_reader :continue_timeout
# Setter for the continue_timeout attribute.
def continue_timeout=(sec)
@socket.continue_timeout = sec if @socket
@continue_timeout = sec
end
# Returns true if the HTTP session has been started.
def started?
@started
end
alias active? started? #:nodoc: obsolete
attr_accessor :close_on_empty_response
# Returns true if SSL/TLS is being used with HTTP.
def use_ssl?
@use_ssl
end
# Turn on/off SSL.
# This flag must be set before starting session.
# If you change use_ssl value after session started,
# a Net::HTTP object raises IOError.
def use_ssl=(flag)
flag = flag ? true : false
if started? and @use_ssl != flag
raise IOError, "use_ssl value changed, but session already started"
end
@use_ssl = flag
end
SSL_ATTRIBUTES = %w(
ssl_version key cert ca_file ca_path cert_store ciphers
verify_mode verify_callback verify_depth ssl_timeout
)
# Sets path of a CA certification file in PEM format.
#
# The file can contain several CA certificates.
attr_accessor :ca_file
# Sets path of a CA certification directory containing certifications in
# PEM format.
attr_accessor :ca_path
# Sets an OpenSSL::X509::Certificate object as client certificate.
# (This method is appeared in Michal Rokos's OpenSSL extension).
attr_accessor :cert
# Sets the X509::Store to verify peer certificate.
attr_accessor :cert_store
# Sets the available ciphers. See OpenSSL::SSL::SSLContext#ciphers=
attr_accessor :ciphers
# Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
# (This method is appeared in Michal Rokos's OpenSSL extension.)
attr_accessor :key
# Sets the SSL timeout seconds.
attr_accessor :ssl_timeout
# Sets the SSL version. See OpenSSL::SSL::SSLContext#ssl_version=
attr_accessor :ssl_version
# Sets the verify callback for the server certification verification.
attr_accessor :verify_callback
# Sets the maximum depth for the certificate chain verification.
attr_accessor :verify_depth
# Sets the flags for server the certification verification at beginning of
# SSL/TLS session.
#
# OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable.
attr_accessor :verify_mode
# Returns the X.509 certificates the server presented.
def peer_cert
if not use_ssl? or not @socket
return nil
end
@socket.io.peer_cert
end
# Opens a TCP connection and HTTP session.
#
# When this method is called with a block, it passes the Net::HTTP
# object to the block, and closes the TCP connection and HTTP session
# after the block has been executed.
#
# When called with a block, it returns the return value of the
# block; otherwise, it returns self.
#
def start # :yield: http
raise IOError, 'HTTP session already opened' if @started
if block_given?
begin
do_start
return yield(self)
ensure
do_finish
end
end
do_start
self
end
def do_start
connect
@started = true
end
private :do_start
def connect
D "opening connection to #{conn_address()}..."
s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) }
D "opened"
if use_ssl?
ssl_parameters = Hash.new
iv_list = instance_variables
SSL_ATTRIBUTES.each do |name|
ivname = "@#{name}".intern
if iv_list.include?(ivname) and
value = instance_variable_get(ivname)
ssl_parameters[name] = value
end
end
@ssl_context = OpenSSL::SSL::SSLContext.new
@ssl_context.set_params(ssl_parameters)
s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
s.sync_close = true
end
@socket = BufferedIO.new(s)
@socket.read_timeout = @read_timeout
@socket.continue_timeout = @continue_timeout
@socket.debug_output = @debug_output
if use_ssl?
begin
if proxy?
@socket.writeline sprintf('CONNECT %s:%s HTTP/%s',
@address, @port, HTTPVersion)
@socket.writeline "Host: #{@address}:#{@port}"
if proxy_user
credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')
credential.delete!("\r\n")
@socket.writeline "Proxy-Authorization: Basic #{credential}"
end
@socket.writeline ''
HTTPResponse.read_new(@socket).value
end
# Server Name Indication (SNI) RFC 3546
s.hostname = @address if s.respond_to? :hostname=
timeout(@open_timeout) { s.connect }
if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
s.post_connection_check(@address)
end
rescue => exception
D "Conn close because of connect error #{exception}"
@socket.close if @socket and not @socket.closed?
raise exception
end
end
on_connect
end
private :connect
def on_connect
end
private :on_connect
# Finishes the HTTP session and closes the TCP connection.
# Raises IOError if the session has not been started.
def finish
raise IOError, 'HTTP session not yet started' unless started?
do_finish
end
def do_finish
@started = false
@socket.close if @socket and not @socket.closed?
@socket = nil
end
private :do_finish
#
# proxy
#
public
# no proxy
@is_proxy_class = false
@proxy_addr = nil
@proxy_port = nil
@proxy_user = nil
@proxy_pass = nil
# Creates an HTTP proxy class which behaves like Net::HTTP, but
# performs all access via the specified proxy.
#
# The arguments are the DNS name or IP address of the proxy host,
# the port to use to access the proxy, and a username and password
# if authorization is required to use the proxy.
#
# You can replace any use of the Net::HTTP class with use of the
# proxy class created.
#
# If +p_addr+ is nil, this method returns self (a Net::HTTP object).
#
# # Example
# proxy_class = Net::HTTP::Proxy('proxy.example.com', 8080)
#
# proxy_class.start('www.ruby-lang.org') {|http|
# # connecting proxy.foo.org:8080
# }
#
# You may use them to work with authorization-enabled proxies:
#
# proxy_host = 'your.proxy.example'
# proxy_port = 8080
# proxy_user = 'user'
# proxy_pass = '<PASSWORD>'
#
# proxy = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass)
# proxy.start('www.example.com') { |http|
# # always connect to your.proxy.example:8080 using specified username
# # and password
# }
#
# Note that net/http does not use the HTTP_PROXY environment variable.
# If you want to use a proxy, you must set it explicitly.
#
def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)
return self unless p_addr
delta = ProxyDelta
proxyclass = Class.new(self)
proxyclass.module_eval {
include delta
# with proxy
@is_proxy_class = true
@proxy_address = p_addr
@proxy_port = p_port || default_port()
@proxy_user = p_user
@proxy_pass = <PASSWORD>
}
proxyclass
end
class << HTTP
# returns true if self is a class which was created by HTTP::Proxy.
def proxy_class?
@is_proxy_class
end
# Address of proxy host. If Net::HTTP does not use a proxy, nil.
attr_reader :proxy_address
# Port number of proxy host. If Net::HTTP does not use a proxy, nil.
attr_reader :proxy_port
# User name for accessing proxy. If Net::HTTP does not use a proxy, nil.
attr_reader :proxy_user
# User password for accessing proxy. If Net::HTTP does not use a proxy,
# nil.
attr_reader :proxy_pass
end
# True if self is a HTTP proxy class.
def proxy?
self.class.proxy_class?
end
# A convenience method for accessing value of proxy_address from Net::HTTP.
def proxy_address
self.class.proxy_address
end
# A convenience method for accessing value of proxy_port from Net::HTTP.
def proxy_port
self.class.proxy_port
end
# A convenience method for accessing value of proxy_user from Net::HTTP.
def proxy_user
self.class.proxy_user
end
# A convenience method for accessing value of proxy_pass from Net::HTTP.
def proxy_pass
self.class.proxy_pass
end
alias proxyaddr proxy_address #:nodoc: obsolete
alias proxyport proxy_port #:nodoc: obsolete
private
# without proxy
def conn_address
address()
end
def conn_port
port()
end
def edit_path(path)
path
end
module ProxyDelta #:nodoc: internal use only
private
def conn_address
proxy_address()
end
def conn_port
proxy_port()
end
def edit_path(path)
use_ssl? ? path : "http://#{addr_port()}#{path}"
end
end
#
# HTTP operations
#
public
# Gets data from +path+ on the connected-to host.
# +initheader+ must be a Hash like { 'Accept' => '*/*', ... },
# and it defaults to an empty hash.
# If +initheader+ doesn't have the key 'accept-encoding', then
# a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used,
# so that gzip compression is used in preference to deflate
# compression, which is used in preference to no compression.
# Ruby doesn't have libraries to support the compress (Lempel-Ziv)
# compression, so that is not supported. The intent of this is
# to reduce bandwidth by default. If this routine sets up
# compression, then it does the decompression also, removing
# the header as well to prevent confusion. Otherwise
# it leaves the body as it found it.
#
# This method returns a Net::HTTPResponse object.
#
# If called with a block, yields each fragment of the
# entity body in turn as a string as it is read from
# the socket. Note that in this case, the returned response
# object will *not* contain a (meaningful) body.
#
# +dest+ argument is obsolete.
# It still works but you must not use it.
#
# This method never raises an exception.
#
# response = http.get('/index.html')
#
# # using block
# File.open('result.txt', 'w') {|f|
# http.get('/~foo/') do |str|
# f.write str
# end
# }
#
def get(path, initheader = {}, dest = nil, &block) # :yield: +body_segment+
res = nil
if HAVE_ZLIB
unless initheader.keys.any?{|k| k.downcase == "accept-encoding"}
initheader = initheader.merge({
"accept-encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
})
@compression = true
end
end
request(Get.new(path, initheader)) {|r|
if r.key?("content-encoding") and @compression
@compression = nil # Clear it till next set.
the_body = r.read_body dest, &block
case r["content-encoding"]
when "gzip"
r.body= Zlib::GzipReader.new(StringIO.new(the_body), encoding: "ASCII-8BIT").read
r.delete("content-encoding")
when "deflate"
r.body= Zlib::Inflate.inflate(the_body);
r.delete("content-encoding")
when "identity"
; # nothing needed
else
; # Don't do anything dramatic, unless we need to later
end
else
r.read_body dest, &block
end
res = r
}
res
end
# Gets only the header from +path+ on the connected-to host.
# +header+ is a Hash like { 'Accept' => '*/*', ... }.
#
# This method returns a Net::HTTPResponse object.
#
# This method never raises an exception.
#
# response = nil
# Net::HTTP.start('some.www.server', 80) {|http|
# response = http.head('/index.html')
# }
# p response['content-type']
#
def head(path, initheader = nil)
request(Head.new(path, initheader))
end
# Posts +data+ (must be a String) to +path+. +header+ must be a Hash
# like { 'Accept' => '*/*', ... }.
#
# This method returns a Net::HTTPResponse object.
#
# If called with a block, yields each fragment of the
# entity body in turn as a string as it is read from
# the socket. Note that in this case, the returned response
# object will *not* contain a (meaningful) body.
#
# +dest+ argument is obsolete.
# It still works but you must not use it.
#
# This method never raises exception.
#
# response = http.post('/cgi-bin/search.rb', 'query=foo')
#
# # using block
# File.open('result.txt', 'w') {|f|
# http.post('/cgi-bin/search.rb', 'query=foo') do |str|
# f.write str
# end
# }
#
# You should set Content-Type: header field for POST.
# If no Content-Type: field given, this method uses
# "application/x-www-form-urlencoded" by default.
#
def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
send_entity(path, data, initheader, dest, Post, &block)
end
# Sends a PATCH request to the +path+ and gets a response,
# as an HTTPResponse object.
def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
send_entity(path, data, initheader, dest, Patch, &block)
end
def put(path, data, initheader = nil) #:nodoc:
request(Put.new(path, initheader), data)
end
# Sends a PROPPATCH request to the +path+ and gets a response,
# as an HTTPResponse object.
def proppatch(path, body, initheader = nil)
request(Proppatch.new(path, initheader), body)
end
# Sends a LOCK request to the +path+ and gets a response,
# as an HTTPResponse object.
def lock(path, body, initheader = nil)
request(Lock.new(path, initheader), body)
end
# Sends a UNLOCK request to the +path+ and gets a response,
# as an HTTPResponse object.
def unlock(path, body, initheader = nil)
request(Unlock.new(path, initheader), body)
end
# Sends a OPTIONS request to the +path+ and gets a response,
# as an HTTPResponse object.
def options(path, initheader = nil)
request(Options.new(path, initheader))
end
# Sends a PROPFIND request to the +path+ and gets a response,
# as an HTTPResponse object.
def propfind(path, body = nil, initheader = {'Depth' => '0'})
request(Propfind.new(path, initheader), body)
end
# Sends a DELETE request to the +path+ and gets a response,
# as an HTTPResponse object.
def delete(path, initheader = {'Depth' => 'Infinity'})
request(Delete.new(path, initheader))
end
# Sends a MOVE request to the +path+ and gets a response,
# as an HTTPResponse object.
def move(path, initheader = nil)
request(Move.new(path, initheader))
end
# Sends a COPY request to the +path+ and gets a response,
# as an HTTPResponse object.
def copy(path, initheader = nil)
request(Copy.new(path, initheader))
end
# Sends a MKCOL request to the +path+ and gets a response,
# as an HTTPResponse object.
def mkcol(path, body = nil, initheader = nil)
request(Mkcol.new(path, initheader), body)
end
# Sends a TRACE request to the +path+ and gets a response,
# as an HTTPResponse object.
def trace(path, initheader = nil)
request(Trace.new(path, initheader))
end
# Sends a GET request to the +path+.
# Returns the response as a Net::HTTPResponse object.
#
# When called with a block, passes an HTTPResponse object to the block.
# The body of the response will not have been read yet;
# the block can process it using HTTPResponse#read_body,
# if desired.
#
# Returns the response.
#
# This method never raises Net::* exceptions.
#
# response = http.request_get('/index.html')
# # The entity body is already read in this case.
# p response['content-type']
# puts response.body
#
# # Using a block
# http.request_get('/index.html') {|response|
# p response['content-type']
# response.read_body do |str| # read body now
# print str
# end
# }
#
def request_get(path, initheader = nil, &block) # :yield: +response+
request(Get.new(path, initheader), &block)
end
# Sends a HEAD request to the +path+ and returns the response
# as a Net::HTTPResponse object.
#
# Returns the response.
#
# This method never raises Net::* exceptions.
#
# response = http.request_head('/index.html')
# p response['content-type']
#
def request_head(path, initheader = nil, &block)
request(Head.new(path, initheader), &block)
end
# Sends a POST request to the +path+.
#
# Returns the response as a Net::HTTPResponse object.
#
# When called with a block, the block is passed an HTTPResponse
# object. The body of that response will not have been read yet;
# the block can process it using HTTPResponse#read_body, if desired.
#
# Returns the response.
#
# This method never raises Net::* exceptions.
#
# # example
# response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
# p response.status
# puts response.body # body is already read in this case
#
# # using block
# http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
# p response.status
# p response['content-type']
# response.read_body do |str| # read body now
# print str
# end
# }
#
def request_post(path, data, initheader = nil, &block) # :yield: +response+
request Post.new(path, initheader), data, &block
end
def request_put(path, data, initheader = nil, &block) #:nodoc:
request Put.new(path, initheader), data, &block
end
alias get2 request_get #:nodoc: obsolete
alias head2 request_head #:nodoc: obsolete
alias post2 request_post #:nodoc: obsolete
alias put2 request_put #:nodoc: obsolete
# Sends an HTTP request to the HTTP server.
# Also sends a DATA string if +data+ is given.
#
# Returns a Net::HTTPResponse object.
#
# This method never raises Net::* exceptions.
#
# response = http.send_request('GET', '/index.html')
# puts response.body
#
def send_request(name, path, data = nil, header = nil)
r = HTTPGenericRequest.new(name,(data ? true : false),true,path,header)
request r, data
end
# Sends an HTTPRequest object +req+ to the HTTP server.
#
# If +req+ is a Net::HTTP::Post or Net::HTTP::Put request containing
# data, the data is also sent. Providing data for a Net::HTTP::Head or
# Net::HTTP::Get request results in an ArgumentError.
#
# Returns an HTTPResponse object.
#
# When called with a block, passes an HTTPResponse object to the block.
# The body of the response will not have been read yet;
# the block can process it using HTTPResponse#read_body,
# if desired.
#
# This method never raises Net::* exceptions.
#
def request(req, body = nil, &block) # :yield: +response+
unless started?
start {
req['connection'] ||= 'close'
return request(req, body, &block)
}
end
if proxy_user()
req.proxy_basic_auth proxy_user(), proxy_pass() unless use_ssl?
end
req.set_body_internal body
res = transport_request(req, &block)
if sspi_auth?(res)
sspi_auth(req)
res = transport_request(req, &block)
end
res
end
private
# Executes a request which uses a representation
# and returns its body.
def send_entity(path, data, initheader, dest, type, &block)
res = nil
request(type.new(path, initheader), data) {|r|
r.read_body dest, &block
res = r
}
res
end
def transport_request(req)
begin_transport req
res = catch(:response) {
req.exec @socket, @curr_http_version, edit_path(req.path)
begin
res = HTTPResponse.read_new(@socket)
end while res.kind_of?(HTTPContinue)
res.reading_body(@socket, req.response_body_permitted?) {
yield res if block_given?
}
res
}
end_transport req, res
res
rescue => exception
D "Conn close because of error #{exception}"
@socket.close if @socket and not @socket.closed?
raise exception
end
def begin_transport(req)
connect if @socket.closed?
if not req.response_body_permitted? and @close_on_empty_response
req['connection'] ||= 'close'
end
req['host'] ||= addr_port()
end
def end_transport(req, res)
@curr_http_version = res.http_version
if @socket.closed?
D 'Conn socket closed'
elsif not res.body and @close_on_empty_response
D 'Conn close'
@socket.close
elsif keep_alive?(req, res)
D 'Conn keep-alive'
else
D 'Conn close'
@socket.close
end
end
def keep_alive?(req, res)
return false if req.connection_close?
if @curr_http_version <= '1.0'
res.connection_keep_alive?
else # HTTP/1.1 or later
not res.connection_close?
end
end
def sspi_auth?(res)
return false unless @sspi_enabled
if res.kind_of?(HTTPProxyAuthenticationRequired) and
proxy? and res["Proxy-Authenticate"].include?("Negotiate")
begin
require 'win32/sspi'
true
rescue LoadError
false
end
else
false
end
end
def sspi_auth(req)
n = Win32::SSPI::NegotiateAuth.new
req["Proxy-Authorization"] = "Negotiate #{n.get_initial_token}"
# Some versions of ISA will close the connection if this isn't present.
req["Connection"] = "Keep-Alive"
req["Proxy-Connection"] = "Keep-Alive"
res = transport_request(req)
authphrase = res["Proxy-Authenticate"] or return res
req["Proxy-Authorization"] = "Negotiate #{n.complete_authentication(authphrase)}"
rescue => err
raise HTTPAuthenticationError.new('HTTP authentication failed', err)
end
#
# utils
#
private
def addr_port
if use_ssl?
address() + (port == HTTP.https_default_port ? '' : ":#{port()}")
else
address() + (port == HTTP.http_default_port ? '' : ":#{port()}")
end
end
def D(msg)
return unless @debug_output
@debug_output << msg
@debug_output << "\n"
end
end
HTTPSession = HTTP
# The HTTPHeader module defines methods for reading and writing
# HTTP headers.
#
# It is used as a mixin by other classes, to provide hash-like
# access to HTTP header values. Unlike raw hash access, HTTPHeader
# provides access via case-insensitive keys. It also provides
# methods for accessing commonly-used HTTP header values in more
# convenient formats.
#
module HTTPHeader
def initialize_http_header(initheader)
@header = {}
return unless initheader
initheader.each do |key, value|
warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE
@header[key.downcase] = [value.strip]
end
end
def size #:nodoc: obsolete
@header.size
end
alias length size #:nodoc: obsolete
# Returns the header field corresponding to the case-insensitive key.
# For example, a key of "Content-Type" might return "text/html"
def [](key)
a = @header[key.downcase] or return nil
a.join(', ')
end
# Sets the header field corresponding to the case-insensitive key.
def []=(key, val)
unless val
@header.delete key.downcase
return val
end
@header[key.downcase] = [val]
end
# [Ruby 1.8.3]
# Adds a value to a named header field, instead of replacing its value.
# Second argument +val+ must be a String.
# See also #[]=, #[] and #get_fields.
#
# request.add_field 'X-My-Header', 'a'
# p request['X-My-Header'] #=> "a"
# p request.get_fields('X-My-Header') #=> ["a"]
# request.add_field 'X-My-Header', 'b'
# p request['X-My-Header'] #=> "a, b"
# p request.get_fields('X-My-Header') #=> ["a", "b"]
# request.add_field 'X-My-Header', 'c'
# p request['X-My-Header'] #=> "a, b, c"
# p request.get_fields('X-My-Header') #=> ["a", "b", "c"]
#
def add_field(key, val)
if @header.key?(key.downcase)
@header[key.downcase].push val
else
@header[key.downcase] = [val]
end
end
# [Ruby 1.8.3]
# Returns an array of header field strings corresponding to the
# case-insensitive +key+. This method allows you to get duplicated
# header fields without any processing. See also #[].
#
# p response.get_fields('Set-Cookie')
# #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
# "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
# p response['Set-Cookie']
# #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
#
def get_fields(key)
return nil unless @header[key.downcase]
@header[key.downcase].dup
end
# Returns the header field corresponding to the case-insensitive key.
# Returns the default value +args+, or the result of the block, or
# raises an IndexError if there's no header field named +key+
# See Hash#fetch
def fetch(key, *args, &block) #:yield: +key+
a = @header.fetch(key.downcase, *args, &block)
a.kind_of?(Array) ? a.join(', ') : a
end
# Iterates through the header names and values, passing in the name
# and value to the code block supplied.
#
# Example:
#
# response.header.each_header {|key,value| puts "#{key} = #{value}" }
#
def each_header #:yield: +key+, +value+
block_given? or return enum_for(__method__)
@header.each do |k,va|
yield k, va.join(', ')
end
end
alias each each_header
# Iterates through the header names in the header, passing
# each header name to the code block.
def each_name(&block) #:yield: +key+
block_given? or return enum_for(__method__)
@header.each_key(&block)
end
alias each_key each_name
# Iterates through the header names in the header, passing
# capitalized header names to the code block.
#
# Note that header names are capitalized systematically;
# capitalization may not match that used by the remote HTTP
# server in its response.
def each_capitalized_name #:yield: +key+
block_given? or return enum_for(__method__)
@header.each_key do |k|
yield capitalize(k)
end
end
# Iterates through header values, passing each value to the
# code block.
def each_value #:yield: +value+
block_given? or return enum_for(__method__)
@header.each_value do |va|
yield va.join(', ')
end
end
# Removes a header field, specified by case-insensitive key.
def delete(key)
@header.delete(key.downcase)
end
# true if +key+ header exists.
def key?(key)
@header.key?(key.downcase)
end
# Returns a Hash consisting of header names and values.
# e.g.
# {"cache-control" => "private",
# "content-type" => "text/html",
# "date" => "Wed, 22 Jun 2005 22:11:50 GMT"}
def to_hash
@header.dup
end
# As for #each_header, except the keys are provided in capitalized form.
#
# Note that header names are capitalized systematically;
# capitalization may not match that used by the remote HTTP
# server in its response.
def each_capitalized
block_given? or return enum_for(__method__)
@header.each do |k,v|
yield capitalize(k), v.join(', ')
end
end
alias canonical_each each_capitalized
def capitalize(name)
name.split(/-/).map {|s| s.capitalize }.join('-')
end
private :capitalize
# Returns an Array of Range objects which represent the Range:
# HTTP header field, or +nil+ if there is no such header.
def range
return nil unless @header['range']
self['Range'].split(/,/).map {|spec|
m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
d1 = m[1].to_i
d2 = m[2].to_i
if m[1] and m[2] then d1..d2
elsif m[1] then d1..-1
elsif m[2] then -d2..-1
else
raise HTTPHeaderSyntaxError, 'range is not specified'
end
}
end
# Sets the HTTP Range: header.
# Accepts either a Range object as a single argument,
# or a beginning index and a length from that index.
# Example:
#
# req.range = (0..1023)
# req.set_range 0, 1023
#
def set_range(r, e = nil)
unless r
@header.delete 'range'
return r
end
r = (r...r+e) if e
case r
when Numeric
n = r.to_i
rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
when Range
first = r.first
last = r.last
last -= 1 if r.exclude_end?
if last == -1
rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
else
raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
rangestr = "#{first}-#{last}"
end
else
raise TypeError, 'Range/Integer is required'
end
@header['range'] = ["bytes=#{rangestr}"]
r
end
alias range= set_range
# Returns an Integer object which represents the HTTP Content-Length:
# header field, or +nil+ if that field was not provided.
def content_length
return nil unless key?('Content-Length')
len = self['Content-Length'].slice(/\d+/) or
raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
len.to_i
end
def content_length=(len)
unless len
@header.delete 'content-length'
return nil
end
@header['content-length'] = [len.to_i.to_s]
end
# Returns "true" if the "transfer-encoding" header is present and
# set to "chunked". This is an HTTP/1.1 feature, allowing the
# the content to be sent in "chunks" without at the outset
# stating the entire content length.
def chunked?
return false unless @header['transfer-encoding']
field = self['Transfer-Encoding']
(/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
end
# Returns a Range object which represents the value of the Content-Range:
# header field.
# For a partial entity body, this indicates where this fragment
# fits inside the full entity body, as range of byte offsets.
def content_range
return nil unless @header['content-range']
m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
m[1].to_i .. m[2].to_i
end
# The length of the range represented in Content-Range: header.
def range_length
r = content_range() or return nil
r.end - r.begin + 1
end
# Returns a content type string such as "text/html".
# This method returns nil if Content-Type: header field does not exist.
def content_type
return nil unless main_type()
if sub_type()
then "#{main_type()}/#{sub_type()}"
else main_type()
end
end
# Returns a content type string such as "text".
# This method returns nil if Content-Type: header field does not exist.
def main_type
return nil unless @header['content-type']
self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
end
# Returns a content type string such as "html".
# This method returns nil if Content-Type: header field does not exist
# or sub-type is not given (e.g. "Content-Type: text").
def sub_type
return nil unless @header['content-type']
_, sub = *self['Content-Type'].split(';').first.to_s.split('/')
return nil unless sub
sub.strip
end
# Any parameters specified for the content type, returned as a Hash.
# For example, a header of Content-Type: text/html; charset=EUC-JP
# would result in type_params returning {'charset' => 'EUC-JP'}
def type_params
result = {}
list = self['Content-Type'].to_s.split(';')
list.shift
list.each do |param|
k, v = *param.split('=', 2)
result[k.strip] = v.strip
end
result
end
# Sets the content type in an HTTP header.
# The +type+ should be a full HTTP content type, e.g. "text/html".
# The +params+ are an optional Hash of parameters to add after the
# content type, e.g. {'charset' => 'iso-8859-1'}
def set_content_type(type, params = {})
@header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
end
alias content_type= set_content_type
# Set header fields and a body from HTML form data.
# +params+ should be an Array of Arrays or
# a Hash containing HTML form data.
# Optional argument +sep+ means data record separator.
#
# Values are URL encoded as necessary and the content-type is set to
# application/x-www-form-urlencoded
#
# Example:
# http.form_data = {"q" => "ruby", "lang" => "en"}
# http.form_data = {"q" => ["ruby", "perl"], "lang" => "en"}
# http.set_form_data({"q" => "ruby", "lang" => "en"}, ';')
#
def set_form_data(params, sep = '&')
query = URI.encode_www_form(params)
query.gsub!(/&/, sep) if sep != '&'
self.body = query
self.content_type = 'application/x-www-form-urlencoded'
end
alias form_data= set_form_data
# Set a HTML form data set.
# +params+ is the form data set; it is an Array of Arrays or a Hash
# +enctype is the type to encode the form data set.
# It is application/x-www-form-urlencoded or multipart/form-data.
# +formpot+ is an optional hash to specify the detail.
#
# boundary:: the boundary of the multipart message
# charset:: the charset of the message. All names and the values of
# non-file fields are encoded as the charset.
#
# Each item of params is an array and contains following items:
# +name+:: the name of the field
# +value+:: the value of the field, it should be a String or a File
# +opt+:: an optional hash to specify additional information
#
# Each item is a file field or a normal field.
# If +value+ is a File object or the +opt+ have a filename key,
# the item is treated as a file field.
#
# If Transfer-Encoding is set as chunked, this send the request in
# chunked encoding. Because chunked encoding is HTTP/1.1 feature,
# you must confirm the server to support HTTP/1.1 before sending it.
#
# Example:
# http.set_form([["q", "ruby"], ["lang", "en"]])
#
# See also RFC 2388, RFC 2616, HTML 4.01, and HTML5
#
def set_form(params, enctype='application/x-www-form-urlencoded', formopt={})
@body_data = params
@body = nil
@body_stream = nil
@form_option = formopt
case enctype
when /\Aapplication\/x-www-form-urlencoded\z/i,
/\Amultipart\/form-data\z/i
self.content_type = enctype
else
raise ArgumentError, "invalid enctype: #{enctype}"
end
end
# Set the Authorization: header for "Basic" authorization.
def basic_auth(account, password)
@header['authorization'] = [basic_encode(account, password)]
end
# Set Proxy-Authorization: header for "Basic" authorization.
def proxy_basic_auth(account, password)
@header['proxy-authorization'] = [basic_encode(account, password)]
end
def basic_encode(account, password)
'Basic ' + ["#{account}:#{password}"].pack('m').delete("\r\n")
end
private :basic_encode
def connection_close?
tokens(@header['connection']).include?('close') or
tokens(@header['proxy-connection']).include?('close')
end
def connection_keep_alive?
tokens(@header['connection']).include?('keep-alive') or
tokens(@header['proxy-connection']).include?('keep-alive')
end
def tokens(vals)
return [] unless vals
vals.map {|v| v.split(',') }.flatten\
.reject {|str| str.strip.empty? }\
.map {|tok| tok.strip.downcase }
end
private :tokens
end
# HTTPGenericRequest is the parent of the HTTPRequest class.
# Do not use this directly; use a subclass of HTTPRequest.
#
# Mixes in the HTTPHeader module to provide easier access to HTTP headers.
#
class HTTPGenericRequest
include HTTPHeader
def initialize(m, reqbody, resbody, path, initheader = nil)
@method = m
@request_has_body = reqbody
@response_has_body = resbody
raise ArgumentError, "no HTTP request path given" unless path
raise ArgumentError, "HTTP request path is empty" if path.empty?
@path = path
initialize_http_header initheader
self['Accept'] ||= '*/*'
self['User-Agent'] ||= 'Ruby'
@body = nil
@body_stream = nil
@body_data = nil
end
attr_reader :method
attr_reader :path
def inspect
"\#<#{self.class} #{@method}>"
end
def request_body_permitted?
@request_has_body
end
def response_body_permitted?
@response_has_body
end
def body_exist?
warn "Net::HTTPRequest#body_exist? is obsolete; use response_body_permitted?" if $VERBOSE
response_body_permitted?
end
attr_reader :body
def body=(str)
@body = str
@body_stream = nil
@body_data = nil
str
end
attr_reader :body_stream
def body_stream=(input)
@body = nil
@body_stream = input
@body_data = nil
input
end
def set_body_internal(str) #:nodoc: internal use only
raise ArgumentError, "both of body argument and HTTPRequest#body set" if str and (@body or @body_stream)
self.body = str if str
end
#
# write
#
def exec(sock, ver, path) #:nodoc: internal use only
if @body
send_request_with_body sock, ver, path, @body
elsif @body_stream
send_request_with_body_stream sock, ver, path, @body_stream
elsif @body_data
send_request_with_body_data sock, ver, path, @body_data
else
write_header sock, ver, path
end
end
private
def send_request_with_body(sock, ver, path, body)
self.content_length = body.bytesize
delete 'Transfer-Encoding'
supply_default_content_type
write_header sock, ver, path
wait_for_continue sock, ver if sock.continue_timeout
sock.write body
end
def send_request_with_body_stream(sock, ver, path, f)
unless content_length() or chunked?
raise ArgumentError,
"Content-Length not given and Transfer-Encoding is not `chunked'"
end
supply_default_content_type
write_header sock, ver, path
wait_for_continue sock, ver if sock.continue_timeout
if chunked?
while s = f.read(1024)
sock.write(sprintf("%x\r\n", s.bytesize) << s << "\r\n")
end
sock.write "0\r\n\r\n"
else
while s = f.read(1024)
sock.write s
end
end
end
def send_request_with_body_data(sock, ver, path, params)
if /\Amultipart\/form-data\z/i !~ self.content_type
self.content_type = 'application/x-www-form-urlencoded'
return send_request_with_body(sock, ver, path, URI.encode_www_form(params))
end
opt = @form_option.dup
require 'securerandom' unless defined?(SecureRandom)
opt[:boundary] ||= SecureRandom.urlsafe_base64(40)
self.set_content_type(self.content_type, boundary: opt[:boundary])
if chunked?
write_header sock, ver, path
encode_multipart_form_data(sock, params, opt)
else
require 'tempfile'
file = Tempfile.new('multipart')
file.binmode
encode_multipart_form_data(file, params, opt)
file.rewind
self.content_length = file.size
write_header sock, ver, path
IO.copy_stream(file, sock)
end
end
def encode_multipart_form_data(out, params, opt)
charset = opt[:charset]
boundary = opt[:boundary]
require 'securerandom' unless defined?(SecureRandom)
boundary ||= SecureRandom.urlsafe_base64(40)
chunked_p = chunked?
buf = ''
params.each do |key, value, h={}|
key = quote_string(key, charset)
filename =
h.key?(:filename) ? h[:filename] :
value.respond_to?(:to_path) ? File.basename(value.to_path) :
nil
buf << "--#{boundary}\r\n"
if filename
filename = quote_string(filename, charset)
type = h[:content_type] || 'application/octet-stream'
buf << "Content-Disposition: form-data; " \
"name=\"#{key}\"; filename=\"#{filename}\"\r\n" \
"Content-Type: #{type}\r\n\r\n"
if !out.respond_to?(:write) || !value.respond_to?(:read)
# if +out+ is not an IO or +value+ is not an IO
buf << (value.respond_to?(:read) ? value.read : value)
elsif value.respond_to?(:size) && chunked_p
# if +out+ is an IO and +value+ is a File, use IO.copy_stream
flush_buffer(out, buf, chunked_p)
out << "%x\r\n" % value.size if chunked_p
IO.copy_stream(value, out)
out << "\r\n" if chunked_p
else
# +out+ is an IO, and +value+ is not a File but an IO
flush_buffer(out, buf, chunked_p)
1 while flush_buffer(out, value.read(4096), chunked_p)
end
else
# non-file field:
# HTML5 says, "The parts of the generated multipart/form-data
# resource that correspond to non-file fields must not have a
# Content-Type header specified."
buf << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
buf << (value.respond_to?(:read) ? value.read : value)
end
buf << "\r\n"
end
buf << "--#{boundary}--\r\n"
flush_buffer(out, buf, chunked_p)
out << "0\r\n\r\n" if chunked_p
end
def quote_string(str, charset)
str = str.encode(charset, fallback:->(c){'&#%d;'%c.encode("UTF-8").ord}) if charset
str = str.gsub(/[\\"]/, '\\\\\&')
end
def flush_buffer(out, buf, chunked_p)
return unless buf
out << "%x\r\n"%buf.bytesize if chunked_p
out << buf
out << "\r\n" if chunked_p
buf.clear
end
def supply_default_content_type
return if content_type()
warn 'net/http: warning: Content-Type did not set; using application/x-www-form-urlencoded' if $VERBOSE
set_content_type 'application/x-www-form-urlencoded'
end
##
# Waits up to the continue timeout for a response from the server provided
# we're speaking HTTP 1.1 and are expecting a 100-continue response.
def wait_for_continue(sock, ver)
if ver >= '1.1' and @header['expect'] and
@header['expect'].include?('100-continue')
if IO.select([sock.io], nil, nil, sock.continue_timeout)
res = HTTPResponse.read_new(sock)
unless res.kind_of?(Net::HTTPContinue)
throw :response, res
end
end
end
end
def write_header(sock, ver, path)
buf = "#{@method} #{path} HTTP/#{ver}\r\n"
each_capitalized do |k,v|
buf << "#{k}: #{v}\r\n"
end
buf << "\r\n"
sock.write buf
end
end
#
# HTTP request class.
# This class wraps together the request header and the request path.
# You cannot use this class directly. Instead, you should use one of its
# subclasses: Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Head.
#
class HTTPRequest < HTTPGenericRequest
# Creates HTTP request object.
def initialize(path, initheader = nil)
super self.class::METHOD,
self.class::REQUEST_HAS_BODY,
self.class::RESPONSE_HAS_BODY,
path, initheader
end
end
class HTTP # reopen
#
# HTTP/1.1 methods --- RFC2616
#
# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Get < HTTPRequest
METHOD = 'GET'
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Head < HTTPRequest
METHOD = 'HEAD'
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = false
end
# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Post < HTTPRequest
METHOD = 'POST'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Put < HTTPRequest
METHOD = 'PUT'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
# See Net::HTTP for usage examples.
class Delete < HTTPRequest
METHOD = 'DELETE'
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
class Options < HTTPRequest
METHOD = 'OPTIONS'
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = false
end
# See Net::HTTPGenericRequest for attributes and methods.
class Trace < HTTPRequest
METHOD = 'TRACE'
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = true
end
#
# PATCH method --- RFC5789
#
# See Net::HTTPGenericRequest for attributes and methods.
class Patch < HTTPRequest
METHOD = 'PATCH'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
#
# WebDAV methods --- RFC2518
#
# See Net::HTTPGenericRequest for attributes and methods.
class Propfind < HTTPRequest
METHOD = 'PROPFIND'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
class Proppatch < HTTPRequest
METHOD = 'PROPPATCH'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
class Mkcol < HTTPRequest
METHOD = 'MKCOL'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
class Copy < HTTPRequest
METHOD = 'COPY'
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
class Move < HTTPRequest
METHOD = 'MOVE'
REQUEST_HAS_BODY = false
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
class Lock < HTTPRequest
METHOD = 'LOCK'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
# See Net::HTTPGenericRequest for attributes and methods.
class Unlock < HTTPRequest
METHOD = 'UNLOCK'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end
end
###
### Response
###
# HTTP exception class.
# You cannot use HTTPExceptions directly; instead, you must use
# its subclasses.
module HTTPExceptions
def initialize(msg, res) #:nodoc:
super msg
@response = res
end
attr_reader :response
alias data response #:nodoc: obsolete
end
class HTTPError < ProtocolError
include HTTPExceptions
end
class HTTPRetriableError < ProtoRetriableError
include HTTPExceptions
end
class HTTPServerException < ProtoServerError
# We cannot use the name "HTTPServerError", it is the name of the response.
include HTTPExceptions
end
class HTTPFatalError < ProtoFatalError
include HTTPExceptions
end
# HTTP response class.
#
# This class wraps together the response header and the response body (the
# entity requested).
#
# It mixes in the HTTPHeader module, which provides access to response
# header values both via hash-like methods and via individual readers.
#
# Note that each possible HTTP response code defines its own
# HTTPResponse subclass. These are listed below.
#
# All classes are
# defined under the Net module. Indentation indicates inheritance.
#
# xxx HTTPResponse
#
# 1xx HTTPInformation
# 100 HTTPContinue
# 101 HTTPSwitchProtocol
#
# 2xx HTTPSuccess
# 200 HTTPOK
# 201 HTTPCreated
# 202 HTTPAccepted
# 203 HTTPNonAuthoritativeInformation
# 204 HTTPNoContent
# 205 HTTPResetContent
# 206 HTTPPartialContent
#
# 3xx HTTPRedirection
# 300 HTTPMultipleChoice
# 301 HTTPMovedPermanently
# 302 HTTPFound
# 303 HTTPSeeOther
# 304 HTTPNotModified
# 305 HTTPUseProxy
# 307 HTTPTemporaryRedirect
#
# 4xx HTTPClientError
# 400 HTTPBadRequest
# 401 HTTPUnauthorized
# 402 HTTPPaymentRequired
# 403 HTTPForbidden
# 404 HTTPNotFound
# 405 HTTPMethodNotAllowed
# 406 HTTPNotAcceptable
# 407 HTTPProxyAuthenticationRequired
# 408 HTTPRequestTimeOut
# 409 HTTPConflict
# 410 HTTPGone
# 411 HTTPLengthRequired
# 412 HTTPPreconditionFailed
# 413 HTTPRequestEntityTooLarge
# 414 HTTPRequestURITooLong
# 415 HTTPUnsupportedMediaType
# 416 HTTPRequestedRangeNotSatisfiable
# 417 HTTPExpectationFailed
#
# 5xx HTTPServerError
# 500 HTTPInternalServerError
# 501 HTTPNotImplemented
# 502 HTTPBadGateway
# 503 HTTPServiceUnavailable
# 504 HTTPGatewayTimeOut
# 505 HTTPVersionNotSupported
#
# xxx HTTPUnknownResponse
#
class HTTPResponse
# true if the response has a body.
def HTTPResponse.body_permitted?
self::HAS_BODY
end
def HTTPResponse.exception_type # :nodoc: internal use only
self::EXCEPTION_TYPE
end
end # reopened after
# :stopdoc:
class HTTPUnknownResponse < HTTPResponse
HAS_BODY = true
EXCEPTION_TYPE = HTTPError
end
class HTTPInformation < HTTPResponse # 1xx
HAS_BODY = false
EXCEPTION_TYPE = HTTPError
end
class HTTPSuccess < HTTPResponse # 2xx
HAS_BODY = true
EXCEPTION_TYPE = HTTPError
end
class HTTPRedirection < HTTPResponse # 3xx
HAS_BODY = true
EXCEPTION_TYPE = HTTPRetriableError
end
class HTTPClientError < HTTPResponse # 4xx
HAS_BODY = true
EXCEPTION_TYPE = HTTPServerException # for backward compatibility
end
class HTTPServerError < HTTPResponse # 5xx
HAS_BODY = true
EXCEPTION_TYPE = HTTPFatalError # for backward compatibility
end
class HTTPContinue < HTTPInformation # 100
HAS_BODY = false
end
class HTTPSwitchProtocol < HTTPInformation # 101
HAS_BODY = false
end
class HTTPOK < HTTPSuccess # 200
HAS_BODY = true
end
class HTTPCreated < HTTPSuccess # 201
HAS_BODY = true
end
class HTTPAccepted < HTTPSuccess # 202
HAS_BODY = true
end
class HTTPNonAuthoritativeInformation < HTTPSuccess # 203
HAS_BODY = true
end
class HTTPNoContent < HTTPSuccess # 204
HAS_BODY = false
end
class HTTPResetContent < HTTPSuccess # 205
HAS_BODY = false
end
class HTTPPartialContent < HTTPSuccess # 206
HAS_BODY = true
end
class HTTPMultipleChoice < HTTPRedirection # 300
HAS_BODY = true
end
class HTTPMovedPermanently < HTTPRedirection # 301
HAS_BODY = true
end
class HTTPFound < HTTPRedirection # 302
HAS_BODY = true
end
HTTPMovedTemporarily = HTTPFound
class HTTPSeeOther < HTTPRedirection # 303
HAS_BODY = true
end
class HTTPNotModified < HTTPRedirection # 304
HAS_BODY = false
end
class HTTPUseProxy < HTTPRedirection # 305
HAS_BODY = false
end
# 306 unused
class HTTPTemporaryRedirect < HTTPRedirection # 307
HAS_BODY = true
end
class HTTPBadRequest < HTTPClientError # 400
HAS_BODY = true
end
class HTTPUnauthorized < HTTPClientError # 401
HAS_BODY = true
end
class HTTPPaymentRequired < HTTPClientError # 402
HAS_BODY = true
end
class HTTPForbidden < HTTPClientError # 403
HAS_BODY = true
end
class HTTPNotFound < HTTPClientError # 404
HAS_BODY = true
end
class HTTPMethodNotAllowed < HTTPClientError # 405
HAS_BODY = true
end
class HTTPNotAcceptable < HTTPClientError # 406
HAS_BODY = true
end
class HTTPProxyAuthenticationRequired < HTTPClientError # 407
HAS_BODY = true
end
class HTTPRequestTimeOut < HTTPClientError # 408
HAS_BODY = true
end
class HTTPConflict < HTTPClientError # 409
HAS_BODY = true
end
class HTTPGone < HTTPClientError # 410
HAS_BODY = true
end
class HTTPLengthRequired < HTTPClientError # 411
HAS_BODY = true
end
class HTTPPreconditionFailed < HTTPClientError # 412
HAS_BODY = true
end
class HTTPRequestEntityTooLarge < HTTPClientError # 413
HAS_BODY = true
end
class HTTPRequestURITooLong < HTTPClientError # 414
HAS_BODY = true
end
HTTPRequestURITooLarge = HTTPRequestURITooLong
class HTTPUnsupportedMediaType < HTTPClientError # 415
HAS_BODY = true
end
class HTTPRequestedRangeNotSatisfiable < HTTPClientError # 416
HAS_BODY = true
end
class HTTPExpectationFailed < HTTPClientError # 417
HAS_BODY = true
end
class HTTPInternalServerError < HTTPServerError # 500
HAS_BODY = true
end
class HTTPNotImplemented < HTTPServerError # 501
HAS_BODY = true
end
class HTTPBadGateway < HTTPServerError # 502
HAS_BODY = true
end
class HTTPServiceUnavailable < HTTPServerError # 503
HAS_BODY = true
end
class HTTPGatewayTimeOut < HTTPServerError # 504
HAS_BODY = true
end
class HTTPVersionNotSupported < HTTPServerError # 505
HAS_BODY = true
end
# :startdoc:
class HTTPResponse # reopen
CODE_CLASS_TO_OBJ = {
'1' => HTTPInformation,
'2' => HTTPSuccess,
'3' => HTTPRedirection,
'4' => HTTPClientError,
'5' => HTTPServerError
}
CODE_TO_OBJ = {
'100' => HTTPContinue,
'101' => HTTPSwitchProtocol,
'200' => HTTPOK,
'201' => HTTPCreated,
'202' => HTTPAccepted,
'203' => HTTPNonAuthoritativeInformation,
'204' => HTTPNoContent,
'205' => HTTPResetContent,
'206' => HTTPPartialContent,
'300' => HTTPMultipleChoice,
'301' => HTTPMovedPermanently,
'302' => HTTPFound,
'303' => HTTPSeeOther,
'304' => HTTPNotModified,
'305' => HTTPUseProxy,
'307' => HTTPTemporaryRedirect,
'400' => HTTPBadRequest,
'401' => HTTPUnauthorized,
'402' => HTTPPaymentRequired,
'403' => HTTPForbidden,
'404' => HTTPNotFound,
'405' => HTTPMethodNotAllowed,
'406' => HTTPNotAcceptable,
'407' => HTTPProxyAuthenticationRequired,
'408' => HTTPRequestTimeOut,
'409' => HTTPConflict,
'410' => HTTPGone,
'411' => HTTPLengthRequired,
'412' => HTTPPreconditionFailed,
'413' => HTTPRequestEntityTooLarge,
'414' => HTTPRequestURITooLong,
'415' => HTTPUnsupportedMediaType,
'416' => HTTPRequestedRangeNotSatisfiable,
'417' => HTTPExpectationFailed,
'500' => HTTPInternalServerError,
'501' => HTTPNotImplemented,
'502' => HTTPBadGateway,
'503' => HTTPServiceUnavailable,
'504' => HTTPGatewayTimeOut,
'505' => HTTPVersionNotSupported
}
class << HTTPResponse
def read_new(sock) #:nodoc: internal use only
httpv, code, msg = read_status_line(sock)
res = response_class(code).new(httpv, code, msg)
each_response_header(sock) do |k,v|
res.add_field k, v
end
res
end
private
def read_status_line(sock)
str = sock.readline
m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/in.match(str) or
raise HTTPBadResponse, "wrong status line: #{str.dump}"
m.captures
end
def response_class(code)
CODE_TO_OBJ[code] or
CODE_CLASS_TO_OBJ[code[0,1]] or
HTTPUnknownResponse
end
def each_response_header(sock)
key = value = nil
while true
line = sock.readuntil("\n", true).sub(/\s+\z/, '')
break if line.empty?
if line[0] == ?\s or line[0] == ?\t and value
value << ' ' unless value.empty?
value << line.strip
else
yield key, value if key
key, value = line.strip.split(/\s*:\s*/, 2)
raise HTTPBadResponse, 'wrong header line format' if value.nil?
end
end
yield key, value if key
end
end
# next is to fix bug in RDoc, where the private inside class << self
# spills out.
public
include HTTPHeader
def initialize(httpv, code, msg) #:nodoc: internal use only
@http_version = httpv
@code = code
@message = msg
initialize_http_header nil
@body = nil
@read = false
end
# The HTTP version supported by the server.
attr_reader :http_version
# The HTTP result code string. For example, '302'. You can also
# determine the response type by examining which response subclass
# the response object is an instance of.
attr_reader :code
# The HTTP result message sent by the server. For example, 'Not Found'.
attr_reader :message
alias msg message # :nodoc: obsolete
def inspect
"#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
end
#
# response <-> exception relationship
#
def code_type #:nodoc:
self.class
end
def error! #:nodoc:
raise error_type().new(@code + ' ' + @message.dump, self)
end
def error_type #:nodoc:
self.class::EXCEPTION_TYPE
end
# Raises an HTTP error if the response is not 2xx (success).
def value
error! unless self.kind_of?(HTTPSuccess)
end
#
# header (for backward compatibility only; DO NOT USE)
#
def response #:nodoc:
warn "#{caller(1)[0]}: warning: HTTPResponse#response is obsolete" if $VERBOSE
self
end
def header #:nodoc:
warn "#{caller(1)[0]}: warning: HTTPResponse#header is obsolete" if $VERBOSE
self
end
def read_header #:nodoc:
warn "#{caller(1)[0]}: warning: HTTPResponse#read_header is obsolete" if $VERBOSE
self
end
#
# body
#
def reading_body(sock, reqmethodallowbody) #:nodoc: internal use only
@socket = sock
@body_exist = reqmethodallowbody && self.class.body_permitted?
begin
yield
self.body # ensure to read body
ensure
@socket = nil
end
end
# Gets the entity body returned by the remote HTTP server.
#
# If a block is given, the body is passed to the block, and
# the body is provided in fragments, as it is read in from the socket.
#
# Calling this method a second or subsequent time for the same
# HTTPResponse object will return the value already read.
#
# http.request_get('/index.html') {|res|
# puts res.read_body
# }
#
# http.request_get('/index.html') {|res|
# p res.read_body.object_id # 538149362
# p res.read_body.object_id # 538149362
# }
#
# # using iterator
# http.request_get('/index.html') {|res|
# res.read_body do |segment|
# print segment
# end
# }
#
def read_body(dest = nil, &block)
if @read
raise IOError, "#{self.class}\#read_body called twice" if dest or block
return @body
end
to = procdest(dest, block)
stream_check
if @body_exist
read_body_0 to
@body = to
else
@body = nil
end
@read = true
@body
end
# Returns the full entity body.
#
# Calling this method a second or subsequent time will return the
# string already read.
#
# http.request_get('/index.html') {|res|
# puts res.body
# }
#
# http.request_get('/index.html') {|res|
# p res.body.object_id # 538149362
# p res.body.object_id # 538149362
# }
#
def body
read_body()
end
# Because it may be necessary to modify the body, Eg, decompression
# this method facilitates that.
def body=(value)
@body = value
end
alias entity body #:nodoc: obsolete
private
def read_body_0(dest)
if chunked?
read_chunked dest
return
end
clen = content_length()
if clen
@socket.read clen, dest, true # ignore EOF
return
end
clen = range_length()
if clen
@socket.read clen, dest
return
end
@socket.read_all dest
end
def read_chunked(dest)
len = nil
total = 0
while true
line = @socket.readline
hexlen = line.slice(/[0-9a-fA-F]+/) or
raise HTTPBadResponse, "wrong chunk size line: #{line}"
len = hexlen.hex
break if len == 0
begin
@socket.read len, dest
ensure
total += len
@socket.read 2 # \r\n
end
end
until @socket.readline.empty?
# none
end
end
def stream_check
raise IOError, 'attempt to read body out of block' if @socket.closed?
end
def procdest(dest, block)
raise ArgumentError, 'both arg and block given for HTTP method' \
if dest and block
if block
ReadAdapter.new(block)
else
dest || ''
end
end
end
# :enddoc:
#--
# for backward compatibility
class HTTP
ProxyMod = ProxyDelta
end
module NetPrivate
HTTPRequest = ::Net::HTTPRequest
end
HTTPInformationCode = HTTPInformation
HTTPSuccessCode = HTTPSuccess
HTTPRedirectionCode = HTTPRedirection
HTTPRetriableCode = HTTPRedirection
HTTPClientErrorCode = HTTPClientError
HTTPFatalErrorCode = HTTPClientError
HTTPServerErrorCode = HTTPServerError
HTTPResponceReceiver = HTTPResponse
end # module Net
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/extfileselectiondialog.rb
|
<reponame>arnab0073/idea
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
mainloop = Thread.new{Tk.mainloop}
#
# Non-modal example
#
nmfsd = Tk::Iwidgets::Extfileselectiondialog.new(:title=>'Non-Modal')
nmfsd.buttonconfigure('OK', :command=>proc{
puts "You selected #{nmfsd.get}"
nmfsd.deactivate
})
nmfsd.activate
#
# Modal example
#
mfsd = Tk::Iwidgets::Extfileselectiondialog.new(:modality=>:application)
mfsd.center
if TkComm.bool(mfsd.activate)
puts "You selected #{mfsd.get}"
else
puts "You cancelled the dialog"
end
mainloop.join
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-shellout-1.6.1/lib/mixlib/shellout/version.rb
|
<gh_stars>0
module Mixlib
class ShellOut
VERSION = "1.6.1"
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/tests/google/credentials_tests.rb
|
<reponame>arnab0073/idea
require 'google/api_client'
Shindo.tests('Google | credentials', ['google']) do
tests('success') do
pending if Fog.mocking?
google_key_location = Fog.credentials[:google_key_location]
if google_key_location.nil?
tests('Needs a :google_key_location credentials key').pending
end
google_key_string = File.open(File.expand_path(google_key_location), 'rb') { |io| io.read }
tests("#using_p12_key_file").succeeds do
Fog::Compute::Google.new(:google_key_location => google_key_location,
:google_key_string => nil,
:google_json_key_location => nil,
:google_json_key_string => nil)
end
tests("#using_p12_key_string").succeeds do
Fog::Compute::Google.new(:google_key_location => nil,
:google_key_string => google_key_string,
:google_json_key_location => nil,
:google_json_key_string => nil)
end
end
tests('success') do
pending if Fog.mocking?
google_json_key_location = Fog.credentials[:google_json_key_location]
if google_json_key_location.nil?
tests('Needs a :google_json_key_location credentials key').pending
end
google_json_key_string = File.open(File.expand_path(google_json_key_location), 'rb') { |io| io.read }
tests("#using_json_key_file").succeeds do
Fog::Compute::Google.new(:google_key_location => nil,
:google_key_string => nil,
:google_json_key_location => google_json_key_location,
:google_json_key_string => nil)
end
tests("#using_json_key_string").succeeds do
Fog::Compute::Google.new(:google_key_location => nil,
:google_key_string => nil,
:google_json_key_location => nil,
:google_json_key_string => google_json_key_string)
end
end
tests('failure') do
tests("#missing_google_project").raises(ArgumentError, 'raises ArgumentError when google_project is missing') do
Fog::Compute::Google.new(:google_project => nil)
end
tests("#missing_google_client_email").raises(ArgumentError, 'raises ArgumentError when google_client_email is missing') do
pending if Fog.mocking? # Mock doesn't check google_client_email
Fog::Compute::Google.new(:google_client_email => nil,
:google_json_key_location => nil) # JSON key overrides google_client_email
end
tests("#missing_keys").raises(ArgumentError, 'raises ArgumentError when google keys are missing') do
pending if Fog.mocking? # Mock doesn't check missing keys
Fog::Compute::Google.new(:google_key_location => nil,
:google_key_string => nil,
:google_json_key_location => nil,
:google_json_key_string => nil)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/bootstraptest/test_block.rb
|
<gh_stars>0
assert_equal %q{1}, %q{
1.times{
begin
a = 1
ensure
foo = nil
end
}
}
assert_equal %q{2}, %q{
[1,2,3].find{|x| x == 2}
}
assert_equal %q{2}, %q{
class E
include Enumerable
def each(&block)
[1, 2, 3].each(&block)
end
end
E.new.find {|x| x == 2 }
}
assert_equal %q{6}, %q{
sum = 0
for x in [1, 2, 3]
sum += x
end
sum
}
assert_equal %q{15}, %q{
sum = 0
for x in (1..5)
sum += x
end
sum
}
assert_equal %q{0}, %q{
sum = 0
for x in []
sum += x
end
sum
}
assert_equal %q{1}, %q{
ans = []
1.times{
for n in 1..3
a = n
ans << a
end
}
}
assert_equal %q{1..3}, %q{
ans = []
for m in 1..3
for n in 1..3
a = [m, n]
ans << a
end
end
}
assert_equal %q{[1, 2, 3]}, %q{
(1..3).to_a
}
assert_equal %q{[4, 8, 12]}, %q{
(1..3).map{|e|
e * 4
}
}
assert_equal %q{[1, 2, 3]}, %q{
class C
include Enumerable
def each
[1,2,3].each{|e|
yield e
}
end
end
C.new.to_a
}
assert_equal %q{[4, 5, 6]}, %q{
class C
include Enumerable
def each
[1,2,3].each{|e|
yield e
}
end
end
C.new.map{|e|
e + 3
}
}
assert_equal %q{100}, %q{
def m
yield
end
def n
yield
end
m{
n{
100
}
}
}
assert_equal %q{20}, %q{
def m
yield 1
end
m{|ib|
m{|jb|
i = 20
}
}
}
assert_equal %q{2}, %q{
def m
yield 1
end
m{|ib|
m{|jb|
ib = 20
kb = 2
}
}
}
assert_equal %q{3}, %q{
def iter1
iter2{
yield
}
end
def iter2
yield
end
iter1{
jb = 2
iter1{
jb = 3
}
jb
}
}
assert_equal %q{2}, %q{
def iter1
iter2{
yield
}
end
def iter2
yield
end
iter1{
jb = 2
iter1{
jb
}
jb
}
}
assert_equal %q{2}, %q{
def m
yield 1
end
m{|ib|
ib*2
}
}
assert_equal %q{92580}, %q{
def m
yield 12345, 67890
end
m{|ib,jb|
ib*2+jb
}
}
assert_equal %q{[10, nil]}, %q{
def iter
yield 10
end
a = nil
[iter{|a|
a
}, a]
}
assert_equal %q{21}, %q{
def iter
yield 10
end
iter{|a|
iter{|a|
a + 1
} + a
}
}
assert_equal %q{[10, 20, 30, 40, nil, nil, nil, nil]}, %q{
def iter
yield 10, 20, 30, 40
end
a = b = c = d = nil
iter{|a, b, c, d|
[a, b, c, d]
} + [a, b, c, d]
}
assert_equal %q{[10, 20, 30, 40, nil, nil]}, %q{
def iter
yield 10, 20, 30, 40
end
a = b = nil
iter{|a, b, c, d|
[a, b, c, d]
} + [a, b]
}
assert_equal %q{[1]}, %q{
$a = []
def iter
yield 1
end
def m
x = iter{|x|
$a << x
y = 0
}
end
m
$a
}
assert_equal %q{[1, [2]]}, %q{
def iter
yield 1, 2
end
iter{|a, *b|
[a, b]
}
}
assert_equal %q{[[1, 2]]}, %q{
def iter
yield 1, 2
end
iter{|*a|
[a]
}
}
assert_equal %q{[1, 2, []]}, %q{
def iter
yield 1, 2
end
iter{|a, b, *c|
[a, b, c]
}
}
assert_equal %q{[1, 2, nil, []]}, %q{
def iter
yield 1, 2
end
iter{|a, b, c, *d|
[a, b, c, d]
}
}
assert_equal %q{1}, %q{
def m
yield
end
m{
1
}
}
assert_equal %q{15129}, %q{
def m
yield 123
end
m{|ib|
m{|jb|
ib*jb
}
}
}
assert_equal %q{2}, %q{
def m a
yield a
end
m(1){|ib|
m(2){|jb|
ib*jb
}
}
}
assert_equal %q{9}, %q{
sum = 0
3.times{|ib|
2.times{|jb|
sum += ib + jb
}}
sum
}
assert_equal %q{10}, %q{
3.times{|bl|
break 10
}
}
assert_equal %q{[1, 2]}, %q{
def iter
yield 1,2,3
end
iter{|i, j|
[i, j]
}
}
assert_equal %q{[1, nil]}, %q{
def iter
yield 1
end
iter{|i, j|
[i, j]
}
}
assert_equal '0', %q{
def m()
end
m {|(v0,*,(*)),|}
m {|(*v0,(*)),|}
m {|(v0,*v1,(*)),|}
m {|((v0,*v1,v2)),|}
m {|(v0,*v1,v2),|}
m {|(v0,*v1,(v2)),|}
m {|((*),*v0,v1),|}
m {|((v0),*v1,v2),|}
m {|(v0,v1,*v2,v3),|}
m {|v0,(v1,*v2,v3),|}
m {|(v0,*v1,v2),v3,|}
m {|(v0,*v1,v2)|}
m {|(v0,*v1,v2),&v3|}
m {|(v0,*v1,v2),*|}
m {|(v0,*v1,v2),*,&v3|}
m {|*,(v0,*v1,v2)|}
m {|*,(v0,*v1,v2),&v3|}
m {|v0,*,(v1,*v2,v3)|}
m {|v0,*,(v1,*v2,v3),&v4|}
m {|(v0,*v1,v2),*,v3|}
m {|(v0,*v1,v2),*,v3,&v4|}
m {|(v0, *v1, v2)|}
m {|(*,v)|}
0
}, "block parameter (shouldn't SEGV: [ruby-dev:31143])"
assert_equal 'nil', %q{
def m
yield
end
m{|&b| b}.inspect
}, '[ruby-dev:31147]'
assert_equal 'nil', %q{
def m()
yield
end
m {|(v,(*))|}.inspect
}, '[ruby-dev:31160]'
assert_equal 'nil', %q{
def m()
yield
end
m {|(*,a,b)|}.inspect
}, '[ruby-dev:31153]'
assert_equal 'nil', %q{
def m()
yield
end
m {|((*))|}.inspect
}
assert_equal %q{[1, 1, [1, nil], [1, nil], [1, nil], [1, nil], [1, 1], 1, [1, nil], [1, nil], [1, nil], [1, nil], [[1, 1], [1, 1]], [1, 1], [1, 1], [1, 1], [1, nil], [1, nil], [[[1, 1], [1, 1]], [[1, 1], [1, 1]]], [[1, 1], [1, 1]], [[1, 1], [1, 1]], [[1, 1], [1, 1]], [1, 1], [1, 1], [[[[1, 1], [1, 1]], [[1, 1], [1, 1]]], [[[1, 1], [1, 1]], [[1, 1], [1, 1]]]], [[[1, 1], [1, 1]], [[1, 1], [1, 1]]], [[[1, 1], [1, 1]], [[1, 1], [1, 1]]], [[[1, 1], [1, 1]], [[1, 1], [1, 1]]], [[1, 1], [1, 1]], [[1, 1], [1, 1]]]}, %q{
def m(ary = [])
yield(ary)
end
$ans = []
o = 1
5.times{
v,(*) = o; $ans << o
m(o){|(v,(*))| $ans << v}
((x, y)) = o; $ans << [x, y]
m(o){|((x, y))| $ans << [x, y]}
(((x, y))) = o; $ans << [x, y]
m(o){|(((x, y)))| $ans << [x, y]}
o = [o, o]
}; $ans
}
assert_equal '0', %q{
def m()
yield [0]
end
m {|*,v| v}.inspect
}, '[ruby-dev:31437]'
assert_equal '[0]', %q{
def m
yield [0]
end
m{|v, &b| v}.inspect
}, '[ruby-dev:31440]'
assert_equal 'ok', %q{
begin
lambda{|a|}.call(1, 2)
rescue ArgumentError
:ok
else
:ng
end
}, '[ruby-dev:31464]'
assert_equal 'ok', %q{
begin
lambda{|&b|}.call(3)
rescue ArgumentError
:ok
else
:ng
end
}, '[ruby-dev:31472]'
assert_equal 'ok', %q{
class C
def each
yield [1,2]
yield 1,2
end
end
vs1 = []
C.new.each {|*v| vs1 << v }
vs2 = []
C.new.to_enum.each {|*v| vs2 << v }
vs1 == vs2 ? :ok : :ng
}, '[ruby-dev:32329]'
assert_normal_exit %q{
e = [1,2,3].each
10000.times {
e = [e].each
}
Thread.new { GC.start }.join
}, '[ruby-dev:32604]'
assert_equal '[nil, []]', %q{
def m() yield nil,[] end
l = lambda {|*v| v}
GC.stress=true
r = m(&l)
GC.stress=false
r.inspect
}, '[ruby-dev:32567]'
assert_equal NilClass.to_s, %q{
r = false; 1.times{|&b| r = b}; r.class
}
assert_equal 'ok', %q{
class C
define_method(:foo) do |arg, &block|
if block then block.call else arg end
end
end
C.new.foo("ng") {"ok"}
}, '[ruby-talk:266422]'
assert_equal 'ok', %q{
class C
define_method(:xyz) do |o, k, &block|
block.call(o, k)
end
end
C.new.xyz("o","k") {|o, k| o+k}
}, '[ruby-core:20544]'
assert_equal 'ok', %q{
class C
define_method(:xyz) do |*args, &block|
block.call(*args)
end
end
C.new.xyz("o","k") {|*args| args.join("")}
}, '[ruby-core:20544]'
assert_equal 'ok', %q{
STDERR.reopen(STDOUT)
class C
define_method(:foo) do |&block|
block.call if block
end
result = "ng"
new.foo() {result = "ok"}
result
end
}
assert_equal "ok", %q{
class Bar
def bar; :ok; end
end
def foo
yield(Bar.new) if block_given?
end
foo(&:bar)
}, '[ruby-core:14279]'
assert_normal_exit %q{
class Controller
def respond_to(&block)
responder = Responder.new
block.call(responder)
responder.respond
end
def test_for_bug
respond_to{|format|
format.js{
puts "in test"
render{|obj|
puts obj
}
}
}
end
def render(&block)
puts "in render"
end
end
class Responder
def method_missing(symbol, &block)
puts "enter method_missing"
@response = Proc.new{
puts 'in method missing'
block.call
}
puts "leave method_missing"
end
def respond
@response.call
end
end
t = Controller.new
t.test_for_bug
}, '[ruby-core:14395]'
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-config-2.2.1/spec/mixlib/config_spec.rb
|
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2008 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper"))
class ConfigIt
extend ::Mixlib::Config
end
describe Mixlib::Config do
before(:each) do
ConfigIt.configure do |c|
c[:alpha] = 'omega'
c[:foo] = nil
end
end
it "should load a config file" do
File.stub(:exists?).and_return(true)
File.stub(:readable?).and_return(true)
IO.stub(:read).with('config.rb').and_return("alpha = 'omega'\nfoo = 'bar'")
lambda {
ConfigIt.from_file('config.rb')
}.should_not raise_error
end
it "should not raise an ArgumentError with an explanation if you try and set a non-existent variable" do
lambda {
ConfigIt[:foobar] = "blah"
}.should_not raise_error
end
it "should raise an Errno::ENOENT if it can't find the file" do
lambda {
ConfigIt.from_file("/tmp/timmytimmytimmy")
}.should raise_error(Errno::ENOENT)
end
it "should allow the error to bubble up when it's anything other than IOError" do
IO.stub(:read).with('config.rb').and_return("@#asdf")
lambda {
ConfigIt.from_file('config.rb')
}.should raise_error(SyntaxError)
end
it "should allow you to reference a value by index" do
ConfigIt[:alpha].should == 'omega'
end
it "should allow you to reference a value by string index" do
ConfigIt['alpha'].should == 'omega'
end
it "should allow you to set a value by index" do
ConfigIt[:alpha] = "one"
ConfigIt[:alpha].should == "one"
end
it "should allow you to set a value by string index" do
ConfigIt['alpha'] = "one"
ConfigIt[:alpha].should == "one"
end
it "should allow setting a value with attribute form" do
ConfigIt.arbitrary_value = 50
ConfigIt.arbitrary_value.should == 50
ConfigIt[:arbitrary_value].should == 50
end
it "should allow setting a value with method form" do
ConfigIt.arbitrary_value 50
ConfigIt.arbitrary_value.should == 50
ConfigIt[:arbitrary_value].should == 50
end
describe "when strict mode is on" do
class StrictClass
extend ::Mixlib::Config
config_strict_mode true
default :x, 1
end
it "allows you to get and set configured values" do
StrictClass.x = StrictClass.x * 2
StrictClass[:x] = StrictClass[:x] * 2
end
it "raises an error when you get an arbitrary config option with .y" do
lambda { StrictClass.y }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Reading unsupported config value y.")
end
it "raises an error when you get an arbitrary config option with [:y]" do
lambda { StrictClass[:y] }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Reading unsupported config value y.")
end
it "raises an error when you set an arbitrary config option with .y = 10" do
lambda { StrictClass.y = 10 }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Cannot set unsupported config value y.")
end
it "raises an error when you set an arbitrary config option with .y 10" do
lambda { StrictClass.y 10 }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Cannot set unsupported config value y.")
end
it "raises an error when you set an arbitrary config option with [:y] = 10" do
lambda { StrictClass[:y] = 10 }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Cannot set unsupported config value y.")
end
end
describe "when a block has been used to set config values" do
before do
ConfigIt.configure { |c| c[:cookbook_path] = "monkey_rabbit"; c[:otherthing] = "boo" }
end
{:cookbook_path => "monkey_rabbit", :otherthing => "boo"}.each do |k,v|
it "should allow you to retrieve the config value for #{k} via []" do
ConfigIt[k].should == v
end
it "should allow you to retrieve the config value for #{k} via method_missing" do
ConfigIt.send(k).should == v
end
end
end
it "should not raise an ArgumentError if you access a config option that does not exist" do
lambda { ConfigIt[:snob_hobbery] }.should_not raise_error
end
it "should return true or false with has_key?" do
ConfigIt.has_key?(:monkey).should eql(false)
ConfigIt[:monkey] = "gotcha"
ConfigIt.has_key?(:monkey).should eql(true)
end
describe "when a class method override writer exists" do
before do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
config_attr_writer :test_method do |blah|
blah.is_a?(Integer) ? blah * 1000 : blah
end
end
end
it "should multiply an integer by 1000" do
@klass[:test_method] = 53
@klass[:test_method].should == 53000
end
it "should multiply an integer by 1000 with the method_missing form" do
@klass.test_method = 63
@klass.test_method.should == 63000
end
it "should multiply an integer by 1000 with the instance_eval DSL form" do
@klass.instance_eval("test_method 73")
@klass.test_method.should == 73000
end
it "should multiply an integer by 1000 via from-file, too" do
IO.stub(:read).with('config.rb').and_return("test_method 99")
@klass.from_file('config.rb')
@klass.test_method.should == 99000
end
it "should receive internal_set with the method name and config value" do
@klass.should_receive(:internal_set).with(:test_method, 53).and_return(true)
@klass[:test_method] = 53
end
end
describe "When a configurable exists" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
configurable :daemonizeme
default :a, 1
config_attr_writer(:b) { |v| v }
config_context(:c)
end
end
it "Getter methods are created for the configurable" do
@klass.respond_to?(:daemonizeme).should == true
@klass.respond_to?(:a).should == true
@klass.respond_to?(:b).should == true
@klass.respond_to?(:c).should == true
@klass.respond_to?(:z).should == false
end
it "Setter methods are created for the configurable" do
@klass.respond_to?("daemonizeme=".to_sym).should == true
@klass.respond_to?("a=".to_sym).should == true
@klass.respond_to?("b=".to_sym).should == true
@klass.respond_to?("c=".to_sym).should == true
@klass.respond_to?("z=".to_sym).should == false
end
describe "and extra methods have been dumped into Object" do
class NopeError < StandardError
end
before :each do
Object.send :define_method, :daemonizeme do
raise NopeError, "NOPE"
end
Object.send :define_method, "daemonizeme=".to_sym do
raise NopeError, "NOPE"
end
end
it 'Normal classes call the extra method' do
normal_class = Class.new
normal_class.extend(::Mixlib::Config)
lambda { normal_class.daemonizeme }.should raise_error(NopeError)
end
it 'Configurables with the same name as the extra method can be set' do
@klass.daemonizeme = 10
@klass[:daemonizeme].should == 10
end
it 'Configurables with the same name as the extra method can be retrieved' do
@klass[:daemonizeme] = 10
@klass.daemonizeme.should == 10
end
end
end
describe "When config has a default value" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval { default :attr, 4 }
end
it "should default to that value" do
@klass.attr.should == 4
end
it "should default to that value when retrieved as a hash" do
@klass[:attr].should == 4
end
it "should be settable to another value" do
@klass.attr 5
@klass.attr.should == 5
end
it "should still default to that value after delete" do
@klass.attr 5
@klass.delete(:attr)
@klass.attr.should == 4
end
it "should still default to that value after reset" do
@klass.attr 5
@klass.reset
@klass.attr.should == 4
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => 4 }
end
it "save should save the new value if it gets set" do
@klass.attr 5
(saved = @klass.save).should == { :attr => 5 }
@klass.reset
@klass.attr.should == 4
@klass.restore(saved)
@klass.attr.should == 5
end
it "save should save the new value even if it is set to its default value" do
@klass.attr 4
(saved = @klass.save).should == { :attr => 4 }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => 4 }
end
end
describe "When config has a default value block" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
default :x, 4
default(:attr) { x*2 }
end
end
it "should default to that value" do
@klass.attr.should == 8
end
it "should be recalculated each time it is retrieved" do
@klass.attr.should == 8
@klass.x = 2
@klass.attr.should == 4
end
it "should default to that value when retrieved as a hash" do
@klass[:attr].should == 8
end
it "should be settable to another value" do
@klass.attr 5
@klass.attr.should == 5
end
it "should still default to that value after delete" do
@klass.attr 5
@klass.delete(:attr)
@klass.attr.should == 8
end
it "should still default to that value after reset" do
@klass.attr 5
@klass.reset
@klass.attr.should == 8
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => 8, :x => 4 }
end
it "save should save the new value if it gets set" do
@klass.attr 5
(saved = @klass.save).should == { :attr => 5 }
@klass.reset
@klass.attr.should == 8
@klass.restore(saved)
@klass.attr.should == 5
end
it "save should save the new value even if it is set to its default value" do
@klass.attr 8
(saved = @klass.save).should == { :attr => 8 }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => 8 }
end
end
describe "When config has an array default value" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval { default :attr, [] }
end
it "reset clears it to its default" do
@klass.attr << 'x'
@klass.attr.should == [ 'x' ]
@klass.reset
@klass.attr.should == []
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => [] }
end
it "save should save the new value if it gets set" do
@klass.attr << 'x'
(saved = @klass.save).should == { :attr => [ 'x' ] }
@klass.reset
@klass.attr.should == []
@klass.restore(saved)
@klass.attr.should == [ 'x' ]
end
it "save should save the new value even if it is set to its default value" do
@klass.attr = []
(saved = @klass.save).should == { :attr => [] }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => [] }
end
end
describe "When config has a hash default value" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval { default :attr, {} }
end
it "reset clears it to its default" do
@klass.attr[:x] = 10
@klass.attr[:x].should == 10
@klass.reset
@klass.attr[:x].should == nil
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => {} }
end
it "save should save the new value if it gets set" do
@klass.attr[:hi] = 'lo'
(saved = @klass.save).should == { :attr => { :hi => 'lo' } }
@klass.reset
@klass.attr.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => { :hi => 'lo' } }
end
it "save should save the new value even if it is set to its default value" do
@klass.attr = {}
(saved = @klass.save).should == { :attr => {} }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => {} }
end
end
describe "When config has a string default value" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval { default :attr, 'hello' }
end
it "reset clears it to its default" do
@klass.attr << ' world'
@klass.attr.should == 'hello world'
@klass.reset
@klass.attr.should == 'hello'
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => 'hello' }
end
it "save should save the new value if it gets set" do
@klass.attr << ' world'
(saved = @klass.save).should == { :attr => 'hello world' }
@klass.reset
@klass.attr.should == 'hello'
@klass.restore(saved)
@klass.attr.should == 'hello world'
end
it "save should save the new value even if it is set to its default value" do
@klass.attr 'hello world'
(saved = @klass.save).should == { :attr => 'hello world' }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => 'hello world' }
end
end
describe "When config has a a default value block" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
default(:attr) { 4 }
end
end
it "should default to that value" do
@klass.attr.should == 4
end
it "should default to that value when retrieved as a hash" do
@klass[:attr].should == 4
end
it "should be settable to another value" do
@klass.attr 5
@klass.attr.should == 5
@klass[:attr].should == 5
end
it "should still default to that value after delete" do
@klass.attr 5
@klass.delete(:attr)
@klass.attr.should == 4
end
it "should still default to that value after reset" do
@klass.attr 5
@klass.reset
@klass.attr.should == 4
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => 4 }
end
it "save should save the new value if it gets set" do
@klass.attr 5
(saved = @klass.save).should == { :attr => 5 }
@klass.reset
@klass.attr.should == 4
@klass.restore(saved)
@klass.attr.should == 5
end
it "save should save the new value even if it is set to its default value" do
@klass.attr 4
(saved = @klass.save).should == { :attr => 4 }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => 4 }
end
end
describe "When a configurable exists with writer and default value" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
configurable(:attr) do |c|
c.defaults_to(4)
c.writes_value { |value| value*2 }
end
end
end
it "should default to that value" do
@klass.attr.should == 4
end
it "should default to that value when retrieved as a hash" do
@klass[:attr].should == 4
end
it "should be settable to another value" do
@klass.attr 5
@klass.attr.should == 10
@klass[:attr].should == 10
end
it "should be settable to another value with attr=" do
@klass.attr = 5
@klass.attr.should == 10
@klass[:attr].should == 10
end
it "should be settable to another value with [:attr]=" do
@klass[:attr] = 5
@klass.attr.should == 10
@klass[:attr].should == 10
end
it "should still default to that value after delete" do
@klass.attr 5
@klass.delete(:attr)
@klass.attr.should == 4
end
it "should still default to that value after reset" do
@klass.attr 5
@klass.reset
@klass.attr.should == 4
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => 4 }
end
it "save should save the new value if it gets set" do
@klass.attr 5
(saved = @klass.save).should == { :attr => 10 }
@klass.reset
@klass.attr.should == 4
@klass.restore(saved)
@klass.attr.should == 10
end
it "save should save the new value even if it is set to its default value" do
@klass.attr 4
(saved = @klass.save).should == { :attr => 8 }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => 8 }
end
end
describe "When a configurable exists with writer and default value set in chained form" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
configurable(:attr).defaults_to(4).writes_value { |value| value*2 }
end
end
it "should default to that value" do
@klass.attr.should == 4
end
it "should default to that value when retrieved as a hash" do
@klass[:attr].should == 4
end
it "should be settable to another value" do
@klass.attr 5
@klass.attr.should == 10
@klass[:attr].should == 10
end
it "should be settable to another value with attr=" do
@klass.attr = 5
@klass.attr.should == 10
@klass[:attr].should == 10
end
it "should be settable to another value with [:attr]=" do
@klass[:attr] = 5
@klass.attr.should == 10
@klass[:attr].should == 10
end
it "should still default to that value after delete" do
@klass.attr 5
@klass.delete(:attr)
@klass.attr.should == 4
end
it "should still default to that value after reset" do
@klass.attr 5
@klass.reset
@klass.attr.should == 4
end
it "save should not save anything for it" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :attr => 4 }
end
it "save should save the new value if it gets set" do
@klass.attr 5
(saved = @klass.save).should == { :attr => 10 }
@klass.reset
@klass.attr.should == 4
@klass.restore(saved)
@klass.attr.should == 10
end
it "save should save the new value even if it is set to its default value" do
@klass.attr 2
(saved = @klass.save).should == { :attr => 4 }
@klass.reset
@klass.save.should == {}
@klass.restore(saved)
@klass.save.should == { :attr => 4 }
end
end
describe "When a configurable exists with a context" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
configurable :x
config_context(:blah) do
default :x, 5
end
end
end
it "configurable defaults in that context work" do
@klass.blah.x.should == 5
end
it "after setting values in the context, the values remain set" do
@klass.blah.x = 10
@klass.blah.x.should == 10
end
it "setting values with the same name in the parent context do not affect the child context" do
@klass.x = 10
@klass.x.should == 10
@klass.blah.x.should == 5
end
it "setting the entire context to a hash with default value overridden sets the value" do
@klass.blah = { :x => 10 }
@klass.blah.x.should == 10
end
it "setting the entire context to a hash sets non-default values" do
@klass.blah = { :y => 10 }
@klass.blah.x.should == 5
@klass.blah.y.should == 10
end
it "setting the entire context to a hash deletes any non-default values and resets default values" do
@klass.blah.x = 10
@klass.blah.y = 10
@klass.blah = { :z => 10 }
@klass.blah.x.should == 5
@klass.blah.y.should == nil
@klass.blah.z.should == 10
end
it "after reset of the parent class, children are reset" do
@klass.blah.x = 10
@klass.blah.x.should == 10
@klass.reset
@klass.blah.x.should == 5
end
it "save should not save anything for it by default" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :blah => { :x => 5 } }
end
it "save should save any new values that are set in the context" do
@klass.blah.x = 10
(saved = @klass.save).should == { :blah => { :x => 10 } }
@klass.reset
@klass.blah.x.should == 5
@klass.restore(saved)
@klass.blah.x.should == 10
@klass.save.should == { :blah => { :x => 10 } }
end
end
describe "When a configurable exists with a nested context" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
config_context(:blah) do
config_context(:yarr) do
default :x, 5
end
end
configurable :x
end
end
it "configurable defaults in that context work" do
@klass.blah.yarr.x.should == 5
end
it "after setting values in the context, the values remain set" do
@klass.blah.yarr.x = 10
@klass.blah.yarr.x.should == 10
end
it "setting values with the same name in the parent context do not affect the child context" do
@klass.x = 10
@klass.x.should == 10
@klass.blah.yarr.x.should == 5
end
it "after reset of the parent class, children are reset" do
@klass.blah.yarr.x = 10
@klass.blah.yarr.x.should == 10
@klass.reset
@klass.blah.yarr.x.should == 5
end
it "save should not save anything for it by default" do
@klass.save.should == {}
end
it "save with include_defaults should save all defaults" do
@klass.save(true).should == { :blah => { :yarr => { :x => 5 } } }
end
it "save should save any new values that are set in the context" do
@klass.blah.yarr.x = 10
(saved = @klass.save).should == { :blah => { :yarr => { :x => 10 } } }
@klass.reset
@klass.blah.yarr.x.should == 5
@klass.restore(saved)
@klass.blah.yarr.x.should == 10
@klass.save.should == { :blah => { :yarr => { :x => 10 } } }
end
end
describe "When a config_context with no defaulted values exists" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
config_context(:blah) do
configurable(:x)
end
end
end
it "save does not save the hash for the config_context" do
@klass.save.should == {}
end
it "save with defaults saves the hash for the config_context" do
@klass.save(true).should == { :blah => {} }
end
end
describe "When a config_context with no configurables exists" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
config_context(:blah)
end
end
it "save does not save the hash for the config_context" do
@klass.save.should == {}
end
it "save with defaults saves the hash for the config_context" do
@klass.save(true).should == { :blah => {} }
end
end
describe "When a nested context has strict mode on" do
class StrictClass2
extend ::Mixlib::Config
config_context :c do
config_strict_mode true
default :x, 1
end
end
it "The parent class allows you to set arbitrary config options" do
StrictClass2.y = 10
end
it "The nested class does not allow you to set arbitrary config options" do
lambda { StrictClass2.c.y = 10 }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Cannot set unsupported config value y.")
end
end
describe "When strict mode is on but a nested context has strict mode unspecified" do
class StrictClass3
extend ::Mixlib::Config
config_strict_mode true
default :x, 1
config_context :c
end
it "The parent class does not allow you to set arbitrary config options" do
lambda { StrictClass3.y = 10 }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Cannot set unsupported config value y.")
end
it "The nested class does not allow you to set arbitrary config options" do
lambda { StrictClass3.y = 10 }.should raise_error(Mixlib::Config::UnknownConfigOptionError, "Cannot set unsupported config value y.")
end
end
describe "When a config_context is opened twice" do
before :each do
@klass = Class.new
@klass.extend(::Mixlib::Config)
@klass.class_eval do
config_context(:blah) do
default :x, 10
end
config_context(:blah) do
default :y, 20
end
end
end
it "Both config_context blocks are honored" do
@klass.blah.x == 10
@klass.blah.y == 20
end
end
it "When a config_context is opened in place of a regular configurable, an error is raised" do
klass = Class.new
klass.extend(::Mixlib::Config)
lambda do
klass.class_eval do
default :blah, 10
config_context(:blah) do
default :y, 20
end
end
end.should raise_error(Mixlib::Config::ReopenedConfigurableWithConfigContextError)
end
it "When a config_context is opened in place of a regular configurable, an error is raised" do
klass = Class.new
klass.extend(::Mixlib::Config)
lambda do
klass.class_eval do
config_context(:blah) do
default :y, 20
end
default :blah, 10
end
end.should raise_error(Mixlib::Config::ReopenedConfigContextWithConfigurableError)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/rspec/logging_helper.rb
|
<reponame>arnab0073/idea
module RSpec
module LoggingHelper
# Capture log messages from the Logging framework and make them
# available via a @log_output instance variable. The @log_output
# supports a readline method to access the log messages.
#
def capture_log_messages( opts = {} )
from = opts.fetch(:from, 'root')
to = opts.fetch(:to, '__rspec__')
exclusive = opts.fetch(:exclusive, true)
appender = Logging::Appenders[to] || Logging::Appenders::StringIo.new(to)
logger = Logging::Logger[from]
if exclusive
logger.appenders = appender
else
logger.add_appenders(appender)
end
before(:all) do
@log_output = Logging::Appenders[to]
end
before(:each) do
@log_output.reset
end
end
end # module LoggingHelper
end # module RSpec
if defined? RSpec::Core::Configuration
class RSpec::Core::Configuration
include RSpec::LoggingHelper
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/known_classes.rb
|
# frozen_string_literal: false
module RDoc
##
# Ruby's built-in classes, modules and exceptions
KNOWN_CLASSES = {
"rb_cArray" => "Array",
"rb_cBasicObject" => "BasicObject",
"rb_cBignum" => "Bignum",
"rb_cClass" => "Class",
"rb_cData" => "Data",
"rb_cDir" => "Dir",
"rb_cEncoding" => "Encoding",
"rb_cFalseClass" => "FalseClass",
"rb_cFile" => "File",
"rb_cFixnum" => "Fixnum",
"rb_cFloat" => "Float",
"rb_cHash" => "Hash",
"rb_cIO" => "IO",
"rb_cInteger" => "Integer",
"rb_cModule" => "Module",
"rb_cNilClass" => "NilClass",
"rb_cNumeric" => "Numeric",
"rb_cObject" => "Object",
"rb_cProc" => "Proc",
"rb_cRange" => "Range",
"rb_cRegexp" => "Regexp",
"rb_cRubyVM" => "RubyVM",
"rb_cSocket" => "Socket",
"rb_cString" => "String",
"rb_cStruct" => "Struct",
"rb_cSymbol" => "Symbol",
"rb_cThread" => "Thread",
"rb_cTime" => "Time",
"rb_cTrueClass" => "TrueClass",
"rb_eArgError" => "ArgError",
"rb_eEOFError" => "EOFError",
"rb_eException" => "Exception",
"rb_eFatal" => "fatal",
"rb_eFloatDomainError" => "FloatDomainError",
"rb_eIOError" => "IOError",
"rb_eIndexError" => "IndexError",
"rb_eInterrupt" => "Interrupt",
"rb_eLoadError" => "LoadError",
"rb_eNameError" => "NameError",
"rb_eNoMemError" => "NoMemError",
"rb_eNotImpError" => "NotImpError",
"rb_eRangeError" => "RangeError",
"rb_eRuntimeError" => "RuntimeError",
"rb_eScriptError" => "ScriptError",
"rb_eSecurityError" => "SecurityError",
"rb_eSignal" => "SignalException",
"rb_eStandardError" => "StandardError",
"rb_eSyntaxError" => "SyntaxError",
"rb_eSystemCallError" => "SystemCallError",
"rb_eSystemExit" => "SystemExit",
"rb_eTypeError" => "TypeError",
"rb_eZeroDivError" => "ZeroDivError",
"rb_mComparable" => "Comparable",
"rb_mEnumerable" => "Enumerable",
"rb_mErrno" => "Errno",
"rb_mFConst" => "File::Constants",
"rb_mFileTest" => "FileTest",
"rb_mGC" => "GC",
"rb_mKernel" => "Kernel",
"rb_mMath" => "Math",
"rb_mProcess" => "Process"
}
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/darwin/cpu_spec.rb
|
#
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2013 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper.rb')
describe Ohai::System, "Darwin cpu plugin" do
before(:each) do
@ohai = Ohai::System.new
@ohai.stub!(:require_plugin).and_return(true)
@ohai[:os] = "darwin"
@ohai.stub(:from).with("sysctl -n hw.physicalcpu").and_return("1")
@ohai.stub(:from).with("sysctl -n hw.logicalcpu").and_return("2")
end
it "should set cpu[:total] to 2" do
@ohai._require_plugin("darwin::cpu")
@ohai[:cpu][:total].should == 2
end
it "should set cpu[:real] to 1" do
@ohai._require_plugin("darwin::cpu")
@ohai[:cpu][:real].should == 1
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/swaplist.rb
|
#
# tkextlib/tcllib/swaplist.rb
# by <NAME> (<EMAIL>)
#
# * Part of tcllib extension
# * A dialog which allows a user to move options between two lists
#
require 'tk'
require 'tkextlib/tcllib.rb'
# TkPackage.require('swaplist', '0.1')
TkPackage.require('swaplist')
module Tk::Tcllib
class Swaplist_Dialog < TkWindow
PACKAGE_NAME = 'swaplist'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('swaplist')
rescue
''
end
end
end
end
class Tk::Tcllib::Swaplist_Dialog
TkCommandNames = ['::swaplist::swaplist'.freeze].freeze
WidgetClassName = 'Swaplist'.freeze
WidgetClassNames[WidgetClassName] ||= self
def self.show(*args)
dialog = self.new(*args)
dialog.show
[dialog.status, dialog.value]
end
def self.display(*args)
self.show(*args)
end
def initialize(*args)
# args = (parent=nil, complete_list=[], selected_list=[], keys=nil)
keys = args.pop
if keys.kind_of?(Hash)
@selected_list = args.pop
@complete_list = args.pop
@keys = _symbolkey2str(keys)
args.push(keys)
else
@selected_list = keys
@complete_list = args.pop
@keys = {}
end
@selected_list = [] unless @selected_list
@complete_list = [] unless @complete_list
@variable = TkVariable.new
@status = nil
super(*args)
end
def create_self(keys)
# dummy
end
private :create_self
def show
@variable.value = ''
@status = bool(tk_call(self.class::TkCommandNames[0],
@path, @variable,
@complete_list, @selected_list,
*hash_kv(@keys)))
end
alias display show
def status
@status
end
def value
@variable.list
end
alias selected value
def cget_strict(slot)
slot = slot.to_s
if slot == 'complete_list'
@complete_list
elsif slot == 'selected_list'
@selected_list
else
@keys[slot]
end
end
def cget(slot)
cget_strict(slot)
end
def configure(slot, value=None)
if slot.kind_of?(Hash)
slot.each{|k, v| configure(k, v)}
else
slot = slot.to_s
value = _symbolkey2str(value) if value.kind_of?(Hash)
if value && value != None
if slot == 'complete_list'
@complete_list = value
elsif slot == 'selected_list'
@selected_list = value
else
@keys[slot] = value
end
else
if slot == 'complete_list'
@complete_list = []
elsif slot == 'selected_list'
@selected_list = []
else
@keys.delete(slot)
end
end
end
self
end
def configinfo(slot = nil)
if slot
slot = slot.to_s
if slot == 'complete_list'
[ slot, nil, nil, nil, @complete_list ]
elsif slot == 'selected_list'
[ slot, nil, nil, nil, @selected_list ]
else
[ slot, nil, nil, nil, @keys[slot] ]
end
else
@keys.collect{|k, v| [ k, nil, nil, nil, v ] } \
<< [ 'complete_list', nil, nil, nil, @complete_list ] \
<< [ 'selected_list', nil, nil, nil, @selected_list ]
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/gdbm/extconf.rb
|
require 'mkmf'
dir_config("gdbm")
if have_library("gdbm", "gdbm_open") and
have_header("gdbm.h")
create_makefile("gdbm")
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/tktable/maxsize.rb
|
<gh_stars>1-10
#!/usr/bin/env ruby
##
## maxsize.rb
##
## This demo uses a really big table. The big startup time is in
## filling the table's Tcl array var.
##
## ( based on 'maxsize.tcl' included source archive of tktable extension )
##
require 'tk'
require 'tkextlib/tktable'
ary = TkVariable.new_hash
rows = 40000
cols = 10
# fill table variable
((-(rows))..rows).each{|x|
((-(cols))..cols).each{|y|
ary[x,y] = "#{x},#{y}"
}
}
lbl = TkLabel.new(:text=>"TkTable v2 Example")
table = Tk::TkTable.new(:rows=>rows, :cols=>cols, :variable=>ary,
:width=>6, :height=>8,
:titlerows=>1, :titlecols=>1,
:coltagcommand=>proc{|col|
col = Integer(col)
(col>0 && col%2 == 1)? 'OddCol': ''
},
:selectmode=>:extended,
:colstretch=>:unset, :rowstretch=>:unset,
:selecttitles=>false, :drawmode=>:slow)
sx = table.xscrollbar(TkScrollbar.new)
sy = table.yscrollbar(TkScrollbar.new)
btn = TkButton.new(:text=>'Exit', :command=>proc{exit})
Tk.grid(lbl, '-', :sticky=>:ew)
Tk.grid(table, sy, :sticky=>:news)
Tk.grid(sx, :sticky=>:ew)
Tk.grid(btn, :sticky=>:ew, :columnspan=>2)
Tk.root.grid_columnconfig(0, :weight=>1)
Tk.root.grid_rowconfig(1, :weight=>1)
table.tag_configure('OddCol', :bg=>'brown', :fg=>'pink')
table.tag_configure('title', :bg=>'red', :fg=>'blue', :relief=>:sunken)
table.tag_configure('dis', :state=>:disabled)
first = table[:colorigin]
%w(n s e w nw ne sw se c).each_with_index{|anchor, idx|
table.tag_configure(anchor, :anchor=>anchor)
table.tag_row(anchor, idx)
table.set([idx,first], anchor)
}
courier = TkFont.new(:family=>'Courier', :size=>10)
table.tag_configure('s', :font=>courier, :justify=>:center)
table.set_width([-2, 8], [-1, 9], [0, 12], [4, 14])
puts "Table is #{table.path} with array #{(table['variable'])}"
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/bootstraptest/runner.rb
|
"exec" "${RUBY-ruby}" "-x" "$0" "$@"; true # -*- mode: ruby; coding: utf-8 -*-
#!./ruby
# $Id: runner.rb 32088 2011-06-14 14:17:42Z akr $
# NOTE:
# Never use optparse in this file.
# Never use test/unit in this file.
# Never use Ruby extensions in this file.
begin
require 'fileutils'
require 'tmpdir'
rescue LoadError
$:.unshift File.join(File.dirname(__FILE__), '../lib')
retry
end
if !Dir.respond_to?(:mktmpdir)
# copied from lib/tmpdir.rb
def Dir.mktmpdir(prefix_suffix=nil, tmpdir=nil)
case prefix_suffix
when nil
prefix = "d"
suffix = ""
when String
prefix = prefix_suffix
suffix = ""
when Array
prefix = prefix_suffix[0]
suffix = prefix_suffix[1]
else
raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
end
tmpdir ||= Dir.tmpdir
t = Time.now.strftime("%Y%m%d")
n = nil
begin
path = "#{tmpdir}/#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
path << "-#{n}" if n
path << suffix
Dir.mkdir(path, 0700)
rescue Errno::EEXIST
n ||= 0
n += 1
retry
end
if block_given?
begin
yield path
ensure
FileUtils.remove_entry_secure path
end
else
path
end
end
end
def main
@ruby = File.expand_path('miniruby')
@verbose = false
$stress = false
dir = nil
quiet = false
tests = nil
ARGV.delete_if {|arg|
case arg
when /\A--ruby=(.*)/
@ruby = $1
@ruby.gsub!(/^([^ ]*)/){File.expand_path($1)}
@ruby.gsub!(/(\s+-I\s*)((?!(?:\.\/)*-(?:\s|\z))\S+)/){$1+File.expand_path($2)}
@ruby.gsub!(/(\s+-r\s*)(\.\.?\/\S+)/){$1+File.expand_path($2)}
true
when /\A--sets=(.*)/
tests = Dir.glob("#{File.dirname($0)}/test_{#{$1}}*.rb").sort
puts tests.map {|path| File.basename(path) }.inspect
true
when /\A--dir=(.*)/
dir = $1
true
when /\A(--stress|-s)/
$stress = true
when /\A(-q|--q(uiet))\z/
quiet = true
true
when /\A(-v|--v(erbose))\z/
@verbose = true
when /\A(-h|--h(elp)?)\z/
puts(<<-End)
Usage: #{File.basename($0, '.*')} --ruby=PATH [--sets=NAME,NAME,...]
--sets=NAME,NAME,... Name of test sets.
--dir=DIRECTORY Working directory.
default: /tmp/bootstraptestXXXXX.tmpwd
-s, --stress stress test.
-v, --verbose Output test name before exec.
-q, --quiet Don\'t print header message.
-h, --help Print this message and quit.
End
exit true
else
false
end
}
if tests and not ARGV.empty?
$stderr.puts "--tests and arguments are exclusive"
exit false
end
tests ||= ARGV
tests = Dir.glob("#{File.dirname($0)}/test_*.rb").sort if tests.empty?
pathes = tests.map {|path| File.expand_path(path) }
unless quiet
puts Time.now
if defined?(RUBY_DESCRIPTION)
puts "Driver is #{RUBY_DESCRIPTION}"
elsif defined?(RUBY_PATCHLEVEL)
puts "Driver is ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}#{RUBY_PLATFORM}) [#{RUBY_PLATFORM}]"
else
puts "Driver is ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
end
puts "Target is #{`#{@ruby} -v`.chomp}"
puts
$stdout.flush
end
in_temporary_working_directory(dir) {
exec_test pathes
}
end
def exec_test(pathes)
@count = 0
@error = 0
@errbuf = []
@location = nil
pathes.each do |path|
$stderr.print "\n#{File.basename(path)} "
$stderr.puts if @verbose
load File.expand_path(path)
end
$stderr.puts
if @error == 0
if @count == 0
$stderr.puts "No tests, no problem"
else
$stderr.puts "PASS all #{@count} tests"
end
exit true
else
@errbuf.each do |msg|
$stderr.puts msg
end
$stderr.puts "FAIL #{@error}/#{@count} tests failed"
exit false
end
end
def show_progress(message = '')
if @verbose
$stderr.print "\##{@count} #{@location} "
end
faildesc = yield
if !faildesc
$stderr.print '.'
$stderr.puts if @verbose
else
$stderr.print 'F'
$stderr.puts if @verbose
error faildesc, message
end
rescue Exception => err
$stderr.print 'E'
$stderr.puts if @verbose
error err.message, message
end
def assert_check(testsrc, message = '', opt = '')
show_progress(message) {
result = get_result_string(testsrc, opt)
check_coredump
yield(result)
}
end
def assert_equal(expected, testsrc, message = '')
newtest
assert_check(testsrc, message) {|result|
if expected == result
nil
else
desc = "#{result.inspect} (expected #{expected.inspect})"
pretty(testsrc, desc, result)
end
}
end
def assert_match(expected_pattern, testsrc, message = '')
newtest
assert_check(testsrc, message) {|result|
if expected_pattern =~ result
nil
else
desc = "#{expected_pattern.inspect} expected to be =~\n#{result.inspect}"
pretty(testsrc, desc, result)
end
}
end
def assert_not_match(unexpected_pattern, testsrc, message = '')
newtest
assert_check(testsrc, message) {|result|
if unexpected_pattern !~ result
nil
else
desc = "#{unexpected_pattern.inspect} expected to be !~\n#{result.inspect}"
pretty(testsrc, desc, result)
end
}
end
def assert_valid_syntax(testsrc, message = '')
newtest
assert_check(testsrc, message, '-c') {|result|
result if /Syntax OK/ !~ result
}
end
def assert_normal_exit(testsrc, *rest)
newtest
opt = {}
opt = rest.pop if Hash === rest.last
message, ignore_signals = rest
message ||= ''
timeout = opt[:timeout]
show_progress(message) {
faildesc = nil
filename = make_srcfile(testsrc)
old_stderr = $stderr.dup
timeout_signaled = false
begin
$stderr.reopen("assert_normal_exit.log", "w")
io = IO.popen("#{@ruby} -W0 #{filename}")
pid = io.pid
th = Thread.new {
io.read
io.close
$?
}
if !th.join(timeout)
Process.kill :KILL, pid
timeout_signaled = true
end
status = th.value
ensure
$stderr.reopen(old_stderr)
old_stderr.close
end
if status.signaled?
signo = status.termsig
signame = Signal.list.invert[signo]
unless ignore_signals and ignore_signals.include?(signame)
sigdesc = "signal #{signo}"
if signame
sigdesc = "SIG#{signame} (#{sigdesc})"
end
if timeout_signaled
sigdesc << " (timeout)"
end
faildesc = pretty(testsrc, "killed by #{sigdesc}", nil)
stderr_log = File.read("assert_normal_exit.log")
if !stderr_log.empty?
faildesc << "\n" if /\n\z/ !~ faildesc
stderr_log << "\n" if /\n\z/ !~ stderr_log
stderr_log.gsub!(/^.*\n/) { '| ' + $& }
faildesc << stderr_log
end
end
end
faildesc
}
end
def assert_finish(timeout_seconds, testsrc, message = '')
newtest
show_progress(message) {
faildesc = nil
filename = make_srcfile(testsrc)
io = IO.popen("#{@ruby} -W0 #{filename}")
pid = io.pid
waited = false
tlimit = Time.now + timeout_seconds
while Time.now < tlimit
if Process.waitpid pid, Process::WNOHANG
waited = true
break
end
sleep 0.1
end
if !waited
Process.kill(:KILL, pid)
Process.waitpid pid
faildesc = pretty(testsrc, "not finished in #{timeout_seconds} seconds", nil)
end
io.close
faildesc
}
end
def flunk(message = '')
newtest
show_progress('') { message }
end
def pretty(src, desc, result)
src = src.sub(/\A.*\n/, '')
(/\n/ =~ src ? "\n#{adjust_indent(src)}" : src) + " #=> #{desc}"
end
INDENT = 27
def adjust_indent(src)
untabify(src).gsub(/^ {#{INDENT}}/o, '').gsub(/^/, ' ')
end
def untabify(str)
str.gsub(/^\t+/) {' ' * (8 * $&.size) }
end
def make_srcfile(src)
filename = 'bootstraptest.tmp.rb'
File.open(filename, 'w') {|f|
f.puts "GC.stress = true" if $stress
f.puts "print(begin; #{src}; end)"
}
filename
end
def get_result_string(src, opt = '')
if @ruby
filename = make_srcfile(src)
begin
`#{@ruby} -W0 #{opt} #{filename}`
ensure
raise CoreDumpError, "core dumped" if $? and $?.coredump?
end
else
eval(src).to_s
end
end
def newtest
@location = File.basename(caller(2).first)
@count += 1
cleanup_coredump
end
def error(msg, additional_message)
@errbuf.push "\##{@count} #{@location}: #{msg} #{additional_message}"
@error += 1
end
def in_temporary_working_directory(dir)
if dir
Dir.mkdir dir
Dir.chdir(dir) {
yield
}
else
Dir.mktmpdir(["bootstraptest", ".tmpwd"]) {|d|
Dir.chdir(d) {
yield
}
}
end
end
def cleanup_coredump
FileUtils.rm_f 'core'
FileUtils.rm_f Dir.glob('core.*')
FileUtils.rm_f @ruby+'.stackdump' if @ruby
end
class CoreDumpError < StandardError; end
def check_coredump
if File.file?('core') or not Dir.glob('core.*').empty? or
(@ruby and File.exist?(@ruby+'.stackdump'))
raise CoreDumpError, "core dumped"
end
end
main
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/gssapi-1.2.0/lib/gssapi/heimdal.rb
|
=begin
Copyright © 2010 <NAME> <<EMAIL>>
Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
=end
module GSSAPI
module LibGSSAPI
GSSAPI_LIB_TYPE = :heimdal
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm1_rescue.rb
|
i=0
while i<30_000_000 # while loop 1
i+=1
begin
rescue
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ruby/test_object.rb
|
<gh_stars>1-10
# -*- coding: us-ascii -*-
# frozen_string_literal: false
require 'test/unit'
class TestObject < Test::Unit::TestCase
def setup
@verbose = $VERBOSE
$VERBOSE = nil
end
def teardown
$VERBOSE = @verbose
end
def test_itself
feature6373 = '[ruby-core:44704] [Feature #6373]'
object = Object.new
assert_same(object, object.itself, feature6373)
end
def test_dup
assert_raise(TypeError) { 1.dup }
assert_raise(TypeError) { true.dup }
assert_raise(TypeError) { nil.dup }
assert_raise(TypeError) do
Object.new.instance_eval { initialize_copy(1) }
end
end
def test_init_dupclone
cls = Class.new do
def initialize_clone(orig); throw :initialize_clone; end
def initialize_dup(orig); throw :initialize_dup; end
end
obj = cls.new
assert_throw(:initialize_clone) {obj.clone}
assert_throw(:initialize_dup) {obj.dup}
end
def test_instance_of
assert_raise(TypeError) { 1.instance_of?(1) }
end
def test_kind_of
assert_raise(TypeError) { 1.kind_of?(1) }
end
def test_taint_frozen_obj
o = Object.new
o.freeze
assert_raise(RuntimeError) { o.taint }
o = Object.new
o.taint
o.freeze
assert_raise(RuntimeError) { o.untaint }
end
def test_freeze_immediate
assert_equal(true, 1.frozen?)
1.freeze
assert_equal(true, 1.frozen?)
assert_equal(true, 2.frozen?)
assert_equal(true, true.frozen?)
assert_equal(true, false.frozen?)
assert_equal(true, nil.frozen?)
end
def test_frozen_error_message
name = "C\u{30c6 30b9 30c8}"
klass = EnvUtil.labeled_class(name) {
attr_accessor :foo
}
obj = klass.new.freeze
assert_raise_with_message(RuntimeError, /#{name}/) {
obj.foo = 1
}
end
def test_nil_to_f
assert_equal(0.0, nil.to_f)
end
def test_not
assert_equal(false, Object.new.send(:!))
assert_equal(true, nil.send(:!))
end
def test_true_and
assert_equal(true, true & true)
assert_equal(true, true & 1)
assert_equal(false, true & false)
assert_equal(false, true & nil)
end
def test_true_or
assert_equal(true, true | true)
assert_equal(true, true | 1)
assert_equal(true, true | false)
assert_equal(true, true | nil)
end
def test_true_xor
assert_equal(false, true ^ true)
assert_equal(false, true ^ 1)
assert_equal(true, true ^ false)
assert_equal(true, true ^ nil)
end
def test_false_and
assert_equal(false, false & true)
assert_equal(false, false & 1)
assert_equal(false, false & false)
assert_equal(false, false & nil)
end
def test_false_or
assert_equal(true, false | true)
assert_equal(true, false | 1)
assert_equal(false, false | false)
assert_equal(false, false | nil)
end
def test_false_xor
assert_equal(true, false ^ true)
assert_equal(true, false ^ 1)
assert_equal(false, false ^ false)
assert_equal(false, false ^ nil)
end
def test_methods
o = Object.new
a1 = o.methods
a2 = o.methods(false)
def o.foo; end
assert_equal([:foo], o.methods(true) - a1)
assert_equal([:foo], o.methods(false) - a2)
end
def test_methods2
c0 = Class.new
c1 = Class.new(c0)
c1.module_eval do
public ; def foo; end
protected; def bar; end
private ; def baz; end
end
c2 = Class.new(c1)
c2.module_eval do
public ; def foo2; end
protected; def bar2; end
private ; def baz2; end
end
o0 = c0.new
o2 = c2.new
assert_equal([:baz, :baz2], (o2.private_methods - o0.private_methods).sort)
assert_equal([:baz2], (o2.private_methods(false) - o0.private_methods(false)).sort)
assert_equal([:bar, :bar2], (o2.protected_methods - o0.protected_methods).sort)
assert_equal([:bar2], (o2.protected_methods(false) - o0.protected_methods(false)).sort)
assert_equal([:foo, :foo2], (o2.public_methods - o0.public_methods).sort)
assert_equal([:foo2], (o2.public_methods(false) - o0.public_methods(false)).sort)
end
def test_methods_prepend
bug8044 = '[ruby-core:53207] [Bug #8044]'
o = Object.new
def o.foo; end
assert_equal([:foo], o.methods(false))
class << o; prepend Module.new; end
assert_equal([:foo], o.methods(false), bug8044)
end
def test_instance_variable_get
o = Object.new
o.instance_eval { @foo = :foo }
assert_equal(:foo, o.instance_variable_get(:@foo))
assert_equal(nil, o.instance_variable_get(:@bar))
assert_raise(NameError) { o.instance_variable_get('@') }
assert_raise(NameError) { o.instance_variable_get(:'@') }
assert_raise(NameError) { o.instance_variable_get(:foo) }
assert_raise(NameError) { o.instance_variable_get("bar") }
assert_raise(TypeError) { o.instance_variable_get(1) }
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "@foo"; end
def n.count; @count; end
assert_equal(:foo, o.instance_variable_get(n))
assert_equal(1, n.count)
end
def test_instance_variable_set
o = Object.new
o.instance_variable_set(:@foo, :foo)
assert_equal(:foo, o.instance_eval { @foo })
assert_raise(NameError) { o.instance_variable_set(:'@', 1) }
assert_raise(NameError) { o.instance_variable_set('@', 1) }
assert_raise(NameError) { o.instance_variable_set(:foo, 1) }
assert_raise(NameError) { o.instance_variable_set("bar", 1) }
assert_raise(TypeError) { o.instance_variable_set(1, 1) }
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "@foo"; end
def n.count; @count; end
o.instance_variable_set(n, :bar)
assert_equal(:bar, o.instance_eval { @foo })
assert_equal(1, n.count)
end
def test_instance_variable_defined
o = Object.new
o.instance_eval { @foo = :foo }
assert_equal(true, o.instance_variable_defined?(:@foo))
assert_equal(false, o.instance_variable_defined?(:@bar))
assert_raise(NameError) { o.instance_variable_defined?(:'@') }
assert_raise(NameError) { o.instance_variable_defined?('@') }
assert_raise(NameError) { o.instance_variable_defined?(:foo) }
assert_raise(NameError) { o.instance_variable_defined?("bar") }
assert_raise(TypeError) { o.instance_variable_defined?(1) }
n = Object.new
def n.to_str; @count = defined?(@count) ? @count + 1 : 1; "@foo"; end
def n.count; @count; end
assert_equal(true, o.instance_variable_defined?(n))
assert_equal(1, n.count)
end
def test_remove_instance_variable
{ 'T_OBJECT' => Object.new,
'T_CLASS,T_MODULE' => Class.new(Object),
'generic ivar' => '',
}.each do |desc, o|
e = assert_raise(NameError, "#{desc} iv removal raises before set") do
o.remove_instance_variable(:@foo)
end
assert_equal([o, :@foo], [e.receiver, e.name])
o.instance_eval { @foo = :foo }
assert_equal(:foo, o.remove_instance_variable(:@foo),
"#{desc} iv removal returns original value")
assert_not_send([o, :instance_variable_defined?, :@foo],
"#{desc} iv removed successfully")
e = assert_raise(NameError, "#{desc} iv removal raises after removal") do
o.remove_instance_variable(:@foo)
end
assert_equal([o, :@foo], [e.receiver, e.name])
end
end
def test_convert_string
o = Object.new
def o.to_s; 1; end
assert_raise(TypeError) { String(o) }
def o.to_s; "o"; end
assert_equal("o", String(o))
def o.to_str; "O"; end
assert_equal("O", String(o))
def o.respond_to?(*) false; end
assert_raise(TypeError) { String(o) }
end
def test_convert_array
o = Object.new
def o.to_a; 1; end
assert_raise(TypeError) { Array(o) }
def o.to_a; [1]; end
assert_equal([1], Array(o))
def o.to_ary; [2]; end
assert_equal([2], Array(o))
def o.respond_to?(*) false; end
assert_equal([o], Array(o))
end
def test_convert_hash
assert_equal({}, Hash(nil))
assert_equal({}, Hash([]))
assert_equal({key: :value}, Hash(key: :value))
assert_raise(TypeError) { Hash([1,2]) }
assert_raise(TypeError) { Hash(Object.new) }
o = Object.new
def o.to_hash; {a: 1, b: 2}; end
assert_equal({a: 1, b: 2}, Hash(o))
def o.to_hash; 9; end
assert_raise(TypeError) { Hash(o) }
end
def test_to_integer
o = Object.new
def o.to_i; nil; end
assert_raise(TypeError) { Integer(o) }
def o.to_i; 42; end
assert_equal(42, Integer(o))
def o.respond_to?(*) false; end
assert_raise(TypeError) { Integer(o) }
end
class MyInteger
def initialize(n); @num = n; end
def to_int; @num; end
def <=>(n); @num <=> n.to_int; end
def <=(n); @num <= n.to_int; end
def +(n); MyInteger.new(@num + n.to_int); end
end
def test_check_to_integer
o1 = MyInteger.new(1)
o9 = MyInteger.new(9)
n = 0
Range.new(o1, o9).step(2) {|x| n += x.to_int }
assert_equal(1+3+5+7+9, n)
end
def test_redefine_method_under_verbose
assert_in_out_err([], <<-INPUT, %w(2), /warning: method redefined; discarding old foo$/)
$VERBOSE = true
o = Object.new
def o.foo; 1; end
def o.foo; 2; end
p o.foo
INPUT
end
def test_redefine_method_which_may_case_serious_problem
assert_in_out_err([], <<-INPUT, [], %r"warning: redefining `object_id' may cause serious problems$")
$VERBOSE = false
def (Object.new).object_id; end
INPUT
assert_in_out_err([], <<-INPUT, [], %r"warning: redefining `__send__' may cause serious problems$")
$VERBOSE = false
def (Object.new).__send__; end
INPUT
bug10421 = '[ruby-dev:48691] [Bug #10421]'
assert_in_out_err([], <<-INPUT, ["1"], [], bug10421)
$VERBOSE = false
class C < BasicObject
def object_id; 1; end
end
puts C.new.object_id
INPUT
end
def test_remove_method
c = Class.new
c.freeze
assert_raise(RuntimeError) do
c.instance_eval { remove_method(:foo) }
end
c = Class.new do
def meth1; "meth" end
end
d = Class.new(c) do
alias meth2 meth1
end
o1 = c.new
assert_respond_to(o1, :meth1)
assert_equal("meth", o1.meth1)
o2 = d.new
assert_respond_to(o2, :meth1)
assert_equal("meth", o2.meth1)
assert_respond_to(o2, :meth2)
assert_equal("meth", o2.meth2)
d.class_eval do
remove_method :meth2
end
bug2202 = '[ruby-core:26074]'
assert_raise(NoMethodError, bug2202) {o2.meth2}
%w(object_id __send__ initialize).each do |m|
assert_in_out_err([], <<-INPUT, %w(:ok), %r"warning: removing `#{m}' may cause serious problems$")
$VERBOSE = false
begin
Class.new.instance_eval { remove_method(:#{m}) }
rescue NameError
p :ok
end
INPUT
end
m = "\u{30e1 30bd 30c3 30c9}"
c = Class.new
EnvUtil.with_default_external(Encoding::UTF_8) do
assert_raise_with_message(NameError, /#{m}/) do
c.class_eval {remove_method m}
end
end
c = Class.new {
define_method(m) {}
remove_method(m)
}
EnvUtil.with_default_external(Encoding::UTF_8) do
assert_raise_with_message(NameError, /#{m}/) do
c.class_eval {remove_method m}
end
end
end
def test_method_missing
assert_raise(ArgumentError) do
1.instance_eval { method_missing }
end
c = Class.new
c.class_eval do
protected
def foo; end
end
assert_raise(NoMethodError) do
c.new.foo
end
assert_raise(NoMethodError) do
1.instance_eval { method_missing(:method_missing) }
end
c.class_eval do
undef_method(:method_missing)
end
assert_raise(ArgumentError) do
c.new.method_missing
end
bug2494 = '[ruby-core:27219]'
c = Class.new do
def method_missing(meth, *args)
super
end
end
b = c.new
foo rescue nil
assert_nothing_raised(bug2494) {[b].flatten}
end
def test_respond_to_missing_string
c = Class.new do
def respond_to_missing?(id, priv)
!(id !~ /\Agadzoks\d+\z/) ^ priv
end
end
foo = c.new
assert_equal(false, foo.respond_to?("gadzooks16"))
assert_equal(true, foo.respond_to?("gadzooks17", true))
assert_equal(true, foo.respond_to?("gadzoks16"))
assert_equal(false, foo.respond_to?("gadzoks17", true))
end
def test_respond_to_missing
c = Class.new do
def respond_to_missing?(id, priv)
if id == :foobar
true
else
false
end
end
def method_missing(id, *args)
if id == :foobar
return [:foo, *args]
else
super
end
end
end
foo = c.new
assert_equal([:foo], foo.foobar);
assert_equal([:foo, 1], foo.foobar(1));
assert_equal([:foo, 1, 2, 3, 4, 5], foo.foobar(1, 2, 3, 4, 5));
assert_respond_to(foo, :foobar)
assert_not_respond_to(foo, :foobarbaz)
assert_raise(NoMethodError) do
foo.foobarbaz
end
foobar = foo.method(:foobar)
assert_equal(-1, foobar.arity);
assert_equal([:foo], foobar.call);
assert_equal([:foo, 1], foobar.call(1));
assert_equal([:foo, 1, 2, 3, 4, 5], foobar.call(1, 2, 3, 4, 5));
assert_equal(foobar, foo.method(:foobar))
assert_not_equal(foobar, c.new.method(:foobar))
c = Class.new(c)
assert_equal(false, c.method_defined?(:foobar))
assert_raise(NameError, '[ruby-core:25748]') do
c.instance_method(:foobar)
end
m = Module.new
assert_equal(false, m.method_defined?(:foobar))
assert_raise(NameError, '[ruby-core:25748]') do
m.instance_method(:foobar)
end
end
def test_implicit_respond_to
bug5158 = '[ruby-core:38799]'
p = Object.new
called = []
p.singleton_class.class_eval do
define_method(:to_ary) do
called << [:to_ary, bug5158]
end
end
[[p]].flatten
assert_equal([[:to_ary, bug5158]], called, bug5158)
called = []
p.singleton_class.class_eval do
define_method(:respond_to?) do |*a|
called << [:respond_to?, *a]
false
end
end
[[p]].flatten
assert_equal([[:respond_to?, :to_ary, true]], called, bug5158)
end
def test_implicit_respond_to_arity_1
p = Object.new
called = []
p.singleton_class.class_eval do
define_method(:respond_to?) do |a|
called << [:respond_to?, a]
false
end
end
[[p]].flatten
assert_equal([[:respond_to?, :to_ary]], called, '[bug:6000]')
end
def test_implicit_respond_to_arity_3
p = Object.new
called = []
p.singleton_class.class_eval do
define_method(:respond_to?) do |a, b, c|
called << [:respond_to?, a, b, c]
false
end
end
msg = 'respond_to? must accept 1 or 2 arguments (requires 3)'
assert_raise_with_message(ArgumentError, msg, '[bug:6000]') do
[[p]].flatten
end
end
def test_method_missing_passed_block
bug5731 = '[ruby-dev:44961]'
c = Class.new do
def method_missing(meth, *args) yield(meth, *args) end
end
a = c.new
result = nil
assert_nothing_raised(LocalJumpError, bug5731) do
a.foo {|x| result = x}
end
assert_equal(:foo, result, bug5731)
result = nil
e = a.enum_for(:foo)
assert_nothing_raised(LocalJumpError, bug5731) do
e.each {|x| result = x}
end
assert_equal(:foo, result, bug5731)
c = Class.new do
def respond_to_missing?(id, priv)
true
end
def method_missing(id, *args, &block)
return block.call(:foo, *args)
end
end
foo = c.new
result = nil
assert_nothing_raised(LocalJumpError, bug5731) do
foo.foobar {|x| result = x}
end
assert_equal(:foo, result, bug5731)
result = nil
assert_nothing_raised(LocalJumpError, bug5731) do
foo.enum_for(:foobar).each {|x| result = x}
end
assert_equal(:foo, result, bug5731)
result = nil
foobar = foo.method(:foobar)
foobar.call {|x| result = x}
assert_equal(:foo, result, bug5731)
result = nil
foobar = foo.method(:foobar)
foobar.enum_for(:call).each {|x| result = x}
assert_equal(:foo, result, bug5731)
end
def test_send_with_no_arguments
assert_raise(ArgumentError) { 1.send }
end
def test_send_with_block
x = :ng
1.send(:times) { x = :ok }
assert_equal(:ok, x)
x = :ok
o = Object.new
def o.inspect
yield if block_given?
super
end
begin
nil.public_send(o) { x = :ng }
rescue TypeError
end
assert_equal(:ok, x)
end
def test_public_send
c = Class.new do
def pub
:ok
end
def invoke(m)
public_send(m)
end
protected
def prot
:ng
end
private
def priv
:ng
end
end.new
assert_equal(:ok, c.public_send(:pub))
assert_raise(NoMethodError) {c.public_send(:priv)}
assert_raise(NoMethodError) {c.public_send(:prot)}
assert_raise(NoMethodError) {c.invoke(:priv)}
bug7499 = '[ruby-core:50489]'
assert_raise(NoMethodError, bug7499) {c.invoke(:prot)}
end
def test_no_superclass_method
bug2312 = '[ruby-dev:39581]'
o = Object.new
e = assert_raise(NoMethodError) {
o.method(:__send__).call(:never_defined_test_no_superclass_method)
}
m1 = e.message
assert_no_match(/no superclass method/, m1, bug2312)
e = assert_raise(NoMethodError) {
o.method(:__send__).call(:never_defined_test_no_superclass_method)
}
assert_equal(m1, e.message, bug2312)
e = assert_raise(NoMethodError) {
o.never_defined_test_no_superclass_method
}
assert_equal(m1, e.message, bug2312)
end
def test_superclass_method
bug2312 = '[ruby-dev:39581]'
assert_in_out_err(["-e", "module Enumerable;undef min;end; (1..2).min{}"],
"", [], /no superclass method/, bug2312)
end
def test_specific_eval_with_wrong_arguments
assert_raise(ArgumentError) do
1.instance_eval("foo") { foo }
end
assert_raise(ArgumentError) do
1.instance_eval
end
assert_raise(ArgumentError) do
1.instance_eval("", 1, 1, 1)
end
end
class InstanceExec
INSTANCE_EXEC = 123
end
def test_instance_exec
x = 1.instance_exec(42) {|a| self + a }
assert_equal(43, x)
x = "foo".instance_exec("bar") {|a| self + a }
assert_equal("foobar", x)
assert_raise(NameError) do
InstanceExec.new.instance_exec { INSTANCE_EXEC }
end
end
def test_extend
assert_raise(ArgumentError) do
1.extend
end
end
def test_untrusted
verbose = $VERBOSE
$VERBOSE = false
begin
obj = Object.new
assert_equal(false, obj.untrusted?)
assert_equal(false, obj.tainted?)
obj.untrust
assert_equal(true, obj.untrusted?)
assert_equal(true, obj.tainted?)
obj.trust
assert_equal(false, obj.untrusted?)
assert_equal(false, obj.tainted?)
obj.taint
assert_equal(true, obj.untrusted?)
assert_equal(true, obj.tainted?)
obj.untaint
assert_equal(false, obj.untrusted?)
assert_equal(false, obj.tainted?)
ensure
$VERBOSE = verbose
end
end
def test_to_s
x = Object.new
x.taint
s = x.to_s
assert_equal(true, s.tainted?)
x = eval(<<-EOS)
class ToS\u{3042}
new.to_s
end
EOS
assert_match(/\bToS\u{3042}:/, x)
name = "X".freeze
x = Object.new.taint
class<<x;self;end.class_eval {define_method(:to_s) {name}}
assert_same(name, x.to_s)
assert_not_predicate(name, :tainted?)
assert_raise(RuntimeError) {name.taint}
assert_equal("X", [x].join(""))
assert_not_predicate(name, :tainted?)
assert_not_predicate(eval('"X".freeze'), :tainted?)
end
def test_inspect
x = Object.new
assert_match(/\A#<Object:0x\h+>\z/, x.inspect)
x.instance_variable_set(:@ivar, :value)
assert_match(/\A#<Object:0x\h+ @ivar=:value>\z/, x.inspect)
x = Object.new
x.instance_variable_set(:@recur, x)
assert_match(/\A#<Object:0x\h+ @recur=#<Object:0x\h+ \.\.\.>>\z/, x.inspect)
x = Object.new
x.instance_variable_set(:@foo, "value")
x.instance_variable_set(:@bar, 42)
assert_match(/\A#<Object:0x\h+ (?:@foo="value", @bar=42|@bar=42, @foo="value")>\z/, x.inspect)
# #inspect does not call #to_s anymore
feature6130 = '[ruby-core:43238]'
x = Object.new
def x.to_s
"to_s"
end
assert_match(/\A#<Object:0x\h+>\z/, x.inspect, feature6130)
x = eval(<<-EOS)
class Inspect\u{3042}
new.inspect
end
EOS
assert_match(/\bInspect\u{3042}:/, x)
x = eval(<<-EOS)
class Inspect\u{3042}
def initialize
@\u{3044} = 42
end
new
end
EOS
assert_match(/\bInspect\u{3042}:.* @\u{3044}=42\b/, x.inspect)
x.instance_variable_set("@\u{3046}".encode(Encoding::EUC_JP), 6)
assert_match(/@\u{3046}=6\b/, x.inspect)
end
def test_singleton_class
x = Object.new
xs = class << x; self; end
assert_equal(xs, x.singleton_class)
y = Object.new
ys = y.singleton_class
assert_equal(class << y; self; end, ys)
assert_equal(NilClass, nil.singleton_class)
assert_equal(TrueClass, true.singleton_class)
assert_equal(FalseClass, false.singleton_class)
assert_raise(TypeError) do
123.singleton_class
end
assert_raise(TypeError) do
:foo.singleton_class
end
end
def test_redef_method_missing
bug5473 = '[ruby-core:40287]'
['ArgumentError.new("bug5473")', 'ArgumentError, "bug5473"', '"bug5473"'].each do |code|
exc = code[/\A[A-Z]\w+/] || 'RuntimeError'
assert_separately([], <<-SRC)
class ::Object
def method_missing(m, *a, &b)
raise #{code}
end
end
assert_raise_with_message(#{exc}, "bug5473") {1.foo}
SRC
end
end
def assert_not_initialize_copy
a = yield
b = yield
assert_nothing_raised("copy") {a.instance_eval {initialize_copy(b)}}
c = a.dup.freeze
assert_raise(RuntimeError, "frozen") {c.instance_eval {initialize_copy(b)}}
d = a.dup.trust
[a, b, c, d]
end
def test_bad_initialize_copy
assert_not_initialize_copy {Object.new}
assert_not_initialize_copy {[].to_enum}
assert_not_initialize_copy {Enumerator::Generator.new {}}
assert_not_initialize_copy {Enumerator::Yielder.new {}}
assert_not_initialize_copy {File.stat(__FILE__)}
assert_not_initialize_copy {open(__FILE__)}.each(&:close)
assert_not_initialize_copy {ARGF.class.new}
assert_not_initialize_copy {Random.new}
assert_not_initialize_copy {//}
assert_not_initialize_copy {/.*/.match("foo")}
st = Struct.new(:foo)
assert_not_initialize_copy {st.new}
end
def test_type_error_message
_issue = "Bug #7539"
assert_raise_with_message(TypeError, "can't convert Array into Integer") {Integer([42])}
assert_raise_with_message(TypeError, 'no implicit conversion of Array into Integer') {[].first([42])}
end
def test_copied_ivar_memory_leak
bug10191 = '[ruby-core:64700] [Bug #10191]'
assert_no_memory_leak([], <<-"end;", <<-"end;", bug10191, timeout: 60, limit: 1.8)
def (a = Object.new).set; @v = nil; end
num = 500_000
end;
num.times {a.clone.set}
end;
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/bcc32/mkexports.rb
|
#!./miniruby -s
$:.unshift(File.expand_path("../..", __FILE__))
require 'win32/mkexports'
class Exports::Bcc < Exports
def forwarding(internal, export)
internal[/\A_?/]+export
end
def each_line(objs, &block)
objs.each do |obj|
opt = /\.(?:so|dll)\z/i =~ obj ? "-ee" : "-oiPUBDEF -oiPUBD32"
IO.foreach("|tdump -q #{opt} #{obj.tr('/', '\\')} < nul", &block)
end
end
def each_export(objs)
objdump(objs) do |l|
next unless /(?:PUBDEF|PUBD32|EXPORT)/ =~ l
yield $1 if /'(.*?)'/ =~ l
end
yield "_strcasecmp", "_stricmp"
yield "_strncasecmp", "_strnicmp"
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/gem-wrappers-1.2.7/gem-wrappers.gemspec
|
<reponame>arnab0073/idea
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
require File.expand_path("../lib/gem-wrappers/version.rb", __FILE__)
Gem::Specification.new do |s|
s.name = "gem-wrappers"
s.version = GemWrappers::VERSION
s.authors = ["<NAME>"]
s.email = ["<EMAIL>"]
s.homepage = "https://github.com/rvm/gem-wrappers"
s.summary = "Create gem wrappers for easy use of gems in cron and other system locations."
s.license = "Apache 2.0"
s.extensions = %w( ext/wrapper_generator/extconf.rb )
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.add_development_dependency("rake")
s.add_development_dependency("minitest")
# s.add_development_dependency("smf-gem")
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/support/platform_helpers.rb
|
<reponame>arnab0073/idea
def ruby_19?
!!(RUBY_VERSION =~ /^1.9/)
end
def ruby_18?
!!(RUBY_VERSION =~ /^1.8/)
end
def windows?
!!(RUBY_PLATFORM =~ /mswin|mingw|windows/)
end
# def jruby?
def unix?
!windows?
end
def os_x?
!!(RUBY_PLATFORM =~ /darwin/)
end
def solaris?
!!(RUBY_PLATFORM =~ /solaris/)
end
def freebsd?
!!(RUBY_PLATFORM =~ /freebsd/)
end
DEV_NULL = windows? ? 'NUL' : '/dev/null'
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/prelude.rb
|
class Thread
MUTEX_FOR_THREAD_EXCLUSIVE = Mutex.new # :nodoc:
# call-seq:
# Thread.exclusive { block } => obj
#
# Wraps the block in a single, VM-global Mutex.synchronize, returning the
# value of the block. A thread executing inside the exclusive section will
# only block other threads which also use the Thread.exclusive mechanism.
def self.exclusive
warn "Thread.exclusive is deprecated, use Mutex", caller
MUTEX_FOR_THREAD_EXCLUSIVE.synchronize{
yield
}
end
end
class IO
# call-seq:
# ios.read_nonblock(maxlen [, options]) -> string
# ios.read_nonblock(maxlen, outbuf [, options]) -> outbuf
#
# Reads at most <i>maxlen</i> bytes from <em>ios</em> using
# the read(2) system call after O_NONBLOCK is set for
# the underlying file descriptor.
#
# If the optional <i>outbuf</i> argument is present,
# it must reference a String, which will receive the data.
# The <i>outbuf</i> will contain only the received data after the method call
# even if it is not empty at the beginning.
#
# read_nonblock just calls the read(2) system call.
# It causes all errors the read(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc.
# The caller should care such errors.
#
# If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN,
# it is extended by IO::WaitReadable.
# So IO::WaitReadable can be used to rescue the exceptions for retrying
# read_nonblock.
#
# read_nonblock causes EOFError on EOF.
#
# If the read byte buffer is not empty,
# read_nonblock reads from the buffer like readpartial.
# In this case, the read(2) system call is not called.
#
# When read_nonblock raises an exception kind of IO::WaitReadable,
# read_nonblock should not be called
# until io is readable for avoiding busy loop.
# This can be done as follows.
#
# # emulates blocking read (readpartial).
# begin
# result = io.read_nonblock(maxlen)
# rescue IO::WaitReadable
# IO.select([io])
# retry
# end
#
# Although IO#read_nonblock doesn't raise IO::WaitWritable.
# OpenSSL::Buffering#read_nonblock can raise IO::WaitWritable.
# If IO and SSL should be used polymorphically,
# IO::WaitWritable should be rescued too.
# See the document of OpenSSL::Buffering#read_nonblock for sample code.
#
# Note that this method is identical to readpartial
# except the non-blocking flag is set.
#
# By specifying `exception: false`, the options hash allows you to indicate
# that read_nonblock should not raise an IO::WaitReadable exception, but
# return the symbol :wait_readable instead.
def read_nonblock(len, buf = nil, exception: true)
__read_nonblock(len, buf, exception)
end
# call-seq:
# ios.write_nonblock(string) -> integer
# ios.write_nonblock(string [, options]) -> integer
#
# Writes the given string to <em>ios</em> using
# the write(2) system call after O_NONBLOCK is set for
# the underlying file descriptor.
#
# It returns the number of bytes written.
#
# write_nonblock just calls the write(2) system call.
# It causes all errors the write(2) system call causes: Errno::EWOULDBLOCK, Errno::EINTR, etc.
# The result may also be smaller than string.length (partial write).
# The caller should care such errors and partial write.
#
# If the exception is Errno::EWOULDBLOCK or Errno::EAGAIN,
# it is extended by IO::WaitWritable.
# So IO::WaitWritable can be used to rescue the exceptions for retrying write_nonblock.
#
# # Creates a pipe.
# r, w = IO.pipe
#
# # write_nonblock writes only 65536 bytes and return 65536.
# # (The pipe size is 65536 bytes on this environment.)
# s = "a" #100000
# p w.write_nonblock(s) #=> 65536
#
# # write_nonblock cannot write a byte and raise EWOULDBLOCK (EAGAIN).
# p w.write_nonblock("b") # Resource temporarily unavailable (Errno::EAGAIN)
#
# If the write buffer is not empty, it is flushed at first.
#
# When write_nonblock raises an exception kind of IO::WaitWritable,
# write_nonblock should not be called
# until io is writable for avoiding busy loop.
# This can be done as follows.
#
# begin
# result = io.write_nonblock(string)
# rescue IO::WaitWritable, Errno::EINTR
# IO.select(nil, [io])
# retry
# end
#
# Note that this doesn't guarantee to write all data in string.
# The length written is reported as result and it should be checked later.
#
# On some platforms such as Windows, write_nonblock is not supported
# according to the kind of the IO object.
# In such cases, write_nonblock raises <code>Errno::EBADF</code>.
#
# By specifying `exception: false`, the options hash allows you to indicate
# that write_nonblock should not raise an IO::WaitWritable exception, but
# return the symbol :wait_writable instead.
def write_nonblock(buf, exception: true)
__write_nonblock(buf, exception)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/nkf/extconf.rb
|
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/nkf/extconf.rb
require 'mkmf'
create_makefile('nkf')
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/openbsd/kernel.rb
|
<reponame>arnab0073/idea
#
# Author:: <NAME> (<EMAIL>)
# Copyright:: Copyright (c) 2009 <NAME>
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
provides "kernel"
kernel[:os] = kernel[:name]
kernel[:securelevel] = from_with_regex("sysctl kern.securelevel", /kern.securelevel=(.+)$/)
mod = Mash.new
popen4("/usr/bin/modstat") do |pid, stdin, stdout, stderr|
stdin.close
stdout.each do |line|
# 1 7 0xc0400000 97f830 kernel
if line =~ /(\d+)\s+(\d+)\s+([0-9a-fx]+)\s+([0-9a-fx]+)\s+([a-zA-Z0-9\_]+)/
kld[$5] = { :size => $4, :refcount => $2 }
end
end
end
kernel[:modules] = mod unless mod.empty?
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkmenubar.rb
|
<gh_stars>10-100
#
# tkmenubar.rb - load tk/menubar.rb
#
require 'tk/menubar'
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/menubar2.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/menubar2.rb
#
# menubar sample 2 : use 'menu' option of root/toplevel widget
#
require 'tk'
radio_var = TkVariable.new('y')
menu_spec = [
[['File', 0],
{:label=>'Open', :command=>proc{puts('Open clicked')}, :underline=>0},
'---',
['Check_A', TkVariable.new(true), 6],
{:type=>'checkbutton', :label=>'Check_B',
:variable=>TkVariable.new, :underline=>6},
'---',
['Radio_X', [radio_var, 'x'], 6, '', {:foreground=>'black'}],
['Radio_Y', [radio_var, 'y'], 6],
['Radio_Z', [radio_var, 'z'], 6],
'---',
['cascade', [
['sss', proc{p 'sss'}, 0],
['ttt', proc{p 'ttt'}, 0],
['uuu', proc{p 'uuu'}, 0],
['vvv', proc{p 'vvv'}, 0],
],
0, '',
{:font=>'Courier 16 italic',
:menu_config=>{:font=>'Times -18 bold', :foreground=>'black'}}],
'---',
['Quit', proc{exit}, 0]],
[['Edit', 0],
['Cut', proc{puts('Cut clicked')}, 2],
['Copy', proc{puts('Copy clicked')}, 0],
['Paste', proc{puts('Paste clicked')}, 0]],
[['Help', 0, {:menu_name=>'help'}],
['About This', proc{puts('Ruby/Tk menubar sample 2')}, 6]]
]
mbar = Tk.root.add_menubar(menu_spec,
# followings are default configure options
'tearoff'=>'false',
'foreground'=>'grey40',
'activeforeground'=>'red',
'font'=>'Helvetia 12 bold')
# This (default configure options) is NOT same the following.
#
# mbar = Tk.root.add_menubar(menu_spec)
# mbar.configure('foreground'=>'grey40', 'activeforeground'=>'red',
# 'font'=>'Helvetia 12 bold')
TkText.new(:wrap=>'word').pack.insert('1.0', 'Please read the sample source, and check how to override default configure options of menu entries on a menu_spec.')
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/spintime.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/spintime.rb
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
Tk::Iwidgets::Spintime.new.pack(:padx=>10, :pady=>10)
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/test/mkmf/test_framework.rb
|
require_relative 'base'
class TestMkmf
class TestHaveFramework < TestMkmf
def create_framework(fw, hdrname = "#{fw}.h")
Dir.mktmpdir("frameworks") do |dir|
fwdir = "#{dir}/#{fw}.framework"
hdrdir = "#{fwdir}/Headers"
FileUtils.mkdir_p(hdrdir)
File.write("#{hdrdir}/#{hdrname}", "")
src = "#{fwdir}/main.c"
File.write(src, "void #{fw}(void) {}")
cmd = LINK_SO.dup
RbConfig.expand(cmd, RbConfig::CONFIG.merge("OBJS"=>src))
cmd.gsub!("$@", "#{fwdir}/#{fw}")
cmd.gsub!(/ -bundle /, ' -dynamiclib ')
assert(xsystem(cmd), MKMFLOG)
$INCFLAGS << " " << "-F#{dir}".quote
yield fw, hdrname
end
end
def test_core_foundation_framework
assert(have_framework("CoreFoundation"), mkmflog("try as Objective-C"))
end
def test_multi_frameworks
assert(have_framework("CoreFoundation"), mkmflog("try as Objective-C"))
assert(have_framework("Cocoa"), mkmflog("try as Objective-C"))
end
def test_empty_framework
create_framework("MkmfTest") do |fw|
assert(have_framework(fw), MKMFLOG)
end
end
def test_different_name_header
bug8593 = '[ruby-core:55745] [Bug #8593]'
create_framework("MkmfTest", "test_mkmf.h") do |fw, hdrname|
assert(!have_framework(fw), MKMFLOG)
assert(have_framework([fw, hdrname]), MKMFLOG)
end
end
end
end if /darwin/ =~ RUBY_PLATFORM
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/test/ruby/test_gc.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/test/ruby/test_gc.rb<gh_stars>0
require 'test/unit'
require_relative "envutil"
class TestGc < Test::Unit::TestCase
class S
def initialize(a)
@a = a
end
end
def test_gc
prev_stress = GC.stress
GC.stress = false
assert_nothing_raised do
1.upto(10000) {
tmp = [0,1,2,3,4,5,6,7,8,9]
}
tmp = nil
end
l=nil
100000.times {
l = S.new(l)
}
GC.start
assert true # reach here or dumps core
l = []
100000.times {
l.push([l])
}
GC.start
assert true # reach here or dumps core
GC.stress = prev_stress
end
def test_enable_disable
GC.enable
assert_equal(false, GC.enable)
assert_equal(false, GC.disable)
assert_equal(true, GC.disable)
assert_equal(true, GC.disable)
assert_nil(GC.start)
assert_equal(true, GC.enable)
assert_equal(false, GC.enable)
ensure
GC.enable
end
def test_count
c = GC.count
GC.start
assert_operator(c, :<, GC.count)
end
def test_stat
res = GC.stat
assert_equal(false, res.empty?)
assert_kind_of(Integer, res[:count])
arg = Hash.new
res = GC.stat(arg)
assert_equal(arg, res)
assert_equal(false, res.empty?)
assert_kind_of(Integer, res[:count])
end
def test_singleton_method
prev_stress = GC.stress
assert_nothing_raised("[ruby-dev:42832]") do
GC.stress = true
10.times do
obj = Object.new
def obj.foo() end
def obj.bar() raise "obj.foo is called, but this is obj.bar" end
obj.foo
end
end
ensure
GC.stress = prev_stress
end
def test_gc_parameter
env = {
"RUBY_GC_MALLOC_LIMIT" => "60000000",
"RUBY_HEAP_MIN_SLOTS" => "100000"
}
assert_normal_exit("exit", "[ruby-core:39777]", :child_env => env)
env = {
"RUBYOPT" => "",
"RUBY_HEAP_MIN_SLOTS" => "100000"
}
assert_in_out_err([env, "-e", "exit"], "", [], [], "[ruby-core:39795]")
assert_in_out_err([env, "-W0", "-e", "exit"], "", [], [], "[ruby-core:39795]")
assert_in_out_err([env, "-W1", "-e", "exit"], "", [], [], "[ruby-core:39795]")
assert_in_out_err([env, "-w", "-e", "exit"], "", [], /heap_min_slots=100000/, "[ruby-core:39795]")
end
def test_profiler_enabled
GC::Profiler.enable
assert_equal(true, GC::Profiler.enabled?)
GC::Profiler.disable
assert_equal(false, GC::Profiler.enabled?)
ensure
GC::Profiler.disable
end
def test_finalizing_main_thread
assert_in_out_err(%w[--disable-gems], <<-EOS, ["\"finalize\""], [], "[ruby-dev:46647]")
ObjectSpace.define_finalizer(Thread.main) { p 'finalize' }
EOS
end
def test_sweep_in_finalizer
bug9205 = '[ruby-core:58833] [Bug #9205]'
2.times do
assert_ruby_status([], <<-'end;', bug9205)
raise_proc = proc do |id|
GC.start
end
1000.times do
ObjectSpace.define_finalizer(Object.new, raise_proc)
end
end;
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkbgerror.rb
|
#
# tkbgerror.rb - load tk/bgerror.rb
#
require 'tk/bgerror'
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-cli-1.6.0/mixlib-cli.gemspec
|
<reponame>arnab0073/idea<gh_stars>0
$:.unshift(File.dirname(__FILE__) + "/lib")
require "mixlib/cli/version"
Gem::Specification.new do |s|
s.name = "mixlib-cli"
s.version = Mixlib::CLI::VERSION
s.platform = Gem::Platform::RUBY
s.has_rdoc = true
s.extra_rdoc_files = ["README.md", "LICENSE", "NOTICE"]
s.summary = "A simple mixin for CLI interfaces, including option parsing"
s.description = s.summary
s.author = "Chef Software, Inc."
s.email = "<EMAIL>"
s.homepage = "https://www.chef.io"
s.license = "Apache-2.0"
# Uncomment this to add a dependency
#s.add_dependency "mixlib-log"
s.add_development_dependency "rake", "< 11.0"
s.add_development_dependency "rspec", "~> 2.14"
s.add_development_dependency "rdoc"
s.add_development_dependency "chefstyle", "~> 0.3"
s.require_path = "lib"
s.files = %w{LICENSE README.md Gemfile Rakefile NOTICE} + Dir.glob("*.gemspec") +
Dir.glob("{lib,spec}/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/extbutton.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/extbutton.rb
#
# tkextlib/iwidgets/extbutton.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Extbutton < Tk::Itk::Widget
end
end
end
class Tk::Iwidgets::Extbutton
TkCommandNames = ['::iwidgets::extbutton'.freeze].freeze
WidgetClassName = 'Extbutton'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __strval_optkeys
super() << 'bitmapforeground' << 'ringbackground'
end
private :__strval_optkeys
def __boolval_optkeys
super() << 'defaultring'
end
private :__boolval_optkeys
def invoke
tk_call(@path, 'invoke')
self
end
def flash
tk_call(@path, 'flash')
self
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.